diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..9cb1e45 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,40 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + name: ${{ matrix.os }}, Python ${{ matrix.python-version }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + python-version: ["3.10", "3.12", "3.14"] + + steps: + - name: Checkout source + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install the package + run: python -m pip install -e ".[dev]" + + - name: Run the tests + run: python -m pytest tests -q + + # The one part that imports IvoryOS, which the tests above run without. + - name: Import the Labware view + run: | + python -m pip install ivoryos-edge + python -c "from plr_ivoryos.labware_view import plugin; print(plugin.id)" diff --git a/README.md b/README.md index 78923ee..964532e 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,10 @@ NextGen the Labware panel shows it live and lets you build it by dragging. > package calls, so each beta here is pinned to exactly one of PyLabRobot's. PyLabRobot's older > `LiquidHandler` (now `pylabrobot.legacy`) is not used: robots that PyLabRobot 1.0 only drives > through it (Nimbus, Vantage, Tecan EVO) are not supported here. +> +> **No real Flex has been run through this package yet**, only the simulator below. PyLabRobot +> 1.0.0b1 itself warns that 20 `FlexHead96` operations and `FlexHead1.aspirate` and `.dispense` have +> "not been tested on hardware". `FlexHead8` carries no such warning, so it is the place to start. --- @@ -82,6 +86,10 @@ discovers what is mounted, uploads labware and sends every command a real run wo tip and volume tracking and its own refusals. What it does not check is the robot's own motion planning. PyLabRobot 1.0.0b1 has no Flex simulator of its own. +A `host` or `serial_port` beside `simulated=True` is refused: it would be ignored, and a run would +look like one on that robot. A pickup from spots holding no tip leaves the tip sensor reading +absent, so the step fails there, as the sensor on a robot makes it. + --- ## The worktable is a file @@ -188,10 +196,14 @@ only IvoryOS NextGen loads it. ## Installation ```bash -pip install --pre plr-ivoryos # 1.0.0b1, with PyLabRobot 1.0.0b1 -pip install --pre "plr-ivoryos[serial]" # a Flex over USB +pip install plr-ivoryos==1.0.0b1 # with PyLabRobot 1.0.0b1 +pip install "plr-ivoryos[serial]==1.0.0b1" # a Flex over USB ``` +Name the version: plain `pip install plr-ivoryos` installs 0.2.0, which has no Flex, and `--pre` +lets every other dependency be a pre-release too. uv takes a pre-release only for a package named +in the command, so name PyLabRobot as well: `uv pip install plr-ivoryos==1.0.0b1 pylabrobot==1.0.0b1`. + Python 3.10 or newer. A Python environment holds one PyLabRobot, so every deck sharing one (the IvoryOS desktop app's decks do) uses the same plr-ivoryos and PyLabRobot. diff --git a/examples/flex_simulated.py b/examples/flex_simulated.py index 4737ad5..712cf3a 100644 --- a/examples/flex_simulated.py +++ b/examples/flex_simulated.py @@ -1,6 +1,6 @@ """A simulated Opentrons Flex in IvoryOS NextGen, through PyLabRobot 1.0. - pip install plr-ivoryos ivoryos-edge + pip install plr-ivoryos==1.0.0b1 ivoryos-edge python examples/flex_simulated.py PyLabRobot's own Flex runs against a simulated robot (plr_ivoryos.opentrons.simulator), so tips, diff --git a/plr_ivoryos/opentrons/flex.py b/plr_ivoryos/opentrons/flex.py index 0091c07..21c3bb8 100644 --- a/plr_ivoryos/opentrons/flex.py +++ b/plr_ivoryos/opentrons/flex.py @@ -83,7 +83,8 @@ class Flex(WorktableRobot): host / port the robot on the network (port 31950) serial_port or its USB-B port instead (needs plr-ivoryos[serial]) - simulated run against a simulated robot (simulator.py) + simulated run against a simulated robot (simulator.py). A host or serial_port beside it is + refused: it would be ignored, and a run would look like one on that robot. worktable the worktable file (worktable.py). Optional: it defaults to worktable.json in the deck's data folder. A file that does not exist yet starts the worktable (a ready-made one, simulated; an empty one on a real robot) and is written on the @@ -105,6 +106,9 @@ def __init__(self, host: Optional[str] = None, port: int = 31950, serial_port: O command_timeout: float = 30.0, tracking: bool = True): if not simulated and not host and not serial_port: raise ValueError("Give the Flex's host (or serial_port), or simulated=True.") + if simulated and (host or serial_port): + raise ValueError("simulated=True runs no robot, so a host or serial_port beside it would be ignored. " + "Turn simulated off to use that robot, or leave them out to simulate.") super().__init__(worktable, "FlexDeck", simulated, step_delay_s, tracking) self._host, self._port, self._serial_port = host, int(port), serial_port self._command_timeout = float(command_timeout) @@ -144,7 +148,8 @@ def _make_plr(self) -> PLRFlex: if "head96" in equipment: mounts = {"left": equipment["head96"]} server = SimulatedFlexServer(mounts, gripper=equipment.get("gripper", False), - trash=equipment.get("trash")) + trash=equipment.get("trash"), + labware=lambda name: self.deck.get_resource(name)) return PLRFlex(host="simulated-flex", deck=self.deck, io=server, command_timeout=self._command_timeout, command_poll_interval=0) if self._serial_port: diff --git a/plr_ivoryos/opentrons/simulator.py b/plr_ivoryos/opentrons/simulator.py index 77aeca5..d7ad193 100644 --- a/plr_ivoryos/opentrons/simulator.py +++ b/plr_ivoryos/opentrons/simulator.py @@ -11,15 +11,17 @@ What it answers: health, instruments, deck configuration (the trash bin), modules (none), runs, run actions, labware definitions and commands. Commands succeed at once; `loadPipette` and `loadLabware` hand out ids, the tip sensor reports what was picked up and dropped, and a position query answers a -fixed position. `log` keeps every command, for tests. +fixed position. A pickup from spots holding no tip leaves the sensor reading absent, which is what +fails it on a robot. `log` keeps every command, for tests. """ import asyncio import itertools import re -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional from pylabrobot.io.http import HTTP, HTTPError +from pylabrobot.resources.errors import NoTipError, ResourceNotFoundError # The Flex pipettes, by the name the robot reports (`instrumentName`): the model it reports for the # simulator, channels, and volume range (µL). The models are ones PyLabRobot has default flow rates for. @@ -41,6 +43,16 @@ API_VERSION = "8.4.0" # recent enough for every command PyLabRobot sends (robot/* needs 8.2.0) +def _holds_a_tip(spot) -> bool: + """Whether a spot held a tip before this pickup. PyLabRobot has already staged taking the tip + when the command arrives, and `get_tip` is what still reads it, as PyLabRobot's own pickup does.""" + try: + spot.tracker.get_tip() + except NoTipError: + return False + return True + + class SimulatedFlexServer(HTTP): """The robot-server of a Flex with these pipettes mounted. @@ -49,10 +61,13 @@ class SimulatedFlexServer(HTTP): gripper whether the gripper is fitted trash the slot of the trash bin, or None delay_s how long each command takes, so a run can be watched + labware finds labware on the worktable by name, so a pickup can tell a used spot from a full + one. Without it every pickup finds a tip. """ def __init__(self, mounts: Dict[str, str], gripper: bool = True, trash: Optional[str] = "A3", - delay_s: float = 0.0, name: str = "simulated-flex"): + delay_s: float = 0.0, name: str = "simulated-flex", + labware: Optional[Callable[[str], Any]] = None): super().__init__("Simulated Opentrons Flex", "http://simulated-flex", timeout=30) unknown = [p for p in mounts.values() if p not in FLEX_PIPETTES] if unknown: @@ -62,6 +77,7 @@ def __init__(self, mounts: Dict[str, str], gripper: bool = True, trash: Optional self.trash = trash self.delay_s = float(delay_s) self.name = name + self.labware = labware self._ids = itertools.count(1) self.runs: Dict[str, dict] = {} self.log: List[dict] = [] @@ -150,11 +166,16 @@ def _execute(self, run: dict, command_type: str, params: dict): """(status, result, error) for one command.""" tips = run["tips"] if command_type == "loadPipette": - return "succeeded", {"pipetteId": self._id("pipette")}, None + pipette_id = self._id("pipette") + run.setdefault("pipettes", {})[pipette_id] = params.get("pipetteName") + return "succeeded", {"pipetteId": pipette_id}, None if command_type == "loadLabware": - return "succeeded", {"labwareId": params.get("labwareId") or self._id("labware")}, None + labware_id = params.get("labwareId") or self._id("labware") + run.setdefault("labware", {})[labware_id] = params.get("displayName") + return "succeeded", {"labwareId": labware_id}, None if command_type == "pickUpTip": - tips[params.get("pipetteId")] = True + pipette = params.get("pipetteId") + tips[pipette] = bool(tips.get(pipette)) or self._finds_a_tip(run, params) elif command_type in ("dropTip", "dropTipInPlace", "unsafe/dropTipInPlace"): tips[params.get("pipetteId")] = False elif command_type == "getTipPresence": @@ -173,3 +194,32 @@ def _execute(self, run: dict, command_type: str, params: dict): elif command_type and command_type.startswith("robot/move"): return "succeeded", {"position": dict(params.get("axis_map") or {})}, None return "succeeded", {}, None + + def _finds_a_tip(self, run: dict, params: dict) -> bool: + """Whether the nozzles of a pickup come down on at least one tip: what a robot's sensor reads + after it. PyLabRobot skips spots it knows are empty and sends an 8- or 96-channel pickup + anyway, so this reading is what fails a pickup from a used column, as on hardware. + + Asked of PyLabRobot's own record of the rack, not kept here, so a rack swapped on the + worktable is a full rack at once. Anything unknown finds a tip, and a partial column is read + as its whole column, so this can pass a pickup the robot would fail, but never fails one the + robot would pass.""" + name = run.get("labware", {}).get(params.get("labwareId")) + well = params.get("wellName") + if self.labware is None or not name or not well: + return True + try: + rack = self.labware(name) + except ResourceNotFoundError: + return True + pipette = run.get("pipettes", {}).get(params.get("pipetteId")) + channels = FLEX_PIPETTES.get(pipette, {}).get("channels") + if channels == 1: + spots = [rack.get_item(well)] + elif channels == 8: + spots = rack.column(int(well[1:]) - 1) + elif channels == 96: + spots = rack.get_all_items() + else: + return True + return any(_holds_a_tip(spot) for spot in spots) diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 0387b81..0000000 --- a/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -pylabrobot>=0.2.2,<1.0 diff --git a/tests/test_flex.py b/tests/test_flex.py index 12bff98..4b2506b 100644 --- a/tests/test_flex.py +++ b/tests/test_flex.py @@ -81,6 +81,56 @@ def test_the_tip_sensor_reads_what_was_picked_up_and_dropped(): assert server._execute(run, "verifyTipPresence", {"pipetteId": "p", "expectedState": "absent"})[0] == "failed" +@pytest.mark.parametrize("given", [{"host": "10.0.0.5"}, {"serial_port": "COM3"}]) +def test_a_robot_named_beside_simulated_is_refused_not_ignored(given): + with pytest.raises(ValueError, match="simulated=True runs no robot"): + Flex(simulated=True, **given) + + +def test_the_default_port_and_empty_fields_a_form_sends_still_simulate(): + robot = Flex(simulated=True, host="", serial_port="", port=31950) + assert list(robot.__ivoryos_instruments__()) == ["left", "right", "gripper"] + + +def test_a_used_column_fails_at_the_pickup_and_the_next_column_still_works(flex): + left = flex.__ivoryos_instruments__()["left"] + left.pick_up_tips("tips[A1:H1]") + left.discard_tips() + with pytest.raises(RuntimeError, match="Tip pickup not detected"): + left.pick_up_tips("tips[A1:H1]") + assert left.has_tip_on_hardware() is False + left.pick_up_tips("tips[A2:H2]") + assert all(left.get_mounted_tips()) + + +def test_a_column_with_some_tips_left_is_picked_up_by_what_is_there(flex): + parts = flex.__ivoryos_instruments__() + parts["right"].pick_up_tips("tips[A1]") + parts["right"].discard_tips() + parts["left"].pick_up_tips("tips[A1:H1]") + mounted = parts["left"].get_mounted_tips() + assert mounted[0] is None and all(mounted[1:]) + + +def test_a_96_channel_head_finds_no_tips_in_a_used_rack(data_folder): + robot = Flex(simulated=True, worktable=write(data_folder, {**FILE, "equipment": {"head96": "p200_96", "trash": "A3"}})) + head = robot.__ivoryos_instruments__()["head96"] + head.pick_up_tips("tips") + head.discard_tips() + with pytest.raises(RuntimeError, match="Tip pickup not detected"): + head.pick_up_tips("tips") + + +def test_a_rack_swapped_on_the_worktable_is_full_at_once(flex): + left = flex.__ivoryos_instruments__()["left"] + left.pick_up_tips("tips[A1:H1]") + left.discard_tips() + flex.__ivoryos_labware_edit__("remove", name="tips") + flex.__ivoryos_labware_edit__("place", definition="flex_96_tiprack_200ul", site="C1", name="tips") + left.pick_up_tips("tips[A1:H1]") + assert all(left.get_mounted_tips()) + + # --- what is mounted ------------------------------------------------------------------------------------ def test_each_mounted_thing_is_an_instrument_of_the_class_its_channels_say(flex):