{ "cells": [ { "cell_type": "markdown", "id": "76d09de2", "metadata": {}, "source": [ "# KingFisher Flex\n", "\n", "```{device-card} thermo-fisher-kingfisher-flex\n", "```\n", "\n", "Run computer-hosted BindIt BDZ exports with a matching **96DW head, tip comb and plates**.\n", "PLR validates the export, binds its plates to resource objects, and streams its generated\n", "commands over USB HID. BindIt does not need to be running during execution.\n", "\n", "**Hardware tested:** actual KingFisher Flex testing covers only the 96-well head with\n", "96DW plates, on firmware 1.01.0 and macOS. Other heads, including the 24-well head,\n", "have not been tested. The driver remains experimental. Tested operations include mixing,\n", "bead collection/release, drying, 37 C heating, timed pauses, loops and host confirmations.\n", "Resource-aware ManualOperator host and physical-Start handling have passed two-plate\n", "loading, mixing and unloading runs, including inventory checks after all four transfers.\n", "The physical-Start check used a diagnostic with mixing shortened to 20 seconds.\n", "A carousel-only reagent-addition diagnostic also passed: the host handler identified\n", "the bound plate and presented holder, awaited confirmation of a 50 uL-per-well water\n", "addition, and verified unchanged plate occupancy before continuing. Robotic transfers\n", "remain application-owned. Command completion does not verify tip-comb\n", "attachment; inspect pickup and clearances. Other head/plate formats, onboard\n", "protocol management and generation of protocols without a BDZ are outside this driver.\n", "\n", "See [installation](../installation.md) and [command-line tools](../cli.md).\n" ] }, { "cell_type": "markdown", "id": "00b27c3c", "metadata": {}, "source": [ "## Physical setup\n", "\n", "Prepare the 96DW head, matching tips and supported plates according to the instrument\n", "instructions. Close BindIt before connecting. Run hardware cells individually.\n" ] }, { "cell_type": "markdown", "id": "45ae786f", "metadata": {}, "source": [ "## Inspect a protocol offline\n", "\n", "Set the path to your BindIt export. Reading and preflight do not open USB.\n", "`compatibility_issues()` lists blockers; `preflight()` raises if any remain.\n", "`prompts()` shows plate actions and reagent additions. Plate labels are not tray numbers.\n", "\n", "\n", "Use an executable export produced by BindIt for the installed 96DW configuration.\n", "The driver retains the exported motions, timing and heating commands; it does not\n", "calculate coordinates from volumes or reconstruct a method from step names. An\n", "unsupported export is rejected as a whole. Passing validation does not prove the\n", "physical setup, plate contents or protocol outcome.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "4c82c377", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "from pylabrobot.thermo_fisher.kingfisher.flex import KingFisherFlex, read_flex_bdz\n", "\n", "protocol = read_flex_bdz(Path(\"protocol.bdz\"))\n", "commands = protocol.preflight()\n", "print(protocol.name, protocol.sha256, len(commands))\n", "print([(plate.name, plate.id) for plate in protocol.plates])\n", "protocol.prompts()" ] }, { "cell_type": "markdown", "id": "e332708f", "metadata": {}, "source": [ "## Logical carousel resources\n", "\n", "`flex.carousel` is a `PlateCarrier` with eight persistent `PlateHolder` sites,\n", "keyed **1–8** to match the printed trays. Each tray holds at most one PLR `Plate`.\n", "Remove its current plate explicitly before assigning another. Assignment and\n", "unassignment only update the resource tree; they do not move hardware.\n", "\n", "The following offline example assigns a KingFisher plate, then removes it.\n", "Plate compatibility with a BDZ is a separate execution check.\n", "\n", "Carousel dimensions and pedestal heights are **unmeasured zero placeholders**;\n", "holder locations are undefined. Local plate coordinates are organizational only.\n", "This model is not calibrated for robot transfers or collision checking." ] }, { "cell_type": "code", "execution_count": null, "id": "5bc99915", "metadata": {}, "outputs": [], "source": [ "from pylabrobot.resources import thermo_TS_kingfisher_96_wellplate_2000uL_Vb\n", "\n", "flex = KingFisherFlex(name=\"flex_a\")\n", "plate = thermo_TS_kingfisher_96_wellplate_2000uL_Vb(\"sample_plate\")\n", "tray = flex.carousel[2]\n", "tray.assign_child_resource(plate) # Equivalent to flex.carousel[2] = plate.\n", "assert plate.parent is tray\n", "assert tray.resource is plate\n", "plate.unassign() # Equivalent to flex.carousel[2] = None." ] }, { "cell_type": "markdown", "id": "b7f1a822", "metadata": {}, "source": [ "`processing_slot` and `loading_slot` identify the trays at the two stations;\n", "`processing_holder` and `loading_holder` return those same holder objects.\n", "They are `None` before initialization, during rotation, and after interruption or\n", "disconnect. Orientation updates only after successful motion completion. Rotation\n", "does not move plates between holders.\n", "\n", "Plate assignments persist through initialization, disconnect and failures.\n", "`inventory_verified` starts false: an empty resource tree does not prove the\n", "physical carousel is empty. Reconcile inventory after connection and before\n", "execution, as shown below. Homing only establishes orientation.\n", "\n", "BDZ execution requires explicit plate identity bindings. Binding does not assign\n", "plates to holders. Action handlers perform transfers and update the resource tree;\n", "the driver checks the result before continuing. Resource changes outside an active\n", "action invalidate inventory certainty. Reconnection, interruption and disconnection\n", "also require a fresh inventory reconciliation." ] }, { "cell_type": "markdown", "id": "c7086f27", "metadata": {}, "source": [ "## Bind every protocol plate before execution\n", "\n", "Choose the PLR `Plate` object representing each physical plate required by this\n", "BDZ. Keys must exactly match the names in `protocol.plates`, including case;\n", "PLR resource names can differ. Include the empty tip-comb pickup/return plate.\n", "\n", "The example below assumes a four-plate export with these names. Replace the\n", "mapping with all names from your selected BDZ and your corresponding PLR plate\n", "objects. Use existing objects when those plates are already modeled elsewhere\n", "in your workcell; do not create another object for the same physical plate.\n", "\n", "`bind_plates()` runs offline and rejects missing or unknown names, duplicate BDZ\n", "names, non-plate resources and reuse of one PLR object for different BDZ plates.\n", "For duplicate BDZ names, give the plates distinct names in BindIt and re-export.\n", "The resulting run retains its selected export and a read-only mapping in\n", "`bound_protocol.plates_by_id`. Editing the input dictionary cannot change it.\n", "Preparing another protocol requires its own bindings.\n", "\n", "Binding records identity only: it does not rename resources, move plates, validate\n", "physical plate geometry or prove which plate an operator has loaded." ] }, { "cell_type": "code", "execution_count": null, "id": "a0d99d2c", "metadata": {}, "outputs": [], "source": [ "tip_plate = thermo_TS_kingfisher_96_wellplate_2000uL_Vb(\"tips_001\")\n", "bead_plate = thermo_TS_kingfisher_96_wellplate_2000uL_Vb(\"beads_001\")\n", "wash_plate = thermo_TS_kingfisher_96_wellplate_2000uL_Vb(\"wash_001\")\n", "resuspension_plate = thermo_TS_kingfisher_96_wellplate_2000uL_Vb(\"resuspension_001\")\n", "\n", "bound_protocol = protocol.bind_plates({\n", " \"Empty Tip Comb Plate\": tip_plate,\n", " \"Bead Plate\": bead_plate,\n", " \"Wash Plate\": wash_plate,\n", " \"Resuspension Plate\": resuspension_plate,\n", "})" ] }, { "cell_type": "markdown", "id": "51bb761a", "metadata": {}, "source": [ "## Connect and identify\n", "\n", "`setup()` opens USB and reads the identity without moving the instrument.\n", "Pass `serial_number=\"...\"` to select among multiple instruments.\n", "\n", "The `name` argument distinguishes resource names; `serial_number` selects the USB instrument.\n", "For two instruments, use distinct names and their respective serial numbers.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "c03729f7", "metadata": {}, "outputs": [], "source": [ "await flex.setup()\n", "(flex.version, flex.serial)" ] }, { "cell_type": "markdown", "id": "b053d5bd", "metadata": {}, "source": [ "## Initialize\n", "\n", "**This moves the instrument**, disables heating, and presents tray 4 at loading\n", "with tray 1 at processing.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "2ab44d80", "metadata": {}, "outputs": [], "source": [ "await flex.initialize()\n", "(flex.processing_slot, flex.loading_slot)" ] }, { "cell_type": "markdown", "id": "112232f5", "metadata": {}, "source": [ "## Reconcile initial inventory\n", "\n", "Inspect all eight physical trays and make the resource assignments match them.\n", "For a preloaded plate, use `flex.carousel[tray_number] = bound_plate`; remove stale\n", "assignments with `plate.unassign()`. The bound object must match the expected tray\n", "in the BDZ loading sequence. Empty trays must be checked too.\n", "\n", "Only after that inspection, execute the confirmation below. It sends no instrument\n", "commands. Running before reconciliation raises an error without starting the method.\n", "Plates can be loaded progressively through action handlers; they need not all be\n", "present before the run. A successful checked run preserves verified inventory.\n", "After interruption, inspect retained assignments, establish a fresh session and\n", "reconcile again before attempting another run." ] }, { "cell_type": "code", "execution_count": null, "id": "f52efc05", "metadata": {}, "outputs": [], "source": [ "flex.reconcile_inventory()\n", "flex.inventory_verified" ] }, { "cell_type": "markdown", "id": "42e2d8b8", "metadata": {}, "source": [ "## Observe events\n", "\n", "Start one event consumer before running. Events include temperature readings,\n", "plate requests, pauses, confirmations, failures, and run completion. Temperature\n", "readings describe heater and ambient sensors, not well-liquid temperature.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "8af32021", "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import logging\n", "\n", "logging.basicConfig(level=logging.INFO)\n", "\n", "\n", "async def observe_events():\n", " async for event in flex.events():\n", " logging.info(\"%s: %s; prompt=%s\", event.kind, event.text, event.prompt)\n", "\n", "\n", "observer = asyncio.create_task(observe_events())" ] }, { "cell_type": "markdown", "id": "bc0f00d7", "metadata": {}, "source": [ "## Software/manual action handling\n", "\n", "A `FlexAction` supplies the bound `plate`, presented `holder`, BDZ `plate_id` and\n", "`plate_name`, instructions in `label`, reagent `additions`, and the source command,\n", "line number and export fingerprint. A generic pause can have no bound plate.\n", "\n", "`FlexManualHandler` uses [ManualOperator](../../../machine-agnostic-features/manual-operator.md):\n", "`move_resource()` handles transfers, and `perform()` handles interventions and\n", "confirmations of preloaded plates. Loading uses the plate's current parent. Your\n", "application supplies the unloading destination. The operator waits for its provider\n", "before updating resource assignments, and the Flex checks occupancy before advancing.\n", "\n", "Here the console provider acknowledges completion when you press Enter. You can\n", "substitute any `OperatorActionProvider`, such as one backed by your application's UI.\n", "Finish the action and clear the carousel before acknowledging. Rejection, failure,\n", "timeout and cancellation prevent further execution and require recovery.\n", "\n", "The logical staging holders below are an example of modeled sources and unloading\n", "destinations. Replace them with your actual workcell resources. Their zero dimensions\n", "are unmeasured placeholders, not robot coordinates. Existing parent assignments are\n", "preserved. A manual load requires a modeled source; binding alone does not supply one." ] }, { "cell_type": "code", "execution_count": null, "id": "123ebf83", "metadata": {}, "outputs": [], "source": [ "from pylabrobot.manual_operator import ConsoleOperatorActionProvider, ManualOperator\n", "from pylabrobot.resources import Resource, ResourceHolder\n", "from pylabrobot.thermo_fisher.kingfisher.flex import FlexAction, FlexManualHandler\n", "\n", "staging = {\n", " plate_id: ResourceHolder(\n", " name=f\"staging_{plate.name}\", size_x=0, size_y=0, size_z=0,\n", " metadata={\"geometry\": \"unmeasured\"},\n", " )\n", " for plate_id, plate in bound_protocol.plates_by_id.items()\n", "}\n", "for plate_id, plate in bound_protocol.plates_by_id.items():\n", " if plate.parent is None:\n", " staging[plate_id].assign_child_resource(plate)\n", "\n", "\n", "def unloading_destination(action: FlexAction) -> Resource:\n", " assert action.plate_id is not None\n", " return staging[action.plate_id]\n", "\n", "\n", "operator = ManualOperator(ConsoleOperatorActionProvider(), name=\"flex_operator\")\n", "manual_handler = FlexManualHandler(operator, unload_destination=unloading_destination)" ] }, { "cell_type": "markdown", "id": "3488faef", "metadata": {}, "source": [ "## Run a local protocol with software acknowledgment\n", "\n", "This starts motion and may start heating. Complete each requested transfer or\n", "intervention before confirming through the provider. The handler updates the model;\n", "plate assignment events alone never advance execution. Reagent requests include\n", "reagent names and volumes per well.\n", "\n", "Host acknowledgment omits PAU, so no physical Start press is needed. An unbound\n", "protocol or unreconciled inventory is rejected before execution commands are sent.\n", "`operator_timeout=None` permits indefinite operator waits while session failures\n", "remain monitored. Temperature setpoints do not themselves wait for target attainment.\n", "The call returns after execution and finalization.\n", "\n", "Only `handle_action` fulfills requests. Use `action.action` to dispatch loading,\n", "unloading and interventions to different application operations. `flex.events()` is\n", "an observation stream; consuming an event does not acknowledge or complete an action.\n", "After the handler returns exactly `True`, the driver checks all eight holders against\n", "the expected post-action inventory. It does not independently sense plate transfers.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5f73c396", "metadata": {}, "outputs": [], "source": [ "result = await flex.run_protocol(\n", " bound_protocol,\n", " handle_action=manual_handler,\n", " acknowledgement=\"host\",\n", " operator_timeout=None,\n", ")\n", "result" ] }, { "cell_type": "markdown", "id": "348eaeb6", "metadata": {}, "source": [ "## Alternative: physical Start through ManualOperator\n", "\n", "Use this path instead of the software-acknowledged run above when you want the\n", "instrument's Start button to acknowledge the actions. Each request gets its own\n", "`FlexStartAcknowledgement` provider, bound to that exact active action. It sends\n", "the original PAU and waits for `PAU END 0` within the ManualOperator lifecycle.\n", "Transfers are recorded after that completion, and the Flex still checks occupancy\n", "before issuing the next command. The provider logs transfer instructions and\n", "ManualOperator publishes lifecycle events; no console Enter press is also required.\n", "\n", "`acknowledgement=\"instrument\"` must be selected before PAU. The adapter cannot\n", "release an already active pause or reuse an acknowledgment for another action.\n", "Firmware completion is not independent verification of physical plate identity." ] }, { "cell_type": "code", "execution_count": null, "id": "4a012eee", "metadata": {}, "outputs": [], "source": [ "from pylabrobot.thermo_fisher.kingfisher.flex import FlexStartAcknowledgement\n", "\n", "\n", "async def physical_handler(action: FlexAction) -> bool:\n", " operator = ManualOperator(\n", " FlexStartAcknowledgement(flex, action), name=\"flex_physical_operator\"\n", " )\n", " handler = FlexManualHandler(operator, unload_destination=unloading_destination)\n", " return await handler(action)\n", "\n", "\n", "result = await flex.run_protocol(\n", " bound_protocol,\n", " handle_action=physical_handler,\n", " acknowledgement=\"instrument\",\n", " operator_timeout=None,\n", ")" ] }, { "cell_type": "markdown", "id": "6f932224", "metadata": {}, "source": [ "## Application-selected handling\n", "\n", "`acknowledgement` can also be a synchronous function returning `\"host\"` or\n", "`\"instrument\"` for each `FlexAction`. Supply a handler that uses the corresponding\n", "provider. For example, transfer actions can use software confirmation while protocol\n", "interventions use physical Start. Selection happens before that action's PAU is sent.\n", "\n", "A robotic handler uses `\"host\"` acknowledgment and awaits its own transfer or\n", "intervention implementation. That implementation must update the resource tree and\n", "finish clearing the carousel before the handler returns `True`. The Flex driver\n", "selects no arm, storage location, unloading destination or calibrated robot path.\n", "Neither ManualOperator nor any specific arm is mandatory for execution.\n", "\n", "## Hardware-free robotic-handler example\n", "\n", "This example exercises only the action interface and resource model. It opens no USB\n", "connection and operates no robot. `simulated_transfer` stands in for an application\n", "transfer operation that returns after motion and model updates finish. Replace it\n", "with a calibrated implementation for a real workcell; these holders have no calibrated\n", "geometry. The synthetic requests are not an executable instrument protocol." ] }, { "cell_type": "code", "execution_count": null, "id": "1dd55c71", "metadata": {}, "outputs": [], "source": [ "from dataclasses import replace\n", "from pylabrobot.thermo_fisher.kingfisher.flex import FlexCommand\n", "\n", "example_flex = KingFisherFlex(name=\"handler_example\")\n", "example_plate = thermo_TS_kingfisher_96_wellplate_2000uL_Vb(\"example_plate\")\n", "example_source = ResourceHolder(\"example_source\", 0, 0, 0)\n", "example_destination = ResourceHolder(\"example_destination\", 0, 0, 0)\n", "example_source.assign_child_resource(example_plate)\n", "\n", "\n", "async def simulated_transfer(resource: Resource, destination: Resource) -> None:\n", " \"\"\"Simulate an awaited transfer with completed model updates; no hardware.\"\"\"\n", " await asyncio.sleep(0)\n", " assert resource.parent is not None\n", " resource.unassign()\n", " destination.assign_child_resource(resource, location=None)\n", "\n", "\n", "async def robotic_handler(action: FlexAction) -> bool:\n", " \"\"\"Application-owned fulfillment; substitute real awaited operations as appropriate.\"\"\"\n", " if action.action == \"pause\":\n", " await asyncio.sleep(0) # Simulated intervention completion.\n", " else:\n", " assert action.plate is not None\n", " destination = action.holder if action.action == \"load\" else example_destination\n", " await simulated_transfer(action.plate, destination)\n", " return True\n", "\n", "\n", "example_action = FlexAction(\n", " action=\"load\", label=\"EXAMPLE\", plate_id=\"example-id\", plate_name=\"EXAMPLE\",\n", " plate=example_plate, holder=example_flex.carousel[2],\n", " processing_slot=7, loading_slot=2, line_number=1,\n", " command=FlexCommand(1, 'PAU 1 \"EXAMPLE\"'), source_sha256=\"0\" * 64,\n", ")\n", "await robotic_handler(example_action)\n", "assert example_plate.parent is example_flex.carousel[2]\n", "await robotic_handler(replace(\n", " example_action, action=\"unload\", line_number=2,\n", " command=FlexCommand(2, 'PAU 2 \"EXAMPLE\"'),\n", "))\n", "assert example_plate.parent is example_destination" ] }, { "cell_type": "markdown", "id": "8ff0e980", "metadata": {}, "source": [ "## Abort and recovery\n", "\n", "Call `await flex.abort()` from another task while execution is pending. Keep the run\n", "in an `asyncio.Task` when it needs a supervising task. Aborting can move axes.\n", "Canceling a Python task, interrupting a notebook cell, or calling `stop()` does not\n", "stop the instrument or guarantee heater shutdown.\n", "\n", "After a rejected action, timeout, fault, abort or disconnect, further execution is\n", "blocked. The driver preserves the last modeled plate assignments but invalidates\n", "orientation and inventory verification. A failed transfer may have physically completed\n", "without its model update, so retained assignments are evidence to inspect, not a\n", "physical inventory reading.\n", "\n", "Before restarting:\n", "\n", "1. Ensure motion has stopped and the instrument can be safely inspected. Check the\n", " tip comb, plates and heater; use the instrument's recovery procedure as needed.\n", "2. Call `await flex.stop()` to close the failed session, then `await flex.setup()`\n", " to establish a fresh connection.\n", "3. Correct the resource tree to match the observed plates, including external sources\n", " and destinations. Initialize only when the instrument is safe to home, using\n", " `await flex.initialize()`; homing does not empty trays or fix an attached tip comb.\n", "4. Inspect all eight trays and call `flex.reconcile_inventory()`. Recheck your plate\n", " bindings and handler before explicitly starting another run.\n", "\n", "There is no automatic retry or mid-protocol resume. Restarting executes the method\n", "from its beginning and can repeat chemical operations.\n" ] }, { "cell_type": "markdown", "id": "59f31c80", "metadata": {}, "source": [ "## Disconnect\n", "\n", "`stop()` closes USB and ends the event stream. It does not stop motion.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "1e56dfff", "metadata": {}, "outputs": [], "source": [ "await flex.stop()\n", "await observer" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }