From 5a08885ad7a555a6c9da9376a2bb5a034463dc8a Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:28:54 -0800 Subject: [PATCH 01/28] `io.USB`: a serial number is read through the descriptor, not PyUSB's empty cache Choosing a device by `serial_number` compared it with `dev._serial_number`, which PyUSB fills only once something has read `dev.serial_number`. Straight after enumeration it is None, so every device was refused as having no serial number. The serial number is now read through the descriptor (`dev.serial_number`), and a device without one (`iSerialNumber == 0`) is still refused. --- pylabrobot/io/usb.py | 4 +++- pylabrobot/io/usb_tests.py | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/pylabrobot/io/usb.py b/pylabrobot/io/usb.py index d8028dbf8ee..8f8b98b524a 100644 --- a/pylabrobot/io/usb.py +++ b/pylabrobot/io/usb.py @@ -351,7 +351,9 @@ def get_available_devices(self) -> List["usb.core.Device"]: continue if self._serial_number is not None: - if dev._serial_number is None: + # PyUSB reads the serial number descriptor on first access; `_serial_number` is only its + # cache, empty until then. + if dev.iSerialNumber == 0 or dev.serial_number is None: raise RuntimeError( f"A serial number was specified for '{self.human_readable_device_name}', but the device does not have a serial number." ) diff --git a/pylabrobot/io/usb_tests.py b/pylabrobot/io/usb_tests.py index 358d1f12ad5..c8ab3787f12 100644 --- a/pylabrobot/io/usb_tests.py +++ b/pylabrobot/io/usb_tests.py @@ -189,3 +189,28 @@ def test_validator_replays_a_write(self) -> None: ] validator = USBValidator(capture, "mock USB", 1, 2) self.assertEqual(validator.ctrl_transfer(0x40, 1, 0, 0, b"\x01"), bytearray()) + + +class USBDeviceSelectionTests(unittest.TestCase): + """Pick a device by serial number, reading the descriptor rather than PyUSB's empty cache.""" + + def _devices(self, *serials): + devices = [] + for serial in serials: + dev = Mock(iSerialNumber=3 if serial else 0, _serial_number=None, serial_number=serial) + devices.append(dev) + return devices + + def test_serial_number_is_read_through_the_descriptor(self) -> None: + devices = self._devices("A", "B") + with patch.object(usb_module, "libusb_package", create=True) as lib: + lib.find.return_value = devices + self.assertEqual( + USB(1, 2, "mock USB", serial_number="B").get_available_devices(), [devices[1]] + ) + + def test_device_without_serial_number_is_refused(self) -> None: + with patch.object(usb_module, "libusb_package", create=True) as lib: + lib.find.return_value = self._devices(None) + with self.assertRaisesRegex(RuntimeError, "does not have a serial number"): + USB(1, 2, "mock USB", serial_number="B").get_available_devices() From 94910a72220a2065b8ac604523dfb0f0208c92d8 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:30:37 -0800 Subject: [PATCH 02/28] `resources`: Beckman Coulter Biomek labware The Biomek tips (T50F, T190F, T230, T1025F, T1070), their 96-tip boxes (BC50F, BC190F, BC230, BC1025F, BC1070), plates (Thermo96VB_PP, BCFlat96, BCDeep96Square, Thomson_24w_Square_RB, with the lids Biomek seats on them) and reservoirs (ThermoNUNC_350CB, Reservoir, ModularReservoir), transcribed from Biomek 5's tip and labware classes. A tip is a `BiomekTip`, a `Tip` that also carries its cone (the radius at its end and the length over which it widens); a well is a `BiomekWell`, a `Well` that also carries Biomek's outline of it by height (`WellSegment`s), from which its height <-> volume table and its wall come. Biomek uses both to place a tip near a well's wall, as `HamiltonTip` and `TecanTip` carry their instruments' data. A tip box is a `StandingTipRack` whose tip spots sit on its top face, where the head's mandrels meet the tips. Each resource carries Biomek's grip point (`preferred_pickup_location`). A resource library page lists them with their part numbers. --- docs/resources/index.md | 1 + docs/resources/library/beckman_coulter.md | 45 +++ pylabrobot/resources/__init__.py | 1 + .../resources/beckman_coulter/__init__.py | 24 ++ .../beckman_coulter/beckman_coulter_tests.py | 204 ++++++++++ .../beckman_coulter/biomek_resource.py | 219 +++++++++++ .../resources/beckman_coulter/plates.py | 348 ++++++++++++++++++ .../resources/beckman_coulter/tip_racks.py | 179 +++++++++ pylabrobot/resources/beckman_coulter/tips.py | 96 +++++ 9 files changed, 1117 insertions(+) create mode 100644 docs/resources/library/beckman_coulter.md create mode 100644 pylabrobot/resources/beckman_coulter/__init__.py create mode 100644 pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py create mode 100644 pylabrobot/resources/beckman_coulter/biomek_resource.py create mode 100644 pylabrobot/resources/beckman_coulter/plates.py create mode 100644 pylabrobot/resources/beckman_coulter/tip_racks.py create mode 100644 pylabrobot/resources/beckman_coulter/tips.py diff --git a/docs/resources/index.md b/docs/resources/index.md index 86aa4006dbc..d101fca9d08 100644 --- a/docs/resources/index.md +++ b/docs/resources/index.md @@ -175,6 +175,7 @@ library/agenbio library/agilent library/alpaqua library/azenta +library/beckman_coulter library/bioer library/biorad library/boekel diff --git a/docs/resources/library/beckman_coulter.md b/docs/resources/library/beckman_coulter.md new file mode 100644 index 00000000000..af2e392ebd7 --- /dev/null +++ b/docs/resources/library/beckman_coulter.md @@ -0,0 +1,45 @@ +# Beckman Coulter + +Company page: [Beckman Coulter Life Sciences](https://www.beckman.com) + +Transcribed from the tip and labware classes of Biomek 5, Beckman Coulter's software for its Biomek +liquid handlers. The labware is defined as Biomek defines it, under Biomek's class names (in +quotes), whoever makes it. Tips are `BiomekTip`s, which also carry the tip's cone; wells are +`BiomekWell`s, which also carry Biomek's outline of the well by height. + +## Tips + +| Description | Image | PLR definition | +|-|-|-| +| 'T50F'
Biomek tip, 50 uL, filter | | `beckman_coulter_biomek_tip_50uL_filter` | +| 'T190F'
Biomek tip, 190 uL, filter | | `beckman_coulter_biomek_tip_190uL_filter` | +| 'T230'
Biomek tip, 230 uL, no filter | | `beckman_coulter_biomek_tip_230uL` | +| 'T1025F'
Biomek tip, 1025 uL, filter | | `beckman_coulter_biomek_tip_1025uL_filter` | +| 'T1070'
Biomek tip, 1070 uL, no filter | | `beckman_coulter_biomek_tip_1070uL` | + +## Tip racks + +| Description | Image | PLR definition | +|-|-|-| +| 'BC50F'
Part no.: B85888
Biomek tip box: 96 T50F tips | | `beckman_coulter_biomek_96_tiprack_50uL_filter` | +| 'BC190F'
Part no.: B85911
Biomek tip box: 96 T190F tips | | `beckman_coulter_biomek_96_tiprack_190uL_filter` | +| 'BC230'
Part no.: B85906 (sterile), B85903 (non-sterile)
Biomek tip box: 96 T230 tips | | `beckman_coulter_biomek_96_tiprack_230uL` | +| 'BC1025F'
Part no.: B85955
Biomek tip box: 96 T1025F tips | | `beckman_coulter_biomek_96_tiprack_1025uL_filter` | +| 'BC1070'
Part no.: B85945 (sterile), B85940 (non-sterile)
Biomek tip box: 96 T1070 tips | | `beckman_coulter_biomek_96_tiprack_1070uL` | + +## Plates + +| Description | Image | PLR definition | +|-|-|-| +| 'Thermo96VB_PP'
96 round, V-bottomed wells; with its 'TiterplateLid' | | `beckman_coulter_biomek_96_wellplate_vb` | +| 'BCFlat96'
Part no.: 609844
96 round, flat-bottomed wells; with its 'TiterplateLid' | | `beckman_coulter_biomek_96_wellplate_flat` | +| 'BCDeep96Square'
Part no.: 140504
96 deep, square, V-bottomed wells | | `beckman_coulter_biomek_96_deepwell_square` | +| 'Thomson_24w_Square_RB'
Part no.: 931568
24 square, round-bottomed wells; with its lid | | `beckman_coulter_biomek_24_wellplate_square_rb` | + +## Reservoirs + +| Description | Image | PLR definition | +|-|-|-| +| 'ThermoNUNC_350CB'
one flat-bottomed section; with its 'TiterplateLid' | | `beckman_coulter_biomek_reservoir_350cb` | +| 'Reservoir'
Part no.: 148033
one flat-bottomed section | | `beckman_coulter_biomek_reservoir` | +| 'ModularReservoir'
Part no.: 372795 (frame)
four V-bottomed sections | | `beckman_coulter_biomek_modular_reservoir` | diff --git a/pylabrobot/resources/__init__.py b/pylabrobot/resources/__init__.py index 07e878f25eb..00d3176d54e 100644 --- a/pylabrobot/resources/__init__.py +++ b/pylabrobot/resources/__init__.py @@ -3,6 +3,7 @@ from .agilent import * from .alpaqua import * from .azenta import * +from .beckman_coulter import * from .biorad import * from .boekel import * from .btx import * diff --git a/pylabrobot/resources/beckman_coulter/__init__.py b/pylabrobot/resources/beckman_coulter/__init__.py new file mode 100644 index 00000000000..4d4403ce12c --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/__init__.py @@ -0,0 +1,24 @@ +from .biomek_resource import BiomekTip, BiomekWell, WellSegment +from .plates import ( + beckman_coulter_biomek_24_wellplate_square_rb, + beckman_coulter_biomek_96_deepwell_square, + beckman_coulter_biomek_96_wellplate_flat, + beckman_coulter_biomek_96_wellplate_vb, + beckman_coulter_biomek_modular_reservoir, + beckman_coulter_biomek_reservoir, + beckman_coulter_biomek_reservoir_350cb, +) +from .tip_racks import ( + beckman_coulter_biomek_96_tiprack_50uL_filter, + beckman_coulter_biomek_96_tiprack_190uL_filter, + beckman_coulter_biomek_96_tiprack_230uL, + beckman_coulter_biomek_96_tiprack_1025uL_filter, + beckman_coulter_biomek_96_tiprack_1070uL, +) +from .tips import ( + beckman_coulter_biomek_tip_50uL_filter, + beckman_coulter_biomek_tip_190uL_filter, + beckman_coulter_biomek_tip_230uL, + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, +) diff --git a/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py new file mode 100644 index 00000000000..72932f1c839 --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py @@ -0,0 +1,204 @@ +"""Beckman Coulter Biomek tips, tip boxes, plates and reservoirs, against the figures of the Biomek +classes they transcribe (cm there, mm here).""" + +import math +import unittest + +from pylabrobot.resources import ( + BiomekTip, + Plate, + BiomekWell, + Resource, + WellSegment, + beckman_coulter_biomek_24_wellplate_square_rb, + beckman_coulter_biomek_96_deepwell_square, + beckman_coulter_biomek_96_tiprack_50uL_filter, + beckman_coulter_biomek_96_tiprack_190uL_filter, + beckman_coulter_biomek_96_tiprack_230uL, + beckman_coulter_biomek_96_tiprack_1025uL_filter, + beckman_coulter_biomek_96_tiprack_1070uL, + beckman_coulter_biomek_96_wellplate_flat, + beckman_coulter_biomek_96_wellplate_vb, + beckman_coulter_biomek_modular_reservoir, + beckman_coulter_biomek_reservoir, + beckman_coulter_biomek_reservoir_350cb, + beckman_coulter_biomek_tip_50uL_filter, + beckman_coulter_biomek_tip_190uL_filter, + beckman_coulter_biomek_tip_230uL, + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, +) +from pylabrobot.resources.tip_rack import StandingTipRack + + +class BiomekTipTests(unittest.TestCase): + def test_a_tip_has_its_class_figures(self) -> None: + # tipheight, capacity, filtered, coniclength (cm); every class seats 0.775 cm on the mandrel. + for make, length, volume, has_filter, cone in ( + (beckman_coulter_biomek_tip_50uL_filter, 51.359, 50.0, True, 38.227), + (beckman_coulter_biomek_tip_190uL_filter, 51.435, 190.0, True, 28.194), + (beckman_coulter_biomek_tip_230uL, 51.435, 230.0, False, 28.194), + (beckman_coulter_biomek_tip_1025uL_filter, 109.855, 1025.0, True, 19.8374), + (beckman_coulter_biomek_tip_1070uL, 109.855, 1070.0, False, 19.8374), + ): + with self.subTest(make.__name__): + tip = make("tip") + self.assertIsInstance(tip, BiomekTip) + self.assertAlmostEqual(tip.get_size_z(), length) + self.assertEqual(tip.maximal_volume, volume) + self.assertEqual(tip.has_filter, has_filter) + self.assertAlmostEqual(tip.fitting_depth, 7.75) + self.assertAlmostEqual(tip.cone_length, cone) + self.assertFalse(tip.is_conductive) + self.assertEqual(tip.model, make.__name__) + + def test_a_tip_widens_along_its_cone(self) -> None: + tip = beckman_coulter_biomek_tip_1070uL("tip") # mintipradius 0.0635, maxtipradius 0.2413 cm + self.assertAlmostEqual(tip.radius_at(0), 0.635) + self.assertAlmostEqual(tip.radius_at(19.8374 / 2), (0.635 + 2.413) / 2) + self.assertAlmostEqual(tip.radius_at(50), 2.413) + + def test_a_tip_reads_back_from_its_serialization(self) -> None: + tip = beckman_coulter_biomek_tip_230uL("tip") + back = Resource.deserialize(tip.serialize()) + self.assertIsInstance(back, BiomekTip) + self.assertEqual(back, tip) + self.assertNotEqual(back, beckman_coulter_biomek_tip_1070uL("tip")) + + +class BiomekTipBoxTests(unittest.TestCase): + BOXES = ( + # make, height, well1xoffset (mm), tip length + (beckman_coulter_biomek_96_tiprack_50uL_filter, 55.9, 14.5, 51.359), + (beckman_coulter_biomek_96_tiprack_190uL_filter, 55.9, 14.5, 51.435), + (beckman_coulter_biomek_96_tiprack_230uL, 55.9, 14.5, 51.435), + (beckman_coulter_biomek_96_tiprack_1025uL_filter, 114.1, 14.4, 109.855), + (beckman_coulter_biomek_96_tiprack_1070uL, 114.1, 14.4, 109.855), + ) + + def test_a_box_holds_96_of_its_tips_on_a_9_mm_grid(self) -> None: + for make, _, _, tip_length in self.BOXES: + with self.subTest(make.__name__): + rack = make("rack") + self.assertIsInstance(rack, StandingTipRack) + self.assertEqual((rack.num_items_x, rack.num_items_y), (12, 8)) + self.assertTrue(all(spot.has_tip() for spot in rack.get_all_items())) + self.assertAlmostEqual(rack.get_item("A1").get_tip().get_size_z(), tip_length) + a1 = rack.get_item("A1").get_location_wrt(rack) + a2 = rack.get_item("A2").get_location_wrt(rack) + b1 = rack.get_item("B1").get_location_wrt(rack) + self.assertAlmostEqual(a2.x - a1.x, 9.0) + self.assertAlmostEqual(a1.y - b1.y, 9.0) + + def test_tip_a1_stands_where_the_class_puts_it(self) -> None: + """A1's centre is `well1xoffset` from the left edge and 1.12 cm from the back edge; the tips' + tops are at the box's height, where the head's mandrels meet them.""" + for make, height, a1_x, _ in self.BOXES: + with self.subTest(make.__name__): + rack = make("rack") + self.assertEqual((rack.get_size_x(), rack.get_size_y()), (127.9, 85.4)) + self.assertAlmostEqual(rack.get_size_z(), height) + centre = rack.get_item("A1").get_location_wrt(rack, "c", "c", "b") + self.assertAlmostEqual(centre.x, a1_x) + self.assertAlmostEqual(centre.y, 85.4 - 11.2) + self.assertAlmostEqual(centre.z, height) + + def test_a_box_is_gripped_below_its_top(self) -> None: + # gripperinfo: the pads at its centre, the fingertips 0.23 cm below its bottom. + rack = beckman_coulter_biomek_96_tiprack_230uL("rack") + point = rack.preferred_pickup_location + assert point is not None + self.assertAlmostEqual(point.x, 127.9 / 2) + self.assertAlmostEqual(point.y, 85.4 / 2) + self.assertAlmostEqual(point.z, -2.3) + + +class BiomekPlateTests(unittest.TestCase): + def test_a_segment_holds_biomeks_section_volume(self) -> None: + # `sectionvolume` (uL) of each segment, from its outline: a cone, a frustum, a rectangular + # section, a round bottom (a spherical cap). + for make, volumes in ( + (beckman_coulter_biomek_96_wellplate_vb, (15.6665, 427.2566)), + (beckman_coulter_biomek_96_wellplate_flat, (365.708,)), + (beckman_coulter_biomek_96_deepwell_square, (133.645, 2282.995)), + (beckman_coulter_biomek_24_wellplate_square_rb, (1072.3303, 9248.0)), + ): + well = make("plate").get_well("A1") + assert isinstance(well, BiomekWell) + for segment, volume in zip(well.segments, volumes): + with self.subTest(make.__name__, volume=volume): + self.assertAlmostEqual(segment.volume(segment.height), volume, delta=0.002 * volume) + + def test_the_logged_liquid_level(self) -> None: + # 200 uL in Thermo96VB_PP: the 96-head's logged dispense rose 0.567 cm with the liquid. + well = beckman_coulter_biomek_96_wellplate_vb("plate").get_well("A1") + self.assertAlmostEqual(well.compute_height_from_volume(200), 5.667, delta=0.01) + assert isinstance(well, BiomekWell) + self.assertAlmostEqual(well.wall_distance(3.67, 0.0), 4.0) + + def test_a_square_well_meets_its_wall_at_the_side(self) -> None: + well = beckman_coulter_biomek_96_deepwell_square("plate").get_well("A1") + assert isinstance(well, BiomekWell) + self.assertAlmostEqual(well.get_size_x(), 8.28) + self.assertAlmostEqual(well.wall_distance(20.0, 0.0), 4.14) + self.assertAlmostEqual(well.wall_distance(20.0, math.pi / 4), 4.14 * math.sqrt(2)) + + def test_a_well_reads_back_from_its_serialization(self) -> None: + plate = beckman_coulter_biomek_96_wellplate_vb("plate", with_lid=True) + back = Resource.deserialize(plate.serialize()) + assert isinstance(back, Plate) + well = back.get_item("A1") + assert isinstance(well, BiomekWell) + self.assertEqual(well, plate.get_item("A1")) + self.assertEqual(well.segments[0], WellSegment(2.0, 2.735, 2.735, 0.0, 0.0)) + + def test_a_lid_sits_where_biomek_seats_it(self) -> None: + # Logged: the fingertips 1.000 cm above the plate's bottom for TiterplateLid on Thermo96VB_PP, + # and 4.200 cm for the Thomson lid on its plate. The lid covers the plate's footprint. + for make, tips_above in ( + (beckman_coulter_biomek_96_wellplate_vb, 10.0), + (beckman_coulter_biomek_24_wellplate_square_rb, 42.0), + ): + with self.subTest(make.__name__): + plate = make("plate", with_lid=True) + lid = plate.lid + assert lid is not None and lid.location is not None + point = lid.preferred_pickup_location + assert point is not None + self.assertAlmostEqual(lid.location.z + point.z, tips_above) + self.assertEqual( + (lid.get_size_x(), lid.get_size_y()), (plate.get_size_x(), plate.get_size_y()) + ) + + def test_an_uncentred_seat_moves_the_grip_point(self) -> None: + # The Thomson lid's seat is its plate's corner: its centre 0.381 mm left, 1.46 mm back. + plate = beckman_coulter_biomek_24_wellplate_square_rb("plate", with_lid=True) + lid = plate.lid + assert lid is not None and lid.preferred_pickup_location is not None + self.assertAlmostEqual(lid.preferred_pickup_location.x - lid.get_size_x() / 2, -0.381) + self.assertAlmostEqual(lid.preferred_pickup_location.y - lid.get_size_y() / 2, 1.4605) + + def test_plates_are_gripped_below_their_bottom(self) -> None: + plate = beckman_coulter_biomek_96_wellplate_vb("plate") + assert plate.preferred_pickup_location is not None + self.assertAlmostEqual(plate.preferred_pickup_location.z, -2.3) + + +class BiomekReservoirTests(unittest.TestCase): + def test_a_reservoir_section_is_a_box(self) -> None: + well = beckman_coulter_biomek_reservoir_350cb("res").get_well("A1") + self.assertAlmostEqual(well.compute_volume_from_height(10), 123.8 * 81.5 * 10, delta=0.01) + self.assertEqual(well.max_volume, 300000.0) + + def test_reservoirs_have_a_well_per_section(self) -> None: + self.assertEqual(len(beckman_coulter_biomek_reservoir("res").children), 1) + modular = beckman_coulter_biomek_modular_reservoir("mod") + self.assertEqual(len(modular.children), 4) + a1 = modular.get_item("A1") + self.assertAlmostEqual(a1.get_size_x(), 23.65) # x1 1.105 to x2 3.47 cm + assert isinstance(a1, BiomekWell) + self.assertEqual(a1.segments, ()) # a V bottom Biomek does not outline + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/resources/beckman_coulter/biomek_resource.py b/pylabrobot/resources/beckman_coulter/biomek_resource.py new file mode 100644 index 00000000000..63f6721c23d --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/biomek_resource.py @@ -0,0 +1,219 @@ +"""Biomek's own shapes on PyLabRobot's resources: a tip's cone and a well's outline by height. + +Biomek describes a tip by its length, capacity and seating depth (which `Tip` holds) and also by its +cone, and a well by its sections from the bottom up, each with an outline that changes with height. +A Biomek touch-off places the tip against the wall at a height, so it needs both: these classes +carry them, and everything else about the resource is PyLabRobot's. +""" + +import math +from dataclasses import asdict, dataclass +from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union + +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.tip import Tip +from pylabrobot.resources.well import Well +from pylabrobot.utils.interpolation import interpolate_1d + + +class BiomekTip(Tip): + """A tip for Biomek instruments: a `Tip` with its cone, which Biomek uses to place the tip near a + wall (a touch-off), from `end_diameter` at its end to `diameter` over `cone_length` (mm).""" + + def __init__( + self, + name: str, + diameter: float, + size_z: float, + has_filter: bool, + maximal_volume: float, + fitting_depth: float, + end_diameter: float, + cone_length: float, + nominal_volume: Optional[float] = None, + collar_height: Optional[float] = None, + category: str = "tip", + model: Optional[str] = None, + pick_up_location: Optional[Coordinate] = None, + is_conductive: Optional[bool] = None, + ): + """Initialize a Biomek tip with its dimensions and its cone.""" + super().__init__( + name=name, + diameter=diameter, + size_z=size_z, + has_filter=has_filter, + maximal_volume=maximal_volume, + fitting_depth=fitting_depth, + nominal_volume=nominal_volume, + collar_height=collar_height, + category=category, + model=model, + pick_up_location=pick_up_location, + is_conductive=is_conductive, + ) + self.end_diameter = end_diameter + self.cone_length = cone_length + + def __eq__(self, other: object) -> bool: + """Compare tip fields and the cone.""" + return ( + isinstance(other, BiomekTip) + and super().__eq__(other) + and self.end_diameter == other.end_diameter + and self.cone_length == other.cone_length + ) + + def serialize(self) -> dict: + """Serialize a Biomek tip with its cone.""" + return { + **super().serialize(), + "end_diameter": self.end_diameter, + "cone_length": self.cone_length, + } + + def radius_at(self, from_end: float) -> float: + """The tip's outside radius `from_end` mm above its end: widening along the cone, then its + full radius.""" + end, full = self.end_diameter / 2, self.get_size_x() / 2 + if self.cone_length <= 0: + return full + return end + (full - end) * min(max(from_end, 0.0) / self.cone_length, 1.0) + + +@dataclass(frozen=True) +class WellSegment: + """One section of a Biomek well, from the bottom up, in mm. + + Attributes: + height: how tall the section is. + top_x, top_y: its half-widths at its top (the radius, for a round section). + bottom_x, bottom_y: its half-widths at its bottom (0 for a cone from a point). + round: whether its outline is round (else a rectangle). + cap: a round bottom: a spherical cap reaching `top_x` at `height`. + """ + + height: float + top_x: float + top_y: float + bottom_x: float + bottom_y: float + round: bool = True + cap: bool = False + + def half_widths(self, z: float) -> Tuple[float, float]: + """Half-widths (x, y), mm, `z` mm above the section's bottom.""" + if self.cap: + sphere = (self.top_x * self.top_x + self.height * self.height) / (2 * self.height) + r = math.sqrt(max(0.0, 2 * sphere * z - z * z)) + return r, r + t = z / self.height + return ( + self.bottom_x + (self.top_x - self.bottom_x) * t, + self.bottom_y + (self.top_y - self.bottom_y) * t, + ) + + def area(self, z: float) -> float: + """Cross-section, mm^2, `z` mm above the section's bottom.""" + hx, hy = self.half_widths(z) + return math.pi * hx * hy if self.round else 4 * hx * hy + + def volume(self, h: float) -> float: + """uL (mm^3) in the bottom `h` mm of the section. The area is quadratic in z for every shape, + so Simpson's rule is exact.""" + h = min(h, self.height) + if h <= 0: + return 0.0 + return h / 6 * (self.area(0) + 4 * self.area(h / 2) + self.area(h)) + + +# mm between a height -> volume table's heights where a section's cross-section changes with height +# (a cone, a cap): PyLabRobot interpolates between them. +KNOT_STEP = 0.1 + + +class BiomekWell(Well): + """A well with Biomek's outline by height (`segments`, bottom up): its height <-> volume table + (`height_volume_data`) is made from them, and `wall_distance` says where its wall is at a height. + With no segments it is a plain `Well`.""" + + def __init__( + self, + name: str, + size_x: float, + size_y: float, + size_z: float, + segments: Sequence[Union[WellSegment, Mapping[str, Any]]] = (), + height_volume_data: Optional[Dict[float, float]] = None, + max_volume: Optional[float] = None, + **kwargs: Any, + ): + self.segments: Tuple[WellSegment, ...] = tuple( + s if isinstance(s, WellSegment) else WellSegment(**s) for s in segments + ) + if height_volume_data is None and self.segments: + height_volume_data = self._height_volume_table(size_z) + if max_volume is None and height_volume_data is not None: + max_volume = interpolate_1d(size_z, height_volume_data, bounds_handling="error") + super().__init__( + name=name, + size_x=size_x, + size_y=size_y, + size_z=size_z, + height_volume_data=height_volume_data, + max_volume=max_volume, + **kwargs, + ) + + def half_widths(self, z: float) -> Tuple[float, float]: + """Half-widths (x, y), mm, `z` mm above the bottom (the top's above the top).""" + left = max(0.0, z) + for seg in self.segments: + if left <= seg.height: + return seg.half_widths(left) + left -= seg.height + last = self.segments[-1] + return last.half_widths(last.height) + + def wall_distance(self, z: float, angle: float) -> float: + """How far, mm, the wall is from the well's axis `z` mm above its bottom, in direction `angle` + (radians): the radius for a round well, to the nearest side for a rectangular one.""" + hx, hy = self.half_widths(z) + if all(s.round for s in self.segments): + return hx + c, s = abs(math.cos(angle)), abs(math.sin(angle)) + return min(hx / c if c > 1e-12 else math.inf, hy / s if s > 1e-12 else math.inf) + + def volume_at(self, z: float) -> float: + """uL held `z` mm above the bottom, by the segments.""" + left, v = z, 0.0 + for seg in self.segments: + v += seg.volume(left) + left -= seg.height + if left <= 0: + break + return v + + def _height_volume_table(self, depth: float) -> Dict[float, float]: + """A point at each section's ends, and every `KNOT_STEP` in a section whose cross-section + changes, up to the rim.""" + zs = [0.0] + for seg in self.segments: + h = seg.height + constant = seg.half_widths(0.0) == seg.half_widths(h) == seg.half_widths(h / 2) + n = 1 if constant else max(1, math.ceil(h / KNOT_STEP)) + zs += [zs[-1] + h * i / n for i in range(1, n + 1)] + if depth > zs[-1]: + zs.append(depth) + return {round(z, 6): self.volume_at(z) for z in zs} + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, BiomekWell) and super().__eq__(other) and self.segments == other.segments + ) + + __hash__ = Resource.__hash__ + + def serialize(self) -> dict: + return {**super().serialize(), "segments": [asdict(s) for s in self.segments]} diff --git a/pylabrobot/resources/beckman_coulter/plates.py b/pylabrobot/resources/beckman_coulter/plates.py new file mode 100644 index 00000000000..62de4335952 --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/plates.py @@ -0,0 +1,348 @@ +"""Plates and reservoirs on Biomek's labware classes (cm there, mm here). + +- `xspan`, `yspan`, `height`: the footprint and height; `wellsx` / `wellsy`, `wellxspacing` / + `wellyspacing`, `well1xoffset` / `well1yoffset` (A1's centre from the left and back edges): the + grid; `welldepth`, the top segment's `topx` / `topy`: a well's size. +- `segments`: a well's outline from the bottom up (`WellSegment`), which gives its height <-> + volume table and where its wall is. +- a reservoir's `sections`: its wells, `x1..x2`, `y1..y2` from the left and back edges, `depth`. +- `gripperinfo`: where Biomek's gripper pads go (`preferred_pickup_location`), the fingertips + `gripperzoffset` above the bottom (below it for a plate). +- `stackablelabwareclasses`: how deep a lid sits on it. +""" + +from typing import Dict, Optional + +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.lid import Lid +from pylabrobot.resources.plate import Plate +from pylabrobot.resources.utils import create_ordered_items_2d +from pylabrobot.resources.well import CrossSectionType, Well, WellBottomType + +from .biomek_resource import BiomekWell, WellSegment + +_96_WELLPLATE_VB_SEGMENTS = ( + WellSegment(2.0, 2.735, 2.735, 0.0, 0.0), + WellSegment(8.5, 4.0, 4.0, 4.0, 4.0), +) + +_96_WELLPLATE_FLAT_SEGMENTS = (WellSegment(10.668, 3.43, 3.43, 3.175, 3.175),) + +_96_DEEPWELL_SQUARE_SEGMENTS = ( + WellSegment(8.61, 3.85, 3.85, 0.0, 0.0), + WellSegment(33.3, 4.14, 4.14, 4.14, 4.14, round=False), +) + +_24_WELLPLATE_SQUARE_RB_SEGMENTS = ( + WellSegment(8.0, 8.0, 8.0, 0.0, 0.0, cap=True), + WellSegment(32.0, 8.5, 8.5, 8.5, 8.5, round=False), +) + + +def beckman_coulter_biomek_96_wellplate_vb(name: str, with_lid: bool = False) -> Plate: + """Greiner polystyrene microplate with 96 round, V-bottomed wells. Part no. 651XXX. + + Biomek labware class Thermo96VB_PP.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses TiterplateLid: x 0.04, y 0.152, z 0.8 cm) 6.1 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.8, + size_y=85.6, + size_z=10.0, # TiterplateLid height 1.0 cm + nesting_z_height=6.1, + model="beckman_coulter_biomek_lid_titerplatelid", + ) + # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.9, 42.805, 2.0) + plate = Plate( + name=name, + size_x=127.8, # xspan 12.78 cm + size_y=85.6, # yspan 8.56 cm + size_z=14.1, # height 1.41 cm + model=beckman_coulter_biomek_96_wellplate_vb.__name__, + lid=lid, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=12, + num_items_y=8, + dx=11.31, # well1xoffset 1.44 cm, less half the well + dy=8.31, # the front row; A1 (well1yoffset 1.12 cm) is at the back + dz=3.6, + item_dx=9.0, + item_dy=9.0, + size_x=6.18, + size_y=6.18, + size_z=10.5, # welldepth 1.05 cm + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.CIRCLE, + segments=_96_WELLPLATE_VB_SEGMENTS, + max_volume=440.0, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(63.9, 42.8, -2.3) + return plate + + +def beckman_coulter_biomek_96_wellplate_flat(name: str, with_lid: bool = False) -> Plate: + """Beckman Coulter microplate with 96 round, flat-bottomed wells. Part no. 609844. + + Biomek labware class BCFlat96.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses TiterplateLid: x 0.038, y 0.146, z 0.8 cm) 6.224 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.762, + size_y=85.471, + size_z=10.0, # TiterplateLid height 1.0 cm + nesting_z_height=6.224, + model="beckman_coulter_biomek_lid_titerplatelid", + ) + # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.88, 42.736, 2.0) + plate = Plate( + name=name, + size_x=127.762, # xspan 12.7762 cm + size_y=85.471, # yspan 8.5471 cm + size_z=14.224, # height 1.4224 cm + model=beckman_coulter_biomek_96_wellplate_flat.__name__, + lid=lid, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=12, + num_items_y=8, + dx=10.95, # well1xoffset 1.438 cm, less half the well + dy=7.811, # the front row; A1 (well1yoffset 1.123 cm) is at the back + dz=3.556, + item_dx=9.0, + item_dy=9.0, + size_x=6.86, + size_y=6.86, + size_z=10.668, # welldepth 1.0668 cm + bottom_type=WellBottomType.FLAT, + cross_section_type=CrossSectionType.CIRCLE, + segments=_96_WELLPLATE_FLAT_SEGMENTS, + max_volume=362.76, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(63.881, 42.7355, -2.3) + return plate + + +def beckman_coulter_biomek_96_deepwell_square(name: str) -> Plate: + """Beckman Coulter microplate with 96 deep, square, V-bottomed wells. Part no. 140504. + + Biomek labware class BCDeep96Square.""" + plate = Plate( + name=name, + size_x=128.17, # xspan 12.817 cm + size_y=85.98, # yspan 8.598 cm + size_z=44.2, # height 4.42 cm + model=beckman_coulter_biomek_96_deepwell_square.__name__, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=12, + num_items_y=8, + dx=10.2364, # well1xoffset 1.43764 cm, less half the well + dy=7.46, # the front row; A1 (well1yoffset 1.138 cm) is at the back + dz=2.29, + item_dx=9.0, + item_dy=9.0, + size_x=8.28, + size_y=8.28, + size_z=41.91, # welldepth 4.191 cm + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + segments=_96_DEEPWELL_SQUARE_SEGMENTS, + max_volume=2200.0, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(64.085, 42.99, -2.3) + return plate + + +def beckman_coulter_biomek_24_wellplate_square_rb(name: str, with_lid: bool = False) -> Plate: + """Thomson microplate with 24 square, round-bottomed wells. Part no. 931568. + + Biomek labware class Thomson_24w_Square_RB.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses Thomson_24w_Square_RB_Lid: x 0.0, y 0.0, z 3.4 cm) 10.0 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.762, + size_y=85.471, + size_z=10.0, # Thomson_24w_Square_RB_Lid height 1.0 cm + nesting_z_height=10.0, + model="beckman_coulter_biomek_lid_thomson_24w_square_rb_lid", + ) + # Biomek's pads: the Thomson_24w_Square_RB_Lid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.5, 44.196, 8.0) + plate = Plate( + name=name, + size_x=127.762, # xspan 12.7762 cm + size_y=85.471, # yspan 8.5471 cm + size_z=44.0, # height 4.4 cm + model=beckman_coulter_biomek_24_wellplate_square_rb.__name__, + lid=lid, + ordered_items=create_ordered_items_2d( + BiomekWell, + num_items_x=6, + num_items_y=4, + dx=10.5, # well1xoffset 1.9 cm, less half the well + dy=6.971, # the front row; A1 (well1yoffset 1.6 cm) is at the back + dz=4.0, + item_dx=18.0, + item_dy=18.0, + size_x=17.0, + size_y=17.0, + size_z=40.0, # welldepth 4.0 cm + bottom_type=WellBottomType.U, + cross_section_type=CrossSectionType.RECTANGLE, + segments=_24_WELLPLATE_SQUARE_RB_SEGMENTS, + max_volume=10000.0, # wellvolume + name_prefix=name, + ), + ) + plate.preferred_pickup_location = Coordinate(63.881, 42.7355, -2.3) + return plate + + +def beckman_coulter_biomek_reservoir_350cb(name: str, with_lid: bool = False) -> Plate: + """Thermo Nunc reservoir with one flat-bottomed section. + + Biomek labware class ThermoNUNC_350CB: a well per section.""" + lid: Optional[Lid] = None + if with_lid: + # PyLabRobot's lid covers the plate's footprint; Biomek seats it + # (stackablelabwareclasses TiterplateLid: x 0.0, y 0.0, z 3.4 cm) 4.0 mm into the plate. + lid = Lid( + name=f"{name}_lid", + size_x=127.8, + size_y=85.85, + size_z=10.0, # TiterplateLid height 1.0 cm + nesting_z_height=4.0, + model="beckman_coulter_biomek_lid_titerplatelid", + ) + # Biomek's pads: the TiterplateLid's own centre on its seat, gripperzoffset above its bottom. + lid.preferred_pickup_location = Coordinate(63.5, 44.575, 2.0) + wells: Dict[str, Well] = {} + wells["A1"] = BiomekWell( + name=f"{name}_A1", + size_x=123.8, # x1 0.2 to x2 12.58 cm + size_y=81.5, # y1 0.2 to y2 8.35 cm + size_z=37.4, # depth 3.74 cm + segments=(WellSegment(37.4, 61.9, 40.75, 61.9, 40.75, round=False),), + bottom_type=WellBottomType.FLAT, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=300000.0, # maxvolume + ) + wells["A1"].location = Coordinate(2.0, 2.35, 0.6) + plate = Plate( + name=name, + size_x=127.8, # xspan 12.78 cm + size_y=85.85, # yspan 8.585 cm + size_z=38.0, # height 3.8 cm + model=beckman_coulter_biomek_reservoir_350cb.__name__, + lid=lid, + ordered_items=wells, + ) + plate.preferred_pickup_location = Coordinate(63.9, 42.925, -2.0) + return plate + + +def beckman_coulter_biomek_reservoir(name: str) -> Plate: + """Reservoir used with the Multimek. Part no. 148033. + + Biomek labware class Reservoir: a well per section.""" + wells: Dict[str, Well] = {} + wells["A1"] = BiomekWell( + name=f"{name}_A1", + size_x=111.04, # x1 0.826 to x2 11.93 cm + size_y=72.65, # y1 0.635 to y2 7.9 cm + size_z=14.53, # depth 1.453 cm + segments=(WellSegment(14.53, 55.52, 36.325, 55.52, 36.325, round=False),), + bottom_type=WellBottomType.FLAT, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=110000.0, # maxvolume + ) + wells["A1"].location = Coordinate(8.26, 3.55, 14.68) + plate = Plate( + name=name, + size_x=127.0, # xspan 12.7 cm + size_y=82.55, # yspan 8.255 cm + size_z=29.21, # height 2.921 cm + model=beckman_coulter_biomek_reservoir.__name__, + ordered_items=wells, + ) + plate.preferred_pickup_location = Coordinate(63.5, 41.275, -2.3) + return plate + + +def beckman_coulter_biomek_modular_reservoir(name: str) -> Plate: + """Beckman Coulter reservoir that may be customized with added sections. Part no. 372795 (Frame); 372790(Quarter); 373792(Quarter Divided by Width); 372788 (Quarter Divided by Length); 372786(Half); 372794(Half Divided by Width). + + Biomek labware class ModularReservoir: a well per section.""" + wells: Dict[str, Well] = {} + wells["A1"] = BiomekWell( + name=f"{name}_A1", + size_x=23.65, # x1 1.105 to x2 3.47 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A1"].location = Coordinate(11.05, 8.69, 14.07) + wells["A2"] = BiomekWell( + name=f"{name}_A2", + size_x=23.65, # x1 3.84825 to x2 6.21325 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A2"].location = Coordinate(38.4825, 8.69, 14.07) + wells["A3"] = BiomekWell( + name=f"{name}_A3", + size_x=23.65, # x1 6.5915 to x2 8.9565 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A3"].location = Coordinate(65.915, 8.69, 14.07) + wells["A4"] = BiomekWell( + name=f"{name}_A4", + size_x=23.65, # x1 9.33475 to x2 11.69975 cm + size_y=69.19, # y1 0.772 to y2 7.691 cm + size_z=24.79, # depth 2.479 cm + # a V bottom 1.156 cm deep: no outline + bottom_type=WellBottomType.V, + cross_section_type=CrossSectionType.RECTANGLE, + max_volume=40700.0, # maxvolume + ) + wells["A4"].location = Coordinate(93.3475, 8.69, 14.07) + plate = Plate( + name=name, + size_x=127.41, # xspan 12.741 cm + size_y=85.6, # yspan 8.56 cm + size_z=38.86, # height 3.886 cm + model=beckman_coulter_biomek_modular_reservoir.__name__, + ordered_items=wells, + ) + plate.preferred_pickup_location = Coordinate(63.705, 42.8, -2.3) + return plate diff --git a/pylabrobot/resources/beckman_coulter/tip_racks.py b/pylabrobot/resources/beckman_coulter/tip_racks.py new file mode 100644 index 00000000000..e00d258fa8c --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/tip_racks.py @@ -0,0 +1,179 @@ +"""Beckman Coulter Biomek tip boxes, from Biomek's labware classes (cm there, mm here). + +- `xspan`, `yspan`, `height`: the box's footprint and height, tips in. +- `wellsx`, `wellsy`, `wellxspacing`, `wellyspacing`: the tip grid. +- `well1xoffset`, `well1yoffset`: tip A1's centre, from the box's left and back edges. +- `wellradius`: the radius of the hole a tip stands in. +- `gripperinfo`: where Biomek's gripper pads go (`preferred_pickup_location`). + +The tips' tops are at the box's `height`, where the head's mandrels meet them, so a tip spot sits +on the top face, as on a nested rack. +""" + +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.tip_rack import StandingTipRack, TipSpot +from pylabrobot.resources.utils import create_ordered_items_2d + +from .tips import ( + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, + beckman_coulter_biomek_tip_190uL_filter, + beckman_coulter_biomek_tip_230uL, + beckman_coulter_biomek_tip_50uL_filter, +) + + +def beckman_coulter_biomek_96_tiprack_50uL_filter( + name: str, with_tips: bool = True +) -> StandingTipRack: + """Biomek BC50F tip box: 96 T50F tips (`beckman_coulter_biomek_tip_50uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T50 filter tips. Part no. B85888. + + Labware class BC50F.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=55.9, # height 5.59 cm + model=beckman_coulter_biomek_96_tiprack_50uL_filter.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.7, # well1xoffset 1.45 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=55.9, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_50uL_filter, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_190uL_filter( + name: str, with_tips: bool = True +) -> StandingTipRack: + """Biomek BC190F tip box: 96 T190F tips (`beckman_coulter_biomek_tip_190uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T190 filter tips. Part no. B85911. + + Labware class BC190F.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=55.9, # height 5.59 cm + model=beckman_coulter_biomek_96_tiprack_190uL_filter.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.7, # well1xoffset 1.45 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=55.9, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_190uL_filter, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_230uL(name: str, with_tips: bool = True) -> StandingTipRack: + """Biomek BC230 tip box: 96 T230 tips (`beckman_coulter_biomek_tip_230uL`). Beckman Coulter tip box containing 96 T230 tips. Part no. Sterile: B85906, Non-Sterile: B85903. + + Labware class BC230.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=55.9, # height 5.59 cm + model=beckman_coulter_biomek_96_tiprack_230uL.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.7, # well1xoffset 1.45 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=55.9, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_230uL, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_1025uL_filter( + name: str, with_tips: bool = True +) -> StandingTipRack: + """Biomek BC1025F tip box: 96 T1025F tips (`beckman_coulter_biomek_tip_1025uL_filter`). Beckman Coulter tip box containing 96 Aerosol Resistant T1025 filtered tips. Part no. B85955. + + Labware class BC1025F.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=114.1, # height 11.41 cm + model=beckman_coulter_biomek_96_tiprack_1025uL_filter.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.6, # well1xoffset 1.44 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=114.1, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_1025uL_filter, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack + + +def beckman_coulter_biomek_96_tiprack_1070uL(name: str, with_tips: bool = True) -> StandingTipRack: + """Biomek BC1070 tip box: 96 T1070 tips (`beckman_coulter_biomek_tip_1070uL`). Beckman Coulter tip box containing 96 T1070 tips. Part no. Sterile: B85945, Non-Sterile: B85940. + + Labware class BC1070.""" + rack = StandingTipRack( + name=name, + size_x=127.9, # xspan 12.79 cm + size_y=85.4, # yspan 8.54 cm + size_z=114.1, # height 11.41 cm + model=beckman_coulter_biomek_96_tiprack_1070uL.__name__, + ordered_items=create_ordered_items_2d( + TipSpot, + num_items_x=12, + num_items_y=8, + dx=11.6, # well1xoffset 1.44 cm, less the hole's radius + dy=8.4, # the front row's hole; A1 (well1yoffset 1.12 cm) is at the back + dz=114.1, + item_dx=9.0, + item_dy=9.0, + size_x=5.6, # wellradius 0.28 cm + size_y=5.6, + make_tip=beckman_coulter_biomek_tip_1070uL, + name_prefix=name, + ), + with_tips=with_tips, + ) + rack.preferred_pickup_location = Coordinate(63.95, 42.7, -2.3) + return rack diff --git a/pylabrobot/resources/beckman_coulter/tips.py b/pylabrobot/resources/beckman_coulter/tips.py new file mode 100644 index 00000000000..756b870e92c --- /dev/null +++ b/pylabrobot/resources/beckman_coulter/tips.py @@ -0,0 +1,96 @@ +"""Beckman Coulter Biomek tips, from Biomek's tip classes (lengths in cm there, mm here). + +- `tipheight`: the tip's length; `capacity`: its volume in uL; `filtered`: a filter tip. +- `spanseatingdepth`: how far a mandrel goes into the tip. +- `maxtipradius`: the tip's radius where it seats on the mandrel. +- `mintipradius`, `coniclength`: its radius at the end, and the length over which it widens from + there to `maxtipradius` (the cone). +- `lls`: whether the tip is conductive, for liquid-level sensing. +""" + +from .biomek_resource import BiomekTip + + +def beckman_coulter_biomek_tip_50uL_filter(name: str) -> BiomekTip: + """Biomek T50F tip, 50 uL, filter: tip class T50F.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_50uL_filter.__name__, + diameter=5.182, # maxtipradius 0.2591 cm + size_z=51.359, # tipheight 5.1359 cm + has_filter=True, + maximal_volume=50.0, # capacity + nominal_volume=50.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=0.812, # mintipradius 0.0406 cm + cone_length=38.227, # coniclength 3.8227 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_190uL_filter(name: str) -> BiomekTip: + """Biomek T190F tip, 190 uL, filter: tip class T190F.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_190uL_filter.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=51.435, # tipheight 5.1435 cm + has_filter=True, + maximal_volume=190.0, # capacity + nominal_volume=190.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=28.194, # coniclength 2.8194 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_230uL(name: str) -> BiomekTip: + """Biomek T230 tip, 230 uL, no filter: tip class T230.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_230uL.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=51.435, # tipheight 5.1435 cm + has_filter=False, + maximal_volume=230.0, # capacity + nominal_volume=230.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=28.194, # coniclength 2.8194 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_1025uL_filter(name: str) -> BiomekTip: + """Biomek T1025F tip, 1025 uL, filter: tip class T1025F.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_1025uL_filter.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=109.855, # tipheight 10.9855 cm + has_filter=True, + maximal_volume=1025.0, # capacity + nominal_volume=1025.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=19.8374, # coniclength 1.98374 cm + is_conductive=False, # lls + ) + + +def beckman_coulter_biomek_tip_1070uL(name: str) -> BiomekTip: + """Biomek T1070 tip, 1070 uL, no filter: tip class T1070.""" + return BiomekTip( + name=name, + model=beckman_coulter_biomek_tip_1070uL.__name__, + diameter=4.826, # maxtipradius 0.2413 cm + size_z=109.855, # tipheight 10.9855 cm + has_filter=False, + maximal_volume=1070.0, # capacity + nominal_volume=1070.0, + fitting_depth=7.75, # spanseatingdepth 0.775 cm + end_diameter=1.27, # mintipradius 0.0635 cm + cone_length=19.8374, # coniclength 1.98374 cm + is_conductive=False, # lls + ) From 89cfcf035a8aa54585ecc126d07751cd8c23f755 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:55:54 +0000 Subject: [PATCH 03/28] `resources`: sort Beckman Coulter import blocks for ruff I001 --- .../resources/beckman_coulter/beckman_coulter_tests.py | 2 +- pylabrobot/resources/beckman_coulter/tip_racks.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py index 72932f1c839..9d267dddfc9 100644 --- a/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py +++ b/pylabrobot/resources/beckman_coulter/beckman_coulter_tests.py @@ -6,8 +6,8 @@ from pylabrobot.resources import ( BiomekTip, - Plate, BiomekWell, + Plate, Resource, WellSegment, beckman_coulter_biomek_24_wellplate_square_rb, diff --git a/pylabrobot/resources/beckman_coulter/tip_racks.py b/pylabrobot/resources/beckman_coulter/tip_racks.py index e00d258fa8c..1e8ef072f54 100644 --- a/pylabrobot/resources/beckman_coulter/tip_racks.py +++ b/pylabrobot/resources/beckman_coulter/tip_racks.py @@ -15,11 +15,11 @@ from pylabrobot.resources.utils import create_ordered_items_2d from .tips import ( - beckman_coulter_biomek_tip_1025uL_filter, - beckman_coulter_biomek_tip_1070uL, + beckman_coulter_biomek_tip_50uL_filter, beckman_coulter_biomek_tip_190uL_filter, beckman_coulter_biomek_tip_230uL, - beckman_coulter_biomek_tip_50uL_filter, + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, ) From 3083c2e42cac3a903894112805884d59fcbbbf04 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:57:51 -0800 Subject: [PATCH 04/28] `resources`: a tip mounting shaft's state is the tip it carries `TipMountingShaft.serialize_state` holds the tool the shaft carries (as it serializes; None for none), as a tip spot's state holds its tip, and `load_state` puts it back: the saved tip goes onto the shaft (a tool of the same name held elsewhere in the tree gives way first), and a saved None takes off the one it carries. State saved before shafts had any leaves the shaft as it is. With it, `save_state_to_file` / `load_state_from_file` keep the tips a head carries across sessions, which a device that cannot sense its tips needs. Tests: a carried tip saved and read back, its own state after it; None taking a tip off; the same tip staying; a tip of that name held elsewhere giving way. --- pylabrobot/resources/n_channel_pipettes.py | 27 +++++++++- .../resources/n_channel_pipettes_tests.py | 49 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/pylabrobot/resources/n_channel_pipettes.py b/pylabrobot/resources/n_channel_pipettes.py index 6e3fe04725c..72b6762fafe 100644 --- a/pylabrobot/resources/n_channel_pipettes.py +++ b/pylabrobot/resources/n_channel_pipettes.py @@ -4,7 +4,7 @@ from typing import Any, Dict, List, Literal, Mapping, Optional, cast, get_args from pylabrobot.resources.coordinate import Coordinate -from pylabrobot.resources.head_tool import HeadTool, move_tool +from pylabrobot.resources.head_tool import HeadTool, move_tool, release_named_tool from pylabrobot.resources.itemized_resource import ItemizedResource from pylabrobot.resources.resource import Resource from pylabrobot.resources.well import CrossSectionType @@ -145,6 +145,31 @@ def tip_bottom(self) -> Optional[Coordinate]: return None return Coordinate(0.0, 0.0, cast(Coordinate, tip.location).z) + def serialize_state(self) -> Dict[str, Any]: + """This shaft's state: the tool it carries (`tip`, as it serializes; None for none), as a tip + spot's state holds its tip. A device that cannot sense its tips reads them back from it.""" + tip = self.tip + return {**super().serialize_state(), "tip": None if tip is None else tip.serialize()} + + def load_state(self, state: Dict[str, Any]) -> None: + """Load this shaft's state: the saved `tip` goes onto it (a tool of the same name held + elsewhere in the same tree gives way first); a saved None takes off the one it carries. State + saved before shafts had any leaves it as it is.""" + super().load_state(state) + if "tip" not in state: + return + saved, current = state["tip"], self.tip + if current is not None and saved is not None and current.serialize() == saved: + return + if current is not None: + self.release_tip() + if saved is None: + return + release_named_tool(self.get_root(), saved["name"]) + tip = Resource.deserialize(saved) + assert isinstance(tip, HeadTool) + self.mount_tip(tip) + def serialize(self) -> dict: """What its size does not say: how it holds a tip, and that it is round rather than a box.""" return { diff --git a/pylabrobot/resources/n_channel_pipettes_tests.py b/pylabrobot/resources/n_channel_pipettes_tests.py index 319a5211e0f..212d0f79873 100644 --- a/pylabrobot/resources/n_channel_pipettes_tests.py +++ b/pylabrobot/resources/n_channel_pipettes_tests.py @@ -18,6 +18,55 @@ def test_a_shaft_is_round(self): TipMountingShaft(name="shaft", tip_pickup_mode="core", cross_section_type="rectangle") +class ShaftSavesItsTip(unittest.TestCase): + """A shaft's state is the tool it carries, so a device that cannot sense its tips reads them back.""" + + def setUp(self): + self.shaft = TipMountingShaft(name="shaft", tip_pickup_mode="core") + + def test_a_carried_tip_is_saved_and_read_back(self): + tip = hamilton_tip_300uL(name="tip") + self.shaft.mount_tip(tip) + tip.tracker.set_volume(120) + state = self.shaft.serialize_all_state() + self.assertEqual(state["shaft"]["tip"], tip.serialize()) + + other = TipMountingShaft(name="shaft", tip_pickup_mode="core") + other.load_all_state(state) + self.assertTrue(other.has_tip()) + assert other.tip is not None + self.assertEqual(other.tip.serialize(), tip.serialize()) + self.assertEqual(other.tip.location, tip.location) + self.assertEqual(other.tip.tracker.get_used_volume(), 120) # the tip's own state, after it + + def test_none_saved_takes_the_tip_off(self): + empty = self.shaft.serialize_all_state() + self.assertIsNone(empty["shaft"]["tip"]) + self.shaft.mount_tip(hamilton_tip_300uL(name="tip")) + self.shaft.load_all_state(empty) + self.assertFalse(self.shaft.has_tip()) + + def test_the_same_tip_stays_and_older_state_leaves_it(self): + tip = hamilton_tip_300uL(name="tip") + self.shaft.mount_tip(tip) + self.shaft.load_state(self.shaft.serialize_state()) + self.assertIs(self.shaft.tip, tip) + self.shaft.load_state({}) + self.assertIs(self.shaft.tip, tip) + + def test_a_tip_of_that_name_held_elsewhere_gives_way(self): + root = Resource("root", size_x=100, size_y=100, size_z=10) + first = TipMountingShaft(name="first", tip_pickup_mode="core") + second = TipMountingShaft(name="second", tip_pickup_mode="core") + root.assign_child_resource(first, location=Coordinate.zero()) + root.assign_child_resource(second, location=Coordinate(20, 0, 0)) + first.mount_tip(hamilton_tip_300uL(name="tip")) + saved = first.serialize_state() + second.load_state(saved) + self.assertTrue(second.has_tip()) + self.assertFalse(first.has_tip()) + + class ShaftHoldsItsTip(unittest.TestCase): """A mounting shaft carries its tip as a child, gripping it by the fitting depth.""" From 86ff6e49ad2a73582c5bfec05086946c47c04d0c Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:56:17 +0000 Subject: [PATCH 05/28] `resources`: narrow restored tip to Tip before reading its tracker --- pylabrobot/resources/n_channel_pipettes_tests.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pylabrobot/resources/n_channel_pipettes_tests.py b/pylabrobot/resources/n_channel_pipettes_tests.py index 212d0f79873..394256531d5 100644 --- a/pylabrobot/resources/n_channel_pipettes_tests.py +++ b/pylabrobot/resources/n_channel_pipettes_tests.py @@ -4,6 +4,7 @@ from pylabrobot.resources.hamilton import hamilton_core_gripper_tool, hamilton_tip_300uL from pylabrobot.resources.n_channel_pipettes import TipMountingShaft from pylabrobot.resources.resource import Resource +from pylabrobot.resources.tip import Tip class TestTipMountingShaft(unittest.TestCase): @@ -35,6 +36,7 @@ def test_a_carried_tip_is_saved_and_read_back(self): other.load_all_state(state) self.assertTrue(other.has_tip()) assert other.tip is not None + assert isinstance(other.tip, Tip) self.assertEqual(other.tip.serialize(), tip.serialize()) self.assertEqual(other.tip.location, tip.location) self.assertEqual(other.tip.tracker.get_used_volume(), 120) # the tip's own state, after it From 766ca414930632e9577562807894b3a2f2e94794 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:51:17 -0800 Subject: [PATCH 06/28] `Biomek i7`: ACE boards over USB: framing, messages and read-only discovery The first part of a Beckman Coulter Biomek i7 driver that talks to the instrument's ACE boards directly over USB (0AB5:ACE0), one board per module: the chassis and one per pod. - `driver/framing.py`, `board.py`: length-prefixed frames packed into interrupt transfers; a board's replies matched to their requests by header, two-stage replies (ACCEPTED, DONE), unsolicited messages to subscribers. - `driver/protocol.py`, `errors.py`: every request the Master Controller was logged sending, plus three reads, and nothing else; each field layout as Biomek's `ace_io` log (Log.db3) decodes it. - `driver/master.py`, `features/chassis.py`, `features/pod.py`, `module.py`: discovery places each board by what it reports (Get Module ID: type and side), not by USB order or serial number, then reads each module's serial number, its boards with their application images and versions, and the names of its inputs, in the order of the Master Controller's cold start. It writes nothing to the boards. Unknown types or sides, two boards in one place, and no chassis are refused. - `driver/simulator.py`, `defaults/`: boards replayed from a cold-start recording; a generic one ships, every serial number replaced by a placeholder. Tests: one exact frame per command (from Biomek's `ace_io` log; three reads it never logged from their layout), build and parse round trips, framing inverses, the replay's rules, and discovery on the generic recording. Discovery sends the same requests as on the full driver this series comes from. --- pylabrobot/beckman_coulter/__init__.py | 1 + .../beckman_coulter/biomek_i7/__init__.py | 1 + .../biomek_i7/defaults/__init__.py | 13 + .../defaults/biomek_i7_generic_coldstart.json | 3004 +++++++++++++++++ .../beckman_coulter/biomek_i7/design.md | 28 + .../biomek_i7/driver/__init__.py | 1 + .../beckman_coulter/biomek_i7/driver/board.py | 292 ++ .../biomek_i7/driver/board_tests.py | 183 + .../biomek_i7/driver/configuration.py | 70 + .../biomek_i7/driver/errors.py | 141 + .../biomek_i7/driver/errors_tests.py | 41 + .../biomek_i7/driver/features/__init__.py | 1 + .../biomek_i7/driver/features/chassis.py | 67 + .../biomek_i7/driver/features/pod.py | 77 + .../biomek_i7/driver/framing.py | 100 + .../biomek_i7/driver/framing_tests.py | 118 + .../biomek_i7/driver/master.py | 225 ++ .../biomek_i7/driver/master_tests.py | 218 ++ .../biomek_i7/driver/module.py | 72 + .../biomek_i7/driver/protocol.py | 711 ++++ .../biomek_i7/driver/protocol_tests.py | 566 ++++ .../biomek_i7/driver/simulator.py | 103 + .../biomek_i7/driver/simulator_tests.py | 80 + .../biomek_i7/simulation_tests_support.py | 47 + 24 files changed, 6160 insertions(+) create mode 100644 pylabrobot/beckman_coulter/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_coldstart.json create mode 100644 pylabrobot/beckman_coulter/biomek_i7/design.md create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/board.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/errors.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/framing.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/master.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/module.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/protocol_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py diff --git a/pylabrobot/beckman_coulter/__init__.py b/pylabrobot/beckman_coulter/__init__.py new file mode 100644 index 00000000000..e113ad03137 --- /dev/null +++ b/pylabrobot/beckman_coulter/__init__.py @@ -0,0 +1 @@ +"""Beckman Coulter devices.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/__init__.py new file mode 100644 index 00000000000..421a55e4014 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/__init__.py @@ -0,0 +1 @@ +"""Beckman Coulter Biomek i7, driven over USB through its ACE boards.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py new file mode 100644 index 00000000000..b7118bd6e87 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py @@ -0,0 +1,13 @@ +"""A generic Biomek i7's cold start: what a simulated instrument answers when given no instrument's +own recording. + +Made from one instrument's cold-start recording (the requests the Master Controller sent at a +start and the boards' replies), with every serial number replaced by a placeholder of the same +length. +""" + +from pathlib import Path + +HERE = Path(__file__).parent + +GENERIC_RECORDING = HERE / "biomek_i7_generic_coldstart.json" diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_coldstart.json b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_coldstart.json new file mode 100644 index 00000000000..32739c1cac9 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_coldstart.json @@ -0,0 +1,3004 @@ +{ + "source": "the cold start of one Biomek i7, serial numbers replaced", + "boards": { + "chassis": [ + [ + "00000000", + [ + "000000010002008000" + ] + ], + [ + "00000003", + [ + "000000020302000200" + ] + ], + [ + "00000002", + [ + "0000000302020053494d554c415445443030313030303030303030303030303030303030303030" + ] + ], + [ + "00000012", + [ + "0000000412020078DB2D6D" + ] + ], + [ + "00000011", + [ + "00000005110200C4100400" + ] + ], + [ + "00000008", + [ + "000000060802000101000201002D0100" + ] + ], + [ + "02010003", + [ + "02010007030200E500" + ] + ], + [ + "02010010", + [ + "02010008100200302E322E34" + ] + ], + [ + "20000008", + [ + "2000000A080200210100220900280100" + ] + ], + [ + "22090001", + [ + "2209000B01020054656D7065726174757265" + ] + ], + [ + "22090012", + [ + "2209000C1202006465672E2043" + ] + ], + [ + "22080001", + [ + "2208000D010200416972205072657373757265" + ] + ], + [ + "22080012", + [ + "2208000E1202006B5061" + ] + ], + [ + "22070001", + [ + "2207000F01020048756D6964697479" + ] + ], + [ + "22070012", + [ + "2207001012020025205248" + ] + ], + [ + "22060001", + [ + "220600110102004C69676874204375727461696E20526567756C61746F72" + ] + ], + [ + "22060012", + [ + "2206001212020056" + ] + ], + [ + "22050001", + [ + "220500130102002B33365620496E7465726C6F636B6564" + ] + ], + [ + "22050012", + [ + "2205001412020056" + ] + ], + [ + "22040001", + [ + "220400150102002B333656205377697463686564" + ] + ], + [ + "22040012", + [ + "2204001612020056" + ] + ], + [ + "22030001", + [ + "220300170102002B323456205377697463686564" + ] + ], + [ + "22030012", + [ + "2203001812020056" + ] + ], + [ + "22020001", + [ + "220200190102002B333656" + ] + ], + [ + "22020012", + [ + "2202001A12020056" + ] + ], + [ + "22010001", + [ + "2201001B0102002B35562056427573" + ] + ], + [ + "22010012", + [ + "2201001C12020056" + ] + ], + [ + "21010001", + [ + "2101001E010200446F6F722053656E736F72" + ] + ], + [ + "2101001101", + [ + "2101001F110200" + ] + ], + [ + "21010010", + [ + "2101002010020001" + ] + ], + [ + "28010001", + [ + "280100220102004465636B204C69676874" + ] + ], + [ + "2801001101", + [ + "28010023110200" + ] + ], + [ + "28010010", + [ + "2801002410020000" + ] + ], + [ + "22010010", + [ + "22010025100200F173A540" + ] + ], + [ + "fe000018", + [ + "FE00002618020001000600" + ] + ], + [ + "01010050", + [ + "01010027500200" + ] + ], + [ + "0101001101", + [ + "01010028110200" + ] + ], + [ + "2d01001002", + [ + "2D010029100200" + ] + ], + [ + "ff0100100201", + [ + "FF01002A1002000101" + ] + ], + [ + "01010051", + [ + "0101002B51020000" + ] + ], + [ + "2d01001003", + [ + "2D01002C100200" + ] + ], + [ + "ff01001001790001", + [ + "FF01002F10020001790000" + ] + ], + [ + "ff01001001790000", + [ + "FF01003110020001790000" + ] + ], + [ + "ff010010019300", + [ + "FF010032100200019300" + ] + ], + [ + "22020010", + [ + "220200371002005E050F42" + ] + ], + [ + "22030010", + [ + "220300381002007470BF41" + ] + ], + [ + "22040010", + [ + "22040039100200884D0D42" + ] + ], + [ + "22050010", + [ + "2205003A100200A10E0E42" + ] + ], + [ + "22060010", + [ + "2206003B1002001854AF41" + ] + ], + [ + "22070010", + [ + "2207003C1002000B2B1642" + ] + ], + [ + "22080010", + [ + "2208003D100200EDFBDB42" + ] + ], + [ + "22090010", + [ + "2209003E100200C0F4BB41" + ] + ] + ], + "multichannel": [ + [ + "00000000", + [ + "00000001000200FD01" + ] + ], + [ + "00000003", + [ + "000000020302000100" + ] + ], + [ + "00000002", + [ + "0000000302020053494d554c415445443030323030303030303030303030303030303030303030" + ] + ], + [ + "00000012", + [ + "0000000412020078DB2D6D" + ] + ], + [ + "00000011", + [ + "00000005110200C4100400" + ] + ], + [ + "00000008", + [ + "00000006080200010100020700" + ] + ], + [ + "02070003", + [ + "02070007030200E300" + ] + ], + [ + "02070010", + [ + "02070009100200322E322E33" + ] + ], + [ + "02060003", + [ + "0206000A0302000001" + ] + ], + [ + "02060002", + [ + "0206000b02020053494d554c415445443030333030303030303030303030303030303030303030" + ] + ], + [ + "02060012", + [ + "0206000C12020078DB2D6D" + ] + ], + [ + "02060011", + [ + "0206000D110200C4100400" + ] + ], + [ + "02050003", + [ + "0205000E0302000001" + ] + ], + [ + "02050002", + [ + "0205000f02020053494d554c415445443030343030303030303030303030303030303030303030" + ] + ], + [ + "02050012", + [ + "0205001012020078DB2D6D" + ] + ], + [ + "02050011", + [ + "02050011110200C4100400" + ] + ], + [ + "02040003", + [ + "020400120302000001" + ] + ], + [ + "02040002", + [ + "0204001302020053494d554c415445443030353030303030303030303030303030303030303030" + ] + ], + [ + "02040012", + [ + "0204001412020078DB2D6D" + ] + ], + [ + "02040011", + [ + "02040015110200C4100400" + ] + ], + [ + "02030003", + [ + "020300160302000001" + ] + ], + [ + "02030002", + [ + "0203001702020053494d554c415445443030363030303030303030303030303030303030303030" + ] + ], + [ + "02030012", + [ + "0203001812020078DB2D6D" + ] + ], + [ + "02030011", + [ + "02030019110200C4100400" + ] + ], + [ + "02020003", + [ + "0202001A0302000001" + ] + ], + [ + "02020002", + [ + "0202001b02020053494d554c415445443030373030303030303030303030303030303030303030" + ] + ], + [ + "02020012", + [ + "0202001C12020078DB2D6D" + ] + ], + [ + "02020011", + [ + "0202001D110200C4100400" + ] + ], + [ + "02010003", + [ + "0201001E0302000001" + ] + ], + [ + "02010002", + [ + "0201001f02020053494d554c415445443030383030303030303030303030303030303030303030" + ] + ], + [ + "02010012", + [ + "0201002012020078DB2D6D" + ] + ], + [ + "02010011", + [ + "02010021110200C4100400" + ] + ], + [ + "20000008", + [ + "20000023080200220400" + ] + ], + [ + "22040001", + [ + "220400240102002B33365620496E7465726C6F636B" + ] + ], + [ + "22040012", + [ + "2204002512020056" + ] + ], + [ + "22030001", + [ + "220300260102002B355620555342" + ] + ], + [ + "22030012", + [ + "2203002712020056" + ] + ], + [ + "22020001", + [ + "220200280102002B333656" + ] + ], + [ + "22020012", + [ + "2202002912020056" + ] + ], + [ + "22010001", + [ + "2201002A0102002B35562056427573" + ] + ], + [ + "22010012", + [ + "2201002B12020056" + ] + ], + [ + "22010010", + [ + "2201002E1002004DC8A440" + ] + ], + [ + "02070004", + [ + "02070031040200312E302E30" + ] + ], + [ + "af0100f7", + [ + "AF010032F70200280FBB405DDC7740E2A38A40" + ] + ], + [ + "110100100001000000807d02000100000000fc0300010000000088130000000000005a050003000300320000605b0300c8000000002d3101b80b0000000200000180ff800c0000b80b307532000000803801000a0000b80b000050000000000000fb1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000000000020000002c01000032000000", + [ + "11010033100200" + ] + ], + [ + "11020010000100000000ee02000100000000b0040001000000001027000000000000e80300030003003200000071020064000000c0e1e400d007000000020000018000800c0000b80b307532000000803801000a0000b004000050000000000000fb1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000000000020000002c01000032000000", + [ + "11020034100200" + ] + ], + [ + "110300100001000000005f00000100000000f401000100000000aa0a000018fcff0000000003000300140000a0860100e803000040420f00e80300008000000008800034080000800c0852d007000000000000010000f401000050000000000000fa1027000010270000c8000000000000003075000018fcffff800100000000e803881300000000000080ffffffff0a006400000000000000000000000000000000000000000000000000000000000000000000000000000050c3000000000000000000000000000000000000000000000000000000000000000000000fd007410000000000000002000000000000000000000000000000000000", + [ + "11030035100200" + ] + ], + [ + "110400100001000000000003000100000000c01200000000000000000000000000801a06000300000050000050c300006400000000000000c8000000b80b00000d00ff480d0000f00a3075b4000000000000000a0000c012000040010000000000fb10270000401f00000000000000000000a8610000a8a80000000000000000f401dc0500000000000080ffffffff0a00102700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11040036100200" + ] + ], + [ + "110500100001000000030f01000100000029830100010000009b1f0f000000000052060300030003f23d0000400d0300e80300000048e80194110000f30100000d0000b0040000dc05640018010000000000000a00298301006f4d000000000000fb10270000d6060a000000000000000000983a000000000000c60000000000f401a00f00000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11050037100200" + ] + ], + [ + "1106001000010000001966010001000000f9f91b0001000000bac317010000000002f00200030003b735000050c30000e803000080841e00d0070000e10300000d0000bc020000dc056400fa000000e02e00000a00f9f91b001966010000000000fb4c1d000020030a000000000000000000a861000000000000290700000000f401d00700000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000d4feffff3705000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "11060038100200" + ] + ], + [ + "11070010000a000000415d0000bc02000030b301000000000000000000d03effff00000000010003380600000000000000000000000000000000000000000000090000b80b0000dc05e8030000000000000000000030b30100161f000000000000fc1027000088130a000000000000000000c8af0000000000003e0158020000640000000000e803fa0000ffffffff0a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11070039100200" + ] + ], + [ + "110800100001000000ebb8010001000000b9bd050001000000e5f61600c396c6ff000000000300039475000020a107006400000080841e00f40100004b0000000d0000bc020000dc05640004010000b03600000200b9bd050075dc000000000000fa4c1d000020030a000000000000000000983a000000000000f00200000000f401c40900000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "1108003A100200" + ] + ], + [ + "0000000f", + [ + "0000003B0F0200" + ] + ], + [ + "11010021", + [ + "1101003C21020001" + ] + ], + [ + "1103001200", + [ + "1103003D120200" + ] + ], + [ + "1000000f", + [ + "1000003E0F0200" + ] + ], + [ + "1107001200", + [ + "1107003F120200" + ] + ], + [ + "1108001200", + [ + "11080040120200" + ] + ], + [ + "1105001200", + [ + "11050041120200" + ] + ], + [ + "1106001200", + [ + "11060042120200" + ] + ], + [ + "1104001200", + [ + "11040044120200" + ] + ], + [ + "1101001200", + [ + "11010045120200" + ] + ], + [ + "1102001200", + [ + "11020046120200" + ] + ], + [ + "11070024", + [ + "110700472402005EFFFFFF" + ] + ], + [ + "11080024", + [ + "11080048240200B352FDFF" + ] + ], + [ + "11050024", + [ + "1105004924020009F90000" + ] + ], + [ + "11060024", + [ + "1106004A24020000000000" + ] + ], + [ + "11030024", + [ + "1103004B24020001FFFFFF" + ] + ], + [ + "11040024", + [ + "1104004C24020090A80000" + ] + ], + [ + "11010024", + [ + "1101004D240200E28B0000" + ] + ], + [ + "11020024", + [ + "1102004E2402008D910000" + ] + ], + [ + "11030040005f000000f4010000aa0a000000000018fcffff0000", + [ + "11030072400032" + ] + ], + [ + "11030051", + [ + "11030073510100", + "11030073510200" + ] + ], + [ + "11070040415d000030b301000000000000000000000000000000", + [ + "11070075400032" + ] + ], + [ + "11070051", + [ + "11070079510100", + "11070079510200" + ] + ], + [ + "1106004019660100f9f91b00bac3170100000000000000000000", + [ + "1106007B400032" + ] + ], + [ + "11060051", + [ + "1106007C510100", + "1106007C510200" + ] + ], + [ + "1106004019660100f9f91b00bac3170100000000a98b00000000", + [ + "1106007E400200" + ] + ], + [ + "1106005030750000", + [ + "1106007F500100", + "1106007F500200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f6160000000000000000000000", + [ + "11080081400032" + ] + ], + [ + "11080051", + [ + "11080082510100", + "11080082510200" + ] + ], + [ + "22020010", + [ + "22020083100200491C1042" + ] + ], + [ + "11080040ebb80100b9bd0500e5f61600000000009bc1fcff0000", + [ + "11080085400200" + ] + ], + [ + "1108005030750000", + [ + "11080086500100", + "11080086500200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f61600000000009454fdff0000", + [ + "11080088400200" + ] + ], + [ + "11050040030f0100298301009b1f0f0000000000000000000000", + [ + "1105008B400032" + ] + ], + [ + "11050051", + [ + "1105008C510100", + "1105008C510200" + ] + ], + [ + "22030010", + [ + "2203008D1002007A9EA740" + ] + ], + [ + "1107005030750000", + [ + "11070090500100", + "11070090500200" + ] + ], + [ + "11050040030f0100298301009b1f0f0000000000d6b900000000", + [ + "11050093400200" + ] + ], + [ + "1105005030750000", + [ + "11050094500100", + "11050094500200" + ] + ], + [ + "1102004000ee020000b004000010270000000000000000000000", + [ + "11020096400032" + ] + ], + [ + "11020051", + [ + "11020097510100", + "11020097510200" + ] + ], + [ + "1102005030750000", + [ + "1102009A500100", + "1102009A500200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f6160000000000dbd8fdff0000", + [ + "1108009C400200" + ] + ], + [ + "11010040807d020000fc03000088130000000000000000000000", + [ + "1101009F400032" + ] + ], + [ + "11010051", + [ + "110100A0510100", + "110100A0510200" + ] + ], + [ + "22040010", + [ + "220400A110020033BD1042" + ] + ], + [ + "11010040807d020000fc03000088130000000000008c00000000", + [ + "110100A3400200" + ] + ], + [ + "1101005030750000", + [ + "110100A4500100", + "110100A4500200" + ] + ], + [ + "110400400000030000c012000000000000000000a8a800000000", + [ + "110400A6400032" + ] + ], + [ + "11040051", + [ + "110400A7510100", + "110400A7510200" + ] + ], + [ + "11030040005f000000f4010000aa0a000000000000fbffff0000", + [ + "110300F7400200" + ] + ], + [ + "1000005073140000", + [ + "100000F8500100", + "100000F8500200" + ] + ], + [ + "11080040a925000037c60000403a0400000000006cd8fdff0000", + [ + "11080002400200" + ] + ], + [ + "11080040ebb80100b9bd0500e5f6160000000000ad52fdff0000", + [ + "1108000D400200" + ] + ], + [ + "1103004095090000f01f0000bf7f00000000000000ffffff0000", + [ + "1103000E400200" + ] + ], + [ + "100000500c170000", + [ + "1000000F500100", + "1000000F500200" + ] + ], + [ + "11010040150000001f0000003201000000000000038c00000000", + [ + "11010018400200" + ] + ], + [ + "11050040030f0100298301009b1f0f000000000013f900000000", + [ + "11050019400200" + ] + ], + [ + "11020040b86f0200077b030044ce2200000000008a9100000000", + [ + "1102001A400200" + ] + ], + [ + "100000501b170000", + [ + "1000001B500100", + "1000001B500200" + ] + ], + [ + "11070040415d000030b30100000000000000000061ffffff0000", + [ + "11070024400200" + ] + ], + [ + "10000050d4130000", + [ + "10000025500100", + "10000025500200" + ] + ], + [ + "1106004019660100f9f91b00bac3170100000000a78800000000", + [ + "11060026400200" + ] + ], + [ + "10000050f7130000", + [ + "10000027500100", + "10000027500200" + ] + ] + ], + "span8": [ + [ + "00000000", + [ + "00000001000200FB02" + ] + ], + [ + "00000003", + [ + "000000020302000100" + ] + ], + [ + "00000002", + [ + "0000000302020053494d554c415445443030393030303030303030303030303030303030303030" + ] + ], + [ + "00000012", + [ + "0000000412020078DB2D6D" + ] + ], + [ + "00000011", + [ + "00000005110200C4100400" + ] + ], + [ + "00000008", + [ + "00000006080200010100020A00" + ] + ], + [ + "020a0003", + [ + "020A0007030200E300" + ] + ], + [ + "02090003", + [ + "02090009030200E200" + ] + ], + [ + "02090010", + [ + "0209000A100200352E302E39" + ] + ], + [ + "02080003", + [ + "0208000B0302000001" + ] + ], + [ + "02080002", + [ + "0208000c02020053494d554c415445443031303030303030303030303030303030303030303030" + ] + ], + [ + "02080012", + [ + "0208000D12020078DB2D6D" + ] + ], + [ + "02080011", + [ + "0208000E110200C4100400" + ] + ], + [ + "02070003", + [ + "0207000F0302000001" + ] + ], + [ + "02070002", + [ + "0207001002020053494d554c415445443031313030303030303030303030303030303030303030" + ] + ], + [ + "02070012", + [ + "0207001112020078DB2D6D" + ] + ], + [ + "02070011", + [ + "02070012110200C4100400" + ] + ], + [ + "02060003", + [ + "02060013030200E100" + ] + ], + [ + "02060010", + [ + "02060014100200302E372E38" + ] + ], + [ + "02050003", + [ + "02050015030200E000" + ] + ], + [ + "02050010", + [ + "02050016100200302E332E3134" + ] + ], + [ + "02040003", + [ + "02040017030200E000" + ] + ], + [ + "02040010", + [ + "02040018100200302E332E3134" + ] + ], + [ + "02030003", + [ + "02030019030200E000" + ] + ], + [ + "02030010", + [ + "0203001A100200302E332E3134" + ] + ], + [ + "02020003", + [ + "0202001B030200E000" + ] + ], + [ + "02020010", + [ + "0202001C100200302E332E3134" + ] + ], + [ + "02010003", + [ + "0201001D0302000001" + ] + ], + [ + "02010002", + [ + "0201001e02020053494d554c415445443031323030303030303030303030303030303030303030" + ] + ], + [ + "02010012", + [ + "0201001F12020078DB2D6D" + ] + ], + [ + "02010011", + [ + "02010020110200C4100400" + ] + ], + [ + "20000008", + [ + "20000022080200220400" + ] + ], + [ + "22040001", + [ + "220400230102002B33365620496E7465726C6F636B" + ] + ], + [ + "22040012", + [ + "2204002412020056" + ] + ], + [ + "22030001", + [ + "220300250102002B355620555342" + ] + ], + [ + "22030012", + [ + "2203002612020056" + ] + ], + [ + "22020001", + [ + "220200270102002B333656" + ] + ], + [ + "22020012", + [ + "2202002812020056" + ] + ], + [ + "22010001", + [ + "220100290102002B35562056427573" + ] + ], + [ + "22010012", + [ + "2201002A12020056" + ] + ], + [ + "22010010", + [ + "2201002D100200C92CA640" + ] + ], + [ + "11010010000100000000ee02000100000000b00400010000000010270000a6faff0000000003000300320000007102006400000080c3c901b80b0000000200000180ff800c0000b80b307532000000803801000a0000b80b000050000000000000fa1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000001800020000002c01000032000000", + [ + "1101002E100200" + ] + ], + [ + "11020010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "1102002F100200" + ] + ], + [ + "11030010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11030030100200" + ] + ], + [ + "11040010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11040031100200" + ] + ], + [ + "11050010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11050032100200" + ] + ], + [ + "11060010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11060033100200" + ] + ], + [ + "11070010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11070034100200" + ] + ], + [ + "11080010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11080035100200" + ] + ], + [ + "11090010ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + [ + "11090036100200" + ] + ], + [ + "110a0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "110A0037100200" + ] + ], + [ + "110b0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "110B0038100200" + ] + ], + [ + "110c0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "110C0039100200" + ] + ], + [ + "110d0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "110D003A100200" + ] + ], + [ + "110e0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "110E003B100200" + ] + ], + [ + "110f0010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "110F003C100200" + ] + ], + [ + "11100010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + [ + "1110003D100200" + ] + ], + [ + "11110010ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + [ + "1111003E100200" + ] + ], + [ + "12010010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "1201003F100200" + ] + ], + [ + "12020010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12020040100200" + ] + ], + [ + "12030010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12030041100200" + ] + ], + [ + "12040010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12040042100200" + ] + ], + [ + "12050010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12050043100200" + ] + ], + [ + "12060010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12060044100200" + ] + ], + [ + "12070010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12070045100200" + ] + ], + [ + "12080010c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + [ + "12080046100200" + ] + ], + [ + "111200100001000000030f01000100000029830100010000009b1f0f000000000052060300030003f23d0000400d0300e80300000048e80194110000f30100000d0000b0040000dc05640018010000000000000a00298301006f4d000000000000fb10270000d6060a000000000000000000983a000000000000c60000000000f401a00f00000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000001800000000000000000000000000", + [ + "11120047100200" + ] + ], + [ + "1113001000010000001966010001000000f9f91b0001000000bac317010000000002f00200030003b735000050c30000e803000080841e00d0070000e10300000d0000bc020000dc056400fa000000e02e00000a00f9f91b001966010000000000fb4c1d000020030a000000000000000000a861000000000000290700000000f401d00700000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000d4feffff3705000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "11130048100200" + ] + ], + [ + "11140010000a000000415d0000bc02000030b301000000000000000000d03effff00000000010003380600000000000000000000000000000000000000000000090000b80b0000dc05e8030000000000000000000030b30100161f000000000000fc1027000088130a000000000000000000c8af0000000000003e0158020000640000000000e803fa0000ffffffff0a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + [ + "11140049100200" + ] + ], + [ + "111500100001000000ebb8010001000000b9bd050001000000e5f61600c396c6ff000000000300039475000020a107006400000080841e00f40100004b0000000d0000bc020000dc05640004010000b03600000200b9bd050075dc000000000000fa4c1d000020030a000000000000000000983a000000000000f00200000000f401c40900000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + [ + "1115004A100200" + ] + ], + [ + "0000000f", + [ + "0000004B0F0200" + ] + ], + [ + "1000000f", + [ + "1000004C0F0200" + ] + ], + [ + "1115001200", + [ + "1115004D120200" + ] + ], + [ + "1113001200", + [ + "1113004E120200" + ] + ], + [ + "1114001200", + [ + "1114004F120200" + ] + ], + [ + "1208001200", + [ + "12080050120200" + ] + ], + [ + "1112001200", + [ + "11120051120200" + ] + ], + [ + "1206001200", + [ + "12060052120200" + ] + ], + [ + "1207001200", + [ + "12070053120200" + ] + ], + [ + "1204001200", + [ + "12040054120200" + ] + ], + [ + "1205001200", + [ + "12050055120200" + ] + ], + [ + "1202001200", + [ + "12020056120200" + ] + ], + [ + "1203001200", + [ + "12030057120200" + ] + ], + [ + "1111001200", + [ + "11110058120200" + ] + ], + [ + "1201001200", + [ + "12010059120200" + ] + ], + [ + "110f001200", + [ + "110F005A120200" + ] + ], + [ + "1110001200", + [ + "1110005B120200" + ] + ], + [ + "110d001200", + [ + "110D005C120200" + ] + ], + [ + "110e001200", + [ + "110E005D120200" + ] + ], + [ + "110b001200", + [ + "110B005E120200" + ] + ], + [ + "110c001200", + [ + "110C005F120200" + ] + ], + [ + "1109001200", + [ + "11090060120200" + ] + ], + [ + "110a001200", + [ + "110A0061120200" + ] + ], + [ + "1107001200", + [ + "11070062120200" + ] + ], + [ + "1108001200", + [ + "11080063120200" + ] + ], + [ + "1105001200", + [ + "11050064120200" + ] + ], + [ + "1106001200", + [ + "11060065120200" + ] + ], + [ + "1103001200", + [ + "11030066120200" + ] + ], + [ + "1104001200", + [ + "11040067120200" + ] + ], + [ + "1101001200", + [ + "11010068120200" + ] + ], + [ + "1102001200", + [ + "11020069120200" + ] + ], + [ + "11150024", + [ + "1115006A2402006251FDFF" + ] + ], + [ + "11130024", + [ + "1113006B24020000000000" + ] + ], + [ + "11140024", + [ + "1114006C2402005EFFFFFF" + ] + ], + [ + "12080024", + [ + "1208006D240200E0010000" + ] + ], + [ + "11120024", + [ + "1112006E2402008EF80000" + ] + ], + [ + "12060024", + [ + "1206006F240200E0010000" + ] + ], + [ + "12070024", + [ + "12070070240200E0010000" + ] + ], + [ + "12040024", + [ + "12040071240200E0010000" + ] + ], + [ + "12050024", + [ + "12050072240200E0010000" + ] + ], + [ + "12020024", + [ + "12020073240200E0010000" + ] + ], + [ + "12030024", + [ + "12030074240200E0010000" + ] + ], + [ + "11110024", + [ + "111100752402006B200000" + ] + ], + [ + "12010024", + [ + "12010076240200E0010000" + ] + ], + [ + "110f0024", + [ + "110F0077240200DC1F0000" + ] + ], + [ + "11100024", + [ + "1110007824020052200000" + ] + ], + [ + "110d0024", + [ + "110D0079240200EE1F0000" + ] + ], + [ + "110e0024", + [ + "110E007A2402000A200000" + ] + ], + [ + "110b0024", + [ + "110B007B240200F81F0000" + ] + ], + [ + "110c0024", + [ + "110C007C24020026200000" + ] + ], + [ + "11090024", + [ + "1109007D2402006D1A0300" + ] + ], + [ + "110a0024", + [ + "110A007E240200E71F0000" + ] + ], + [ + "11070024", + [ + "1107007F2402005F1A0300" + ] + ], + [ + "11080024", + [ + "110800802402006B1A0300" + ] + ], + [ + "11050024", + [ + "110500812402006B1A0300" + ] + ], + [ + "11060024", + [ + "110600822402006B1A0300" + ] + ], + [ + "11030024", + [ + "110300832402006A1A0300" + ] + ], + [ + "11040024", + [ + "110400842402006B1A0300" + ] + ], + [ + "11010024", + [ + "110100852402006CE1FFFF" + ] + ], + [ + "11020024", + [ + "11020086240200691A0300" + ] + ], + [ + "11100040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "11100005400032" + ] + ], + [ + "11110040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "11110006400032" + ] + ], + [ + "110e0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110E0007400032" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110F0008400032" + ] + ], + [ + "110c0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110C0009400032" + ] + ], + [ + "110d0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110D000A400032" + ] + ], + [ + "110a0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110A000B400032" + ] + ], + [ + "110b0040a6ae02006f711100fcc4f53100000000af2500000000", + [ + "110B000C400032" + ] + ], + [ + "110a0051", + [ + "110A0010510100", + "110A0010510200" + ] + ], + [ + "110e0051", + [ + "110E0011510100", + "110E0011510200" + ] + ], + [ + "110b0051", + [ + "110B0014510100", + "110B0014510200" + ] + ], + [ + "110f0051", + [ + "110F0015510100", + "110F0015510200" + ] + ], + [ + "110c0051", + [ + "110C0018510100", + "110C0018510200" + ] + ], + [ + "11100051", + [ + "11100019510100", + "11100019510200" + ] + ], + [ + "110d0051", + [ + "110D001C510100", + "110D001C510200" + ] + ], + [ + "11110051", + [ + "1111001D510100", + "1111001D510200" + ] + ], + [ + "1000005088130000", + [ + "1000002E500100", + "1000002E500200" + ] + ], + [ + "11140040415d000030b301000000000000000000000000000000", + [ + "11140030400032" + ] + ], + [ + "11140051", + [ + "11140035510100", + "11140035510200" + ] + ], + [ + "1113004019660100f9f91b00bac3170100000000000000000000", + [ + "11130037400032" + ] + ], + [ + "11130051", + [ + "11130039510100", + "11130039510200" + ] + ], + [ + "1113004019660100f9f91b00bac3170100000000a98b00000000", + [ + "1113003B400200" + ] + ], + [ + "1113005030750000", + [ + "1113003C500100", + "1113003C500200" + ] + ], + [ + "22020010", + [ + "2202003D1002001AFC0F42" + ] + ], + [ + "11150040ebb80100b9bd0500e5f6160000000000000000000000", + [ + "1115003F400032" + ] + ], + [ + "11150051", + [ + "11150041510100", + "11150041510200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f61600000000009bc1fcff0000", + [ + "11150043400200" + ] + ], + [ + "1115005030750000", + [ + "11150044500100", + "11150044500200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f61600000000009454fdff0000", + [ + "11150046400200" + ] + ], + [ + "11120040030f0100298301009b1f0f0000000000000000000000", + [ + "11120049400032" + ] + ], + [ + "11120051", + [ + "1112004B510100", + "1112004B510200" + ] + ], + [ + "22030010", + [ + "2203004C100200424FA740" + ] + ], + [ + "1114005030750000", + [ + "1114004F500100", + "1114004F500200" + ] + ], + [ + "11120040030f0100298301009b1f0f0000000000d6b900000000", + [ + "11120053400200" + ] + ], + [ + "1112005030750000", + [ + "11120054500100", + "11120054500200" + ] + ], + [ + "1108004043700100f0f2020080e29e0000000000000000000000", + [ + "1108005D400032" + ] + ], + [ + "1109004043700100f0f2020080e29e0000000000000000000000", + [ + "1109005E400032" + ] + ], + [ + "1106004043700100f0f2020080e29e0000000000000000000000", + [ + "1106005F400032" + ] + ], + [ + "1107004043700100f0f2020080e29e0000000000000000000000", + [ + "11070060400032" + ] + ], + [ + "1104004043700100f0f2020080e29e0000000000000000000000", + [ + "11040061400032" + ] + ], + [ + "1105004043700100f0f2020080e29e0000000000000000000000", + [ + "11050062400032" + ] + ], + [ + "1102004043700100f0f2020080e29e0000000000000000000000", + [ + "11020063400032" + ] + ], + [ + "1103004043700100f0f2020080e29e0000000000000000000000", + [ + "11030064400032" + ] + ], + [ + "11020051", + [ + "1102006E510100", + "1102006E510200" + ] + ], + [ + "22040010", + [ + "2204006F100200A5E60F42" + ] + ], + [ + "11150040ebb80100b9bd0500e5f6160000000000dbd8fdff0000", + [ + "11150093400200" + ] + ], + [ + "1101004000ee020000b004000010270000000000000000000000", + [ + "11010096400032" + ] + ], + [ + "11010051", + [ + "11010098510100", + "11010098510200" + ] + ], + [ + "1101004000ee020000b00400001027000000000000f6ffff0000", + [ + "1101009A400200" + ] + ], + [ + "1101005030750000", + [ + "1101009B500100", + "1101009B500200" + ] + ], + [ + "13010010", + [ + "1301009C1002000202020202020202" + ] + ], + [ + "110b0040ffaa0200ae59110021bdb131000000009d1500000000", + [ + "110B00C8400200" + ] + ], + [ + "110a0040fcad02001d6d11007766e931000000008b1500000000", + [ + "110A00C9400200" + ] + ], + [ + "110d0040feab020029601100e84ac43100000000971500000000", + [ + "110D00CA400200" + ] + ], + [ + "110c004007a30200dc251100e54e1d3100000000cd1500000000", + [ + "110C00CB400200" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000871500000000", + [ + "110F00CC400200" + ] + ], + [ + "110e004083a60200883c11001f3f5e3100000000b81500000000", + [ + "110E00CD400200" + ] + ], + [ + "11110040bd97020071dc100011084b3000000000111600000000", + [ + "111100CE400200" + ] + ], + [ + "11100040649b020032f41000ed0f8f3000000000fb1500000000", + [ + "111000CF400200" + ] + ], + [ + "1000005002140000", + [ + "100000D0500100", + "100000D0500200" + ] + ], + [ + "110b004001260200d0f80d00f89a0428000000009a1500000000", + [ + "110B000C400200" + ] + ], + [ + "110a004001260200d0f80d00f89a042800000000881500000000", + [ + "110A000D400200" + ] + ], + [ + "110d004001260200d0f80d00f89a042800000000941500000000", + [ + "110D000E400200" + ] + ], + [ + "110c004001260200d0f80d00f89a042800000000ca1500000000", + [ + "110C000F400200" + ] + ], + [ + "110f0040ac6e01008b500900a5bcad1a00000000851500000000", + [ + "110F0010400200" + ] + ], + [ + "110e004001260200d0f80d00f89a042800000000b51500000000", + [ + "110E0011400200" + ] + ], + [ + "11110040ac6e01008b500900a5bcad1a000000000f1600000000", + [ + "11110012400200" + ] + ], + [ + "11100040ac6e01008b500900a5bcad1a00000000f91500000000", + [ + "11100013400200" + ] + ], + [ + "100000508e130000", + [ + "10000014500100", + "10000014500200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f616000000000099d8fdff0000", + [ + "1115004F400200" + ] + ], + [ + "11010040ae060000451600001359000000000000faf5ffff0000", + [ + "11010050400200" + ] + ], + [ + "10000050f8130000", + [ + "10000051500100", + "10000051500200" + ] + ], + [ + "1101004000ee020000b004000010270000000000afe1ffff0000", + [ + "1101006F400200" + ] + ], + [ + "100000501a150000", + [ + "10000070500100", + "10000070500200" + ] + ], + [ + "1103004043700100f0f2020080e29e00000000006a1a03000000", + [ + "1103008E400200" + ] + ], + [ + "1102004043700100f0f2020080e29e00000000006a1a03000000", + [ + "1102008F400200" + ] + ], + [ + "1105004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11050090400200" + ] + ], + [ + "1104004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11040091400200" + ] + ], + [ + "1107004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11070092400200" + ] + ], + [ + "1106004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11060093400200" + ] + ], + [ + "1109004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11090094400200" + ] + ], + [ + "1108004043700100f0f2020080e29e00000000006a1a03000000", + [ + "11080095400200" + ] + ], + [ + "10000050f01d0000", + [ + "10000096500100", + "10000096500200" + ] + ], + [ + "11150040ebb80100b9bd0500e5f61600000000006251fdff0000", + [ + "111500B5400200" + ] + ], + [ + "100000500f170000", + [ + "100000B6500100", + "100000B6500200" + ] + ], + [ + "110b0040099e020066051100ee56c03000000000e91800000000", + [ + "110B00B9400200" + ] + ], + [ + "110a004046ac020000621100b190c93100000000e91800000000", + [ + "110A00BA400200" + ] + ], + [ + "110d0040c8a202004424110084bf183100000000e91800000000", + [ + "110D00BB400200" + ] + ], + [ + "110c004011780200760e10003b12fd2d00000000e91800000000", + [ + "110C00BC400200" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000e91800000000", + [ + "110F00BD400200" + ] + ], + [ + "110e0040ad8802007f7a10004980322f00000000e91800000000", + [ + "110E00BE400200" + ] + ], + [ + "111100407b4102007eab0e00795f042a00000000e91800000000", + [ + "111100BF400200" + ] + ], + [ + "11100040e2520200ac1c0f00a189482b00000000e91800000000", + [ + "111000C0400200" + ] + ], + [ + "10000050c1130000", + [ + "100000C1500100", + "100000C1500200" + ] + ], + [ + "1101004000ee020000b004000010270000000000aee1ffff0000", + [ + "1101001A400200" + ] + ], + [ + "10000050a0130000", + [ + "1000001B500100", + "1000001B500200" + ] + ], + [ + "110b004099aa000073550400856f1f0e000000007de2feff0000", + [ + "110B0058400200" + ] + ], + [ + "110a0040f8aa0000d9570400d54c270e00000000d1e1feff0000", + [ + "110A0059400200" + ] + ], + [ + "110d0040aaab00005c5c04002509360e000000008ee0feff0000", + [ + "110D005A400200" + ] + ], + [ + "110c0040d7aa0000035704007991240e000000000de2feff0000", + [ + "110C005B400200" + ] + ], + [ + "110f0040d8aa000006570400aaa6240e000000000ce2feff0000", + [ + "110F005C400200" + ] + ], + [ + "110e00403dab00009859040022032d0e0000000054e1feff0000", + [ + "110E005D400200" + ] + ], + [ + "1111004096aa00005a550400f12f1f0e0000000084e2feff0000", + [ + "1111005E400200" + ] + ], + [ + "1110004082aa0000d954040016881d0e00000000a8e2feff0000", + [ + "1110005F400200" + ] + ], + [ + "100000503f1b0000", + [ + "10000060500100", + "10000060500200" + ] + ], + [ + "12010051", + [ + "12010069510100", + "12010069510200" + ] + ], + [ + "12020040c8000000a05a0000c800000050c300000000000000", + [ + "1202007B400200" + ] + ], + [ + "12010040c8000000a05a0000c800000050c300000000000000", + [ + "1201007C400200" + ] + ], + [ + "12040040c8000000a05a0000c800000050c300000000000000", + [ + "1204007D400200" + ] + ], + [ + "12030040c8000000a05a0000c800000050c300000000000000", + [ + "1203007E400200" + ] + ], + [ + "12060040c8000000a05a0000c800000050c300000000000000", + [ + "1206007F400200" + ] + ], + [ + "12050040c8000000a05a0000c800000050c300000000000000", + [ + "12050080400200" + ] + ], + [ + "12080040c8000000a05a0000c800000050c300000000000000", + [ + "12080081400200" + ] + ], + [ + "12070040c8000000a05a0000c800000050c300000000000000", + [ + "12070082400200" + ] + ], + [ + "1000005070170000", + [ + "10000083500100", + "10000083500200" + ] + ], + [ + "12020040c800000098480000c8000000409c0000c05d000000", + [ + "12020084400200" + ] + ], + [ + "12010040c800000098480000c8000000409c0000c05d000000", + [ + "12010085400200" + ] + ], + [ + "12040040c800000098480000c8000000409c0000c05d000000", + [ + "12040086400200" + ] + ], + [ + "12030040c800000098480000c8000000409c0000c05d000000", + [ + "12030087400200" + ] + ], + [ + "12060040c800000098480000c8000000409c0000c05d000000", + [ + "12060088400200" + ] + ], + [ + "12050040c800000098480000c8000000409c0000c05d000000", + [ + "12050089400200" + ] + ], + [ + "12080040c800000098480000c8000000409c0000c05d000000", + [ + "1208008A400200" + ] + ], + [ + "12070040c800000098480000c8000000409c0000c05d000000", + [ + "1207008B400200" + ] + ], + [ + "10000050b41a0000", + [ + "1000008C500100", + "1000008C500200" + ] + ], + [ + "12020040c8000000a05a0000c800000050c30000c05d000001", + [ + "1202008D400200" + ] + ], + [ + "12010040c8000000a05a0000c800000050c30000c05d000001", + [ + "1201008E400200" + ] + ], + [ + "12040040c8000000a05a0000c800000050c30000c05d000001", + [ + "1204008F400200" + ] + ], + [ + "12030040c8000000a05a0000c800000050c30000c05d000001", + [ + "12030090400200" + ] + ], + [ + "12060040c8000000a05a0000c800000050c30000c05d000001", + [ + "12060091400200" + ] + ], + [ + "12050040c8000000a05a0000c800000050c30000c05d000001", + [ + "12050092400200" + ] + ], + [ + "12080040c8000000a05a0000c800000050c30000c05d000001", + [ + "12080093400200" + ] + ], + [ + "12070040c8000000a05a0000c800000050c30000c05d000001", + [ + "12070094400200" + ] + ], + [ + "12020040c800000098480000c8000000409c00000000000001", + [ + "12020096400200" + ] + ], + [ + "12010040c800000098480000c8000000409c00000000000001", + [ + "12010097400200" + ] + ], + [ + "12040040c800000098480000c8000000409c00000000000001", + [ + "12040098400200" + ] + ], + [ + "12030040c800000098480000c8000000409c00000000000001", + [ + "12030099400200" + ] + ], + [ + "12060040c800000098480000c8000000409c00000000000001", + [ + "1206009A400200" + ] + ], + [ + "12050040c800000098480000c8000000409c00000000000001", + [ + "1205009B400200" + ] + ], + [ + "12080040c800000098480000c8000000409c00000000000001", + [ + "1208009C400200" + ] + ], + [ + "12070040c800000098480000c8000000409c00000000000001", + [ + "1207009D400200" + ] + ], + [ + "100000505b1a0000", + [ + "1000009E500100", + "1000009E500200" + ] + ], + [ + "110b004066aa0200ca551100fcc4f53100000000e91800000000", + [ + "110B0032400200" + ] + ], + [ + "110a0040e0ab0200655f1100fcc4f53100000000e91800000000", + [ + "110A0033400200" + ] + ], + [ + "110d0040a6ae02006f711100fcc4f53100000000e91800000000", + [ + "110D0034400200" + ] + ], + [ + "110c00405cab02000c5c1100fcc4f53100000000e91800000000", + [ + "110C0035400200" + ] + ], + [ + "110f00405eab02001a5c1100fcc4f53100000000e91800000000", + [ + "110F0036400200" + ] + ], + [ + "110e0040f3ac020060661100fcc4f53100000000e91800000000", + [ + "110E0037400200" + ] + ], + [ + "1111004056aa020066551100fcc4f53100000000e91800000000", + [ + "11110038400200" + ] + ], + [ + "1110004007aa020064531100fcc4f53100000000e91800000000", + [ + "11100039400200" + ] + ], + [ + "10000050eb150000", + [ + "1000003A500100", + "1000003A500200" + ] + ], + [ + "12020040c8000000e8000000c800000010270000e001000001", + [ + "1202003B400200" + ] + ], + [ + "12010040c8000000e8000000c800000010270000e001000001", + [ + "1201003C400200" + ] + ], + [ + "12040040c8000000e8000000c800000010270000e001000001", + [ + "1204003D400200" + ] + ], + [ + "12030040c8000000e8000000c800000010270000e001000001", + [ + "1203003E400200" + ] + ], + [ + "12060040c8000000e8000000c800000010270000e001000001", + [ + "1206003F400200" + ] + ], + [ + "12050040c8000000e8000000c800000010270000e001000001", + [ + "12050040400200" + ] + ], + [ + "12080040c8000000e8000000c800000010270000e001000001", + [ + "12080041400200" + ] + ], + [ + "12070040c8000000e8000000c800000010270000e001000001", + [ + "12070042400200" + ] + ], + [ + "10000050951e0000", + [ + "10000043500100", + "10000043500200" + ] + ], + [ + "110b0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110B00D5400200" + ] + ], + [ + "110a0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110A00D6400200" + ] + ], + [ + "110d0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110D00D7400200" + ] + ], + [ + "110c0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110C00D8400200" + ] + ], + [ + "110f0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110F00D9400200" + ] + ], + [ + "110e0040a6ae02006f711100fcc4f53100000000542200000000", + [ + "110E00DA400200" + ] + ], + [ + "11110040a6ae02006f711100fcc4f53100000000542200000000", + [ + "111100DB400200" + ] + ], + [ + "11100040a6ae02006f711100fcc4f53100000000542200000000", + [ + "111000DC400200" + ] + ], + [ + "10000050e6130000", + [ + "100000DD500100", + "100000DD500200" + ] + ], + [ + "11010040360000005d01000024e7030000000000aee1ffff0000", + [ + "110100FB400200" + ] + ], + [ + "110b00400aaa020075531100e9e79f31000000009d1500000000", + [ + "110B00FC400200" + ] + ], + [ + "110a0040cfad0200fc6b11006d28e631000000008b1500000000", + [ + "110A00FD400200" + ] + ], + [ + "110d00404cab0200a25b1100c052b73100000000971500000000", + [ + "110D00FE400200" + ] + ], + [ + "110c0040fb9f02000c1211003491e43000000000cd1500000000", + [ + "110C00FF400200" + ] + ], + [ + "110e004062a40200aa2e11002387363100000000b81500000000", + [ + "110E0002400200" + ] + ], + [ + "11110040bc91020063b51000b32bdb2f00000000111600000000", + [ + "11110003400200" + ] + ], + [ + "11100040589602005dd31000c608313000000000fb1500000000", + [ + "11100004400200" + ] + ], + [ + "10000050f5130000", + [ + "10000005500100", + "10000005500200" + ] + ], + [ + "110a0040513b0000bd540000634f030000000000452300000000", + [ + "110A0023400200" + ] + ], + [ + "110c0040343a000026530000793f030000000000452300000000", + [ + "110C0024400200" + ] + ], + [ + "110b0040033b00004e5400000c4b030000000000452300000000", + [ + "110B0025400200" + ] + ], + [ + "110e00408f3a0000a75300008944030000000000452300000000", + [ + "110E0026400200" + ] + ], + [ + "110d00401d3b0000735400007f4c030000000000452300000000", + [ + "110D0027400200" + ] + ], + [ + "111000406d3900000a5200006134030000000000452300000000", + [ + "11100028400200" + ] + ], + [ + "110f0040623b0000d65400005a50030000000000452300000000", + [ + "110F0029400200" + ] + ], + [ + "11120040030f0100298301009b1f0f00000000008df800000000", + [ + "1112002A400200" + ] + ], + [ + "111100400e39000082510000132f030000000000452300000000", + [ + "1111002B400200" + ] + ], + [ + "1000005018170000", + [ + "1000002C500100", + "1000002C500200" + ] + ], + [ + "11140040415d000030b30100000000000000000061ffffff0000", + [ + "1114004A400200" + ] + ], + [ + "10000050d4130000", + [ + "1000004B500100", + "1000004B500200" + ] + ], + [ + "1113004019660100f9f91b00bac3170100000000398800000000", + [ + "1113004C400200" + ] + ], + [ + "10000050fc130000", + [ + "1000004D500100", + "1000004D500200" + ] + ] + ] + } +} diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md new file mode 100644 index 00000000000..6f5de098859 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -0,0 +1,28 @@ +# How the Biomek i7 integration is built + +The patterns this driver follows. It follows the STAR's (`pylabrobot/hamilton/star/design.md`, +P1-P20); this says only where the Biomek differs or adds something. + +## What makes the Biomek different + +A STAR takes operations ("pick up tips here") and plans the motion itself. A Biomek's boards take +one axis at a time, in encoder counts. Three layers of Beckman software sit between a method and the +boards: **Biomek** (the application) plans operations, safe heights, collisions and liquid handling; +**the Master Controller** (MC) takes host commands in counts (`AM`, `HM`, `LT`...), coordinates each +pod's axes and keeps their positions; **the ACE boards** (a chassis and one per pod) take +single-axis commands over USB. This driver replaces the top two and talks to the boards directly. + +| Layer | What it reproduces | Where | +|---|---|---| +| L1 wire | the ACE messages | `driver/framing.py`, `board.py`, `protocol.py` | +| L2 board commands | one board request each | `_unchecked_fw_*` on the pods and chassis | +| L3 MC | one MC host command each | the pods' public primitives, `driver/recipes/` | +| L4 planning | Biomek's planning | `driver/motion.py`, `pod_geometry.py`, `liquid.py` (no I/O) | +| L5 PyLabRobot | the PLR API | `device.py`, the operation features, `resource_model/` | + +Each layer calls only the one below it. + +**I1. The boards say what is fitted.** `discover()` (read-only) asks each board its module type and +side; that places it, not the USB serial number or the enumeration order. An unknown type or side, +two boards claiming one place, or no chassis is refused. `driver/simulator.py` simulates the boards +at the wire, answering identity reads from a recording of a real instrument's. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/__init__.py new file mode 100644 index 00000000000..582f4e5646a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/__init__.py @@ -0,0 +1 @@ +"""The Biomek i7's ACE boards: framing, messages, and the boards themselves.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/board.py b/pylabrobot/beckman_coulter/biomek_i7/driver/board.py new file mode 100644 index 00000000000..1eddc8fdfd7 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/board.py @@ -0,0 +1,292 @@ +"""One ACE board: its USB link, its sequence numbers, and the replies it sends back. + +A Biomek i7 has one ACE board per module (the chassis, and one per arm), each its own USB device +(VID 0x0AB5, PID 0xACE0). A board accepts many requests at once and answers them in whatever +order they finish, so replies are matched to requests by their header, not by order. Moves and +homes answer twice, ACCEPTED when they start and DONE when they finish. The board also sends +messages nobody asked for, with sequence 0; those go to subscribers. + +When a Move All fails, the axes that failed answer with the Move All's sequence under their own +device and index, before the Move All's own DONE; those replies are kept with the Move All and +raised with it. +""" + +import asyncio +import logging +from dataclasses import dataclass, field, replace +from typing import Callable, Dict, List, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError, ace_error +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import IN_PACKET_SIZE, FrameReader, pack +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import ( + SAGIAN_CAN, + Reply, + Request, + Status, + describe_routine_unsolicited, + describe_sagian_can, +) +from pylabrobot.io.usb import USB + +logger = logging.getLogger(__name__) + +ACE_VENDOR_ID = 0x0AB5 +ACE_PRODUCT_ID = 0xACE0 +ACE_READ_ENDPOINT = 0x81 +ACE_WRITE_ENDPOINT = 0x02 + +UnsolicitedCallback = Callable[[Reply], None] + + +@dataclass +class _Pending: + request: Request + done: "asyncio.Future[Reply]" + accepted: "asyncio.Future[Reply]" + related: List[Reply] = field(default_factory=list) + + +class AceBoard: + """The link to one ACE board.""" + + def __init__( + self, + serial_number: Optional[str] = None, + device_address: Optional[int] = None, + io: Optional[USB] = None, + name: str = "Biomek i7 ACE board", + default_timeout: float = 10.0, + ): + """ + Args: + serial_number: the board's USB serial number. With neither it nor `device_address`, the + first ACE board found is used. + device_address: the board's USB address, an alternative to the serial number. + io: a transport to use instead of opening the USB device; for tests and simulators. + name: what logs and errors call this board. + default_timeout: seconds to wait for a request's final reply when the caller gives none. + """ + self.name = name + self.usb_serial_number = serial_number + self.default_timeout = default_timeout + self.io = io or USB( + id_vendor=ACE_VENDOR_ID, + id_product=ACE_PRODUCT_ID, + human_readable_device_name=name, + serial_number=serial_number, + device_address=device_address, + read_endpoint_address=ACE_READ_ENDPOINT, + write_endpoint_address=ACE_WRITE_ENDPOINT, + zero_length_packets=False, + packet_read_timeout=0.5, + ) + self._frames = FrameReader() + self._pending: Dict[Tuple[int, int, int, int], _Pending] = {} + self._sequence = 0 + self._write_lock = asyncio.Lock() + self._reader: Optional["asyncio.Task[None]"] = None + self._subscribers: List[UnsolicitedCallback] = [] + + # -- lifecycle ------------------------------------------------------------- + + async def setup(self) -> None: + """Open the board and start reading its replies.""" + await self.io.setup() + self._frames.reset() + self._reader = asyncio.create_task(self._read_loop(), name=f"{self.name} reader") + + async def stop(self) -> None: + """Stop reading, fail every request still waiting, and release the board.""" + if self._reader is not None: + self._reader.cancel() + try: + await self._reader + except asyncio.CancelledError: + pass + self._reader = None + self._fail_pending(ConnectionError(f"{self.name} stopped")) + await self.io.stop() + + @property + def connected(self) -> bool: + return self._reader is not None and not self._reader.done() + + def subscribe(self, callback: UnsolicitedCallback) -> Callable[[], None]: + """Call `callback` with every message the board sends unasked. Returns an unsubscribe.""" + self._subscribers.append(callback) + return lambda: self._subscribers.remove(callback) + + # -- requests -------------------------------------------------------------- + + async def send(self, request: Request, timeout: Optional[float] = None) -> Reply: + """Send one request and return its final reply. + + Raises: + AceError: if the board reports an error. + TimeoutError: if no final reply arrives within `timeout` seconds. + """ + return (await self.send_many([request], timeout=timeout))[0] + + async def send_many( + self, + requests: Sequence[Request], + timeout: Optional[float] = None, + raise_errors: bool = True, + ) -> List[Reply]: + """Send requests together, packed into as few transfers as fit, and return their final + replies in request order. Every request is waited for before any error is raised; the first + error in request order is raised. + + Args: + requests: the requests, sent in this order. + timeout: seconds to wait for every final reply. Defaults to `default_timeout`. + raise_errors: when False, replies that report an error are returned instead of raised, for + a caller that decides on them (such as a move refused because the axis is not homed). + + Raises: + AceError: if `raise_errors` and the board reports an error for any of them. + TimeoutError: if any final reply does not arrive within `timeout` seconds. + """ + if not self.connected: + raise ConnectionError(f"{self.name} is not set up") + timeout = self.default_timeout if timeout is None else timeout + loop = asyncio.get_running_loop() + entries: List[Tuple[Tuple[int, int, int, int], _Pending]] = [] + messages = [] + for request in requests: + sequence = self._next_sequence() + key = (request.device, request.index, sequence, request.opcode) + entry = _Pending(request, loop.create_future(), loop.create_future()) + self._pending[key] = entry + entries.append((key, entry)) + messages.append(request.encode(sequence)) + try: + async with self._write_lock: + for message in messages: # one line per message, unframed, as Biomek's `ace_io` logs them + logger.debug("%s write %s", self.name, message.hex()) + for transfer in pack(messages): + await self.io.write(transfer) + done, not_done = await asyncio.wait([e.done for _, e in entries], timeout=timeout) + if not_done: + late = [str(e.request) for _, e in entries if not e.done.done()] + raise TimeoutError(f"{self.name}: no reply within {timeout} s to {', '.join(late)}") + replies = [replace(e.done.result(), related=tuple(e.related)) for _, e in entries] + if raise_errors: + for (_, entry), reply in zip(entries, replies): + self._raise_for(entry, reply) + return replies + finally: + for key, entry in entries: + self._pending.pop(key, None) + for future in (entry.done, entry.accepted): + if not future.done(): + future.cancel() + + def _raise_for(self, entry: _Pending, reply: Reply) -> None: + """Raise the reply's error, with the errors of the axes a failed Move All names.""" + if reply.error_code is None: + return + error = ace_error( + reply.error_code, reply.device_error, str(entry.request), reply.device, reply.index + ) + causes = [r for r in entry.related if r.error_code is not None] + if causes: + error.axis_errors = [ + ace_error( + r.error_code or 0, + r.device_error, + f"device 0x{r.device:02X} index {r.index}", + r.device, + r.index, + ) + for r in causes + ] + error.args = (str(error) + "; " + "; ".join(str(e) for e in error.axis_errors),) + raise error + + def _next_sequence(self) -> int: + """The next free sequence number, 1-255 then 1 again; 0 is the board's own.""" + in_use = {key[2] for key in self._pending} + for _ in range(255): + self._sequence = self._sequence % 255 + 1 + if self._sequence not in in_use: + return self._sequence + raise RuntimeError(f"{self.name}: all 255 sequence numbers are waiting for replies") + + # -- replies --------------------------------------------------------------- + + async def _read_loop(self) -> None: + while True: + try: + data = await self.io.read(timeout=1, size=IN_PACKET_SIZE) + except TimeoutError: + continue + except asyncio.CancelledError: + raise + except Exception as e: # the link is gone; nobody will answer what is waiting + logger.error("%s: read failed: %s", self.name, e) + self._fail_pending(ConnectionError(f"{self.name}: read failed: {e}")) + return + try: + messages = self._frames.feed(data) + except FrameError as e: + logger.error("%s: %s", self.name, e) + continue + for message in messages: + self._dispatch(message) + + def _dispatch(self, message: bytes) -> None: + logger.debug("%s read %s", self.name, message.hex()) + try: + reply = Reply.parse(message) + except ValueError as e: + logger.error("%s: %s", self.name, e) + return + if reply.unsolicited: + self._deliver_unsolicited(reply) + return + entry = self._pending.get(reply.key) + if entry is None: + related = self._pending_with_sequence(reply.sequence, reply.opcode) + if related is not None: + related.related.append(reply) + else: + logger.warning("%s: reply to no waiting request: %s", self.name, message.hex()) + return + if reply.status == Status.ACCEPTED and reply.error_code is None: + if not entry.accepted.done(): + entry.accepted.set_result(reply) + return + if not entry.done.done(): + entry.done.set_result(reply) + + def _pending_with_sequence(self, sequence: int, opcode: int) -> Optional[_Pending]: + for key, entry in self._pending.items(): + if key[2] == sequence and key[3] == opcode: + return entry + return None + + def _deliver_unsolicited(self, reply: Reply) -> None: + if (reply.device, reply.opcode) == SAGIAN_CAN: + # A message the board saw on its SAGIAN CAN bus, passed up: normal when a success or a + # request (see `describe_sagian_can`), flagged otherwise. + text, normal = describe_sagian_can(reply.data) + if normal: + logger.debug("%s: SAGIAN CAN %s (forwarded, normal)", self.name, text) + else: + logger.info("%s: SAGIAN CAN %s: a status not seen in normal operation", self.name, text) + elif (routine := describe_routine_unsolicited(reply)) is not None: + logger.debug("%s: %s (routine)", self.name, routine) + elif reply.status in (Status.EMERGENCY, Status.EVENT) or reply.error_code is not None: + logger.info("%s: unsolicited %s", self.name, reply) + for callback in list(self._subscribers): + try: + callback(reply) + except Exception: + logger.exception("%s: subscriber failed on %s", self.name, reply) + + def _fail_pending(self, error: Exception) -> None: + for entry in self._pending.values(): + if not entry.done.done(): + entry.done.set_exception(error) + self._pending.clear() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py new file mode 100644 index 00000000000..f625baa7680 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/board_tests.py @@ -0,0 +1,183 @@ +"""AceBoard against a fake board: matching, two-stage replies, unsolicited messages, errors.""" + +import asyncio +import unittest +from typing import Callable, List, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import ( + InterlockTrippedError, + MotionError, + NotHomedError, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split +from pylabrobot.io.usb import USB + +Handler = Callable[[bytes], List[bytes]] + + +def done(request: bytes, payload: bytes = b"") -> bytes: + return request[:5] + b"\x02\x00" + payload + + +def accepted(request: bytes) -> bytes: + return request[:5] + b"\x01\x00" + + +def recorder(into: List[bytes], answer: Handler = lambda m: []) -> Handler: + """A handler that keeps every request in `into`, then answers with `answer`.""" + + def handler(message: bytes) -> List[bytes]: + into.append(message) + return answer(message) + + return handler + + +def answer_done(message: bytes) -> List[bytes]: + return [done(message)] + + +class FakeAceUSB(USB): + """A board on the far side of the USB link: records transfers, answers through `handler`, and + sends replies in 16-byte packets as a board does.""" + + def __init__(self, handler: Optional[Handler] = None): + super().__init__(0x0AB5, 0xACE0, "fake ACE board") + self.handler: Handler = handler or answer_done + self.transfers: List[bytes] = [] + self._packets: "asyncio.Queue[bytes]" = asyncio.Queue() + + async def setup(self, empty_buffer=True): + pass + + async def stop(self): + pass + + async def write(self, data: bytes, timeout: Optional[float] = None): + self.transfers.append(data) + for message in split(data): + for reply in self.handler(message): + self.push(reply) + + def push(self, message: bytes) -> None: + framed = frame(message) + for i in range(0, len(framed), 16): + self._packets.put_nowait(framed[i : i + 16]) + + async def read(self, timeout=None, size=None, endpoint=None) -> bytes: + try: + return await asyncio.wait_for(self._packets.get(), timeout=0.01) + except asyncio.TimeoutError: + raise TimeoutError("no packet") from None + + +class BoardTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + self.usb = FakeAceUSB() + self.board = AceBoard(io=self.usb, default_timeout=1) + await self.board.setup() + + async def asyncTearDown(self) -> None: + await self.board.stop() + + async def test_simple_request(self) -> None: + self.usb.handler = lambda m: [done(m, b"\x80\x00")] + reply = await self.board.send(p.get_module_id()) + self.assertEqual(p.parse_module_id(reply.payload).type, "chassis") + self.assertEqual(self.usb.transfers, [frame(p.get_module_id().encode(1))]) + + async def test_replies_out_of_order_match_their_requests(self) -> None: + held: List[bytes] = [] + self.usb.handler = recorder(held) + task = asyncio.create_task( + self.board.send_many([p.get_current_position(p.Device.MOTOR, axis) for axis in range(1, 9)]) + ) + while len(held) < 8: + await asyncio.sleep(0) + for message in reversed(held): + self.usb.push(done(message, message[1].to_bytes(4, "little"))) + replies = await task + self.assertEqual([p.parse_s32(r.payload) for r in replies], list(range(1, 9))) + self.assertEqual(len(self.usb.transfers), 1) # packed together + + async def test_two_stage_reply_waits_for_done(self) -> None: + held: List[bytes] = [] + self.usb.handler = recorder(held, lambda m: [accepted(m)]) + task = asyncio.create_task(self.board.send(p.move_all(5000))) + await asyncio.sleep(0.05) + self.assertFalse(task.done()) + self.usb.push(done(held[0])) + self.assertEqual((await task).status, p.Status.DONE) + + async def test_unsolicited_messages_go_to_subscribers_between_replies(self) -> None: + seen: List[p.Reply] = [] + self.board.subscribe(seen.append) + host_alive = bytes.fromhex("0000000040FE00") + emcy = bytes.fromhex("0000000031FF007E0010013704110000") + self.usb.handler = lambda m: [host_alive, emcy, done(m)] + await self.board.send(p.get_module_serial_number()) + await asyncio.sleep(0.05) + self.assertEqual([(r.device, r.opcode) for r in seen], [p.HOST_ALIVE, p.EMCY]) + self.assertEqual(p.parse_emcy(seen[1].data).device_error, 0x0437) + + async def test_error_status_raises(self) -> None: + self.usb.handler = lambda m: [m[:5] + b"\x00\x32"] + with self.assertRaises(NotHomedError): + await self.board.send(p.set_motor_move_parameters(1, 0, 1, 1, 1)) + + async def test_failed_move_all_raises_with_its_axes(self) -> None: + def handler(m: bytes) -> List[bytes]: + axis = bytes([0x11, 0x0A, 0x00, m[3], 0x50, 0x02, 0x3C, 0x00, 0x01, 0x00, 0x00]) + return [accepted(m), axis, m[:5] + b"\x02\x38"] + + self.usb.handler = handler + with self.assertRaises(MotionError) as ctx: + await self.board.send(p.move_all(5000)) + self.assertEqual([e.device_error for e in ctx.exception.axis_errors], [0x100]) + self.assertIn("motion error window exceeded", str(ctx.exception)) + + async def test_interlock_on_completion(self) -> None: + self.usb.handler = lambda m: [accepted(m), m[:5] + b"\x02\x0f\x07\x04\x00\x00"] + with self.assertRaises(InterlockTrippedError) as ctx: + await self.board.send(p.move(1, 30000)) + self.assertEqual(ctx.exception.device_error, 0x407) + + async def test_timeout_releases_the_sequence(self) -> None: + self.usb.handler = lambda m: [] + with self.assertRaises(TimeoutError): + await self.board.send(p.get_module_id(), timeout=0.05) + self.assertEqual(self.board._pending, {}) + + async def test_sequence_wraps_past_zero_and_skips_waiting_ones(self) -> None: + self.board._sequence = 254 + seen_requests: List[bytes] = [] + self.usb.handler = recorder(seen_requests, lambda m: [done(m)]) + for _ in range(3): + await self.board.send(p.get_module_id()) + self.assertEqual([m[3] for m in seen_requests], [255, 1, 2]) + + held: List[bytes] = [] + self.usb.handler = recorder(held) + waiting = asyncio.create_task(self.board.send(p.get_module_id())) # takes 3 + await asyncio.sleep(0) + self.board._sequence = 2 + self.usb.handler = recorder(seen_requests, lambda m: [done(m)]) + await self.board.send(p.get_module_serial_number()) + self.assertEqual(seen_requests[-1][3], 4) + self.usb.push(done(held[0])) + await waiting + + async def test_stop_fails_waiting_requests(self) -> None: + self.usb.handler = lambda m: [] + task = asyncio.create_task(self.board.send(p.get_module_id())) + await asyncio.sleep(0.02) + await self.board.stop() + with self.assertRaises(ConnectionError): + await task + await self.board.setup() # so tearDown can stop it again + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py new file mode 100644 index 00000000000..2bd18e6f5df --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -0,0 +1,70 @@ +"""What the driver knows about an instrument: facts only (STAR design.md P3). + +What the boards answer about themselves at setup: each module's identity, its boards with their +application images and versions, and the names of its inputs and outputs (`ModuleConfiguration`, +`BoardInfo`). +""" + +from dataclasses import dataclass, field +from typing import Dict, List, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import HardwareVersion, ModuleId + + +# The firmware this driver has been run against (one instrument, 2026-10-24 through 2026-11-10): +# every motion board and module the same image, and the other boards' application versions +# (chassis 0.2.4, SAGIAN Motion 0.3.14, LLS 0.7.8, syringe pump 5.0.9). The Master Controller +# flashes the boards when it brings other firmware, which would change what the boards answer. +TESTED_FIRMWARE_IMAGES = {(0x6D2DDB78, 266436)} +TESTED_APPLICATION_VERSIONS = {"0.2.4", "0.3.14", "0.7.8", "5.0.9"} + + +@dataclass +class BoardInfo: + """One board inside a module, as the module reports it.""" + + index: int + hardware: HardwareVersion + serial_number: Optional[str] = None + application_version: Optional[str] = None + application_crc: Optional[int] = None + application_length: Optional[int] = None + + +@dataclass +class ModuleConfiguration: + """One ACE module (the chassis, or an arm): its identity, its boards, and its inputs.""" + + module_id: ModuleId + usb_serial_number: Optional[str] + serial_number: str + hardware: HardwareVersion + application_crc: int + application_length: int + device_counts: Dict[int, int] + boards: List[BoardInfo] = field(default_factory=list) + analog_inputs: Dict[int, str] = field(default_factory=dict) + analog_units: Dict[int, str] = field(default_factory=dict) + digital_inputs: Dict[int, str] = field(default_factory=dict) + digital_outputs: Dict[int, str] = field(default_factory=dict) + + def untested_firmware(self) -> List[str]: + """What this module runs that the driver has not been run against: one line per image or + version, empty when everything is tested.""" + found = [] + if (self.application_crc, self.application_length) not in TESTED_FIRMWARE_IMAGES: + found.append( + f"module image CRC {self.application_crc:#010x}, {self.application_length} bytes" + ) + for b in self.boards: + image = (b.application_crc, b.application_length) + if b.application_crc is not None and image not in TESTED_FIRMWARE_IMAGES: + found.append( + f"board {b.index} image CRC {b.application_crc:#010x}, {b.application_length} bytes" + ) + if ( + b.application_version is not None + and b.application_version not in TESTED_APPLICATION_VERSIONS + ): + found.append(f"board {b.index} application {b.application_version}") + return found diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py new file mode 100644 index 00000000000..dfe7c096599 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py @@ -0,0 +1,141 @@ +"""Biomek i7 error types, and the reply bytes that raise them.""" + +from typing import Dict, List, Mapping, Optional, Tuple + +# ACE error codes, the byte after a reply's status. The Master Controller names more, but their +# numbers are not guessed. +ACE_ERROR_NAMES: Dict[int, str] = { + 0x0F: "interlock tripped", + 0x30: "motion device not configured", + 0x31: "motion device not enabled", + 0x32: "motion device not homed", + 0x38: "coordinated motion failed", + 0x3C: "motion error window exceeded", +} + +# Device error codes: the drive's own reason, after the ACE error code of a failed move, and in an +# EMCY message. Each one here was seen in a reply or an EMCY message. +DEVICE_ERROR_NAMES: Dict[int, str] = { + 0x0100: "motion error window exceeded", + 0x0407: "interlock tripped", + 0x0416: "interlock active", + 0x0431: "servo home aborted", + 0x0437: "stepper glitch", +} + + +class FrameError(Exception): + """Bytes from a board that do not split into whole frames.""" + + +class AceError(Exception): + """A board refused a command or reported that it failed. + + Attributes: + code: the ACE error code. + device_error: the drive's own error code, when the reply carries one. + request: a short description of the command that failed. + axis_errors: for a failed Move All, the errors the axes that failed reported. + """ + + def __init__( + self, + code: int, + device_error: Optional[int], + request: str, + device: Optional[int] = None, + index: Optional[int] = None, + ): + self.code = code + self.device_error = device_error + self.request = request + # The device and index the reply came from, when known: which axis failed. + self.device = device + self.index = index + self.axis_errors: List["AceError"] = [] + self.reason = ACE_ERROR_NAMES.get(code, f"ACE error 0x{code:02X}") + name = ACE_ERROR_NAMES.get(code, f"ACE error 0x{code:02X}") + detail = "" + if device_error is not None: + device_name = DEVICE_ERROR_NAMES.get(device_error) + detail = f" (device error 0x{device_error:X}" + (f": {device_name})" if device_name else ")") + super().__init__(f"{request}: {name}{detail}") + + +class InterlockTrippedError(AceError): + """The interlock tripped (light curtain broken, or tripped by the host), so the board stopped or + refused the move.""" + + +class NotConfiguredError(AceError): + """The axis has no motor table loaded: the board was powered up, or the drive lost its + parameters, since the last Configure.""" + + +class NotEnabledError(AceError): + """The axis is configured but disabled (Set State ENABLED has not been sent since).""" + + +class NotHomedError(AceError): + """The axis has not been homed since the board started.""" + + +class MotionError(AceError): + """A move did not complete: the axis left its error window, or a coordinated move failed.""" + + +# The ACE error a board answers when the interlock is tripped. +INTERLOCK_TRIPPED_CODE = 0x0F + +_ERROR_CLASSES = { + INTERLOCK_TRIPPED_CODE: InterlockTrippedError, + 0x30: NotConfiguredError, + 0x31: NotEnabledError, + 0x32: NotHomedError, + 0x38: MotionError, + 0x3C: MotionError, +} + + +def ace_error( + code: int, + device_error: Optional[int], + request: str, + device: Optional[int] = None, + index: Optional[int] = None, +) -> AceError: + """Build the exception for an ACE error code.""" + return _ERROR_CLASSES.get(code, AceError)(code, device_error, request, device, index) + + +# The errors the Master Controller reports as one axis's motion failing (not enabled, homing failed, operational parameters exceeded, error window exceeded, framing +# error, controller error; only those with a known number here). +_MOTION_FAILED_CODES = {0x31, 0x3C} +COORDINATED_MOTION_FAILED_CODE = 0x38 + + +def english(error: AceError, axis_names: Mapping[Tuple[int, int], str]) -> str: + """What the Master Controller replies for a command that failed with `error`, as its logs show + it, with each axis named by `axis_names` ((device, index) -> + name): + + - not homed: "The instrument needs to be homed."; + - interlock tripped: "A light curtain violation has occurred."; + - a coordinated move failed: "The motion failed: ." for each axis that reported; + - an axis's own motion error: the same, for that axis; + - anything else: " failed: ". + """ + + def motion_failed(e: AceError) -> str: + name = axis_names.get((e.device, e.index)) if e.device is not None else None # type: ignore[arg-type] + return f"The {name or e.request} motion failed: {e.reason}." + + if isinstance(error, NotHomedError): + return "The instrument needs to be homed." + if isinstance(error, InterlockTrippedError): + return "A light curtain violation has occurred." + if error.code == COORDINATED_MOTION_FAILED_CODE and error.axis_errors: + return " ".join(motion_failed(e) for e in error.axis_errors) + if error.code in _MOTION_FAILED_CODES and error.device is not None: + return motion_failed(error) + return f"{error.request} failed: {error.reason}." diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py new file mode 100644 index 00000000000..fa88302e947 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors_tests.py @@ -0,0 +1,41 @@ +"""Board errors as the Master Controller words them in its replies, as its logs show them.""" + +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import ace_error, english + +NAMES = {(0x11, 1): "left X", (0x11, 3): "left Z"} + + +class EnglishTests(unittest.TestCase): + def test_not_homed_and_interlock(self) -> None: + self.assertEqual( + english(ace_error(0x32, None, "Set X Move Parameters"), NAMES), + "The instrument needs to be homed.", + ) + self.assertEqual( + english(ace_error(0x0F, None, "Move All"), NAMES), + "A light curtain violation has occurred.", + ) + + def test_a_coordinated_move_names_each_axis_that_failed(self) -> None: + error = ace_error(0x38, None, "Move All", 0x10, 0) + error.axis_errors = [ + ace_error(0x3C, 0x0100, "device 0x11 index 1", 0x11, 1), + ace_error(0x3C, None, "device 0x11 index 3", 0x11, 3), + ] + self.assertEqual( + english(error, NAMES), + "The left X motion failed: motion error window exceeded. " + "The left Z motion failed: motion error window exceeded.", + ) + + def test_an_axis_error_and_anything_else(self) -> None: + self.assertEqual( + english(ace_error(0x31, None, "Move", 0x11, 1), NAMES), + "The left X motion failed: motion device not enabled.", + ) + self.assertEqual( + english(ace_error(0x0A, None, "Get Tip Status"), NAMES), + "Get Tip Status failed: ACE error 0x0A.", + ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py new file mode 100644 index 00000000000..fc83f97406e --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py @@ -0,0 +1 @@ +"""What a Biomek i7 is fitted with: the chassis, and a pod per side (`pod.py`, STAR's X-arm).""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py new file mode 100644 index 00000000000..df4974fd77a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py @@ -0,0 +1,67 @@ +"""The chassis module: its inputs and outputs, the legacy deck devices it lists, and the interlock's +state.""" + +from typing import Dict, List, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( + read_analog_inputs, + read_module, +) + + +class Chassis: + """The chassis's ACE module. Reached as `driver.chassis`.""" + + def __init__(self, board: AceBoard): + self.board = board + self.configuration: Optional[ModuleConfiguration] = None + + async def discover(self) -> ModuleConfiguration: + """Read what the chassis says about itself. Moves nothing.""" + self.configuration = await read_module(self.board) + return self.configuration + + def _require_configuration(self) -> ModuleConfiguration: + if self.configuration is None: + raise RuntimeError("the chassis has not been read; call `discover()` or `setup()` first") + return self.configuration + + async def request_analog_inputs(self) -> Dict[str, float]: + """Every analog input (supply voltages, temperature...) by name, in its units.""" + return await read_analog_inputs(self.board, self._require_configuration()) + + async def request_digital_inputs(self) -> Dict[str, int]: + config = self._require_configuration() + replies = await self.board.send_many( + [p.read_input_output(p.Device.DIGITAL_INPUT, i) for i in config.digital_inputs] + ) + return {config.digital_inputs[i]: r.payload[0] for i, r in zip(config.digital_inputs, replies)} + + async def request_digital_outputs(self) -> Dict[str, int]: + config = self._require_configuration() + replies = await self.board.send_many( + [p.read_input_output(p.Device.DIGITAL_OUTPUT, i) for i in config.digital_outputs] + ) + return { + config.digital_outputs[i]: r.payload[0] for i, r in zip(config.digital_outputs, replies) + } + + async def request_legacy_alp_devices(self) -> List[bytes]: + """The legacy ALP devices the chassis lists, as the raw entries it answers.""" + payload = (await self.board.send(p.list_legacy_alp_devices())).payload + return [payload[i : i + 2] for i in range(0, len(payload), 2)] + + # -- interlock ------------------------------------------------------------- + # The interlock cuts the arms' drive power when the light curtain is broken or the host trips it; + # nothing moves while it is tripped. Here it is only read. + + async def request_interlock_state(self) -> p.InterlockState: + """`armed` (the drives may have power) or `tripped`. Moves nothing. + + Biomek's logs never show the Master Controller sending Get Interlock Status. The request only + reads the state; it changes nothing. + """ + return p.parse_interlock_status((await self.board.send(p.get_interlock_status())).payload) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py new file mode 100644 index 00000000000..d23b667f1fa --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -0,0 +1,77 @@ +"""One pod: an arm on the shared X rail, and its ACE module.""" + +from typing import Dict, Literal, Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( + read_analog_inputs, + read_module, +) + +# How Biomek numbers its pods. Pod1 is the left pod and Pod2 the right on the instrument this +# driver was written against; whether that holds on every build is not established. +POD_NUMBERS = {"left": 1, "right": 2} +COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"} + +# The arm board's analog input carrying the interlocked motor supply ("+36V Interlock"). +DRIVE_SUPPLY_INPUT = "+36V Interlock" + + +class Pod: + """One pod. Reached as `driver.left_x_arm` / `driver.right_x_arm`: it fills the slot of STAR's + `XArm`, though more of the instrument hangs on it. One board drives its X, Y and Z, its head + or channels and its gripper. + + `module_type` is what the board reports itself to be (Get Module ID): `multichannel` (a + 96-channel head) or `span8` (eight independent channels). + """ + + def __init__(self, board: AceBoard, side: Literal["left", "right"], module_type: str): + self.board = board + self.side = side + self.module_type = module_type + self.configuration: Optional[ModuleConfiguration] = None + + @property + def pod_number(self) -> int: + return POD_NUMBERS[self.side] + + def __str__(self) -> str: + return f"{self.side} pod (Pod{self.pod_number}, {self.module_type})" + + @property + def component(self) -> str: + """The name Biomek gives this pod's component in its logs (`host_command.component`): + `MC_1`, `SPAN8_2`.""" + return f"{COMPONENT_PREFIXES[self.module_type]}_{self.pod_number}" + + async def discover(self) -> ModuleConfiguration: + """Read what the pod's module says about itself. Moves nothing.""" + self.configuration = await read_module(self.board) + return self.configuration + + async def request_drive_supply(self) -> float: + """The pod's interlocked motor supply, in volts: about 36 with the interlock armed, about 0.1 + tripped. Moves nothing. + + Raises: + RuntimeError: if the pod has no input named for it. + """ + if self.configuration is None: + raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first") + for index, name in self.configuration.analog_inputs.items(): + if name.startswith(DRIVE_SUPPLY_INPUT): + reply = await self.board.send(p.read_input_output(p.Device.ANALOG_INPUT, index)) + return p.parse_float(reply.payload) + raise RuntimeError(f"{self} has no {DRIVE_SUPPLY_INPUT!r} analog input") + + async def request_accuframe_offsets(self) -> Tuple[float, float, float]: + """The X, Y and Z offsets the pod's AccuFrame board holds.""" + return p.parse_accuframe_offsets((await self.board.send(p.get_accuframe_offsets())).payload) + + async def request_analog_inputs(self) -> Dict[str, float]: + if self.configuration is None: + raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first") + return await read_analog_inputs(self.board, self.configuration) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py new file mode 100644 index 00000000000..5407f0f16c6 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/framing.py @@ -0,0 +1,100 @@ +"""ACE framing: how messages travel in the Biomek i7's USB transfers. + +Every message travels as a frame, a length byte followed by that many message bytes:: + + length (1) | message (length) + +The host packs one or more frames into an interrupt OUT transfer on endpoint 0x02 (32-byte +packets) and sends no zero-length packet after one that fills its last packet. A board sends one +frame per interrupt IN transfer on endpoint 0x81 (16-byte packets); a frame longer than 15 bytes +spans several packets. Established on a cold start captured with USBPcap, 2026-10-24: all 3,507 +transfers split into whole frames. +""" + +from typing import Iterable, List + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError + +# The largest OUT transfer the Master Controller sent in the captured cold start. Larger ones are +# not known to be accepted, so frames are packed no further than this. +MAX_OUT_TRANSFER = 253 + +# The IN endpoint's packet size: one read returns at most one packet. +IN_PACKET_SIZE = 16 + + +def frame(message: bytes) -> bytes: + """Prefix one message with its length byte. + + Raises: + ValueError: if the message is empty or longer than 255 bytes. + """ + if not 0 < len(message) <= 0xFF: + raise ValueError(f"an ACE message is 1-255 bytes, got {len(message)}") + return bytes([len(message)]) + message + + +def pack(messages: Iterable[bytes], max_transfer: int = MAX_OUT_TRANSFER) -> List[bytes]: + """Pack messages, in order, into as few OUT transfers as fit `max_transfer` bytes each.""" + transfers: List[bytes] = [] + current = b"" + for message in messages: + framed = frame(message) + if len(framed) > max_transfer: + raise ValueError(f"a {len(framed)}-byte frame does not fit a {max_transfer}-byte transfer") + if len(current) + len(framed) > max_transfer: + transfers.append(current) + current = b"" + current += framed + if current: + transfers.append(current) + return transfers + + +def split(transfer: bytes) -> List[bytes]: + """Split one whole transfer into its messages. + + Raises: + FrameError: if the transfer does not end on a frame boundary, or holds an empty frame. + """ + reader = FrameReader() + messages = reader.feed(transfer) + if reader.pending: + raise FrameError(f"transfer ends inside a frame: {transfer.hex()}") + return messages + + +class FrameReader: + """Reassemble frames from IN packets, which may end anywhere inside a frame.""" + + def __init__(self) -> None: + self._buffer = bytearray() + + @property + def pending(self) -> int: + """How many bytes of an unfinished frame are held.""" + return len(self._buffer) + + def feed(self, data: bytes) -> List[bytes]: + """Take the next bytes read and return every message they complete. + + Raises: + FrameError: on a zero length byte, which no board sends and which would never advance. + """ + self._buffer += data + messages: List[bytes] = [] + while self._buffer: + length = self._buffer[0] + if length == 0: + bad = bytes(self._buffer) + self._buffer.clear() + raise FrameError(f"zero-length frame in {bad.hex()}") + if len(self._buffer) < length + 1: + break + messages.append(bytes(self._buffer[1 : length + 1])) + del self._buffer[: length + 1] + return messages + + def reset(self) -> None: + """Drop an unfinished frame, as after a read error.""" + self._buffer.clear() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py new file mode 100644 index 00000000000..bb4663ce5ee --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/framing_tests.py @@ -0,0 +1,118 @@ +"""ACE framing: length-prefixed messages, packed into OUT transfers and read back from 16-byte IN +packets.""" + +import random +import unittest +from typing import List + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import FrameError +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import ( + IN_PACKET_SIZE, + MAX_OUT_TRANSFER, + FrameReader, + frame, + pack, + split, +) + +# Transfers from a captured cold start, each as it went over the wire: three Set Move Parameters +# packed into one OUT transfer, and three answers, each its own IN transfer, the last longer than a +# packet (an analog input's name, "Temperature"). +CAPTURED_OUT = ( + "1b1101001840150000001f0000003201000000000000038c00000000" + "1b1105001940030f0100298301009b1f0f000000000013f900000000" + "1b1102001a40b86f0200077b030044ce2200000000008a9100000000" +) +CAPTURED_IN = [ + "09000000010002008000", + "0902010007030200e500", + "122209000b01020054656d7065726174757265", +] + + +def messages(rng: random.Random, count: int) -> List[bytes]: + return [bytes(rng.randrange(256) for _ in range(rng.randrange(1, 256))) for _ in range(count)] + + +class CapturedTransferTests(unittest.TestCase): + def test_a_packed_out_transfer_splits_into_its_requests(self) -> None: + data = bytes.fromhex(CAPTURED_OUT) + requests = split(data) + self.assertEqual([(m[0], m[1], m[3], m[4]) for m in requests], + [(0x11, 1, 0x18, 0x40), (0x11, 5, 0x19, 0x40), (0x11, 2, 0x1A, 0x40)]) # fmt: skip + self.assertEqual(pack(requests), [data]) + + def test_in_transfers_hold_one_frame_each(self) -> None: + for hex_data in CAPTURED_IN: + data = bytes.fromhex(hex_data) + (message,) = split(data) + self.assertEqual(frame(message), data) + + +class InverseTests(unittest.TestCase): + """Framing and splitting undo each other, for any messages.""" + + def setUp(self) -> None: + self.rng = random.Random(11) + + def test_frame_then_split(self) -> None: + for message in messages(self.rng, 200) + [b"\x00", b"\xff" * 255]: + self.assertEqual(split(frame(message)), [message]) + + def test_pack_then_split_keeps_order_and_fits(self) -> None: + for _ in range(50): + batch = [m[: MAX_OUT_TRANSFER - 1] for m in messages(self.rng, self.rng.randrange(1, 12))] + transfers = pack(batch) + self.assertTrue(all(len(t) <= MAX_OUT_TRANSFER for t in transfers)) + self.assertEqual([m for t in transfers for m in split(t)], batch) + + def test_frames_reassemble_from_packets(self) -> None: + """Read packet by packet, as the board's reader does, the frames come out unchanged.""" + reader = FrameReader() + for message in messages(self.rng, 200): + data = frame(message) + out: List[bytes] = [] + for i in range(0, len(data), IN_PACKET_SIZE): + out += reader.feed(data[i : i + IN_PACKET_SIZE]) + self.assertEqual(out, [message]) + self.assertEqual(reader.pending, 0) + + def test_frames_reassemble_from_any_cut(self) -> None: + stream = b"".join(frame(m) for m in messages(self.rng, 20)) + for _ in range(20): + reader = FrameReader() + cuts = sorted(self.rng.sample(range(1, len(stream)), 15)) + out: List[bytes] = [] + for a, b in zip([0] + cuts, cuts + [len(stream)]): + out += reader.feed(stream[a:b]) + self.assertEqual(out, split(stream)) + + +class PackTests(unittest.TestCase): + def test_packs_in_order_until_the_transfer_is_full(self) -> None: + messages = [bytes([i]) * 100 for i in range(3)] + transfers = pack(messages) + self.assertEqual(transfers, [frame(messages[0]) + frame(messages[1]), frame(messages[2])]) + self.assertTrue(all(len(t) <= MAX_OUT_TRANSFER for t in transfers)) + + def test_rejects_empty_and_oversized_messages(self) -> None: + with self.assertRaises(ValueError): + frame(b"") + with self.assertRaises(ValueError): + frame(b"x" * 256) + with self.assertRaises(ValueError): + pack([b"x" * 255]) # a frame larger than a transfer + + def test_split_rejects_a_truncated_transfer(self) -> None: + with self.assertRaises(FrameError): + split(bytes([5, 1, 2])) + + def test_zero_length_frame_is_an_error(self) -> None: + reader = FrameReader() + with self.assertRaises(FrameError): + reader.feed(b"\x00\x01") + self.assertEqual(reader.pending, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py new file mode 100644 index 00000000000..21b0e1b98b8 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -0,0 +1,225 @@ +"""BiomekI7Driver: finds the instrument's ACE boards, works out what each one is, and owns them. + +A Biomek i7 shows up as one USB device per ACE module: the chassis, and one per arm. Which is which +is not fixed by USB order or serial number, so setup opens every ACE device, asks each its module +ID (its type, and an arm's side), and builds the chassis and a pod per arm from the answers. Only one +program can hold an ACE board at a time: Biomek's Master Controller must not be running. +""" + +import logging +from typing import Dict, List, Optional, Sequence, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import ( + ACE_PRODUCT_ID, + ACE_VENDOR_ID, + AceBoard, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod +from pylabrobot.io.usb import USB + +logger = logging.getLogger(__name__) + + +def find_ace_boards() -> Dict[str, int]: + """Every ACE board attached: its USB serial number and current USB address. + + Reading a serial number opens the device; the handle is released straight after, because a + WinUSB device admits one open handle at a time. + """ + import usb.util # optional dependency, as in pylabrobot.io.usb + + boards: Dict[str, int] = {} + for device in USB(ACE_VENDOR_ID, ACE_PRODUCT_ID, "ACE board").get_available_devices(): + try: + boards[str(device.serial_number)] = device.address + finally: + usb.util.dispose_resources(device) + return boards + + +class BiomekI7Driver: + """The Biomek i7's ACE boards, as a chassis and up to two pods.""" + + def __init__( + self, + serial_numbers: Optional[Sequence[str]] = None, + boards: Optional[Sequence[AceBoard]] = None, + ): + """ + Args: + serial_numbers: the ACE boards' USB serial numbers. Defaults to every ACE board attached. + boards: boards to use instead of opening USB devices: a simulated instrument + (`simulator.replay_boards`). + """ + self._serial_numbers = list(serial_numbers) if serial_numbers is not None else None + self._given_boards = list(boards) if boards is not None else None + self.boards: List[AceBoard] = [] + self._connected = False + self.chassis: Optional[Chassis] = None + # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, Feature map). + self.left_x_arm: Optional[Pod] = None + self.right_x_arm: Optional[Pod] = None + + # -- lifecycle ------------------------------------------------------------- + + async def setup(self) -> None: + """Connect to the instrument and find out what it is. Reads only: nothing is written to a + board and nothing moves. Repeatable: the boards stay open, and discovery reads them again. A + setup that fails part way releases the boards. + + Raises: + RuntimeError: if no chassis is found, or a board cannot be placed (`discover`). + """ + logger.warning( + "The Biomek i7 driver's discovery has run on one instrument; it is untested on other " + "instruments. Please report what works and what does not." + ) + if not self._connected: + await self._open() + try: + await self.discover() + except BaseException: + await self.stop() + raise + + async def _open(self) -> None: + """Open every ACE board and start reading it.""" + if self._given_boards is not None: + self.boards = list(self._given_boards) + else: + found = find_ace_boards() + if not found: + raise RuntimeError("no ACE boards (USB 0AB5:ACE0) found") + serials = self._serial_numbers or sorted(found) + missing = [s for s in serials if s not in found] + if missing: + raise RuntimeError(f"ACE boards {missing} not found; attached: {sorted(found)}") + # Opened by the address just enumerated: matching on serial number would open each device + # again to read its descriptor. + self.boards = [AceBoard(device_address=found[s], name=f"ACE {s}") for s in serials] + for board, serial in zip(self.boards, serials): + board.usb_serial_number = serial + self._connected = True + for board in self.boards: + await board.setup() + + async def discover(self) -> None: + """Work out which board is which, then read each module, chassis first. Moves nothing, arms + nothing and writes nothing: it opens the boards if `setup` has not, and can be called on its + own. + + Each board says what it is: Get Module ID answers a module type (`protocol.MODULE_TYPES`: + chassis, Multichannel, Span-8) and a side (left, right). That, not its USB serial number or + order, places it. Seen on one instrument; an unknown type or side, two boards claiming one + place, or no chassis is refused. + + Raises: + RuntimeError: for a board this driver cannot place, or no chassis. + """ + if not self._connected: + await self._open() + places: Dict[str, AceBoard] = {} + types: Dict[str, str] = {} + for board in self.boards: + module = p.parse_module_id((await board.send(p.get_module_id())).payload) + if module.type is None: + raise RuntimeError( + f"{board.name}: module type 0x{module.type_code:02X} is not one this driver knows" + ) + place = "chassis" if module.type == "chassis" else str(module.side) + if place in places: + raise RuntimeError( + f"{board.name} and {places[place].name} both report themselves as {place}" + ) + if place not in ("chassis", "left", "right"): + raise RuntimeError( + f"{board.name}: {module.type} module reports side 0x{module.side_code:02X}" + ) + places[place] = board + types[place] = module.type + if "chassis" not in places: + raise RuntimeError("no chassis module among the ACE boards") + self.chassis = Chassis(places["chassis"]) + self.left_x_arm = Pod(places["left"], "left", types["left"]) if "left" in places else None + self.right_x_arm = Pod(places["right"], "right", types["right"]) if "right" in places else None + modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())] + for pod in self.arms: + modules.append((str(pod), await pod.discover())) + logger.info( + "found %s, module %s", pod, pod.configuration.serial_number if pod.configuration else "?" + ) + for name, found in modules: + untested = found.untested_firmware() + if untested: + logger.warning( + "%s runs firmware this driver has not been run against: %s", name, "; ".join(untested) + ) + + async def request_serial_numbers(self) -> Dict[str, Optional[str]]: + """The serial numbers the modules report: `chassis`, and `left` / `right` for each pod found. + Moves nothing. + + Raises: + RuntimeError: before discovery (`discover` or `setup`). + """ + return self._serial_numbers_found() + + def _serial_numbers_found(self) -> Dict[str, Optional[str]]: + if self.chassis is None or self.chassis.configuration is None: + raise RuntimeError("the modules have not been read; call `discover()` or `setup()` first") + found: Dict[str, Optional[str]] = {"chassis": self.chassis.configuration.serial_number} + for pod in self.arms: + found[pod.side] = pod.configuration.serial_number if pod.configuration else None + return found + + async def stop(self) -> None: + """Release every board. Writes nothing and moves nothing.""" + for board in self.boards: + try: + await board.stop() + except Exception: + logger.exception("failed to release %s", board.name) + self._connected = False + + # -- what the instrument has ------------------------------------------------ + + @property + def arms(self) -> List[Pod]: + """The pods this instrument has, left first (STAR's `arms`).""" + return [pod for pod in (self.left_x_arm, self.right_x_arm) if pod is not None] + + @property + def x_arm(self) -> Pod: + """The pod, on an instrument with one (STAR's `x_arm`). + + Raises: + RuntimeError: before discovery, when which pods are fitted is not yet known. + ValueError: with no pod, or two; reach two as `left_x_arm` and `right_x_arm`. + """ + if self.chassis is None: + raise RuntimeError("the instrument has not been read; call `discover()` or `setup()` first") + arms = self.arms + if not arms: + raise ValueError("this instrument has no pod") + if len(arms) > 1: + raise ValueError( + "this instrument has two pods, so `x_arm` is ambiguous - reach it through " + "`left_x_arm` or `right_x_arm`." + ) + return arms[0] + + def arm(self, name: Union[str, int]) -> Pod: + """A pod by any name it goes by: its side (`"left"`), Biomek's number (`1`, `"Pod1"`), or + Biomek's component name in its logs (`"MC_1"`). For porting Biomek methods and logs, which + name pods by number; the driver itself names them by side. + + Raises: + KeyError: if no pod goes by that name. + """ + for pod in self.arms: + if name in (pod.side, pod.pod_number, f"Pod{pod.pod_number}", pod.component): + return pod + raise KeyError(f"no pod {name!r}; have {[(p.side, p.component) for p in self.arms]}") diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py new file mode 100644 index 00000000000..2df0cea1da8 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master_tests.py @@ -0,0 +1,218 @@ +"""Discovery on a replayed instrument: each board placed by what it says it is, then read.""" + +import asyncio +import itertools +import unittest +from typing import Any, Dict, List + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_boards, + generic_driver, + generic_recording, +) + +# The commands that only read: discovery sends nothing else. +READS = {name for name in p.COMMANDS.values() if name.startswith(("Get ", "Read ", "List "))} + + +def answer(recording: Dict[str, Any], module: str, key: str, reply: str) -> None: + """Have `module` answer the request `key` (its bytes less the sequence) with `reply`.""" + entries: List[List[Any]] = recording["boards"][module] + for entry in entries: + if entry[0] == key: + entry[1] = [reply] + return + entries.append([key, [reply]]) + + +def module_id(recording: Dict[str, Any], module: str, type_code: int, side_code: int) -> None: + answer(recording, module, "00000000", f"00000000000200{type_code:02X}{side_code:02X}") + + +class ReplayedTestCase(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) # the test loop's debug mode makes replays slow + + +class PlacementTests(ReplayedTestCase): + async def test_boards_are_placed_by_what_they_say_in_any_order(self) -> None: + for order in itertools.permutations(["chassis", "multichannel", "span8"]): + with self.subTest(order=order): + driver = generic_driver(generic_boards(modules=order)) + await driver.discover() + try: + self.assertIsNotNone(driver.chassis) + assert driver.chassis is not None and driver.left_x_arm and driver.right_x_arm + self.assertEqual(driver.chassis.board.name, "replayed chassis") + self.assertEqual(driver.left_x_arm.board.name, "replayed multichannel") + self.assertEqual(driver.right_x_arm.board.name, "replayed span8") + finally: + await driver.stop() + left, right = driver.left_x_arm, driver.right_x_arm + assert left is not None and right is not None + self.assertEqual(str(left), "left pod (Pod1, multichannel)") + self.assertEqual((left.component, left.pod_number), ("MC_1", 1)) + self.assertEqual((right.component, right.pod_number), ("SPAN8_2", 2)) + self.assertEqual(driver.arms, [left, right]) + + async def test_two_boards_in_one_place_are_refused(self) -> None: + recording = generic_recording() + module_id(recording, "span8", 0xFB, 0x01) # a second left pod + driver = generic_driver(generic_boards(recording)) + with self.assertRaisesRegex(RuntimeError, "replayed span8 and replayed multichannel both"): + await driver.discover() + await driver.stop() + + async def test_no_chassis_is_refused(self) -> None: + driver = generic_driver(generic_boards(modules=["multichannel", "span8"])) + with self.assertRaisesRegex(RuntimeError, "no chassis"): + await driver.discover() + await driver.stop() + + async def test_an_unknown_module_type_is_refused(self) -> None: + recording = generic_recording() + module_id(recording, "span8", 0x42, 0x02) + driver = generic_driver(generic_boards(recording)) + with self.assertRaisesRegex(RuntimeError, "module type 0x42"): + await driver.discover() + await driver.stop() + + async def test_an_unknown_side_is_refused(self) -> None: + recording = generic_recording() + module_id(recording, "span8", 0xFB, 0x07) + driver = generic_driver(generic_boards(recording)) + with self.assertRaisesRegex(RuntimeError, "side 0x07"): + await driver.discover() + await driver.stop() + + async def test_setup_releases_the_boards_when_discovery_fails(self) -> None: + boards = generic_boards(modules=["multichannel", "span8"]) + with self.assertRaisesRegex(RuntimeError, "no chassis"): + await generic_driver(boards).setup() + self.assertFalse(any(board.connected for board in boards)) + + +class PodNameTests(ReplayedTestCase): + async def test_one_pod(self) -> None: + driver = generic_driver(generic_boards(modules=["chassis", "span8"])) + with self.assertRaisesRegex(RuntimeError, "discover"): + driver.x_arm + await driver.discover() + self.assertIsNone(driver.left_x_arm) + self.assertIs(driver.x_arm, driver.right_x_arm) + await driver.stop() + + async def test_two_pods(self) -> None: + driver = generic_driver() + await driver.discover() + with self.assertRaisesRegex(ValueError, "left_x_arm"): + driver.x_arm + for name in ("left", 1, "Pod1", "MC_1"): + self.assertIs(driver.arm(name), driver.left_x_arm) + for name in ("right", 2, "Pod2", "SPAN8_2"): + self.assertIs(driver.arm(name), driver.right_x_arm) + with self.assertRaises(KeyError): + driver.arm("MC_2") + await driver.stop() + + +class ReadTests(ReplayedTestCase): + async def asyncSetUp(self) -> None: + await super().asyncSetUp() + self.boards = generic_boards() + self.driver = generic_driver(self.boards) + + async def asyncTearDown(self) -> None: + await self.driver.stop() + + async def test_discovery_on_its_own_opens_the_boards_and_only_reads(self) -> None: + await self.driver.discover() + self.assertTrue(all(board.connected for board in self.boards)) + for board in self.boards: + assert isinstance(board.io, ReplayAceUSB) + self.assertEqual(board.io.unanswered, [], board.name) + sent = {p.COMMANDS[(m[0], m[4])] for m in board.io.requests} + self.assertLessEqual(sent, READS, board.name) + + async def test_serial_numbers(self) -> None: + with self.assertRaisesRegex(RuntimeError, "discover"): + await self.driver.request_serial_numbers() + await self.driver.discover() + serials = await self.driver.request_serial_numbers() + self.assertEqual(set(serials), {"chassis", "left", "right"}) + for serial in serials.values(): + assert serial is not None + self.assertTrue(serial.startswith("SIMULATED"), serial) + self.assertEqual(len(set(serials.values())), 3) + + async def test_each_modules_boards_and_inputs(self) -> None: + await self.driver.discover() + chassis, left, right = self.driver.chassis, self.driver.left_x_arm, self.driver.right_x_arm + assert chassis and chassis.configuration and left and left.configuration + assert right and right.configuration + self.assertEqual(chassis.configuration.module_id.type, "chassis") + self.assertEqual(chassis.configuration.digital_inputs[1], "Door Sensor") + self.assertEqual(chassis.configuration.analog_units[9], "deg. C") + self.assertEqual( + [b.index for b in left.configuration.boards], + list(range(len(left.configuration.boards), 0, -1)), # highest index first + ) + self.assertTrue(any(b.hardware.name == "AccuFrame" for b in left.configuration.boards)) + self.assertEqual(right.configuration.untested_firmware(), []) + + async def test_sensor_reads(self) -> None: + await self.driver.discover() + chassis, left, right = self.driver.chassis, self.driver.left_x_arm, self.driver.right_x_arm + assert chassis and left and right + analog = await chassis.request_analog_inputs() + self.assertIn("Temperature", analog) + self.assertEqual(set(await chassis.request_digital_inputs()), {"Door Sensor"}) + self.assertEqual(len(await chassis.request_digital_outputs()), 1) + self.assertIsInstance(await chassis.request_legacy_alp_devices(), list) + for pod in (left, right): + # The recording answers as the instrument did when it was made, with the interlock armed. + self.assertGreater(await pod.request_drive_supply(), 30.0) + self.assertIn("+36V Interlock", await pod.request_analog_inputs()) + self.assertEqual(len(await left.request_accuframe_offsets()), 3) + + async def test_untested_firmware_is_warned_about(self) -> None: + with self.assertNoLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "WARNING"): + await self.driver.discover() + recording = generic_recording() + answer(recording, "span8", "00000012", "000000001202" + "00EFBEADDE") + driver = generic_driver(generic_boards(recording)) + with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "WARNING") as logs: + await driver.discover() + await driver.stop() + self.assertIn("module image CRC 0xdeadbeef", "\n".join(logs.output)) + + async def test_stop_releases_the_boards_and_discovery_runs_again(self) -> None: + await self.driver.discover() + await self.driver.stop() + self.assertFalse(any(board.connected for board in self.boards)) + await self.driver.discover() + self.assertTrue(all(board.connected for board in self.boards)) + + +class InterlockStateTests(unittest.IsolatedAsyncioTestCase): + """Get Interlock Status, which the Master Controller never sends, answers the interlock's byte + (read on the instrument 2026-11-09: `FF` tripped, `00` armed).""" + + async def test_states(self) -> None: + for byte, state in (("FF", "tripped"), ("00", "armed")): + board = AceBoard( + io=ReplayAceUSB({"01010010": ["0101000010" + "0200" + byte]}), default_timeout=0.3 + ) + await board.setup() + try: + self.assertEqual(await Chassis(board).request_interlock_state(), state) + finally: + await board.stop() + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/module.py b/pylabrobot/beckman_coulter/biomek_i7/driver/module.py new file mode 100644 index 00000000000..3956e87bfd8 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/module.py @@ -0,0 +1,72 @@ +"""Reading what an ACE module says about itself: identity, its boards, and its inputs. + +The order follows the Master Controller's cold start: the module, then each of its boards from +the highest index down (a motion board's serial number and firmware image, any other board's +application version), then the names of its inputs and outputs. Nothing here moves or writes. +""" + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import BoardInfo, ModuleConfiguration + +# Board kinds whose identity is a serial number and firmware image; every other kind reports an +# application version. AccuFrame boards are left at their hardware version. +_IMAGE_BOARDS = {0x00} +_ACCUFRAME = 0xE3 + + +async def read_module(board: AceBoard) -> ModuleConfiguration: + """Read a module's identity, board inventory and input/output names.""" + module_id = p.parse_module_id((await board.send(p.get_module_id())).payload) + hardware = p.parse_hardware_version((await board.send(p.get_module_hardware_version())).payload) + serial = p.parse_string((await board.send(p.get_module_serial_number())).payload) + crc = p.parse_u32((await board.send(p.get_module_application_image_crc())).payload) + length = p.parse_u32((await board.send(p.get_module_application_image_length())).payload) + counts = p.parse_device_count((await board.send(p.get_module_device_count())).payload) + usb_serial = board.usb_serial_number + config = ModuleConfiguration(module_id, usb_serial, serial, hardware, crc, length, counts) + + for index in range(counts.get(p.Device.BOARD, 0), 0, -1): + info = BoardInfo( + index, + p.parse_hardware_version((await board.send(p.get_board_hardware_version(index))).payload), + ) + if info.hardware.type_code in _IMAGE_BOARDS: + info.serial_number = p.parse_string( + (await board.send(p.get_board_serial_number(index))).payload + ) + info.application_crc = p.parse_u32( + (await board.send(p.get_board_application_image_crc(index))).payload + ) + info.application_length = p.parse_u32( + (await board.send(p.get_board_application_image_length(index))).payload + ) + elif info.hardware.type_code != _ACCUFRAME: + info.application_version = p.parse_string( + (await board.send(p.get_board_application_version(index))).payload + ) + config.boards.append(info) + + io_counts = p.parse_device_count((await board.send(p.get_io_service_device_count())).payload) + for index in range(1, io_counts.get(p.Device.ANALOG_INPUT, 0) + 1): + name = await board.send(p.get_input_output_name(p.Device.ANALOG_INPUT, index)) + units = await board.send(p.get_analog_input_units(index)) + config.analog_inputs[index] = p.parse_string(name.payload) + config.analog_units[index] = p.parse_string(units.payload) + for index in range(1, io_counts.get(p.Device.DIGITAL_INPUT, 0) + 1): + name = await board.send(p.get_input_output_name(p.Device.DIGITAL_INPUT, index)) + config.digital_inputs[index] = p.parse_string(name.payload) + for index in range(1, io_counts.get(p.Device.DIGITAL_OUTPUT, 0) + 1): + name = await board.send(p.get_input_output_name(p.Device.DIGITAL_OUTPUT, index)) + config.digital_outputs[index] = p.parse_string(name.payload) + return config + + +async def read_analog_inputs(board: AceBoard, config: ModuleConfiguration) -> dict: + """Every analog input's value, by name, in its units.""" + replies = await board.send_many( + [p.read_input_output(p.Device.ANALOG_INPUT, i) for i in config.analog_inputs] + ) + return { + config.analog_inputs[i]: p.parse_float(r.payload) for i, r in zip(config.analog_inputs, replies) + } diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py b/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py new file mode 100644 index 00000000000..63b78df4497 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/protocol.py @@ -0,0 +1,711 @@ +"""ACE messages: what the Biomek i7's boards are sent and what they answer. + +A request is a 5-byte header and its parameters, little-endian:: + + device (1) | index (1) | 0x00 | sequence (1) | opcode (1) | parameters + +`device` names the kind of thing addressed on the board (the module itself, one of its boards, a +motor, a syringe pump, an input...), `index` which one of them, and `opcode` the operation, whose +meaning depends on `device`. A board answers with the same header, then a status byte and the +status's data:: + + device | index | 0x00 | sequence | opcode | status (1) | data + +A command that starts something answers twice, ACCEPTED and then DONE; anything else answers +DONE once. Boards also send messages nobody asked for, with sequence 0: EVENT (an input changed, +the interlock tripped), NOTICE (the host-alive heartbeat, a move stopped by the interlock) and +EMERGENCY (CANopen EMCY from a drive, SAGIAN CAN traffic). + +The requests here are the ones the Master Controller was logged sending, plus the reads in +`FIRMWARE_READS`, and nothing else: `Request` refuses any device/opcode pair not in `COMMANDS`, +so firmware upgrade and flash commands cannot be sent through this module. A firmware read is one the Master Controller never sends, which only reads a state and changes +nothing. +""" + +import enum +import struct +from dataclasses import dataclass, field +from typing import Dict, List, Literal, Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error + + +class Device(enum.IntEnum): + """The device byte: what kind of thing on a board a message addresses.""" + + MODULE = 0x00 + INTERLOCK = 0x01 + BOARD = 0x02 + MOTION_SERVICE = 0x10 + MOTOR = 0x11 + PUMP = 0x12 + TIP_SENSOR = 0x13 + IO_SERVICE = 0x20 + DIGITAL_INPUT = 0x21 + ANALOG_INPUT = 0x22 + DIGITAL_OUTPUT = 0x28 + STATUS_DISPLAY = 0x2D + ACCUFRAME = 0xAF + LEGACY_ALP = 0xFE + IO_BOX = 0xFF + + +class Status(enum.IntEnum): + """A reply's status byte.""" + + ERROR = 0x00 + ACCEPTED = 0x01 + DONE = 0x02 + EVENT = 0x03 + NOTICE = 0xFE + EMERGENCY = 0xFF + + +# Every request this driver may send, by (device, opcode). The names are the Master Controller's. +COMMANDS: Dict[Tuple[int, int], str] = { + (Device.MODULE, 0x00): "Get Module ID", + (Device.MODULE, 0x02): "Get Module Serial Number", + (Device.MODULE, 0x03): "Get Module Hardware Version", + (Device.MODULE, 0x08): "Get Module Device Count", + (Device.MODULE, 0x0F): "Stop Module Execution", + (Device.MODULE, 0x11): "Get Module Application Image Length", + (Device.MODULE, 0x12): "Get Module Application Image CRC", + (Device.BOARD, 0x02): "Get Board Serial Number", + (Device.BOARD, 0x03): "Get Board Hardware Version", + (Device.BOARD, 0x04): "Get Board Bootloader Version", + (Device.BOARD, 0x10): "Get Board Application Version", + (Device.BOARD, 0x11): "Get Board Application Image Length", + (Device.BOARD, 0x12): "Get Board Application Image CRC", + (Device.INTERLOCK, 0x11): "Notify On Interlock Trip", + (Device.INTERLOCK, 0x50): "Trip Interlock", + (Device.INTERLOCK, 0x51): "Re-Arm Interlock", + (Device.MOTION_SERVICE, 0x0F): "Stop Motion Service", + (Device.MOTION_SERVICE, 0x50): "Move All", + (Device.MOTOR, 0x10): "Configure", + (Device.MOTOR, 0x12): "Set State", + (Device.MOTOR, 0x21): "Get Homed State", + (Device.MOTOR, 0x24): "Get Current Position", + (Device.MOTOR, 0x31): "Get Control Effort", + (Device.MOTOR, 0x40): "Set Move Parameters", + (Device.MOTOR, 0x50): "Move", + (Device.MOTOR, 0x51): "Home", + (Device.PUMP, 0x10): "Configure", + (Device.PUMP, 0x12): "Set State", + (Device.PUMP, 0x21): "Get Homed State", + (Device.PUMP, 0x24): "Get Current Position", + (Device.PUMP, 0x40): "Set Move Parameters", + (Device.PUMP, 0x51): "Home", + (Device.TIP_SENSOR, 0x10): "Get Tip Status", + (Device.TIP_SENSOR, 0x41): "Set LLS/CD Sensitivity", + (Device.IO_SERVICE, 0x08): "Get IO Service Device Count", + (Device.DIGITAL_INPUT, 0x01): "Get Digital Input Name", + (Device.DIGITAL_INPUT, 0x10): "Read Digital Input", + (Device.DIGITAL_INPUT, 0x11): "Notify On Digital Input Change", + (Device.ANALOG_INPUT, 0x01): "Get Analog Input Name", + (Device.ANALOG_INPUT, 0x10): "Read Analog Input", + (Device.ANALOG_INPUT, 0x12): "Get Analog Input Units", + (Device.DIGITAL_OUTPUT, 0x01): "Get Digital Output Name", + (Device.DIGITAL_OUTPUT, 0x10): "Read Digital Output", + (Device.DIGITAL_OUTPUT, 0x11): "Notify On Digital Output Change", + (Device.STATUS_DISPLAY, 0x10): "Set Status Display", + (Device.ACCUFRAME, 0xF7): "Get AccuFrame Offsets", + (Device.LEGACY_ALP, 0x18): "List Legacy ALP Devices", + (Device.IO_BOX, 0x10): "Send Digital I/O Box", +} + +# Reads the Master Controller never sends. Get State answers an axis's state byte (`AxisState`) +# with no precondition, and changes nothing. Get Interlock Status answers the interlock's state +# byte; the Master Controller's log names it "Get Interlock Status". +FIRMWARE_READS: Dict[Tuple[int, int], str] = { + (Device.MOTOR, 0x11): "Get State", + (Device.PUMP, 0x11): "Get State", + (Device.INTERLOCK, 0x10): "Get Interlock Status", +} +COMMANDS.update(FIRMWARE_READS) + +# Requests that answer ACCEPTED before DONE. +TWO_STAGE: frozenset = frozenset( + {(Device.MOTION_SERVICE, 0x50), (Device.MOTOR, 0x50), (Device.MOTOR, 0x51), (Device.PUMP, 0x51)} +) + +# The opcode a board's unsolicited messages carry, by (device, opcode). +HOST_ALIVE = (Device.MODULE, 0x40) +EMCY = (Device.MODULE, 0x31) +SAGIAN_CAN = (Device.MODULE, 0x30) +INTERLOCK_TRIPPED = (Device.INTERLOCK, 0x10) +DIGITAL_INPUT_VALUE = (Device.DIGITAL_INPUT, 0x10) + +# A SAGIAN CAN message a Span-8 board passes up: the message's kind and status bytes, named as the +# Master Controller's log names them ("SAGIAN CAN TO_NODE 05:00 READ SUCCESS F7 ..."). The board +# shares the CAN bus with the SAGIAN devices behind it (the AccuFrame is node 05) and forwards what +# it sees there, the answers to the host's own requests included: reading the AccuFrame's offsets +# through the Multichannel's board brings the AccuFrame's answer back from the Span-8's as well. +# Every such message in the Master Controller's logs (2026-07-27 .. 10-27) is a success or a +# request; any other status is not known to be harmless. +SAGIAN_CAN_KINDS = {0x00: "ACTION", 0x01: "READ", 0x02: "WRITE", 0x03: "EVENT"} +SAGIAN_CAN_KNOWN_STATUSES = {0x00: "REQUEST", 0x01: "SUCCESS"} + + +def describe_sagian_can(data: bytes) -> Tuple[str, bool]: + """A forwarded SAGIAN CAN message as the Master Controller's log words it + (`TO_NODE 05:00 READ SUCCESS F7 28 0F BB 40`), and whether its status is one of those seen in + normal operation (`SAGIAN_CAN_KNOWN_STATUSES`).""" + if len(data) < 7: + return f"short message {data.hex()}", False + kind = SAGIAN_CAN_KINDS.get(data[5], f"kind 0x{data[5]:02X}") + status = SAGIAN_CAN_KNOWN_STATUSES.get(data[6]) + words = [ + "TO_NODE" if data[1] == 0x01 else f"direction 0x{data[1]:02X}", + f"{data[2]:02X}:{data[4]:02X}", + kind, + status or f"status 0x{data[6]:02X}", + ] + if len(data) > 7: + words.append(data[7:].hex(" ").upper()) + return " ".join(words), status is not None and data[1] == 0x01 + + +# A drive's own error code while its motor power is off, the interlock tripped ("interlock active"). +INTERLOCK_ACTIVE = 0x0416 + + +def describe_routine_unsolicited(reply: "Reply") -> Optional[str]: + """What an unsolicited message every session sees says, or None for one worth showing. + + Routine: a drive's EMCY with error 0000 (its fault cleared, as it is enabled), a drive's EMCY + naming `interlock active`, and a Move All notice ending in `interlock tripped`. The last two + follow every interlock trip, the driver's own at `stop` included. So does the chassis's trip event + (Notify On Interlock Trip), which is logged at INFO; `BiomekI7Driver` tells a trip it made from + one it did not.""" + if (reply.device, reply.opcode) == EMCY and reply.status == Status.EMERGENCY: + if len(reply.data) < 8: + return None + emcy = parse_emcy(reply.data) + if emcy.error_code == 0: + return f"drive node 0x{emcy.node:02X}: fault cleared (EMCY 0000)" + if emcy.device_error == INTERLOCK_ACTIVE: + return f"drive node 0x{emcy.node:02X}: interlock active (EMCY {emcy.error_code:04X})" + return None + if reply.status == Status.NOTICE and reply.error_code == INTERLOCK_TRIPPED_CODE: + return f"device 0x{reply.device:02X} index {reply.index}: move ended, interlock tripped" + return None + + +@dataclass(frozen=True) +class Request: + """One request, before a sequence number is given to it.""" + + device: int + index: int + opcode: int + params: bytes = b"" + + def __post_init__(self) -> None: + if (self.device, self.opcode) not in COMMANDS: + raise ValueError( + f"device 0x{self.device:02X} opcode 0x{self.opcode:02X} is not a command this driver sends" + ) + if not 0 <= self.index <= 0xFF: + raise ValueError(f"index must be 0-255, got {self.index}") + + @property + def name(self) -> str: + return COMMANDS[(self.device, self.opcode)] + + @property + def two_stage(self) -> bool: + """Whether the board answers ACCEPTED before DONE.""" + return (self.device, self.opcode) in TWO_STAGE + + def encode(self, sequence: int) -> bytes: + """The message bytes, with `sequence` (1-255; 0 is the boards' own).""" + if not 1 <= sequence <= 0xFF: + raise ValueError(f"sequence must be 1-255, got {sequence}") + return bytes([self.device, self.index, 0x00, sequence, self.opcode]) + self.params + + def __str__(self) -> str: + return f"{self.name} (device 0x{self.device:02X}, index {self.index})" + + +@dataclass(frozen=True) +class Reply: + """One message from a board.""" + + device: int + index: int + sequence: int + opcode: int + status: int + data: bytes + # Replies the board sent under this request's sequence for other devices: a Move All's axes + # report there when they end other than plainly. Set by `AceBoard` on the final reply. + related: Tuple["Reply", ...] = field(default=(), compare=False) + + @classmethod + def parse(cls, message: bytes) -> "Reply": + """Split a message into its header, status and data. + + Raises: + ValueError: if the message is shorter than a header and a status byte. + """ + if len(message) < 6: + raise ValueError(f"ACE reply too short: {message.hex()}") + device, index, _, sequence, opcode, status = message[:6] + return cls(device, index, sequence, opcode, status, bytes(message[6:])) + + @property + def key(self) -> Tuple[int, int, int, int]: + """What a reply shares with the request it answers.""" + return (self.device, self.index, self.sequence, self.opcode) + + @property + def unsolicited(self) -> bool: + return self.sequence == 0 + + @property + def error_code(self) -> Optional[int]: + """The ACE error code, or None when the reply reports success.""" + if self.status == Status.ERROR: + return self.data[0] if self.data else 0 + if self.status in (Status.ACCEPTED, Status.DONE, Status.NOTICE) and self.data and self.data[0]: + return self.data[0] + return None + + @property + def device_error(self) -> Optional[int]: + """The drive's own error code that follows the ACE error code, when there is one.""" + if self.error_code is None or len(self.data) < 2: + return None + return int.from_bytes(self.data[1:], "little") + + @property + def payload(self) -> bytes: + """What a successful reply returns, after its zero error byte.""" + return self.data[1:] + + def raise_for_error(self, request: str) -> None: + """Raise the `AceError` this reply reports, if it reports one.""" + code = self.error_code + if code is not None: + raise ace_error(code, self.device_error, request, self.device, self.index) + + def check(self, request: str) -> "Reply": + """Return this reply, or raise the `AceError` it reports.""" + self.raise_for_error(request) + return self + + +# -- requests ---------------------------------------------------------------- + + +def get_module_id() -> Request: + return Request(Device.MODULE, 0, 0x00) + + +def get_module_serial_number() -> Request: + return Request(Device.MODULE, 0, 0x02) + + +def get_module_hardware_version() -> Request: + return Request(Device.MODULE, 0, 0x03) + + +def get_module_device_count() -> Request: + return Request(Device.MODULE, 0, 0x08) + + +def get_module_application_image_length() -> Request: + return Request(Device.MODULE, 0, 0x11) + + +def get_module_application_image_crc() -> Request: + return Request(Device.MODULE, 0, 0x12) + + +def stop_module_execution() -> Request: + return Request(Device.MODULE, 0, 0x0F) + + +def get_board_serial_number(board: int) -> Request: + return Request(Device.BOARD, board, 0x02) + + +def get_board_hardware_version(board: int) -> Request: + return Request(Device.BOARD, board, 0x03) + + +def get_board_bootloader_version(board: int) -> Request: + return Request(Device.BOARD, board, 0x04) + + +def get_board_application_version(board: int) -> Request: + return Request(Device.BOARD, board, 0x10) + + +def get_board_application_image_length(board: int) -> Request: + return Request(Device.BOARD, board, 0x11) + + +def get_board_application_image_crc(board: int) -> Request: + return Request(Device.BOARD, board, 0x12) + + +def get_interlock_status(interlock: int = 1) -> Request: + return Request(Device.INTERLOCK, interlock, 0x10) + + +def notify_on_interlock_trip(interlock: int = 1, notify: bool = True) -> Request: + return Request(Device.INTERLOCK, interlock, 0x11, bytes([int(notify)])) + + +def trip_interlock(interlock: int = 1) -> Request: + return Request(Device.INTERLOCK, interlock, 0x50) + + +def rearm_interlock(interlock: int = 1) -> Request: + return Request(Device.INTERLOCK, interlock, 0x51) + + +def stop_motion_service() -> Request: + return Request(Device.MOTION_SERVICE, 0, 0x0F) + + +def move_all(timeout_ms: int) -> Request: + """Start every move whose parameters were set since the last move, together.""" + return Request(Device.MOTION_SERVICE, 0, 0x50, struct.pack(" Request: + """Load an axis's motor table. `payload` is the table exactly as the Master Controller sent it.""" + return Request(device, axis, 0x10, payload) + + +def set_state_enabled(device: int, axis: int) -> Request: + return Request(device, axis, 0x12, b"\x00") + + +def get_state(device: int, axis: int) -> Request: + """Ask a motor or pump for its state byte; see `AxisState`.""" + return Request(device, axis, 0x11) + + +def get_homed_state(device: int, axis: int) -> Request: + """Whether a motor or a pump (`device`) has been homed since the board started.""" + return Request(device, axis, 0x21) + + +def get_current_position(device: int, axis: int) -> Request: + return Request(device, axis, 0x24) + + +def get_control_effort(axis: int) -> Request: + return Request(Device.MOTOR, axis, 0x31) + + +# The largest force limit Set Move Parameters can carry: a u32 of the Master Controller's units x1000. +MAX_FORCE = 4294967.295 + + +def set_motor_move_parameters( + axis: int, + position: int, + velocity: int, + acceleration: int, + jerk: int, + force: int = 0, + sensor: int = 0, + trigger: int = 0, +) -> Request: + """Set a motor's next move, in counts, laid out as the Master Controller's logged requests lay + it out. `force` is the force limit x1000 (grip and tip loading), 0 for none. `sensor` + and `trigger` make the move stop where a sensor fires: liquid-level sensing on a Span-8 Z, the + AccuFrame when framing (0, 0: no sensor).""" + params = struct.pack(" Request: + """Set a syringe pump's next move, in counts, with the valve position it moves through.""" + params = struct.pack( + " Request: + """Start one motor's move on its own.""" + return Request(Device.MOTOR, axis, 0x50, struct.pack(" Request: + return Request(device, axis, 0x51) + + +def get_tip_status(sensor: int = 1) -> Request: + return Request(Device.TIP_SENSOR, sensor, 0x10) + + +def set_lls_cd_sensitivity(clot_detection: bool, value: int) -> Request: + """Liquid-level (or, with `clot_detection`, clot-detection) sensitivity, 0-4095, on the Span-8's + LLS/CD board (the device that also answers Get Tip Status): what the Master Controller sends + for `SS`.""" + if not 0 <= value <= 4095: + raise ValueError(f"sensitivity {value} is outside 0..4095") + return Request(Device.TIP_SENSOR, 1, 0x41, struct.pack(" Request: + return Request(Device.IO_SERVICE, 0, 0x08) + + +def get_input_output_name(device: int, index: int) -> Request: + return Request(device, index, 0x01) + + +def read_input_output(device: int, index: int) -> Request: + return Request(device, index, 0x10) + + +def notify_on_change(device: int, index: int, notify: bool = True) -> Request: + return Request(device, index, 0x11, bytes([int(notify)])) + + +def get_analog_input_units(index: int) -> Request: + return Request(Device.ANALOG_INPUT, index, 0x12) + + +# ERROR is what the Master Controller shows after a failed move (2026-07-31, `2D 01 00 seq 10 05`). +StatusDisplayState = Literal["ready", "running", "paused", "error"] +STATUS_DISPLAY_STATES = {"ready": 0x02, "running": 0x03, "paused": 0x04, "error": 0x05} + + +def set_status_display(state: StatusDisplayState, display: int = 1) -> Request: + return Request(Device.STATUS_DISPLAY, display, 0x10, bytes([STATUS_DISPLAY_STATES[state]])) + + +def get_accuframe_offsets(accuframe: int = 1) -> Request: + return Request(Device.ACCUFRAME, accuframe, 0xF7) + + +def list_legacy_alp_devices() -> Request: + return Request(Device.LEGACY_ALP, 0, 0x18) + + +def send_digital_io_box(params: bytes, box: int = 1) -> Request: + """Pass a command to the digital I/O box. Its bytes are the box's own and are not decoded here.""" + return Request(Device.IO_BOX, box, 0x10, params) + + +# -- replies ----------------------------------------------------------------- + +# Get Module ID's two bytes, as the Master Controller's log decodes them ("Chassis", "Left +# Multichannel", "Right Span-8"). Only these three were seen, on one instrument. +MODULE_TYPES = {0x80: "chassis", 0xFD: "multichannel", 0xFB: "span8"} +MODULE_SIDES = {0x00: None, 0x01: "left", 0x02: "right"} + +# Hardware version type codes, as the Master Controller names them. +HARDWARE_NAMES = { + 0x00: "Motion Board", + 0x01: "Transport Supervisor", + 0x02: "Chassis Supervisor", + 0xE0: "SAGIAN Motion Board", + 0xE1: "SAGIAN LLS Board", + 0xE2: "SAGIAN Syringe Pump Board", + 0xE3: "AccuFrame", + 0xE5: "Device Controller", +} + +# Tip sensor codes. 1 is "cannot determine" in the Master Controller's `VT` replies. +TIP_STATES = {0x00: "loaded", 0x01: "unknown", 0x02: "unloaded"} + +# What an axis reports when its part of a Move All ends other than plainly. A 1-byte report is +# one of the statuses; a 5-byte report is a type and the s32 position where its sensor fired. +LLS_LIQUID_SENSED = 69 +LLS_LIQUID_NOT_SENSED = 70 +CD_CLOT_NOT_DETECTED = 71 +CD_CLOT_DETECTED = 72 +ACCUFRAME = 175 +MotionOutcome = Literal[ + "done", "liquid-sensed", "accuframe", "liquid-not-sensed", "clot-not-detected", "clot-detected" +] +MOTION_OUTCOMES: Dict[int, MotionOutcome] = { + LLS_LIQUID_SENSED: "liquid-sensed", + LLS_LIQUID_NOT_SENSED: "liquid-not-sensed", + CD_CLOT_NOT_DETECTED: "clot-not-detected", + CD_CLOT_DETECTED: "clot-detected", + ACCUFRAME: "accuframe", +} + + +class AxisState(enum.IntEnum): + """A motor's or pump's state byte, as Get State answers it. + + An axis starts NOT_CONFIGURED at power-up, and goes back to it when Configure starts or a SAGIAN + drive reports it lost its parameters. Configure ends DISABLED; Set State moves between DISABLED + and ENABLED; Home and moves need ENABLED. FAULT follows a drive error. + """ + + ENABLED = 0x00 + DISABLED = 0x01 + NOT_CONFIGURED = 0xFE + FAULT = 0xFF + + +AxisStateName = Literal["enabled", "disabled", "not_configured", "fault"] +"""An `AxisState` as the public API gives it (`Pod.request_axis_states`): its name, lower case.""" + + +@dataclass(frozen=True) +class ModuleId: + """What Get Module ID answers: the kind of module and, for an arm's, its side.""" + + type_code: int + side_code: int + + @property + def type(self) -> Optional[str]: + """`chassis`, `multichannel` or `span8`; None for a code not seen yet.""" + return MODULE_TYPES.get(self.type_code) + + @property + def side(self) -> Optional[str]: + """`left` or `right` for an arm's module, None for the chassis.""" + return MODULE_SIDES.get(self.side_code) + + +@dataclass(frozen=True) +class HardwareVersion: + type_code: int + revision: int + + @property + def name(self) -> str: + return HARDWARE_NAMES.get(self.type_code, f"hardware 0x{self.type_code:02X}") + + def __str__(self) -> str: + return f"{self.name} {self.revision}" + + +@dataclass(frozen=True) +class Emcy: + """A CANopen emergency message a drive sent through its board.""" + + node: int + error_code: int + error_register: int + device_error: int + source: int + + +def parse_module_id(payload: bytes) -> ModuleId: + return ModuleId(payload[0], payload[1]) + + +def parse_string(payload: bytes) -> str: + return payload.decode("ascii") + + +def parse_hardware_version(payload: bytes) -> HardwareVersion: + return HardwareVersion(payload[0], payload[1]) + + +def parse_device_count(payload: bytes) -> Dict[int, int]: + """Each kind of device a module or service holds, by device byte, and how many.""" + if len(payload) % 3: + raise ValueError(f"device count is (device, u16 count) triples, got {payload.hex()}") + return { + payload[i]: int.from_bytes(payload[i + 1 : i + 3], "little") for i in range(0, len(payload), 3) + } + + +def parse_u32(payload: bytes) -> int: + return int(struct.unpack_from(" int: + return int(struct.unpack_from(" float: + return float(struct.unpack_from(" Tuple[float, float, float]: + x, y, z = struct.unpack_from(" InterlockState: + """Raises `ValueError` for a byte not seen.""" + state = INTERLOCK_STATES.get(payload[0]) + if state is None: + raise ValueError(f"interlock state 0x{payload[0]:02X} has not been seen") + return state # type: ignore[return-value] + + +def parse_axis_state(payload: bytes) -> AxisState: + """Raises `ValueError` for a state byte the firmware does not set.""" + return AxisState(payload[0]) + + +def parse_tip_status(payload: bytes) -> List[Optional[str]]: + """Each channel's tip, `loaded` or `unloaded`; None for a code not seen yet.""" + return [TIP_STATES.get(b) for b in payload] + + +@dataclass(frozen=True) +class MotionComplete: + """How one axis's part of a Move All ended: `done`, or a sensor outcome; `position` is where a + sensor stopped it (liquid sensed, AccuFrame), else None.""" + + device: int + index: int + outcome: MotionOutcome + position: Optional[int] = None + + +def parse_motion_complete(reply: Reply) -> MotionComplete: + """An axis's report inside a Move All.""" + payload = reply.payload + if len(payload) == 5: + (position,) = struct.unpack_from(" Emcy: + """Decode an EMERGENCY reply's data: node, CANopen error code and register, then the drive's own + error code and the source it names.""" + node = data[1] + error_code, error_register, device_error, source = struct.unpack_from(" (the request, its sequence, the frame's bytes, what the log says it is). +# The reads the Master Controller never sends (`FIRMWARE_READS`) were never logged; their frames +# follow the request layout. +FRAMES: Dict[Tuple[int, int], Tuple[Callable[[], p.Request], int, str, str]] = { + (0x00, 0x00): (p.get_module_id, 0x01, "0000000100", "Get Module ID"), + (0x00, 0x02): (p.get_module_serial_number, 0x03, "0000000302", "Get Module Serial Number"), + (0x00, 0x03): (p.get_module_hardware_version, 0x02, "0000000203", "Get Module Hardware Version"), + (0x00, 0x08): (p.get_module_device_count, 0x06, "0000000608", "Get Module Device Count"), + (0x00, 0x0F): (p.stop_module_execution, 0x75, "000000750F", "Stop Module Execution"), + (0x00, 0x11): ( + p.get_module_application_image_length, + 0x05, + "0000000511", + "Get Module Application Image Length", + ), + (0x00, 0x12): ( + p.get_module_application_image_crc, + 0x04, + "0000000412", + "Get Module Application Image CRC", + ), + (0x02, 0x02): ( + lambda: p.get_board_serial_number(6), + 0x0B, + "0206000B02", + "Get Board 6 Serial Number", + ), + (0x02, 0x03): ( + lambda: p.get_board_hardware_version(1), + 0x07, + "0201000703", + "Get Board 1 Hardware Version", + ), + (0x02, 0x04): ( + lambda: p.get_board_bootloader_version(7), + 0x31, + "0207003104", + "Get Board 7 Bootloader Version", + ), + (0x02, 0x10): ( + lambda: p.get_board_application_version(1), + 0x08, + "0201000810", + "Get Board 1 Application Version", + ), + (0x02, 0x11): ( + lambda: p.get_board_application_image_length(6), + 0x0D, + "0206000D11", + "Get Board 6 Application Image Length", + ), + (0x02, 0x12): ( + lambda: p.get_board_application_image_crc(6), + 0x0C, + "0206000C12", + "Get Board 6 Application Image CRC", + ), + (0x01, 0x10): (p.get_interlock_status, 0x09, "0101000910", "(never logged)"), + (0x01, 0x11): (p.notify_on_interlock_trip, 0x28, "010100281101", "Notify On Interlock Trip TRUE"), + (0x01, 0x50): (p.trip_interlock, 0xEA, "010100EA50", "Trip Interlock"), + (0x01, 0x51): (p.rearm_interlock, 0xE1, "010100E151", "Re-Arm Interlock"), + (0x10, 0x0F): (p.stop_motion_service, 0x67, "100000670F", "Stop Motion Service"), + (0x10, 0x50): (lambda: p.move_all(5000), 0x28, "100000285088130000", "Move All Timeout:5000"), + (0x11, 0x10): ( + lambda: p.configure(p.Device.MOTOR, 2, MOTOR_TABLE), + 0x2F, + "1102002F10" + MOTOR_TABLE.hex(), + "Configure Y1 Minimum Velocity:23 ...", + ), + (0x11, 0x11): (lambda: p.get_state(p.Device.MOTOR, 3), 0x07, "1103000711", "(never logged)"), + (0x11, 0x12): ( + lambda: p.set_state_enabled(p.Device.MOTOR, 3), + 0x76, + "110300761200", + "Set Z State ENABLED", + ), + (0x11, 0x21): ( + lambda: p.get_homed_state(p.Device.MOTOR, 1), + 0x3C, + "1101003C21", + "Get X Homed State", + ), + (0x11, 0x24): ( + lambda: p.get_current_position(p.Device.MOTOR, 7), + 0x80, + "1107008024", + "Get GZ Current Position", + ), + (0x11, 0x31): (lambda: p.get_control_effort(0x13), 0x96, "1113009631", "Get GG Control Effort"), + (0x11, 0x40): ( + lambda: p.set_motor_move_parameters( + 3, position=-1000, velocity=24320, acceleration=128000, jerk=698880 + ), + 0xAB, + "110300AB40005F000000F4010000AA0A000000000018FCFFFF0000", + "Set Z Move Parameters Position:-1000 Velocity:24320 Acceleration:128000 Jerk:698880", + ), + (0x11, 0x50): (lambda: p.move(3, 30000), 0xAC, "110300AC5030750000", "Move Z Timeout:30000"), + (0x11, 0x51): (lambda: p.home(p.Device.MOTOR, 3), 0xAD, "110300AD51", "Home Z"), + (0x12, 0x10): ( + lambda: p.configure(p.Device.PUMP, 1, PUMP_TABLE), + 0x3F, + "1201003F10" + PUMP_TABLE.hex(), + "Configure D1 Minimum Start Velocity:200 ...", + ), + (0x12, 0x11): (lambda: p.get_state(p.Device.PUMP, 1), 0x07, "1201000711", "(never logged)"), + (0x12, 0x12): ( + lambda: p.set_state_enabled(p.Device.PUMP, 8), + 0x6B, + "1208006B1200", + "Set D8 State ENABLED", + ), + (0x12, 0x21): ( + lambda: p.get_homed_state(p.Device.PUMP, 1), + 0xDB, + "120100DB21", + "Get D1 Homed State", + ), + (0x12, 0x24): ( + lambda: p.get_current_position(p.Device.PUMP, 8), + 0x88, + "1208008824", + "Get D8 Current Position", + ), + (0x12, 0x40): ( + lambda: p.set_pump_move_parameters( + 2, + position=0, + start_velocity=200, + max_velocity=23200, + cutoff_velocity=200, + acceleration=50000, + valve="input", + ), + 0x72, + "1202007240C8000000A05A0000C800000050C300000000000000", + "Set D2 Move Parameters Position:0 Valve:INPUT Start Velocity:200 Maximum Velocity:23200 " + "Cutoff Velocity:200 Acceleration:50000", + ), + (0x12, 0x51): (lambda: p.home(p.Device.PUMP, 1), 0x60, "1201006051", "Home D1"), + (0x13, 0x10): (p.get_tip_status, 0x95, "1301009510", "Get Tip Status"), + (0x13, 0x41): ( + lambda: p.set_lls_cd_sensitivity(False, 3500), + 0xA2, + "130100A24100AC0D", + "Set LLS Sensitivity 3500", + ), + (0x20, 0x08): (p.get_io_service_device_count, 0x0A, "2000000A08", "Get IO Service Device Count"), + (0x21, 0x01): ( + lambda: p.get_input_output_name(p.Device.DIGITAL_INPUT, 1), + 0x1E, + "2101001E01", + "Get Digital Input 1 Name", + ), + (0x21, 0x10): ( + lambda: p.read_input_output(p.Device.DIGITAL_INPUT, 1), + 0x20, + "2101002010", + "Read Digital Input 1", + ), + (0x21, 0x11): ( + lambda: p.notify_on_change(p.Device.DIGITAL_INPUT, 1), + 0x1F, + "2101001F1101", + "Notify On Digital Input 1 Change TRUE", + ), + (0x22, 0x01): ( + lambda: p.get_input_output_name(p.Device.ANALOG_INPUT, 9), + 0x0B, + "2209000B01", + "Get Analog Input 9 Name", + ), + (0x22, 0x10): ( + lambda: p.read_input_output(p.Device.ANALOG_INPUT, 1), + 0x65, + "2201006510", + "Read Analog Input 1", + ), + (0x22, 0x12): ( + lambda: p.get_analog_input_units(9), + 0x0C, + "2209000C12", + "Get Analog Input 9 Units", + ), + (0x28, 0x01): ( + lambda: p.get_input_output_name(p.Device.DIGITAL_OUTPUT, 1), + 0x22, + "2801002201", + "Get Digital Output 1 Name", + ), + (0x28, 0x10): ( + lambda: p.read_input_output(p.Device.DIGITAL_OUTPUT, 1), + 0x24, + "2801002410", + "Read Digital Output 1", + ), + (0x28, 0x11): ( + lambda: p.notify_on_change(p.Device.DIGITAL_OUTPUT, 1), + 0x23, + "280100231101", + "Notify On Digital Output 1 Change TRUE", + ), + (0x2D, 0x10): ( + lambda: p.set_status_display("running"), + 0xE2, + "2D0100E21003", + "Set Status Display RUNNING", + ), + (0xAF, 0xF7): (p.get_accuframe_offsets, 0x32, "AF010032F7", "Get AccuFrame Offsets"), + (0xFE, 0x18): (p.list_legacy_alp_devices, 0x26, "FE00002618", "List Legacy ALP Devices"), + (0xFF, 0x10): ( + lambda: p.send_digital_io_box(b"\x02\x01"), + 0xE0, + "FF0100E0100201", + "Send Digital I/O Box 00 WRITE 01", + ), +} + + +def decode(message: bytes) -> Tuple[int, int, int, int, bytes]: + """A request's header and parameters, by the layout in `protocol.py`'s docstring.""" + device, index, zero, sequence, opcode = message[:5] + assert zero == 0 + return device, index, sequence, opcode, message[5:] + + +class ExactFrameTests(unittest.TestCase): + def test_every_command_has_its_frame(self) -> None: + """A command added to `COMMANDS` needs its frame here.""" + self.assertEqual(set(FRAMES), set(p.COMMANDS)) + + def test_each_request_is_the_logged_frame(self) -> None: + for key, (build, sequence, frame_hex, logged) in FRAMES.items(): + with self.subTest(command=p.COMMANDS[key], logged=logged): + request = build() + self.assertEqual((request.device, request.opcode), key) + self.assertEqual(request.encode(sequence), bytes.fromhex(frame_hex)) + + def test_reads_never_logged_only_read(self) -> None: + for key, name in p.FIRMWARE_READS.items(): + self.assertTrue(name.startswith("Get "), name) + self.assertEqual(p.COMMANDS[key], name) + + def test_status_display_error_is_the_logged_frame(self) -> None: + # Log.db3, after a failed move: `2D 01 00 seq 10 05`. + self.assertEqual(p.set_status_display("error").encode(0x2E), bytes.fromhex("2D01002E1005")) + + def test_only_moves_and_homes_answer_twice(self) -> None: + two_stage = {key for key in FRAMES if FRAMES[key][0]().two_stage} + self.assertEqual(two_stage, {(0x10, 0x50), (0x11, 0x50), (0x11, 0x51), (0x12, 0x51)}) + + +class RoundTripTests(unittest.TestCase): + """Build, then parse: every field comes back out as it went in.""" + + def setUp(self) -> None: + self.random = random.Random(7) + + def test_header(self) -> None: + for key in FRAMES: + for _ in range(5): + index, sequence = self.random.randrange(256), self.random.randrange(1, 256) + params = bytes(self.random.randrange(256) for _ in range(self.random.randrange(4))) + message = p.Request(key[0], index, key[1], params).encode(sequence) + self.assertEqual(decode(message), (key[0], index, sequence, key[1], params)) + + def test_motor_move_parameters(self) -> None: + for _ in range(50): + values = dict( + velocity=self.random.randrange(2**32), + acceleration=self.random.randrange(2**32), + jerk=self.random.randrange(2**32), + force=self.random.randrange(2**32), + position=self.random.randrange(-(2**31), 2**31), + sensor=self.random.randrange(256), + trigger=self.random.randrange(256), + ) + axis = self.random.randrange(1, 32) + device, index, _, opcode, params = decode( + p.set_motor_move_parameters(axis, **values).encode(1) + ) + self.assertEqual((device, index, opcode), (p.Device.MOTOR, axis, 0x40)) + fields = struct.unpack(" None: + for valve, code in p.VALVE_POSITIONS.items(): + values = [self.random.randrange(2**32) for _ in range(4)] + position = self.random.randrange(-(2**31), 2**31) + request = p.set_pump_move_parameters( + 3, + position, + values[0], + values[1], + values[2], + values[3], + valve, # type: ignore[arg-type] + ) + _, index, _, opcode, params = decode(request.encode(1)) + self.assertEqual((request.device, index, opcode), (p.Device.PUMP, 3, 0x40)) + self.assertEqual(struct.unpack(" None: + for timeout in (0, 5000, 30000, 2**32 - 1): + self.assertEqual(struct.unpack(" None: + for table in (MOTOR_TABLE, PUMP_TABLE): + self.assertEqual(decode(p.configure(p.Device.MOTOR, 1, table).encode(1))[4], table) + + def test_lls_cd_sensitivity(self) -> None: + for clot in (False, True): + for value in (0, 1, 3500, 4095): + params = decode(p.set_lls_cd_sensitivity(clot, value).encode(1))[4] + self.assertEqual(struct.unpack(" None: + for _ in range(50): + header = [self.random.randrange(256) for _ in range(5)] + header[2] = 0 + status = self.random.choice(list(p.Status)) + data = bytes(self.random.randrange(256) for _ in range(self.random.randrange(8))) + reply = p.Reply.parse(bytes(header) + bytes([status]) + data) + self.assertEqual( + (reply.device, reply.index, reply.sequence, reply.opcode, reply.status, reply.data), + (header[0], header[1], header[3], header[4], status, data), + ) + self.assertEqual(reply.key, (header[0], header[1], header[3], header[4])) + self.assertEqual(reply.unsolicited, header[3] == 0) + + def test_numbers(self) -> None: + for _ in range(50): + s32 = self.random.randrange(-(2**31), 2**31) + u32 = self.random.randrange(2**32) + self.assertEqual(p.parse_s32(struct.pack(" None: + counts = {0x02: 6, 0x11: 21, 0x12: 8, 0x22: 300} + payload = b"".join(bytes([d]) + n.to_bytes(2, "little") for d, n in counts.items()) + self.assertEqual(p.parse_device_count(payload), counts) + with self.assertRaises(ValueError): + p.parse_device_count(payload[:-1]) + version = p.parse_hardware_version(bytes([0xE3, 4])) + self.assertEqual((version.type_code, version.revision, str(version)), (0xE3, 4, "AccuFrame 4")) + self.assertEqual(str(p.parse_hardware_version(bytes([0x7A, 1]))), "hardware 0x7A 1") + + +class RefusalTests(unittest.TestCase): + def test_unknown_commands_are_refused(self) -> None: + with self.assertRaises(ValueError): + p.Request(p.Device.BOARD, 1, 0x05) # not a logged opcode: other commands stay unsendable + + def test_index_and_sequence_ranges(self) -> None: + with self.assertRaises(ValueError): + p.Request(p.Device.MOTOR, 256, 0x24) + for sequence in (0, 256): + with self.assertRaises(ValueError): + p.get_module_id().encode(sequence) + + +class ReplyTests(unittest.TestCase): + """Replies as the boards send them (the header, status, then data).""" + + def test_module_id(self) -> None: + seen: List[Tuple[object, object]] = [] + for message in ("000000010002008000", "00000001000200FD01", "00000001000200FB02"): + module = p.parse_module_id( + p.Reply.parse(bytes.fromhex(message)).check("Get Module ID").payload + ) + seen.append((module.type, module.side)) + self.assertEqual(seen, [("chassis", None), ("multichannel", "left"), ("span8", "right")]) + unknown = p.parse_module_id(bytes([0x42, 0x07])) + self.assertEqual((unknown.type, unknown.side), (None, None)) + + def test_strings(self) -> None: + reply = p.Reply.parse(bytes.fromhex("0000000302020053494D554C41544544") + b"0" * 4) + self.assertEqual(p.parse_string(reply.payload), "SIMULATED0000") + reply = p.Reply.parse(bytes.fromhex("02010008100200302E322E34")) + self.assertEqual(p.parse_string(reply.payload), "0.2.4") + + def test_interlock_status(self) -> None: + self.assertEqual(p.parse_interlock_status(b"\x00"), "armed") + self.assertEqual(p.parse_interlock_status(b"\xff"), "tripped") + with self.assertRaisesRegex(ValueError, "not been seen"): + p.parse_interlock_status(b"\x01") + # The unsolicited trip event carries the same byte. + event = p.Reply.parse(bytes.fromhex("01010000100300FF")) + self.assertEqual((event.device, event.opcode), p.INTERLOCK_TRIPPED) + self.assertEqual(p.parse_interlock_status(event.payload), "tripped") + + def test_axis_state(self) -> None: + for code, state in [(0x00, "ENABLED"), (0x01, "DISABLED"), (0xFE, "NOT_CONFIGURED"), + (0xFF, "FAULT")]: # fmt: skip + self.assertEqual(p.parse_axis_state(bytes([code])).name, state) + with self.assertRaises(ValueError): + p.parse_axis_state(b"\x02") + + def test_tip_status(self) -> None: + states = p.parse_tip_status(bytes([0, 2, 1, 2, 0, 0, 2, 9])) + self.assertEqual( + states, ["loaded", "unloaded", "unknown", "unloaded", "loaded", "loaded", "unloaded", None] + ) + + def test_motion_complete(self) -> None: + sensed = p.Reply.parse( + bytes([0x11, 9, 0, 5, 0x50, 0x02, 0, p.LLS_LIQUID_SENSED]) + struct.pack(" None: + emcy = p.parse_emcy(bytes.fromhex("007700100116040100")) + self.assertEqual( + (emcy.node, emcy.error_code, emcy.error_register, emcy.device_error, emcy.source), + (0x77, 0x1000, 0x01, 0x0416, 0x01), + ) + + def test_success_has_no_error(self) -> None: + # Get Module ID's DONE; a Move's ACCEPTED and DONE; the host-alive NOTICE (sequence 0). + for message in ("000000010002" + "008000", "110300AC5001" + "00", "110300AC5002" + "00", + "0000000040FE" + "00"): # fmt: skip + self.assertIsNone(p.Reply.parse(bytes.fromhex(message)).error_code, message) + + def test_errors_raise_their_kind(self) -> None: + cases = { + "1103000712" + "0030": NotConfiguredError, + "1103000751" + "0031": NotEnabledError, + "1103000740" + "0032": NotHomedError, + "1003000750" + "000F": InterlockTrippedError, + "1003000750" + "0238": MotionError, + "110300075002" + "3C0001": MotionError, + "1103000750" + "0077": AceError, + } + for message, kind in cases.items(): + with self.subTest(message=message): + reply = p.Reply.parse(bytes.fromhex(message.replace(" ", ""))) + with self.assertRaises(kind): + reply.raise_for_error("request") + + def test_device_error_follows_the_ace_error(self) -> None: + # A Move whose axis left its error window: DONE, ACE error 0x3C, device error 0x0100. + reply = p.Reply.parse(bytes.fromhex("110300075002" + "3C0001")) + self.assertEqual((reply.error_code, reply.device_error), (0x3C, 0x0100)) + with self.assertRaisesRegex(MotionError, r"device error 0x100: motion error window exceeded"): + reply.raise_for_error("Move Z") + + +class SagianCanTests(unittest.TestCase): + """Forwarded SAGIAN CAN messages, worded as the Master Controller's log words them.""" + + # Every distinct pattern in the Master Controller's logs (2026-07-27 .. 10-27), with its words. + LOGGED = { + "00010500000101f7280fbb40": "TO_NODE 05:00 READ SUCCESS F7 28 0F BB 40", + "00010500000001f0": "TO_NODE 05:00 ACTION SUCCESS F0", + "0001050000020101": "TO_NODE 05:00 WRITE SUCCESS 01", + "000105000003016801": "TO_NODE 05:00 EVENT SUCCESS 68 01", + "00012300040300": "TO_NODE 23:04 EVENT REQUEST", + "00012a00080300": "TO_NODE 2A:08 EVENT REQUEST", + } + + def test_logged_messages_read_as_the_master_controller_reads_them(self) -> None: + for data, words in self.LOGGED.items(): + with self.subTest(data=data): + self.assertEqual(p.describe_sagian_can(bytes.fromhex(data)), (words, True)) + + def test_any_other_status_is_not_called_normal(self) -> None: + text, normal = p.describe_sagian_can(bytes.fromhex("00010500000102")) + self.assertFalse(normal) + self.assertIn("status 0x02", text) + self.assertFalse(p.describe_sagian_can(bytes([0, 1]))[1]) + + +class RoutineUnsolicitedTests(unittest.TestCase): + """Unsolicited messages every session sees, as the instrument sent them (2026-11-09).""" + + @staticmethod + def reply(message: str) -> p.Reply: + return p.Reply.parse(bytes.fromhex(message)) + + def test_a_drive_clearing_its_fault_is_routine(self) -> None: + text = p.describe_routine_unsolicited(self.reply("00000000 31ff 007e0000000000000000")) + self.assertEqual(text, "drive node 0x7E: fault cleared (EMCY 0000)") + + def test_a_drive_reporting_the_interlock_is_routine(self) -> None: + for source in ("01", "02"): + with self.subTest(source=source): + text = p.describe_routine_unsolicited( + self.reply(f"0000000031ff007700100116 04{source}0000") + ) + self.assertEqual(text, "drive node 0x77: interlock active (EMCY 1000)") + + def test_a_move_the_interlock_ended_is_routine(self) -> None: + text = p.describe_routine_unsolicited(self.reply("11120000 50fe 0f1604")) + self.assertEqual(text, "device 0x11 index 18: move ended, interlock tripped") + + def test_other_messages_are_shown(self) -> None: + for message in ( + "00000000 31ff 007e0010010704010000", # another drive error: interlock tripped (0407) + "11120000 50fe 3c0001", # a move ended by its error window + "01010000 1003 00ff", # the chassis: the interlock tripped + "21010000 1003 0001", # a digital input changed (the door) + "00000000 31ff 007e", # too short to read + ): + with self.subTest(message=message): + self.assertIsNone(p.describe_routine_unsolicited(self.reply(message.replace(" ", "")))) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py new file mode 100644 index 00000000000..357375452b9 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -0,0 +1,103 @@ +"""Simulated boards: boards that answer from what a real Biomek i7's boards answered. + +`ReplayAceUSB` replays a recording; nothing it does reaches a USB device. A replayed board holds a +recording of request -> replies, keyed on everything in a request but its sequence number, and +answers a request it has a recording for with those replies under the request's sequence number. +A request it has no recording for gets no answer, as a board that ignored it would, and is kept in +`unanswered`. +""" + +import asyncio +import gzip +import json +import os +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split +from pylabrobot.io.usb import USB + +# Names the recording the simulator answers from (identity and sensor reads, recorded at an +# instrument's cold start) when no path is given. A generic one ships in `defaults/` +# (`biomek_i7_generic_coldstart.json`). +RECORDING_ENV = "BIOMEK_I7_SIMULATOR_RECORDING" + + +def recording_path(path: Optional[Union[str, Path]] = None) -> Path: + """`path`, else the file `$BIOMEK_I7_SIMULATOR_RECORDING` names. + + Raises: + ValueError: with neither. + """ + path = path or os.environ.get(RECORDING_ENV) + if not path: + raise ValueError( + f"no recording for the simulator to answer from: pass its path or set ${RECORDING_ENV}" + ) + return Path(path) + + +def load_recording(path: Optional[Union[str, Path]] = None) -> Dict[str, Any]: + """A recording (`recording_path`), gzipped (`.gz`) or not.""" + where = recording_path(path) + if where.suffix == ".gz": + with gzip.open(where, "rt", encoding="utf-8") as fh: + return dict(json.load(fh)) + with open(where, encoding="utf-8") as fh: + return dict(json.load(fh)) + + +def _request_key(message: bytes) -> str: + return (message[:3] + message[4:]).hex() + + +class ReplayAceUSB(USB): + """One board's USB link, answered from a recording.""" + + def __init__(self, recording: Dict[str, List[str]], name: str = "replayed ACE board"): + super().__init__(0x0AB5, 0xACE0, name) + self.recording = {k: [bytes.fromhex(r) for r in v] for k, v in recording.items()} + self.requests: List[bytes] = [] + self.unanswered: List[bytes] = [] + self._packets: "asyncio.Queue[bytes]" = asyncio.Queue() + + async def setup(self, empty_buffer=True): + pass + + async def stop(self): + pass + + async def write(self, data: bytes, timeout: Optional[float] = None): + for message in split(data): + self.requests.append(message) + replies = self.recording.get(_request_key(message)) + if replies is None: + self.unanswered.append(message) + continue + for reply in replies: + framed = frame(reply[:3] + message[3:4] + reply[4:]) + for i in range(0, len(framed), 16): + self._packets.put_nowait(framed[i : i + 16]) + + async def read(self, timeout=None, size=None, endpoint=None) -> bytes: + try: + return await asyncio.wait_for(self._packets.get(), timeout=0.05) + except asyncio.TimeoutError: + raise TimeoutError("no packet") from None + + +def replay_boards( + path: Optional[Union[str, Path]] = None, default_timeout: float = 1.0 +) -> List[AceBoard]: + """One replayed board per module in a recording (`recording_path`), as + `BiomekI7Driver(boards=...)` takes them.""" + data = load_recording(path) + return [ + AceBoard( + io=ReplayAceUSB(dict(entries), name=f"replayed {module}"), + name=f"replayed {module}", + default_timeout=default_timeout, + ) + for module, entries in data["boards"].items() + ] diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py new file mode 100644 index 00000000000..d8fcebca10c --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator_tests.py @@ -0,0 +1,80 @@ +"""Replayed boards: what they answer, and what they do not.""" + +import gzip +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ( + RECORDING_ENV, + ReplayAceUSB, + load_recording, + recording_path, + replay_boards, +) + +# Get Module ID answered once, and a Move answered twice (ACCEPTED, then DONE); keys leave out the +# sequence number, and the replies' sequence bytes are placeholders. +RECORDING = { + "00000000": ["000000000002008000"], + "1103005030750000": ["11030000500100", "11030000500200"], +} + + +class ReplayTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + self.io = ReplayAceUSB(RECORDING) + self.board = AceBoard(io=self.io, default_timeout=0.3) + await self.board.setup() + + async def asyncTearDown(self) -> None: + await self.board.stop() + + async def test_a_recorded_request_is_answered_under_its_own_sequence(self) -> None: + for _ in range(3): # each send takes the next sequence number; the recording ignores it + reply = await self.board.send(p.get_module_id()) + self.assertEqual(p.parse_module_id(reply.payload).type, "chassis") + self.assertEqual([m[3] for m in self.io.requests], [1, 2, 3]) + self.assertEqual(self.io.unanswered, []) + + async def test_replies_come_in_their_recorded_order(self) -> None: + reply = await self.board.send(p.move(3, 30000)) + self.assertEqual(reply.status, p.Status.DONE) + + async def test_an_unrecorded_request_gets_no_answer(self) -> None: + with self.assertRaises(TimeoutError): + await self.board.send(p.get_module_serial_number()) + self.assertEqual(self.io.unanswered, [p.get_module_serial_number().encode(1)]) + + +class RecordingFileTests(unittest.TestCase): + def test_gzipped_and_plain_recordings_load(self) -> None: + data = {"boards": {"chassis": [["00000000", ["000000000002008000"]]]}} + with tempfile.TemporaryDirectory() as folder: + plain = Path(folder) / "recording.json" + plain.write_text(json.dumps(data), encoding="utf-8") + packed = Path(folder) / "recording.json.gz" + with gzip.open(packed, "wt", encoding="utf-8") as fh: + json.dump(data, fh) + self.assertEqual(load_recording(plain), data) + self.assertEqual(load_recording(packed), data) + boards = replay_boards(packed) + self.assertEqual([b.name for b in boards], ["replayed chassis"]) + + def test_a_recording_must_be_named(self) -> None: + environment = {k: v for k, v in os.environ.items() if k != RECORDING_ENV} + with mock.patch.dict(os.environ, environment, clear=True): + with self.assertRaisesRegex(ValueError, RECORDING_ENV): + recording_path() + with mock.patch.dict(os.environ, {RECORDING_ENV: "from-the-environment.json"}): + self.assertEqual(recording_path(), Path("from-the-environment.json")) + self.assertEqual(recording_path("given.json"), Path("given.json")) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py new file mode 100644 index 00000000000..c07366257d4 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -0,0 +1,47 @@ +"""What the package's tests build their simulated Biomek i7 from: the generic one in `defaults/`, +named explicitly (never through `$BIOMEK_I7_SIMULATOR_RECORDING`). Not a test module itself.""" + +import copy +import json +from typing import Any, Dict, List, Optional, Sequence + +from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_RECORDING +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB + +_GENERIC: Optional[Dict[str, Any]] = None + + +def generic_recording() -> Dict[str, Any]: + """The generic cold-start recording, a fresh copy a test may change: `boards` maps each module + (`chassis`, `multichannel`, `span8`) to its [request key, [replies]] pairs.""" + global _GENERIC + if _GENERIC is None: + with open(GENERIC_RECORDING, encoding="utf-8") as fh: + _GENERIC = json.load(fh) + return copy.deepcopy(_GENERIC) + + +def generic_boards( + recording: Optional[Dict[str, Any]] = None, + modules: Optional[Sequence[str]] = None, + default_timeout: float = 1.0, +) -> List[AceBoard]: + """A replayed board per module of `recording` (by default the generic one), as + `simulator.replay_boards` builds them; `modules` picks and orders them.""" + data = recording if recording is not None else generic_recording() + names = list(data["boards"]) if modules is None else list(modules) + return [ + AceBoard( + io=ReplayAceUSB(dict(data["boards"][module]), name=f"replayed {module}"), + name=f"replayed {module}", + default_timeout=default_timeout, + ) + for module in names + ] + + +def generic_driver(boards: Optional[Sequence[AceBoard]] = None) -> BiomekI7Driver: + """A driver over `boards`, by default the generic instrument replayed.""" + return BiomekI7Driver(boards=generic_boards() if boards is None else boards) From 9ed3216bcdfd53290dec92273d18cfb5da53c345 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:56:32 +0000 Subject: [PATCH 07/28] `Biomek i7`: sort imports for ruff I001 --- pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index 2bd18e6f5df..892bf89baeb 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -10,7 +10,6 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import HardwareVersion, ModuleId - # The firmware this driver has been run against (one instrument, 2026-10-24 through 2026-11-10): # every motion board and module the same image, and the other boards' application versions # (chassis 0.2.4, SAGIAN Motion 0.3.14, LLS 0.7.8, syringe pump 5.0.9). The Master Controller From f0c0f35b17d4bb32c5fb08a5a6e7fae47c230a06 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:00:48 -0800 Subject: [PATCH 08/28] `Biomek i7`: the declared configuration, motor tables and units What the boards cannot report about an instrument, declared per instrument in one JSON file given by path (`declared_configuration_json`, now required): - `driver/configuration.py`: `DeviceConfiguration`, the motor tables (the Master Controller's instrument record: each axis's Configure parameters, home position and measured hysteresis, and the modules' serial numbers) and per pod the conversions, travel limits, geometry and settings from Biomek's instrument file, with the default deck's calibrated positions and layout. Each source's values carry a fingerprint; a file changed after import is refused at load. `anonymized()` makes a generic one: no serial numbers, no measured hysteresis. - `driver/motors.py`: the axes of each arm type and the limits read from their Configure bytes. - `units.py`: the one place PyLabRobot's units (mm, uL, mm/s) meet Biomek's (cm, its frame, the speed field). - `defaults/`: the generic configuration, one instrument's physical values with every serial number removed. - Discovery refuses a pod type other than the declared one, and on the instrument a configuration whose serial numbers are not the modules', or the generic one. Each pod gets its type's axes and its declared values. Tests: conversions give the counts Biomek's logs show for the instrument file's targets, the bridges meet where Biomek's logged moves stopped, save / load and the changed-file refusal, anonymizing, declared against found, the serial-number check on the instrument's own path, every speed field round-tripping on every Z and pump, and the motor tables' limits. --- .../biomek_i7/defaults/__init__.py | 12 +- .../biomek_i7_generic_configuration.json | 2667 +++++++++++++++++ .../beckman_coulter/biomek_i7/design.md | 11 + .../biomek_i7/driver/configuration.py | 452 ++- .../biomek_i7/driver/configuration_tests.py | 184 ++ .../biomek_i7/driver/features/pod.py | 47 +- .../biomek_i7/driver/master.py | 119 +- .../biomek_i7/driver/motors.py | 150 + .../biomek_i7/driver/motors_tests.py | 85 + .../biomek_i7/driver/serial_numbers_tests.py | 104 + .../biomek_i7/simulation_tests_support.py | 64 +- pylabrobot/beckman_coulter/biomek_i7/units.py | 222 ++ .../beckman_coulter/biomek_i7/units_tests.py | 83 + 13 files changed, 4176 insertions(+), 24 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/configuration_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/motors.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/units.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/units_tests.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py index b7118bd6e87..5521919f901 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py @@ -1,13 +1,15 @@ -"""A generic Biomek i7's cold start: what a simulated instrument answers when given no instrument's -own recording. +"""A generic Biomek i7: what a simulation is given when it has no instrument's own files. -Made from one instrument's cold-start recording (the requests the Master Controller sent at a -start and the boards' replies), with every serial number replaced by a placeholder of the same -length. +Made from one instrument's declared configuration and cold-start recording, with every serial +number and name removed. Its physical values (motor tables, conversions, travel, geometry, +settings, the default deck's calibration and layout) are that instrument's, so another +instrument's differ: drive an instrument with its own files. The configuration is marked +`generic` and carries no serial numbers, so a live session refuses it (`BiomekI7Driver.discover`). """ from pathlib import Path HERE = Path(__file__).parent +GENERIC_CONFIGURATION = HERE / "biomek_i7_generic_configuration.json" GENERIC_RECORDING = HERE / "biomek_i7_generic_coldstart.json" diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json new file mode 100644 index 00000000000..e33fd37ffb0 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json @@ -0,0 +1,2667 @@ +{ + "generic": true, + "chassis_serial_number": null, + "instrument_serial_number": null, + "sources": { + "instrument_file": { + "fingerprint": "sha256:9cbfcd7168db1a0a0e9f6436c4d1479bc1664e1c39c7e4c125f5694b96dee046" + }, + "master_controller": { + "fingerprint": "sha256:f4aceddd504ac0579c6fee9dad49a9ec4a637f2bd538ae4cd9a8191445a0af07" + } + }, + "pods": { + "left": { + "component": "MC_1", + "module_type": "multichannel", + "module_serial_number": null, + "source": "bif:Devices/Pipettor1/Pod1", + "conversion": { + "D": { + "const": 229.932355946194, + "offset": 187.7766869, + "unit": "uL" + }, + "GG": { + "const": 18334.65, + "offset": -5.981, + "unit": "cm" + }, + "GR": { + "const": -376.2492651, + "offset": 376.295, + "unit": "deg" + }, + "GY": { + "const": 1982.2617, + "offset": -15.833, + "unit": "cm" + }, + "GZ": { + "const": 1591.549, + "offset": -37.949, + "unit": "cm" + }, + "X": { + "const": 2560.0, + "offset": -10.518999999999998, + "unit": "cm" + }, + "Y": { + "const": 2560.0, + "offset": -14.446000000000002, + "unit": "cm" + }, + "Z": { + "const": 2560.0, + "offset": -39.863, + "unit": "cm" + } + }, + "limits": { + "D": [ + -185.9935538, + 1200.0 + ], + "GG": [ + 5.981, + 15.681 + ], + "GR": [ + -370.0, + 190.0 + ], + "GY": [ + 15.834, + 62.683 + ], + "GZ": [ + 6.943, + 37.949 + ], + "X": [ + 10.52, + 108.7457 + ], + "Y": [ + 14.596, + 59.5976 + ], + "Z": [ + 11.153599999999999, + 39.863 + ] + }, + "geometry": { + "bridge_x_span": 39.0154, + "bridge_to_head_x_offset": 11.020399999999999, + "mandrel1_x_offset": 4.353700000000001, + "mandrel1_y_offset": 2.5650000000000004, + "mandrel_x_spacing": 0.9, + "mandrel_y_spacing": 0.9, + "avoidance_margin": 0.2164, + "pod_x_span": 18.606, + "pod_y_span": 11.43, + "gripper_x_offset": 0.309, + "gripper_y_offset": 0.206, + "gripper_z_offset": -7.304, + "frame_safety_left": 0.5, + "frame_safety_right": 1.5, + "additional_safe_height": 0.5336, + "additional_safe_height_gripper": 0.5336, + "mandrels_x": 12, + "mandrels_y": 8, + "sub_mandrel_safe_height": 0.2705 + }, + "park": { + "GG": 7.889, + "GR": 90.0, + "GY": 48.0, + "GZMargin": -0.1, + "XMargin": 14.0, + "Y": 29.0, + "ZMargin": -0.1 + }, + "settings": { + "AlwaysMaxZ": false, + "AStarSearchLimit": 10000, + "DAxisULPerCM": 178.139348120214, + "DiscardStackHeightThreshold": 5.6, + "DiscardWiderUnsqueeze": 10.326, + "Fixed": true, + "GlobalMinSafeHeight": -100000.0, + "HeadBodyXSpan": 13.0175, + "HeadBodyYSpan": 7.9375, + "HeadFlangeHeight": 1.0795, + "HeadHeight": 9.8171, + "HeadSerialNumber": null, + "HeadType": "MC96_1200", + "HeadTypeLabel": "1200 \u00b5L MC-96 Head", + "HomingTimeout": 300000, + "HysteresisX": 1.0, + "HysteresisY": 1.0, + "LeftPod": true, + "ManualControlSafety": 0.5, + "MaxAllowedPositionDiffAfterRetry": 0.05, + "Name": "Pod1", + "NotHomedCode": "needs to be homed", + "PerActionOverhead": 0.001, + "PerMoveActionOverhead": 0.005, + "PodName": "MC_1", + "PodToHeadBodyXOffset": 2.795000000000001, + "PodToHeadBodyYOffset": 1.7462500000000007, + "PodType": "MC", + "PodTypeLabel": "Multichannel Pod", + "PruneMoves": true, + "RetrySpeed": 20, + "RotationPenalty": 10.0, + "SensorEnabled": false, + "SpeedLimit": 100.0, + "TimeoutSlop": 25.0, + "TipLoadForceLimitOffset": 250.0, + "TipLoadForceLimitSlope": 2150, + "TipLoadOverheadTime": 5.2, + "TipLoadPushOffDistance": 0.292, + "TipLoadPushOffSpeed": 5, + "TipLoadRelieveSpeed": 5, + "TipLoadRelieveZOffset": -0.7, + "TipLoadSettlingTime": 2.0, + "TipLoadSpeed": 10, + "TipLoadStartZOffset": 0.0, + "TipLoadXRangePadding": 70.5978, + "TipLoadZOffset": -1.25, + "TipSeatingDepth": 0.7074, + "TipUnloadShuckSpeed": 100, + "TipUnloadZOffset": -0.661, + "Type": "Pod96", + "UI_CLSID": "{b6711077-a389-4d59-8f40-95c4129106da}", + "WarningThresholdAngleChange": 0.25, + "WarningThresholdGripChange": 0.01, + "Head/PodToMandrel1": { + "X": 2.0477, + "Y": -6.325, + "Z": -10.5245 + }, + "GripperSqueezeForce": 5.0 + }, + "gripper_model": { + "Finger": { + "Base": [ + { + "X": -1.45, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.27 + }, + { + "X": 11.668, + "Y": -5.946999999999999 + }, + { + "X": 13.316, + "Y": -5.946999999999999 + }, + { + "X": 13.316, + "Y": -7.279999999999999 + }, + { + "X": 9.544, + "Y": -7.279999999999999 + }, + { + "X": 9.544, + "Y": -5.566000000000001 + }, + { + "X": 3.574, + "Y": -0.619 + }, + { + "X": -1.45, + "Y": -0.619 + } + ], + "BaseWithProbes": [ + { + "X": -1.45, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.27 + }, + { + "X": 11.668, + "Y": -5.946999999999999 + }, + { + "X": 11.90625, + "Y": -5.946999999999999 + }, + { + "X": 11.90625, + "Y": -9.234 + }, + { + "X": 9.544, + "Y": -9.234 + }, + { + "X": 9.544, + "Y": -5.566000000000001 + }, + { + "X": 3.574, + "Y": -0.619 + }, + { + "X": -1.45, + "Y": -0.619 + } + ], + "BottomPart": { + "FingerwiseSpan": 9.421, + "TopSurface": -0.508, + "ZOffset": 0.27, + "ZSpan": 7.55 + }, + "ClipperThickness": 0.106, + "ExtensionSpan": 9.065, + "FingerCenterOffset": -0.003, + "FingerMountOriginSpanAtHardstop": 6.321, + "FingerwiseOffset": 0.6330000000000002, + "LWFingerSpacing": 0.191, + "OverallAngledThickness": 1.022, + "PadsCenterToRotationCenter": 11.443, + "Thickness": 0.635, + "TopPart": { + "FingerwiseSpan": 5.345, + "ZSpan": 0.619 + } + }, + "Lowerhand": { + "FingerwiseSpan": 4.166, + "YSpanNoFingerMountExtension": 9.525, + "ZSpan": 3.175 + }, + "Upperhand": { + "CenterXOffset": 0.0, + "CenterYOffset": 0.0, + "XSpan": 4.851, + "YSpan": 8.165, + "ZSpan": 8.949 + } + }, + "obstacles": [ + { + "name": "BackLeftTower", + "buffer": 0.2, + "x2": 3.117, + "y2": 12.177 + }, + { + "name": "LeftShield", + "buffer": 0.2, + "x2": -6.496, + "y2": 70.24600000000001 + }, + { + "name": "LightCurtain", + "buffer": 0.5, + "y1": 70.24600000000001 + }, + { + "name": "BackShield", + "buffer": 0.2, + "y2": -2.0920000000000005 + }, + { + "name": "IBeam", + "buffer": 0.2, + "y2": 11.091999999999999, + "z1": 37.069 + }, + { + "name": "RightShield", + "buffer": 0.2, + "x1": 158.41400000000002, + "y2": 70.24600000000001 + }, + { + "name": "Floor", + "buffer": 0.2, + "z1": -500.0, + "z2": 0.0 + }, + { + "name": "BackRightTower", + "buffer": 0.2, + "x1": 148.8, + "y2": 12.177 + }, + { + "name": "LeftCamera", + "buffer": 0.2, + "x2": -1.6689999999999998, + "y1": 65.561, + "z1": 32.078 + }, + { + "name": "RightCamera", + "buffer": 0.2, + "x1": 153.586, + "y1": 65.561, + "z1": 32.078 + }, + { + "name": "PumpBank", + "buffer": 0.2, + "x1": 121.044, + "y2": 13.447, + "z2": 37.069 + } + ] + }, + "right": { + "component": "SPAN8_2", + "module_type": "span8", + "module_serial_number": null, + "source": "bif:Devices/Pipettor1/Pod2", + "conversion": { + "D1": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D2": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D3": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D4": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D5": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D6": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D7": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D8": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "D": { + "const": 24.0, + "offset": 0.0, + "unit": "uL" + }, + "GG": { + "const": 18334.65, + "offset": -5.987, + "unit": "cm" + }, + "GR": { + "const": -376.2492651, + "offset": 377.175, + "unit": "deg" + }, + "GY": { + "const": 1982.2617, + "offset": -15.901, + "unit": "cm" + }, + "GZ": { + "const": 1591.549, + "offset": -37.931, + "unit": "cm" + }, + "S": { + "const": 4713.0, + "offset": -6.3, + "unit": "cm" + }, + "X": { + "const": 2560.0, + "offset": -146.40669375, + "unit": "cm" + }, + "Y": { + "const": 4713.0, + "offset": -15.123735233662208, + "unit": "cm" + }, + "Z1": { + "const": 4823.423, + "offset": -37.235921235034354, + "unit": "cm" + }, + "Z2": { + "const": 4823.423, + "offset": -37.20402123503435, + "unit": "cm" + }, + "Z3": { + "const": 4823.423, + "offset": -37.23722123503438, + "unit": "cm" + }, + "Z4": { + "const": 4823.423, + "offset": -37.305421235034345, + "unit": "cm" + }, + "Z5": { + "const": 4823.423, + "offset": -37.27122123503436, + "unit": "cm" + }, + "Z6": { + "const": 4823.423, + "offset": -37.222921235034356, + "unit": "cm" + }, + "Z7": { + "const": 4823.423, + "offset": -37.21462123503436, + "unit": "cm" + }, + "Z8": { + "const": 4823.423, + "offset": -37.22662123503437, + "unit": "cm" + }, + "Z": { + "const": 4823.423, + "offset": -42.81242123503436, + "unit": "cm" + } + }, + "limits": { + "D": [ + 0.0, + 1000.0 + ], + "D1": [ + 0.0, + 1000.0 + ], + "D2": [ + 0.0, + 1000.0 + ], + "D3": [ + 0.0, + 1000.0 + ], + "D4": [ + 0.0, + 1000.0 + ], + "D5": [ + 0.0, + 1000.0 + ], + "D6": [ + 0.0, + 1000.0 + ], + "D7": [ + 0.0, + 1000.0 + ], + "D8": [ + 0.0, + 1000.0 + ], + "GG": [ + 5.987, + 15.687 + ], + "GR": [ + -370.0, + 190.0 + ], + "GY": [ + 15.902, + 62.966 + ], + "GZ": [ + 6.925, + 37.931 + ], + "Span": [ + 6.3, + 35.0 + ], + "X": [ + 48.199, + 146.406 + ], + "Y": [ + 15.274, + 66.455 + ], + "Z": [ + 22.635421235034357, + 39.52602123503435 + ], + "Z1": [ + 17.05892123503436, + 39.55792123503436 + ], + "Z2": [ + 17.05892123503436, + 39.52602123503435 + ], + "Z3": [ + 17.05892123503436, + 39.559221235034386 + ], + "Z4": [ + 17.05892123503436, + 39.62742123503435 + ], + "Z5": [ + 17.05892123503436, + 39.59322123503436 + ], + "Z6": [ + 17.05892123503436, + 39.54492123503436 + ], + "Z7": [ + 17.05892123503436, + 39.53662123503436 + ], + "Z8": [ + 17.05892123503436, + 39.548621235034375 + ] + }, + "geometry": { + "bridge_x_span": 25.7204, + "bridge_to_head_x_offset": 13.274799999999999, + "mandrel1_x_offset": 1.0, + "mandrel1_y_offset": 1.0, + "mandrel_x_spacing": 0.9, + "mandrel_y_spacing": 0.9, + "avoidance_margin": 0.2164, + "pod_x_span": 4.0, + "pod_y_span": 10.0, + "gripper_x_offset": 1.445, + "gripper_y_offset": 0.2, + "gripper_z_offset": -7.398, + "frame_safety_left": 1.0, + "frame_safety_right": 1.5, + "additional_safe_height": 1.0, + "additional_safe_height_gripper": 0.5336 + }, + "park": { + "GG": 7.889, + "GR": 90.0, + "GY": 48.0, + "GZMargin": -0.1, + "ZMargin": -0.1 + }, + "settings": { + "ADSlowMoveRange": 0.5, + "AlwaysMaxZ": false, + "AStarSearchLimit": 12500, + "CalibrateVolumeForProbes": false, + "D1SpeedLimit": 80.1724, + "D2SpeedLimit": 80.1724, + "D3SpeedLimit": 80.1724, + "D4SpeedLimit": 80.1724, + "D5SpeedLimit": 80.1724, + "D6SpeedLimit": 80.1724, + "D7SpeedLimit": 80.1724, + "D8SpeedLimit": 80.1724, + "DetectTips": true, + "DiscardHeight": 39.52602123503435, + "DiscardOffset": 0.35, + "DiscardOvershoot": 0.0, + "DiscardOvershootFixed": true, + "DiscardSpeed": 25, + "DiscardStackHeightThreshold": 5.6, + "DiscardWiderUnsqueeze": 10.326, + "DSpeedLimit": 100.0, + "Fixed": false, + "FixedHomingOffset": 0.2134, + "FixedProbeZOffset": 5.7899, + "GlobalMinSafeHeight": -100000.0, + "HeadSerialNumber": null, + "HeadType": "Unknown", + "HomingTimeout": 300000, + "HysteresisX": 1.0, + "HysteresisY": 1.0, + "LeftPod": false, + "LoadSpeed": 25, + "MandrelExtender": 5.7899, + "ManualControlSafety": 0.5, + "MaxAllowedPositionDiffAfterRetry": 0.05, + "MaxLoadingProbes": 2, + "MaxSafeDeltaY": 2.0, + "MaxSafeDeltaZ": 10.0, + "MaxUnloadingProbes": 4, + "MinLoadingInterval": 4, + "MinUnloadingInterval": 1, + "Name": "Pod2", + "NotHomedCode": "needs to be homed", + "OverrideRTSimulatedLLS": true, + "PerActionOverhead": 0.001, + "PerMoveActionOverhead": 0.005, + "PodName": "SPAN8_2", + "PodType": "SPAN8", + "PodTypeLabel": "Span Pod", + "PostClotDetectionPause": 0.1, + "PostRunWashVolume": 1.0, + "ProbeCount": 8, + "ProbeReservoirYMargin": 0.16256, + "ProbeSize": 0.9, + "ProbeSwitchPoint": 11.0, + "PruneMoves": true, + "realvsExpected1_7": -0.010500000000000398, + "RetrySpeed": 20, + "RH_Backoff": 50.0, + "RotationPenalty": 10.0, + "SensorEnabled": true, + "SpeedLimit": 100, + "STAGSpeed": 1, + "SystemTrailingAirgap": 20.0, + "TimeoutSlop": 25.0, + "TiploadExitZOffset": 2.0, + "TipLoadTime": 8.0, + "TipLoadZOffset": -0.77, + "TipShuckDiameter": 0.83, + "Type": "Pod8Span", + "UI_CLSID": "{fbe216b4-1c3a-4bac-91d0-53c036b3de70}", + "UISpanToRealSpan": 0.7, + "UnloadSpeed": 35, + "UseAccessPoints": false, + "ValveMoveTime": 0.35, + "ValveNoMoveTime": 0.045, + "WarningThresholdAngleChange": 0.25, + "WarningThresholdGripChange": 0.01, + "XShift1_7": -0.02970000000000539, + "BrokenTips": [ + false, + false, + false, + false, + false, + false, + false, + false + ], + "LoadingOffsets": [ + -0.05, + -0.05, + -0.05, + -0.05, + -0.05, + -0.05, + -0.05, + -0.05 + ], + "DefaultTipHubInfo": { + "Length": 0.9779, + "MaxRadius": 0.3429, + "MinRadius": 0.3302 + }, + "LLSWireModel": { + "AnchorCenterY": 40.721, + "AnchorHalfLength": 4.166, + "AnchorXOffset": 9.953, + "FixedTipZOriginToWireOffset": 3.371, + "WireBottomAtZMax": 29.78, + "WireStartXOffset": 2.6 + }, + "GripperSqueezeForce": 5.0 + }, + "gripper_model": { + "Finger": { + "Base": [ + { + "X": -1.45, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.27 + }, + { + "X": 11.668, + "Y": -5.946999999999999 + }, + { + "X": 13.316, + "Y": -5.946999999999999 + }, + { + "X": 13.316, + "Y": -7.279999999999999 + }, + { + "X": 9.544, + "Y": -7.279999999999999 + }, + { + "X": 9.544, + "Y": -5.566000000000001 + }, + { + "X": 3.574, + "Y": -0.619 + }, + { + "X": -1.45, + "Y": -0.619 + } + ], + "BaseWithProbes": [ + { + "X": -1.45, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.778 + }, + { + "X": 3.894, + "Y": 0.27 + }, + { + "X": 11.668, + "Y": -5.946999999999999 + }, + { + "X": 11.90625, + "Y": -5.946999999999999 + }, + { + "X": 11.90625, + "Y": -9.234 + }, + { + "X": 9.544, + "Y": -9.234 + }, + { + "X": 9.544, + "Y": -5.566000000000001 + }, + { + "X": 3.574, + "Y": -0.619 + }, + { + "X": -1.45, + "Y": -0.619 + } + ], + "BottomPart": { + "FingerwiseSpan": 9.421, + "TopSurface": -0.508, + "ZOffset": 0.27, + "ZSpan": 7.55 + }, + "ClipperThickness": 0.106, + "ExtensionSpan": 9.065, + "FingerCenterOffset": 0.014, + "FingerMountOriginSpanAtHardstop": 6.321, + "FingerwiseOffset": 0.6330000000000002, + "LWFingerSpacing": 0.191, + "OverallAngledThickness": 1.022, + "PadsCenterToRotationCenter": 11.42, + "Thickness": 0.635, + "TopPart": { + "FingerwiseSpan": 5.345, + "ZSpan": 0.619 + } + }, + "Lowerhand": { + "FingerwiseSpan": 4.166, + "YSpanNoFingerMountExtension": 9.525, + "ZSpan": 3.175 + }, + "Upperhand": { + "CenterXOffset": 0.0, + "CenterYOffset": 0.0, + "XSpan": 4.851, + "YSpan": 8.165, + "ZSpan": 8.949 + } + }, + "obstacles": [ + { + "name": "BackLeftTower", + "buffer": 0.2, + "x2": 3.117, + "y2": 12.177 + }, + { + "name": "LightCurtain", + "buffer": 0.5, + "y1": 70.246 + }, + { + "name": "BackShield", + "buffer": 0.2, + "y2": -2.092 + }, + { + "name": "IBeam", + "buffer": 0.2, + "y2": 11.092, + "z1": 37.069 + }, + { + "name": "Floor", + "buffer": 0.2, + "z1": -500.0, + "z2": 0.0 + }, + { + "name": "LeftCamera", + "buffer": 0.2, + "x2": -1.669, + "y1": 65.561, + "z1": 32.078 + }, + { + "name": "BackRightTower", + "buffer": 0.2, + "x1": 148.8, + "y2": 12.177 + }, + { + "name": "RightCamera", + "buffer": 0.2, + "x1": 153.586, + "y1": 65.561, + "z1": 32.078 + }, + { + "name": "RightShield", + "buffer": 0.2, + "x1": 158.414, + "y2": 70.246 + }, + { + "name": "PumpBank", + "buffer": 0.2, + "x1": 121.044, + "y2": 13.447, + "z2": 37.069 + }, + { + "name": "LeftShield", + "buffer": 0.2, + "x2": -7.874, + "y2": 70.246 + } + ] + } + }, + "deck_positions": { + "BS1": { + "corners": { + "1": [ + 40.3464, + 15.4873, + 16.0968 + ], + "2": [ + 40.423, + 15.474, + 16.1 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "CP1": { + "corners": { + "1": [ + 98.8117, + 15.3923, + 16.7973 + ], + "2": [ + 98.742, + 15.474, + 16.3 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "P1": { + "corners": { + "1": [ + 40.4144, + 25.8845, + 15.9601 + ], + "2": [ + 40.418, + 25.888, + 15.965 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "P10": { + "corners": { + "1": [ + 69.579, + 57.17080029449462, + 15.966 + ], + "2": [ + 69.58119999999998, + 57.16830029449462, + 15.9787 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Deck" + } + }, + "P11": { + "corners": { + "1": [ + 84.1574, + 36.3236, + 15.9652 + ], + "2": [ + 84.156, + 36.302, + 15.965 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "P12": { + "corners": { + "1": [ + 84.162, + 46.736, + 15.968 + ], + "2": [ + 84.1707, + 46.737, + 15.9679 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "P13": { + "corners": { + "1": [ + 84.155, + 57.175900294494625, + 15.972 + ], + "2": [ + 84.15719999999999, + 57.17340029449463, + 15.9851 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Deck" + } + }, + "P14": { + "corners": { + "1": [ + 98.691, + 25.939, + 15.974 + ], + "2": [ + 98.7398, + 25.9237, + 15.9713 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "P15": { + "corners": { + "1": [ + 98.715, + 36.324, + 15.975 + ], + "2": [ + 98.7468, + 36.3267, + 15.9744 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "P16": { + "corners": { + "1": [ + 98.709, + 46.744, + 15.972 + ], + "2": [ + 98.7184, + 46.7501, + 15.9737 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "P17": { + "corners": { + "1": [ + 98.723, + 57.177, + 15.964 + ], + "2": [ + 98.7366, + 57.1795, + 15.9766 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "P18": { + "corners": { + "1": [ + 113.314, + 15.476, + 15.964 + ], + "2": [ + 113.3297, + 15.4973, + 15.9615 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Position" + } + }, + "P19": { + "corners": { + "1": [ + 113.314, + 25.89, + 15.964 + ], + "2": [ + 113.3246, + 25.9146, + 15.9659 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Position" + } + }, + "P2": { + "corners": { + "1": [ + 40.4558, + 36.313, + 16.0101 + ], + "2": [ + 40.418, + 36.302, + 15.965 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "P20": { + "corners": { + "1": [ + 113.314, + 36.304, + 15.964 + ], + "2": [ + 113.3359, + 36.3325, + 15.9708 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Position" + } + }, + "P21": { + "corners": { + "1": [ + 113.314, + 46.718, + 15.964 + ], + "2": [ + 113.3125, + 46.7644, + 15.9665 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Position" + } + }, + "P22": { + "corners": { + "1": [ + 113.314, + 57.132, + 15.964 + ], + "2": [ + 113.3238, + 57.181, + 15.9735 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Position" + } + }, + "P23": { + "corners": { + "1": [ + 127.893, + 46.718, + 15.964 + ], + "2": [ + 127.8847, + 46.7469, + 15.9565 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Position" + } + }, + "P24": { + "corners": { + "1": [ + 127.893, + 57.132, + 15.964 + ], + "2": [ + 127.8928, + 57.1835, + 15.9636 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Position" + } + }, + "P3": { + "corners": { + "1": [ + 40.4703, + 46.7005, + 16.0425 + ], + "2": [ + 40.418, + 46.716, + 15.965 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "P4": { + "corners": { + "1": [ + 40.4777, + 57.1474, + 16.0187 + ], + "2": [ + 40.418, + 57.13, + 15.965 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "P5": { + "corners": { + "1": [ + 55.0039, + 36.3134, + 15.9538 + ], + "2": [ + 54.997, + 36.302, + 15.965 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "P6": { + "corners": { + "1": [ + 54.996, + 46.729, + 15.969 + ], + "2": [ + 55.0004, + 46.7289, + 15.9686 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "P7": { + "corners": { + "1": [ + 54.994, + 57.16830029449462, + 15.971 + ], + "2": [ + 54.99619999999999, + 57.16580029449462, + 15.9839 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Deck" + } + }, + "P8": { + "corners": { + "1": [ + 69.572, + 36.325, + 15.963 + ], + "2": [ + 69.6, + 36.3197, + 15.965 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "P9": { + "corners": { + "1": [ + 69.584, + 46.737, + 15.962 + ], + "2": [ + 69.6464, + 46.7379, + 15.9609 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Position" + } + }, + "TA1": { + "corners": { + "1": [ + 129.977, + 36.098, + 15.959 + ], + "2": [ + 129.9485, + 36.3464, + 15.9532 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Not", + "2": "Position" + } + }, + "TL1": { + "corners": { + "1": [ + 11.2464, + 36.3048, + 16.1996 + ], + "2": [ + 11.259, + 36.302, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TL10": { + "corners": { + "1": [ + 25.8297, + 15.4482, + 16.2324 + ], + "2": [ + 25.838, + 15.474, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TL11": { + "corners": { + "1": [ + 25.8394, + 25.8775, + 16.209 + ], + "2": [ + 25.838, + 25.888, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TL2": { + "corners": { + "1": [ + 11.2418, + 46.7271, + 16.2016 + ], + "2": [ + 11.259, + 46.716, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TL3": { + "corners": { + "1": [ + 11.2511, + 57.1587, + 16.2016 + ], + "2": [ + 11.259, + 57.13, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TL4": { + "corners": { + "1": [ + 25.8414, + 36.315, + 16.2141 + ], + "2": [ + 25.838, + 36.302, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TL5": { + "corners": { + "1": [ + 25.8609, + 46.7377, + 16.211 + ], + "2": [ + 25.838, + 46.716, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TL6": { + "corners": { + "1": [ + 25.8461, + 57.1603, + 16.2098 + ], + "2": [ + 25.838, + 57.13, + 16.219 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Position", + "2": "Deck" + } + }, + "TR1": { + "corners": { + "1": [ + 10.94730025939942, + 17.57920008850098, + 20.7014 + ], + "2": [ + 10.949500259399407, + 17.57670008850098, + 20.7016 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Deck" + } + }, + "TR2": { + "corners": { + "1": [ + 128.2010999909401, + 17.57920008850098, + 20.7014 + ], + "2": [ + 128.20329999094008, + 17.57670008850098, + 20.7016 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Deck" + } + }, + "W2": { + "corners": { + "1": [ + 142.26539992294312, + 56.92709994659424, + 22.2255 + ], + "2": [ + 142.26759992294313, + 56.92459994659424, + 22.2257 + ] + }, + "x_span": 3.175, + "y_span": 8.9992, + "framed": { + "1": "Deck", + "2": "Deck" + } + }, + "W3": { + "corners": { + "1": [ + 78.62710000000004, + 14.321300000000033, + 10.689400000000001 + ], + "2": [ + 78.62930000000003, + 14.318800000000035, + 10.839200000000002 + ] + }, + "x_span": 12.819, + "y_span": 8.59, + "framed": { + "1": "Deck", + "2": "Deck" + } + } + }, + "deck_layout": [ + { + "name": "TrashLeftBin_1", + "alp_type": "TrashLeftBin", + "column": 6, + "row": 12, + "positions": [ + "TR1" + ], + "x1": -7.5796997406005815 + }, + { + "name": "TipLoad1x1_1", + "alp_type": "TipLoad1x1", + "column": 6, + "row": 20, + "positions": [ + "TL1" + ], + "x1": 10.80570000190735 + }, + { + "name": "TipLoad1x1_2", + "alp_type": "TipLoad1x1", + "column": 6, + "row": 25, + "positions": [ + "TL2" + ], + "x1": 10.80110000190735 + }, + { + "name": "TipLoad1x1_3", + "alp_type": "TipLoad1x1", + "column": 6, + "row": 30, + "positions": [ + "TL3" + ], + "x1": 10.81040000190735 + }, + { + "name": "TipLoad1x1_10", + "alp_type": "TipLoad1x1", + "column": 13, + "row": 10, + "positions": [ + "TL10" + ], + "x1": 25.388600000000004 + }, + { + "name": "TipLoad1x1_11", + "alp_type": "TipLoad1x1", + "column": 13, + "row": 15, + "positions": [ + "TL11" + ], + "x1": 25.398300000000006 + }, + { + "name": "TipLoad1x1_6", + "alp_type": "TipLoad1x1", + "column": 13, + "row": 20, + "positions": [ + "TL4" + ], + "x1": 25.400300001907354 + }, + { + "name": "TipLoad1x1_5", + "alp_type": "TipLoad1x1", + "column": 13, + "row": 25, + "positions": [ + "TL5" + ], + "x1": 25.419800001907355 + }, + { + "name": "TipLoad1x1_4", + "alp_type": "TipLoad1x1", + "column": 13, + "row": 30, + "positions": [ + "TL6" + ], + "x1": 25.405000001907354 + }, + { + "name": "Static1x1_3", + "alp_type": "Static1x1", + "column": 20, + "row": 15, + "positions": [ + "P1" + ], + "x1": 39.97340000190736 + }, + { + "name": "Static1x1_25", + "alp_type": "Static1x1", + "column": 20, + "row": 20, + "positions": [ + "P2" + ], + "x1": 40.01430000000002 + }, + { + "name": "Static1x1_26", + "alp_type": "Static1x1", + "column": 20, + "row": 25, + "positions": [ + "P3" + ], + "x1": 40.02880000000002 + }, + { + "name": "Static1x1_27", + "alp_type": "Static1x1", + "column": 20, + "row": 30, + "positions": [ + "P4" + ], + "x1": 40.036200000000015 + }, + { + "name": "BioShake_1", + "alp_type": "BioShake", + "column": 21, + "row": 10, + "positions": [ + "BS1" + ], + "x1": 39.650700000000015 + }, + { + "name": "Static1x1_28", + "alp_type": "Static1x1", + "column": 27, + "row": 20, + "positions": [ + "P5" + ], + "x1": 54.56300000000002 + }, + { + "name": "Static1x1_6", + "alp_type": "Static1x1", + "column": 27, + "row": 25, + "positions": [ + "P6" + ], + "x1": 54.55550000190736 + }, + { + "name": "Static1x1_7", + "alp_type": "Static1x1", + "column": 27, + "row": 30, + "positions": [ + "P7" + ], + "x1": 54.55320000190736 + }, + { + "name": "ELx405DW_1", + "alp_type": "ELx405DW", + "column": 32, + "row": 11, + "positions": [ + "W3" + ], + "x1": 54.85710000000004 + }, + { + "name": "Static1x1_24", + "alp_type": "Static1x1", + "column": 34, + "row": 20, + "positions": [ + "P8" + ], + "x1": 69.13050000190735 + }, + { + "name": "Static1x1_9", + "alp_type": "Static1x1", + "column": 34, + "row": 25, + "positions": [ + "P9" + ], + "x1": 69.14280000190737 + }, + { + "name": "Static1x1_8", + "alp_type": "Static1x1", + "column": 34, + "row": 30, + "positions": [ + "P10" + ], + "x1": 69.13760000190736 + }, + { + "name": "Static1x1_29", + "alp_type": "Static1x1", + "column": 41, + "row": 20, + "positions": [ + "P11" + ], + "x1": 83.7167 + }, + { + "name": "Static1x1_10", + "alp_type": "Static1x1", + "column": 41, + "row": 25, + "positions": [ + "P12" + ], + "x1": 83.72100000190736 + }, + { + "name": "Static1x1_11", + "alp_type": "Static1x1", + "column": 41, + "row": 30, + "positions": [ + "P13" + ], + "x1": 83.71470000190736 + }, + { + "name": "Static1x1_14", + "alp_type": "Static1x1", + "column": 48, + "row": 15, + "positions": [ + "P14" + ], + "x1": 98.25030000190736 + }, + { + "name": "Static1x1_23", + "alp_type": "Static1x1", + "column": 48, + "row": 20, + "positions": [ + "P15" + ], + "x1": 98.27370000190736 + }, + { + "name": "Static1x1_13", + "alp_type": "Static1x1", + "column": 48, + "row": 25, + "positions": [ + "P16" + ], + "x1": 98.26750000190737 + }, + { + "name": "Static1x1_12", + "alp_type": "Static1x1", + "column": 48, + "row": 30, + "positions": [ + "P17" + ], + "x1": 98.28230000190736 + }, + { + "name": "ColdPlate_1", + "alp_type": "ColdPlate", + "column": 49, + "row": 10, + "positions": [ + "CP1" + ], + "x1": 98.11540000000001 + }, + { + "name": "Static1x1_16", + "alp_type": "Static1x1", + "column": 55, + "row": 10, + "positions": [ + "P18" + ], + "x1": 112.87250000190735 + }, + { + "name": "Static1x1_17", + "alp_type": "Static1x1", + "column": 55, + "row": 15, + "positions": [ + "P19" + ], + "x1": 112.87250000190735 + }, + { + "name": "Static1x1_18", + "alp_type": "Static1x1", + "column": 55, + "row": 20, + "positions": [ + "P20" + ], + "x1": 112.87250000190735 + }, + { + "name": "Static1x1_19", + "alp_type": "Static1x1", + "column": 55, + "row": 25, + "positions": [ + "P21" + ], + "x1": 112.87250000190735 + }, + { + "name": "Static1x1_20", + "alp_type": "Static1x1", + "column": 55, + "row": 30, + "positions": [ + "P22" + ], + "x1": 112.87250000190735 + }, + { + "name": "TrashRightBin_1", + "alp_type": "TrashRightBin", + "column": 62, + "row": 12, + "positions": [ + "TR2" + ], + "x1": 127.1010999909401 + }, + { + "name": "Static1x1_22", + "alp_type": "Static1x1", + "column": 62, + "row": 25, + "positions": [ + "P23" + ], + "x1": 127.45210000190735 + }, + { + "name": "Static1x1_21", + "alp_type": "Static1x1", + "column": 62, + "row": 30, + "positions": [ + "P24" + ], + "x1": 127.45210000190735 + }, + { + "name": "Tilting-ALP_1", + "alp_type": "Tilting-ALP", + "column": 63, + "row": 20, + "positions": [ + "TA1" + ], + "x1": 128.7869 + }, + { + "name": "WashStationSpan8_1", + "alp_type": "WashStationSpan8", + "column": 71, + "row": 30, + "positions": [ + "W2" + ], + "x1": 141.77009992294313 + } + ], + "modules": { + "multichannel": [ + { + "name": "X", + "device": 17, + "index": 1, + "configure": "0001000000807d02000100000000fc0300010000000088130000000000005a050003000300320000605b0300c8000000002d3101b80b0000000200000180ff800c0000b80b307532000000803801000a0000b80b000050000000000000fb1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000000000020000002c01000032000000", + "limits": { + "max_velocity": 163200, + "max_acceleration": 261120, + "max_jerk": 1280000, + "min_position": 0, + "max_position": 350720 + }, + "home_position": 35840, + "hysteresis": 0 + }, + { + "name": "Y", + "device": 17, + "index": 2, + "configure": "000100000000ee02000100000000b0040001000000001027000000000000e80300030003003200000071020064000000c0e1e400d007000000020000018000800c0000b80b307532000000803801000a0000b004000050000000000000fb1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000000000020000002c01000032000000", + "limits": { + "max_velocity": 192000, + "max_acceleration": 307200, + "max_jerk": 2560000, + "min_position": 0, + "max_position": 256000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "Z", + "device": 17, + "index": 3, + "configure": "0001000000005f00000100000000f401000100000000aa0a000018fcff0000000003000300140000a0860100e803000040420f00e80300008000000008800034080000800c0852d007000000000000010000f401000050000000000000fa1027000010270000c8000000000000003075000018fcffff800100000000e803881300000000000080ffffffff0a006400000000000000000000000000000000000000000000000000000000000000000000000000000050c3000000000000000000000000000000000000000000000000000000000000000000000fd007410000000000000002000000000000000000000000000000000000", + "limits": { + "max_velocity": 24320, + "max_acceleration": 128000, + "max_jerk": 698880, + "min_position": -256000, + "max_position": 0 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D", + "device": 17, + "index": 4, + "configure": "0001000000000003000100000000c01200000000000000000000000000801a06000300000050000050c300006400000000000000c8000000b80b00000d00ff480d0000f00a3075b4000000000000000a0000c012000040010000000000fb10270000401f00000000000000000000a8610000a8a80000000000000000f401dc0500000000000080ffffffff0a00102700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + "limits": { + "max_velocity": 196608, + "max_acceleration": 1228800, + "max_jerk": 0, + "min_position": 0, + "max_position": 400000 + }, + "home_position": 400, + "hysteresis": 0 + }, + { + "name": "GY", + "device": 17, + "index": 5, + "configure": "0001000000030f01000100000029830100010000009b1f0f000000000052060300030003f23d0000400d0300e80300000048e80194110000f30100000d0000b0040000dc05640018010000000000000a00298301006f4d000000000000fb10270000d6060a000000000000000000983a000000000000c60000000000f401a00f00000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + "limits": { + "max_velocity": 69379, + "max_acceleration": 99113, + "max_jerk": 991131, + "min_position": 0, + "max_position": 198226 + }, + "home_position": 47574, + "hysteresis": 0 + }, + { + "name": "GG", + "device": 17, + "index": 6, + "configure": "00010000001966010001000000f9f91b0001000000bac317010000000002f00200030003b735000050c30000e803000080841e00d0070000e10300000d0000bc020000dc056400fa000000e02e00000a00f9f91b001966010000000000fb4c1d000020030a000000000000000000a861000000000000290700000000f401d00700000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000d4feffff3705000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + "limits": { + "max_velocity": 91673, + "max_acceleration": 1833465, + "max_jerk": 18334650, + "min_position": 0, + "max_position": 192514 + }, + "home_position": 35753, + "hysteresis": 0 + }, + { + "name": "GZ", + "device": 17, + "index": 7, + "configure": "000a000000415d0000bc02000030b301000000000000000000d03effff00000000010003380600000000000000000000000000000000000000000000090000b80b0000dc05e8030000000000000000000030b30100161f000000000000fc1027000088130a000000000000000000c8af0000000000003e0158020000640000000000e803fa0000ffffffff0a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + "limits": { + "max_velocity": 23873, + "max_acceleration": 111408, + "max_jerk": 0, + "min_position": -49456, + "max_position": 0 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "GR", + "device": 17, + "index": 8, + "configure": "0001000000ebb8010001000000b9bd050001000000e5f61600c396c6ff000000000300039475000020a107006400000080841e00f40100004b0000000d0000bc020000dc05640004010000b03600000200b9bd050075dc000000000000fa4c1d000020030a000000000000000000983a000000000000f00200000000f401c40900000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + "limits": { + "max_velocity": 112875, + "max_acceleration": 376249, + "max_jerk": 1504997, + "min_position": -3762493, + "max_position": 0 + }, + "home_position": -141093, + "hysteresis": 0 + } + ], + "span8": [ + { + "name": "X", + "device": 17, + "index": 1, + "configure": "000100000000ee02000100000000b00400010000000010270000a6faff0000000003000300320000007102006400000080c3c901b80b0000000200000180ff800c0000b80b307532000000803801000a0000b80b000050000000000000fa1027000010270000000000000000000060ea000000000000800100000000f401a00f00000000000000ffffffff0a0064000000000000002f440000803f000000000000905f0100c94eaa3acea074395d1feb330000000000000000141b000014000000b1010000ea100000401f000000000000f4010000102700000f0000000000000000000000000000001800020000002c01000032000000", + "limits": { + "max_velocity": 192000, + "max_acceleration": 307200, + "max_jerk": 2560000, + "min_position": -350720, + "max_position": 0 + }, + "home_position": -2560, + "hysteresis": 0 + }, + { + "name": "Y1", + "device": 17, + "index": 2, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 23569, + "hysteresis": 0 + }, + { + "name": "Y2", + "device": 17, + "index": 3, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 27811, + "hysteresis": 0 + }, + { + "name": "Y3", + "device": 17, + "index": 4, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 32053, + "hysteresis": 0 + }, + { + "name": "Y4", + "device": 17, + "index": 5, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 36296, + "hysteresis": 0 + }, + { + "name": "Y5", + "device": 17, + "index": 6, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 40538, + "hysteresis": 0 + }, + { + "name": "Y6", + "device": 17, + "index": 7, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 44781, + "hysteresis": 0 + }, + { + "name": "Y7", + "device": 17, + "index": 8, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 49023, + "hysteresis": 0 + }, + { + "name": "Y8", + "device": 17, + "index": 9, + "configure": "ff170000004370010074000000f0f20200bb01000080e29e00000000004f3107000200034925000078000000640000005e01000066660000ee02000001c4098a020000d0070000", + "limits": { + "max_velocity": 94275, + "max_acceleration": 193264, + "max_jerk": 10412672, + "min_position": 0, + "max_position": 471375 + }, + "home_position": 53265, + "hysteresis": 0 + }, + { + "name": "Z1", + "device": 17, + "index": 10, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "Z2", + "device": 17, + "index": 11, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "Z3", + "device": 17, + "index": 12, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "Z4", + "device": 17, + "index": 13, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "Z5", + "device": 17, + "index": 14, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "Z6", + "device": 17, + "index": 15, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "Z7", + "device": 17, + "index": 16, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee020000ffc4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "Z8", + "device": 17, + "index": 17, + "configure": "ffe8010000a6ae0200890900006f71110061240000fcc4f531daa3f8ff6abc0000020043aa44000096000000780000005e010000ff7f0000ee02000001c4098a02000088130000", + "limits": { + "max_velocity": 175782, + "max_acceleration": 1143151, + "max_jerk": 838190332, + "min_position": -482342, + "max_position": 48234 + }, + "home_position": -4823, + "hysteresis": 0 + }, + { + "name": "D1", + "device": 18, + "index": 1, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D2", + "device": 18, + "index": 2, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D3", + "device": 18, + "index": 3, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D4", + "device": 18, + "index": 4, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D5", + "device": 18, + "index": 5, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D6", + "device": 18, + "index": 6, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D7", + "device": 18, + "index": 7, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "D8", + "device": 18, + "index": 8, + "configure": "c8000000a00f000014000000a05a0000c8000000302a00001027000050c3000000000000c05d00005800", + "limits": { + "max_velocity": 23200, + "max_acceleration": 50000, + "min_position": 0, + "max_position": 24000 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "GY", + "device": 17, + "index": 18, + "configure": "0001000000030f01000100000029830100010000009b1f0f000000000052060300030003f23d0000400d0300e80300000048e80194110000f30100000d0000b0040000dc05640018010000000000000a00298301006f4d000000000000fb10270000d6060a000000000000000000983a000000000000c60000000000f401a00f00000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000001800000000000000000000000000", + "limits": { + "max_velocity": 69379, + "max_acceleration": 99113, + "max_jerk": 991131, + "min_position": 0, + "max_position": 198226 + }, + "home_position": 47574, + "hysteresis": 0 + }, + { + "name": "GG", + "device": 17, + "index": 19, + "configure": "00010000001966010001000000f9f91b0001000000bac317010000000002f00200030003b735000050c30000e803000080841e00d0070000e10300000d0000bc020000dc056400fa000000e02e00000a00f9f91b001966010000000000fb4c1d000020030a000000000000000000a861000000000000290700000000f401d00700000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000d4feffff3705000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + "limits": { + "max_velocity": 91673, + "max_acceleration": 1833465, + "max_jerk": 18334650, + "min_position": 0, + "max_position": 192514 + }, + "home_position": 35753, + "hysteresis": 0 + }, + { + "name": "GZ", + "device": 17, + "index": 20, + "configure": "000a000000415d0000bc02000030b301000000000000000000d03effff00000000010003380600000000000000000000000000000000000000000000090000b80b0000dc05e8030000000000000000000030b30100161f000000000000fc1027000088130a000000000000000000c8af0000000000003e0158020000640000000000e803fa0000ffffffff0a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000", + "limits": { + "max_velocity": 23873, + "max_acceleration": 111408, + "max_jerk": 0, + "min_position": -49456, + "max_position": 0 + }, + "home_position": 0, + "hysteresis": 0 + }, + { + "name": "GR", + "device": 17, + "index": 21, + "configure": "0001000000ebb8010001000000b9bd050001000000e5f61600c396c6ff000000000300039475000020a107006400000080841e00f40100004b0000000d0000bc020000dc05640004010000b03600000200b9bd050075dc000000000000fa4c1d000020030a000000000000000000983a000000000000f00200000000f401c40900000000000000ffffffff0a00640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000dc0500000000000000000000000000000000", + "limits": { + "max_velocity": 112875, + "max_acceleration": 376249, + "max_jerk": 1504997, + "min_position": -3762493, + "max_position": 0 + }, + "home_position": -141093, + "hysteresis": 0 + } + ] + } +} diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index 6f5de098859..4aba0525520 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -26,3 +26,14 @@ Each layer calls only the one below it. side; that places it, not the USB serial number or the enumeration order. An unknown type or side, two boards claiming one place, or no chassis is refused. `driver/simulator.py` simulates the boards at the wire, answering identity reads from a recording of a real instrument's. + +**I2. The configuration is declared.** What the boards cannot report (motor tables, each axis's home +position and hysteresis, per pod the counts conversions, limits, geometry, calibration and settings) +is a `DeviceConfiguration`, read only from `declared_configuration_json` and written by +`save_configuration`. It describes what is fitted; it never decides what is present. + +**I3. Units: a Biomek-unit core behind one boundary.** The public API is in PyLabRobot's units (mm, +uL, s, degrees, the deck's frame). Planning, recipes and the counts layer work in Biomek's (cm, its +frame with Y towards the front, the per-mille speed field), which is what its logs and files are +compared in. A public method converts its arguments once, in `units.py`, and calls its `_`-prefixed +Biomek-unit twin; nothing is converted back and forth inside. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index 892bf89baeb..605bd779f99 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -1,13 +1,33 @@ """What the driver knows about an instrument: facts only (STAR design.md P3). -What the boards answer about themselves at setup: each module's identity, its boards with their -application images and versions, and the names of its inputs and outputs (`ModuleConfiguration`, -`BoardInfo`). +Two kinds: + +- **What the boards answer** about themselves at setup (`ModuleConfiguration`, `BoardInfo`). +- **What they cannot answer**, declared per instrument (`DeviceConfiguration`): + - the motor tables loaded into the boards after every power-up; + - per pod, the counts conversions, travel limits, geometry and settings that Biomek keeps on + the host side. + + One JSON file per instrument, made from the instrument's two Biomek sources and given to the + driver by path; no instrument's own ships with the driver (the generic one in `defaults/`, + anonymized, is for simulation): + - Biomek's instrument file (`.bif`): the pods, the deck's calibrated positions and its layout; + - the Master Controller's instrument record: the motor tables (with each instrument's measured + hysteresis) and the modules' serial numbers. + + `sources` records, per source, where it was read, when, and a fingerprint of exactly the values + taken from it. Loading refuses a file whose values no longer match its fingerprints (changed + after it was imported). """ -from dataclasses import dataclass, field -from typing import Dict, List, Optional +import copy +import hashlib +import json +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Dict, List, Literal, Optional, Tuple, Union +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import MotorTables from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import HardwareVersion, ModuleId # The firmware this driver has been run against (one instrument, 2026-10-24 through 2026-11-10): @@ -67,3 +87,425 @@ def untested_firmware(self) -> List[str]: ): found.append(f"board {b.index} application {b.application_version}") return found + + +# -- declared per instrument ------------------------------------------------------------------------- + +Side = Literal["left", "right"] + + +@dataclass(frozen=True) +class AxisConversion: + """How Biomek turns a value into counts for one axis or quantity: `counts = (value + offset) x + const`, rounded. `unit` is what `value` is in: Biomek's own units, `cm`, `deg` or `uL`. + + Read from the instrument file's `CmdGen/Conversion` (`Const`, `Offset`). Checked on + this instrument against positions it logged: + - the Multichannel's park GR, 90 deg, is -175,443 counts; + - its rest Z, 39.763 cm, is -256 counts; + - the Span-8 Z park, 39.1079 cm on Z1, is 9,029 counts. + """ + + const: float + offset: float + unit: str + + def to_counts(self, value: float) -> int: + return round((value + self.offset) * self.const) + + def to_value(self, counts: int) -> float: + return counts / self.const - self.offset + + +@dataclass(frozen=True) +class PodGeometry: + """A pod's dimensions as Biomek's collision model uses them, in cm. + + From the instrument file's per-device pod entry. That entry, not the pod type's defaults under + `HardwareSetupInfo/PodTypes`, is what reproduces the travel Biomek logged: + - BridgeXSpan is 39.0154 here, 12.7 in the type defaults; + - the bridges touch at left X + |right X| = 250,807 counts, and the most Biomek ever commanded + was 250,678. + + The optional fields are absent on a pod type that has no such part. + """ + + bridge_x_span: float + bridge_to_head_x_offset: float + mandrel1_x_offset: float + mandrel1_y_offset: float + mandrel_x_spacing: float + mandrel_y_spacing: float + avoidance_margin: float + pod_x_span: float + pod_y_span: float + gripper_x_offset: float + gripper_y_offset: float + gripper_z_offset: float + frame_safety_left: float + frame_safety_right: float + additional_safe_height: float + additional_safe_height_gripper: float + mandrels_x: Optional[int] = None + mandrels_y: Optional[int] = None + sub_mandrel_safe_height: Optional[float] = None + + +@dataclass(frozen=True) +class Obstacle: + """A fixed obstacle on the deck, as Biomek keeps it per pod (`Obstacles` in the instrument + file): a box in Biomek's frame (cm; Y towards the front, Z up from the deck surface), + a bound that is None open on that side, widened by `buffer`. Walls (the shields, the towers, the + light curtain) have no Z bounds; the pump bank is a floor up to `z2`; the I-beam a ceiling from + `z1`.""" + + name: str + buffer: float = 0.0 + x1: Optional[float] = None + x2: Optional[float] = None + y1: Optional[float] = None + y2: Optional[float] = None + z1: Optional[float] = None + z2: Optional[float] = None + + +# The settings the driver takes from a pod's entry in the instrument file, never assumed: a pod +# whose entry lacks one is refused (`PodConfiguration`). Every pod's; a gripper's; each pod type's. +POD_SETTINGS: Tuple[str, ...] = () +GRIPPER_SETTINGS: Tuple[str, ...] = () +TYPE_SETTINGS: Dict[str, Tuple[str, ...]] = { + "span8": ("ProbeSize",), + "multichannel": (), +} + + +def required_settings(module_type: str, gripper: bool) -> Tuple[str, ...]: + """The settings a pod of `module_type` (with a gripper or not) must have in its entry.""" + return ( + *POD_SETTINGS, + *(GRIPPER_SETTINGS if gripper else ()), + *TYPE_SETTINGS.get(module_type, ()), + ) + + +@dataclass +class PodConfiguration: + """One pod's facts the boards do not hold. + + - `conversion`: per axis or quantity, keyed by Biomek's own names (`X`, `Y`, `Z`, `D`, `GY`, + `GG`, `GZ`, `GR`; on a Span-8 also `S` for the span, `Z1`..`Z8`, `D1`..`D8`). + - `limits`: each axis's travel in those units, `(lowest, highest)`. + - `park`: Biomek's park location. + - `settings`: every other scalar Biomek keeps for the pod, and the Span-8's per-probe lists + (`LoadingOffsets`, `BrokenTips`) (tip loading, safe heights, speeds, + gripper squeeze) under its own name, for the features that will use them. + - `gripper_model`: the gripper's dimensions, as Biomek nests them; empty for a pod with no + gripper. + - `module_serial_number`: the serial number the pod's module reports, which ties these facts to + one module (`BiomekI7Driver.discover` checks it), from the Master Controller's record; None in + the generic configuration. + """ + + component: str + module_type: str + side: Side + conversion: Dict[str, AxisConversion] + limits: Dict[str, Tuple[float, float]] + geometry: PodGeometry + park: Dict[str, float] = field(default_factory=dict) + settings: Dict[str, Any] = field(default_factory=dict) + gripper_model: Dict[str, Any] = field(default_factory=dict) + obstacles: List[Obstacle] = field(default_factory=list) + source: str = "" + module_serial_number: Optional[str] = None + + def __post_init__(self) -> None: + missing = [ + k + for k in required_settings(self.module_type, bool(self.gripper_model)) + if k not in self.settings + ] + if missing: + raise ValueError( + f"{self.component}: the instrument file's entry for this pod has no {', '.join(missing)}; " + "the driver takes these from it and never assumes them" + ) + + def to_counts(self, axis: str, value: float) -> int: + """A value in Biomek's units for `axis` (see `conversion`) as counts. + + Raises: + ValueError: for an axis with no conversion. + """ + return self._conversion(axis).to_counts(value) + + def to_value(self, axis: str, counts: int) -> float: + """Counts on `axis` as a value in Biomek's units for it.""" + return self._conversion(axis).to_value(counts) + + def probe_spacing(self) -> float: + """A Span-8's probes' spacing at their narrowest (cm): the span axis's zero shared out between + the eight (`S` counts from that span, and each probe's Y counts from its narrowest place), or + `ProbeSize` without a span axis.""" + if "S" in self.conversion: + return -self.conversion["S"].offset / 7 + return float(self.settings["ProbeSize"]) + + def probe_y(self, probe: int, counts: int) -> float: + """Span-8 probe `probe`'s (1-8) Y in cm from its `Y` counts: the `Y` conversion is + probe 1's, and each next probe's counts start one narrowest spacing further on.""" + return self.to_value("Y", counts) + (probe - 1) * self.probe_spacing() + + def _conversion(self, axis: str) -> AxisConversion: + if axis not in self.conversion: + raise ValueError( + f"{self.component} has no conversion for {axis!r}; has {sorted(self.conversion)}" + ) + return self.conversion[axis] + + +@dataclass(frozen=True) +class DeckPosition: + """A deck position as Biomek calibrated it, in Biomek's frame (cm; Y towards the front, Z up + from the deck surface): a corner per pod, by Biomek's pod number, and the position's spans. + + Each pod moves to a position relative to its own corner: corner n is the one that shifts when + pod n's deck framing changes (`ShiftDeck` applied to `X`/`Y`/`Z`). `framed[n]` says + how corner n was obtained: `Position` (framed at this position) or `Deck` (from the deck's framing). + """ + + corners: Dict[int, Tuple[float, float, float]] + x_span: float + y_span: float + framed: Dict[int, str] = field(default_factory=dict) + + def corner(self, pod_number: int) -> Tuple[float, float, float]: + """Raises: + ValueError: for a pod with no corner here. + """ + if pod_number not in self.corners: + raise ValueError(f"no corner for pod {pod_number}; have {sorted(self.corners)}") + return self.corners[pod_number] + + +@dataclass(frozen=True) +class AlpPlacement: + """One ALP of a deck layout, as an instrument file places it (`Decks//Groups/`): its + name and Biomek type, the pin column of its left pins and the pin row of its front pins, the + names of its positions, and the X Biomek has its left edge at (`X1`, cm), which checks the + column.""" + + name: str + alp_type: str + column: int + row: int + positions: Tuple[str, ...] + x1: Optional[float] = None + + +SOURCES = ("instrument_file", "master_controller") + + +def source_parts(data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]: + """A serialized configuration's values split by the source each comes from (`SOURCES`).""" + pods = data.get("pods", {}) + return { + "instrument_file": { + "instrument_serial_number": data.get("instrument_serial_number"), + "pods": { + side: {k: v for k, v in pod.items() if k != "module_serial_number"} + for side, pod in pods.items() + }, + "deck_positions": data.get("deck_positions", {}), + "deck_layout": data.get("deck_layout", []), + }, + "master_controller": { + "chassis_serial_number": data.get("chassis_serial_number"), + "module_serial_numbers": { + side: pod.get("module_serial_number") for side, pod in pods.items() + }, + "modules": data.get("modules", {}), + }, + } + + +def fingerprint(value: Any) -> str: + """A digest of `value`'s canonical JSON: equal values, equal fingerprints.""" + text = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + return "sha256:" + hashlib.sha256(text.encode("ascii")).hexdigest() + + +@dataclass +class DeviceConfiguration: + """Everything declared about one instrument: its motor tables and its pods. + + `chassis_serial_number` and each pod's `module_serial_number` tie the file to the instrument it + describes: a live session refuses a file whose serial numbers are not the instrument's + (`BiomekI7Driver.discover`). `generic` marks a file that describes no instrument in particular + (the package's default, for simulation; `anonymized`): it carries no serial numbers and no + measured hysteresis, and a live session refuses it. `instrument_serial_number` is the instrument + file's own, for information only. `sources`: per source (`SOURCES`), its `fingerprint`, and for + an instrument's own file where (`path`, `kind`) and when (`read_at`) it was read.""" + + chassis_serial_number: Optional[str] + instrument_serial_number: Optional[str] + modules: Dict[str, Any] + pods: Dict[Side, PodConfiguration] + sources: Dict[str, Dict[str, str]] = field(default_factory=dict) + # The default deck's positions by Biomek's name (`P1`, `TL1`), as calibrated; empty if not + # imported. + deck_positions: Dict[str, DeckPosition] = field(default_factory=dict) + generic: bool = False + # The default deck's ALPs, as the instrument file places them; empty if not imported. + deck_layout: List[AlpPlacement] = field(default_factory=list) + + @property + def motor_tables(self) -> MotorTables: + return MotorTables.from_dict(self.modules) + + def pod(self, side: Side) -> PodConfiguration: + """Raises: + ValueError: if nothing is declared for that side. + """ + if side not in self.pods: + raise ValueError(f"no pod declared on the {side}; declared: {sorted(self.pods)}") + return self.pods[side] + + def fingerprints(self) -> Dict[str, str]: + """The fingerprint of the values taken from each source, as they are now.""" + parts = source_parts(self.to_dict()) + return {name: fingerprint(parts[name]) for name in SOURCES} + + def unrecorded_changes(self) -> List[str]: + """The sources whose values no longer match the fingerprints recorded at import: changed after + the file was made, by hand or otherwise.""" + now = self.fingerprints() + return [name for name in SOURCES if self.sources.get(name, {}).get("fingerprint") != now[name]] + + def anonymized(self) -> "DeviceConfiguration": + """This configuration as a generic Biomek i7: every serial number removed (any key naming one, + at any depth), the measured hysteresis zeroed, `generic` set, and the sources reduced to their + fingerprints (no path or date).""" + data = self.to_dict() + + def scrub(value: Any) -> Any: + if isinstance(value, dict): + return {k: None if "serial" in k.lower() else scrub(v) for k, v in value.items()} + if isinstance(value, list): + return [scrub(v) for v in value] + return value + + data = scrub(data) + for axes in data["modules"].values(): + for axis in axes: + axis["hysteresis"] = 0 + data["generic"] = True + data["sources"] = {} + generic = DeviceConfiguration.from_dict(data) + generic.sources = {name: {"fingerprint": f} for name, f in generic.fingerprints().items()} + return generic + + @classmethod + def load(cls, path: Union[str, Path]) -> "DeviceConfiguration": + """An instrument's declared configuration, from the file `save` wrote. + + Raises: + ValueError: if its values no longer match the fingerprints recorded at import: it was + changed afterwards. Import it again. + """ + with open(path, encoding="utf-8") as fh: + config = cls.from_dict(json.load(fh)) + changed = config.unrecorded_changes() + if changed: + raise ValueError( + f"{path}: the values from {' and '.join(changed)} are not the ones imported (changed " + "after import); import it again from the instrument's Biomek files" + ) + return config + + def save(self, path: Union[str, Path], indent: Optional[int] = 2) -> None: + """Write it as `load` reads it; `indent` as `json.dump`'s (None: one line).""" + Path(path).write_text(json.dumps(self.to_dict(), indent=indent) + "\n", encoding="utf-8") + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DeviceConfiguration": + pods: Dict[Side, PodConfiguration] = {} + for side, p in data.get("pods", {}).items(): + pods[side] = PodConfiguration( + component=p["component"], + module_type=p["module_type"], + side=side, + conversion={k: AxisConversion(**v) for k, v in p["conversion"].items()}, + limits={k: (v[0], v[1]) for k, v in p["limits"].items()}, + geometry=PodGeometry(**p["geometry"]), + park=dict(p.get("park", {})), + settings=dict(p.get("settings", {})), + gripper_model=dict(p.get("gripper_model", {})), + obstacles=[Obstacle(**o) for o in p.get("obstacles", [])], + source=p.get("source", ""), + module_serial_number=p.get("module_serial_number"), + ) + positions = { + name: DeckPosition( + corners={int(n): (c[0], c[1], c[2]) for n, c in p["corners"].items()}, + x_span=p["x_span"], + y_span=p["y_span"], + framed={int(n): v for n, v in p.get("framed", {}).items()}, + ) + for name, p in data.get("deck_positions", {}).items() + } + return cls( + chassis_serial_number=data.get("chassis_serial_number"), + instrument_serial_number=data.get("instrument_serial_number"), + modules=data["modules"], + pods=pods, + sources=copy.deepcopy(data.get("sources", {})), + deck_positions=positions, + generic=bool(data.get("generic", False)), + deck_layout=[ + AlpPlacement( + name=a["name"], + alp_type=a["alp_type"], + column=a["column"], + row=a["row"], + positions=tuple(a["positions"]), + x1=a.get("x1"), + ) + for a in data.get("deck_layout", []) + ], + ) + + def to_dict(self) -> Dict[str, Any]: + return { + "generic": self.generic, + "chassis_serial_number": self.chassis_serial_number, + "instrument_serial_number": self.instrument_serial_number, + "sources": self.sources, + "pods": { + side: { + "component": p.component, + "module_type": p.module_type, + "module_serial_number": p.module_serial_number, + "source": p.source, + "conversion": {k: asdict(c) for k, c in p.conversion.items()}, + "limits": {k: list(v) for k, v in p.limits.items()}, + "geometry": {k: v for k, v in asdict(p.geometry).items() if v is not None}, + "park": p.park, + "settings": p.settings, + "gripper_model": p.gripper_model, + "obstacles": [{k: v for k, v in asdict(o).items() if v is not None} for o in p.obstacles], + } + for side, p in self.pods.items() + }, + "deck_positions": { + name: { + "corners": {str(n): list(c) for n, c in p.corners.items()}, + "x_span": p.x_span, + "y_span": p.y_span, + "framed": {str(n): v for n, v in p.framed.items()}, + } + for name, p in self.deck_positions.items() + }, + "deck_layout": [{**asdict(a), "positions": list(a.positions)} for a in self.deck_layout], + "modules": self.modules, + } diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration_tests.py new file mode 100644 index 00000000000..d87feb86824 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration_tests.py @@ -0,0 +1,184 @@ +"""The declared configuration: how it converts, how it is kept, and how discovery checks it against +the boards. On the package's generic configuration, whose physical values are one instrument's.""" + +import asyncio +import dataclasses +import json +import os +import tempfile +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_configuration, + generic_driver, + sealed, +) + +MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master" + + +class DeclaredConfigurationTests(unittest.TestCase): + def setUp(self) -> None: + self.config = generic_configuration() + self.left, self.right = self.config.pod("left"), self.config.pod("right") + + def test_pods_as_the_instrument_file_has_them(self) -> None: + self.assertEqual((self.left.component, self.left.module_type), ("MC_1", "multichannel")) + self.assertEqual((self.right.component, self.right.module_type), ("SPAN8_2", "span8")) + self.assertEqual(self.left.geometry.bridge_x_span, 39.0154) + self.assertEqual(self.right.geometry.bridge_x_span, 25.7204) + self.assertAlmostEqual(self.left.conversion["X"].offset, -10.519) + self.assertAlmostEqual(self.right.conversion["X"].offset, -146.40669375) + self.assertEqual(self.left.settings["TipLoadForceLimitSlope"], 2150) + + def test_conversions_give_the_counts_biomek_logged(self) -> None: + # Targets Biomek's instrument file holds, and the counts its logs show it sent for them. + self.assertEqual(self.left.to_counts("GR", self.left.park["GR"]), -175443) # the park's GR + self.assertEqual(self.left.to_counts("D", 0.0), 43176) # the plunger's home + self.assertEqual(self.left.to_counts("Z", 39.763), -256) # the rest Z + self.assertEqual(self.right.to_counts("Z1", 39.107921235034354), 9029) # the Span-8 Z park + self.assertEqual(self.right.to_counts("D1", 1000.0), 24000) # a pump's full stroke + self.assertAlmostEqual(self.left.to_value("X", self.left.to_counts("X", 42.0)), 42.0, 3) + + def test_the_bridges_meet_where_biomek_stopped(self) -> None: + """The left bridge's right edge meets the right bridge's left edge at left X + |right X| = + 250,807 counts. Biomek never commanded more than 250,678 in 20 days of logs.""" + lg, rg = self.left.geometry, self.right.geometry + left_reach = -lg.bridge_to_head_x_offset - lg.mandrel1_x_offset + lg.bridge_x_span + right_reach = -rg.bridge_to_head_x_offset - rg.mandrel1_x_offset + lx, rx = self.left.conversion["X"], self.right.conversion["X"] + # Deck X of a pod at `c` counts is c / const - offset; the edges meet when + # (L - R) / 2560 = (-rx.offset + right_reach) - (-lx.offset + left_reach). + combined = ((-rx.offset + right_reach) - (-lx.offset + left_reach)) * lx.const + self.assertEqual(round(combined), 250807) + self.assertLess(250678, combined) + + def test_each_pod_works_from_its_own_corner_of_a_position(self) -> None: + """Heights Biomek logged (Details, 2026-10-20), less the moving pod's corner: the same at every + position, as the labware there is the same. The Multichannel (Pod1) approaching four plates to + dispense, and the Span-8 (Pod2) pressing onto tips in four boxes. Against the other pod's + corner they spread by up to 0.01 cm.""" + positions = self.config.deck_positions + mc = {"P6": 27.757, "P9": 27.750, "P12": 27.756, "P16": 27.760} + span8 = {"P14": 20.741, "P15": 20.744, "P21": 20.737, "P23": 20.727} + for pod, logged, height in ((1, mc, 11.788), (2, span8, 4.770)): + for name, z in logged.items(): + with self.subTest(pod=pod, position=name): + self.assertAlmostEqual(z - positions[name].corner(pod)[2], height, delta=0.0011) + self.assertEqual(positions["P6"].framed, {1: "Position", 2: "Position"}) + with self.assertRaises(ValueError): + positions["P6"].corner(3) + + def test_unknown_axis_and_side(self) -> None: + with self.assertRaises(ValueError): + self.left.to_counts("Z1", 1.0) + config = generic_configuration() + del config.pods["right"] + with self.assertRaisesRegex(ValueError, "no pod declared on the right"): + config.pod("right") + + +class KeepingTests(unittest.TestCase): + def setUp(self) -> None: + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.path = os.path.join(self.folder.name, "configuration.json") + + def test_save_and_load_round_trip(self) -> None: + config = generic_configuration() + config.save(self.path) + self.assertEqual(DeviceConfiguration.load(self.path).to_dict(), config.to_dict()) + with open(GENERIC_CONFIGURATION, encoding="utf-8") as fh: + self.assertEqual(json.load(fh), config.to_dict()) + + def test_a_file_changed_after_import_is_refused_at_load(self) -> None: + for change in ( + lambda data: data["pods"]["left"]["conversion"]["X"].update(const=1.0), # instrument file + lambda data: data["modules"]["span8"][0].update(hysteresis=7), # Master Controller record + ): + config = generic_configuration() + data = config.to_dict() + change(data) + with open(self.path, "w", encoding="utf-8") as fh: + json.dump(data, fh) + with self.assertRaisesRegex(ValueError, "not the ones imported"): + DeviceConfiguration.load(self.path) + + def test_anonymized_keeps_no_serial_numbers_and_no_measured_hysteresis(self) -> None: + config = generic_configuration() + config.generic = False + config.chassis_serial_number = "A" * 32 + config.instrument_serial_number = "B" * 11 + for pod in config.pods.values(): + pod.module_serial_number = "C" * 32 + config.modules["span8"][0]["hysteresis"] = 12 + config.sources = { + name: {"path": "C:/somewhere", "kind": "file", "read_at": "2026-01-01", "fingerprint": f} + for name, f in config.fingerprints().items() + } + generic = config.anonymized() + text = json.dumps(generic.to_dict()) + for serial in ("A" * 32, "B" * 11, "C" * 32): + self.assertNotIn(serial, text) + self.assertTrue(generic.generic) + self.assertEqual({a["hysteresis"] for axes in generic.modules.values() for a in axes}, {0}) + self.assertEqual({k for s in generic.sources.values() for k in s}, {"fingerprint"}) + self.assertEqual(generic.unrecorded_changes(), []) + self.assertEqual(generic.to_dict(), generic_configuration().to_dict()) + + +class DeclaredAgainstFoundTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + + async def discover_with(self, configuration: DeviceConfiguration) -> BiomekI7Driver: + driver = generic_driver(configuration=sealed(configuration)) + self.addAsyncCleanup(driver.stop) + await driver.discover() + return driver + + async def test_the_generic_instrument_matches(self) -> None: + driver = generic_driver() + self.addAsyncCleanup(driver.stop) + with self.assertNoLogs(MASTER_LOGGER, level="WARNING"): + await driver.discover() + assert driver.left_x_arm and driver.left_x_arm.declared + self.assertEqual(driver.left_x_arm.declared.component, "MC_1") + + async def test_pods_swapped_are_refused(self) -> None: + config = generic_configuration() + left, right = config.pods["left"], config.pods["right"] + config.pods = { + "left": dataclasses.replace(right, side="left"), + "right": dataclasses.replace(left, side="right"), + } + with self.assertRaisesRegex(ValueError, "span8 pod on the left"): + await self.discover_with(config) + + async def test_a_pod_declared_but_not_found_is_only_logged(self) -> None: + config = generic_configuration() + del config.pods["right"] + with self.assertLogs(MASTER_LOGGER, level="WARNING") as logs: + driver = await self.discover_with(config) + self.assertIn("right pod: declared nothing, found span8", "\n".join(logs.output)) + assert driver.right_x_arm is not None + self.assertIsNone(driver.right_x_arm.declared) + + async def test_another_instruments_configuration_is_not_checked_on_given_boards(self) -> None: + # Refused on the instrument's own boards (`serial_numbers_tests.py`); simulated ones are not + # tied to an instrument. + config = generic_configuration() + config.chassis_serial_number = "0" * 32 + driver = await self.discover_with(config) + self.assertEqual(driver.declared.chassis_serial_number, "0" * 32) + + def test_a_declared_configuration_is_required(self) -> None: + with self.assertRaisesRegex(ValueError, "no declared configuration"): + BiomekI7Driver(boards=[]) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index d23b667f1fa..c08056a6c9a 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -1,20 +1,28 @@ -"""One pod: an arm on the shared X rail, and its ACE module.""" +"""One pod: an arm on the shared X rail, its ACE module, and the axes that module drives.""" -from typing import Dict, Literal, Optional, Tuple +from typing import Dict, List, Literal, Optional, Tuple +from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard -from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + ModuleConfiguration, + PodConfiguration, +) from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, read_module, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, MotorTables # How Biomek numbers its pods. Pod1 is the left pod and Pod2 the right on the instrument this # driver was written against; whether that holds on every build is not established. POD_NUMBERS = {"left": 1, "right": 2} COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"} +# Biomek's "Safe Height" (`GlobalMinSafeHeight`) at or below this is unset (it stores -100000). +UNSET_SAFE_HEIGHT = -1000.0 + # The arm board's analog input carrying the interlocked motor supply ("+36V Interlock"). DRIVE_SUPPLY_INPUT = "+36V Interlock" @@ -25,14 +33,37 @@ class Pod: or channels and its gripper. `module_type` is what the board reports itself to be (Get Module ID): `multichannel` (a - 96-channel head) or `span8` (eight independent channels). + 96-channel head) or `span8` (eight independent channels). Its axes are the motor tables' for + that type; what else is known of the pod (conversions, travel limits, geometry, settings) is the + declared configuration's. """ - def __init__(self, board: AceBoard, side: Literal["left", "right"], module_type: str): + def __init__( + self, + board: AceBoard, + side: Literal["left", "right"], + module_type: str, + motor_tables: MotorTables, + declared: Optional[PodConfiguration] = None, + ): self.board = board self.side = side self.module_type = module_type + self.axes: List[Axis] = motor_tables.axes(module_type) self.configuration: Optional[ModuleConfiguration] = None + # What the instrument's declared configuration says about this pod: its conversions, travel + # limits and geometry. None when nothing is declared for this side. + self.declared = declared + # The height the channels rise to before traveling over the deck, mm of the channels' bottom + # above the deck: STAR's `default_minimum_traverse_height`. Seeded from Biomek's "Safe Height" + # (`GlobalMinSafeHeight`) when it is set; None, as on an instrument where it is not (-100000), + # means the top of travel less the park margin, which is what Biomek does with Safe Height set + # to the top. + self.default_minimum_traverse_height: Optional[float] = None + if declared is not None: + safe = declared.settings.get("GlobalMinSafeHeight") + if isinstance(safe, (int, float)) and safe > UNSET_SAFE_HEIGHT: + self.default_minimum_traverse_height = units.to_mm(float(safe)) @property def pod_number(self) -> int: @@ -47,6 +78,12 @@ def component(self) -> str: `MC_1`, `SPAN8_2`.""" return f"{COMPONENT_PREFIXES[self.module_type]}_{self.pod_number}" + def axis(self, name: str) -> Axis: + for axis in self.axes: + if axis.name == name: + return axis + raise ValueError(f"{self} has no axis {name!r}; it has {[a.name for a in self.axes]}") + async def discover(self) -> ModuleConfiguration: """Read what the pod's module says about itself. Moves nothing.""" self.configuration = await read_module(self.board) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index 21b0e1b98b8..75a257162e8 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -15,7 +15,10 @@ ACE_VENDOR_ID, AceBoard, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + DeviceConfiguration, + ModuleConfiguration, +) from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod from pylabrobot.io.usb import USB @@ -46,15 +49,44 @@ class BiomekI7Driver: def __init__( self, serial_numbers: Optional[Sequence[str]] = None, + declared_configuration_json: Optional[str] = None, boards: Optional[Sequence[AceBoard]] = None, ): """ Args: serial_numbers: the ACE boards' USB serial numbers. Defaults to every ACE board attached. + declared_configuration_json: path of the instrument's declared configuration (motor tables, + and per pod its conversions, limits, geometry and calibration), made from the instrument's + Biomek files. Required: the driver never falls back to another, the package's generic one + included. boards: boards to use instead of opening USB devices: a simulated instrument - (`simulator.replay_boards`). + (`simulator.replay_boards`). With them, the checks that tie the configuration to a real + instrument (`discover`) are not made. + + Raises: + ValueError: with no declared configuration, or one changed since it was imported + (`DeviceConfiguration.load`). """ + if declared_configuration_json is None: + raise ValueError( + "no declared configuration: pass `declared_configuration_json`, the instrument's own, made " + "from its Biomek files" + ) self._serial_numbers = list(serial_numbers) if serial_numbers is not None else None + self.declared_configuration_json = declared_configuration_json + self.declared = DeviceConfiguration.load(declared_configuration_json) + logger.info( + "declared configuration %s: chassis %s%s; %s", + declared_configuration_json, + self.declared.chassis_serial_number or "none", + " (generic)" if self.declared.generic else "", + "; ".join( + f"{name} {s.get('kind', '')} {s.get('path', '')} read {s.get('read_at', '?')} " + f"{s.get('fingerprint', '')[:19]}".replace(" ", " ") + for name, s in self.declared.sources.items() + ), + ) + self.motor_tables = self.declared.motor_tables self._given_boards = list(boards) if boards is not None else None self.boards: List[AceBoard] = [] self._connected = False @@ -72,6 +104,7 @@ async def setup(self) -> None: Raises: RuntimeError: if no chassis is found, or a board cannot be placed (`discover`). + ValueError: for a declared configuration that is not this instrument's (`discover`). """ logger.warning( "The Biomek i7 driver's discovery has run on one instrument; it is untested on other " @@ -114,10 +147,16 @@ async def discover(self) -> None: Each board says what it is: Get Module ID answers a module type (`protocol.MODULE_TYPES`: chassis, Multichannel, Span-8) and a side (left, right). That, not its USB serial number or order, places it. Seen on one instrument; an unknown type or side, two boards claiming one - place, or no chassis is refused. + place, no chassis, or a pod type other than the declared one is refused + (`_check_declared_against`). + + On the instrument (no `boards` given), the declared configuration must be this instrument's: + its chassis serial number and each declared pod's module serial number as the modules report + them, and not the generic one (`DeviceConfiguration.generic`). Otherwise it is refused. Raises: RuntimeError: for a board this driver cannot place, or no chassis. + ValueError: for a declared configuration that is not this instrument's. """ if not self._connected: await self._open() @@ -142,9 +181,20 @@ async def discover(self) -> None: types[place] = module.type if "chassis" not in places: raise RuntimeError("no chassis module among the ACE boards") + self._check_declared_against(types) self.chassis = Chassis(places["chassis"]) - self.left_x_arm = Pod(places["left"], "left", types["left"]) if "left" in places else None - self.right_x_arm = Pod(places["right"], "right", types["right"]) if "right" in places else None + self.left_x_arm = ( + Pod(places["left"], "left", types["left"], self.motor_tables, self.declared.pods.get("left")) + if "left" in places + else None + ) + self.right_x_arm = ( + Pod( + places["right"], "right", types["right"], self.motor_tables, self.declared.pods.get("right") + ) + if "right" in places + else None + ) modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())] for pod in self.arms: modules.append((str(pod), await pod.discover())) @@ -157,6 +207,17 @@ async def discover(self) -> None: logger.warning( "%s runs firmware this driver has not been run against: %s", name, "; ".join(untested) ) + if self._given_boards is not None: + return # simulated: no instrument to tie the configuration to + mismatches = self._serial_number_mismatches() + if mismatches: + raise ValueError( + "the declared configuration is not this instrument's: " + + "; ".join(mismatches) + + ". Its motor tables, conversions, geometry and calibration may not fit. Pass this " + "instrument's own `declared_configuration_json`, made from its Biomek files." + ) + logger.info("the declared configuration is this instrument's: serial numbers match the modules") async def request_serial_numbers(self) -> Dict[str, Optional[str]]: """The serial numbers the modules report: `chassis`, and `left` / `right` for each pod found. @@ -167,6 +228,54 @@ async def request_serial_numbers(self) -> Dict[str, Optional[str]]: """ return self._serial_numbers_found() + def _serial_number_mismatches(self) -> List[str]: + """How the declared configuration's serial numbers differ from the modules' (read at discovery), + each as a sentence; empty when they are this instrument's.""" + found = self._serial_numbers_found() + d = self.declared + problems = ( + ["it is the generic configuration, which describes no instrument"] if d.generic else [] + ) + if d.chassis_serial_number != found["chassis"]: + problems.append( + f"chassis {d.chassis_serial_number or 'not recorded'}, found {found['chassis']}" + ) + for side, pod in d.pods.items(): + if side in found and pod.module_serial_number != found[side]: + problems.append( + f"{side} pod module {pod.module_serial_number or 'not recorded'}, found {found[side]}" + ) + return problems + + def _check_declared_against(self, types: Dict[str, str]) -> None: + """Refuse an instrument whose pods are not the ones declared: their motor tables and geometry + would be another arm's. A pod declared but not found, or found but not declared, is only + logged (a single-pod instrument, or one being configured). + + Raises: + ValueError: if a pod is declared on a side where the boards report another arm type. + """ + for side in ("left", "right"): + declared = self.declared.pods.get(side) + found = types.get(side) + if declared is not None and found is not None and declared.module_type != found: + raise ValueError( + f"the declared configuration has a {declared.module_type} pod on the {side}, but the " + f"boards report a {found}; pass this instrument's own `declared_configuration_json`" + ) + if (declared is None) != (found is None): + logger.warning( + "%s pod: declared %s, found %s", + side, + declared.module_type if declared else "nothing", + found or "nothing", + ) + + def save_configuration(self, path: str) -> None: + """Write the declared configuration to `path`, as loaded, for `declared_configuration_json` to + read back. Nothing found at discovery is written into it.""" + self.declared.save(path) + def _serial_numbers_found(self) -> Dict[str, Optional[str]]: if self.chassis is None or self.chassis.configuration is None: raise RuntimeError("the modules have not been read; call `discover()` or `setup()` first") diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py new file mode 100644 index 00000000000..9287a7ad4b3 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py @@ -0,0 +1,150 @@ +"""Motor tables: the axes each arm's board drives, and the Configure parameters each one takes. + +A board does not keep its motor tables across a power cycle and cannot be asked for them, so the +host loads them at a cold start. Two more values per axis never reach a board: the Master +Controller keeps them in its own motor record and applies them itself. `home_position` is its +`phome`: where its Home All leaves X, the Multichannel's Y and the gripper axes (the Z channels, +the plunger and the Span-8 Y channels end elsewhere). +`hysteresis` is what it adds to an axis's targets; only the Span-8 Z channels have any, and it +differs channel by channel, measured per instrument. They are data, the Master Controller's own +record of the instrument (the `modules` section of its declared configuration, +`driver/configuration.py`), not something the driver works out. No instrument's tables ship with +the driver: they come with each instrument's declared configuration. + +Three layouts of Configure parameters were seen, each starting with the axis's limits: + + CiA 402 drive (X, Y, Z, D, grippers): 0x00 | 6 x u32 velocity/acceleration/jerk limits | + s32 min position | s32 max position | ... + SAGIAN drive (Span-8 Y1-Y8, Z1-Z8): 0xFF | the same limits | ... + syringe pump (Span-8 D1-D8): 8 x u32 velocity/acceleration limits | + s32 min position | s32 max position | u16 backlash +""" + +import struct +from dataclasses import dataclass +from typing import Any, Dict, List, Literal + +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import Device + +ModuleType = Literal["multichannel", "span8"] + + +@dataclass(frozen=True) +class AxisLimits: + """An axis's limits, as the Master Controller's motor record has them (`vmin` .. `jmax`). A + `max_jerk` of 0 means the axis takes no jerk (a trapezoidal profile: the Multichannel D and the + gripper Z, and the syringe pumps).""" + + min_position: int + max_position: int + max_velocity: int + max_acceleration: int + max_jerk: int + min_velocity: int = 1 + min_acceleration: int = 1 + min_jerk: int = 0 + + +@dataclass(frozen=True) +class PumpLimits: + """A syringe pump's own parameters (the Master Controller's ``), velocities in + counts/s and `backlash` in counts.""" + + min_start_velocity: int + max_start_velocity: int + min_cutoff_velocity: int + max_cutoff_velocity: int + backlash: int + + +@dataclass(frozen=True) +class Axis: + """One axis an arm's board drives, in the board's counts.""" + + name: str + device: int + index: int + configure: bytes + home_position: int = 0 + hysteresis: int = 0 + + @property + def is_pump(self) -> bool: + return self.device == Device.PUMP + + @property + def drive(self) -> Literal["cia402", "sagian", "pump"]: + """The kind of drive, read off the Configure layout. A CiA 402 drive reports a fault whenever + its motor power is off (interlock tripped); a SAGIAN drive or pump does not.""" + if self.is_pump: + return "pump" + return "sagian" if self.configure[0] == 0xFF else "cia402" + + @property + def limits(self) -> AxisLimits: + """The limits at the head of the axis's Configure parameters.""" + if self.is_pump: + values = struct.unpack_from("<8I2i", self.configure) + return AxisLimits(values[8], values[9], values[3], values[7], 0, values[2], values[6], 0) + values = struct.unpack_from("<6I2i", self.configure, 1) + return AxisLimits(values[6], values[7], values[1], values[3], values[5], *values[0:5:2]) + + @property + def pump_limits(self) -> PumpLimits: + """A syringe pump's start and cutoff velocity limits and backlash, from its Configure + parameters (min/max start velocity, min/max velocity, min/max cutoff velocity, min/max + acceleration, min/max position, backlash). + + Raises: + ValueError: if the axis is not a pump. + """ + if not self.is_pump: + raise ValueError(f"{self.name} is not a syringe pump") + values = struct.unpack_from("<8I2iH", self.configure) + return PumpLimits(values[0], values[1], values[4], values[5], values[10]) + + def check_position(self, position: int) -> None: + """Raise `ValueError` for a target outside the axis's position limits.""" + limits = self.limits + if not limits.min_position <= position <= limits.max_position: + raise ValueError( + f"{self.name} position {position} is outside ({limits.min_position}, {limits.max_position})" + ) + + +class MotorTables: + """The axes of every arm type of one instrument, in the order they are configured + (`DeviceConfiguration.motor_tables`).""" + + def __init__(self, modules: Dict[str, List[Axis]]): + self.modules = modules + + @classmethod + def from_dict(cls, modules: Dict[str, Any]) -> "MotorTables": + """From a declared configuration's `modules` section: per arm type, its axes.""" + return cls( + { + module: [ + Axis( + a["name"], + a["device"], + a["index"], + bytes.fromhex(a["configure"]), + a.get("home_position", 0), + a.get("hysteresis", 0), + ) + for a in axes + ] + for module, axes in modules.items() + } + ) + + def axes(self, module: str) -> List[Axis]: + """The axes of one arm type. + + Raises: + ValueError: if the recording has no tables for that type. + """ + if module not in self.modules: + raise ValueError(f"no motor tables recorded for a {module} arm; have {sorted(self.modules)}") + return self.modules[module] diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py new file mode 100644 index 00000000000..0e33306691d --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py @@ -0,0 +1,85 @@ +"""Motor tables: each axis's Configure parameters and the limits read from them, and the axes a pod +gets from them. On the package's generic configuration.""" + +import asyncio +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_configuration, + generic_driver, + sealed, +) + + +class MotorTableTests(unittest.TestCase): + def setUp(self) -> None: + self.config = generic_configuration() + self.tables = self.config.motor_tables + + def test_limits_from_configure_parameters_match_the_logged_ones(self) -> None: + """The limits parsed from each axis's Configure bytes are the ones the Master Controller + logged for it.""" + for module, axes in self.config.modules.items(): + for axis, logged in zip(self.tables.axes(module), axes): + for name, value in logged["limits"].items(): + self.assertEqual(getattr(axis.limits, name), value, (module, axis.name, name)) + + def test_axes_in_configure_order(self) -> None: + mc = [a.name for a in self.tables.axes("multichannel")] + self.assertEqual(mc[:3], ["X", "Y", "Z"]) + self.assertIn("D", mc) + span8 = [a.name for a in self.tables.axes("span8")] + for n in range(1, 9): + self.assertIn(f"Z{n}", span8) + self.assertIn(f"D{n}", span8) + self.assertEqual( + {a.drive for a in self.tables.axes("span8") if a.name.startswith("D")}, {"pump"} + ) + self.assertTrue(all(a.is_pump for a in self.tables.axes("span8") if a.name.startswith("D"))) + + def test_position_check(self) -> None: + x = self.tables.axes("multichannel")[0] + x.check_position(350720) + with self.assertRaisesRegex(ValueError, "outside"): + x.check_position(350721) + + def test_an_unknown_module_has_no_axes(self) -> None: + with self.assertRaisesRegex(ValueError, "no motor tables recorded for a robot arm"): + self.tables.axes("robot") + + +class PodAxesTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + + async def test_each_pod_gets_its_types_axes_and_declaration(self) -> None: + driver = generic_driver() + self.addAsyncCleanup(driver.stop) + await driver.discover() + left, right = driver.left_x_arm, driver.right_x_arm + assert left is not None and right is not None + self.assertEqual( + [a.name for a in left.axes], [a.name for a in driver.motor_tables.axes("multichannel")] + ) + self.assertIs(left.declared, driver.declared.pods["left"]) + self.assertEqual(right.axis("Z8").name, "Z8") + with self.assertRaisesRegex(ValueError, "has no axis 'Z8'"): + left.axis("Z8") + + async def test_the_traverse_default_follows_biomeks_safe_height(self) -> None: + driver = generic_driver() # "Safe Height" unset (-100000), as on the instrument it came from + self.addAsyncCleanup(driver.stop) + await driver.discover() + assert driver.left_x_arm is not None + self.assertIsNone(driver.left_x_arm.default_minimum_traverse_height) + config = generic_configuration() + config.pods["left"].settings["GlobalMinSafeHeight"] = 30.0 + driver = generic_driver(configuration=sealed(config)) + self.addAsyncCleanup(driver.stop) + await driver.discover() + assert driver.left_x_arm is not None + self.assertEqual(driver.left_x_arm.default_minimum_traverse_height, 300.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py new file mode 100644 index 00000000000..ea1af8ca706 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py @@ -0,0 +1,104 @@ +"""The check that ties a declared configuration to one instrument: its serial numbers, on the +instrument's own path. The replayed generic cold start answers placeholder serial numbers, as long +as real ones; a configuration copy naming them stands for that instrument's own. + +The instrument's path (no `boards` given) is taken with the replayed boards attached where `_open` +would open the USB devices, so `discover` runs exactly as on the instrument.""" + +import asyncio +import dataclasses +import unittest +from typing import Iterator, List +from unittest import mock + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + GENERIC_SERIAL_NUMBERS, + as_instrument, + configuration_file, + generic_boards, + generic_configuration, + generic_driver, + sealed, +) + +READS = {name for name in p.COMMANDS.values() if name.startswith(("Get ", "Read ", "List "))} + + +class InstrumentPathTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + self.boards: List[AceBoard] = [] + + def driver(self, configuration: DeviceConfiguration) -> BiomekI7Driver: + driver = BiomekI7Driver(declared_configuration_json=configuration_file(configuration)) + self.boards = boards = generic_boards() + + async def attach() -> None: + driver.boards = list(boards) + driver._connected = True + for board in driver.boards: + await board.setup() + + patcher = mock.patch.object(driver, "_open", attach) + patcher.start() + self.addCleanup(patcher.stop) + self.addAsyncCleanup(driver.stop) + return driver + + def requests(self) -> Iterator[str]: + for board in self.boards: + assert isinstance(board.io, ReplayAceUSB) + for message in board.io.requests: + yield p.COMMANDS[(message[0], message[4])] + + async def test_the_instruments_own_configuration_is_accepted(self) -> None: + driver = self.driver(as_instrument(generic_configuration())) + await driver.discover() + self.assertEqual(await driver.request_serial_numbers(), GENERIC_SERIAL_NUMBERS) + self.assertEqual(set(self.requests()) - READS, set()) + + async def test_another_instruments_serial_number_is_refused_before_anything_is_written( + self, + ) -> None: + config = as_instrument(generic_configuration()) + config.pods["right"] = dataclasses.replace(config.pods["right"], module_serial_number="X" * 32) + driver = self.driver(sealed(config)) + with self.assertRaisesRegex(ValueError, "right pod module X{32}, found SIMULATED009"): + await driver.setup() + self.assertEqual(set(self.requests()) - READS, set()) + + async def test_another_chassis_is_refused(self) -> None: + config = as_instrument(generic_configuration()) + config.chassis_serial_number = "Y" * 32 + with self.assertRaisesRegex(ValueError, "chassis Y{32}, found SIMULATED001"): + await self.driver(sealed(config)).discover() + + async def test_the_generic_configuration_is_refused_even_with_matching_numbers(self) -> None: + config = as_instrument(generic_configuration()) + config.generic = True + with self.assertRaisesRegex(ValueError, "generic"): + await self.driver(sealed(config)).discover() + + async def test_the_generic_configuration_is_refused(self) -> None: + with self.assertRaisesRegex(ValueError, "generic configuration.*chassis not recorded"): + await self.driver(generic_configuration()).discover() + + +class SimulationTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + + async def test_a_simulation_is_not_tied_to_an_instrument(self) -> None: + driver = generic_driver() # the generic configuration, no serial numbers + self.addAsyncCleanup(driver.stop) + await driver.discover() + self.assertTrue(driver.declared.generic) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py index c07366257d4..dc56c661fa4 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -1,17 +1,29 @@ """What the package's tests build their simulated Biomek i7 from: the generic one in `defaults/`, named explicitly (never through `$BIOMEK_I7_SIMULATOR_RECORDING`). Not a test module itself.""" +import atexit import copy import json +import shutil +import tempfile +from pathlib import Path from typing import Any, Dict, List, Optional, Sequence -from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_RECORDING +from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION, GENERIC_RECORDING from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB _GENERIC: Optional[Dict[str, Any]] = None +# The serial numbers the generic cold start answers: placeholders as long as real ones. +GENERIC_SERIAL_NUMBERS = { + "chassis": "SIMULATED00100000000000000000000", + "left": "SIMULATED00200000000000000000000", + "right": "SIMULATED00900000000000000000000", +} + def generic_recording() -> Dict[str, Any]: """The generic cold-start recording, a fresh copy a test may change: `boards` maps each module @@ -42,6 +54,50 @@ def generic_boards( ] -def generic_driver(boards: Optional[Sequence[AceBoard]] = None) -> BiomekI7Driver: - """A driver over `boards`, by default the generic instrument replayed.""" - return BiomekI7Driver(boards=generic_boards() if boards is None else boards) +def generic_configuration() -> DeviceConfiguration: + """The generic declared configuration, loaded afresh (a test may change its copy).""" + return DeviceConfiguration.load(GENERIC_CONFIGURATION) + + +def sealed(configuration: DeviceConfiguration) -> DeviceConfiguration: + """A test's changed copy, with its fingerprints recorded again so that it loads. Only tests do + this: the package makes a configuration from Biomek's files, never from another.""" + configuration.sources = { + name: {**configuration.sources.get(name, {}), "fingerprint": f} + for name, f in configuration.fingerprints().items() + } + return configuration + + +def as_instrument(configuration: DeviceConfiguration) -> DeviceConfiguration: + """`configuration` as the generic instrument's own: not generic, and naming the serial numbers + its cold start answers (sealed).""" + configuration.generic = False + configuration.chassis_serial_number = GENERIC_SERIAL_NUMBERS["chassis"] + for side, pod in configuration.pods.items(): + pod.module_serial_number = GENERIC_SERIAL_NUMBERS[side] + return sealed(configuration) + + +def configuration_file(configuration: DeviceConfiguration) -> str: + """`configuration` saved to a new temporary file, for `declared_configuration_json`; removed + when the tests end.""" + folder = Path(tempfile.mkdtemp(prefix="biomek_i7_test_")) + atexit.register(shutil.rmtree, folder, ignore_errors=True) + path = folder / "configuration.json" + configuration.save(path) + return str(path) + + +def generic_driver( + boards: Optional[Sequence[AceBoard]] = None, + configuration: Optional[DeviceConfiguration] = None, +) -> BiomekI7Driver: + """A driver over `boards` (by default the generic instrument replayed), declared by + `configuration` (by default the generic configuration's file).""" + return BiomekI7Driver( + declared_configuration_json=( + str(GENERIC_CONFIGURATION) if configuration is None else configuration_file(configuration) + ), + boards=generic_boards() if boards is None else boards, + ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/units.py b/pylabrobot/beckman_coulter/biomek_i7/units.py new file mode 100644 index 00000000000..0372726e99a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/units.py @@ -0,0 +1,222 @@ +"""Where PyLabRobot's units meet Biomek's: the one place they are converted. + +The public API takes and returns PyLabRobot's units: mm, mm/s, uL, uL/s, s, deg, in the deck's +frame (Y towards the back). Biomek works in its own, and so does the driver's planning (the +plans, the recipes): cm, its frame (X to the right, Y +towards the front), and a speed field, per mille of each axis's maximum velocity (1..1000). A +public method converts its arguments here once and hands them to its Biomek-unit counterpart; +nothing inside converts back and forth, so a run is the same request for request. + +Imports nothing of the package's, so every layer can use it. +""" + +import math +from dataclasses import dataclass +from typing import TYPE_CHECKING, Optional, Tuple + +from pylabrobot.resources.coordinate import Coordinate + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + +MM_PER_CM = 10.0 + +# The deck's frame against Biomek's, chosen rather than measured: its left edge 10 cm left of +# Biomek's X origin, clear of the left trash bin, and its front edge 70 cm in front of Biomek's Y +# origin, clear of the front row of ALPs. x = X + FRAME_X, y = FRAME_Y - Y (mm). +FRAME_X = 10.0 * MM_PER_CM +FRAME_Y = 70.0 * MM_PER_CM + +FULL_SPEED = 1000 +"""The speed field's top: the axis's maximum velocity.""" + + +# -- lengths --------------------------------------------------------------------------------------- + + +def cm(value: float) -> float: + """A length Biomek states in centimetres, in millimetres. + + Every dimension transcribed from a Biomek definition goes through here, written as Biomek states + it, so the literal in the code can be compared against its source as it stands. + """ + return value * MM_PER_CM + + +def to_cm(mm: float) -> float: + """A length in mm, in Biomek's cm.""" + return mm / MM_PER_CM + + +def optional_cm(mm: Optional[float]) -> Optional[float]: + """`to_cm`, passing None through (an argument left to its default).""" + return None if mm is None else to_cm(mm) + + +def to_mm(cm_value: float) -> float: + """A length in Biomek's cm, in mm.""" + return cm_value * MM_PER_CM + + +# -- the frame ------------------------------------------------------------------------------------- + + +def biomek_x(x: float) -> float: + """A deck x, in mm, as Biomek's X in mm.""" + return x - FRAME_X + + +def biomek_y(y: float) -> float: + """A deck y, in mm, as Biomek's Y in mm (the flip is its own inverse: `deck_y`).""" + return FRAME_Y - y + + +def deck_x(x: float) -> float: + """Biomek's X, in mm, as a deck x in mm.""" + return x + FRAME_X + + +deck_y = biomek_y +"""Biomek's Y, in mm, as a deck y in mm.""" + + +@dataclass(frozen=True) +class BiomekPoint: + """A point in Biomek's frame, cm: X to the right, Y towards the front, Z up from the deck.""" + + x: float + y: float + z: float + + +def to_biomek(point: Coordinate) -> BiomekPoint: + """A deck coordinate (mm, PyLabRobot's frame) in Biomek's frame (cm).""" + return BiomekPoint( + biomek_x(point.x) / MM_PER_CM, biomek_y(point.y) / MM_PER_CM, point.z / MM_PER_CM + ) + + +def offset_to_biomek(x: float, y: float, offset: Coordinate) -> Tuple[float, float]: + """Biomek X/Y (cm) moved by a PyLabRobot `offset` (mm): Biomek's Y runs to the front.""" + return x + offset.x / MM_PER_CM, y - offset.y / MM_PER_CM + + +# -- axis values ----------------------------------------------------------------------------------- + + +def _is_y(axis: str) -> bool: + return axis == "GY" or (axis[0] == "Y" and (len(axis) == 1 or axis[1:].isdigit())) + + +def axis_to_biomek(axis: str, value: float) -> float: + """An axis's target in PyLabRobot's units as Biomek's value for it: + - X, Y, Y1-Y8, GY: a deck x / y, mm, in Biomek's frame, cm; + - Z, Z1-Z8, GZ (mm above the deck), GG, S (mm): cm; + - GR: degrees counterclockwise from +X seen from above (PyLabRobot's), as Biomek's, which turn + the other way (its 90 points the fingers to the front); + - the pumps (D, D1-D8): uL, as Biomek's. + """ + if axis == "X": + return to_cm(biomek_x(value)) + if _is_y(axis): + return to_cm(biomek_y(value)) + if axis == "GR": + return -value + if axis[0] == "D": + return value + return to_cm(value) + + +def axis_from_biomek(axis: str, value: float) -> float: + """`axis_to_biomek`'s inverse.""" + if axis == "X": + return deck_x(to_mm(value)) + if _is_y(axis): + return deck_y(to_mm(value)) + if axis == "GR": + return -value + if axis[0] == "D": + return value + return to_mm(value) + + +def axis_to_counts(pod: "Pod", axis: str, value: float) -> int: + """An axis's target in PyLabRobot's units (`axis_to_biomek`) in counts.""" + declared = pod.declared + if declared is None: + raise RuntimeError(f"{pod} has no declared configuration") + return declared.to_counts(axis, axis_to_biomek(axis, value)) + + +def counts_to_axis(pod: "Pod", axis: str, counts: int) -> float: + """An axis's position in counts in PyLabRobot's units (`axis_from_biomek`).""" + declared = pod.declared + if declared is None: + raise RuntimeError(f"{pod} has no declared configuration") + return axis_from_biomek(axis, declared.to_value(axis, counts)) + + +# -- speeds ---------------------------------------------------------------------------------------- + + +def percent_to_field(percent: float, truncate: bool = False) -> int: + """A speed Biomek states in percent of an axis's maximum, as the speed field, 1..1000. Biomek + rounds, except where it truncates (`truncate`: the Span-8 prime's `D1SpeedLimit`, 80.17 %, is + the logged 801).""" + field = int(percent * 10) if truncate else round(percent * 10) + return max(1, min(FULL_SPEED, field)) + + +def _per_unit(pod: "Pod", axis: str) -> float: + """Counts per PyLabRobot unit of `axis` (per mm, deg or uL).""" + declared = pod.declared + if declared is None: + raise RuntimeError(f"{pod} has no declared configuration") + conversion = declared.conversion[axis] + return abs(conversion.const) / (MM_PER_CM if conversion.unit == "cm" else 1.0) + + +def max_rate(pod: "Pod", axis: str) -> float: + """`axis`'s maximum velocity in PyLabRobot units per second (mm/s, deg/s, uL/s).""" + return pod.axis(axis).limits.max_velocity / _per_unit(pod, axis) + + +def rate_to_field(pod: "Pod", axis: str, rate: float, clamp: bool = False) -> int: + """The speed field that moves `axis` at `rate` PyLabRobot units per second (mm/s, deg/s, uL/s): + its peak velocity; the move's acceleration scales with it, as the instrument has one speed per + move. + + Raises: + ValueError: for a rate not above 0, or above the axis's maximum (unless `clamp`, which takes + it to 1..1000). + """ + field = round(rate * _per_unit(pod, axis) / pod.axis(axis).limits.max_velocity * FULL_SPEED) + if clamp: + return max(1, min(FULL_SPEED, field)) + if not rate > 0 or field > FULL_SPEED: + raise ValueError( + f"{pod}: {axis} moves at up to {max_rate(pod, axis):.4g} per second, not {rate}" + ) + return max(1, field) + + +def field_to_rate(pod: "Pod", axis: str, field: int) -> float: + """The rate (PyLabRobot units per second) the speed field `field` moves `axis` at.""" + return field / FULL_SPEED * max_rate(pod, axis) + + +def fraction_to_field(fraction: float) -> int: + """A speed as a fraction of each axis's maximum, (0, 1], as the speed field: for a move of + several axes, whose maxima differ, so that no single rate describes it. + + Raises: + ValueError: outside (0, 1]. + """ + if not 0 < fraction <= 1 or math.isnan(fraction): + raise ValueError(f"a speed fraction is above 0 and at most 1, not {fraction}") + return max(1, round(fraction * FULL_SPEED)) + + +def cutoff_to_counts(pod: "Pod", axis: str, rate: float) -> int: + """A pump's cutoff velocity, uL/s, in counts/s.""" + return round(rate * _per_unit(pod, axis)) diff --git a/pylabrobot/beckman_coulter/biomek_i7/units_tests.py b/pylabrobot/beckman_coulter/biomek_i7/units_tests.py new file mode 100644 index 00000000000..d455ba8c112 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/units_tests.py @@ -0,0 +1,83 @@ +"""The one place PyLabRobot's units meet Biomek's (`units.py`): exact where Biomek's logs are.""" + +import asyncio +import unittest + +from pylabrobot.beckman_coulter.biomek_i7 import units as u +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_driver + + +class LengthAndFrameTests(unittest.TestCase): + def test_lengths_and_the_frame_round_trip(self) -> None: + for mm in (0.0, 1.0, 123.456, -7.5): + self.assertAlmostEqual(u.to_mm(u.to_cm(mm)), mm) + self.assertAlmostEqual(u.deck_x(u.biomek_x(mm)), mm) + self.assertAlmostEqual(u.deck_y(u.biomek_y(mm)), mm) + self.assertIsNone(u.optional_cm(None)) + point = u.to_biomek(Coordinate(100.0, 700.0, 25.0)) + self.assertEqual(point, u.BiomekPoint(0.0, 0.0, 2.5)) # the frame's origin, 2.5 cm up + + def test_an_offset_turns_with_biomeks_y(self) -> None: + self.assertEqual(u.offset_to_biomek(10.0, 20.0, Coordinate(5.0, 5.0, 0)), (10.5, 19.5)) + + def test_percent_is_biomeks_rounding_or_truncation(self) -> None: + self.assertEqual(u.percent_to_field(25), 250) + self.assertEqual(u.percent_to_field(80.1724), 802) + self.assertEqual(u.percent_to_field(80.1724, truncate=True), 801) # the logged prime speed + self.assertEqual(u.percent_to_field(0.01), 1) + self.assertEqual(u.percent_to_field(150), 1000) + + def test_a_fraction_is_refused_outside_zero_to_one(self) -> None: + self.assertEqual(u.fraction_to_field(1.0), 1000) + self.assertEqual(u.fraction_to_field(0.25), 250) + for bad in (0.0, 1.01, -0.5, float("nan")): + with self.assertRaises(ValueError): + u.fraction_to_field(bad) + + +class RateTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + self.driver = generic_driver() + await self.driver.discover() + self.addAsyncCleanup(self.driver.stop) + + def axes(self): + for pod in self.driver.arms: + assert pod.declared is not None + for axis in pod.axes: + if axis.name in pod.declared.conversion and (axis.name[0] in "ZD" or axis.name == "GZ"): + yield pod, axis.name + + def test_every_field_round_trips_on_every_z_and_pump(self) -> None: + checked = 0 + for pod, axis in self.axes(): + for field in range(1, 1001): + rate = u.field_to_rate(pod, axis, field) + self.assertEqual(u.rate_to_field(pod, axis, rate), field, f"{pod} {axis} {field}") + checked += 1 + self.assertGreaterEqual(checked, 20 * 1000) # Z, D, GZ; Z1-Z8, D1-D8, GZ + + def test_a_rate_above_the_maximum_is_refused_naming_it(self) -> None: + left = self.driver.left_x_arm + assert left is not None + top = u.max_rate(left, "Z") + self.assertAlmostEqual(top, 95.0) # mm/s: the Multichannel Z, 24320 counts/s at 2560 /cm + with self.assertRaisesRegex(ValueError, "Z moves at up to 95"): + u.rate_to_field(left, "Z", 125.0) # the STAR's default z speed + with self.assertRaises(ValueError): + u.rate_to_field(left, "Z", 0.0) + self.assertEqual(u.rate_to_field(left, "Z", 125.0, clamp=True), 1000) + + def test_the_flow_rate_is_the_old_plunger_arithmetic(self) -> None: + left = self.driver.left_x_arm + assert left is not None and left.declared is not None + for flow in (1.0, 50.0, 90.0, 100.0, 150.0, 400.0, 2000.0): + per_second = flow * left.declared.conversion["D"].const + old = max(1, min(1000, round(per_second / left.axis("D").limits.max_velocity * 1000))) + self.assertEqual(u.rate_to_field(left, "D", flow, clamp=True), old) + + +if __name__ == "__main__": + unittest.main() From 5bc4f1ff03e8cb1f6cd6ba5edd30b99c90e384d8 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:56:44 +0000 Subject: [PATCH 09/28] `Biomek i7`: sort imports for ruff I001 --- pylabrobot/beckman_coulter/biomek_i7/units_tests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/units_tests.py b/pylabrobot/beckman_coulter/biomek_i7/units_tests.py index d455ba8c112..9de769f9d66 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/units_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/units_tests.py @@ -4,8 +4,8 @@ import unittest from pylabrobot.beckman_coulter.biomek_i7 import units as u -from pylabrobot.resources.coordinate import Coordinate from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_driver +from pylabrobot.resources.coordinate import Coordinate class LengthAndFrameTests(unittest.TestCase): From f06ab9be711a5c27a52fb81c64229ba23e2e7694 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:08:03 -0800 Subject: [PATCH 10/28] `Biomek i7`: the declared configuration made from Biomek's files, and checked against them `DeviceConfiguration.from_biomek` makes an instrument's declared configuration from its two Biomek sources, read-only, standard library only (`biomek_files/`): - `variant_tree.py`: Biomek's variant-tree files (the instrument file, `.bif`); a file with any byte it cannot account for is refused, not misread. - `instrument_file.py`: the pods (conversions, travel, geometry, settings, gripper, obstacles), the default deck's calibrated positions and layout; Biomek's runtime state in the same file is left out. - `master_controller.py`: the Master Controller's instrument record (its database's `instrument` table, or a text file of it): motor tables, home positions, measured hysteresis, the modules' serial numbers. - `importer.py`: the two put together and checked against each other, each source's path, kind, read time and fingerprint recorded; `check_sources` reads them again and lists what changed. On the instrument, discovery now also refuses a configuration whose sources have changed since it was imported (a re-framed position, a re-measured hysteresis), and warns where they cannot be found. Reading the database closes its connection. Tests: the readers on files written in the test from the generic configuration (a small variant-tree writer and a record writer, `files_tests_support.py`): every value kind and class body, the refusals, the round trip from configuration to files and back, inconsistent sources, changes found by `check_sources`, and the discovery check on the instrument's own path. --- .../biomek_i7/biomek_files/__init__.py | 5 + .../biomek_files/files_tests_support.py | 237 ++++++++++ .../biomek_i7/biomek_files/importer.py | 174 ++++++++ .../biomek_i7/biomek_files/importer_tests.py | 105 +++++ .../biomek_i7/biomek_files/instrument_file.py | 222 ++++++++++ .../biomek_files/instrument_file_tests.py | 84 ++++ .../biomek_files/master_controller.py | 218 +++++++++ .../biomek_files/master_controller_tests.py | 115 +++++ .../biomek_i7/biomek_files/variant_tree.py | 415 ++++++++++++++++++ .../biomek_files/variant_tree_tests.py | 165 +++++++ .../beckman_coulter/biomek_i7/design.md | 9 + .../biomek_i7/driver/configuration.py | 87 +++- .../biomek_i7/driver/master.py | 59 ++- .../biomek_i7/driver/serial_numbers_tests.py | 42 +- 14 files changed, 1914 insertions(+), 23 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree_tests.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/__init__.py new file mode 100644 index 00000000000..77a9b218380 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/__init__.py @@ -0,0 +1,5 @@ +"""Reading an instrument's Biomek files into its declared configuration +(`DeviceConfiguration.from_biomek`): Biomek's instrument file (`instrument_file.py`, over the +variant-tree reader `variant_tree.py`) and the Master Controller's instrument record +(`master_controller.py`), put together and checked against each other by `importer.py`. Read-only +on every Biomek file, and standard library only.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py new file mode 100644 index 00000000000..37eb214676d --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py @@ -0,0 +1,237 @@ +"""Biomek files built for tests: a variant-tree writer, and an instrument file (`.bif`) and a +Master Controller instrument record written from a declared configuration, so the readers can be +checked against inputs made in the test. Not a test module itself, and not used by the driver.""" + +import struct +import zlib +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.instrument_file import ( + GEOMETRY, + LIST_SETTINGS, + NESTED_SETTINGS, + OPTIONAL_GEOMETRY, +) +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.variant_tree import ( + DICTIONARY, + HEADER_SIZE, + LIST, + Ref, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration + + +class Array: + """An array variant: its vartype and its elements, as `variant_tree` reads them.""" + + def __init__(self, vartype: int, values: List[Any], fmt: Optional[str] = None): + self.vartype, self.values, self.fmt = vartype, values, fmt + + +class Writer: + """Writes Python values as a variant stream: dicts as dictionaries, lists as lists, `Ref` as a + reference, `Array` as an array; None, bools, ints (int32), floats (double) and strings.""" + + def __init__(self) -> None: + self.objects = 0 + + @staticmethod + def string(text: str) -> bytes: + return struct.pack(" bytes: + if value is None: + return b"\x01" + if value is True: + return b"\x02" + if value is False: + return b"\x03" + if isinstance(value, int): + return b"\x06" + struct.pack(" bytes: + """An object definition's start: its index (the objects so far) and class id.""" + head = b"\x0e" + struct.pack(" bytes: + """A decompressed variant-tree stream: its size, then `root`.""" + body = Writer().variant(root) + return struct.pack(" bytes: + """A variant-tree file's bytes: the header, then the stream compressed.""" + return b"\x00" * HEADER_SIZE + zlib.compress(data) + + +# -- an instrument file ---------------------------------------------------------------------------- + +PODS = {"left": "Pod1", "right": "Pod2"} +POD_TYPES = {"multichannel": "MC", "span8": "SPAN8"} + +# Runtime state an instrument file carries in a pod entry beside its configuration, which the +# reader leaves out. +STATE = {"XPosition": 12.5, "Tip1": "none", "Z3Position": 4.0, "RT_Speed": 3, "LastTips": "T230"} + + +def _pod_entry(side: str, pod: Dict[str, Any]) -> Dict[str, Any]: + settings = dict(pod["settings"]) + entry: Dict[str, Any] = { + "Name": PODS[side], + "PodName": pod["component"], + "PodType": POD_TYPES[pod["module_type"]], + "LeftPod": side == "left", + "CmdGen": { + "Conversion": { + f"{axis}{part}": c[key] + for axis, c in pod["conversion"].items() + for part, key in (("Const", "const"), ("Offset", "offset")) + } + }, + "Min": {axis: low for axis, (low, _) in pod["limits"].items()}, + "Max": {axis: high for axis, (_, high) in pod["limits"].items()}, + "ParkLocation": pod["park"], + "GripperModel": pod["gripper_model"], + "Obstacles": [ + { + "Name": o["name"], + "Buffer": o["buffer"], + **{k.upper(): o[k] for k in ("x1", "x2", "y1", "y2", "z1", "z2") if k in o}, + } + for o in pod["obstacles"] + ], + } + for name, key in GEOMETRY.items(): + entry[key] = pod["geometry"][name] + for name, key in OPTIONAL_GEOMETRY.items(): + if name in pod["geometry"]: + entry[key] = pod["geometry"][name] + if "GripperSqueezeForce" in settings: + entry["Gripper"] = {"SqueezeForce": settings.pop("GripperSqueezeForce")} + for path in NESTED_SETTINGS: + value = settings.pop("/".join(path), None) + if value is not None: + node = entry + for key in path[:-1]: + node = node.setdefault(key, {}) + node[path[-1]] = value + for key, value in settings.items(): + entry[key] = list(value) if key in LIST_SETTINGS else value + entry.update(STATE) + return entry + + +def instrument_file_tree(configuration: DeviceConfiguration, deck: str = "Deck1") -> Dict[str, Any]: + """What an instrument file holds for `configuration`, as plain values for `Writer`: the two pod + entries (with runtime state beside them) and the default deck, with another deck that is not the + default.""" + data = configuration.to_dict() + pipettor: Dict[str, Any] = {"SerialNumber": data["instrument_serial_number"]} + for side, pod in data["pods"].items(): + pipettor[PODS[side]] = _pod_entry(side, pod) + positions = { + name: { + **{f"{a}{n}": p["corners"][n][i] for n in p["corners"] for i, a in enumerate("XYZ")}, + "XSpan": p["x_span"], + "YSpan": p["y_span"], + **{f"Framed{n}": how for n, how in p["framed"].items()}, + } + for name, p in data["deck_positions"].items() + } + groups = { + a["name"]: { + "Type": a["alp_type"], + "column": a["column"], + "row": a["row"], + "Positions": {name: {} for name in a["positions"]}, + **({"X1": a["x1"]} if a.get("x1") is not None else {}), + } + for a in data["deck_layout"] + } + return { + "Devices": {"Pipettor1": pipettor}, + "Decks": { + "Other": {"IsDefault": False, "Positions": {}, "Groups": {}}, + deck: {"IsDefault": True, "Positions": positions, "Groups": groups}, + }, + } + + +def write_instrument_file(configuration: DeviceConfiguration, path: Union[str, Path]) -> None: + Path(path).write_bytes(container(stream(instrument_file_tree(configuration)))) + + +# -- a Master Controller instrument record ------------------------------------------------------- + +PUMP_CONFIGURE = "<8I2iH" # the pump's Configure layout, which its record packs + + +def _motor(axis: Dict[str, Any]) -> str: + limits = axis["limits"] + configure = bytes.fromhex(axis["configure"]) + vmin = amin = 0 + if axis["device"] == 0x12: + (min_start, max_start, vmin, _vmax, min_cutoff, max_cutoff, amin, _amax, _pmin, _pmax, + backlash) = struct.unpack(PUMP_CONFIGURE, configure) # fmt: skip + config = f"#( {min_start} {max_start} {min_cutoff} {max_cutoff} {backlash})" + jmax = "#f" + else: + config = "#vu8(" + " ".join(str(b) for b in configure) + ")" + jmax = str(limits["max_jerk"]) + fields = [ + "", axis["name"], axis["device"], axis["index"], 0, limits["min_position"], + limits["max_position"], axis["home_position"], axis["hysteresis"], vmin, + limits["max_velocity"], amin, limits["max_acceleration"], 0, jmax, "#f", config, + ] # fmt: skip + return "#(" + " ".join(str(f) for f in fields) + ")" + + +def record_text(configuration: DeviceConfiguration) -> str: + """The Master Controller's instrument record for `configuration`, as its database holds it.""" + arms: List[str] = [] + for side, pod in configuration.pods.items(): + kind = {"multichannel": "mc", "span8": "span8"}[pod.module_type] + motors = " ".join(_motor(a) for a in configuration.modules[pod.module_type]) + arms.append(f'#( "{pod.module_serial_number}" {side} {kind} #({motors}))') + return f'#( "{configuration.chassis_serial_number}" ' + " ".join(arms) + ")" + + +def write_record(configuration: DeviceConfiguration, path: Union[str, Path]) -> None: + Path(path).write_text(record_text(configuration) + "\n", encoding="utf-8") + + +def write_database(texts: List[Tuple[str, str]], path: Union[str, Path]) -> None: + """A Master Controller database holding only its `instrument` table: (name, record) rows.""" + import sqlite3 + + db = sqlite3.connect(str(path)) + try: + with db: + db.execute("CREATE TABLE instrument (name TEXT, definition TEXT)") + db.executemany("INSERT INTO instrument VALUES (?, ?)", texts) + finally: + db.close() diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer.py new file mode 100644 index 00000000000..acc5c65a03b --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer.py @@ -0,0 +1,174 @@ +"""Make an instrument's declared configuration from its Biomek files, and check it against them. + +`import_configuration` is the one way a declared configuration is made +(`DeviceConfiguration.from_biomek`): +1. the instrument file gives the pods, the deck's positions and its layout + (`instrument_file.read_instrument_file`); +2. the Master Controller's instrument record gives the motor tables and the modules' serial + numbers (`master_controller.read_master_controller`); +3. the two must describe one instrument: an arm on the same sides in both, each pod's arm type in + the record, and every travel window the instrument file gives inside the motor's own limits; +4. `sources` records each source's path, kind, read time and the fingerprint of the values taken + from it. + +`check_sources` reads the recorded sources again and lists what changed since. +""" + +import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.instrument_file import read_instrument_file +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.master_controller import ( + read_master_controller, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + SOURCES, + DeviceConfiguration, + SourcesCheck, + differences, + fingerprint, + source_parts, +) + + +def _inconsistencies( + instrument_file: Dict[str, Any], master_controller: Dict[str, Any] +) -> List[str]: + """How the two sources disagree about the instrument, one sentence each.""" + problems = [] + serials = master_controller["module_serial_numbers"] + for side in sorted(set(instrument_file["pods"]) | set(serials)): + pod = instrument_file["pods"].get(side) + if pod is None or side not in serials: + problems.append( + f"the {side} arm is in the {'Master Controller record' if pod is None else 'instrument file'}" + " only" + ) + continue + if pod["module_type"] not in master_controller["modules"]: + problems.append(f"the {side} pod is a {pod['module_type']}; the record has no such arm") + continue + axes = {a["name"]: a for a in master_controller["modules"][pod["module_type"]]} + for axis, (low, high) in pod["limits"].items(): + conversion = pod["conversion"].get(axis) + if conversion is None or axis not in axes: + continue + ends = sorted(round((v + conversion["offset"]) * conversion["const"]) for v in (low, high)) + limits = axes[axis]["limits"] + if ends[0] < limits["min_position"] or ends[1] > limits["max_position"]: + problems.append( + f"the {side} pod's {axis} travel, counts {ends}, is outside the motor's " + f"[{limits['min_position']}, {limits['max_position']}]" + ) + return problems + + +def _now() -> str: + return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds") + + +def import_configuration( + bif: Union[str, Path], + master_controller_db: Optional[Union[str, Path]] = None, + master_controller_record: Optional[Union[str, Path]] = None, + chassis_serial_number: Optional[str] = None, +) -> DeviceConfiguration: + """`DeviceConfiguration.from_biomek`. + + Raises: + ValueError: for files that do not describe one consistent instrument. + """ + instrument_file = read_instrument_file(bif) + master_controller = read_master_controller( + master_controller_db=master_controller_db, + master_controller_record=master_controller_record, + chassis_serial_number=chassis_serial_number, + ) + problems = _inconsistencies(instrument_file, master_controller) + if problems: + raise ValueError( + "the instrument file and the Master Controller's record do not describe one instrument: " + + "; ".join(problems) + ) + pods = { + side: {**pod, "module_serial_number": master_controller["module_serial_numbers"][side]} + for side, pod in instrument_file["pods"].items() + } + config = DeviceConfiguration.from_dict({ + "generic": False, + "chassis_serial_number": master_controller["chassis_serial_number"], + "instrument_serial_number": instrument_file["instrument_serial_number"], + "pods": pods, + "deck_positions": instrument_file["deck_positions"], + "deck_layout": instrument_file["deck_layout"], + "modules": master_controller["modules"], + }) # fmt: skip + fingerprints = config.fingerprints() + read_at = _now() + config.sources = { + "instrument_file": { + "kind": "bif", + "path": str(Path(bif).resolve()), + "read_at": read_at, + "fingerprint": fingerprints["instrument_file"], + }, + "master_controller": { + "kind": "database" if master_controller_db is not None else "record", + "path": str(Path(master_controller_db or master_controller_record).resolve()), # type: ignore[arg-type] + "read_at": read_at, + "fingerprint": fingerprints["master_controller"], + }, + } + return config + + +def _read_again(config: DeviceConfiguration, name: str, path: Path) -> Dict[str, Any]: + """The serialized configuration with the values from source `name` read again from `path`.""" + data = config.to_dict() + if name == "instrument_file": + fresh = read_instrument_file(path) + data["instrument_serial_number"] = fresh["instrument_serial_number"] + data["deck_positions"] = fresh["deck_positions"] + data["deck_layout"] = fresh["deck_layout"] + data["pods"] = { + side: {**pod, "module_serial_number": data["pods"].get(side, {}).get("module_serial_number")} + for side, pod in fresh["pods"].items() + } + else: + kind = config.sources[name].get("kind") + fresh = read_master_controller( + master_controller_db=path if kind == "database" else None, + master_controller_record=path if kind == "record" else None, + chassis_serial_number=config.chassis_serial_number, + ) + data["chassis_serial_number"] = fresh["chassis_serial_number"] + data["modules"] = fresh["modules"] + for side, pod in data["pods"].items(): + pod["module_serial_number"] = fresh["module_serial_numbers"].get(side) + # Through the dataclasses, so both sides are serialized the same way. + return DeviceConfiguration.from_dict(data).to_dict() + + +def check_sources(config: DeviceConfiguration) -> SourcesCheck: + """`DeviceConfiguration.check_sources`. + + Raises: + ValueError: for a source that is there but no longer reads as one (the reader's own error). + """ + changed: List[str] = [] + unavailable: List[str] = [] + for name in SOURCES: + source = config.sources.get(name, {}) + if "path" not in source: + unavailable.append(f"{name}: no path recorded") + continue + path = Path(source["path"]) + if not path.exists(): + unavailable.append(f"{name}: {path} not found") + continue + fresh = source_parts(_read_again(config, name, path))[name] + if fingerprint(fresh) != source["fingerprint"]: + declared = source_parts(config.to_dict())[name] + changed += [f"{name}: {line}" for line in differences(declared, fresh)] + return SourcesCheck(changed=changed, unavailable=unavailable) diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer_tests.py new file mode 100644 index 00000000000..bd69ce15b6d --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/importer_tests.py @@ -0,0 +1,105 @@ +"""`DeviceConfiguration.from_biomek` end to end, on an instrument file and a Master Controller record +written in the test, and `check_sources` finding what changed in them since.""" + +import dataclasses +import tempfile +import unittest +from pathlib import Path + +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import ( + write_instrument_file, + write_record, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + DeviceConfiguration, + differences, +) +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + as_instrument, + generic_configuration, +) + + +def instrument() -> DeviceConfiguration: + """The generic configuration as one instrument's: serial numbers, a measured hysteresis.""" + config = as_instrument(generic_configuration()) + config.instrument_serial_number = "TEST0000001" + for side, pod in config.pods.items(): + pod.settings["HeadSerialNumber"] = f"HEAD-{side}" + next(a for a in config.modules["span8"] if a["name"] == "Z5")["hysteresis"] = 9 + return config + + +class ImportTests(unittest.TestCase): + def setUp(self) -> None: + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.bif = Path(folder.name) / "Biomek_i7.bif" + self.record = Path(folder.name) / "record.txt" + self.config = instrument() + write_instrument_file(self.config, self.bif) + write_record(self.config, self.record) + + def imported(self) -> DeviceConfiguration: + return DeviceConfiguration.from_biomek(self.bif, master_controller_record=self.record) + + def test_importing_gives_the_configuration_the_files_were_written_from(self) -> None: + imported = self.imported() + expected, got = self.config.to_dict(), imported.to_dict() + expected.pop("sources") + sources = got.pop("sources") + self.assertEqual(differences(expected, got), []) + self.assertEqual(sources["instrument_file"]["kind"], "bif") + self.assertEqual(sources["master_controller"]["kind"], "record") + self.assertEqual(Path(sources["instrument_file"]["path"]), self.bif.resolve()) + self.assertEqual(imported.unrecorded_changes(), []) + path = self.bif.parent / "configuration.json" + imported.save(path) + self.assertEqual(DeviceConfiguration.load(path).to_dict(), imported.to_dict()) + + def test_a_travel_window_outside_its_motors_limits_is_refused(self) -> None: + config = instrument() + low, high = config.pods["left"].limits["X"] + config.pods["left"].limits["X"] = (low, high + 1000.0) + write_instrument_file(config, self.bif) + with self.assertRaisesRegex(ValueError, "left pod's X travel.*outside the motor's"): + self.imported() + + def test_unchanged_sources_check_clean(self) -> None: + check = self.imported().check_sources() + self.assertEqual((check.changed, check.unavailable), ([], [])) + + def test_a_re_measured_hysteresis_is_found(self) -> None: + imported = self.imported() + remeasured = instrument() + next(a for a in remeasured.modules["span8"] if a["name"] == "Z5")["hysteresis"] = 10 + write_record(remeasured, self.record) + changed = imported.check_sources().changed + self.assertEqual(len(changed), 1) + self.assertRegex(changed[0], r"^master_controller: modules/span8\[\d+\]/hysteresis: 9 -> 10$") + + def test_a_re_framed_position_is_found(self) -> None: + imported = self.imported() + reframed = instrument() + position = reframed.deck_positions["P6"] + corners = dict(position.corners) + corners[1] = (corners[1][0] + 0.05, corners[1][1], corners[1][2]) + reframed.deck_positions["P6"] = dataclasses.replace(position, corners=corners) + write_instrument_file(reframed, self.bif) + changed = imported.check_sources().changed + self.assertEqual(len(changed), 1) + self.assertTrue(changed[0].startswith("instrument_file: deck_positions/P6/corners/1[0]")) + + def test_sources_not_found_are_unavailable(self) -> None: + imported = self.imported() + self.record.unlink() + check = imported.check_sources() + self.assertEqual(check.changed, []) + self.assertEqual(len(check.unavailable), 1) + self.assertIn("master_controller", check.unavailable[0]) + check = generic_configuration().check_sources() # fingerprints only: no paths + self.assertEqual(len(check.unavailable), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py new file mode 100644 index 00000000000..dc11ff06384 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py @@ -0,0 +1,222 @@ +"""What a declared configuration takes from Biomek's instrument file (`.bif`). + +From the live pod entries `Devices/Pipettor1/Pod1` and `Pod2`, per pod: +- the counts conversions, travel limits and park location; +- the geometry (the collision model's dimensions); +- every other scalar setting, and the few kept as a dictionary (`NESTED_SETTINGS`); +- the gripper model; +- the deck obstacles Biomek keeps per pod (boxes, an absent bound open); + +and from the default deck, its positions with a corner per pod, and its ALPs. + +The per-device entries are used, not the pod-type defaults under `HardwareSetupInfo/PodTypes`: +they are what reproduces Biomek's logged travel (see `PodGeometry`). Runtime state the file also +carries (positions, tips, gripped labware, `RT_*`) is left out: Biomek rewrites it during ordinary +runs, and it is not configuration. +""" + +from pathlib import Path +from typing import Any, Dict, List, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.variant_tree import Tree, parse_file, plain + +MODULE_TYPES = {"MC": "multichannel", "SPAN8": "span8"} + +# Geometry fields (driver `PodGeometry`) and the pod entry's keys they come from. +GEOMETRY = { + "bridge_x_span": "BridgeXSpan", + "bridge_to_head_x_offset": "BridgeToHeadXOffset", + "mandrel1_x_offset": "Mandrel1XOffset", + "mandrel1_y_offset": "Mandrel1YOffset", + "mandrel_x_spacing": "MandrelXSpacing", + "mandrel_y_spacing": "MandrelYSpacing", + "avoidance_margin": "AvoidanceMargin", + "pod_x_span": "PodXSpan", + "pod_y_span": "PodYSpan", + "gripper_x_offset": "GripperXOffset", + "gripper_y_offset": "GripperYOffset", + "gripper_z_offset": "GripperZOffset", + "frame_safety_left": "Frame_Safety_L", + "frame_safety_right": "Frame_Safety_R", + "additional_safe_height": "AdditionalSafeHeight", + "additional_safe_height_gripper": "AdditionalSafeHeightGripper", +} +OPTIONAL_GEOMETRY = { + "mandrels_x": "MandrelsX", + "mandrels_y": "MandrelsY", + "sub_mandrel_safe_height": "SubMandrelSafeHeight", +} + +# Runtime state Biomek writes back into the file: where things are and what is held. +STATE_KEYS = { + "CurrentSpeed", "DPosition", "GGPosition", "GRPosition", "GYPosition", "GZPosition", + "GripSide", "GrippedLabware", "GrippedLabwareOffsets", "HasGripperProbes", "LastOperation", + "LastTips", "LastValidation", "PositionSaved", "SPosition", "Squeeze", "SqueezeForce", "Tips", + "TipsFrom", "TipsFromLW", "TipsSelected", "XPosition", "YPosition", "ZPosition", +} # fmt: skip + +# Per-probe lists of numbers, kept as settings like the scalars (the seat per probe). +LIST_SETTINGS = {"LoadingOffsets", "BrokenTips"} + +# Settings Biomek keeps as a dictionary in the pod entry, taken as that dictionary under the key's +# path: a Multichannel's mandrel A1 from the pod (`Head/PodToMandrel1`: X, Y, Z in cm, Z the bare +# mandrels' end), a Span-8 probe's tip hub (`DefaultTipHubInfo`: Length, MinRadius, MaxRadius), a +# Span-8's tubing bundle (`LLSWireModel`: where it leaves the probes, its anchor, its lowest point). +NESTED_SETTINGS = (("Head", "PodToMandrel1"), ("DefaultTipHubInfo",), ("LLSWireModel",)) + + +def is_state(key: str) -> bool: + """Whether a pod entry's key is runtime state rather than configuration.""" + if key.startswith("RT_") or key in STATE_KEYS: + return True + # Per channel or pump: Tip1..Tip8, Z1Position.., D1Position.. + return (key.startswith("Tip") and key[3:].isdigit()) or ( + key.endswith("Position") and key[0] in "ZD" and key[1:-8].isdigit() + ) + + +def _plain_dict(tree: Tree, obj: Any) -> Dict[str, Any]: + """A dictionary as plain JSON values, without the reader's bookkeeping keys.""" + + def clean(v: Any) -> Any: + if isinstance(v, dict): + return {k: clean(x) for k, x in v.items() if not k.startswith("$")} + if isinstance(v, list): + return [clean(x) for x in v] + return v + + return clean(plain(obj, tree.objects, inline=False)) # type: ignore[no-any-return] + + +def _unit_of(axis: str) -> str: + if axis == "GR": + return "deg" + if axis[0] == "D": + return "uL" + return "cm" + + +def _pod(tree: Tree, pod: Any) -> Tuple[str, Dict[str, Any]]: + get = tree.deref + e = {k: get(v) for k, v in pod.entries.items()} + conversion_entries = get(get(e["CmdGen"]).entries["Conversion"]).entries + conversion = {} + for key, value in conversion_entries.items(): + if key.endswith("Const"): + axis = key[: -len("Const")] + conversion[axis] = { + "const": value, + "offset": conversion_entries[f"{axis}Offset"], + "unit": _unit_of(axis), + } + low, high = get(e["Min"]).entries, get(e["Max"]).entries + limits = {k: [low[k], high[k]] for k in high if k in low} + geometry: Dict[str, Any] = {name: e[key] for name, key in GEOMETRY.items()} + geometry.update({name: e[key] for name, key in OPTIONAL_GEOMETRY.items() if key in e}) + used = set(GEOMETRY.values()) | set(OPTIONAL_GEOMETRY.values()) + settings: Dict[str, Any] = { + k: v + for k, v in e.items() + if k not in used and not is_state(k) and isinstance(v, (bool, int, float, str)) + } + for k, v in e.items(): + items = getattr(v, "items", None) + if k not in used and not is_state(k) and k in LIST_SETTINGS and isinstance(items, list): + settings[k] = [get(x) for x in items] + for path in NESTED_SETTINGS: + node: Any = pod + for key in path: + entries = getattr(get(node), "entries", None) + node = entries.get(key) if entries is not None else None + if node is None: + break + if node is not None: + settings["/".join(path)] = _plain_dict(tree, get(node)) + # The force a grip closes with (`SF` on GG; Biomek sends it as is). The pod's own + # `SqueezeForce` is runtime state; the gripper's is the setting. + gripper = get(e["Gripper"]).entries if "Gripper" in e else {} + if "SqueezeForce" in gripper: + settings["GripperSqueezeForce"] = gripper["SqueezeForce"] + side = "left" if e["LeftPod"] else "right" + return side, { + "component": e["PodName"], + "module_type": MODULE_TYPES[e["PodType"]], + "source": f"bif:Devices/Pipettor1/{e['Name']}", + "conversion": conversion, + "limits": limits, + "geometry": geometry, + "park": _plain_dict(tree, e["ParkLocation"]), + "settings": settings, + "gripper_model": _plain_dict(tree, e["GripperModel"]), + "obstacles": [ + { + "name": o["Name"], + "buffer": o.get("Buffer", 0.0), + **{k.lower(): o[k] for k in ("X1", "X2", "Y1", "Y2", "Z1", "Z2") if k in o}, + } + for o in (_plain_dict(tree, get(item)) for item in get(e["Obstacles"]).items) + ], + } + + +def _default_deck(tree: Tree) -> Tuple[str, Any]: + get = tree.deref + decks = get(tree.root.entries["Decks"]) + name = next(k for k in decks.entries if get(decks.entries[k]).entries.get("IsDefault")) + return name, get(decks.entries[name]) + + +def _positions(tree: Tree) -> Dict[str, Dict[str, Any]]: + """The default deck's positions: each one's corner per pod (`X`/`Y`/`Z`), its spans and + how each corner was framed.""" + get = tree.deref + positions = {} + for name, ref in get(_default_deck(tree)[1].entries["Positions"]).entries.items(): + e = get(ref).entries + if not all(f"{a}{n}" in e for a in "XYZ" for n in (1, 2)): + continue + positions[name] = { + "corners": {str(n): [e[f"X{n}"], e[f"Y{n}"], e[f"Z{n}"]] for n in (1, 2)}, + "x_span": e["XSpan"], + "y_span": e["YSpan"], + "framed": {str(n): e[f"Framed{n}"] for n in (1, 2) if f"Framed{n}" in e}, + } + return dict(sorted(positions.items())) + + +def _layout(tree: Tree) -> List[Dict[str, Any]]: + """The default deck's ALPs (`Decks//Groups`): each one's name, `Type`, pin `column` and + `row`, its positions' names and its left edge `X1` (cm), left to right.""" + get = tree.deref + layout = [] + for name, ref in get(_default_deck(tree)[1].entries["Groups"]).entries.items(): + e = get(ref).entries + positions = get(e.get("Positions")) + layout.append({ + "name": name, + "alp_type": e["Type"], + "column": e["column"], + "row": e["row"], + "positions": list(positions.entries) if positions is not None and positions.entries else [], + "x1": e.get("X1"), + }) # fmt: skip + return sorted(layout, key=lambda a: (a["column"], a["row"])) + + +def read_instrument_file(path: Union[str, Path]) -> Dict[str, Any]: + """The part of a declared configuration an instrument file gives, as `DeviceConfiguration` + serializes it: `instrument_serial_number`, `pods` (without their module serial numbers, which + the Master Controller's record gives), `deck_positions` and `deck_layout`. + + Raises: + ParseError: for a file this reader cannot account for completely. + """ + tree = parse_file(str(path)) + pipettor = tree.deref(tree.deref(tree.root.entries["Devices"]).entries["Pipettor1"]) + pods = dict(_pod(tree, tree.deref(pipettor.entries[name])) for name in ("Pod1", "Pod2")) + return { + "instrument_serial_number": pipettor.entries.get("SerialNumber"), + "pods": pods, + "deck_positions": _positions(tree), + "deck_layout": _layout(tree), + } diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file_tests.py new file mode 100644 index 00000000000..1c739b202d2 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file_tests.py @@ -0,0 +1,84 @@ +"""What a declared configuration takes from an instrument file, read from one written in the test +from the package's generic configuration.""" + +import tempfile +import unittest +from pathlib import Path + +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import ( + STATE, + container, + instrument_file_tree, + stream, + write_instrument_file, +) +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.instrument_file import ( + is_state, + read_instrument_file, +) +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.variant_tree import ParseError +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration + + +def configuration(): # type: ignore[no-untyped-def] + config = generic_configuration() + config.instrument_serial_number = "TEST0000001" + for side, pod in config.pods.items(): + pod.settings["HeadSerialNumber"] = f"HEAD-{side}" + return config + + +class InstrumentFileTests(unittest.TestCase): + def setUp(self) -> None: + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.path = Path(folder.name) / "Biomek_i7.bif" + self.config = configuration() + write_instrument_file(self.config, self.path) + self.read = read_instrument_file(self.path) + self.expected = self.config.to_dict() + + def test_the_pods_come_back_as_written(self) -> None: + for side, pod in self.expected["pods"].items(): + with self.subTest(side=side): + # The module serial numbers are the Master Controller record's, not the instrument file's. + expected = {k: v for k, v in pod.items() if k != "module_serial_number"} + self.assertEqual(self.read["pods"][side], expected) + self.assertEqual(self.read["instrument_serial_number"], "TEST0000001") + + def test_the_default_deck_comes_back_as_written(self) -> None: + self.assertEqual(self.read["deck_positions"], self.expected["deck_positions"]) + self.assertEqual(self.read["deck_layout"], self.expected["deck_layout"]) + + def test_runtime_state_is_left_out(self) -> None: + for side in ("left", "right"): + for key in STATE: + self.assertNotIn(key, self.read["pods"][side]["settings"]) + for key in ("RT_Anything", "Tip8", "D3Position", "Z1Position", "GrippedLabware"): + self.assertTrue(is_state(key), key) + for key in ("TipLoadForceLimitSlope", "Tips2Load", "ZMargin"): + self.assertFalse(is_state(key), key) + + def test_settings_kept_as_dictionaries_and_lists(self) -> None: + for side, pod in self.expected["pods"].items(): + for key, value in pod["settings"].items(): + if isinstance(value, (dict, list)): + self.assertEqual(self.read["pods"][side]["settings"][key], value, (side, key)) + + def test_a_position_without_both_corners_is_left_out(self) -> None: + tree = instrument_file_tree(self.config) + positions = tree["Decks"]["Deck1"]["Positions"] + name = next(iter(positions)) + del positions[name]["Z2"] + self.path.write_bytes(container(stream(tree))) + self.assertNotIn(name, read_instrument_file(self.path)["deck_positions"]) + + def test_a_file_this_reader_cannot_account_for_is_refused(self) -> None: + data = stream(instrument_file_tree(self.config)) + self.path.write_bytes(container(data[:4] + data[4:] + b"\x01")) + with self.assertRaises(ParseError): + read_instrument_file(self.path) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller.py new file mode 100644 index 00000000000..9c8bdc4184c --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller.py @@ -0,0 +1,218 @@ +"""What a declared configuration takes from Biomek's Master Controller: its instrument record. + +The Master Controller keeps one record per instrument it drives, in the `instrument` table of its +database (`C:\\ProgramData\\Beckman Coulter\\Biomek Master Controller\\Log.db3`; the same file +holds its logs). The record is the instrument's motor configuration, keyed by serial numbers: + + #( "" + #( "" left|right mc|span8 + #(#( ...) ...)) + ...) + +Each `` holds, in order: the axis's name, device byte, index and mask; its minimum and +maximum position; its home position (where Home All leaves it); its hysteresis (what the Master +Controller adds to its targets, measured per instrument: non-zero on the Span-8 Z channels); its +minimum and maximum velocity, acceleration and jerk (`#f` for none); a simulated flag; and its +Configure parameters as sent to its board (`#vu8(...)`), or for a syringe pump a `` +of its start and cutoff velocity limits and backlash, from which the pump's Configure parameters +are packed. Every value checks against the Configure bytes the Master Controller sends at a cold +start (the same limits; the same bytes). The record is rewritten only when the instrument's +motors are changed or measured, and carries no runtime state. + +The record is read in one of two ways, to the same result: +- from the database, read-only (`master_controller_db`), choosing the instrument by its chassis + serial number when the database holds more than one; +- from a text file holding the record (`master_controller_record`), for a computer without the + database, or a Python without `sqlite3`. +""" + +import re +import struct +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +MODULE_TYPES = {"mc": "multichannel", "span8": "span8"} +PUMP_DEVICE = 0x12 + +_TOKEN = re.compile(r'\s*(#vu8\(|#\(|\(|\)|"(?:[^"\\]|\\.)*"|[^\s()"]+)') + + +class Symbol(str): + """A bare word of the record (a name, `left`, `#f`), as opposed to a string.""" + + +def parse_record(text: str) -> List[Any]: + """Every top-level value of a record's text: vectors and lists as Python lists, byte vectors as + `bytes`, integers as `int`, `#t` / `#f` as `True` / `False`, strings as `str`, other words as + `Symbol`. + + Raises: + ValueError: for text that is not a record. + """ + tokens = [] + at = 0 + while text[at:].strip(): + m = _TOKEN.match(text, at) + if m is None: + raise ValueError(f"the Master Controller record holds text this reader does not know at {at}") + tokens.append(m.group(1)) + at = m.end() + pos = 0 + + def value() -> Any: + nonlocal pos + token = tokens[pos] + pos += 1 + if token in ("#(", "("): + items = [] + while tokens[pos] != ")": + items.append(value()) + pos += 1 + return items + if token == "#vu8(": + data = [] + while tokens[pos] != ")": + data.append(int(tokens[pos])) + pos += 1 + pos += 1 + return bytes(data) + if token == ")": + raise ValueError("unbalanced ')' in the Master Controller record") + if token.startswith('"'): + return token[1:-1] + if token in ("#t", "#f"): + return token == "#t" + if re.fullmatch(r"-?\d+", token): + return int(token) + return Symbol(token) + + out = [] + try: + while pos < len(tokens): + out.append(value()) + except IndexError as e: + raise ValueError("the Master Controller record ends inside a value") from e + return out + + +def _axis(motor: List[Any]) -> Dict[str, Any]: + """One `` record as a declared configuration's axis.""" + (_, name, device, index, _mask, pmin, pmax, phome, hysteresis, vmin, vmax, amin, amax, _jmin, + jmax, _simulated, config) = motor # fmt: skip + limits: Dict[str, int] = {"max_velocity": vmax, "max_acceleration": amax} + if device == PUMP_DEVICE: + _, min_start, max_start, min_cutoff, max_cutoff, backlash = config + configure = struct.pack( + "<8I2iH", min_start, max_start, vmin, vmax, min_cutoff, max_cutoff, amin, amax, pmin, pmax, + backlash, + ) # fmt: skip + else: + configure = config + limits["max_jerk"] = jmax if jmax is not False else 0 + limits.update({"min_position": pmin, "max_position": pmax}) + return { + "name": str(name), + "device": device, + "index": index, + "configure": configure.hex(), + "limits": limits, + "home_position": phome, + "hysteresis": hysteresis, + } + + +def _instrument(record: List[Any]) -> Dict[str, Any]: + """One `` record as the part of a declared configuration it gives.""" + if not record or record[0] != "": + raise ValueError("not a Master Controller instrument record") + modules: Dict[str, List[Dict[str, Any]]] = {} + module_serial_numbers: Dict[str, str] = {} + for arm in record[2:]: + if not arm or arm[0] != "": + raise ValueError("an instrument record entry that is not an arm") + _, serial, side, arm_type, motors = arm + if arm_type not in MODULE_TYPES: + raise ValueError(f"a {arm_type} arm, which this driver has no tables for") + module = MODULE_TYPES[arm_type] + if module in modules: + raise ValueError(f"two {module} arms in one instrument record") + modules[module] = [_axis(m) for m in motors] + module_serial_numbers[str(side)] = serial.upper() + return { + "chassis_serial_number": record[1].upper(), + "module_serial_numbers": module_serial_numbers, + "modules": modules, + } + + +def _records( + master_controller_db: Optional[Union[str, Path]], + master_controller_record: Optional[Union[str, Path]], +) -> List[str]: + if (master_controller_db is None) == (master_controller_record is None): + raise ValueError("give one of master_controller_db and master_controller_record") + if master_controller_record is not None: + return [Path(master_controller_record).read_text(encoding="utf-8")] + import contextlib + import sqlite3 # standard library; only needed for this way of reading the record + + uri = Path(master_controller_db).resolve().as_uri() + "?mode=ro" # type: ignore[arg-type] + with contextlib.closing(sqlite3.connect(uri, uri=True)) as db: # closed, not only committed + return [row[0] for row in db.execute("SELECT definition FROM instrument ORDER BY name")] + + +def read_master_controller( + master_controller_db: Optional[Union[str, Path]] = None, + master_controller_record: Optional[Union[str, Path]] = None, + chassis_serial_number: Optional[str] = None, +) -> Dict[str, Any]: + """The part of a declared configuration the Master Controller's instrument record gives: + `chassis_serial_number`, `module_serial_numbers` (per side) and `modules` (the motor tables). + + Args: + master_controller_db: its database (`Log.db3`), opened read-only. + master_controller_record: a text file holding the record, instead of the database. + chassis_serial_number: which instrument, when more than one record is found. + + Raises: + ValueError: for neither or both sources, no record of that instrument, more than one record + and no chassis serial number to choose by, or a record this reader does not know. + """ + found = [ + _instrument(record) + for text in _records(master_controller_db, master_controller_record) + for record in parse_record(text) + ] + if chassis_serial_number is not None: + found = [r for r in found if r["chassis_serial_number"] == chassis_serial_number.upper()] + if len(found) != 1: + serials = [r["chassis_serial_number"] for r in found] + raise ValueError( + f"{len(found)} Master Controller instrument records" + + (f" for chassis {chassis_serial_number}" if chassis_serial_number else "") + + (f" ({', '.join(serials)}); pass chassis_serial_number" if len(found) > 1 else "") + ) + return found[0] + + +def write_record(text: str, path: Union[str, Path]) -> None: + """Write a record's text to a file `master_controller_record` reads, after checking it parses.""" + for record in parse_record(text): + _instrument(record) + Path(path).write_text(text + "\n", encoding="utf-8") + + +def record_text( + master_controller_db: Union[str, Path], chassis_serial_number: Optional[str] = None +) -> str: + """The record's text as the database holds it, for `write_record`: the one instrument, or the one + with that chassis serial number.""" + texts = _records(master_controller_db, None) + matches: List[Tuple[str, Dict[str, Any]]] = [ + (t, _instrument(r)) for t in texts for r in parse_record(t) + ] + if chassis_serial_number is not None: + matches = [m for m in matches if m[1]["chassis_serial_number"] == chassis_serial_number.upper()] + if len(matches) != 1: + raise ValueError(f"{len(matches)} matching Master Controller instrument records") + return matches[0][0] diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller_tests.py new file mode 100644 index 00000000000..0432c192110 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/master_controller_tests.py @@ -0,0 +1,115 @@ +"""What a declared configuration takes from the Master Controller's instrument record, read from a +record written in the test from the package's generic configuration, as text and as a database.""" + +import tempfile +import unittest +from pathlib import Path + +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import ( + record_text, + write_database, + write_record, +) +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.master_controller import ( + Symbol, + parse_record, + read_master_controller, +) +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.master_controller import ( + write_record as save_record, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + as_instrument, + generic_configuration, +) + + +def instrument(chassis: str = "simulated00100000000000000000000") -> DeviceConfiguration: + """The generic configuration as an instrument's, with a measured hysteresis on a Span-8 Z.""" + config = as_instrument(generic_configuration()) + config.chassis_serial_number = chassis + z2 = next(a for a in config.modules["span8"] if a["name"] == "Z2") + z2["hysteresis"] = 11 + return config + + +class RecordTextTests(unittest.TestCase): + def test_values_of_each_kind(self) -> None: + parsed = parse_record('#( "ab\\"c" left 12 -3 #t #f (1 2) #vu8(0 255 7))') + self.assertEqual( + parsed, [["", 'ab\\"c', "left", 12, -3, True, False, [1, 2], b"\x00\xff\x07"]] + ) + self.assertIsInstance(parsed[0][2], Symbol) + self.assertNotIsInstance(parsed[0][1], Symbol) + + def test_text_that_is_not_a_record_is_refused(self) -> None: + for text in ("#(1 2", ")", '#(1 "unclosed)'): + with self.subTest(text=text), self.assertRaises(ValueError): + parse_record(text) + + +class ReadTests(unittest.TestCase): + def setUp(self) -> None: + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.folder = Path(folder.name) + self.config = instrument() + + def test_the_record_gives_the_motor_tables_and_serial_numbers(self) -> None: + path = self.folder / "record.txt" + write_record(self.config, path) + read = read_master_controller(master_controller_record=path) + self.assertEqual( + read["modules"], self.config.modules + ) # pumps' Configure packed from the record + self.assertEqual( + read["chassis_serial_number"], "SIMULATED00100000000000000000000" + ) # upper case + self.assertEqual( + read["module_serial_numbers"], + {side: pod.module_serial_number for side, pod in self.config.pods.items()}, + ) + + def test_a_database_gives_the_same(self) -> None: + db = self.folder / "Log.db3" + write_database([("one", record_text(self.config))], db) + record = self.folder / "record.txt" + write_record(self.config, record) + self.assertEqual( + read_master_controller(master_controller_db=db), + read_master_controller(master_controller_record=record), + ) + + def test_an_instrument_is_chosen_by_its_chassis(self) -> None: + db = self.folder / "Log.db3" + other = instrument(chassis="B" * 32) + write_database([("a", record_text(self.config)), ("b", record_text(other))], db) + with self.assertRaisesRegex(ValueError, "2 Master Controller instrument records.*pass"): + read_master_controller(master_controller_db=db) + chosen = read_master_controller(master_controller_db=db, chassis_serial_number="b" * 32) + self.assertEqual(chosen["chassis_serial_number"], "B" * 32) + with self.assertRaisesRegex(ValueError, "0 Master Controller instrument records for chassis"): + read_master_controller(master_controller_db=db, chassis_serial_number="0" * 32) + + def test_one_source_exactly(self) -> None: + path = self.folder / "record.txt" + write_record(self.config, path) + with self.assertRaisesRegex(ValueError, "one of"): + read_master_controller() + with self.assertRaisesRegex(ValueError, "one of"): + read_master_controller(master_controller_db=path, master_controller_record=path) + + def test_records_this_reader_does_not_know_are_refused(self) -> None: + text = record_text(self.config) + for bad, message in ( + ("#( 1)", "not a Master Controller instrument record"), + (text.replace(" span8 #(", " span96 #("), "span96 arm"), + (text.replace(" span8 #(", " mc #("), "two multichannel arms"), + ): + with self.subTest(message=message), self.assertRaisesRegex(ValueError, message): + save_record(bad, self.folder / "record.txt") + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree.py new file mode 100644 index 00000000000..6ea4b7d1b5f --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree.py @@ -0,0 +1,415 @@ +"""Read Biomek's variant-tree files: the instrument file (`.bif`), and labware / tip class data. + +Container: 5 header bytes, then zlib. Inside is one int32 size and one variant. A variant starts +with one code byte; its low nibble is the type and bit 0x10 marks an interface reference: + + 0x00 empty 0x01 null 0x02 true 0x03 false 0x04 byte 0x05 int16 0x06 int32 + 0x07 single 0x08 double 0x09 currency (int64 / 10000) 0x0A date (double, days) + 0x0B string (int32 length, UTF-16LE) 0x0C error (int32) + 0x0D reference to an object defined earlier (int32 index) + 0x0E object definition: int32 index (= objects so far), 16-byte class id, then the object's body + 0x0F array: vartype byte, uint16 dims, dims x (uint32 count, int32 lbound), then the elements + +Two classes carry most of a file: + +- a dictionary: a flag byte; if non-zero a class id follows, and with flag 1 an extension body of + that class comes first; then an int32 count of (string key, variant value) entries; +- a list: an int32 count of variants. + +The other classes' bodies (`EXTENSIONS`, `OBJECTS`) were measured on the files in hand. `parse` +refuses to finish with any byte unaccounted for, so a file in a format not seen here is refused, +not misread. +""" + +import struct +import uuid +import zlib +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple + +HEADER_SIZE = 5 + + +def _class_id(text: str) -> bytes: + return uuid.UUID(text).bytes_le + + +DICTIONARY = _class_id("E4C29FFF-BCE3-44DB-BEB6-5B5B6EBC0DF1") +LIST = _class_id("62DBE1C1-B344-4AB4-804F-73722341CBE5") +DATA_SET_MANAGER = _class_id("B6D3BEC0-0085-4F00-A09A-C310B1DAFB72") +DATA_SET = _class_id("C025C3B2-323C-4AC8-B61D-1F13EFFFE37F") +LABWARE = _class_id("739C5987-FD91-4D70-82CB-2A5B768E3CCB") +WORKSPACE = _class_id("23008335-C70E-46F0-87A8-4948F25298E8") +DECK_POSITION = _class_id("0E7CDB5A-E774-4F1A-A72E-A013F06ED62A") +PROMISE = _class_id("FD7B3B46-B8DA-4E47-B7FF-51B975DE468D") +WELL_VALUES = _class_id("51297284-DD58-4725-A9B9-429BD5610D69") + +CLASS_NAMES = { + DICTIONARY: "dictionary", + LIST: "list", + DATA_SET_MANAGER: "data set manager", + DATA_SET: "data set", + LABWARE: "labware", + WORKSPACE: "workspace", + DECK_POSITION: "deck position", + PROMISE: "promise", + WELL_VALUES: "well values", +} + +# Array vartypes whose elements are fixed-size values, read as raw bytes. +_ARRAY_RAW = { + 0x02: "h", + 0x03: "i", + 0x04: "f", + 0x05: "d", + 0x06: "q", + 0x07: "d", + 0x0A: "i", + 0x0B: "h", + 0x11: "B", +} + + +class ParseError(Exception): + """The file is not a variant tree as this reader knows it.""" + + +@dataclass +class Obj: + """An object definition: its class, what its extension or own body read, and its entries.""" + + index: int + class_id: bytes + flag: Optional[int] = None + extension_class_id: Optional[bytes] = None + extension: Any = None + entries: Optional[Dict[str, Any]] = None + items: Optional[List[Any]] = None + + @property + def class_name(self) -> str: + return CLASS_NAMES.get(self.class_id, str(uuid.UUID(bytes_le=self.class_id))) + + @property + def extension_name(self) -> Optional[str]: + if self.extension_class_id is None: + return None + return CLASS_NAMES.get( + self.extension_class_id, str(uuid.UUID(bytes_le=self.extension_class_id)) + ) + + +@dataclass +class Ref: + """A reference to an object defined earlier in the stream.""" + + index: int + + +@dataclass +class Currency: + value: int # x 10000 + + +@dataclass +class Date: + days: float # since 1899-12-30 + + +@dataclass +class Tree: + root: Any + objects: List[Obj] = field(default_factory=list) + + def deref(self, value: Any) -> Any: + """`value`, or the object it refers to.""" + return self.objects[value.index] if isinstance(value, Ref) else value + + +class Reader: + def __init__(self, data: bytes): + self.data = data + self.pos = 0 + self.objects: List[Obj] = [] + + # -- primitives -------------------------------------------------------------------------------- + + def take(self, n: int) -> bytes: + if n < 0 or self.pos + n > len(self.data): + raise ParseError(f"read of {n} bytes past the end at {self.pos}") + chunk = self.data[self.pos : self.pos + n] + self.pos += n + return chunk + + def unpack(self, fmt: str) -> Any: + return struct.unpack("<" + fmt, self.take(struct.calcsize("<" + fmt)))[0] + + def string(self) -> str: + n = self.unpack("i") + if n < 0: + raise ParseError(f"negative string length at {self.pos - 4}") + return self.take(2 * n).decode("utf-16-le") + + # -- variants ---------------------------------------------------------------------------------- + + def variant(self) -> Any: + at = self.pos + code = self.unpack("B") + kind = code & 0x0F + if kind == 0x00: + if code not in (0x00, 0x10, 0x20): + raise ParseError(f"unknown stream code {code:#x} at {at}") + return None + if kind == 0x01: + return None + if kind == 0x02: + return True + if kind == 0x03: + return False + if kind == 0x04: + return self.unpack("B") + if kind == 0x05: + return self.unpack("h") + if kind == 0x06: + return self.unpack("i") + if kind == 0x07: + return self.unpack("f") + if kind == 0x08: + return self.unpack("d") + if kind == 0x09: + return Currency(self.unpack("q")) + if kind == 0x0A: + return Date(self.unpack("d")) + if kind == 0x0B: + return self.string() + if kind == 0x0C: + return ("error", self.unpack("i")) + if kind == 0x0D: + index = self.unpack("i") + if not 0 <= index < len(self.objects): + raise ParseError(f"undefined object reference {index} at {at}") + return Ref(index) + if kind == 0x0E: + return self.object(at) + if kind == 0x0F: + return self.array() + raise ParseError(f"unknown stream code {code:#x} at {at}") # pragma: no cover + + def array(self) -> List[Any]: + vartype = self.unpack("B") + dims = self.unpack("H") + counts = [] + for _ in range(dims): + counts.append(self.unpack("I")) + self.unpack("i") # lower bound + total = 1 + for c in counts: + total *= c + if vartype in _ARRAY_RAW: + fmt = _ARRAY_RAW[vartype] + return list(struct.unpack(f"<{total}{fmt}", self.take(total * struct.calcsize(fmt)))) + if vartype == 0x08: + return [self.string() for _ in range(total)] + if vartype in (0x09, 0x0C, 0x0D): + return [self.variant() for _ in range(total)] + raise ParseError(f"invalid array vartype {vartype:#x} at {self.pos}") + + def object(self, at: int) -> Obj: + index = self.unpack("i") + if index != len(self.objects): + raise ParseError(f"invalid object definition {index} (expected {len(self.objects)}) at {at}") + obj = Obj(index=index, class_id=self.take(16)) + self.objects.append(obj) + if obj.class_id == DICTIONARY: + self.dictionary(obj) + elif obj.class_id == LIST: + obj.items = [self.variant() for _ in range(self.unpack("i"))] + elif obj.class_id in OBJECTS: + obj.extension = OBJECTS[obj.class_id](self) + else: + raise ParseError(f"no reader for class {obj.class_name} at {at}") + return obj + + def dictionary(self, obj: Obj) -> None: + obj.flag = self.unpack("B") + if obj.flag: + obj.extension_class_id = self.take(16) + if obj.flag == 1: + loader = EXTENSIONS.get(obj.extension_class_id) + if loader is None: + raise ParseError(f"no reader for extension {obj.extension_name} at {self.pos}") + obj.extension = loader(self) + elif obj.flag != 4: + raise ParseError(f"unknown dictionary flag {obj.flag} at {self.pos}") + count = self.unpack("i") + if count < 0: + raise ParseError(f"negative dictionary count at {self.pos - 4}") + obj.entries = {} + for _ in range(count): + key = self.string() + obj.entries[key] = self.variant() + + +# -- class-specific bodies --------------------------------------------------------------------- + + +def _string_list(r: Reader) -> List[str]: + """Data set manager: the data set names in order, as a counted list of strings.""" + return [r.string() for _ in range(r.unpack("i"))] + + +def _nothing(r: Reader) -> None: + """Data set: nothing of its own before the dictionary's entries.""" + return None + + +def _labware(r: Reader) -> Dict[str, Any]: + """Labware: per-well state, as (array variant, int32 well count) pairs. + + Measured on 8-, 96- and 384-well labware: four pairs, a flag byte, six more pairs when it is + set, and a closing flag byte that has only been seen clear. + """ + + def pairs(n: int) -> List[Any]: + out = [] + for _ in range(n): + values = r.variant() + wells = r.unpack("i") + if not isinstance(values, list) or len(values) != wells: + raise ParseError(f"labware array of {wells} wells does not hold {wells} at {r.pos}") + out.append(values) + return out + + arrays = pairs(4) + more = r.unpack("B") + if more: + arrays += pairs(6) + last = r.unpack("B") + if last: + raise ParseError(f"labware closing flag {last} not seen before, at {r.pos - 1}") + return {"arrays": arrays} + + +def _well_values(r: Reader) -> Dict[str, Any]: + """Well values: one value per well of a labware, named (a string), as int32 columns and int32 + rows, then columns x rows variants. Measured on the per-well liquid names (`DataSets` / + `RuntimeDataSets` "Liquid") Biomek writes into the instrument file with the deck's labware after + a run: 24-, 96- and 8-well labware.""" + name = r.string() + columns, rows = r.unpack("i"), r.unpack("i") + if columns < 0 or rows < 0: + raise ParseError(f"well values of {columns} x {rows} wells at {r.pos - 8}") + return { + "name": name, + "columns": columns, + "rows": rows, + "values": [r.variant() for _ in range(columns * rows)], + } + + +def _workspace(r: Reader) -> Dict[str, Any]: + """Workspace root: an int32 version, then two (int32, int32, int32, int32) records. Measured.""" + version = r.unpack("i") + records = [tuple(r.unpack("i") for _ in range(4)) for _ in range(2)] + return {"version": version, "records": records} + + +def _promise(r: Reader) -> Dict[str, Any]: + """Promise: three doubles, then a variant, then int32 and a byte. Measured.""" + values = [r.unpack("d") for _ in range(3)] + status = r.variant() + tail = (r.unpack("i"), r.unpack("B")) + return {"values": values, "status": status, "tail": tail} + + +EXTENSIONS: Dict[bytes, Callable[[Reader], Any]] = { + DATA_SET_MANAGER: _string_list, + DATA_SET: _nothing, + LABWARE: _labware, + WORKSPACE: _workspace, + WELL_VALUES: _well_values, +} + +OBJECTS: Dict[bytes, Callable[[Reader], Any]] = { + PROMISE: _promise, +} + + +# -- entry points ------------------------------------------------------------------------------ + + +def decompress(blob: bytes) -> bytes: + return zlib.decompress(blob[HEADER_SIZE:]) + + +def parse(data: bytes) -> Tree: + """Parse a decompressed stream completely: one int32 size, then one variant, nothing after. + + Raises: + ParseError: for anything else. + """ + r = Reader(data) + size = r.unpack("i") + if size != len(data) - 4: + raise ParseError(f"stream says {size} bytes, holds {len(data) - 4}") + root = r.variant() + if r.pos != len(data): + raise ParseError(f"{len(data) - r.pos} bytes left unparsed at {r.pos}") + return Tree(root=root, objects=r.objects) + + +def parse_file(path: str) -> Tree: + with open(path, "rb") as f: + return parse(decompress(f.read())) + + +def plain(value: Any, objects: List[Obj], inline: bool = False, _open: Optional[set] = None) -> Any: + """The tree as JSON-ready values: dictionaries as dicts, lists as lists, refs as {"$ref": n}. + + With `inline`, a reference is replaced by the object it names, except inside that same object + (a cycle), where it stays {"$ref": n}. + """ + _open = set() if _open is None else _open + if isinstance(value, Ref) and inline and value.index not in _open: + return plain(objects[value.index], objects, inline, _open) + if isinstance(value, Obj): + _open = _open | {value.index} + + def sub(v: Any) -> Any: + return plain(v, objects, inline, _open) + + if value.entries is not None: + out: Dict[str, Any] = {} + if value.extension_class_id is not None: + out["$class"] = value.extension_name + if value.extension is not None: + out["$extension"] = sub(value.extension) + out["$id"] = value.index + out.update({k: sub(v) for k, v in value.entries.items()}) + return out + if value.items is not None: + return [sub(v) for v in value.items] + return {"$class": value.class_name, "$id": value.index, "$body": sub(value.extension)} + if isinstance(value, Ref): + return {"$ref": value.index} + if isinstance(value, Currency): + return value.value / 10000 + if isinstance(value, Date): + return {"$date": value.days} + if isinstance(value, dict): + return {k: plain(v, objects, inline, _open) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [plain(v, objects, inline, _open) for v in value] + return value + + +def walk(value: Any, path: str = "") -> Iterator[Tuple[str, Any]]: + """Every leaf value with its path (`/Decks/Standard/Groups/...`), over a `plain` tree.""" + if isinstance(value, dict): + for k, v in value.items(): + yield from walk(v, f"{path}/{k}") + elif isinstance(value, list): + for i, v in enumerate(value): + yield from walk(v, f"{path}[{i}]") + else: + yield path, value diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree_tests.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree_tests.py new file mode 100644 index 00000000000..b6d31ef978f --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/variant_tree_tests.py @@ -0,0 +1,165 @@ +"""The variant-tree reader on streams built in the test: every value kind, objects and references, +the class bodies it knows, and the refusals that keep a file of another format from being misread.""" + +import struct +import unittest +import uuid + +from pylabrobot.beckman_coulter.biomek_i7.biomek_files import variant_tree as vt +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import ( + Array, + Writer, + container, + stream, +) + + +def parse_root(value: object) -> object: + tree = vt.parse(stream(value)) + return vt.plain(tree.root, tree.objects, inline=True) + + +def without_ids(value: object) -> object: + if isinstance(value, dict): + return {k: without_ids(v) for k, v in value.items() if k != "$id"} + if isinstance(value, list): + return [without_ids(v) for v in value] + return value + + +class ValueTests(unittest.TestCase): + def test_scalars_round_trip(self) -> None: + for value in (None, True, False, 0, -7, 2**31 - 1, 1.5, -0.001, "", "Pod1", "µL ≤ 1"): + with self.subTest(value=value): + self.assertEqual(parse_root(value), value) + + def test_fixed_size_codes(self) -> None: + cases = [ + (b"\x04\x2a", 42), + (b"\x05" + struct.pack(" None: + value = {"Devices": {"Pipettor1": {"Pod1": {"Name": "Pod1", "X": [1, 2.5, "three"]}}}} + self.assertEqual(without_ids(parse_root(value)), value) + paths = dict(vt.walk(without_ids(parse_root(value)))) + self.assertEqual(paths["/Devices/Pipettor1/Pod1/X[2]"], "three") + + def test_references_name_objects_defined_earlier(self) -> None: + shared = {"a": 1} + tree = vt.parse(stream([shared, vt.Ref(1)])) + self.assertIsInstance(tree.root.items[1], vt.Ref) + self.assertIs(tree.deref(tree.root.items[1]), tree.objects[1]) + plain = vt.plain(tree.root, tree.objects, inline=True) + self.assertEqual(without_ids(plain), [shared, shared]) + + def test_arrays(self) -> None: + self.assertEqual(parse_root(Array(0x03, [1, -2, 3], "i")), [1, -2, 3]) + self.assertEqual(parse_root(Array(0x05, [0.25, 2.0], "d")), [0.25, 2.0]) + self.assertEqual(parse_root(Array(0x08, ["a", "bc"])), ["a", "bc"]) + self.assertEqual(parse_root(Array(0x0C, [1, "x", None])), [1, "x", None]) + + def test_the_container_is_a_header_then_zlib(self) -> None: + data = stream({"k": "v"}) + self.assertEqual(vt.decompress(container(data)), data) + + +class ClassBodyTests(unittest.TestCase): + """The bodies of the classes besides dictionaries and lists, as `EXTENSIONS` / `OBJECTS` read + them, on bodies laid out as each reader states.""" + + @staticmethod + def extended(class_id: bytes, body: bytes) -> object: + """A dictionary with an extension of `class_id`, its body `body`, and one entry.""" + w = Writer() + data = w.define(vt.DICTIONARY) + b"\x01" + class_id + body + struct.pack(" None: + w = Writer() + body = struct.pack(" None: + w = Writer() + body = w.string("Liquid") + struct.pack(" None: + w = Writer() + pair = w.variant(Array(0x05, [0.0, 1.0], "d")) + struct.pack(" None: + plain = self.extended(vt.WORKSPACE, struct.pack("<9i", 3, *range(8))) + assert isinstance(plain, dict) + self.assertEqual(plain["$extension"], {"version": 3, "records": [[0, 1, 2, 3], [4, 5, 6, 7]]}) + w = Writer() + data = w.define(vt.PROMISE) + struct.pack("<3d", 1.0, 2.0, 3.0) + w.variant(5) + data += struct.pack(" bytes: + return struct.pack(" None: + good = stream({"a": 1}) + with self.assertRaisesRegex(vt.ParseError, "stream says"): + vt.parse(good + b"\x00") + with self.assertRaisesRegex(vt.ParseError, "left unparsed"): + vt.parse(self.body(good[4:] + b"\x01")) + with self.assertRaisesRegex(vt.ParseError, "past the end"): + vt.parse(self.body(b"\x0b" + struct.pack(" None: + with self.assertRaisesRegex(vt.ParseError, "unknown stream code"): + vt.parse(self.body(b"\x30")) + with self.assertRaisesRegex(vt.ParseError, "undefined object reference"): + vt.parse(self.body(b"\x0d" + struct.pack(" str: return "sha256:" + hashlib.sha256(text.encode("ascii")).hexdigest() +def differences(old: Any, new: Any, path: str = "") -> List[str]: + """Where two JSON values differ, one line per leaf (`pods/left/limits/X: [..] -> [..]`).""" + if isinstance(old, dict) and isinstance(new, dict): + lines = [] + for key in sorted(set(old) | set(new), key=str): + sub = f"{path}/{key}" if path else str(key) + if key not in old: + lines.append(f"{sub}: added") + elif key not in new: + lines.append(f"{sub}: removed") + else: + lines += differences(old[key], new[key], sub) + return lines + if isinstance(old, list) and isinstance(new, list) and len(old) == len(new): + return [ + line for i, (a, b) in enumerate(zip(old, new)) for line in differences(a, b, f"{path}[{i}]") + ] + return [] if old == new else [f"{path}: {old!r} -> {new!r}"] + + +@dataclass(frozen=True) +class SourcesCheck: + """How a configuration's sources compare with it now (`DeviceConfiguration.check_sources`): + `changed` lists each value that differs, `unavailable` each source that could not be found.""" + + changed: List[str] + unavailable: List[str] + + @dataclass class DeviceConfiguration: """Everything declared about one instrument: its motor tables and its pods. @@ -371,6 +402,45 @@ def pod(self, side: Side) -> PodConfiguration: raise ValueError(f"no pod declared on the {side}; declared: {sorted(self.pods)}") return self.pods[side] + @classmethod + def from_biomek( + cls, + bif: Union[str, Path], + master_controller_db: Optional[Union[str, Path]] = None, + master_controller_record: Optional[Union[str, Path]] = None, + chassis_serial_number: Optional[str] = None, + ) -> "DeviceConfiguration": + """An instrument's declared configuration, from its Biomek files: the only way one is made. + + Args: + bif: Biomek's instrument file (on the instrument's computer, + `C:\\Users\\Public\\Documents\\Biomek5\\Biomek_i7.bif`). + master_controller_db: the Master Controller's database (`C:\\ProgramData\\Beckman + Coulter\\Biomek Master Controller\\Log.db3`), read-only. + master_controller_record: instead of the database, a text file holding its instrument + record (`biomek_files.master_controller.write_record`). + chassis_serial_number: which instrument's record, when the database holds more than one. + + Raises: + ValueError: for files that do not describe one consistent instrument (see + `biomek_files.importer`). + """ + from pylabrobot.beckman_coulter.biomek_i7.biomek_files.importer import import_configuration + + return import_configuration( + bif, + master_controller_db=master_controller_db, + master_controller_record=master_controller_record, + chassis_serial_number=chassis_serial_number, + ) + + def check_sources(self) -> SourcesCheck: + """Read this configuration's sources again (read-only) and say what has changed since it was + imported, and which sources cannot be found here.""" + from pylabrobot.beckman_coulter.biomek_i7.biomek_files.importer import check_sources + + return check_sources(self) + def fingerprints(self) -> Dict[str, str]: """The fingerprint of the values taken from each source, as they are now.""" parts = source_parts(self.to_dict()) @@ -378,7 +448,7 @@ def fingerprints(self) -> Dict[str, str]: def unrecorded_changes(self) -> List[str]: """The sources whose values no longer match the fingerprints recorded at import: changed after - the file was made, by hand or otherwise.""" + the file was made, by hand or by anything but `from_biomek`.""" now = self.fingerprints() return [name for name in SOURCES if self.sources.get(name, {}).get("fingerprint") != now[name]] @@ -407,11 +477,11 @@ def scrub(value: Any) -> Any: @classmethod def load(cls, path: Union[str, Path]) -> "DeviceConfiguration": - """An instrument's declared configuration, from the file `save` wrote. + """An instrument's declared configuration, from the file `from_biomek` made and `save` wrote. Raises: ValueError: if its values no longer match the fingerprints recorded at import: it was - changed afterwards. Import it again. + changed afterwards. Make it again with `from_biomek`. """ with open(path, encoding="utf-8") as fh: config = cls.from_dict(json.load(fh)) @@ -419,7 +489,8 @@ def load(cls, path: Union[str, Path]) -> "DeviceConfiguration": if changed: raise ValueError( f"{path}: the values from {' and '.join(changed)} are not the ones imported (changed " - "after import); import it again from the instrument's Biomek files" + "after import, or not made by `DeviceConfiguration.from_biomek`); import it again from " + "the instrument's Biomek files" ) return config diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index 75a257162e8..f7aeab409b6 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -56,9 +56,9 @@ def __init__( Args: serial_numbers: the ACE boards' USB serial numbers. Defaults to every ACE board attached. declared_configuration_json: path of the instrument's declared configuration (motor tables, - and per pod its conversions, limits, geometry and calibration), made from the instrument's - Biomek files. Required: the driver never falls back to another, the package's generic one - included. + and per pod its conversions, limits, geometry and calibration), as + `DeviceConfiguration.from_biomek` makes it from the instrument's Biomek files. Required: + the driver never falls back to another, the package's generic one included. boards: boards to use instead of opening USB devices: a simulated instrument (`simulator.replay_boards`). With them, the checks that tie the configuration to a real instrument (`discover`) are not made. @@ -70,7 +70,7 @@ def __init__( if declared_configuration_json is None: raise ValueError( "no declared configuration: pass `declared_configuration_json`, the instrument's own, made " - "from its Biomek files" + "by `DeviceConfiguration.from_biomek` from its Biomek files" ) self._serial_numbers = list(serial_numbers) if serial_numbers is not None else None self.declared_configuration_json = declared_configuration_json @@ -150,13 +150,17 @@ async def discover(self) -> None: place, no chassis, or a pod type other than the declared one is refused (`_check_declared_against`). - On the instrument (no `boards` given), the declared configuration must be this instrument's: - its chassis serial number and each declared pod's module serial number as the modules report - them, and not the generic one (`DeviceConfiguration.generic`). Otherwise it is refused. + On the instrument (no `boards` given), two checks follow, each refusing: + - the declared configuration must be this instrument's: its chassis serial number and each + declared pod's module serial number as the modules report them, and not the generic one + (`DeviceConfiguration.generic`); + - it must still match the Biomek files it was imported from, where they can be found + (`DeviceConfiguration.check_sources`): a re-framed deck or re-measured motors there make it + stale. Where they cannot be found (another computer), a warning says so. Raises: RuntimeError: for a board this driver cannot place, or no chassis. - ValueError: for a declared configuration that is not this instrument's. + ValueError: for a declared configuration that is not this instrument's, or is stale. """ if not self._connected: await self._open() @@ -215,9 +219,32 @@ async def discover(self) -> None: "the declared configuration is not this instrument's: " + "; ".join(mismatches) + ". Its motor tables, conversions, geometry and calibration may not fit. Pass this " - "instrument's own `declared_configuration_json`, made from its Biomek files." + "instrument's own `declared_configuration_json`, made by " + "`DeviceConfiguration.from_biomek` from its Biomek files." ) - logger.info("the declared configuration is this instrument's: serial numbers match the modules") + sources = self.declared.check_sources() + if sources.changed: + shown = sources.changed[:20] + more = len(sources.changed) - len(shown) + raise ValueError( + "the declared configuration no longer matches the Biomek files it was imported from (" + + "; ".join(shown) + + (f"; and {more} more" if more else "") + + "): the instrument was re-calibrated or re-configured since. Import it again: " + "`DeviceConfiguration.from_biomek(...).save(path)`." + ) + if sources.unavailable: + logger.warning( + "the declared configuration's sources cannot be read here (%s): whether the instrument " + "was re-calibrated since %s cannot be checked", + "; ".join(sources.unavailable), + self.declared.sources.get("instrument_file", {}).get("read_at", "it was imported"), + ) + logger.info( + "the declared configuration is this instrument's: serial numbers match the modules; " + "sources %s", + "unchanged since import" if not sources.unavailable else "partly not checked (above)", + ) async def request_serial_numbers(self) -> Dict[str, Optional[str]]: """The serial numbers the modules report: `chassis`, and `left` / `right` for each pod found. @@ -271,10 +298,16 @@ def _check_declared_against(self, types: Dict[str, str]) -> None: found or "nothing", ) - def save_configuration(self, path: str) -> None: + def save_configuration(self, path: str, indent: Optional[int] = 2) -> None: """Write the declared configuration to `path`, as loaded, for `declared_configuration_json` to - read back. Nothing found at discovery is written into it.""" - self.declared.save(path) + read back. A configuration is made only from the instrument's Biomek files + (`DeviceConfiguration.from_biomek`), so nothing found at discovery is written into it. + + Args: + path: where to write it. + indent: how far to indent the JSON, or None to write it on one line. + """ + self.declared.save(path, indent=indent) def _serial_numbers_found(self) -> Dict[str, Optional[str]]: if self.chassis is None or self.chassis.configuration is None: diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py index ea1af8ca706..f77e3888fc4 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/serial_numbers_tests.py @@ -1,5 +1,5 @@ -"""The check that ties a declared configuration to one instrument: its serial numbers, on the -instrument's own path. The replayed generic cold start answers placeholder serial numbers, as long +"""The checks that tie a declared configuration to one instrument, on the instrument's own path: +its serial numbers, and its Biomek files still matching. The replayed generic cold start answers placeholder serial numbers, as long as real ones; a configuration copy naming them stands for that instrument's own. The instrument's path (no `boards` given) is taken with the replayed boards attached where `_open` @@ -7,10 +7,16 @@ import asyncio import dataclasses +import tempfile import unittest +from pathlib import Path from typing import Iterator, List from unittest import mock +from pylabrobot.beckman_coulter.biomek_i7.biomek_files.files_tests_support import ( + write_instrument_file, + write_record, +) from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration @@ -26,6 +32,7 @@ sealed, ) +MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master" READS = {name for name in p.COMMANDS.values() if name.startswith(("Get ", "Read ", "List "))} @@ -89,6 +96,37 @@ async def test_the_generic_configuration_is_refused(self) -> None: await self.driver(generic_configuration()).discover() +class SourcesTests(InstrumentPathTests): + """A configuration imported from Biomek files written in the test, as the instrument's own.""" + + async def asyncSetUp(self) -> None: + await super().asyncSetUp() + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.bif, self.record = Path(folder.name) / "Biomek_i7.bif", Path(folder.name) / "record.txt" + self.instrument = as_instrument(generic_configuration()) + write_instrument_file(self.instrument, self.bif) + write_record(self.instrument, self.record) + self.imported = DeviceConfiguration.from_biomek(self.bif, master_controller_record=self.record) + + async def test_matching_sources_are_accepted(self) -> None: + with self.assertNoLogs(MASTER_LOGGER, "WARNING"): + await self.driver(self.imported).discover() + + async def test_a_re_measured_hysteresis_makes_it_stale(self) -> None: + next(a for a in self.instrument.modules["span8"] if a["name"] == "Z3")["hysteresis"] = 4 + write_record(self.instrument, self.record) + with self.assertRaisesRegex(ValueError, r"no longer matches.*hysteresis: 0 -> 4.*from_biomek"): + await self.driver(self.imported).discover() + self.assertEqual(set(self.requests()) - READS, set()) + + async def test_sources_not_found_here_are_warned_about(self) -> None: + self.bif.unlink() + with self.assertLogs(MASTER_LOGGER, "WARNING") as logs: + await self.driver(self.imported).discover() + self.assertIn("cannot be read here", " ".join(logs.output)) + + class SimulationTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self) -> None: asyncio.get_running_loop().set_debug(False) From 687c97c346582c77ed27d40b1c46408b4a4f6b38 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:21:26 -0800 Subject: [PATCH 11/28] `Biomek i7`: configuring, the interlock, faults, pause and stop `setup()` now brings the instrument up after discovery, moving nothing: the motor tables are loaded where a board has lost them, the interlock is armed and every axis enabled, in the order Biomek's Master Controller logs show. - `driver/master.py`: `initialize`, `configure`, `arm_interlock`; a fault at rest is only noted, one under power is reset with a warning, one that does not clear trips the interlock and shows ERROR; per-pod skips; `stop` stops each pod's module and trips the interlock when the driver armed it; a motor failing on its own, or the interlock tripping under the driver, trips it and shows ERROR, as the Master Controller's logs show; `pause` / `resume` (a deliberate trip with PAUSED shown, then re-arm and enable). - `driver/features/chassis.py`, `door.py`: the interlock's writes, the status display, the door (`front_cover`), which only reports. - `driver/features/pod.py`: configure, enable, axis states, positions, homed state. - `driver/simulator.py`: `SimulatedAceUSB`, each axis's state and the interlock, door and drive supply the boards of one instrument share. - `session_log.py`: a run's log lines in a file of its own, to compare with Biomek's logs. Tests: the simulated boards' rules; configure sends the Configure, interlock and I/O box requests the Master Controller sent at the recorded cold start, in its order; enabling follows its order; faults at rest, under power and stuck; the drive supply, an open door, a broken light curtain; door reports; pause / resume; a motor failing on its own; stop; the session log. --- .../beckman_coulter/biomek_i7/design.md | 12 + .../biomek_i7/driver/features/chassis.py | 68 ++- .../biomek_i7/driver/features/door.py | 58 +++ .../biomek_i7/driver/features/pod.py | 93 ++++- .../biomek_i7/driver/lifecycle_tests.py | 380 +++++++++++++++++ .../biomek_i7/driver/master.py | 387 +++++++++++++++++- .../biomek_i7/driver/recipes/__init__.py | 1 + .../biomek_i7/driver/recipes/homing.py | 19 + .../biomek_i7/driver/simulator.py | 247 ++++++++++- .../beckman_coulter/biomek_i7/session_log.py | 88 ++++ .../biomek_i7/session_log_tests.py | 49 +++ .../biomek_i7/simulation_tests_support.py | 10 +- 12 files changed, 1389 insertions(+), 23 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/features/door.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/lifecycle_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/session_log.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/session_log_tests.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index b119ee12e3f..a74397bc096 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -46,3 +46,15 @@ on the instrument, discovery refuses one whose serial numbers are not the module sources have changed since. There is no switch to skip a check; the fix is to import again. A simulation with no files uses the package's generic instrument (`defaults/`), which a live session refuses. + +## The pods + +`left_x_arm` / `right_x_arm` (STAR's names) are `Pod`s, one ACE board each, on one shared X rail. A +pod's axes, head or channels and gripper are driven by one board through one position record, so the +pod keeps the shared mechanics (moves, homing, enabling, the reads, every `_unchecked_fw_*`) and its +features send through it. `driver.arm(name)` also takes Biomek's names (`1`, `"Pod1"`, `"MC_1"`). + +**I5. Safety state.** The instrument rests with the interlock tripped; the driver arms it only to +move and leaves it as it found it. `stop()` moves nothing (Biomek stops in place). `pause` / +`resume` is Biomek's whole-system pause. A fault under power is cleared by enabling, with a warning; +one that will not clear trips the interlock. The door only reports: it has no interlock of its own. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py index df4974fd77a..0217e61071b 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/chassis.py @@ -1,11 +1,12 @@ -"""The chassis module: its inputs and outputs, the legacy deck devices it lists, and the interlock's -state.""" +"""The chassis module: interlock, status display, deck I/O and the instrument's own sensors (the door +is its own feature, `door.py`, read through the chassis).""" from typing import Dict, List, Optional from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ModuleConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, read_module, @@ -18,6 +19,7 @@ class Chassis: def __init__(self, board: AceBoard): self.board = board self.configuration: Optional[ModuleConfiguration] = None + self.front_cover = Door(self) async def discover(self) -> ModuleConfiguration: """Read what the chassis says about itself. Moves nothing.""" @@ -55,8 +57,9 @@ async def request_legacy_alp_devices(self) -> List[bytes]: return [payload[i : i + 2] for i in range(0, len(payload), 2)] # -- interlock ------------------------------------------------------------- - # The interlock cuts the arms' drive power when the light curtain is broken or the host trips it; - # nothing moves while it is tripped. Here it is only read. + # The interlock cuts the arms' drive power when the light curtain is broken or the host trips it + # (the door does not: see `door.py`); nothing moves while it is tripped. It can be read, tripped and re-armed; there is + # deliberately no way here to bypass it. async def request_interlock_state(self) -> p.InterlockState: """`armed` (the drives may have power) or `tripped`. Moves nothing. @@ -65,3 +68,60 @@ async def request_interlock_state(self) -> p.InterlockState: reads the state; it changes nothing. """ return p.parse_interlock_status((await self.board.send(p.get_interlock_status())).payload) + + async def prepare_interlock(self) -> None: + """Trip the interlock, ask to be told when it trips, and show READY, as before the motor tables + are loaded after a power-up.""" + await self._unchecked_fw_trip_interlock() + await self._unchecked_fw_notify_on_interlock_trip() + await self._unchecked_fw_set_status_display("ready") + + async def _io_box_write_after_configure(self) -> None: + """Send the legacy deck digital I/O box its WRITE 01, a cancel of what that box was doing: + Biomek's logs show it after every Stop Module Execution (the Master Controller stopping the + box), which in a cold start falls after the motor tables are loaded. Kept where the recorded + start sends it, so the start stays byte for byte; it has nothing to do with the light curtain.""" + await self._unchecked_fw_send_digital_io_box(b"\x02\x01") + + async def trip_interlock(self, error: bool = False) -> None: + """Cut the arms' drive power and show READY: how the Master Controller leaves the instrument + at rest (it does so at every start; the drive supply reads off in over 90% of its polls). + With `error`, show ERROR, as it does after a failed move.""" + await self._unchecked_fw_trip_interlock() + await self._unchecked_fw_set_status_display("error" if error else "ready") + + async def arm_interlock(self) -> None: + """Re-arm the interlock and show RUNNING. The light curtain must be clear. + + Raises: + RuntimeError: if the interlock does not report ARMED. + """ + state = await self._unchecked_fw_rearm_interlock() + if state[:1] != b"\x00": + raise RuntimeError( + f"the interlock did not arm (state {state.hex()}); is the light curtain clear?" + ) + await self._unchecked_fw_set_status_display("running") + + # -- firmware commands ----------------------------------------------------- + # The chassis's writes, one request each, as the Master Controller sends them. No checks and no + # bookkeeping: the public methods above decide when each is sent. + + async def _unchecked_fw_trip_interlock(self) -> None: + await self.board.send(p.trip_interlock()) + + async def _unchecked_fw_rearm_interlock(self) -> bytes: + """Re-Arm Interlock. Returns what it answers: `00` when armed.""" + return (await self.board.send(p.rearm_interlock())).payload + + async def _unchecked_fw_notify_on_interlock_trip(self) -> None: + await self.board.send(p.notify_on_interlock_trip()) + + async def _unchecked_fw_set_status_display(self, state: p.StatusDisplayState) -> None: + await self.board.send(p.set_status_display(state)) + + async def _unchecked_fw_send_digital_io_box(self, data: bytes) -> None: + await self.board.send(p.send_digital_io_box(data)) + + async def _unchecked_fw_notify_on_input_change(self, index: int, notify: bool) -> None: + await self.board.send(p.notify_on_change(p.Device.DIGITAL_INPUT, index, notify)) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/door.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/door.py new file mode 100644 index 00000000000..695fc5cbcaa --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/door.py @@ -0,0 +1,58 @@ +"""The instrument's door: STAR's `FrontCover`, and reached by its name, `driver.front_cover` / +`biomek.front_cover`. + +The door sensor is the chassis's digital input "Door Sensor": 1 closed, 0 open. The door only +reports: opening it does not trip the interlock, and Biomek arms the interlock with it open +(Biomek's logs, July to October 2026). The interlock (`chassis`) answers to the light curtain and +to the host. STAR's `enable_control` / `disable_control` have no counterpart here: the door has no +interlock to turn off. +""" + +from typing import TYPE_CHECKING, Callable, Literal + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis + +DoorState = Literal["open", "closed"] +DOOR_SENSOR_INPUT = "Door Sensor" +DOOR_CLOSED = 1 + + +class Door: + """The door, read through the chassis's door sensor.""" + + def __init__(self, chassis: "Chassis"): + self._chassis = chassis + + def _input(self) -> int: + config = self._chassis._require_configuration() + for index, name in config.digital_inputs.items(): + if name == DOOR_SENSOR_INPUT: + return index + raise RuntimeError(f"the chassis has no digital input named {DOOR_SENSOR_INPUT!r}") + + async def request_state(self) -> DoorState: + """Whether the door is open or closed (STAR's `FrontCover.request_state`). Moves nothing.""" + board = self._chassis.board + reply = await board.send(p.read_input_output(p.Device.DIGITAL_INPUT, self._input())) + return "closed" if reply.payload[0] == DOOR_CLOSED else "open" + + def subscribe(self, callback: Callable[[DoorState], None]) -> Callable[[], None]: + """Call `callback` whenever the door opens or closes. Returns an unsubscribe. + + The chassis reports changes only once asked to (Notify On Digital Input Change, which the + Master Controller sends at every start and `notify_changes` sends).""" + index = self._input() + + def on_message(reply: p.Reply) -> None: + if (reply.device, reply.opcode) == p.DIGITAL_INPUT_VALUE and reply.index == index: + callback("closed" if reply.payload[:1] == bytes([DOOR_CLOSED]) else "open") + + return self._chassis.board.subscribe(on_message) + + async def notify_changes(self, notify: bool = True) -> None: + """Ask the chassis to report the door opening and closing (or, False, to stop). Moves + nothing.""" + await self._chassis._unchecked_fw_notify_on_input_change(self._input(), notify) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index c08056a6c9a..67627737673 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -1,6 +1,7 @@ """One pod: an arm on the shared X rail, its ACE module, and the axes that module drives.""" -from typing import Dict, List, Literal, Optional, Tuple +import logging +from typing import Dict, List, Literal, Optional, Sequence, Tuple, cast from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p @@ -14,18 +15,31 @@ read_module, ) from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, MotorTables +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ENABLE_ORDER, ENABLE_PREFIX + +logger = logging.getLogger(__name__) # How Biomek numbers its pods. Pod1 is the left pod and Pod2 the right on the instrument this # driver was written against; whether that holds on every build is not established. POD_NUMBERS = {"left": 1, "right": 2} COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"} +# Get Homed State answers. 0x01 was read from every axis at a cold start, 0x00 from every axis of +# both pods after Biomek's Home All (H1, 2026-10-24). +HOMED_STATES = {0x00: "homed", 0x01: "not_homed"} + # Biomek's "Safe Height" (`GlobalMinSafeHeight`) at or below this is unset (it stores -100000). UNSET_SAFE_HEIGHT = -1000.0 # The arm board's analog input carrying the interlocked motor supply ("+36V Interlock"). DRIVE_SUPPLY_INPUT = "+36V Interlock" +# Set State ENABLED on a CiA 402 drive resets a fault, then steps the drive through shutdown, switch +# on and enable operation, waiting up to 3 s for each. Whether a board enables +# a batch one drive at a time is not known, so a batch is given that per axis; it is a bound for +# a drive that does not come up, not how long enabling takes. +ENABLE_SECONDS_PER_AXIS = 9.0 + class Pod: """One pod. Reached as `driver.left_x_arm` / `driver.right_x_arm`: it fills the slot of STAR's @@ -89,6 +103,26 @@ async def discover(self) -> ModuleConfiguration: self.configuration = await read_module(self.board) return self.configuration + async def request_positions(self) -> Dict[str, int]: + """Every axis's current position, in counts, as the drives report it.""" + replies = await self.board.send_many( + [p.get_current_position(axis.device, axis.index) for axis in self.axes] + ) + return {axis.name: p.parse_s32(r.payload) for axis, r in zip(self.axes, replies)} + + async def request_axis_states(self) -> Dict[str, p.AxisStateName]: + """Every axis's state (motors and pumps), sent together: `enabled` (it may move), `disabled` + (configured, not enabled), `not_configured` (as at power-up) or `fault`. Moves nothing. + + Raises: + ValueError: for a state byte the firmware does not set. + """ + replies = await self.board.send_many([p.get_state(a.device, a.index) for a in self.axes]) + return { + a.name: cast(p.AxisStateName, p.parse_axis_state(r.payload).name.lower()) + for a, r in zip(self.axes, replies) + } + async def request_drive_supply(self) -> float: """The pod's interlocked motor supply, in volts: about 36 with the interlock armed, about 0.1 tripped. Moves nothing. @@ -104,6 +138,13 @@ async def request_drive_supply(self) -> float: return p.parse_float(reply.payload) raise RuntimeError(f"{self} has no {DRIVE_SUPPLY_INPUT!r} analog input") + async def request_homed_state(self, axis_name: str) -> str: + """Whether an axis (a motor or a pump) has been homed: `homed`, `not_homed`, or the raw code + of a state not yet seen.""" + axis = self.axis(axis_name) + code = (await self.board.send(p.get_homed_state(axis.device, axis.index))).payload[0] + return HOMED_STATES.get(code, f"0x{code:02X}") + async def request_accuframe_offsets(self) -> Tuple[float, float, float]: """The X, Y and Z offsets the pod's AccuFrame board holds.""" return p.parse_accuframe_offsets((await self.board.send(p.get_accuframe_offsets())).payload) @@ -112,3 +153,53 @@ async def request_analog_inputs(self) -> Dict[str, float]: if self.configuration is None: raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first") return await read_analog_inputs(self.board, self.configuration) + + # -- configuration and enabling ------------------------------------------------ + # These write to the board. Nothing in this driver calls them on its own. + + async def configure(self) -> None: + """Load every axis's motor table into the board, then Stop Module Execution, as after a + power-up. The tables come from the motor recording; the board cannot be asked for them. + + Configuring an axis that is configured is accepted, and leaves it disabled and not homed, so + this un-homes the pod.""" + logger.info("%s configure (%d axes)", self.component, len(self.axes)) + for axis in self.axes: + await self._unchecked_fw_configure(axis) + await self._unchecked_fw_stop_module_execution() + + async def enable_axes(self) -> Dict[str, int]: + """Stop motion and enable every axis, as after the interlock is armed (its drive power was + off), and read where each is, as the Master Controller resumes: each axis enabled and read. + Returns every axis's position.""" + axes = [self.axis(name) for name in ENABLE_ORDER[self.module_type]] + await self._unchecked_fw_enable(ENABLE_PREFIX[self.module_type]) + await self._unchecked_fw_stop_motion() + await self._unchecked_fw_enable(ENABLE_ORDER[self.module_type]) + replies = await self.board.send_many([p.get_current_position(a.device, a.index) for a in axes]) + return {a.name: p.parse_s32(r.payload) for a, r in zip(axes, replies)} + + # -- drive commands ---------------------------------------------------------- + # One request, or one batch sent together, each, as the Master Controller sends them. No checks + # and no bookkeeping: the public methods above decide when each is sent. + + async def _unchecked_fw_enable(self, axes: Sequence[str]) -> None: + """Set State ENABLED on each axis, sent together. On a drive in fault this is also the fault + reset; one that cannot come up answers an error and stays in fault.""" + if axes: + targets = [self.axis(name) for name in axes] + await self.board.send_many( + [p.set_state_enabled(a.device, a.index) for a in targets], + timeout=5.0 + ENABLE_SECONDS_PER_AXIS * len(targets), + ) + + async def _unchecked_fw_stop_motion(self) -> None: + """Stop Motion Service on this pod's board: stops every axis and drops pending moves.""" + await self.board.send(p.stop_motion_service()) + + async def _unchecked_fw_configure(self, axis: Axis) -> None: + """Load one axis's motor table (Configure). Leaves it disabled and not homed.""" + await self.board.send(p.configure(axis.device, axis.index, axis.configure)) + + async def _unchecked_fw_stop_module_execution(self) -> None: + await self.board.send(p.stop_module_execution()) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/lifecycle_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/lifecycle_tests.py new file mode 100644 index 00000000000..9d438edf10d --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/lifecycle_tests.py @@ -0,0 +1,380 @@ +"""Configure, the interlock, faults, pause / resume and stop, against the generic instrument +simulated: what the driver sends, and how it handles what the boards answer. Nothing here moves an +axis.""" + +import asyncio +import unittest +from typing import Any, Dict, List + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import SimulatedAceUSB +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_driver, + generic_recording, + generic_simulated_boards, +) + +MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master" +MODULES = ("chassis", "multichannel", "span8") +READ_ONLY_SETUP = dict(skip_device_initialization=True, skip_left_x_arm=True, skip_right_x_arm=True) + + +def zero_sequence(message: bytes) -> str: + return (message[:3] + b"\x00" + message[4:]).hex() + + +def name_of(message: bytes) -> str: + return p.COMMANDS[(message[0], message[4])] + + +class SimulatedTest(unittest.IsolatedAsyncioTestCase): + """A driver on the generic instrument simulated, and what each board was sent since a mark.""" + + marks: Dict[str, int] + + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) # the test loop's debug mode makes runs slow + + async def start(self, homed: Any = True, configured: Any = None) -> BiomekI7Driver: + driver = generic_driver(generic_simulated_boards(homed=homed, configured=configured)) + await driver.setup(**READ_ONLY_SETUP) + self.addAsyncCleanup(driver.stop) + self.marks = {} + self.mark(driver) + return driver + + async def start_initialized(self, homed: Any = True, configured: Any = None, **flags: Any): # type: ignore[no-untyped-def] + driver = await self.start(homed, configured) + await driver.initialize(**flags) + return driver + + def usb(self, driver: BiomekI7Driver, module: str) -> SimulatedAceUSB: + for board in driver.boards: + if board.name == f"simulated {module}": + assert isinstance(board.io, SimulatedAceUSB) + return board.io + raise KeyError(module) + + def mark(self, driver: BiomekI7Driver) -> None: + for module in MODULES: + self.marks[module] = len(self.usb(driver, module).requests) + + def sent(self, driver: BiomekI7Driver, module: str) -> List[bytes]: + return self.usb(driver, module).requests[self.marks[module] :] + + def names(self, driver: BiomekI7Driver, module: str) -> List[str]: + return [name_of(m) for m in self.sent(driver, module)] + + def written(self, driver: BiomekI7Driver) -> List[str]: + """Every request since the mark that is not a read.""" + return [ + name + for module in MODULES + for name in self.names(driver, module) + if not name.startswith(("Get ", "Read ", "List ")) + ] + + async def settle(self) -> None: + """Let the boards' read loops and the driver's background writes run.""" + for _ in range(5): + await asyncio.sleep(0.02) + + +class SimulatorRuleTests(SimulatedTest): + """The simulated boards answer as the instrument's did.""" + + async def test_an_axis_is_configured_before_it_takes_a_state(self) -> None: + driver = await self.start(homed=False, configured=False) + pod = driver.left_x_arm + assert pod is not None + with self.assertRaisesRegex(AceError, "not configured"): + await pod._unchecked_fw_enable(["Y"]) + await pod._unchecked_fw_configure(pod.axis("Y")) + self.assertEqual((await pod.request_axis_states())["Y"], "disabled") + self.assertEqual(await pod.request_homed_state("Y"), "not_homed") + + async def test_at_rest_cia402_drives_are_in_fault_and_refuse_enabling(self) -> None: + driver = await self.start() + left, right = driver.left_x_arm, driver.right_x_arm + assert left is not None and right is not None + self.assertEqual(set((await left.request_axis_states()).values()), {"fault"}) + self.assertEqual((await right.request_axis_states())["Z1"], "enabled") # a SAGIAN drive + with self.assertRaisesRegex(AceError, "interlock tripped"): + await left._unchecked_fw_enable(["X"]) + self.assertLess(await left.request_drive_supply(), 1.0) + + async def test_armed_the_supply_comes_up_and_enabling_resets_a_fault(self) -> None: + driver = await self.start() + left = driver.left_x_arm + assert left is not None and driver.chassis is not None + await driver.chassis.arm_interlock() + self.assertGreater(await left.request_drive_supply(), 30.0) + await left._unchecked_fw_enable(["X"]) + self.assertEqual((await left.request_axis_states())["X"], "enabled") + self.usb(driver, "multichannel").axis_model("Y").stuck_fault = True + with self.assertRaises(AceError) as caught: + await left._unchecked_fw_enable(["Y"]) + self.assertEqual(caught.exception.code, 0x3D) + + +class InitializeTests(SimulatedTest): + async def test_only_a_board_that_lost_its_tables_is_configured(self) -> None: + driver = await self.start_initialized( + homed={"multichannel": ["X"]}, configured={"multichannel": True, "span8": False} + ) + self.assertNotIn("Configure", self.names(driver, "multichannel")) + assert driver.right_x_arm is not None + self.assertEqual(self.names(driver, "span8").count("Configure"), len(driver.right_x_arm.axes)) + self.assertEqual( + self.names(driver, "chassis")[:3], + ["Trip Interlock", "Notify On Interlock Trip", "Set Status Display"], + ) + states = await driver.request_axis_states() + self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"}) + + async def test_configure_sends_what_the_recorded_cold_start_sent(self) -> None: + """Each pod's Configure requests, and the chassis's interlock requests before them and the + I/O box write after, are the ones the Master Controller sent at the cold start the generic + recording comes from, in its order.""" + driver = await self.start(homed=False, configured=False) + await driver.configure() + recording = generic_recording()["boards"] + for module in ("multichannel", "span8"): + recorded = [ + key for key, _ in recording[module] if key[6:8] == "10" and key[:2] in ("11", "12") + ] + sent = [(m[:3] + m[4:]).hex() for m in self.sent(driver, module) if name_of(m) == "Configure"] + self.assertEqual(sent, recorded, module) + self.assertEqual(self.names(driver, module)[-1], "Stop Module Execution") + chassis = [(m[:3] + m[4:]).hex() for m in self.sent(driver, "chassis")] + recorded_keys = {key for key, _ in recording["chassis"]} + self.assertEqual( + self.names(driver, "chassis"), + ["Trip Interlock", "Notify On Interlock Trip", "Set Status Display", "Send Digital I/O Box"], + ) + self.assertTrue(set(chassis) <= recorded_keys, set(chassis) - recorded_keys) + + async def test_drives_at_rest_are_in_fault_and_enabling_clears_it(self) -> None: + driver = await self.start() + with self.assertLogs(MASTER_LOGGER, "INFO") as logs: + await driver.initialize() + self.assertTrue(any("as at rest" in line for line in logs.output)) + self.assertFalse(any("collision" in line for line in logs.output)) + self.assertNotIn("Configure", self.written(driver)) + states = await driver.request_axis_states() + self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"}) + self.assertFalse(driver.interlock_tripped.is_set()) + + async def test_enabling_follows_the_master_controllers_order(self) -> None: + driver = await self.start() + await driver.arm_interlock() + left = [m for m in self.sent(driver, "multichannel") if name_of(m) == "Set State"] + assert driver.left_x_arm is not None + names = {(a.device, a.index): a.name for a in driver.left_x_arm.axes} + self.assertEqual( + [names[(m[0], m[1])] for m in left], ["Z", "GZ", "GR", "GY", "GG", "Z", "D", "X", "Y"] + ) + + async def test_a_fault_under_power_is_reset_with_a_warning(self) -> None: + driver = await self.start() + usb = self.usb(driver, "multichannel") + usb.interlock.armed = True # left armed, by an earlier session + for model in usb.axes.values(): + model.state = p.AxisState.ENABLED + usb.axis_model("Z").state = p.AxisState.FAULT + with self.assertLogs(MASTER_LOGGER, "WARNING") as logs: + await driver.initialize() + self.assertTrue(any(": Z in fault" in line and "collision" in line for line in logs.output)) + self.assertEqual(usb.axis_model("Z").state, p.AxisState.ENABLED) + + async def test_a_sagian_fault_is_warned_about_even_at_rest(self) -> None: + driver = await self.start() + self.usb(driver, "span8").axis_model("Z3").state = p.AxisState.FAULT + with self.assertLogs(MASTER_LOGGER, "WARNING") as logs: + await driver.initialize() + self.assertTrue(any("Z3" in line and "collision" in line for line in logs.output)) + + async def test_a_fault_that_does_not_clear_returns_the_instrument_to_rest(self) -> None: + driver = await self.start() + self.usb(driver, "multichannel").axis_model("Z").stuck_fault = True + with self.assertRaises(AceError): + await driver.initialize() + chassis = self.sent(driver, "chassis") + self.assertEqual([name_of(m) for m in chassis[-2:]], ["Trip Interlock", "Set Status Display"]) + self.assertEqual( + zero_sequence(chassis[-1]), zero_sequence(p.set_status_display("error").encode(1)) + ) + self.assertFalse(self.usb(driver, "chassis").interlock.armed) + self.assertTrue(driver.interlock_tripped.is_set()) + + async def test_a_drive_supply_that_stays_off_stops_it_before_enabling(self) -> None: + driver = await self.start() + self.usb(driver, "chassis").interlock.supply_comes_up = False + with self.assertRaisesRegex(RuntimeError, "drive supply"): + await driver.initialize() + self.assertNotIn("Set State", self.written(driver)) + self.assertFalse(self.usb(driver, "chassis").interlock.armed) + + async def test_an_open_door_does_not_stop_it(self) -> None: + driver = await self.start() + chassis_usb = self.usb(driver, "chassis") + chassis_usb.interlock.door_open = True + assert driver.chassis and driver.front_cover + self.assertEqual(await driver.front_cover.request_state(), "open") + await driver.initialize() # Biomek arms with the door open + self.assertEqual(await driver.chassis.request_interlock_state(), "armed") + + async def test_a_broken_light_curtain_stops_it(self) -> None: + driver = await self.start() + chassis_usb = self.usb(driver, "chassis") + chassis_usb.interlock.light_curtain_broken = True + with self.assertRaisesRegex(RuntimeError, "light curtain"): + await driver.initialize() + self.assertFalse(chassis_usb.interlock.armed) + + async def test_door_changes_are_reported_and_the_light_curtain_trips_the_interlock(self) -> None: + driver = await self.start_initialized() + assert driver.chassis and driver.front_cover + await driver.front_cover.notify_changes() + seen: List[str] = [] + driver.front_cover.subscribe(seen.append) + chassis_usb = self.usb(driver, "chassis") + chassis_usb.set_door(True) + await self.settle() + self.assertEqual(seen, ["open"]) + self.assertEqual(await driver.chassis.request_interlock_state(), "armed") + chassis_usb.set_door(False) + await self.settle() + self.assertEqual(seen, ["open", "closed"]) + with self.assertLogs(MASTER_LOGGER, "ERROR") as logs: + chassis_usb.set_light_curtain(True) + await self.settle() + self.assertIn("light curtain violation", "\n".join(logs.output)) + self.assertEqual(await driver.chassis.request_interlock_state(), "tripped") + self.assertTrue(driver.interlock_tripped.is_set()) + self.assertEqual( + zero_sequence(self.sent(driver, "chassis")[-2]), + zero_sequence(p.set_status_display("error").encode(1)), + ) + + async def test_skipping_configuration_leaves_unconfigured_pods_alone(self) -> None: + driver = await self.start(homed=False, configured=False) + await driver.initialize(skip_device_initialization=True) + self.assertEqual(self.written(driver), []) + + async def test_a_skipped_pod_is_left_alone(self) -> None: + driver = await self.start_initialized(skip_right_x_arm=True) + self.assertEqual([n for n in self.names(driver, "span8") if not n.startswith("Get ")], []) + self.assertIn("Set State", self.names(driver, "multichannel")) + + async def test_setup_brings_the_instrument_up_and_is_repeatable(self) -> None: + driver = generic_driver(generic_simulated_boards(homed=False)) + self.addAsyncCleanup(driver.stop) + await driver.setup() + states = await driver.request_axis_states() + self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"}) + await driver.setup() # configured already: not configured again + states = await driver.request_axis_states() + self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"}) + + +class PauseTests(SimulatedTest): + async def test_pause_trips_and_shows_paused_and_resume_re_arms(self) -> None: + driver = await self.start_initialized() + chassis_usb = self.usb(driver, "chassis") + self.mark(driver) + await driver.pause() + self.assertTrue(driver.paused) + self.assertFalse(chassis_usb.interlock.armed) + self.assertTrue(driver.interlock_tripped.is_set()) + self.assertEqual( + [zero_sequence(m) for m in self.sent(driver, "chassis")], + [ + zero_sequence(p.trip_interlock().encode(1)), + zero_sequence(p.set_status_display("paused").encode(1)), + ], + ) + with self.assertRaisesRegex(RuntimeError, "already paused"): + await driver.pause() + await driver.resume() + self.assertFalse(driver.paused) + self.assertTrue(chassis_usb.interlock.armed) + self.assertFalse(driver.interlock_tripped.is_set()) + states = await driver.request_axis_states() + self.assertEqual({s for pod in states.values() for s in pod.values()}, {"enabled"}) + + async def test_a_pause_is_not_an_error(self) -> None: + driver = await self.start_initialized() + with self.assertNoLogs(MASTER_LOGGER, "ERROR"): + await driver.pause() + await self.settle() + + async def test_a_broken_light_curtain_keeps_it_paused(self) -> None: + driver = await self.start_initialized() + chassis_usb = self.usb(driver, "chassis") + await driver.pause() + chassis_usb.set_light_curtain(True) + with self.assertRaisesRegex(RuntimeError, "light curtain"): + await driver.resume() + self.assertTrue(driver.paused) + self.assertFalse(chassis_usb.interlock.armed) + chassis_usb.set_light_curtain(False) + await driver.resume() + self.assertFalse(driver.paused) + self.assertTrue(chassis_usb.interlock.armed) + + async def test_pause_needs_an_armed_interlock(self) -> None: + driver = await self.start() + with self.assertRaisesRegex(RuntimeError, "not armed"): + await driver.pause() + with self.assertRaisesRegex(RuntimeError, "not paused"): + await driver.resume() + + +class FaultAndStopTests(SimulatedTest): + async def test_a_motor_failing_on_its_own_trips_the_interlock(self) -> None: + driver = await self.start_initialized() + assert driver.left_x_arm is not None + x = driver.left_x_arm.axis("X") + self.mark(driver) + with self.assertLogs(MASTER_LOGGER, "ERROR") as logs: + # A Move All's NOTICE for X with a following error, sequence 0: nobody asked. + self.usb(driver, "multichannel")._queue(bytes([x.device, x.index, 0, 0, 0x50, 0xFE, 0x3C])) + await self.settle() + self.assertIn("The left X motor failed", "\n".join(logs.output)) + self.assertEqual(self.names(driver, "chassis"), ["Trip Interlock", "Set Status Display"]) + self.assertEqual(self.sent(driver, "chassis")[1][5:], p.set_status_display("error").params) + self.assertTrue(driver.interlock_tripped.is_set()) + + async def test_a_trip_the_driver_made_is_not_an_error(self) -> None: + driver = await self.start_initialized() + self.mark(driver) + with self.assertNoLogs(MASTER_LOGGER, "ERROR"): + await driver.stop() + # The chassis's own trip event, after the driver's trip. + self.usb(driver, "chassis")._queue(bytes([p.Device.INTERLOCK, 1, 0, 0, 0x10, 0x03, 0, 0xFF])) + await self.settle() + + async def test_stop_leaves_the_instrument_at_rest(self) -> None: + driver = await self.start() + await driver.stop() # never armed: nothing is sent + self.assertEqual(self.written(driver), []) + driver = await self.start_initialized() + self.mark(driver) + await driver.stop() + for module in ("multichannel", "span8"): + self.assertEqual(self.names(driver, module), ["Stop Module Execution"]) + self.assertEqual( + [zero_sequence(m) for m in self.sent(driver, "chassis")], + [ + zero_sequence(p.trip_interlock().encode(1)), + zero_sequence(p.set_status_display("ready").encode(1)), + ], + ) + self.assertFalse(self.usb(driver, "chassis").interlock.armed) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index f7aeab409b6..75859505457 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -4,10 +4,19 @@ is not fixed by USB order or serial number, so setup opens every ACE device, asks each its module ID (its type, and an arm's side), and builds the chassis and a pod per arm from the answers. Only one program can hold an ACE board at a time: Biomek's Master Controller must not be running. + +At rest the interlock is tripped: the arms' drives have no motor power, and every CiA 402 drive +reads FAULT. That is how the Master Controller leaves the instrument (its drive supply polls read +off over 90% of the time), so it is not an error here. Bringing the instrument up arms the +interlock and enables every axis, which is each faulted drive's reset, as Biomek does; a fault +that does not clear stops it before anything moves. When anything fails once the interlock is +armed, the driver shows ERROR and trips the interlock; `stop` trips it too, as the Master +Controller's logs show it doing. """ +import asyncio import logging -from typing import Dict, List, Optional, Sequence, Tuple, Union +from typing import Awaitable, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import ( @@ -19,12 +28,34 @@ DeviceConfiguration, ModuleConfiguration, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis +from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod from pylabrobot.io.usb import USB logger = logging.getLogger(__name__) +# A pod's drive supply ("+36V Interlock") reads about 35-36 V with the interlock armed and 0.1-0.16 +# V tripped (Master Controller polls, 2026-07 to 10). Above this it counts as on. +DRIVE_SUPPLY_ON_VOLTS = 30.0 + +# How long returning to rest may take, in seconds: two requests to the chassis. +REST_TIMEOUT = 5.0 + + +async def _together(aws: Iterable[Awaitable[object]]) -> None: + """Run the pods' work at once. If one fails, the others are cancelled and waited for before the + error is raised, so nothing is left sending to a board behind the caller's back.""" + tasks = [asyncio.ensure_future(a) for a in aws] + try: + await asyncio.gather(*tasks) + except BaseException: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + raise + def find_ace_boards() -> Dict[str, int]: """Every ACE board attached: its USB serial number and current USB address. @@ -90,6 +121,15 @@ def __init__( self._given_boards = list(boards) if boards is not None else None self.boards: List[AceBoard] = [] self._connected = False + self._armed = False # this driver armed the interlock, and has not tripped it since + self._tripping = False # this driver is tripping it: the chassis's trip event is our own + self._paused = False # paused (`pause`), waiting for `resume` + # Set while the interlock is tripped as far as this driver knows: from the start, when the + # chassis reports a trip, or when this driver trips it; cleared when it arms it. + self.interlock_tripped = asyncio.Event() + self.interlock_tripped.set() + self._unwatch: List[Callable[[], None]] = [] + self._background: Set["asyncio.Task[None]"] = set() self.chassis: Optional[Chassis] = None # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, Feature map). self.left_x_arm: Optional[Pod] = None @@ -97,23 +137,45 @@ def __init__( # -- lifecycle ------------------------------------------------------------- - async def setup(self) -> None: - """Connect to the instrument and find out what it is. Reads only: nothing is written to a - board and nothing moves. Repeatable: the boards stay open, and discovery reads them again. A - setup that fails part way releases the boards. + async def setup( + self, + skip_device_initialization: bool = False, + *, + skip_left_x_arm: bool = False, + skip_right_x_arm: bool = False, + ) -> None: + """Connect to the instrument, find out what it is, and bring it up. + + `discover` is the read-only part; then the motor tables are loaded where a board has lost them, + the interlock is armed and every axis enabled. Nothing moves: the drives hold where they stand. + With every skip below set, setup only reads. Repeatable: the boards stay open and discovery + reads them again. A setup that fails part way releases the boards. + + Args: + skip_device_initialization: do not load motor tables, even into a board that has lost them. + A pod with an axis not configured is then left as it is. + skip_left_x_arm: leave the left pod as it is: not configured or enabled. + skip_right_x_arm: leave the right pod as it is. Raises: - RuntimeError: if no chassis is found, or a board cannot be placed (`discover`). + RuntimeError: if no chassis is found, a board cannot be placed (`discover`), or the + interlock or a drive supply does not come up. ValueError: for a declared configuration that is not this instrument's (`discover`). + AceError: if an axis cannot be enabled; the interlock is then tripped and ERROR shown. """ logger.warning( - "The Biomek i7 driver's discovery has run on one instrument; it is untested on other " - "instruments. Please report what works and what does not." + "The Biomek i7 driver's discovery, configuration and interlock have run on one instrument; " + "they are untested on other instruments. Please report what works and what does not." ) if not self._connected: await self._open() try: await self.discover() + await self.initialize( + skip_device_initialization=skip_device_initialization, + skip_left_x_arm=skip_left_x_arm, + skip_right_x_arm=skip_right_x_arm, + ) except BaseException: await self.stop() raise @@ -199,6 +261,7 @@ async def discover(self) -> None: if "right" in places else None ) + self._watch_faults() modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())] for pod in self.arms: modules.append((str(pod), await pod.discover())) @@ -318,7 +381,23 @@ def _serial_numbers_found(self) -> Dict[str, Optional[str]]: return found async def stop(self) -> None: - """Release every board. Writes nothing and moves nothing.""" + """Return the instrument to rest and release every board. Moves nothing. + + If this driver armed the interlock, as the Master Controller does when its host goes away: each + pod's module is stopped (Stop Module Execution), then the interlock is tripped and READY shown. + Otherwise nothing is written. What the boards do on their own when the host goes away is not + known. + """ + if self._armed: + for pod in self.arms: + try: + await asyncio.wait_for(pod._unchecked_fw_stop_module_execution(), REST_TIMEOUT) + except BaseException: + logger.exception("could not stop %s", pod) + await self._return_to_rest() + for unwatch in self._unwatch: + unwatch() + self._unwatch = [] for board in self.boards: try: await board.stop() @@ -365,3 +444,293 @@ def arm(self, name: Union[str, int]) -> Pod: if name in (pod.side, pod.pod_number, f"Pod{pod.pod_number}", pod.component): return pod raise KeyError(f"no pod {name!r}; have {[(p.side, p.component) for p in self.arms]}") + + @property + def front_cover(self) -> Optional[Door]: + """The door, by STAR's name for it, once discovery has found the chassis.""" + return None if self.chassis is None else self.chassis.front_cover + + async def request_axis_states(self) -> Dict[str, Dict[str, p.AxisStateName]]: + """Every axis's state, by pod side then axis name. Moves nothing.""" + return {pod.side: await pod.request_axis_states() for pod in self.arms} + + # -- configuration and interlock ------------------------------------------------ + # These write to the boards. Run them only on a clear deck, with someone at the emergency stop. + + def _require_chassis(self) -> Chassis: + if self.chassis is None: + raise RuntimeError("no chassis; call `setup()` first") + return self.chassis + + def skipped_sides( + self, *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False + ) -> Set[str]: + """The sides (`"left"`, `"right"`) a setup with these skips leaves as they are.""" + return {s for s, skip in (("left", skip_left_x_arm), ("right", skip_right_x_arm)) if skip} + + async def initialize( + self, + skip_device_initialization: bool = False, + *, + skip_left_x_arm: bool = False, + skip_right_x_arm: bool = False, + ) -> None: + """Bring the instrument up: what `setup` does after discovery. + + Reads every axis's state first. A pod with an axis not configured (the board was powered up, or + a drive lost its parameters) has its motor tables loaded; one fully configured does not, since + loading them again would un-home it. Then the interlock is armed and every axis enabled + (`arm_interlock`). The arguments are those of `setup`. + + An axis in fault is not refused: enabling it is its fault reset, as when Biomek re-arms and + enables after a fault, and calling this is the person's go-ahead that Biomek waits for. A CiA + 402 drive in fault with its motor supply off is the instrument at rest and is only noted; any + other fault is warned about, since under power it usually means a following error or a + collision. A fault that does not clear fails the enable, and the instrument is returned to rest. + + Raises: + RuntimeError: if the interlock or a drive supply does not come up when armed. + AceError: if an axis cannot be enabled; the interlock is then tripped and ERROR shown. + """ + skipped = self.skipped_sides(skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm) + pods = [pod for pod in self.arms if pod.side not in skipped] + if skip_device_initialization and not pods: + return + + states = await self.request_axis_states() + for pod in pods: + faulted = [name for name, state in states[pod.side].items() if state == "fault"] + if not faulted: + continue + supply = await pod.request_drive_supply() + at_rest = supply < DRIVE_SUPPLY_ON_VOLTS and all( + pod.axis(name).drive == "cia402" for name in faulted + ) + if at_rest: + logger.info("%s: %s in fault with the drive supply off (%.1f V), as at rest", pod, + ", ".join(faulted), supply) # fmt: skip + else: + positions = await pod.request_positions() + logger.warning( + "%s: %s in fault with the drive supply at %.1f V; enabling will reset them. A fault under " + "power usually means a following error or a collision: check the deck. Positions: %s", + pod, + ", ".join(faulted), + supply, + {name: positions[name] for name in faulted}, + ) + + unconfigured = [pod for pod in pods if "not_configured" in states[pod.side].values()] + if unconfigured and skip_device_initialization: + logger.warning( + "%s not configured, and configuring was skipped; left as they are, and they cannot move", + ", ".join(str(pod) for pod in unconfigured), + ) + pods = [pod for pod in pods if pod not in unconfigured] + unconfigured = [] + if unconfigured: + await self.configure(unconfigured) + if pods: + try: + await self.arm_interlock(pods) + except BaseException: + await self._return_to_rest(error=True) + raise + + # A pod that answered every request is not a pod that came up, so each is asked again. + states = await self.request_axis_states() + down = [ + f"{pod.side} {name} ({state})" + for pod in pods + for name, state in states[pod.side].items() + if state != "enabled" + ] + if down: + logger.warning("initialize finished with these axes not enabled: %s", ", ".join(down)) + + async def configure(self, pods: Optional[Sequence[Pod]] = None) -> None: + """Load the motor tables into pods' boards (every pod by default), as after a power-up. Moves + nothing. + + A board keeps its tables until it loses power. Loading them into a configured board is + accepted, and leaves every axis disabled and not homed, so this un-homes + the pods; `initialize` loads them only where an axis is not configured. + """ + chassis = self._require_chassis() + await chassis.prepare_interlock() + for pod in self.arms if pods is None else pods: + await pod.configure() + await chassis._io_box_write_after_configure() + + async def arm_interlock(self, pods: Optional[Sequence[Pod]] = None) -> None: + """Arm the interlock, check the pods' drive supply came up, then enable every axis of pods + (every pod by default). Enabling resets a drive's fault. Moves nothing: the drives hold where + they stand. + + The door does not take part: Biomek arms with it open, and opening it does not trip the + interlock (Biomek's logs); only its state is logged. + + Raises: + RuntimeError: if the interlock does not arm (the light curtain broken), or a pod's drive + supply stays off. + AceError: if an axis cannot be enabled. + """ + targets = self.arms if pods is None else list(pods) + chassis = self._require_chassis() + if await chassis.front_cover.request_state() == "open": + logger.info("arming the interlock with the door open (the door does not trip it)") + self._armed = True # before the request: a re-arm that times out may still have armed it + self.interlock_tripped.clear() + await chassis.arm_interlock() + state = await chassis.request_interlock_state() + if state != "armed": + raise RuntimeError(f"the interlock reads {state} after re-arming") + for pod in targets: + supply = await pod.request_drive_supply() + if supply < DRIVE_SUPPLY_ON_VOLTS: + raise RuntimeError(f"{pod}: the drive supply reads {supply:.1f} V with the interlock armed") + await _together(pod.enable_axes() for pod in targets) + + async def _return_to_rest(self, error: bool = False) -> None: + """Trip the interlock, if this driver armed it, and show READY (ERROR with `error`). Never + raises: it runs on the way out of a failure.""" + if not self._armed: + return + await self._trip(error) + + async def _trip(self, error: bool) -> None: + """Trip the interlock and show READY or ERROR. Never raises.""" + if self.chassis is None: + return + self._tripping = True + try: + await asyncio.wait_for(self.chassis.trip_interlock(error=error), REST_TIMEOUT) + self._armed = False + self.interlock_tripped.set() + except BaseException: + logger.exception( + "could not trip the interlock; the drives may still be powered: use the E-stop" + ) + finally: + self._tripping = False + + # -- pause for access -------------------------------------------------------------- + # Biomek's whole-system pause, as its logs show it: a deliberate interlock trip with PAUSED shown; + # resuming re-arms and enables every axis. There is no mute: the light curtain may be broken only + # because the drives have no power. + + @property + def paused(self) -> bool: + """Whether the instrument is paused (`pause`), waiting for `resume`.""" + return self._paused + + async def pause(self) -> None: + """Pause for access: cut the pods' drive power and show PAUSED, so the light curtain may be + broken without an error. Call it between operations, as Biomek's Pause step runs between + steps. + + Raises: + RuntimeError: if the interlock is not armed by this driver (nothing to pause), or the + instrument is already paused. + """ + if self._paused: + raise RuntimeError("the instrument is already paused") + if not self._armed: + raise RuntimeError("the interlock is not armed: nothing to pause") + chassis = self._require_chassis() + self._tripping = True + try: + await chassis._unchecked_fw_trip_interlock() + self._armed = False + self.interlock_tripped.set() + finally: + self._tripping = False + await chassis._unchecked_fw_set_status_display("paused") + self._paused = True + logger.info("paused: the interlock is tripped; the light curtain may be broken") + + async def resume(self) -> None: + """Resume after `pause`: re-arm the interlock and enable every axis. Nothing is homed. + + Raises: + RuntimeError: if not paused, or if the interlock does not arm (the light curtain still + broken): the instrument stays paused, so clear it and call `resume` again. + """ + if not self._paused: + raise RuntimeError("the instrument is not paused") + try: + await self.arm_interlock() + except BaseException: + self._armed = False + self.interlock_tripped.set() + raise + self._paused = False + logger.info("resumed: the interlock is armed") + + # -- faults the boards report unasked ------------------------------------------ + # As the Master Controller handles them, as its logs show it. + + def _watch_faults(self) -> None: + """Listen for the chassis reporting the interlock tripped and the pods reporting a motor that + failed on its own (both arrive unasked, sequence 0).""" + for unwatch in self._unwatch: + unwatch() + self._unwatch = [] + if self.chassis is not None: + self._unwatch.append(self.chassis.board.subscribe(self._on_chassis_message)) + for pod in self.arms: + self._unwatch.append(pod.board.subscribe(self._pod_watcher(pod))) + + def _pod_watcher(self, pod: Pod) -> Callable[[p.Reply], None]: + return lambda reply: self._on_pod_message(pod, reply) + + def _on_chassis_message(self, reply: p.Reply) -> None: + """The interlock tripped (Notify On Interlock Trip): the light curtain broken, or a trip by + the host.""" + if reply.status == p.Status.EVENT and (reply.device, reply.opcode) == p.INTERLOCK_TRIPPED: + self._interlock_tripped("A light curtain violation has occurred.") + + def _on_pod_message(self, pod: Pod, reply: p.Reply) -> None: + """A motor's Move All ended in an error nobody was waiting for: the Master Controller trips + the interlock with "The motor failed: ." (an interlock trip itself is + reported by the chassis instead).""" + if not ( + reply.opcode == 0x50 + and reply.status == p.Status.NOTICE + and reply.device in (p.Device.MOTOR, p.Device.PUMP) + and reply.error_code is not None + and reply.error_code != INTERLOCK_TRIPPED_CODE + ): + return + names = {(a.device, a.index): a.name for a in pod.axes} + axis = names.get((reply.device, reply.index), f"device 0x{reply.device:02X} {reply.index}") + error = ace_error(reply.error_code, reply.device_error, f"{pod} {axis}") + logger.error("The %s %s motor failed: %s.", pod.side, axis, error) + self.interlock_tripped.set() + self._in_background(self._trip(error=True)) + + def _interlock_tripped(self, reason: str) -> None: + """What the Master Controller does when the interlock trips under a running instrument: waits + end, and ERROR is shown. A trip this driver made itself (at rest, or after a failure) only marks + it tripped.""" + ours = self._tripping or not self._armed + self.interlock_tripped.set() + if ours: + return + logger.error("the interlock tripped: %s", reason) + self._armed = False + if self.chassis is not None: + self._in_background(self.chassis._unchecked_fw_set_status_display("error")) + + def _in_background(self, coroutine: Awaitable[None]) -> None: + """Run a board write from a message handler, which cannot wait; its failure is logged.""" + + async def run() -> None: + try: + await coroutine + except Exception: + logger.exception("after a fault the boards reported") + + task = asyncio.get_running_loop().create_task(run()) + self._background.add(task) + task.add_done_callback(self._background.discard) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py new file mode 100644 index 00000000000..e338b229eab --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py @@ -0,0 +1 @@ +"""The Master Controller's multi-step host commands, as the pods run them: `homing.py`.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py new file mode 100644 index 00000000000..028126699fc --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py @@ -0,0 +1,19 @@ +"""Bringing a pod's axes up, as the Master Controller does it. + +Enabling (after the interlock is armed, or a fault): the Master Controller enables a pod's axes in a +fixed order, and on the Multichannel first its Z alone, then stops motion; this order, as its logs +show it, is what `Pod.enable_axes` sends. +""" + +from typing import Dict, Tuple + +# The order the Master Controller enables every axis in after the interlock is armed, and reads +# their positions in. The Multichannel board is sent one Z enable first. +ENABLE_ORDER: Dict[str, Tuple[str, ...]] = { + "multichannel": ("GZ", "GR", "GY", "GG", "Z", "D", "X", "Y"), + "span8": ( + "GR", "GG", "GZ", "D8", "GY", "D6", "D7", "D4", "D5", "D2", "D3", "Z8", "D1", "Z6", "Z7", + "Z4", "Z5", "Z2", "Z3", "Y8", "Z1", "Y6", "Y7", "Y4", "Y5", "Y2", "Y3", "X", "Y1", + ), +} # fmt: skip +ENABLE_PREFIX: Dict[str, Tuple[str, ...]] = {"multichannel": ("Z",), "span8": ()} diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py index 357375452b9..274a0a74f41 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -1,26 +1,34 @@ -"""Simulated boards: boards that answer from what a real Biomek i7's boards answered. +"""Simulated instruments: boards that answer from what a real Biomek i7's boards answered. -`ReplayAceUSB` replays a recording; nothing it does reaches a USB device. A replayed board holds a -recording of request -> replies, keyed on everything in a request but its sequence number, and -answers a request it has a recording for with those replies under the request's sequence number. -A request it has no recording for gets no answer, as a board that ignored it would, and is kept in -`unanswered`. +`ReplayAceUSB` only replays a recording. `SimulatedAceUSB` also models each axis's state and the +interlock, so configuring, arming and enabling can run against it; nothing it does reaches a USB +device. + +A replayed board holds a recording of request -> replies, keyed on everything in a request +but its sequence number, and answers a request it has a recording for with those replies under +the request's sequence number. A request it has no recording for gets no answer, as a board that +ignored it would, and is kept in `unanswered`. """ import asyncio import gzip import json import os +import struct +from dataclasses import dataclass from pathlib import Path -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, MotorTables +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import AxisState, Device from pylabrobot.io.usb import USB # Names the recording the simulator answers from (identity and sensor reads, recorded at an # instrument's cold start) when no path is given. A generic one ships in `defaults/` -# (`biomek_i7_generic_coldstart.json`). +# (`biomek_i7_generic_coldstart.json`), which `BiomekI7(simulation=True)` uses when neither is +# given. RECORDING_ENV = "BIOMEK_I7_SIMULATOR_RECORDING" @@ -101,3 +109,226 @@ def replay_boards( ) for module, entries in data["boards"].items() ] + + +class SimulatedAceUSB(ReplayAceUSB): + """One board's USB link, answered from a model of its axes rather than only a recording. + + Each axis has a state (`AxisState`), is homed or not, and has a position, by the boards' rules: + an axis starts not configured; Configure leaves it disabled and not homed; Set State is refused + "not configured" before that. Identity and sensor reads are answered from the recording. + + The boards of one instrument share an `Interlock`. While it is tripped, as at rest, a CiA 402 + axis that was enabled reads FAULT (its drive lost motor power: H1, 2026-10-27; one configured at + rest reads DISABLED, as on H2 the same day), its enable fails, and the arm's drive supply + input reads 0.12 V; armed, 35.4 V. + Enabling a CiA 402 axis in fault resets it, unless it was given a fault that + does not clear (`_AxisModel.stuck_fault`). The error codes of a failed enable are not known; the + model answers "interlock tripped" without power and 0x3D for a stuck fault. + """ + + def __init__( + self, + recording: Dict[str, List[str]], + axes: Sequence[Axis] = (), + homed: Iterable[str] = (), + name: str = "simulated ACE board", + configured: bool = False, + interlock: Optional["Interlock"] = None, + supply_input: Optional[int] = None, + door_input: Optional[int] = None, + ): + super().__init__(recording, name=name) + self.door_input = door_input + homed = set(homed) + if homed and not configured: + raise ValueError("an axis cannot be homed on a board that is not configured") + self.interlock = interlock or Interlock() + self.supply_input = supply_input + self.axes: Dict[Tuple[int, int], _AxisModel] = {} + for a in axes: + # At rest a configured instrument's SAGIAN axes read ENABLED, as on 2026-10-27; CiA 402 + # axes read FAULT while the interlock is tripped (`_apply_power`). + state = AxisState.ENABLED if configured else AxisState.NOT_CONFIGURED + self.axes[(a.device, a.index)] = _AxisModel(a.name, a.name in homed, state, a.drive) + + def _apply_power(self) -> None: + """An enabled CiA 402 drive faults when its motor power goes. One configured with the power + already off stays DISABLED (H2, 2026-10-27: every axis read DISABLED after the Master + Controller's Configure at rest).""" + if self.interlock.armed: + return + for model in self.axes.values(): + if model.drive == "cia402" and model.state == AxisState.ENABLED: + model.state = AxisState.FAULT + + def set_door(self, open_: bool) -> None: + """Open or close the door, on the chassis's link: the door sensor reports the change; the + interlock is not affected (as in Biomek's logs).""" + self.interlock.door_open = open_ + self._queue( + bytes([Device.DIGITAL_INPUT, self.door_input or 1, 0, 0, 0x10, 0x03, 0, int(not open_)]) + ) + + def set_light_curtain(self, broken: bool) -> None: + """Break or clear the light curtain: breaking it trips an armed interlock, which reports it + (Notify On Interlock Trip); while broken, the interlock does not arm.""" + self.interlock.light_curtain_broken = broken + if broken and self.interlock.armed: + self.interlock.armed = False + self._queue(bytes([Device.INTERLOCK, 1, 0, 0, 0x10, 0x03, 0, 0xFF])) + + def axis_model(self, name: str) -> "_AxisModel": + for model in self.axes.values(): + if model.name == name: + return model + raise KeyError(name) + + def answer(self, message: bytes) -> Optional[List[bytes]]: + device, index, opcode, params = message[0], message[1], message[4], message[5:] + header = message[:5] + done = header + b"\x02\x00" + tripped = header + b"\x00\x0f" + self._apply_power() + if device == Device.ANALOG_INPUT and opcode == 0x10 and index == self.supply_input: + powered = self.interlock.armed and self.interlock.supply_comes_up + return [done + struct.pack(" None: + framed = frame(message) + for i in range(0, len(framed), 16): + self._packets.put_nowait(framed[i : i + 16]) + + +@dataclass +class Interlock: + """The interlock one instrument's simulated boards share. `supply_comes_up=False` models an + interlock that arms while the drive supply stays off.""" + + armed: bool = False + supply_comes_up: bool = True + door_open: bool = False + light_curtain_broken: bool = False + + +@dataclass +class _AxisModel: + name: str + homed: bool + state: AxisState = AxisState.NOT_CONFIGURED + drive: str = "cia402" + stuck_fault: bool = False + position: int = 0 + + +# The analog input carrying the interlocked drive supply, per module (the Master Controller's cold +# start: "+36V Interlocked" is the chassis's input 5, "+36V Interlock" each arm's input 4). +SUPPLY_INPUTS = {"chassis": 5, "multichannel": 4, "span8": 4} +# The chassis's digital input 1 is "Door Sensor". +DOOR_INPUTS = {"chassis": 1} + + +def simulated_boards( + motor_tables: MotorTables, + homed: Union[bool, Dict[str, Iterable[str]]] = False, + path: Optional[Union[str, Path]] = None, + default_timeout: float = 1.0, + configured: Optional[Union[bool, Dict[str, bool]]] = None, +) -> List[AceBoard]: + """A simulated instrument as `BiomekI7Driver(boards=...)` takes it: the recorded chassis, a left + Multichannel and a right Span-8 pod. + + Args: + motor_tables: the axes to model: the declared configuration's + (`DeviceConfiguration.motor_tables`), the one the driver is given. + homed: True for every axis homed, False for none, or the homed axes' names per arm type. + path: the recording that answers identity and sensor reads (`recording_path`). + configured: whether each arm's board has its motor tables, as one value or per arm type. + Defaults to configured wherever an axis is homed, and not configured (just powered up) + otherwise. + """ + tables = motor_tables + data = load_recording(path) + interlock = Interlock() + boards = [] + for module, entries in data["boards"].items(): + axes = tables.axes(module) if module in tables.modules else [] + if isinstance(homed, bool): + homed_axes: Iterable[str] = [a.name for a in axes] if homed else [] + else: + homed_axes = homed.get(module, []) + homed_axes = list(homed_axes) + if configured is None: + is_configured = bool(homed_axes) + elif isinstance(configured, bool): + is_configured = configured + else: + is_configured = configured.get(module, False) + usb = SimulatedAceUSB( + dict(entries), + axes, + homed_axes, + name=f"simulated {module}", + configured=is_configured, + interlock=interlock, + supply_input=SUPPLY_INPUTS.get(module), + door_input=DOOR_INPUTS.get(module), + ) + boards.append(AceBoard(io=usb, name=f"simulated {module}", default_timeout=default_timeout)) + return boards diff --git a/pylabrobot/beckman_coulter/biomek_i7/session_log.py b/pylabrobot/beckman_coulter/biomek_i7/session_log.py new file mode 100644 index 00000000000..3bca1a33eb8 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/session_log.py @@ -0,0 +1,88 @@ +"""A run's log in a file of its own, to compare a live run with Biomek's logs of the same work. + +`start_session_log(directory)` writes every line of this package's loggers to +`/biomek_i7_.log`: the driver's commands, warnings and errors, and with +`usb_frames` every message to and from the boards, unframed and in +hex, which is what Biomek's Master Controller keeps in its `ace_io` table. Each line starts with +the time in milliseconds since the epoch, as the Master Controller's tables stamp theirs. + +PyLabRobot's own `pylabrobot.setup_logger` writes one file per day for every PyLabRobot logger; +this one is per run and holds only the Biomek i7's lines, so one run reads on its own. +""" + +import datetime +import logging +from pathlib import Path +from typing import Optional, Union + +PACKAGE_LOGGER = "pylabrobot.beckman_coulter.biomek_i7" +LINE_FORMAT = "%(created_ms)d %(asctime)s.%(msecs)03d %(name)s %(levelname)s %(message)s" +DATE_FORMAT = "%Y-%m-%d %H:%M:%S" + + +class _EpochMilliseconds(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + record.created_ms = int(record.created * 1000) + return super().format(record) + + +class SessionLog: + """A session log being written; `stop()` closes it.""" + + def __init__(self, path: Path, handler: logging.Handler): + self.path = path + self._handler = handler + + def stop(self) -> None: + """Stop writing the log and close its file.""" + logging.getLogger(PACKAGE_LOGGER).removeHandler(self._handler) + self._handler.close() + + def __enter__(self) -> "SessionLog": + return self + + def __exit__(self, *exc) -> None: + self.stop() + + +def start_session_log( + directory: Union[str, Path], + usb_frames: bool = True, + name: Optional[str] = None, +) -> SessionLog: + """Start writing this package's log lines to a new timestamped file in `directory`. + + The package's loggers are set to log at DEBUG (with `usb_frames`) or INFO, and any of its + loggers set higher is reset to follow the package's level, so every line reaches the file. What + a console shows is up to the console's own handler and its level. + + Args: + directory: where to write the log; made if missing. + usb_frames: also write every message to and from the boards (DEBUG lines ` write ` + and ` read `). + name: the file's name; default `biomek_i7_.log`. + + Returns: + The log being written; `.path` is its file. + """ + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + path = directory / (name or f"biomek_i7_{stamp}.log") + handler = logging.FileHandler(path, encoding="utf-8") + handler.setLevel(logging.NOTSET) + handler.setFormatter(_EpochMilliseconds(LINE_FORMAT, DATE_FORMAT)) + + level = logging.DEBUG if usb_frames else logging.INFO + package = logging.getLogger(PACKAGE_LOGGER) + package.setLevel(level) + for logger_name, logger in logging.root.manager.loggerDict.items(): + if ( + logger_name.startswith(PACKAGE_LOGGER + ".") + and isinstance(logger, logging.Logger) + and logger.level > level + ): + logger.setLevel(logging.NOTSET) + package.addHandler(handler) + package.info("session log started: %s (USB frames %s)", path, "on" if usb_frames else "off") + return SessionLog(path, handler) diff --git a/pylabrobot/beckman_coulter/biomek_i7/session_log_tests.py b/pylabrobot/beckman_coulter/biomek_i7/session_log_tests.py new file mode 100644 index 00000000000..d91626bd110 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/session_log_tests.py @@ -0,0 +1,49 @@ +"""A session log holds the driver's commands and, at DEBUG, every message to and from the boards.""" + +import asyncio +import re +import tempfile +import unittest +from pathlib import Path + +from pylabrobot.beckman_coulter.biomek_i7.session_log import start_session_log +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_driver, + generic_simulated_boards, +) + + +class SessionLogTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + + async def run_setup(self) -> None: + driver = generic_driver(generic_simulated_boards()) # just powered up: configured at setup + await driver.setup() + await driver.stop() + + async def test_a_run_is_logged_with_its_frames(self) -> None: + with tempfile.TemporaryDirectory() as directory: + log = start_session_log(directory) + try: + await self.run_setup() + finally: + log.stop() + lines = Path(log.path).read_text(encoding="utf-8").splitlines() + self.assertTrue(Path(log.path).name.startswith("biomek_i7_")) + self.assertTrue(all(re.match(r"\d{13} ", line) for line in lines)) + self.assertTrue(any(" MC_1 configure" in line for line in lines)) + self.assertTrue(any(re.search(r" write [0-9a-f]+$", line) for line in lines)) + self.assertTrue(any(re.search(r" read [0-9a-f]+$", line) for line in lines)) + + async def test_info_only_leaves_out_the_frames(self) -> None: + with tempfile.TemporaryDirectory() as directory: + with start_session_log(directory, usb_frames=False) as log: + await self.run_setup() + text = Path(log.path).read_text(encoding="utf-8") + self.assertIn(" SPAN8_2 configure", text) + self.assertNotIn(" write ", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py index dc56c661fa4..383804b7c66 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -13,7 +13,7 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver -from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB, simulated_boards _GENERIC: Optional[Dict[str, Any]] = None @@ -89,6 +89,14 @@ def configuration_file(configuration: DeviceConfiguration) -> str: return str(path) +def generic_simulated_boards(**kwargs: Any) -> List[AceBoard]: + """The generic instrument simulated (`simulator.simulated_boards`), with the generic + configuration's motor tables and the generic cold start; `kwargs` as `simulated_boards` takes + them (`homed`, `configured`).""" + kwargs.setdefault("path", GENERIC_RECORDING) + return simulated_boards(generic_configuration().motor_tables, **kwargs) + + def generic_driver( boards: Optional[Sequence[AceBoard]] = None, configuration: Optional[DeviceConfiguration] = None, From f14bdc112107b5f11a94c4ff07a385a6c5f7dd45 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:27:59 -0800 Subject: [PATCH 12/28] `Biomek i7`: Home All, coordinated moves, and the rail and self-collision guards Moves in counts, planned as Biomek's Master Controller plans them, with the guards from the first X move: - `driver/motion.py`: the `AM` plan (each axis's speeds so all arrive together, jerk-corrected S-curves, the Move All timeout), the position record (position, adjusted) and the Span-8 Z channels' hysteresis, the order of the per-axis requests; checked against Biomek's logged moves. - `driver/recipes/homing.py`: Home All per arm type, every request as Biomek's logs show it, homed axes kept or homed again (`force`). - `driver/features/pod.py`: `move_axes` (positions read where unknown, force limits, sensor stops), `home`, `park`, `move_aside`, travel at a traverse height (`move_over`, `lift_channels`). - `driver/x_rail.py`, `driver/pod_geometry.py`: the shared X rail; a move into the other pod's range is refused before anything is sent, one crossing only its running move's path waits. - `driver/pod_collision.py`: the gripper (and what it holds) against its own pod's pipettor. - `driver/master.py`: `home`, homing in `initialize` and `setup`, a pod left out whose X is not homed refuses moves beside it, `move_axes` for both pods together, `resume` moving the pods back; positions forgotten on a trip, a failed move, `stop` and `pause`. - `driver/simulator.py`: positions, moves, homes and linked homes, force and sensor stops, and moves taking the instrument's time (`time_scale`). Tests: a cold Home All sends, on each pod's board, the requests the Master Controller sent at the cold start the generic recording was made from, first sent in its order; a forced Home All of a homed instrument as Biomek's logs show it; logged `AM` moves inline; the rail and self-collision guards; moves, homing, park, the position record; faults and positions. --- .../beckman_coulter/biomek_i7/design.md | 13 + .../biomek_i7/driver/configuration.py | 7 +- .../biomek_i7/driver/fault_tests.py | 60 ++ .../biomek_i7/driver/features/pod.py | 912 +++++++++++++++++- .../biomek_i7/driver/homing_tests.py | 328 +++++++ .../biomek_i7/driver/master.py | 240 ++++- .../biomek_i7/driver/motion.py | 395 ++++++++ .../biomek_i7/driver/motion_tests.py | 329 +++++++ .../biomek_i7/driver/motors.py | 22 +- .../biomek_i7/driver/pod_collision.py | 279 ++++++ .../biomek_i7/driver/pod_collision_tests.py | 104 ++ .../biomek_i7/driver/pod_geometry.py | 371 +++++++ .../biomek_i7/driver/pod_move_tests.py | 180 ++++ .../biomek_i7/driver/pod_tests.py | 141 +++ .../biomek_i7/driver/recipes/__init__.py | 2 +- .../biomek_i7/driver/recipes/homing.py | 331 ++++++- .../biomek_i7/driver/simulator.py | 176 +++- .../biomek_i7/driver/x_rail.py | 219 +++++ .../biomek_i7/driver/x_rail_tests.py | 244 +++++ .../biomek_i7/simulation_tests_support.py | 5 +- 20 files changed, 4266 insertions(+), 92 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/motion.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/motion_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_move_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index a74397bc096..0e9d2b98c84 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -58,3 +58,16 @@ features send through it. `driver.arm(name)` also takes Biomek's names (`1`, `"P move and leaves it as it found it. `stop()` moves nothing (Biomek stops in place). `pause` / `resume` is Biomek's whole-system pause. A fault under power is cleared by enabling, with a warning; one that will not clear trips the interlock. The door only reports: it has no interlock of its own. + +**I6. Positions are kept as the MC keeps them.** Each axis has `(position, adjusted)`; moves are +planned from where the driver last put the axis, not from a read. An axis whose position is unknown +(after homing, a force-limited move or a failure) is read before its next move. That, and sending +each move's requests in the MC's order, keeps the traffic request for request the MC's. Home All is +the MC's recipe (`driver/recipes/homing.py`), its targets from the motor record. + +**I7. Pod against pod is the driver's job.** Nothing below the driver stops the pods colliding. +Before a pod moves, its swept X range (bridge, pipettor and gripper as posed, with what it holds) +must clear the other pod's range and any move it has in flight, or the move is refused before +anything is sent (`driver/x_rail.py`, Biomek's own rule). The driver does not move the other pod out +of the way; a caller makes room (`Pod.move_aside`, `Pod.park`). The guard uses the configuration +only, so it holds without a deck. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index b423c4a6391..fed087c574c 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -174,10 +174,13 @@ class Obstacle: # The settings the driver takes from a pod's entry in the instrument file, never assumed: a pod # whose entry lacks one is refused (`PodConfiguration`). Every pod's; a gripper's; each pod type's. POD_SETTINGS: Tuple[str, ...] = () -GRIPPER_SETTINGS: Tuple[str, ...] = () +GRIPPER_SETTINGS: Tuple[str, ...] = ("GripperSqueezeForce",) TYPE_SETTINGS: Dict[str, Tuple[str, ...]] = { "span8": ("ProbeSize",), - "multichannel": (), + "multichannel": ( + "HeadBodyXSpan", + "HeadBodyYSpan", + ), } diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py new file mode 100644 index 00000000000..55989602bfb --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py @@ -0,0 +1,60 @@ +"""Faults the boards report unasked, as the Master Controller handles them, and the positions: a +motor that fails on its own trips the interlock and every position is forgotten; after an interlock +trip, re-arming reads every position again.""" + +import asyncio + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest + + +class FaultTests(PodMoveTest): + async def settle(self) -> None: + """Let the boards' read loops and the driver's background writes run.""" + for _ in range(5): + await asyncio.sleep(0.02) + + def unasked(self, driver: BiomekI7Driver, module: str, message: bytes) -> None: + self.usb(driver, module)._queue(message) + + async def test_a_motor_failing_on_its_own_trips_the_interlock(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + await pod.move_axes({"X": 100000}) + x = pod.axis("X") + self.mark(driver) + with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "ERROR") as logs: + # A Move All's NOTICE for X with a following error, sequence 0: nobody asked. + self.unasked(driver, "multichannel", bytes([x.device, x.index, 0, 0, 0x50, 0xFE, 0x3C])) + await self.settle() + self.assertIn("The left X motor failed", "\n".join(logs.output)) + self.assertEqual( + [n for n, _ in self.sent(driver, "chassis")], ["Trip Interlock", "Set Status Display"] + ) + self.assertEqual(self.sent(driver, "chassis")[1][1], p.set_status_display("error").params) + self.assertIsNone(pod.cpositions["X"][0]) + self.assertTrue(driver.interlock_tripped.is_set()) + + async def test_an_interlock_trip_forgets_positions_and_shows_error(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "right") + await pod.move_axes({"Z1": -10000}) + self.mark(driver) + with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "ERROR"): + self.unasked(driver, "chassis", bytes([p.Device.INTERLOCK, 1, 0, 0, 0x10, 0x03, 0x00, 0x01])) + await self.settle() + self.assertEqual( + self.sent(driver, "chassis"), [("Set Status Display", p.set_status_display("error").params)] + ) + self.assertTrue(all(c[0] is None for c in pod.cpositions.values() if c is not None)) + # Re-arming reads every position again, as the Master Controller's resume does. + await driver.arm_interlock() + self.assertFalse(driver.interlock_tripped.is_set()) + self.assertIsNotNone(pod.cpositions["Z1"][0]) + + +if __name__ == "__main__": + import unittest + + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index 67627737673..82ef8564a41 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -1,9 +1,24 @@ """One pod: an arm on the shared X rail, its ACE module, and the axes that module drives.""" import logging -from typing import Dict, List, Literal, Optional, Sequence, Tuple, cast +import math +from dataclasses import dataclass, field +from typing import ( + Callable, + Dict, + Iterable, + List, + Literal, + Mapping, + Optional, + Sequence, + Set, + Tuple, + cast, +) from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.driver import motion from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( @@ -14,8 +29,17 @@ read_analog_inputs, read_module, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, MotorTables -from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ENABLE_ORDER, ENABLE_PREFIX +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ( + ENABLE_ORDER, + ENABLE_PREFIX, + HOME_RECIPES, + Homer, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail logger = logging.getLogger(__name__) @@ -23,11 +47,21 @@ # driver was written against; whether that holds on every build is not established. POD_NUMBERS = {"left": 1, "right": 2} COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"} +# The axes that change what a pod takes up along the X rail. +RAIL_AXES = ("X", "GR", "GG") +# The gripper's axes; a move of these, or of the channels' Y or Z, is checked against the pod's own +# parts (`pod_collision`). +OWN_COLLISION_AXES = {"GY", "GZ", "GR", "GG"} +GRIPPER_HEIGHT_STEP = 0.1 # cm: how finely the gripper's travel height is searched # Get Homed State answers. 0x01 was read from every axis at a cold start, 0x00 from every axis of # both pods after Biomek's Home All (H1, 2026-10-24). HOMED_STATES = {0x00: "homed", 0x01: "not_homed"} +# The timeouts the Master Controller gives the boards: a single axis's move, and a Move All. +MOVE_TIMEOUT_MS = 30000 +MOVE_ALL_TIMEOUT_MS = 5000 + # Biomek's "Safe Height" (`GlobalMinSafeHeight`) at or below this is unset (it stores -100000). UNSET_SAFE_HEIGHT = -1000.0 @@ -41,15 +75,35 @@ ENABLE_SECONDS_PER_AXIS = 9.0 +@dataclass(frozen=True) +class MoveResult: + """What a coordinated move did: the motions it sent (empty when every axis was already there), + and each axis's report that was not a plain finish. A sensor stop says where + (`MotionComplete.position`).""" + + motions: List[motion.Motion] = field(default_factory=list) + completions: Dict[str, p.MotionComplete] = field(default_factory=dict) + + def stopped_at(self, axis: str) -> Optional[int]: + """Where a sensor stopped `axis`, in counts; None if none did.""" + complete = self.completions.get(axis) + return complete.position if complete is not None else None + + +# How long this driver waits for a board to answer a Home, in seconds. The longest homing seen +# took 9 s; the boards' own homing timeouts (Configure "Homing Timeout") are up to 60 s. +HOME_REPLY_TIMEOUT = 65.0 + + class Pod: """One pod. Reached as `driver.left_x_arm` / `driver.right_x_arm`: it fills the slot of STAR's `XArm`, though more of the instrument hangs on it. One board drives its X, Y and Z, its head - or channels and its gripper. + or channels and its gripper, through one position record. - `module_type` is what the board reports itself to be (Get Module ID): `multichannel` (a - 96-channel head) or `span8` (eight independent channels). Its axes are the motor tables' for - that type; what else is known of the pod (conversions, travel limits, geometry, settings) is the - declared configuration's. + Holds what every pod has: one board and its axes, moved together (`move_axes`, the Master + Controller's `AM`), the position record the Master Controller keeps, homing, and the pod's pose + on the shared X rail. `module_type` is what the board reports itself to be: `multichannel` (a + 96-channel head) or `span8` (eight independent channels). """ def __init__( @@ -68,6 +122,20 @@ def __init__( # What the instrument's declared configuration says about this pod: its conversions, travel # limits and geometry. None when nothing is declared for this side. self.declared = declared + # The shared X rail, set by the driver once both pods are found. Every move that changes what + # the pod takes up along it (X, the gripper's GR or GG) goes through it. + self.rail: Optional[XRail] = None + # What the gripper holds, as the rail counts it; the pod cannot sense it. + self._held_labware: Optional[g.HeldLabware] = None + # Where this driver last put each axis, as the Master Controller keeps it (`cpositions`): + # (position, adjusted); position None until read. Starts as after homing. + self._cpositions: Dict[str, motion.CPos] = {a.name: (None, a.home_position) for a in self.axes} + # The pumps' state, kept with the positions as the Master Controller keeps it in the Span-8's + # state record, because every pump move carries it. Each syringe + # pump's valve as last set (None until then), and the cutoff velocity (`CV`), counts/s, + # clamped to each pump's range when used. + self._valves: Dict[str, Optional[p.Valve]] = {a.name: None for a in self.axes if a.is_pump} + self._cutoff_velocity = 0 # The height the channels rise to before traveling over the deck, mm of the channels' bottom # above the deck: STAR's `default_minimum_traverse_height`. Seeded from Biomek's "Safe Height" # (`GlobalMinSafeHeight`) when it is set; None, as on an instrument where it is not (-100000), @@ -78,6 +146,8 @@ def __init__( safe = declared.settings.get("GlobalMinSafeHeight") if isinstance(safe, (int, float)) and safe > UNSET_SAFE_HEIGHT: self.default_minimum_traverse_height = units.to_mm(float(safe)) + # Who follows the position record (`add_position_listener`). + self._listeners: List[Callable[["Pod"], None]] = [] @property def pod_number(self) -> int: @@ -89,7 +159,8 @@ def __str__(self) -> str: @property def component(self) -> str: """The name Biomek gives this pod's component in its logs (`host_command.component`): - `MC_1`, `SPAN8_2`.""" + `MC_1`, `SPAN8_2`. The driver's own log lines for host commands use it too, so a session can + be lined up with one of Biomek's.""" return f"{COMPONENT_PREFIXES[self.module_type]}_{self.pod_number}" def axis(self, name: str) -> Axis: @@ -154,8 +225,8 @@ async def request_analog_inputs(self) -> Dict[str, float]: raise RuntimeError(f"{self} has not been read; call `discover()` or `setup()` first") return await read_analog_inputs(self.board, self.configuration) - # -- configuration and enabling ------------------------------------------------ - # These write to the board. Nothing in this driver calls them on its own. + # -- configuration and homing ------------------------------------------------ + # These write to the board and move the arm. Nothing in this driver calls them on its own. async def configure(self) -> None: """Load every axis's motor table into the board, then Stop Module Execution, as after a @@ -164,24 +235,750 @@ async def configure(self) -> None: Configuring an axis that is configured is accepted, and leaves it disabled and not homed, so this un-homes the pod.""" logger.info("%s configure (%d axes)", self.component, len(self.axes)) + self._set_home_positions(a.name for a in self.axes) for axis in self.axes: await self._unchecked_fw_configure(axis) await self._unchecked_fw_stop_module_execution() async def enable_axes(self) -> Dict[str, int]: """Stop motion and enable every axis, as after the interlock is armed (its drive power was - off), and read where each is, as the Master Controller resumes: each axis enabled and read. - Returns every axis's position.""" + off), and read where each is, as the Master Controller resumes: the positions cleared, then + each axis enabled and read. Returns every axis's position.""" axes = [self.axis(name) for name in ENABLE_ORDER[self.module_type]] + self._forget_positions() await self._unchecked_fw_enable(ENABLE_PREFIX[self.module_type]) await self._unchecked_fw_stop_motion() await self._unchecked_fw_enable(ENABLE_ORDER[self.module_type]) replies = await self.board.send_many([p.get_current_position(a.device, a.index) for a in axes]) - return {a.name: p.parse_s32(r.payload) for a, r in zip(axes, replies)} + positions = {a.name: p.parse_s32(r.payload) for a, r in zip(axes, replies)} + # As the Master Controller does, each read is the axis's position. + for axis in axes: + self._cpositions[axis.name] = motion.update_cpos( + self._cpositions[axis.name], positions[axis.name], axis.hysteresis + ) + self._positions_changed() + return positions + + async def home(self, force: bool = False) -> None: + """Home every axis but the plunger (or syringe pumps), in the Master Controller's `HM` order. + + Axes not homed are homed. Axes already homed are moved to where a Home would leave them, or, + with `force`, moved to their approach positions and homed again as `HM` does. Each ends where + Biomek leaves it.""" + logger.info("%s HM%s", self.component, "" if force else " (homed axes kept)") + try: + await Homer(self, force=force).run(HOME_RECIPES[self.module_type]) + finally: + self._set_home_positions(Homer.axes(HOME_RECIPES[self.module_type])) + + # -- coordinated moves ------------------------------------------------------- + # The Master Controller's `AM`, with its position bookkeeping: see `motion.py`. + + @property + def cpositions(self) -> Dict[str, motion.CPos]: + """Each axis's (position, adjusted), as this driver keeps them; position None until read.""" + return dict(self._cpositions) + + def _set_home_positions(self, names: Iterable[str]) -> None: + """After homing: position unknown, adjusted at the axis's home.""" + for name in names: + self._cpositions[name] = (None, self.axis(name).home_position) + self._positions_changed() + + def _forget_positions( + self, + names: Optional[Iterable[str]] = None, + adjusted: Optional[Mapping[str, motion.CPos]] = None, + ) -> None: + """Mark positions unknown, so the next move reads them first; adjusted + positions stay, or are taken from `adjusted`.""" + for name in list(self._cpositions) if names is None else names: + self._cpositions[name] = (None, (adjusted or self._cpositions)[name][1]) + self._positions_changed() + + async def _read_unknown_positions(self, pumps: bool = False) -> None: + """As the Master Controller does before every move: if any axis's position is + unknown, Stop Motion Service, then enable and read each such axis. Syringe pumps are included + only when the move uses them (`pumps`).""" + unknown = [ + a for a in self.axes if (pumps or not a.is_pump) and self._cpositions[a.name][0] is None + ] + if not unknown: + return + await self._unchecked_fw_stop_motion() + await self._unchecked_fw_enable([a.name for a in unknown]) + replies = await self.board.send_many( + [p.get_current_position(a.device, a.index) for a in unknown] + ) + for axis, reply in zip(unknown, replies): + position = p.parse_s32(reply.payload) + self._cpositions[axis.name] = motion.update_cpos( + self._cpositions[axis.name], position, axis.hysteresis + ) + self._positions_changed() + + async def request_x_position(self) -> int: + """Where the pod's X is, in counts, as its drive reports it. Moves nothing.""" + x = self.axis("X") + return p.parse_s32((await self.board.send(p.get_current_position(x.device, x.index))).payload) + + # -- the pod against itself ---------------------------------------------------- + + def _own_state( + self, positions: Optional[Mapping[str, motion.CPos]] = None + ) -> Optional[Tuple[float, pc.GripperState, pc.PipettorState]]: + """The pose the pod's own collision check takes (`pod_collision`), in Biomek's units, from + `positions` (the position record by default); None while any of its axes is unknown.""" + d = self.declared + if d is None or not d.gripper_model: + return None + positions = self._cpositions if positions is None else positions + channels = self.channel_z_axes + ys = [f"Y{i}" for i in range(1, 9)] if self.module_type == "span8" else ["Y"] + names = ["X", "GY", "GZ", "GR", "GG", *ys, *channels] + counts = {n: positions[n][0] for n in names} + if any(c is None for c in counts.values()): + return None + v = {n: d.to_value("Y" if n in ys else n, c) for n, c in counts.items()} # type: ignore[arg-type] + if self.module_type == "span8": + # Each probe's Y counts from its own narrowest place (`probe_y`), not probe 1's. + v.update({n: d.probe_y(i, counts[n]) for i, n in enumerate(ys, 1)}) # type: ignore[arg-type] + lengths: Dict[str, float] = {} # no channel carries a tip + gripper = pc.GripperState(v["GY"], v["GZ"], v["GR"], v["GG"], self._held_labware) + pipettor = pc.PipettorState( + tuple(v[n] for n in ys), + tuple(v[z] for z in channels), + tuple(lengths.get(z, 0.0) for z in channels), + ) + return v["X"], gripper, pipettor + + def _check_own_collision( + self, + start: Mapping[str, motion.CPos], + end: Mapping[str, motion.CPos], + moving: Set[str], + ) -> None: + """Refuse a move whose path brings the gripper (or what it holds) into the pipettor. + + Raises: + PodCollisionError: naming the parts that would meet; nothing has been sent. + """ + if not moving & OWN_COLLISION_AXES and not any(a[:1] in "YZ" for a in moving): + return + a, b = self._own_state(start), self._own_state(end) + if a is None or b is None or self.declared is None: + return + found = pc.swept_collisions(self.declared, (a[0], b[0]), (a[1], b[1]), (a[2], b[2])) + if found: + parts = ", ".join(f"the {x} and {y}" for x, y in found[:3]) + raise pc.PodCollisionError(f"{self}: the move would bring together {parts}") + + def _gripper_traverse_height(self, gr: float) -> float: + """The GZ (cm) the gripper travels at to turn from where it is to GR `gr` (degrees): its + ceiling (`_traverse_ceilings`), or as far below it as keeps it (and what it holds) clear of the + pod's own pipettor at its traverse heights on the way, in steps of `GRIPPER_HEIGHT_STEP`. + + Raises: + PodCollisionError: if no height down to the grip's travel limit is clear. + """ + d = self._require_declared() + state = self._own_state() + ceiling = self._traverse_ceilings()["GZ"] + if state is None: + return ceiling + x, gripper, pipettor = state + heights = self._traverse_heights() + raised = pc.PipettorState( + pipettor.ys, + tuple(max(z, heights[n]) for z, n in zip(pipettor.zs, self.channel_z_axes)), + pipettor.tips, + ) + low = d.limits["GZ"][0] + gz = ceiling + while gz >= low: + a = pc.GripperState(gripper.gy, gz, gripper.gr, gripper.gg, gripper.held) + b = pc.GripperState(gripper.gy, gz, gr, gripper.gg, gripper.held) + if not pc.swept_collisions(d, (x, x), (a, b), (raised, raised)): + return gz + gz -= GRIPPER_HEIGHT_STEP + raise pc.PodCollisionError(f"{self}: no gripper height clears the pod's own parts at GR {gr}") + + async def _make_room_for_gripper(self, targets: Mapping[str, int]) -> None: + """Before the gripper travels to `targets` (counts: X, GY, GR): on a Span-8 whose probes + would be in its way there, narrow them to the smallest span and move them to the end of their + Y travel away from the gripper (as Biomek's path search does when it minimises the pod's Y + span). Nothing on a 96-head pod, or with the probes already clear. + + Raises: + PodCollisionError: if the probes cannot be moved clear. + """ + if self.module_type != "span8": + return + d = self._require_declared() + await self._read_unknown_positions() + state = self._own_state() + if state is None: + return + x, gripper, pipettor = state + gy = d.to_value("GY", targets.get("GY", self._cpositions["GY"][1])) + gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1])) + gz = self._gripper_traverse_height(gr) if gr != gripper.gr else gripper.gz + end = pc.GripperState(gy, gz, gr, gripper.gg, gripper.held) + if not pc.collisions(d, x, end, pipettor): + return + low, high = d.limits["Y"] + span = d.limits["Span"][0] + y = low if gy >= (low + high) / 2 else high - span + ys = tuple(y + i * span / (len(pipettor.ys) - 1) for i in range(len(pipettor.ys))) + if pc.collisions(d, x, end, pc.PipettorState(ys, pipettor.zs, pipettor.tips)): + raise pc.PodCollisionError(f"{self}: the probes cannot be moved clear of the gripper") + await self._lift_channels() + await self.move_axes({"Y": d.to_counts("Y", y), "S": d.to_counts("S", span)}) + + async def _travel_gripper( + self, + targets: Mapping[str, int], + speed: int = 1000, + minimum_traverse_height: Optional[float] = None, + ) -> MoveResult: + """Take the gripper to `targets` (counts: X, GY, GR) clear of the deck and of the pod's own + pipettor: the channels raised (`_move_over`), the probes moved out of its way + (`_make_room_for_gripper`), the gripper at the highest height that clears the pod's own parts + for the turn (`_gripper_traverse_height`), lowered to it first if it is above.""" + d = self._require_declared() + await self._read_unknown_positions() + await self._make_room_for_gripper(targets) + gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1])) + gz = self._gripper_traverse_height(gr) + if d.to_counts("GZ", gz) < self._cpositions["GZ"][1]: + await self.move_axes({"GZ": d.to_counts("GZ", gz)}, speed) + return await self._move_over( + targets, speed, minimum_traverse_height=minimum_traverse_height, gripper_height=gz + ) + + # -- the shared X rail --------------------------------------------------------- + + def _rail_pose(self, x: int, gr: Optional[int], gg: Optional[int]) -> PodPose: + """A pose in counts as the rail takes it: deck X, and the gripper in degrees and cm.""" + d = self._require_declared() + gripper = None + if gr is not None and gg is not None: + gripper = g.GripperPose(d.to_value("GR", gr), d.to_value("GG", gg), self._held_labware) + return PodPose(d.to_value("X", x), gripper) + + def _require_declared(self) -> PodConfiguration: + if self.declared is None: + raise RuntimeError(f"{self} has no declared configuration") + return self.declared + + def add_position_listener(self, listener: Callable[["Pod"], None]) -> Callable[[], None]: + """Call `listener(pod)` whenever the position record changes: after a move, a read, homing, + or a position becoming unknown. Returns what removes it. For what follows the pod, such as its + model in a resource tree; a listener that raises is logged and kept.""" + self._listeners.append(listener) + return lambda: self._listeners.remove(listener) + + def _positions_changed(self) -> None: + self._tell_rail() + for listener in list(self._listeners): + try: + listener(self) + except Exception: + logger.exception("%s: position listener %r failed", self, listener) + + def _tell_rail(self) -> None: + """Give the rail this pod's pose from the position record (unknown parts as unknown).""" + if self.rail is None or self.declared is None: + return + x = self._cpositions["X"][0] + pose = None + if x is not None: + pose = self._rail_pose(x, self._cpositions["GR"][0], self._cpositions["GG"][0]) + self.rail.update(self.side, pose) + + async def request_rail_pose(self) -> PodPose: + """Where the pod is along the rail, as its drives report X, GR and GG. Moves nothing.""" + axes = [self.axis(n) for n in ("X", "GR", "GG")] + replies = await self.board.send_many([p.get_current_position(a.device, a.index) for a in axes]) + x, gr, gg = (p.parse_s32(r.payload) for r in replies) + return self._rail_pose(x, gr, gg) + + async def move_axes( + self, + targets: Mapping[str, int], + speed: int = 1000, + forces: Optional[Mapping[str, float]] = None, + sensors: Optional[Mapping[str, Tuple[int, int]]] = None, + ) -> MoveResult: + """Move several axes together so they arrive at once: Biomek's `AM` (with `SF` force limits and + sensor stops). The slowest axis moves at its limits x + speed / 1000, the others scaled to match; axes already at their target stay put. + + Targets are in counts. On the Span-8 Z channels they are adjusted positions (the channel's + hysteresis is added to downward moves, as Biomek does). Syringe pumps move through the valve + each was last set to, at the cutoff velocity last set, as the Master Controller carries both. + + A move of X, GR or GG is checked against the other pod first (`driver/x_rail.py`). One that + would run into it is refused, and nothing is sent. One crossing only the path of the other + pod's move in flight waits for that move to finish. Whether the pod may move now (interlock + armed) is the caller's to decide. + + Args: + targets: target per axis name. On a Span-8, also `Y` (channel 1) and `S` (the span from + channel 1 to 8), as Biomek sends them: they set Y1-Y8 as the Master Controller does + (`motion.span_targets`), and cannot be given with Y1-Y8. + speed: 1..1000, Biomek's speed field. + forces: force limit per axis, in the Master Controller's units (its `SF`; sent x1000). The + axis stops where that force stalls it (a grip, a tip pressed on); its position is then + not known until read, which the next move does. + sensors: per axis, the (sensor, trigger) that stops it where the sensor fires (a Span-8 Z + sensing liquid). Where it stopped is in the result and becomes the axis's position, as + the Master Controller keeps it. Whether liquid not sensed or a clot is an + error is the caller's to decide (the Master Controller fails the `AM` for the first and + reports the second). + + Returns: + The motions sent and how the axes ended. + + Raises: + ValueError: for an unknown axis, a target outside an axis's limits, a force or sensor on an + axis without a target, or a speed outside 1..1000; nothing is sent. + RuntimeError: for a pump whose valve this driver has not set; nothing is sent. + NotHomedError: if an axis has not been homed; its pending moves are dropped. + RailCollisionError: if X, GR or GG would move into the other pod's range; nothing is sent. + PodCollisionError: if the gripper (or what it holds) would meet the pod's own pipettor on + the way (`pod_collision`); nothing is sent. + """ + forces, sensors = dict(forces or {}), dict(sensors or {}) + given, targets = dict(targets), dict(targets) + if self.module_type == "span8" and ("Y" in targets or "S" in targets): + channels = sorted(n for n in targets if n in {f"Y{i}" for i in range(1, 9)}) + if channels: + raise ValueError(f"{self}: Y or S with {channels}; give one or the other") + y, span = targets.pop("Y", None), targets.pop("S", None) + targets.update(motion.span_targets(self._cpositions, y, span)) + if not 1 <= speed <= 1000: + raise ValueError(f"speed {speed} is outside 1..1000") + for name, target in targets.items(): + axis = self.axis(name) + axis.check_position(target) + if axis.is_pump and self._valves[name] is None: + raise RuntimeError(f"{self}: {name}'s valve has not been set") + stray = sorted({*forces, *sensors} - set(targets)) + if stray: + raise ValueError(f"{self}: a force or sensor on {stray}, which have no target") + for name, force in forces.items(): + if self.axis(name).is_pump or not 0 <= force <= p.MAX_FORCE: + raise ValueError( + f"{self}: force {force} on {name}: not a motor, or outside 0..{p.MAX_FORCE}" + ) + uses_pumps = any(self.axis(n).is_pump for n in targets) + try: + await self._read_unknown_positions(pumps=uses_pumps) + motions, timeout_ms, after = motion.plan_move( + self.axes, self._cpositions, targets, speed, self._cutoff_velocity + ) + logger.info( + "%s AM %s speed %d%s%s: %d axes move, Move All timeout %d ms", + self.component, + " ".join(f"{n}={t}" for n, t in given.items()), + speed, + "".join(f" SF {n} {f}" for n, f in forces.items()), + "".join(f" sensor {n} {s} {t}" for n, (s, t) in sensors.items()), + len(motions), + timeout_ms, + ) + if not motions: + return MoveResult() + self._check_own_collision(self._cpositions, after, {m.axis for m in motions}) + if self.rail is not None and any(m.axis in RAIL_AXES for m in motions): + start = self._rail_pose(*(self._cpositions[n][0] or 0 for n in RAIL_AXES)) + end_counts = [after[n][0] or 0 for n in RAIL_AXES] + if "GG" in forces: # stops on what it grips, short of its target: count the wider end + end_counts[2] = max(end_counts[2], self._cpositions["GG"][0] or 0) + end = self._rail_pose(*end_counts) + async with self.rail.moving(self.side, start, end): + completions = await self._send_motions(motions, timeout_ms, forces, sensors) + else: + completions = await self._send_motions(motions, timeout_ms, forces, sensors) + except (RailCollisionError, pc.PodCollisionError): + raise # refused before anything was sent: every position is as it was + except BaseException as e: + # As the Master Controller after a failed command, and its reply, so a + # session's log reads as Biomek's: "#AM The left X motion failed: ...". + self._forget_positions() + if isinstance(e, AceError): + names = {(a.device, a.index): f"{self.side} {a.name}" for a in self.axes} + logger.error("%s #AM %s", self.component, english(e, names)) + raise + before = self._cpositions + self._cpositions = after + # Force stopped these short of where they were sent: as the Master Controller does, their + # positions become unknown (adjusted as before), read before the next move. + if forces: + self._forget_positions(forces, before) + # A sensor stop reports where it stopped; the Master Controller takes that as the position. + for name, complete in completions.items(): + if complete.position is not None and name not in forces: + axis = self.axis(name) + self._cpositions[name] = motion.update_cpos( + self._cpositions[name], complete.position, axis.hysteresis + ) + self._positions_changed() + return MoveResult(list(motions), completions) + + # -- travel over the deck (design.md I12) ------------------------------------------- + + @property + def channel_z_axes(self) -> List[str]: + """The axes whose height is the channels' bottom: `Z` on a Multichannel, `Z1`-`Z8` on a Span-8.""" + return [ + a.name for a in self.axes if a.name == "Z" or (a.name[0] == "Z" and a.name[1:].isdigit()) + ] + + def _traverse_heights(self) -> Dict[str, float]: + """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default, cm + of its bottom above the deck: its ceiling (`_traverse_ceilings`), or + `default_minimum_traverse_height` where that is lower.""" + ceilings = self._traverse_ceilings() + wanted = units.optional_cm(self.default_minimum_traverse_height) + return { + name: top if wanted is None or name == "GZ" else min(wanted, top) + for name, top in ceilings.items() + } + + def _traverse_ceilings(self) -> Dict[str, float]: + """The highest each Z-type axis travels, cm of its bottom above the deck: the top of travel less + the park margin (`ParkLocation` `ZMargin`, `GZMargin`), as Biomek parks them (the + Multichannel's rest Z, 39.763 cm, is -256 counts). A Span-8 probe goes no higher than its top + less `DiscardOffset`: above that its stripper pushes a tip off (Biomek travels carrying probes + there, as its logs show).""" + d = self._require_declared() + shuck = d.settings.get("DiscardOffset") if self.module_type == "span8" else None + ceilings = {} + for name in self.channel_z_axes + ["GZ"]: + top = d.limits[name][1] + ceiling = top + d.park.get("GZMargin" if name == "GZ" else "ZMargin", 0.0) + if shuck is not None and name != "GZ": + ceiling = min(ceiling, top - shuck) + ceilings[name] = ceiling + return ceilings + + async def park(self) -> None: + """Biomek's park (`_park`): the channels and the gripper raised, the pod to its park X and Y, + the gripper turned and closed to its park.""" + await self._park() + + async def _park(self, over: Optional[Mapping[str, int]] = None) -> None: + """Biomek's park (`ParkLocation`): the channels and the gripper raised to their ceilings + (`_traverse_ceilings`), the pod to the park X (`XMargin` in from its own end of the rail) and + `Y`, the gripper turned and closed to its park (`GR`, `GY`, then `GG`). As logged after a + prime (2026-10-09), to the count. `over`: X/Y targets (counts) for a pod whose park declares + none. Without either, it parks where it stands. + + Raises: + RuntimeError: without a declared configuration. + """ + d = self.declared + if d is None: + raise RuntimeError(f"{self} needs a declared configuration") + if self._held_labware is not None: + raise RuntimeError(f"{self}: the gripper holds labware; place it before parking") + p = d.park + targets: Dict[str, int] = dict(over or {}) + if "XMargin" in p and "X" not in targets: + low, high = d.limits["X"] + x = low + p["XMargin"] if self.side == "left" else high - p["XMargin"] + targets["X"] = d.to_counts("X", x) + if "Y" in p and "Y" not in targets: + targets["Y"] = d.to_counts("Y", p["Y"]) + targets.update({a: d.to_counts(a, p[a]) for a in ("GR", "GY") if a in p}) + await self._move_over(targets) + # The channels rest at the top less the park margin, and on a Span-8 less `DiscardOffset` as + # well (39.1079 cm on Z1, 9029 counts: lower than the probes travel, `_traverse_ceilings`). + shuck = d.settings.get("DiscardOffset", 0.0) if self.module_type == "span8" else 0.0 + rest = { + z: d.to_counts(z, d.limits[z][1] + p.get("ZMargin", 0.0) - shuck) for z in self.channel_z_axes + } + if any(self.cpositions[z][1] != c for z, c in rest.items()): + await self.move_axes(rest) + if "GG" in p: + # Closed under the grip force, as Biomek's park closes it (it may stop on its own fingers). + force = d.settings["GripperSqueezeForce"] + await self.move_axes({"GG": d.to_counts("GG", p["GG"])}, forces={"GG": force}) + # The force leaves GG's position unknown, and the rail counts an unknown gripper as every + # pose it could take, in the other pod's way: read it back now. + await self._read_unknown_positions() + + async def move_aside(self) -> None: + """Raise the pod and take it to the end of its X travel on its own side (the left pod to its + lowest X, the right pod to its highest), leaving the other pod the most of the rail. Biomek + moves a pod out of the way itself; the rail guard here refuses instead + (`x_rail.py`), so a caller makes room with this. + + Raises: + RuntimeError: without a declared configuration. + """ + d = self.declared + if d is None: + raise RuntimeError(f"{self} needs a declared configuration") + low, high = d.limits["X"] + await self._move_over({"X": d.to_counts("X", low if self.side == "left" else high)}) + + async def _move_over( + self, + targets: Mapping[str, int], + speed: int = 1000, + minimum_traverse_height: Optional[float] = None, + z_final: Optional[float] = None, + clearance: Optional[float] = None, + allow_below_clearance: bool = False, + tip_lengths: Optional[Mapping[str, float]] = None, + gripper_height: Optional[float] = None, + ) -> MoveResult: + """Travel to `targets` (X, Y and the like, in counts, as `move_axes` takes them) clear of the + deck: lift the channels and the gripper to a traverse height, move, then optionally set the + channels to `z_final`. STAR's `minimum_traverse_height_at_beginning_of_a_command` and + `z_final`, and Biomek's Safe Height; design.md I12. Heights here are Biomek's frame, cm above + the deck surface, and are each channel's lowest point, as STAR's are: the end of the tip it + carries (`tip_lengths`), else its bottom. An axis already above its traverse height is not + lowered. + + Args: + targets: the travel's targets; channel Z axes in them are refused (use `z_final`). + speed: as `move_axes`, for every step. + minimum_traverse_height: the channels' lowest points while traveling. Default: each channel + at `_traverse_heights` (as high as it goes). The gripper travels at its default + always. + z_final: where to set the channels' bottoms once there; None leaves them at the traverse + height. + clearance: the lowest height the deck under the path allows, from a deck model, if known. + allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately. + tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, cm; none + when None. + gripper_height: GZ (cm) to travel at. Default: its traverse height, no higher than clears + the pod's own pipettor for the travel's GR (`_gripper_traverse_height`). + + Raises: + ValueError: for a channel Z axis in `targets`; for a path through a wall (a shield, a + tower, the light curtain); for a traverse height below what the path needs (unless + `allow_below_clearance`), a need above what the channels reach, or a height a channel + cannot lift its tip to (under its `_traverse_ceilings`). Nothing is sent. + """ + d = self._require_declared() + channels = self.channel_z_axes + stray = sorted(set(targets) & set(channels)) + if stray: + raise ValueError(f"{self}: {stray} in a travel's targets; use z_final") + lengths = {} if tip_lengths is None else dict(tip_lengths) + await self._read_unknown_positions() + area = self._travel_area(targets) + need = g.obstacle_clearance(d.obstacles, *area) + if need.walls: + raise ValueError(f"{self}: the travel would pass through {', '.join(need.walls)}") + required = max(need.height, -math.inf if clearance is None else clearance) + heights, reach, traverse = self._traverse_targets(minimum_traverse_height, lengths) + if required > reach: + raise ValueError(f"{self}: the path needs {required:.3f} cm, above what the channels reach") + if traverse < required and not allow_below_clearance: + raise ValueError( + f"{self}: traverse height {traverse:.3f} cm is below the {required:.3f} cm the path needs;" + " pass allow_below_clearance=True to travel lower deliberately" + ) + if gripper_height is None: + # No higher than clears the pod's own pipettor for the gripper's angle, and its turn if the + # travel turns it; only that lowers it (an axis above its traverse height stays there). + gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1])) + clear = self._gripper_traverse_height(gr) + if clear < heights["GZ"]: + gripper_height = clear + if gripper_height is not None: + heights["GZ"] = gripper_height + if d.to_counts("GZ", gripper_height) < self._cpositions["GZ"][1]: + await self.move_axes({"GZ": d.to_counts("GZ", gripper_height)}, speed) + await self._raise_to(heights, speed) + result = await self.move_axes(targets, speed) + if z_final is not None: + await self.move_axes({n: d.to_counts(n, z_final) for n in channels}, speed) + return result + + async def move_over( + self, + targets: Mapping[str, float], + speed_fraction: float = 1.0, + minimum_traverse_height: Optional[float] = None, + z_final: Optional[float] = None, + clearance: Optional[float] = None, + allow_below_clearance: bool = False, + tip_lengths: Optional[Mapping[str, float]] = None, + gripper_height: Optional[float] = None, + ) -> MoveResult: + """Travel to `targets` clear of the deck: lift the channels and the gripper to a traverse + height, move, then optionally set the channels to `z_final` (STAR's + `minimum_traverse_height_at_beginning_of_a_command` and `z_final`; Biomek's Safe Height). + Heights are mm above the deck of each channel's lowest point, as STAR's are: the end of the + tip it carries, else its bottom. An axis already above its traverse height is not lowered. + + Args: + targets: per axis, in PyLabRobot's units (`units.axis_to_biomek`): X and Y as deck x / y + (mm) of the point the pod's X and Y name (mandrel A1, probe 1), S (the Span-8's span) and + GG in mm, GR in degrees, pumps in uL. Channel Z axes are refused (use `z_final`). + speed_fraction: the share of each axis's maximum velocity every step moves at, (0, 1]: one + for the whole move, as the instrument has. + minimum_traverse_height: the channels' lowest points while traveling, mm. Default: each at + `traverse_heights`. + z_final: where to set the channels' bottoms once there, mm; None leaves them at the traverse + height. + clearance: the lowest height the deck under the path allows, mm (`traverse_clearance`). + allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately. + tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, mm. The + pod's own record when None (`carried_tip_lengths`). + gripper_height: GZ, mm, to travel at. Default: its traverse height, no higher than clears + the pod's own pipettor. + + Raises: + ValueError: as `_move_over`, its Biomek-unit counterpart; for a `speed_fraction` outside + (0, 1]. Nothing is sent. + """ + return await self._move_over( + {axis: units.axis_to_counts(self, axis, value) for axis, value in targets.items()}, + units.fraction_to_field(speed_fraction), + minimum_traverse_height=units.optional_cm(minimum_traverse_height), + z_final=units.optional_cm(z_final), + clearance=units.optional_cm(clearance), + allow_below_clearance=allow_below_clearance, + tip_lengths=( + None if tip_lengths is None else {a: units.to_cm(v) for a, v in tip_lengths.items()} + ), + gripper_height=units.optional_cm(gripper_height), + ) + + def traverse_heights(self) -> Dict[str, float]: + """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default, mm + of its bottom above the deck: its ceiling (`traverse_ceilings`), or + `default_minimum_traverse_height` where that is lower.""" + return {axis: units.to_mm(v) for axis, v in self._traverse_heights().items()} + + def traverse_ceilings(self) -> Dict[str, float]: + """The highest each Z-type axis travels, mm of its bottom above the deck (`_traverse_ceilings`).""" + return {axis: units.to_mm(v) for axis, v in self._traverse_ceilings().items()} + + def _traverse_targets( + self, minimum_traverse_height: Optional[float], tip_lengths: Mapping[str, float] + ) -> Tuple[Dict[str, float], float, float]: + """Where each Z-type axis's bottom goes to travel, cm; the highest every channel's lowest point + reaches; and how high the lowest one travels. By default each at `_traverse_heights` + (defined on the bottoms: the tips do not change where they go); given a height, the channels' + lowest points there (a channel's bottom at the height + its tip's length, `tip_lengths`). + + Raises: + ValueError: for a height a channel cannot lift its tip to. + """ + channels = self.channel_z_axes + lengths = {n: tip_lengths.get(n, 0.0) for n in channels} + heights = self._traverse_heights() + ceilings = self._traverse_ceilings() + reach = min(ceilings[n] - lengths[n] for n in channels) + if minimum_traverse_height is None: + return heights, reach, min(heights[n] - lengths[n] for n in channels) + short = { + n: round(ceilings[n] - lengths[n], 4) + for n in channels + if minimum_traverse_height + lengths[n] > ceilings[n] + 1e-9 + } + if short: + raise ValueError( + f"{self}: traverse height {minimum_traverse_height:.3f} cm is above what the channels" + f" reach with their tips: {short}" + ) + heights.update({n: minimum_traverse_height + lengths[n] for n in channels}) + return heights, reach, minimum_traverse_height + + async def _lift_channels( + self, + minimum_traverse_height: Optional[float] = None, + tip_lengths: Optional[Mapping[str, float]] = None, + speed: int = 1000, + ) -> None: + """Raise the channels (not the gripper) where they stand to a traverse height, as `_move_over` + does before traveling (the same meaning of heights, the same tips); never lower. + + Raises: + ValueError: for a height a channel cannot lift its tip to. Nothing is sent. + """ + lengths = {} if tip_lengths is None else tip_lengths + heights, _, _ = self._traverse_targets(minimum_traverse_height, lengths) + await self._read_unknown_positions() + await self._raise_to({n: heights[n] for n in self.channel_z_axes}, speed) + + async def _raise_to(self, heights: Mapping[str, float], speed: int) -> None: + """Move the axes below their `heights` (cm) up to them, together.""" + d = self._require_declared() + lift = {} + for name, height in heights.items(): + counts = d.to_counts(name, height) + if self._cpositions[name][1] < counts: # counts grow with height on every Z-type axis + lift[name] = counts + if lift: + await self.move_axes(lift, speed) + + def _travel_area(self, targets: Mapping[str, int]) -> Tuple[g.Range, g.Range]: + """The X/Y area the pod's body covers from where it is to `targets`, cm.""" + d = self._require_declared() + y_axis = "Y" if self.module_type == "multichannel" else "Y1" + x0 = d.to_value("X", self._cpositions["X"][1]) + y0 = d.to_value("Y", self._cpositions[y_axis][1]) + x1 = d.to_value("X", targets.get("X", self._cpositions["X"][1])) + y1 = d.to_value("Y", targets.get("Y", targets.get(y_axis, self._cpositions[y_axis][1]))) + (ax, ay), (bx, by) = g.pod_xy_box(d.geometry, x0, y0), g.pod_xy_box(d.geometry, x1, y1) + return g.union(ax, bx), g.union(ay, by) + + async def _send_motions( + self, + motions: Sequence[motion.Motion], + timeout_ms: int, + forces: Mapping[str, float], + sensors: Mapping[str, Tuple[int, int]], + ) -> Dict[str, p.MotionComplete]: + """Set each motion's parameters, then start them together and wait for them to finish. + Returns, per axis, its report when it was not a plain finish. + + The parameters go out in the order the Master Controller's requests reach the board + (`motion.spawn_order`), motors and pumps together, so a session's traffic lines up with + Biomek's request for request.""" + moves = [] + for m in motion.spawn_order(motions): + sensor, trigger = sensors.get(m.axis, (0, 0)) + moves.append( + AxisMove( + m.axis, + m.position, + m.velocity, + m.acceleration, + m.jerk or 0, + round(forces.get(m.axis, 0.0) * 1000), + sensor, + trigger, + ) + ) + accepted = await self._unchecked_fw_set_move_parameters(moves) + if not all(accepted): + await self._unchecked_fw_stop_motion() + refused = [m.axis for m, ok in zip(moves, accepted) if not ok] + raise NotHomedError(0x32, None, f"{self}: {refused} not homed") + reports = await self._unchecked_fw_move_all(timeout_ms) + names = {(a.device, a.index): a.name for a in self.axes} + return { + names[(c.device, c.index)]: c + for c in reports + if (c.device, c.index) in names and c.outcome != "done" + } # -- drive commands ---------------------------------------------------------- - # One request, or one batch sent together, each, as the Master Controller sends them. No checks - # and no bookkeeping: the public methods above decide when each is sent. + # The only way this driver commands a drive: one request, or one batch sent together, each. They + # check targets against the axis's limits and nothing else. Whether an axis may move now (homed, + # interlock armed, clear of the other pod) is the caller's to decide, as homing does by asking + # the board. async def _unchecked_fw_enable(self, axes: Sequence[str]) -> None: """Set State ENABLED on each axis, sent together. On a drive in fault this is also the fault @@ -193,6 +990,89 @@ async def _unchecked_fw_enable(self, axes: Sequence[str]) -> None: timeout=5.0 + ENABLE_SECONDS_PER_AXIS * len(targets), ) + async def _unchecked_fw_set_move_parameters(self, moves: Sequence[AxisMove]) -> List[bool]: + """Set each axis's next move, sent together in the order given. Returns, per move, whether the + board took it (True) or refused it because the axis has not been homed since power-up (False). + + A syringe pump's move is sent as the Span-8's `move` does: the pump's minimum start velocity, + the move's velocity and acceleration, the cutoff velocity clamped to the pump's range, and the + valve as last set; its jerk, force and sensor are not sent. + + Raises: + ValueError: for a target outside the axis's limits; nothing is sent. + RuntimeError: for a pump whose valve has not been set; nothing is sent. + AceError: for any refusal other than "not homed". + """ + requests = [] + for move in moves: + axis = self.axis(move.axis) + axis.check_position(move.position) + limits = axis.limits + velocity = limits.max_velocity if move.velocity is None else move.velocity + acceleration = limits.max_acceleration if move.acceleration is None else move.acceleration + if axis.is_pump: + valve = self._valves[move.axis] + if valve is None: + raise RuntimeError(f"{self}: {move.axis}'s valve has not been set") + pump = axis.pump_limits + cutoff = int( + motion.range_(pump.min_cutoff_velocity, self._cutoff_velocity, pump.max_cutoff_velocity) + ) + requests.append( + p.set_pump_move_parameters( + axis.index, + move.position, + pump.min_start_velocity, + velocity, + cutoff, + acceleration, + valve, + ) + ) + continue + requests.append( + p.set_motor_move_parameters( + axis.index, + move.position, + velocity, + acceleration, + limits.max_jerk if move.jerk is None else move.jerk, + move.force, + move.sensor, + move.trigger, + ) + ) + replies = await self.board.send_many(requests, raise_errors=False) + accepted = [] + for move, reply in zip(moves, replies): + try: + reply.raise_for_error(f"{self}: Set {move.axis} Move Parameters") + accepted.append(True) + except NotHomedError: + accepted.append(False) + return accepted + + async def _unchecked_fw_move(self, axis: str, timeout_ms: int = MOVE_TIMEOUT_MS) -> None: + """Start one axis's move to the parameters set for it, and wait for it to finish.""" + await self.board.send( + p.move(self.axis(axis).index, timeout_ms), timeout=timeout_ms / 1000 + 5.0 + ) + + async def _unchecked_fw_move_all( + self, timeout_ms: int = MOVE_ALL_TIMEOUT_MS + ) -> List[p.MotionComplete]: + """Start every axis whose move parameters were set since its last move, together, and wait for + all of them to finish. Returns the reports the axes sent under the Move All.""" + reply = await self.board.send(p.move_all(timeout_ms), timeout=timeout_ms / 1000 + 5.0) + return [p.parse_motion_complete(r) for r in reply.related] + + async def _unchecked_fw_home(self, axes: Sequence[str]) -> None: + """Home the axes, sent together, and wait for every one to finish.""" + targets = [self.axis(name) for name in axes] + await self.board.send_many( + [p.home(a.device, a.index) for a in targets], timeout=HOME_REPLY_TIMEOUT + ) + async def _unchecked_fw_stop_motion(self) -> None: """Stop Motion Service on this pod's board: stops every axis and drops pending moves.""" await self.board.send(p.stop_motion_service()) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py new file mode 100644 index 00000000000..9f21856d1ff --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py @@ -0,0 +1,328 @@ +"""Home All against the generic instrument simulated: the requests each board is sent are the ones +Biomek's Master Controller sent (the cold start the generic recording was made from; a forced Home +All of a homed instrument, as its logs show it), and where each axis ends.""" + +import asyncio +import struct +import unittest +from typing import Dict, List + +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import HOME_RECIPES, Homer +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import SimulatedAceUSB +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_driver, + generic_recording, + generic_simulated_boards, +) + +SPAN8_Z = [f"Z{i}" for i in range(1, 9)] +# Reads the driver sends that Biomek's logs of a Home All leave out: the reads Biomek never +# sends (Get State, Get Interlock Status), and Read Analog/Digital Input (the drive supply and door +# checks), which Biomek polls in the background. +NOT_IN_RECORDINGS = set(p.FIRMWARE_READS) | { + (p.Device.ANALOG_INPUT, 0x10), + (p.Device.DIGITAL_INPUT, 0x10), +} +MASTER_LOGGER = "pylabrobot.beckman_coulter.biomek_i7.driver.master" +READ_ONLY_SETUP = dict(skip_device_initialization=True, skip_left_x_arm=True, skip_right_x_arm=True) +READS = ("Get ", "Read ", "List ") + +# The Multichannel board's requests in a forced Home All of a homed instrument (`HM`), as +# Biomek's logs show it (2026-10-23): command, axis, and a move's target or a Move's timeout. +FORCED_HM_MULTICHANNEL = [ + ("Set State", "Z", None), + ("Set Move Parameters", "Z", -1000), + ("Move", "Z", 30000), + ("Home", "Z", None), + ("Set State", "GZ", None), + ("Set Move Parameters", "GZ", 0), + ("Move", "GZ", 30000), + ("Set State", "GG", None), + ("Set Move Parameters", "GG", 0), + ("Move", "GG", 30000), + ("Home", "GG", None), + ("Set State", "GG", None), + ("Set Move Parameters", "GG", 35753), + ("Move", "GG", 30000), + ("Set State", "GR", None), + ("Set Move Parameters", "GR", 0), + ("Move", "GR", 30000), + ("Home", "GR", None), + ("Set State", "GR", None), + ("Set Move Parameters", "GR", -212581), + ("Move", "GR", 30000), + ("Set State", "GR", None), + ("Set Move Parameters", "GR", -174956), + ("Move", "GR", 30000), + ("Set State", "GY", None), + ("Set Move Parameters", "GY", 0), + ("Move", "GY", 30000), + ("Home", "GY", None), + ("Set State", "GZ", None), + ("Set Move Parameters", "GZ", 0), + ("Move", "GZ", 30000), + ("Home", "GZ", None), + ("Set State", "GY", None), + ("Set Move Parameters", "GY", 47574), + ("Move", "GY", 30000), + ("Set State", "Y", None), + ("Set Move Parameters", "Y", 0), + ("Move", "Y", 30000), + ("Home", "Y", None), + ("Set State", "Y", None), + ("Set Move Parameters", "Y", 0), + ("Move", "Y", 30000), + ("Set State", "GR", None), + ("Set Move Parameters", "GR", -141093), + ("Move", "GR", 30000), + ("Set State", "X", None), + ("Set Move Parameters", "X", 0), + ("Move", "X", 30000), + ("Home", "X", None), + ("Set State", "X", None), + ("Set Move Parameters", "X", 35840), + ("Move", "X", 30000), +] + + +def zero_sequence(message: bytes) -> str: + return (message[:3] + b"\x00" + message[4:]).hex() + + +def opcode_names(messages: List[str]) -> List[str]: + return [p.COMMANDS[(bytes.fromhex(h)[0], bytes.fromhex(h)[4])] for h in messages] + + +class SimulatedRunTest(unittest.IsolatedAsyncioTestCase): + """What each simulated board was sent since a mark.""" + + marks: Dict[str, int] + + async def asyncSetUp(self) -> None: + # IsolatedAsyncioTestCase runs its loop in debug mode, which records a stack for every + # callback and future; a simulated Home All makes thousands, and takes 3 s instead of 0.03 s. + # Nothing here is timed. The board-level tests keep debug mode's checks. + asyncio.get_running_loop().set_debug(False) + + async def start(self, homed, configured=None, configuration=None) -> BiomekI7Driver: + """A driver on the generic instrument simulated, read but not brought up; `configuration`, a + declared configuration to use instead of the generic one (sealed).""" + driver = generic_driver( + generic_simulated_boards(homed=homed, configured=configured), configuration=configuration + ) + await driver.setup(**READ_ONLY_SETUP) + self.addAsyncCleanup(driver.stop) + self.marks = {} + self.mark(driver) + return driver + + def usb(self, driver: BiomekI7Driver, module: str) -> SimulatedAceUSB: + for board in driver.boards: + if board.name == f"simulated {module}": + assert isinstance(board.io, SimulatedAceUSB) + return board.io + raise KeyError(module) + + def mark(self, driver: BiomekI7Driver) -> None: + for module in ("chassis", "multichannel", "span8"): + self.marks[module] = len(self.usb(driver, module).requests) + + def since_mark(self, driver: BiomekI7Driver, module: str) -> List[str]: + """What a board was sent since the mark, without the reads Biomek's recordings leave out.""" + requests = self.usb(driver, module).requests[self.marks[module] :] + return [zero_sequence(m) for m in requests if (m[0], m[4]) not in NOT_IN_RECORDINGS] + + +class HomeAllTests(SimulatedRunTest): + async def test_a_cold_home_all_sends_what_the_recorded_cold_start_sent(self) -> None: + """From power-up (nothing configured or homed), setup configures and homes; every request each + pod's board is sent that is not a read is one the Master Controller sent at the cold start the + generic recording was made from, first sent in the same order.""" + driver = generic_driver(generic_simulated_boards(homed=False, configured=False)) + self.addAsyncCleanup(driver.stop) + await driver.setup() + recording = generic_recording()["boards"] + for module in ("multichannel", "span8"): + sent: List[str] = [] + for m in self.usb(driver, module).requests: + key = (m[:3] + m[4:]).hex() + if not p.COMMANDS[(m[0], m[4])].startswith(READS) and key not in sent: + sent.append(key) + recorded = [ + key + for key, _ in recording[module] + if not p.COMMANDS[(int(key[0:2], 16), int(key[6:8], 16))].startswith(READS) + ] + self.assertGreater(len(sent), 40, module) + self.assertEqual(sent, recorded[: len(sent)], module) + + async def test_axes_end_where_biomek_leaves_them(self) -> None: + driver = await self.start(False) + await driver.configure() + await driver.home() + assert driver.left_x_arm and driver.right_x_arm + left = await driver.left_x_arm.request_positions() + self.assertEqual( + (left["X"], left["GY"], left["GG"], left["GR"]), (35840, 47574, 35753, -141093) + ) + right = await driver.right_x_arm.request_positions() + self.assertEqual((right["X"], right["Z1"], right["Z8"]), (-2560, 9647, 9647)) + for pod in driver.arms: + for axis in pod.axes: + if not axis.is_pump and axis.name != "D": # the plunger and pumps are homed apart (`HD`) + self.assertEqual(await pod.request_homed_state(axis.name), "homed", (pod.side, axis.name)) + + +class InitializeTests(SimulatedRunTest): + """`initialize`, which `setup` runs after discovery: homing forced or not, and refusals that come + before anything is written.""" + + async def start_initialized(self, homed, configured=None, **flags) -> BiomekI7Driver: + driver = await self.start(homed, configured) + await driver.initialize(**flags) + return driver + + def written(self, driver: BiomekI7Driver) -> List[str]: + return [ + name + for module in ("chassis", "multichannel", "span8") + for name in opcode_names(self.since_mark(driver, module)) + if not name.startswith(("Get ", "Read ", "List ")) + ] + + async def test_forced_on_a_homed_instrument_is_biomeks_home_all(self) -> None: + driver = await self.start_initialized(True, force_initialize=True) + assert driver.left_x_arm is not None + names = {(a.device, a.index): a.name for a in driver.left_x_arm.axes} + sent = [bytes.fromhex(h) for h in self.since_mark(driver, "multichannel")] + decoded = [] + for m in sent: + name = p.COMMANDS[(m[0], m[4])] + value = None + if name == "Set Move Parameters": + value = struct.unpack_from(" None: + forced = await self.start_initialized(True, force_initialize=True) + forced_sent = {m: self.since_mark(forced, m) for m in ("multichannel", "span8")} + driver = await self.start_initialized(True) + names = self.written(driver) + self.assertNotIn("Configure", names) + self.assertNotIn("Home", names) + for module in ("multichannel", "span8"): + sent = self.since_mark(driver, module) + # Every move is one Biomek makes, in Biomek's order: the default only leaves homes out. + moves = [h for h in sent if bytes.fromhex(h)[4] == 0x40] + forced_moves = [h for h in forced_sent[module] if bytes.fromhex(h)[4] == 0x40] + it = iter(forced_moves) + self.assertTrue(all(m in it for m in moves), module) + assert driver.left_x_arm and driver.right_x_arm + left = await driver.left_x_arm.request_positions() + self.assertEqual( + (left["X"], left["GY"], left["GG"], left["GR"], left["Z"]), + (35840, 47574, 35753, -141093, -1000), + ) + right = await driver.right_x_arm.request_positions() + self.assertEqual((right["X"], right["Z1"], right["Z8"]), (-2560, 9647, 9647)) + + def moves(self, driver: BiomekI7Driver) -> List[str]: + """Every Set Move Parameters, Move, Move All and Home sent since the mark.""" + motion = {"Set Move Parameters", "Move", "Move All", "Home"} + return [ + name + for module in ("multichannel", "span8") + for name in opcode_names(self.since_mark(driver, module)) + if name in motion + ] + + async def test_resume_moves_an_axis_pushed_by_hand_back(self) -> None: + driver = await self.start_initialized(True) + left = self.usb(driver, "multichannel") + await driver.pause() + x = left.axis_model("X") + paused_at = x.position + x.position += 2000 # pushed by hand while the drives had no power + await driver.resume() + self.assertEqual(x.position, paused_at) + + async def test_no_pod_moves_beside_a_skipped_pod_whose_x_is_not_homed(self) -> None: + for flags in ( + dict(skip_right_x_arm=True), + dict(skip_device_initialization=True), # the right pod is left out, unconfigured + ): + with self.subTest(**flags): + driver = await self.start( + {"multichannel": ["X"]}, configured={"multichannel": True, "span8": False} + ) + with self.assertRaisesRegex(RuntimeError, "shared X rail"): + await driver.initialize(**flags) + self.assertEqual(self.written(driver), []) + + async def test_a_skipped_pod_with_x_homed_is_left_alone(self) -> None: + driver = await self.start_initialized(True, skip_right_x_arm=True) + self.assertEqual( + [n for n in opcode_names(self.since_mark(driver, "span8")) if not n.startswith("Get ")], [] + ) + self.assertIn("Move", opcode_names(self.since_mark(driver, "multichannel"))) + + async def test_setup_brings_the_instrument_up(self) -> None: + driver = generic_driver(generic_simulated_boards()) + self.addAsyncCleanup(driver.stop) + await driver.setup() + assert driver.right_x_arm + self.assertEqual(await driver.right_x_arm.request_homed_state("Y4"), "homed") + await driver.setup() # repeatable: an instrument that is up is left up + self.assertEqual(await driver.right_x_arm.request_homed_state("Y4"), "homed") + + +class RecipeTests(unittest.TestCase): + def setUp(self) -> None: + async def discover() -> list: + driver = generic_driver() + await driver.discover() + await driver.stop() + return list(driver.arms) + + self.pods = {pod.module_type: pod for pod in asyncio.run(discover())} + + def test_every_target_is_within_the_axis_limits(self) -> None: + for module, steps in HOME_RECIPES.items(): + pod = self.pods[module] + homer = Homer(pod) + for step in steps: + for name, target in homer.targets(step): + pod.axis(name).check_position(target) + + def test_post_home_targets_are_the_recorded_home_positions(self) -> None: + """Where a recipe leaves X, the left Y and the gripper axes is the Master Controller's `phome` + for them, as the motor recording carries it.""" + for module, steps in HOME_RECIPES.items(): + pod = self.pods[module] + homer = Homer(pod) + last: Dict[str, int] = {} + for step in steps: + for name, target in homer.targets(step): + last[name] = target + for name in ("X", "GY", "GG", "GR") + (("Y",) if module == "multichannel" else ()): + self.assertEqual(last[name], pod.axis(name).home_position, (module, name)) + + def test_the_gripper_turns_from_its_home_position(self) -> None: + # Home, then 190 and 90 degrees from the home position, then the home position: the counts + # Biomek's homes sent. + for module, pod in self.pods.items(): + homer = Homer(pod) + turns = [t for step in HOME_RECIPES[module] for n, t in homer.targets(step) if n == "GR"] + self.assertEqual(turns, [0, -212581, -174956, -141093], module) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index 75859505457..57a539f3510 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -16,8 +16,21 @@ import asyncio import logging -from typing import Awaitable, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union +from typing import ( + Awaitable, + Callable, + Dict, + Iterable, + List, + Mapping, + Optional, + Sequence, + Set, + Tuple, + Union, +) +from pylabrobot.beckman_coulter.biomek_i7.driver import motion from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import ( ACE_PRODUCT_ID, @@ -31,7 +44,8 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door -from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import MoveResult, Pod +from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import XRail from pylabrobot.io.usb import USB logger = logging.getLogger(__name__) @@ -91,7 +105,7 @@ def __init__( `DeviceConfiguration.from_biomek` makes it from the instrument's Biomek files. Required: the driver never falls back to another, the package's generic one included. boards: boards to use instead of opening USB devices: a simulated instrument - (`simulator.replay_boards`). With them, the checks that tie the configuration to a real + (`simulator.simulated_boards`). With them, the checks that tie the configuration to a real instrument (`discover`) are not made. Raises: @@ -118,12 +132,15 @@ def __init__( ), ) self.motor_tables = self.declared.motor_tables + # Called when a head's tips change; the device saves its heads' tips on it (`state_json`). + self.on_tips_changed: Callable[[], None] = lambda: None self._given_boards = list(boards) if boards is not None else None self.boards: List[AceBoard] = [] self._connected = False self._armed = False # this driver armed the interlock, and has not tripped it since self._tripping = False # this driver is tripping it: the chassis's trip event is our own - self._paused = False # paused (`pause`), waiting for `resume` + # While paused (`pause`): each pod's positions when the pause began, by side. + self._paused: Optional[Dict[str, Dict[str, int]]] = None # Set while the interlock is tripped as far as this driver knows: from the start, when the # chassis reports a trip, or when this driver trips it; cleared when it arms it. self.interlock_tripped = asyncio.Event() @@ -131,7 +148,9 @@ def __init__( self._unwatch: List[Callable[[], None]] = [] self._background: Set["asyncio.Task[None]"] = set() self.chassis: Optional[Chassis] = None - # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, Feature map). + # The shared X rail (design.md I7), built at discovery from the declared pod geometry. + self.rail: Optional[XRail] = None + # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, The pods). self.left_x_arm: Optional[Pod] = None self.right_x_arm: Optional[Pod] = None @@ -143,29 +162,31 @@ async def setup( *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, + force_initialize: bool = False, ) -> None: """Connect to the instrument, find out what it is, and bring it up. - `discover` is the read-only part; then the motor tables are loaded where a board has lost them, - the interlock is armed and every axis enabled. Nothing moves: the drives hold where they stand. - With every skip below set, setup only reads. Repeatable: the boards stay open and discovery - reads them again. A setup that fails part way releases the boards. + This moves the arms: every pod is homed. `discover` is the read-only part; with every skip + below set, setup only reads. Repeatable: the boards stay open, discovery reads them again, and + initializing an instrument that is up re-homes nothing (unless `force_initialize`). A setup that + fails part way releases the boards. Args: skip_device_initialization: do not load motor tables, even into a board that has lost them. - A pod with an axis not configured is then left as it is. - skip_left_x_arm: leave the left pod as it is: not configured or enabled. + A pod with an axis not configured is then left as it is, and cannot move. + skip_left_x_arm: leave the left pod as it is: not configured, enabled or moved. skip_right_x_arm: leave the right pod as it is. + force_initialize: home again axes that are already homed, as Biomek's Home All does. Raises: - RuntimeError: if no chassis is found, a board cannot be placed (`discover`), or the - interlock or a drive supply does not come up. - ValueError: for a declared configuration that is not this instrument's (`discover`). - AceError: if an axis cannot be enabled; the interlock is then tripped and ERROR shown. + RuntimeError: if no chassis is found, two modules claim the same place, an axis reports a + fault, or a pod would move on the X rail beside a skipped pod whose X is not homed. """ logger.warning( - "The Biomek i7 driver's discovery, configuration and interlock have run on one instrument; " - "they are untested on other instruments. Please report what works and what does not." + "The Biomek i7 driver's discovery, configuration, interlock, Home All and moves have run on " + "one instrument; its commands were compared with Biomek's logs where Biomek ran the same " + "operation; it is untested on other instruments. Please report what works and what does " + "not." ) if not self._connected: await self._open() @@ -175,6 +196,7 @@ async def setup( skip_device_initialization=skip_device_initialization, skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm, + force_initialize=force_initialize, ) except BaseException: await self.stop() @@ -209,8 +231,7 @@ async def discover(self) -> None: Each board says what it is: Get Module ID answers a module type (`protocol.MODULE_TYPES`: chassis, Multichannel, Span-8) and a side (left, right). That, not its USB serial number or order, places it. Seen on one instrument; an unknown type or side, two boards claiming one - place, no chassis, or a pod type other than the declared one is refused - (`_check_declared_against`). + place, no chassis, or a pod type other than the declared one is refused (`_check_declared_against`). On the instrument (no `boards` given), two checks follow, each refusing: - the declared configuration must be this instrument's: its chassis serial number and each @@ -261,7 +282,11 @@ async def discover(self) -> None: if "right" in places else None ) + self.rail = XRail({pod.side: pod.declared for pod in self.arms}) self._watch_faults() + for pod in self.arms: + pod.rail = self.rail + self.rail.readers[pod.side] = pod.request_rail_pose modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())] for pod in self.arms: modules.append((str(pod), await pod.discover())) @@ -384,16 +409,20 @@ async def stop(self) -> None: """Return the instrument to rest and release every board. Moves nothing. If this driver armed the interlock, as the Master Controller does when its host goes away: each - pod's module is stopped (Stop Module Execution), then the interlock is tripped and READY shown. - Otherwise nothing is written. What the boards do on their own when the host goes away is not - known. + pod's module is stopped (Stop Module Execution) and its positions forgotten, then the + interlock is tripped and READY shown. Otherwise nothing is written. What the boards do on their + own when the host goes away is not known. """ + # As the Master Controller does when its host goes away: stop each pod's + # module, forget its positions, then trip the interlock. Only while this driver has the + # interlock armed: otherwise the drives have no power, and a read-only session writes nothing. if self._armed: for pod in self.arms: try: await asyncio.wait_for(pod._unchecked_fw_stop_module_execution(), REST_TIMEOUT) except BaseException: logger.exception("could not stop %s", pod) + pod._forget_positions() await self._return_to_rest() for unwatch in self._unwatch: unwatch() @@ -454,8 +483,9 @@ async def request_axis_states(self) -> Dict[str, Dict[str, p.AxisStateName]]: """Every axis's state, by pod side then axis name. Moves nothing.""" return {pod.side: await pod.request_axis_states() for pod in self.arms} - # -- configuration and interlock ------------------------------------------------ - # These write to the boards. Run them only on a clear deck, with someone at the emergency stop. + # -- configuration, interlock and homing --------------------------------------- + # These write to the boards and move the arms. Run them only on a clear deck, with someone at + # the emergency stop. def _require_chassis(self) -> Chassis: if self.chassis is None: @@ -474,23 +504,27 @@ async def initialize( *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, + force_initialize: bool = False, ) -> None: - """Bring the instrument up: what `setup` does after discovery. + """Bring the instrument up: what `setup` does after discovery, and what Home All is later. Reads every axis's state first. A pod with an axis not configured (the board was powered up, or a drive lost its parameters) has its motor tables loaded; one fully configured does not, since - loading them again would un-home it. Then the interlock is armed and every axis enabled - (`arm_interlock`). The arguments are those of `setup`. + loading them again would un-home it. Then the pods are homed together (`home`). The arguments + are those of `setup`. An axis in fault is not refused: enabling it is its fault reset, as when Biomek re-arms and enables after a fault, and calling this is the person's go-ahead that Biomek waits for. A CiA 402 drive in fault with its motor supply off is the instrument at rest and is only noted; any other fault is warned about, since under power it usually means a following error or a - collision. A fault that does not clear fails the enable, and the instrument is returned to rest. + collision. A fault that does not clear fails the enable, and `home` returns the instrument to + rest before anything moves. Raises: - RuntimeError: if the interlock or a drive supply does not come up when armed. - AceError: if an axis cannot be enabled; the interlock is then tripped and ERROR shown. + RuntimeError: if a pod would move on the X rail beside a skipped pod whose X is not homed + (nothing has been written), or the drive supply does not come up when armed. + AceError: if an axis cannot be enabled, or a move or home fails; the interlock is then + tripped and ERROR shown. """ skipped = self.skipped_sides(skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm) pods = [pod for pod in self.arms if pod.side not in skipped] @@ -528,14 +562,12 @@ async def initialize( ) pods = [pod for pod in pods if pod not in unconfigured] unconfigured = [] + if pods: + await self._check_shared_x_rail(pods) if unconfigured: await self.configure(unconfigured) if pods: - try: - await self.arm_interlock(pods) - except BaseException: - await self._return_to_rest(error=True) - raise + await self.home(pods, force=force_initialize) # A pod that answered every request is not a pod that came up, so each is asked again. states = await self.request_axis_states() @@ -548,6 +580,27 @@ async def initialize( if down: logger.warning("initialize finished with these axes not enabled: %s", ", ".join(down)) + async def _check_shared_x_rail(self, moving: Sequence[Pod]) -> None: + """Refuse to move pods on the X rail beside a pod left out whose X is not homed: where that pod + stands is not known. Reads only. + + Raises: + RuntimeError: if a pod left out has its X not homed. + """ + for pod in self.arms: + if pod in moving: + continue + others = ", ".join(str(m) for m in moving) + if await pod.request_homed_state("X") != "homed": + raise RuntimeError( + f"the {pod} is left as it is and its X is not homed, so where it stands on the shared X " + f"rail is not known; the {others} cannot move beside it. Bring up both pods. Nothing was " + "moved" + ) + logger.warning( + "the %s is left as it is; the %s's X moves are not checked against it", pod, others + ) + async def configure(self, pods: Optional[Sequence[Pod]] = None) -> None: """Load the motor tables into pods' boards (every pod by default), as after a power-up. Moves nothing. @@ -591,6 +644,63 @@ async def arm_interlock(self, pods: Optional[Sequence[Pod]] = None) -> None: raise RuntimeError(f"{pod}: the drive supply reads {supply:.1f} V with the interlock armed") await _together(pod.enable_axes() for pod in targets) + async def home(self, pods: Optional[Sequence[Pod]] = None, force: bool = False) -> None: + """Home pods (every pod by default) at once, the Master Controller's Home All without its + Span-8 priming. + + Arms the interlock, then homes the pods together, as Biomek does: each runs its `HM` recipe. + Needs the motor tables loaded (`initialize` sees to it). + + If anything fails once the interlock is armed, ERROR is shown and the interlock tripped, which + cuts the drives' power, before the error is raised; nothing is retried. Biomek instead leaves + the drives powered while its dialog waits for the person; here no one may be waiting, so the + instrument goes back to rest. + + Args: + pods: the pods to home. + force: home again axes already homed, as Biomek does. Without it they are only moved to + where a Home leaves them. + """ + targets = self.arms if pods is None else list(pods) + + try: + await self.arm_interlock(targets) + await _together(pod.home(force=force) for pod in targets) + except BaseException: + await self._return_to_rest(error=True) + raise + + async def move_axes( + self, targets: Mapping[str, Mapping[str, int]], speed: int = 1000 + ) -> Dict[str, MoveResult]: + """Move axes of both pods at once: each pod's `AM` (`Pod.move_axes`), started together, as + Biomek runs the two pods' steps. The shared X rail keeps them apart: a move into the other + pod's range is refused, and one crossing only the other's path waits for it. + + Args: + targets: per pod side (`left`, `right`), its axes' targets in counts. + speed: 1..1000, Biomek's speed field, for both. + + Returns: + Each pod's result, by side. + + Raises: + ValueError: for a side with no pod. Otherwise as `Pod.move_axes`; if one pod's move fails, + the other's is cancelled and waited for first. Nothing returns the instrument to rest: + whether to is the caller's (design.md I5). + """ + pods: Dict[str, Pod] = {pod.side: pod for pod in self.arms} + missing = sorted(set(targets) - set(pods)) + if missing: + raise ValueError(f"no pod on the {', '.join(missing)}; have {sorted(pods)}") + results: Dict[str, MoveResult] = {} + + async def move(side: str) -> None: + results[side] = await pods[side].move_axes(targets[side], speed) + + await _together(move(side) for side in targets) + return results + async def _return_to_rest(self, error: bool = False) -> None: """Trip the interlock, if this driver armed it, and show READY (ERROR with `error`). Never raises: it runs on the way out of a failure.""" @@ -615,25 +725,26 @@ async def _trip(self, error: bool) -> None: self._tripping = False # -- pause for access -------------------------------------------------------------- - # Biomek's whole-system pause, as its logs show it: a deliberate interlock trip with PAUSED shown; - # resuming re-arms and enables every axis. There is no mute: the light curtain may be broken only - # because the drives have no power. + # Biomek's whole-system pause, as its logs show it: a deliberate interlock trip with PAUSED shown + # and the pods' positions saved; resuming re-arms, enables every axis and moves the pods back. + # There is no mute: the light curtain may be broken only because the drives have no power. @property def paused(self) -> bool: """Whether the instrument is paused (`pause`), waiting for `resume`.""" - return self._paused + return self._paused is not None async def pause(self) -> None: """Pause for access: cut the pods' drive power and show PAUSED, so the light curtain may be broken without an error. Call it between operations, as Biomek's Pause step runs between - steps. + steps: a move still running is stopped where it is. Moving the pods out of the way first is + the caller's. Each pod's positions are read and kept for `resume`. Raises: RuntimeError: if the interlock is not armed by this driver (nothing to pause), or the instrument is already paused. """ - if self._paused: + if self._paused is not None: raise RuntimeError("the instrument is already paused") if not self._armed: raise RuntimeError("the interlock is not armed: nothing to pause") @@ -646,17 +757,34 @@ async def pause(self) -> None: finally: self._tripping = False await chassis._unchecked_fw_set_status_display("paused") - self._paused = True + # Biomek reads the positions after the trip; the drives answer without power. Kept as the + # adjusted positions moves take (a Span-8 Z channel's hysteresis), as the driver keeps them. + saved: Dict[str, Dict[str, int]] = {} + for pod in self.arms: + read = await pod.request_positions() + saved[pod.side] = { + name: motion.update_cpos(pod.cpositions[name], counts, pod.axis(name).hysteresis)[1] + for name, counts in read.items() + } + pod._forget_positions() + self._paused = saved logger.info("paused: the interlock is tripped; the light curtain may be broken") - async def resume(self) -> None: - """Resume after `pause`: re-arm the interlock and enable every axis. Nothing is homed. + async def resume(self, speed: int = 200) -> None: + """Resume after `pause`: re-arm the interlock, enable every axis, then move each pod back to + where it was when paused (an axis pushed by hand is returned; the plunger and syringe pumps + are not, as Biomek does not, nor is a gripper holding labware opened or closed). Nothing is + homed. + + Args: + speed: 1..1000, Biomek's speed field, for the moves back. Raises: RuntimeError: if not paused, or if the interlock does not arm (the light curtain still broken): the instrument stays paused, so clear it and call `resume` again. """ - if not self._paused: + saved = self._paused + if saved is None: raise RuntimeError("the instrument is not paused") try: await self.arm_interlock() @@ -664,8 +792,18 @@ async def resume(self) -> None: self._armed = False self.interlock_tripped.set() raise - self._paused = False + self._paused = None logger.info("resumed: the interlock is armed") + for pod in self.arms: + keep = {"D"} | ({"GG"} if pod._held_labware is not None else set()) + back = { + name: counts + for name, counts in saved.get(pod.side, {}).items() + if name not in keep and not pod.axis(name).is_pump + } + if any(pod.cpositions[name][1] != counts for name, counts in back.items()): + logger.info("%s moving back to where it was paused", pod.component) + await pod.move_axes(back, speed) # -- faults the boards report unasked ------------------------------------------ # As the Master Controller handles them, as its logs show it. @@ -707,14 +845,18 @@ def _on_pod_message(self, pod: Pod, reply: p.Reply) -> None: error = ace_error(reply.error_code, reply.device_error, f"{pod} {axis}") logger.error("The %s %s motor failed: %s.", pod.side, axis, error) self.interlock_tripped.set() + for each in self.arms: + each._forget_positions() self._in_background(self._trip(error=True)) def _interlock_tripped(self, reason: str) -> None: - """What the Master Controller does when the interlock trips under a running instrument: waits - end, and ERROR is shown. A trip this driver made itself (at rest, or after a failure) only marks - it tripped.""" + """What the Master Controller does when the interlock trips under a running instrument: every + position is forgotten (read again after re-arming), waits end, and ERROR is shown. A trip this + driver made itself (at rest, or after a failure) only marks it tripped.""" ours = self._tripping or not self._armed self.interlock_tripped.set() + for pod in self.arms: + pod._forget_positions() if ours: return logger.error("the interlock tripped: %s", reason) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motion.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motion.py new file mode 100644 index 00000000000..5161162969a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motion.py @@ -0,0 +1,395 @@ +"""Biomek's coordinated-move model: how the Master Controller turns one `AM` into each axis's move. + +Pure arithmetic, no board access. It reproduces the requests the Master Controller sends for +each `AM`. Per `AM`: + +1. Each axis's distance comes from where the Master Controller last put it, not from a position + read: per axis it keeps `(position, adjusted)` (`cpositions`), the position it last commanded + and the one it targets for hysteresis. `adjust_delta` adds an axis's hysteresis (only the Span-8 + Z channels have any) to moves in one direction; `update_cpos` keeps the pair afterwards. +2. `get_scaling_factors`: per axis, velocity, acceleration and jerk per count of travel, the + slowest axis winning: `max(min limit, speed/1000 x max limit) / distance`. Axes are grouped: + each Span-8 channel's pump (D1-D8) and its Z, while that pump moves, have their own group, so + eight channels aspirating different volumes each finish together with their own Z; everything + else is one group, scaled by the slowest axis anywhere. +3. `get_motions_and_duration`: each axis's velocity/acceleration/jerk is its factor x its distance, + rounded and clamped to its limits; jerk is then corrected (`correct_j`) so the S-curve's phases + land on the board's 2.5 kHz servo ticks; pumps are rounded to their own steps. The move takes the + longest axis's time (`motor_move_time`, from the uncorrected jerk), rounded up to the ms. +4. The Move All carries that duration + 5000 ms as its timeout. + +Integer division is exact (`Fraction`) until something inexact (a float) enters, so results match +the Master Controller's logged requests to the last count. +""" + +import math +from dataclasses import dataclass +from fractions import Fraction +from typing import Dict, List, Mapping, Optional, Sequence, Tuple, TypeVar, Union + +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis + +Number = Union[int, Fraction, float] +CPos = Tuple[Optional[int], int] +"""An axis's `(position, adjusted)`: the position last commanded (None when unknown, as after a +force-limited move), and the position its next move is planned from.""" + +MOVE_ALL_MARGIN_MS = 5000 +"""Added to the planned duration for the Move All's timeout, as logged.""" + +PARTITIONED = {f"D{n}": n for n in range(1, 9)} +PARTITIONED_Z = {f"Z{n}": n for n in range(1, 9)} + + +@dataclass(frozen=True) +class Motion: + """One axis's move in a coordinated move, in counts; `jerk` None for an axis that + takes none (trapezoidal profile, pumps).""" + + axis: str + position: int + velocity: int + acceleration: int + jerk: Optional[int] + + +# -- exact arithmetic ---------------------------------------------------------------------------- + + +def _inexact(*xs: Number) -> bool: + return any(isinstance(x, float) for x in xs) + + +def _min(*xs: Number) -> Number: + m = min(xs) + return float(m) if _inexact(*xs) else m + + +def _max(*xs: Number) -> Number: + m = max(xs) + return float(m) if _inexact(*xs) else m + + +def _div(x: Number, *ys: Number) -> Number: + """`/`, exact when every argument is.""" + for y in ys: + x = x / y if _inexact(x, y) else Fraction(x) / Fraction(y) + return x + + +def _sqrt(x: Number) -> Number: + """`sqrt`, exact for an exact perfect square, inexact otherwise.""" + if not isinstance(x, float): + f = Fraction(x) + if f >= 0: + n, d = math.isqrt(f.numerator), math.isqrt(f.denominator) + if n * n == f.numerator and d * d == f.denominator: + return Fraction(n, d) + return math.sqrt(float(x)) + + +def _cbrt(x: Number) -> float: + """x ** 0.3333333333333333, as the Master Controller computes the cube root.""" + return math.pow(float(x), 0.3333333333333333) + + +def _exact_round(x: Number) -> int: + """x rounded half to even, as Python's `round`.""" + return round(x) + + +def range_(lo: Number, x: Number, hi: Number) -> Number: + """x clamped to [lo, hi].""" + return lo if x < lo else (x if x < hi else hi) + + +def quantize(x: Number, width: float) -> int: + """x to the nearest multiple of width.""" + return int(round(_div(x, width)) * width) + + +# -- move times ------------------------------------------------------------------------------------ + + +def _s_curve_phases(d: Number, v_max: Number, a_max: Number, j: Number) -> Tuple[Number, Number]: + t1a = _min(_sqrt(_div(v_max, j)), _cbrt(_div(d, 2, j))) + t1b = _div(a_max, j) + if t1a < t1b: + return t1a, t1a + x = _div(a_max, 2, j) + return t1b, _min(_div(v_max, a_max), _sqrt(x * x + _div(d, a_max)) - x) + + +def s_curve_move_time(d: Number, v_max: Number, a_max: Number, j: Number) -> Number: + """Seconds for an S-curve move of d counts.""" + if d > 0 and v_max > 0 and a_max > 0 and j > 0: + t1, t2 = _s_curve_phases(d, v_max, a_max, j) + return _div(d, j, t1, t2) + t1 + t2 + if d == 0: + return 0 + raise ValueError(f"s_curve_move_time: invalid input {d} {v_max} {a_max} {j}") + + +def trapezoid_move_time(d: Number, v_max: Number, a: Number) -> Number: + """Seconds for a trapezoidal move of d counts.""" + if d > 0 and v_max > 0 and a > 0: + t1a, t1b = _div(v_max, a), _sqrt(_div(d, a)) + return t1a + _div(d, v_max) if t1a < t1b else t1b * 2 + if d == 0: + return 0 + raise ValueError(f"trapezoid_move_time: invalid input {d} {v_max} {a}") + + +def trapezoid_a_for_s_curve(d: Number, v_max: Number, a_max: Number, j: Number) -> Number: + """The acceleration a trapezoidal move needs to take as long as the + S-curve one (so an axis without jerk keeps pace with ones that have it).""" + if not (d > 0 and v_max > 0 and a_max > 0 and j > 0): + raise ValueError(f"trapezoid_a_for_s_curve: invalid input {d} {v_max} {a_max} {j}") + t1, t2 = _s_curve_phases(d, v_max, a_max, j) + return _div(j * t1 * t2, t1 + t2) + + +def motor_move_time(d: Number, v: Number, a: Number, j: Optional[Number]) -> Number: + """Seconds for a motor's move.""" + return s_curve_move_time(d, v, a, j) if j else trapezoid_move_time(d, v, a) + + +def pump_move_time(d: Number, v_max: Number, a: Number, s: Number, c: Number) -> Number: + """Seconds for a syringe pump move of d counts, starting at velocity s and + ending at cutoff velocity c.""" + if d > 0 and v_max > 0 and a > 0: + s = _min(s, v_max) + c = _max(s, _min(c, v_max)) + tmp1 = s * s + 2 * a * d + if tmp1 < c * c: + return _div(_sqrt(tmp1) - s, a) + tmp2 = _div(s * s + c * c, 2) + p = _min(_sqrt(a * d + tmp2), v_max) + return _div(d, p) + _div(p - s - c + _div(tmp2, p), a) + if d == 0: + return 0 + raise ValueError(f"pump_move_time: invalid input {d} {v_max} {a} {s} {c}") + + +# -- coordination (the Master Controller's coordinated move) ------------------------------------- + + +def correct_j(d: int, v_max: int, a_max: int, j: int, jmin: int, jmax: int) -> int: + """The jerk sent, adjusted so the S-curve's jerk phase (t1) and, when it reaches its + maximum acceleration, its acceleration phase (t2) are whole 0.4 ms servo ticks.""" + + def q(x: Number) -> float: + return round(float(x) * 2500.0) * (1 / 2500.0) + + def correct(t1: float, t2: float) -> int: + if t1 > 0.0 and t2 > 0.0: + return int(range_(jmin, _exact_round(v_max / (t1 * t2)), jmax)) + return j + + t1a = _div(a_max, j) + t1b = _sqrt(_div(v_max, j)) + t1c = _cbrt(_div(d, 2, j)) + if t1a <= t1b and t1a <= t1c: + t2a = _div(v_max, a_max) + x = _div(t1a, 2) + t2b = _sqrt(x * x + _div(d, a_max)) - x + return correct(q(t1a), q(t2a)) if t2a < t2b else j + if t1b < t1a and t1b < t1c: + t1 = q(t1b) + return correct(t1, t1) + return j + + +def _partition(axes: Sequence[Axis], deltas: Sequence[int], i: int) -> int: + name = axes[i].name + if name in PARTITIONED: + return PARTITIONED[name] + if name in PARTITIONED_Z: + n = PARTITIONED_Z[name] + for k, a in enumerate(axes): + if a.name == f"D{n}": + return 0 if deltas[k] == 0 else n + return 0 + + +def get_scaling_factors( + axes: Sequence[Axis], deltas: Sequence[int], fspeed: float +) -> List[Optional[List[Number]]]: + """Per moving axis, its group's [velocity, acceleration, jerk] per count + of travel (None for an axis that does not move). Group 0's factors end as the minimum over every + group; each other group's as the minimum of its own and group 0's (as it was before that).""" + factors: List[List[Number]] = [[math.inf, math.inf, math.inf] for _ in range(9)] + out: List[Optional[List[Number]]] = [] + for i, (axis, delta) in enumerate(zip(axes, deltas)): + if delta == 0: + out.append(None) + continue + d = abs(delta) + lim = axis.limits + f = factors[_partition(axes, deltas, i)] + f[0] = _min(_div(_max(lim.min_velocity, fspeed * lim.max_velocity), d), f[0]) + f[1] = _min(_div(_max(lim.min_acceleration, fspeed * lim.max_acceleration), d), f[1]) + if lim.max_jerk: + f[2] = _min(_div(_max(lim.min_jerk, fspeed * lim.max_jerk), d), f[2]) + out.append(f) + f0 = factors[0] + for fi in factors[1:]: + for k in range(3): + fi[k] = _min(f0[k], fi[k]) + for fi in factors[1:]: + for k in range(3): + f0[k] = _min(f0[k], fi[k]) + return out + + +def get_motions_and_duration( + axes: Sequence[Axis], + cpositions: Sequence[CPos], + deltas: Sequence[int], + fspeed: float, + cutoff_velocity: int = 0, +) -> Tuple[List[Motion], int]: + """Each moving axis's motion, and the move's duration in ms (the slowest + axis's, rounded up). `cutoff_velocity` is the Span-8 pumps' (0 on a Multichannel).""" + scaling = get_scaling_factors(axes, deltas, fspeed) + motions: List[Motion] = [] + duration: Number = 0 + for i, (axis, cpos, delta) in enumerate(zip(axes, cpositions, deltas)): + if delta == 0: + continue + d = abs(delta) + factor = scaling[i] + assert factor is not None + k_v, k_a, k_j = factor + lim = axis.limits + + def cvt(k: Number) -> int: + return _exact_round(k * d) + + velocity = int(range_(lim.min_velocity, cvt(k_v), lim.max_velocity)) + k_acc = k_a if lim.max_jerk or math.isinf(k_j) else trapezoid_a_for_s_curve(1, k_v, k_a, k_j) + acceleration = int(range_(lim.min_acceleration, cvt(k_acc), lim.max_acceleration)) + jerk = int(range_(lim.min_jerk, cvt(k_j), lim.max_jerk)) if lim.max_jerk else None + if cpos[0] is None: + raise ValueError(f"{axis.name}: position unknown; read it before planning a move") + position = delta + cpos[0] + if axis.is_pump: + pump = axis.pump_limits + s = pump.min_start_velocity + velocity, acceleration = quantize(velocity, 4.0), quantize(acceleration, 10000.0) + if delta > 0 and pump.backlash > 0: + t = pump_move_time(d + pump.backlash, velocity, acceleration, s, s) + pump_move_time( + pump.backlash, velocity, acceleration, s, cutoff_velocity + ) + else: + t = pump_move_time(d, velocity, acceleration, s, cutoff_velocity) + motions.append(Motion(axis.name, position, velocity, acceleration, None)) + else: + sent = ( + correct_j(d, velocity, acceleration, jerk, lim.min_jerk, lim.max_jerk) + if jerk is not None + else None + ) + t = motor_move_time(d, velocity, acceleration, jerk) + motions.append(Motion(axis.name, position, velocity, acceleration, sent)) + duration = _max(duration, t) + return motions, math.ceil(1000 * duration) + + +# -- positions and hysteresis ---------------------------------------------------------------------- + + +def adjust_delta(cpos: CPos, delta: int, hysteresis: int) -> int: + """The distance an axis travels for a move of `delta` from its adjusted position, + with its hysteresis added when moving in hysteresis's direction (negative hysteresis: downward + moves).""" + if hysteresis == 0 or delta == 0: + return delta + if cpos[0] is None: + raise ValueError("position unknown; read it before planning a move") + offset = cpos[1] - cpos[0] + if hysteresis < 0: + return delta + offset + hysteresis if delta < 0 else delta + offset + return delta + offset if delta < 0 else delta + offset + hysteresis + + +def update_cpos(cpos: CPos, position: int, hysteresis: int) -> CPos: + """An axis's `(position, adjusted)` once it is at `position`.""" + if hysteresis == 0: + return position, position + adjusted = cpos[1] + if hysteresis < 0: + if position < adjusted + hysteresis: + return position, position - hysteresis + return (position, adjusted) if position <= adjusted else (position, position) + if position < adjusted: + return position, position + return ( + (position, adjusted) if position <= adjusted + hysteresis else (position, position - hysteresis) + ) + + +T = TypeVar("T") + + +def spawn_order(motions: Sequence[T]) -> List[T]: + """The order the Master Controller's per-axis requests of one move reach the board: the motions + reversed, taken two at a time from the end, each pair in order. Motions 1..5 go out as 1, 3 2, + 5 4. Matches every multi-axis move logged.""" + reverse = list(reversed(motions)) + pairs = [reverse[i : i + 2] for i in range(0, len(reverse), 2)] + return [m for pair in reversed(pairs) for m in pair] + + +def span_targets( + cpositions: Mapping[str, CPos], y: Optional[int] = None, span: Optional[int] = None +) -> Dict[str, int]: + """The Span-8 channels' Y targets for a move given Biomek's `Y` (channel 1) and `S` (the span from + channel 1 to 8), in counts, as the Master Controller's logged moves place them. + An omitted `y` is channel 1's adjusted position, an omitted `span` the current span + (max(Y8 - Y1, 0), adjusted); channel i goes to y + round((i - 1) * span / 7), an exact ratio + rounded half to even. + + Raises: + ValueError: for a negative span. + """ + y1, y8 = cpositions["Y1"][1], cpositions["Y8"][1] + y = y1 if y is None else y + span = max(y8 - y1, 0) if span is None else span + if span < 0: + raise ValueError(f"span {span} is negative") + return {f"Y{i}": y + round(Fraction((i - 1) * span, 7)) for i in range(1, 9)} + + +def plan_move( + axes: Sequence[Axis], + cpositions: Mapping[str, CPos], + targets: Mapping[str, int], + speed: int = 1000, + cutoff_velocity: int = 0, +) -> Tuple[List[Motion], int, Dict[str, CPos]]: + """An absolute coordinated move, as the Master Controller plans an `AM`: each target is + where the axis's adjusted position should end. Returns the motions (axes already there are left + out), the Move All timeout in ms (duration + 5000), and every axis's `(position, adjusted)` + after the move. + + Raises: + ValueError: for a speed outside 1..1000 or an unknown axis. + """ + if not 1 <= speed <= 1000: + raise ValueError(f"speed {speed} is outside 1..1000") + names = {a.name for a in axes} + unknown = set(targets) - names + if unknown: + raise ValueError(f"no axes named {sorted(unknown)}; have {sorted(names)}") + cpos = [cpositions[a.name] for a in axes] + deltas = [ + adjust_delta(c, targets[a.name] - c[1], a.hysteresis) if a.name in targets else 0 + for a, c in zip(axes, cpos) + ] + motions, duration = get_motions_and_duration(axes, cpos, deltas, speed / 1000.0, cutoff_velocity) + after = dict(cpositions) + for m in motions: + axis = next(a for a in axes if a.name == m.axis) + after[m.axis] = update_cpos(cpositions[m.axis], m.position, axis.hysteresis) + return motions, duration + MOVE_ALL_MARGIN_MS, after diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motion_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motion_tests.py new file mode 100644 index 00000000000..2b670a9133f --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motion_tests.py @@ -0,0 +1,329 @@ +"""Biomek's coordinated-move model, checked against coordinated moves Biomek made. + +`LOGGED_MOVES` holds logged `AM` commands, one of each kind, each with the positions the Master +Controller planned it from, and the Set Move Parameters and Move All timeout it sent. +""" + +import math +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.driver import motion +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration + +TABLES = generic_configuration().motor_tables + +LOGGED_MOVES = [ + { + "cpositions": { + "GR": [-175443, -175443], + "GY": [63763, 63763], + "GZ": [-159, -159], + "X": [35841, 35841], + "Y": [37266, 37266], + "Z": [0, 0], + }, + "cutoff_velocity": 0, + "kind": "multichannel full axes=0", + "module": "multichannel", + "motions": {}, + "speed": 1000, + "targets": {"GR": -175443, "GY": 63763, "GZ": -159, "X": 35841, "Y": 37266, "Z": 0}, + "timeout": 5000, + }, + { + "cpositions": {"GR": [-175774, -175774], "GZ": [-161, -161]}, + "cutoff_velocity": 0, + "kind": "span8 full axes=0", + "module": "span8", + "motions": {}, + "speed": 1000, + "targets": {"GR": -175774, "GZ": -161}, + "timeout": 5000, + }, + { + "cpositions": {"GG": [0, 0]}, + "cutoff_velocity": 0, + "kind": "multichannel slow axes=0", + "module": "multichannel", + "motions": {}, + "speed": 200, + "targets": {"GG": 0}, + "timeout": 5000, + }, + { + "cpositions": { + "D": [91463, 91463], + "GG": [0, 0], + "GR": [-175443, -175443], + "GY": [63730, 63730], + "GZ": [-160, -160], + "X": [4833, 4833], + "Y": [10952, 10952], + "Z": [0, 0], + }, + "cutoff_velocity": 0, + "kind": "multichannel full jerk-corrected s-curve trapezoid axes=3", + "module": "multichannel", + "motions": { + "D": {"acceleration": 1228495, "position": 43176, "velocity": 196608}, + "X": {"acceleration": 51, "jerk": 1280000, "position": 4831, "velocity": 8}, + "Y": {"acceleration": 25, "jerk": 640000, "position": 10953, "velocity": 4}, + }, + "speed": 1000, + "targets": { + "D": 43176, + "GG": 0, + "GR": -175443, + "GY": 63730, + "GZ": -160, + "X": 4831, + "Y": 10953, + "Z": 0, + }, + "timeout": 5411, + }, + { + "cpositions": {"D3": [1320, 1320], "Z3": [-78827, -78827]}, + "cutoff_velocity": 3600, + "kind": "span8 slow hysteresis jerk-corrected pump axes=2", + "module": "span8", + "motions": { + "D3": {"acceleration": 10000, "position": 720, "velocity": 604}, + "Z3": {"acceleration": 4000, "jerk": 21792949, "position": -78587, "velocity": 488}, + }, + "speed": 26, + "targets": {"D3": 720, "Z3": -78587}, + "timeout": 6007, + }, + { + "cpositions": {"Z": [-255, -255]}, + "cutoff_velocity": 0, + "kind": "multichannel full jerk-corrected s-curve axes=1", + "module": "multichannel", + "motions": { + "Z": {"acceleration": 128000, "jerk": 698690, "position": -31982, "velocity": 24320} + }, + "speed": 1000, + "targets": {"Z": -31982}, + "timeout": 6678, + }, + { + "cpositions": { + "Y1": [203370, 203370], + "Y2": [203370, 203370], + "Y3": [203370, 203370], + "Y4": [203370, 203370], + "Y5": [203370, 203370], + "Y6": [203370, 203370], + "Y7": [203370, 203370], + "Y8": [203370, 203370], + }, + "cutoff_velocity": 0, + "kind": "span8 full axes=0 span-y", + "module": "span8", + "motions": {}, + "speed": 1000, + "targets": { + "Y1": 203370, + "Y2": 203370, + "Y3": 203370, + "Y4": 203370, + "Y5": 203370, + "Y6": 203370, + "Y7": 203370, + "Y8": 203370, + }, + "timeout": 5000, + }, + { + "cpositions": { + "D": [43161, 43161], + "GG": [34983, 34983], + "GR": [-175443, -175443], + "GY": [63747, 63747], + "GZ": [-796, -796], + "X": [35692, 35692], + "Y": [37274, 37274], + "Z": [0, 0], + }, + "cutoff_velocity": 0, + "kind": "multichannel full jerk-corrected s-curve axes=4", + "module": "multichannel", + "motions": { + "GG": {"acceleration": 100, "jerk": 546, "position": 34981, "velocity": 19}, + "GR": {"acceleration": 50, "jerk": 273, "position": -175442, "velocity": 9}, + "X": {"acceleration": 50, "jerk": 273, "position": 35691, "velocity": 9}, + "Z": {"acceleration": 128000, "jerk": 698880, "position": -2561, "velocity": 24320}, + }, + "speed": 1000, + "targets": { + "D": 43161, + "GG": 34981, + "GR": -175442, + "GY": 63747, + "GZ": -796, + "X": 35691, + "Y": 37274, + "Z": -2561, + }, + "timeout": 5490, + }, + { + "cpositions": { + "GR": [-175443, -175443], + "GY": [63744, 63744], + "GZ": [-796, -796], + "X": [35767, 35767], + "Y": [37244, 37244], + "Z": [0, 0], + }, + "cutoff_velocity": 0, + "kind": "multichannel full axes=0", + "module": "multichannel", + "motions": {}, + "speed": 1000, + "targets": {"GR": -175443, "GY": 63744, "GZ": -796, "X": 35767, "Y": 37244, "Z": 0}, + "timeout": 5000, + }, +] + + +def load_moves(): + return LOGGED_MOVES + + +class LoggedMoveTests(unittest.TestCase): + """Every logged move plans to exactly what the Master Controller sent.""" + + def test_every_logged_move(self) -> None: + moves = load_moves() + for move in moves: + axes = TABLES.axes(move["module"]) + cpositions = {a.name: (0, 0) for a in axes} + cpositions.update({n: (c[0], c[1]) for n, c in move["cpositions"].items()}) + motions, timeout, _ = motion.plan_move( + axes, cpositions, move["targets"], move["speed"], move["cutoff_velocity"] + ) + planned = { + m.axis: { + "position": m.position, + "velocity": m.velocity, + "acceleration": m.acceleration, + **( + {"jerk": m.jerk if m.jerk is not None else 0} + if "jerk" in move["motions"].get(m.axis, {}) + else {} + ), + } # fmt: skip + for m in motions + } + with self.subTest(kind=move["kind"], targets=move["targets"]): + self.assertEqual(planned, move["motions"]) + if motions: + self.assertEqual(timeout, move["timeout"]) + + def test_fixture_covers_every_kind_of_move(self) -> None: + kinds = " ".join(m["kind"] for m in load_moves()) + # Hysteresis is measured per instrument and the generic configuration has none: it is + # checked on its own (`HysteresisTests`), and the logged moves with it in the local replay. + for kind in ("multichannel", "span8", "slow", "trapezoid", "pump", "jerk-corrected", + "span-y", "axes=4", "axes=0"): # fmt: skip + self.assertIn(kind, kinds) + + +class MoveTimeTests(unittest.TestCase): + def test_short_s_curve_never_reaches_max_acceleration(self) -> None: + # 280 counts of the Multichannel Z at its limits: pure jerk, 4 phases of (d / 2j)^(1/3). + t = motion.s_curve_move_time(280, 24320, 128000, 698880) + self.assertAlmostEqual(t, 4 * (280 / 2 / 698880) ** (1 / 3), places=12) + self.assertEqual(math.ceil(1000 * t), 235) + + def test_trapezoid(self) -> None: + self.assertEqual(motion.trapezoid_move_time(200, 10, 1), 30) # reaches v: v/a + d/v + self.assertEqual(motion.trapezoid_move_time(4, 10, 1), 4) # triangle: 2 sqrt(d/a), exact + + def test_zero_distance_takes_no_time(self) -> None: + self.assertEqual(motion.s_curve_move_time(0, 1, 1, 1), 0) + self.assertEqual(motion.pump_move_time(0, 1, 1, 1, 1), 0) + + def test_invalid_input_raises(self) -> None: + with self.assertRaises(ValueError): + motion.s_curve_move_time(10, 0, 1, 1) + + +class HysteresisTests(unittest.TestCase): + """The Span-8 Z channels' hysteresis is negative: downward moves travel |h| further, and the + adjusted position stays |h| above where the axis is.""" + + H = -862 + + def test_down_move_adds_hysteresis(self) -> None: + cpos = (1000, 1000) + self.assertEqual(motion.adjust_delta(cpos, -500, self.H), -500 - 862) + + def test_up_move_after_down_move_does_not(self) -> None: + cpos = motion.update_cpos((1000, 1000), -362, self.H) + self.assertEqual(cpos, (-362, 500)) + self.assertEqual(motion.adjust_delta(cpos, 1000 - cpos[1], self.H), 1000 - 500 + 862) + + def test_no_hysteresis_leaves_moves_alone(self) -> None: + self.assertEqual(motion.adjust_delta((5, 5), 10, 0), 10) + self.assertEqual(motion.update_cpos((5, 5), 15, 0), (15, 15)) + + +class PlanTests(unittest.TestCase): + AXES = TABLES.axes("multichannel") + + def cpositions(self, **at: int): + out = {a.name: (0, 0) for a in self.AXES} + out.update({n: (p, p) for n, p in at.items()}) + return out + + def test_axes_already_there_are_left_out(self) -> None: + motions, timeout, after = motion.plan_move(self.AXES, self.cpositions(X=100), {"X": 100}) + self.assertEqual(motions, []) + self.assertEqual(timeout, motion.MOVE_ALL_MARGIN_MS) + self.assertEqual(after["X"], (100, 100)) + + def test_leader_moves_at_its_limits_and_followers_arrive_with_it(self) -> None: + motions, _, after = motion.plan_move(self.AXES, self.cpositions(), {"X": 100000, "Y": 1000}) + x, y = motions + lim = self.AXES[0].limits + self.assertEqual( + (x.axis, x.velocity, x.acceleration), ("X", lim.max_velocity, lim.max_acceleration) + ) + self.assertEqual(y.velocity, round(lim.max_velocity * 1000 / 100000)) + self.assertEqual(after["Y"], (1000, 1000)) + + def test_speed_scales_the_leader(self) -> None: + (x,), _, _ = motion.plan_move(self.AXES, self.cpositions(), {"X": 100000}, speed=500) + self.assertEqual(x.velocity, round(self.AXES[0].limits.max_velocity * 0.5)) + + def test_rejects_bad_speed_and_unknown_axes(self) -> None: + with self.assertRaises(ValueError): + motion.plan_move(self.AXES, self.cpositions(), {"X": 1}, speed=0) + with self.assertRaises(ValueError): + motion.plan_move(self.AXES, self.cpositions(), {"Q": 1}) + + def test_unknown_position_must_be_read_first(self) -> None: + cpositions = self.cpositions() + cpositions["X"] = (None, 0) + with self.assertRaises(ValueError): + motion.plan_move(self.AXES, cpositions, {"X": 1000}) + + +if __name__ == "__main__": + unittest.main() + + +class SpawnOrderTests(unittest.TestCase): + def test_pairs_from_the_end_each_in_order(self) -> None: + # As logged: a Multichannel Z+D move sends D first; a Span-8 move of X and Z1-Z8 sends X, then + # Z2 Z1, Z4 Z3, ... + self.assertEqual(motion.spawn_order(["Z", "D"]), ["D", "Z"]) + z = [f"Z{n}" for n in range(1, 9)] + self.assertEqual( + motion.spawn_order(["X"] + z), ["X", "Z2", "Z1", "Z4", "Z3", "Z6", "Z5", "Z8", "Z7"] + ) + self.assertEqual(motion.spawn_order(["X"]), ["X"]) + self.assertEqual(motion.spawn_order([]), []) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py index 9287a7ad4b3..0f09f7e49b9 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motors.py @@ -3,8 +3,8 @@ A board does not keep its motor tables across a power cycle and cannot be asked for them, so the host loads them at a cold start. Two more values per axis never reach a board: the Master Controller keeps them in its own motor record and applies them itself. `home_position` is its -`phome`: where its Home All leaves X, the Multichannel's Y and the gripper axes (the Z channels, -the plunger and the Span-8 Y channels end elsewhere). +`phome`: where its Home All leaves X, the Multichannel's Y and the gripper axes (see +`driver/recipes/homing.py`; the Z channels, the plunger and the Span-8 Y channels end elsewhere). `hysteresis` is what it adds to an axis's targets; only the Span-8 Z channels have any, and it differs channel by channel, measured per instrument. They are data, the Master Controller's own record of the instrument (the `modules` section of its declared configuration, @@ -22,7 +22,7 @@ import struct from dataclasses import dataclass -from typing import Any, Dict, List, Literal +from typing import Any, Dict, List, Literal, Optional from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import Device @@ -112,6 +112,22 @@ def check_position(self, position: int) -> None: ) +@dataclass(frozen=True) +class AxisMove: + """One axis's next move, in counts. Speeds left as None are the axis's maximum; `force` is the + force limit x1000 (grip and tip loading), 0 for none; `sensor` and `trigger` stop the move + where that sensor fires (0, 0 for none).""" + + axis: str + position: int + velocity: Optional[int] = None + acceleration: Optional[int] = None + jerk: Optional[int] = None + force: int = 0 + sensor: int = 0 + trigger: int = 0 + + class MotorTables: """The axes of every arm type of one instrument, in the order they are configured (`DeviceConfiguration.motor_tables`).""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py new file mode 100644 index 00000000000..444602a4932 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py @@ -0,0 +1,279 @@ +"""A pod against itself: its gripper (and what it holds) against its pipettor, as Biomek keeps +them apart, as pure functions. + +Biomek models each part of a pod as a box in 3D and refuses a pose where the gripper's boxes and +the pipettor's overlap. Its path planner searches around that; here a move whose path would +overlap is refused before anything is sent (`Pod.move_axes`), and the gripper's operations make +room first (`Pod._make_room_for_gripper`). + +The parts, in Biomek's frame (cm; X along the rail, Y towards the front, Z up from the deck): + +- the gripper, about its rotation centre (`pod_geometry`: the pod's X + `GripperXOffset` − + `PadsCenterToRotationCenter`, its GY + `GripperYOffset` − `FingerCenterOffset`), its hand's + bottom at GZ + `GripperZOffset` + the fingers' height (the deepest point of the finger profile, + `Finger/Base`), so the fingertips are at GZ + `GripperZOffset`: + - the upper hand, from the lower hand's top (`Lowerhand/ZSpan`) up without end; it does not turn; + - the lower hand with the fingers' top part, down to the top part's depth (`TopPart/ZSpan`); + - the lower fingers, down to the fingertips; + - what it holds, from its bottom (the fingertips less the grip height) to its top; + the last three turned by GR; each widened by `AvoidanceMargin`; +- a Span-8's probes: each probe a band in Y halfway to its neighbours (the end ones out to + `Mandrel1YOffset`), below the LLS module a box `ProbeSize` wide from the end of its tip up to + `MandrelExtender` above its mandrel's bottom, widened by `AvoidanceMargin` and, in Z, by + `AdditionalSafeHeight`; above it the probe's upper part, up without end; +- the 96-head: its body (`HeadBodyXSpan` × `HeadBodyYSpan`, mandrel A1 at the pod's X and Y, + the mandrels centred), from the end of its tips up without end. + +A Span-8's tubing bundle (`LLSWireModel`, `span8_bundle_box`) is not one of the pipettor's parts +here: Biomek's own prime approach sweeps the probes past the gripper parked after homing through +that box, so what Biomek tests it against is not yet known. It is computed for drawing. +""" + +import math +from dataclasses import dataclass +from typing import Dict, List, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration + +OPEN = 1e10 # a part with no top + + +class PodCollisionError(ValueError): + """A move would bring a pod's gripper (or what it holds) into its own pipettor. Raised before + anything is sent.""" + + +Point = Tuple[float, float] + + +@dataclass(frozen=True) +class Part: + """A part of a pod at a pose: a convex outline seen from above (deck cm) and its Z range.""" + + name: str + outline: Tuple[Point, ...] + z_low: float + z_high: float + + +@dataclass(frozen=True) +class GripperState: + """The gripper's axes in Biomek's units (cm, degrees) and what it holds.""" + + gy: float + gz: float + gr: float + gg: float + held: Optional[g.HeldLabware] = None + + +@dataclass(frozen=True) +class PipettorState: + """The pipettor's axes in Biomek's units: a Span-8's probes' Y (`ys`), mandrel bottoms (`zs`) + and tip lengths below them, or the 96-head's Y and Z (one each) and its tips' length.""" + + ys: Tuple[float, ...] + zs: Tuple[float, ...] + tips: Tuple[float, ...] + + +def _box(x0: float, x1: float, y0: float, y1: float) -> Tuple[Point, ...]: + return ((x0, y0), (x1, y0), (x1, y1), (x0, y1)) + + +def _place(outline: Sequence[Point], cx: float, cy: float, degrees: float) -> Tuple[Point, ...]: + c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) + return tuple((cx + x * c - y * s, cy + x * s + y * c) for x, y in outline) + + +def finger_depth(model: Dict) -> float: + """How far below the hand's bottom the fingertips are: the finger profile's deepest point.""" + return -float(min(p["Y"] for p in model["Finger"]["Base"])) + + +def gripper_parts(config: PodConfiguration, x: float, state: GripperState) -> List[Part]: + """The gripper's parts with the pod's X at `x`.""" + geo, model = config.geometry, config.gripper_model + gm = g.GripperModel.from_bif(model) + margin = geo.avoidance_margin + cx = x + geo.gripper_x_offset - gm.pads_center_to_rotation_center + cy = state.gy + geo.gripper_y_offset - gm.finger_center_offset + depth = finger_depth(model) + hand = state.gz + geo.gripper_z_offset + depth # the hand's bottom + tips = hand - depth + hand_top = hand + model["Lowerhand"]["ZSpan"] + top_part = hand - model["Finger"]["TopPart"]["ZSpan"] + fixed, turning = g.gripper_boxes(gm, margin, state.gg, state.held) + parts = [Part("upper hand", _place(_box(*fixed[0]), cx, cy, 0.0), hand_top, OPEN)] + parts.append(Part("lower hand", _place(_box(*turning[0]), cx, cy, state.gr), top_part, hand_top)) + parts.append(Part("fingers", _place(_box(*turning[1]), cx, cy, state.gr), tips, top_part)) + if state.held is not None: + bottom = tips - state.held.grip_offset + for box in turning[2:]: + outline = _place(_box(*box), cx, cy, state.gr) + parts.append(Part("held labware", outline, bottom, bottom + state.held.height)) + return parts + + +def span8_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + """A Span-8's probes with the pod's X at `x` (probe axes at X).""" + geo, s = config.geometry, config.settings + margin, lift = geo.avoidance_margin, geo.additional_safe_height + half = s["ProbeSize"] / 2 + extender = s.get("MandrelExtender", 0.0) + ys = state.ys + parts = [] + for i, (y, z, tip) in enumerate(zip(ys, state.zs, state.tips)): + low = y - geo.mandrel1_y_offset if i == 0 else (ys[i - 1] + y) / 2 + high = y + geo.mandrel1_y_offset if i == len(ys) - 1 else (y + ys[i + 1]) / 2 + low, high = min(low, high), max(low, high) + lower = _box(x - half - margin, x + half + margin, low - margin, high + margin) + parts.append(Part(f"probe {i + 1}", lower, z - tip - lift, z + extender)) + upper = _box(x - geo.mandrel1_x_offset - margin, x + half + margin, low - margin, high + margin) + parts.append(Part(f"probe {i + 1} upper part", upper, z + extender, OPEN)) + return parts + + +@dataclass(frozen=True) +class BundleBox: + """The space a Span-8's tubing bundle may hang in (Biomek's frame, cm), open upward.""" + + x0: float + x1: float + y0: float + y1: float + z_low: float + + +def span8_bundle_box( + config: PodConfiguration, x: float, state: PipettorState +) -> Optional[BundleBox]: + """Where a Span-8's tubing bundle hangs with the probe axes at `x`, from `LLSWireModel` (None + without it): + + - X: from the probes' axis + `WireStartXOffset` to + `AnchorXOffset`; + - Y: the probes' range, out to halfway towards the anchor's (`AnchorCenterY` ± + `AnchorHalfLength`); + - Z: up from the lower of where the bundle leaves the lowest probe (its mandrel's bottom + + `MandrelExtender` + `FixedTipZOriginToWireOffset`) and the loop's bottom, `WireBottomAtZMax` + less half as far as that probe is below its highest Z. The lowest probe is the one furthest + below its own highest Z (`Z1`..`Z8` limits). + No `AvoidanceMargin`: the bundle is not widened. + """ + wire = config.settings.get("LLSWireModel") + if not wire: + return None + extender = config.settings.get("MandrelExtender", 0.0) + lowest = [] + for i, z in enumerate(state.zs): + low, high = config.limits.get(f"Z{i + 1}", config.limits.get("Z", (z, z))) + z = max(low, min(high, z)) + lowest.append((high - z, z + extender + wire["FixedTipZOriginToWireOffset"])) + below, leaves = max(lowest) + y0, y1 = min(state.ys), max(state.ys) + near, far = ( + wire["AnchorCenterY"] - wire["AnchorHalfLength"], + wire["AnchorCenterY"] + wire["AnchorHalfLength"], + ) + return BundleBox( + x + wire["WireStartXOffset"], + x + wire["AnchorXOffset"], + min(y0, (y0 + near) / 2), + max(y1, (y1 + far) / 2), + min(leaves, wire["WireBottomAtZMax"] - below / 2), + ) + + +def head96_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + """The 96-head with mandrel A1 at (`x`, `state.ys[0]`), its bottom at `state.zs[0]`.""" + geo, s = config.geometry, config.settings + margin = geo.avoidance_margin + body_x, body_y = s["HeadBodyXSpan"], s["HeadBodyYSpan"] + grid_x = ((geo.mandrels_x or 1) - 1) * geo.mandrel_x_spacing + grid_y = ((geo.mandrels_y or 1) - 1) * geo.mandrel_y_spacing + left = x - (body_x - grid_x) / 2 + back = state.ys[0] - (body_y - grid_y) / 2 # A1 is the back row; Y runs to the front + outline = _box(left - margin, left + body_x + margin, back - margin, back + body_y + margin) + return [Part("96-head", outline, state.zs[0] - state.tips[0], OPEN)] + + +def pipettor_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + if config.module_type == "span8": + return span8_parts(config, x, state) + return head96_parts(config, x, state) + + +def _axes(outline: Sequence[Point]) -> List[Point]: + n = len(outline) + return [ + (outline[i][1] - outline[(i + 1) % n][1], outline[(i + 1) % n][0] - outline[i][0]) + for i in range(n) + ] + + +def overlap(a: Part, b: Part) -> bool: + """Whether two parts share any volume (touching is clear): Z ranges, then separating axes.""" + if a.z_high <= b.z_low or b.z_high <= a.z_low: + return False + for ax, ay in _axes(a.outline) + _axes(b.outline): + pa = [px * ax + py * ay for px, py in a.outline] + pb = [px * ax + py * ay for px, py in b.outline] + if max(pa) <= min(pb) or max(pb) <= min(pa): + return False + return True + + +def collisions( + config: PodConfiguration, x: float, gripper: GripperState, pipettor: PipettorState +) -> List[Tuple[str, str]]: + """The (gripper part, pipettor part) pairs that overlap at this pose.""" + gp, pp = gripper_parts(config, x, gripper), pipettor_parts(config, x, pipettor) + return [(a.name, b.name) for a in gp for b in pp if overlap(a, b)] + + +# cm: the most any point moves between two checked poses. Every part is widened by +# `AvoidanceMargin` (0.2164 cm), so a contact cannot pass between two steps unseen. +SWEEP_STEP = 0.1 + + +def swept_collisions( + config: PodConfiguration, + x: Tuple[float, float], + gripper: Tuple[GripperState, GripperState], + pipettor: Tuple[PipettorState, PipettorState], +) -> List[Tuple[str, str]]: + """The overlaps anywhere along a coordinated move (every axis on the same profile, scaled to its + distance), checked at steps no point covers more than `SWEEP_STEP` in. The parts are widened by + `AvoidanceMargin`, more than a step.""" + (g0, g1), (p0, p1) = gripper, pipettor + # X carries every part alike, so only the other axes change what overlaps. + reach = config.gripper_model["Finger"]["PadsCenterToRotationCenter"] + 15.0 + travel = max( + [abs(g1.gy - g0.gy), abs(g1.gz - g0.gz), abs(g1.gg - g0.gg)] + + [reach * math.radians(abs(g1.gr - g0.gr))] + + [abs(b - a) for a, b in zip(p0.ys, p1.ys)] + + [abs(b - a) for a, b in zip(p0.zs, p1.zs)] + ) + steps = max(1, math.ceil(travel / SWEEP_STEP)) + found: List[Tuple[str, str]] = [] + for i in range(steps + 1): + t = i / steps + + def lerp(a: float, b: float) -> float: + return float(a + t * (b - a)) + + gs = GripperState( + lerp(g0.gy, g1.gy), lerp(g0.gz, g1.gz), lerp(g0.gr, g1.gr), lerp(g0.gg, g1.gg), g0.held + ) + ps = PipettorState( + tuple(lerp(a, b) for a, b in zip(p0.ys, p1.ys)), + tuple(lerp(a, b) for a, b in zip(p0.zs, p1.zs)), + p0.tips, + ) + for pair in collisions(config, lerp(*x), gs, ps): + if pair not in found: + found.append(pair) + if found: + return found + return found diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py new file mode 100644 index 00000000000..cecd76051de --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py @@ -0,0 +1,104 @@ +"""The pod's own collision check: the gripper against the pipettor.""" + +import dataclasses +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration + + +class PodCollisionTests(unittest.TestCase): + def setUp(self) -> None: + self.right = generic_configuration().pod("right") + + def probes(self, y: float, z: float, span: float = 6.3, tip: float = 0.0) -> pc.PipettorState: + return pc.PipettorState(tuple(y + i * span / 7 for i in range(8)), (z,) * 8, (tip,) * 8) + + def test_the_parked_gripper_is_clear_of_the_probes(self) -> None: + # The park: GR 90, GY 48, GZ at its top, GG 7.889; the probes over the wash station. + gripper = pc.GripperState(48.0, 37.8, 90.0, 7.889) + self.assertEqual(pc.collisions(self.right, 120.0, gripper, self.probes(58.275, 39.1)), []) + + def test_fingers_turned_under_the_probes_collide(self) -> None: + # GR 0 points the fingers along +X, under the probe axes; with the probes over them in Y + # and the fingers' top above the probes' tips, they meet. + gripper = pc.GripperState(30.0, 30.0, 0.0, 9.0) + found = pc.collisions(self.right, 120.0, gripper, self.probes(28.0, 20.0)) + self.assertIn(("fingers", "probe 1"), found) + + def test_probes_at_the_far_end_of_y_clear_the_turned_fingers(self) -> None: + # Logged before a turn to 0 degrees with GY 61.26: the probes sent to Y 15.274, span 6.3. + gripper = pc.GripperState(61.263, 30.0, 0.0, 9.706) + self.assertEqual(pc.collisions(self.right, 120.0, gripper, self.probes(15.274, 20.0)), []) + + def test_held_labware_counts(self) -> None: + held = g.HeldLabware(12.78, 8.56, height=1.41, grip_offset=-0.23) + gripper = pc.GripperState(30.0, 30.0, 0.0, 8.5, held) + self.assertIn("held labware", [p.name for p in pc.gripper_parts(self.right, 120.0, gripper)]) + + def test_a_turn_through_the_probes_is_caught_on_its_way(self) -> None: + # From 180 degrees (fingers away from the probes) to 90: never under the probes. To 0 and + # back is caught at 0, the end; a sweep from 180 to -90 passes 0 only between its ends. + a = pc.GripperState(30.0, 30.0, 180.0, 9.0) + b = pc.GripperState(30.0, 30.0, -180.0, 9.0) + probes = self.probes(28.0, 20.0) + self.assertEqual(pc.collisions(self.right, 120.0, a, probes), []) + self.assertEqual(pc.collisions(self.right, 120.0, b, probes), []) + found = pc.swept_collisions(self.right, (120.0, 120.0), (a, b), (probes, probes)) + self.assertTrue(found) + + def bundle(self, z: float = 30.0) -> pc.BundleBox: + box = pc.span8_bundle_box(self.right, 120.0, self.probes(28.0, z)) + assert box is not None + return box + + def test_the_tubing_bundle_hangs_beside_the_probes_towards_its_anchor(self) -> None: + wire = self.right.settings["LLSWireModel"] + box = self.bundle() + self.assertAlmostEqual(box.x0, 120.0 + wire["WireStartXOffset"]) + self.assertAlmostEqual(box.x1, 120.0 + wire["AnchorXOffset"]) + # The anchor is in front of these probes: the box reaches halfway to its far end. + self.assertAlmostEqual(box.y0, 28.0) + far = wire["AnchorCenterY"] + wire["AnchorHalfLength"] + self.assertAlmostEqual(box.y1, (34.3 + far) / 2) + + def test_the_bundle_loop_drops_half_as_far_as_the_lowest_probe(self) -> None: + # Low enough that the loop's bottom, not where the bundle leaves the probes, is lowest. + self.assertAlmostEqual(self.bundle(26.0).z_low - self.bundle(30.0).z_low, -2.0) + # At the top the bundle leaves the probes below the loop's bottom. + wire, s = self.right.settings["LLSWireModel"], self.right.settings + top = self.right.limits["Z1"][1] + top_box = pc.span8_bundle_box( + self.right, 120.0, pc.PipettorState((28.0,) * 8, (top,) * 8, (0.0,) * 8) + ) + assert top_box is not None + self.assertLessEqual( + top_box.z_low, top + s["MandrelExtender"] + wire["FixedTipZOriginToWireOffset"] + ) + + def test_the_bundle_does_not_guard_the_gripper(self) -> None: + # Biomek's prime approach sweeps the probes from Y 15.1 to 58.3 with the gripper as homing + # left it (GR -2.2 degrees, GY 39.9, at its top); around Y 47 the bundle's box covers the + # fingers, and Biomek sends the move all the same. + gripper = pc.GripperState(39.9, 37.931, -2.18, 7.937) + probes = self.probes(47.86, 39.2) + box = pc.span8_bundle_box(self.right, 145.4, probes) + assert box is not None + fingers = next(p for p in pc.gripper_parts(self.right, 145.4, gripper) if p.name == "fingers") + self.assertTrue( + pc.overlap( + fingers, pc.Part("bundle", pc._box(box.x0, box.x1, box.y0, box.y1), box.z_low, pc.OPEN) + ) + ) + self.assertEqual(pc.collisions(self.right, 145.4, gripper, probes), []) + + def test_a_span8_without_a_bundle_model_has_no_bundle(self) -> None: + config = dataclasses.replace( + self.right, settings={k: v for k, v in self.right.settings.items() if k != "LLSWireModel"} + ) + self.assertIsNone(pc.span8_bundle_box(config, 120.0, self.probes(28.0, 30.0))) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py new file mode 100644 index 00000000000..56a0ee26540 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py @@ -0,0 +1,371 @@ +"""Where a pod is along the shared X rail: Biomek's collision model, as pure functions. + +Biomek's rule: + +- A pod's X range at a pose is the union of its bridge, its pipettor (widened by the avoidance + margin) and its gripper. +- The gripper is boxes, each widened by the avoidance margin, in the gripper's own frame: + - the upper hand, which does not turn; + - the lower hand with the top of the fingers; + - the lower fingers; + - the held labware, if any. + + The fingers open to the grip width, or wider to clear the labware. Every box but the upper + hand turns by GR about the rotation centre, then all move with the gripper. The rotation + centre's deck X is the pod's X + `GripperXOffset` - `PadsCenterToRotationCenter`. GR = 0 points + the fingers to +X (GR ~90 to the front, ~189 at its maximum). +- A move's swept range comes from its start and end poses. +- Two ranges collide when their edges, floored to 1/16 cm cells, overlap or share a cell + (`grid_overlap`). + +Everything is in Biomek's units: deck X in cm, GR in degrees, the grip width GG in cm. A pod's X +is `PodConfiguration.to_value("X", counts)`, and its GR and GG likewise. + +Where this differs from Biomek, it says so: +- **Sweeps.** Biomek's swept range is the union of the start and end poses. Here a move's sweep + follows its coordinated path (`swept_x_range`), so a gripper turning through the other pod's + side between those poses is caught. This is never looser. +- **Held labware.** Biomek reads its size, and the stack on it, from its labware library. Here the + caller gives it, from the resource the gripper holds (`HeldLabware`). +""" + +import math +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import Obstacle, PodGeometry + +Range = Tuple[float, float] +"""An X interval in deck cm, `(lowest, highest)`.""" + +Box = Tuple[float, float, float, float] +"""A box in the gripper's frame, seen from above: `(x_low, x_high, y_low, y_high)`, cm. x runs +along the fingers, y across them, from the rotation centre.""" + + +@dataclass(frozen=True) +class GripperModel: + """The gripper's dimensions, in cm, from the instrument file's `GripperModel`, named after its + keys.""" + + upperhand_x_span: float + upperhand_y_span: float + upperhand_center_x: float + upperhand_center_y: float + lowerhand_fingerwise_span: float + lowerhand_default_span: float + finger_fingerwise_offset: float + finger_extension_span: float + top_part_fingerwise_span: float + bottom_part_fingerwise_span: float + finger_thickness: float + clipper_thickness: float + lw_finger_spacing: float + finger_center_offset: float + overall_angled_thickness: float + pads_center_to_rotation_center: float + + @classmethod + def from_bif(cls, model: Dict[str, Any]) -> "GripperModel": + """From the declared configuration's `gripper_model` (the `.bif` `GripperModel` dict).""" + up, low, finger = model["Upperhand"], model["Lowerhand"], model["Finger"] + return cls( + upperhand_x_span=up["XSpan"], + upperhand_y_span=up["YSpan"], + upperhand_center_x=up["CenterXOffset"], + upperhand_center_y=up["CenterYOffset"], + lowerhand_fingerwise_span=low["FingerwiseSpan"], + lowerhand_default_span=low["YSpanNoFingerMountExtension"], + finger_fingerwise_offset=finger["FingerwiseOffset"], + finger_extension_span=finger["ExtensionSpan"], + top_part_fingerwise_span=finger["TopPart"]["FingerwiseSpan"], + bottom_part_fingerwise_span=finger["BottomPart"]["FingerwiseSpan"], + finger_thickness=finger["Thickness"], + clipper_thickness=finger["ClipperThickness"], + lw_finger_spacing=finger["LWFingerSpacing"], + finger_center_offset=finger["FingerCenterOffset"], + overall_angled_thickness=finger["OverallAngledThickness"], + pads_center_to_rotation_center=finger["PadsCenterToRotationCenter"], + ) + + +@dataclass(frozen=True) +class StackedLayer: + """A layer stacked on what the gripper holds (a lid on a plate), in the gripper's frame, cm: its + footprint's `length` along the fingers and `width` across them, and where its corner is from + the corner of the layer below (`dx`, `dy`).""" + + dx: float + dy: float + length: float + width: float + + +@dataclass(frozen=True) +class HeldLabware: + """What the gripper holds, in its own frame, cm: `length` along the fingers, `width` between + them; offsets move it from the centre of the pads. `layers` are what is stacked on it, bottom + up (as Biomek counts it: the gripped labware is a stack; the bottom layer is centred on the + pads less `GrippedLabwareOffsets`, each layer above sits at its offset from the corner of the + one below, and the footprint is every layer's box). The grip width is the bottom layer's. + `height` is the stack's, from its bottom to its top; `grip_offset` how far above its bottom the + fingertips are (negative below it).""" + + length: float + width: float + offset_x: float = 0.0 + offset_y: float = 0.0 + layers: Tuple[StackedLayer, ...] = () + height: float = 0.0 + grip_offset: float = 0.0 + + +@dataclass(frozen=True) +class GripperPose: + """The gripper's rotation `gr` (degrees) and grip width `gg` (cm), and what it holds.""" + + gr: float + gg: float + held: Optional[HeldLabware] = None + + +def bridge_x_range(geometry: PodGeometry, x: float) -> Range: + low = x - geometry.bridge_to_head_x_offset - geometry.mandrel1_x_offset + return low, low + geometry.bridge_x_span + + +def pipettor_x_span(geometry: PodGeometry) -> float: + """The pipettor's X extent: the pod's `PodXSpan` in the instrument file, 18.606 cm on the + Multichannel, 4.0 on the Span-8.""" + return geometry.pod_x_span + + +def pipettor_x_range(geometry: PodGeometry, x: float) -> Range: + low = x - geometry.mandrel1_x_offset + margin = geometry.avoidance_margin + return low - margin, low + pipettor_x_span(geometry) + margin + + +def union(a: Range, b: Range) -> Range: + return min(a[0], b[0]), max(a[1], b[1]) + + +def gripper_boxes( + model: GripperModel, margin: float, gg: float, held: Optional[HeldLabware] +) -> Tuple[List[Box], List[Box]]: + """The gripper's boxes in its frame, each widened by `margin`. Returns the boxes + that stay put (the upper hand) and those that turn with GR.""" + m = model + opening = (m.lw_finger_spacing + m.finger_thickness) * 2 + max(gg, 0.0) + if held is not None: + finger = m.lw_finger_spacing + m.clipper_thickness + m.finger_thickness + opening = max(opening, 2 * finger + held.width) + finger_y_high = opening / 2 + m.finger_center_offset + finger_y_low = m.finger_center_offset - opening / 2 + hand_span = max((m.finger_extension_span + m.finger_thickness) * 2 - opening, opening) + hand_y_low = min(-m.lowerhand_default_span / 2, m.finger_center_offset - hand_span / 2) + hand_y_high = max(m.lowerhand_default_span / 2, hand_span / 2 + m.finger_center_offset) + top_end = m.top_part_fingerwise_span - m.lowerhand_fingerwise_span / 2 + top_end += m.finger_fingerwise_offset + + def box(x0: float, x1: float, y0: float, y1: float) -> Box: + return x0 - margin, x1 + margin, y0 - margin, y1 + margin + + upperhand = box( + m.upperhand_center_x - m.upperhand_x_span / 2, + m.upperhand_center_x + m.upperhand_x_span / 2, + m.upperhand_center_y - m.upperhand_y_span / 2, + m.upperhand_center_y + m.upperhand_y_span / 2, + ) + turning = [ + # the lower hand with the top portion of the fingers + box( + -m.lowerhand_fingerwise_span / 2, + top_end, + min(finger_y_low, hand_y_low), + max(finger_y_high, hand_y_high), + ), + # the lower portion of the fingers + box(top_end, top_end + m.bottom_part_fingerwise_span, finger_y_low, finger_y_high), + ] + if held is not None: + x0 = m.pads_center_to_rotation_center - held.offset_x - held.length / 2 + y0 = m.finger_center_offset - held.offset_y - held.width / 2 + turning.append(box(x0, x0 + held.length, y0, y0 + held.width)) + for layer in held.layers: + x0, y0 = x0 + layer.dx, y0 + layer.dy + turning.append(box(x0, x0 + layer.length, y0, y0 + layer.width)) + return [upperhand], turning + + +def turned_x_extent(box: Box, start: float, end: float) -> Range: + """The X a box covers while turning about the origin from `start` to `end` degrees + (counterclockwise from +X). Each corner's X is r cos(angle + phase); between the ends it peaks + where that angle crosses a multiple of 180 degrees.""" + low_angle, high_angle = min(start, end), max(start, end) + xs: List[float] = [] + for x in (box[0], box[1]): + for y in (box[2], box[3]): + r, phase = math.hypot(x, y), math.degrees(math.atan2(y, x)) + angles = [low_angle, high_angle] + k = math.ceil((low_angle + phase) / 180.0) + while k * 180.0 - phase <= high_angle: + angles.append(k * 180.0 - phase) + k += 1 + xs.extend(r * math.cos(math.radians(a + phase)) for a in angles) + return min(xs), max(xs) + + +def gripper_x_range( + geometry: PodGeometry, + model: GripperModel, + x: float, + start: GripperPose, + end: Optional[GripperPose] = None, +) -> Range: + """The X the gripper covers with the pod at `x`, at `start`, or turning and opening from + `start` to `end`.""" + end = end or start + centre = x + geometry.gripper_x_offset - model.pads_center_to_rotation_center + margin = geometry.avoidance_margin + gg = max(start.gg, end.gg) + low, high = math.inf, -math.inf + for held in {start.held, end.held}: + fixed, turning = gripper_boxes(model, margin, gg, held) + for b in fixed: + low, high = min(low, centre + b[0]), max(high, centre + b[1]) + for b in turning: + lo, hi = turned_x_extent(b, start.gr, end.gr) + low, high = min(low, centre + lo), max(high, centre + hi) + return low, high + + +@dataclass(frozen=True) +class Gripper: + """A gripper on a pod, at a pose: what the X range needs to count it.""" + + model: GripperModel + pose: GripperPose + + +def pod_x_range(geometry: PodGeometry, x: float, gripper: Optional[Gripper] = None) -> Range: + """The X a pod takes up with its X at `x` and its gripper at its pose. Without + a gripper, its bridge and pipettor only.""" + base = union(bridge_x_range(geometry, x), pipettor_x_range(geometry, x)) + if gripper is None: + return base + return union(base, gripper_x_range(geometry, gripper.model, x, gripper.pose)) + + +SWEEP_TOLERANCE = 0.02 +"""How far, in cm, any point may move between two of the poses a sweep checks; the result is +widened by it, so it is never looser than the continuous move.""" + + +def swept_x_range( + geometry: PodGeometry, + start: float, + end: float, + gripper_start: Optional[Gripper] = None, + gripper_end: Optional[Gripper] = None, +) -> Range: + """The X a pod takes up while moving its X from `start` to `end`, and its + gripper from one pose to the other. + + A coordinated move (`motion.py`, the Master Controller's `AM`) takes every axis along the same + profile, scaled to its distance, so the pod passes through X(s) and GR(s), GG(s) together for + s from 0 to 1. The sweep follows that path, at steps no point can cover more than + `SWEEP_TOLERANCE` in, widened by it. Biomek checks the start and end poses only; a gripper + turning through the other pod's side between them is caught here.""" + if gripper_start is None: + return union(pod_x_range(geometry, start), pod_x_range(geometry, end)) + model = gripper_start.model + a, b = gripper_start.pose, (gripper_end or gripper_start).pose + swept = union( + pod_x_range(geometry, start, gripper_start), pod_x_range(geometry, end, Gripper(model, b)) + ) + if (a.gr, a.gg, a.held) == (b.gr, b.gg, b.held): + return swept # the footprint only translates with X: its two ends bound it exactly + reach = max( + math.hypot(max(abs(box[0]), abs(box[1])), max(abs(box[2]), abs(box[3]))) + for held in {a.held, b.held} + for boxes in gripper_boxes(model, geometry.avoidance_margin, max(a.gg, b.gg), held) + for box in boxes + ) + # Between two steps the footprint translates (bounded by the steps themselves) and turns and + # opens, by at most this far: + travel = reach * math.radians(abs(b.gr - a.gr)) + abs(b.gg - a.gg) + steps = max(1, math.ceil(travel / SWEEP_TOLERANCE)) + low, high = swept + for i in range(steps + 1): + s = i / steps + pose = GripperPose(a.gr + s * (b.gr - a.gr), a.gg + s * (b.gg - a.gg), a.held) + x = start + s * (end - start) + for held in {a.held, b.held}: + lo, hi = gripper_x_range(geometry, model, x, GripperPose(pose.gr, pose.gg, held)) + low, high = min(low, lo), max(high, hi) + return low - SWEEP_TOLERANCE, high + SWEEP_TOLERANCE + + +def overlap(a: Range, b: Range) -> bool: + """Whether two ranges share any X. Touching is not overlapping.""" + return a[0] < b[1] and b[0] < a[1] + + +# Biomek compares range edges as whole sixteenths of a cm, rounded down (`floor(x * 16)`). +GRID_PER_CM = 16 + + +def grid_cell(x: float) -> int: + return math.floor(x * GRID_PER_CM) + + +def grid_overlap(a: Range, b: Range) -> bool: + """Biomek's collision test: each edge floored to its 1/16 cm cell; the ranges + collide unless one's high cell is below the other's low cell. Edges in the same cell collide.""" + return not (grid_cell(a[1]) < grid_cell(b[0]) or grid_cell(b[1]) < grid_cell(a[0])) + + +def pod_xy_box(geometry: PodGeometry, x: float, y: float) -> Tuple[Range, Range]: + """The pod's body seen from above at X `x`, Y `y` (mandrel A1 / probe 1), cm: its corner is + `Mandrel1XOffset` / `Mandrel1YOffset` back from that.""" + x0, y0 = x - geometry.mandrel1_x_offset, y - geometry.mandrel1_y_offset + return (x0, x0 + geometry.pod_x_span), (y0, y0 + geometry.pod_y_span) + + +def _open_overlap(low: Optional[float], high: Optional[float], span: Range, buffer: float) -> bool: + lo = -math.inf if low is None else low - buffer + hi = math.inf if high is None else high + buffer + return lo < span[1] and span[0] < hi + + +@dataclass(frozen=True) +class Clearance: + """What a pod's travel over an X/Y area must clear: the lowest height (cm) its channels may + travel at, and the obstacles in the way that no height clears (walls).""" + + height: float + walls: Tuple[str, ...] + + +def obstacle_clearance(obstacles: Sequence[Obstacle], x: Range, y: Range) -> Clearance: + """Over the area `x` by `y` (cm): the top (plus buffer) of every obstacle there with a top and + no floor (the pump bank), and every obstacle there with no top (a wall, or a ceiling). + + Ceilings (a bottom and no top: the I-beam from Z 37.069 behind Y 11.092, the cameras from Z 32.078 + at the front corners) count as walls. Biomek makes every obstacle a box (an open top at 1e10, + each face widened by its buffer) and checks the pod's whole part model against + them, the carriage above the channels included, so a ceiling bounds the pod's body, not its + channels' bottom; with the channels at a traverse height the body is above every ceiling. None of + the 12,321 X/Y moves Biomek logged put a pod's body under one (the furthest back was Y 14.27 cm), + so blocking them refuses nothing Biomek did.""" + height = -math.inf + walls = [] + for o in obstacles: + if not (_open_overlap(o.x1, o.x2, x, o.buffer) and _open_overlap(o.y1, o.y2, y, o.buffer)): + continue + if o.z2 is None: + walls.append(o.name) + elif o.z2 is not None and (o.z1 is None or o.z1 < 0): + height = max(height, o.z2 + o.buffer) + return Clearance(height, tuple(walls)) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_move_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_move_tests.py new file mode 100644 index 00000000000..99d777b879f --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_move_tests.py @@ -0,0 +1,180 @@ +"""A pod's coordinated move (`Pod.move_axes`), against a simulated instrument: what each board is +sent, and the position record kept as the Master Controller keeps it.""" + +import struct +from typing import List, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver import motion +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import NotHomedError +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod +from pylabrobot.beckman_coulter.biomek_i7.driver.homing_tests import SimulatedRunTest +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_configuration, + sealed, +) + +SPAN8_MOTORS = 21 # X, Y1-Y8, Z1-Z8, GY, GG, GZ, GR: every Span-8 axis but the pumps + + +class PodMoveTest(SimulatedRunTest): + """Helpers for tests on homed simulated pods.""" + + async def homed(self, homed=True, configuration=None) -> BiomekI7Driver: + driver = await self.start(homed, configuration=configuration) + await driver.home() + self.mark(driver) + return driver + + def sent(self, driver: BiomekI7Driver, module: str) -> List[Tuple[str, bytes]]: + """(command name, parameters) of each request a board was sent since the mark.""" + requests = self.usb(driver, module).requests[self.marks[module] :] + return [(p.COMMANDS[(m[0], m[4])], m[5:]) for m in requests] + + def pod(self, driver: BiomekI7Driver, side: str) -> Pod: + pod = driver.left_x_arm if side == "left" else driver.right_x_arm + assert pod is not None + return pod + + +class PodMoveTests(PodMoveTest): + async def test_first_move_reads_positions_then_moves_together(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + usb = self.usb(driver, "multichannel") + before = {a.name: (usb.axis_model(a.name).position,) * 2 for a in pod.axes} + expected = motion.plan_move(pod.axes, before, {"X": 100000, "Y": 50000}) + unknown = sum(1 for c in pod.cpositions.values() if c[0] is None) # every axis homed + self.assertGreaterEqual(unknown, 7) + result = await pod.move_axes({"X": 100000, "Y": 50000}) + motions = result.motions + self.assertEqual(motions, expected[0]) + self.assertEqual(result.completions, {}) + names = [n for n, _ in self.sent(driver, "multichannel")] + # enable-all: the positions are unknown after homing. + n = 1 + 2 * unknown + self.assertEqual(names[0], "Stop Motion Service") + self.assertEqual(names[1 : 1 + unknown], ["Set State"] * unknown) + self.assertEqual(names[1 + unknown : n], ["Get Current Position"] * unknown) + self.assertEqual(names[n:], ["Set Move Parameters"] * 2 + ["Move All"]) + sent = self.sent(driver, "multichannel") + for m, (_, params) in zip(motion.spawn_order(motions), sent[n : n + 2]): + self.assertEqual( + struct.unpack(" None: + driver = await self.homed() + pod = self.pod(driver, "left") + await pod.move_axes({"X": 100000}) + self.mark(driver) + (x,) = (await pod.move_axes({"X": 50000, "Y": 0})).motions # Y is already at 0 + self.assertEqual( + [n for n, _ in self.sent(driver, "multichannel")], ["Set Move Parameters", "Move All"] + ) + self.assertEqual((x.axis, x.velocity), ("X", pod.axis("X").limits.max_velocity)) + + async def test_nothing_is_sent_when_every_axis_is_there(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + await pod.move_axes({"X": 100000}) + self.mark(driver) + self.assertEqual((await pod.move_axes({"X": 100000})).motions, []) + self.assertEqual(self.sent(driver, "multichannel"), []) + + async def test_bad_requests_send_nothing(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "right") + for targets, speed, forces in ( + ({"X": 10**7}, 1000, {}), + ({"X": -100}, 0, {}), + ({"Q": 1}, 1000, {}), + ({"Z1": -1000}, 1000, {"Z2": 1.0}), # a force on an axis without a target + ({"Z1": -1000}, 1000, {"Z1": -1.0}), + ): + with self.subTest(targets=targets, speed=speed), self.assertRaises(ValueError): + await pod.move_axes(targets, speed, forces=forces) + with self.assertRaises(RuntimeError): # its valve has not been set + await pod.move_axes({"D1": 100}) + self.assertEqual(self.sent(driver, "span8"), []) + + async def test_span8_z_moves_down_by_its_hysteresis_more(self) -> None: + # Hysteresis is measured per instrument; the generic configuration has none, so this test + # gives two channels some. + config = generic_configuration() + for axis in config.modules["span8"]: + if axis["name"] in ("Z1", "Z2"): + axis["hysteresis"] = -57 + driver = await self.homed(configuration=sealed(config)) + pod = self.pod(driver, "right") + await pod.move_axes({"Z1": -20000, "Z2": -20000}) + names = [n for n, _ in self.sent(driver, "span8")] + self.assertEqual(names[1 : 1 + 2 * SPAN8_MOTORS].count("Get Current Position"), SPAN8_MOTORS) + usb = self.usb(driver, "span8") + for name in ("Z1", "Z2"): + h = pod.axis(name).hysteresis + self.assertLess(h, 0) + self.assertEqual(usb.axis_model(name).position, -20000 + h) + self.assertEqual(pod.cpositions[name], (-20000 + h, -20000)) + # Back up: the move takes up the hysteresis, and the channel ends at its target. + await pod.move_axes({"Z1": -10000}) + self.assertEqual(usb.axis_model("Z1").position, -10000) + self.assertEqual(pod.cpositions["Z1"], (-10000, -10000)) + + async def test_not_homed_axis_drops_the_move_and_forgets_positions(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + self.usb(driver, "multichannel").axis_model("Y").homed = False # as after a power cycle + with self.assertRaises(NotHomedError): + await pod.move_axes({"X": 1000, "Y": 1000}) + self.assertEqual(self.sent(driver, "multichannel")[-1][0], "Stop Motion Service") + self.assertTrue(all(c[0] is None for c in pod.cpositions.values())) + + async def test_homing_forgets_positions(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + await pod.move_axes({"X": 100000}) + await pod.home() + self.assertEqual(pod.cpositions["X"], (None, pod.axis("X").home_position)) + + async def test_sensor_stop_is_reported_with_its_position(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "right") + z1 = self.usb(driver, "span8").axis_model("Z1") + await pod.move_axes({"Z1": -10000}) + z1.sensed_at = -150000 + result = await pod.move_axes({"Z1": -200000, "Z2": -200000}, sensors={"Z1": (1, 1)}) + self.assertEqual(result.completions["Z1"].outcome, "liquid-sensed") + self.assertEqual(result.stopped_at("Z1"), -150000) + self.assertIsNone(result.stopped_at("Z2")) + # The reported position is taken as Z1's, as the Master Controller takes it, with its hysteresis as for any move. + self.assertEqual(pod.cpositions["Z1"][0], -150000) + self.assertIsNotNone(pod.cpositions["Z2"][0]) + + async def test_both_pods_move_together(self) -> None: + driver = await self.homed() + results = await driver.move_axes({"left": {"Y": 20000}, "right": {"Z1": -10000}}) + self.assertEqual(sorted(results), ["left", "right"]) + self.assertEqual([m.axis for m in results["left"].motions], ["Y"]) + self.assertEqual(self.pod(driver, "right").cpositions["Z1"][1], -10000) + with self.assertRaises(ValueError): + await driver.move_axes({"middle": {"X": 0}}) + + async def test_span8_takes_y_and_span_as_biomek_sends_them(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "right") + # As logged: `AM 7 1000 0 -230264 154304 0` puts every channel at Y 154304 (S 6.3 cm, 0 counts). + await pod.move_axes({"Y": 154304, "S": 0}) + self.assertEqual({pod.cpositions[f"Y{i}"][1] for i in range(1, 9)}, {154304}) + await pod.move_axes({"S": 7000}) # Y kept: channel i 1000 counts further each + self.assertEqual( + [pod.cpositions[f"Y{i}"][1] for i in range(1, 9)], [154304 + 1000 * i for i in range(8)] + ) + with self.assertRaises(ValueError): + await pod.move_axes({"Y": 0, "Y3": 0}) + with self.assertRaises(ValueError): + await pod.move_axes({"S": -1}) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_tests.py new file mode 100644 index 00000000000..67df383c38a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_tests.py @@ -0,0 +1,141 @@ +"""A pod's drive commands, checked on the wire against a fake board. + +Where a command has a counterpart in the Master Controller's log, the expected bytes are that +logged message (sequence number aside). +""" + +import asyncio +import unittest +from typing import List + +from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard +from pylabrobot.beckman_coulter.biomek_i7.driver.board_tests import ( + FakeAceUSB, + accepted, + done, + recorder, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import InterlockTrippedError +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod +from pylabrobot.beckman_coulter.biomek_i7.driver.framing import split +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import AxisMove +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration + +TABLES = generic_configuration().motor_tables + + +def without_sequence(message: bytes) -> bytes: + return message[:3] + b"\x00" + message[4:] + + +def logged(hex_message: str) -> bytes: + return without_sequence(bytes.fromhex(hex_message)) + + +def answer_like_a_board(message: bytes) -> List[bytes]: + if message[4] in (0x50, 0x51): + return [accepted(message), done(message)] + return [done(message)] + + +class PodDriveCommandTests(unittest.IsolatedAsyncioTestCase): + async def make_pod(self, module: str, side: str) -> Pod: + self.usb = FakeAceUSB(answer_like_a_board) + board = AceBoard(io=self.usb, default_timeout=1) + await board.setup() + self.addAsyncCleanup(board.stop) + return Pod(board, side, module, TABLES) # type: ignore[arg-type] + + def sent(self) -> List[bytes]: + return [without_sequence(m) for t in self.usb.transfers for m in split(t)] + + async def test_move_parameters_default_to_the_axis_maximum(self) -> None: + pod = await self.make_pod("multichannel", "left") + self.assertEqual(await pod._unchecked_fw_set_move_parameters([AxisMove("X", 35840)]), [True]) + # Set X Move Parameters Position:35840, logged in the 2026-10-24 cold start. + self.assertEqual( + self.sent(), [logged("110100A340807D020000FC03000088130000000000008C00000000")] + ) + + async def test_move_parameters_with_force_and_explicit_speeds(self) -> None: + """A grip at force 5.000 and a tip-loading Z move at 787.500, both logged in the 2026-10-08 + method run.""" + span8 = await self.make_pod("span8", "right") + await span8._unchecked_fw_set_move_parameters([AxisMove("GG", 34873, force=5000)]) + self.assertEqual( + self.sent(), [logged("111300F54019660100F9F91B00BAC3170188130000398800000000")] + ) + + left = await self.make_pod("multichannel", "left") + await left._unchecked_fw_set_move_parameters( + [AxisMove("Z", -35182, velocity=2432, acceleration=12800, jerk=69869, force=787500)] + ) + self.assertEqual( + self.sent(), [logged("1103005F408009000000320000ED1001002C040C009276FFFF0000")] + ) + + async def test_targets_outside_the_limits_send_nothing(self) -> None: + pod = await self.make_pod("multichannel", "left") + with self.assertRaisesRegex(ValueError, "outside"): + await pod._unchecked_fw_set_move_parameters([AxisMove("Y", 0), AxisMove("X", 350721)]) + self.assertEqual(self.usb.transfers, []) + + async def test_a_pump_whose_valve_is_not_set_is_refused(self) -> None: + pod = await self.make_pod("span8", "right") + with self.assertRaisesRegex(RuntimeError, "valve"): + await pod._unchecked_fw_set_move_parameters([AxisMove("D1", 0)]) + self.assertEqual(self.usb.transfers, []) + + async def test_not_homed_is_an_answer_and_other_refusals_raise(self) -> None: + pod = await self.make_pod("span8", "right") + self.usb.handler = lambda m: [m[:5] + b"\x00\x32"] if m[1] == 0x0A else [done(m)] + accepted_ = await pod._unchecked_fw_set_move_parameters( + [AxisMove("Z1", 9647), AxisMove("Z2", 9647)] + ) + self.assertEqual(accepted_, [False, True]) + self.usb.handler = lambda m: [m[:5] + b"\x00\x0f"] + with self.assertRaises(InterlockTrippedError): + await pod._unchecked_fw_set_move_parameters([AxisMove("X", -2560)]) + + async def test_a_batch_travels_together(self) -> None: + pod = await self.make_pod("span8", "right") + await pod._unchecked_fw_set_move_parameters([AxisMove(f"Z{i}", 9647) for i in range(1, 9)]) + self.assertEqual(len(self.usb.transfers), 1) + self.assertEqual([m[1] for m in self.sent()], list(range(0x0A, 0x12))) + + async def test_move_and_move_all(self) -> None: + pod = await self.make_pod("multichannel", "left") + await pod._unchecked_fw_move("GG") + await pod._unchecked_fw_move_all() + # Move GG Timeout:30000 and Move All Timeout:5000, as logged. + self.assertEqual(self.sent(), [logged("1106007F5030750000"), logged("1000002E5088130000")]) + + async def test_home_waits_for_every_axis(self) -> None: + pod = await self.make_pod("span8", "right") + held: List[bytes] = [] + self.usb.handler = recorder(held, lambda m: [accepted(m)]) + task = asyncio.create_task(pod._unchecked_fw_home(["Z1", "Z5"])) + while len(held) < 2: + await asyncio.sleep(0) + self.assertEqual(len(self.usb.transfers), 1) # both homes start together + self.usb.push(done(held[0])) + await asyncio.sleep(0.05) + self.assertFalse(task.done()) + self.usb.push(done(held[1])) + await task + self.assertEqual( + [without_sequence(m) for m in held], [logged("110A001051"), logged("110E001151")] + ) + + async def test_enable_addresses_pumps_and_motors(self) -> None: + pod = await self.make_pod("span8", "right") + await pod._unchecked_fw_enable(["D8", "GY"]) + await pod._unchecked_fw_stop_motion() + self.assertEqual( + self.sent(), + [logged("1208006B1200"), logged("1112006C1200"), logged("100000670F")], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py index e338b229eab..009985ef604 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py @@ -1 +1 @@ -"""The Master Controller's multi-step host commands, as the pods run them: `homing.py`.""" +"""The Master Controller's multi-step host commands, as recipes the pods run: `homing.py` (`HM`).""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py index 028126699fc..b8d16908cb9 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py @@ -1,11 +1,167 @@ -"""Bringing a pod's axes up, as the Master Controller does it. +"""Home All, as the Master Controller does it: a recipe of steps per arm type. -Enabling (after the interlock is armed, or a fault): the Master Controller enables a pod's axes in a -fixed order, and on the Multichannel first its Z alone, then stops motion; this order, as its logs -show it, is what `Pod.enable_axes` sends. +Each recipe was read off four Home Alls on one instrument (two after a power cycle, two with the +instrument already homed, one of those with the Span-8 Z channels not homed) and reproduces every +request each arm's board was sent, in order. Every target was the same in all four runs whatever +the axes' positions before homing. Where a Home All leaves X, the Multichannel's Y and the gripper +axes is each axis's home position in the instrument's motor record (`phome`, carried by its declared +configuration: `FromHome`); the gripper's two turns on the way are that position turned by 190 and +90 degrees in the instrument's GR scale, and the plunger's approach is its zero (`AtValue`). The Z +approaches (the Multichannel's -1000, the Span-8 channels' 9647) are this instrument's logged +counts, constants until another instrument's logs show where they come from. + +A step decides between moving and homing the way the Master Controller does, by asking the board. +It first sets the axis's move parameters; a board refuses that with "not homed" for an axis that has +not been homed since power-up, and then the step homes it, otherwise it moves. So one recipe serves +a cold start, a homed instrument, and anything between. + +The steps, as the requests they send (E = Set State ENABLED, P = Set Move Parameters at the axis's +maximum speeds, M = Move, H = Home, S = Stop Motion Service, MA = Move All): + + Home(axis, approach) E P; homed: M [E] H; not homed: [E] H. The Span-8 board's sequence + has the bracketed E, the Multichannel board's does not. + Retract(axis, target) E P; homed: M; not homed: S E P, then [E] H. + MoveTo(axis, target) E P M. + RetractGroup(axes, target) E P on every axis together; homed: MA; not homed: S, home the axes + in pairs (E E H H), then E P on every axis again, MA. + HomeGroup(...) the Span-8's Y and Z channels: E P on Y1-Y8 at 0; homed: MA; not + homed: S. Then E on Y1-Y8, H Y1, home the Z channels in pairs, E P the + Z channels to their target, MA. + +That is the Master Controller's Home All, which homes again an axis already homed: `force=True`. +Without it, an axis that was homed before the run began is only moved, and ends where a Home +would have left it: a Home step moves it to its approach and stops there (a Home leaves an axis at +its approach, to a few counts: the Multichannel's Z read -1000 six times out of six after Biomek's +homes, its plunger 43175-43178 for 43176, the gripper and Y axes 0 or -1), and a HomeGroup whose +channels were all homed before skips homing Y1 and the Z pairs. An axis the run itself homed is +homed again where the recipe says, as Biomek does (the gripper Z is homed twice at a cold start). +Every other request, and the order of every move, is the same either way; on an instrument with no +axis homed the two send the same requests. """ -from typing import Dict, Tuple +import logging +import math +from dataclasses import dataclass +from typing import TYPE_CHECKING, Dict, List, Sequence, Set, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import NotHomedError +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import AxisMove + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class FromHome: + """The axis's home position in the pod's motor record (`AxisTable.home_position`), turned by + `degrees` in the pod's conversion for the axis: the turn's counts, rounded down, added to it. Both + logged turns fit that (190 and 90 degrees from the gripper's home, -71487.4 and -33862.4 counts + in this instrument's scale, were sent 71488 and 33863 counts on); another rounding would be at + most a count, 0.003 degrees, off.""" + + degrees: float = 0.0 + + +@dataclass(frozen=True) +class AtValue: + """The counts for `value` in the pod's conversion for the axis (`PodConfiguration.to_counts`).""" + + value: float + + +Target = Union[int, FromHome, AtValue] + + +@dataclass(frozen=True) +class Home: + axis: str + approach: Target + + +@dataclass(frozen=True) +class Retract: + axis: str + target: int + + +@dataclass(frozen=True) +class MoveTo: + axis: str + target: Target + + +@dataclass(frozen=True) +class RetractGroup: + axes: Tuple[str, ...] + target: int + home_pairs: Tuple[Tuple[str, str], ...] + + +@dataclass(frozen=True) +class HomeGroup: + probe_axes: Tuple[str, ...] + probe_target: int + enable_axes: Tuple[str, ...] + home_axis: str + then: RetractGroup + + +Step = Union[Home, Retract, MoveTo, RetractGroup, HomeGroup] + +# The Span-8's Z channels, in the orders the Master Controller uses for them. +_SPAN8_Z = RetractGroup( + axes=("Z7", "Z8", "Z5", "Z6", "Z3", "Z4", "Z1", "Z2"), + target=9647, + home_pairs=(("Z1", "Z5"), ("Z2", "Z6"), ("Z3", "Z7"), ("Z4", "Z8")), +) + +# The Master Controller's `HM`: every axis but the plunger. +HOME_RECIPES: Dict[str, Tuple[Step, ...]] = { + "multichannel": ( + Home("Z", -1000), + Retract("GZ", 0), + Home("GG", 0), + MoveTo("GG", FromHome()), + Home("GR", 0), + MoveTo("GR", FromHome(190.0)), + MoveTo("GR", FromHome(90.0)), + Home("GY", 0), + Home("GZ", 0), + MoveTo("GY", FromHome()), + Home("Y", 0), + MoveTo("Y", FromHome()), + MoveTo("GR", FromHome()), + Home("X", 0), + MoveTo("X", FromHome()), + ), + "span8": ( + _SPAN8_Z, + Retract("GZ", 0), + Home("GG", 0), + MoveTo("GG", FromHome()), + Home("GR", 0), + MoveTo("GR", FromHome(190.0)), + MoveTo("GR", FromHome(90.0)), + Home("GY", 0), + Home("GZ", 0), + MoveTo("GY", FromHome()), + HomeGroup( + probe_axes=("Y7", "Y8", "Y5", "Y6", "Y3", "Y4", "Y1", "Y2"), + probe_target=0, + enable_axes=("Y2", "Y4", "Y3", "Y6", "Y5", "Y8", "Y7", "Y1"), + home_axis="Y1", + then=_SPAN8_Z, + ), + MoveTo("GR", FromHome()), + Home("X", 0), + MoveTo("X", FromHome()), + ), +} + +# Whether the board's sequence enables an axis again right before homing it. +ENABLE_BEFORE_HOME = {"multichannel": False, "span8": True} # The order the Master Controller enables every axis in after the interlock is armed, and reads # their positions in. The Multichannel board is sent one Z enable first. @@ -17,3 +173,168 @@ ), } # fmt: skip ENABLE_PREFIX: Dict[str, Tuple[str, ...]] = {"multichannel": ("Z",), "span8": ()} + + +class Homer: + """Runs recipes on one pod, through the pod's drive commands (`Pod._unchecked_fw_*`) only. + + Args: + pod: the pod whose board is sent the requests. + force: home again axes that were homed before the run, as the Master Controller does. + """ + + def __init__(self, pod: "Pod", force: bool = False): + self.pod = pod + self.force = force + self.enable_before_home = ENABLE_BEFORE_HOME[pod.module_type] + self._homed_in_run: Set[str] = set() + + def _keep_home(self, axes: Sequence[str]) -> bool: + """Whether axes that answer homed may be left as they are: not forced, and none of them homed + by this run (the recipe's later homes of those are Biomek's own).""" + return not self.force and not self._homed_in_run.intersection(axes) + + @staticmethod + def _step_targets(step: Step) -> List[Tuple[str, Target]]: + if isinstance(step, (Home,)): + return [(step.axis, step.approach)] + if isinstance(step, (Retract, MoveTo)): + return [(step.axis, step.target)] + if isinstance(step, RetractGroup): + return [(axis, step.target) for axis in step.axes] + return [(axis, step.probe_target) for axis in step.probe_axes] + Homer._step_targets(step.then) + + def targets(self, step: Step) -> List[Tuple[str, int]]: + """Every (axis, position) a step may set move parameters to on this pod, in order.""" + return [(axis, self._counts(axis, target)) for axis, target in self._step_targets(step)] + + @staticmethod + def axes(steps: Sequence[Step]) -> List[str]: + """Every axis a recipe moves or homes, once each.""" + names = [axis for step in steps for axis, _ in Homer._step_targets(step)] + return list(dict.fromkeys(names)) + + def _counts(self, axis: str, target: Target) -> int: + """`target` on this pod's `axis`, in counts. + + Raises: + ValueError: for a turn or a value on a pod with no declared configuration to convert it. + """ + if isinstance(target, int): + return target + if isinstance(target, FromHome) and not target.degrees: + return self.pod.axis(axis).home_position + declared = self.pod.declared + if declared is None: + raise ValueError(f"{self.pod}: {target} on {axis} needs the pod's declared configuration") + if isinstance(target, AtValue): + return declared.to_counts(axis, target.value) + turn = target.degrees * declared.conversion[axis].const + return self.pod.axis(axis).home_position + math.floor(turn) + + async def run(self, steps: Sequence[Step]) -> None: + for step in steps: + logger.debug("%s: %s", self.pod, step) + if isinstance(step, Home): + await self._home(step) + elif isinstance(step, Retract): + await self._retract(step) + elif isinstance(step, MoveTo): + await self._move_to(step) + elif isinstance(step, RetractGroup): + await self._retract_group(step) + else: + await self._home_group(step) + + # -- drive commands -------------------------------------------------------- + + async def _enable(self, names: Sequence[str]) -> None: + await self.pod._unchecked_fw_enable(names) + + async def _probe(self, names: Sequence[str], target: int) -> bool: + """Set move parameters on every axis at its maximum speeds; True if the board took them all, + False if any axis is not homed.""" + accepted = await self.pod._unchecked_fw_set_move_parameters( + [AxisMove(name, target) for name in names] + ) + if not all(accepted) and any(accepted): + # Only all-or-none was seen; homing every axis of the group is the safe reading. + logger.warning("%s: some of %s are homed and some are not; homing them all", self.pod, names) + return all(accepted) + + async def _stop(self) -> None: + await self.pod._unchecked_fw_stop_motion() + + async def _move(self, name: str) -> None: + await self.pod._unchecked_fw_move(name) + + async def _move_all(self) -> None: + await self.pod._unchecked_fw_move_all() + + async def _home_axes(self, names: Sequence[str]) -> None: + await self.pod._unchecked_fw_home(names) + self._homed_in_run.update(names) + + # -- steps ----------------------------------------------------------------- + + async def _home(self, step: Home) -> None: + await self._enable([step.axis]) + if await self._probe([step.axis], self._counts(step.axis, step.approach)): + await self._move(step.axis) + if self._keep_home([step.axis]): + return + if self.enable_before_home: + await self._enable([step.axis]) + await self._home_axes([step.axis]) + + async def _retract(self, step: Retract) -> None: + await self._enable([step.axis]) + if await self._probe([step.axis], step.target): + await self._move(step.axis) + return + await self._stop() + await self._enable([step.axis]) + if await self._probe([step.axis], step.target): + await self._move(step.axis) + return + if self.enable_before_home: + await self._enable([step.axis]) + await self._home_axes([step.axis]) + + async def _move_to(self, step: MoveTo) -> None: + await self._enable([step.axis]) + if not await self._probe([step.axis], self._counts(step.axis, step.target)): + raise NotHomedError(0x32, None, f"{self.pod}: {step.axis} is not homed for {step}") + await self._move(step.axis) + + async def _home_pairs(self, pairs: Sequence[Tuple[str, str]]) -> None: + for pair in pairs: + await self._enable(pair) + await self._home_axes(pair) + + async def _retract_group(self, step: RetractGroup) -> None: + await self._enable(step.axes) + if not await self._probe(step.axes, step.target): + await self._stop() + await self._home_pairs(step.home_pairs) + await self._enable(step.axes) + if not await self._probe(step.axes, step.target): + raise NotHomedError(0x32, None, f"{self.pod}: {step.axes} still not homed after homing") + await self._move_all() + + async def _home_group(self, step: HomeGroup) -> None: + await self._enable(step.probe_axes) + homed = await self._probe(step.probe_axes, step.probe_target) + if homed: + await self._move_all() + else: + await self._stop() + group = (step.home_axis, *step.probe_axes, *step.then.axes) + if not homed or not self._keep_home(group): + await self._enable(step.enable_axes) + await self._home_axes([step.home_axis]) + await self._home_pairs(step.then.home_pairs) + await self._enable(step.then.axes) + if not await self._probe(step.then.axes, step.then.target): + raise NotHomedError(0x32, None, f"{self.pod}: {step.then.axes} still not homed after homing") + await self._move_all() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py index 274a0a74f41..9f0011ca412 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -1,8 +1,8 @@ """Simulated instruments: boards that answer from what a real Biomek i7's boards answered. -`ReplayAceUSB` only replays a recording. `SimulatedAceUSB` also models each axis's state and the -interlock, so configuring, arming and enabling can run against it; nothing it does reaches a USB -device. +`ReplayAceUSB` only replays a recording. `SimulatedAceUSB` also models each axis (homed or not, +its position, its pending move), so configuring, arming and homing can run against it; nothing it +does reaches a USB device. A replayed board holds a recording of request -> replies, keyed on everything in a request but its sequence number, and answers a request it has a recording for with those replies under @@ -13,22 +13,35 @@ import asyncio import gzip import json +import math import os import struct from dataclasses import dataclass from pathlib import Path -from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union +from typing import ( + Any, + Dict, + Iterable, + List, + Optional, + Sequence, + Tuple, + Union, +) from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.framing import frame, split from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, MotorTables -from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import AxisState, Device +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import ( + LLS_LIQUID_SENSED, + AxisState, + Device, +) from pylabrobot.io.usb import USB # Names the recording the simulator answers from (identity and sensor reads, recorded at an # instrument's cold start) when no path is given. A generic one ships in `defaults/` -# (`biomek_i7_generic_coldstart.json`), which `BiomekI7(simulation=True)` uses when neither is -# given. +# (`biomek_i7_generic_coldstart.json`). RECORDING_ENV = "BIOMEK_I7_SIMULATOR_RECORDING" @@ -111,20 +124,45 @@ def replay_boards( ] +# Axes a Home of one axis also homes. Biomek homes only Y1 of the Span-8's eight Y channels, and +# after its Home All every one of them reads as homed (H1, 2026-10-24). +LINKED_HOMES: Dict[str, Dict[str, Tuple[str, ...]]] = { + "span8": { + "Y1": tuple(f"Y{i}" for i in range(1, 9)), + "D1": tuple(f"D{i}" for i in range(1, 9)), # the pumps (`HD`, 2026-10-09) + }, +} + + class SimulatedAceUSB(ReplayAceUSB): """One board's USB link, answered from a model of its axes rather than only a recording. - Each axis has a state (`AxisState`), is homed or not, and has a position, by the boards' rules: - an axis starts not configured; Configure leaves it disabled and not homed; Set State is refused - "not configured" before that. Identity and sensor reads are answered from the recording. + Each axis has a state (`AxisState`), is homed or not, and has a position and a pending move, by + the boards' rules: an axis starts not configured; Configure leaves it + disabled and not homed; Set State and Set Move Parameters are refused "not configured" before + that; Home is refused "not enabled" unless the axis is enabled. Set Move Parameters is refused + "not homed" for an axis not homed, as a board refuses it after power-up; Move, Move All and Home + answer ACCEPTED then DONE and update the model. A homed axis ends at 0 in the model; a real + board ends where its Configure parameters say (Biomek read the Multichannel's Z at -1000 and its + plunger at 43175 straight after homing). Identity and sensor reads are answered from the + recording. The boards of one instrument share an `Interlock`. While it is tripped, as at rest, a CiA 402 axis that was enabled reads FAULT (its drive lost motor power: H1, 2026-10-27; one configured at - rest reads DISABLED, as on H2 the same day), its enable fails, and the arm's drive supply - input reads 0.12 V; armed, 35.4 V. + rest reads DISABLED, as on H2 the same day), its enable fails, moves and homes + are refused "interlock tripped", and the arm's drive supply input reads 0.12 V; armed, 35.4 V. Enabling a CiA 402 axis in fault resets it, unless it was given a fault that does not clear (`_AxisModel.stuck_fault`). The error codes of a failed enable are not known; the model answers "interlock tripped" without power and 0x3D for a stuck fault. + + A move with a force limit stops where the axis meets something (`_AxisModel.obstacle`, set by a + test). A move with a sensor stops where the sensor fires (`_AxisModel.sensed_at`), and the + Move All carries that axis's report (LLS_LIQUID_SENSED and the position) under its sequence. + A pump keeps the valve it was last moved through. + + Moves complete at once unless `time_scale` is set: then a Move or Move All is accepted at once + and done after the slowest axis's move would take (`_AxisModel.duration`), times `time_scale` + (1: about as long as on the instrument), so a simulated run can be watched and stopped. """ def __init__( @@ -133,16 +171,21 @@ def __init__( axes: Sequence[Axis] = (), homed: Iterable[str] = (), name: str = "simulated ACE board", + linked_homes: Optional[Dict[str, Tuple[str, ...]]] = None, configured: bool = False, interlock: Optional["Interlock"] = None, supply_input: Optional[int] = None, door_input: Optional[int] = None, + time_scale: float = 0.0, ): super().__init__(recording, name=name) + self.time_scale = time_scale + self._move_seconds = 0.0 # how long the move just answered takes (`answer`) self.door_input = door_input homed = set(homed) if homed and not configured: raise ValueError("an axis cannot be homed on a board that is not configured") + self.linked_homes = linked_homes or {} self.interlock = interlock or Interlock() self.supply_input = supply_input self.axes: Dict[Tuple[int, int], _AxisModel] = {} @@ -151,6 +194,7 @@ def __init__( # axes read FAULT while the interlock is tripped (`_apply_power`). state = AxisState.ENABLED if configured else AxisState.NOT_CONFIGURED self.axes[(a.device, a.index)] = _AxisModel(a.name, a.name in homed, state, a.drive) + self.axes_list = list(axes) def _apply_power(self) -> None: """An enabled CiA 402 drive faults when its motor power goes. One configured with the power @@ -188,6 +232,7 @@ def answer(self, message: bytes) -> Optional[List[bytes]]: device, index, opcode, params = message[0], message[1], message[4], message[5:] header = message[:5] done = header + b"\x02\x00" + accepted = header + b"\x01\x00" tripped = header + b"\x00\x0f" self._apply_power() if device == Device.ANALOG_INPUT and opcode == 0x10 and index == self.supply_input: @@ -196,6 +241,8 @@ def answer(self, message: bytes) -> Optional[List[bytes]]: axis = self.axes.get((device, index)) if axis is not None: configured = axis.state != AxisState.NOT_CONFIGURED + if opcode in (0x50, 0x51) and not self.interlock.armed: + return [tripped] if opcode == 0x11: return [done + bytes([axis.state])] if opcode == 0x24: @@ -203,7 +250,7 @@ def answer(self, message: bytes) -> Optional[List[bytes]]: if opcode == 0x21: return [done + (b"\x00" if axis.homed else b"\x01")] if opcode == 0x10: - axis.state, axis.homed = AxisState.DISABLED, False + axis.state, axis.homed, axis.pending = AxisState.DISABLED, False, None return [done] if opcode == 0x12: if not configured: @@ -216,8 +263,51 @@ def answer(self, message: bytes) -> Optional[List[bytes]]: return [header + b"\x00\x3d"] axis.state = AxisState(params[0]) return [done] + if opcode == 0x40: + if not configured: + return [header + b"\x00\x30"] + if not axis.homed: + return [header + b"\x00\x32"] + axis.pending = struct.unpack_from(" Optional[List[bytes]]: async def write(self, data: bytes, timeout: Optional[float] = None): for message in split(data): + self._move_seconds = 0.0 replies = self.answer(message) if replies is None: await super().write(frame(message), timeout) continue self.requests.append(message) - for reply in replies: - self._queue(reply) + delay = self._move_seconds * self.time_scale + if delay > 0 and len(replies) > 1: + # Accepted now; the rest (reports, done) once the move would have finished. + self._queue(replies[0]) + asyncio.get_running_loop().call_later(delay, self._queue_all, replies[1:]) + continue + self._queue_all(replies) + + def _queue_all(self, replies: List[bytes]) -> None: + for reply in replies: + self._queue(reply) def _queue(self, message: bytes) -> None: framed = frame(message) @@ -275,6 +375,48 @@ class _AxisModel: drive: str = "cia402" stuck_fault: bool = False position: int = 0 + pending: Optional[int] = None + # The pending move's force limit (x1000) and sensor; a pump's valve (0-3, None until moved). + force: int = 0 + sensor: int = 0 + valve: Optional[int] = None + # Where a force-limited move meets something, and where a sensor fires; None: nowhere. + obstacle: Optional[int] = None + sensed_at: Optional[int] = None + # The pending move's top speed (counts/s) and acceleration (counts/s2), as last set. + velocity: int = 0 + acceleration: int = 0 + + def duration(self) -> float: + """Seconds the pending move takes: up to speed, at speed, down again (jerk left out); 0 + with none, or without speeds.""" + if self.pending is None or self.velocity <= 0 or self.acceleration <= 0: + return 0.0 + distance = abs(self.pending - self.position) + v, a = float(self.velocity), float(self.acceleration) + if distance >= v * v / a: + return distance / v + v / a + return 2.0 * math.sqrt(distance / a) + + def finish_move(self) -> Optional[str]: + """Run the pending move to its end: its target, or where force or a sensor stops it. Returns + "stalled" or "sensed" for those, else None.""" + if self.pending is None: + return None + low, high = sorted((self.position, self.pending)) + target, self.pending = self.pending, None + obstacle, sensed_at = self.obstacle, self.sensed_at + # An obstacle stops a force-limited move into it, not one leaving it. + if ( + self.force and obstacle is not None and obstacle != self.position and low <= obstacle <= high + ): + self.position = obstacle + return "stalled" + if self.sensor and sensed_at is not None and low <= sensed_at <= high: + self.position = sensed_at + return "sensed" + self.position = target + return None # The analog input carrying the interlocked drive supply, per module (the Master Controller's cold @@ -290,6 +432,7 @@ def simulated_boards( path: Optional[Union[str, Path]] = None, default_timeout: float = 1.0, configured: Optional[Union[bool, Dict[str, bool]]] = None, + time_scale: float = 0.0, ) -> List[AceBoard]: """A simulated instrument as `BiomekI7Driver(boards=...)` takes it: the recorded chassis, a left Multichannel and a right Span-8 pod. @@ -302,6 +445,7 @@ def simulated_boards( configured: whether each arm's board has its motor tables, as one value or per arm type. Defaults to configured wherever an axis is homed, and not configured (just powered up) otherwise. + time_scale: how long moves take, as `SimulatedAceUSB` takes it (0: at once). """ tables = motor_tables data = load_recording(path) @@ -325,10 +469,12 @@ def simulated_boards( axes, homed_axes, name=f"simulated {module}", + linked_homes=LINKED_HOMES.get(module), configured=is_configured, interlock=interlock, supply_input=SUPPLY_INPUTS.get(module), door_input=DOOR_INPUTS.get(module), + time_scale=time_scale, ) boards.append(AceBoard(io=usb, name=f"simulated {module}", default_timeout=default_timeout)) return boards diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py new file mode 100644 index 00000000000..87de159982e --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py @@ -0,0 +1,219 @@ +"""The shared X rail: keeps the two pods from running into each other (design.md I7). + +Both pods ride one rail and nothing below the driver stops them colliding: the Master +Controller plans each pod on its own, and each board knows only its pod. Biomek keeps them +apart. Before a pod moves, its swept range must clear the other pod's +range; if it does not, the other pod is moved out of the way first and the mover waits. A pod's +range counts its bridge, its pipettor and its gripper, turned and opened as it is, with what it +holds (`driver/pod_geometry.py`). + +`XRail` applies the same rule. It differs in three ways: +- **It refuses** a move into where the other pod stands, or will stand once its move ends, + rather than moving the other pod; `make_space` comes later. +- **It waits** when a move conflicts only with a move of the other pod still running, then + checks again: the other pod is passing through, not staying (Biomek runs such moves together). +- **It reserves** every move in flight, so two moves started together cannot pass through each + other. + +It works from the declared configuration (`driver/configuration.py`), never from the resource +tree, so it holds with no deck. Poses are in Biomek's units: deck X in cm, GR in degrees, GG in cm. +""" + +import asyncio +import contextlib +import logging +from dataclasses import dataclass +from typing import AsyncIterator, Awaitable, Callable, Dict, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration, Side + +logger = logging.getLogger(__name__) + +OTHER: Dict[Side, Side] = {"left": "right", "right": "left"} + +# How long a move waits for the other pod's move to clear, in seconds. Longer than any single +# move (the Master Controller's Move All timeouts are seconds), so a wait this long means +# something is stuck. +WAIT_TIMEOUT = 120.0 + + +class RailCollisionError(ValueError): + """A move would bring a pod into the other pod's X range. Raised before anything is sent.""" + + +@dataclass(frozen=True) +class PodPose: + """Where a pod is, as the rail needs it: deck X (cm) and its gripper's pose, None when not + known (then every pose the gripper could take is counted).""" + + x: float + gripper: Optional[g.GripperPose] = None + + +class XRail: + """Where each pod is on the rail, and what each pod's move in flight has reserved. + + Args: + pods: the declared configuration of each pod on the rail. A side with None has a pod whose + geometry is not declared: it cannot be guarded, so neither pod may move. + """ + + def __init__(self, pods: Dict[Side, Optional[PodConfiguration]]): + self.pods = pods + self._pose: Dict[Side, Optional[PodPose]] = {side: None for side in pods} + self._reserved: Dict[Side, Optional[g.Range]] = {side: None for side in pods} + self._end: Dict[Side, Optional[g.Range]] = {side: None for side in pods} + self._done: Dict[Side, asyncio.Event] = {side: asyncio.Event() for side in pods} + self._lock = asyncio.Lock() + # How to read a pod's pose when the rail does not know it. Set by the driver. + self.readers: Dict[Side, Callable[[], Awaitable[PodPose]]] = {} + self._models = { + side: g.GripperModel.from_bif(p.gripper_model) if p and p.gripper_model else None + for side, p in pods.items() + } + + def _require_pod(self, side: Side) -> PodConfiguration: + pod = self.pods.get(side) + if pod is None: + raise RuntimeError( + f"the {side} pod has no declared geometry, so the X rail cannot keep the pods apart; " + "pass a declared configuration that includes it" + ) + return pod + + def _gripper(self, side: Side, pose: Optional[g.GripperPose]) -> Optional[g.Gripper]: + model = self._models.get(side) + if model is None or pose is None: + return None + return g.Gripper(model, pose) + + def range_at(self, side: Side, pose: PodPose) -> g.Range: + """The X a pod takes up at a pose. An unknown gripper pose counts every pose it could take: + the whole of GR's travel, fully open.""" + pod = self._require_pod(side) + if pose.gripper is not None or self._models.get(side) is None: + return g.pod_x_range(pod.geometry, pose.x, self._gripper(side, pose.gripper)) + return self.swept(side, PodPose(pose.x, None), PodPose(pose.x, None)) + + def swept(self, side: Side, start: PodPose, end: PodPose) -> g.Range: + """The X a pod takes up while moving from `start` to `end`.""" + pod = self._require_pod(side) + a, b = start.gripper, end.gripper + if self._models.get(side) is not None and (a is None or b is None): + # Not known: count every pose the gripper could take, fully open, holding what it holds. + known = a or b + held = known.held if known is not None else None + gr_low, gr_high = pod.limits["GR"] + gg_open = pod.limits["GG"][1] + a, b = g.GripperPose(gr_low, gg_open, held), g.GripperPose(gr_high, gg_open, held) + return g.swept_x_range( + pod.geometry, start.x, end.x, self._gripper(side, a), self._gripper(side, b) + ) + + def update(self, side: Side, pose: Optional[PodPose]) -> None: + """Record where a pod is, or None when not known (after homing, or a move that failed). A + known pose ends the reservation a failed move left, but never one of a move still running: a + read can come back after that move started.""" + if side not in self.pods: + return + self._pose[side] = pose + if pose is not None and not self._in_flight(side): + self._reserved[side] = None + + def _in_flight(self, side: Side) -> bool: + return self._end[side] is not None + + def occupied(self, side: Side) -> Optional[g.Range]: + """The X a pod takes up now: its move's reservation while one is in flight or a failed one + left, else its range where it is. None when its position is not known.""" + if self._reserved.get(side) is not None: + return self._reserved[side] + pose = self._pose.get(side) + return None if pose is None else self.range_at(side, pose) + + def check(self, side: Side, start: PodPose, end: PodPose) -> g.Range: + """Check a move of `side` against the other pod. Returns the move's swept range. + + Raises: + RailCollisionError: if the swept range overlaps where the other pod stands, or will stand + once its move ends. + RuntimeError: if the other pod's position is not known and the move goes towards it, or a + pod on the rail has no declared geometry. + """ + swept = self.swept(side, start, end) + other = OTHER[side] + if other not in self.pods: + return swept + self._require_pod(other) + end_range = self._end.get(other) + if end_range is not None: # the other pod is moving + if g.grid_overlap(swept, end_range): + raise self._collision(side, swept, other, end_range, "will stand") + return swept # any overlap with its sweep is waited out in `moving` + taken = self.occupied(other) + if taken is None: + if ( + (swept[1] > self.range_at(side, start)[1]) + if side == "left" + else (swept[0] < self.range_at(side, start)[0]) + ): + raise RuntimeError( + f"the {other} pod's position is not known, and the {side} pod's move goes towards it" + ) + return swept + if g.grid_overlap(swept, taken): + raise self._collision(side, swept, other, taken, "stands") + return swept + + def _collision( + self, side: Side, swept: g.Range, other: Side, taken: g.Range, how: str + ) -> RailCollisionError: + return RailCollisionError( + f"the {side} pod's move would take up deck X {swept[0]:.2f}..{swept[1]:.2f} cm, into " + f"{taken[0]:.2f}..{taken[1]:.2f}, where the {other} pod {how}" + ) + + async def ensure_known(self, side: Side) -> None: + """Read a pod's pose if the rail does not know it and a reader is set. Moves nothing.""" + if side in self.pods and self.occupied(side) is None and side in self.readers: + self.update(side, await self.readers[side]()) + + @contextlib.asynccontextmanager + async def moving(self, side: Side, start: PodPose, end: PodPose) -> AsyncIterator[None]: + """Hold a move's swept range for as long as the move runs. + + Checked and reserved together, under one lock. A move that conflicts only with the other + pod's move in flight waits for that move to finish, then is checked again. On success the + pod's pose becomes `end`. On failure it becomes unknown, but the reservation stays until a + pose is read: the pod is somewhere in that range. + + Raises: + RailCollisionError, RuntimeError: as `check`, before the move starts. + TimeoutError: if the other pod's move does not finish within `WAIT_TIMEOUT`. + """ + other = OTHER[side] + await self.ensure_known(other) + while True: + async with self._lock: + swept = self.check(side, start, end) + running = ( + self._reserved.get(other) if other in self.pods and self._in_flight(other) else None + ) + if running is None or not g.grid_overlap(swept, running): + self._reserved[side] = swept + self._end[side] = self.range_at(side, end) + self._done[side].clear() + break + done = self._done[other] + logger.info("%s pod waits for the %s pod's move to clear its path", side, other) + await asyncio.wait_for(done.wait(), WAIT_TIMEOUT) + try: + yield + except BaseException: + self._pose[side] = None + raise + finally: + self._end[side] = None + self._done[side].set() + self.update(side, end) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py new file mode 100644 index 00000000000..c2809857f57 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py @@ -0,0 +1,244 @@ +"""The shared X rail: Biomek's pod-against-pod rule with the gripper, the reservations for moves +in flight, waiting versus refusing, and moves refused before anything is sent.""" + +import asyncio +import unittest +from typing import Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.homing_tests import SimulatedRunTest +from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration + +CONFIG = generic_configuration() +LEFT, RIGHT = CONFIG.pod("left"), CONFIG.pod("right") +PODS = {"left": LEFT, "right": RIGHT} +PARK_GG = 7.889 # the park's grip width, cm +PLATE = g.HeldLabware(length=12.776, width=8.548) # an SBS plate, held lengthwise + + +def pose(side: str, counts: int, gr: Optional[float] = 0.0, held=None) -> PodPose: + """A pod at X `counts`, its gripper turned to `gr` degrees (None: not known).""" + gripper = None if gr is None else g.GripperPose(gr, PARK_GG, held) + return PodPose(PODS[side].to_value("X", counts), gripper) + + +def rail() -> XRail: + return XRail({"left": LEFT, "right": RIGHT}) + + +class PodGeometryTests(unittest.TestCase): + def test_the_pipettor_lies_inside_the_bridge(self) -> None: + for pod in (LEFT, RIGHT): + self.assertEqual(g.pod_x_range(pod.geometry, 50.0), g.bridge_x_range(pod.geometry, 50.0)) + + def test_a_box_turning_covers_every_angle_between(self) -> None: + box = (1.0, 2.0, 0.0, 0.0) + self.assertEqual(g.turned_x_extent(box, 0, 0), (1.0, 2.0)) + lo, hi = g.turned_x_extent(box, 180, 180) + self.assertAlmostEqual(lo, -2.0) + self.assertAlmostEqual(hi, -1.0) + lo, hi = g.turned_x_extent(box, 0, 180) + self.assertAlmostEqual(lo, -2.0) + self.assertAlmostEqual(hi, 2.0) + + def test_the_right_gripper_reaches_past_its_bridge_towards_the_left_pod(self) -> None: + model = g.GripperModel.from_bif(RIGHT.gripper_model) + bridge = g.bridge_x_range(RIGHT.geometry, 100.0) + facing_left = g.gripper_x_range(RIGHT.geometry, model, 100.0, g.GripperPose(180, PARK_GG)) + self.assertAlmostEqual(bridge[0] - facing_left[0], 9.2, 1) + holding = g.gripper_x_range(RIGHT.geometry, model, 100.0, g.GripperPose(180, PARK_GG, PLATE)) + self.assertLess(holding[0], facing_left[0] - 4) # the plate sticks out past the fingers + + def test_the_left_gripper_never_reaches_past_its_bridge_towards_the_right_pod(self) -> None: + model = g.GripperModel.from_bif(LEFT.gripper_model) + low, high = LEFT.limits["GR"] + reach = g.gripper_x_range( + LEFT.geometry, + model, + 100.0, + g.GripperPose(low, 15.681, PLATE), + g.GripperPose(high, 15.681, PLATE), + ) + self.assertLess(reach[1], g.bridge_x_range(LEFT.geometry, 100.0)[1]) + + def test_a_turn_is_swept_along_its_path(self) -> None: + model = g.GripperModel.from_bif(RIGHT.gripper_model) + a, b = ( + g.Gripper(model, g.GripperPose(90, PARK_GG)), + g.Gripper(model, g.GripperPose(-90, PARK_GG)), + ) + swept = g.swept_x_range(RIGHT.geometry, 100.0, 100.0, a, b) + at_zero = g.gripper_x_range(RIGHT.geometry, model, 100.0, g.GripperPose(0, PARK_GG)) + self.assertGreaterEqual(swept[1], at_zero[1]) # passes through 0 degrees on the way + + +class RailTests(unittest.IsolatedAsyncioTestCase): + def test_the_bridges_meet_one_grid_cell_short_of_touching(self) -> None: + """The right gripper facing right (GR 0) stays inside its bridge: the bridges decide. They + touch at a combined 250,807 counts; Biomek compares edges as 1/16 cm cells, so with the + right pod here the last move allowed is a combined 250,767.""" + r = rail() + r.update("right", pose("right", -9258)) + r.check("left", pose("left", 0), pose("left", 241420)) # Biomek's own move + r.check("left", pose("left", 0), pose("left", 250767 - 9258)) + with self.assertRaises(RailCollisionError): + r.check("left", pose("left", 0), pose("left", 250768 - 9258)) + with self.assertRaises(RailCollisionError): # touching, and in the same cell + r.check("left", pose("left", 0), pose("left", 250807 - 9258)) + + def test_the_parked_right_gripper_takes_the_left_pod_closer_in(self) -> None: + """Parked facing the front (GR 90), the right gripper reaches 0.86 cm past its bridge.""" + r = rail() + r.update("right", pose("right", -9258, gr=90)) + with self.assertRaises(RailCollisionError): + r.check("left", pose("left", 0), pose("left", 250807 - 9258)) + r.check("left", pose("left", 0), pose("left", 250807 - 9258 - 2300)) + + def test_turning_the_gripper_into_the_other_pod_is_refused(self) -> None: + r = rail() + r.update("left", pose("left", int((70 - 10.519) * 2560))) # deck X 70: bridge to 93.6 + right_x = int((110 - 146.40669375) * 2560) # deck X 110: bridge from 95.7 + r.check("right", pose("right", right_x, gr=0), pose("right", right_x, gr=0)) + with self.assertRaises(RailCollisionError): + r.check("right", pose("right", right_x, gr=0), pose("right", right_x, gr=180)) + + def test_an_unknown_gripper_pose_counts_every_pose(self) -> None: + r = rail() + right_x = int((110 - 146.40669375) * 2560) + r.update("right", pose("right", right_x, gr=None)) + with self.assertRaises(RailCollisionError): # it could be facing left + r.check("left", pose("left", 0), pose("left", int((70 - 10.519) * 2560))) + + def test_either_pod_is_checked(self) -> None: + # Counts run from each pod's own home: the right pod's -2,560 is its park at the right end. + r = rail() + r.update("left", pose("left", 241420)) + r.check("right", pose("right", -2560), pose("right", 241420 - 250717)) + with self.assertRaises(RailCollisionError): + r.check("right", pose("right", -2560), pose("right", 241420 - 250718)) + + def test_a_pod_cannot_pass_through_the_other(self) -> None: + r = rail() + r.update("left", pose("left", 100000)) + with self.assertRaises(RailCollisionError): + r.check("right", pose("right", -2560), pose("right", -230000)) + + async def test_crossing_only_a_running_move_waits_for_it(self) -> None: + r = rail() + r.update("left", pose("left", 200000)) # far over; retreating home + r.update("right", pose("right", -2560)) + order = [] + + async def right_moves() -> None: + async with r.moving("right", pose("right", -2560), pose("right", -60000)): + order.append("right") + + async with r.moving("left", pose("left", 200000), pose("left", 0)): + task = asyncio.create_task(right_moves()) + await asyncio.sleep(0) + order.append("left") + await task + self.assertEqual(order, ["left", "right"]) + + async def test_crossing_where_a_running_move_ends_is_refused(self) -> None: + r = rail() + r.update("left", pose("left", 0)) + r.update("right", pose("right", -2560)) + async with r.moving("left", pose("left", 0), pose("left", 200000)): + with self.assertRaises(RailCollisionError): + async with r.moving("right", pose("right", -2560), pose("right", -60000)): + pass + + async def test_a_read_coming_back_mid_move_keeps_the_reservation(self) -> None: + r = rail() + r.update("left", pose("left", 0)) + r.update("right", pose("right", -2560)) + async with r.moving("right", pose("right", -2560), pose("right", -150000)): + r.update("right", pose("right", -2560)) + with self.assertRaises(RailCollisionError): + r.check("left", pose("left", 0), pose("left", 150000)) + + async def test_a_failed_move_keeps_its_reservation_until_read(self) -> None: + r = rail() + r.update("left", pose("left", 0)) + r.update("right", pose("right", -2560)) + with self.assertRaises(OSError): + async with r.moving("left", pose("left", 0), pose("left", 200000)): + raise OSError("lost the board") + self.assertEqual(r.occupied("left"), r.swept("left", pose("left", 0), pose("left", 200000))) + r.update("left", pose("left", 150000)) + self.assertEqual(r.occupied("left"), r.range_at("left", pose("left", 150000))) + + def test_an_unknown_position_allows_only_moving_away(self) -> None: + r = rail() + r.update("left", pose("left", 100000)) + r.check("left", pose("left", 100000), pose("left", 50000)) + with self.assertRaisesRegex(RuntimeError, "not known"): + r.check("left", pose("left", 100000), pose("left", 120000)) + + async def test_an_unknown_position_is_read_first(self) -> None: + r = rail() + r.update("left", pose("left", 0)) + + async def read_right() -> PodPose: + return pose("right", -2560) + + r.readers["right"] = read_right + async with r.moving("left", pose("left", 0), pose("left", 100000)): + pass + self.assertIsNotNone(r.occupied("right")) + + def test_no_declared_geometry_no_moves(self) -> None: + r = XRail({"left": LEFT, "right": None}) + with self.assertRaisesRegex(RuntimeError, "no declared geometry"): + r.check("left", pose("left", 0), pose("left", 1000)) + + def test_a_lone_pod_is_free(self) -> None: + XRail({"left": LEFT}).check("left", pose("left", 0), pose("left", 300000)) + + +class RailOnTheInstrumentTests(SimulatedRunTest): + async def test_a_move_into_the_other_pod_sends_no_motion(self) -> None: + driver = await self.start(True) + await driver.home() + assert driver.left_x_arm and driver.right_x_arm + await driver.right_x_arm.move_axes({"X": -100000}) + self.mark(driver) + with self.assertRaises(RailCollisionError): + await driver.left_x_arm.move_axes({"X": 200000}) + sent = {m[4] for m in self.usb(driver, "multichannel").requests[self.marks["multichannel"] :]} + self.assertNotIn(0x40, sent) # no Set Move Parameters + self.assertNotIn(0x50, sent) # no Move All + await driver.left_x_arm.move_axes({"X": 140000}) + self.assertEqual(driver.left_x_arm.cpositions["X"], (140000, 140000)) + + async def test_turning_a_gripper_into_the_other_pod_sends_no_motion(self) -> None: + driver = await self.start(True) + await driver.home() + assert driver.left_x_arm and driver.right_x_arm + left, right = driver.left_x_arm, driver.right_x_arm + await left.move_axes({"X": int((70 - 10.519) * 2560)}) + await right.move_axes({"X": int((110 - 146.40669375) * 2560)}) + facing_left = RIGHT.to_counts("GR", 180.0) + self.mark(driver) + with self.assertRaises(RailCollisionError): + await right.move_axes({"GR": facing_left}) + sent = {m[4] for m in self.usb(driver, "span8").requests[self.marks["span8"] :]} + self.assertNotIn(0x40, sent) + self.assertNotIn(0x50, sent) + + async def test_both_pods_moving_at_once_cannot_cross(self) -> None: + driver = await self.start(True) + await driver.home() + assert driver.left_x_arm and driver.right_x_arm + results = await asyncio.gather( + driver.left_x_arm.move_axes({"X": 150000}), + driver.right_x_arm.move_axes({"X": -150000}), + return_exceptions=True, + ) + self.assertEqual(sum(isinstance(r, RailCollisionError) for r in results), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py index 383804b7c66..703e6e8b87a 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -100,12 +100,15 @@ def generic_simulated_boards(**kwargs: Any) -> List[AceBoard]: def generic_driver( boards: Optional[Sequence[AceBoard]] = None, configuration: Optional[DeviceConfiguration] = None, + **kwargs: Any, ) -> BiomekI7Driver: """A driver over `boards` (by default the generic instrument replayed), declared by - `configuration` (by default the generic configuration's file).""" + `configuration` (by default the generic configuration's file); `kwargs` as `BiomekI7Driver` + takes them.""" return BiomekI7Driver( declared_configuration_json=( str(GENERIC_CONFIGURATION) if configuration is None else configuration_file(configuration) ), boards=generic_boards() if boards is None else boards, + **kwargs, ) From 09bcb33a3a9e53974cff7a4c5a49bdc3df8271af Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:57:53 +0000 Subject: [PATCH 13/28] `Biomek i7`: reword Home All runs for typos and sort imports --- .../beckman_coulter/biomek_i7/driver/features/pod.py | 8 ++++---- .../beckman_coulter/biomek_i7/driver/recipes/homing.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index 82ef8564a41..73c8e9961c5 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -19,26 +19,26 @@ from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.driver import motion +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( ModuleConfiguration, PodConfiguration, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, read_module, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ( ENABLE_ORDER, ENABLE_PREFIX, HOME_RECIPES, Homer, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english -from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail logger = logging.getLogger(__name__) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py index b8d16908cb9..e3abbdfd119 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py @@ -1,6 +1,6 @@ """Home All, as the Master Controller does it: a recipe of steps per arm type. -Each recipe was read off four Home Alls on one instrument (two after a power cycle, two with the +Each recipe was read off four Home All runs on one instrument (two after a power cycle, two with the instrument already homed, one of those with the Span-8 Z channels not homed) and reproduces every request each arm's board was sent, in order. Every target was the same in all four runs whatever the axes' positions before homing. Where a Home All leaves X, the Multichannel's Y and the gripper From 09bcd2fc357782be925ac92b610fec4ee5f172cf Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:19:09 -0800 Subject: [PATCH 14/28] `Biomek i7`: the deck, the device and the pods' models A PyLabRobot deck and the instrument as a resource, in both modes, as the STAR's: - `deck.py`: the deck in Biomek's pin grid and frame, ALPs placed by Biomek's own `column` and `row`, the declared configuration's layout (`BiomekI7Deck.from_configuration`). - `resource_model/`: Biomek's ALPs and their positions (the tip-loading position's adaptor plate, trash disposal offsets), the bridges and pods with their heads, probes and grippers from each pod's declared geometry, with 3D models; Biomek's labware classes by name (`labware.py`: the definitions in `pylabrobot.resources.beckman_coulter`) and Biomek's touch-off distance. A pod's body is of category `pod`, an ordinary child of its bridge. - `targeting.py`: from a resource on the deck to where a pod's first channel goes, with the pod's calibration of the deck position; `layouts.py`: a method's Instrument Setup on the deck. - `device.py`: `BiomekI7Device` and `BiomekI7(...)`, the instrument or `simulation=True` (the generic instrument when given no files); the pods' models drawn from the declared configuration before setup and following each pod's axes after; `setup` (home, then park), `park`, `pause`, `resume`, `home_all`, `stop`, the deck's traverse clearance; `state_json`, the tree's state (`save_state_to_file`: the tips on the heads' shafts), restored when the device is built and carried over to the models rebuilt at setup. - `Pod.resource`, `driver.deck`. Tests: on the generic configuration's own deck: positions where Biomek's instrument file has them, the models taking up the X the rail guard counts and following each axis, targets against Biomek's logged moves, travel at the traverse height and the deck's clearance, Biomek's labware by class name and its touch-off distance, the device in both modes. --- pylabrobot/beckman_coulter/biomek_i7/deck.py | 151 +++++ .../beckman_coulter/biomek_i7/deck_tests.py | 62 ++ .../biomek_i7/defaults/__init__.py | 2 +- .../beckman_coulter/biomek_i7/design.md | 26 + .../beckman_coulter/biomek_i7/device.py | 561 ++++++++++++++++++ .../biomek_i7/device_model_tests.py | 302 ++++++++++ .../beckman_coulter/biomek_i7/device_tests.py | 152 +++++ .../biomek_i7/driver/configuration.py | 6 +- .../biomek_i7/driver/features/pod.py | 12 +- .../biomek_i7/driver/master.py | 7 + .../biomek_i7/driver/simulator.py | 3 +- .../biomek_i7/driver/traverse_tests.py | 148 +++++ .../beckman_coulter/biomek_i7/layouts.py | 48 ++ .../biomek_i7/resource_model/__init__.py | 56 ++ .../biomek_i7/resource_model/alps.py | 471 +++++++++++++++ .../beckman_coulter_biomek_alp_BioShake.glb | Bin 0 -> 5784 bytes .../beckman_coulter_biomek_alp_ColdPlate.glb | Bin 0 -> 5764 bytes .../beckman_coulter_biomek_alp_ELx405DW.glb | Bin 0 -> 5732 bytes ...ckman_coulter_biomek_alp_OrbitalShaker.glb | Bin 0 -> 5788 bytes .../beckman_coulter_biomek_alp_Static1x1.glb | Bin 0 -> 5752 bytes .../beckman_coulter_biomek_alp_Static1x3.glb | Bin 0 -> 7048 bytes .../beckman_coulter_biomek_alp_Static1x5.glb | Bin 0 -> 8352 bytes ...an_coulter_biomek_alp_StaticPeltier_96.glb | Bin 0 -> 5780 bytes ...beckman_coulter_biomek_alp_Tilting_ALP.glb | Bin 0 -> 5792 bytes .../beckman_coulter_biomek_alp_TipLoad1x1.glb | Bin 0 -> 5768 bytes ...eckman_coulter_biomek_alp_TrashLeftBin.glb | Bin 0 -> 5784 bytes ...ckman_coulter_biomek_alp_TrashRightBin.glb | Bin 0 -> 5772 bytes ...an_coulter_biomek_alp_WashStationSpan8.glb | Bin 0 -> 5788 bytes .../beckman_coulter_biomek_i7.glb | Bin 0 -> 1149440 bytes ...ckman_coulter_biomek_i7_gripper_finger.glb | Bin 0 -> 3352 bytes .../beckman_coulter_biomek_i7_head_96.glb | Bin 0 -> 8516 bytes ...eckman_coulter_biomek_i7_span8_channel.glb | Bin 0 -> 4416 bytes .../biomek_i7/resource_model/heads.py | 188 ++++++ .../biomek_i7/resource_model/labware.py | 133 +++++ .../biomek_i7/resource_model/labware_tests.py | 109 ++++ .../biomek_i7/resource_model/pods.py | 402 +++++++++++++ .../biomek_i7/resource_model/units.py | 6 + .../biomek_i7/simulation_tests.py | 49 ++ .../biomek_i7/simulation_tests_support.py | 22 +- .../beckman_coulter/biomek_i7/targeting.py | 78 +++ .../biomek_i7/targeting_tests.py | 65 ++ 41 files changed, 3053 insertions(+), 6 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/deck.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/deck_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/device.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/device_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/layouts.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_BioShake.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_ColdPlate.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_ELx405DW.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_OrbitalShaker.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x1.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x3.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x5.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_StaticPeltier_96.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Tilting_ALP.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_TipLoad1x1.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_TrashLeftBin.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_TrashRightBin.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_WashStationSpan8.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_gripper_finger.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_head_96.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_span8_channel.glb create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/labware.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/labware_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/units.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/targeting.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/targeting_tests.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/deck.py b/pylabrobot/beckman_coulter/biomek_i7/deck.py new file mode 100644 index 00000000000..062bcce39ba --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/deck.py @@ -0,0 +1,151 @@ +"""The Biomek i7 deck: a plate with a grid of pins that ALPs are placed on. + +Biomek places an ALP by a pin: `column` is the pin column of its left pins, `row` the pin row of its +front pins. Biomek's own frame has X to the right and Y towards the front, in centimetres; this +deck's frame is PyLabRobot's, millimetres with Y towards the back, origin at the front left corner: + + x = X + FRAME_X + y = FRAME_Y - Y +""" + +import logging +from typing import TYPE_CHECKING, Any, Dict, List + +from pylabrobot.beckman_coulter.biomek_i7.resource_model.alps import ALP_TYPES, BiomekALP +from pylabrobot.beckman_coulter.biomek_i7.resource_model.units import cm + +# The frame's conversions live in `units.py`; re-exported here, where they were first. +from pylabrobot.beckman_coulter.biomek_i7.units import FRAME_X as FRAME_X +from pylabrobot.beckman_coulter.biomek_i7.units import FRAME_Y as FRAME_Y +from pylabrobot.beckman_coulter.biomek_i7.units import biomek_x as biomek_x +from pylabrobot.beckman_coulter.biomek_i7.units import biomek_y as biomek_y +from pylabrobot.beckman_coulter.biomek_i7.units import deck_x as deck_x +from pylabrobot.beckman_coulter.biomek_i7.units import deck_y as deck_y +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.deck import Deck +from pylabrobot.resources.resource_holder import ResourceHolder + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration + +logger = logging.getLogger(__name__) + +# Pin pitch, both ways. Biomek_i7.bif: DeckPitch; also every ALP definition's pin spacing. +PIN_PITCH = cm(2.0828) + +# Where pin column 0 and pin row 0 are in Biomek's frame. Fitted over every ALP placed on this +# unit's three decks (Biomek_i7.bif Decks/*/Groups: X1 + Pins.OffsetX against column, and +# Y1 + Pins.OffsetY + (Pins.RowCount - 1) x DeckPitch against row): all within 0.1 cm, which is the +# per-ALP calibration these files carry. +PIN_COLUMN_0_X = cm(-1.0827) +PIN_ROW_0_Y = cm(3.128) + +# The deck's extent in that frame. Chosen to enclose what this unit's layouts place, from the left +# trash bin to the right of the Span-8 wash station and from the front ALPs to the back of the +# ELx405; the deck plate itself has not been measured. +DECK_SIZE_X = cm(160.0) +DECK_SIZE_Y = cm(86.0) +# Working height above the deck: what the viewer draws the deck's space up to. Not a Biomek value. +DECK_SIZE_Z = cm(90.0) + + +class BiomekI7Deck(Deck): + """The deck of a Biomek i7: ALPs placed by pin, and their positions found by Biomek's names.""" + + def __init__(self, name: str = "deck", **kwargs: Any): + """`kwargs`: what `serialize` writes besides the name (the deck's fixed size and category); + taken so a saved deck loads (`Resource.load_from_json_file`), and otherwise ignored.""" + super().__init__( + name=name, + size_x=DECK_SIZE_X, + size_y=DECK_SIZE_Y, + size_z=DECK_SIZE_Z, + category="deck", + ) + + @property + def alps(self) -> Dict[str, BiomekALP]: + """The ALPs on the deck, by name.""" + return {c.name: c for c in self.children if isinstance(c, BiomekALP)} + + @staticmethod + def pin_location(column: int, row: int) -> Coordinate: + """Where pin (`column`, `row`) is on this deck.""" + return Coordinate( + FRAME_X + PIN_COLUMN_0_X + column * PIN_PITCH, + FRAME_Y - (PIN_ROW_0_Y + row * PIN_PITCH), + 0, + ) + + def alp_location(self, alp: BiomekALP, column: int, row: int) -> Coordinate: + """Where `alp`'s front left corner goes with its left pins in `column` and front pins in `row`.""" + pin = self.pin_location(column, row) + rows = alp.pin_count[1] + # The ALP's back left pin, from its back left corner, is its pin offset; its front pins are + # rows - 1 pitches in front of that, and its front edge the rest of its depth further. + back_edge_to_front_pins = alp.pin_offset[1] + (rows - 1) * PIN_PITCH + front_pins_to_front_edge = alp.get_size_y() - back_edge_to_front_pins + return Coordinate(pin.x - alp.pin_offset[0], pin.y - front_pins_to_front_edge, 0) + + def assign_alp(self, alp: BiomekALP, column: int, row: int) -> None: + """Place `alp` with its left pins in pin `column` and its front pins in pin `row`.""" + self.assign_child_resource(alp, location=self.alp_location(alp, column, row)) + + @classmethod + def from_configuration( + cls, configuration: "DeviceConfiguration", name: str = "deck" + ) -> "BiomekI7Deck": + """The deck a declared configuration lays out (`deck_layout`, imported from the instrument + file's default deck), each ALP by its pin column and row with its positions' names. + + Where the instrument file has an ALP's left edge (`X1`) whole pin pitches from where its + column puts it, the column is corrected to match: the file lists the Span-8 wash station at + column 71 and places it one pitch to the left, on all three decks of the file this was written + against, so the column is its pin offset's, not a placement. An ALP type this package has no + model for is left out, with a warning. + """ + deck = cls(name=name) + for placed in configuration.deck_layout: + factory = ALP_TYPES.get(placed.alp_type) + if factory is None: + logger.warning( + "%s: no model for ALP type %r; left off the deck", placed.name, placed.alp_type + ) + continue + alp = factory(placed.name, list(placed.positions)) + column = placed.column + if placed.x1 is not None: + left = biomek_x(deck.alp_location(alp, column, placed.row).x) / 10 # cm + steps = round((placed.x1 - left) * 10 / PIN_PITCH) + if steps: + logger.info( + "%s: placed %+d columns from its listed %d, at its X1", alp.name, steps, column + ) + column += steps + deck.assign_alp(alp, column=column, row=placed.row) + return deck + + def get_position(self, name: str) -> ResourceHolder: + """A deck position by Biomek's name for it (`P1`, `TL1`, `TR1`).""" + resource = self.get_resource(name) + if not isinstance(resource, ResourceHolder): + raise TypeError(f"{name} is a {type(resource).__name__}, not a deck position") + return resource + + @property + def position_names(self) -> List[str]: + """Every deck position Biomek names on this deck, across all its ALPs.""" + return [site.name for alp in self.alps.values() for site in alp.sites.values()] + + def summary(self) -> str: + """One line per ALP, left to right and back to front: what it is, where, its positions.""" + lines = [] + for alp in sorted( + self.alps.values(), key=lambda a: (a.get_location_wrt(self).x, -a.get_location_wrt(self).y) + ): + loc = alp.get_location_wrt(self) + sites = " ".join(s.name for s in alp.sites.values()) + lines.append( + f"{alp.name:20s} {alp.alp_type or '':17s} x={loc.x:7.1f} y={loc.y:6.1f} {sites}" + ) + return "\n".join(lines) diff --git a/pylabrobot/beckman_coulter/biomek_i7/deck_tests.py b/pylabrobot/beckman_coulter/biomek_i7/deck_tests.py new file mode 100644 index 00000000000..ed607790dea --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/deck_tests.py @@ -0,0 +1,62 @@ +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck, biomek_x, biomek_y +from pylabrobot.beckman_coulter.biomek_i7.resource_model import biomek_static_1x3, cm +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck +from pylabrobot.resources import beckman_coulter_biomek_96_tiprack_1070uL + + +class BiomekI7DeckTests(unittest.TestCase): + def setUp(self): + self.deck = generic_deck() + + def test_the_generic_deck_has_biomeks_positions(self): + # Deck1 of the instrument file the generic configuration was made from. + logged = {f"P{i}" for i in range(1, 25)} | {f"TL{i}" for i in (1, 2, 3, 4, 5, 6, 10, 11)} + logged |= {"TR1", "TR2", "W2", "W3", "BS1", "CP1", "TA1"} + self.assertEqual(set(self.deck.position_names), logged) + + def test_positions_land_where_biomek_has_them(self): + # The instrument file's Decks/Deck1/Positions/: X1, Y1, the position's back left corner + # in cm, within 1.1 mm: the per-ALP calibration the file carries beyond the pin grid. + expected = { + "P1": (40.4144, 25.8845), + "TR1": (10.9473, 17.5792), + "W2": (142.2654, 56.9271), + "W3": (78.6271, 14.3213), + "TL3": (11.2511, 57.1587), + } + for name, (x1, y1) in expected.items(): + with self.subTest(position=name): + site = self.deck.get_position(name) + loc = site.get_location_wrt(self.deck) + self.assertAlmostEqual(biomek_x(loc.x), cm(x1), delta=1.1) + self.assertAlmostEqual(biomek_y(loc.y + site.get_size_y()), cm(y1), delta=1.1) + + def test_biomek_front_is_plr_front(self): + # Biomek's Y grows towards the front: row 30 is the front row, row 10 the back one. + front = self.deck.get_position("P4").get_location_wrt(self.deck) + back = self.deck.get_position("TL10").get_location_wrt(self.deck) + self.assertLess(front.y, back.y) + + def test_an_alps_first_site_is_at_its_back(self): + alp = biomek_static_1x3("s", ["a", "b", "c"]) + a, c = alp.get_site("A1").location, alp.get_site("A3").location + assert a is not None and c is not None + self.assertGreater(a.y, c.y) + + def test_a_tip_box_on_a_tip_load_position(self): + deck = BiomekI7Deck() + deck.assign_alp(biomek_static_1x3("s", ["P1", "P2", "P3"]), column=20, row=30) + rack = beckman_coulter_biomek_96_tiprack_1070uL("tips") + deck.get_position("P1").assign_child_resource(rack) + a1 = rack.get_item("A1") + centre = a1.get_location_wrt(rack) + a1.center() + # BC1070: well1xoffset 1.44 cm, well1yoffset 1.12 cm from the back, height 11.41 cm. + self.assertAlmostEqual(centre.x, 14.4) + self.assertAlmostEqual(rack.get_size_y() - centre.y, 11.2) + self.assertAlmostEqual(centre.z, 114.1) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py index 5521919f901..5e329842dd3 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/__init__.py @@ -1,4 +1,4 @@ -"""A generic Biomek i7: what a simulation is given when it has no instrument's own files. +"""A generic Biomek i7: what `BiomekI7(simulation=True)` simulates when given no instrument's files. Made from one instrument's declared configuration and cold-start recording, with every serial number and name removed. Its physical values (motor tables, conversions, travel, geometry, diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index 0e9d2b98c84..0ea080aa312 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -71,3 +71,29 @@ must clear the other pod's range and any move it has in flight, or the move is r anything is sent (`driver/x_rail.py`, Biomek's own rule). The driver does not move the other pod out of the way; a caller makes room (`Pod.move_aside`, `Pod.park`). The guard uses the configuration only, so it holds without a deck. + +## The deck and the device + +**I8. The deck is optional; the device holds the models.** The driver homes, parks and moves with no +deck. `BiomekI7Device` (built by `BiomekI7(...)`, or `simulation=True`) is the resource tree: the +deck, and per pod a bridge and pod model built from the declared geometry, following the pod's axes. +The features hold their heads as the STAR's do (`head96.resource`, `pipettes.resources`). + +**I9. Targeting is PyLabRobot-native, with one Biomek correction** (`targeting.py`): a target is the +resource's location on the deck plus the offset, in Biomek's frame, plus the moving pod's +calibration of the deck position it stands on. Positions centre their labware, as Biomek does. + +**I10. Labware is Biomek's own.** Biomek's labware and tip classes are PyLabRobot definitions +(`pylabrobot.resources.beckman_coulter`); `resource_model/labware.py` names them by class, and +`layouts.place_labware` places a method's Instrument Setup. A tip's end is its length less its +seating depth; a tip-loading position's adaptor plate takes its labware 0.254 cm lower. + +**I11. Tips are shaft state.** A tip a head carries is a child of its `TipMountingShaft`, whose +state is the tip (`serialize_state`). The device saves the tree's state (`state_json`) whenever a +head's tips change, restores it when built, and carries it over to the models it rebuilds at setup: +the 96-head cannot sense tips, so that is how they are known across sessions. + +**I12. Travel is a traverse height, not a path planner.** Before X/Y travel the channels and the +gripper rise to a traverse height (by default near the top of travel; per call, as STAR's +`minimum_traverse_height_*`). A height below what the deck model and Biomek's per-pod obstacles need +is refused, not routed. diff --git a/pylabrobot/beckman_coulter/biomek_i7/device.py b/pylabrobot/beckman_coulter/biomek_i7/device.py new file mode 100644 index 00000000000..ad716652d6b --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/device.py @@ -0,0 +1,561 @@ +"""The Biomek i7 as one resource: its frame, its deck, and its two bridges with their pods. + +The frame's proportions, in centimetres: + +- `BaseXSpan` 188.0 on an i7 (130.0 on the single-pod frame), 91.025 deep, from 17 left of Biomek's + X origin and 11 behind its Y origin. +- `BaseHeight` 46.355: the cabinet under the deck plate. +- Three 2.667 plates stacked under the deck surface. +- Corner posts 8 x 8 standing `BaseHeight` + 20 - 8 = 58.355 above the plates, carrying the rails the + bridges ride on, 8 x 8 in section. + +The frame here is the device resource's own: origin at the front left bottom corner of the cabinet, millimetres, Y towards the back. +""" + +import logging +import os +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.deck import ( + FRAME_X, + FRAME_Y, + BiomekI7Deck, + biomek_x, + biomek_y, + deck_x, + deck_y, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis +from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver + +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import RECORDING_ENV, simulated_boards +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION, GENERIC_RECORDING +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + DeviceConfiguration, + PodConfiguration, +) +from pylabrobot.beckman_coulter.biomek_i7.resource_model import cm, pod_model +from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import PROBES +from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import ( + GripperModel, + gripper_model, + place_head96, + place_span8_channel, + span8_channels, +) +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.resource import Resource + +logger = logging.getLogger(__name__) + +BASE_X_SPAN = cm(188.0) # BaseXSpan default on an i7 +BASE_Y_SPAN = cm(91.025) +BASE_LEFT_OF_X0 = cm(17.0) # the base starts 17 cm left of Biomek's X origin +BASE_BEHIND_Y0 = cm(11.0) # and 11 cm behind its Y origin +CABINET_HEIGHT = cm(46.355) # BaseHeight +PLATE_THICKNESS = cm(2.667) +PLATES = 3 +POST_SECTION = cm(8.0) +POST_HEIGHT = cm(46.355 + 20.0 - 8.0) +RAIL_SECTION = cm(8.0) + +DECK_Z = CABINET_HEIGHT + PLATES * PLATE_THICKNESS +# The height the bridges ride at. The posts and rails are not drawn, so the device's own extent ends +# at the deck surface and the bridges and pods stand above it. +RAIL_TOP_Z = DECK_Z + POST_HEIGHT + RAIL_SECTION +SIZE_Z = DECK_Z + +# Where the deck's frame sits in the device's. Biomek X = deck x - FRAME_X, and the base begins +# BASE_LEFT_OF_X0 left of Biomek X 0; Biomek Y = FRAME_Y - deck y, and the base's back edge is +# BASE_BEHIND_Y0 behind Biomek Y 0. +DECK_X = BASE_LEFT_OF_X0 - FRAME_X +DECK_Y = BASE_Y_SPAN - BASE_BEHIND_Y0 - FRAME_Y + + +class BiomekI7Device(Resource): + """A Biomek i7: its frame, a deck, and a bridge per pod, driven through `driver` (STAR's + `STARDevice`; `BiomekI7(...)` builds one, as `STAR(...)` does). + + Each pod's model (`pod_models[side]`) rides its bridge (`bridges[side]`), which is the pod's + `resource` once the driver has found it (STAR's `x_arm.resource`). The models are built from the + instrument's declared geometry when the device is made, and each bridge follows its pod's X as + the driver moves it, placed as Biomek's collision model places it, so the resource tree takes up + the X the rail guard counts. The rest follows the pod's other axes (`_show_pod`): the + Multichannel's carriage its Y and its head (an `NChannelPipette`) its Z, each Span-8 probe's + channel its own Y and Z, and the gripper (a `MechanicalGripper`) GY, GZ, GR and GG. Each bridge + marks the point its pod's X names (`resource_model.pods.pod_model`). `update_bridge_location`, + `update_pod_location` and `update_probe_location` place the models by hand; nothing moves. + """ + + def __init__( + self, + driver: BiomekI7Driver, + deck: Optional[BiomekI7Deck] = None, + name: str = "biomek_i7", + state_json: Optional[str] = None, + ): + """ + Args: + driver: what talks to the instrument, or a simulated one (`BiomekI7(simulation=True)`). + deck: the deck. Defaults to the one the declared configuration lays out (`deck_layout`, + `BiomekI7Deck.from_configuration`), else an empty one (place ALPs with `deck.assign_alp`). + name: the resource's name. + state_json: where to keep this resource tree's state between sessions + (`save_state_to_file`): the tips on each head's shafts, which the 96-head cannot sense. + Loaded here when it exists, saved whenever a head's tips change. + """ + self.driver: BiomekI7Driver = driver + super().__init__( + name=name, + size_x=BASE_X_SPAN, + size_y=BASE_Y_SPAN, + size_z=SIZE_Z, + category="device", + model="beckman_coulter_biomek_i7", + ) + if deck is None: + # The default deck the declared configuration lays out, else an empty one. + deck = BiomekI7Deck.from_configuration(driver.declared) + self.deck = deck + driver.deck = self.deck # the operations work on this deck (STAR's `driver.deck`) + self.assign_child_resource(self.deck, location=Coordinate(DECK_X, DECK_Y, DECK_Z)) + + self.bridges: Dict[str, Resource] = {} + self.pod_models: Dict[str, Resource] = {} + # Each pod's gripper (from its declared model), posed from its axes. + self.gripper_models: Dict[str, GripperModel] = {} + self._unfollow: List[Callable[[], None]] = [] + self._build_declared_models(driver.declared) + self.state_json = state_json + if state_json is not None and os.path.exists(state_json): + self.load_state_from_file(state_json) # the tips on the declared heads' shafts + driver.on_tips_changed = self._tips_changed + if driver.arms: + self._follow_driver() # given a driver already set up + + # -- what the instrument has (read through to the driver) ------------------------ + # `left_x_arm` / `right_x_arm` are the driver's pods, named as STAR names its X-arms; + # `pod_models` and `bridges` are their models in the resource tree. + + @property + def left_x_arm(self) -> Optional[Pod]: + """The left pod, on an instrument that has one (known after `setup`).""" + return self.driver.left_x_arm + + @property + def right_x_arm(self) -> Optional[Pod]: + """The right pod, on an instrument that has one (known after `setup`).""" + return self.driver.right_x_arm + + @property + def arms(self) -> List[Pod]: + """The pods, left first.""" + return self.driver.arms + + @property + def x_arm(self) -> Pod: + """The pod, on an instrument with one (`BiomekI7Driver.x_arm`, which raises otherwise).""" + return self.driver.x_arm + + @property + def chassis(self) -> Optional[Chassis]: + """The chassis: the interlock and the chassis's inputs (known after `setup`).""" + return self.driver.chassis + + @property + def front_cover(self) -> Optional[Door]: + """The door, by STAR's name for it (known after `setup`).""" + return self.driver.front_cover + + async def setup( + self, + skip_device_initialization: bool = False, + *, + skip_left_x_arm: bool = False, + skip_right_x_arm: bool = False, + force_initialize: bool = False, + park: bool = True, + ) -> None: + """Bring the instrument up. This homes the arms, then parks the pods, as Biomek's Home All + does (`park`). + + Args: + skip_device_initialization: as `BiomekI7Driver.setup` takes it. + skip_left_x_arm: as `BiomekI7Driver.setup` takes it. + skip_right_x_arm: as `BiomekI7Driver.setup` takes it. + force_initialize: as `BiomekI7Driver.setup` takes it. + park: park every pod that was brought up (`park`). + """ + await self.driver.setup( + skip_device_initialization=skip_device_initialization, + skip_left_x_arm=skip_left_x_arm, + skip_right_x_arm=skip_right_x_arm, + force_initialize=force_initialize, + ) + self._follow_driver() + skipped = self.driver.skipped_sides( + skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm + ) + if park: + await self.park(skip=skipped) + + async def park(self, skip: Iterable[str] = ()) -> None: + """Park the pods as Biomek does (`Pod.park`), the left pod first, as each pod's park is at its + own end of the rail. `skip`: sides to leave as they are.""" + for pod in sorted(self.driver.arms, key=lambda p: p.side != "left"): + if pod.side in skip: + continue + await pod.park() + + async def pause(self) -> None: + """Pause for access, as Biomek's Pause step: the pods' drive power is cut and PAUSED shown, + so the light curtain may be broken. Move the pods out of the way first if needed + (`move_aside`, `park`). See `BiomekI7Driver.pause`.""" + await self.driver.pause() + + async def resume(self, speed: int = 200) -> None: + """Resume after `pause`: re-arm (the light curtain must be clear), enable, and move the pods + back to where they were. See `BiomekI7Driver.resume`.""" + await self.driver.resume(speed) + + async def home_all(self, force: bool = True) -> None: + """Biomek's Home All: bring the instrument up again, by default homing every axis as Biomek + does. `force=False` homes only what is not homed.""" + await self.driver.initialize(force_initialize=force) + + async def stop(self) -> None: + """Release the instrument. Moves nothing.""" + for unfollow in self._unfollow: + unfollow() + self._unfollow = [] + await self.driver.stop() + + # -- the pods' models ------------------------------------------------------------ + + def _build_pod_model( + self, side: str, module_type: str, declared: Optional[PodConfiguration] = None + ) -> None: + """(Re)build a side's bridge and pod, keeping the bridge where it was.""" + old = self.bridges.pop(side, None) + geometry = declared.geometry if declared is not None else None + settings = declared.settings if declared is not None else None + rail, pod = pod_model(side, module_type, BASE_Y_SPAN, geometry, settings) + if old is not None and old.location is not None: + x = old.location.x + self.unassign_child_resource(old) + elif side == "left": + x = POST_SECTION + else: + x = BASE_X_SPAN - POST_SECTION - rail.get_size_x() + # The bridges ride on the rails' top faces. + self.assign_child_resource(rail, location=Coordinate(x, 0, RAIL_TOP_Z)) + self.bridges[side], self.pod_models[side] = rail, pod + + def _follow_driver(self) -> None: + """Rebuild each pod's model from the driver's pod (its module type and declared geometry) and + follow its X from now on.""" + for unfollow in self._unfollow: + unfollow() + self._unfollow = [] + # The heads' tips, carried over to the rebuilt models (the state the tree saves). + saved: Dict[str, Dict[str, Any]] = {} + for bridge in self.bridges.values(): + saved.update(bridge.serialize_all_state()) + for pod in self.driver.arms: + self._build_pod_model(pod.side, pod.module_type, pod.declared) + self._build_gripper_model(pod.side, pod.declared) + if pod.declared is not None: + self._show_parked(pod.side, pod.declared) + pod.resource = self.bridges[pod.side] + self.bridges[pod.side].load_all_state(saved) + if pod.declared is not None: + self._unfollow.append(pod.add_position_listener(self._show_pod)) + self._show_pod(pod) + + def _tips_changed(self) -> None: + """A head's tips changed: save the tree's state, when there is a `state_json`.""" + if self.state_json is not None: + self.save_state_to_file(self.state_json, indent=1) + + def _build_declared_models(self, configuration: DeviceConfiguration) -> None: + """Build each declared pod's models, before the instrument is read: the pods the driver will + find, where the declared configuration describes them (discovery refuses another pod type).""" + for side, declared in configuration.pods.items(): + self._build_pod_model(side, declared.module_type, declared) + self._build_gripper_model(side, declared) + self._show_parked(side, declared) + + def _show_parked(self, side: str, declared: PodConfiguration) -> None: + """Pose a pod's model as Biomek parks it, before the driver says where it is: its channels at + the top of their travel less `ZMargin`, a Multichannel's carriage at the park's Y (else the + back of its travel), a Span-8's probes at the back at their narrowest span.""" + limits, park, geo = declared.limits, declared.park, declared.geometry + margin = park.get("ZMargin", 0.0) + if declared.module_type == "multichannel": + y = park.get("Y", limits.get("Y", (0.0, 0.0))[0]) + z = limits["Z"][1] + margin if "Z" in limits else None + front = y - geo.mandrel1_y_offset + geo.pod_y_span + self.update_pod_location(side, deck_y(cm(front)), z=None if z is None else cm(z)) + return + y1 = limits.get("Y", (0.0, 0.0))[0] + spacing = self._probe_spacing(declared) + for probe in range(1, PROBES + 1): + zs = limits.get(f"Z{probe}", limits.get("Z")) + if zs is None: + continue + y = y1 + (probe - 1) * spacing + self.update_probe_location(side, probe, deck_y(cm(y)), cm(zs[1] + margin)) + front = y1 - geo.mandrel1_y_offset + geo.pod_y_span + self.update_pod_location(side, deck_y(cm(front))) + + @staticmethod + def _probe_spacing(declared: PodConfiguration) -> float: + """The Span-8's probes' spacing at their narrowest (cm; `PodConfiguration.probe_spacing`).""" + return declared.probe_spacing() + + def _build_gripper_model(self, side: str, declared: Optional[PodConfiguration]) -> None: + """(Re)build a side's gripper on its bridge, posed as parked until the driver says otherwise.""" + old = self.gripper_models.pop(side, None) + if old is not None: + for part in (old.upper_hand, old.gripper): + if part.parent is not None: + part.unassign() + if declared is None or not declared.gripper_model: + return + gg_range = declared.limits.get("GG", (0.0, 20.0)) + model = gripper_model(f"{side}_gripper", declared.gripper_model, gg_range) + bridge = self.bridges[side] + for part in (model.upper_hand, model.gripper): + bridge.assign_child_resource(part, location=Coordinate.zero()) + self.gripper_models[side] = model + park, limits = declared.park, declared.limits + gz_top = limits["GZ"][1] + park.get("GZMargin", 0.0) if "GZ" in limits else 0.0 + model.pose( + self._gripper_centre(side, declared, park.get("GY", 0.0), gz_top), + park.get("GR", 90.0), + park.get("GG", gg_range[0]), + ) + + def _gripper_centre( + self, side: str, declared: PodConfiguration, gy: float, gz: float + ) -> Coordinate: + """Where the gripper's rotation centre is in its bridge's frame (mm), at GY `gy` and GZ `gz` + (cm), as `pod_geometry` places it: X + `GripperXOffset` - `PadsCenterToRotationCenter`, which + is a fixed distance from the bridge's left edge (`bridge_x_range`), GY + `GripperYOffset` - + `FingerCenterOffset`, and the hand's bottom the fingers' depth above GZ + `GripperZOffset`.""" + geo, finger = declared.geometry, declared.gripper_model["Finger"] + model, bridge = self.gripper_models[side], self.bridges[side] + at = bridge.location if bridge.location is not None else Coordinate.zero() + x = geo.gripper_x_offset - finger["PadsCenterToRotationCenter"] + x += geo.bridge_to_head_x_offset + geo.mandrel1_x_offset + cy = gy + geo.gripper_y_offset - finger["FingerCenterOffset"] + cz = gz + geo.gripper_z_offset + model.depth + return Coordinate(cm(x), DECK_Y + deck_y(cm(cy)) - at.y, DECK_Z + cm(cz) - at.z) + + @staticmethod + def _axis_counts(pod: Pod, axis: str) -> Optional[int]: + """An axis's position, counts, as the Master Controller keeps it adjusted for the axis's + hysteresis (`motion.update_cpos`): the position its targets name, so the frame the operations + are placed in (`targeting.py`), and known whenever the axis is (the raw position is not after + a home or a force-limited move). One rule for every part shown, so the bridge, the pod, its + head or probes and the gripper never disagree.""" + if axis not in pod.cpositions: + return None + return pod.cpositions[axis][1] + + @classmethod + def _axis_value(cls, pod: Pod, axis: str) -> Optional[float]: + """An axis's position in its unit (`_axis_counts`).""" + d, counts = pod.declared, cls._axis_counts(pod, axis) + return None if d is None or counts is None else d.to_value(axis, counts) + + def _show_gripper(self, pod: Pod) -> None: + """Pose a pod's gripper model from its axes (the rotation centre: `pod_geometry`).""" + d, model = pod.declared, self.gripper_models.get(pod.side) + if d is None or model is None: + return + v = {a: self._axis_value(pod, a) for a in ("GY", "GZ", "GR", "GG")} + if any(value is None for value in v.values()): + return + gy, gz, gr, gg = (float(v[a]) for a in ("GY", "GZ", "GR", "GG")) # type: ignore[arg-type] + model.pose(self._gripper_centre(pod.side, d, gy, gz), gr, gg) + + def _show_pod(self, pod: Pod) -> None: + """Put a pod's model where the pod's axes are (an unknown one: where it was). + + - X: the bridge's left edge at `bridge_x_range` in Biomek's X. + - Y and Z, on a Multichannel: Biomek's Y and Z name mandrel A1 (Y over a plate's well A1, Z the + bare mandrel's bottom above the deck's surface). The carriage's back edge is `Mandrel1YOffset` behind it and follows Y; the head + follows Z in it, its flange bottom taken as the mandrels' bottom. + - On a Span-8, each probe's Y and Z (`Y1`..`Y8`, `Z1`..`Z8`), as the probes are targeted: a + probe's Y counts from its narrowest place, `S`'s zero span shared out between the eight + (`_probe_spacing`), and its Z is the bare probe's end. The carriage follows probe 1. + - The gripper: `_show_gripper`. + """ + d = pod.declared + if d is None: + return + x = self._axis_value(pod, "X") + if x is not None: + low, _ = g.bridge_x_range(d.geometry, x) + self.update_bridge_location(pod.side, deck_x(cm(low))) + self._show_gripper(pod) + geo = d.geometry + if pod.module_type == "multichannel": + y, z = self._axis_value(pod, "Y"), self._axis_value(pod, "Z") + if y is None: + return + front = y - geo.mandrel1_y_offset + geo.pod_y_span + self.update_pod_location(pod.side, deck_y(cm(front)), z=None if z is None else cm(z)) + return + for probe in range(1, PROBES + 1): + yc, zc = self._axis_counts(pod, f"Y{probe}"), self._axis_counts(pod, f"Z{probe}") + if yc is None or zc is None: + continue + y = d.probe_y(probe, yc) + self.update_probe_location(pod.side, probe, deck_y(cm(y)), cm(d.to_value(f"Z{probe}", zc))) + if probe == 1: + self.update_pod_location(pod.side, deck_y(cm(y - geo.mandrel1_y_offset + geo.pod_y_span))) + + def traverse_clearance( + self, side: str, x: Tuple[float, float], y: Tuple[float, float], tip_length: float = 0.0 + ) -> float: + """The lowest height, mm above the deck, a pod's channels may travel at over the area `x` by + `y` (deck x and y ranges, mm), for `Pod.move_over`'s `clearance`: the top of the tallest + resource there, plus the pod's `AdditionalSafeHeight`, plus `tip_length` (mm the tips reach + below the channels' bottom). Its Biomek-unit counterpart is `_traverse_clearance`.""" + bx = sorted(units.to_cm(units.biomek_x(v)) for v in x) + by = sorted(units.to_cm(units.biomek_y(v)) for v in y) + clearance = self._traverse_clearance( + side, (bx[0], bx[1]), (by[0], by[1]), units.to_cm(tip_length) + ) + return units.to_mm(clearance) + + def _traverse_clearance( + self, side: str, x: Tuple[float, float], y: Tuple[float, float], tip_length: float = 0.0 + ) -> float: + """The lowest height (Biomek Z, cm) a pod's channels may travel at over the area `x` by `y` + (Biomek X/Y, cm), for `Pod._move_over`'s `clearance`: the top of the tallest resource on the + deck there, plus the pod's `AdditionalSafeHeight`, plus `tip_length` (cm the tips reach below + the channels' bottom). Biomek's Z is the deck model's z in cm (design.md I9). The deck itself, + its ALPs' frames included, counts; the pods' own models do not.""" + pod = self.driver.arm(side) + if pod.declared is None: + raise RuntimeError(f"{pod} has no declared configuration") + top = 0.0 + for resource in self.deck.get_all_children(): + loc = resource.get_location_wrt(self.deck) + left, right = biomek_x(loc.x) / 10, biomek_x(loc.x + resource.get_size_x()) / 10 + back, front = biomek_y(loc.y + resource.get_size_y()) / 10, biomek_y(loc.y) / 10 + if left < x[1] and x[0] < right and back < y[1] and y[0] < front: + top = max(top, (loc.z + resource.get_size_z()) / 10) + return top + pod.declared.geometry.additional_safe_height + tip_length + + def update_bridge_location(self, side: str, x: float) -> None: + """Put a side's bridge's left edge at deck x `x` mm, carrying its pod along the rails.""" + rail = self.bridges[side] + loc = rail.location + if loc is None: + raise ValueError(f"{rail.name} is not placed on {self.name}") + rail.location = Coordinate(DECK_X + x, loc.y, loc.z) + + def update_pod_location(self, side: str, y: float, z: Optional[float] = None) -> None: + """Put a side's pod's front edge at deck y `y` mm along its bridge, and, on a Multichannel, its + head's bottom (the mandrels' ends) at deck z `z` mm; the carriage keeps its height. + + Raises: + ValueError: for a `z` on a pod with no 96-channel head: a Span-8's probes move one by one + (`update_probe_location`). + """ + pod = self.pod_models[side] + loc = pod.location + if loc is None or pod.parent is None: + raise ValueError(f"{pod.name} is not on a bridge") + if z is not None and not any(c.name == f"{pod.name}_head" for c in pod.children): + raise ValueError( + f"{pod.name} has no 96-channel head; place its probes with update_probe_location" + ) + pod.location = Coordinate(loc.x, DECK_Y + y, loc.z) + if z is not None: + place_head96(pod, DECK_Z + z - pod.get_location_wrt(self).z) + + def update_probe_location(self, side: str, probe: int, y: float, z: float) -> None: + """Put a Span-8's probe `probe` (1..8) end at deck y `y` and deck z `z` (mm), on its bridge's + line: the X the pod names.""" + rail = self.bridges[side] + channels = span8_channels(rail) + if not 1 <= probe <= len(channels): + raise ValueError(f"{rail.name} has no probe {probe}") + at = rail.location if rail.location is not None else Coordinate.zero() + ref = getattr(rail, "reference_point", None) + x = ref.x if ref is not None else channels[probe - 1].reference_point.x # type: ignore[attr-defined] + place_span8_channel(channels[probe - 1], x, DECK_Y + y - at.y, DECK_Z + z - at.z) + + +def BiomekI7( + deck: Optional[BiomekI7Deck] = None, + simulation: bool = False, + declared_configuration_json: Optional[str] = None, + driver: Optional[BiomekI7Driver] = None, + name: str = "biomek_i7", + simulator_recording: Optional[str] = None, + state_json: Optional[str] = None, + simulate_motion_time: bool = False, + motion_time_scale: float = 0.25, +) -> BiomekI7Device: + """A Biomek i7 (`BiomekI7Device`) and what drives it, as `STAR(...)` builds a `STARDevice`, with + its arguments in the same order. + + Args: + deck: the deck. Defaults to the one the declared configuration lays out (`deck_layout`, + `BiomekI7Deck.from_configuration`), else an empty one (place ALPs with `deck.assign_alp`). + simulation: drive a simulated instrument instead (`driver/simulator.py`): powered up, not + configured, not homed. Ignored when a driver is given. + declared_configuration_json: the instrument's declared configuration (its calibration, axis scales + and limits, deck positions), as `DeviceConfiguration.from_biomek` makes it from its Biomek + files, for the driver this builds. Required for the instrument; in simulation, the package's + generic one when None. Ignored when a driver is given. + simulator_recording: the cold-start recording a simulated instrument answers identity and + sensor reads from; `$BIOMEK_I7_SIMULATOR_RECORDING` when None, else the package's generic + one (`defaults/biomek_i7_generic_coldstart.json`). + driver: what talks to the instrument, instead of the one this builds. + name: the resource's name. + state_json: where the device keeps its tree's state between sessions, the tips on each head + among it (`BiomekI7Device`'s `state_json`). + simulate_motion_time: whether a simulated move takes time at all, as the STAR's and the + Prep's simulators take it: the time the instrument's drives would take (from each move's + distance, speed and acceleration), so a viewer shows each step. Off, every move answers at + once. + motion_time_scale: the share of the instrument's time a move takes when it does: a quarter, + so a step is watched rather than waited for. 1.0 keeps the instrument's time. + + Two modes, as the STAR's: the instrument (`BiomekI7Driver`, from its own declared + configuration; nothing is opened until `setup`), or a simulated one (`simulation=True`). A + simulated instrument given no configuration is the package's generic one (`defaults/`): a + Biomek i7 with one instrument's physical values, no serial numbers and no measured hysteresis. + The instrument is never driven from it. + """ + if driver is not None and simulation: + logger.warning("both a driver and simulation given; driving the driver") + if driver is None and simulation: + if declared_configuration_json is None: + logger.info("simulating a generic Biomek i7 (%s)", GENERIC_CONFIGURATION.name) + declared_configuration_json = str(GENERIC_CONFIGURATION) + if simulator_recording is None and not os.environ.get(RECORDING_ENV): + simulator_recording = str(GENERIC_RECORDING) + tables = DeviceConfiguration.load(declared_configuration_json).motor_tables + boards = simulated_boards( + motor_tables=tables, + path=simulator_recording, + time_scale=motion_time_scale if simulate_motion_time else 0.0, + ) + driver = BiomekI7Driver( + declared_configuration_json=declared_configuration_json, boards=boards + ) + elif driver is None: + driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json) + return BiomekI7Device(driver=driver, deck=deck, name=name, state_json=state_json) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py new file mode 100644 index 00000000000..5f67e8797ce --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py @@ -0,0 +1,302 @@ +"""The pods' models in the resource tree: built from the declared geometry, following each pod's X, +and taking up the X the rail guard counts (`driver/pod_geometry.py`).""" + +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.deck import FRAME_X, biomek_y +from pylabrobot.beckman_coulter.biomek_i7.device import ( + DECK_X, + DECK_Y, + DECK_Z, + BiomekI7, + BiomekI7Device, +) +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.resource_model import MM_PER_CM +from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import gripper_model +from pylabrobot.resources import Resource +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.rotation import Rotation +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_biomek, + generic_configuration, + generic_deck, +) + + +def biomek_x_range(lh: BiomekI7Device, resource: Resource) -> g.Range: + """A resource's X extent in Biomek's X, cm.""" + low = (resource.get_location_wrt(lh).x - DECK_X - FRAME_X) / MM_PER_CM + return low, low + resource.get_size_x() / MM_PER_CM + + +class DeviceModelTests(PodMoveTest): + async def test_the_models_take_up_the_x_the_rail_counts(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + left, right = self.pod(driver, "left"), self.pod(driver, "right") + await left.move_axes({"X": 100000}) + await right.move_axes({"X": right.axis("X").home_position}) + for pod in (left, right): + assert pod.declared is not None + geometry = pod.declared.geometry + x = pod.declared.to_value("X", pod.cpositions["X"][0] or 0) + bridge = g.bridge_x_range(geometry, x) + pipettor = g.pipettor_x_range(geometry, x) + margin = geometry.avoidance_margin + with self.subTest(side=pod.side): + for got, want in zip(biomek_x_range(lh, lh.bridges[pod.side]), bridge): + self.assertAlmostEqual(got, want, delta=1e-4) # 1 um: PyLabRobot rounds coordinates + for got, want in zip( + biomek_x_range(lh, lh.pod_models[pod.side]), (pipettor[0] + margin, pipettor[1] - margin) + ): + self.assertAlmostEqual(got, want, delta=1e-4) # 1 um: PyLabRobot rounds coordinates + + async def test_a_bridge_follows_its_pod(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + left = self.pod(driver, "left") + assert left.declared is not None + for counts in (60000, 140000): + await left.move_axes({"X": counts}) + x = left.declared.to_value("X", counts) + self.assertAlmostEqual( + biomek_x_range(lh, lh.bridges["left"])[0], g.bridge_x_range(left.declared.geometry, x)[0] + ) + await lh.stop() # stops following + before = lh.bridges["left"].location + left._positions_changed() + self.assertEqual(lh.bridges["left"].location, before) + + async def test_the_multichannel_follows_y_and_z_at_mandrel_a1(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + left = self.pod(driver, "left") + d = left.declared + assert d is not None + # Homed, GR is at -16 degrees: the fingers under the head. Turn them out first, as the park does. + await left.move_axes({"GR": d.to_counts("GR", d.park["GR"])}) + await left.move_axes({"Y": 50000, "Z": -60000}) + y, z = d.to_value("Y", 50000), d.to_value("Z", -60000) + pod = lh.pod_models["left"] + back = pod.get_location_wrt(lh).y - DECK_Y + pod.get_size_y() # deck y grows to the back + self.assertAlmostEqual(biomek_y(back) / MM_PER_CM, y - d.geometry.mandrel1_y_offset, delta=1e-4) + head = lh.get_resource("left_pod_head") + self.assertAlmostEqual((head.get_location_wrt(lh).z - DECK_Z) / MM_PER_CM, z, delta=1e-4) + # Mandrel A1's shaft is over A1's X and Y, its end at Z; the carriage did not move in Z. + a1 = head.get_item("A1") # type: ignore[attr-defined] + centre = a1.get_location_wrt(lh) + Coordinate(a1.get_size_x() / 2, a1.get_size_y() / 2, 0) + self.assertAlmostEqual(biomek_y(centre.y - DECK_Y) / MM_PER_CM, y, delta=1e-4) + self.assertAlmostEqual( + (centre.x - DECK_X - FRAME_X) / MM_PER_CM, + d.to_value("X", left.cpositions["X"][1]), + delta=1e-4, + ) + self.assertAlmostEqual((centre.z - DECK_Z) / MM_PER_CM, z, delta=1e-4) + carriage = pod.get_location_wrt(lh).z + await left.move_axes({"Z": -20000}) + self.assertAlmostEqual(pod.get_location_wrt(lh).z, carriage) + + async def test_each_arms_line_marks_the_x_its_pod_names(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + left, right = self.pod(driver, "left"), self.pod(driver, "right") + await right.move_axes({"X": right.axis("X").home_position}) + for pod, counts in ((left, 60000), (left, 140000), (right, right.axis("X").home_position)): + if pod is left: + await left.move_axes({"X": counts}) + d = pod.declared + assert d is not None and pod.resource is lh.bridges[pod.side] + bridge = pod.resource + line = bridge.get_location_wrt(lh).x + bridge.reference_point.x # type: ignore[attr-defined] + x = d.to_value("X", counts) # cm, Biomek's X: what mandrel A1 / probe 1 is at + self.assertAlmostEqual((line - DECK_X - FRAME_X) / MM_PER_CM, x, delta=1e-4) + # The pod's own mark is at the same X. + model = lh.pod_models[pod.side] + ref = model.reference_point # type: ignore[attr-defined] + ref_x = ref["x"] if isinstance(ref, dict) else ref.x + self.assertAlmostEqual(model.get_location_wrt(lh).x + ref_x, line, delta=1e-3) + + async def test_the_multichannel_marks_mandrel_a1(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + left = self.pod(driver, "left") + d = left.declared + assert d is not None + await left.move_axes({"GR": d.to_counts("GR", d.park["GR"])}) + await left.move_axes({"X": 100000, "Y": 50000}) + pod = lh.pod_models["left"] + ref = pod.reference_point # type: ignore[attr-defined] + at = pod.get_location_wrt(lh) + self.assertAlmostEqual( + (at.x + ref["x"] - DECK_X - FRAME_X) / MM_PER_CM, d.to_value("X", 100000), delta=1e-4 + ) + self.assertAlmostEqual( + biomek_y(at.y + ref["y"] - DECK_Y) / MM_PER_CM, d.to_value("Y", 50000), delta=1e-4 + ) + lo, hi = ref["y_range"] + self.assertAlmostEqual((lo + hi) / 2, ref["y"]) + + def test_the_models_are_the_declared_pods_before_setup(self) -> None: + lh = generic_biomek() + for side, declared in lh.driver.declared.pods.items(): + self.assertAlmostEqual(lh.bridges[side].get_size_x(), declared.geometry.bridge_x_span * 10) + self.assertEqual(lh.pod_models["right"].name, "right_pod") + self.assertEqual(set(lh.gripper_models), {"left", "right"}) + + def test_the_96_head_stands_its_mandrels_out_of_its_body(self) -> None: + lh = generic_biomek() + settings = lh.driver.declared.pods["left"].settings + head = lh.get_resource("left_pod_head") + # Flange to the mandrels' end: Head/PodToMandrel1 Z. + self.assertAlmostEqual(head.get_size_z(), 105.245, delta=1e-6) + for name in ("A1", "H12"): + shaft = head.get_item(name) # type: ignore[attr-defined] + with self.subTest(shaft=name): + assert shaft.location is not None + self.assertAlmostEqual(shaft.location.z, 0.0) # its end is the head's bottom + # It stands out of the body by the head's seating depth: a seated tip meets the body. + self.assertAlmostEqual( + shaft.get_size_z(), settings["TipSeatingDepth"] * MM_PER_CM, delta=1e-6 + ) + + def test_the_span8_channels_stand_apart_at_their_narrowest(self) -> None: + lh = generic_biomek() + settings = lh.driver.declared.pods["right"].settings + pod = lh.pod_models["right"] + channels = [lh.get_resource(f"right_pod_channel_{i}") for i in range(1, 9)] + for front, back in zip(channels[1:], channels): # probe 1 is at the back (deck y grows back) + gap = back.get_location_wrt(lh).y - (front.get_location_wrt(lh).y + front.get_size_y()) + with self.subTest(probe=channels.index(front) + 1): + self.assertGreater(gap, 0.5) + for channel in channels: + shaft = channel.children[0] + with self.subTest(channel=channel.name): + # The probe is as wide as its tip hub, and each channel spans the pod in X. + self.assertAlmostEqual( + shaft.get_size_x(), 2 * settings["DefaultTipHubInfo"]["MaxRadius"] * MM_PER_CM + ) + self.assertAlmostEqual( + channel.get_location_wrt(lh).x, pod.get_location_wrt(lh).x, delta=1e-3 + ) + self.assertAlmostEqual(channel.get_size_x(), pod.get_size_x()) + + async def test_the_span8_probes_follow_y_span_and_z(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + right = self.pod(driver, "right") + d = right.declared + assert d is not None + park = d.park + await right.move_axes({a: d.to_counts(a, park[a]) for a in ("GR", "GY")}) # gripper clear + y1, span = 30.0, 14.0 # cm: probe 1's Y, and probe 1 to 8 + await right.move_axes({"Y": d.to_counts("Y", y1), "S": d.to_counts("S", span)}) + await right.move_axes({"Z3": d.to_counts("Z3", 25.0)}) + x = d.to_value("X", right.cpositions["X"][1]) + for probe in range(1, 9): + channel = lh.get_resource(f"right_pod_channel_{probe}") + end = channel.get_location_wrt(lh) + channel.reference_point # type: ignore[attr-defined] + with self.subTest(probe=probe): + # Within a count's rounding: each probe's Y is a whole number of counts. + self.assertAlmostEqual( + biomek_y(end.y - DECK_Y) / MM_PER_CM, y1 + (probe - 1) * span / 7, delta=1e-3 + ) + self.assertAlmostEqual((end.x - DECK_X - FRAME_X) / MM_PER_CM, x, delta=1e-3) + channel = lh.get_resource("right_pod_channel_3") + end = channel.get_location_wrt(lh) + channel.reference_point # type: ignore[attr-defined] + self.assertAlmostEqual((end.z - DECK_Z) / MM_PER_CM, 25.0, delta=1e-3) + # The carriage follows probe 1. + pod = lh.pod_models["right"] + back = pod.get_location_wrt(lh).y - DECK_Y + pod.get_size_y() + self.assertAlmostEqual( + biomek_y(back) / MM_PER_CM, y1 - d.geometry.mandrel1_y_offset, delta=1e-3 + ) + + async def test_after_home_the_bridge_and_the_gripper_agree_on_x(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + for side in ("left", "right"): + pod = self.pod(driver, side) + d = pod.declared + assert d is not None + x = d.to_value("X", pod.cpositions["X"][1]) # adjusted: what the model follows + with self.subTest(side=side): + self.assertAlmostEqual( + biomek_x_range(lh, lh.bridges[side])[0], g.bridge_x_range(d.geometry, x)[0], delta=1e-4 + ) + gripper = lh.gripper_models[side].gripper + centre = gripper.get_location_wrt(lh) + gripper.proximal_joint.rotated( + gripper.get_absolute_rotation() + ) + finger = d.gripper_model["Finger"] + want = x + d.geometry.gripper_x_offset - finger["PadsCenterToRotationCenter"] + self.assertAlmostEqual((centre.x - DECK_X - FRAME_X) / MM_PER_CM, want, delta=1e-3) + + +class GripperModelTests(unittest.TestCase): + """The gripper's model posed by hand: it turns about the rotation centre to any GR, its fingers + span the instrument file's finger outline, and its pads stand GG apart.""" + + def setUp(self) -> None: + self.declared = generic_configuration().pod("left") + self.model = gripper_model("g", self.declared.gripper_model, self.declared.limits["GG"]) + self.finger = self.declared.gripper_model["Finger"] + + def test_the_tool_centre_point_turns_with_gr_about_the_centre(self) -> None: + centre = Coordinate(100, 200, 300) + gripper = self.model.gripper + for gr in (-16.0, 0.0, 37.5, 90.0, 180.0): + self.model.pose(centre, gr, 8.0) + with self.subTest(gr=gr): + turn = Rotation(z=-gr) + joint = gripper.location + gripper.proximal_joint.rotated(turn) # type: ignore[operator] + for got, want in zip(joint.vector(), centre.vector()): + self.assertAlmostEqual(got, want, places=6) + tcp = gripper.location + self.model.pads().rotated(turn) # type: ignore[operator] + along = Coordinate( + self.finger["PadsCenterToRotationCenter"] * MM_PER_CM, + -self.finger["FingerCenterOffset"] * MM_PER_CM, + -self.model.depth * MM_PER_CM, + ).rotated(turn) + for got, want in zip(tcp.vector(), (centre + along).vector()): + self.assertAlmostEqual(got, want, places=6) + + def test_the_fingers_span_the_outline_from_the_centre(self) -> None: + self.model.pose(Coordinate.zero(), 90.0, 8.0) + gripper = self.model.gripper + xs = [p["X"] for p in self.finger["Base"]] + for finger in gripper.fingers: + assert finger.location is not None + start = (finger.location.x - gripper.proximal_joint.x) / MM_PER_CM + self.assertAlmostEqual(start, min(xs), places=6) + self.assertAlmostEqual(start + finger.get_size_x() / MM_PER_CM, max(xs), places=6) + self.assertAlmostEqual( + (finger.location.z - gripper.proximal_joint.z) / MM_PER_CM, -self.model.depth, places=6 + ) + + def test_the_pads_stand_gg_apart(self) -> None: + gripper = self.model.gripper + for gg in (6.5, 8.0, 12.0): + self.model.pose(Coordinate.zero(), 0.0, gg) + faces = [] + for finger, pad in zip(gripper.fingers, gripper.pads): + assert finger.location is not None and pad.location is not None + low = finger.location.y + pad.location.y + faces.append((low, low + pad.get_size_y())) + gap = faces[0][0] - faces[1][1] # the first pad's face is its low side + self.assertAlmostEqual(gap / MM_PER_CM, gg, places=6) + + +class HeldStackTests(unittest.TestCase): + def test_a_layer_wider_than_the_one_below_widens_the_footprint(self) -> None: + pod = generic_configuration().pod("left") + model, geometry = g.GripperModel.from_bif(pod.gripper_model), pod.geometry + base = g.HeldLabware(length=12.776, width=8.548) + # A layer hanging 1 cm past the plate's far end along the fingers. + stacked = g.HeldLabware(12.776, 8.548, layers=(g.StackedLayer(1.0, 0.0, 12.776, 8.548),)) + pose = g.GripperPose(0.0, 7.889) + plain = g.gripper_x_range(geometry, model, 0.0, g.GripperPose(pose.gr, pose.gg, base)) + wider = g.gripper_x_range(geometry, model, 0.0, g.GripperPose(pose.gr, pose.gg, stacked)) + self.assertAlmostEqual(wider[1] - plain[1], 1.0) + self.assertAlmostEqual(wider[0], plain[0]) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_tests.py new file mode 100644 index 00000000000..a37f92c3d75 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/device_tests.py @@ -0,0 +1,152 @@ +import asyncio +import glob +import json +import os +import struct +import unittest +from unittest import mock +from typing import Dict + +from pylabrobot.beckman_coulter.biomek_i7.device import DECK_Z, RAIL_TOP_Z, BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import RECORDING_ENV +from pylabrobot.beckman_coulter.biomek_i7.resource_model import alps +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + as_instrument, + configuration_file, + generic_biomek, + generic_configuration, + generic_driver, + generic_simulated_boards, +) +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.resource import Resource + +MODELS = os.path.join(os.path.dirname(__file__), "resource_model") + + +def glb_bounds(path: str): + """A .glb's extent in mm, from its POSITION accessors (files are written in metres).""" + with open(path, "rb") as f: + data = f.read() + length = struct.unpack_from(" Coordinate: + """Where `resource` is in the deck's frame, measured through the device that holds both.""" + deck = self.biomek.deck.location + assert deck is not None + return resource.get_location_wrt(self.biomek) - deck + + def test_every_mesh_fits_the_resource_it_draws(self): + resources: Dict[str, Resource] = { + r.model: r for r in [self.biomek, *self.biomek.get_all_children()] if r.model is not None + } + for name in dir(alps): + if name.startswith("biomek_"): + alp = getattr(alps, name)("x") + assert alp.model is not None + resources[alp.model] = alp + files = glob.glob(os.path.join(MODELS, "beckman_coulter_*.glb")) + self.assertGreater(len(files), 0) + for path in files: + model = os.path.basename(path)[: -len(".glb")] + with self.subTest(model=model): + drawn = resources[model] + lo, hi = glb_bounds(path) + size = (drawn.get_size_x(), drawn.get_size_y(), drawn.get_size_z()) + for axis in range(3): + self.assertGreaterEqual(lo[axis], -1.0) + self.assertLessEqual(hi[axis], size[axis] + 1.0) + + def test_the_deck_is_inside_the_frame(self): + deck = self.biomek.deck + for alp in deck.alps.values(): + if alp.alp_type == "ELx405DW": + continue # the washer stands behind the frame, as it does on the instrument + loc = alp.get_location_wrt(self.biomek) + with self.subTest(alp=alp.name): + self.assertGreaterEqual(loc.x, 0) + self.assertLessEqual(loc.x + alp.get_size_x(), self.biomek.get_size_x()) + self.assertGreaterEqual(loc.y, 0) + self.assertLessEqual(loc.y + alp.get_size_y(), self.biomek.get_size_y()) + self.assertAlmostEqual(loc.z, DECK_Z) + + def test_moving_a_bridge_carries_its_pod(self): + before = self.biomek.pod_models["left"].get_location_wrt(self.biomek) + self.biomek.update_bridge_location("left", 600.0) + after = self.biomek.pod_models["left"].get_location_wrt(self.biomek) + self.assertAlmostEqual(after.y, before.y) + self.assertAlmostEqual(self.deck_frame(self.biomek.bridges["left"]).x, 600.0) + + def test_moving_a_pod_along_its_bridge(self): + carriage = self.biomek.pod_models["left"].get_location_wrt(self.biomek).z + self.biomek.update_pod_location("left", 250.0, z=150.0) + self.assertAlmostEqual(self.deck_frame(self.biomek.pod_models["left"]).y, 250.0) + self.assertAlmostEqual(self.deck_frame(self.biomek.get_resource("left_pod_head")).z, 150.0) + # The head moves in Z; the carriage keeps its height under the rail. + self.assertAlmostEqual(self.biomek.pod_models["left"].get_location_wrt(self.biomek).z, carriage) + self.assertLess(carriage, RAIL_TOP_Z) + with self.assertRaises(ValueError): # a Span-8's probes are placed one by one + self.biomek.update_pod_location("right", 250.0, z=150.0) + + def test_moving_a_span8_probe(self): + self.biomek.update_probe_location("right", 3, 300.0, 120.0) + channel = self.biomek.get_resource("right_pod_channel_3") + end = self.deck_frame(channel) + channel.reference_point # type: ignore[attr-defined] + self.assertAlmostEqual(end.y, 300.0) + self.assertAlmostEqual(end.z, 120.0) + + +class DeviceSessionTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + # Debug mode makes a simulated Home All ~100x slower; see driver/homing_tests.py. + asyncio.get_running_loop().set_debug(False) + + async def test_without_simulation_it_drives_the_instrument_and_opens_nothing_yet(self): + instrument = configuration_file(as_instrument(generic_configuration())) + device = BiomekI7(declared_configuration_json=instrument) + self.assertEqual(device.driver.boards, []) # not set up: no board is opened + with self.assertRaisesRegex(ValueError, "no declared configuration"): + BiomekI7() # never the generic one + + async def test_simulation_without_files_is_the_generic_instrument(self): + with mock.patch.dict(os.environ, {RECORDING_ENV: ""}): + device = BiomekI7(simulation=True) + self.assertTrue(device.driver.declared.generic) + self.assertIn("TL1", device.deck.position_names) # its default deck, from the layout + self.assertEqual(set(device.bridges), {"left", "right"}) # drawn before setup + await device.setup() + self.addAsyncCleanup(device.stop) + self.assertEqual([a.module_type for a in device.arms], ["multichannel", "span8"]) + + async def test_simulation_drives_a_simulated_instrument(self): + device = generic_biomek() + await device.setup() + self.addAsyncCleanup(device.stop) + assert device.driver is not None and device.driver.right_x_arm is not None + self.assertEqual(await device.driver.right_x_arm.request_homed_state("X"), "homed") + + async def test_setup_and_home_all_go_to_the_driver(self): + driver = generic_driver(generic_simulated_boards()) + device = BiomekI7(driver=driver) + await device.setup() + self.addAsyncCleanup(device.stop) + assert driver.left_x_arm + self.assertEqual(await driver.left_x_arm.request_homed_state("GR"), "homed") + await device.home_all() + self.assertEqual(await driver.left_x_arm.request_homed_state("GR"), "homed") + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index fed087c574c..afa9f70a4ea 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -176,8 +176,12 @@ class Obstacle: POD_SETTINGS: Tuple[str, ...] = () GRIPPER_SETTINGS: Tuple[str, ...] = ("GripperSqueezeForce",) TYPE_SETTINGS: Dict[str, Tuple[str, ...]] = { - "span8": ("ProbeSize",), + "span8": ( + "ProbeSize", + "DefaultTipHubInfo", + ), "multichannel": ( + "Head/PodToMandrel1", "HeadBodyXSpan", "HeadBodyYSpan", ), diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index 73c8e9961c5..925d9e8c7c7 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -4,6 +4,7 @@ import math from dataclasses import dataclass, field from typing import ( + TYPE_CHECKING, Callable, Dict, Iterable, @@ -41,6 +42,9 @@ ) from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail +if TYPE_CHECKING: + from pylabrobot.resources.resource import Resource + logger = logging.getLogger(__name__) # How Biomek numbers its pods. Pod1 is the left pod and Pod2 the right on the instrument this @@ -125,6 +129,9 @@ def __init__( # The shared X rail, set by the driver once both pods are found. Every move that changes what # the pod takes up along it (X, the gripper's GR or GG) goes through it. self.rail: Optional[XRail] = None + # The pod's model in the resource tree, its bridge (STAR's `x_arm.resource`): set by the device + # that draws it (`BiomekI7`), which keeps it in step with the pod's axes; None without one. + self.resource: Optional["Resource"] = None # What the gripper holds, as the rail counts it; the pod cannot sense it. self._held_labware: Optional[g.HeldLabware] = None # Where this driver last put each axis, as the Master Controller keeps it (`cpositions`): @@ -474,7 +481,7 @@ def _require_declared(self) -> PodConfiguration: def add_position_listener(self, listener: Callable[["Pod"], None]) -> Callable[[], None]: """Call `listener(pod)` whenever the position record changes: after a move, a read, homing, or a position becoming unknown. Returns what removes it. For what follows the pod, such as its - model in a resource tree; a listener that raises is logged and kept.""" + model in a resource tree (`BiomekI7`); a listener that raises is logged and kept.""" self._listeners.append(listener) return lambda: self._listeners.remove(listener) @@ -752,7 +759,8 @@ async def _move_over( always. z_final: where to set the channels' bottoms once there; None leaves them at the traverse height. - clearance: the lowest height the deck under the path allows, from a deck model, if known. + clearance: the lowest height the deck under the path allows, from the deck model + (`BiomekI7._traverse_clearance`), if known. allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately. tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, cm; none when None. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index 57a539f3510..53148ea368f 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -17,6 +17,7 @@ import asyncio import logging from typing import ( + TYPE_CHECKING, Awaitable, Callable, Dict, @@ -48,6 +49,9 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import XRail from pylabrobot.io.usb import USB +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck + logger = logging.getLogger(__name__) # A pod's drive supply ("+36V Interlock") reads about 35-36 V with the interlock armed and 0.1-0.16 @@ -153,6 +157,9 @@ def __init__( # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, The pods). self.left_x_arm: Optional[Pod] = None self.right_x_arm: Optional[Pod] = None + # The deck the operations work on (STAR's `driver.deck`), set by `BiomekI7`; None without one. + # Moves, homing and the rail guard never need it. + self.deck: Optional["BiomekI7Deck"] = None # -- lifecycle ------------------------------------------------------------- diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py index 9f0011ca412..204974c3f22 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -41,7 +41,8 @@ # Names the recording the simulator answers from (identity and sensor reads, recorded at an # instrument's cold start) when no path is given. A generic one ships in `defaults/` -# (`biomek_i7_generic_coldstart.json`). +# (`biomek_i7_generic_coldstart.json`), which `BiomekI7(simulation=True)` uses when neither is +# given. RECORDING_ENV = "BIOMEK_I7_SIMULATOR_RECORDING" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py new file mode 100644 index 00000000000..74976d7ef54 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py @@ -0,0 +1,148 @@ +"""Travel over the deck at a traverse height (design.md B9): `Pod._move_over`, the obstacles Biomek +keeps per pod, and the deck model's clearance.""" + +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_configuration, + generic_deck, +) + + +class ObstacleTests(unittest.TestCase): + def setUp(self) -> None: + self.obstacles = generic_configuration().pod("left").obstacles + + def test_the_pump_bank_is_cleared_from_above(self) -> None: + # The pump bank: X from 121.044, Y to 13.447 cm, up to Z 37.069, buffer 0.2. + self.assertAlmostEqual(g.obstacle_clearance(self.obstacles, (125, 130), (5, 12)).height, 37.269) + # Elsewhere only the floor (Z to 0, buffer 0.2). + self.assertAlmostEqual(g.obstacle_clearance(self.obstacles, (50, 60), (30, 40)).height, 0.2) + + def test_walls_and_ceilings_are_not_cleared(self) -> None: + self.assertEqual( + g.obstacle_clearance(self.obstacles, (157, 160), (30, 40)).walls, ("RightShield",) + ) + # The I-beam (from Z 37.069 behind Y 11.092) bounds the pod's body: under it is refused. + self.assertEqual(g.obstacle_clearance(self.obstacles, (50, 60), (5, 10)).walls, ("IBeam",)) + # Just clear of it, with its 0.2 cm buffer. + self.assertEqual(g.obstacle_clearance(self.obstacles, (50, 60), (11.3, 20)).walls, ()) + + +class MoveOverTests(PodMoveTest): + async def test_lifts_then_travels_at_the_park_height(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + await pod.move_axes({"Z": -20000, "GZ": -3000}) + self.mark(driver) + await pod._move_over({"X": 100000}) + d = pod.declared + assert d is not None + # Z to its rest height, 39.763 cm (-256 counts), and GZ to its own, then X alone. + self.assertEqual(d.to_counts("Z", pod._traverse_heights()["Z"]), -256) + self.assertEqual(pod.cpositions["Z"][1], -256) + self.assertEqual(pod.cpositions["GZ"][1], d.to_counts("GZ", d.limits["GZ"][1] - 0.1)) + self.assertEqual(pod.cpositions["X"][1], 100000) + moves = [n for n, _ in self.sent(driver, "multichannel") if n == "Move All"] + self.assertEqual(len(moves), 2) + + async def test_an_axis_above_the_traverse_height_is_not_lowered(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + await pod.move_axes({"Z": 0, "GZ": 0}) # the top of travel + await pod._move_over({"X": 100000}) + self.assertEqual((pod.cpositions["Z"][1], pod.cpositions["GZ"][1]), (0, 0)) + + async def test_an_override_is_checked_and_z_final_set(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + d = pod.declared + assert d is not None + self.mark(driver) + with self.assertRaisesRegex(ValueError, "below"): + await pod._move_over({"X": 100000}, minimum_traverse_height=25.0, clearance=30.0) + self.assertNotIn("Move All", [n for n, _ in self.sent(driver, "multichannel")]) + await pod._move_over( + {"X": 100000}, + minimum_traverse_height=25.0, + clearance=30.0, + allow_below_clearance=True, + z_final=20.0, + ) + self.assertEqual(pod.cpositions["Z"][1], d.to_counts("Z", 20.0)) + with self.assertRaisesRegex(ValueError, "z_final"): + await pod._move_over({"Z": 0}) + + async def test_the_default_is_biomeks_safe_height_when_set(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + d = pod.declared + assert d is not None + self.assertIsNone(pod.default_minimum_traverse_height) # this instrument: -100000, unset + pod.default_minimum_traverse_height = 350.0 # mm + await pod.move_axes({"Z": -20000}) + await pod._move_over({"X": 100000}) + self.assertEqual(pod.cpositions["Z"][1], d.to_counts("Z", 35.0)) + pod.default_minimum_traverse_height = 990.0 # mm, above the top: kept to the top of travel + self.assertEqual(pod._traverse_heights()["Z"], d.limits["Z"][1] - 0.1) + + +class DeckClearanceTests(PodMoveTest): + async def test_the_tallest_labware_under_the_path(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + site = lh.deck.get_position("P6") + plate = cor_96_wellplate_360uL_Fb("plate") + site.assign_child_resource(plate) + left = self.pod(driver, "left") + assert left.declared is not None + loc = site.get_location_wrt(lh.deck) + # Biomek X/Y of the position's middle, cm. + x = (loc.x + site.get_size_x() / 2 - 100.0) / 10 # deck x = Biomek X + FRAME_X (10 cm) + y = (700.0 - (loc.y + site.get_size_y() / 2)) / 10 # deck y = FRAME_Y (70 cm) - Biomek Y + top = (loc.z + plate.get_size_z()) / 10 + safe = left.declared.geometry.additional_safe_height + self.assertAlmostEqual( + lh._traverse_clearance("left", (x - 1, x + 1), (y - 1, y + 1)), top + safe, places=4 + ) + self.assertAlmostEqual( + lh._traverse_clearance("left", (x - 1, x + 1), (y - 1, y + 1), tip_length=9.0), + top + safe + 9.0, + places=4, + ) + + +class PublicTravelInMillimetresTests(PodMoveTest): + """The public travel and traverse API is mm (and deck frame); its Biomek-unit twins are `_`.""" + + async def test_move_over_in_mm_sends_what_its_native_twin_sends(self) -> None: + from pylabrobot.beckman_coulter.biomek_i7 import units + + native, public = await self.homed(), await self.homed() + for driver in (native, public): + await self.pod(driver, "right").move_aside() + pn, pp = self.pod(native, "left"), self.pod(public, "left") + d = pn.declared + assert d is not None + x_counts, y_counts = 100000, 50000 + self.mark(native) + await pn._move_over({"X": x_counts, "Y": y_counts}, 500, minimum_traverse_height=30.0) + x = units.counts_to_axis(pp, "X", x_counts) + y = units.counts_to_axis(pp, "Y", y_counts) + self.mark(public) + await pp.move_over({"X": x, "Y": y}, speed_fraction=0.5, minimum_traverse_height=300.0) + self.assertEqual(self.sent(public, "multichannel"), self.sent(native, "multichannel")) + self.assertEqual(pp.cpositions["X"][1], x_counts) + + async def test_traverse_figures_are_mm(self) -> None: + pod = self.pod(await self.homed(), "left") + for axis, cm_value in pod._traverse_heights().items(): + self.assertAlmostEqual(pod.traverse_heights()[axis], cm_value * 10) + for axis, cm_value in pod._traverse_ceilings().items(): + self.assertAlmostEqual(pod.traverse_ceilings()[axis], cm_value * 10) + with self.assertRaises(ValueError): + await pod.move_over({"X": 500.0}, speed_fraction=1.5) diff --git a/pylabrobot/beckman_coulter/biomek_i7/layouts.py b/pylabrobot/beckman_coulter/biomek_i7/layouts.py new file mode 100644 index 00000000000..362a77d30f9 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/layouts.py @@ -0,0 +1,48 @@ +"""Putting a method's labware on a Biomek i7 deck: `place_labware` places a Biomek Instrument +Setup's labware classes on the deck positions it names. The deck itself (which ALPs stand where) +is each instrument's: build it with `BiomekI7Deck.assign_alp`, by Biomek's own `column` (an ALP's +left pins) and `row` (its front pins), as the instrument file's `Decks//Groups/` gives +them.""" + +from typing import Iterable, List, Mapping, Optional + +from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_labware + + +def place_labware(deck: BiomekI7Deck, setup: Iterable[Mapping[str, Optional[str]]]) -> List[str]: + """Put Biomek labware on `deck` as a method's Instrument Setup step places it: each item a + `position` (Biomek's name, `P6`, `TL1`), the labware `class` (`Thermo96VB_PP`, `BC1025F`) and the + `name` the method gives it (the position's name when it gives none; `_` when + two share one), and optionally a `lid` class to seat on it (or "default"). Each class is its PyLabRobot + definition (`resource_model/labware.py` names them); a position's labware is centred in it, as + Biomek does. + + Returns: + What was left out and why: a class not built yet (a tube rack, a lid), or a position the deck + does not have. + + Raises: + ValueError: for an item without a position or a class. + """ + skipped = [] + names: set = set() + for item in setup: + position, cls = item.get("position"), item.get("class") + if not position or not cls: + raise ValueError(f"a setup item needs a position and a class: {dict(item)}") + # Resource names are unique in a tree; a method may give two positions the same one. + name = item.get("name") or position + if name in names: + name = f"{name}_{position}" + names.add(name) + if position not in deck.position_names: + skipped.append(f"{position}: no such position on {deck.name}") + continue + try: + labware = biomek_labware(cls, name, lid=item.get("lid")) + except NotImplementedError as e: + skipped.append(f"{position}: {e}") + continue + deck.get_position(position).assign_child_resource(labware) + return skipped diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/__init__.py new file mode 100644 index 00000000000..894a7c1147b --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/__init__.py @@ -0,0 +1,56 @@ +from pylabrobot.beckman_coulter.biomek_i7.resource_model.alps import ( + BiomekALP, + Site, + biomek_bioshake, + biomek_cold_plate, + biomek_elx405dw, + biomek_orbital_shaker, + biomek_static_1x1, + biomek_static_1x3, + biomek_static_1x5, + biomek_static_peltier_96, + biomek_tilting_alp, + biomek_tip_load_1x1, + biomek_trash_left_bin, + biomek_trash_right_bin, + biomek_wash_station_span8, +) +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import ( + biomek_labware, + biomek_labware_classes, + biomek_tip, +) +from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import ( + bridge, + pod_96, + pod_model, + pod_span8, +) +from pylabrobot.beckman_coulter.biomek_i7.resource_model.units import MM_PER_CM, cm + +__all__ = [ + "BiomekALP", + "biomek_labware", + "biomek_labware_classes", + "biomek_tip", + "bridge", + "MM_PER_CM", + "Site", + "biomek_bioshake", + "biomek_cold_plate", + "biomek_elx405dw", + "biomek_orbital_shaker", + "biomek_static_1x1", + "biomek_static_1x3", + "biomek_static_1x5", + "biomek_static_peltier_96", + "biomek_tilting_alp", + "biomek_tip_load_1x1", + "biomek_trash_left_bin", + "biomek_trash_right_bin", + "biomek_wash_station_span8", + "cm", + "pod_96", + "pod_model", + "pod_span8", +] diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py new file mode 100644 index 00000000000..a18dfb41638 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py @@ -0,0 +1,471 @@ +"""Biomek ALPs (Automated Labware Positioners): the accessories pinned onto the Biomek deck. + +An ALP is a carrier: a body standing on the deck's pin grid, with one site per labware position. +Every number here is transcribed from the ALP's own definition file, as Biomek states it in +centimetres, and converted once through `cm`. The definitions are Beckman's +`C:\\ProgramData\\Beckman Coulter\\AlpDefinitions\\**\\.alp` (JSON, `AlpDefinitionV1`). + +Biomek's deck Y runs from the back towards the front, PyLabRobot's from the front towards the back, +so an ALP definition's Y offsets, measured from the ALP's back edge, are flipped here. Where +Biomek's fields go: + +- `XSpan`, `YSpan`, `ZSpan`: the ALP's size. +- `Pins.ColCount`, `Pins.RowCount`: how many deck pins it covers; `Pins.OffsetX`, `Pins.OffsetY`: + its back left pin, from its back left corner. The deck places an ALP by its pins. +- `Positions[key].OffsetX`, `.OffsetY`: a site's back left corner, from the ALP's; `.OffsetZ`: how + far below the ALP's top the site's floor is; `.XSpan`, `.YSpan`: the site's footprint; + `.BaseName`: the prefix Biomek numbers this kind of position under on a deck (`P`, `TL`, `TR`). +- `Positions[key].AdaptorPlate.Z`: where labware sits from the position's floor (the tip-loading + ALP's adaptor plate takes it 0.254 cm lower). Biomek's per-class `LabwareOffsets` are not kept: + on that position every tip box's equals the adaptor plate's. +- `Positions[key].CustomData`'s `TipDisposalOffset*`: where the pods discard tips at a trash. +""" + +from typing import Any, Dict, List, NamedTuple, Optional, Sequence, Tuple + +from pylabrobot.resources.carrier import Carrier +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.resource_holder import ResourceHolder + +from .units import cm + + +class Site(NamedTuple): + """One labware position on an ALP, in Biomek's centimetres and Biomek's frame. + + Attributes: + key: Biomek's name for it on the ALP (`A1`, `A2`, ...). + base_name: what Biomek numbers it under on a deck (`P`, `TL`, `TR`, `W`, ...). + offset_x: its left edge, from the ALP's left edge. + offset_y: its back edge, from the ALP's back edge. + offset_z: its floor, from the ALP's top. + size_x: its width. + size_y: its depth. + adaptor_z: where labware sits from its floor (`AdaptorPlate.Z`). + tip_disposal: where the pods discard tips, for a trash. + head96_tip_loading: whether the 96-head may load tips here (the position's characteristic + "Multichannel Can Load Tips": only the tip-loading ALP's, built to take the press). + """ + + key: str + base_name: str + offset_x: float + offset_y: float + offset_z: float + size_x: float + size_y: float + adaptor_z: float = 0.0 + tip_disposal: Optional["TipDisposal"] = None + head96_tip_loading: bool = False + + +class TipDisposal(NamedTuple): + """Where the pods discard tips at a trash position, in Biomek's centimetres from the position's + back left corner (Y forward), from the ALP's `CustomData`. Biomek's tip unload puts the + 96-head's mandrel A1 at (`x`, `y`) with the tips' ends `z` above the + position, the tips' length being the effective one (`TipHeight` - `TipSeatingDepth`). + + Attributes: + x: `TipDisposalOffsetX`, the 96-head's mandrel A1. + y: `TipDisposalOffsetY`. + z: `TipDisposalOffsetZ`, the tips' ends above the position. + span8_x: `Span8TipDisposalOffsetX`. + span8_y: `Span8TipDisposalOffsetY`. + """ + + x: float + y: float + z: float + span8_x: float + span8_y: float + + +class BiomekPosition(ResourceHolder): + """A deck position on an ALP. Biomek centres the labware in it: a position is a little larger + than the labware (12.819 x 8.59 cm against a tip box's 12.79 x 8.54), and Biomek's targets are the + position's corner + half the difference + the labware's A1 offset. A labware set down here sits the + same way, `labware_z` above the position's floor (the TL positions' adaptor plate: 2.54 mm lower). + + Attributes: + labware_z: where labware sits from the position's floor, mm (`Site.adaptor_z`). + tip_disposal: for a trash, where the pods discard tips. + head96_tip_loading: whether the 96-head may load tips here (`Site.head96_tip_loading`). + """ + + def __init__( + self, + name: str, + size_x: float, + size_y: float, + size_z: float, + labware_z: float = 0.0, + tip_disposal: Optional[Sequence[float]] = None, + head96_tip_loading: bool = False, + **kwargs: Any, + ): + super().__init__(name=name, size_x=size_x, size_y=size_y, size_z=size_z, **kwargs) + self.head96_tip_loading = head96_tip_loading + self.labware_z = labware_z + self.tip_disposal = None if tip_disposal is None else TipDisposal(*tip_disposal) + + def get_default_child_location(self, resource) -> Coordinate: # type: ignore[no-untyped-def] + centred = Coordinate( + (self.get_size_x() - resource.get_size_x()) / 2, + (self.get_size_y() - resource.get_size_y()) / 2, + self.labware_z, + ) + return super().get_default_child_location(resource) + centred + + def serialize(self) -> dict: + return { + **super().serialize(), + "labware_z": self.labware_z, + "tip_disposal": None if self.tip_disposal is None else list(self.tip_disposal), + "head96_tip_loading": self.head96_tip_loading, + } + + +def alp_model(alp_type: str) -> str: + """The model name of an ALP type: Biomek's name, namespaced, so its mesh file is unambiguous.""" + return "beckman_coulter_biomek_alp_" + alp_type.replace("-", "_") + + +class BiomekALP(Carrier[ResourceHolder]): + """An ALP: a carrier that stands on the Biomek deck's pin grid. + + `site_keys` lists Biomek's key for each site in index order and `base_names` what Biomek numbers + each under on a deck. + """ + + def __init__( + self, + name: str, + size_x: float, + size_y: float, + size_z: float, + pin_count: Tuple[int, int], + pin_offset: Tuple[float, float], + sites: Optional[Dict[int, ResourceHolder]] = None, + site_keys: Optional[List[str]] = None, + base_names: Optional[Dict[str, str]] = None, + alp_type: Optional[str] = None, + **kwargs: Any, + ): + """ + Args: + name: what to call this one. + size_x: its width, in mm. + size_y: its depth, in mm. + size_z: its height, in mm. + pin_count: how many deck pins it covers, as (columns, rows). + pin_offset: its back left pin, from its back left corner, as (right, forward) in mm. + sites: its labware positions, by index. + site_keys: Biomek's key for each site, in index order. + base_names: what Biomek numbers each site under on a deck, by key. + alp_type: the ALP type, as Biomek names it (`Static1x1`). The model is this, namespaced. + kwargs: what `serialize` writes besides these (category, model), taken so a saved deck loads; + a loaded ALP's sites come back as its children. + """ + super().__init__( + name=name, + size_x=size_x, + size_y=size_y, + size_z=size_z, + sites=sites, + category="alp", + model=None if alp_type is None else alp_model(alp_type), + ) + self.alp_type = alp_type + self.pin_count = pin_count + self.pin_offset = pin_offset + self.site_keys = site_keys or [] + self.base_names = base_names or {} + + def get_site(self, key: str) -> ResourceHolder: + """The site Biomek calls `key` on this ALP (`A1`).""" + return self.sites[self.site_keys.index(key)] + + def serialize(self) -> dict: + return { + **super().serialize(), + "alp_type": self.alp_type, + "pin_count": list(self.pin_count), + "pin_offset": list(self.pin_offset), + "site_keys": self.site_keys, + "base_names": self.base_names, + } + + +def _alp( + name: str, + model: str, + size: Tuple[float, float, float], + pin_count: Tuple[int, int], + pin_offset: Tuple[float, float], + sites: List[Site], + position_names: Optional[Sequence[str]], +) -> BiomekALP: + """An ALP from its definition, every length in Biomek's centimetres. + + Args: + position_names: what each site is called, in site order; `_` when not given. A deck + layout passes the names Biomek gives the positions on the deck (`P1`, `TL1`, ...). + """ + if position_names is None: + position_names = [f"{name}_{site.key}" for site in sites] + if len(position_names) != len(sites): + raise ValueError(f"{model} has {len(sites)} positions, {len(position_names)} names were given") + size_x, size_y, size_z = (cm(v) for v in size) + holders: Dict[int, ResourceHolder] = {} + for i, (site, position_name) in enumerate(zip(sites, position_names)): + holder = BiomekPosition( + name=position_name, + size_x=cm(site.size_x), + size_y=cm(site.size_y), + size_z=0, + labware_z=cm(site.adaptor_z), + tip_disposal=site.tip_disposal, + head96_tip_loading=site.head96_tip_loading, + ) + # Carrier places a site at its own `location`. Biomek measures from the back edge. + holder.location = Coordinate( + cm(site.offset_x), + size_y - cm(site.offset_y) - cm(site.size_y), + size_z + cm(site.offset_z), + ) + holders[i] = holder + return BiomekALP( + name=name, + size_x=size_x, + size_y=size_y, + size_z=size_z, + pin_count=pin_count, + pin_offset=(cm(pin_offset[0]), cm(pin_offset[1])), + sites=holders, + site_keys=[site.key for site in sites], + base_names={site.key: site.base_name for site in sites}, + alp_type=model, + ) + + +# A standard titer-plate site on the static ALPs: 12.819 x 8.59 cm, 0.441 cm in from the left. +# Alps - Common\Static1x*.alp, TipLoad1x1.alp: Positions[*].XSpan, YSpan, OffsetX +_PLATE_SITE = (12.819, 8.59) +_STATIC_SITE_X = 0.441 +# Positions[A1..A5].OffsetY on Static1x5.alp (Static1x1 and Static1x3 share the first ones). +_STATIC_SITE_Y = (0.441, 10.855, 21.269, 31.683, 42.097) + +Names = Optional[Sequence[str]] + + +def _static(name: str, model: str, size_y: float, rows: int, sites: int, names: Names) -> BiomekALP: + return _alp( + name=name, + model=model, + size=(13.701, size_y, 15.875), # XSpan, ZSpan as on every static ALP + pin_count=(7, rows), + pin_offset=(0.602, 0.57), # Pins.OffsetX, OffsetY + sites=[ + Site(f"A{i + 1}", "P", _STATIC_SITE_X, _STATIC_SITE_Y[i], 0.0, *_PLATE_SITE) + for i in range(sites) + ], + position_names=names, + ) + + +def biomek_static_1x1(name: str, position_names: Names = None) -> BiomekALP: + """Static 1x1 ALP: one titer-plate position. Alps - Common\\Static1x1.alp""" + return _static(name, "Static1x1", size_y=9.472, rows=5, sites=1, names=position_names) + + +def biomek_static_1x3(name: str, position_names: Names = None) -> BiomekALP: + """Static 1x3 ALP: three titer-plate positions, A1 at the back. Alps - Common\\Static1x3.alp""" + return _static(name, "Static1x3", size_y=30.3, rows=15, sites=3, names=position_names) + + +def biomek_static_1x5(name: str, position_names: Names = None) -> BiomekALP: + """Static 1x5 ALP: five titer-plate positions, A1 at the back. Alps - Common\\Static1x5.alp""" + return _static(name, "Static1x5", size_y=51.128, rows=25, sites=5, names=position_names) + + +def biomek_tip_load_1x1(name: str, position_names: Names = None) -> BiomekALP: + """Tip-loading ALP for the 96-head: one tip box, on an adaptor plate that takes it 0.254 cm lower + than a static position would (`AdaptorPlate.Z`). Alps - Common\\TipLoad1x1.alp""" + return _alp( + name=name, + model="TipLoad1x1", + size=(13.701, 9.472, 16.129), # XSpan, YSpan, ZSpan + pin_count=(7, 5), + pin_offset=(0.602, 0.57), + sites=[ + Site( + "A1", + "TL", + 0.441, + 0.441, + 0.0, + *_PLATE_SITE, + adaptor_z=-0.254, + head96_tip_loading=True, + ) + ], + position_names=position_names, + ) + + +def _trash( + name: str, + model: str, + pin_offset_x: float, + site_x: float, + tip_disposal: TipDisposal, + names: Names, +) -> BiomekALP: + return _alp( + name=name, + model=model, + size=(32.446, 14.418, 27.508), # XSpan, YSpan, ZSpan + pin_count=(7, 7), + pin_offset=(pin_offset_x, 0.961), + # The chute's opening sits 6.896 cm below the top. + sites=[Site("A1", "TR", site_x, 2.9351, -6.896, *_PLATE_SITE, tip_disposal=tip_disposal)], + position_names=names, + ) + + +def biomek_trash_left_bin(name: str, position_names: Names = None) -> BiomekALP: + """Trash ALP hanging off the deck's left edge, into a bin. Alps - Common\\TrashLeftBin.alp""" + return _trash( + name, + "TrashLeftBin", + pin_offset_x=18.997, + site_x=18.527, + tip_disposal=TipDisposal(0.0, 1.124, 5.896, span8_x=-4.2186, span8_y=0.0), # CustomData + names=position_names, + ) + + +def biomek_trash_right_bin(name: str, position_names: Names = None) -> BiomekALP: + """Trash ALP hanging off the deck's right edge, into a bin. Alps - Common\\TrashRightBin.alp""" + return _trash( + name, + "TrashRightBin", + pin_offset_x=0.953, + site_x=1.1, + tip_disposal=TipDisposal(5.9995, 1.124, 5.896, span8_x=4.561, span8_y=0.0), # CustomData + names=position_names, + ) + + +def biomek_wash_station_span8(name: str, position_names: Names = None) -> BiomekALP: + """Span-8 wash station: a narrow trough the 8 probes dip into. Alps - Common\\WashStationSpan8.alp""" + return _alp( + name=name, + model="WashStationSpan8", + size=(5.715, 9.9568, 22.1361), + pin_count=(2, 5), + pin_offset=(2.9464, 0.8128), + sites=[Site("A1", "W", 0.4953, 0.4788, 0.0, 3.175, 8.9992)], + position_names=position_names, + ) + + +def biomek_orbital_shaker(name: str, position_names: Names = None) -> BiomekALP: + """Orbital shaker ALP. Alps - Common\\OrbitalShaker.alp""" + return _alp( + name=name, + model="OrbitalShaker", + size=(14.802, 10.16, 16.134), + pin_count=(7, 5), + pin_offset=(1.118, 0.914), + sites=[Site("A1", "Orbital", 0.815, 0.851, 0.0, *_PLATE_SITE)], + position_names=position_names, + ) + + +def biomek_bioshake(name: str, position_names: Names = None) -> BiomekALP: + """Q.Instruments BioShake ALP. Devices\\Q Instruments\\BioShake.alp""" + return _alp( + name=name, + model="BioShake", + size=(14.21, 10.0, 17.13), + pin_count=(5, 5), + pin_offset=(2.934, 0.834), + sites=[Site("A1", "BS", 0.696, 0.705, 0.0, *_PLATE_SITE)], + position_names=position_names, + ) + + +def biomek_cold_plate(name: str, position_names: Names = None) -> BiomekALP: + """Q.Instruments ColdPlate ALP. Devices\\Q Instruments\\ColdPlate.alp""" + return _alp( + name=name, + model="ColdPlate", + size=(14.21, 10.0, 16.057), + pin_count=(5, 5), + pin_offset=(2.934, 0.834), + sites=[Site("A1", "CP", 0.696, 0.705, 0.0, *_PLATE_SITE)], + position_names=position_names, + ) + + +def biomek_static_peltier_96(name: str, position_names: Names = None) -> BiomekALP: + """Static Peltier ALP with a 96-well block. Peltiers\\StaticPeltier_96.alp""" + return _alp( + name=name, + model="StaticPeltier_96", + size=(15.24, 11.113, 16.5275), + pin_count=(7, 5), + pin_offset=(1.384, 1.391), + sites=[Site("A1", "Pelt", 1.173, 1.224, 0.0, 12.894, 8.662)], + position_names=position_names, + ) + + +def biomek_tilting_alp(name: str, position_names: Names = None) -> BiomekALP: + """Tilting ALP (site-defined). Custom\\Tilting-ALP.alp""" + return _alp( + name=name, + model="Tilting-ALP", + size=(15.2, 10.1, 15.87), + pin_count=(7, 5), + pin_offset=(1.35, 1.09), + sites=[Site("A1", "TA", 1.19, 0.755, 0.0, *_PLATE_SITE)], + position_names=position_names, + ) + + +def biomek_elx405dw(name: str, position_names: Names = None) -> BiomekALP: + """BioTek ELx405 deep-well washer, at the back of the deck. Devices\\ELx405DW.alp + + Drawn as its envelope: the definition gives the space it takes and its plate position, nothing + of its shape. + """ + return _alp( + name=name, + model="ELx405DW", + size=(41.1, 42.6, 10.6), + pin_count=(11, 2), + pin_offset=(10.713, 38.375), + sites=[Site("A1", "W", 23.77, 28.76, 0.0, *_PLATE_SITE)], + position_names=position_names, + ) + + +# Each ALP above by the type Biomek names it by (an instrument file's `Decks//Groups/` +# `Type`), for building a deck from a declared layout (`BiomekI7Deck.from_configuration`). +ALP_TYPES = { + "Static1x1": biomek_static_1x1, + "Static1x3": biomek_static_1x3, + "Static1x5": biomek_static_1x5, + "TipLoad1x1": biomek_tip_load_1x1, + "TrashLeftBin": biomek_trash_left_bin, + "TrashRightBin": biomek_trash_right_bin, + "WashStationSpan8": biomek_wash_station_span8, + "OrbitalShaker": biomek_orbital_shaker, + "BioShake": biomek_bioshake, + "ColdPlate": biomek_cold_plate, + "StaticPeltier_96": biomek_static_peltier_96, + "Tilting-ALP": biomek_tilting_alp, + "ELx405DW": biomek_elx405dw, +} diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_BioShake.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_BioShake.glb new file mode 100644 index 0000000000000000000000000000000000000000..e0aef2d6c5f0fa89df9a71e8880a0fceb3a125b6 GIT binary patch literal 5784 zcmd^@&u>&!6vw~*LPbG9Ma5tE@F$Mt{hBv3#ZCnT1WT)JMfp+6o9S&Cn9kIhDcUqm zh%Q|aU1^LlF~)@}#`Asi4qRG`uf~n~k~#PDZol{3bIv{Y zkuX&s-E%#F_csEct^)Rt3=PgZal36gPVc;P+O*oWX2a=q{2tfIIa8)#T5+e@l9^7k zS#NKfs#khu=A4C`)2_-NonAMkw$poL-f1)^49Oi^7|UILllgdBv`)oTPff>-@oICn z-Z8E5O07959}CldOb<0)|jYOsqtm!SOToYbq11?5-sB)$T{jEv_0f) z58gsj4t1H9s#}sRm4Z|ylC)}uAVtvzuyIf^50 zPgn@@fftq{FD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{%xEiq&FQ<2KxmHCQWlE$+ZNtj7ki z8*nG?!rj;?b|db=y|@pX#BRd@Y^ej$l;mC|(i!3J!`rh*!nFir2)xhC^Zx z;jq}lI3o54j*2~sF|lJfCiWP{#g5~+*yD)B#;Ay`penYC39%Ehr@<5^#h#GSpeCci zNf`}J$!JiQ(O_CegNBR-O&JYlWHfkPMuV1&25lJ)Ix-r}%4l#}MuRtGG^Fz6*8RHuiyMC1zPZ{{Cck&|Tp#(HiPdGBZ4LR$kG3Tmo2lo#`cc-k^tqUAjk4}* u`_Xu)QP!B%r{-e&v03v{z3oR?{Zm6uFSraVzV9pe9{yW>vpWCG_u&ui5XW!; literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_ColdPlate.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_ColdPlate.glb new file mode 100644 index 0000000000000000000000000000000000000000..74f632181c4135003b7b0e6ab19f5dab8b1ba07d GIT binary patch literal 5764 zcmd^@&u>&!6vw}cqM{(6Rz*d8;4d8Od-LABnJIQER6ww_*w(7hT4$!WWnel}XQsub zX+qGQ3)G!)p>g4Yl`EH!_#-9;R&I#Kor!;h8_)O6JM^}-_-fp!FPU>cbLM-`J?Gqe zUz1K%hY#Hh;JpsugN?w^p@IGdr`T+omeaN1%$Y{BQm;8(PP)@|QqGjAnMScyZ-}Q= zuUDJTO;t;sGxN@3%4wG6N2kk;sp)i`TySdj2}5$n7ROT8zlpy%En25!%4epFwefO& zw%Rg{@lvHeZO)7rt25)h_3Fg&YO!Tx*=f@}C6O6|7)4xfjG0Ddy3(r5#gmJzR-;my zZSm`Zb9`Xv$ncSY{wV$afx%<@`2?NLKjV8rKJ*h0=l-rq+?_M?xGk!MAq`iQyFvxmd#?55iAfL{sQ(mVVwY9yB z29$V`Z$lTg+>5L|-oD-bMBoRdb!O@Yp`_&ILf;Q_QLd7gn+d&iF37u*R_ICr^krRN zIG+jgVJ4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c)ZtM}e2Yay(`_U)14{zX29Kb=b2k{pA zaR>uq2QY}kcpF1vhcGO57$agwa764892I*M$HX4Pak0noj@Wl_LhK2g6nhe<#Gb;a z*ioDodm3Y6$MCM$cM*$?Q4(81S!@~OV#no7gGo$?JtM0@MOK5evKpL|)u1Y?!IZ29 zHCYYnvKmawYVe+{1`Syanz9{~b literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_OrbitalShaker.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_OrbitalShaker.glb new file mode 100644 index 0000000000000000000000000000000000000000..2638d70bf612ae4173d4b1d873e032cc5802d3b9 GIT binary patch literal 5788 zcmd^@%WoV-5XL_q36DU41QOna3E{bznVs3$T?em8LIMei9c&XG!I;@~+u3-%Yj)QG z%d!-~fg4B&34xH1kdVlMGba)W32{IOBrXWVg)9F65*O<0ox&X(hcV&;jO6Oyl)tX7 zs_q_3o^FgCxER3u+klTZ0*6M2hZeo0(=lDIf6+T-+MRl<>Gga0KHtlE)23+RQu)@yrrDismU+Bem|v-*MEG`Yqlm0$sb=D&;9Wx{$y6PUe(lQW|QVb ztu^21n)XDs-kLQt6G>xkVz^zccaz5GiDbsKW$9VdIU&&*hG?Vyoj7yt`fR;hKa~bZ zy4`lYI^X5%qIYz7^x)XR;UQbb(D2BSJ%_#iK#Hq3C+jt8^0Is)sn(MQv&l)b)`$@1 zJdF^!5ejaEV97Q{L#9pZHD_nFDE*10_PJ{Nh>>PA>a~&9{Pc;Y>DY9uNyqGKHCpWh zNzHD`albDrhJ`SQ%5e~te7{^M-?lF5xR+Rax{W)-$taAf>&(=TVoAv_#bFqiY_5`*UxHG|leV z!kiq;LXeMho}9|2T!SDlo8Gm4@7Vr*ArE6+?u0bkXLkHy>ylTjk9`ly%TGyuANWDc zAr8W5oQ-prm!#LV{L1-~-Rk*r`qK3CkzC0%{n34U4(}O}+j@QmR=jot^3fjwR@U#A zOdwJ#3oOUHL8rQOqVK?P-2ELpi(o?y3L& ze7Ucs^VgR%cmDF>1(ugxSTQ{>cPexCp}o#SyS;MqyE}JNuk32b>Zj(7x3*VWTVAtzWmiL1zv^H8`O5*9U5&D8xYp(k zUs=7ft0AkOF|e zs^NT{%lTyOAzAxF*4i0EYbR^%Wah7XswTfuGUUwK6(eWcKWq;ver)K zAli5qwNkJCoUa?N)y5PJ3?kS(tgGb@s4V z|6j13Gnk5Guy;b|{2%SRV58WLxD1!$3S24nN^HVa zxEhv03NiQR_nxDhwuX0bQp7Tk*4aJ$&saR+wbPIzKH?8IHz zg}cSxjeBq}?!*0J@5ckk;X(9??ZZRx5g;!%j}Q?Gh{eVzqJ%Q~#r9)29>xGFVk;QL zBiMtzV)tSn9>snf5PJZR;c*1P@#>)?6Y`I>~lCS_Bfsw`#i?Qj^hQfFJMCK1YQ*TA`-C)s$#3CiLGH$ z?4+z|FpVj(CuB6J%V=;?MuQm{4H_~U%*trcl+mCiqrsev1~18I(3a7lBcnlAMuT}7 z4Nl2u@Un~sugGYyAfu7>7V!4#8y?>N-Y>f!@b9XSfBop}0QuARH&tAAHRQ7=cUg_g z)YGqVlyxp+u4GrEtn0dQG#_e|HD`^fwYYIy*1A;h#!=Sz)R5B)F2lO-`#Qdd|JK;- J&Oh^g_#Gg0t5E;| literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x1.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x1.glb new file mode 100644 index 0000000000000000000000000000000000000000..b48be21809996126bf903202857bf314e864d32c GIT binary patch literal 5752 zcmd^@+ix3H5XL`l<*MdM~z9;*gfMw4@0np|rFiteun8)Uku@ltxjc zB6t7^DLf(Zgv4I~5+Z^Mgy4}E1mZt{Hy-=IeCr)@l8~}Nya1Lw^Yi38b7p4G*-D+R zj~%)a!1-Ok+gpI6qr*cBPTX#rj?=r~oHMO@`s~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LBRaf}>)O z;yDcB7>2|SVHnTj1&oLt!Km0#jENn?i(+5Iak0nolGvAULhK2g6nhdci+vfV#Gb-w zv8OREb{wyWeFYO@C-AD+R}qViQ4w1~RcsZLVkc!!gK12OJtN+rCf?vR@djtb8`Q-c z%!oH=h&O18H<%S~@Va<|mUx4QD;c!PQIM)sS>#W&yI$8X`? z-DUdrZ=dv$pZn(8vdy-J{Ov_2(b!Bqw=H_(%nfJr*Ind$U literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x3.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x3.glb new file mode 100644 index 0000000000000000000000000000000000000000..b4a5b90ea33288f4f1437d530a22dfea8eceb0e9 GIT binary patch literal 7048 zcmeI0+izUe6~2w?ImN)DbhkUQ#Et;0; zq*=S8J6XHk>^`vAtPL%%c^d_(xyC z(o))*tG8F0nd!{c8to->X)bLp&rM}%)~E-ULk+uRx);?mTmY@d?fO{mG?p4!V>LgV zW?83ETgmWo-FswW>h$#KiE*3$_{8Md(J^m0(4rcx`9>X@qJ~a2#YWmhCIxL$9}i){ zqld`#5W60N4cid9%$wC~%As0G`;utg%eBr~lcmjOqdwVQS-jXXU7Kz#?V1zqX1jAT zt=r2u?+-<#Fb;#Lk_1uN_bYK+@P}gk9F&qI4ogW~3?ghLQ7H&wKQ8%ErC2Ezf+63w zwHJmC)t~0uVNhp#1GVSZcPN~X!l<^*O#LX)l>BlMhDq7xs(JZw5){i(#n-eFUkkuq z$q$t)aZ*X*N?b1YO*Z(-T+17nn6$1J*ll-uJ+7@RESS!@hIz)`b-lf`+-{jxHodm2 z0~rU!q~Pf^wsic1qF#Dt_q}rup0I=1&}TuL?ISz9(Yo}q-3!8!ALw4_hiZekT#9GW zD>tI%xvhv>&uc>0p4WlPGcHE@^yL{(ofsV(ozw^O%Nba4|C&qvOZKA(<>>|4HHb@E zpj*DS&L1jP$}#Rv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 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x5.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_Static1x5.glb new file mode 100644 index 0000000000000000000000000000000000000000..9cf9387d2a65c153ac036670b0b14162414d9505 GIT binary patch literal 8352 zcmeI0-)|gO6~|8kq(2e@4W*Dk+hkG-6ywh9&dl!GWVcReLK4R=w(HhO9Cvm-wzpaD zy1Qd1mSri>7b+^1Cj?Ja{VRBCq*g_!NbtY|5~v8N5Bvi>@W2D-J3C+dWK)|ps1KoC zY0mxZ_4l58&bjwa_GYm$b#}jqym?&Y^#dXoCdbD%oT$@@6K80{S&Q49daLOSIk`dC z8E_WkX55aFR$F_LR;$r@da+R*Tv>NE2b@k#|L6?48FieYD;rL;H6MfA+0EI3t#8^N zEvwe4#9l6r;zcEKFE81DfIlJ>z0CGz#RUW6}p-L`U-AdxfFz@FenAZ;*P<39~om3I?QV^$s|yQpd%7OqNY}d7 zT3%^2<7P6ozM>m4@N(gRqr0)G+uzISq9`)MRa&jy69%w=j98o zr+tB^iD>Hu#X>NPYS}q8(ml=DJ6=P&d%SMBEasfA=P!$S^32HS$b=rvJ0nQNyJfxY zp*L&S_mQElQQCSzK{K=!(CTRc+^|^a7NF#pwm-$Yis64$GIjxaLg`IKx9D!g@QT~x zSqu$#dpYcuNVh|EJ&DH`7Sgw$j>Xr}xVf0<+sE@m4L6C}i+DBWb(iM0!?|m4SN-3Q z*OOVibACP5cTS(*W%|7D_6+y@bZ7J#zF+kJr}1G<59=M}(}Ua_{?<}t%V3HfhJI1s zkjIbz^Qg$_^JDUx{QYJ9XDa<1dhdbq2XFnVgfHZ)Z#ZRY!0d-+_~^m%+8e(dvTQYA ztNF>l4whg3|gwPn6!s{ykgdh8w6lWa9$_Ct>k*Me*{VD_WMhx>tSHDqcq7xx?4YQXG=KjebP zvekgC2EH*Kda~7k*$)llvTQYAtKqqWo@_PXnbFrzRX+T28EiE?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omek_i7/resource_model/beckman_coulter_biomek_alp_StaticPeltier_96.glb new file mode 100644 index 0000000000000000000000000000000000000000..098dcea5bd1f7901d3157f2ed6714a2f1a62c545 GIT binary patch literal 5780 zcmd^@%WoV-5XL`V;cXy5fDj-|cm)<`X6LcHCSH>S5*!jc*d{!JF|+Hovt+$%cE3jmNJt?52d=S%#07EVz#{?)ICDjCqrTZG+_7;OBQC&5uKrE!*VR?k-4iLZ z&545-19*2E@X;3F@c8J+k`s5kCUFLqoYSV$ZM0j?fK%*uoq{uKTBZ{x?T&bocDvc# zGuy27&o4U51*cn=ADsa=qpmY>V##T>rwz%ST%Iia@h1LwPP9(V)KAUDt*Lr@p_!P@ zRISmTGpDBF=KR!n5+{xNG1E*M@r$ib8K{ccw%^TBrRrSbnNK9BhG*)B{o{qjXE_&$sm@58*!5f6{KYwMDPoaMhNT( zp&h|nPTQj)v)1)mw5wKH90_J{KBm7*y0OHo+#0=lB0~N7q#5WtUcSzUH)|72enOR>IRXdK3!g6`TWW7JlwYK`P$315%I%Sla;4EBS1IG^vzU z7_dUC8-W|~2e(o#b1$U@K`B^mOL<*4WUckptnS9zT-KH%$94Vm)n@n-X-zLA+tuB$ zPe*z(YKw^(ota5Li_%BF9x<)iM7~E}5V0|FXO`bgUk+?>HJf#ld+NVGUoL6+{PpF6 zpTE3+f#vdRl={Rs8SwuY>JYF7GoRNGr$PxZ>ShOBXmH`S^dZhJ(NBgO4Ysl)So{#Q@vaKPjpCcbV56ZSiSv6cs&zrKXA*-M9 zSPTDbwl!p1!`Pfpy|S$#tDhRp%Vt|cwl#Y1s8_Z%do!lFJ5Cu{9wt)0xrKJ!}7M(0p#=RDPt zKmF`b_3TYcD|z|bO5c!oZX(s^VbKnWF4gB@$z@1#I?H_WFmPr_q-Utl!&%Jqdyt2- zoVf<_aMqJlpNF&lr}{k1JhD1_*sFg-W-nPM1$mfz#X70a!=hbboz&-H$z_FgQlE#V z))kSSp*|01G4=d#tqXFNGuP1kFUVO>QcWJtdY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xPydSzQfRzEeGm(8|@Y-{x1QLk)k$X9ml zk(qgCKiSskJ*8joAX)EMZ*T8@DeHaFnb*CX0kY02S?7?VN*2@_q>uiwOC(Z_$ z_2^k-?pF=>>t60BYY)lVAF|fY7+O17YbR^%WUZaN-giT5r)IsothH04wUf1Wver)4 z+R1$Enb&&On?tRg`&3K*kdBq&^Qzt=B|)nfg4O#nk!XS=Z$(XP%+?Uzf9F0V*9Zd`>-Ds zu@wy9IUK-2u?KMof5u@P5qkvB;{^=jsMw=;5kokJVX?y)!AtlHM#YX|OzarO#g5~+ z*yA`M_5@xQ`!Ze;`wC8qJ&99dPvNxK(>Npc3?{@*;H=oQm=rsSb7IdS5u2bYwu+kA z8m7cf$(aT-m==3pR)e~%2CvF$a6wjshO7p&vKlmHHE79dFej_QYqA=&Wi{x?YS5L{ zU|v>(i?SMAlGWgKSq&CsHFDkpE_}4V^2U$f?fYTNXoY;~>2LRwzgT*I1=||(TZhL| zjm_Lkzs6D4y^Ohsbf&Mvqt8@}%w_#XaJ LW3xLy&-dZKe*pve literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_TrashRightBin.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_TrashRightBin.glb new file mode 100644 index 0000000000000000000000000000000000000000..7854463e79dcae133687982dd4cda07709f4715e GIT binary patch literal 5772 zcmd^@&2Lm?6viJ>QBgrb@mu7g_%+u1HFstTOa%liLW^xd5No|NecO&qXX?xpXqqM@ zCb|&g!i{bu@#{};DT#?oS1dFd{{q=-j0?|m=N|jgTD&E0)Jb~Y-<&@0dCxibythdw z>m&Qu064!H_;4+7aCmTF-ih07({Xy|ozte(t~DD@ujBW)PR^M$4bzG{&6apN&1Sv* z>}0*tGc)HbmX~pfSq1xnBXHTsmM^BsfltgD3ViNUQ;>@&a)3r|RbQ&P;bXv8_ zY=>Xxog;(8{UiN@14$VJgF}aRA98v<@i`qt;Ka_lapqx5FyAp8X>eJ zVxNY_}>&@2wxSBka zlWtE~2=aj!mLe}Kx^5|-&$&H$`R)~>C?6D}yzhl{MPb47@@~H1h9$q`=e!;_X>Ioy z4Jh#>-#pZa(t-Vpwt|t;m%E=qtE^ za48>^qI@Y|EUuWW_m{aA7dSO>RUTlw+3NPVGCMJ0TE}YUO!BO&&FPtD!!$Z0b2BoS zdC!k>j!b1ku7T&vL+>Ph=h(iz0f$jWQii(6Wp?~w>*BMCFYv=KUt0VW3&IX`FDP26!IJ z_lq(^tk0FsS-tRrl1INM!|2O1)ekrMZWQ>-dLbt*uVwLBEX`zTAu_DXw=cFLkVs29 zA=xfI3wt(_xv0!_%;3aC@;a0*^6MefnC!@_$O|L3C2mdfT^Y!@`it2t+uT)O`+m8i z#VgO3>wV?%!BvhALU+k_U#?N+>;t)ZSDwDQ?WLl$$}YaZD`mAV;0^6Qhx8d(oet%t zAn(cVHvoJ32XJ)LXJz@5m3)5v@w4(zpIj*Mi*o;W=gX=gtDl-X-u}FN`u&f3ZMHRJ zTl3{FpO@dbv~>sd%C?5Aerhgk`J&w1_*SApxZ4Fud)M#Ed+ZwX1(R)X|vaKOs*s@(_=7U{iTch`s ze!YWayQcdb}eqg&A0{Y#ID1wxDB^sz1a2G zfIDy}Hj3SdO}GnpW3$-JxCi&*KHM+%emsB&@em#s`!KfP5p0Dc*1~=hk zC-5Ym68jXMMh?%QM{EzCg$ob9SRVmGxd&KU+ zUObO|*e`ZJ4&Vj!`A;T_En6E9mQ*6U&EN#F}yDJb;M$0RK!+L6qC##Y3=5V|e?tJU_%R7HtH&iB{dHUyFZ&o@>X^e5g^@oHeG_V#l#r>r%ZPM_J=jLryQaEUUint9T#&TVu03|IGX050iTI AO8@`> literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_WashStationSpan8.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_alp_WashStationSpan8.glb new file mode 100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hZJjRRJwv^)SEx7k4)wu4p}yER)DQcG`eXml02~k+hy(csg$9R);E>Qz92y#i!$QMx ZcxVKU2#v&%p;0(0G#W>T#^4yf{{gmuH(3Ax literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_gripper_finger.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_gripper_finger.glb new file mode 100644 index 0000000000000000000000000000000000000000..6d8eedd81ce5601f431caa5de096cf1b048a7b79 GIT binary patch literal 3352 zcmeH~Pj4GV7{(u3NNFJj8rp^eX*z*Yz}Wl8Yp>m;Aq`1!N$irCR7w>^YiI2)wRf%c zx)52Ga^%1#;KGRmUxHpaBJl}Ok$UTAVBWFEo^E5ws>BIK%H-L1fAh@yzB7Apy-{92 z0bq6-`1>Sqd%INZGN;{kBbM*7hi=&R0-xoXk|$;ss6j!M>N> zuZLc%#UnM(ue%}Ny6Lv>b9b^KDO_K~rxkilFY+D^44fzmy-Fvd$1b~5+Afp}rJ^XK zSlZfL*VwZ}0F_J*OeE5%~-PgOdBDE#w@>bPjmttxCA*Moy#QRkwmp z{l4$E#by6H{G5u|%p_a@hSSa@#MNO+mc{^2JQacFyc~?5Mnj7wT?sua4YS3&2 zzUxQj!xld(OE)qJ#?Q&;7sIv_ED~Y1v$kr|>3IB-@ccENocN<`obN?UPiHe$P8q~# z8IuapY|XOwdWkMmx7TT>$+wR$=V$c%a&wryu8q>)UR~K(*<#d*o17C?NEqx@DN?*L8YGP@qYvT;@Gqv4CiW949dX_xJr^{2qU+Oq7bl}+i{Hi7NnLJSm<8|usW#M`L>8<5SwBq%z zTNDGk6WJV;X1qd=_uuO}vG3d_IR6yp8j?z~>9Nh*`XYOMJeBckv$H#~h#Ma2fNs z0>)>C1$=-Hah17k-%q2A_WaP446p6LIzpb$RUsGSi}-;U>Tod1vjyZ hFR+Gn+`^YA;5NR(1~ySd33u={wy=#dzQGRe;va=?-i-hN literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_head_96.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_head_96.glb new file mode 100644 index 0000000000000000000000000000000000000000..f8b8d0955d2df6ddb76825803651b18cb9d0cb45 GIT binary patch literal 8516 zcmeI0&u?7S6~_;85<=Pr8Yq;sh4MlvP-EV&c{AhSG5J9tsbhm}!jIUPH{)w($auz` z89P{3q--ixu<)u<78MZs5A??#tCcELsa;eokU&W6+C^9GKfw9kd0%`9wt2&*5>2Ez z_v7R5z4x4R&mF&)#m4mMJtA`I0g+$r7dbmMF~07losQ{x!|UFvX?N6ET(RqBaQ5{-d^R5hfotpmA8}>8mc*7Ugy=H6Pfc)7jvxA@ir2ceC zwO-ZKE-j_axms(b(KYS4YQ42&F3r`8a~DlIKUYq4&n45jsLNtL&@R{40?Y0CQoUPW z&1REg$A@7al|Gt*}##%PW>9l5#;etQphov}7{HR>;<2dw-4EWnvWe&G8-F)2hr zQcQ}2!H{q3+S`hY`a_yZoBM8g3s;bSc6LY0X&R;TeFht8SaB5kjDHBw-;e zlnaG&sibLWq;XIzmGswsDJ}((s&)!A**4HfBh|dpnx0^%)$SF!y0Wlf+UM)$vOVlt zYiYUFG|lex+OqayAqaIXZN#Q_eh})Zcdg$$|J2C{ZCKZ9fNG?4dD=WCQ-p08(@r4hz@8?!W~P97gSKB*V=ixF6H z9}#R*2%Fh%xd(nB+$Q;WyWn>@gBwHFYt?V^dPH00ce}!NM0KreCKeX#cb^sxKaQE^ zVpqR@f;iD|yJ>q7UyM;)PQtBlzBIX~{`&L7a#;G}{&5K>>1-eEvV9c$H%#v@{J2!q z#`^lM+YQXeEk6QiX{p(gwb~Rx7 zp+}u(Hr};*va12p4?Su_J=xWO>4zS*XFOzA1EwE(oGtSuyBaY4(4%))PqM24(+@rR zj%Pu3HDLOwXFtFXb~R*buowG{>}tUDGhg;IMtocin11N7Hs-tRYQV0>#;b8dPj)q6 z`k~>ybJ^8^uZ{h3WM;z~0aFj=Jq7a)f_cBdygOu^1vNNFF#8$IUInuc!H5}s2xk9) zQ7iNh7{`{AxEAQR4zKQkn@JHoCqru11R-cDeJE}UX&%+wa zsK)Ug;>p7zS4UNP75Y4!t!e*O<>4%5>>+tLtBKX;;jHFXpNA1gmS+!p`R~Z6CGvzI z596$mC-iw(wVTKj`aG<$Y$8wS^RVW+snV;^=izKk_7C>jm9v1bqGMPlH ze-7-eeDd!7WtV^d#)l)+fL+aPf81MH-MH62bCO*Rn0~DJy9f7GUi;v>)stNfnEu}L z(!NUT@PK`0#`6!@)qv@z{;#WV+2=R-!LEi(4feYIz&ln?b~Rx7u|9GcnYnKDWLE>G zA9~d4&C%X-CfU`1>4zS5=5s08)qv@T9`&G}>}tUDLyy`s9^HKj0n?8)kqbU9yBe^o!P=M)J=xWO z>4(O~g@hb-HDFi6dj~z))qwd<0d_UKr||O*f_cAsbGPo4dtcb|oQoa+vsc0FLoi}S zAA*rDdJN3o0HaRm4KUA?jQP}HKA3d|vxZ>S2h7~v`hb}`n7M4d%|d?0@DC zKXV5&cQA7YGj}j^2QzoF%_q}fKIdXSn7Mmcm{<&53Ba(`_xvg zMxDA@&T5{UF~6VZwo3DRrZd+I5%;A*l{O+_C8`Yc{qFDx%ocTd(YiOZL>47 ljGy&<`(!)Eo`Icy^L?sUhQ90AZ{7cw`kU`l-{kkH&j44)MX3M) literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_span8_channel.glb b/pylabrobot/beckman_coulter/biomek_i7/resource_model/beckman_coulter_biomek_i7_span8_channel.glb new file mode 100644 index 0000000000000000000000000000000000000000..259c11ea308c5bbd831b40f611bdb9f0b40340e5 GIT binary patch literal 4416 zcmd^?&2Lmy7{(u|qE1Z3l#f!%o$2XxU^;i4nHHL+ z35kCI3zx3c=-R)4CPWh#?ld9Muww6m#J%rx=f3m+DPCFXP3C=n^Y%ICywADkG;OIe zF}Ml9(QUwQZNSO#(UBF$Ycx#L$*(v|rrs#~RVVKxx?CsbluXssy{2E6O4Ii%jYFkM zp{us+tj3&1QGV#;-H;kierm<3`m=`QPOnbK9(fr>IcFgTlRm{XwR(A>+$=AJ3xyJJmnzdY-`9`=bY_#I(z)>ZHH~PHRMM% z-+%Sv13lT+D658Rwf%56&@0;-vewn(pZD(vdio;U8nV`@=U(0W5=U&dHDp`EeHOog zUfI@=wI0kVd!u^p6WP`TV=WE$Ui(qDHDs-Ge!g4vt88n?TBn|8NB2|N){wPMJs*7+ z%C?5Ab!I;F*`gNP8fDdREj@3_wuY>A&Pgx)*lcUawuWkj$Rt6P!Kz zi@2snL@AKjn1KZ=Q!1pZ~t_n_tuV;wW$1iZfjrskBLAZg+<#Z zxxmrp%r&(CCvvza zfhG!vdmiYcF#8C7wy@>@A2=A(7m6eWcS6VfAL_yWwhRa7MZN!r>(7AyUvEMip2c(6 zEO9fQ#|wB7?GoGZ5?;m@Y?Zhbui#Z|!*+?=@fvpEb?lV56K~*6?80t|yRipv;ce`d zxEK4-f&FkKI_ShZcozpG9>9BeA0ObL#Dn+{F?@tBiCs7Z7jYycCXhr5-AGGJBZDk* z$V<%Qu>1krgIyizYB^z098Gi#FtE21y literal 0 HcmV?d00001 diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py new file mode 100644 index 00000000000..70749a787c3 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py @@ -0,0 +1,188 @@ +"""The Biomek i7's pipetting heads in the resource tree, as the STAR's are: the Multichannel head an +`NChannelPipette` of 96 `TipMountingShaft`s (category `head96`), each Span-8 probe a channel +(category `pipette_channel`) carrying one shaft. + +Sized in centimetres from the instrument file's pod entry (`HeadBodyXSpan`, `HeadHeight`, +`HeadFlangeHeight`, `Head/PodToMandrel1`, `PodToHeadBody*Offset`, `Mandrel1*Offset`, the mandrels' +spacing; `ProbeSize`, `MandrelExtender`, `DefaultTipHubInfo`), else the pod type's values. Biomek's +Z names the bare mandrels' end (design.md I9). The head hangs from the pod by its flange: the body +reaches `HeadHeight` below the pod, and the mandrels end `Head/PodToMandrel1` Z below it, so they +stand `TipSeatingDepth` (the difference) out of the body, and a seated tip's top meets the body. A +Span-8 probe reaches `MandrelExtender` below its channel. A value marked `assumed` has no source +yet. +""" + +from typing import Any, Mapping, Optional + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodGeometry +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.n_channel_pipettes import ( + SHAFT_DIAMETER, + NChannelPipette, + TipMountingShaft, +) +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.utils import create_ordered_items_2d + +from .units import cm + +# The Multichannel head. PodTypes/MC: HeadBodyXSpan, HeadBodyYSpan, HeadHeight, HeadFlangeHeight, +# Head/PodToMandrel1 (Z: the mandrels' end below the pod), PodToHeadBodyXOffset, +# PodToHeadBodyYOffset; the pod entry's Mandrel1X/YOffset and spacing. +HEAD_BODY_X_SPAN = 13.0175 +HEAD_BODY_Y_SPAN = 7.9375 +HEAD_HEIGHT = 9.8171 +HEAD_FLANGE_HEIGHT = 1.0795 +POD_TO_MANDREL1_Z = -10.5245 +POD_TO_HEAD_BODY_X_OFFSET = 2.795 +POD_TO_HEAD_BODY_Y_OFFSET = 1.74625 +MANDREL1_X_OFFSET = 4.3537 +MANDREL1_Y_OFFSET = 2.565 +MANDREL_SPACING = 0.9 +ROWS, COLUMNS = 8, 12 + +# A Span-8 probe. ProbeSize (the probes' narrowest spacing), MandrelExtender (the probe below its +# channel), DefaultTipHubInfo MaxRadius (the tip hub at the probe's end); PodXSpan and +# Mandrel1XOffset (the channel's extent in X about its probe, as the pod's). +PROBE_SIZE = 0.9 +PROBE_LENGTH = 5.7899 +PROBE_HUB_MAX_RADIUS = 0.3429 +SPAN8_POD_X_SPAN = 4.0 +SPAN8_MANDREL1_X_OFFSET = 1.0 +PROBES = 8 +# assumed: how tall a probe's channel is drawn above its probe. Not a Biomek value. +SPAN8_CHANNEL_HEIGHT = 3.0 +# assumed: the gap left between two channels' bodies at the narrowest spacing, so each reads as +# its own. Not a Biomek value. +SPAN8_CHANNEL_GAP = 0.1 + +MODEL_HEAD_96 = "beckman_coulter_biomek_i7_head_96" +MODEL_SPAN8_CHANNEL = "beckman_coulter_biomek_i7_span8_channel" + + +def head96( + name: str, + settings: Optional[Mapping[str, Any]] = None, + geometry: Optional[PodGeometry] = None, + pod_y_span: Optional[float] = None, +) -> NChannelPipette: + """The Multichannel head: its flange and body, with a shaft at each mandrel standing out of the + body's bottom (`mandrel_protrusion`), A1 at the back left (`reference_point`, at the shafts' end: + the head's bottom). Its origin is the body's front left corner at the mandrels' end; it hangs + `PodToHeadBody*Offset` in from the carriage's front left corner (`head96_location`). + + Args: + name: what to call it; its shafts are `_tipmountingshaft_A1` .. `_H12`. + settings: the pod's settings (the instrument file's pod entry); the pod type's values for those + missing. + geometry: the pod's geometry, for the mandrels' offsets and spacing. + pod_y_span: the carriage's depth (cm), from which mandrel A1 is `Mandrel1YOffset` forward. + """ + s = dict(settings or {}) + body_x = float(s.get("HeadBodyXSpan", HEAD_BODY_X_SPAN)) + body_y = float(s.get("HeadBodyYSpan", HEAD_BODY_Y_SPAN)) + height = head96_height(s) + protrusion = mandrel_protrusion(s) + to_x = float(s.get("PodToHeadBodyXOffset", POD_TO_HEAD_BODY_X_OFFSET)) + to_y = float(s.get("PodToHeadBodyYOffset", POD_TO_HEAD_BODY_Y_OFFSET)) + m1x = geometry.mandrel1_x_offset if geometry is not None else MANDREL1_X_OFFSET + m1y = geometry.mandrel1_y_offset if geometry is not None else MANDREL1_Y_OFFSET + pitch_x = geometry.mandrel_x_spacing if geometry is not None else MANDREL_SPACING + pitch_y = geometry.mandrel_y_spacing if geometry is not None else MANDREL_SPACING + depth = pod_y_span if pod_y_span is not None else (geometry.pod_y_span if geometry else 11.43) + # Mandrel A1 in the body's frame: X from the carriage's left edge, Y back from its front edge + # (the deck's y grows to the back, Biomek's to the front). + a1_x, a1_y = cm(m1x - to_x), cm(depth - m1y - to_y) + half = SHAFT_DIAMETER / 2 + return NChannelPipette( + name=name, + size_x=cm(body_x), + size_y=cm(body_y), + size_z=cm(height), + reference_point=Coordinate(a1_x, a1_y, 0.0), + ordered_items=create_ordered_items_2d( + TipMountingShaft, + name_prefix=name, + num_items_x=COLUMNS, + num_items_y=ROWS, + # A shaft is placed by its corner; its axis is the mandrel's. Row A is the back one. + dx=a1_x - half, + dy=a1_y - (ROWS - 1) * cm(pitch_y) - half, + # The mandrels' ends are the head's bottom: the shafts stand from there to the body. + dz=0.0, + item_dx=cm(pitch_x), + item_dy=cm(pitch_y), + tip_pickup_mode="friction", + size_z=cm(protrusion), + ), + category="head96", + model=MODEL_HEAD_96, + ) + + +def head96_height(settings: Optional[Mapping[str, Any]] = None) -> float: + """How far the head reaches below its pod, flange to the mandrels' end (cm): + `Head/PodToMandrel1` Z.""" + s = dict(settings or {}) + to_mandrel1 = s.get("Head/PodToMandrel1") or {} + return -float(to_mandrel1.get("Z", POD_TO_MANDREL1_Z)) + + +def mandrel_protrusion(settings: Optional[Mapping[str, Any]] = None) -> float: + """How far the mandrels stand out of the head's body (cm): the head's reach below its pod less + the body's (`HeadHeight`). Equal to the head's `TipSeatingDepth`: a seated tip meets the body.""" + s = dict(settings or {}) + return head96_height(s) - float(s.get("HeadHeight", HEAD_HEIGHT)) + + +def head96_location(settings: Optional[Mapping[str, Any]] = None) -> Coordinate: + """Where the head's body sits in its carriage, x and y (mm); z is where the head is.""" + s = dict(settings or {}) + return Coordinate( + cm(float(s.get("PodToHeadBodyXOffset", POD_TO_HEAD_BODY_X_OFFSET))), + cm(float(s.get("PodToHeadBodyYOffset", POD_TO_HEAD_BODY_Y_OFFSET))), + 0.0, + ) + + +def span8_channel( + name: str, + settings: Optional[Mapping[str, Any]] = None, + mandrel1_x_offset: float = SPAN8_MANDREL1_X_OFFSET, + pod_x_span: float = SPAN8_POD_X_SPAN, +) -> Resource: + """A Span-8 probe's channel, with its probe a shaft hanging below it, the channel measured from + the probe's end (`reference_point`), as the STAR's channels are (`add_tip_mounting_shaft`). + + The channel spans the pod in X (`pod_x_span`, cm), its probe `mandrel1_x_offset` (cm) in from its + left edge, and is `ProbeSize` deep less `SPAN8_CHANNEL_GAP`, so eight at their narrowest spacing + stand side by side as eight. The probe is `MandrelExtender` long and as wide as the tip hub at + its end (`DefaultTipHubInfo` MaxRadius).""" + s = dict(settings or {}) + depth = cm(float(s.get("ProbeSize", PROBE_SIZE)) - SPAN8_CHANNEL_GAP) + width = cm(pod_x_span) + axis_x = cm(mandrel1_x_offset) + length = cm(float(s.get("MandrelExtender", PROBE_LENGTH))) + hub = s.get("DefaultTipHubInfo") or {} + diameter = cm(2 * float(hub.get("MaxRadius", PROBE_HUB_MAX_RADIUS))) + channel = Resource( + name=name, + size_x=width, + size_y=depth, + size_z=cm(SPAN8_CHANNEL_HEIGHT), + category="pipette_channel", + model=MODEL_SPAN8_CHANNEL, + ) + shaft = TipMountingShaft( + name=f"{name}_tip_mounting_shaft", + tip_pickup_mode="friction", + size_x=diameter, + size_y=diameter, + size_z=length, + ) + channel.assign_child_resource( + shaft, location=Coordinate(axis_x - diameter / 2, (depth - diameter) / 2, -length) + ) + # Stated on a plain `Resource`, as the STAR states it on its channels. + channel.reference_point = Coordinate(axis_x, depth / 2, -length) # type: ignore[attr-defined] + return channel diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/labware.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/labware.py new file mode 100644 index 00000000000..698911a60cc --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/labware.py @@ -0,0 +1,133 @@ +"""Biomek's labware by its class name, and Biomek's touch-off distance. + +The definitions are PyLabRobot's (`pylabrobot.resources.beckman_coulter`), one per Biomek labware +or tip class. This module names them as a Biomek method does (`LABWARE`, `TIPS`), so a method's +Instrument Setup can be put on the deck (`layouts.place_labware`), and gives the distance Biomek +touches off at for a `BiomekWell` and a `BiomekTip` (`biomek_touch_distance`). +""" + +import math +from typing import Any, Callable, Dict, List, Optional + +from pylabrobot.resources.beckman_coulter import ( + BiomekTip, + BiomekWell, + beckman_coulter_biomek_24_wellplate_square_rb, + beckman_coulter_biomek_96_deepwell_square, + beckman_coulter_biomek_96_tiprack_50uL_filter, + beckman_coulter_biomek_96_tiprack_190uL_filter, + beckman_coulter_biomek_96_tiprack_230uL, + beckman_coulter_biomek_96_tiprack_1025uL_filter, + beckman_coulter_biomek_96_tiprack_1070uL, + beckman_coulter_biomek_96_wellplate_flat, + beckman_coulter_biomek_96_wellplate_vb, + beckman_coulter_biomek_modular_reservoir, + beckman_coulter_biomek_reservoir, + beckman_coulter_biomek_reservoir_350cb, + beckman_coulter_biomek_tip_50uL_filter, + beckman_coulter_biomek_tip_190uL_filter, + beckman_coulter_biomek_tip_230uL, + beckman_coulter_biomek_tip_1025uL_filter, + beckman_coulter_biomek_tip_1070uL, +) +from pylabrobot.resources.plate import Plate +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.tip import Tip +from pylabrobot.resources.tip_rack import TipRack + +TIPS: Dict[str, Callable[[str], BiomekTip]] = { + "T50F": beckman_coulter_biomek_tip_50uL_filter, + "T190F": beckman_coulter_biomek_tip_190uL_filter, + "T230": beckman_coulter_biomek_tip_230uL, + "T1025F": beckman_coulter_biomek_tip_1025uL_filter, + "T1070": beckman_coulter_biomek_tip_1070uL, +} +TIP_BOXES: Dict[str, Callable[..., TipRack]] = { + "BC50F": beckman_coulter_biomek_96_tiprack_50uL_filter, + "BC190F": beckman_coulter_biomek_96_tiprack_190uL_filter, + "BC230": beckman_coulter_biomek_96_tiprack_230uL, + "BC1025F": beckman_coulter_biomek_96_tiprack_1025uL_filter, + "BC1070": beckman_coulter_biomek_96_tiprack_1070uL, +} +PLATES: Dict[str, Callable[..., Plate]] = { + "Thermo96VB_PP": beckman_coulter_biomek_96_wellplate_vb, + "BCFlat96": beckman_coulter_biomek_96_wellplate_flat, + "BCDeep96Square": beckman_coulter_biomek_96_deepwell_square, + "Thomson_24w_Square_RB": beckman_coulter_biomek_24_wellplate_square_rb, + "ThermoNUNC_350CB": beckman_coulter_biomek_reservoir_350cb, + "Reservoir": beckman_coulter_biomek_reservoir, + "ModularReservoir": beckman_coulter_biomek_modular_reservoir, +} +# The lid class a plate's definition seats on it (`with_lid`). +LIDS = { + "Thermo96VB_PP": "TiterplateLid", + "BCFlat96": "TiterplateLid", + "Thomson_24w_Square_RB": "Thomson_24w_Square_RB_Lid", + "ThermoNUNC_350CB": "TiterplateLid", +} +LABWARE: Dict[str, Callable[..., Resource]] = {**TIP_BOXES, **PLATES} + + +def _named(table: Dict[str, Callable], class_name: str, kind: str) -> str: + """The table's key for `class_name`: Biomek's classes name each other in any case.""" + if class_name in table: + return class_name + match = {k.lower(): k for k in table}.get(class_name.lower()) + if match is None: + raise NotImplementedError(f"no PyLabRobot definition of Biomek {kind} class {class_name!r}") + return match + + +def biomek_labware_classes() -> List[str]: + """Every Biomek labware class with a definition here.""" + return sorted(LABWARE) + + +def biomek_labware( + class_name: str, name: str, with_tips: bool = True, lid: Optional[str] = None +) -> Any: + """The definition of Biomek labware class `class_name` (`BC230`, `Thermo96VB_PP`, ...): a + `TipRack` or a `Plate`. + + Args: + with_tips: for a tip box, whether it holds its tips. + lid: the lid class to seat on it (`LIDS`), or "default" for the one its definition has. + + Raises: + NotImplementedError: for a class with no definition yet (tube racks, ...). + ValueError: for a lid its definition does not have. + """ + key = _named(LABWARE, class_name, "labware") + if key in TIP_BOXES: + return TIP_BOXES[key](name, with_tips=with_tips) + if lid is None: + return PLATES[key](name) + own = LIDS.get(key) + if own is None or lid.lower() not in ("default", own.lower()): + raise ValueError( + f"{key} has no seat for a {lid} lid here" + (f"; its lid is {own}" if own else "") + ) + return PLATES[key](name, with_lid=True) + + +def biomek_tip(class_name: str, name: str) -> BiomekTip: + """A tip of Biomek tip class `class_name` (`T1070`, `T190F`, ...).""" + return TIPS[_named(TIPS, class_name, "tip")](name) + + +def biomek_touch_distance( + container: Resource, tip: Tip, above_bottom: float, theta: float = 90.0 +) -> Optional[float]: + """Biomek's touch-off distance, mm, for a `BiomekWell` with a shape and a `BiomekTip`, the tip's + end `above_bottom` mm over the well's bottom: the wall's distance at that height in direction + (360 - theta) degrees, less the tip's radius where it crosses the rim; 0 when that leaves no + room. None for anything else. Pass it as `TipTouch.distance`.""" + if ( + not isinstance(container, BiomekWell) + or not container.segments + or not isinstance(tip, BiomekTip) + ): + return None + wall = container.wall_distance(above_bottom, math.radians(360.0 - theta)) + radius = tip.radius_at(container.get_size_z() - above_bottom) + return max(wall - radius, 0.0) diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/labware_tests.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/labware_tests.py new file mode 100644 index 00000000000..8a4d4350cb1 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/labware_tests.py @@ -0,0 +1,109 @@ +"""Biomek's labware by class name, Biomek's touch-off distance, and where labware sits on a deck +position.""" + +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import ( + LABWARE, + TIPS, + biomek_labware, + biomek_labware_classes, + biomek_tip, + biomek_touch_distance, +) +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck +from pylabrobot.resources import ( + Plate, + Tip, + beckman_coulter_biomek_96_tiprack_230uL, + beckman_coulter_biomek_96_wellplate_vb, + beckman_coulter_biomek_tip_1070uL, + cor_96_wellplate_360uL_Fb, +) + + +class LabwareByClassTests(unittest.TestCase): + def test_every_class_names_its_definition(self) -> None: + for cls in biomek_labware_classes(): + with self.subTest(cls=cls): + resource = biomek_labware(cls, "x") + self.assertEqual(resource.model, LABWARE[cls].__name__) + for cls, make in TIPS.items(): + self.assertEqual(biomek_tip(cls, "t"), make("t")) + + def test_a_class_is_named_in_any_case(self) -> None: + box = biomek_labware("bc230", "box") + self.assertEqual(box.model, beckman_coulter_biomek_96_tiprack_230uL.__name__) + self.assertFalse(biomek_labware("BC230", "empty", with_tips=False).get_item("A1").has_tip()) + + def test_a_class_with_no_definition_says_so(self) -> None: + with self.assertRaises(NotImplementedError): + biomek_labware("SmallTubeRack_Microfuge", "rack") + with self.assertRaises(NotImplementedError): + biomek_tip("T190F_LLS", "t") + + def test_a_plate_takes_the_lid_its_definition_has(self) -> None: + for lid in ("TiterplateLid", "titerplatelid", "default"): + plate = biomek_labware("Thermo96VB_PP", "plate", lid=lid) + assert isinstance(plate, Plate) + self.assertIsNotNone(plate.lid) + with self.assertRaises(ValueError): + biomek_labware("Thermo96VB_PP", "plate", lid="Greiner384Lid") + with self.assertRaises(ValueError): + biomek_labware("BCDeep96Square", "plate", lid="default") + + +class TouchOffTests(unittest.TestCase): + def test_any_biomek_tip_in_a_biomek_well(self) -> None: + well = beckman_coulter_biomek_96_wellplate_vb("p").get_well("A1") + distance = biomek_touch_distance(well, beckman_coulter_biomek_tip_1070uL("t"), 7.0) + assert distance is not None + self.assertGreater(distance, 0.0) + plain = Tip( + "t", diameter=4.8, size_z=100, has_filter=False, maximal_volume=1000, fitting_depth=7 + ) + self.assertIsNone(biomek_touch_distance(well, plain, 7.0)) + native = cor_96_wellplate_360uL_Fb("n").get_well("A1") + self.assertIsNone(biomek_touch_distance(native, beckman_coulter_biomek_tip_1070uL("t"), 7.0)) + + +class PositionTests(unittest.TestCase): + def test_a_tip_load_position_takes_labware_lower(self) -> None: + from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware + + deck = generic_deck() + place_labware( + deck, + [ + {"position": "TL1", "class": "BC230", "name": "on_tl"}, + {"position": "TL2", "class": "BCFlat96", "name": "flat_on_tl"}, + {"position": "P1", "class": "BC230", "name": "on_static"}, + ], + ) + # TipLoad1x1.alp: its adaptor plate takes labware 0.254 cm lower; none on a P position. + for name, below in (("on_tl", 2.54), ("flat_on_tl", 2.54), ("on_static", 0.0)): + labware = deck.get_resource(name) + position, location = labware.parent, labware.location + assert position is not None and location is not None + with self.subTest(name=name): + self.assertAlmostEqual(location.z, -below) + self.assertAlmostEqual(location.x, (position.get_size_x() - labware.get_size_x()) / 2) + + def test_trash_positions_carry_their_tip_disposal_offsets(self) -> None: + from pylabrobot.beckman_coulter.biomek_i7.resource_model.alps import ( + BiomekPosition, + TipDisposal, + ) + + deck = generic_deck() + tr1 = deck.get_position("TR1") + assert isinstance(tr1, BiomekPosition) + self.assertEqual(tr1.tip_disposal, TipDisposal(0.0, 1.124, 5.896, -4.2186, 0.0)) + self.assertIsNone(deck.get_position("P1").tip_disposal) # type: ignore[attr-defined] + serialized = tr1.serialize() + self.assertEqual(serialized["tip_disposal"], [0.0, 1.124, 5.896, -4.2186, 0.0]) + self.assertEqual(serialized["labware_z"], 0.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py new file mode 100644 index 00000000000..252c70394d5 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py @@ -0,0 +1,402 @@ +"""Biomek i7 pods and their bridges. + +Each pod hangs from a bridge that spans the deck from front to back and rides the X rails; the pod +travels along its bridge in Y, and its head in Z. On this unit pod 1 carries the 96-channel +Multichannel head and pod 2 the Span-8, each with a gripper. + +Sized in centimetres. The spans the collision model uses (BridgeXSpan, +BridgeToHeadXOffset, PodXSpan, PodYSpan) are the instrument's own when its declared configuration +is given (`pod_model`), so the model's X extents are the ones the rail guard computes +(`driver/pod_geometry.py`); otherwise the pod type's defaults under +`HardwareSetupInfo/PodTypes/`. A value marked `assumed` has no source yet. + +Along X, as Biomek's collision model places them: the bridge's left edge is BridgeToHeadXOffset left of the +pipettor's (`bridge_x_range`, `pipettor_x_range` without the avoidance margin), and the pipettor +is the carriage, PodXSpan wide. + +A pod is its carriage: its frame is the carriage's front left bottom corner, and it follows the +pod's Y along its bridge. A Multichannel's head (`heads.head96`) hangs below it and follows Z in +it (`place_head96`). The parts with axes of their own are the bridge's: a Span-8's probes +(`heads.span8_channel`, each following its own Y and Z) and the gripper (`gripper_model`, a +`MechanicalGripper` posed from GY, GZ, GR and GG). +""" + +from dataclasses import dataclass +from typing import Any, Dict, List, Mapping, Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodGeometry +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.end_effector import MechanicalGripper +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.rotation import Rotation + +from . import heads +from .units import MM_PER_CM, cm + +# Both pod types. Biomek_i7.bif HardwareSetupInfo/PodTypes/: BridgeXSpan, +# BridgeToHeadXOffset +BRIDGE_X_SPAN = 12.7 +BRIDGE_TO_HEAD_X_OFFSET = 2.0 + +# Pod 1, the 96-channel Multichannel pod. PodTypes/MC: PodXSpan, PodYSpan. Its head is +# `heads.head96`. +POD_96_X_SPAN = 18.606 +POD_96_Y_SPAN = 11.43 + +# Pod 2, the Span-8 pod. PodTypes/Span8: PodXSpan, PodYSpan. Its probes are `heads.span8_channel`. +POD_SPAN8_X_SPAN = 4.0 +POD_SPAN8_Y_SPAN = 10.0 + +# assumed: the bridge's section and the carriage's height. Not yet sourced. The gripper is the +# instrument file's model (`gripper_model`). +BRIDGE_HEIGHT = 10.0 +POD_BODY_HEIGHT = 25.0 +# How long the viewer's mark at mandrel A1 is, front to back, mm. Not a Biomek value. +A1_MARK_LENGTH = 9.0 + +_COLORS: Dict[str, str] = { + "x_arm": "#6b7a85", + "pod": "#c9ced3", + "head_body": "#3d4f63", + "head_flange": "#8a96a3", +} + + +# Model names, namespaced: the viewer draws a resource from `.glb` under the package. +MODEL_GRIPPER_FINGER = "beckman_coulter_biomek_i7_gripper_finger" + + +def _part( + name: str, + size_x: float, + size_y: float, + size_z: float, + category: str, + model: Optional[str] = None, +) -> Resource: + """A box of a pod, every length in Biomek's centimetres.""" + part = Resource( + name=name, + size_x=cm(size_x), + size_y=cm(size_y), + size_z=cm(size_z), + category=category, + model=model, + ) + if category in _COLORS: + # A field the viewer reads off the resource; `Resource` does not declare it. + part.appearance = {"color": _COLORS[category]} # type: ignore[attr-defined] + return part + + +Outline = List[Tuple[float, float]] + + +def finger_outline(model: Dict[str, Any]) -> Outline: + """A finger seen from the side, from the instrument file's `Finger/Base` (cm): x along the + fingers from the rotation centre, y up from the hand's bottom. A bar under the hand + (`TopPart`), a strut angled down and out, and the pad block at the tip (`BottomPart` spans the + strut and the block). Biomek's collision boxes take the same spans: the bar ends at + `TopPart/FingerwiseSpan` - `Lowerhand/FingerwiseSpan` / 2 + `FingerwiseOffset`.""" + return [(float(p["X"]), float(p["Y"])) for p in model["Finger"]["Base"]] + + +def pad_block(outline: Outline) -> Tuple[float, float, float, float]: + """The block at the finger's tip that meets the labware, from the outline (cm): + `(x_low, x_high, y_low, y_high)`. Its bottom is the outline's lowest edge, its top the lower of + the two corners next to that edge.""" + bottom = min(y for _, y in outline) + ends = [i for i, (_, y) in enumerate(outline) if y == bottom] + n = len(outline) + beside = [outline[(i + d) % n][1] for i in ends for d in (-1, 1)] + top = min(y for y in beside if y != bottom) + xs = [outline[i][0] for i in ends] + return min(xs), max(xs), bottom, top + + +@dataclass +class GripperModel: + """A pod's gripper in the resource tree, from the instrument file's `GripperModel` (cm), posed by + `pose`: the upper hand, which does not turn, and the gripper (`MechanicalGripper`), which turns + about the rotation centre with the lower hand (its body) and the fingers, its pads its tool centre + point. Both are children of what the gripper is posed in (the pod's bridge).""" + + upper_hand: Resource + gripper: MechanicalGripper + model: Dict[str, Any] + + @property + def fingers(self) -> Tuple[Resource, Resource]: + return self.gripper.fingers[0], self.gripper.fingers[1] + + @property + def depth(self) -> float: + """How far below the hand's bottom the fingertips are, cm.""" + return -min(y for _, y in finger_outline(self.model)) + + def pose(self, centre: Coordinate, gr: float, gg: float) -> None: + """Put the rotation centre at `centre` (mm, the hand's bottom; in the parent's frame), turned + by GR `gr` degrees (Biomek's: counterclockwise with Y to the front, so clockwise here), the + pads `gg` cm apart (held to the jaws' range).""" + m = self.model + up = m["Upperhand"] + gripper = self.gripper + turn = -gr + gripper.rotate_to(z=turn) + gripper.location = centre - gripper.proximal_joint.rotated(Rotation(z=turn)) + low, high = gripper.jaw_range + width = cm(gg + 2 * m["Finger"]["LWFingerSpacing"]) + gripper.jaw_width = min(max(width, low), high) + self.upper_hand.location = centre + Coordinate( + cm(up["CenterXOffset"] - up["XSpan"] / 2), + -cm(up["CenterYOffset"] + up["YSpan"] / 2), + cm(m["Lowerhand"]["ZSpan"]), + ) + + def pads(self) -> Coordinate: + """The pads' centre in the gripper's frame (mm): `PadsCenterToRotationCenter` along the fingers + from the rotation centre, `FingerCenterOffset` across (to the front in Biomek's frame), at the + fingertips: the tool centre point.""" + return self.gripper.proximal_joint + self.gripper.tool_center_point + + +def gripper_model( + name: str, model: Dict[str, Any], gg_range: Tuple[float, float] = (0.0, 20.0) +) -> GripperModel: + """The gripper of the instrument file's `GripperModel` dict: `` (a `MechanicalGripper`, + with `_lower_hand`, `_finger_0` / `_1` and their pads `_pad_0` / `_1`) and + `_upper_hand`. `gg_range` is GG's travel (cm, the declared limits): the gap between the + pads, which the jaws' range follows. + + The gripper's origin is the lower hand's corner; it turns about `proximal_joint`, the rotation + centre at the hand's bottom. A finger is its outline's bounds (`finger_outline`), `Thickness` + across, its plate `LWFingerSpacing` back from the pad face; each pad is the outline's pad block + (`pad_block`), standing that spacing into the gap, so the jaws' width is GG + 2 x the spacing. + """ + up, low, finger = model["Upperhand"], model["Lowerhand"], model["Finger"] + upper = _part(f"{name}_upper_hand", up["XSpan"], up["YSpan"], up["ZSpan"], "body") + body = _part( + f"{name}_lower_hand", + low["FingerwiseSpan"], + low["YSpanNoFingerMountExtension"], + low["ZSpan"], + "body", + ) + outline = finger_outline(model) + x0, x1 = min(x for x, _ in outline), max(x for x, _ in outline) + y0, y1 = min(y for _, y in outline), max(y for _, y in outline) + thickness, spacing = finger["Thickness"], finger["LWFingerSpacing"] + fingers = [ + _part(f"{name}_finger_{i}", x1 - x0, thickness, y1 - y0, "finger", MODEL_GRIPPER_FINGER) + for i in range(2) + ] + px0, px1, py0, py1 = pad_block(outline) + pads = [_part(f"{name}_pad_{i}", px1 - px0, spacing, py1 - py0, "pad") for i in range(2)] + joint = Coordinate(cm(low["FingerwiseSpan"] / 2), cm(low["YSpanNoFingerMountExtension"] / 2), 0) + gripper = MechanicalGripper( + name=name, + proximal_joint=joint, + tool_center_point=Coordinate( + cm(finger["PadsCenterToRotationCenter"]), -cm(finger["FingerCenterOffset"]), cm(y0) + ), + body=body, + body_location=Coordinate.zero(), + fingers=fingers, + # Along the fingers from the rotation centre, the fingertips at the outline's bottom. + finger_location=Coordinate(joint.x + cm(x0), 0, joint.z + cm(y0)), + jaw_range=(cm(gg_range[0] + 2 * spacing), cm(gg_range[1] + 2 * spacing)), + pads=pads, + # Into the gap: the first finger's face is its low side, the second's its high side. + pad_location=Coordinate(cm(px0 - x0), -cm(spacing), cm(py0 - y0)), + ) + gripper.pads[1].location = Coordinate(cm(px0 - x0), cm(thickness), cm(py0 - y0)) + gm = GripperModel(upper, gripper, model) + gm.pose(Coordinate.zero(), 90.0, gg_range[0]) + return gm + + +def pod_96( + name: str = "left_pod", + pod_x_span: float = POD_96_X_SPAN, + pod_y_span: float = POD_96_Y_SPAN, + settings: Optional[Mapping[str, Any]] = None, + geometry: Optional[PodGeometry] = None, +) -> Resource: + """The Multichannel pod: its carriage (cm spans), with the 96-channel head (`heads.head96`, + `_head`) hanging below it. The carriage follows Y along its bridge; the head follows Z in + it (`place_head96`).""" + # The pod body (category `pod`): an ordinary child of its bridge, as the STAR's head is of its + # X-arm, so the viewer carries it along with the bridge. + pod = _part(name, pod_x_span, pod_y_span, POD_BODY_HEIGHT, "pod") + head = heads.head96(f"{name}_head", settings, geometry, pod_y_span) + at = heads.head96_location(settings) + pod.assign_child_resource(head, location=Coordinate(at.x, at.y, -head.get_size_z())) + return pod + + +def place_head96(pod: Resource, z: float) -> None: + """Put a Multichannel pod's head with its bottom (the mandrels' ends) at `z` mm in the pod's + frame (the carriage's bottom is 0).""" + head = pod.get_resource(f"{pod.name}_head") + loc = head.location + assert loc is not None + head.location = Coordinate(loc.x, loc.y, z) + + +def pod_span8( + name: str = "right_pod", + pod_x_span: float = POD_SPAN8_X_SPAN, + pod_y_span: float = POD_SPAN8_Y_SPAN, +) -> Resource: + """The Span-8 pod: its carriage (cm spans). Its probes are channels of their own on the bridge + (`span8_channels`), since each moves in Y and Z by itself.""" + return _part(name, pod_x_span, pod_y_span, POD_BODY_HEIGHT, "pod") + + +def span8_channels(bridge: Resource) -> List[Resource]: + """A Span-8 bridge's probes' channels, probe 1 first.""" + found = [c for c in bridge.children if c.category == "pipette_channel"] + return sorted(found, key=lambda c: int(c.name.rsplit("_", 1)[1])) + + +def bridge( + name: str, + pod: Resource, + length: float, + pod_y: float, + bridge_x_span: float = BRIDGE_X_SPAN, + bridge_to_head_x_offset: float = BRIDGE_TO_HEAD_X_OFFSET, +) -> Resource: + """A bridge `length` mm long front to back, carrying `pod` at `pod_y` mm from its front end. + + Args: + name: what to call the bridge. + pod: the pod it carries, hung below it. + length: how far it spans, in mm: the deck's depth. + pod_y: where the pod's front edge is along the bridge, in mm. + bridge_x_span: the bridge's width, cm (BridgeXSpan). + bridge_to_head_x_offset: how far right of the bridge's left edge the pod's carriage begins, + cm (BridgeToHeadXOffset). + """ + rail = Resource( + name=name, + size_x=cm(bridge_x_span), + size_y=length, + size_z=cm(BRIDGE_HEIGHT), + # The viewer draws an x_arm as an open frame riding the rails, so the deck shows through it. + category="x_arm", + ) + rail.appearance = {"color": _COLORS["x_arm"]} # type: ignore[attr-defined] + rail.assign_child_resource( + pod, location=Coordinate(cm(bridge_to_head_x_offset), pod_y, -pod.get_size_z()) + ) + return rail + + +def pod_model( + side: str, + module_type: str, + length: float, + geometry: Optional[PodGeometry] = None, + settings: Optional[Mapping[str, Any]] = None, +) -> Tuple[Resource, Resource]: + """A pod and the bridge carrying it, named `_pod` and `_bridge`: from the pod's + declared `geometry` when given, else the pod type's defaults. Returns (bridge, pod). + + With the geometry, both declare the `reference_point` the viewer marks: the point the pod's X + names, which is mandrel A1 on a Multichannel and probe 1 on a Span-8 (`targeting.py`). It is + `BridgeToHeadXOffset + Mandrel1XOffset` right of the bridge's left edge, the offset + `pod_geometry.bridge_x_range` takes off the X, so the line and the rail guard cannot disagree + (the rail rule reproduces every logged move to within its 1/16 cm cells). The bridge's line + runs its whole depth. On a Multichannel, whose model also follows Y, the pod marks mandrel A1 + itself, a short line at A1's Y (`Mandrel1YOffset` in front of the carriage's back edge); a + Span-8's probes have a Y each, so its pod marks the X only. + + A Multichannel's head is the pod's (`pod_96`); a Span-8's probes, `_pod_channel_1` .. + `_8` (`heads.span8_channel`, sized from `settings`), are the bridge's, at its reference line. + """ + if module_type not in ("multichannel", "span8"): + raise ValueError(f"no model for a {module_type!r} pod; have ['multichannel', 'span8']") + x_span = geometry.pod_x_span if geometry is not None else None + y_span = geometry.pod_y_span if geometry is not None else None + if module_type == "multichannel": + pod = pod_96( + f"{side}_pod", + x_span or POD_96_X_SPAN, + y_span or POD_96_Y_SPAN, + settings=settings, + geometry=geometry, + ) + else: + pod = pod_span8(f"{side}_pod", x_span or POD_SPAN8_X_SPAN, y_span or POD_SPAN8_Y_SPAN) + if geometry is None: + rail = bridge(f"{side}_bridge", pod, length, 0.0) + if module_type == "span8": + _add_span8_channels(rail, pod, BRIDGE_TO_HEAD_X_OFFSET, 1.0, 1.0, settings) + return rail, pod + rail = bridge( + f"{side}_bridge", + pod, + length, + 0.0, + geometry.bridge_x_span, + geometry.bridge_to_head_x_offset, + ) + a1_x = cm(geometry.mandrel1_x_offset) + rail.reference_point = Coordinate(cm(geometry.bridge_to_head_x_offset) + a1_x, 0, 0) # type: ignore[attr-defined] + if module_type == "multichannel": + a1_y = cm(geometry.pod_y_span - geometry.mandrel1_y_offset) + pod.reference_point = { # type: ignore[attr-defined] + "x": a1_x, + "y": a1_y, + "z": 0.0, + "y_range": [a1_y - A1_MARK_LENGTH / 2, a1_y + A1_MARK_LENGTH / 2], + } + else: + pod.reference_point = Coordinate(a1_x, 0, 0) # type: ignore[attr-defined] + _add_span8_channels( + rail, + pod, + geometry.bridge_to_head_x_offset, + geometry.mandrel1_x_offset, + geometry.mandrel1_y_offset, + settings, + ) + return rail, pod + + +def _add_span8_channels( + rail: Resource, + pod: Resource, + to_head_x: float, + m1x: float, + m1y: float, + settings: Optional[Mapping[str, Any]], +) -> None: + """Hang a Span-8's probes from its bridge, at their narrowest span below the carriage: probe 1 + `Mandrel1YOffset` forward of the carriage's back edge, each next one `ProbeSize` further forward + (deck y down), each channel spanning the pod in X. The device moves them from there + (`place_span8_channel`).""" + pod_loc = pod.location + assert pod_loc is not None + pitch = cm(float(dict(settings or {}).get("ProbeSize", heads.PROBE_SIZE))) + back = pod_loc.y + pod.get_size_y() - cm(m1y) + for i in range(1, heads.PROBES + 1): + channel = heads.span8_channel( + f"{pod.name}_channel_{i}", settings, m1x, pod.get_size_x() / MM_PER_CM + ) + ref = channel.reference_point # type: ignore[attr-defined] + rail.assign_child_resource( + channel, + location=Coordinate( + cm(to_head_x + m1x) - ref.x, + back - (i - 1) * pitch - ref.y, + pod_loc.z - channel.get_size_z(), + ), + ) + + +def place_span8_channel(channel: Resource, x: float, y: float, z: float) -> None: + """Put a Span-8 channel's probe end at `x`, `y`, `z` (mm, in its bridge's frame).""" + ref = channel.reference_point # type: ignore[attr-defined] + channel.location = Coordinate(x - ref.x, y - ref.y, z - ref.z) diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/units.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/units.py new file mode 100644 index 00000000000..d892ed88077 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/units.py @@ -0,0 +1,6 @@ +"""Biomek's centimetres as PyLabRobot's millimetres, for the resource model: re-exported from the +package's `units.py`, where every conversion lives.""" + +from pylabrobot.beckman_coulter.biomek_i7.units import MM_PER_CM, cm + +__all__ = ["MM_PER_CM", "cm"] diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py new file mode 100644 index 00000000000..214a7165ca2 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py @@ -0,0 +1,49 @@ +"""A simulated instrument as `BiomekI7(simulation=True)` builds it: a pod moves aside for the other, +and moves take the instrument's time when asked to.""" + +import asyncio +import time +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_biomek + + +class SimulationTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + # Debug mode makes a simulated Home All ~100x slower; see driver/homing_tests.py. + asyncio.get_running_loop().set_debug(False) + self.biomek = generic_biomek() + await self.biomek.setup() + self.addAsyncCleanup(self.biomek.stop) + + async def test_a_pod_moves_aside(self) -> None: + pod = self.biomek.left_x_arm + assert pod is not None and pod.declared is not None + await pod.move_aside() + low, _ = pod.declared.limits["X"] + self.assertEqual(pod.cpositions["X"][1], pod.declared.to_counts("X", low)) + + +class TimedSimulationTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + + async def test_moves_take_the_instruments_time(self) -> None: + # A long X move takes over a second on the instrument, and a quarter of that simulated by + # default (`motion_time_scale`); untimed, it answers at once. + took = {} + for timed in (False, True): + biomek = generic_biomek(simulate_motion_time=timed) + await biomek.setup(park=False) + self.addAsyncCleanup(biomek.stop) + pod = biomek.left_x_arm + assert pod is not None and pod.declared is not None + started = time.monotonic() + await pod.move_axes({"X": pod.declared.to_counts("X", 60.0)}) + took[timed] = time.monotonic() - started + self.assertLess(took[False], 0.1) + self.assertGreater(took[True], 0.2) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py index 703e6e8b87a..203bb137d17 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -7,14 +7,18 @@ import shutil import tempfile from pathlib import Path -from typing import Any, Dict, List, Optional, Sequence +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence +from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION, GENERIC_RECORDING from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ReplayAceUSB, simulated_boards +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7Device + _GENERIC: Optional[Dict[str, Any]] = None # The serial numbers the generic cold start answers: placeholders as long as real ones. @@ -112,3 +116,19 @@ def generic_driver( boards=generic_boards() if boards is None else boards, **kwargs, ) + + +def generic_deck(name: str = "deck") -> BiomekI7Deck: + """The deck the generic configuration lays out (`BiomekI7Deck.from_configuration`).""" + return BiomekI7Deck.from_configuration(generic_configuration(), name=name) + + +def generic_biomek(**kwargs: Any) -> "BiomekI7Device": + """`BiomekI7(simulation=True, ...)` of the generic configuration and cold start, named + explicitly; `kwargs` as `BiomekI7` takes them.""" + from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 + + kwargs.setdefault("simulation", True) + kwargs.setdefault("declared_configuration_json", str(GENERIC_CONFIGURATION)) + kwargs.setdefault("simulator_recording", str(GENERIC_RECORDING)) + return BiomekI7(**kwargs) diff --git a/pylabrobot/beckman_coulter/biomek_i7/targeting.py b/pylabrobot/beckman_coulter/biomek_i7/targeting.py new file mode 100644 index 00000000000..e3e719896db --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/targeting.py @@ -0,0 +1,78 @@ +"""From a PyLabRobot location on the deck to where a Biomek pod must put its first channel. + +The chain, as STAR and Prep target their channels plus one Biomek correction: + +1. a resource's location on the deck (`get_location_wrt(deck, ...)`, mm), plus the caller's offset; +2. into Biomek's frame (`deck.biomek_x` / `biomek_y`; Z is the deck z), in cm; +3. the pod's calibration of the deck position the resource stands on. Biomek moves each pod + relative to that pod's own calibrated corner of the position (`DeckPosition.corner`, imported + from the instrument file; corner n is pod n's), not to the nominal pin-grid position this + package's deck model places it at. The difference, up to about 0.1 cm, is added. + +What the pod's X/Y/Z name: mandrel A1 on a Multichannel and probe 1 on a Span-8, and the bare +channel's bottom for Z (design.md I9). The axis counts come from `PodConfiguration.to_counts`. +""" + +from typing import Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.resource_holder import ResourceHolder +from pylabrobot.beckman_coulter.biomek_i7.units import MM_PER_CM, BiomekPoint, to_biomek # noqa: F401 (re-exported) + + +def deck_position_of(deck: BiomekI7Deck, resource: Resource) -> Optional[ResourceHolder]: + """The deck position (a named site of an ALP: `P6`, `TL1`) the resource stands on, or is; None + for a resource on no position.""" + names = set(deck.position_names) + node: Optional[Resource] = resource + while node is not None: + if node.name in names and isinstance(node, ResourceHolder): + return node + node = node.parent + return None + + +def position_correction( + deck: BiomekI7Deck, + configuration: DeviceConfiguration, + position: ResourceHolder, + pod_number: int, +) -> Tuple[float, float, float]: + """How far, cm, pod `pod_number`'s calibrated corner of `position` is from where the deck model + puts the position's corner (its back left bottom corner, in Biomek's frame). Zero for a position + the configuration does not hold.""" + calibrated = configuration.deck_positions.get(position.name) + if calibrated is None: + return 0.0, 0.0, 0.0 + loc = position.get_location_wrt(deck) + nominal = to_biomek(Coordinate(loc.x, loc.y + position.get_size_y(), loc.z)) + x, y, z = calibrated.corner(pod_number) + return x - nominal.x, y - nominal.y, z - nominal.z + + +def target( + deck: BiomekI7Deck, + configuration: DeviceConfiguration, + pod_number: int, + resource: Resource, + x: str = "c", + y: str = "c", + z: str = "b", + offset: Coordinate = Coordinate.zero(), +) -> BiomekPoint: + """Where pod `pod_number`'s first channel must be, in Biomek's frame, to be at the anchor (`x`, + `y`, `z`, as `Resource.get_location_wrt` takes them) of `resource`, plus `offset` (mm): the + resource's deck location, corrected by the pod's calibration of the deck position it stands on. + + Raises: + ValueError: for a resource not on `deck`. + """ + point = to_biomek(resource.get_location_wrt(deck, x=x, y=y, z=z) + offset) + position = deck_position_of(deck, resource) + if position is None: + return point + dx, dy, dz = position_correction(deck, configuration, position, pod_number) + return BiomekPoint(point.x + dx, point.y + dy, point.z + dz) diff --git a/pylabrobot/beckman_coulter/biomek_i7/targeting_tests.py b/pylabrobot/beckman_coulter/biomek_i7/targeting_tests.py new file mode 100644 index 00000000000..312a50ff4db --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/targeting_tests.py @@ -0,0 +1,65 @@ +"""Targeting: from labware on the deck to where a pod's first channel goes, against Biomek's logged +moves (2026-10-20). The plate is Biomek's own class (`BCFlat96`).""" + +import unittest + +from pylabrobot.beckman_coulter.biomek_i7 import targeting +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_labware +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_configuration, + generic_deck, +) +from pylabrobot.resources import Plate, beckman_coulter_biomek_96_tiprack_1070uL + + +def bc_flat_96(name: str) -> Plate: + plate = biomek_labware("BCFlat96", name) + assert isinstance(plate, Plate) + return plate + + +class TargetingTests(unittest.TestCase): + def setUp(self) -> None: + self.deck = generic_deck() + self.config = generic_configuration() + + def test_a_position_centres_its_labware(self) -> None: + rack = beckman_coulter_biomek_96_tiprack_1070uL("tips") + site = self.deck.get_position("TL1") + site.assign_child_resource(rack) + assert rack.location is not None + self.assertAlmostEqual(rack.location.x, (site.get_size_x() - rack.get_size_x()) / 2) + self.assertAlmostEqual(rack.location.y, (site.get_size_y() - rack.get_size_y()) / 2) + + def test_tips_and_a_plate_where_biomek_moved(self) -> None: + rack = beckman_coulter_biomek_96_tiprack_1070uL("tips") + self.deck.get_position("TL1").assign_child_resource(rack) + plate = bc_flat_96("plate") + self.deck.get_position("P6").assign_child_resource(plate) + for pod, resource, logged in ( + (1, rack.get_item("A1"), (12.701, 37.45)), # the Multichannel's 96-tip load + (1, plate.get_well("A1"), (56.456, 47.864)), # its dispense into the plate + (2, plate.get_well("A1"), (56.46, 47.864)), # the Span-8's probe 1 over the same well + ): + point = targeting.target(self.deck, self.config, pod, resource) + with self.subTest(pod=pod, resource=resource.name): + # PyLabRobot's labware definitions differ from Biomek's classes by up to 0.1 mm. + self.assertAlmostEqual(point.x, logged[0], delta=0.015) + self.assertAlmostEqual(point.y, logged[1], delta=0.015) + + def test_each_pod_uses_its_own_corner(self) -> None: + plate = bc_flat_96("plate") + self.deck.get_position("P9").assign_child_resource(plate) + a1 = plate.get_well("A1") + one = targeting.target(self.deck, self.config, 1, a1) + two = targeting.target(self.deck, self.config, 2, a1) + corners = self.config.deck_positions["P9"] + self.assertAlmostEqual(two.x - one.x, corners.corner(2)[0] - corners.corner(1)[0]) + self.assertAlmostEqual(two.z - one.z, corners.corner(2)[2] - corners.corner(1)[2]) + + def test_a_resource_on_no_position_is_not_corrected(self) -> None: + rack = beckman_coulter_biomek_96_tiprack_1070uL("tips") + self.deck.assign_child_resource(rack, location=self.deck.pin_location(30, 5)) + self.assertIsNone(targeting.deck_position_of(self.deck, rack)) + point = targeting.target(self.deck, self.config, 1, rack) + self.assertEqual(point, targeting.to_biomek(rack.get_location_wrt(self.deck, "c", "c", "b"))) From ec9d1adbdfa826e2de88e85d5443c0d380ed2464 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:58:12 +0000 Subject: [PATCH 15/28] `Biomek i7`: sort imports for ruff I001 --- pylabrobot/beckman_coulter/biomek_i7/device.py | 17 +++++++---------- .../biomek_i7/device_model_tests.py | 6 +++--- .../beckman_coulter/biomek_i7/device_tests.py | 2 +- .../biomek_i7/driver/traverse_tests.py | 2 +- .../beckman_coulter/biomek_i7/targeting.py | 6 +++++- 5 files changed, 17 insertions(+), 16 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device.py b/pylabrobot/beckman_coulter/biomek_i7/device.py index ad716652d6b..c153fe85d50 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device.py @@ -26,18 +26,17 @@ deck_x, deck_y, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis -from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door -from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod -from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver - -from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import RECORDING_ENV, simulated_boards -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION, GENERIC_RECORDING +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( DeviceConfiguration, PodConfiguration, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis +from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod +from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import RECORDING_ENV, simulated_boards from pylabrobot.beckman_coulter.biomek_i7.resource_model import cm, pod_model from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import PROBES from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import ( @@ -553,9 +552,7 @@ def BiomekI7( path=simulator_recording, time_scale=motion_time_scale if simulate_motion_time else 0.0, ) - driver = BiomekI7Driver( - declared_configuration_json=declared_configuration_json, boards=boards - ) + driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json, boards=boards) elif driver is None: driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json) return BiomekI7Device(driver=driver, deck=deck, name=name, state_json=state_json) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py index 5f67e8797ce..95453c5e70c 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py @@ -15,14 +15,14 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.resource_model import MM_PER_CM from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import gripper_model -from pylabrobot.resources import Resource -from pylabrobot.resources.coordinate import Coordinate -from pylabrobot.resources.rotation import Rotation from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( generic_biomek, generic_configuration, generic_deck, ) +from pylabrobot.resources import Resource +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.rotation import Rotation def biomek_x_range(lh: BiomekI7Device, resource: Resource) -> g.Range: diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_tests.py index a37f92c3d75..bb0d40c83a2 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device_tests.py @@ -4,8 +4,8 @@ import os import struct import unittest -from unittest import mock from typing import Dict +from unittest import mock from pylabrobot.beckman_coulter.biomek_i7.device import DECK_Z, RAIL_TOP_Z, BiomekI7 from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import RECORDING_ENV diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py index 74976d7ef54..9368ec7ec92 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py @@ -6,11 +6,11 @@ from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest -from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( generic_configuration, generic_deck, ) +from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb class ObstacleTests(unittest.TestCase): diff --git a/pylabrobot/beckman_coulter/biomek_i7/targeting.py b/pylabrobot/beckman_coulter/biomek_i7/targeting.py index e3e719896db..3e6b042f33b 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/targeting.py +++ b/pylabrobot/beckman_coulter/biomek_i7/targeting.py @@ -17,10 +17,14 @@ from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import DeviceConfiguration +from pylabrobot.beckman_coulter.biomek_i7.units import ( # noqa: F401 (re-exported) + MM_PER_CM, + BiomekPoint, + to_biomek, +) from pylabrobot.resources.coordinate import Coordinate from pylabrobot.resources.resource import Resource from pylabrobot.resources.resource_holder import ResourceHolder -from pylabrobot.beckman_coulter.biomek_i7.units import MM_PER_CM, BiomekPoint, to_biomek # noqa: F401 (re-exported) def deck_position_of(deck: BiomekI7Deck, resource: Resource) -> Optional[ResourceHolder]: From 3f7910c302a7aa9288e7277fa8856596eb470f53 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:30:00 -0800 Subject: [PATCH 16/28] `Biomek i7`: the Span-8: tips, priming, aspirate and dispense The Span-8 pod's eight channels as a feature (`pod.pipettes`, `driver.pipettes`, `biomek.pipettes`), STAR's `Pipettes` signatures, built as Biomek's logs show its operations: - `driver/features/pipettes.py`: the pumps' valves (`VI` `VO` `VB` `VE`), cutoff velocity (`CV`) and the sensors' sensitivity (`SS`); the tip sensor (`GT`, `VT`); picking up tips in Biomek's press groups and discarding them by the stripper at the top of travel; priming over the wash station (start, stop, a set number of strokes); aspirate and dispense with mixes, conditioning, blowout and trailing air, tip touch; the probes' tips recorded and shown on their shafts (the device saves and restores them); parking over the wash station. - `driver/liquid.py`: Biomek's pipetting templates as a plan (heights from the bottom, top or liquid, following the liquid, the mix, the touch-off), with any PyLabRobot container's shape. - `techniques.py`: the argument types the features take (`Conditioning`, `TipTouch`, `MixHeights`, `HeightFrom`). - The device: `setup` takes off tips the Span-8's sensor finds (`discard_tips`) and skips the Span-8's pod on `skip_pipettes`; the simulator's tip sensor reports the probes' recorded tips. Tests: a full load and discard of tips, a prime, a transfer and a mix send the moves Biomek's logs show for the same operations; press groups, partial loads with tip tracking, the tip check, travel below the stripper; the template's mix, touch-off and heights; setup's tip discard. --- .../beckman_coulter/biomek_i7/design.md | 14 + .../beckman_coulter/biomek_i7/device.py | 83 +- .../biomek_i7/driver/configuration.py | 13 + .../biomek_i7/driver/errors.py | 5 + .../biomek_i7/driver/features/pipettes.py | 1349 +++++++++++++++++ .../biomek_i7/driver/features/pod.py | 59 +- .../biomek_i7/driver/liquid.py | 517 +++++++ .../biomek_i7/driver/liquid_tests.py | 331 ++++ .../biomek_i7/driver/master.py | 57 +- .../biomek_i7/driver/pipettes_tests.py | 55 + .../biomek_i7/driver/pipettes_tip_tests.py | 168 ++ .../biomek_i7/driver/prime_tests.py | 94 ++ .../biomek_i7/driver/pump_homing_tests.py | 39 + .../biomek_i7/driver/simulator.py | 36 +- .../biomek_i7/resource_model/heads.py | 41 +- .../biomek_i7/simulation_tests.py | 40 +- .../beckman_coulter/biomek_i7/techniques.py | 60 + 17 files changed, 2927 insertions(+), 34 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/liquid.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pump_homing_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/techniques.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index 0ea080aa312..27fae593a9e 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -97,3 +97,17 @@ the 96-head cannot sense tips, so that is how they are known across sessions. gripper rise to a traverse height (by default near the top of travel; per call, as STAR's `minimum_traverse_height_*`). A height below what the deck model and Biomek's per-pod obstacles need is refused, not routed. + +## Operation features + +A feature exists once discovery says it is fitted (STAR's P2): `pipettes` on a Span-8 pod. Shortcuts +(`driver.pipettes`, `lh.pipettes`) give it when exactly one pod carries it. Calls take STAR's shape: +the arguments every PyLabRobot liquid handler shares are positional, in STAR's order; the rest are +keyword-only, so a STAR positional argument this driver lacks is refused, not misread. Where the +Span-8 applies one value to all probes, a per-channel list whose values differ is refused. + +**I13. Pipetting follows Biomek's templates** (`driver/liquid.py`): its height rule (from the +bottom, top or liquid), following the liquid, mixes, conditioning, blowout, trailing air and the +touch-off, for any PyLabRobot container from its height <-> volume function. A setting the driver +does not build yet is refused, never run without it. The Span-8's tips are checked by its tip +sensor; it cannot drop tips into a rack, only discard them. diff --git a/pylabrobot/beckman_coulter/biomek_i7/device.py b/pylabrobot/beckman_coulter/biomek_i7/device.py index c153fe85d50..a0c20938364 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device.py @@ -14,7 +14,7 @@ import logging import os -from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple +from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.deck import ( @@ -34,9 +34,17 @@ ) from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import ( + DEFAULT_TRASH as SPAN8_TRASH, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver -from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import RECORDING_ENV, simulated_boards +from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ( + RECORDING_ENV, + sense_recorded_tips, + simulated_boards, +) from pylabrobot.beckman_coulter.biomek_i7.resource_model import cm, pod_model from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import PROBES from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import ( @@ -46,6 +54,7 @@ place_span8_channel, span8_channels, ) +from pylabrobot.resources.beckman_coulter.tips import beckman_coulter_biomek_tip_1070uL from pylabrobot.resources.coordinate import Coordinate from pylabrobot.resources.resource import Resource @@ -85,9 +94,11 @@ class BiomekI7Device(Resource): the driver moves it, placed as Biomek's collision model places it, so the resource tree takes up the X the rail guard counts. The rest follows the pod's other axes (`_show_pod`): the Multichannel's carriage its Y and its head (an `NChannelPipette`) its Z, each Span-8 probe's - channel its own Y and Z, and the gripper (a `MechanicalGripper`) GY, GZ, GR and GG. Each bridge - marks the point its pod's X names (`resource_model.pods.pod_model`). `update_bridge_location`, - `update_pod_location` and `update_probe_location` place the models by hand; nothing moves. + channel its own Y and Z, and the gripper (a `MechanicalGripper`) GY, GZ, GR and GG. The Span-8's + probes are its feature's resources, so the tips they carry hang from their shafts, as the STAR's + do. Each bridge marks the point its pod's X names (`resource_model.pods.pod_model`). + `update_bridge_location`, `update_pod_location` and `update_probe_location` place the models by + hand; nothing moves. """ def __init__( @@ -170,45 +181,86 @@ def front_cover(self) -> Optional[Door]: """The door, by STAR's name for it (known after `setup`).""" return self.driver.front_cover + @property + def pipettes(self) -> Optional[Pipettes]: + """The Span-8 channels, on an instrument where one pod has them.""" + return self.driver.pipettes + async def setup( self, skip_device_initialization: bool = False, + skip_pipettes: bool = False, *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, force_initialize: bool = False, + discard_tips: bool = True, park: bool = True, ) -> None: - """Bring the instrument up. This homes the arms, then parks the pods, as Biomek's Home All - does (`park`). + """Bring the instrument up. This homes the arms, then, as the STAR does, takes off any tips + left on (`discard_tips`), and parks the pods, as Biomek's Home All does (`park`). Args: skip_device_initialization: as `BiomekI7Driver.setup` takes it. + skip_pipettes: as `BiomekI7Driver.setup` takes it. skip_left_x_arm: as `BiomekI7Driver.setup` takes it. skip_right_x_arm: as `BiomekI7Driver.setup` takes it. force_initialize: as `BiomekI7Driver.setup` takes it. + discard_tips: shuck tips found on a Span-8 that was brought up into its trash: the probes + the tip sensor finds a tip on. Needs the trash position on the deck. park: park every pod that was brought up (`park`). """ await self.driver.setup( skip_device_initialization=skip_device_initialization, + skip_pipettes=skip_pipettes, skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm, force_initialize=force_initialize, ) self._follow_driver() skipped = self.driver.skipped_sides( - skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm + skip_pipettes=skip_pipettes, + skip_left_x_arm=skip_left_x_arm, + skip_right_x_arm=skip_right_x_arm, ) + if discard_tips: + await self._discard_found_tips(skipped) if park: await self.park(skip=skipped) + async def _discard_found_tips(self, skipped: Set[str]) -> None: + """Shuck the tips found on the pods not `skipped` (`setup`'s `discard_tips`). A Span-8 probe + the sensor finds a tip on that the session did not record is taken to carry the longest + Biomek tip, so its travel to the trash clears the deck; a recorded tip the sensor does not + find is forgotten.""" + names = set(self.deck.position_names) + for pod in self.arms: + if pod.side in skipped: + continue + if pod.pipettes is not None and SPAN8_TRASH in names: + pipettes = pod.pipettes + states = await pipettes.sense_tip_presence() + found = [n for n, state in enumerate(states, start=1) if state == "loaded"] + gone = [n for n, t in enumerate(pipettes.tips, start=1) if t is not None and n not in found] + if gone: + pipettes._set_tips({n: None for n in gone}) + if found: + assumed = beckman_coulter_biomek_tip_1070uL("assumed tip") + pipettes._set_tips({n: pipettes._carried_tip(n) or assumed for n in found}) + logger.warning("%s: tips found on probes %s; discarding them", pod, found) + await pipettes.discard_tips(use_channels=[n - 1 for n in found]) + async def park(self, skip: Iterable[str] = ()) -> None: - """Park the pods as Biomek does (`Pod.park`), the left pod first, as each pod's park is at its - own end of the rail. `skip`: sides to leave as they are.""" + """Park the pods as Biomek does (`Pod.park`; a Span-8 over its wash station, + `pipettes.park`), the left pod first, as each pod's park is at its own end of the rail. `skip`: + sides to leave as they are.""" for pod in sorted(self.driver.arms, key=lambda p: p.side != "left"): if pod.side in skip: continue - await pod.park() + if pod.pipettes is not None: + await pod.pipettes.park() + else: + await pod.park() async def pause(self) -> None: """Pause for access, as Biomek's Pause step: the pods' drive power is cut and PAUSED shown, @@ -271,10 +323,18 @@ def _follow_driver(self) -> None: self._show_parked(pod.side, pod.declared) pod.resource = self.bridges[pod.side] self.bridges[pod.side].load_all_state(saved) + self._give_heads(pod) if pod.declared is not None: self._unfollow.append(pod.add_position_listener(self._show_pod)) self._show_pod(pod) + def _give_heads(self, pod: Pod) -> None: + """Hand a Span-8's probes to its feature, as the STAR's driver hands each feature its + resources; the feature takes the tips their shafts carry as its own.""" + if pod.pipettes is not None: + pod.pipettes.resources = span8_channels(self.bridges[pod.side]) + pod.pipettes._adopt_tips() + def _tips_changed(self) -> None: """A head's tips changed: save the tree's state, when there is a `state_json`.""" if self.state_json is not None: @@ -553,6 +613,7 @@ def BiomekI7( time_scale=motion_time_scale if simulate_motion_time else 0.0, ) driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json, boards=boards) + sense_recorded_tips(driver, boards) # the simulator does not model tips elif driver is None: driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json) return BiomekI7Device(driver=driver, deck=deck, name=name, state_json=state_json) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index afa9f70a4ea..fe2020a5632 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -179,6 +179,19 @@ class Obstacle: "span8": ( "ProbeSize", "DefaultTipHubInfo", + "LoadingOffsets", + "DetectTips", + "SystemTrailingAirgap", + "D1SpeedLimit", + "LoadSpeed", + "TipLoadZOffset", + "MaxLoadingProbes", + "MinLoadingInterval", + "DiscardHeight", + "DiscardSpeed", + "DiscardOvershoot", + "MaxUnloadingProbes", + "MinUnloadingInterval", ), "multichannel": ( "Head/PodToMandrel1", diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py index dfe7c096599..a2c2898ee43 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py @@ -139,3 +139,8 @@ def motion_failed(e: AceError) -> str: if error.code in _MOTION_FAILED_CODES and error.device is not None: return motion_failed(error) return f"{error.request} failed: {error.reason}." + + +class TipCheckError(RuntimeError): + """A probe's tip is not what was expected, or cannot be determined: the Master Controller's + `VT`.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py new file mode 100644 index 00000000000..88326d49ee9 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py @@ -0,0 +1,1349 @@ +"""A Span-8 pod's eight independent channels: their syringe pumps, valves, liquid-level sensors and +tip sensor. Reached as `driver.right_x_arm.pipettes` (on whichever pod is a Span-8). + +The channels' axes (Y1-Y8, Z1-Z8, D1-D8) are the pod's, moved through `Pod.move_axes`. The pumps' +valves and cutoff velocity are kept in the pod's state, because every pump move carries them; +this feature is what sets them. The host commands here are the Master Controller's Span-8 ones, as +its logs show them: `CV`, `VI`/`VO`/`VB`/`VE`, `SS`, `GT`, `VT`. + +Picking tips up and discarding them are Biomek's compositions of plain moves, as its logs show +them, replayed against every logged one: + +- pick up, per set of spots the probes reach in one X/Y/S move (one rack, one X, evenly spaced in + Y): probe 1 over its spot with the span the spots need; the probes used, and every other probe + without a tip over an emptied spot of the rack (tip tracking), down to an approach over the rack's top (`AdditionalSafeHeight` + + `AvoidanceMargin`, Biomek's safe height there, in its world model: by pod 1's corner of the + position); then pressed in groups (the first probe still waiting and later ones + at least `MinLoadingInterval` from the last taken, up to `MaxLoadingProbes`: 1+5, 2+6, 3+7, 4+8). + One move per group at `LoadSpeed` sends the group to the seat (the rack's top + `TipLoadZOffset` + + the probe's `LoadingOffsets`) and the group before it up to the exit (the top + 1.0 cm); the + last group then rises alone. `TiploadExitZOffset` and `TipLoadTime` are declared, but no logged + move depends on either; +- discard: probe 1 at the trash's `XSpan`/2 + `Span8TipDisposalOffsetX`, the probes centred in Y + ((`YSpan` - span)/2 + `Span8TipDisposalOffsetY`) at the narrowest span, the probes at + `DiscardHeight` - 1.0 cm; then shucked in groups (the first probe still to go and + later ones at least `MinUnloadingInterval` from the last taken, up to `MaxUnloadingProbes`): each + probe of a group driven to the top of its travel + `DiscardOvershoot` at `DiscardSpeed`, where + the pod's stripper pushes the tip off, and back; +- with `DetectTips` set, the tip sensor then checks the probes worked (`VT`). + +Priming fills the pumps and probes with system fluid over the Span-8 wash station, as Biomek's +prime dialog does (the pumps homed, then strokes until the operator stops it), and as logged +(2026-10-09; the same position in four logs): the probes, +without tips, centred in Y at the narrowest span and lowered at speed 250 to the wash position's +height; the pumps homed (`HD`); then strokes, each a full draw with the valves to the system fluid +(`VI`) and a full push out through the probes (`VO`), at the pumps' `D1SpeedLimit` (80.17 % is the +logged 801); when stopped, the probes up and the system trailing air gap drawn at speed 10. +`start_prime` and `stop_prime` are those two halves, for an operator who watches for bubbles; +`prime` runs a set number of strokes. + +The stripper works only at the top of travel, so a Span-8 cannot put tips back into a rack: they go +to waste. Carrying probes travel no higher than the top less `DiscardOffset` +(`Pod._traverse_ceilings`). Which probes carry which tips is its record of what they picked up. +""" + +import asyncio +import collections +import logging +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7 import targeting +from pylabrobot.beckman_coulter.biomek_i7.driver import motion +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import NotHomedError, TipCheckError +from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.driver import liquid +from pylabrobot.beckman_coulter.biomek_i7.techniques import ( + Conditioning, + HeightFrom, + MixHeights, + TipTouch, +) +from pylabrobot.beckman_coulter.biomek_i7.units import ( + cutoff_to_counts, + offset_to_biomek, + percent_to_field, + rate_to_field, +) +from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of, show_tip +from pylabrobot.resources.container import Container +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.errors import HasTipError +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.tip import Tip +from pylabrobot.resources.tip_rack import TipSpot +from pylabrobot.resources.volume_tracker import VolumeTracker, does_volume_tracking + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck + from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + DeviceConfiguration, + PodConfiguration, + ) + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + +logger = logging.getLogger(__name__) + +# The valves' Move All timeout, as the Master Controller's logs show it. +VALVE_MOVE_ALL_TIMEOUT_MS = 6000 + +# Cutoff velocity range (`CV`), counts/s; quantized to 4. +CUTOFF_VELOCITY_RANGE = (200, 10800) + +PROBES = 8 +DEFAULT_TRASH = "TR2" # the right trash, where Biomek discards the Span-8's tips +EXIT_ABOVE_TOP = 1.0 # cm: the probes leave a pickup this far above the rack (logged) +DISCARD_BELOW = 1.0 # cm: the probes shuck from `DiscardHeight` less this (logged) +# How far apart, cm, two spots may be in X, or off the probes' even spacing in Y, for one move. +ALIGNMENT_TOLERANCE = 0.005 +# uL: how far a pump read back from counts may sit below what it was sent to (a count is 0.042 uL). +PLUNGER_TOLERANCE = 0.05 +AIR_GAP_SPEED = 200 # the speed field Biomek draws the system trailing air gap at +DEFAULT_WASH = "W2" # the Span-8 wash station's position, where Biomek primes +# cm: probe 1's X from the wash position's centre in every logged prime (X -7761 counts, 143.375 +# cm, where W2's centre is 143.855). Not traced to Biomek's code; kept so the probes enter the +# trough where Biomek's do. +PRIME_X_OFFSET = -0.48 +PRIME_Z_SPEED = 250 # the speed field the probes are lowered into the wash station at +PRIME_AIR_GAP_SPEED = 10 # the speed field of the air gap drawn after priming +# s: the least a prime stroke takes. A stroke takes about 4.4 s on the instrument (logged); this +# keeps an instant simulator to one a second rather than hundreds. +MINIMUM_STROKE_SECONDS = 1.0 +# The Span-8's `HD`: these pumps enabled together, then D1, then one Home of D1 homes all eight. +PUMP_ENABLE_ORDER = ("D2", "D4", "D3", "D6", "D5", "D8", "D7") + + +def press_groups(probes: Sequence[int], most: int, interval: int) -> List[Tuple[int, ...]]: + """Biomek's grouping of probes for pressing onto tips or shucking them, as its logs show it: each + group takes the first probe still waiting, then later ones at least + `interval` probes from the last one taken, up to `most`.""" + waiting = sorted(probes) + groups = [] + while waiting: + group = [waiting.pop(0)] + for probe in list(waiting): + if len(group) < most and probe - group[-1] >= interval: + group.append(probe) + waiting.remove(probe) + groups.append(tuple(group)) + return groups + + +@dataclass(frozen=True) +class PrimePlan: + """Where a prime goes (probe 1, Biomek cm; the probes' ends at `z`), and its strokes: uL per + pump and the pumps' speed field.""" + + x: float + y: float + span: float + z: float + stroke: float + speed: int + + +class _Job(NamedTuple): + """A probe and its tip spot, with where the probe must be (Biomek cm), the rack's top for this + pod, the rack's top in Biomek's world model (pod 1's corner of the position) and the rack's + spots with where each is (X, Y).""" + + probe: int + spot: TipSpot + x: float + y: float + top: float + world_top: float + rack_spots: Tuple[Tuple[TipSpot, float, float], ...] + + +@dataclass(frozen=True) +class PickUpPlan: + """One X/Y/S move's pickup, in Biomek's frame (cm): probe 1's X/Y, the span from probe 1 to 8, + which probe meets which spot, the heights (the probes' bottoms), the probes lowered to the + approach (those picking up, and those without tips over the rack) and the press groups.""" + + x: float + y: float + span: float + pairs: Tuple[Tuple[int, TipSpot], ...] + approach: float + lowered: Tuple[int, ...] + seats: Dict[int, float] + exit: float + groups: Tuple[Tuple[int, ...], ...] + + +@dataclass(frozen=True) +class DiscardPlan: + """A discard, in Biomek's frame (cm): probe 1's X/Y, the span, the probes' Z before the shuck, + the shuck groups and each probe's shuck target.""" + + x: float + y: float + span: float + z: float + groups: Tuple[Tuple[int, ...], ...] + shuck: Dict[int, float] + + +@dataclass(frozen=True) +class ProbePlan: + """One X/Y/S move's aspirate or dispense, in Biomek's frame (cm): probe 1's X/Y, the span, the + probes' channels, the template's moves (`driver/liquid.py`) and which probe works which + container.""" + + x: float + y: float + span: float + channels: Tuple[liquid.Channel, ...] + steps: Tuple[liquid.Step, ...] + pairs: Tuple[Tuple[int, Container], ...] + + +def tip_problems(states: Sequence[Optional[str]], expected: Mapping[int, bool]) -> List[str]: + """What the Master Controller's `VT` reports, in its words: per probe (1..8) whose tip is not as + `expected` says, in probe order. A state of `loaded` is a tip, `unknown` cannot be told, and + anything else is no tip.""" + problems = [] + for probe, should in sorted(expected.items()): + state = states[probe - 1] + if state == "unknown": + problems.append(f"The system cannot determine whether or not probe {probe} has a tip on.") + elif state == "loaded" and not should: + problems.append(f"Probe {probe} should not have a tip on, but it does.") + elif state != "loaded" and should: + problems.append(f"Probe {probe} should have a tip on, but it does not.") + return problems + + +class Pipettes: + """The eight channels of a Span-8 pod.""" + + # Where neither the caller nor a technique gives a value (STAR P6): the tips' ends 1 mm above + # the bottom, Biomek's Water liquid type's 90 uL/s and cutoff velocity, the Z speed and the + # conductivity of its S8 techniques. + default_liquid_height: float = 1.0 # mm + default_flow_rate: float = 90.0 # uL/s + default_z_speed: float = 109.3 # mm/s: its S8 techniques' 30 % of a Span-8 Z on this unit + default_cutoff_velocity: float = 150.0 # uL/s + default_lls_sensitivity: int = 3500 + + def __init__(self, pod: "Pod"): + self._pod = pod + # The tips on the probes, by probe (1..8), as this session picked them up. + self._tips: Dict[int, Tip] = {} + # The probes' channels in the resource tree, probe 1 first, as the STAR's + # `pipettes.resources`: each one's shaft carries its tip. Set by the device that models them + # (`BiomekI7Device`); empty when nothing models them. + self.resources: List[Resource] = [] + self._priming: Optional["asyncio.Task[int]"] = None + self._stop_priming = asyncio.Event() + # Whether the pumps are homed: None until this session homes them (`home_pumps`) or asks + # (`_require_pumps_homed`); a power-up leaves them not homed, and Home All does not home them. + self._pumps_homed: Optional[bool] = None + + def __str__(self) -> str: + return f"{self._pod}'s channels" + + @property + def arm(self) -> "Pod": + """The pod these channels are on (STAR's `feature.arm`).""" + return self._pod + + # -- pumps ------------------------------------------------------------------------- + + def _set_cutoff_velocity(self, velocity: int) -> None: + """The syringe pumps' cutoff velocity for the moves that follow, counts/s: the Master + Controller's `CV`, quantized to 4 as it does. Sends nothing. + + Private: callers pass it per call (`aspirate` / `dispense`'s `cutoff_velocity`, uL/s). It is + kept as the Master Controller keeps it, because Biomek's moves between two `CV`s (the air gap + before an aspirate, a prime) carry the last one set. + + Raises: + ValueError: outside 200..10800. + """ + low, high = CUTOFF_VELOCITY_RANGE + if not low <= velocity <= high: + raise ValueError(f"cutoff velocity {velocity} is outside {low}..{high}") + self._pod._cutoff_velocity = motion.quantize(velocity, 4.0) + + @property + def valves(self) -> Dict[str, Optional[p.Valve]]: + """Each syringe pump's valve, as this driver last set it; None until set.""" + return dict(self._pod._valves) + + async def set_valves(self, valves: Mapping[str, p.Valve]) -> None: + """Turn syringe pumps' valves: the Master Controller's `VI`/`VO`/`VB`/`VE`. Each pump is sent Set Move Parameters at the position it is at, with + its minimum start and cutoff velocities, maximum velocity and acceleration, and the new valve; + then one Move All. Positions not known are read first, as before any move. + + Raises: + ValueError: for an axis that is not a syringe pump, or an unknown valve. + """ + pod = self._pod + for name, valve in valves.items(): + if not pod.axis(name).is_pump: + raise ValueError(f"{pod}: {name} is not a syringe pump") + if valve not in p.VALVE_POSITIONS: + raise ValueError(f"unknown valve {valve!r}; have {sorted(p.VALVE_POSITIONS)}") + if not valves: + return + logger.info("%s V %s", pod.component, " ".join(f"{n}={v}" for n, v in valves.items())) + try: + await pod._read_unknown_positions(pumps=True) + await self._unchecked_fw_set_valves(valves) + await pod._unchecked_fw_move_all(VALVE_MOVE_ALL_TIMEOUT_MS) + except BaseException: + for name in valves: + pod._valves[name] = None + pod._forget_positions(valves) + raise + pod._valves.update(valves) + + async def _unchecked_fw_set_valves(self, valves: Mapping[str, p.Valve]) -> None: + """Each pump's Set Move Parameters to turn its valve where it stands, sent together.""" + pod = self._pod + requests = [] + for name, valve in valves.items(): + axis = pod.axis(name) + limits, pump = axis.limits, axis.pump_limits + requests.append( + p.set_pump_move_parameters( + axis.index, + pod._cpositions[name][0] or 0, # read before this is called + pump.min_start_velocity, + limits.max_velocity, + pump.min_cutoff_velocity, + limits.max_acceleration, + valve, + ) + ) + await pod.board.send_many(requests) + + # -- sensors ----------------------------------------------------------------------- + + async def _set_lls_sensitivity(self, value: int) -> None: + """The liquid-level sensors' sensitivity, 0-4095: the Master Controller's `SS` (Biomek sends + 3500 on this instrument). Moves nothing. Private: callers pass it per call (`aspirate` / + `dispense`'s `lls_sensitivity`), which sets it before each move measured from the liquid. + + Raises: + ValueError: outside 0..4095. + """ + if not 0 <= value <= 4095: + raise ValueError(f"{self._pod}: LLS sensitivity is 0..4095, not {value}") + logger.info("%s SS %d", self._pod.component, value) + await self._pod.board.send(p.set_lls_cd_sensitivity(False, value)) + + async def sense_tip_presence(self) -> List[Optional[str]]: + """Each probe's tip, `loaded`, `unloaded` or `unknown`, as the tip sensor reports it: the + Master Controller's `GT` (STAR's `sense_tip_presence`, which answers 1 or 0 per channel; the + Span-8's sensor can also answer that it cannot tell). Moves nothing.""" + return p.parse_tip_status((await self._pod.board.send(p.get_tip_status())).payload) + + async def verify_tips(self, expected: Mapping[int, bool]) -> None: + """Check that channels do or do not carry a tip, from the tip sensor: the Master Controller's + `VT`. `expected` maps a channel (0-indexed from the back, as `use_channels`) to whether it + should have a tip. Moves nothing. + + Raises: + ValueError: for a channel out of range. + TipCheckError: naming every probe that does not match, or whose tip cannot be determined. + """ + states = await self.sense_tip_presence() + for channel in expected: + if not 0 <= channel < len(states): + raise ValueError(f"{self._pod}: no channel {channel}; have 0..{len(states) - 1}") + problems = tip_problems(states, {channel + 1: want for channel, want in expected.items()}) + if problems: + raise TipCheckError(f"{self._pod}: " + "\n".join(problems)) + + # -- priming ------------------------------------------------------------------------------------ + + async def home_pumps(self) -> None: + """Home the syringe pumps, the Master Controller's Span-8 `HD`: the pumps enabled (D1 last) + and one Home of D1, after which all eight read 0 (logged 2026-10-09). `start_prime` does this; + Home All does not home the Span-8's pumps.""" + pod = self._pod + logger.info("%s HD", pod.component) + await pod._unchecked_fw_enable(PUMP_ENABLE_ORDER) + await pod._unchecked_fw_enable(["D1"]) + await pod._unchecked_fw_home(["D1"]) + pod._set_home_positions(f"D{n}" for n in range(1, PROBES + 1)) + self._pumps_homed = True + + def plan_prime(self, wash: Optional[Resource] = None) -> PrimePlan: + """Where a prime goes, over `wash` (the deck's `W2` by default), and its strokes: a full + stroke at the pumps' `D1SpeedLimit`.""" + deck, configuration, declared = self._context() + position = wash if wash is not None else deck.get_position(DEFAULT_WASH) + at = targeting.target(deck, configuration, self._pod.pod_number, position) + span = declared.limits["Span"][0] + return PrimePlan( + x=at.x + PRIME_X_OFFSET, + y=at.y - span / 2, + span=span, + z=at.z, + stroke=declared.limits["D1"][1], + speed=percent_to_field(declared.settings["D1SpeedLimit"], truncate=True), + ) + + @property + def priming(self) -> bool: + """Whether a prime started by `start_prime` has not been stopped.""" + return self._priming is not None + + async def start_prime( + self, + wash: Optional[Resource] = None, + strokes: Optional[int] = None, + minimum_traverse_height: Optional[float] = None, + minimum_stroke_seconds: float = MINIMUM_STROKE_SECONDS, + ) -> None: + """Lower the probes into the wash station, home the pumps and start priming: strokes run in + the background until `stop_prime` (or, given `strokes`, until that many are done; `stop_prime` + still lifts the probes). Heights in mm, as `pick_up_tips`. A stroke takes at least + `minimum_stroke_seconds`: on the instrument one takes longer (about 4.4 s), so this only paces + a simulator that answers at once, which would otherwise stroke hundreds of times a second. + + Raises: + RuntimeError: if a prime is running, or a probe carries a tip. + """ + if self._priming is not None: + raise RuntimeError(f"{self}: already priming; call stop_prime first") + carrying = [n for n, t in enumerate(self.tips, start=1) if t is not None] + if carrying: + raise RuntimeError(f"{self}: probes {carrying} carry tips; discard them before priming") + plan = self.plan_prime(wash) + _, _, declared = self._context() + pod = self._pod + logger.info("%s prime over %s", pod.component, wash.name if wash else DEFAULT_WASH) + await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height) + await pod.move_axes( + {f"Z{n}": declared.to_counts(f"Z{n}", plan.z) for n in range(1, PROBES + 1)}, PRIME_Z_SPEED + ) + await self.home_pumps() + self._stop_priming.clear() + self._priming = asyncio.ensure_future( + self._prime_strokes(plan, strokes, minimum_stroke_seconds) + ) + + async def _prime_strokes(self, plan: PrimePlan, limit: Optional[int], least: float) -> int: + _, _, declared = self._context() + pumps = [f"D{n}" for n in range(1, PROBES + 1)] + loop = asyncio.get_running_loop() + done = 0 + while not self._stop_priming.is_set() and (limit is None or done < limit): + started = loop.time() + await self.set_valves({a: "input" for a in pumps}) + await self._pod.move_axes({a: declared.to_counts(a, plan.stroke) for a in pumps}, plan.speed) + await self.set_valves({a: "output" for a in pumps}) + await self._pod.move_axes({a: 0 for a in pumps}, plan.speed) + done += 1 + logger.debug("%s prime stroke %d", self._pod.component, done) + rest = least - (loop.time() - started) + if rest > 0 and (limit is None or done < limit): + try: # the rest of the stroke's least time, cut short by a stop + await asyncio.wait_for(self._stop_priming.wait(), rest) + except asyncio.TimeoutError: + pass + return done + + async def stop_prime( + self, park: bool = True, minimum_traverse_height_end: Optional[float] = None + ) -> int: + """Stop priming once the stroke under way has pushed out, lift the probes, draw the system + trailing air gap and, as Biomek does, park the pod (`park`; over the wash station, so only the + probes and the gripper move). Returns the strokes made. `minimum_traverse_height_end` (mm): + where the probes are lifted to without parking. + + Raises: + RuntimeError: if no prime was started. A stroke's error is raised here. + """ + task = self._priming + if task is None: + raise RuntimeError(f"{self}: not priming") + self._stop_priming.set() + try: + strokes = await task + finally: + self._priming = None + _, _, declared = self._context() + pod = self._pod + end = minimum_traverse_height_end + await pod._lift_channels(None if end is None else end / 10) + gap = declared.settings["SystemTrailingAirgap"] + pumps = [f"D{n}" for n in range(1, PROBES + 1)] + await pod.move_axes({a: declared.to_counts(a, gap) for a in pumps}, PRIME_AIR_GAP_SPEED) + logger.info("%s primed: %d strokes", pod.component, strokes) + if park: + await self.park() + return strokes + + async def park(self, wash: Optional[Resource] = None) -> None: + """Park the pod as Biomek parks a Span-8: over its wash station (`wash`, the deck's `W2` by + default), where it primes, at the narrowest span (logged after Home All and after a prime: + X -7760, Y 203370), the probes and the gripper raised and the gripper to its park + (`Pod.park`). Without a wash station on the deck, it parks where it stands. + """ + deck, _, declared = self._context() + over = None + if wash is not None or DEFAULT_WASH in deck.position_names: + plan = self.plan_prime(wash) + over = { + "X": declared.to_counts("X", plan.x), + "Y": declared.to_counts("Y", plan.y), + "S": declared.to_counts("S", plan.span), + } + await self._pod._park(over) + + async def prime( + self, + strokes: int, + wash: Optional[Resource] = None, + minimum_stroke_seconds: float = MINIMUM_STROKE_SECONDS, + ) -> int: + """`start_prime` for `strokes` strokes, then `stop_prime`. Returns the strokes made.""" + await self.start_prime(wash, strokes=strokes, minimum_stroke_seconds=minimum_stroke_seconds) + if self._priming is None: + raise RuntimeError(f"{self._pod}: the prime did not start") + await asyncio.shield(self._priming) + return await self.stop_prime() + + # -- tips --------------------------------------------------------------------------------------- + + @property + def tips(self) -> List[Optional[str]]: + """Each probe's tip (its model, else its name), probe 1..8; None for none: the ones picked up, + or that the shafts carried when the device restored the last session's state (`_adopt_tips`), + checked against the tip sensor after each load and discard.""" + out: List[Optional[str]] = [] + for probe in range(1, PROBES + 1): + tip = self._tips.get(probe) + out.append(None if tip is None else tip.model or tip.name) + return out + + def _set_tips(self, probes: Mapping[int, Optional[Tip]]) -> None: + """Record the tip each of `probes` (1..8) carries (None: none), show it on the probe's shaft + (`_show_tips`), and tell the driver (`on_tips_changed`: the device saves its heads' tips).""" + for probe, tip in probes.items(): + if tip is None: + self._tips.pop(probe, None) + else: + self._tips[probe] = tip + self._show_tips(list(probes)) + if self._pod.driver is not None: + self._pod.driver.on_tips_changed() + + def _adopt_tips(self) -> None: + """Take as carried the tips the probes' shafts hold: the device puts them there from the last + session's state.""" + for probe, channel in enumerate(self.resources, start=1): + tip = shaft_of(channel).tip + if isinstance(tip, Tip): + self._tips[probe] = tip + + def _show_tips(self, probes: Optional[Sequence[int]] = None) -> None: + """Put on each of `probes`' (1..8; all, when None) shafts in the model the tip it carries, and + take off the shaft of one that carries none, as the STAR mounts and releases its tips.""" + if not self.resources: + return + for probe in range(1, PROBES + 1) if probes is None else probes: + if 1 <= probe <= len(self.resources): + show_tip(shaft_of(self.resources[probe - 1]), self._carried_tip(probe)) + + def _carried_tip(self, probe: int) -> Optional[Tip]: + """The tip on `probe`, or None.""" + return self._tips.get(probe) + + def _context(self) -> Tuple["BiomekI7Deck", "DeviceConfiguration", "PodConfiguration"]: + driver, declared = self._pod.driver, self._pod.declared + if driver is None or driver.deck is None or declared is None: + raise RuntimeError(f"{self} needs a deck and a declared configuration (use `BiomekI7`)") + return driver.deck, driver.declared, declared + + @staticmethod + def tip_length(tip: Tip) -> float: + """How far below its probe `tip`'s end is, mm: its length less its `SpanSeatingDepth` + (`fitting_depth`).""" + return units.to_mm(Pipettes._tip_length(tip)) + + @staticmethod + def _tip_length(tip: Tip) -> float: + """How far below its probe `tip`'s end is, cm: its length less its `SpanSeatingDepth` + (`fitting_depth`).""" + return float((tip.get_size_z() - tip.fitting_depth) / 10) + + def _carried_tip_lengths(self) -> Dict[str, float]: + """Per probe carrying a tip, its Z axis and how far below the probe the tip ends, cm + (`_carried_tip`). + + Raises: + RuntimeError: for a tip whose length is not known. + """ + lengths = {} + for probe, model in enumerate(self.tips, start=1): + if model is None: + continue + tip = self._carried_tip(probe) + if tip is None: + raise RuntimeError(f"{self}: the length of probe {probe}'s tip ({model}) is not known") + lengths[f"Z{probe}"] = self._tip_length(tip) + return lengths + + def _probe(self, channel: int) -> int: + if not 0 <= channel < PROBES: + raise ValueError(f"{self}: no channel {channel}; have 0..{PROBES - 1}") + return channel + 1 + + def plan_pick_up( + self, + tip_spots: Sequence[TipSpot], + use_channels: Optional[Sequence[int]] = None, + offsets: Optional[Sequence[Coordinate]] = None, + ) -> List[PickUpPlan]: + """The moves a pickup takes: one per set of spots the probes reach at once (one rack, one X, + spaced evenly in Y for the probes taking them, a span the pod reaches), in channel order. + + Raises: + ValueError: for a channel out of range or given twice, or not one channel per spot. + """ + deck, configuration, declared = self._context() + channels = list(range(len(tip_spots))) if use_channels is None else list(use_channels) + if len(channels) != len(tip_spots) or len(set(channels)) != len(channels): + raise ValueError(f"{self}: one distinct channel per tip spot, please") + offsets = [Coordinate.zero()] * len(tip_spots) if offsets is None else list(offsets) + number = self._pod.pod_number + jobs: List[_Job] = [] + spots_of: Dict[str, Tuple[Tuple[TipSpot, float, float], ...]] = {} + for channel, spot, offset in sorted(zip(channels, tip_spots, offsets), key=lambda j: j[0]): + rack = spot.parent + if rack is None: + raise ValueError(f"{self}: tip spot {spot.name} is in no rack") + at = targeting.target(deck, configuration, number, spot, offset=offset) + top = targeting.target(deck, configuration, number, rack, z="t").z + world_top = targeting.target(deck, configuration, 1, rack, z="t").z + if rack.name not in spots_of: + spots_of[rack.name] = tuple( + (s, t.x, t.y) + for s, t in ( + (s, targeting.target(deck, configuration, number, s)) for s in rack.get_all_items() + ) + ) + jobs.append(_Job(self._probe(channel), spot, at.x, at.y, top, world_top, spots_of[rack.name])) + low, high = declared.limits["Span"] + plans: List[PickUpPlan] = [] + while jobs: + first = jobs.pop(0) + batch: List[_Job] = [first] + span: Optional[float] = None + for job in list(jobs): + if abs(job.x - first.x) > ALIGNMENT_TOLERANCE or abs(job.top - first.top) > 1e-6: + continue + if span is None: + wanted = (job.y - first.y) * (PROBES - 1) / (job.probe - first.probe) + if not low - 1e-6 <= wanted <= high + 1e-6: + continue + span = wanted + if abs(first.y + (job.probe - first.probe) * span / (PROBES - 1) - job.y) <= ( + ALIGNMENT_TOLERANCE + ): + batch.append(job) + jobs.remove(job) + plans.append(self._pick_up_plan(batch, low if span is None else span, declared)) + return plans + + def _pick_up_plan( + self, batch: List["_Job"], span: float, declared: "PodConfiguration" + ) -> PickUpPlan: + s, geometry = declared.settings, declared.geometry + first = batch[0] + loading = s["LoadingOffsets"] + probes = [job.probe for job in batch] + y = first.y - (first.probe - 1) * span / (PROBES - 1) + # Biomek also lowers every probe without a tip that stands over an emptied spot of the rack; one + # over a spot still holding a tip, or over none, stays up (as logged). Spots whose contents are + # not tracked count as holding tips. + tips = self.tips + + def over_an_empty_spot(n: int) -> bool: + yn = y + (n - 1) * span / (PROBES - 1) + return any( + abs(sx - first.x) <= ALIGNMENT_TOLERANCE + and abs(sy - yn) <= ALIGNMENT_TOLERANCE + and spot.tracks_tips + and not spot.has_tip() + for spot, sx, sy in first.rack_spots + ) + + over = [n for n in range(1, PROBES + 1) if tips[n - 1] is None and over_an_empty_spot(n)] + return PickUpPlan( + x=first.x, + y=y, + span=span, + pairs=tuple((job.probe, job.spot) for job in batch), + # Biomek's safe height over the rack, in its world model, which places labware by pod 1's + # corner of the position (the press uses this pod's: they differ by up to 0.008 cm here). + approach=first.world_top + geometry.additional_safe_height + geometry.avoidance_margin, + lowered=tuple(sorted(set(probes) | set(over))), + seats={n: first.top + s["TipLoadZOffset"] + loading[n - 1] for n in probes}, + exit=first.top + EXIT_ABOVE_TOP, + groups=tuple(press_groups(probes, s["MaxLoadingProbes"], s["MinLoadingInterval"])), + ) + + def plan_discard(self, probes: Sequence[int], trash: Optional[Resource] = None) -> DiscardPlan: + """Where a discard of `probes` (1..8) goes and how they are shucked, as Biomek does it. + + Raises: + ValueError: for a position that is not a trash (no `tip_disposal`). + """ + deck, configuration, declared = self._context() + position = trash if trash is not None else deck.get_position(DEFAULT_TRASH) + disposal = getattr(position, "tip_disposal", None) + if disposal is None: + raise ValueError(f"{position.name} is not a trash position (no tip disposal offsets)") + corner = targeting.target( + deck, configuration, self._pod.pod_number, position, x="l", y="b", z="b" + ) + calibrated = configuration.deck_positions.get(position.name) + x_span = calibrated.x_span if calibrated else position.get_size_x() / 10 + y_span = calibrated.y_span if calibrated else position.get_size_y() / 10 + s = declared.settings + span = declared.limits["Span"][0] + overshoot = s["DiscardOvershoot"] + return DiscardPlan( + x=corner.x + x_span / 2 + disposal.span8_x, + y=corner.y + (y_span - span) / 2 + disposal.span8_y, + span=span, + z=s["DiscardHeight"] - DISCARD_BELOW, + groups=tuple(press_groups(probes, s["MaxUnloadingProbes"], s["MinUnloadingInterval"])), + shuck={n: declared.limits[f"Z{n}"][1] + overshoot for n in probes}, + ) + + async def _travel(self, x: float, y: float, span: float, height: Optional[float]) -> None: + """Probe 1 to X/Y with the span (Biomek cm), clear of the deck; `height` in mm (lowest points).""" + _, _, declared = self._context() + await self._pod._move_over( + { + "X": declared.to_counts("X", x), + "Y": declared.to_counts("Y", y), + "S": declared.to_counts("S", span), + }, + minimum_traverse_height=None if height is None else height / 10, + ) + + async def pick_up_tips( + self, + tip_spots: Sequence[TipSpot], + use_channels: Optional[List[int]] = None, + offsets: Optional[List[Coordinate]] = None, + *, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Pick up a tip from each spot, one channel per spot (STAR's `Pipettes` signature), as Biomek + does: see the module's description. With `DetectTips` set, the tip sensor checks every probe + afterwards. + + Args: + tip_spots: where to pick up from, one per channel. + use_channels: which channels, 0-indexed from the back (channel 0 is probe 1). The first + `len(tip_spots)` when None. + offsets: added to each spot's centre, in mm. None for none. + minimum_traverse_height_start: how high the channels' lowest points (a tip's end, else the + probe's) travel, mm above the deck. When None, the probes travel as high as they go. + minimum_traverse_height_end: where the channels' lowest points are left, mm. When None, the + probes are left as high as they go. + + Raises: + HasTipError: if a channel already carries a tip. + ValueError: for a channel out of range, or a height out of reach. + TipCheckError: if the tip sensor disagrees afterwards. + """ + if not tip_spots: + return + channels = list(range(len(tip_spots))) if use_channels is None else list(use_channels) + tips = self.tips + for channel in channels: + if tips[self._probe(channel) - 1] is not None: + raise HasTipError(f"{self}: channel {channel} already carries a tip") + plans = self.plan_pick_up(tip_spots, channels, offsets) + _, _, declared = self._context() + pod = self._pod + speed = percent_to_field(declared.settings["LoadSpeed"]) + + def z(probes: Sequence[int], height: float) -> Dict[str, int]: + return {f"Z{n}": declared.to_counts(f"Z{n}", height) for n in probes} + + for plan in plans: + probes = [n for n, _ in plan.pairs] + logger.info( + "%s pick up tips on probes %s at X %.3f Y %.3f S %.3f", + pod.component, probes, plan.x, plan.y, plan.span, + ) # fmt: skip + await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height_start) + await pod.move_axes(z(plan.lowered, plan.approach)) + previous: Tuple[int, ...] = () + for group in plan.groups: + targets = z(previous, plan.exit) + targets.update({f"Z{n}": declared.to_counts(f"Z{n}", plan.seats[n]) for n in group}) + await pod.move_axes(targets, speed) + previous = group + await pod.move_axes(z(previous, plan.exit), speed) + picked: Dict[int, Optional[Tip]] = {} + for probe, spot in plan.pairs: + tip = spot.tip_for_pickup() + if spot.tracks_tips: + spot.unassign_tip() + self._tips[probe] = tip + picked[probe] = tip + self._set_tips(picked) + end = minimum_traverse_height_end + await pod._lift_channels(None if end is None else end / 10) + await self._check_tips(sorted(n for plan in plans for n, _ in plan.pairs)) + + async def drop_tips(self, tip_spots: Sequence[TipSpot], *args: Any, **kwargs: Any) -> None: + """Not possible on a Span-8: its stripper pushes tips off only at the top of the probes' + travel, so tips cannot be put back into a rack; they go to waste with `discard_tips`. + + Raises: + NotImplementedError: always. + """ + raise NotImplementedError( + f"{self}: a Span-8 cannot put tips back into a rack (its stripper works only at the top of " + "the probes' travel); use discard_tips" + ) + + async def discard_tips( + self, + use_channels: Optional[List[int]] = None, + *, + trash: Optional[Resource] = None, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Shuck the channels' tips into the trash (`TR2` by default), as Biomek does: see the module's + description. With `DetectTips` set, the tip sensor checks every probe afterwards. + + Args: + use_channels: which channels, 0-indexed from the back. Every channel carrying a tip when None. + trash: the trash position. + minimum_traverse_height_start: how high the channels' lowest points (the tips' ends) travel + to the trash, mm above the deck. When None, the probes travel as high as they go. + minimum_traverse_height_end: where the probes are left, mm. When None, as high as they go. + + Raises: + RuntimeError: if no channel named carries a tip. + TipCheckError: if the tip sensor disagrees afterwards. + """ + tips = self.tips + named = range(PROBES) if use_channels is None else use_channels + probes = sorted(n for n in (self._probe(c) for c in named) if tips[n - 1] is not None) + if not probes: + raise RuntimeError(f"{self}: no channel named carries a tip") + plan = self.plan_discard(probes, trash) + _, _, declared = self._context() + pod = self._pod + logger.info("%s discard tips on probes %s", pod.component, probes) + + def z(group: Sequence[int], height: Mapping[int, float]) -> Dict[str, int]: + return {f"Z{n}": declared.to_counts(f"Z{n}", height[n]) for n in group} + + below = {n: plan.z for n in probes} + await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height_start) + await pod.move_axes(z(probes, below)) + speed = percent_to_field(declared.settings["DiscardSpeed"]) + for group in plan.groups: + await pod.move_axes(z(group, plan.shuck), speed) + await pod.move_axes(z(group, below), speed) + for probe in probes: + self._tips.pop(probe, None) + self._set_tips({n: None for n in probes}) + end = minimum_traverse_height_end + await pod._lift_channels(None if end is None else end / 10) + await self._check_tips(probes) + + async def _check_tips(self, probes: Sequence[int]) -> None: + """With `DetectTips` set, the tip sensor checks the probes worked against its record, as + Biomek's `VT `.""" + declared = self._pod.declared + if declared is not None and declared.settings["DetectTips"]: + tips = self.tips + await self.verify_tips({n - 1: tips[n - 1] is not None for n in probes}) + + # -- aspirate and dispense ---------------------------------------------------------------------- + + def _tip_of(self, probe: int) -> Tip: + tip = self._carried_tip(probe) + if tip is None: + key = self.tips[probe - 1] + raise RuntimeError(f"{self}: probe {probe}'s tip ({key or 'none'}) is not known") + return tip + + def plan_liquid( + self, + operation: str, + containers: Sequence[Container], + volumes: Sequence[float], + use_channels: Optional[Sequence[int]], + settings: liquid.Settings, + flow_rate: float, + ) -> List[ProbePlan]: + """The moves an aspirate (`operation` "aspirate") or dispense takes: one batch per set of + containers the probes reach in one X/Y/S move (one X, evenly spaced in Y; every probe working + one container goes in together, centred at the narrowest span), in channel order. Levels come + from the containers' trackers when volume tracking is on. + + Raises: + ValueError: for a channel out of range or given twice, a channel without a tip, or a height + that cannot be worked out (from the liquid, or following, in a container without a + height <-> volume function or with untracked contents). + """ + deck, configuration, declared = self._context() + channels = list(range(len(containers))) if use_channels is None else list(use_channels) + if len(channels) != len(containers) or len(volumes) != len(containers): + raise ValueError(f"{self}: one channel and one volume per container, please") + if len(set(channels)) != len(channels): + raise ValueError(f"{self}: a channel given twice") + number = self._pod.pod_number + low, high = declared.limits["Span"] + tracking = does_volume_tracking() + jobs = [] + for channel, container, volume in sorted( + zip(channels, containers, volumes), key=lambda j: j[0] + ): + probe = self._probe(channel) + if self.tips[probe - 1] is None: + raise ValueError(f"{self}: channel {channel} carries no tip") + at = targeting.target(deck, configuration, number, container) + jobs.append((probe, container, float(volume), at.x, at.y)) + batches: List[Tuple[float, float, List[Tuple[int, Container, float]]]] = [] + while jobs: + first = jobs.pop(0) + batch = [first] + shared = [j for j in jobs if j[1] is first[1]] + if shared: # one container for several probes: centred, at the narrowest span + batch += shared + for j in shared: + jobs.remove(j) + probes = [j[0] for j in batch] + mid = (min(probes) + max(probes)) / 2 + span = low + y1 = first[4] - (mid - 1) * span / (PROBES - 1) + batches.append((first[3], y1, span, [(j[0], j[1], j[2]) for j in batch])) # type: ignore[arg-type] + continue + span_: Optional[float] = None + for job in list(jobs): + if abs(job[3] - first[3]) > ALIGNMENT_TOLERANCE: + continue + if span_ is None: + wanted = (job[4] - first[4]) * (PROBES - 1) / (job[0] - first[0]) + if not low - 1e-6 <= wanted <= high + 1e-6: + continue + span_ = wanted + if ( + abs(first[4] + (job[0] - first[0]) * span_ / (PROBES - 1) - job[4]) <= ALIGNMENT_TOLERANCE + ): + batch.append(job) + jobs.remove(job) + span = low if span_ is None else span_ + y1 = first[4] - (first[0] - 1) * span / (PROBES - 1) + batches.append((first[3], y1, span, [(j[0], j[1], j[2]) for j in batch])) # type: ignore[arg-type] + plans = [] + for x, y1, span, members in batches: # type: ignore[misc] + share: Dict[int, int] = collections.Counter(id(c) for _, c, _ in members) # type: ignore[assignment] + chans = [] + for probe, container, volume in members: + shape = liquid.ContainerShape(container) + tip = self._tip_of(probe) + chans.append( + liquid.Channel( + name=f"Z{probe}", + well=shape, + bottom=targeting.target(deck, configuration, number, container, z="b").z + + shape.floor / 10, + tip_length=self._tip_length(tip), + volume=volume, + held=container.tracker.get_used_volume() if tracking else None, + tip_radius=tip.get_size_x() / 20, # its diameter, mm -> its radius, cm + share=share[id(container)], + ) + ) + steps = (liquid.plan_aspirate if operation == "aspirate" else liquid.plan_dispense)( + chans, settings, flow_rate + ) + plans.append( + ProbePlan(x, y1, span, tuple(chans), tuple(steps), tuple((p, c) for p, c, _ in members)) + ) + return plans + + def moves( + self, plan: ProbePlan, offset: Coordinate, d_start: Mapping[str, float] + ) -> List[Tuple[Dict[str, float], int, float, bool]]: + """One batch's moves after the travel: (axis targets in Biomek's units, Z1..Z8 / X / Y / S + cm, D1..D8 uL; speed field; delay s after; whether its sensors' sensitivity is set first). The + approach carries `offset` (mm) with X/Y/S, as the reservoir templates' first move does. The + plungers start at `d_start` uL and stop at `SystemTrailingAirgap`, the air that keeps the + system liquid from the sample. + + Raises: + ValueError: for a dispense of more than a tip holds. + """ + _, _, declared = self._context() + floor = declared.settings["SystemTrailingAirgap"] + x, y = offset_to_biomek(plan.x, plan.y, offset) + d = { + f"D{name[1:]}": d_start.get(f"D{name[1:]}", floor) for name in (c.name for c in plan.channels) + } + out: List[Tuple[Dict[str, float], int, float, bool]] = [] + first = True + for step in plan.steps: + if isinstance(step, liquid.ZMove): + targets: Dict[str, float] = dict(step.z) + if first and (offset.x or offset.y): + targets.update(X=x, Y=y, S=plan.span) + first = False + out.append((targets, step.speed, 0.0, step.liquid)) + elif isinstance(step, liquid.PlungerMove): + targets = {} + for z_name, amount in step.volume.items(): + axis = f"D{z_name[1:]}" + new = floor if step.empty else d[axis] + amount + if new < floor - PLUNGER_TOLERANCE: + raise ValueError( + f"{self}: a dispense of {-amount:.3f} uL is more than probe {z_name[1:]} holds" + ) + new = max(new, floor) + if abs(new - d[axis]) > PLUNGER_TOLERANCE: + targets[axis] = round(new, 6) + d[axis] = new + if not targets: + continue # nothing to move (a 0 uL operation): Biomek sends no move + targets.update(step.z) + out.append((targets, self._d_speed(step.flow_rate), step.delay, False)) + elif step.dx or step.dy: + out.append(({"X": x + step.dx, "Y": y + step.dy, "S": plan.span}, step.speed, 0.0, False)) + out.append(({"X": x, "Y": y, "S": plan.span}, step.speed, step.delay, False)) + return out + + def _d_speed(self, flow_rate: float) -> int: + """The `AM` speed field for the pumps at `flow_rate` uL/s: per mille of a pump's maximum.""" + return rate_to_field(self._pod, "D1", flow_rate, clamp=True) + + def _settings(self, **given: Any) -> liquid.Settings: + """The template's settings: the arguments given, else this feature's `default_*`.""" + z_speed = given.pop("z_speed", None) + rate = self.default_z_speed if z_speed is None else z_speed + base = liquid.Settings( + liquid_height=self.default_liquid_height, + z_speed_field=units.rate_to_field(self._pod, "Z1", rate), + ) + return liquid.settings(base, **given) + + async def _run_liquid( + self, + plans: List[ProbePlan], + offset: Coordinate, + cutoff_velocity: float, + lls_sensitivity: int, + minimum_traverse_height_start: Optional[float], + minimum_traverse_height_end: Optional[float], + ) -> None: + _, _, declared = self._context() + pod = self._pod + pumps = [f"D{n}" for n in range(1, PROBES + 1)] + gap = declared.settings["SystemTrailingAirgap"] + d_start = { + a: declared.to_value(a, pod.cpositions[a][1]) + for a in pumps + if pod.cpositions[a][1] is not None + } + # The system trailing air gap keeps the system liquid from the sample: Biomek draws it into + # every pump (at 20 %) when a method starts; a pump below it draws it before pipetting. + short = [a for a in pumps if d_start.get(a, 0.0) < gap - PLUNGER_TOLERANCE] + d_start.update({a: gap for a in short}) + batches = [] + for plan in plans: # all checked before anything moves + moves = self.moves(plan, offset, d_start) + for targets, _, _, _ in moves: + d_start.update({a: v for a, v in targets.items() if a.startswith("D")}) + batches.append((plan, moves)) + if short: + if any(self._pod._valves.get(a) != "output" for a in pumps): + await self.set_valves({a: "output" for a in pumps}) + await pod.move_axes({a: declared.to_counts(a, gap) for a in pumps}, AIR_GAP_SPEED) + self._set_cutoff_velocity(cutoff_to_counts(self._pod, "D1", cutoff_velocity)) + for plan, moves in batches: + await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height_start) + for targets, speed, delay, sense in moves: + if sense: + await self._set_lls_sensitivity(lls_sensitivity) + if any(a.startswith("D") for a in targets) and any( + self._pod._valves.get(a) != "output" for a in targets if a.startswith("D") + ): + await self.set_valves({a: "output" for a in pumps}) + await pod.move_axes({a: declared.to_counts(a, v) for a, v in targets.items()}, speed) + if delay > 0: + await asyncio.sleep(delay) + # Biomek turns every valve to output after each operation (`VO 255`). + await self.set_valves({a: "output" for a in pumps}) + end = minimum_traverse_height_end + await pod._lift_channels(None if end is None else end / 10) + + def _book(self, plans: List[ProbePlan], extra: float, aspirate: bool) -> List[Any]: + """Move each probe's volume (+ `extra`) between its container's and its tip's trackers + (pending, to commit or roll back).""" + if not does_volume_tracking(): + return [] + booked = [] + for plan in plans: + for c, (probe, container) in zip(plan.channels, plan.pairs): + tip = self._tips.get(probe) + giver: Optional[VolumeTracker] = container.tracker + taker: Optional[VolumeTracker] = tip.tracker if tip is not None else None + if not aspirate: + giver, taker = taker, giver + amount = c.volume + extra + if giver is not None: + booked.append(giver) + giver.remove_liquid(min(amount, giver.get_used_volume())) + if taker is not None: + booked.append(taker) + taker.add_liquid(amount) + return booked + + async def _require_pumps_homed(self, operation: str) -> None: + """Refuse `operation` before anything moves when the pumps are not homed. Known once this + session homes them; otherwise each pump is asked once, as the Master Controller asks them. + + Raises: + NotHomedError: a pump is not homed; nothing is sent. + """ + if self._pumps_homed is None: + states = [await self._pod.request_homed_state(f"D{n}") for n in range(1, PROBES + 1)] + self._pumps_homed = all(state == "homed" for state in states) + if not self._pumps_homed: + raise NotHomedError( + 0x32, + None, + f"{self._pod}: the pumps, before {operation}: prime the Span-8 (`prime`) or home its pumps " + "(`home_pumps`) first", + ) + + async def _liquid( + self, + operation: str, + containers: Sequence[Container], + volumes: Sequence[float], + use_channels: Optional[Sequence[int]], + offsets: Optional[Sequence[Coordinate]], + flow_rates: Optional[Sequence[Optional[float]]], + settings: liquid.Settings, + cutoff_velocity: Optional[float], + lls_sensitivity: Optional[int], + start: Optional[float], + end: Optional[float], + ) -> None: + rates = {r for r in (flow_rates or []) if r is not None} + if len(rates) > 1: + raise ValueError( + f"{self}: the pumps move together: one flow rate, please (got {sorted(rates)})" + ) + offset_set = {(o.x, o.y, o.z) for o in (offsets or [])} + if len(offset_set) > 1: + raise ValueError(f"{self}: the probes move together in X: one offset, please") + offset = (offsets or [Coordinate.zero()])[0] + flow = rates.pop() if rates else self.default_flow_rate + plans = self.plan_liquid(operation, containers, volumes, use_channels, settings, flow) + aspirate = operation == "aspirate" + if settings.mix is not None: + chans = [(probe, c) for plan in plans for c, (probe, _) in zip(plan.channels, plan.pairs)] + liquid.check_tips_empty_for_mix( + self, [self._tips.get(probe) for probe, _ in chans], + [0.0 if aspirate else c.volume for _, c in chans], settings, + ) # fmt: skip + await self._require_pumps_homed(operation) + logger.info( + "%s %s %s uL on probes %s", self._pod.component, operation, list(volumes), + [p for plan in plans for p, _ in plan.pairs], + ) # fmt: skip + booked = self._book(plans, settings.conditioning.excess if aspirate else 0.0, aspirate) + try: + await self._run_liquid( + plans, offset, cutoff_velocity or self.default_cutoff_velocity, + self.default_lls_sensitivity if lls_sensitivity is None else lls_sensitivity, start, end, + ) # fmt: skip + except BaseException: + for tracker in booked: + tracker.rollback() + raise + for tracker in booked: + tracker.commit() + + async def aspirate( + self, + containers: Sequence[Container], + volumes: Sequence[float], + use_channels: Optional[Sequence[int]] = None, + resource_offsets: Optional[Sequence[Coordinate]] = None, + liquid_heights: Optional[Sequence[Optional[float]]] = None, + lld_mode: Optional[Any] = None, + flow_rates: Optional[Sequence[Optional[float]]] = None, + *, + height_from: Optional[HeightFrom] = None, + follow_liquid: Optional[bool] = None, + minimum_height: Optional[float] = None, + z_speed: Optional[float] = None, + approach_height: Optional[float] = None, + settling_times: Optional[Sequence[float]] = None, + blow_out_air_volumes: Optional[Sequence[float]] = None, + pre_mixes: Optional[Sequence[Optional[Mix]]] = None, + mix_heights: Optional[MixHeights] = None, + transport_air_volumes: Optional[Sequence[float]] = None, + conditioning: Optional[Conditioning] = None, + tip_touch: Optional[TipTouch] = None, + cutoff_velocity: Optional[float] = None, + lls_sensitivity: Optional[int] = None, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Draw `volumes` (uL, one per channel) from `containers`, as Biomek's "S8 Pipetting" template + does (see `driver/liquid.py`): one batch per set of containers the probes reach in one move + (a shared container: the probes centred in it at the narrowest span). STAR's `Pipettes` + signature. + + Args: + containers: one per channel. + volumes: uL, one per channel. + use_channels: 0-indexed from the back (channel 0 is probe 1); the first ones when None. + resource_offsets: added to the targets, mm; one for every channel (the probes share X). + liquid_heights: mm from `height_from`, one per channel or one for all. + lld_mode: liquid-level sensing: None or OFF only, until it is built. + flow_rates: uL/s; the pumps move together, so one rate for all. + height_from: "bottom" (default), "top" or "liquid" (needs volume tracking). + follow_liquid: the tips follow the liquid down as it is drawn. + minimum_height: mm above the bottom no height goes below (Biomek's Minimum Height). + z_speed: mm/s of Z for the moves in the well (`default_z_speed`); above Z's maximum is + refused. + approach_height: mm above the top the probes come down to first. + settling_times: s after drawing (Biomek's aspirate delay), STAR's per-channel list. + blow_out_air_volumes: uL of air drawn above the well first, for a blowout; per channel. + transport_air_volumes: uL of air drawn after leaving the well (the trailing air gap); per + channel. The template applies one value to every probe, so the per-channel values must + agree. + pre_mixes: STAR's per-channel `Mix`es, one mix for every probe or None for all, mixed before + drawing (Biomek's Mix): `repetitions` times, draw and push back `volume` uL at `flow_rate` + uL/s, at `z_speed`; `auto_surface_following` follows the liquid while drawing and pushing + (Biomek's Follow Liquid). The tips must hold no liquid. + mix_heights: where the mix draws and pushes; the operation's own height when None. + conditioning: extra drawn and pushed back before leaving (Biomek's conditioning). + tip_touch: a touch-off before leaving. + cutoff_velocity: the pumps' cutoff velocity, uL/s (Biomek's technique; `CV`). + lls_sensitivity: the liquid-level sensors' sensitivity, set before each move measured from + the liquid (Biomek's conductivity; `SS`). + minimum_traverse_height_start / _end: as `pick_up_tips`. + + Raises: + NotImplementedError: for liquid-level sensing. + ValueError: for channels, containers or heights that cannot be worked out, or per-channel + values that differ. + """ + _no_lld(self, lld_mode) + settings = self._settings( + liquid_height=_one("liquid_heights", liquid_heights), height_from=height_from, + follow_liquid=follow_liquid, minimum_height=minimum_height, z_speed=z_speed, + approach_height=approach_height, settling_time=_one("settling_times", settling_times), + blow_out_air_volume=_one("blow_out_air_volumes", blow_out_air_volumes), + transport_air_volume=_one("transport_air_volumes", transport_air_volumes), + conditioning=conditioning, tip_touch=tip_touch, + ) # fmt: skip + settings = liquid.with_mix(settings, _one_mix("pre_mixes", pre_mixes), mix_heights) + await self._liquid( + "aspirate", containers, volumes, use_channels, resource_offsets, flow_rates, settings, + cutoff_velocity, lls_sensitivity, minimum_traverse_height_start, minimum_traverse_height_end, + ) # fmt: skip + + async def dispense( + self, + containers: Sequence[Container], + volumes: Sequence[float], + use_channels: Optional[Sequence[int]] = None, + resource_offsets: Optional[Sequence[Coordinate]] = None, + liquid_heights: Optional[Sequence[Optional[float]]] = None, + lld_mode: Optional[Any] = None, + flow_rates: Optional[Sequence[Optional[float]]] = None, + *, + height_from: Optional[HeightFrom] = None, + follow_liquid: Optional[bool] = None, + minimum_height: Optional[float] = None, + z_speed: Optional[float] = None, + approach_height: Optional[float] = None, + settling_times: Optional[Sequence[float]] = None, + post_mixes: Optional[Sequence[Optional[Mix]]] = None, + mix_heights: Optional[MixHeights] = None, + blow_out_air_volumes: Optional[Sequence[float]] = None, + blow_out_delay: Optional[float] = None, + tip_touch: Optional[TipTouch] = None, + empty: bool = False, + cutoff_velocity: Optional[float] = None, + lls_sensitivity: Optional[int] = None, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Push `volumes` (uL, one per channel) into `containers`, as Biomek's "S8 Pipetting" template + does; arguments as `aspirate`. The pumps stop at `SystemTrailingAirgap`. + + Args: + follow_liquid: the tips follow the liquid up as it fills. + post_mixes, mix_heights: mixed after dispensing, one `Mix` for every probe, as `aspirate`'s + `pre_mixes`; the tips must be left holding no liquid (Biomek: "The mix operation cannot + begin until tips are empty"). + blow_out_air_volumes: uL of air pushed out after the liquid (Biomek's blowout), then + `blow_out_delay` s. + empty: push out everything the tips hold, at the starting height (Biomek's Empty Tips). + + Raises: + NotImplementedError: for liquid-level sensing. + ValueError: for channels, containers or heights that cannot be worked out, more than a tip + holds, or per-channel values that differ. + """ + _no_lld(self, lld_mode) + settings = self._settings( + liquid_height=_one("liquid_heights", liquid_heights), height_from=height_from, + follow_liquid=follow_liquid, minimum_height=minimum_height, z_speed=z_speed, + approach_height=approach_height, settling_time=_one("settling_times", settling_times), + blow_out_air_volume=_one("blow_out_air_volumes", blow_out_air_volumes), + blow_out_delay=blow_out_delay, tip_touch=tip_touch, empty=empty, + ) # fmt: skip + settings = liquid.with_mix(settings, _one_mix("post_mixes", post_mixes), mix_heights) + await self._liquid( + "dispense", containers, volumes, use_channels, resource_offsets, flow_rates, settings, + cutoff_velocity, lls_sensitivity, minimum_traverse_height_start, minimum_traverse_height_end, + ) # fmt: skip + + +def _one(name: str, values: Optional[Sequence[Optional[float]]]) -> Optional[float]: + """The one value a per-channel argument (STAR's lists) gives every channel: the template applies + one value to all probes (one height measured the same way, one wait, one air volume).""" + given = {v for v in (values or []) if v is not None} + if len(given) > 1: + raise ValueError(f"{name}: one value for all channels, please (got {sorted(given)})") + return given.pop() if given else None + + +def _one_mix(name: str, mixes: Optional[Sequence[Optional[Mix]]]) -> Optional[Mix]: + """The one mix a per-channel list (STAR's `pre_mixes` / `post_mixes`) gives every probe: the + template mixes with all of them alike, so a mix on some channels only, or mixes that differ, are + refused.""" + given = set(mixes or []) + if len(given) > 1: + raise ValueError(f"{name}: one mix for all channels, or None for all, please (got {given})") + return given.pop() if given else None + + +def _no_lld(pipettes: Pipettes, lld_mode: Any) -> None: + if lld_mode is not None and getattr(lld_mode, "name", lld_mode) != "OFF": + raise NotImplementedError(f"{pipettes}: liquid-level sensing is not built yet") diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index 925d9e8c7c7..c30be5a973d 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -40,9 +40,11 @@ HOME_RECIPES, Homer, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver from pylabrobot.resources.resource import Resource logger = logging.getLogger(__name__) @@ -51,6 +53,12 @@ # driver was written against; whether that holds on every build is not established. POD_NUMBERS = {"left": 1, "right": 2} COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"} +# What each module type carries besides the pod's own axes, by the feature's name on `Pod`. The +# module type is what the board reports (Get Module ID, `protocol.MODULE_TYPES`); a new pod type is +# a new entry here and in the motor tables. +MODULE_FEATURES: Dict[str, Tuple[str, ...]] = { + "span8": ("pipettes",), +} # The axes that change what a pod takes up along the X rail. RAIL_AXES = ("X", "GR", "GG") # The gripper's axes; a move of these, or of the channels' Y or Z, is checked against the pod's own @@ -107,7 +115,8 @@ class Pod: Holds what every pod has: one board and its axes, moved together (`move_axes`, the Master Controller's `AM`), the position record the Master Controller keeps, homing, and the pod's pose on the shared X rail. `module_type` is what the board reports itself to be: `multichannel` (a - 96-channel head) or `span8` (eight independent channels). + 96-channel head) or `span8` (eight independent channels). What else the pod carries is its + features (`MODULE_FEATURES`): on a `span8`, its channels (`pipettes`). """ def __init__( @@ -126,6 +135,9 @@ def __init__( # What the instrument's declared configuration says about this pod: its conversions, travel # limits and geometry. None when nothing is declared for this side. self.declared = declared + # The driver this pod belongs to, set at discovery: what the features reach the deck and the + # declared deck positions through. None for a pod used on its own. + self.driver: Optional["BiomekI7Driver"] = None # The shared X rail, set by the driver once both pods are found. Every move that changes what # the pod takes up along it (X, the gripper's GR or GG) goes through it. self.rail: Optional[XRail] = None @@ -138,7 +150,7 @@ def __init__( # (position, adjusted); position None until read. Starts as after homing. self._cpositions: Dict[str, motion.CPos] = {a.name: (None, a.home_position) for a in self.axes} # The pumps' state, kept with the positions as the Master Controller keeps it in the Span-8's - # state record, because every pump move carries it. Each syringe + # state record, because every pump move carries it; set through `pipettes`. Each syringe # pump's valve as last set (None until then), and the cutoff velocity (`CV`), counts/s, # clamped to each pump's range when used. self._valves: Dict[str, Optional[p.Valve]] = {a.name: None for a in self.axes if a.is_pump} @@ -155,6 +167,9 @@ def __init__( self.default_minimum_traverse_height = units.to_mm(float(safe)) # Who follows the position record (`add_position_listener`). self._listeners: List[Callable[["Pod"], None]] = [] + # What the pod carries (STAR's arm features): what its module type has (`MODULE_FEATURES`). + features = MODULE_FEATURES.get(module_type, ()) + self.pipettes: Optional[Pipettes] = Pipettes(self) if "pipettes" in features else None @property def pod_number(self) -> int: @@ -350,7 +365,7 @@ def _own_state( if self.module_type == "span8": # Each probe's Y counts from its own narrowest place (`probe_y`), not probe 1's. v.update({n: d.probe_y(i, counts[n]) for i, n in enumerate(ys, 1)}) # type: ignore[arg-type] - lengths: Dict[str, float] = {} # no channel carries a tip + lengths = self._carried_tip_lengths() gripper = pc.GripperState(v["GY"], v["GZ"], v["GR"], v["GG"], self._held_labware) pipettor = pc.PipettorState( tuple(v[n] for n in ys), @@ -523,7 +538,8 @@ async def move_axes( Targets are in counts. On the Span-8 Z channels they are adjusted positions (the channel's hysteresis is added to downward moves, as Biomek does). Syringe pumps move through the valve - each was last set to, at the cutoff velocity last set, as the Master Controller carries both. + each was last set to (`pipettes.set_valves`), at the cutoff velocity last set (an aspirate's + or dispense's `cutoff_velocity`), as the Master Controller carries both. A move of X, GR or GG is checked against the other pod first (`driver/x_rail.py`). One that would run into it is refused, and nothing is sent. One crossing only the path of the other @@ -570,7 +586,9 @@ async def move_axes( axis = self.axis(name) axis.check_position(target) if axis.is_pump and self._valves[name] is None: - raise RuntimeError(f"{self}: {name}'s valve has not been set") + raise RuntimeError( + f"{self}: {name}'s valve has not been set; call `pipettes.set_valves` first" + ) stray = sorted({*forces, *sensors} - set(targets)) if stray: raise ValueError(f"{self}: a force or sensor on {stray}, which have no target") @@ -673,7 +691,8 @@ def _traverse_ceilings(self) -> Dict[str, float]: async def park(self) -> None: """Biomek's park (`_park`): the channels and the gripper raised, the pod to its park X and Y, - the gripper turned and closed to its park.""" + the gripper turned and closed to its park. A Span-8 parks over its wash station + (`pipettes.park`).""" await self._park() async def _park(self, over: Optional[Mapping[str, int]] = None) -> None: @@ -681,7 +700,8 @@ async def _park(self, over: Optional[Mapping[str, int]] = None) -> None: (`_traverse_ceilings`), the pod to the park X (`XMargin` in from its own end of the rail) and `Y`, the gripper turned and closed to its park (`GR`, `GY`, then `GG`). As logged after a prime (2026-10-09), to the count. `over`: X/Y targets (counts) for a pod whose park declares - none. Without either, it parks where it stands. + none; a Span-8 parks over its wash station (`pipettes.park`). Without either, it parks where + it stands. Raises: RuntimeError: without a declared configuration. @@ -762,8 +782,8 @@ async def _move_over( clearance: the lowest height the deck under the path allows, from the deck model (`BiomekI7._traverse_clearance`), if known. allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately. - tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, cm; none - when None. + tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, cm. The + pod's own record when None (`_carried_tip_lengths`). gripper_height: GZ (cm) to travel at. Default: its traverse height, no higher than clears the pod's own pipettor for the travel's GR (`_gripper_traverse_height`). @@ -778,7 +798,7 @@ async def _move_over( stray = sorted(set(targets) & set(channels)) if stray: raise ValueError(f"{self}: {stray} in a travel's targets; use z_final") - lengths = {} if tip_lengths is None else dict(tip_lengths) + lengths = self._carried_tip_lengths() if tip_lengths is None else dict(tip_lengths) await self._read_unknown_positions() area = self._travel_area(targets) need = g.obstacle_clearance(d.obstacles, *area) @@ -861,6 +881,14 @@ async def move_over( gripper_height=units.optional_cm(gripper_height), ) + def carried_tip_lengths(self) -> Dict[str, float]: + """Per channel Z axis carrying a tip, how far below the channel the tip ends, mm. + + Raises: + RuntimeError: for a carried tip whose length is not known. + """ + return {axis: units.to_mm(v) for axis, v in self._carried_tip_lengths().items()} + def traverse_heights(self) -> Dict[str, float]: """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default, mm of its bottom above the deck: its ceiling (`traverse_ceilings`), or @@ -871,6 +899,15 @@ def traverse_ceilings(self) -> Dict[str, float]: """The highest each Z-type axis travels, mm of its bottom above the deck (`_traverse_ceilings`).""" return {axis: units.to_mm(v) for axis, v in self._traverse_ceilings().items()} + def _carried_tip_lengths(self) -> Dict[str, float]: + """Per channel Z axis carrying a tip, how far below the channel the tip ends, cm: from the + head's or the probes' tip record. + + Raises: + RuntimeError: for a carried tip whose length is not known. + """ + return {} if self.pipettes is None else self.pipettes._carried_tip_lengths() + def _traverse_targets( self, minimum_traverse_height: Optional[float], tip_lengths: Mapping[str, float] ) -> Tuple[Dict[str, float], float, float]: @@ -914,7 +951,7 @@ async def _lift_channels( Raises: ValueError: for a height a channel cannot lift its tip to. Nothing is sent. """ - lengths = {} if tip_lengths is None else tip_lengths + lengths = self._carried_tip_lengths() if tip_lengths is None else tip_lengths heights, _, _ = self._traverse_targets(minimum_traverse_height, lengths) await self._read_unknown_positions() await self._raise_to({n: heights[n] for n in self.channel_z_axes}, speed) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid.py b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid.py new file mode 100644 index 00000000000..0602e9b9d8b --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid.py @@ -0,0 +1,517 @@ +"""Biomek's pipetting templates ("MC Pipetting", "S8 Pipetting" and their reservoir variants), as a +plan of moves both heads carry out. + +Biomek runs an aspirate or dispense as a template: a list of steps whose parameters are bound to +the technique (`=C__Height`, ...). The templates are project data, the same for both heads, and +what follows reproduces every aspirate and dispense Biomek logged: + +- aspirate: to 1 mm above the top (100 %; the reservoir variants carry their X offset in this move, + the Span-8's goes to 10 mm); the leading air gap for a blowout; the mix; down to the height (at the + technique's Z speed); aspirate the volume + the conditioning, the tip following the liquid down + when asked (`AspirateDelay` after); dispense each conditioning section back (`DispenseDelay` after + each); the tip touch; up to 1 mm above the top (Z speed); the trailing air gap; +- dispense: to the approach; down to the height; dispense, following the liquid up when asked (or, + emptying, everything at the starting height); the mix; when the well's contents are known, up to + 2 mm above the liquid (Z speed); the blowout; the tip touch; up to 1 mm above the top (Z speed). + +The mix (the template's Mix step, when asked): its count of cycles, each to the draw height, draw +the mix volume, to the push height, push it back, both at the mix's flow rate, with no waits; its +moves at the operation's Z speed, a move to where the tips already are not sent; while drawing and +pushing the tips follow the liquid when asked, as the operation's own draw does. + +Heights: mm from the bottom, the top (+ the well's depth) or the liquid (+ its level, +refused when the contents are not known), then at least `minimum_height` mm above the bottom. Any +PyLabRobot container works, through PyLabRobot's interface only (`ContainerShape`): the bottom is its +cavity bottom, the level comes from the volume its tracker holds through its +`compute_height_from_volume` (needed only for heights from the liquid and for following, as Biomek +needs known amounts). Following moves the tip by the level's change. A tip touch goes out the given distance in direction theta (Biomek's angle +360 - theta degrees: 90 is -Y) and back; without a distance, to the container's top +outline less the tip's widest radius; one move for all the channels, measured at the last one, as +Biomek's logged touch-offs are. (Biomek's own distance, the wall at the touch height less its +tip's cone at the rim, is `labware.biomek_touch_distance`.) + +This module plans; it moves nothing. Heights are Biomek's: cm above the deck, of the channel's +bottom (the tip end + the tip's length); volumes are uL in the tip. +""" + +import dataclasses +import math +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7.techniques import Conditioning, MixHeights, TipTouch +from pylabrobot.beckman_coulter.biomek_i7.units import fraction_to_field +from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.resources.container import Container +from pylabrobot.resources.tip import Tip +from pylabrobot.resources.volume_tracker import does_volume_tracking +from pylabrobot.resources.well import CrossSectionType + +APPROACH_ABOVE_TOP = 1.0 # mm: every template's approach (the Span-8 reservoir variant's is 10) +MIX_EMPTY_TOLERANCE = 1e-3 # uL a tip may hold and count as empty for a mix +EXIT_ABOVE_TOP = 1.0 # mm: every template leaves to here +ABOVE_LIQUID = 2.0 # mm: where a dispense rises to when the contents are known +FULL_SPEED = 1000 + + +class ContainerShape: + """What the templates need of a container, in Biomek's cm, from PyLabRobot's interface: the depth + from its cavity bottom, the liquid's height for a volume, the wall's distance from its axis.""" + + def __init__(self, container: Container): + self.container = container + self.floor = _material_z_thickness(container) # mm from the resource's bottom to the cavity's + self.depth = (container.get_size_z() - self.floor) / 10 + + def height(self, volume: float) -> float: + """The liquid's height above the cavity bottom, cm, for `volume` uL. + + Raises: + ValueError: for a container without a height <-> volume function. + """ + if not self.container.supports_compute_height_volume_functions(): + raise ValueError( + f"{self.container.name} has no height <-> volume function: heights from the liquid and " + "following need one" + ) + return self.container.compute_height_from_volume(volume) / 10 + + def wall_distance(self, z: float, angle: float) -> float: + """How far, cm, the wall is from the container's axis `z` cm above its cavity bottom, in + direction `angle` (radians, Biomek's X/Y). The cross-section's area there is the volume + function's slope (dV/dh, as the Prep driver builds its segments), shaped like the top outline + (round, or a box of the top's proportions); without a volume function, the top outline.""" + hx, hy = self.container.get_size_x() / 20, self.container.get_size_y() / 20 + circle = getattr(self.container, "cross_section_type", None) == CrossSectionType.CIRCLE + area = self._area(z * 10) + if area is not None: + if circle: + return math.sqrt(area / math.pi) / 10 + scale = math.sqrt(area / (4 * hx * hy * 100)) # mm2 over the top's area + hx, hy = hx * scale, hy * scale + elif circle: + return min(hx, hy) + c, s = abs(math.cos(angle)), abs(math.sin(angle)) + return min(hx / c if c > 1e-12 else math.inf, hy / s if s > 1e-12 else math.inf) + + def _area(self, z: float) -> Optional[float]: + """The cross-section's area, mm2, `z` mm above the cavity bottom, from the volume function; None + without one, or where it gives no area.""" + if not self.container.supports_compute_height_volume_functions(): + return None + depth = self.depth * 10 + low, high = max(0.0, min(z, depth) - 0.05), min(depth, max(z, 0.0) + 0.05) + if high <= low: + return None + try: + area = ( + self.container.compute_volume_from_height(high) + - self.container.compute_volume_from_height(low) + ) / (high - low) + except ValueError: + return None + return area if area > 0 else None + + +def _material_z_thickness(container: Container) -> float: + try: + return float(container.material_z_thickness) + except NotImplementedError: + return 0.0 + + +@dataclass(frozen=True) +class Channel: + """One channel's part of an operation: its container's shape, the Biomek cm of its cavity bottom for + this channel, the tip (length below the channel, widest radius, cm), the uL to move and what the + container holds (None: not known).""" + + name: str # the channel's Z axis on a Span-8, the mandrel on the 96-head + well: ContainerShape + bottom: float + tip_length: float + volume: float + held: Optional[float] + tip_radius: float = 0.0 + share: int = 1 # channels drawing on the same well at once (a reservoir under the 96-head) + + +@dataclass(frozen=True) +class Settings: + """An operation's arguments, in the template's units (mm, the speed field, uL/s, s): the + features convert their own (`z_speed`, mm/s) into these at their entry (`units.py`).""" + + liquid_height: float = 0.0 + height_from: str = "bottom" + follow_liquid: bool = False + minimum_height: float = 0.0 + z_speed_field: int = 1000 + approach_height: float = APPROACH_ABOVE_TOP + settling_time: float = 0.0 + blow_out_air_volume: float = 0.0 + blow_out_delay: float = 0.0 + transport_air_volume: float = 0.0 + conditioning: Conditioning = field(default_factory=Conditioning) + tip_touch: Optional[TipTouch] = None + empty: bool = False + mix: Optional["MixSettings"] = None + + +@dataclass(frozen=True) +class MixSettings: + """The template's Mix step: `repetitions` times, to the draw height (mm from its `from`), draw + `volume` uL, to the push height, push it back, both at `flow_rate` uL/s; the tips follow the + liquid while drawing and pushing when `follow`. Its moves go at the operation's Z speed.""" + + volume: float + repetitions: int + flow_rate: float + aspirate_height: float + aspirate_height_from: str + dispense_height: float + dispense_height_from: str + follow: bool = False + + +def settings(base: Settings, **given: object) -> Settings: + """`base` with every argument given (not None) in its place.""" + return dataclasses.replace(base, **{k: v for k, v in given.items() if v is not None}) # type: ignore[arg-type] + + +def with_mix(s: Settings, mix: Optional[Mix], heights: Optional[MixHeights]) -> Settings: + """`s` with PyLabRobot's `mix` as the template's Mix, at `heights` (the operation's own height + when None). Its `auto_surface_following` is Biomek's following during the mix. + + Raises: + ValueError: for a negative volume or repetition count (Biomek's "Mix count cannot be negative"). + NotImplementedError: for a `surface_following_distance`: Biomek follows by the level only. + """ + if mix is None: + return dataclasses.replace(s, mix=None) + if mix.repetitions < 0: + raise ValueError(f"mix count cannot be negative (got {mix.repetitions})") + if mix.volume < 0: + raise ValueError(f"a mix volume cannot be negative (got {mix.volume})") + if mix.surface_following_distance: + raise NotImplementedError( + "a mix follows the liquid by what each draw moves it (auto_surface_following), not a " + "surface_following_distance" + ) + if heights is None: + heights = MixHeights(s.liquid_height, s.height_from) # type: ignore[arg-type] + push = heights.aspirate_height if heights.dispense_height is None else heights.dispense_height + push_from = heights.dispense_height_from or heights.aspirate_height_from + return dataclasses.replace( + s, + mix=MixSettings( + volume=float(mix.volume), + repetitions=int(mix.repetitions), + flow_rate=float(mix.flow_rate), + aspirate_height=float(heights.aspirate_height), + aspirate_height_from=heights.aspirate_height_from, + dispense_height=float(push), + dispense_height_from=push_from, + follow=mix.auto_surface_following, + ), + ) + + +def check_tips_empty_for_mix( + owner: object, tips: Sequence[Optional[Tip]], leaving: Sequence[float], s: Settings +) -> None: + """Biomek's rule for a mix: the tips hold no liquid when it starts (air only), checked from the + tips' trackers when volume tracking is on, `leaving` uL of each tip going out first (the + dispense). + + Raises: + ValueError: for a tip still holding liquid ("The mix operation cannot begin until tips are + empty"). + """ + if not does_volume_tracking() or s.empty: + return + for tip, out in zip(tips, leaving): + if tip is None: + continue + left = tip.tracker.get_used_volume() - out + if left > MIX_EMPTY_TOLERANCE: + raise ValueError( + f"{owner}: the mix cannot begin until the tips are empty; a tip would hold {left:.3f} uL" + ) + + +@dataclass(frozen=True) +class ZMove: + """Channels' bottoms to these heights (cm). `liquid` when measured from the liquid (the Span-8 + sets its sensors' sensitivity first).""" + + z: Dict[str, float] + speed: int + liquid: bool = False + + +@dataclass(frozen=True) +class PlungerMove: + """Each channel's plunger by this many uL (+ draws, - pushes), at `flow_rate` uL/s; the bottoms + to `z` at the same time (following the liquid); then `delay` s.""" + + volume: Dict[str, float] + flow_rate: float + z: Dict[str, float] = field(default_factory=dict) + delay: float = 0.0 + empty: bool = False # push out everything the tip holds + + +@dataclass(frozen=True) +class Touch: + """Out by (dx, dy) cm in Biomek's frame and back, at speed field `speed`; then `delay` s. `above_bottom`: + where the last channel's tip end is (a Span-8 batch's highest-numbered probe), cm over its cavity + bottom: the touch-off is measured there.""" + + dx: float + dy: float + speed: int + delay: float = 0.0 + above_bottom: float = 0.0 + + +Step = Union[ZMove, PlungerMove, Touch] + + +def level(c: Channel, held: Optional[float]) -> Optional[float]: + """The liquid's height above the bottom, cm, for `held` uL in the well (None: not known).""" + return None if held is None else c.well.height(held) + + +def height_above_bottom( + c: Channel, height: float, height_from: str, held: Optional[float], minimum: float +) -> float: + """A template height (mm from the bottom, top or liquid) as cm above the well's bottom, at least + `minimum` mm. + + Raises: + ValueError: for a height from the liquid in a well whose contents are not known (Biomek's + "Cannot move relative to liquid level if liquid amounts are not defined"). + """ + if height_from == "bottom": + z = height / 10 + elif height_from == "top": + z = height / 10 + c.well.depth + elif height_from == "liquid": + surface = level(c, held) + if surface is None: + raise ValueError( + f"{c.name}: cannot move relative to the liquid level; the well's contents are not known" + ) + z = height / 10 + surface + else: + raise ValueError(f"height_from must be bottom, top or liquid, not {height_from!r}") + return max(z, minimum / 10) + + +def _z(c: Channel, above_bottom: float) -> float: + return c.bottom + above_bottom + c.tip_length + + +def touch_offset(c: Channel, above_bottom: float, touch: TipTouch) -> Tuple[float, float]: + """(dx, dy), cm, of a touch-off with the tip end `above_bottom` cm over the bottom: its + `distance`, else the container's top outline less the tip's widest radius, in the direction + (360 - theta) degrees. (0, 0) where that leaves no room, as Biomek moves nowhere. + """ + angle = math.radians(360.0 - touch.theta) + if touch.distance is not None: + r = touch.distance / 10 + else: + r = c.well.wall_distance(above_bottom, angle) - c.tip_radius + if r <= 0: + return 0.0, 0.0 + return round(math.cos(angle) * r, 6), round(math.sin(angle) * r, 6) + + +def _touch( + channels: Sequence[Channel], s: Settings, held: Dict[str, Optional[float]] +) -> List[Step]: + t = s.tip_touch + if t is None: + return [] + # One move for every channel, measured at the last one (a Span-8 batch's highest-numbered probe), + # as every logged Biomek touch-off is: where the channels stand at different heights, the others + # reach further or less far than their own wells' room, as they do under Biomek. + last = channels[-1] + zs = { + c.name: _z(c, height_above_bottom(c, t.height, t.height_from, held[c.name], s.minimum_height)) + for c in channels + } + above = zs[last.name] - last.bottom - last.tip_length + dx, dy = touch_offset(last, above, t) + return [ + ZMove(zs, fraction_to_field(t.speed_fraction), liquid=t.height_from == "liquid"), + Touch(dx, dy, fraction_to_field(t.speed_fraction), t.delay, above), + ] + + +def _top(c: Channel, mm: float) -> float: + return _z(c, c.well.depth + mm / 10) + + +def _mix( + channels: Sequence[Channel], s: Settings, held: Dict[str, Optional[float]], at: Dict[str, float] +) -> List[Step]: + """The Mix step's moves, the channels' bottoms at `at` (cm) over wells holding `held` uL: each + cycle to the draw height, draw, to the push height, push. A move to where the channels already + are is not sent (Biomek sends none: logged mixes at the dispense height have no Z moves).""" + m = s.mix + if m is None: + return [] + steps: List[Step] = [] + where, contents = dict(at), dict(held) + for _ in range(m.repetitions): + for sign, height, height_from in ( + (1, m.aspirate_height, m.aspirate_height_from), + (-1, m.dispense_height, m.dispense_height_from), + ): + target = { + c.name: _z( + c, height_above_bottom(c, height, height_from, contents[c.name], s.minimum_height) + ) + for c in channels + } + if any(abs(target[n] - where[n]) > 1e-9 for n in target): + steps.append(ZMove(target, s.z_speed_field, height_from == "liquid")) + where = target + after = { + c.name: None + if contents[c.name] is None + else max(contents[c.name] - sign * m.volume * c.share, 0.0) # type: ignore[operator] + for c in channels + } + follow: Dict[str, float] = {} + if m.follow: + for c in channels: + before, now = level(c, contents[c.name]), level(c, after[c.name]) + if before is not None and now is not None: + start = where[c.name] - c.bottom - c.tip_length + follow[c.name] = _z(c, max(start + now - before, s.minimum_height / 10)) + steps.append(PlungerMove({c.name: sign * m.volume for c in channels}, m.flow_rate, z=follow)) + where = {**where, **follow} + contents = after + return steps + + +def plan_aspirate(channels: Sequence[Channel], s: Settings, flow_rate: float) -> List[Step]: + """The template's moves for an aspirate. + + Raises: + ValueError: for a height that cannot be worked out (see `height_above_bottom`). + """ + held = {c.name: c.held for c in channels} + approach = {c.name: _top(c, s.approach_height) for c in channels} + steps: List[Step] = [ZMove(approach, FULL_SPEED)] + if s.blow_out_air_volume > 0: + steps.append( + PlungerMove( + {c.name: s.blow_out_air_volume for c in channels}, flow_rate, delay=s.settling_time + ) + ) + steps += _mix(channels, s, held, approach) + start = { + c.name: height_above_bottom(c, s.liquid_height, s.height_from, held[c.name], s.minimum_height) + for c in channels + } + steps.append( + ZMove( + {c.name: _z(c, start[c.name]) for c in channels}, s.z_speed_field, s.height_from == "liquid" + ) + ) + drawn = {c.name: c.volume + s.conditioning.extra for c in channels} + after = { + c.name: None if held[c.name] is None else max(held[c.name] - drawn[c.name] * c.share, 0.0) # type: ignore[operator] + for c in channels + } + follow: Dict[str, float] = {} + if s.follow_liquid: + for c in channels: + before, now = level(c, held[c.name]), level(c, after[c.name]) + if before is not None and now is not None: + end = max(start[c.name] + now - before, s.minimum_height / 10) + follow[c.name] = _z(c, end) + steps.append(PlungerMove(drawn, flow_rate, z=follow, delay=s.settling_time)) + for _ in range(s.conditioning.sections): + steps.append( + PlungerMove( + {c.name: -s.conditioning.section_volume for c in channels}, + s.conditioning.flow_rate or flow_rate, + delay=s.conditioning.delay, + ) + ) + for c in channels: + if after[c.name] is not None: + after[c.name] += s.conditioning.section_volume * c.share # type: ignore[operator] + steps += _touch(channels, s, after) + steps.append(ZMove({c.name: _top(c, EXIT_ABOVE_TOP) for c in channels}, s.z_speed_field)) + if s.transport_air_volume > 0: + steps.append( + PlungerMove( + {c.name: s.transport_air_volume for c in channels}, flow_rate, delay=s.settling_time + ) + ) + return steps + + +def plan_dispense(channels: Sequence[Channel], s: Settings, flow_rate: float) -> List[Step]: + """The template's moves for a dispense. + + Raises: + ValueError: for a height that cannot be worked out (see `height_above_bottom`). + """ + held = {c.name: c.held for c in channels} + steps: List[Step] = [ZMove({c.name: _top(c, s.approach_height) for c in channels}, FULL_SPEED)] + start = { + c.name: height_above_bottom(c, s.liquid_height, s.height_from, held[c.name], s.minimum_height) + for c in channels + } + steps.append( + ZMove( + {c.name: _z(c, start[c.name]) for c in channels}, s.z_speed_field, s.height_from == "liquid" + ) + ) + after = { + c.name: None if held[c.name] is None else held[c.name] + c.volume * c.share # type: ignore[operator] + for c in channels + } + follow: Dict[str, float] = {} + if s.follow_liquid and not s.empty: + for c in channels: + before, now = level(c, held[c.name]), level(c, after[c.name]) + if before is not None and now is not None: + follow[c.name] = _z(c, max(start[c.name] + now - before, s.minimum_height / 10)) + steps.append( + PlungerMove( + {c.name: -c.volume for c in channels}, + flow_rate, + z=follow, + delay=s.settling_time, + empty=s.empty, + ) + ) + at = {c.name: follow.get(c.name, _z(c, start[c.name])) for c in channels} + steps += _mix(channels, s, after, at) + if all(after[c.name] is not None for c in channels): + steps.append( + ZMove( + { + c.name: _z(c, height_above_bottom(c, ABOVE_LIQUID, "liquid", after[c.name], 0.0)) + for c in channels + }, + s.z_speed_field, + liquid=True, + ) + ) + if s.blow_out_air_volume > 0 and not s.empty: + steps.append( + PlungerMove( + {c.name: -s.blow_out_air_volume for c in channels}, flow_rate, delay=s.blow_out_delay + ) + ) + steps += _touch(channels, s, after) + steps.append(ZMove({c.name: _top(c, EXIT_ABOVE_TOP) for c in channels}, s.z_speed_field)) + return steps diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py new file mode 100644 index 00000000000..ceac9ec7d41 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py @@ -0,0 +1,331 @@ +"""Aspirate and dispense on the Span-8 on the simulator, on the deck of a method Biomek's logs ran +(2026-10-20, a dilution): the logged method's technique values given as arguments, the moves sent +compared with the Master Controller's own log of that run.""" + +from typing import Dict, List, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.driver import liquid +from pylabrobot.beckman_coulter.biomek_i7.driver.liquid import ( + ContainerShape, + PlungerMove, + Touch, + ZMove, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import ( + biomek_labware, + biomek_tip, + biomek_touch_distance, +) +from pylabrobot.beckman_coulter.biomek_i7.techniques import MixHeights, TipTouch +from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.resources import Coordinate, cor_96_wellplate_360uL_Fb, set_volume_tracking +from pylabrobot.resources.beckman_coulter import BiomekWell + +# The Span-8's eight probes from the reservoir (the "S8 Pipetting Reservoir Offset Aspirate" +# template: 10 mm approach), then probe 1 into A1 of the plate the 96-head filled. +LOGGED_SPAN8_ASPIRATE = [ + "AM 2047 1000 0 -180729 105210 0 -58375 -58221 -58381 -58710 -58545 -58312 -58272 -58330", + "AM 2040 300 0 -80273 -80120 -80280 -80609 -80444 -80211 -80171 -80229", + "AM 522240 52 0 3516 3509 3401 3312 3118 3528 2472 3566", + "AM 2040 300 0 -62716 -62562 -62722 -63051 -62886 -62653 -62613 -62671", +] +LOGGED_SPAN8_DISPENSE = [ + "AM 8 1000 0 -74227", + "AM 8 300 0 -77040", # at the liquid's surface (SS before) + "AM 2056 52 0 -75826 480", # following up + "AM 8 300 0 -74862", # 2 mm above the liquid (SS before) + "AM 8 1000 0 -76309", # touch: liquid - 1 mm (SS before) + "AM 7 1000 0 -230264 152817 0", + "AM 7 1000 0 -230264 154304 0", + "AM 8 300 0 -74227", +] +# 2026-09-22 13.45 (a transfection method): probes 5-8 dispense 190 uL into A2-D2 of the +# Thomson 24-well plate at P6, 3 mm from the bottom, then mix 3 x 150 uL at 200 uL/s, drawing 5 mm +# and pushing 15 mm from the bottom, at the step's 25 % (Biomek did not know the plate's amounts: no +# move 2 mm above the liquid; the blowout has nothing left above the system air gap to push). +LOGGED_SPAN8_MIX = [ + "AM 1920 1000 0 -59975 -59742 -59702 -59760", # 1 mm above the top + "AM 1920 250 0 -78304 -78071 -78031 -78089", # 3 mm above the bottom + "AM 491520 103 0 480 480 480 480", # 190 uL at 100 uL/s + *[ + "AM 1920 250 0 -77339 -77106 -77066 -77124", # the draw's 5 mm + "AM 491520 207 0 4080 4080 4080 4080", # 150 uL at 200 uL/s + "AM 1920 250 0 -72516 -72283 -72243 -72301", # the push's 15 mm + "AM 491520 207 0 480 480 480 480", + ] + * 3, + "AM 1920 250 0 -59975 -59742 -59702 -59760", # 1 mm above the top +] +SPAN8_VOLUMES = [146.5, 146.2, 141.7, 138, 129.9, 147, 103, 148.6] # D after, uL; 20 before + + +SPAN8_SLOTS = ["X", "Y", "S"] + [f"Z{n}" for n in range(1, 9)] + [f"D{n}" for n in range(1, 9)] + + +def parse_span8(command: str) -> Tuple[Dict[str, int], int]: + f = [int(x) for x in command.split()[1:]] + mask, speed, values = f[0], f[1], iter(f[3:]) + return {n: next(values) for i, n in enumerate(SPAN8_SLOTS) if mask & (1 << i)}, speed + + +class LiquidTests(PodMoveTest): + async def setup_deck(self): # type: ignore[no-untyped-def] + set_volume_tracking(True) + self.addCleanup(set_volume_tracking, False) + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + place_labware( + lh.deck, + [ + {"position": "P8", "class": "ThermoNUNC_350CB", "name": "Reservoir"}, + {"position": "P6", "class": "Thermo96VB_PP", "name": "Plate"}, + ], + ) + reservoir = lh.deck.get_resource("Reservoir").get_item(0) # type: ignore[attr-defined] + reservoir.tracker.set_volume(reservoir.max_volume) + # As after Biomek's Home All and `setup()`: the right gripper parked (GR 90, GY 48), its + # fingers out of the probes' way. + right = self.pod(driver, "right") + park = right.declared.park # type: ignore[union-attr] + await right.move_axes({a: right.declared.to_counts(a, park[a]) for a in ("GR", "GY")}) # type: ignore[union-attr] + return driver, lh + + def record(self, driver, side: str) -> List[Tuple[Dict[str, int], int]]: # type: ignore[no-untyped-def] + pod = self.pod(driver, side) + moves: List[Tuple[Dict[str, int], int]] = [] + original = pod.move_axes + + async def move_axes(targets, speed=1000, **kwargs): # type: ignore[no-untyped-def] + moves.append((dict(targets), speed)) + return await original(targets, speed, **kwargs) + + pod.move_axes = move_axes # type: ignore[method-assign, assignment] + return moves + + def after_travel(self, moves): # type: ignore[no-untyped-def] + """The moves after the X/Y travel (`_move_over` lifts first, then moves X/Y alone).""" + travel = max(i for i, (t, _) in enumerate(moves) if "X" in t and not any("Z" in k for k in t)) + return [m for m in moves[travel + 1 :] if not set(m[0]) <= {"Z", "GZ"} or m[1] != 1000][:99] + + async def test_the_span8s_logged_transfer(self) -> None: + driver, lh = await self.setup_deck() + pipettes = lh.pipettes + pipettes._set_tips({n: biomek_tip("T190F", "t") for n in range(1, 9)}) + # As logged: the left pod's gripper turned to 90 degrees and the pod at X 12.701, clear of P6. + left = self.pod(driver, "left") + await left.move_axes({"GR": left.declared.to_counts("GR", 90)}) # type: ignore[union-attr] + await left.move_axes({"X": 5586, "Y": 58890}) + plate = lh.deck.get_resource("Plate") + plate.get_well("A1").tracker.set_volume(200) # the 96-head's dispense before + moves = self.record(driver, "right") + reservoir = lh.deck.get_resource("Reservoir").get_item(0) + await pipettes.aspirate( + [reservoir] * 8, [v - 20 for v in SPAN8_VOLUMES], resource_offsets=[Coordinate(-2, 0, 0)] * 8, + liquid_heights=[2.0] * 8, flow_rates=[50] * 8, z_speed=109.3, settling_times=[0.2] * 8, + approach_height=10, + ) # fmt: skip + start = next(i for i, (t, _) in enumerate(moves) if "S" in t and "Z1" in t) + self.assertEqual(moves[start : start + 4], [parse_span8(c) for c in LOGGED_SPAN8_ASPIRATE]) + moves.clear() + sensed = self.usb(driver, "span8").requests.copy() + await pipettes.dispense( + [plate.get_well("A1")], [SPAN8_VOLUMES[0] - 20], use_channels=[0], liquid_heights=[0.0], + height_from="liquid", follow_liquid=True, flow_rates=[50], z_speed=109.3, + tip_touch=TipTouch(height=-1.0, height_from="liquid", theta=90, speed_fraction=1.0, distance=3.1563), + ) # fmt: skip + first = next( + i for i, (t, _) in enumerate(moves) if t == parse_span8(LOGGED_SPAN8_DISPENSE[0])[0] + ) + self.assertEqual(moves[first : first + 8], [parse_span8(c) for c in LOGGED_SPAN8_DISPENSE]) + self.assertGreater(len(self.usb(driver, "span8").requests), len(sensed)) + self.assertAlmostEqual(plate.get_well("A1").tracker.get_used_volume(), 200 + 126.5) + + async def test_a_batchs_touch_off_is_measured_at_its_last_probe(self) -> None: + # One touch-off moves every probe of a batch; Biomek's logged touch-offs (e.g. 2026-10-20's + # dilution, where the probes followed different amounts up) are measured at the batch's last + # probe, and the others reach as far. + driver, lh = await self.setup_deck() + pipettes = lh.pipettes + pipettes._set_tips({n: biomek_tip("T190F", "t") for n in range(1, 9)}) + plate = lh.deck.get_resource("Plate") + wells = [plate.get_well("A1"), plate.get_well("B1")] + wells[0].tracker.set_volume(20) + wells[1].tracker.set_volume(120) + settings = pipettes._settings( + liquid_height=0.0, height_from="liquid", follow_liquid=True, + tip_touch=TipTouch(height=-1.0, height_from="liquid", theta=90), + ) # fmt: skip + (plan,) = pipettes.plan_liquid("dispense", wells, [30, 30], [0, 1], settings, 50) + self.assertEqual([p for p, _ in plan.pairs], [1, 2]) + touch = next(s for s in plan.steps if isinstance(s, Touch)) + at = plan.steps[plan.steps.index(touch) - 1] # the move to the touch height + assert isinstance(at, ZMove) + heights = {c.name: at.z[c.name] - c.bottom - c.tip_length for c in plan.channels} + first, last = plan.channels + self.assertAlmostEqual(touch.above_bottom, heights[last.name], places=9) + self.assertNotAlmostEqual(heights[first.name], heights[last.name], places=3) + t = settings.tip_touch + assert t is not None + self.assertEqual((touch.dx, touch.dy), liquid.touch_offset(last, heights[last.name], t)) + self.assertNotEqual((touch.dx, touch.dy), liquid.touch_offset(first, heights[first.name], t)) + + async def test_a_liquid_height_needs_known_contents(self) -> None: + driver, lh = await self.setup_deck() + set_volume_tracking(False) + lh.pipettes._set_tips({1: biomek_tip("T190F", "t")}) + with self.assertRaisesRegex(ValueError, "liquid level"): + await lh.pipettes.dispense( + [lh.deck.get_resource("Plate").get_well("A1")], [10], liquid_heights=[0.0], + height_from="liquid", + ) # fmt: skip + + def test_biomeks_touch_off_distance(self) -> None: + # Biomek's distance: the wall at the touch height less the tip's cone where it crosses the rim. + well = biomek_labware("Thermo96VB_PP", "p").get_well("A1") + t1025f, t190f = biomek_tip("T1025F", "t"), biomek_tip("T190F", "t") + self.assertAlmostEqual(biomek_touch_distance(well, t1025f, 3.67) or 0.0, 2.7532, places=3) + self.assertAlmostEqual(biomek_touch_distance(well, t190f, 7.184) or 0.0, 3.1563, places=3) + self.assertEqual(biomek_touch_distance(well, t190f, 0.2), 0.0) # in the cone: no room + native = cor_96_wellplate_360uL_Fb("n").get_well("A1") + self.assertIsNone(biomek_touch_distance(native, t190f, 3.0)) # not Biomek's labware + + def test_wall_from_the_volume_function(self) -> None: + # The wall at a height is the volume function's slope (an area) in the top outline's shape: for + # a cone-bottomed round well it is Biomek's segment wall; for a round bottom under a square top + # PyLabRobot's one cross-section shape reads it as a square, a little inside the wall. + for name, low in (("Thermo96VB_PP", False), ("Thomson_24w_Square_RB", True)): + well = biomek_labware(name, "p").get_well("A1") + shape = ContainerShape(well) + assert isinstance(well, BiomekWell) + for z in (0.1, 0.3, 0.6, 0.9 * shape.depth): + ours, biomeks = shape.wall_distance(z, 0.0), well.wall_distance(z * 10, 0.0) / 10 + if low: + self.assertLessEqual(ours, biomeks + 1e-6) + else: + self.assertAlmostEqual(ours, biomeks, delta=0.001) + + async def test_the_span8s_logged_mix(self) -> None: + driver, lh = await self.setup_deck() + set_volume_tracking(False) # as Biomek, which did not know the plate's amounts + lh.deck.get_resource("Plate").unassign() + place_labware( + lh.deck, [{"position": "P6", "class": "Thomson_24w_Square_RB", "name": "Culture"}] + ) + left = self.pod(driver, "left") + await left.move_axes({"GR": left.declared.to_counts("GR", 90)}) # type: ignore[union-attr] + await left.move_axes({"X": 5586, "Y": 58890}) + pipettes, right = lh.pipettes, self.pod(driver, "right") + pipettes._set_tips({n: biomek_tip("T190F", "t") for n in range(1, 9)}) + await pipettes.set_valves({f"D{n}": "output" for n in range(1, 9)}) + held = {f"D{n}": 20.0 if n < 5 else 210.0 for n in range(1, 9)} + await right.move_axes({a: right.declared.to_counts(a, v) for a, v in held.items()}) # type: ignore[union-attr] + plate = lh.deck.get_resource("Culture") + moves = self.record(driver, "right") + mix = Mix(volume=150, repetitions=3, flow_rate=200) + await pipettes.dispense( + [plate.get_well(w) for w in ("A2", "B2", "C2", "D2")], [190] * 4, use_channels=[4, 5, 6, 7], + liquid_heights=[3.0] * 4, flow_rates=[100] * 4, z_speed=units.field_to_rate(right, "Z1", 250), + post_mixes=[mix] * 4, mix_heights=MixHeights(5.0, "bottom", 15.0, "bottom"), + ) # fmt: skip + first = next(i for i, (t, _) in enumerate(moves) if t == parse_span8(LOGGED_SPAN8_MIX[0])[0]) + self.assertEqual( + moves[first : first + len(LOGGED_SPAN8_MIX)], [parse_span8(c) for c in LOGGED_SPAN8_MIX] + ) + + async def test_a_mix_in_the_aspirate_template(self) -> None: + # The aspirate's mix comes after the blowout air and before the descent, at its own heights; + # moves measured from the liquid set the sensors first (`liquid`). + driver, lh = await self.setup_deck() + pipettes = lh.pipettes + pipettes._set_tips({1: biomek_tip("T190F", "t")}) + well = lh.deck.get_resource("Plate").get_well("A1") + well.tracker.set_volume(200) + settings = pipettes._settings(liquid_height=1.0, blow_out_air_volume=10.0) + mixed = liquid.with_mix(settings, Mix(25, 2, 50), MixHeights(-2.0, "liquid")) + plain = pipettes.plan_liquid("aspirate", [well], [20], [0], settings, 50)[0].steps + steps = pipettes.plan_liquid("aspirate", [well], [20], [0], mixed, 50)[0].steps + self.assertEqual(steps[:2], plain[:2]) # approach, blowout air + self.assertEqual(steps[2 + 8 :], plain[2:]) # descent, draw, exit + cycle = steps[2:6] + to_draw, draw, to_push, push = cycle + assert isinstance(to_draw, ZMove) and isinstance(to_push, ZMove) + assert isinstance(draw, PlungerMove) and isinstance(push, PlungerMove) + self.assertTrue(to_draw.liquid and to_push.liquid) + self.assertEqual((draw.volume, push.volume), ({"Z1": 25}, {"Z1": -25})) + self.assertEqual((draw.z, push.z), ({}, {})) + # The push is measured from the level the draw left: 25 uL lower. + shape = ContainerShape(well) + self.assertAlmostEqual( + to_draw.z["Z1"] - to_push.z["Z1"], shape.height(200) - shape.height(175), places=9 + ) + self.assertEqual(steps[6:10], cycle) # the second cycle as the first + self.assertAlmostEqual(well.tracker.get_used_volume(), 200) # planning books nothing + # Following, the tips end each draw and push where the next push and draw are measured: only + # the first move to the mix's height is sent. + following = liquid.with_mix( + settings, Mix(25, 2, 50, auto_surface_following=True), MixHeights(-2.0, "liquid") + ) + steps = pipettes.plan_liquid("aspirate", [well], [20], [0], following, 50)[0].steps + self.assertEqual(steps[2], to_draw) + moves = steps[3:7] + assert all(isinstance(m, PlungerMove) for m in moves) + self.assertEqual([m.volume["Z1"] for m in moves], [25, -25, 25, -25]) # type: ignore[union-attr] + self.assertAlmostEqual(moves[0].z["Z1"], to_push.z["Z1"], places=9) # type: ignore[union-attr] + self.assertAlmostEqual(moves[1].z["Z1"], to_draw.z["Z1"], places=9) # type: ignore[union-attr] + self.assertEqual(steps[7:], plain[2:]) + + async def test_a_mix_at_the_dispense_height_moves_no_z(self) -> None: + # As logged (09-22, Greiner96RoundDeep): a mix at the height the dispense left the tips at sends + # only the plunger's moves. + driver, lh = await self.setup_deck() + pipettes = lh.pipettes + pipettes._set_tips({1: biomek_tip("T190F", "t")}) + well = lh.deck.get_resource("Plate").get_well("A1") + settings = liquid.with_mix(pipettes._settings(liquid_height=2.0), Mix(35, 2, 100), None) + steps = pipettes.plan_liquid("dispense", [well], [9], [0], settings, 90)[0].steps + mix = steps[3:7] + self.assertTrue(all(isinstance(s, PlungerMove) and s.flow_rate == 100 for s in mix)) + self.assertEqual([s.volume["Z1"] for s in mix], [35, -35, 35, -35]) # type: ignore[union-attr] + + async def test_a_mix_needs_empty_tips_and_one_mix_for_all_probes(self) -> None: + driver, lh = await self.setup_deck() + pipettes = lh.pipettes + tips = {n: biomek_tip("T190F", "t") for n in (1, 2)} + pipettes._set_tips(tips) + pipettes._tips.update(tips) # as a pickup leaves them: the tips whose trackers book liquid + plate = lh.deck.get_resource("Plate") + wells = [plate.get_well("A1"), plate.get_well("B1")] + mix = Mix(10, 1, 50) + with self.assertRaisesRegex(ValueError, "one mix for all channels"): + await pipettes.dispense(wells, [5, 5], post_mixes=[mix, None]) + with self.assertRaisesRegex(ValueError, "one mix for all channels"): + await pipettes.dispense(wells, [5, 5], post_mixes=[mix, Mix(20, 1, 50)]) + for tip in tips.values(): + tip.tracker.add_liquid(30) + # Biomek: "The mix operation cannot begin until tips are empty". + with self.assertRaisesRegex(ValueError, "until the tips are empty"): + await pipettes.dispense(wells, [20, 20], post_mixes=[mix] * 2) + with self.assertRaisesRegex(ValueError, "until the tips are empty"): + await pipettes.aspirate(wells, [5, 5], pre_mixes=[mix] * 2) + with self.assertRaisesRegex(ValueError, "cannot be negative"): + await pipettes.dispense(wells, [30, 30], post_mixes=[Mix(10, -1, 50)] * 2) + with self.assertRaises(NotImplementedError): + await pipettes.dispense( + wells, [30, 30], post_mixes=[Mix(10, 1, 50, surface_following_distance=1.0)] * 2 + ) + # Drawn for real this time, then a dispense that leaves the tips empty mixes. + for tip in tips.values(): + tip.tracker.remove_liquid(30) + left = self.pod(driver, "left") + await left.move_axes({"GR": left.declared.to_counts("GR", 90)}) # type: ignore[union-attr] + await left.move_axes({"X": 5586, "Y": 58890}) + reservoir = lh.deck.get_resource("Reservoir").get_item(0) + await pipettes.aspirate([reservoir] * 2, [30, 30]) + await pipettes.dispense(wells, [30, 30], post_mixes=[mix] * 2) + self.assertAlmostEqual(wells[0].tracker.get_used_volume(), 30) + self.assertAlmostEqual(tips[1].tracker.get_used_volume(), 0) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index 53148ea368f..d31a00b9db5 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -45,6 +45,7 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import MoveResult, Pod from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import XRail from pylabrobot.io.usb import USB @@ -166,6 +167,7 @@ def __init__( async def setup( self, skip_device_initialization: bool = False, + skip_pipettes: bool = False, *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, @@ -181,6 +183,8 @@ async def setup( Args: skip_device_initialization: do not load motor tables, even into a board that has lost them. A pod with an axis not configured is then left as it is, and cannot move. + skip_pipettes: leave the pod carrying the Span-8 as it is (STAR's per-feature skip). A pod's + axes come up together, so this skips the whole pod, its gripper included. skip_left_x_arm: leave the left pod as it is: not configured, enabled or moved. skip_right_x_arm: leave the right pod as it is. force_initialize: home again axes that are already homed, as Biomek's Home All does. @@ -190,10 +194,10 @@ async def setup( fault, or a pod would move on the X rail beside a skipped pod whose X is not homed. """ logger.warning( - "The Biomek i7 driver's discovery, configuration, interlock, Home All and moves have run on " - "one instrument; its commands were compared with Biomek's logs where Biomek ran the same " - "operation; it is untested on other instruments. Please report what works and what does " - "not." + "The Biomek i7 driver has run on one instrument (Home All, moves, prime, the Span-8's tips " + "and transfers, park); its commands were compared with Biomek's logs where Biomek ran the " + "same operation; it is untested on other instruments. Please report what works and what " + "does not." ) if not self._connected: await self._open() @@ -201,6 +205,7 @@ async def setup( await self.discover() await self.initialize( skip_device_initialization=skip_device_initialization, + skip_pipettes=skip_pipettes, skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm, force_initialize=force_initialize, @@ -292,6 +297,7 @@ async def discover(self) -> None: self.rail = XRail({pod.side: pod.declared for pod in self.arms}) self._watch_faults() for pod in self.arms: + pod.driver = self pod.rail = self.rail self.rail.readers[pod.side] = pod.request_rail_pose modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())] @@ -481,11 +487,31 @@ def arm(self, name: Union[str, int]) -> Pod: return pod raise KeyError(f"no pod {name!r}; have {[(p.side, p.component) for p in self.arms]}") + def _one_with(self, feature: str) -> Optional[Pod]: + """The one pod carrying `feature`, None if none does. + + Raises: + ValueError: if more than one pod carries it; reach it through the pod instead. + """ + carriers = [pod for pod in self.arms if getattr(pod, feature) is not None] + if len(carriers) > 1: + raise ValueError( + f"both pods have a {feature}, so `{feature}` is ambiguous - reach it through " + f"`left_x_arm.{feature}` or `right_x_arm.{feature}`." + ) + return carriers[0] if carriers else None + @property def front_cover(self) -> Optional[Door]: """The door, by STAR's name for it, once discovery has found the chassis.""" return None if self.chassis is None else self.chassis.front_cover + @property + def pipettes(self) -> Optional[Pipettes]: + """The Span-8 channels, on an instrument where one pod has them.""" + pod = self._one_with("pipettes") + return pod.pipettes if pod is not None else None + async def request_axis_states(self) -> Dict[str, Dict[str, p.AxisStateName]]: """Every axis's state, by pod side then axis name. Moves nothing.""" return {pod.side: await pod.request_axis_states() for pod in self.arms} @@ -500,14 +526,25 @@ def _require_chassis(self) -> Chassis: return self.chassis def skipped_sides( - self, *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False + self, + *, + skip_pipettes: bool = False, + skip_left_x_arm: bool = False, + skip_right_x_arm: bool = False, ) -> Set[str]: - """The sides (`"left"`, `"right"`) a setup with these skips leaves as they are.""" - return {s for s, skip in (("left", skip_left_x_arm), ("right", skip_right_x_arm)) if skip} + """The sides (`"left"`, `"right"`) a setup with these skips leaves as they are: the sides + named, and the pod carrying each feature named (STAR's per-feature skips; a feature this + instrument does not have skips nothing). Known after discovery.""" + sides = {s for s, skip in (("left", skip_left_x_arm), ("right", skip_right_x_arm)) if skip} + for pod in self.arms: + if skip_pipettes and pod.pipettes is not None: + sides.add(pod.side) + return sides async def initialize( self, skip_device_initialization: bool = False, + skip_pipettes: bool = False, *, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, @@ -533,7 +570,11 @@ async def initialize( AceError: if an axis cannot be enabled, or a move or home fails; the interlock is then tripped and ERROR shown. """ - skipped = self.skipped_sides(skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm) + skipped = self.skipped_sides( + skip_pipettes=skip_pipettes, + skip_left_x_arm=skip_left_x_arm, + skip_right_x_arm=skip_right_x_arm, + ) pods = [pod for pod in self.arms if pod.side not in skipped] if skip_device_initialization and not pods: return diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tests.py new file mode 100644 index 00000000000..60a7cd67342 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tests.py @@ -0,0 +1,55 @@ +"""A Span-8 pod's channels (`Pod.pipettes`) on the simulator: valves, cutoff velocity, pump moves +through them, and the tip check.""" + +import struct + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import TipCheckError +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest + + +class PipettesTests(PodMoveTest): + async def test_valves_then_pump_moves_through_them(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "right") + pipettes = pod.pipettes + assert pipettes is not None + usb = self.usb(driver, "span8") + await pipettes.set_valves({"D1": "input", "D2": "input"}) + pump_params = [ + params for name, params in self.sent(driver, "span8") if name == "Set Move Parameters" + ] + self.assertEqual(len(pump_params), 2) + self.assertEqual(struct.unpack(" None: + driver = await self.homed() + pod = self.pod(driver, "right") + pipettes = pod.pipettes + assert pipettes is not None + self.usb(driver, "span8").tip_states = bytes([0, 0, 2, 2, 1, 2, 2, 2]) + await pipettes.verify_tips({0: True, 1: True, 2: False}) # channels, 0-based + with self.assertRaises(TipCheckError) as caught: + await pipettes.verify_tips({0: False, 2: True, 4: True}) + message = str(caught.exception) + for text in ("Probe 1 should not", "Probe 3 should have", "probe 5 has"): + self.assertIn(text, message) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py new file mode 100644 index 00000000000..8bcb6ad1786 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py @@ -0,0 +1,168 @@ +"""The Span-8 picking up and discarding tips on the simulator, on the deck of a method Biomek's logs +ran (BC190F tips at P24, 2026-10-20), against what Biomek sent for the same load and discard.""" + +from typing import Dict, List, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck +from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import TipCheckError +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import press_groups +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.resources import set_tip_tracking +from pylabrobot.resources.errors import HasTipError + +SLOTS = ["X", "Y", "S"] + [f"Z{n}" for n in range(1, 9)] + +# What Biomek sent for a full load of BC190F tips at P24, column 1 (2026-10-20, the Master +# Controller's log): the X/Y/S move, the approach, the paired presses and the last pair's rise. +LOGGED_LOAD = [ + "AM 7 1000 0 -43646 203624 0", + "AM 2040 1000 0 -69773 -69619 -69780 -70109 -69944 -69711 -69671 -69728", + "AM 136 250 0 -79598 -79768", + "AM 408 250 0 -70819 -79444 -70989 -79535", + "AM 816 250 0 -70665 -79604 -70756 -79495", + "AM 1632 250 0 -70825 -79933 -70716 -79553", + "AM 1088 250 0 -71154 -70774", +] +# And for discarding them into TR2: over the trash, Z to DiscardHeight - 1, then each group of +# four up to the top of travel (where the stripper takes the tips) and back. +LOGGED_DISCARD = [ + "AM 7 1000 0 -18516 16957 0", + "AM 2040 1000 0 6223 6377 6216 5887 6052 6285 6325 6268", + "AM 120 250 0 11200 11200 11200 11200", + "AM 120 250 0 6223 6377 6216 5887", + "AM 1920 250 0 11200 11200 11200 11200", + "AM 1920 250 0 6052 6285 6325 6268", +] + +LOADED, UNLOADED = 0x00, 0x02 + + +def parse(command: str) -> Tuple[Dict[str, int], int]: + f = [int(x) for x in command.split()[1:]] + mask, speed, values = f[0], f[1], iter(f[3:]) + return {n: next(values) for i, n in enumerate(SLOTS) if mask & (1 << i)}, speed + + +class PipettesTipTests(PodMoveTest): + async def setup_deck(self): # type: ignore[no-untyped-def] + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + place_labware(lh.deck, [{"position": "P24", "class": "BC190F", "name": "Tips"}]) + # As after Biomek's Home All and `setup()`: the right gripper parked (GR 90, GY 48), its + # fingers out of the probes' way. + right = self.pod(driver, "right") + park = right.declared.park # type: ignore[union-attr] + await right.move_axes({a: right.declared.to_counts(a, park[a]) for a in ("GR", "GY")}) # type: ignore[union-attr] + pipettes = self.pod(driver, "right").pipettes + assert pipettes is not None + return driver, lh, pipettes + + def record(self, driver) -> List[Tuple[Dict[str, int], int]]: # type: ignore[no-untyped-def] + """Every `move_axes` the right pod is asked for from now on: (targets, speed).""" + pod = self.pod(driver, "right") + moves: List[Tuple[Dict[str, int], int]] = [] + original = pod.move_axes + + async def move_axes(targets, speed=1000, **kwargs): # type: ignore[no-untyped-def] + moves.append((dict(targets), speed)) + return await original(targets, speed, **kwargs) + + pod.move_axes = move_axes # type: ignore[method-assign, assignment] + return moves + + def sensor(self, driver, state: int) -> None: # type: ignore[no-untyped-def] + self.usb(driver, "span8").tip_states = bytes([state] * 8) + + def from_travel(self, moves): # type: ignore[no-untyped-def] + """The moves from the X/Y/S travel on (`_move_over` lifts the channels first).""" + first = next(i for i, (t, _) in enumerate(moves) if "X" in t) + return moves[first:] + + async def test_a_full_load_sends_biomeks_moves_and_records_the_tips(self) -> None: + driver, lh, pipettes = await self.setup_deck() + rack = lh.deck.get_resource("Tips") + moves = self.record(driver) + self.sensor(driver, LOADED) + await pipettes.pick_up_tips([rack.get_item(f"{r}1") for r in "ABCDEFGH"]) + self.assertEqual(self.from_travel(moves)[: len(LOGGED_LOAD)], [parse(c) for c in LOGGED_LOAD]) + self.assertEqual(pipettes.tips, ["beckman_coulter_biomek_tip_190uL_filter"] * 8) + # As the STAR shows them: each tip on its probe's shaft, the probe's channel where its axes are. + self.assertEqual(len(pipettes.resources), 8) + self.assertTrue(all(shaft_of(c).has_tip() for c in pipettes.resources)) + # The tips' effective length: T190F's TipHeight less its SpanSeatingDepth, cm. + self.assertAlmostEqual(pipettes._carried_tip_lengths()["Z1"], 5.1435 - 0.775, places=4) + with self.assertRaises(HasTipError): + await pipettes.pick_up_tips([rack.get_item("A2")]) + + async def test_discard_shucks_in_fours_at_the_top_of_travel(self) -> None: + driver, lh, pipettes = await self.setup_deck() + rack = lh.deck.get_resource("Tips") + self.sensor(driver, LOADED) + await pipettes.pick_up_tips([rack.get_item(f"{r}1") for r in "ABCDEFGH"]) + moves = self.record(driver) + self.sensor(driver, UNLOADED) + await pipettes.discard_tips() + self.assertEqual( + self.from_travel(moves)[: len(LOGGED_DISCARD)], [parse(c) for c in LOGGED_DISCARD] + ) + self.assertEqual(pipettes.tips, [None] * 8) + self.assertFalse(any(shaft_of(c).has_tip() for c in pipettes.resources)) + with self.assertRaises(RuntimeError): + await pipettes.discard_tips() + + async def test_the_tip_sensor_checks_the_probes_worked(self) -> None: + driver, lh, pipettes = await self.setup_deck() + rack = lh.deck.get_resource("Tips") + self.sensor(driver, UNLOADED) # the sensor sees no tip where one was pressed on + with self.assertRaises(TipCheckError): + await pipettes.pick_up_tips([rack.get_item("A1")]) + + async def test_tips_cannot_go_back_into_a_rack(self) -> None: + driver, lh, pipettes = await self.setup_deck() + rack = lh.deck.get_resource("Tips") + with self.assertRaisesRegex(NotImplementedError, "discard_tips"): + await pipettes.drop_tips([rack.get_item("A1")]) + + async def test_a_partial_load_presses_by_biomeks_groups(self) -> None: + set_tip_tracking(True) + self.addCleanup(set_tip_tracking, False) + driver, lh, pipettes = await self.setup_deck() + rack = lh.deck.get_resource("Tips") + # Probes 6-8 over F1-H1: the span stays at its narrowest, probe 1 five rows behind F1. + spots = [rack.get_item(n) for n in ("F1", "G1", "H1")] + (plan,) = pipettes.plan_pick_up(spots, [5, 6, 7]) + self.assertEqual(plan.groups, ((6,), (7,), (8,))) # none 4 apart + self.assertEqual(plan.lowered, (6, 7, 8)) # A1-E1 still hold tips: probes 1-5 stay up + self.assertAlmostEqual(plan.span, 6.3, places=6) + self.sensor(driver, LOADED) + await pipettes.pick_up_tips(spots, [5, 6, 7]) + self.assertIsNone(rack.get_item("H1").tip) + self.assertEqual(pipettes.tips[5:], ["beckman_coulter_biomek_tip_190uL_filter"] * 3) + # The next load from that column lowers the tipless probes over its emptied spots as well. + (plan,) = pipettes.plan_pick_up([rack.get_item("A1")], [0]) + self.assertEqual(plan.lowered, (1,)) # probes 6-8 carry tips; 2-5 stand over full spots + + def test_biomeks_groups(self) -> None: + self.assertEqual(press_groups(range(1, 9), 2, 4), [(1, 5), (2, 6), (3, 7), (4, 8)]) + self.assertEqual(press_groups(range(1, 9), 4, 1), [(1, 2, 3, 4), (5, 6, 7, 8)]) + self.assertEqual(press_groups([2, 3, 4, 5, 6, 7, 8], 2, 4), [(2, 6), (3, 7), (4, 8), (5,)]) + + async def test_carrying_probes_travel_below_the_stripper(self) -> None: + driver, lh, pipettes = await self.setup_deck() + pod = self.pod(driver, "right") + d = pod.declared + assert d is not None + ceilings = pod._traverse_ceilings() + self.assertAlmostEqual(ceilings["Z6"], d.limits["Z6"][1] - d.settings["DiscardOffset"]) + rack = lh.deck.get_resource("Tips") + self.sensor(driver, LOADED) + await pipettes.pick_up_tips([rack.get_item("A1")]) + # Heights at the API are the tips' ends, mm: one the tip on probe 1 cannot reach is refused. + reach_mm = (ceilings["Z1"] - pipettes._carried_tip_lengths()["Z1"]) * 10 + with self.assertRaisesRegex(ValueError, "reach with their tips"): + await pipettes.pick_up_tips( + [rack.get_item("A2")], [1], minimum_traverse_height_start=reach_mm + 1 + ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py new file mode 100644 index 00000000000..df1e20915fb --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py @@ -0,0 +1,94 @@ +"""Priming the Span-8 on the simulator, against Biomek's logged prime (the Master Controller's log, +2026-10-09).""" + +import asyncio +from typing import Dict, List, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_tip + +# The logged prime: the probes into the wash station, each pump's full stroke and the air gap. +LOGGED_Z = [-72401, -72247, -72407, -72736, -72571, -72338, -72298, -72356] +LOGGED_X, LOGGED_Y = -7761, 203370 +PUMPS = [f"D{n}" for n in range(1, 9)] + + +class PrimeTests(PodMoveTest): + async def setup_pipettes(self): # type: ignore[no-untyped-def] + driver = await self.homed() + BiomekI7(driver=driver, deck=generic_deck()) + pod = self.pod(driver, "right") + assert pod.pipettes is not None + moves: List[Tuple[Dict[str, int], int]] = [] + original = pod.move_axes + + async def move_axes(targets, speed=1000, **kwargs): # type: ignore[no-untyped-def] + moves.append((dict(targets), speed)) + return await original(targets, speed, **kwargs) + + pod.move_axes = move_axes # type: ignore[method-assign, assignment] + return pod, pod.pipettes, moves + + async def test_a_prime_moves_as_biomeks(self) -> None: + pod, pipettes, moves = await self.setup_pipettes() + self.assertEqual(await pipettes.prime(3, minimum_stroke_seconds=0), 3) + lowered = next(t for t, s in moves if s == 250) + self.assertEqual([lowered[f"Z{n}"] for n in range(1, 9)], LOGGED_Z) + travel = next(t for t, _ in moves if "X" in t) + self.assertEqual(travel["X"], LOGGED_X) + self.assertAlmostEqual(travel["Y"], LOGGED_Y, delta=2) # the deck position's calibration + strokes = [(t, s) for t, s in moves if set(t) == set(PUMPS)] + self.assertEqual(strokes[:2], [({a: 24000 for a in PUMPS}, 801), ({a: 0 for a in PUMPS}, 801)]) + self.assertEqual(len(strokes), 3 * 2 + 1) + self.assertEqual(strokes[-1], ({a: 480 for a in PUMPS}, 10)) # the 20 uL system air gap + self.assertFalse(pipettes.priming) + self.assertEqual(pipettes.valves["D1"], "output") + + async def test_start_and_stop(self) -> None: + pod, pipettes, moves = await self.setup_pipettes() + await pipettes.start_prime() + self.assertTrue(pipettes.priming) + with self.assertRaises(RuntimeError): + await pipettes.start_prime() + await asyncio.sleep(0.05) + strokes = await pipettes.stop_prime() + self.assertGreaterEqual(strokes, 1) + self.assertIn(({a: 480 for a in PUMPS}, 10), moves) + with self.assertRaises(RuntimeError): + await pipettes.stop_prime() + + async def test_a_prime_ends_parked_as_biomeks(self) -> None: + # Logged after the prime: X/Y where it primed, the probes at 9029, the gripper to its park. + pod, pipettes, moves = await self.setup_pipettes() + await pipettes.prime(1, minimum_stroke_seconds=0) + for axis, logged in [("X", LOGGED_X), ("GY", 63629), ("GR", -175774), ("GG", 34873)]: + self.assertEqual(pod.cpositions[axis][1], logged, axis) + self.assertAlmostEqual(pod.cpositions["Y1"][1], LOGGED_Y, delta=2) + self.assertEqual({pod.cpositions[f"Z{n}"][1] for n in range(1, 9)}, {9029}) + + async def test_the_96_head_pod_parks_as_biomeks(self) -> None: + driver = await self.homed() + BiomekI7(driver=driver, deck=generic_deck()) + pod = self.pod(driver, "left") + await pod.park() + logged = {"X": 35843, "Y": 37258, "Z": -256, "GY": 63763, "GR": -175443, "GG": 34983} + self.assertEqual({a: pod.cpositions[a][1] for a in logged}, logged) + + async def test_an_instant_simulator_strokes_no_faster_than_the_least_time(self) -> None: + # The simulator here answers at once; strokes still take a second each, and a stop is prompt. + pod, pipettes, moves = await self.setup_pipettes() + loop = asyncio.get_running_loop() + await pipettes.start_prime() + await asyncio.sleep(1.5) + stopping = loop.time() + self.assertEqual(await pipettes.stop_prime(), 2) + self.assertLess(loop.time() - stopping, 0.5) + + async def test_no_prime_with_tips(self) -> None: + pod, pipettes, moves = await self.setup_pipettes() + pipettes._set_tips({1: biomek_tip("T190F", "t")}) + with self.assertRaises(RuntimeError): + await pipettes.start_prime() + self.assertEqual(moves, []) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pump_homing_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pump_homing_tests.py new file mode 100644 index 00000000000..56a26568986 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pump_homing_tests.py @@ -0,0 +1,39 @@ +"""The Span-8's pumps must be homed before it aspirates or dispenses: after a power-up they are not +(Home All does not home them), and the board would refuse the pump move halfway through an +operation. The driver knows once it homes them, or asks each pump once, and refuses first.""" + +from pylabrobot.beckman_coulter.biomek_i7.driver import liquid_tests +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import NotHomedError +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_tip + + +class PumpHomingTests(PodMoveTest): + setup_deck = liquid_tests.LiquidTests.setup_deck + record = liquid_tests.LiquidTests.record + + async def test_pumps_not_homed_refuse_before_anything_moves(self) -> None: + driver, lh = await self.setup_deck() # type: ignore[misc] + self.usb(driver, "span8").axis_model("D1").homed = False + pipettes = lh.pipettes + pipettes._pumps_homed = None # a session that has not homed them yet + pipettes._set_tips({n: biomek_tip("T190F", "t") for n in range(1, 3)}) + reservoir = lh.deck.get_resource("Reservoir").get_item(0) + moves = self.record(driver, "right") # type: ignore[misc] + with self.assertRaisesRegex(NotHomedError, "prime the Span-8"): + await pipettes.aspirate([reservoir] * 2, [30, 30]) + self.assertEqual(moves, []) + await pipettes.home_pumps() + await pipettes.aspirate([reservoir] * 2, [30, 30]) + self.assertTrue(moves) + + async def test_pumps_homed_in_this_session_are_not_asked_again(self) -> None: + driver, lh = await self.setup_deck() # type: ignore[misc] + pipettes = lh.pipettes + await pipettes.home_pumps() + self.mark(driver) + pipettes._set_tips({n: biomek_tip("T190F", "t") for n in range(1, 3)}) + reservoir = lh.deck.get_resource("Reservoir").get_item(0) + await pipettes.aspirate([reservoir] * 2, [30, 30]) + asked = [name for name, _ in self.sent(driver, "span8") if name == "Get Homed State"] + self.assertEqual(asked, []) # the traffic stays the Master Controller's diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py index 204974c3f22..8ba3a0eaf7d 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -19,7 +19,9 @@ from dataclasses import dataclass from pathlib import Path from typing import ( + TYPE_CHECKING, Any, + Callable, Dict, Iterable, List, @@ -39,6 +41,9 @@ ) from pylabrobot.io.usb import USB +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver + # Names the recording the simulator answers from (identity and sensor reads, recorded at an # instrument's cold start) when no path is given. A generic one ships in `defaults/` # (`biomek_i7_generic_coldstart.json`), which `BiomekI7(simulation=True)` uses when neither is @@ -159,7 +164,10 @@ class SimulatedAceUSB(ReplayAceUSB): A move with a force limit stops where the axis meets something (`_AxisModel.obstacle`, set by a test). A move with a sensor stops where the sensor fires (`_AxisModel.sensed_at`), and the Move All carries that axis's report (LLS_LIQUID_SENSED and the position) under its sequence. - A pump keeps the valve it was last moved through. + A pump keeps the valve it was last + moved through. Get Tip Status answers `tip_states` when set, else `tip_sensor()` when set (the + simulator does not model tips; `sense_recorded_tips` has it report the session's), else from the + recording. Moves complete at once unless `time_scale` is set: then a Move or Move All is accepted at once and done after the slowest axis's move would take (`_AxisModel.duration`), times `time_scale` @@ -196,6 +204,10 @@ def __init__( state = AxisState.ENABLED if configured else AxisState.NOT_CONFIGURED self.axes[(a.device, a.index)] = _AxisModel(a.name, a.name in homed, state, a.drive) self.axes_list = list(axes) + # Get Tip Status's answer, one byte per probe (0 loaded, 1 cannot tell, 2 unloaded); None + # answers from the recording. + self.tip_states: Optional[bytes] = None + self.tip_sensor: Optional[Callable[[], bytes]] = None def _apply_power(self) -> None: """An enabled CiA 402 drive faults when its motor power goes. One configured with the power @@ -309,6 +321,12 @@ def answer(self, message: bytes) -> Optional[List[bytes]]: + struct.pack(" None: + """Have each simulated Span-8 board's tip sensor report the tips its pod's `pipettes` record (0 loaded, 2 unloaded per probe), so a simulated run's tip checks pass where the + pickups and discards it ran would leave tips. `boards`: the driver's simulated boards.""" + for board in boards: + io = board.io + if not isinstance(io, SimulatedAceUSB) or board.name != "simulated span8": + continue + + def sense() -> bytes: + pod = next((p for p in driver.arms if p.module_type == "span8"), None) + tips = pod.pipettes.tips if pod is not None and pod.pipettes is not None else [None] * 8 + return bytes(0x00 if t is not None else 0x02 for t in tips[:8]) + + io.tip_sensor = sense diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py index 70749a787c3..41ff263be23 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/heads.py @@ -1,6 +1,7 @@ """The Biomek i7's pipetting heads in the resource tree, as the STAR's are: the Multichannel head an `NChannelPipette` of 96 `TipMountingShaft`s (category `head96`), each Span-8 probe a channel -(category `pipette_channel`) carrying one shaft. +(category `pipette_channel`) carrying one shaft. A tip a head carries is a child of its shaft +(`show_tip`), so it rides the head and the viewer draws it. Sized in centimetres from the instrument file's pod entry (`HeadBodyXSpan`, `HeadHeight`, `HeadFlangeHeight`, `Head/PodToMandrel1`, `PodToHeadBody*Offset`, `Mandrel1*Offset`, the mandrels' @@ -22,6 +23,7 @@ TipMountingShaft, ) from pylabrobot.resources.resource import Resource +from pylabrobot.resources.tip import Tip from pylabrobot.resources.utils import create_ordered_items_2d from .units import cm @@ -186,3 +188,40 @@ def span8_channel( # Stated on a plain `Resource`, as the STAR states it on its channels. channel.reference_point = Coordinate(axis_x, depth / 2, -length) # type: ignore[attr-defined] return channel + + +def shaft_of(channel: Resource) -> TipMountingShaft: + """A Span-8 channel's shaft.""" + for child in channel.children: + if isinstance(child, TipMountingShaft): + return child + raise ValueError(f"{channel.name} carries no tip mounting shaft") + + +def show_tip(shaft: TipMountingShaft, tip: Optional[Tip]) -> None: + """Put `tip` on `shaft` in the tree, or take whatever it carries off (None). + + A tip already on the shaft stays. A tip that cannot go in the tree as it is - one held on + another shaft, or whose name the tree already has - is shown by a copy named after the + shaft.""" + if shaft.tip is tip and tip is not None: + return + if shaft.has_tip(): + shaft.release_tip() + if tip is None: + return + if isinstance(tip.parent, TipMountingShaft) or _name_taken(shaft, tip): + tip = Tip.deserialize({**tip.serialize(), "name": f"{shaft.name}_tip"}) + assert isinstance(tip, Tip) + shaft.mount_tip(tip) + + +def _name_taken(shaft: Resource, tip: Tip) -> bool: + root = shaft.get_root() + if tip.parent is not None and tip.get_root() is root: + return False # it is the one by that name, and moves rather than copies + try: + root.get_resource(tip.name) + except Exception: + return False + return True diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py index 214a7165ca2..9e4302b0d68 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py @@ -1,10 +1,16 @@ -"""A simulated instrument as `BiomekI7(simulation=True)` builds it: a pod moves aside for the other, -and moves take the instrument's time when asked to.""" +"""A simulated instrument as `BiomekI7(simulation=True)` builds it: the Span-8's tip sensor reports +the tips the session records, a pod moves aside for the other, moves take the instrument's time +when asked to, and setup takes off tips left on.""" import asyncio +import os +import tempfile import time import unittest +from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_tip +from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import span8_channels from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_biomek @@ -16,6 +22,13 @@ async def asyncSetUp(self) -> None: await self.biomek.setup() self.addAsyncCleanup(self.biomek.stop) + async def test_the_tip_sensor_reports_the_recorded_tips(self) -> None: + pipettes = self.biomek.pipettes + assert pipettes is not None + self.assertEqual(await pipettes.sense_tip_presence(), ["unloaded"] * 8) + pipettes._set_tips({2: biomek_tip("T230", "t")}) + self.assertEqual((await pipettes.sense_tip_presence())[:3], ["unloaded", "loaded", "unloaded"]) + async def test_a_pod_moves_aside(self) -> None: pod = self.biomek.left_x_arm assert pod is not None and pod.declared is not None @@ -45,5 +58,28 @@ async def test_moves_take_the_instruments_time(self) -> None: self.assertGreater(took[True], 0.2) +class SetupDiscardTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + + async def test_setup_takes_off_tips_left_on(self) -> None: + # A Span-8 tip left on last session, as its saved state has it on the shaft, and the sensor + # finds: it goes to its trash, and the state then has none. + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "state.json") + last = generic_biomek(state_json=path) + probe_3 = shaft_of(span8_channels(last.bridges["right"])[2]) + probe_3.mount_tip(biomek_tip("T230", "probe_tip")) + last.save_state_to_file(path) + + biomek = generic_biomek(state_json=path) + await biomek.setup() + self.addAsyncCleanup(biomek.stop) + assert biomek.pipettes is not None + self.assertEqual(biomek.pipettes.tips, [None] * 8) + after = generic_biomek(state_json=path) + self.assertFalse(shaft_of(span8_channels(after.bridges["right"])[2]).has_tip()) + + if __name__ == "__main__": unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/techniques.py b/pylabrobot/beckman_coulter/biomek_i7/techniques.py new file mode 100644 index 00000000000..0a19517b1a3 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/techniques.py @@ -0,0 +1,60 @@ +"""The arguments the pipetting features take that PyLabRobot has no type for, named after what +Biomek's techniques hold: conditioning, a tip touch, a mix's heights, and what a height is +measured from.""" + +from dataclasses import dataclass +from typing import Literal, Optional + + +@dataclass(frozen=True) +class Conditioning: + """Biomek's conditioning: aspirate `sections` x `section_volume` + `excess` uL more than asked, + then dispense each section back in place before leaving the well (`MC Pipetting` / `S8 + Pipetting`'s loop), leaving the excess in the tip. The sections go back at `flow_rate` uL/s (the + technique's dispense speed; the aspirate's when None), each followed by `delay` s.""" + + sections: int = 0 + section_volume: float = 0.0 + excess: float = 0.0 + flow_rate: Optional[float] = None + delay: float = 0.0 + + @property + def extra(self) -> float: + return self.sections * self.section_volume + self.excess + + +HeightFrom = Literal["bottom", "top", "liquid"] +"""What a height is measured from: the container's bottom, its top, or the liquid in it.""" + + +@dataclass(frozen=True) +class TipTouch: + """A touch-off: the tip end to `height` mm from `height_from`, out `distance` mm in the direction + `theta` (degrees counterclockwise from +X seen from above, PyLabRobot's: 90 is towards the back of + the deck; Biomek states the same figure, and turns by 360 less it) and back, at `speed_fraction` of + the axes' maximum ((0, 1]: the touch moves X and Y together), then `delay` s. `distance` None goes to the container's wall at its top outline, less the + tip's widest radius (STAR's `side_touch_off_distance` is the same kind of figure). Biomek goes to + the wall at the touch height less its tip's cone where it crosses the rim: + `resource_model.labware.biomek_touch_distance` gives that distance for its labware.""" + + height: float + height_from: HeightFrom = "liquid" + theta: float = 90.0 + speed_fraction: float = 1.0 + delay: float = 0.0 + distance: Optional[float] = None + + +@dataclass(frozen=True) +class MixHeights: + """Where a mix's tips stand: each draw `aspirate_height` mm from `aspirate_height_from`, each push + `dispense_height` mm from `dispense_height_from` (None: as the draw's). Biomek's Mix tab of a + technique section (Aspirate / Dispense From and Height). A mix measured from the liquid needs the + container's contents, as any height from the liquid does; STAR's + `mix_position_from_liquid_surface` d is `MixHeights(-d, "liquid")`.""" + + aspirate_height: float + aspirate_height_from: HeightFrom = "bottom" + dispense_height: Optional[float] = None + dispense_height_from: Optional[HeightFrom] = None From 2b779bcfc4a841f864ee1753abb13d76bcd22546 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:59:54 +0000 Subject: [PATCH 17/28] `Biomek i7`: sort imports for ruff I001 --- .../beckman_coulter/biomek_i7/driver/features/pipettes.py | 8 +++----- .../beckman_coulter/biomek_i7/driver/features/pod.py | 2 +- .../beckman_coulter/biomek_i7/driver/liquid_tests.py | 4 ++-- .../biomek_i7/driver/pipettes_tip_tests.py | 4 ++-- .../beckman_coulter/biomek_i7/driver/prime_tests.py | 2 +- 5 files changed, 9 insertions(+), 11 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py index 88326d49ee9..e7fb09bec0f 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py @@ -48,12 +48,11 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple -from pylabrobot.beckman_coulter.biomek_i7 import targeting -from pylabrobot.beckman_coulter.biomek_i7.driver import motion +from pylabrobot.beckman_coulter.biomek_i7 import targeting, units +from pylabrobot.beckman_coulter.biomek_i7.driver import liquid, motion from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.errors import NotHomedError, TipCheckError -from pylabrobot.beckman_coulter.biomek_i7 import units -from pylabrobot.beckman_coulter.biomek_i7.driver import liquid +from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of, show_tip from pylabrobot.beckman_coulter.biomek_i7.techniques import ( Conditioning, HeightFrom, @@ -67,7 +66,6 @@ rate_to_field, ) from pylabrobot.lib.liquid_handling.mix import Mix -from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of, show_tip from pylabrobot.resources.container import Container from pylabrobot.resources.coordinate import Coordinate from pylabrobot.resources.errors import HasTipError diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index c30be5a973d..9fd03d5f242 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -29,6 +29,7 @@ PodConfiguration, ) from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, read_module, @@ -40,7 +41,6 @@ HOME_RECIPES, Homer, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail if TYPE_CHECKING: diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py index ceac9ec7d41..5b3740d131c 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py @@ -4,8 +4,8 @@ from typing import Dict, List, Tuple -from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 from pylabrobot.beckman_coulter.biomek_i7.driver import liquid from pylabrobot.beckman_coulter.biomek_i7.driver.liquid import ( ContainerShape, @@ -15,12 +15,12 @@ ) from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import ( biomek_labware, biomek_tip, biomek_touch_distance, ) +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.beckman_coulter.biomek_i7.techniques import MixHeights, TipTouch from pylabrobot.lib.liquid_handling.mix import Mix from pylabrobot.resources import Coordinate, cor_96_wellplate_360uL_Fb, set_volume_tracking diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py index 8bcb6ad1786..0e3df514f47 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py @@ -4,12 +4,12 @@ from typing import Dict, List, Tuple from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck -from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of from pylabrobot.beckman_coulter.biomek_i7.driver.errors import TipCheckError from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import press_groups from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.resources import set_tip_tracking from pylabrobot.resources.errors import HasTipError diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py index df1e20915fb..b5e7c0007f3 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/prime_tests.py @@ -6,8 +6,8 @@ from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_tip +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck # The logged prime: the probes into the wash station, each pump's full stroke and the air gap. LOGGED_Z = [-72401, -72247, -72407, -72736, -72571, -72338, -72298, -72356] From 0eb8d919131e075a60124f4bc868ea93883e42af Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:37:10 -0800 Subject: [PATCH 18/28] `Biomek i7`: the 96-channel head: tips, aspirate and dispense The Multichannel pod's head as a feature (`pod.head96`, `driver.head96`, `biomek.head96`), as Biomek's logs show its operations: - `driver/features/head96.py`: tips picked up with the Master Controller's force-limited `LT` (only on a tip-loading position, a partial load counting the tips under the head), put back or discarded (the D-axis shuck over the trash); aspirate and dispense of a 96-well plate or one container through the same templates as the Span-8 (mix, conditioning, blowout, trailing air, tip touch); the tips recorded and shown on the head's shafts, which the device saves and restores (the head cannot sense tips). - `driver/recipes/tip_load.py`: `LT` as Biomek sends it, its arguments from the pod's instrument file settings; the settle ends early when the interlock trips, as the Master Controller's does. - `driver/recipes/homing.py`: the plunger's `HD`, run after the pod's `HM` in a Home All. - The device: `setup` discards what the 96-head may carry (it has no tip sensor: the tips it records, and by default an eject over its trash as if the longest tip were on; `precautionary_discard`), and skips the head's pod on `skip_head96`. Tests: `LT` and the head's pick-up, return and discard send what Biomek's logs show; a transfer and a mix as logged; a forced Home All with the plunger's `HD` as logged; a trip ending the `LT` settle; setup's discards. --- .../beckman_coulter/biomek_i7/design.md | 5 + .../beckman_coulter/biomek_i7/device.py | 56 +- .../biomek_i7/driver/configuration.py | 13 + .../biomek_i7/driver/fault_tests.py | 19 +- .../biomek_i7/driver/features/head96.py | 867 ++++++++++++++++++ .../biomek_i7/driver/features/pipettes.py | 37 +- .../biomek_i7/driver/features/pod.py | 16 +- .../biomek_i7/driver/head96_tests.py | 108 +++ .../biomek_i7/driver/head96_tip_tests.py | 107 +++ .../biomek_i7/driver/homing_tests.py | 14 +- .../biomek_i7/driver/liquid_tests.py | 134 ++- .../biomek_i7/driver/master.py | 41 +- .../biomek_i7/driver/recipes/__init__.py | 3 +- .../biomek_i7/driver/recipes/homing.py | 4 + .../biomek_i7/driver/recipes/tip_load.py | 197 ++++ .../biomek_i7/simulation_tests.py | 90 +- 16 files changed, 1642 insertions(+), 69 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/recipes/tip_load.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index 27fae593a9e..03ace571c1c 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -111,3 +111,8 @@ bottom, top or liquid), following the liquid, mixes, conditioning, blowout, trai touch-off, for any PyLabRobot container from its height <-> volume function. A setting the driver does not build yet is refused, never run without it. The Span-8's tips are checked by its tip sensor; it cannot drop tips into a rack, only discard them. + +`head96` is the Multichannel pod's. Its tips are loaded force-limited by the MC's `LT` +(`driver/recipes/tip_load.py`, its arguments from the configuration) and ejected by the plunger's +shuck. It has no tip sensor, so `setup` ejects over its trash even with no tips recorded +(`precautionary_discard`). diff --git a/pylabrobot/beckman_coulter/biomek_i7/device.py b/pylabrobot/beckman_coulter/biomek_i7/device.py index a0c20938364..dc4d73a33f7 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device.py @@ -34,6 +34,10 @@ ) from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import ( + DEFAULT_TRASH as HEAD96_TRASH, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import ( DEFAULT_TRASH as SPAN8_TRASH, ) @@ -94,9 +98,9 @@ class BiomekI7Device(Resource): the driver moves it, placed as Biomek's collision model places it, so the resource tree takes up the X the rail guard counts. The rest follows the pod's other axes (`_show_pod`): the Multichannel's carriage its Y and its head (an `NChannelPipette`) its Z, each Span-8 probe's - channel its own Y and Z, and the gripper (a `MechanicalGripper`) GY, GZ, GR and GG. The Span-8's - probes are its feature's resources, so the tips they carry hang from their shafts, as the STAR's - do. Each bridge marks the point its pod's X names (`resource_model.pods.pod_model`). + channel its own Y and Z, and the gripper (a `MechanicalGripper`) GY, GZ, GR and GG. The heads + are the features' resources, so the tips they carry hang from their shafts, as the STAR's do. + Each bridge marks the point its pod's X names (`resource_model.pods.pod_model`). `update_bridge_location`, `update_pod_location` and `update_probe_location` place the models by hand; nothing moves. """ @@ -181,6 +185,11 @@ def front_cover(self) -> Optional[Door]: """The door, by STAR's name for it (known after `setup`).""" return self.driver.front_cover + @property + def head96(self) -> Optional[Head96]: + """The 96-channel head, on an instrument where one pod has it.""" + return self.driver.head96 + @property def pipettes(self) -> Optional[Pipettes]: """The Span-8 channels, on an instrument where one pod has them.""" @@ -191,10 +200,12 @@ async def setup( skip_device_initialization: bool = False, skip_pipettes: bool = False, *, + skip_head96: bool = False, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, force_initialize: bool = False, discard_tips: bool = True, + precautionary_discard: bool = True, park: bool = True, ) -> None: """Bring the instrument up. This homes the arms, then, as the STAR does, takes off any tips @@ -203,36 +214,45 @@ async def setup( Args: skip_device_initialization: as `BiomekI7Driver.setup` takes it. skip_pipettes: as `BiomekI7Driver.setup` takes it. + skip_head96: as `BiomekI7Driver.setup` takes it. skip_left_x_arm: as `BiomekI7Driver.setup` takes it. skip_right_x_arm: as `BiomekI7Driver.setup` takes it. force_initialize: as `BiomekI7Driver.setup` takes it. - discard_tips: shuck tips found on a Span-8 that was brought up into its trash: the probes - the tip sensor finds a tip on. Needs the trash position on the deck. + discard_tips: shuck tips found on a pod that was brought up into its trash: on a Span-8 the + probes the tip sensor finds a tip on, on the 96-head the tips it records (it has no tip + sensor). Needs the trash position on the deck. + precautionary_discard: with `discard_tips`, eject into the 96-head's trash even when no + tips are recorded, as if the longest tip were on (`head96.discard_any_tips`), + as the STAR's 96-head initialization ejects into its waste: the head cannot sense tips, + and a lost state would leave them on unseen. False skips it, for an operator who has + checked the head is empty. A path to the trash that is not clear for the longest tip + refuses the move: clear it, or pass False. park: park every pod that was brought up (`park`). """ await self.driver.setup( skip_device_initialization=skip_device_initialization, skip_pipettes=skip_pipettes, + skip_head96=skip_head96, skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm, force_initialize=force_initialize, ) self._follow_driver() skipped = self.driver.skipped_sides( - skip_pipettes=skip_pipettes, - skip_left_x_arm=skip_left_x_arm, - skip_right_x_arm=skip_right_x_arm, - ) + skip_pipettes=skip_pipettes, skip_head96=skip_head96, + skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm, + ) # fmt: skip if discard_tips: - await self._discard_found_tips(skipped) + await self._discard_found_tips(skipped, precautionary_discard) if park: await self.park(skip=skipped) - async def _discard_found_tips(self, skipped: Set[str]) -> None: + async def _discard_found_tips(self, skipped: Set[str], precautionary: bool = True) -> None: """Shuck the tips found on the pods not `skipped` (`setup`'s `discard_tips`). A Span-8 probe the sensor finds a tip on that the session did not record is taken to carry the longest Biomek tip, so its travel to the trash clears the deck; a recorded tip the sensor does not - find is forgotten.""" + find is forgotten. The 96-head, which has no sensor, discards whatever it may carry when + `precautionary`, else only the tips recorded.""" names = set(self.deck.position_names) for pod in self.arms: if pod.side in skipped: @@ -249,6 +269,12 @@ async def _discard_found_tips(self, skipped: Set[str]) -> None: pipettes._set_tips({n: pipettes._carried_tip(n) or assumed for n in found}) logger.warning("%s: tips found on probes %s; discarding them", pod, found) await pipettes.discard_tips(use_channels=[n - 1 for n in found]) + if pod.head96 is not None and HEAD96_TRASH in names: + if any(pod.head96.tips): + logger.warning("%s: the 96-head carries tips, as recorded; discarding them", pod) + await pod.head96.discard_tips() + elif precautionary: + await pod.head96.discard_any_tips() async def park(self, skip: Iterable[str] = ()) -> None: """Park the pods as Biomek does (`Pod.park`; a Span-8 over its wash station, @@ -329,8 +355,12 @@ def _follow_driver(self) -> None: self._show_pod(pod) def _give_heads(self, pod: Pod) -> None: - """Hand a Span-8's probes to its feature, as the STAR's driver hands each feature its + """Hand a pod's head or probes to its feature, as the STAR's driver hands each feature its resources; the feature takes the tips their shafts carry as its own.""" + model = self.pod_models[pod.side] + if pod.head96 is not None: + pod.head96.resource = model.get_resource(f"{model.name}_head") # type: ignore[assignment] + pod.head96._adopt_tips() if pod.pipettes is not None: pod.pipettes.resources = span8_channels(self.bridges[pod.side]) pod.pipettes._adopt_tips() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index fe2020a5632..b4f06e7f5ab 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -197,6 +197,19 @@ class Obstacle: "Head/PodToMandrel1", "HeadBodyXSpan", "HeadBodyYSpan", + "DAxisULPerCM", + "TipSeatingDepth", + "TipLoadZOffset", + "TipLoadForceLimitOffset", + "TipLoadForceLimitSlope", + "TipLoadSpeed", + "TipLoadSettlingTime", + "TipLoadRelieveZOffset", + "TipLoadRelieveSpeed", + "TipLoadPushOffDistance", + "TipLoadPushOffSpeed", + "TipUnloadZOffset", + "TipUnloadShuckSpeed", ), } diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py index 55989602bfb..4732b1c95cc 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py @@ -1,11 +1,15 @@ """Faults the boards report unasked, as the Master Controller handles them, and the positions: a motor that fails on its own trips the interlock and every position is forgotten; after an interlock -trip, re-arming reads every position again.""" +trip, re-arming reads every position again; a trip ends the `LT` settle.""" import asyncio +import dataclasses from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import InterlockTrippedError +from pylabrobot.beckman_coulter.biomek_i7.driver.head96_tests import LOGGED from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest @@ -53,6 +57,19 @@ async def test_an_interlock_trip_forgets_positions_and_shows_error(self) -> None self.assertFalse(driver.interlock_tripped.is_set()) self.assertIsNotNone(pod.cpositions["Z1"][0]) + async def test_a_trip_ends_the_tip_load_settle(self) -> None: + driver = await self.homed() + head96 = self.pod(driver, "left").head96 + assert head96 is not None + load = dataclasses.replace(TipLoad.parse(LOGGED), settling_time=30.0) + task = asyncio.create_task(head96.load_tips(load)) + await self.settle() + self.assertFalse(task.done()) # pressed, settling + with self.assertLogs("pylabrobot.beckman_coulter.biomek_i7.driver.master", "ERROR"): + self.unasked(driver, "chassis", bytes([p.Device.INTERLOCK, 1, 0, 0, 0x10, 0x03, 0x00, 0x01])) + with self.assertRaises(InterlockTrippedError): + await asyncio.wait_for(task, 1.0) + if __name__ == "__main__": import unittest diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py new file mode 100644 index 00000000000..2b20b9caa27 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py @@ -0,0 +1,867 @@ +"""A Multichannel pod's 96-channel head: its mandrels and plunger (D). Reached as +`driver.left_x_arm.head96` (on whichever pod is a Multichannel). + +The head's axes (Z, D) are the pod's, moved through `Pod.move_axes`. The host commands here are the +Master Controller's Multichannel ones: `LT` (`driver/recipes/tip_load.py`) and `HD`. Picking tips up, +dropping them into a rack and discarding them are Biomek's compositions of those: + +- pick up: the gripper turned clear (GR to its park angle), mandrel A1 over its tip spot, Z down to + the seat (the rack's top: on a TL position the rack sits 0.254 cm lower, on the ALP's + adaptor plate), `LT` with the arguments Biomek derives (`TipLoad.from_configuration`: the + force scales with the tips loaded), Z up; +- drop into a rack: mandrel A1 over its spot, Z to the seat + `TipUnloadZOffset`, then the eject; +- discard: mandrel A1 at the trash position's `TipDisposalOffsetX`/`Y` from its back left corner, + the tips' ends `TipDisposalOffsetZ` above it (`resource_model.alps.TipDisposal`), then the eject; +- the eject: the plunger to the bottom of its travel, which drives the ejector, while Z rises by + the plunger's stroke (so the tips stay put as the mandrels leave them), then the plunger to 0, to + the bottom again and to 0, at `TipUnloadShuckSpeed`. + +Partial loads align as STAR's head does: mandrel `channel` over spot `tip_spot`; only mandrels over +a spot of the rack take a tip (Biomek's 12- and 24-tip loads put mandrel A1 over row H or G). +The head has no tip sensor: which mandrels carry tips is its record of the tips it picked up, +which the device saves and restores on the shafts (`BiomekI7Device`'s `state_json`). + +A carried tip's end is the head's Z less the tip's effective length, `TipHeight` less the head's +`TipSeatingDepth` (on the 96-head the seating depth is the head's, not +the tip class's, so the `Tip`'s `fitting_depth`, the Span-8's, is not used here). +""" + +import asyncio +import logging +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7 import targeting +from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.driver import liquid +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import PLUNGER_RECIPES, Homer +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad, load_tips +from pylabrobot.beckman_coulter.biomek_i7.resource_model.alps import BiomekPosition +from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import show_tip +from pylabrobot.beckman_coulter.biomek_i7.techniques import ( + Conditioning, + HeightFrom, + MixHeights, + TipTouch, +) +from pylabrobot.beckman_coulter.biomek_i7.units import ( + offset_to_biomek, + percent_to_field, + rate_to_field, +) +from pylabrobot.beckman_coulter.biomek_i7.units import optional_cm as _cm +from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.resources.container import Container +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.n_channel_pipettes import NChannelPipette +from pylabrobot.resources.plate import Plate +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.beckman_coulter.tips import beckman_coulter_biomek_tip_1070uL +from pylabrobot.resources.tip import Tip +from pylabrobot.resources.tip_rack import TipRack, TipSpot +from pylabrobot.resources.volume_tracker import VolumeTracker, does_volume_tracking + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck + from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + DeviceConfiguration, + PodConfiguration, + ) + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + +logger = logging.getLogger(__name__) + +ROWS, COLUMNS = 8, 12 +# uL: how far a plunger read back from counts may sit below what it was sent to (a count is +# 0.0043 uL on this head). +PLUNGER_TOLERANCE = 0.01 +DEFAULT_TRASH = "TR1" +# The longest tip the 96-head takes (1070 uL and 1025 uL classes: 10.9855 cm), assumed for a +# precautionary discard when no tips are recorded (`discard_any_tips`). +ASSUMED_TIP = beckman_coulter_biomek_tip_1070uL + + +def mandrel_name(row: int, column: int) -> str: + return f"{'ABCDEFGH'[row]}{column + 1}" + + +def mandrel_index(name: str) -> Tuple[int, int]: + """(row, column) of a mandrel or well name such as `A1`, `H12`.""" + row, column = "ABCDEFGH".index(name[0].upper()), int(name[1:]) - 1 + if not (0 <= row < ROWS and 0 <= column < COLUMNS): + raise ValueError(f"no mandrel {name!r} on a 96-channel head") + return row, column + + +@dataclass(frozen=True) +class HeadPlan: + """Where the head goes for a tip operation: mandrel A1's X/Y and the operation's Z, in Biomek's + frame (cm), and which mandrel meets which tip spot.""" + + x: float + y: float + z: float + pairs: Tuple[Tuple[str, TipSpot], ...] = () + + +@dataclass(frozen=True) +class LiquidPlan: + """An aspirate or dispense: mandrel A1's X/Y over the well(s) in Biomek's frame (cm), the + channels, the template's moves (`driver/liquid.py`) and which mandrel works which container.""" + + x: float + y: float + channels: Tuple[liquid.Channel, ...] + steps: Tuple[liquid.Step, ...] + pairs: Tuple[Tuple[str, Container], ...] + + +class Head96: + """The 96-channel head of a Multichannel pod.""" + + # Where neither the caller nor a technique gives a value (STAR P6): the tips' ends 1 mm above + # the bottom, Biomek's Water liquid type's 90 uL/s, the Z speed of its MC techniques. + default_liquid_height: float = 1.0 # mm + default_flow_rate: float = 90.0 # uL/s + default_z_speed: float = 19.0 # mm/s: its MC techniques' 20 % of the Multichannel Z on this unit + + def __init__(self, pod: "Pod"): + self._pod = pod + # The tips on the mandrels, by mandrel name, as this session picked them up. + self._tips: Dict[str, Tip] = {} + # The head in the resource tree, as the STAR's `head96.resource`: its shafts carry the tips. + # Set by the device that models it (`BiomekI7Device`); None when nothing models it. + self.resource: Optional[NChannelPipette] = None + + def __str__(self) -> str: + return f"{self._pod}'s 96-channel head" + + @property + def arm(self) -> "Pod": + """The pod this head is on (STAR's `feature.arm`).""" + return self._pod + + async def home_plunger(self, force: bool = False) -> None: + """Home the plunger, the Master Controller's `HD`; `force` as for `Pod.home`.""" + pod = self._pod + recipe = PLUNGER_RECIPES[pod.module_type] + logger.info("%s HD%s", pod.component, "" if force else " (if not homed)") + try: + await Homer(pod, force=force).run(recipe) + finally: + pod._set_home_positions(Homer.axes(recipe)) + + async def load_tips(self, load: TipLoad) -> int: + """Press the head onto tips, the Master Controller's `LT`: see `driver/recipes/tip_load.py`, and + `TipLoad.from_configuration` for the arguments Biomek would send. Returns the loaded Z, in + counts. + + Raises: + ValueError: for arguments the Master Controller refuses; nothing is sent. + """ + return await load_tips(self._pod, load) + + # -- tips --------------------------------------------------------------------------------------- + + @property + def tips(self) -> List[Optional[str]]: + """Each mandrel's tip (its model, else its name), A1..H12 row by row; None for none. The head + cannot sense tips: these are the ones it picked up, or that its shafts carried when the device + restored the last session's state (`_adopt_tips`).""" + out: List[Optional[str]] = [] + for row in range(ROWS): + for column in range(COLUMNS): + tip = self._tips.get(mandrel_name(row, column)) + out.append(None if tip is None else tip.model or tip.name) + return out + + def _set_tips(self, mandrels: Mapping[str, Optional[Tip]]) -> None: + """Record the tip each of `mandrels` carries (None: none), show it on the mandrel's shaft + (`_show_tips`), and tell the driver (`on_tips_changed`: the device saves its heads' tips).""" + for name, tip in mandrels.items(): + if tip is None: + self._tips.pop(name, None) + else: + self._tips[name] = tip + self._show_tips(list(mandrels)) + if self._pod.driver is not None: + self._pod.driver.on_tips_changed() + + def _adopt_tips(self) -> None: + """Take as carried the tips the head's shafts hold: the device puts them there from the last + session's state.""" + if self.resource is None: + return + for row in range(ROWS): + for column in range(COLUMNS): + name = mandrel_name(row, column) + tip = self.resource.get_item(name).tip + if isinstance(tip, Tip): + self._tips[name] = tip + + def _show_tips(self, mandrels: Optional[Sequence[str]] = None) -> None: + """Put on each of `mandrels`' shafts (all, when None) in the head's model the tip it carries, + and take off the shaft of one that carries none, as the STAR mounts and releases its tips.""" + head = self.resource + if head is None: + return + names = mandrels + if names is None: + names = [mandrel_name(r, c) for r in range(ROWS) for c in range(COLUMNS)] + for name in names: + show_tip(head.get_item(name), self._carried_tip(name)) + + def _carried_tip(self, mandrel: str) -> Optional[Tip]: + """The tip on `mandrel`, or None.""" + return self._tips.get(mandrel) + + def _context(self) -> Tuple["BiomekI7Deck", "DeviceConfiguration", "PodConfiguration"]: + driver, declared = self._pod.driver, self._pod.declared + if driver is None or driver.deck is None or declared is None: + raise RuntimeError(f"{self} needs a deck and a declared configuration (use `BiomekI7`)") + return driver.deck, driver.declared, declared + + def _pairs(self, rack: TipRack, channel: str, tip_spot: str) -> Tuple[Tuple[str, TipSpot], ...]: + """Each mandrel over one of `rack`'s spots, with mandrel `channel` over spot `tip_spot`.""" + cr, cc = mandrel_index(channel) + sr, sc = mandrel_index(tip_spot) + pairs = [] + for r in range(ROWS): + for c in range(COLUMNS): + rr, rc = r - cr + sr, c - cc + sc + if 0 <= rr < rack.num_items_y and 0 <= rc < rack.num_items_x: + pairs.append((mandrel_name(r, c), rack.get_item(mandrel_name(rr, rc)))) + return tuple(pairs) + + def _a1_over( + self, rack: TipRack, channel: str, tip_spot: str, offset: Coordinate + ) -> Tuple[float, float]: + """Mandrel A1's X/Y (Biomek cm) with mandrel `channel` over spot `tip_spot`.""" + deck, configuration, declared = self._context() + spot = targeting.target( + deck, configuration, self._pod.pod_number, rack.get_item(tip_spot), offset=offset + ) + cr, cc = mandrel_index(channel) + geometry = declared.geometry + return spot.x - cc * geometry.mandrel_x_spacing, spot.y - cr * geometry.mandrel_y_spacing + + def _seat(self, rack: TipRack) -> float: + """The seat: the rack's top (the position's Z + its offset for the rack's class + the class's + `Height`), as the logged tip loads put it.""" + deck, configuration, _ = self._context() + return targeting.target(deck, configuration, self._pod.pod_number, rack, z="t").z + + def effective_tip_length(self, tip: Tip) -> float: + """How far below the mandrels `tip`'s end is, mm: its length less the head's + `TipSeatingDepth` (`_effective_tip_length`).""" + return units.to_mm(self._effective_tip_length(tip)) + + def _effective_tip_length(self, tip: Tip) -> float: + """How far below the mandrels `tip`'s end is, cm: its length less the head's `TipSeatingDepth` + (as the logged tip moves confirm).""" + if self._pod.declared is None: + raise RuntimeError(f"{self} needs a declared configuration") + return float(tip.get_size_z() / 10 - self._pod.declared.settings["TipSeatingDepth"]) + + def plan_pick_up( + self, + tip_rack: TipRack, + offset: Coordinate = Coordinate.zero(), + channel: str = "A1", + tip_spot: str = "A1", + ) -> Tuple[HeadPlan, TipLoad]: + """Where a pickup goes, and the `LT` it sends. Only spots holding a tip (when tracked) count. + + Raises: + ValueError: if no mandrel would meet a tip, or the rack is on a deck position that does not + take a 96-head tip load (Biomek's "Multichannel Can Load Tips": only the tip-loading + ALP's positions; elsewhere the press is not meant to land). + """ + deck, _, declared = self._context() + position = targeting.deck_position_of(deck, tip_rack) + if isinstance(position, BiomekPosition) and not position.head96_tip_loading: + raise ValueError( + f"{self}: {position.name} is not a tip-loading position; the 96-head loads tips only on a " + "tip-loading ALP (TipLoad1x1)" + ) + pairs = tuple( + (m, s) for m, s in self._pairs(tip_rack, channel, tip_spot) if not s.tracks_tips or s.tip + ) + if not pairs: + raise ValueError(f"{self}: no tips under the head on {tip_rack.name}") + x, y = self._a1_over(tip_rack, channel, tip_spot, offset) + seat = self._seat(tip_rack) + plan = HeadPlan(x, y, seat, pairs) + return plan, TipLoad.from_configuration(declared, seat, len(pairs)) + + def plan_drop( + self, + tip_rack: TipRack, + offset: Coordinate = Coordinate.zero(), + channel: str = "A1", + tip_spot: str = "A1", + ) -> HeadPlan: + """Where a drop into `tip_rack` goes: the seat + `TipUnloadZOffset`.""" + _, _, declared = self._context() + x, y = self._a1_over(tip_rack, channel, tip_spot, offset) + z = self._seat(tip_rack) + declared.settings["TipUnloadZOffset"] + return HeadPlan(x, y, z, self._pairs(tip_rack, channel, tip_spot)) + + def plan_discard(self, tip_length: float, trash: Optional[Resource] = None) -> HeadPlan: + """Where a discard of tips `tip_length` cm long (effective: `_effective_tip_length`) goes: + mandrel A1 at the trash position's `TipDisposal` X/Y from its back left corner, the tips' ends + its Z above it, as the logged discards put it. + + Raises: + ValueError: for a position that is not a trash (no `tip_disposal`). + """ + deck, configuration, _ = self._context() + position = trash if trash is not None else deck.get_position(DEFAULT_TRASH) + disposal = getattr(position, "tip_disposal", None) + if disposal is None: + raise ValueError(f"{position.name} is not a trash position (no tip disposal offsets)") + corner = targeting.target( + deck, configuration, self._pod.pod_number, position, x="l", y="b", z="b" + ) + z = corner.z + tip_length + disposal.z + return HeadPlan(corner.x + disposal.x, corner.y + disposal.y, z) + + def _tip_length(self, mandrels: List[str]) -> float: + """The longest carried tip's effective length, cm (`_carried_tip`).""" + lengths = [] + for i, key in enumerate(self.tips): + name = mandrel_name(i // COLUMNS, i % COLUMNS) + if key is None or name not in mandrels: + continue + tip = self._carried_tip(name) + if tip is not None: + lengths.append(self._effective_tip_length(tip)) + if not lengths: + raise RuntimeError(f"{self}: the carried tips' length is not known") + return max(lengths) + + def _carried_tip_lengths(self) -> Dict[str, float]: + """`{"Z": cm}`: how far below the mandrels the longest carried tip ends; empty without tips. + + Raises: + RuntimeError: for carried tips whose length is not known. + """ + carried = [ + mandrel_name(i // COLUMNS, i % COLUMNS) for i, t in enumerate(self.tips) if t is not None + ] + return {"Z": self._tip_length(carried)} if carried else {} + + async def pick_up_tips( + self, + tip_rack: TipRack, + offset: Optional[Coordinate] = None, + *, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + channel: str = "A1", + tip_spot: str = "A1", + ) -> None: + """Pick up tips from `tip_rack` with mandrel `channel` over spot `tip_spot` (STAR's `Head96` + signature). Every mandrel over a spot holding a tip takes it. Heights are mm above the deck of + the head's lowest point (the tips' ends when it carries tips, else the mandrels), as STAR's; + None travels and leaves the head as high as it goes. + + Raises: + RuntimeError: if the head already carries tips, or there is no deck. + ValueError: if no mandrel would meet a tip. + """ + if any(t is not None for t in self.tips): + raise RuntimeError(f"{self} already carries tips; drop or discard them first") + plan, load = self.plan_pick_up(tip_rack, offset or Coordinate.zero(), channel, tip_spot) + _, _, declared = self._context() + pod = self._pod + logger.info("%s pick up %d tips from %s", pod.component, len(plan.pairs), tip_rack.name) + await self._clear_gripper() + await pod._move_over( + {"X": declared.to_counts("X", plan.x), "Y": declared.to_counts("Y", plan.y)}, + minimum_traverse_height=_cm(minimum_traverse_height_start), + ) + await pod.move_axes({"Z": declared.to_counts("Z", plan.z)}, 1000) + await self.load_tips(load) + picked: Dict[str, Optional[Tip]] = {} + for mandrel, spot in plan.pairs: + tip = spot.tip_for_pickup() + if spot.tracks_tips: + spot.unassign_tip() + self._tips[mandrel] = tip + picked[mandrel] = tip + self._set_tips(picked) + await pod._lift_channels(_cm(minimum_traverse_height_end)) + + async def drop_tips( + self, + resource: TipRack, + offset: Optional[Coordinate] = None, + *, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + channel: str = "A1", + tip_spot: str = "A1", + ) -> None: + """Put the head's tips into `resource`, mandrel `channel` over spot `tip_spot`, and eject them. + Heights as `pick_up_tips`. + + Raises: + RuntimeError: if the head carries no tips, or there is no deck. + ValueError: if a mandrel with a tip would meet an occupied spot, or none would meet a spot. + """ + carried = self._carried() + plan = self.plan_drop(resource, offset or Coordinate.zero(), channel, tip_spot) + targets = [(m, s) for m, s in plan.pairs if m in carried] + if not targets: + raise ValueError(f"{self}: no mandrel with a tip is over {resource.name}") + occupied = [s.name for _, s in targets if s.tracks_tips and s.tip is not None] + if occupied: + raise ValueError(f"{self}: tip spots {occupied} already hold tips") + await self._eject_at(plan, minimum_traverse_height_start) + for mandrel, spot in targets: + tip = self._tips.pop(mandrel, None) + if spot.tracks_tips: + spot.assign_tip(tip if tip is not None else spot.make_tip()) + self._set_tips({m: None for m in carried}) + await self._pod._lift_channels(_cm(minimum_traverse_height_end)) + + async def discard_tips( + self, + *, + trash: Optional[Resource] = None, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Eject the head's tips into the trash (`TR1` by default). Heights as `pick_up_tips`. + + Raises: + RuntimeError: if the head carries no tips, or there is no deck. + """ + carried = self._carried() + plan = self.plan_discard(self._tip_length(carried), trash) + await self._eject_at(plan, minimum_traverse_height_start) + for mandrel in carried: + self._tips.pop(mandrel, None) + self._set_tips({m: None for m in carried}) + await self._pod._lift_channels(_cm(minimum_traverse_height_end)) + + async def discard_any_tips(self, trash: Optional[Resource] = None) -> None: + """Eject into the trash (`TR1` by default) whatever tips the head may carry, recorded or not: + the head has no tip sensor, so a lost record would otherwise leave tips on it unseen. + With tips recorded, as `discard_tips`; with none, the head travels and ejects as if it carried + the longest tip it takes (1070 uL, `ASSUMED_TIP`), so its travel clears the deck for any tip + and an ejected tip of any length falls into the bin. With no tips on, the eject runs over the + empty bin. `BiomekI7.setup` does this by default. + + Raises: + RailCollisionError, ValueError: if the way to the trash is not clear for the longest tip + (the move is refused before anything is sent). + """ + if any(t is not None for t in self.tips): + await self.discard_tips(trash=trash) + return + length = self._effective_tip_length(ASSUMED_TIP("assumed tip")) + logger.warning( + "%s: discarding any tips on the 96-head (it cannot sense them), as if %.2f cm long", + self._pod.component, + length, + ) + plan = self.plan_discard(length, trash) + await self._eject_at(plan, None, tip_length=length) + await self._pod._lift_channels(None, tip_lengths={"Z": length}) + + def _carried(self) -> List[str]: + carried = [ + mandrel_name(i // COLUMNS, i % COLUMNS) for i, t in enumerate(self.tips) if t is not None + ] + if not carried: + raise RuntimeError(f"{self} carries no tips") + return carried + + async def _eject_at( + self, plan: HeadPlan, start: Optional[float], tip_length: Optional[float] = None + ) -> None: + """Travel over `plan` and eject there. `tip_length`: the tip the travel clears the deck for, + cm; the recorded tips' when None.""" + _, _, declared = self._context() + pod = self._pod + logger.info("%s eject tips at X %.3f Y %.3f Z %.3f cm", pod.component, plan.x, plan.y, plan.z) + await self._clear_gripper() + await pod._move_over( + {"X": declared.to_counts("X", plan.x), "Y": declared.to_counts("Y", plan.y)}, + minimum_traverse_height=_cm(start), + tip_lengths=None if tip_length is None else {"Z": tip_length}, + ) + await pod.move_axes({"Z": declared.to_counts("Z", plan.z)}, 1000) + await self.eject() + + async def eject(self) -> None: + """Push the tips off the mandrels where the head is: the plunger to the bottom of its travel + (which drives the ejector) while Z rises by the plunger's stroke, so the tips stay where they + are as the mandrels leave them; then the plunger to 0, the bottom and 0 again; all at + `TipUnloadShuckSpeed`.""" + _, _, declared = self._context() + pod = self._pod + bottom = declared.limits["D"][0] # uL, below 0: the ejector stroke + stroke = -bottom / declared.settings["DAxisULPerCM"] # cm the plunger travels + speed = percent_to_field(declared.settings["TipUnloadShuckSpeed"]) + z = declared.to_value("Z", pod.cpositions["Z"][1]) + d_bottom, d_zero = declared.to_counts("D", bottom), declared.to_counts("D", 0.0) + await pod.move_axes({"Z": declared.to_counts("Z", z + stroke), "D": d_bottom}, speed) + for target in (d_zero, d_bottom, d_zero): + await pod.move_axes({"D": target}, speed) + + async def _clear_gripper(self) -> None: + """Turn the gripper to its park angle (GR), as Biomek does before the head works the deck. + + Raises: + RuntimeError: while the gripper holds labware (turning would swing it). + """ + if self._pod._held_labware is not None: + raise RuntimeError(f"{self}: the gripper holds labware; place it before the head works") + _, _, declared = self._context() + gr = declared.to_counts("GR", declared.park["GR"]) + if self._pod.cpositions["GR"][1] != gr: + await self._pod.move_axes({"GR": gr}) + + # -- aspirate and dispense ---------------------------------------------------------------------- + + def _tip_on(self, mandrel: str) -> Tip: + tip = self._carried_tip(mandrel) + if tip is None: + row, column = mandrel_index(mandrel) + key = self.tips[row * COLUMNS + column] + raise RuntimeError(f"{self}: the tip on {mandrel} ({key or 'none'}) is not known") + return tip + + def _wells(self, resource: Resource) -> Tuple[Tuple[str, Container], ...]: + """Each carrying mandrel and the container under it: the wells of a 96-well plate (mandrel A1 + over well A1), or one container (a reservoir's, or a 1-well plate's) under every mandrel.""" + carried = self._carried() + if isinstance(resource, Plate) and resource.num_items == ROWS * COLUMNS: + return tuple((m, resource.get_well(m)) for m in carried) + container: Optional[Resource] = resource + if isinstance(resource, Plate) and resource.num_items == 1: + container = resource.get_item(0) + if not isinstance(container, Container): + raise ValueError( + f"{self}: aspirate or dispense from a 96-well plate or one container, not {resource.name}" + ) + return tuple((m, container) for m in carried) + + def plan_liquid( + self, + operation: str, + resource: Resource, + volume: float, + settings: liquid.Settings, + flow_rate: float, + ) -> LiquidPlan: + """Where an aspirate (`operation` "aspirate") or dispense goes and the template's moves: mandrel + A1 over well A1 of a 96-well plate, or the head centred over one container; the liquid's levels + from the containers' trackers when volume tracking is on (else not known). + + Raises: + ValueError: for a height that cannot be worked out (from the liquid, or following, in a + container without a height <-> volume function or with untracked contents). + """ + deck, configuration, declared = self._context() + number = self._pod.pod_number + pairs = self._wells(resource) + tracking = does_volume_tracking() + share = len(pairs) if len({id(c) for _, c in pairs}) == 1 else 1 + channels = [] + for mandrel, container in pairs: + shape = liquid.ContainerShape(container) + tip = self._tip_on(mandrel) + channels.append( + liquid.Channel( + name=mandrel, + well=shape, + bottom=targeting.target(deck, configuration, number, container, z="b").z + + shape.floor / 10, + tip_length=self._effective_tip_length(tip), + volume=volume, + held=container.tracker.get_used_volume() if tracking else None, + tip_radius=tip.get_size_x() / 20, # its diameter, mm -> its radius, cm + share=share, + ) + ) + geometry = declared.geometry + if share > 1: # one container under the head: the head centred over it + centre = targeting.target(deck, configuration, number, pairs[0][1]) + x = centre.x - (COLUMNS - 1) / 2 * geometry.mandrel_x_spacing + y = centre.y - (ROWS - 1) / 2 * geometry.mandrel_y_spacing + else: + at = targeting.target(deck, configuration, number, pairs[0][1]) + row, column = mandrel_index(pairs[0][0]) + x = at.x - column * geometry.mandrel_x_spacing + y = at.y - row * geometry.mandrel_y_spacing + plan = (liquid.plan_aspirate if operation == "aspirate" else liquid.plan_dispense)( + channels, settings, flow_rate + ) + return LiquidPlan(x, y, tuple(channels), tuple(plan), tuple(pairs)) + + def moves( + self, plan: LiquidPlan, offset: Coordinate, d_start: float + ) -> List[Tuple[Dict[str, float], int, float]]: + """The plan as the head's moves after its travel to the well: (axis targets in Biomek's units: + X/Y/Z cm, D uL; speed field; delay s after). The approach carries `offset` (mm, PyLabRobot's + frame) as the reservoir templates' first move does; the plunger starts at `d_start` uL. One Z + serves every mandrel: the lowest any of them needs. + + Raises: + ValueError: for a dispense of more than the tips hold. + """ + x, y = offset_to_biomek(plan.x, plan.y, offset) + d = d_start + out: List[Tuple[Dict[str, float], int, float]] = [] + first = True + for step in plan.steps: + if isinstance(step, liquid.ZMove): + targets: Dict[str, float] = {"Z": min(step.z.values())} + if first and (offset.x or offset.y): + targets.update(X=x, Y=y) + first = False + out.append((targets, step.speed, 0.0)) + elif isinstance(step, liquid.PlungerMove): + amount = next(iter(step.volume.values())) + before, d = d, 0.0 if step.empty else d + amount + if d < -PLUNGER_TOLERANCE: + raise ValueError(f"{self}: a dispense of {-amount:.3f} uL is more than the tips hold") + d = max(d, 0.0) + if abs(d - before) <= PLUNGER_TOLERANCE: + continue # nothing to move (a 0 uL operation): Biomek sends no move + targets = {"D": round(d, 6)} + if step.z: + targets["Z"] = min(step.z.values()) + out.append((targets, self._d_speed(step.flow_rate), step.delay)) + elif step.dx or step.dy: + out.append(({"X": x + step.dx, "Y": y + step.dy}, step.speed, 0.0)) + out.append(({"X": x, "Y": y}, step.speed, step.delay)) + return out + + def _d_speed(self, flow_rate: float) -> int: + """The `AM` speed field for the plunger at `flow_rate` uL/s: per mille of D's maximum.""" + return rate_to_field(self._pod, "D", flow_rate, clamp=True) + + def _settings(self, **given: Any) -> liquid.Settings: + """The template's settings: the arguments given, else this feature's `default_*`.""" + z_speed = given.pop("z_speed", None) + rate = self.default_z_speed if z_speed is None else z_speed + base = liquid.Settings( + liquid_height=self.default_liquid_height, + z_speed_field=units.rate_to_field(self._pod, "Z", rate), + ) + return liquid.settings(base, **given) + + async def _run_liquid( + self, + plan: LiquidPlan, + offset: Coordinate, + minimum_traverse_height_start: Optional[float], + minimum_traverse_height_end: Optional[float], + ) -> None: + _, _, declared = self._context() + pod = self._pod + d_start = declared.to_value("D", pod.cpositions["D"][1]) + # Below 0 the plunger is in the ejector's stroke (after homing or a tip load's push-off): + # Biomek brings it to 0 at full speed before pipetting. + below = d_start < -PLUNGER_TOLERANCE + moves = self.moves(plan, offset, 0.0 if below else d_start) # checked before anything moves + if below: + await pod.move_axes({"D": declared.to_counts("D", 0.0)}) + await self._clear_gripper() + await pod._move_over( + {"X": declared.to_counts("X", plan.x), "Y": declared.to_counts("Y", plan.y)}, + minimum_traverse_height=_cm(minimum_traverse_height_start), + ) + for targets, speed, delay in moves: + await pod.move_axes({a: declared.to_counts(a, v) for a, v in targets.items()}, speed) + if delay > 0: + await asyncio.sleep(delay) + await pod._lift_channels(_cm(minimum_traverse_height_end)) + + def _book(self, plan: LiquidPlan, volume: float, aspirate: bool) -> List[Any]: + """Move `volume` per mandrel between the containers' and the tips' trackers (pending, to commit + or roll back).""" + if not does_volume_tracking(): + return [] + booked = [] + for mandrel, container in plan.pairs: + tip = self._tips.get(mandrel) + giver: Optional[VolumeTracker] = container.tracker + taker: Optional[VolumeTracker] = tip.tracker if tip is not None else None + if not aspirate: + giver, taker = taker, giver + if giver is not None: + booked.append(giver) + giver.remove_liquid(min(volume, giver.get_used_volume())) + if taker is not None: + booked.append(taker) + taker.add_liquid(volume) + return booked + + async def _liquid( + self, + operation: str, + resource: Resource, + volume: float, + offset: Optional[Coordinate], + flow_rate: float, + settings: liquid.Settings, + start: Optional[float], + end: Optional[float], + ) -> None: + offset = offset or Coordinate.zero() + plan = self.plan_liquid(operation, resource, volume, settings, flow_rate) + aspirate = operation == "aspirate" + moved = volume + (settings.conditioning.excess if aspirate else 0.0) + if settings.mix is not None: + liquid.check_tips_empty_for_mix( + self, [self._tips.get(m) for m, _ in plan.pairs], + [0.0 if aspirate else volume] * len(plan.pairs), settings, + ) # fmt: skip + logger.info( + "%s %s %.3f uL %s %s", self._pod.component, operation, volume, + "from" if aspirate else "into", resource.name, + ) # fmt: skip + booked = self._book(plan, moved, aspirate) + try: + await self._run_liquid(plan, offset, start, end) + except BaseException: + for tracker in booked: + tracker.rollback() + raise + for tracker in booked: + tracker.commit() + + async def aspirate( + self, + resource: Resource, + volume: float, + offset: Optional[Coordinate] = None, + liquid_height: Optional[float] = None, + lld_mode: Optional[Any] = None, + flow_rate: Optional[float] = None, + *, + height_from: Optional[HeightFrom] = None, + follow_liquid: Optional[bool] = None, + minimum_height: Optional[float] = None, + z_speed: Optional[float] = None, + approach_height: Optional[float] = None, + settling_time: Optional[float] = None, + blow_out_air_volume: Optional[float] = None, + pre_mix: Optional[Mix] = None, + mix_heights: Optional[MixHeights] = None, + transport_air_volume: Optional[float] = None, + conditioning: Optional[Conditioning] = None, + tip_touch: Optional[TipTouch] = None, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Draw `volume` uL into every carried tip, from a 96-well plate (mandrel A1 over well A1) or + one container (the head centred over it), as Biomek's "MC Pipetting" template does (see + `driver/liquid.py`). + + Args: + resource: a plate of 96 wells, or a container (a reservoir's well, a 1-well plate). + volume: uL per tip. + offset: added to the target, mm (a reservoir template's X offset is (-2, 0, 0)). + liquid_height: mm from `height_from` of the tips' ends while drawing + (`default_liquid_height`). + lld_mode: the head has no liquid-level sensor: None or OFF only. + flow_rate: uL/s (`default_flow_rate`). + height_from: "bottom" (default), "top" or "liquid" (needs volume tracking). + follow_liquid: the tips follow the liquid down as it is drawn. + minimum_height: mm above the bottom no height goes below (Biomek's Minimum Height). + z_speed: mm/s of Z for the moves in the well (`default_z_speed`); above Z's maximum is + refused. + approach_height: mm above the top the head comes down to first (1). + settling_time: s after drawing (Biomek's aspirate delay). + blow_out_air_volume: uL of air drawn above the well first, for a blowout. + pre_mix: mixed before drawing (Biomek's Mix): `repetitions` times, draw and push back + `volume` uL at `flow_rate` uL/s, at `z_speed`; `auto_surface_following` follows the liquid + while drawing and pushing (Biomek's Follow Liquid). The tips must hold no liquid. + mix_heights: where the mix draws and pushes; the operation's own height when None. + transport_air_volume: uL of air drawn after leaving the well (the trailing air gap). + conditioning: extra drawn and pushed back before leaving (Biomek's conditioning). + tip_touch: a touch-off before leaving. + minimum_traverse_height_start / _end: as `pick_up_tips`. + + Raises: + NotImplementedError: for a liquid-level sensing mode. + RuntimeError: if the head carries no tips. + ValueError: for a resource or height that cannot be worked out, or more than the tips hold. + """ + _no_lld(self, lld_mode) + settings = self._settings( + liquid_height=liquid_height, height_from=height_from, follow_liquid=follow_liquid, + minimum_height=minimum_height, z_speed=z_speed, approach_height=approach_height, + settling_time=settling_time, blow_out_air_volume=blow_out_air_volume, + transport_air_volume=transport_air_volume, conditioning=conditioning, tip_touch=tip_touch, + ) # fmt: skip + settings = liquid.with_mix(settings, pre_mix, mix_heights) + await self._liquid( + "aspirate", resource, volume, offset, flow_rate or self.default_flow_rate, settings, + minimum_traverse_height_start, minimum_traverse_height_end, + ) # fmt: skip + + async def dispense( + self, + resource: Resource, + volume: float, + offset: Optional[Coordinate] = None, + liquid_height: Optional[float] = None, + lld_mode: Optional[Any] = None, + flow_rate: Optional[float] = None, + *, + height_from: Optional[HeightFrom] = None, + follow_liquid: Optional[bool] = None, + minimum_height: Optional[float] = None, + z_speed: Optional[float] = None, + approach_height: Optional[float] = None, + settling_time: Optional[float] = None, + post_mix: Optional[Mix] = None, + mix_heights: Optional[MixHeights] = None, + blow_out_air_volume: Optional[float] = None, + blow_out_delay: Optional[float] = None, + tip_touch: Optional[TipTouch] = None, + empty: bool = False, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Push `volume` uL out of every carried tip, into a 96-well plate or one container, as + Biomek's "MC Pipetting" template does (see `driver/liquid.py`); arguments as `aspirate`. + + Args: + follow_liquid: the tips follow the liquid up as it fills. + post_mix, mix_heights: mixed after dispensing, as `aspirate`'s `pre_mix`; the tips must be + left holding no liquid (Biomek: "The mix operation cannot begin until tips are empty"). + blow_out_air_volume: uL of air pushed out after the liquid (Biomek's blowout), then + `blow_out_delay` s. + empty: push out everything the tips hold, at the starting height (Biomek's Empty Tips). + + Raises: + NotImplementedError: for a liquid-level sensing mode. + RuntimeError: if the head carries no tips. + ValueError: for a resource or height that cannot be worked out, or more than the tips hold. + """ + _no_lld(self, lld_mode) + settings = self._settings( + liquid_height=liquid_height, height_from=height_from, follow_liquid=follow_liquid, + minimum_height=minimum_height, z_speed=z_speed, approach_height=approach_height, + settling_time=settling_time, blow_out_air_volume=blow_out_air_volume, + blow_out_delay=blow_out_delay, tip_touch=tip_touch, empty=empty, + ) # fmt: skip + settings = liquid.with_mix(settings, post_mix, mix_heights) + await self._liquid( + "dispense", resource, volume, offset, flow_rate or self.default_flow_rate, settings, + minimum_traverse_height_start, minimum_traverse_height_end, + ) # fmt: skip + + +def _no_lld(head: Head96, lld_mode: Any) -> None: + if lld_mode is not None and getattr(lld_mode, "name", lld_mode) != "OFF": + raise NotImplementedError(f"{head}: the 96-channel head has no liquid-level sensing") diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py index e7fb09bec0f..238d5d4aeb9 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py @@ -1221,24 +1221,13 @@ async def aspirate( liquid_heights: mm from `height_from`, one per channel or one for all. lld_mode: liquid-level sensing: None or OFF only, until it is built. flow_rates: uL/s; the pumps move together, so one rate for all. - height_from: "bottom" (default), "top" or "liquid" (needs volume tracking). - follow_liquid: the tips follow the liquid down as it is drawn. - minimum_height: mm above the bottom no height goes below (Biomek's Minimum Height). - z_speed: mm/s of Z for the moves in the well (`default_z_speed`); above Z's maximum is - refused. - approach_height: mm above the top the probes come down to first. - settling_times: s after drawing (Biomek's aspirate delay), STAR's per-channel list. - blow_out_air_volumes: uL of air drawn above the well first, for a blowout; per channel. - transport_air_volumes: uL of air drawn after leaving the well (the trailing air gap); per - channel. The template applies one value to every probe, so the per-channel values must - agree. - pre_mixes: STAR's per-channel `Mix`es, one mix for every probe or None for all, mixed before - drawing (Biomek's Mix): `repetitions` times, draw and push back `volume` uL at `flow_rate` - uL/s, at `z_speed`; `auto_surface_following` follows the liquid while drawing and pushing - (Biomek's Follow Liquid). The tips must hold no liquid. - mix_heights: where the mix draws and pushes; the operation's own height when None. - conditioning: extra drawn and pushed back before leaving (Biomek's conditioning). - tip_touch: a touch-off before leaving. + settling_times, blow_out_air_volumes, transport_air_volumes: STAR's per-channel lists, as + `Head96.aspirate`'s `settling_time`, `blow_out_air_volume`, `transport_air_volume`; the + template applies one value to every probe, so the values must agree. + pre_mixes: STAR's per-channel `Mix`es, as `Head96.aspirate`'s `pre_mix`: one mix for every + probe, or None for all. + height_from, follow_liquid, minimum_height, z_speed, approach_height, conditioning, + tip_touch, mix_heights: as `Head96.aspirate`. cutoff_velocity: the pumps' cutoff velocity, uL/s (Biomek's technique; `CV`). lls_sensitivity: the liquid-level sensors' sensitivity, set before each move measured from the liquid (Biomek's conductivity; `SS`). @@ -1292,16 +1281,8 @@ async def dispense( minimum_traverse_height_end: Optional[float] = None, ) -> None: """Push `volumes` (uL, one per channel) into `containers`, as Biomek's "S8 Pipetting" template - does; arguments as `aspirate`. The pumps stop at `SystemTrailingAirgap`. - - Args: - follow_liquid: the tips follow the liquid up as it fills. - post_mixes, mix_heights: mixed after dispensing, one `Mix` for every probe, as `aspirate`'s - `pre_mixes`; the tips must be left holding no liquid (Biomek: "The mix operation cannot - begin until tips are empty"). - blow_out_air_volumes: uL of air pushed out after the liquid (Biomek's blowout), then - `blow_out_delay` s. - empty: push out everything the tips hold, at the starting height (Biomek's Empty Tips). + does; arguments as `aspirate` and `Head96.dispense` (`post_mixes` one `Mix` for every probe, + as `pre_mixes`). The pumps stop at `SystemTrailingAirgap`. Raises: NotImplementedError: for liquid-level sensing. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index 9fd03d5f242..9546ea4817f 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -1,5 +1,6 @@ """One pod: an arm on the shared X rail, its ACE module, and the axes that module drives.""" +import asyncio import logging import math from dataclasses import dataclass, field @@ -41,6 +42,7 @@ HOME_RECIPES, Homer, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail if TYPE_CHECKING: @@ -57,6 +59,7 @@ # module type is what the board reports (Get Module ID, `protocol.MODULE_TYPES`); a new pod type is # a new entry here and in the motor tables. MODULE_FEATURES: Dict[str, Tuple[str, ...]] = { + "multichannel": ("head96",), "span8": ("pipettes",), } # The axes that change what a pod takes up along the X rail. @@ -114,9 +117,9 @@ class Pod: Holds what every pod has: one board and its axes, moved together (`move_axes`, the Master Controller's `AM`), the position record the Master Controller keeps, homing, and the pod's pose - on the shared X rail. `module_type` is what the board reports itself to be: `multichannel` (a - 96-channel head) or `span8` (eight independent channels). What else the pod carries is its - features (`MODULE_FEATURES`): on a `span8`, its channels (`pipettes`). + on the shared X rail. `module_type` says what else the pod carries, as features + (`MODULE_FEATURES`): `multichannel` a 96-channel head (`head96`), `span8` eight independent + channels (`pipettes`). """ def __init__( @@ -155,6 +158,9 @@ def __init__( # clamped to each pump's range when used. self._valves: Dict[str, Optional[p.Valve]] = {a.name: None for a in self.axes if a.is_pump} self._cutoff_velocity = 0 + # Set while the interlock is tripped, shared by the driver (`BiomekI7Driver.interlock_tripped`); + # None for a pod used without one. Waits that the Master Controller abandons on a trip watch it. + self.interlock_tripped: Optional[asyncio.Event] = None # The height the channels rise to before traveling over the deck, mm of the channels' bottom # above the deck: STAR's `default_minimum_traverse_height`. Seeded from Biomek's "Safe Height" # (`GlobalMinSafeHeight`) when it is set; None, as on an instrument where it is not (-100000), @@ -169,6 +175,7 @@ def __init__( self._listeners: List[Callable[["Pod"], None]] = [] # What the pod carries (STAR's arm features): what its module type has (`MODULE_FEATURES`). features = MODULE_FEATURES.get(module_type, ()) + self.head96: Optional[Head96] = Head96(self) if "head96" in features else None self.pipettes: Optional[Pipettes] = Pipettes(self) if "pipettes" in features else None @property @@ -906,7 +913,8 @@ def _carried_tip_lengths(self) -> Dict[str, float]: Raises: RuntimeError: for a carried tip whose length is not known. """ - return {} if self.pipettes is None else self.pipettes._carried_tip_lengths() + feature = self.head96 if self.head96 is not None else self.pipettes + return {} if feature is None else feature._carried_tip_lengths() def _traverse_targets( self, minimum_traverse_height: Optional[float], tip_lengths: Mapping[str, float] diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py new file mode 100644 index 00000000000..9af9752d13d --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py @@ -0,0 +1,108 @@ +"""The Multichannel pod's 96-channel head (`Pod.head96`) on the simulator: loading tips (`LT`), against +an `LT` Biomek logged, request for request.""" + +import dataclasses +import struct + +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ( + PLUNGER_RECIPES, + AtValue, + Home, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration + +# A logged `LT`: 20 µL tips on this instrument (2026-07-31), with no settling wait. +LOGGED = "LT 43176 -50081 518.750 100 2.000 -48673 50 31216 -47926 50 43176" + + +class Head96Tests(PodMoveTest): + async def test_press_stops_on_the_tips_and_reports_where(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + head96 = pod.head96 + assert head96 is not None + usb = self.usb(driver, "multichannel") + await pod.move_axes({"Z": -46881, "D": 43176}) + usb.axis_model("Z").obstacle = -48983 # the tips' collars + self.mark(driver) + load = dataclasses.replace(TipLoad.parse(LOGGED), settling_time=0.0) + self.assertEqual(await head96.load_tips(load), -48983) + sent = self.sent(driver, "multichannel") + self.assertEqual( + [n for n, _ in sent], + [ + # D is already at load_d. Press Z, force-limited. + "Set Move Parameters", + "Move All", + # Read Z: the loaded Z. + "Stop Motion Service", + "Set State", + "Get Current Position", + # Relieve, still force-limited. + "Set Move Parameters", + "Move All", + # Read Z again; the simulated drive is where it was sent, so the unforced relieve sends + # nothing (Biomek's drive had eased off a few counts, and it moved). + "Stop Motion Service", + "Set State", + "Get Current Position", + # Leave: D, then Z, as the Master Controller sends them. + "Set Move Parameters", + "Set Move Parameters", + "Move All", + # End: D back. + "Set Move Parameters", + "Move All", + ], + ) + smp = [params for name, params in sent if name == "Set Move Parameters"] + force_and_position = [struct.unpack_from(" None: + driver = await self.homed() + head96 = self.pod(driver, "left").head96 + assert head96 is not None + load = TipLoad.parse(LOGGED) + for bad in ( + dataclasses.replace(load, load_force=-1.0), + dataclasses.replace(load, load_speed=0), + dataclasses.replace(load, leave_speed=1001), + dataclasses.replace(load, settling_time=-0.5), + dataclasses.replace(load, load_z=10**9), + ): + with self.assertRaises(ValueError): + await head96.load_tips(bad) + self.assertEqual(self.sent(driver, "multichannel"), []) + self.assertEqual(self.sent(driver, "span8"), []) + + def test_parse(self) -> None: + load = TipLoad.parse(LOGGED) + self.assertEqual((load.load_force, load.settling_time, load.end_d), (518.75, 2.0, 43176)) + with self.assertRaises(ValueError): + TipLoad.parse("AM 1 2 3") + + def test_the_plunger_homes_to_its_zero(self) -> None: + # The plunger's approach is its zero in the pod's conversion: the 43176 counts Biomek's HD sent. + self.assertEqual(PLUNGER_RECIPES["multichannel"], (Home("D", AtValue(0.0)),)) + self.assertEqual(generic_configuration().pods["left"].to_counts("D", 0.0), 43176) + + def test_arguments_from_the_configuration_are_biomeks(self) -> None: + # Two logged LTs: 12 tips seated at 21.55 cm, and a full head of 96 at 27.3557 cm. + pod = generic_configuration().pod("left") + self.assertEqual(TipLoad.from_configuration(pod, 21.55, 12), TipLoad.parse(LOGGED)) + self.assertEqual( + TipLoad.from_configuration(pod, 27.3557, 96), + TipLoad.parse("LT 43176 -35219 2400.000 100 2.000 -33811 50 31216 -33063 50 43176"), + ) + with self.assertRaises(ValueError): + TipLoad.from_configuration(pod, 21.55, 97) + with self.assertRaises(ValueError): + TipLoad.from_configuration(generic_configuration().pod("right"), 21.55, 8) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py new file mode 100644 index 00000000000..ff86af31c22 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py @@ -0,0 +1,107 @@ +"""The 96-head picking up, dropping and discarding tips on the simulator, on the deck of a method +Biomek's logs ran (a dilution), against what Biomek sent for the same operations.""" + +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.resources import set_tip_tracking + +# The `LT` Biomek sent for a full load of BC1025F tips at TL1 (2026-10-20). +LOGGED_LT = "LT 43176 -35219 2400.000 100 2.000 -33811 50 31216 -33063 50 43176" + + +class Head96TipTests(PodMoveTest): + async def setup_deck(self): # type: ignore[no-untyped-def] + driver = await self.homed() + lh = BiomekI7(driver=driver, deck=generic_deck()) + place_labware( + lh.deck, + [ + {"position": "TL1", "class": "BC1025F", "name": "BufferTips"}, + {"position": "TL4", "class": "BC230", "name": "SmallTips"}, + ], + ) + head96 = self.pod(driver, "left").head96 + assert head96 is not None + return driver, lh, head96 + + async def test_pick_up_sends_biomeks_lt_and_records_the_tips(self) -> None: + driver, lh, head96 = await self.setup_deck() + rack = lh.deck.get_resource("BufferTips") + plan, load = head96.plan_pick_up(rack) + self.assertEqual(load, TipLoad.parse(LOGGED_LT)) + self.assertAlmostEqual(plan.x, 12.701, delta=0.0015) + self.assertAlmostEqual(plan.y, 37.45, delta=0.0015) + self.assertAlmostEqual(plan.z, 27.356, delta=0.0015) + await head96.pick_up_tips(rack) + self.assertEqual(sum(t is not None for t in head96.tips), 96) + self.assertEqual(head96.tips[0], "beckman_coulter_biomek_tip_1025uL_filter") + # As the STAR shows them: each tip on its mandrel's shaft in the head's model. + assert head96.resource is not None + shafts = head96.resource.get_all_items() + self.assertTrue(all(shaft.has_tip() for shaft in shafts)) + self.assertEqual(len({shaft.tip.name for shaft in shafts}), 96) # type: ignore[union-attr] + with self.assertRaises(RuntimeError): + await head96.pick_up_tips(rack) + + async def test_tips_load_only_on_a_tip_loading_position(self) -> None: + # Biomek's "Multichannel Can Load Tips": the TipLoad1x1 ALP's position, not a static one. + driver, lh, head96 = await self.setup_deck() + place_labware(lh.deck, [{"position": "P5", "class": "BC230", "name": "StaticTips"}]) + with self.assertRaises(ValueError): + head96.plan_pick_up(lh.deck.get_resource("StaticTips")) + + async def test_a_partial_load_counts_only_the_tips_under_the_head(self) -> None: + driver, lh, head96 = await self.setup_deck() + rack = lh.deck.get_resource("SmallTips") + # Biomek's 12-tip loads: mandrel A1 over row H, so only row A meets tips. + plan, load = head96.plan_pick_up(rack, tip_spot="H1") + self.assertEqual(len(plan.pairs), 12) + self.assertEqual(load.load_force, 518.75) + self.assertEqual( + load, TipLoad.parse("LT 43176 -50081 518.750 100 2.000 -48673 50 31216 -47926 50 43176") + ) + + async def test_tracked_racks_give_up_their_tips(self) -> None: + set_tip_tracking(True) + self.addCleanup(set_tip_tracking, False) + driver, lh, head96 = await self.setup_deck() + rack = lh.deck.get_resource("SmallTips") + await head96.pick_up_tips(rack, tip_spot="H1") # row H gone + plan, load = head96.plan_pick_up(rack, tip_spot="G1") # rows A, B over G, H: only G left + self.assertEqual(len(plan.pairs), 12) + self.assertIsNone(rack.get_item("H1").tip) + # Back into the rack where they came from, then the rack holds them again. + assert head96.resource is not None + tip = head96.resource.get_item("A1").tip + self.assertIsNotNone(tip) + await head96.drop_tips(rack, tip_spot="H1") + self.assertIs(rack.get_item("H1").tip, tip) # the same tip, off the shaft and back in its spot + self.assertTrue(all(t is None for t in head96.tips)) + self.assertFalse(any(shaft.has_tip() for shaft in head96.resource.get_all_items())) + + async def test_discard_and_eject(self) -> None: + driver, lh, head96 = await self.setup_deck() + rack = lh.deck.get_resource("SmallTips") + await head96.pick_up_tips(rack) + # T230 tips over the trash: Z = TR1's Z + their effective length (5.1435 - TipSeatingDepth + # 0.7074) + TipDisposalOffsetZ 5.896 = 31.034 cm, as Biomek logged. + self.assertAlmostEqual(head96._tip_length(["A1"]), 4.4361) + plan = head96.plan_discard(head96._tip_length(["A1"])) + self.assertAlmostEqual(plan.x, 10.947, delta=0.0015) + self.assertAlmostEqual(plan.y, 18.703, delta=0.0015) + self.assertAlmostEqual(plan.z, 31.034, delta=0.0015) + self.mark(driver) + await head96.discard_tips() + pod = self.pod(driver, "left") + d = pod.declared + assert d is not None + # The eject ends with the plunger at 0 and the tips gone from the head. + self.assertEqual(pod.cpositions["D"][1], d.to_counts("D", 0.0)) + self.assertTrue(all(t is None for t in head96.tips)) + assert head96.resource is not None + self.assertFalse(any(shaft.has_tip() for shaft in head96.resource.get_all_items())) + with self.assertRaises(RuntimeError): + await head96.discard_tips() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py index 9f21856d1ff..9d1207679b3 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/homing_tests.py @@ -85,6 +85,13 @@ ("Set Move Parameters", "X", 35840), ("Move", "X", 30000), ] +# Then the head's plunger (`HD`), as the same log shows it: D is homed after the pod. +FORCED_HD_MULTICHANNEL = [ + ("Set State", "D", None), + ("Set Move Parameters", "D", 43176), + ("Move", "D", 30000), + ("Home", "D", None), +] def zero_sequence(message: bytes) -> str: @@ -206,9 +213,10 @@ async def test_forced_on_a_homed_instrument_is_biomeks_home_all(self) -> None: elif name in ("Move", "Move All"): value = struct.unpack_from(" None: diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py index 5b3740d131c..a3abd935330 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py @@ -1,11 +1,13 @@ -"""Aspirate and dispense on the Span-8 on the simulator, on the deck of a method Biomek's logs ran +"""Aspirate and dispense on both heads on the simulator, on the deck of a method Biomek's logs ran (2026-10-20, a dilution): the logged method's technique values given as arguments, the moves sent compared with the Master Controller's own log of that run.""" +import math from typing import Dict, List, Tuple -from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import ROWS, COLUMNS, mandrel_name +from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.driver import liquid from pylabrobot.beckman_coulter.biomek_i7.driver.liquid import ( ContainerShape, @@ -15,17 +17,39 @@ ) from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import ( biomek_labware, biomek_tip, biomek_touch_distance, ) -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck -from pylabrobot.beckman_coulter.biomek_i7.techniques import MixHeights, TipTouch +from pylabrobot.beckman_coulter.biomek_i7.techniques import Conditioning, MixHeights, TipTouch from pylabrobot.lib.liquid_handling.mix import Mix from pylabrobot.resources import Coordinate, cor_96_wellplate_360uL_Fb, set_volume_tracking from pylabrobot.resources.beckman_coulter import BiomekWell +MC_NAMES = ["X", "Y", "Z", "D", "GY", "GG", "GZ", "GR"] +MC_BITS = {"X": 0, "Y": 1, "Z": 3, "D": 11, "GY": 19, "GG": 20, "GZ": 21, "GR": 22} + +# The 96-head's 200 uL from the reservoir at P8 (the "MC Pipetting Reservoir with Asp Offset" +# template: 0.2 cm in -X), then into the plate at P6; the Master Controller's log. +LOGGED_96_ASPIRATE = [ + "AM 154400 58897 -24888 43176 -31385 -109660 -60398 -141581 1000 11", # approach, X offset + "AM -26929 -36982 -34206 43176 -31385 -109660 -60398 -141581 500 8", # 2 mm above the bottom + "AM -26929 -36982 -102049 91462 -31385 -109660 -60398 -141581 117 2048", # 210 uL + "AM -26929 -36982 -102049 89162 -31385 -109660 -60398 -141581 117 2048", # 10 back + "AM -26929 -36982 -24888 89162 -31385 -109660 -60398 -141581 500 8", # 1 mm above the top +] +LOGGED_96_DISPENSE = [ + "AM -26929 -36982 -30991 43176 -31385 -109660 -60398 -141581 1000 8", + "AM -26929 -36982 -33679 43176 -31385 -109660 -60398 -141581 250 8", # 1 mm above the bottom + "AM -26929 -36982 -32228 43176 -31385 -109660 -60398 -141581 146 2056", # following up + "AM -26929 -36982 -31972 43176 -31385 -109660 -60398 -141581 250 8", # 2 mm above the liquid + "AM -26929 -36982 -32996 43176 -31385 -109660 -60398 -141581 1000 8", # touch: liquid - 2 mm + "AM 117597 84845 -102049 43176 -31385 -109660 -60398 -141581 1000 3", + "AM 117597 85550 -102049 43176 -31385 -109660 -60398 -141581 1000 3", + "AM -26929 -36982 -30991 43176 -31385 -109660 -60398 -141581 250 8", +] # The Span-8's eight probes from the reservoir (the "S8 Pipetting Reservoir Offset Aspirate" # template: 10 mm approach), then probe 1 into A1 of the plate the 96-head filled. LOGGED_SPAN8_ASPIRATE = [ @@ -73,6 +97,11 @@ def parse_span8(command: str) -> Tuple[Dict[str, int], int]: return {n: next(values) for i, n in enumerate(SPAN8_SLOTS) if mask & (1 << i)}, speed +def parse_mc(command: str) -> Tuple[Dict[str, int], int]: + *pos, speed, mask = [int(x) for x in command.split()[1:]] + return {n: v for n, v in zip(MC_NAMES, pos) if mask & (1 << MC_BITS[n])}, speed + + class LiquidTests(PodMoveTest): async def setup_deck(self): # type: ignore[no-untyped-def] set_volume_tracking(True) @@ -112,6 +141,37 @@ def after_travel(self, moves): # type: ignore[no-untyped-def] travel = max(i for i, (t, _) in enumerate(moves) if "X" in t and not any("Z" in k for k in t)) return [m for m in moves[travel + 1 :] if not set(m[0]) <= {"Z", "GZ"} or m[1] != 1000][:99] + async def test_the_96_heads_logged_transfer(self) -> None: + driver, lh = await self.setup_deck() + head = lh.head96 + head._set_tips( + { + mandrel_name(r, c): biomek_tip("T1025F", f"t_{r}_{c}") + for r in range(ROWS) + for c in range(COLUMNS) + } + ) + moves = self.record(driver, "left") + await head.aspirate( + lh.deck.get_resource("Reservoir"), 200, offset=Coordinate(-2, 0, 0), liquid_height=2.0, + z_speed=47.5, flow_rate=100, settling_time=0.1, minimum_height=0.2, + conditioning=Conditioning(sections=1, section_volume=10, flow_rate=100), + ) # fmt: skip + aspirated = [m for m in moves if m[1] != 1000 or "X" in m[0] and "Z" in m[0]] + self.assertEqual(aspirated[:5], [parse_mc(c) for c in LOGGED_96_ASPIRATE]) + moves.clear() + plate = lh.deck.get_resource("Plate") + await head.dispense( + plate, 200, liquid_height=1.0, follow_liquid=True, minimum_height=0.2, z_speed=23.75, + flow_rate=125, + # Biomek's touch-off distance for this well and tip (`biomek_touch_distance`): 2.753 mm. + tip_touch=TipTouch(height=-2.0, height_from="liquid", theta=90, speed_fraction=1.0, distance=2.7532), + ) # fmt: skip + first = next(i for i, (t, s) in enumerate(moves) if t == parse_mc(LOGGED_96_DISPENSE[0])[0]) + self.assertEqual(moves[first : first + 8], [parse_mc(c) for c in LOGGED_96_DISPENSE]) + # The wells now hold what the head pushed out; the reservoir lost 96 x 210 - 96 x 10. + self.assertAlmostEqual(plate.get_well("H12").tracker.get_used_volume(), 200) + async def test_the_span8s_logged_transfer(self) -> None: driver, lh = await self.setup_deck() pipettes = lh.pipettes @@ -184,6 +244,11 @@ async def test_a_liquid_height_needs_known_contents(self) -> None: height_from="liquid", ) # fmt: skip + async def test_the_96_head_has_no_lld(self) -> None: + driver, lh = await self.setup_deck() + with self.assertRaises(NotImplementedError): + await lh.head96.aspirate(lh.deck.get_resource("Plate"), 10, lld_mode="CAPACITIVE") + def test_biomeks_touch_off_distance(self) -> None: # Biomek's distance: the wall at the touch height less the tip's cone where it crosses the rim. well = biomek_labware("Thermo96VB_PP", "p").get_well("A1") @@ -209,6 +274,44 @@ def test_wall_from_the_volume_function(self) -> None: else: self.assertAlmostEqual(ours, biomeks, delta=0.001) + async def test_pylabrobots_own_labware(self) -> None: + # A plate defined by PyLabRobot: heights from its cavity bottom, the level from its own + # height <-> volume function, the touch-off to its outline less the tip's radius. + driver, lh = await self.setup_deck() + head = lh.head96 + tip = biomek_tip("T1025F", "t") + head._set_tips( + { + mandrel_name(r, c): biomek_tip("T1025F", f"t_{r}_{c}") + for r in range(ROWS) + for c in range(COLUMNS) + } + ) + plate = cor_96_wellplate_360uL_Fb("Native") + lh.deck.get_position("P6").assign_child_resource(plate) + reservoir = lh.deck.get_resource("Reservoir") + await head.aspirate(reservoir, 100) + settings = head._settings( + liquid_height=1.0, follow_liquid=True, tip_touch=TipTouch(height=-1.0) + ) + plan = head.plan_liquid("dispense", plate, 100, settings, 100) + well = plate.get_well("A1") + rise = well.compute_height_from_volume(100) / 10 + dispense = next(s for s in plan.steps if isinstance(s, PlungerMove)) + start = plan.steps[1].z["A1"] # type: ignore[union-attr] + self.assertAlmostEqual(dispense.z["A1"] - start, rise, places=6) + touch = next(s for s in plan.steps if isinstance(s, Touch)) + # The wall where the tip touches: the tapered well's area there (its volume function's slope). + h = touch.above_bottom * 10 + area = ( + well.compute_volume_from_height(h + 0.05) - well.compute_volume_from_height(h - 0.05) + ) / 0.1 + wall = math.sqrt(area / math.pi) / 10 + self.assertLess(wall, well.get_size_x() / 20) + self.assertAlmostEqual(-touch.dy, wall - tip.get_size_x() / 20, places=6) + await head.dispense(plate, 100, liquid_height=1.0, follow_liquid=True) + self.assertAlmostEqual(well.tracker.get_used_volume(), 100) + async def test_the_span8s_logged_mix(self) -> None: driver, lh = await self.setup_deck() set_volume_tracking(False) # as Biomek, which did not know the plate's amounts @@ -329,3 +432,26 @@ async def test_a_mix_needs_empty_tips_and_one_mix_for_all_probes(self) -> None: await pipettes.dispense(wells, [30, 30], post_mixes=[mix] * 2) self.assertAlmostEqual(wells[0].tracker.get_used_volume(), 30) self.assertAlmostEqual(tips[1].tracker.get_used_volume(), 0) + + async def test_the_96_heads_mix(self) -> None: + # The same template on the 96-head (no logged method mixes on it): after the dispense the + # plunger draws and pushes the mix volume back, at the dispense height, at the mix's rate. + driver, lh = await self.setup_deck() + head = lh.head96 + tips = { + mandrel_name(r, c): biomek_tip("T1025F", "t") for r in range(ROWS) for c in range(COLUMNS) + } + head._set_tips(tips) + head._tips.update(tips) + await head.aspirate(lh.deck.get_resource("Reservoir"), 100, liquid_height=2.0) + plate = lh.deck.get_resource("Plate") + moves = self.record(driver, "left") + await head.dispense(plate, 100, liquid_height=1.0, post_mix=Mix(50, 2, 100)) + d = [t["D"] for t, _ in moves if "D" in t] + ul = [lh.head96._pod.declared.to_value("D", c) for c in d] # type: ignore[union-attr] + steps = [b - a for a, b in zip(ul, ul[1:])] + self.assertEqual(len(steps), 4) # after the dispense: draw, push, draw, push + for step, want in zip(steps, [50, -50, 50, -50]): + self.assertAlmostEqual(step, want, delta=0.01) # to a count + self.assertAlmostEqual(plate.get_well("A1").tracker.get_used_volume(), 100) + self.assertAlmostEqual(tips["A1"].tracker.get_used_volume(), 0) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index d31a00b9db5..74a0f23c222 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -45,6 +45,7 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import MoveResult, Pod from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import XRail @@ -147,7 +148,8 @@ def __init__( # While paused (`pause`): each pod's positions when the pause began, by side. self._paused: Optional[Dict[str, Dict[str, int]]] = None # Set while the interlock is tripped as far as this driver knows: from the start, when the - # chassis reports a trip, or when this driver trips it; cleared when it arms it. + # chassis reports a trip, or when this driver trips it; cleared when it arms it. A pod's + # waits (the `LT` settle) end early when it is set, as the Master Controller's do. self.interlock_tripped = asyncio.Event() self.interlock_tripped.set() self._unwatch: List[Callable[[], None]] = [] @@ -169,6 +171,7 @@ async def setup( skip_device_initialization: bool = False, skip_pipettes: bool = False, *, + skip_head96: bool = False, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, force_initialize: bool = False, @@ -185,6 +188,7 @@ async def setup( A pod with an axis not configured is then left as it is, and cannot move. skip_pipettes: leave the pod carrying the Span-8 as it is (STAR's per-feature skip). A pod's axes come up together, so this skips the whole pod, its gripper included. + skip_head96: leave the pod carrying the 96-head as it is; as `skip_pipettes`. skip_left_x_arm: leave the left pod as it is: not configured, enabled or moved. skip_right_x_arm: leave the right pod as it is. force_initialize: home again axes that are already homed, as Biomek's Home All does. @@ -194,8 +198,8 @@ async def setup( fault, or a pod would move on the X rail beside a skipped pod whose X is not homed. """ logger.warning( - "The Biomek i7 driver has run on one instrument (Home All, moves, prime, the Span-8's tips " - "and transfers, park); its commands were compared with Biomek's logs where Biomek ran the " + "The Biomek i7 driver has run on one instrument (Home All, prime, tips and transfers on " + "both heads, park); its commands were compared with Biomek's logs where Biomek ran the " "same operation; it is untested on other instruments. Please report what works and what " "does not." ) @@ -206,6 +210,7 @@ async def setup( await self.initialize( skip_device_initialization=skip_device_initialization, skip_pipettes=skip_pipettes, + skip_head96=skip_head96, skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm, force_initialize=force_initialize, @@ -299,6 +304,7 @@ async def discover(self) -> None: for pod in self.arms: pod.driver = self pod.rail = self.rail + pod.interlock_tripped = self.interlock_tripped self.rail.readers[pod.side] = pod.request_rail_pose modules: List[Tuple[str, ModuleConfiguration]] = [("chassis", await self.chassis.discover())] for pod in self.arms: @@ -506,6 +512,12 @@ def front_cover(self) -> Optional[Door]: """The door, by STAR's name for it, once discovery has found the chassis.""" return None if self.chassis is None else self.chassis.front_cover + @property + def head96(self) -> Optional[Head96]: + """The 96-channel head, on an instrument where one pod has it.""" + pod = self._one_with("head96") + return pod.head96 if pod is not None else None + @property def pipettes(self) -> Optional[Pipettes]: """The Span-8 channels, on an instrument where one pod has them.""" @@ -529,6 +541,7 @@ def skipped_sides( self, *, skip_pipettes: bool = False, + skip_head96: bool = False, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, ) -> Set[str]: @@ -537,7 +550,7 @@ def skipped_sides( instrument does not have skips nothing). Known after discovery.""" sides = {s for s, skip in (("left", skip_left_x_arm), ("right", skip_right_x_arm)) if skip} for pod in self.arms: - if skip_pipettes and pod.pipettes is not None: + if (skip_pipettes and pod.pipettes is not None) or (skip_head96 and pod.head96 is not None): sides.add(pod.side) return sides @@ -546,6 +559,7 @@ async def initialize( skip_device_initialization: bool = False, skip_pipettes: bool = False, *, + skip_head96: bool = False, skip_left_x_arm: bool = False, skip_right_x_arm: bool = False, force_initialize: bool = False, @@ -571,10 +585,9 @@ async def initialize( tripped and ERROR shown. """ skipped = self.skipped_sides( - skip_pipettes=skip_pipettes, - skip_left_x_arm=skip_left_x_arm, - skip_right_x_arm=skip_right_x_arm, - ) + skip_pipettes=skip_pipettes, skip_head96=skip_head96, + skip_left_x_arm=skip_left_x_arm, skip_right_x_arm=skip_right_x_arm, + ) # fmt: skip pods = [pod for pod in self.arms if pod.side not in skipped] if skip_device_initialization and not pods: return @@ -696,8 +709,9 @@ async def home(self, pods: Optional[Sequence[Pod]] = None, force: bool = False) """Home pods (every pod by default) at once, the Master Controller's Home All without its Span-8 priming. - Arms the interlock, then homes the pods together, as Biomek does: each runs its `HM` recipe. - Needs the motor tables loaded (`initialize` sees to it). + Arms the interlock, then homes the pods together, as Biomek does: each runs its `HM` recipe, + and a Multichannel pod then homes its plunger (`HD`). The Span-8's syringe pumps are left for + priming. Needs the motor tables loaded (`initialize` sees to it). If anything fails once the interlock is armed, ERROR is shown and the interlock tripped, which cuts the drives' power, before the error is raised; nothing is retried. Biomek instead leaves @@ -711,9 +725,14 @@ async def home(self, pods: Optional[Sequence[Pod]] = None, force: bool = False) """ targets = self.arms if pods is None else list(pods) + async def home_pod(pod: Pod) -> None: + await pod.home(force=force) + if pod.head96 is not None: + await pod.head96.home_plunger(force=force) + try: await self.arm_interlock(targets) - await _together(pod.home(force=force) for pod in targets) + await _together(home_pod(pod) for pod in targets) except BaseException: await self._return_to_rest(error=True) raise diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py index 009985ef604..b101139b945 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/__init__.py @@ -1 +1,2 @@ -"""The Master Controller's multi-step host commands, as recipes the pods run: `homing.py` (`HM`).""" +"""The Master Controller's multi-step host commands, as recipes the pods run: `homing.py` (`HM`, +`HD`) and `tip_load.py` (`LT`).""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py index e3abbdfd119..010588d2c21 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/homing.py @@ -160,6 +160,10 @@ class HomeGroup: ), } +# The Master Controller's `HD` on a Multichannel pod: the head's plunger. The Span-8's syringe +# pumps are homed as part of priming, not here. +PLUNGER_RECIPES: Dict[str, Tuple[Step, ...]] = {"multichannel": (Home("D", AtValue(0.0)),)} + # Whether the board's sequence enables an axis again right before homing it. ENABLE_BEFORE_HOME = {"multichannel": False, "span8": True} diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/tip_load.py b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/tip_load.py new file mode 100644 index 00000000000..a039dff9caa --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/recipes/tip_load.py @@ -0,0 +1,197 @@ +"""Loading tips on a Multichannel head, as the Master Controller does it: `LT`. + +The head presses its mandrels into a rack of tips with Z force-limited, so Z stops where the tips +are seated, not at its target. The recipe, as coordinated moves (`Pod.move_axes`): + + 1. D to `load_d` at full speed (the plunger where tips are loaded). + 2. Z to `load_z` at `load_speed`, force-limited to `load_force`: Z stops on the tips. + 3. Wait `settling_time` seconds. + 4. Read Z (the press left it unknown): the loaded Z, which `LT` replies. + 5. Z to `relieve_z` at `relieve_speed`, still force-limited, then the same move again with no + force (Z was force-limited, so it is read first; the drive has eased off a few counts). + 6. Z to `leave_z` and D to `leave_d` together at `leave_speed`. + 7. D to `end_d` at full speed. + +Every argument comes from the host; the Master Controller only checks them. Biomek computes them +from the pod's instrument-file settings, the height the tips seat at and how many tips are loaded: `TipLoad.from_configuration`. + +As the Master Controller does, the settling wait ends with an error if the interlock trips +(`_settle`). +""" + +import asyncio +import logging +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import ( + INTERLOCK_TRIPPED_CODE, + InterlockTrippedError, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.protocol import MAX_FORCE +from pylabrobot.beckman_coulter.biomek_i7.units import percent_to_field + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class TipLoad: + """The arguments of an `LT`, in its order: positions in counts, speeds 1..1000 (Biomek's speed + field), the force in the Master Controller's units (its `SF`), the settling time in seconds.""" + + load_d: int + load_z: int + load_force: float + load_speed: int + settling_time: float + relieve_z: int + relieve_speed: int + leave_d: int + leave_z: int + leave_speed: int + end_d: int + + def check(self) -> None: + """The Master Controller's checks of the arguments (it refuses others as invalid). + + Raises: + ValueError: for a force outside 0..4294967.295, a speed outside 1..1000, or a negative + settling time. + """ + if not 0 <= self.load_force <= MAX_FORCE: + raise ValueError(f"load_force {self.load_force} is outside 0..{MAX_FORCE}") + for name in ("load_speed", "relieve_speed", "leave_speed"): + if not 1 <= getattr(self, name) <= 1000: + raise ValueError(f"{name} {getattr(self, name)} is outside 1..1000") + if self.settling_time < 0: + raise ValueError(f"settling_time {self.settling_time} is negative") + + @classmethod + def from_configuration(cls, pod: PodConfiguration, seat_z: float, tips: int) -> "TipLoad": + """The `LT` Biomek sends to load `tips` tips seated at Z `seat_z` (cm, Biomek's Z), from the + pod's settings, as every logged `LT` has them: + + - force: `TipLoadForceLimitOffset` + `TipLoadForceLimitSlope` x the share of the head's + mandrels loaded (`tips` / rows x columns); + - Z: pressed to `seat_z` + `TipLoadZOffset`, relieved to `seat_z` + `TipLoadRelieveZOffset`, + and left `TipLoadPushOffDistance` above that; + - D: 0 uL to load and to end; while Z leaves, the plunger follows it down by the same + distance (-`TipLoadPushOffDistance` cm x `DAxisULPerCM`); + - speeds: `TipLoadSpeed`, `TipLoadRelieveSpeed`, `TipLoadPushOffSpeed`, percent, as Biomek's + speed field (x10); `TipLoadSettlingTime`. + + Raises: + ValueError: for a pod with no 96-channel head settings, or `tips` outside 1..mandrels. + """ + s = pod.settings + mandrels = (pod.geometry.mandrels_x or 0) * (pod.geometry.mandrels_y or 0) + if not mandrels or pod.module_type != "multichannel": + raise ValueError(f"{pod.component} has no 96-channel head") + if not 1 <= tips <= mandrels: + raise ValueError(f"tips {tips} is outside 1..{mandrels}") + relieve = seat_z + s["TipLoadRelieveZOffset"] + push_off = s["TipLoadPushOffDistance"] + empty = pod.to_counts("D", 0.0) + return cls( + load_d=empty, + load_z=pod.to_counts("Z", seat_z + s["TipLoadZOffset"]), + load_force=s["TipLoadForceLimitOffset"] + tips / mandrels * s["TipLoadForceLimitSlope"], + load_speed=percent_to_field(s["TipLoadSpeed"]), + settling_time=s["TipLoadSettlingTime"], + relieve_z=pod.to_counts("Z", relieve), + relieve_speed=percent_to_field(s["TipLoadRelieveSpeed"]), + leave_d=pod.to_counts("D", -1.0 * push_off * s["DAxisULPerCM"]), + leave_z=pod.to_counts("Z", relieve + push_off), + leave_speed=percent_to_field(s["TipLoadPushOffSpeed"]), + end_d=empty, + ) + + @classmethod + def parse(cls, command: str) -> "TipLoad": + """From a logged `LT` host command, such as `LT 43176 -50081 518.750 100 2.000 ...`.""" + name, *f = command.split() + if name != "LT" or len(f) != 11: + raise ValueError(f"not an LT command: {command!r}") + return cls( + int(f[0]), + int(f[1]), + float(f[2]), + int(f[3]), + float(f[4]), + int(f[5]), + int(f[6]), + int(f[7]), + int(f[8]), + int(f[9]), + int(f[10]), + ) + + +async def _settle(pod: "Pod", seconds: float) -> None: + """The settling wait, as the Master Controller's: it ends with an error if the + interlock trips, or is tripped when the wait begins. + + Raises: + InterlockTrippedError: then; the press is left as it is. + """ + tripped = pod.interlock_tripped + if tripped is None: + await asyncio.sleep(seconds) + return + if not tripped.is_set(): + try: + await asyncio.wait_for(tripped.wait(), seconds) + except asyncio.TimeoutError: + return + raise InterlockTrippedError(INTERLOCK_TRIPPED_CODE, None, f"{pod} LT settling") + + +async def load_tips(pod: "Pod", load: TipLoad) -> int: + """Run `load` on a Multichannel pod. Returns the loaded Z: where the press left Z, in counts. + + Raises: + ValueError: for arguments the Master Controller refuses, a target outside an axis's limits, or + a pod that is not a Multichannel; nothing is sent. + """ + if pod.module_type != "multichannel": + raise ValueError(f"{pod} has no 96-channel head to load tips on") + load.check() + for axis, target in ( + ("D", load.load_d), + ("Z", load.load_z), + ("Z", load.relieve_z), + ("D", load.leave_d), + ("Z", load.leave_z), + ("D", load.end_d), + ): + pod.axis(axis).check_position(target) + logger.info( + "%s LT D %d, Z %d force %s speed %d, settle %s s, relieve Z %d speed %d, leave D %d Z %d " + "speed %d, end D %d", + pod.component, + load.load_d, + load.load_z, + load.load_force, + load.load_speed, + load.settling_time, + load.relieve_z, + load.relieve_speed, + load.leave_d, + load.leave_z, + load.leave_speed, + load.end_d, + ) + await pod.move_axes({"D": load.load_d}, 1000) + await pod.move_axes({"Z": load.load_z}, load.load_speed, forces={"Z": load.load_force}) + await _settle(pod, load.settling_time) + await pod._read_unknown_positions() + loaded_z = pod.cpositions["Z"][1] + await pod.move_axes({"Z": load.relieve_z}, load.relieve_speed, forces={"Z": load.load_force}) + await pod.move_axes({"Z": load.relieve_z}, load.relieve_speed) + await pod.move_axes({"Z": load.leave_z, "D": load.leave_d}, load.leave_speed) + await pod.move_axes({"D": load.end_d}, 1000) + return loaded_z diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py index 9e4302b0d68..7e42804f998 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py @@ -1,12 +1,14 @@ """A simulated instrument as `BiomekI7(simulation=True)` builds it: the Span-8's tip sensor reports the tips the session records, a pod moves aside for the other, moves take the instrument's time -when asked to, and setup takes off tips left on.""" +when asked to, and setup takes off tips left on (the 96-head, which cannot sense them, ejects over +its trash even with none recorded).""" import asyncio import os import tempfile import time import unittest +from typing import Dict, List from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import shaft_of from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_tip @@ -63,11 +65,18 @@ async def asyncSetUp(self) -> None: asyncio.get_running_loop().set_debug(False) async def test_setup_takes_off_tips_left_on(self) -> None: - # A Span-8 tip left on last session, as its saved state has it on the shaft, and the sensor - # finds: it goes to its trash, and the state then has none. + # Tips left on last session, as its saved state has them on the shafts: a Span-8 tip the sensor + # finds, and the 96-head's, which it cannot sense, go to their trash; the state then has none. + from pylabrobot.resources.n_channel_pipettes import NChannelPipette + with tempfile.TemporaryDirectory() as d: path = os.path.join(d, "state.json") last = generic_biomek(state_json=path) + left = last.pod_models["left"] + head = left.get_resource(f"{left.name}_head") + assert isinstance(head, NChannelPipette) + for shaft in head.get_all_items(): + shaft.mount_tip(biomek_tip("T230", f"{shaft.name}_tip")) probe_3 = shaft_of(span8_channels(last.bridges["right"])[2]) probe_3.mount_tip(biomek_tip("T230", "probe_tip")) last.save_state_to_file(path) @@ -75,11 +84,84 @@ async def test_setup_takes_off_tips_left_on(self) -> None: biomek = generic_biomek(state_json=path) await biomek.setup() self.addAsyncCleanup(biomek.stop) - assert biomek.pipettes is not None + assert biomek.pipettes is not None and biomek.head96 is not None self.assertEqual(biomek.pipettes.tips, [None] * 8) + self.assertFalse(any(biomek.head96.tips)) + after = generic_biomek(state_json=path) + left = after.pod_models["left"] + head = left.get_resource(f"{left.name}_head") + assert isinstance(head, NChannelPipette) + self.assertFalse(any(shaft.has_tip() for shaft in head.get_all_items())) self.assertFalse(shaft_of(span8_channels(after.bridges["right"])[2]).has_tip()) + async def test_a_heads_tips_are_kept_across_sessions(self) -> None: + # The 96-head cannot sense tips: those it picked up come back from the saved state. + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "state.json") + first = generic_biomek(state_json=path) + await first.setup(precautionary_discard=False) + assert first.head96 is not None + first.head96._set_tips({"A1": biomek_tip("T230", "a1"), "B2": biomek_tip("T1025F", "b2")}) + await first.stop() + + second = generic_biomek(state_json=path) + await second.setup(discard_tips=False) + self.addAsyncCleanup(second.stop) + assert second.head96 is not None + tips = second.head96.tips + self.assertEqual(tips[0], "beckman_coulter_biomek_tip_230uL") + self.assertEqual(tips[13], "beckman_coulter_biomek_tip_1025uL_filter") + self.assertEqual(sum(t is not None for t in tips), 2) + + +class PrecautionaryDiscardTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + asyncio.get_running_loop().set_debug(False) + + async def setup_recording(self, **setup_kwargs): # type: ignore[no-untyped-def] + biomek = generic_biomek() + moves: List[Dict[str, int]] = [] + biomek_setup = biomek.setup + + async def setup() -> None: + await biomek_setup(discard_tips=False, park=False) + pod = biomek.left_x_arm + assert pod is not None + original = pod.move_axes + + async def move_axes(targets, speed=1000, **kwargs): # type: ignore[no-untyped-def] + moves.append(dict(targets)) + return await original(targets, speed, **kwargs) + + pod.move_axes = move_axes # type: ignore[method-assign, assignment] + await biomek._discard_found_tips(set(), setup_kwargs.get("precautionary_discard", True)) + + await setup() + self.addAsyncCleanup(biomek.stop) + return biomek, moves + + async def test_no_recorded_tips_still_ejects_over_the_trash(self) -> None: + # The head cannot sense tips: with none recorded it ejects as if the longest were on, which + # lands where Biomek's logged discards of 1025 uL tips (the same length) do. + biomek, moves = await self.setup_recording() + head = biomek.head96 + assert head is not None and biomek.left_x_arm is not None + d = biomek.left_x_arm.declared + assert d is not None + plan = head.plan_discard(head._effective_tip_length(biomek_tip("T1025F", "t"))) + self.assertIn({"Z": d.to_counts("Z", plan.z)}, moves) + self.assertTrue(any(m.get("D") == d.to_counts("D", d.limits["D"][0]) for m in moves)) + travel = next(m for m in moves if "X" in m and "Y" in m) + self.assertEqual( + (travel["X"], travel["Y"]), (d.to_counts("X", plan.x), d.to_counts("Y", plan.y)) + ) + self.assertFalse(any(head.tips)) + + async def test_the_operator_can_skip_it(self) -> None: + biomek, moves = await self.setup_recording(precautionary_discard=False) + self.assertEqual(moves, []) + if __name__ == "__main__": unittest.main() From 28e13251c2da7ff8927a92aab450cd25d815c8a1 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:00:28 +0000 Subject: [PATCH 19/28] `Biomek i7`: sort imports for ruff I001 --- pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py | 2 +- .../beckman_coulter/biomek_i7/driver/features/head96.py | 5 ++--- pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py | 2 +- pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py | 2 +- .../beckman_coulter/biomek_i7/driver/head96_tip_tests.py | 4 ++-- pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py | 6 +++--- 6 files changed, 10 insertions(+), 11 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py index 4732b1c95cc..c51aaff295a 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/fault_tests.py @@ -9,8 +9,8 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.errors import InterlockTrippedError from pylabrobot.beckman_coulter.biomek_i7.driver.head96_tests import LOGGED from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver -from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad class FaultTests(PodMoveTest): diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py index 2b20b9caa27..857cb62e1d4 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py @@ -31,8 +31,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Tuple -from pylabrobot.beckman_coulter.biomek_i7 import targeting -from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7 import targeting, units from pylabrobot.beckman_coulter.biomek_i7.driver import liquid from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import PLUNGER_RECIPES, Homer from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad, load_tips @@ -51,12 +50,12 @@ ) from pylabrobot.beckman_coulter.biomek_i7.units import optional_cm as _cm from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.resources.beckman_coulter.tips import beckman_coulter_biomek_tip_1070uL from pylabrobot.resources.container import Container from pylabrobot.resources.coordinate import Coordinate from pylabrobot.resources.n_channel_pipettes import NChannelPipette from pylabrobot.resources.plate import Plate from pylabrobot.resources.resource import Resource -from pylabrobot.resources.beckman_coulter.tips import beckman_coulter_biomek_tip_1070uL from pylabrobot.resources.tip import Tip from pylabrobot.resources.tip_rack import TipRack, TipSpot from pylabrobot.resources.volume_tracker import VolumeTracker, does_volume_tracking diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index 9546ea4817f..bd8a42228bb 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -30,6 +30,7 @@ PodConfiguration, ) from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, @@ -42,7 +43,6 @@ HOME_RECIPES, Homer, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail if TYPE_CHECKING: diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py index 9af9752d13d..79b031475fd 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tests.py @@ -4,13 +4,13 @@ import dataclasses import struct +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ( PLUNGER_RECIPES, AtValue, Home, ) from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad -from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration # A logged `LT`: 20 µL tips on this instrument (2026-07-31), with no settling wait. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py index ff86af31c22..e0a86eb040d 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/head96_tip_tests.py @@ -2,10 +2,10 @@ Biomek's logs ran (a dilution), against what Biomek sent for the same operations.""" from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck -from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.tip_load import TipLoad from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.resources import set_tip_tracking # The `LT` Biomek sent for a full load of BC1025F tips at TL1 (2026-10-20). diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py index a3abd935330..b8942adbb0b 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py @@ -5,10 +5,10 @@ import math from typing import Dict, List, Tuple -from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 -from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import ROWS, COLUMNS, mandrel_name from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 from pylabrobot.beckman_coulter.biomek_i7.driver import liquid +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import COLUMNS, ROWS, mandrel_name from pylabrobot.beckman_coulter.biomek_i7.driver.liquid import ( ContainerShape, PlungerMove, @@ -17,12 +17,12 @@ ) from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import ( biomek_labware, biomek_tip, biomek_touch_distance, ) +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_deck from pylabrobot.beckman_coulter.biomek_i7.techniques import Conditioning, MixHeights, TipTouch from pylabrobot.lib.liquid_handling.mix import Mix from pylabrobot.resources import Coordinate, cor_96_wellplate_360uL_Fb, set_volume_tracking From 6f3bb4aed284e6be1bc0c4c94b2a5e6aa055aa7c Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:44:41 -0800 Subject: [PATCH 20/28] `Biomek i7`: the gripper on both pods Each pod's gripper as a feature (`pod.gripper`, where the declared configuration describes one; `driver.gripper` and `biomek.gripper` on an instrument with one), STAR's iSWAP / core gripper signatures, built as Biomek's logs show its grips: - `driver/features/gripper.py`: pick up, place, move and return a resource: travel with the gripper turned to the grip direction at the highest height clear of the pod's own pipettor, open, down, a force-limited close that stops on the labware, lift clear, carry at the labware's speed, place; the grip checked by the control effort (`AU`, `AG`) as each pod's `SensorEnabled` says; what it holds counted by the rail and the pod's own collision check. - Biomek's grip widths as the gripper's defaults (`Y_CLEARANCE`, `SQUEEZE_MM`: its labware classes open and close by the same margins around the labware's width), and a method step's grip side as a direction (`biomek_grip_direction`). - The device hangs what the gripper holds from it in the resource tree; the simulator stops a close on the labware between the fingers and reads the control effort a held grip reads. Tests: lid and plate grips on both pods send what Biomek's logs show, with and without checks; a close on nothing is refused; Biomek's grip widths and sides; what each pod carries and the shortcuts to it; the held stack's footprint. --- .../beckman_coulter/biomek_i7/design.md | 6 + .../beckman_coulter/biomek_i7/device.py | 47 +- .../biomek_i7/device_model_tests.py | 23 +- .../biomek_i7/driver/configuration.py | 5 +- .../biomek_i7/driver/errors.py | 5 + .../biomek_i7/driver/features/__init__.py | 4 +- .../biomek_i7/driver/features/gripper.py | 764 ++++++++++++++++++ .../biomek_i7/driver/features/pod.py | 27 +- .../biomek_i7/driver/gripper_tests.py | 192 +++++ .../biomek_i7/driver/master.py | 17 +- .../biomek_i7/driver/pod_features_tests.py | 162 ++++ .../biomek_i7/driver/pod_geometry.py | 2 +- .../biomek_i7/driver/simulator.py | 27 +- .../biomek_i7/resource_model/pods.py | 12 +- .../beckman_coulter/biomek_i7/session_log.py | 5 +- .../biomek_i7/simulation_tests_support.py | 18 +- 16 files changed, 1286 insertions(+), 30 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_features_tests.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index 03ace571c1c..2e565c9b375 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -116,3 +116,9 @@ sensor; it cannot drop tips into a rack, only discard them. (`driver/recipes/tip_load.py`, its arguments from the configuration) and ejected by the plunger's shuck. It has no tip sensor, so `setup` ejects over its trash even with no tips recorded (`precautionary_discard`). + +**I14. A grip is Biomek's.** `.gripper` takes STAR's iSWAP / CoRe gripper calls with a +`direction`: travel turned, open, down, a force-limited close that stops on the labware, lift clear, +carry, place. The grip point is the resource's `preferred_pickup_location`; the widths default to +Biomek's margins around the labware's width; a close that reaches its target met nothing and is +refused. A pod's own gripper and pipettor are kept apart (`driver/pod_collision.py`). diff --git a/pylabrobot/beckman_coulter/biomek_i7/device.py b/pylabrobot/beckman_coulter/biomek_i7/device.py index dc4d73a33f7..1085bb0d3d5 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device.py @@ -34,6 +34,7 @@ ) from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import ( DEFAULT_TRASH as HEAD96_TRASH, ) @@ -47,6 +48,7 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import ( RECORDING_ENV, sense_recorded_tips, + simulate_grips, simulated_boards, ) from pylabrobot.beckman_coulter.biomek_i7.resource_model import cm, pod_model @@ -61,6 +63,7 @@ from pylabrobot.resources.beckman_coulter.tips import beckman_coulter_biomek_tip_1070uL from pylabrobot.resources.coordinate import Coordinate from pylabrobot.resources.resource import Resource +from pylabrobot.resources.rotation import Rotation logger = logging.getLogger(__name__) @@ -74,6 +77,8 @@ POST_SECTION = cm(8.0) POST_HEIGHT = cm(46.355 + 20.0 - 8.0) RAIL_SECTION = cm(8.0) +# How near the grip's GR the gripper is taken to be at it, degrees: GR is read back from counts. +GRIP_ANGLE_TOLERANCE = 0.5 DECK_Z = CABINET_HEIGHT + PLATES * PLATE_THICKNESS # The height the bridges ride at. The posts and rails are not drawn, so the device's own extent ends @@ -140,7 +145,7 @@ def __init__( self.bridges: Dict[str, Resource] = {} self.pod_models: Dict[str, Resource] = {} - # Each pod's gripper (from its declared model), posed from its axes. + # Each pod's gripper (from its declared model), posed from its axes; what it holds hangs from it. self.gripper_models: Dict[str, GripperModel] = {} self._unfollow: List[Callable[[], None]] = [] self._build_declared_models(driver.declared) @@ -195,6 +200,12 @@ def pipettes(self) -> Optional[Pipettes]: """The Span-8 channels, on an instrument where one pod has them.""" return self.driver.pipettes + @property + def gripper(self) -> Optional[Gripper]: + """The gripper, on an instrument with one pod; with two, reach it as `left_x_arm.gripper` or + `right_x_arm.gripper`.""" + return self.driver.gripper + async def setup( self, skip_device_initialization: bool = False, @@ -407,9 +418,14 @@ def _probe_spacing(declared: PodConfiguration) -> float: return declared.probe_spacing() def _build_gripper_model(self, side: str, declared: Optional[PodConfiguration]) -> None: - """(Re)build a side's gripper on its bridge, posed as parked until the driver says otherwise.""" + """(Re)build a side's gripper on its bridge, posed as parked until the driver says otherwise. + What the old one held is let go, to be hung on the new one when the pod is next shown.""" old = self.gripper_models.pop(side, None) if old is not None: + parts = {old.gripper.body.name, *(f.name for f in old.gripper.fingers)} + for child in list(old.gripper.children): + if child.name not in parts: + child.unassign() for part in (old.upper_hand, old.gripper): if part.parent is not None: part.unassign() @@ -463,7 +479,8 @@ def _axis_value(cls, pod: Pod, axis: str) -> Optional[float]: return None if d is None or counts is None else d.to_value(axis, counts) def _show_gripper(self, pod: Pod) -> None: - """Pose a pod's gripper model from its axes (the rotation centre: `pod_geometry`).""" + """Pose a pod's gripper model from its axes (the rotation centre: `pod_geometry`), and hang + what it holds from it, its grip point at the pads.""" d, model = pod.declared, self.gripper_models.get(pod.side) if d is None or model is None: return @@ -471,7 +488,30 @@ def _show_gripper(self, pod: Pod) -> None: if any(value is None for value in v.values()): return gy, gz, gr, gg = (float(v[a]) for a in ("GY", "GZ", "GR", "GG")) # type: ignore[arg-type] + gripper, plan = pod.gripper, None + held = gripper.held_resource if gripper is not None else None + if gripper is not None: + plan = gripper.held_plan + # At the grip's angle, to the counts' resolution, the gripper is at that angle: what it holds + # then stands as it did on the deck, as placing it reckons from. + if plan is not None and abs((gr - plan.gr + 180) % 360 - 180) < GRIP_ANGLE_TOLERANCE: + gr = plan.gr model.pose(self._gripper_centre(pod.side, d, gy, gz), gr, gg) + if held is None or plan is None or held.parent is model.gripper: + return + # Its rotation in the gripper's frame: on the deck it is `plan.rotation`, with the gripper + # turned -GR at the grip; it turns with the gripper from there. + turn = (plan.rotation + plan.gr) % 360 + held.rotation = Rotation(z=turn) + point = held.preferred_pickup_location + xy = ( + Coordinate(held.get_size_x() / 2, held.get_size_y() / 2, 0) + if point is None + else Coordinate(point.x, point.y, 0) + ).rotated(Rotation(z=turn)) + pads = model.pads() + location = Coordinate(pads.x - xy.x, pads.y - xy.y, pads.z - plan.held.grip_offset * 10) + model.gripper.assign_child_resource(held, location=location) def _show_pod(self, pod: Pod) -> None: """Put a pod's model where the pod's axes are (an unknown one: where it was). @@ -644,6 +684,7 @@ def BiomekI7( ) driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json, boards=boards) sense_recorded_tips(driver, boards) # the simulator does not model tips + simulate_grips(driver, boards) # nor labware between the fingers elif driver is None: driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json) return BiomekI7Device(driver=driver, deck=deck, name=name, state_json=state_json) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py index 95453c5e70c..f91c05e311f 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py @@ -12,17 +12,19 @@ BiomekI7Device, ) from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import held_labware_of from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.resource_model import MM_PER_CM from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import gripper_model +from pylabrobot.resources import Resource +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb +from pylabrobot.resources.rotation import Rotation from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( generic_biomek, generic_configuration, generic_deck, ) -from pylabrobot.resources import Resource -from pylabrobot.resources.coordinate import Coordinate -from pylabrobot.resources.rotation import Rotation def biomek_x_range(lh: BiomekI7Device, resource: Resource) -> g.Range: @@ -289,6 +291,21 @@ def test_the_pads_stand_gg_apart(self) -> None: class HeldStackTests(unittest.TestCase): + def test_a_lid_is_a_layer_of_the_held_stack(self) -> None: + plate = cor_96_wellplate_360uL_Fb("plate", with_lid=True) + held = held_labware_of(plate) + self.assertAlmostEqual(held.length, plate.get_size_x() / MM_PER_CM) + self.assertAlmostEqual(held.width, plate.get_size_y() / MM_PER_CM) + (layer,) = held.layers + lid = plate.lid + assert lid is not None and lid.location is not None + self.assertAlmostEqual(layer.dx, lid.location.x / MM_PER_CM) + self.assertAlmostEqual(layer.length, lid.get_size_x() / MM_PER_CM) + bare = held_labware_of(cor_96_wellplate_360uL_Fb("bare")) + self.assertEqual(bare.layers, ()) + across_x = held_labware_of(plate, across="x") + self.assertAlmostEqual(across_x.width, plate.get_size_x() / MM_PER_CM) + def test_a_layer_wider_than_the_one_below_widens_the_footprint(self) -> None: pod = generic_configuration().pod("left") model, geometry = g.GripperModel.from_bif(pod.gripper_model), pod.geometry diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index b4f06e7f5ab..6ae6b93d6a5 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -174,7 +174,10 @@ class Obstacle: # The settings the driver takes from a pod's entry in the instrument file, never assumed: a pod # whose entry lacks one is refused (`PodConfiguration`). Every pod's; a gripper's; each pod type's. POD_SETTINGS: Tuple[str, ...] = () -GRIPPER_SETTINGS: Tuple[str, ...] = ("GripperSqueezeForce",) +GRIPPER_SETTINGS: Tuple[str, ...] = ( + "SensorEnabled", + "GripperSqueezeForce", +) TYPE_SETTINGS: Dict[str, Tuple[str, ...]] = { "span8": ( "ProbeSize", diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py index a2c2898ee43..fe74cb58ae1 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/errors.py @@ -141,6 +141,11 @@ def motion_failed(e: AceError) -> str: return f"{error.request} failed: {error.reason}." +class GripCheckError(RuntimeError): + """The gripper holds no labware when it should, or holds labware when it should not: the Master + Controller's `AG` / `AU`.""" + + class TipCheckError(RuntimeError): """A probe's tip is not what was expected, or cannot be determined: the Master Controller's `VT`.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py index fc83f97406e..28fce059020 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/__init__.py @@ -1 +1,3 @@ -"""What a Biomek i7 is fitted with: the chassis, and a pod per side (`pod.py`, STAR's X-arm).""" +"""What a Biomek i7 is fitted with: the chassis, and a pod per side (`pod.py`, STAR's X-arm), each +carrying a `gripper` and either a `head96` (Multichannel) or `pipettes` (Span-8). The Master +Controller's multi-step commands they run are in `driver/recipes/`.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py new file mode 100644 index 00000000000..4877a532a5b --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py @@ -0,0 +1,764 @@ +"""A pod's gripper: the four gripper axes (GY, GG, GZ, GR), on a pod whose declared configuration +describes a gripper. Reached as +`driver.left_x_arm.gripper` / `driver.right_x_arm.gripper`. + +The gripper's axes are the pod's: it moves through `Pod.move_axes` with the rest of the pod (a grip +is GG moved force-limited), and what it holds widens the pod's range on the X rail and counts in its +own collision check. This feature moves labware (`pick_up_resource`, `place_resource`, +`move_resource`: the STAR's and the Prep's CoRe-gripper calls, with a `direction` named as STAR's +iSWAP names one), checks +grips, and tells the rail what is held. + +A grip, as Biomek's logs have it: travel over the labware with the gripper up and turned to the +grip direction; open; down to the grip height; close force-limited (it stops on the labware); lift +it straight out until it clears what it sat in by Biomek's gripper margin +(`AdditionalSafeHeightGripper` + `AvoidanceMargin`); carry it at the labware's speed; come down +over the destination; open; rise. Where Biomek checks the grip (`AG` / `AU`: the pod's +`SensorEnabled`), it checks before the pickup, after the close, after each move while holding, and +after the release. +""" + +import logging +import math +import warnings +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7 import targeting +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p +from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import GripCheckError +from pylabrobot.beckman_coulter.biomek_i7.units import MM_PER_CM +from pylabrobot.beckman_coulter.biomek_i7.units import optional_cm as _cm +from pylabrobot.lib.pick_and_place.assignment import assign_placed_resource +from pylabrobot.lib.pick_and_place.locations import ( + get_pick_location, + get_place_location, + get_rotation_wrt, +) +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.lid import Lid, Liddable +from pylabrobot.resources.resource import Resource +from pylabrobot.resources.resource_holder import ResourceHolder +from pylabrobot.resources.rotation import Rotation + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck + from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( + DeviceConfiguration, + PodConfiguration, + ) + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + +logger = logging.getLogger(__name__) + +# GG's control effort below this means the gripper holds labware, as the Master Controller judges +# a grip (`AG` / `AU`). +GRIPPED_LABWARE_LIMIT = -200 + + +# A grip direction: where the fingers point, as STAR's iSWAP names it (its +# `GRIPPER_DECK_DIRECTIONS`): degrees on the deck, counterclockwise from +x seen from above. The +# hand is on the other side of the labware: "right" grips with the hand on its left. (The legacy +# `GripDirection` named the hand's side, half a turn from this.) +GripperDirection = Literal["right", "back", "left", "front"] +GRIPPER_DECK_DIRECTIONS: Dict[GripperDirection, float] = { + "right": 0.0, + "back": 90.0, + "left": 180.0, + "front": -90.0, +} +# GR for each direction: Biomek's angles turn the other way (`units.axis_to_biomek`), so its 90 +# points the fingers to the front. +GRIP_ANGLES: Dict[GripperDirection, float] = { + "right": 0.0, + "front": 90.0, + "left": 180.0, + "back": -90.0, +} +GRIP_DIRECTIONS: Dict[float, GripperDirection] = {gr: name for name, gr in GRIP_ANGLES.items()} + + +def gripper_direction(direction: Union[GripperDirection, float]) -> GripperDirection: + """A direction's name, given its name or its degrees on the deck (STAR's iSWAP takes either). + + Raises: + ValueError: for an unknown name, or degrees that are not a multiple of 90: the fingers close + across a side of the labware. + """ + if isinstance(direction, str): + if direction not in GRIPPER_DECK_DIRECTIONS: + raise ValueError(f"{direction!r} is not one of {tuple(GRIPPER_DECK_DIRECTIONS)}") + return direction + for name, angle in GRIPPER_DECK_DIRECTIONS.items(): + if (direction - angle) % 360 == 0: + return name + raise ValueError(f"{direction} degrees: a grip direction is a multiple of 90 degrees") + + +# A close that ends within this of its target (cm) met nothing: the logged grips stop 0.3-0.9 cm +# wider than their target, on the labware. +EMPTY_GRIP_MARGIN = 0.05 + +# Biomek's grip widths, per side: its labware classes open the fingers 1.146 cm wider than the +# labware and close them towards 0.663 cm narrower (`unsqueeze`, `squeeze`). +Y_CLEARANCE = 5.73 +SQUEEZE_MM = 3.315 + + +# Where the fingers point (`direction`) for each of Biomek's grip sides on labware at rotation 0, A1 +# at its back left: "A1 near" has the hand on A1's side, the left, so the fingers point right. +GRIP_SIDES: Dict[str, GripperDirection] = { + "A1 near": "right", + "A1 away from": "left", + "Wide A1 near": "front", + "Wide A1 away from": "back", +} +# A direction turned a quarter counterclockwise seen from above: right goes to the back. +_QUARTER_TURN: Dict[GripperDirection, GripperDirection] = { + "right": "back", + "back": "left", + "left": "front", + "front": "right", +} + + +def biomek_grip_direction(resource: Resource, grip_side: str) -> GripperDirection: + """Where the fingers point on the deck (`direction`) for a Biomek method step's `GripSide` on + `resource`: "A1 near" (the hand on A1's side), "A1 away from", and the "Wide" ones (the fingers + across the labware's long side). A1 is at the back left of labware at rotation 0, so "A1 near" + puts the hand on the left there and the fingers point right; a turned labware turns it. + + Raises: + ValueError: for an unknown side, or a rotation that is not a multiple of 90 degrees. + """ + if grip_side not in GRIP_SIDES: + raise ValueError(f"unknown grip side {grip_side!r}; one of {sorted(GRIP_SIDES)}") + turn = resource.get_absolute_rotation().z % 360 + if turn % 90: + raise ValueError(f"{resource.name} is turned {turn} degrees; grips are along its sides") + side = GRIP_SIDES[grip_side] + for _ in range(int(turn // 90)): + side = _QUARTER_TURN[side] + return side + + +@dataclass(frozen=True) +class GripPlan: + """A grip or a release, in Biomek's units: the pod's X and the gripper's GY, GZ (the grip + height) and GR (cm, degrees), the widths GG opens to and closes towards (cm), the GZ it lifts to + clear what the labware sat in, what the rail counts while it is held, its width between the + fingers (cm) and its rotation on the deck (degrees, in the tree). Biomek-native, as every plan: + what the driver sends, for comparing with Biomek's logs (`units.py`).""" + + x: float + gy: float + gz: float + gr: float + open_width: float + close_width: float + lift: float + held: g.HeldLabware + width: float + rotation: float + + +def held_labware_of( + resource: Resource, + across: Literal["x", "y"] = "y", + offset_x: float = 0.0, + offset_y: float = 0.0, + grip_height: float = 0.0, +) -> g.HeldLabware: + """What the rail and the pod's own collision check count for `resource` held by the gripper: + its footprint, the lid on it as a stacked layer (as Biomek counts a gripped stack), and its + height, in cm. + + Args: + resource: what is held. A lid seated on it (`resource.lid`) is the layer above it. + across: the resource's axis between the fingers: `y` when the fingers close on its front and + back, `x` on its sides. The other runs along the fingers. + offset_x, offset_y: how far the resource's centre is from the pads' centre, along and across + the fingers, cm (Biomek's `GrippedLabwareOffsets`). + grip_height: how far above its bottom the fingertips are, mm (negative below it). + """ + + def footprint(r: Resource) -> List[float]: + size = [r.get_size_x() / MM_PER_CM, r.get_size_y() / MM_PER_CM] + return size if across == "y" else size[::-1] + + length, width = footprint(resource) + layers = [] + top = resource.get_size_z() + lid = getattr(resource, "lid", None) + if lid is not None and lid.location is not None: + corner = [lid.location.x / MM_PER_CM, lid.location.y / MM_PER_CM] + dx, dy = corner if across == "y" else corner[::-1] + layers.append(g.StackedLayer(dx, dy, *footprint(lid))) + top = max(top, lid.location.z + lid.get_size_z()) + return g.HeldLabware( + length, + width, + offset_x, + offset_y, + tuple(layers), + height=top / MM_PER_CM, + grip_offset=grip_height / MM_PER_CM, + ) + + +class Gripper: + """The gripper on one pod.""" + + # Where the fingers point when an operation names no direction (STAR P18); None: the pod's own + # (`_direction`). + default_direction: Optional[Union[GripperDirection, float]] = None + + def __init__(self, pod: "Pod"): + self._pod = pod + self._held: Optional[Resource] = None + self._held_plan: Optional[GripPlan] = None + self._held_checks = False + self._held_speed = 1000 + self._taken_from: Tuple[Optional[Resource], Optional[Coordinate]] = (None, None) + + def __str__(self) -> str: + return f"{self._pod}'s gripper" + + @property + def arm(self) -> "Pod": + """The pod this gripper is on (STAR's `feature.arm`).""" + return self._pod + + @property + def held_labware(self) -> Optional[g.HeldLabware]: + """What the gripper holds, as the rail counts it; None for nothing. The pod cannot sense it: + it is what was last set.""" + return self._pod._held_labware + + def set_held_labware(self, held: Optional[g.HeldLabware]) -> None: + """Tell the rail what the gripper now holds (None: nothing), so the pod's range counts it.""" + self._pod._held_labware = held + self._pod._positions_changed() + + async def request_control_effort(self, axis: str = "GG") -> int: + """How hard a motor is working to hold its position, in the drive's units. Moves nothing.""" + reply = await self._pod.board.send(p.get_control_effort(self._pod.axis(axis).index)) + return p.parse_s32(reply.payload) + + async def check_grip(self, expect_labware: bool) -> None: + """Check that the gripper does (`expect_labware`) or does not hold labware, from GG's control + effort: the Master Controller's `AG` / `AU`. Moves nothing. + + Raises: + GripCheckError: if it does not match. + """ + effort = await self.request_control_effort("GG") + logger.info( + "%s %s: GG control effort %d", self._pod.component, "AG" if expect_labware else "AU", effort + ) + holds = effort < GRIPPED_LABWARE_LIMIT + if holds != expect_labware: + what = "holds no labware" if expect_labware else "still holds labware" + raise GripCheckError(f"{self._pod}: the gripper {what} (GG control effort {effort})") + + # -- moving labware ----------------------------------------------------------------------------- + + @property + def held_resource(self) -> Optional[Resource]: + """The resource the gripper holds (`pick_up_resource`), or None.""" + return self._held + + @property + def held_plan(self) -> Optional[GripPlan]: + """How the held resource was gripped, or None.""" + return self._held_plan + + def _context(self) -> Tuple["BiomekI7Deck", "DeviceConfiguration", "PodConfiguration"]: + driver, declared = self._pod.driver, self._pod.declared + if driver is None or driver.deck is None or declared is None: + raise RuntimeError(f"{self} needs a deck and a declared configuration (use `BiomekI7`)") + return driver.deck, driver.declared, declared + + def _direction(self, direction: Optional[Union[GripperDirection, float]]) -> GripperDirection: + """`direction`, else `default_direction`, else the pod's own: the left pod's fingers point + right (its hand on the labware's left), the right pod's left, as Biomek's methods grip on + this instrument ("A1 near" on labware at rotation 0). + + Raises: + ValueError: see `gripper_direction`. + """ + if direction is not None: + return gripper_direction(direction) + if self.default_direction is not None: + return gripper_direction(self.default_direction) + return "right" if self._pod.side == "left" else "left" + + def _grip_point( + self, + resource: Resource, + origin: Coordinate, + rotation: float, + offset: Coordinate, + pickup_distance_from_top: Optional[float], + pickup_distance_from_bottom: Optional[float], + ) -> Tuple[Coordinate, float]: + """Where the pads' centre goes (deck mm, the fingertips' height as its z) for `resource` with + its origin at `origin` turned `rotation` degrees, and the grip height (mm above its bottom). + + Raises: + ValueError: for both distances given, or neither and no `preferred_pickup_location`. + """ + size = Coordinate(resource.get_size_x(), resource.get_size_y(), resource.get_size_z()) + point = resource.preferred_pickup_location + if pickup_distance_from_top is not None and pickup_distance_from_bottom is not None: + raise ValueError("give pickup_distance_from_top or pickup_distance_from_bottom, not both") + if pickup_distance_from_top is not None: + height = size.z - pickup_distance_from_top + elif pickup_distance_from_bottom is not None: + height = pickup_distance_from_bottom + elif point is not None: + height = point.z + else: + raise ValueError( + f"{resource.name} has no preferred_pickup_location; give pickup_distance_from_top or " + "pickup_distance_from_bottom" + ) + xy = Coordinate(size.x / 2, size.y / 2, 0) if point is None else Coordinate(point.x, point.y, 0) + turned = xy.rotated(Rotation(z=rotation)) + return origin + Coordinate(turned.x, turned.y, height) + offset, height + + def _pose(self, pads: "targeting.BiomekPoint", gr: float) -> Tuple[float, float, float]: + """X, GY and GZ (Biomek cm) that put the pads' centre at `pads` (its z the fingertips) at GR + `gr`: about the rotation centre (`pod_geometry`), the pads `PadsCenterToRotationCenter` along + the fingers and `FingerCenterOffset` across them.""" + _, _, declared = self._context() + geo, model = declared.geometry, g.GripperModel.from_bif(declared.gripper_model) + r, f = model.pads_center_to_rotation_center, model.finger_center_offset + c, s = math.cos(math.radians(gr)), math.sin(math.radians(gr)) + cx, cy = pads.x - (r * c - f * s), pads.y - (r * s + f * c) + return ( + cx - geo.gripper_x_offset + r, + cy - geo.gripper_y_offset + f, + pads.z - geo.gripper_z_offset, + ) + + def _to_biomek( + self, point: Coordinate, where: Union[Resource, Coordinate] + ) -> "targeting.BiomekPoint": + """A deck point (mm) in Biomek's frame (cm), corrected by this pod's calibration of the deck + position `where` stands on (or is).""" + deck, configuration, _ = self._context() + b = targeting.to_biomek(point) + position = None if isinstance(where, Coordinate) else targeting.deck_position_of(deck, where) + if position is None: + return b + dx, dy, dz = targeting.position_correction(deck, configuration, position, self._pod.pod_number) + return targeting.BiomekPoint(b.x + dx, b.y + dy, b.z + dz) + + def _checks(self, check_grip: Optional[bool]) -> bool: + _, _, declared = self._context() + enabled = bool(declared.settings["SensorEnabled"]) + if check_grip is None: + return enabled + if check_grip and not enabled: + logger.warning( + "%s: grip checks asked for; Biomek's configuration has this pod's grip sensor " + "(SensorEnabled) off", + self, + ) + return check_grip + + def plan_pick_up( + self, + resource: Resource, + offset: Coordinate = Coordinate.zero(), + pickup_distance_from_top: Optional[float] = None, + pickup_distance_from_bottom: Optional[float] = None, + *, + direction: Optional[Union[GripperDirection, float]] = None, + y_clearance: float = Y_CLEARANCE, + squeeze_mm: float = SQUEEZE_MM, + ) -> GripPlan: + """Where and how a pickup of `resource` goes (see `pick_up_resource`). Moves nothing. + + Raises: + ValueError: for a resource not on the deck, a grip height neither given nor preferred, widths + the fingers cannot open or close to, or a pose outside the axes' travel. + """ + deck, _, _ = self._context() + direction = self._direction(direction) + rotation = get_rotation_wrt(resource, deck).z + origin = get_pick_location(resource, deck) + pads, height = self._grip_point( + resource, origin, rotation, offset, pickup_distance_from_top, pickup_distance_from_bottom + ) + return self._plan( + resource, pads, height, direction, rotation, y_clearance, squeeze_mm, resource + ) + + def _plan( + self, + resource: Resource, + pads: Coordinate, + height: float, + direction: GripperDirection, + rotation: float, + y_clearance: float, + squeeze_mm: float, + where: Union[Resource, Coordinate], + ) -> GripPlan: + _, _, declared = self._context() + if y_clearance < 0 or squeeze_mm < 0: + raise ValueError(f"y_clearance and squeeze_mm must be 0 or more: {y_clearance}, {squeeze_mm}") + gr = GRIP_ANGLES[direction] + # The fingers close across the resource's own y when they point along its x. + across_y = (gr - rotation) % 180 == 0 + width = resource.get_size_y() if across_y else resource.get_size_x() + open_cm = (width + 2 * y_clearance) / MM_PER_CM + close_cm = (width - 2 * squeeze_mm) / MM_PER_CM + low, high = declared.limits["GG"] + if not low <= close_cm < open_cm <= high: + raise ValueError( + f"{self}: the fingers open {low}-{high} cm; {resource.name} needs {close_cm:.3f} to " + f"{open_cm:.3f}" + ) + x, gy, gz = self._pose(self._to_biomek(pads, where), gr) + for axis, value in (("X", x), ("GY", gy), ("GZ", gz), ("GR", gr)): + lo, hi = declared.limits[axis] + if not lo <= value <= hi: + raise ValueError(f"{self}: {axis} {value:.3f} is outside its travel {lo}-{hi}") + # Lifted out straight until it clears what it sat in (a lid its plate) by Biomek's margin. + nest = resource.nesting_z_height if isinstance(resource, Lid) else 0.0 + lift = gz + nest / MM_PER_CM + declared.geometry.additional_safe_height_gripper + lift += declared.geometry.avoidance_margin + held = held_labware_of(resource, "y" if across_y else "x", grip_height=height) + return GripPlan( + x, + gy, + gz, + gr, + open_cm, + close_cm, + min(lift, declared.limits["GZ"][1]), + held, + width / MM_PER_CM, + rotation, + ) + + def _held_field(self, z_speed: Optional[float]) -> int: + """The speed field the gripper moves at while it holds labware: `z_speed`, mm/s of GZ (None: + full speed). The same fraction of their maximum drives the other axes of those moves, as + Biomek's labware speed limit does. + + Raises: + ValueError: for a speed not above 0, or above GZ's maximum. + """ + if z_speed is None: + return units.FULL_SPEED + return units.rate_to_field(self._pod, "GZ", z_speed) + + async def _check(self, enabled: bool, expect_labware: bool) -> None: + if enabled: + await self.check_grip(expect_labware) + + def _travel_targets(self, plan: GripPlan) -> Dict[str, int]: + _, _, d = self._context() + return { + "X": d.to_counts("X", plan.x), + "GY": d.to_counts("GY", plan.gy), + "GR": d.to_counts("GR", plan.gr), + } + + async def pick_up_resource( + self, + resource: Resource, + offset: Coordinate = Coordinate.zero(), + pickup_distance_from_top: Optional[float] = None, + pickup_distance_from_bottom: Optional[float] = None, + *, + direction: Optional[Union[GripperDirection, float]] = None, + minimum_traverse_height_start: Optional[float] = None, + y_clearance: float = Y_CLEARANCE, + squeeze_mm: float = SQUEEZE_MM, + grip_strength: Optional[float] = None, + z_speed: Optional[float] = None, + check_grip: Optional[bool] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Grip `resource` where the tree has it and lift it out: the STAR's and the Prep's + `pick_up_resource`, with a `direction`. + + The gripper travels over it with its fingers pointing in `direction`, opens to its width plus + `y_clearance` either side, comes down, and closes towards its width less `squeeze_mm` either + side under `grip_strength`: the close stops on the resource. It then lifts it straight up until + it clears what it sat in (a lid its plate) by Biomek's gripper margin, and holds it. The pads go + to its `preferred_pickup_location` (its centre when it has none), the fingertips that far above + its bottom (negative below it, as Biomek grips plates). The default widths are Biomek's. + + Args: + resource: what to grip. + offset: added to where the pads go, mm. + pickup_distance_from_top, pickup_distance_from_bottom: where the fingertips go, mm below its + top or above its bottom; at most one. Neither: `preferred_pickup_location`'s z. + direction: where the fingers point, as STAR's iSWAP names it: "right", "back", "left", + "front" (`GripperDirection`), or degrees on the deck, counterclockwise from +x (a multiple + of 90). The hand is on the other side: "right" grips with the hand on the labware's left. + None: `default_direction`, else the pod's own ("right" on the left pod, "left" on the + right pod). + minimum_traverse_height_start: the channels' lowest point while traveling to it, mm, as + `Pod._move_over` takes it; the gripper travels at its ceiling. + y_clearance: how far each finger opens past it, mm. Biomek's is `Y_CLEARANCE`. + squeeze_mm: how far past its walls each finger may close, mm. Biomek's is `SQUEEZE_MM`. + grip_strength: the close's force limit, in Biomek's units (its `SF`); None is the gripper's + `SqueezeForce`. + z_speed: how fast it lifts and lowers the labware once held, mm/s of GZ (STAR's CoRe + grippers' `z_speed`); its travel holding it moves at the same fraction of each axis's + maximum (Biomek's labware speed limit). None: full speed. + check_grip: check the grip from GG's control effort (`AG` / `AU`); None as Biomek does on + this pod (its grip sensor setting, `SensorEnabled`). + minimum_traverse_height_end: the channels' lowest point after, mm. + + Raises: + RuntimeError: if the gripper already holds something. + ValueError: see `plan_pick_up`. + GripCheckError: if the fingers closed on nothing (they reached their close target; on every + pod) or a grip check fails; the gripper is left where it is. + """ + if self._held is not None: + raise RuntimeError(f"{self} already holds {self._held.name}; place it first") + direction = self._direction(direction) + plan = self.plan_pick_up( + resource, offset, pickup_distance_from_top, pickup_distance_from_bottom, + direction=direction, y_clearance=y_clearance, squeeze_mm=squeeze_mm, + ) # fmt: skip + _, _, d = self._context() + pod = self._pod + checks = self._checks(check_grip) + held_speed = self._held_field(z_speed) + force = d.settings["GripperSqueezeForce"] if grip_strength is None else grip_strength + logger.info("%s pick up %s (fingers %s)", pod.component, resource.name, direction) + await self._check(checks, expect_labware=False) + targets = self._travel_targets(plan) + await pod._travel_gripper(targets, minimum_traverse_height=_cm(minimum_traverse_height_start)) + await pod.move_axes({"GG": d.to_counts("GG", plan.open_width)}) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.gz)}) + self._simulate(plan.width) + await pod.move_axes({"GG": d.to_counts("GG", plan.close_width)}, forces={"GG": force}) + await self._check_stopped_width(plan) + await self._check(checks, expect_labware=True) + self._hold(resource, plan, checks, held_speed) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.lift)}, held_speed) + await self._check(checks, expect_labware=True) + if minimum_traverse_height_end is not None: + await pod._move_over({}, held_speed, minimum_traverse_height=_cm(minimum_traverse_height_end)) + + async def _check_stopped_width(self, plan: GripPlan) -> None: + """The close is force-limited and stops on what it grips; one that reached its target closed + on nothing. Read GG back (the force left it unknown) and refuse that, on every pod.""" + pod = self._pod + await pod._read_unknown_positions() + _, _, d = self._context() + counts = pod.cpositions["GG"][0] + if counts is None: + raise GripCheckError(f"{self}: GG's position after the grip is not known") + stopped = d.to_value("GG", counts) + logger.info( + "%s GG stopped at %.3f cm (closing towards %.3f)", pod.component, stopped, plan.close_width + ) + if stopped - plan.close_width < EMPTY_GRIP_MARGIN: + raise GripCheckError( + f"{self}: the fingers closed to {stopped:.3f} cm, their target: nothing between them" + ) + + def _simulate(self, width: Optional[float]) -> None: + """In simulation, put labware `width` cm wide between the fingers (None: nothing).""" + driver = self._pod.driver + if driver is not None and driver.simulated_grip is not None: + driver.simulated_grip(self._pod, width) + + def _hold(self, resource: Resource, plan: GripPlan, checks: bool, speed: int) -> None: + self._taken_from = (resource.parent, resource.location) + if resource.parent is not None: + resource.unassign() + self._held, self._held_plan = resource, plan + self._held_checks, self._held_speed = checks, speed + self.set_held_labware(plan.held) # the device hangs it from the gripper's model + + def plan_place( + self, + to: Union[Resource, Coordinate], + offset: Coordinate = Coordinate.zero(), + *, + direction: Optional[Union[GripperDirection, float]] = None, + y_clearance: Optional[float] = None, + ) -> Tuple[GripPlan, Coordinate, float]: + """Where a place of the held resource into `to` goes, where its origin ends up (deck mm) and + how far the move turns it (degrees, in the tree). Moves nothing. + + Raises: + RuntimeError: if nothing is held. + ValueError: if `to` refuses it, or the pose is outside the axes' travel. + """ + held, picked = self._held, self._held_plan + if held is None or picked is None: + raise RuntimeError(f"{self} holds nothing; pick_up_resource first") + deck, _, _ = self._context() + direction = GRIP_DIRECTIONS[picked.gr] if direction is None else gripper_direction(direction) + # A turn of the hand turns what it holds; Biomek's Y runs to the front, so the other way in + # the tree. + turn = (picked.gr - GRIP_ANGLES[direction]) % 360 + if isinstance(to, Coordinate): + deck.check_can_drop_resource_here(held) + else: + to.check_can_drop_resource_here(held) + location = get_place_location(held, to, deck, rotation_applied_by_move=turn) + rotation = (picked.rotation + turn) % 360 + pads, height = self._grip_point( + held, location, rotation, offset, None, picked.held.grip_offset * MM_PER_CM + ) + clearance = ( + (picked.open_width - picked.width) * MM_PER_CM / 2 if y_clearance is None else y_clearance + ) + squeeze = (picked.width - picked.close_width) * MM_PER_CM / 2 + plan = self._plan(held, pads, height, direction, rotation, clearance, squeeze, to) + return plan, location, turn + + async def place_resource( + self, + to: Union[Resource, Coordinate], + offset: Coordinate = Coordinate.zero(), + *, + direction: Optional[Union[GripperDirection, float]] = None, + minimum_traverse_height_start: Optional[float] = None, + y_clearance: Optional[float] = None, + z_speed: Optional[float] = None, + check_grip: Optional[bool] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Put the held resource into `to` (a resource, or a deck `Coordinate` for its origin); the + tree follows once it is let go: the STAR's and the Prep's `place_resource`. + + It travels over `to`, comes down to where it was gripped, opens (to its pickup width, or its + width plus `y_clearance` either side), and the gripper rises. A `direction` other than the + pickup's turns it. + + Args: + z_speed: as `pick_up_resource`'s; None is the pickup's. + check_grip: as `pick_up_resource`'s; None is the pickup's. + the others: as `pick_up_resource`'s. + + Raises: + RuntimeError: if nothing is held. + ValueError: see `plan_place`. + GripCheckError: if a grip check fails. + """ + plan, location, turn = self.plan_place(to, offset, direction=direction, y_clearance=y_clearance) + held = self._held + if held is None: + raise RuntimeError(f"{self}: holds nothing to place") + deck, _, d = self._context() + pod = self._pod + checks = self._held_checks if check_grip is None else self._checks(check_grip) + held_speed = self._held_speed if z_speed is None else self._held_field(z_speed) + logger.info("%s place %s", pod.component, held.name) + targets = self._travel_targets(plan) + await pod._travel_gripper( + targets, held_speed, minimum_traverse_height=_cm(minimum_traverse_height_start) + ) + await self._check(checks, expect_labware=True) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.gz)}, held_speed) + await self._check(checks, expect_labware=True) + await pod.move_axes({"GG": d.to_counts("GG", plan.open_width)}) + self._simulate(None) + picked = self._held_plan + if picked is None: + raise RuntimeError(f"{self}: has no plan for what it holds") + self._held = self._held_plan = None + self.set_held_labware(None) + # Off the gripper's model, turned as it was on the deck: the move adds its own turn. + if held.parent is not None: + held.unassign() + held.rotation = Rotation(z=picked.rotation) + assign_placed_resource(held, to, deck, location=location, rotation_applied_by_move=turn) + await self._check(checks, expect_labware=False) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.lift)}) + if minimum_traverse_height_end is not None: + await pod._move_over({}, minimum_traverse_height=_cm(minimum_traverse_height_end)) + + async def drop_resource(self, *args: Any, **kwargs: Any) -> None: + """Deprecated: use `place_resource`.""" + warnings.warn( + "`drop_resource` is deprecated; use `place_resource`.", DeprecationWarning, stacklevel=2 + ) + await self.place_resource(*args, **kwargs) + + async def return_resource( + self, + offset: Coordinate = Coordinate.zero(), + *, + direction: Optional[Union[GripperDirection, float]] = None, + minimum_traverse_height_start: Optional[float] = None, + y_clearance: Optional[float] = None, + z_speed: Optional[float] = None, + check_grip: Optional[bool] = None, + minimum_traverse_height_end: Optional[float] = None, + ) -> None: + """Put the held resource back where `pick_up_resource` took it from (a lid on its plate): STAR's + `return_resource`. + + Args: + offset: as `place_resource` takes it, and every other argument too. + + Raises: + RuntimeError: if nothing is held, or it was taken from no parent. + """ + parent, location = self._taken_from if self._held is not None else (None, None) + if parent is None: + raise RuntimeError(f"{self}: nothing to return it to") + to: Union[Resource, Coordinate] + if isinstance(parent, (ResourceHolder, Liddable)): + to = parent + else: + deck, _, _ = self._context() + to = parent.get_location_wrt(deck) + (location or Coordinate.zero()) + await self.place_resource( + to, offset, direction=direction, minimum_traverse_height_start=minimum_traverse_height_start, + y_clearance=y_clearance, z_speed=z_speed, check_grip=check_grip, + minimum_traverse_height_end=minimum_traverse_height_end, + ) # fmt: skip + + async def move_resource( + self, + resource: Resource, + to: Union[Resource, Coordinate], + *, + pickup_offset: Coordinate = Coordinate.zero(), + pickup_distance_from_top: Optional[float] = None, + pickup_distance_from_bottom: Optional[float] = None, + pickup_direction: Optional[Union[GripperDirection, float]] = None, + place_offset: Coordinate = Coordinate.zero(), + place_direction: Optional[Union[GripperDirection, float]] = None, + minimum_traverse_height_start: Optional[float] = None, + minimum_traverse_height_during: Optional[float] = None, + minimum_traverse_height_end: Optional[float] = None, + y_clearance: float = Y_CLEARANCE, + squeeze_mm: float = SQUEEZE_MM, + grip_strength: Optional[float] = None, + z_speed: Optional[float] = None, + check_grip: Optional[bool] = None, + ) -> None: + """Pick `resource` up and place it into `to`: the Prep's `move_resource`, with pickup and place + directions. The arguments are `pick_up_resource`'s and `place_resource`'s.""" + await self.pick_up_resource( + resource, pickup_offset, pickup_distance_from_top, pickup_distance_from_bottom, + direction=pickup_direction, minimum_traverse_height_start=minimum_traverse_height_start, + y_clearance=y_clearance, squeeze_mm=squeeze_mm, grip_strength=grip_strength, z_speed=z_speed, + check_grip=check_grip, minimum_traverse_height_end=minimum_traverse_height_during, + ) # fmt: skip + await self.place_resource( + to, place_offset, direction=place_direction, + minimum_traverse_height_start=minimum_traverse_height_during, + minimum_traverse_height_end=minimum_traverse_height_end, + ) # fmt: skip diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index bd8a42228bb..15fd93067f6 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -21,28 +21,29 @@ from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.driver import motion -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( ModuleConfiguration, PodConfiguration, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english -from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 -from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, read_module, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ( ENABLE_ORDER, ENABLE_PREFIX, HOME_RECIPES, Homer, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail if TYPE_CHECKING: @@ -57,7 +58,8 @@ COMPONENT_PREFIXES = {"multichannel": "MC", "span8": "SPAN8"} # What each module type carries besides the pod's own axes, by the feature's name on `Pod`. The # module type is what the board reports (Get Module ID, `protocol.MODULE_TYPES`); a new pod type is -# a new entry here and in the motor tables. +# a new entry here and in the motor tables. The gripper is not here: it is fitted where the declared +# configuration describes one. MODULE_FEATURES: Dict[str, Tuple[str, ...]] = { "multichannel": ("head96",), "span8": ("pipettes",), @@ -119,7 +121,7 @@ class Pod: Controller's `AM`), the position record the Master Controller keeps, homing, and the pod's pose on the shared X rail. `module_type` says what else the pod carries, as features (`MODULE_FEATURES`): `multichannel` a 96-channel head (`head96`), `span8` eight independent - channels (`pipettes`). + channels (`pipettes`); either a `gripper` where the declared configuration describes one. """ def __init__( @@ -147,7 +149,8 @@ def __init__( # The pod's model in the resource tree, its bridge (STAR's `x_arm.resource`): set by the device # that draws it (`BiomekI7`), which keeps it in step with the pod's axes; None without one. self.resource: Optional["Resource"] = None - # What the gripper holds, as the rail counts it; the pod cannot sense it. + # What the gripper holds, as the rail counts it: set through `gripper.set_held_labware`; the + # pod cannot sense it. self._held_labware: Optional[g.HeldLabware] = None # Where this driver last put each axis, as the Master Controller keeps it (`cpositions`): # (position, adjusted); position None until read. Starts as after homing. @@ -173,10 +176,14 @@ def __init__( self.default_minimum_traverse_height = units.to_mm(float(safe)) # Who follows the position record (`add_position_listener`). self._listeners: List[Callable[["Pod"], None]] = [] - # What the pod carries (STAR's arm features): what its module type has (`MODULE_FEATURES`). + # What the pod carries (STAR's arm features): what its module type has (`MODULE_FEATURES`), and + # a gripper where the declared configuration describes one, as the rail counts one only then. features = MODULE_FEATURES.get(module_type, ()) self.head96: Optional[Head96] = Head96(self) if "head96" in features else None self.pipettes: Optional[Pipettes] = Pipettes(self) if "pipettes" in features else None + self.gripper: Optional[Gripper] = ( + Gripper(self) if declared is not None and declared.gripper_model else None + ) @property def pod_number(self) -> int: diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py new file mode 100644 index 00000000000..2bb3c79cc15 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py @@ -0,0 +1,192 @@ +"""The gripper's operations on the simulator, against Biomek's logged lid grips at P17 (both pods, +a transfection method, 2026-09-22): TiterplateLid on a Thermo96VB_PP.""" + +import asyncio +import unittest +from typing import Dict, List, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import GripCheckError +from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import ( + SQUEEZE_MM, + Y_CLEARANCE, + Gripper, + biomek_grip_direction, +) +from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.resources import Plate, beckman_coulter_biomek_96_wellplate_vb +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_biomek, +) + +# Biomek's TiterplateLid widths (open 9.401 cm, close 7.592 cm) on the lid, which PyLabRobot sizes +# to its plate's 8.56 cm: per call, as the gripper's defaults are Biomek's margins for labware. +LID_Y_CLEARANCE, LID_SQUEEZE_MM = 4.205, 4.84 + +# The logged grips' counts (X, GY, GR at the grip; GG open; GZ down; GG close), host_command. +LOGGED = { + "left": {"X": 241420, "GR": -141581, "GG open": 62705, "GZ": -21774, "GG close": 29537}, + "right": { + "X": -50856, + "GY": 89997, + "GR": -209637, + "GG open": 62594, + "GZ": -21576, + "GG close": 29427, + }, +} + + +class GripperTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self) -> None: + # Debug mode makes a simulated Home All ~100x slower; see homing_tests.py. + asyncio.get_running_loop().set_debug(False) + self.biomek = generic_biomek() + await self.biomek.setup(precautionary_discard=False) + self.addAsyncCleanup(self.biomek.stop) + place_labware( + self.biomek.deck, + [{"position": "P17", "class": "Thermo96VB_PP", "name": "plate", "lid": "TiterplateLid"}], + ) + plate = self.biomek.deck.get_resource("plate") + assert isinstance(plate, Plate) and plate.lid is not None + self.plate, self.lid = plate, plate.lid + + def record(self, side: str) -> List[Tuple[Dict[str, int], Dict[str, float]]]: + pod = self.biomek.driver.arm(side) # type: ignore[union-attr] + moves: List[Tuple[Dict[str, int], Dict[str, float]]] = [] + original = pod.move_axes + + async def move_axes(targets, speed=1000, forces=None, sensors=None): # type: ignore[no-untyped-def] + moves.append((dict(targets), dict(forces or {}))) + return await original(targets, speed, forces, sensors) + + pod.move_axes = move_axes # type: ignore[method-assign] + return moves + + def gripper(self, side: str) -> Gripper: + gripper = self.biomek.driver.arm(side).gripper # type: ignore[union-attr] + assert gripper is not None + return gripper + + def checks(self, side: str) -> List[str]: + gripper = self.gripper(side) + found: List[str] = [] + original = gripper.check_grip + + async def check_grip(expect_labware: bool) -> None: + found.append("G" if expect_labware else "U") + await original(expect_labware) + + gripper.check_grip = check_grip # type: ignore[method-assign] + return found + + async def lid_off_and_on(self, side: str) -> Tuple[List, List[str]]: + other = "right" if side == "left" else "left" + await self.biomek.driver.arm(other).move_aside() # type: ignore[union-attr] + gripper = self.gripper(side) + moves, checks = self.record(side), self.checks(side) + await gripper.pick_up_resource(self.lid, y_clearance=LID_Y_CLEARANCE, squeeze_mm=LID_SQUEEZE_MM) + self.assertIs(gripper.held_resource, self.lid) + self.assertIsNone(self.plate.lid) + # In the tree it hangs from the gripper's hand, lifted clear of its plate. + self.assertIs(self.lid.parent, self.biomek.gripper_models[side].hand) + device = self.biomek + plate_top = self.plate.get_location_wrt(device).z + self.plate.get_size_z() + self.assertGreater(self.lid.get_location_wrt(device).z, plate_top) + lid_x = self.lid.get_location_wrt(device, x="c").x + self.assertAlmostEqual(lid_x, self.plate.get_location_wrt(device, x="c").x, delta=0.5) + await gripper.return_resource() + self.assertIs(self.plate.lid, self.lid) + self.assertIsNone(gripper.held_resource) + return moves, checks + + def assert_logged(self, side: str, moves: List) -> None: + logged = LOGGED[side] + close = next(t for t, f in moves if "GG" in f) + i = next(i for i, (t, f) in enumerate(moves) if t is close) + self.assertEqual(close["GG"], logged["GG close"]) + self.assertEqual(moves[i - 1][0], {"GZ": logged["GZ"]}) + self.assertEqual(moves[i - 2][0], {"GG": logged["GG open"]}) + travel = moves[i - 3][0] + for axis in ("X", "GY", "GR"): + if axis in logged: + self.assertAlmostEqual(travel[axis], logged[axis], delta=3, msg=axis) + + async def test_the_left_pod_takes_the_lid_as_logged_without_checks(self) -> None: + moves, checks = await self.lid_off_and_on("left") + self.assert_logged("left", moves) + self.assertEqual( + checks, [] + ) # Biomek's configuration has the left pod's grip checks off (SensorEnabled False) + + async def test_the_right_pod_takes_the_lid_as_logged_with_checks(self) -> None: + moves, checks = await self.lid_off_and_on("right") + self.assert_logged("right", moves) + self.assertEqual("".join(checks), "UGGGGU") + + async def test_delid_move_the_plate_and_relid(self) -> None: + # The validation notebook's sequence: the left pod takes the lid and moves aside holding it + # (its gripper kept below the 96-head), the right pod moves the plate to P16, the left pod + # puts the lid back on it there. + driver = self.biomek.driver + assert driver is not None + left, right = driver.arm("left"), driver.arm("right") + await right.move_aside() + await self.gripper("left").pick_up_resource( + self.lid, y_clearance=LID_Y_CLEARANCE, squeeze_mm=LID_SQUEEZE_MM + ) + await left.move_aside() + p16 = self.biomek.deck.get_position("P16") + await self.gripper("right").move_resource(self.plate, p16) + self.assertIs(self.plate.parent, p16) + # Turned to 180 degrees the right hand reaches 9.2 cm past its bridge, over the left pod's + # P16: aside and parked (GR 90) it is clear. + await right.move_aside() + await right.park() + await self.gripper("left").place_resource(self.plate) + self.assertIs(self.plate.lid, self.lid) + self.assertIsNone(self.gripper("left").held_resource) + await self.biomek.park() + + async def test_a_close_on_nothing_is_refused_on_every_pod(self) -> None: + await self.biomek.driver.arm("right").move_aside() # type: ignore[union-attr] + gripper = self.gripper("left") + self.biomek.driver.simulated_grip = None # type: ignore[union-attr] # nothing between the fingers + with self.assertRaises(GripCheckError): + await gripper.pick_up_resource( + self.lid, y_clearance=LID_Y_CLEARANCE, squeeze_mm=LID_SQUEEZE_MM + ) + + async def test_a_plate_moves_between_positions(self) -> None: + place_labware(self.biomek.deck, [{"position": "P16", "class": "Thermo96VB_PP", "name": "p2"}]) + plate = self.biomek.deck.get_resource("p2") + await self.biomek.driver.arm("left").move_aside() # type: ignore[union-attr] + gripper = self.gripper("right") + target = self.biomek.deck.get_position("P12") + await gripper.move_resource(plate, target, pickup_direction="left") + self.assertIs(plate.parent, target) + + +class GripDefaultsTests(unittest.TestCase): + def test_the_default_widths_are_biomeks(self) -> None: + # Thermo96VB_PP (8.56 cm): Biomek opens to 9.706 cm and closes towards 7.897 cm. + plate = beckman_coulter_biomek_96_wellplate_vb("plate") + self.assertAlmostEqual(plate.get_size_y() + 2 * Y_CLEARANCE, 97.06) + self.assertAlmostEqual(plate.get_size_y() - 2 * SQUEEZE_MM, 78.97) + + def test_grip_sides_follow_a1(self) -> None: + plate = beckman_coulter_biomek_96_wellplate_vb("plate") + # Where the fingers point: "A1 near" has the hand on A1's side, the left at rotation 0. + self.assertEqual(biomek_grip_direction(plate, "A1 near"), "right") + self.assertEqual(biomek_grip_direction(plate, "A1 away from"), "left") + self.assertEqual(biomek_grip_direction(plate, "Wide A1 near"), "front") + plate.rotate(z=180) + self.assertEqual(biomek_grip_direction(plate, "A1 near"), "left") + plate.rotate(z=90) + self.assertEqual(biomek_grip_direction(plate, "A1 near"), "front") + with self.assertRaises(ValueError): + biomek_grip_direction(plate, "sideways") + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index 74a0f23c222..cb8894f60f2 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -45,6 +45,7 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.errors import INTERLOCK_TRIPPED_CODE, ace_error from pylabrobot.beckman_coulter.biomek_i7.driver.features.chassis import Chassis from pylabrobot.beckman_coulter.biomek_i7.driver.features.door import Door +from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import MoveResult, Pod @@ -163,6 +164,9 @@ def __init__( # The deck the operations work on (STAR's `driver.deck`), set by `BiomekI7`; None without one. # Moves, homing and the rail guard never need it. self.deck: Optional["BiomekI7Deck"] = None + # In simulation, what has a pod's GG stop on labware the gripper closes on (its width, cm; + # None: nothing between the fingers). Set by `simulator.simulate_grips`. + self.simulated_grip: Optional[Callable[[Pod, Optional[float]], None]] = None # -- lifecycle ------------------------------------------------------------- @@ -199,9 +203,9 @@ async def setup( """ logger.warning( "The Biomek i7 driver has run on one instrument (Home All, prime, tips and transfers on " - "both heads, park); its commands were compared with Biomek's logs where Biomek ran the " - "same operation; it is untested on other instruments. Please report what works and what " - "does not." + "both heads, grips on both pods, park); its commands were compared with Biomek's logs " + "where Biomek ran the same operation; it is untested on other instruments. Please report " + "what works and what does not." ) if not self._connected: await self._open() @@ -524,6 +528,13 @@ def pipettes(self) -> Optional[Pipettes]: pod = self._one_with("pipettes") return pod.pipettes if pod is not None else None + @property + def gripper(self) -> Optional[Gripper]: + """The gripper, on an instrument with one pod that has one (a pod has a gripper where its + declared configuration describes one).""" + pod = self._one_with("gripper") + return pod.gripper if pod is not None else None + async def request_axis_states(self) -> Dict[str, Dict[str, p.AxisStateName]]: """Every axis's state, by pod side then axis name. Moves nothing.""" return {pod.side: await pod.request_axis_states() for pod in self.arms} diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_features_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_features_tests.py new file mode 100644 index 00000000000..f3ad7ab9239 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_features_tests.py @@ -0,0 +1,162 @@ +"""What each pod carries (`head96`, `pipettes`, `gripper`), the instrument-level shortcuts to them, +and finding a pod by the names Biomek gives it.""" + +from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( + generic_biomek, + generic_driver, + generic_simulated_boards, +) + + +class PodFeaturesTests(PodMoveTest): + async def test_each_pod_carries_what_its_module_has(self) -> None: + driver = await self.homed() + left, right = self.pod(driver, "left"), self.pod(driver, "right") + self.assertEqual((left.module_type, right.module_type), ("multichannel", "span8")) + self.assertIsNotNone(left.head96) + self.assertIsNone(left.pipettes) + self.assertIsNone(right.head96) + self.assertIsNotNone(right.pipettes) + self.assertIsNotNone(left.gripper) + self.assertIsNotNone(right.gripper) + + async def test_shortcuts_resolve_only_when_one_pod_has_the_feature(self) -> None: + driver = await self.homed() + left, right = self.pod(driver, "left"), self.pod(driver, "right") + self.assertIs(driver.head96, left.head96) + self.assertIs(driver.pipettes, right.pipettes) + with self.assertRaisesRegex(ValueError, "left_x_arm.gripper"): + driver.gripper + with self.assertRaisesRegex(ValueError, "left_x_arm"): + driver.x_arm + self.assertEqual(driver.arms, [left, right]) + driver.right_x_arm = None # an instrument with one pod + self.assertIs(driver.gripper, left.gripper) + self.assertIsNone(driver.pipettes) + self.assertIs(driver.x_arm, left) + + async def test_each_feature_knows_its_arm(self) -> None: + driver = await self.homed() + left, right = self.pod(driver, "left"), self.pod(driver, "right") + assert left.head96 is not None and right.pipettes is not None + self.assertIs(left.head96.arm, left) + self.assertIs(right.pipettes.arm, right) + for pod in (left, right): + assert pod.gripper is not None + self.assertIs(pod.gripper.arm, pod) + + async def test_the_device_reads_through_to_the_driver(self) -> None: + driver = await self.homed() + lh = BiomekI7(driver=driver) + self.assertIs(lh.left_x_arm, driver.left_x_arm) + self.assertIs(lh.right_x_arm, driver.right_x_arm) + self.assertIs(lh.head96, driver.head96) + self.assertIs(lh.pipettes, driver.pipettes) + self.assertIs(lh.chassis, driver.chassis) + self.assertEqual(lh.arms, driver.arms) + with self.assertRaises(ValueError): + lh.gripper + with self.assertRaises(ValueError): + lh.x_arm + self.assertIsNone(generic_biomek().left_x_arm) # not yet set up + + async def test_a_pod_by_any_name_biomek_gives_it(self) -> None: + driver = await self.homed() + left, right = self.pod(driver, "left"), self.pod(driver, "right") + for name in ("left", 1, "Pod1", "MC_1"): + self.assertIs(driver.arm(name), left) + for name in ("right", 2, "Pod2", "SPAN8_2"): + self.assertIs(driver.arm(name), right) + with self.assertRaises(KeyError): + driver.arm("Pod3") + + +class StarAlignmentTests(PodMoveTest): + """The second pass's alignments with STAR (PLR_PARITY_AUDIT.md).""" + + async def test_x_arm_refuses_as_the_stars_does(self) -> None: + + with self.assertRaises(RuntimeError): # not read yet + generic_driver(generic_simulated_boards()).x_arm + driver = await self.homed() + with self.assertRaises(ValueError): # two pods + driver.x_arm + driver.left_x_arm = driver.right_x_arm = None + with self.assertRaisesRegex(ValueError, "no pod"): + driver.x_arm + + async def test_the_span8s_settings_and_trash_are_checked_and_named(self) -> None: + pipettes = self.pod(await self.homed(), "right").pipettes + assert pipettes is not None + with self.assertRaises(ValueError): + await pipettes._set_lls_sensitivity(5000) + with self.assertRaises(TypeError): # the trash is keyword-only: no offsets taken for it + await pipettes.discard_tips([0], [object()]) # type: ignore[arg-type, misc] + + async def test_star_shaped_calls_cannot_land_on_the_wrong_argument(self) -> None: + driver = await self.homed() + head96, pipettes = self.pod(driver, "left").head96, self.pod(driver, "right").pipettes + assert head96 is not None and pipettes is not None + # STAR's positional arguments past the targets and offsets (a pickup method, the heights in + # its own order) are refused rather than taken as heights. + with self.assertRaises(TypeError): + await pipettes.pick_up_tips([], [0], None, 100.0) # type: ignore[misc] + with self.assertRaises(TypeError): + await head96.pick_up_tips(None, None, 100.0) # type: ignore[arg-type, misc] + with self.assertRaises(TypeError): + await head96.drop_tips(None, None, 100.0) # type: ignore[arg-type, misc] + with self.assertRaises(TypeError): + await head96.discard_tips(None) # type: ignore[misc] + # STAR's per-channel lists; the template applies one value to every probe. + with self.assertRaisesRegex(ValueError, "settling_times: one value"): + await pipettes.aspirate([], [], settling_times=[0.1, 0.2]) + with self.assertRaisesRegex(ValueError, "blow_out_air_volumes: one value"): + await pipettes.dispense([], [], blow_out_air_volumes=[5.0, 10.0]) + + async def test_setup_skips_name_features_as_the_star_does(self) -> None: + driver = await self.homed() + self.assertEqual(driver.skipped_sides(skip_head96=True), {"left"}) + self.assertEqual(driver.skipped_sides(skip_pipettes=True), {"right"}) + self.assertEqual( + driver.skipped_sides(skip_pipettes=True, skip_left_x_arm=True), {"left", "right"} + ) + self.assertEqual(driver.skipped_sides(), set()) + + def test_return_resource_takes_place_resources_arguments(self) -> None: + import inspect + + from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper + + place = inspect.signature(Gripper.place_resource).parameters + back = inspect.signature(Gripper.return_resource).parameters + self.assertEqual([n for n in place if n != "to"], list(back)) # as STAR's return_resource + + async def test_axis_states_are_names(self) -> None: + states = await self.pod(await self.homed(), "left").request_axis_states() + self.assertEqual(set(states.values()), {"enabled"}) + + async def test_the_grip_direction_default_is_an_attribute(self) -> None: + driver = await self.homed() + left, right = self.pod(driver, "left").gripper, self.pod(driver, "right").gripper + assert left is not None and right is not None + self.assertIsNone(left.default_direction) + # Each pod's own: the fingers point away from its side, the hand on the labware's near side. + self.assertEqual(left._direction(None), "right") + self.assertEqual(right._direction(None), "left") + left.default_direction = "front" + self.assertEqual(left._direction(None), "front") + self.assertEqual(left._direction("back"), "back") + self.assertEqual(left._direction(-270.0), "back") # degrees on the deck, as STAR's iSWAP + with self.assertRaises(ValueError): + left._direction(45.0) + with self.assertRaises(ValueError): + left._direction("up") # type: ignore[arg-type] + + def test_grip_directions_are_half_a_turn_from_the_legacy_hand_sides(self) -> None: + from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import GRIP_ANGLES + + # Biomek's GR for each, as its logged grips show them. + # 0 points the fingers along +x (the hand on the labware's left), 90 to the front. + self.assertEqual(GRIP_ANGLES, {"right": 0.0, "front": 90.0, "left": 180.0, "back": -90.0}) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py index 56a0ee26540..22fd7b00115 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py @@ -26,7 +26,7 @@ follows its coordinated path (`swept_x_range`), so a gripper turning through the other pod's side between those poses is caught. This is never looser. - **Held labware.** Biomek reads its size, and the stack on it, from its labware library. Here the - caller gives it, from the resource the gripper holds (`HeldLabware`). + caller gives it, from the resource the gripper holds (`HeldLabware`, `gripper.held_labware_of`). """ import math diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py index 8ba3a0eaf7d..44a75d64249 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -43,6 +43,7 @@ if TYPE_CHECKING: from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod # Names the recording the simulator answers from (identity and sensor reads, recorded at an # instrument's cold start) when no path is given. A generic one ships in `defaults/` @@ -162,7 +163,8 @@ class SimulatedAceUSB(ReplayAceUSB): model answers "interlock tripped" without power and 0x3D for a stuck fault. A move with a force limit stops where the axis meets something (`_AxisModel.obstacle`, set by a - test). A move with a sensor stops where the sensor fires (`_AxisModel.sensed_at`), and the + test), and the axis then reads `stalled_effort` as its control effort (a gripper holding a + plate). A move with a sensor stops where the sensor fires (`_AxisModel.sensed_at`), and the Move All carries that axis's report (LLS_LIQUID_SENSED and the position) under its sequence. A pump keeps the valve it was last moved through. Get Tip Status answers `tip_states` when set, else `tip_sensor()` when set (the @@ -276,6 +278,8 @@ def answer(self, message: bytes) -> Optional[List[bytes]]: return [header + b"\x00\x3d"] axis.state = AxisState(params[0]) return [done] + if opcode == 0x31: + return [done + struct.pack(" Optional[str]: if ( self.force and obstacle is not None and obstacle != self.position and low <= obstacle <= high ): - self.position = obstacle + self.position, self.effort = obstacle, self.stalled_effort return "stalled" + self.effort = 0 if self.sensor and sensed_at is not None and low <= sensed_at <= high: self.position = sensed_at return "sensed" @@ -499,6 +507,21 @@ def simulated_boards( return boards +def simulate_grips(driver: "BiomekI7Driver", boards: Sequence[AceBoard]) -> None: + """Have each simulated pod's GG stop, force-limited, at the width of what its gripper closes on + (and read the stalled control effort a held grip reads), so a simulated run's grips and grip + checks behave as the instrument's. `boards`: the driver's simulated boards.""" + models = {b.name: b.io for b in boards if isinstance(b.io, SimulatedAceUSB)} + + def grip(pod: "Pod", width: Optional[float]) -> None: + io = models.get(f"simulated {pod.module_type}") + if io is None or pod.declared is None: + return + io.axis_model("GG").obstacle = None if width is None else pod.declared.to_counts("GG", width) + + driver.simulated_grip = grip + + def sense_recorded_tips(driver: "BiomekI7Driver", boards: Sequence[AceBoard]) -> None: """Have each simulated Span-8 board's tip sensor report the tips its pod's `pipettes` record (0 loaded, 2 unloaded per probe), so a simulated run's tip checks pass where the pickups and discards it ran would leave tips. `boards`: the driver's simulated boards.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py index 252c70394d5..6617a031570 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/pods.py @@ -18,7 +18,7 @@ pod's Y along its bridge. A Multichannel's head (`heads.head96`) hangs below it and follows Z in it (`place_head96`). The parts with axes of their own are the bridge's: a Span-8's probes (`heads.span8_channel`, each following its own Y and Z) and the gripper (`gripper_model`, a -`MechanicalGripper` posed from GY, GZ, GR and GG). +`MechanicalGripper` posed from GY, GZ, GR and GG), from which what it holds hangs. """ from dataclasses import dataclass @@ -118,13 +118,19 @@ def pad_block(outline: Outline) -> Tuple[float, float, float, float]: class GripperModel: """A pod's gripper in the resource tree, from the instrument file's `GripperModel` (cm), posed by `pose`: the upper hand, which does not turn, and the gripper (`MechanicalGripper`), which turns - about the rotation centre with the lower hand (its body) and the fingers, its pads its tool centre - point. Both are children of what the gripper is posed in (the pod's bridge).""" + about the rotation centre with the lower hand (its body) and the fingers, and holds what the + gripper holds at the pads (its tool centre point). Both are children of what the gripper is posed + in (the pod's bridge).""" upper_hand: Resource gripper: MechanicalGripper model: Dict[str, Any] + @property + def hand(self) -> MechanicalGripper: + """What turns and what the held labware hangs from: the gripper.""" + return self.gripper + @property def fingers(self) -> Tuple[Resource, Resource]: return self.gripper.fingers[0], self.gripper.fingers[1] diff --git a/pylabrobot/beckman_coulter/biomek_i7/session_log.py b/pylabrobot/beckman_coulter/biomek_i7/session_log.py index 3bca1a33eb8..f4cdae613ca 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/session_log.py +++ b/pylabrobot/beckman_coulter/biomek_i7/session_log.py @@ -1,8 +1,9 @@ """A run's log in a file of its own, to compare a live run with Biomek's logs of the same work. `start_session_log(directory)` writes every line of this package's loggers to -`/biomek_i7_.log`: the driver's commands, warnings and errors, and with -`usb_frames` every message to and from the boards, unframed and in +`/biomek_i7_.log`: the driver's commands (each move's axis targets in +counts, speed, force limits and Move All timeout; homes, valve and tip commands, grip checks), +warnings and errors, and with `usb_frames` every message to and from the boards, unframed and in hex, which is what Biomek's Master Controller keeps in its `ace_io` table. Each line starts with the time in milliseconds since the epoch, as the Master Controller's tables stamp theirs. diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py index 203bb137d17..79d7be98ace 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -7,7 +7,8 @@ import shutil import tempfile from pathlib import Path -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence +import asyncio +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck from pylabrobot.beckman_coulter.biomek_i7.defaults import GENERIC_CONFIGURATION, GENERIC_RECORDING @@ -18,6 +19,7 @@ if TYPE_CHECKING: from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7Device + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod _GENERIC: Optional[Dict[str, Any]] = None @@ -132,3 +134,17 @@ def generic_biomek(**kwargs: Any) -> "BiomekI7Device": kwargs.setdefault("declared_configuration_json", str(GENERIC_CONFIGURATION)) kwargs.setdefault("simulator_recording", str(GENERIC_RECORDING)) return BiomekI7(**kwargs) + + +def generic_pods() -> Tuple["Pod", "Pod"]: + """The generic instrument's pods (the Multichannel's, the Span-8's), discovered on the replayed + cold start: what an argument given per arm (`arm=`) takes its units from.""" + + async def discover() -> Tuple["Pod", "Pod"]: + driver = generic_driver() + await driver.discover() + await driver.stop() + assert driver.left_x_arm is not None and driver.right_x_arm is not None + return driver.left_x_arm, driver.right_x_arm + + return asyncio.run(discover()) From 0062e9a3df1413296821b8a1c9094151f703eed0 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:00:56 +0000 Subject: [PATCH 21/28] `Biomek i7`: sort imports for ruff I001 --- .../biomek_i7/device_model_tests.py | 8 ++++---- .../biomek_i7/driver/features/gripper.py | 3 +-- .../biomek_i7/driver/features/pod.py | 14 +++++++------- .../biomek_i7/driver/gripper_tests.py | 2 +- .../beckman_coulter/biomek_i7/driver/simulator.py | 2 +- .../biomek_i7/simulation_tests_support.py | 2 +- 6 files changed, 15 insertions(+), 16 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py index f91c05e311f..aeae11510f7 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py @@ -16,15 +16,15 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.resource_model import MM_PER_CM from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import gripper_model -from pylabrobot.resources import Resource -from pylabrobot.resources.coordinate import Coordinate -from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb -from pylabrobot.resources.rotation import Rotation from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( generic_biomek, generic_configuration, generic_deck, ) +from pylabrobot.resources import Resource +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb +from pylabrobot.resources.rotation import Rotation def biomek_x_range(lh: BiomekI7Device, resource: Resource) -> g.Range: diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py index 4877a532a5b..cb3323ac9da 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py @@ -24,10 +24,9 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union -from pylabrobot.beckman_coulter.biomek_i7 import targeting +from pylabrobot.beckman_coulter.biomek_i7 import targeting, units from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p -from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.driver.errors import GripCheckError from pylabrobot.beckman_coulter.biomek_i7.units import MM_PER_CM from pylabrobot.beckman_coulter.biomek_i7.units import optional_cm as _cm diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index 15fd93067f6..d124063d678 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -21,29 +21,29 @@ from pylabrobot.beckman_coulter.biomek_i7 import units from pylabrobot.beckman_coulter.biomek_i7.driver import motion +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( ModuleConfiguration, PodConfiguration, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english +from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, read_module, ) +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ( ENABLE_ORDER, ENABLE_PREFIX, HOME_RECIPES, Homer, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper -from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 -from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes -from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english -from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail if TYPE_CHECKING: diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py index 2bb3c79cc15..bf16430c79c 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py @@ -13,10 +13,10 @@ biomek_grip_direction, ) from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware -from pylabrobot.resources import Plate, beckman_coulter_biomek_96_wellplate_vb from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( generic_biomek, ) +from pylabrobot.resources import Plate, beckman_coulter_biomek_96_wellplate_vb # Biomek's TiterplateLid widths (open 9.401 cm, close 7.592 cm) on the lid, which PyLabRobot sizes # to its plate's 8.56 cm: per call, as the gripper's defaults are Biomek's margins for labware. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py index 44a75d64249..21a4d11a7ae 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/simulator.py @@ -42,8 +42,8 @@ from pylabrobot.io.usb import USB if TYPE_CHECKING: - from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver # Names the recording the simulator answers from (identity and sensor reads, recorded at an # instrument's cold start) when no path is given. A generic one ships in `defaults/` diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py index 79d7be98ace..39ae36c4960 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests_support.py @@ -1,13 +1,13 @@ """What the package's tests build their simulated Biomek i7 from: the generic one in `defaults/`, named explicitly (never through `$BIOMEK_I7_SIMULATOR_RECORDING`). Not a test module itself.""" +import asyncio import atexit import copy import json import shutil import tempfile from pathlib import Path -import asyncio from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck From 26d6301f8032f0cc983f2907ff234d175029e9d7 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:47:58 -0800 Subject: [PATCH 22/28] `Biomek i7`: Biomek's techniques and liquid types as plain arguments `techniques.py` reads Biomek's techniques and liquid types as plain records (Biomek's field names, as its project database stores them) and turns them into the keyword arguments the pipetting features take (`aspirate_arguments`, `dispense_arguments`, `method_step_arguments` for a method's step with its template's offset and approach, `for_channels` for the Span-8's per-channel lists), which a caller splats and overrides. A technique that needs what the features do not take yet (prewet, liquid-level sensing, clot detection, a volume calibration, a mix given as a method variable or with two speeds) is refused rather than run without it. Tests: a method's logged steps give the arguments `liquid_tests` checks against the logged moves; the liquid type unless the technique overrides it; the Span-8's own values; refusals. --- .../beckman_coulter/biomek_i7/design.md | 4 + .../biomek_i7/driver/features/head96.py | 3 +- .../biomek_i7/driver/features/pipettes.py | 3 +- .../beckman_coulter/biomek_i7/techniques.py | 370 +++++++++++++++++- .../biomek_i7/techniques_tests.py | 161 ++++++++ 5 files changed, 534 insertions(+), 7 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index 2e565c9b375..e219c7fe1f1 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -122,3 +122,7 @@ shuck. It has no tip sensor, so `setup` ejects over its trash even with no tips carry, place. The grip point is the resource's `preferred_pickup_location`; the widths default to Biomek's margins around the labware's width; a close that reaches its target met nothing and is refused. A pod's own gripper and pipettor are kept apart (`driver/pod_collision.py`). + +**I15. Biomek's techniques are a translation, not a mode.** `techniques.py` turns a Biomek technique +and liquid type into the features' keyword arguments, which a caller splats and overrides. There is +no `technique=` argument and no selection by rank. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py index 857cb62e1d4..b8edd01c879 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py @@ -762,7 +762,8 @@ async def aspirate( ) -> None: """Draw `volume` uL into every carried tip, from a 96-well plate (mandrel A1 over well A1) or one container (the head centred over it), as Biomek's "MC Pipetting" template does (see - `driver/liquid.py`). + `driver/liquid.py`). `techniques.aspirate_arguments` gives the keywords a Biomek technique + stands for. Args: resource: a plate of 96 wells, or a container (a reservoir's well, a 1-well plate). diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py index 238d5d4aeb9..8eeda5c5f56 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py @@ -1211,7 +1211,8 @@ async def aspirate( """Draw `volumes` (uL, one per channel) from `containers`, as Biomek's "S8 Pipetting" template does (see `driver/liquid.py`): one batch per set of containers the probes reach in one move (a shared container: the probes centred in it at the narrowest span). STAR's `Pipettes` - signature. + signature; `techniques.aspirate_arguments(..., arm=pod)` gives the keywords a Biomek + technique stands for (`liquid_height`, `flow_rate` as one value for every channel). Args: containers: one per channel. diff --git a/pylabrobot/beckman_coulter/biomek_i7/techniques.py b/pylabrobot/beckman_coulter/biomek_i7/techniques.py index 0a19517b1a3..8d4a3cba66b 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/techniques.py +++ b/pylabrobot/beckman_coulter/biomek_i7/techniques.py @@ -1,9 +1,72 @@ -"""The arguments the pipetting features take that PyLabRobot has no type for, named after what -Biomek's techniques hold: conditioning, a tip touch, a mix's heights, and what a height is -measured from.""" +"""Biomek's techniques and liquid types, translated into the arguments of the pipetting features. -from dataclasses import dataclass -from typing import Literal, Optional +The features (`head96.aspirate` / `dispense`, `pipettes.aspirate` / `dispense`) take PyLabRobot's +arguments only. Biomek keeps the same knowledge in two records of its project database: + +- a **liquid type** (`Water`, `Serum`): flow rates, delays, blowout and trailing air volumes, the + cutoff velocity, the prewet overage and the tip-touch defaults: what PyLabRobot calls a liquid + class; +- a **technique** (`MC P1200 High`, or a method step's own `[Custom]` copy): per operation the + height and what it is measured from (Top, Bottom or Liquid), Follow Liquid, the Z speed in the + well and the switches (blowout, trailing air gap, tip touch, mix); in its General section the + minimum height, conditioning, prewet, liquid-level sensing and clot detection, and its own copy + of the liquid type's values, used instead of the liquid type's when `overrideliquidtypesettings` + is set (every logged step on this instrument has it set, and its values are the ones logged). + +This module reads both as plain records (Biomek's field names without the `c__` prefix, as the +project database stores them) and turns them into +keyword arguments: + + args = aspirate_arguments(technique, water) + await lh.head96.aspirate(plate, 200, **{**args, "flow_rate": 50}) + +What each argument means, and how the pipetting template uses it, is the features' business; the +mapping is here: + +| Biomek | argument | +|---|---| +| Height (mm) from Top / Bottom / Liquid | `liquid_height` (mm), `height_from` | +| Follow Liquid | `follow_liquid` | +| Minimum Height (mm above the bottom) | `minimum_height` | +| Speed (% of Z's maximum, in the well) | `z_speed` (mm/s on the arm's Z) | +| aspirate / dispense speed (uL/s) | `flow_rate` | +| aspirate / dispense delay (ms) | `settling_time` (s) | +| Blowout + blowout volume | `blow_out_air_volume` (0 when off) | +| Trailing Air Gap + its volume | `transport_air_volume` (0 when off) | +| conditioning (sections, section volume, excess) | `conditioning` | +| Tip Touch + height, from, theta, speed (%), delay | `tip_touch` (None when off; its speed a fraction) | +| Empty Tips (dispense) | `empty` | +| Mix + count, volume, aspirate / dispense speed (uL/s), Follow Liquid | `pre_mix` (aspirate) / `post_mix` (dispense): PyLabRobot's `Mix`, `auto_surface_following` from Follow Liquid | +| Mix aspirate / dispense height (mm) and from | `mix_heights` (`MixHeights`) | +| cutoff velocity (uL/s), conductivity (Span-8) | `cutoff_velocity`, `lls_sensitivity` | + +A mix's draw and push share one flow rate (PyLabRobot's `Mix`), so a technique whose two mix speeds +differ is refused, as is a mix volume or count that is an expression (`=DilutionVolume`: a method's +variable, which only the method knows; pass the `Mix` yourself). Prewet, liquid-level sensing and +clot detection map to arguments the features do not take yet; a technique that turns them on is +refused rather than run without them. `CalibrationSlope` / +`CalibrationOffset` (volume correction) are not applied: how Biomek applies them is not traced, and +a technique with other than 1 / 0 is refused. + +A method's pipetting step (with its `[Custom]` technique) adds its own height when it overrides the technique's, and names a template: +the reservoir variants of the standard templates move every aspirate 2 mm to the left (`radius +0.2` cm at `theta 180`), and the Span-8's also approaches 10 mm above the liquid. +`method_step_arguments` gives all of it, the offset as a `Coordinate` (mm). +""" + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Dict, Literal, Mapping, Optional, Tuple + +from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.resources.coordinate import Coordinate + +if TYPE_CHECKING: + from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import Pod + +# What a technique's heights are measured from (Biomek's `HeightFrom`): 0 the liquid's surface, +# 1 the well's bottom, 2 its top. +HEIGHT_FROM: Dict[int, "HeightFrom"] = {0: "liquid", 1: "bottom", 2: "top"} @dataclass(frozen=True) @@ -58,3 +121,300 @@ class MixHeights: aspirate_height_from: HeightFrom = "bottom" dispense_height: Optional[float] = None dispense_height_from: Optional[HeightFrom] = None + + +def _strip(record: Mapping[str, Any]) -> Dict[str, Any]: + """A section of a project database record: keys without `c__`, lower case; Biomek's number + strings as numbers; the reader's `$id`s dropped.""" + out: Dict[str, Any] = {} + for key, value in record.items(): + if key.startswith("$"): + continue + name = key.lower() + name = name[3:] if name.startswith("c__") else name + if isinstance(value, str): + try: + value = float(value) if "." in value else int(value) + except ValueError: + pass + out[name] = value + return out + + +@dataclass +class BiomekLiquidType: + """A Biomek liquid type: its values under Biomek's names (`aspiratespeed`, `blowoutvolume`...).""" + + name: str + values: Dict[str, Any] = field(default_factory=dict) + + @classmethod + def from_record(cls, record: Mapping[str, Any]) -> "BiomekLiquidType": + """From a liquid type record (Biomek's field names, without the `c__` prefix).""" + values = _strip(record.get("context") or {}) + for key in ("conductivity", "cdconductivity"): + if key in record: + values[key] = record[key] + return cls(name=str(record.get("name") or values.get("liquidtype") or ""), values=values) + + +@dataclass +class BiomekTechnique: + """A Biomek technique: its sections under Biomek's names (`height`, `heightfrom`...).""" + + name: str + template: str = "" + aspirate: Dict[str, Any] = field(default_factory=dict) + dispense: Dict[str, Any] = field(default_factory=dict) + mix: Dict[str, Any] = field(default_factory=dict) + general: Dict[str, Any] = field(default_factory=dict) + context: Dict[str, Any] = field(default_factory=dict) + + @classmethod + def from_record(cls, record: Mapping[str, Any]) -> "BiomekTechnique": + """From a technique record (Biomek's field names, without the `c__` prefix), or a method + step's embedded copy in the same shape.""" + return cls( + name=str(record.get("name") or ""), + template=str(record.get("template") or ""), + **{s: _strip(record.get(s) or {}) for s in ("aspirate", "dispense", "mix", "general")}, + context=_strip(record.get("context") or {}), + ) + + +# -- the translation ------------------------------------------------------------------------------ + + +def _liquid_values(technique: BiomekTechnique, liquid_type: Optional[BiomekLiquidType]) -> Dict: + """The liquid values a step runs with: the technique's own copy when it overrides the liquid + type (or no liquid type is given), else the liquid type's.""" + general = technique.general + if liquid_type is None or general.get("overrideliquidtypesettings", True): + return general + return {**general, **liquid_type.values} + + +def _refuse_unbuilt(technique: BiomekTechnique, section: Mapping[str, Any]) -> None: + general = technique.general + unbuilt = [ + name + for name, on in (("prewet", general.get("prewet") and section is technique.aspirate),) + if on + ] + if general.get("calibrationslope", 1.0) != 1.0 or general.get("calibrationoffset", 0.0) != 0.0: + unbuilt.append("volume calibration") + if unbuilt: + raise NotImplementedError( + f"technique {technique.name!r} uses {', '.join(unbuilt)}, which the driver does not do yet" + ) + + +def _tip_touch(section: Mapping[str, Any], liquid: Mapping[str, Any]) -> Optional[TipTouch]: + if not section.get("tiptouch"): + return None + return TipTouch( + height=float(liquid.get("tiptouchheight", 0.0)), + height_from=HEIGHT_FROM[int(liquid.get("tiptouchheightfrom", 0))], + theta=float(liquid.get("tiptouchtheta", 90.0)), + speed_fraction=float(liquid.get("tiptouchspeed", 100.0)) / 100, + delay=float(liquid.get("tiptouchdelay", 0.0)) / 1000, + ) + + +def _mix_number(section: Mapping[str, Any], key: str, technique: BiomekTechnique) -> float: + value = section.get(key) + if not isinstance(value, (int, float)) or isinstance(value, bool): + raise NotImplementedError( + f"technique {technique.name!r} uses a mix whose {key[3:]} is {value!r}, which the driver " + "cannot evaluate (a method's variable): pass the Mix yourself" + ) + return float(value) + + +def _mix(section: Mapping[str, Any], technique: BiomekTechnique) -> Dict[str, Any]: + """The section's Mix as a `Mix` and its `MixHeights`, or nothing when it does not mix.""" + if not section.get("mix"): + return {} + draw, push = ( + _mix_number(section, k, technique) for k in ("mixaspiratespeed", "mixdispensespeed") + ) + if draw != push: + raise NotImplementedError( + f"technique {technique.name!r} uses a mix whose aspirate and dispense speeds differ " + f"({draw:g}, {push:g} uL/s), which the driver does not do: one flow rate for both" + ) + return { + "mix": Mix( + volume=_mix_number(section, "mixvolume", technique), + repetitions=int(_mix_number(section, "mixcount", technique)), + flow_rate=draw, + auto_surface_following=bool(section.get("followliquid", False)), + ), + "mix_heights": MixHeights( + aspirate_height=float(section.get("mixaspirateheight", 0.0)), + aspirate_height_from=HEIGHT_FROM[int(section.get("mixaspiratefrom", 1))], + dispense_height=float(section.get("mixdispenseheight", 0.0)), + dispense_height_from=HEIGHT_FROM[int(section.get("mixdispensefrom", 1))], + ), + } + + +def _common(section: Mapping[str, Any], general: Mapping[str, Any], arm: "Pod") -> Dict[str, Any]: + z = arm.channel_z_axes[0] # every channel's Z alike + return { + "liquid_height": float(section.get("height", 0.0)), + "height_from": HEIGHT_FROM[int(section.get("heightfrom", 1))], + "follow_liquid": bool(section.get("followliquid", False)), + "minimum_height": float(general.get("minimumheight", 0.0)), + "z_speed": units.field_to_rate( + arm, z, units.percent_to_field(float(section.get("speed", 100.0))) + ), + } + + +def _span8(liquid: Mapping[str, Any], general: Mapping[str, Any]) -> Dict[str, Any]: + return { + "cutoff_velocity": float(liquid.get("cutoffvelocity", 150.0)), + "lls_sensitivity": int(general.get("conductivity", liquid.get("conductivity", 3500))), + } + + +def aspirate_arguments( + technique: BiomekTechnique, + liquid_type: Optional[BiomekLiquidType] = None, + *, + arm: "Pod", +) -> Dict[str, Any]: + """The aspirate arguments a technique (and liquid type) stand for on `arm` (its Z speed in mm/s + on that arm's Z, from Biomek's %, exactly); a Span-8 arm adds its own (`cutoff_velocity`, + `lls_sensitivity`). With the section's Mix on, `pre_mix` and `mix_heights`. Scalars: a Span-8 + caller lists the per-channel ones (`for_channels`). + + Raises: + NotImplementedError: if the technique turns on what the driver does not do yet, or mixes with + two speeds or a volume it cannot evaluate. + """ + section, general = technique.aspirate, technique.general + _refuse_unbuilt(technique, section) + liquid = _liquid_values(technique, liquid_type) + args = _common(section, general, arm) + args.update( + flow_rate=float(liquid.get("aspiratespeed", 100.0)), + settling_time=float(liquid.get("aspiratedelay", 0.0)) / 1000, + blow_out_air_volume=float(liquid.get("blowoutvolume", 0.0)) if section.get("blowout") else 0.0, + transport_air_volume=( + float(liquid.get("trailingairgapvolume", 0.0)) if section.get("trailingairgap") else 0.0 + ), + conditioning=Conditioning( + sections=int(general.get("conditioningsectioncount", 0)), + section_volume=float(general.get("conditioningsectionvolume", 0.0)), + excess=float(general.get("conditioningexcess", 0.0)), + flow_rate=float(liquid.get("dispensespeed", 100.0)), + delay=float(liquid.get("dispensedelay", 0.0)) / 1000, + ), + tip_touch=_tip_touch(section, liquid), + ) + mix = _mix(section, technique) + if mix: + args.update(pre_mix=mix["mix"], mix_heights=mix["mix_heights"]) + if arm.pipettes is not None: + args.update(_span8(liquid, general)) + return args + + +def dispense_arguments( + technique: BiomekTechnique, + liquid_type: Optional[BiomekLiquidType] = None, + *, + arm: "Pod", +) -> Dict[str, Any]: + """The dispense arguments a technique (and liquid type) stand for; as `aspirate_arguments`, + the mix as `post_mix`. + + Raises: + NotImplementedError: if the technique turns on what the driver does not do yet. + """ + section, general = technique.dispense, technique.general + _refuse_unbuilt(technique, section) + liquid = _liquid_values(technique, liquid_type) + args = _common(section, general, arm) + args.update( + flow_rate=float(liquid.get("dispensespeed", 100.0)), + settling_time=float(liquid.get("dispensedelay", 0.0)) / 1000, + blow_out_air_volume=float(liquid.get("blowoutvolume", 0.0)) if section.get("blowout") else 0.0, + blow_out_delay=float(liquid.get("blowoutdelay", 0.0)) / 1000, + tip_touch=_tip_touch(section, liquid), + empty=bool(general.get("emptytips", False)), + ) + mix = _mix(section, technique) + if mix: + args.update(post_mix=mix["mix"], mix_heights=mix["mix_heights"]) + if arm.pipettes is not None: + args.update(_span8(liquid, general)) + return args + + +# What the reservoir templates change in the standard ones, per operation (their records, project +# database: `radius 0.2` at `theta 180` on every move of the aspirate; the Span-8's approach 10 mm). +TEMPLATE_VARIANTS: Dict[str, Dict[str, Dict[str, Any]]] = { + "MC Pipetting Reservoir with Asp Offset": {"aspirate": {"offset": (-2.0, 0.0)}}, + "S8 Pipetting Reservoir Offset Aspirate": { + "aspirate": {"offset": (-2.0, 0.0), "approach_height": 10.0} + }, +} + + +def method_step_arguments( + step: Mapping[str, Any], liquid_type: Optional[BiomekLiquidType] = None, *, arm: "Pod" +) -> Dict[str, Any]: + """The arguments a method's Aspirate or Dispense step stands for, on `arm` (a step's + `Operation`, `Span8`, its `technique` (`asdict(BiomekTechnique)`), and `Height` / `HeightFrom` + when it overrides the technique's): `aspirate_arguments` / `dispense_arguments`, and + `offset` (a `Coordinate`, mm; a Span-8 caller passes it per channel as `resource_offsets`) and + `approach_height` from its template. + + Raises: + ValueError: for a step that is not an aspirate or a dispense. + NotImplementedError: as `aspirate_arguments`. + """ + operation = (step.get("Operation") or "").lower() + if operation not in ("aspirate", "dispense"): + raise ValueError(f"not an aspirate or dispense step: {step.get('Operation')!r}") + technique = BiomekTechnique(**step["technique"]) + translate = aspirate_arguments if operation == "aspirate" else dispense_arguments + if bool(step.get("Span8")) != (arm.pipettes is not None): + raise ValueError( + f"the step is for {'a Span-8' if step.get('Span8') else 'the 96-head'}, not {arm}" + ) + args = translate(technique, liquid_type, arm=arm) + if step.get("OverrideHeight") or step.get("CustomHeight"): + args["liquid_height"] = float(step["Height"]) + args["height_from"] = HEIGHT_FROM[int(step["HeightFrom"])] + extra = TEMPLATE_VARIANTS.get(technique.template, {}).get(operation, {}) + offset: Tuple[float, float] = extra.get("offset", (0.0, 0.0)) + args["offset"] = Coordinate(offset[0], offset[1], 0) + if "approach_height" in extra: + args["approach_height"] = extra["approach_height"] + return args + + +def for_channels(args: Mapping[str, Any], channels: int) -> Dict[str, Any]: + """`args` for a Span-8's `aspirate` / `dispense`, which take STAR's per-channel arguments: the + same `liquid_height`, `flow_rate`, `offset`, `settling_time`, `blow_out_air_volume`, + `transport_air_volume`, `pre_mix` and `post_mix` on each of `channels` channels (as + `liquid_heights`, `flow_rates`, `resource_offsets`, `settling_times`, `blow_out_air_volumes`, + `transport_air_volumes`, `pre_mixes`, `post_mixes`).""" + out = dict(args) + for one, many in ( + ("liquid_height", "liquid_heights"), + ("flow_rate", "flow_rates"), + ("offset", "resource_offsets"), + ("settling_time", "settling_times"), + ("blow_out_air_volume", "blow_out_air_volumes"), + ("transport_air_volume", "transport_air_volumes"), + ("pre_mix", "pre_mixes"), + ("post_mix", "post_mixes"), + ): + if one in out: + out[many] = [out.pop(one)] * channels + return out diff --git a/pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py b/pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py new file mode 100644 index 00000000000..3e2735be86c --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py @@ -0,0 +1,161 @@ +"""Biomek techniques as PyLabRobot arguments: the 96-head steps of a method Biomek's logs ran +(2026-10-20, a dilution), as records exported from Biomek's project database, give the arguments +`driver/liquid_tests.py` checks against the logged moves.""" + +import unittest +from dataclasses import asdict +from typing import Any, Dict + +from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.beckman_coulter.biomek_i7.techniques import ( + BiomekLiquidType, + BiomekTechnique, + Conditioning, + MixHeights, + TipTouch, + aspirate_arguments, + dispense_arguments, + for_channels, + method_step_arguments, +) +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_pods + +SECTION = {"c__mix": False, "c__tiptouch": False, "c__blowout": False, "c__trailingairgap": False} +GENERAL = { + "c__aspiratedelay": 100.0, "c__aspiratespeed": 100.0, "c__dispensedelay": 0.0, + "c__dispensespeed": 100.0, "c__blowoutvolume": 10.0, "c__blowoutdelay": 0.0, + "C__CalibrationSlope": 1.0, "C__CalibrationOffset": 0.0, "C__ConditioningExcess": 0.0, + "C__ConditioningSectionCount": 1.0, "C__ConditioningSectionVolume": 10.0, + "C__MinimumHeight": 0.2, "C__Prewet": False, "c__cutoffvelocity": 150.0, + "C__Conductivity": "3500", "c__overrideliquidtypesettings": True, + "c__tiptouchheight": -2.0, "c__tiptouchheightfrom": 0.0, "c__tiptouchspeed": 100.0, + "c__tiptouchtheta": 90.0, "c__tiptouchdelay": 0.0, +} # fmt: skip +# The method's aspirate step (from the reservoir) and dispense step, sections as a method embeds. +ASPIRATE: Dict[str, Any] = { + "name": "[Custom]", + "template": "MC Pipetting Reservoir with Asp Offset", + "aspirate": {**SECTION, "C__Height": 2.0, "C__HeightFrom": 1, "C__Speed": 50.0, + "C__FollowLiquid": False}, + "general": GENERAL, +} # fmt: skip +DISPENSE: Dict[str, Any] = { + "name": "[Custom]", + "template": "MC Pipetting", + "dispense": {**SECTION, "C__Height": 1.0, "C__HeightFrom": 1, "C__Speed": 25.0, + "C__FollowLiquid": True, "C__TipTouch": True}, + "general": {**GENERAL, "c__dispensespeed": 125.0}, +} # fmt: skip +# The Span-8 dispense step that mixes (the same method): once, 25 uL at 25 uL/s, +# drawing and pushing 2 mm from the bottom, following the liquid as its dispense does. +MIXING_DISPENSE: Dict[str, Any] = { + "name": "[Custom]", + "template": "S8 Pipetting", + "dispense": {**SECTION, "C__Height": 2.0, "C__HeightFrom": 1, "C__Speed": 30.0, + "C__FollowLiquid": True, "c__blowout": True, "c__mix": True, "C__MixCount": 1.0, + "C__MixVolume": 25.0, "C__MixAspirateFrom": 1, "C__MixAspirateHeight": 2.0, + "C__MixAspirateSpeed": 25.0, "C__MixDispenseFrom": 1, "C__MixDispenseHeight": 2.0, + "C__MixDispenseSpeed": 25.0}, + "general": GENERAL, +} # fmt: skip +WATER = {"name": "Water", "context": {"c__aspiratespeed": 90.0, "c__dispensespeed": 90.0}} + + +# The generic instrument's pods: the 96-head's and the Span-8's (the techniques' units are theirs). +MC, S8 = generic_pods() + + +class TechniqueTests(unittest.TestCase): + def test_the_logged_aspirate(self) -> None: + args = aspirate_arguments(BiomekTechnique.from_record(ASPIRATE), arm=MC) + self.assertEqual(args["liquid_height"], 2.0) + self.assertEqual(args["height_from"], "bottom") + self.assertFalse(args["follow_liquid"]) + self.assertEqual(args["minimum_height"], 0.2) # mm, as the log shows + self.assertAlmostEqual(args["z_speed"], 47.5) # mm/s: 50 % of the Multichannel Z's 95 + self.assertEqual(units.rate_to_field(MC, "Z", args["z_speed"]), 500) # Biomek's field, exactly + self.assertEqual(args["flow_rate"], 100.0) + self.assertAlmostEqual(args["settling_time"], 0.1) + self.assertEqual(args["blow_out_air_volume"], 0.0) # off in the aspirate section + self.assertEqual(args["conditioning"], Conditioning(1, 10.0, 0.0, 100.0, 0.0)) + self.assertIsNone(args["tip_touch"]) + + def test_a_method_step(self) -> None: + # The reservoir template moves the aspirate 2 mm left; a step's own height overrides. + step = { + "Operation": "Aspirate", + "Span8": False, + "technique": asdict(BiomekTechnique.from_record(ASPIRATE)), + "OverrideHeight": True, + "Height": 3.0, + "HeightFrom": 2, + } + args = method_step_arguments(step, arm=MC) + self.assertEqual(args["offset"], Coordinate(-2.0, 0.0, 0)) + self.assertEqual((args["liquid_height"], args["height_from"]), (3.0, "top")) + with self.assertRaises(ValueError): + method_step_arguments({**step, "Operation": "Mix"}, arm=MC) + with self.assertRaisesRegex(ValueError, "96-head"): + method_step_arguments(step, arm=S8) # a 96-head step on the Span-8 + + def test_for_channels(self) -> None: + args = for_channels({"liquid_height": 1.0, "flow_rate": 20.0, "z_speed": 30.0}, 3) + self.assertEqual(args, {"liquid_heights": [1.0] * 3, "flow_rates": [20.0] * 3, "z_speed": 30.0}) + + def test_the_logged_dispense(self) -> None: + args = dispense_arguments(BiomekTechnique.from_record(DISPENSE), arm=MC) + self.assertTrue(args["follow_liquid"]) + self.assertEqual(args["flow_rate"], 125.0) + self.assertEqual(args["tip_touch"], TipTouch(height=-2.0, height_from="liquid", theta=90.0)) + self.assertFalse(args["empty"]) + + def test_the_span8_adds_its_own(self) -> None: + args = aspirate_arguments(BiomekTechnique.from_record(ASPIRATE), arm=S8) + self.assertEqual((args["cutoff_velocity"], args["lls_sensitivity"]), (150.0, 3500)) + + def test_the_liquid_type_unless_the_technique_overrides_it(self) -> None: + water = BiomekLiquidType.from_record(WATER) + general = {**GENERAL, "c__overrideliquidtypesettings": False} + technique = BiomekTechnique.from_record({**ASPIRATE, "general": general}) + self.assertEqual(aspirate_arguments(technique, water, arm=MC)["flow_rate"], 90.0) + overriding = BiomekTechnique.from_record(ASPIRATE) + self.assertEqual(aspirate_arguments(overriding, water, arm=MC)["flow_rate"], 100.0) + + def test_the_logged_mixing_dispense(self) -> None: + args = dispense_arguments(BiomekTechnique.from_record(MIXING_DISPENSE), arm=S8) + self.assertEqual(args["post_mix"], Mix(25.0, 1, 25.0, auto_surface_following=True)) + self.assertEqual(args["mix_heights"], MixHeights(2.0, "bottom", 2.0, "bottom")) + self.assertNotIn("pre_mix", args) + span8 = for_channels(args, 8) + self.assertEqual(span8["post_mixes"], [args["post_mix"]] * 8) + self.assertNotIn("post_mix", span8) + # An aspirate section that mixes gives `pre_mix`; one that does not, no mix arguments. + section = {**MIXING_DISPENSE["dispense"], "C__FollowLiquid": False, "C__MixAspirateFrom": 0, + "C__MixAspirateHeight": -1.0} # fmt: skip + mixing = {**ASPIRATE, "aspirate": section} + args = aspirate_arguments(BiomekTechnique.from_record(mixing), arm=MC) + self.assertEqual(args["pre_mix"], Mix(25.0, 1, 25.0)) + self.assertEqual(args["mix_heights"], MixHeights(-1.0, "liquid", 2.0, "bottom")) + self.assertNotIn( + "mix_heights", aspirate_arguments(BiomekTechnique.from_record(ASPIRATE), arm=MC) + ) + + def test_a_mix_the_driver_cannot_take_is_refused(self) -> None: + def dispense(**changes: Any) -> None: + record = {**MIXING_DISPENSE, "dispense": {**MIXING_DISPENSE["dispense"], **changes}} + dispense_arguments(BiomekTechnique.from_record(record), arm=S8) + + with self.assertRaisesRegex(NotImplementedError, "speeds differ"): + dispense(C__MixDispenseSpeed=100.0) # PyLabRobot's Mix has one flow rate + with self.assertRaisesRegex(NotImplementedError, "DilutionVolume"): + dispense(C__MixVolume="=DilutionVolume") # a method's variable + + def test_what_is_not_built_is_refused(self) -> None: + prewetting = {**ASPIRATE, "general": {**GENERAL, "C__Prewet": True}} + with self.assertRaisesRegex(NotImplementedError, "prewet"): + aspirate_arguments(BiomekTechnique.from_record(prewetting), arm=MC) + calibrated = {**ASPIRATE, "general": {**GENERAL, "C__CalibrationSlope": 1.02}} + with self.assertRaisesRegex(NotImplementedError, "calibration"): + aspirate_arguments(BiomekTechnique.from_record(calibrated), arm=MC) From 332c219f0a67b3387baddc0d5877ebb59732ce9b Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:01:11 +0000 Subject: [PATCH 23/28] `Biomek i7`: sort imports for ruff I001 --- pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py b/pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py index 3e2735be86c..a769c2b0a98 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/techniques_tests.py @@ -7,8 +7,7 @@ from typing import Any, Dict from pylabrobot.beckman_coulter.biomek_i7 import units -from pylabrobot.lib.liquid_handling.mix import Mix -from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_pods from pylabrobot.beckman_coulter.biomek_i7.techniques import ( BiomekLiquidType, BiomekTechnique, @@ -20,7 +19,8 @@ for_channels, method_step_arguments, ) -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_pods +from pylabrobot.lib.liquid_handling.mix import Mix +from pylabrobot.resources.coordinate import Coordinate SECTION = {"c__mix": False, "c__tiptouch": False, "c__blowout": False, "c__trailingairgap": False} GENERAL = { From 288f811019b144a05f9f874d0a79a62b32d34de3 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:51:25 -0500 Subject: [PATCH 24/28] `Visualizer3D`: a boundary is an outline with no fill --- pylabrobot/visualizer3D/README.md | 3 ++- pylabrobot/visualizer3D/static/appearance.js | 11 +++++++++-- pylabrobot/visualizer3D/static/boxes.js | 3 ++- pylabrobot/visualizer3D/static/constants.js | 6 ++++++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/pylabrobot/visualizer3D/README.md b/pylabrobot/visualizer3D/README.md index 846f29b4d49..a01ca297284 100644 --- a/pylabrobot/visualizer3D/README.md +++ b/pylabrobot/visualizer3D/README.md @@ -359,6 +359,7 @@ The sets in `constants.js`, and `GROUND` in `drawn.js`: | set | categories | where it matters | |---|---|---| | `MOVING_PARTS` | `x_arm`, `arm`, `gripper`, `head`, `channel` | drawn as an open frame with a reference line in a group of its own (`marks.js`); no box fill or generic outline (`boxes.js`); `MOVING_OPACITY`, and the carried layer in a plan (`appearance.js`); `tracker.x` and `locations` glide it (`live.js`); takes a click on its rim (`tools.js`); everything under it travels (`drawn.js`) | +| `BOUNDARIES` | `boundary` | a collision box with no shape of its own: outline only, no fill, in both views (`boxes.js`, `appearance.js`); the tree's dot is the outline's grey | | `PICKABLE_PARTS` | `pipette_channel` | a click selects it although it has children | | `NO_REFERENCE_MARK` | `pipette_channel` | its `reference_point` gets no mark | | `TREE_HIDDEN` | `well`, `tip_spot`, `tube` | no tree row; the parent's row counts them | @@ -367,7 +368,7 @@ The sets in `constants.js`, and `GROUND` in `drawn.js`: | `SEARCH_CONTAINERS` | `well`, `tube`, `trough`, `container`, `petri_dish` | the search "Wells" filter | | `CONTAINERS` | `plate`, `tip_rack`, `tube_rack`, `plate_adapter`, `plate_holder`, `resource_holder`, `trough`, `trash` | keep their walls at `SHELL_OPACITY` while their contents are drawn | | `CATEGORY_OPACITY` | `tip_rack` 0.7, `plate` 0.25 | the box's own opacity | -| `RESOURCE_COLORS` | 31 categories and `default` | the box colour and the tree's dot | +| `RESOURCE_COLORS` | 32 categories and `default` | the box colour and the tree's dot | | `GROUND` | `facility`, `deck` | `SPACE_OPACITY`, out of the depth buffer | Categories named directly in the code: diff --git a/pylabrobot/visualizer3D/static/appearance.js b/pylabrobot/visualizer3D/static/appearance.js index dd1f2d6256b..9ca55ad9126 100644 --- a/pylabrobot/visualizer3D/static/appearance.js +++ b/pylabrobot/visualizer3D/static/appearance.js @@ -8,6 +8,7 @@ import { ARM_EDGE_WIDTH_3D, ARM_EDGE_WIDTH_FLAT, ARM_REFERENCE_OPACITY, + BOUNDARIES, BOX_OPACITY, CATEGORY_OPACITY, CONTAINERS, @@ -72,8 +73,14 @@ let renderModeDirty = false; // box that stood in for it. Every mode change asks this rather than each one deciding again. function fillsBox(entry) { // A vessel's box is drawn by its own cavity mesh, which fills it exactly. Drawing the box as well - // puts two surfaces on the same plane, and the depth buffer cannot choose between them. - return !MOVING_PARTS.has(entry.model.category) && !entry.modelDrawn && !entry.isVessel; + // puts two surfaces on the same plane, and the depth buffer cannot choose between them. A + // boundary is a collision box: its outline says where it is, and a fill would hide the deck. + return ( + !MOVING_PARTS.has(entry.model.category) && + !BOUNDARIES.has(entry.model.category) && + !entry.modelDrawn && + !entry.isVessel + ); } // Whether this is a thing you look into. Its walls stay drawn, at the shell's opacity, however much diff --git a/pylabrobot/visualizer3D/static/boxes.js b/pylabrobot/visualizer3D/static/boxes.js index e9d94a3f08a..df7ae8957c1 100644 --- a/pylabrobot/visualizer3D/static/boxes.js +++ b/pylabrobot/visualizer3D/static/boxes.js @@ -6,6 +6,7 @@ import { LineSegments2 } from "three/addons/lines/LineSegments2.js"; import { LineSegmentsGeometry } from "three/addons/lines/LineSegmentsGeometry.js"; import { + BOUNDARIES, EDGE_WIDTH_3D, FILTER, FILTER_BELOW_COLLAR, @@ -148,7 +149,7 @@ function makeDrawing(model, count, encloses, edgeDepth) { if (vessel) material.color.setHex(VESSEL_RIM); material.userData.lit = material; - if (MOVING_PARTS.has(model.category)) material.visible = false; + if (MOVING_PARTS.has(model.category) || BOUNDARIES.has(model.category)) material.visible = false; // Culled by the sphere three works out over the instances, as every instanced mesh, overlay // and outline here is: what is off screen is not submitted. A move or a hide drops the sphere. diff --git a/pylabrobot/visualizer3D/static/constants.js b/pylabrobot/visualizer3D/static/constants.js index 81ae39a3c4b..eea65f2b6f3 100644 --- a/pylabrobot/visualizer3D/static/constants.js +++ b/pylabrobot/visualizer3D/static/constants.js @@ -45,6 +45,8 @@ export const RESOURCE_COLORS = { body: 0xb8471f, finger: 0xff2d55, pad: 0xff7a90, + // A collision box with no shape of its own: the tree's dot matches the outline that carries it. + boundary: 0x49555e, default: 0xbdb163, }; @@ -54,6 +56,10 @@ export const RESOURCE_COLORS = { // part, and this list is a stand-in until that exists. export const MOVING_PARTS = new Set(["x_arm", "arm", "gripper", "head", "channel"]); +// A collision box with no shape of its own. The fill would hide the deck, so only the outline is +// drawn, in both the free view and the top view. +export const BOUNDARIES = new Set(["boundary"]); + // Parts whose reference point says nothing the picture does not already. A single pipetting channel // is measured from its own axis, which is where it visibly is, and eight of them side by side turn // one useful line into a thicket over the deck. A head is a different case and keeps its mark: it From 9ec0493eb7819f6422e46c97c68d086d27d12e29 Mon Sep 17 00:00:00 2001 From: cmoscy <46687103+cmoscy@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:04:05 -0800 Subject: [PATCH 25/28] `Biomek i7`: deck collision and Biomek's planner Every move a pod makes is checked against the deck before it is sent, and every planned call is planned whole, as Biomek's planner plans it (driver/planning/): - The pod model: each tool a few boxes (the 96-head; a Span-8's probes; the gripper's hands, fingers and what it holds), widened by AvoidanceMargin on every side, the pipettor's lower parts AdditionalSafeHeight lower. - The obstacles: per pod, one box per deck position up to its safe height, the positions' own obstacles and the instrument's structure, from the instrument file; built once per deck change. - One check: each part swept from start to end (a turn between quarter turns bounded by the box over its corners' arcs) against the deck, the operation's own position left out, and the pod's gripper against its pipettor. - The planner: out of any position the pod stands in, each part straight up; the safe heights (the tallest thing under each tool's footprint swept, plus margins); the direct way, or else Biomek's search; the stages merged as one path; the whole call planned before anything moves. It plans with a larger model than the check (the gripper padded by AdditionalSafeHeightGripper, the other pod as a wall at the end of its travel), so its plans pass the check. - The other pod: moved aside just far enough before a move that needs its room, when it is idle. Compared with the controller's logs: of 3,540 planned operations replayed from their logged start, none is refused; of 31,657 logged moves checked, 48 are refused, 36 of them by 0.02 cm or less (the right pod's calibration of a position) and the rest the lid turns at the light curtain with the lid at its real size. Every setting the planner reads is required in the pod's entry of the instrument file. --- .../biomek_files/files_tests_support.py | 1 + .../biomek_i7/biomek_files/instrument_file.py | 1 + pylabrobot/beckman_coulter/biomek_i7/deck.py | 15 +- .../biomek_i7_generic_configuration.json | 119 +- .../beckman_coulter/biomek_i7/design.md | 42 +- .../beckman_coulter/biomek_i7/device.py | 179 ++- .../biomek_i7/device_model_tests.py | 5 +- .../beckman_coulter/biomek_i7/device_tests.py | 40 + .../biomek_i7/driver/configuration.py | 15 +- .../biomek_i7/driver/features/gripper.py | 123 +- .../biomek_i7/driver/features/head96.py | 87 +- .../biomek_i7/driver/features/pipettes.py | 131 +- .../biomek_i7/driver/features/pod.py | 1076 +++++++++++++---- .../biomek_i7/driver/gripper_tests.py | 22 +- .../biomek_i7/driver/liquid_tests.py | 27 + .../biomek_i7/driver/master.py | 8 + .../biomek_i7/driver/motors_tests.py | 17 +- .../biomek_i7/driver/pipettes_tip_tests.py | 6 +- .../biomek_i7/driver/planner_tests.py | 81 ++ .../biomek_i7/driver/planning/__init__.py | 3 + .../biomek_i7/driver/planning/check.py | 437 +++++++ .../biomek_i7/driver/planning/check_tests.py | 138 +++ .../biomek_i7/driver/planning/destinations.py | 68 ++ .../biomek_i7/driver/planning/find_path.py | 73 ++ .../biomek_i7/driver/planning/merge.py | 213 ++++ .../biomek_i7/driver/planning/obstacles.py | 85 ++ .../driver/planning/obstacles_tests.py | 30 + .../biomek_i7/driver/planning/pod_model.py | 435 +++++++ .../biomek_i7/driver/planning/search.py | 444 +++++++ .../biomek_i7/driver/planning/traverse.py | 243 ++++ .../biomek_i7/driver/pod_collision.py | 279 ----- .../biomek_i7/driver/pod_collision_tests.py | 71 +- .../biomek_i7/driver/pod_geometry.py | 46 +- .../biomek_i7/driver/pod_planning_tests.py | 279 +++++ .../biomek_i7/driver/traverse_tests.py | 173 ++- .../biomek_i7/driver/x_rail.py | 29 +- .../biomek_i7/driver/x_rail_tests.py | 98 +- .../biomek_i7/resource_model/alps.py | 101 +- .../biomek_i7/resource_model/structure.py | 147 +++ .../biomek_i7/simulation_tests.py | 10 +- .../beckman_coulter/biomek_i7/targeting.py | 5 +- 41 files changed, 4506 insertions(+), 896 deletions(-) create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planner_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/__init__.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/check.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/check_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/destinations.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/find_path.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/merge.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/pod_model.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/search.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/planning/traverse.py delete mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py create mode 100644 pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py index 37eb214676d..c072754ed0e 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/files_tests_support.py @@ -159,6 +159,7 @@ def instrument_file_tree(configuration: DeviceConfiguration, deck: str = "Deck1" "XSpan": p["x_span"], "YSpan": p["y_span"], **{f"Framed{n}": how for n, how in p["framed"].items()}, + **({"MinSafeHeight": p["min_safe_height"]} if "min_safe_height" in p else {}), } for name, p in data["deck_positions"].items() } diff --git a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py index dc11ff06384..1bae188335e 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py +++ b/pylabrobot/beckman_coulter/biomek_i7/biomek_files/instrument_file.py @@ -180,6 +180,7 @@ def _positions(tree: Tree) -> Dict[str, Dict[str, Any]]: "x_span": e["XSpan"], "y_span": e["YSpan"], "framed": {str(n): e[f"Framed{n}"] for n in (1, 2) if f"Framed{n}" in e}, + **({"min_safe_height": e["MinSafeHeight"]} if "MinSafeHeight" in e else {}), } return dict(sorted(positions.items())) diff --git a/pylabrobot/beckman_coulter/biomek_i7/deck.py b/pylabrobot/beckman_coulter/biomek_i7/deck.py index 062bcce39ba..bb051021aa0 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/deck.py +++ b/pylabrobot/beckman_coulter/biomek_i7/deck.py @@ -11,7 +11,11 @@ import logging from typing import TYPE_CHECKING, Any, Dict, List -from pylabrobot.beckman_coulter.biomek_i7.resource_model.alps import ALP_TYPES, BiomekALP +from pylabrobot.beckman_coulter.biomek_i7.resource_model.alps import ( + ALP_TYPES, + BiomekALP, + BiomekPosition, +) from pylabrobot.beckman_coulter.biomek_i7.resource_model.units import cm # The frame's conversions live in `units.py`; re-exported here, where they were first. @@ -123,6 +127,15 @@ def from_configuration( ) column += steps deck.assign_alp(alp, column=column, row=placed.row) + # The instrument file's per-position `MinSafeHeight`, where it gives one, over the ALP type's. + for site in alp.children: + given = configuration.deck_positions.get(site.name) + if ( + isinstance(site, BiomekPosition) + and given is not None + and given.min_safe_height is not None + ): + site.min_safe_height = cm(given.min_safe_height) return deck def get_position(self, name: str) -> ResourceHolder: diff --git a/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json index e33fd37ffb0..1189d109376 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json +++ b/pylabrobot/beckman_coulter/biomek_i7/defaults/biomek_i7_generic_configuration.json @@ -4,7 +4,7 @@ "instrument_serial_number": null, "sources": { "instrument_file": { - "fingerprint": "sha256:9cbfcd7168db1a0a0e9f6436c4d1479bc1664e1c39c7e4c125f5694b96dee046" + "fingerprint": "sha256:a35f93cee89af8d302280bf0ffdd0c080d330041eff8bcd43775726d43d6081d" }, "master_controller": { "fingerprint": "sha256:f4aceddd504ac0579c6fee9dad49a9ec4a637f2bd538ae4cd9a8191445a0af07" @@ -956,7 +956,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 2.1 }, "CP1": { "corners": { @@ -976,7 +977,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 2.0 }, "P1": { "corners": { @@ -996,7 +998,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P10": { "corners": { @@ -1016,7 +1019,8 @@ "framed": { "1": "Deck", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P11": { "corners": { @@ -1036,7 +1040,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P12": { "corners": { @@ -1056,7 +1061,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 0.0 }, "P13": { "corners": { @@ -1076,7 +1082,8 @@ "framed": { "1": "Deck", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P14": { "corners": { @@ -1096,7 +1103,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P15": { "corners": { @@ -1116,7 +1124,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P16": { "corners": { @@ -1136,7 +1145,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P17": { "corners": { @@ -1156,7 +1166,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P18": { "corners": { @@ -1176,7 +1187,8 @@ "framed": { "1": "Deck", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P19": { "corners": { @@ -1196,7 +1208,8 @@ "framed": { "1": "Deck", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P2": { "corners": { @@ -1216,7 +1229,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P20": { "corners": { @@ -1236,7 +1250,8 @@ "framed": { "1": "Deck", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P21": { "corners": { @@ -1256,7 +1271,8 @@ "framed": { "1": "Deck", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P22": { "corners": { @@ -1276,7 +1292,8 @@ "framed": { "1": "Deck", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P23": { "corners": { @@ -1296,7 +1313,8 @@ "framed": { "1": "Deck", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P24": { "corners": { @@ -1316,7 +1334,8 @@ "framed": { "1": "Deck", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P3": { "corners": { @@ -1336,7 +1355,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P4": { "corners": { @@ -1356,7 +1376,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P5": { "corners": { @@ -1376,7 +1397,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P6": { "corners": { @@ -1396,7 +1418,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P7": { "corners": { @@ -1416,7 +1439,8 @@ "framed": { "1": "Deck", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "P8": { "corners": { @@ -1436,7 +1460,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 1.0 }, "P9": { "corners": { @@ -1456,7 +1481,8 @@ "framed": { "1": "Position", "2": "Position" - } + }, + "min_safe_height": 0.0 }, "TA1": { "corners": { @@ -1476,7 +1502,8 @@ "framed": { "1": "Not", "2": "Position" - } + }, + "min_safe_height": 5.0 }, "TL1": { "corners": { @@ -1496,7 +1523,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TL10": { "corners": { @@ -1516,7 +1544,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TL11": { "corners": { @@ -1536,7 +1565,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TL2": { "corners": { @@ -1556,7 +1586,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TL3": { "corners": { @@ -1576,7 +1607,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TL4": { "corners": { @@ -1596,7 +1628,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TL5": { "corners": { @@ -1616,7 +1649,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TL6": { "corners": { @@ -1636,7 +1670,8 @@ "framed": { "1": "Position", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "TR1": { "corners": { @@ -1656,7 +1691,8 @@ "framed": { "1": "Deck", "2": "Deck" - } + }, + "min_safe_height": 0.1 }, "TR2": { "corners": { @@ -1676,7 +1712,8 @@ "framed": { "1": "Deck", "2": "Deck" - } + }, + "min_safe_height": 0.1 }, "W2": { "corners": { @@ -1696,7 +1733,8 @@ "framed": { "1": "Deck", "2": "Deck" - } + }, + "min_safe_height": 1.0 }, "W3": { "corners": { @@ -1716,7 +1754,8 @@ "framed": { "1": "Deck", "2": "Deck" - } + }, + "min_safe_height": 2.0 } }, "deck_layout": [ diff --git a/pylabrobot/beckman_coulter/biomek_i7/design.md b/pylabrobot/beckman_coulter/biomek_i7/design.md index e219c7fe1f1..433891bfd22 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/design.md +++ b/pylabrobot/beckman_coulter/biomek_i7/design.md @@ -17,7 +17,7 @@ single-axis commands over USB. This driver replaces the top two and talks to the | L1 wire | the ACE messages | `driver/framing.py`, `board.py`, `protocol.py` | | L2 board commands | one board request each | `_unchecked_fw_*` on the pods and chassis | | L3 MC | one MC host command each | the pods' public primitives, `driver/recipes/` | -| L4 planning | Biomek's planning | `driver/motion.py`, `pod_geometry.py`, `liquid.py` (no I/O) | +| L4 planning | Biomek's planning | `driver/planning/`, `motion.py`, `pod_geometry.py`, `liquid.py` (no I/O) | | L5 PyLabRobot | the PLR API | `device.py`, the operation features, `resource_model/` | Each layer calls only the one below it. @@ -45,7 +45,8 @@ instrument. Each source's values are fingerprinted: a file changed after import on the instrument, discovery refuses one whose serial numbers are not the modules', and one whose sources have changed since. There is no switch to skip a check; the fix is to import again. A simulation with no files uses the package's generic instrument (`defaults/`), which a live session -refuses. +refuses. Every setting the driver reads is required in the pod's entry: a pod whose entry lacks one +is refused (`required_settings`), never given a default. ## The pods @@ -68,9 +69,11 @@ the MC's recipe (`driver/recipes/homing.py`), its targets from the motor record. **I7. Pod against pod is the driver's job.** Nothing below the driver stops the pods colliding. Before a pod moves, its swept X range (bridge, pipettor and gripper as posed, with what it holds) must clear the other pod's range and any move it has in flight, or the move is refused before -anything is sent (`driver/x_rail.py`, Biomek's own rule). The driver does not move the other pod out -of the way; a caller makes room (`Pod.move_aside`, `Pod.park`). The guard uses the configuration -only, so it holds without a deck. +anything is sent (`driver/x_rail.py`, Biomek's own rule, on its 1/16 cm grid). Before that check, as +Biomek clears the way, an idle other pod moves aside just far enough: its near edge to the next +grid line past the zone the move needs, plus 1/64 cm, its gripper turned to a quarter turn. A busy +one is not moved, and the move is refused. The guard uses the configuration only, so it holds +without a deck. ## The deck and the device @@ -93,10 +96,29 @@ state is the tip (`serialize_state`). The device saves the tree's state (`state_ head's tips change, restores it when built, and carries it over to the models it rebuilds at setup: the 96-head cannot sense tips, so that is how they are known across sessions. -**I12. Travel is a traverse height, not a path planner.** Before X/Y travel the channels and the -gripper rise to a traverse height (by default near the top of travel; per call, as STAR's -`minimum_traverse_height_*`). A height below what the deck model and Biomek's per-pod obstacles need -is refused, not routed. +**I12. Motion is planned and checked as Biomek's planner does** (`driver/planning/`): + +- *Parts.* Each tool is a few boxes, each widened by `AvoidanceMargin`: the 96-head (flange and + up, head, tips' block), a Span-8 probe (a lower box, an open-topped upper part), the gripper + (upper hand; lower hand, fingers and what it holds, which turn with GR). The pipettor's lower + parts reach `AdditionalSafeHeight` lower. The world is boxes too: the deck's positions, their own + obstacles, the instrument's structure. +- *One check, before every move* (`check.py`): each part swept from start to end (a hull; a turn + from one quarter turn to another, the box over each corner's arc; any other turn, sampled), + against the deck (the operation's own position left out) and the pod's other tool, and the rail + (I7). Not clear: refused, nothing sent. +- *One planner per planned call* (`features/pod.py`, `find_path.py`): out of any position the pod + stands in, straight up, part by part; the safe heights (the tallest thing under each tool's + footprint, plus margins); the direct way, or else Biomek's search (one axis of one part at a + time, to the next contact); merged as Biomek merges (`merge.py`). The whole call is planned + before anything moves: with no path, nothing moves. +- *Two models.* The planner plans with more than the check checks (the gripper padded by + `AdditionalSafeHeightGripper`, the other pod as a wall at the end of its travel), so its plans + pass the check; the check stands alone for every other move. + +A call may give its traverse height (STAR's `minimum_traverse_height_*`); the travel at it is +planned like any other: straight when clear, else searched around what it would meet at that +height, else refused. ## Operation features @@ -121,7 +143,7 @@ shuck. It has no tip sensor, so `setup` ejects over its trash even with no tips `direction`: travel turned, open, down, a force-limited close that stops on the labware, lift clear, carry, place. The grip point is the resource's `preferred_pickup_location`; the widths default to Biomek's margins around the labware's width; a close that reaches its target met nothing and is -refused. A pod's own gripper and pipettor are kept apart (`driver/pod_collision.py`). +refused. A pod's own gripper and pipettor are kept apart (`driver/planning/check.py`). **I15. Biomek's techniques are a translation, not a mode.** `techniques.py` turns a Biomek technique and liquid type into the features' keyword arguments, which a caller splats and overrides. There is diff --git a/pylabrobot/beckman_coulter/biomek_i7/device.py b/pylabrobot/beckman_coulter/biomek_i7/device.py index 1085bb0d3d5..3c45f23a073 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device.py @@ -16,13 +16,11 @@ import os from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple -from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7 import targeting, units from pylabrobot.beckman_coulter.biomek_i7.deck import ( FRAME_X, FRAME_Y, BiomekI7Deck, - biomek_x, - biomek_y, deck_x, deck_y, ) @@ -52,7 +50,14 @@ simulated_boards, ) from pylabrobot.beckman_coulter.biomek_i7.resource_model import cm, pod_model +from pylabrobot.beckman_coulter.biomek_i7.resource_model.alps import BiomekPosition from pylabrobot.beckman_coulter.biomek_i7.resource_model.heads import PROBES +from pylabrobot.beckman_coulter.biomek_i7.resource_model.structure import ( + BiomekObstacle, + FrameToDevice, + merge_obstacles, + structure_resources, +) from pylabrobot.beckman_coulter.biomek_i7.resource_model.pods import ( GripperModel, gripper_model, @@ -62,8 +67,11 @@ ) from pylabrobot.resources.beckman_coulter.tips import beckman_coulter_biomek_tip_1070uL from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.utils.linalg import matrix_vector_multiply_3x3 from pylabrobot.resources.resource import Resource from pylabrobot.resources.rotation import Rotation +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.pod_model import OPEN, Part +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.obstacles import Obstacles, obstacle_part logger = logging.getLogger(__name__) @@ -92,6 +100,17 @@ DECK_X = BASE_LEFT_OF_X0 - FRAME_X DECK_Y = BASE_Y_SPAN - BASE_BEHIND_Y0 - FRAME_Y +# What the instrument's structure is drawn within, Biomek's frame (cm): its base, from just below +# the deck surface to above the pods' tops (`structure_resources`). +STRUCTURE_EXTENT = ( + -BASE_LEFT_OF_X0 / 10, + (BASE_X_SPAN - BASE_LEFT_OF_X0) / 10, + -BASE_BEHIND_Y0 / 10, + (BASE_Y_SPAN - BASE_BEHIND_Y0) / 10, + -2.0, + 60.0, +) + class BiomekI7Device(Resource): """A Biomek i7: its frame, a deck, and a bridge per pod, driven through `driver` (STAR's @@ -136,12 +155,21 @@ def __init__( category="device", model="beckman_coulter_biomek_i7", ) + # Each pod's obstacles (`obstacles`), by pod number, until the tree changes. + self._obstacles: Dict[int, Obstacles] = {} if deck is None: # The default deck the declared configuration lays out, else an empty one. deck = BiomekI7Deck.from_configuration(driver.declared) self.deck = deck driver.deck = self.deck # the operations work on this deck (STAR's `driver.deck`) self.assign_child_resource(self.deck, location=Coordinate(DECK_X, DECK_Y, DECK_Z)) + # The instrument's structure around the deck, from the declared configuration's obstacles. + self.structure: List[BiomekObstacle] = [] + to_device = FrameToDevice(Coordinate(DECK_X, DECK_Y, DECK_Z), FRAME_X, FRAME_Y) + obstacles = merge_obstacles(p.obstacles for p in driver.declared.pods.values()) + for part, location in structure_resources(obstacles, STRUCTURE_EXTENT, to_device): + self.assign_child_resource(part, location=location) + self.structure.append(part) self.bridges: Dict[str, Resource] = {} self.pod_models: Dict[str, Resource] = {} @@ -153,6 +181,11 @@ def __init__( if state_json is not None and os.path.exists(state_json): self.load_state_from_file(state_json) # the tips on the declared heads' shafts driver.on_tips_changed = self._tips_changed + driver.obstacles = self.obstacles + # Any resource assigned or unassigned under the device (labware, lids, tips, what a gripper + # holds; the callbacks reach up the tree) changes what the pods must clear. + self.register_did_assign_resource_callback(self.invalidate_obstacles) + self.register_did_unassign_resource_callback(self.invalidate_obstacles) if driver.arms: self._follow_driver() # given a driver already set up @@ -302,7 +335,7 @@ async def park(self, skip: Iterable[str] = ()) -> None: async def pause(self) -> None: """Pause for access, as Biomek's Pause step: the pods' drive power is cut and PAUSED shown, so the light curtain may be broken. Move the pods out of the way first if needed - (`move_aside`, `park`). See `BiomekI7Driver.pause`.""" + (`park`, or a move of the pod). See `BiomekI7Driver.pause`.""" await self.driver.pause() async def resume(self, speed: int = 200) -> None: @@ -377,7 +410,9 @@ def _give_heads(self, pod: Pod) -> None: pod.pipettes._adopt_tips() def _tips_changed(self) -> None: - """A head's tips changed: save the tree's state, when there is a `state_json`.""" + """A head's tips changed: the obstacles built are dropped, and the tree's state saved when + there is a `state_json`.""" + self.invalidate_obstacles() if self.state_json is not None: self.save_state_to_file(self.state_json, indent=1) @@ -550,39 +585,82 @@ def _show_pod(self, pod: Pod) -> None: if probe == 1: self.update_pod_location(pod.side, deck_y(cm(y - geo.mandrel1_y_offset + geo.pod_y_span))) - def traverse_clearance( - self, side: str, x: Tuple[float, float], y: Tuple[float, float], tip_length: float = 0.0 - ) -> float: - """The lowest height, mm above the deck, a pod's channels may travel at over the area `x` by - `y` (deck x and y ranges, mm), for `Pod.move_over`'s `clearance`: the top of the tallest - resource there, plus the pod's `AdditionalSafeHeight`, plus `tip_length` (mm the tips reach - below the channels' bottom). Its Biomek-unit counterpart is `_traverse_clearance`.""" - bx = sorted(units.to_cm(units.biomek_x(v)) for v in x) - by = sorted(units.to_cm(units.biomek_y(v)) for v in y) - clearance = self._traverse_clearance( - side, (bx[0], bx[1]), (by[0], by[1]), units.to_cm(tip_length) + def obstacles(self, pod_number: int) -> Obstacles: + """What pod `pod_number`'s moves must clear, in Biomek's frame (cm), from this resource tree + alone, as Biomek builds it: + + - the instrument's structure as Biomek bounds it (`structure`), each widened by its buffer; + - one box per deck position (`BiomekPosition`): its footprint, where this pod's calibration puts + it, from its ALP's base up to the higher of its `min_safe_height` and the top of what stands + on it (lids and standing tips included); + - each position's own obstacles (a trash's walls), from below the deck up. + + What a gripper holds is not on the deck, so it is not here. Built once per pod and kept until + the tree changes (a resource assigned or unassigned anywhere under the device, tips included); + a resource moved by setting its `location` changes nothing the device hears of: call + `invalidate_obstacles` after such a change. + + Raises: + ValueError: for a position turned other than by a multiple of 90 degrees. + """ + found = self._obstacles.get(pod_number) + if found is None: + found = self._obstacles[pod_number] = self._build_obstacles(pod_number) + return found + + def invalidate_obstacles(self, *_: Any) -> None: + """Forget the obstacles built for each pod: the next `obstacles` builds them again.""" + self._obstacles.clear() + + def _build_obstacles(self, pod_number: int) -> Obstacles: + """`obstacles`, built from the tree.""" + structure = tuple( + obstacle_part(o.name, (o.x1, o.x2), (o.y1, o.y2), (o.z1, o.z2), o.buffer) + for o in (part.obstacle() for part in self.structure) ) - return units.to_mm(clearance) - - def _traverse_clearance( - self, side: str, x: Tuple[float, float], y: Tuple[float, float], tip_length: float = 0.0 - ) -> float: - """The lowest height (Biomek Z, cm) a pod's channels may travel at over the area `x` by `y` - (Biomek X/Y, cm), for `Pod._move_over`'s `clearance`: the top of the tallest resource on the - deck there, plus the pod's `AdditionalSafeHeight`, plus `tip_length` (cm the tips reach below - the channels' bottom). Biomek's Z is the deck model's z in cm (design.md I9). The deck itself, - its ALPs' frames included, counts; the pods' own models do not.""" - pod = self.driver.arm(side) - if pod.declared is None: - raise RuntimeError(f"{pod} has no declared configuration") - top = 0.0 - for resource in self.deck.get_all_children(): - loc = resource.get_location_wrt(self.deck) - left, right = biomek_x(loc.x) / 10, biomek_x(loc.x + resource.get_size_x()) / 10 - back, front = biomek_y(loc.y + resource.get_size_y()) / 10, biomek_y(loc.y) / 10 - if left < x[1] and x[0] < right and back < y[1] and y[0] < front: - top = max(top, (loc.z + resource.get_size_z()) / 10) - return top + pod.declared.geometry.additional_safe_height + tip_length + deck_origin = self.deck.get_absolute_location() + deck: List[Part] = [] + positions = [ + h for alp in self.deck.children for h in alp.children if isinstance(h, BiomekPosition) + ] + for position in positions: + rotation = position.get_absolute_rotation() + turn = rotation.z % 90 + if min(turn, 90 - turn) > 1e-6: + raise ValueError(f"{position.name} is turned {rotation.z} degrees") + frame = (position.get_absolute_location() - deck_origin, rotation.get_rotation_matrix()) + # Where this pod's own calibration puts the position: the frame its parts are modelled in. + shift = targeting.position_correction( + self.deck, self.driver.declared, position, pod_number, frame[0] + ) + floor = frame[0].z + base = floor - (position.location.z if position.location is not None else 0.0) # its ALP's + top = max( + [floor + position.min_safe_height] + + [c.get_highest_known_point() - deck_origin.z for c in position.children] + ) + deck.append( + _world_box( + position.name, + frame, + (0, position.get_size_x()), + (0, position.get_size_y()), + (base, top), + shift, + ) + ) + for o in position.obstacles: + deck.append( + _world_box( + f"{position.name} {o.name}", + frame, + (o.x0, o.x1), + (o.y0, o.y1), + (-OPEN * 10, floor + o.top), + shift, + ) + ) + return Obstacles(structure, tuple(deck), tuple(p.name for p in positions)) def update_bridge_location(self, side: str, x: float) -> None: """Put a side's bridge's left edge at deck x `x` mm, carrying its pod along the rails.""" @@ -688,3 +766,30 @@ def BiomekI7( elif driver is None: driver = BiomekI7Driver(declared_configuration_json=declared_configuration_json) return BiomekI7Device(driver=driver, deck=deck, name=name, state_json=state_json) + + +def _world_box( + name: str, + frame: Tuple[Coordinate, List[List[float]]], + x: Tuple[float, float], + y: Tuple[float, float], + z: Tuple[float, float], + shift: Tuple[float, float, float], +) -> Part: + """The box `x` by `y` (mm along a frame's axes, from its origin; `frame`: that origin on the deck + and its rotation matrix), `z` (mm from the deck), in Biomek's frame (cm), moved by `shift` + (cm).""" + origin, matrix = frame + xs, ys = [], [] + for px in x: + for py in y: + d = matrix_vector_multiply_3x3(matrix, (px, py, 0.0)) + xs.append(units.biomek_x(origin.x + d[0]) / 10) + ys.append(units.biomek_y(origin.y + d[1]) / 10) + dx, dy, dz = shift + return obstacle_part( + name, + (min(xs) + dx, max(xs) + dx), + (min(ys) + dy, max(ys) + dy), + (z[0] / 10 + dz, z[1] / 10 + dz), + ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py index aeae11510f7..4c0d4d34077 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device_model_tests.py @@ -79,8 +79,9 @@ async def test_the_multichannel_follows_y_and_z_at_mandrel_a1(self) -> None: assert d is not None # Homed, GR is at -16 degrees: the fingers under the head. Turn them out first, as the park does. await left.move_axes({"GR": d.to_counts("GR", d.park["GR"])}) - await left.move_axes({"Y": 50000, "Z": -60000}) - y, z = d.to_value("Y", 50000), d.to_value("Z", -60000) + # Above the trash walls at TR1 under it (the deck check refuses lower). + await left.move_axes({"Y": 50000, "Z": -20000}) + y, z = d.to_value("Y", 50000), d.to_value("Z", -20000) pod = lh.pod_models["left"] back = pod.get_location_wrt(lh).y - DECK_Y + pod.get_size_y() # deck y grows to the back self.assertAlmostEqual(biomek_y(back) / MM_PER_CM, y - d.geometry.mandrel1_y_offset, delta=1e-4) diff --git a/pylabrobot/beckman_coulter/biomek_i7/device_tests.py b/pylabrobot/beckman_coulter/biomek_i7/device_tests.py index bb0d40c83a2..1269b27dbaa 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/device_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/device_tests.py @@ -7,9 +7,11 @@ from typing import Dict from unittest import mock +from pylabrobot.beckman_coulter.biomek_i7 import targeting from pylabrobot.beckman_coulter.biomek_i7.device import DECK_Z, RAIL_TOP_Z, BiomekI7 from pylabrobot.beckman_coulter.biomek_i7.driver.simulator import RECORDING_ENV from pylabrobot.beckman_coulter.biomek_i7.resource_model import alps +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_labware from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( as_instrument, configuration_file, @@ -82,6 +84,44 @@ def test_the_deck_is_inside_the_frame(self): self.assertLessEqual(loc.y + alp.get_size_y(), self.biomek.get_size_y()) self.assertAlmostEqual(loc.z, DECK_Z) + def test_the_obstacles_follow_every_change_of_the_tree(self): + # Each pod's obstacles are built once and dropped when anything under the device is assigned + # or unassigned: after each change they equal a fresh build. + device = self.biomek + deck = device.deck + position = deck.get_position(deck.position_names[0]) + + def check() -> None: + for pod in (1, 2): + self.assertEqual(device.obstacles(pod), device._build_obstacles(pod)) + + check() + rack = biomek_labware("BC230", "rack") + position.assign_child_resource(rack) + check() + rack.get_item(0).unassign_tip() # a tip taken: a child of its spot + check() + rack.unassign() + check() + + def test_each_pods_boxes_are_on_its_own_calibration(self): + # A position's box for pod n is where pod n's calibration puts the position: the boxes of the + # two pods differ by the difference of their corrections (Biomek's cache takes pod 1's for both). + device = self.biomek + boxes = {pod: {p.name: p for p in device.obstacles(pod).deck} for pod in (1, 2)} + for name in device.deck.position_names: + position = device.deck.get_position(name) + c1, c2 = ( + targeting.position_correction(device.deck, device.driver.declared, position, pod) + for pod in (1, 2) + ) + (x1, _, y1, _), (x2, _, y2, _) = (boxes[pod][name].extent for pod in (1, 2)) + self.assertAlmostEqual(x2 - x1, c2[0] - c1[0], places=9, msg=name) + self.assertAlmostEqual(y2 - y1, c2[1] - c1[1], places=9, msg=name) + self.assertAlmostEqual( + boxes[2][name].z_high - boxes[1][name].z_high, c2[2] - c1[2], places=9, msg=name + ) + def test_moving_a_bridge_carries_its_pod(self): before = self.biomek.pod_models["left"].get_location_wrt(self.biomek) self.biomek.update_bridge_location("left", 600.0) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py index 6ae6b93d6a5..acda104d4ba 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/configuration.py @@ -173,7 +173,12 @@ class Obstacle: # The settings the driver takes from a pod's entry in the instrument file, never assumed: a pod # whose entry lacks one is refused (`PodConfiguration`). Every pod's; a gripper's; each pod type's. -POD_SETTINGS: Tuple[str, ...] = () +POD_SETTINGS: Tuple[str, ...] = ( + "AStarSearchLimit", + "RotationPenalty", + "GlobalMinSafeHeight", + "AlwaysMaxZ", +) GRIPPER_SETTINGS: Tuple[str, ...] = ( "SensorEnabled", "GripperSqueezeForce", @@ -181,6 +186,8 @@ class Obstacle: TYPE_SETTINGS: Dict[str, Tuple[str, ...]] = { "span8": ( "ProbeSize", + "MandrelExtender", + "LLSWireModel", "DefaultTipHubInfo", "LoadingOffsets", "DetectTips", @@ -190,6 +197,7 @@ class Obstacle: "TipLoadZOffset", "MaxLoadingProbes", "MinLoadingInterval", + "DiscardOffset", "DiscardHeight", "DiscardSpeed", "DiscardOvershoot", @@ -316,6 +324,9 @@ class DeckPosition: x_span: float y_span: float framed: Dict[int, str] = field(default_factory=dict) + # The least height (cm above its floor) the pods' parts stay over it (`MinSafeHeight`), where the + # instrument file gives one; None in a configuration imported before it was read. + min_safe_height: Optional[float] = None def corner(self, pod_number: int) -> Tuple[float, float, float]: """Raises: @@ -558,6 +569,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "DeviceConfiguration": x_span=p["x_span"], y_span=p["y_span"], framed={int(n): v for n, v in p.get("framed", {}).items()}, + min_safe_height=p.get("min_safe_height"), ) for name, p in data.get("deck_positions", {}).items() } @@ -610,6 +622,7 @@ def to_dict(self) -> Dict[str, Any]: "x_span": p.x_span, "y_span": p.y_span, "framed": {str(n): v for n, v in p.framed.items()}, + **({} if p.min_safe_height is None else {"min_safe_height": p.min_safe_height}), } for name, p in self.deck_positions.items() }, diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py index cb3323ac9da..75b67c99f90 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/gripper.py @@ -41,6 +41,7 @@ from pylabrobot.resources.resource import Resource from pylabrobot.resources.resource_holder import ResourceHolder from pylabrobot.resources.rotation import Rotation +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import traverse if TYPE_CHECKING: from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck @@ -172,7 +173,7 @@ def held_labware_of( ) -> g.HeldLabware: """What the rail and the pod's own collision check count for `resource` held by the gripper: its footprint, the lid on it as a stacked layer (as Biomek counts a gripped stack), and its - height, in cm. + height, in cm, from their labware definitions (recorded in `source`). Args: resource: what is held. A lid seated on it (`resource.lid`) is the layer above it. @@ -187,6 +188,13 @@ def footprint(r: Resource) -> List[float]: size = [r.get_size_x() / MM_PER_CM, r.get_size_y() / MM_PER_CM] return size if across == "y" else size[::-1] + def definition(r: Resource) -> str: + """The labware definition `r` was made from, and its size (mm).""" + name = r.model or type(r).__name__ + return f"{name} {r.get_size_x():g} x {r.get_size_y():g} x {r.get_size_z():g} mm" + + sources = [definition(resource)] + length, width = footprint(resource) layers = [] top = resource.get_size_z() @@ -196,6 +204,7 @@ def footprint(r: Resource) -> List[float]: dx, dy = corner if across == "y" else corner[::-1] layers.append(g.StackedLayer(dx, dy, *footprint(lid))) top = max(top, lid.location.z + lid.get_size_z()) + sources.append(f"lid {definition(lid)}") return g.HeldLabware( length, width, @@ -204,6 +213,7 @@ def footprint(r: Resource) -> List[float]: tuple(layers), height=top / MM_PER_CM, grip_offset=grip_height / MM_PER_CM, + source="; ".join(sources), ) @@ -222,6 +232,19 @@ def __init__(self, pod: "Pod"): self._held_speed = 1000 self._taken_from: Tuple[Optional[Resource], Optional[Coordinate]] = (None, None) + @property + def default_minimum_traverse_height(self) -> traverse.TraverseDefault: + """How the gripper (and what it holds) travels by default: "safe", Biomek's safe height over the way (the tallest + thing under it, plus Biomek's margins); "max", as high as it goes; or a height, mm of + its lowest point above the deck. A call's `minimum_traverse_height_start` / `_end` overrides + it. It starts as Biomek's setting for the pod (`AlwaysMaxZ`); the deck check refuses any travel + too low, whatever the height.""" + return self._pod.traverse_defaults["gripper"] + + @default_minimum_traverse_height.setter + def default_minimum_traverse_height(self, value: traverse.TraverseDefault) -> None: + self._pod.traverse_defaults["gripper"] = traverse.traverse_default(value) + def __str__(self) -> str: return f"{self._pod}'s gripper" @@ -539,19 +562,32 @@ async def pick_up_resource( force = d.settings["GripperSqueezeForce"] if grip_strength is None else grip_strength logger.info("%s pick up %s (fingers %s)", pod.component, resource.name, direction) await self._check(checks, expect_labware=False) + # The approach is planned, nothing exempt; the get's own moves work in the resource's position. targets = self._travel_targets(plan) await pod._travel_gripper(targets, minimum_traverse_height=_cm(minimum_traverse_height_start)) - await pod.move_axes({"GG": d.to_counts("GG", plan.open_width)}) - await pod.move_axes({"GZ": d.to_counts("GZ", plan.gz)}) - self._simulate(plan.width) - await pod.move_axes({"GG": d.to_counts("GG", plan.close_width)}, forces={"GG": force}) - await self._check_stopped_width(plan) - await self._check(checks, expect_labware=True) - self._hold(resource, plan, checks, held_speed) - await pod.move_axes({"GZ": d.to_counts("GZ", plan.lift)}, held_speed) - await self._check(checks, expect_labware=True) - if minimum_traverse_height_end is not None: - await pod._move_over({}, held_speed, minimum_traverse_height=_cm(minimum_traverse_height_end)) + with pod.working_at(resource): + await pod.move_axes({"GG": d.to_counts("GG", plan.open_width)}) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.gz)}) + self._simulate(plan.width) + # What it closes on counts as part of the pod from the close on (on the rail, and against + # the pod's own parts and the deck): it moves with the fingers once they close. + self.set_held_labware(plan.held) + try: + await pod.move_axes({"GG": d.to_counts("GG", plan.close_width)}, forces={"GG": force}) + await self._check_stopped_width(plan) + await self._check(checks, expect_labware=True) + except BaseException: + self.set_held_labware(None) + raise + self._hold(resource, plan, checks, held_speed) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.lift)}, held_speed) + await self._check(checks, expect_labware=True) + # Then up to the height it travels at, still part of the get, as Biomek's get does. + await pod._raise_gripper(held_speed) + if minimum_traverse_height_end is not None: + await pod._move_over( + {}, held_speed, minimum_traverse_height=_cm(minimum_traverse_height_end) + ) async def _check_stopped_width(self, plan: GripPlan) -> None: """The close is force-limited and stops on what it grips; one that reached its target closed @@ -612,8 +648,11 @@ def plan_place( deck.check_can_drop_resource_here(held) else: to.check_can_drop_resource_here(held) - location = get_place_location(held, to, deck, rotation_applied_by_move=turn) rotation = (picked.rotation + turn) % 360 + # Reckoned from the pickup: the gripper may have turned it since (as it hangs now, at the + # gripper's own angle), so the turn from where it hangs. + now = get_rotation_wrt(held, deck).z + location = get_place_location(held, to, deck, rotation_applied_by_move=rotation - now) pads, height = self._grip_point( held, location, rotation, offset, None, picked.held.grip_offset * MM_PER_CM ) @@ -662,29 +701,45 @@ async def place_resource( checks = self._held_checks if check_grip is None else self._checks(check_grip) held_speed = self._held_speed if z_speed is None else self._held_field(z_speed) logger.info("%s place %s", pod.component, held.name) + # The approach is planned, nothing exempt; the put's own moves work in the destination. targets = self._travel_targets(plan) await pod._travel_gripper( targets, held_speed, minimum_traverse_height=_cm(minimum_traverse_height_start) ) - await self._check(checks, expect_labware=True) - await pod.move_axes({"GZ": d.to_counts("GZ", plan.gz)}, held_speed) - await self._check(checks, expect_labware=True) - await pod.move_axes({"GG": d.to_counts("GG", plan.open_width)}) - self._simulate(None) - picked = self._held_plan - if picked is None: - raise RuntimeError(f"{self}: has no plan for what it holds") - self._held = self._held_plan = None - self.set_held_labware(None) - # Off the gripper's model, turned as it was on the deck: the move adds its own turn. - if held.parent is not None: - held.unassign() - held.rotation = Rotation(z=picked.rotation) - assign_placed_resource(held, to, deck, location=location, rotation_applied_by_move=turn) - await self._check(checks, expect_labware=False) - await pod.move_axes({"GZ": d.to_counts("GZ", plan.lift)}) - if minimum_traverse_height_end is not None: - await pod._move_over({}, minimum_traverse_height=_cm(minimum_traverse_height_end)) + with pod.working_at(*self._places(to)): + await self._check(checks, expect_labware=True) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.gz)}, held_speed) + await self._check(checks, expect_labware=True) + await pod.move_axes({"GG": d.to_counts("GG", plan.open_width)}) + self._simulate(None) + picked = self._held_plan + if picked is None: + raise RuntimeError(f"{self}: has no plan for what it holds") + self._held = self._held_plan = None + self.set_held_labware(None) + # Off the gripper's model, turned as it was on the deck: the move adds its own turn. + if held.parent is not None: + held.unassign() + held.rotation = Rotation(z=picked.rotation) + assign_placed_resource(held, to, deck, location=location, rotation_applied_by_move=turn) + await self._check(checks, expect_labware=False) + await pod.move_axes({"GZ": d.to_counts("GZ", plan.lift)}) + await pod._raise_gripper() # up to its travel height, still part of the put + if minimum_traverse_height_end is not None: + await pod._move_over({}, minimum_traverse_height=_cm(minimum_traverse_height_end)) + + def _places(self, to: Union[Resource, Coordinate]) -> Tuple[Resource, ...]: + """What a place into `to` works in, for the deck check: `to`, or the deck position under a + deck `Coordinate`.""" + if not isinstance(to, Coordinate): + return (to,) + deck, _, _ = self._context() + return tuple( + p + for p in deck.get_all_children() + if isinstance(p, ResourceHolder) + and _contains(p.get_location_wrt(deck), p.get_absolute_size_x(), p.get_absolute_size_y(), to) + )[:1] async def drop_resource(self, *args: Any, **kwargs: Any) -> None: """Deprecated: use `place_resource`.""" @@ -761,3 +816,7 @@ async def move_resource( minimum_traverse_height_start=minimum_traverse_height_during, minimum_traverse_height_end=minimum_traverse_height_end, ) # fmt: skip + + +def _contains(corner: Coordinate, size_x: float, size_y: float, point: Coordinate) -> bool: + return corner.x <= point.x <= corner.x + size_x and corner.y <= point.y <= corner.y + size_y diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py index b8edd01c879..e9f70ed3a0f 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/head96.py @@ -59,6 +59,7 @@ from pylabrobot.resources.tip import Tip from pylabrobot.resources.tip_rack import TipRack, TipSpot from pylabrobot.resources.volume_tracker import VolumeTracker, does_volume_tracking +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import traverse if TYPE_CHECKING: from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck @@ -101,6 +102,8 @@ class HeadPlan: y: float z: float pairs: Tuple[Tuple[str, TipSpot], ...] = () + # What it works in besides the spots (the trash), for the deck check. + where: Tuple[Resource, ...] = () @dataclass(frozen=True) @@ -115,6 +118,11 @@ class LiquidPlan: pairs: Tuple[Tuple[str, Container], ...] +def _plan_places(plan: HeadPlan) -> Tuple[Resource, ...]: + """What a tip plan works in, for the deck check: its spots, and the trash.""" + return (*plan.where, *(s for _, s in plan.pairs)) + + class Head96: """The 96-channel head of a Multichannel pod.""" @@ -132,6 +140,19 @@ def __init__(self, pod: "Pod"): # Set by the device that models it (`BiomekI7Device`); None when nothing models it. self.resource: Optional[NChannelPipette] = None + @property + def default_minimum_traverse_height(self) -> traverse.TraverseDefault: + """How the head travels by default: "safe", Biomek's safe height over the way (the tallest + thing under it, plus Biomek's margins); "max", as high as it goes; or a height, mm of + its lowest point above the deck. A call's `minimum_traverse_height_start` / `_end` overrides + it. It starts as Biomek's setting for the pod (`AlwaysMaxZ`); the deck check refuses any travel + too low, whatever the height.""" + return self._pod.traverse_defaults["channels"] + + @default_minimum_traverse_height.setter + def default_minimum_traverse_height(self, value: traverse.TraverseDefault) -> None: + self._pod.traverse_defaults["channels"] = traverse.traverse_default(value) + def __str__(self) -> str: return f"{self._pod}'s 96-channel head" @@ -323,7 +344,7 @@ def plan_discard(self, tip_length: float, trash: Optional[Resource] = None) -> H deck, configuration, self._pod.pod_number, position, x="l", y="b", z="b" ) z = corner.z + tip_length + disposal.z - return HeadPlan(corner.x + disposal.x, corner.y + disposal.y, z) + return HeadPlan(corner.x + disposal.x, corner.y + disposal.y, z, where=(position,)) def _tip_length(self, mandrels: List[str]) -> float: """The longest carried tip's effective length, cm (`_carried_tip`).""" @@ -350,6 +371,19 @@ def _carried_tip_lengths(self) -> Dict[str, float]: ] return {"Z": self._tip_length(carried)} if carried else {} + def _tip_block(self) -> Optional[Tuple[int, int, int, int]]: + """The block of mandrels carrying tips: (first column, last column, first row, last row), from + 0; None without tips.""" + at = [(i % COLUMNS, i // COLUMNS) for i, t in enumerate(self.tips) if t is not None] + if not at: + return None + return ( + min(c for c, _ in at), + max(c for c, _ in at), + min(r for _, r in at), + max(r for _, r in at), + ) + async def pick_up_tips( self, tip_rack: TipRack, @@ -376,12 +410,13 @@ async def pick_up_tips( pod = self._pod logger.info("%s pick up %d tips from %s", pod.component, len(plan.pairs), tip_rack.name) await self._clear_gripper() - await pod._move_over( + await pod._move_over( # the approach: planned, nothing exempt {"X": declared.to_counts("X", plan.x), "Y": declared.to_counts("Y", plan.y)}, minimum_traverse_height=_cm(minimum_traverse_height_start), ) - await pod.move_axes({"Z": declared.to_counts("Z", plan.z)}, 1000) - await self.load_tips(load) + with pod.working_at(tip_rack): + await pod.move_axes({"Z": declared.to_counts("Z", plan.z)}, 1000) + await self.load_tips(load) picked: Dict[str, Optional[Tip]] = {} for mandrel, spot in plan.pairs: tip = spot.tip_for_pickup() @@ -390,7 +425,8 @@ async def pick_up_tips( self._tips[mandrel] = tip picked[mandrel] = tip self._set_tips(picked) - await pod._lift_channels(_cm(minimum_traverse_height_end)) + with pod.working_at(tip_rack): # the rise out of it is the load's own + await pod._lift_channels(_cm(minimum_traverse_height_end)) async def drop_tips( self, @@ -423,7 +459,8 @@ async def drop_tips( if spot.tracks_tips: spot.assign_tip(tip if tip is not None else spot.make_tip()) self._set_tips({m: None for m in carried}) - await self._pod._lift_channels(_cm(minimum_traverse_height_end)) + with self._pod.working_at(*_plan_places(plan)): # the rise out of it is the eject's own + await self._pod._lift_channels(_cm(minimum_traverse_height_end)) async def discard_tips( self, @@ -443,7 +480,8 @@ async def discard_tips( for mandrel in carried: self._tips.pop(mandrel, None) self._set_tips({m: None for m in carried}) - await self._pod._lift_channels(_cm(minimum_traverse_height_end)) + with self._pod.working_at(*_plan_places(plan)): # the rise out of it is the eject's own + await self._pod._lift_channels(_cm(minimum_traverse_height_end)) async def discard_any_tips(self, trash: Optional[Resource] = None) -> None: """Eject into the trash (`TR1` by default) whatever tips the head may carry, recorded or not: @@ -468,7 +506,8 @@ async def discard_any_tips(self, trash: Optional[Resource] = None) -> None: ) plan = self.plan_discard(length, trash) await self._eject_at(plan, None, tip_length=length) - await self._pod._lift_channels(None, tip_lengths={"Z": length}) + with self._pod.working_at(*_plan_places(plan)): + await self._pod._lift_channels(None, tip_lengths={"Z": length}) def _carried(self) -> List[str]: carried = [ @@ -487,13 +526,14 @@ async def _eject_at( pod = self._pod logger.info("%s eject tips at X %.3f Y %.3f Z %.3f cm", pod.component, plan.x, plan.y, plan.z) await self._clear_gripper() - await pod._move_over( + await pod._move_over( # the approach: planned, nothing exempt {"X": declared.to_counts("X", plan.x), "Y": declared.to_counts("Y", plan.y)}, minimum_traverse_height=_cm(start), tip_lengths=None if tip_length is None else {"Z": tip_length}, ) - await pod.move_axes({"Z": declared.to_counts("Z", plan.z)}, 1000) - await self.eject() + with pod.working_at(*_plan_places(plan)): + await pod.move_axes({"Z": declared.to_counts("Z", plan.z)}, 1000) + await self.eject() async def eject(self) -> None: """Push the tips off the mandrels where the head is: the plunger to the bottom of its travel @@ -512,16 +552,12 @@ async def eject(self) -> None: await pod.move_axes({"D": target}, speed) async def _clear_gripper(self) -> None: - """Turn the gripper to its park angle (GR), as Biomek does before the head works the deck. - - Raises: - RuntimeError: while the gripper holds labware (turning would swing it). - """ - if self._pod._held_labware is not None: - raise RuntimeError(f"{self}: the gripper holds labware; place it before the head works") + """Turn the gripper to its park angle (GR), as Biomek does before the head works the deck, + with whatever it holds: the deck check decides whether the turn, and the head's moves after + it, are clear.""" _, _, declared = self._context() gr = declared.to_counts("GR", declared.park["GR"]) - if self._pod.cpositions["GR"][1] != gr: + if not self._pod._at_angle(gr): await self._pod.move_axes({"GR": gr}) # -- aspirate and dispense ---------------------------------------------------------------------- @@ -672,15 +708,16 @@ async def _run_liquid( if below: await pod.move_axes({"D": declared.to_counts("D", 0.0)}) await self._clear_gripper() - await pod._move_over( + await pod._move_over( # the approach: planned, nothing exempt {"X": declared.to_counts("X", plan.x), "Y": declared.to_counts("Y", plan.y)}, minimum_traverse_height=_cm(minimum_traverse_height_start), ) - for targets, speed, delay in moves: - await pod.move_axes({a: declared.to_counts(a, v) for a, v in targets.items()}, speed) - if delay > 0: - await asyncio.sleep(delay) - await pod._lift_channels(_cm(minimum_traverse_height_end)) + with pod.working_at(*(c for _, c in plan.pairs)): + for targets, speed, delay in moves: + await pod.move_axes({a: declared.to_counts(a, v) for a, v in targets.items()}, speed) + if delay > 0: + await asyncio.sleep(delay) + await pod._lift_channels(_cm(minimum_traverse_height_end)) # out of it: the step's own def _book(self, plan: LiquidPlan, volume: float, aspirate: bool) -> List[Any]: """Move `volume` per mandrel between the containers' and the tips' trackers (pending, to commit diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py index 8eeda5c5f56..58229ee4cd9 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pipettes.py @@ -73,6 +73,7 @@ from pylabrobot.resources.tip import Tip from pylabrobot.resources.tip_rack import TipSpot from pylabrobot.resources.volume_tracker import VolumeTracker, does_volume_tracking +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import traverse if TYPE_CHECKING: from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck @@ -140,6 +141,8 @@ class PrimePlan: z: float stroke: float speed: int + # The wash station's position, for the deck check. + where: Tuple[Resource, ...] = () class _Job(NamedTuple): @@ -184,6 +187,8 @@ class DiscardPlan: z: float groups: Tuple[Tuple[int, ...], ...] shuck: Dict[int, float] + # The trash's position, for the deck check. + where: Tuple[Resource, ...] = () @dataclass(frozen=True) @@ -237,11 +242,25 @@ def __init__(self, pod: "Pod"): # (`BiomekI7Device`); empty when nothing models them. self.resources: List[Resource] = [] self._priming: Optional["asyncio.Task[int]"] = None + self._priming_in: Tuple[Resource, ...] = () # the prime's wash station, until it stops self._stop_priming = asyncio.Event() # Whether the pumps are homed: None until this session homes them (`home_pumps`) or asks # (`_require_pumps_homed`); a power-up leaves them not homed, and Home All does not home them. self._pumps_homed: Optional[bool] = None + @property + def default_minimum_traverse_height(self) -> traverse.TraverseDefault: + """How the probes travel by default: "safe", Biomek's safe height over the way (the tallest + thing under they, plus Biomek's margins); "max", as high as they go; or a height, mm of + their lowest point above the deck. A call's `minimum_traverse_height_start` / `_end` overrides + it. It starts as Biomek's setting for the pod (`AlwaysMaxZ`); the deck check refuses any travel + too low, whatever the height.""" + return self._pod.traverse_defaults["channels"] + + @default_minimum_traverse_height.setter + def default_minimum_traverse_height(self, value: traverse.TraverseDefault) -> None: + self._pod.traverse_defaults["channels"] = traverse.traverse_default(value) + def __str__(self) -> str: return f"{self._pod}'s channels" @@ -387,6 +406,7 @@ def plan_prime(self, wash: Optional[Resource] = None) -> PrimePlan: z=at.z, stroke=declared.limits["D1"][1], speed=percent_to_field(declared.settings["D1SpeedLimit"], truncate=True), + where=(position,), ) @property @@ -420,10 +440,12 @@ async def start_prime( pod = self._pod logger.info("%s prime over %s", pod.component, wash.name if wash else DEFAULT_WASH) await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height) - await pod.move_axes( - {f"Z{n}": declared.to_counts(f"Z{n}", plan.z) for n in range(1, PROBES + 1)}, PRIME_Z_SPEED - ) - await self.home_pumps() + with pod.working_at(*plan.where): + await pod.move_axes( + {f"Z{n}": declared.to_counts(f"Z{n}", plan.z) for n in range(1, PROBES + 1)}, PRIME_Z_SPEED + ) + await self.home_pumps() + self._priming_in = plan.where self._stop_priming.clear() self._priming = asyncio.ensure_future( self._prime_strokes(plan, strokes, minimum_stroke_seconds) @@ -472,7 +494,8 @@ async def stop_prime( _, _, declared = self._context() pod = self._pod end = minimum_traverse_height_end - await pod._lift_channels(None if end is None else end / 10) + with pod.working_at(*self._priming_in): # out of the wash station: the prime's own rise + await pod._lift_channels(None if end is None else end / 10) gap = declared.settings["SystemTrailingAirgap"] pumps = [f"D{n}" for n in range(1, PROBES + 1)] await pod.move_axes({a: declared.to_counts(a, gap) for a in pumps}, PRIME_AIR_GAP_SPEED) @@ -719,6 +742,7 @@ def plan_discard(self, probes: Sequence[int], trash: Optional[Resource] = None) z=s["DiscardHeight"] - DISCARD_BELOW, groups=tuple(press_groups(probes, s["MaxUnloadingProbes"], s["MinUnloadingInterval"])), shuck={n: declared.limits[f"Z{n}"][1] + overshoot for n in probes}, + where=(position,), ) async def _travel(self, x: float, y: float, span: float, height: Optional[float]) -> None: @@ -776,31 +800,35 @@ async def pick_up_tips( def z(probes: Sequence[int], height: float) -> Dict[str, int]: return {f"Z{n}": declared.to_counts(f"Z{n}", height) for n in probes} - for plan in plans: + # Each batch's travel is planned, nothing exempt; its own moves work in its spots' positions, + # the last batch's through the rise out. + for i, plan in enumerate(plans): probes = [n for n, _ in plan.pairs] logger.info( "%s pick up tips on probes %s at X %.3f Y %.3f S %.3f", pod.component, probes, plan.x, plan.y, plan.span, ) # fmt: skip await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height_start) - await pod.move_axes(z(plan.lowered, plan.approach)) - previous: Tuple[int, ...] = () - for group in plan.groups: - targets = z(previous, plan.exit) - targets.update({f"Z{n}": declared.to_counts(f"Z{n}", plan.seats[n]) for n in group}) - await pod.move_axes(targets, speed) - previous = group - await pod.move_axes(z(previous, plan.exit), speed) - picked: Dict[int, Optional[Tip]] = {} - for probe, spot in plan.pairs: - tip = spot.tip_for_pickup() - if spot.tracks_tips: - spot.unassign_tip() - self._tips[probe] = tip - picked[probe] = tip - self._set_tips(picked) - end = minimum_traverse_height_end - await pod._lift_channels(None if end is None else end / 10) + with pod.working_at(*(s for _, s in plan.pairs)): + await pod.move_axes(z(plan.lowered, plan.approach)) + previous: Tuple[int, ...] = () + for group in plan.groups: + targets = z(previous, plan.exit) + targets.update({f"Z{n}": declared.to_counts(f"Z{n}", plan.seats[n]) for n in group}) + await pod.move_axes(targets, speed) + previous = group + await pod.move_axes(z(previous, plan.exit), speed) + picked: Dict[int, Optional[Tip]] = {} + for probe, spot in plan.pairs: + tip = spot.tip_for_pickup() + if spot.tracks_tips: + spot.unassign_tip() + self._tips[probe] = tip + picked[probe] = tip + self._set_tips(picked) + if i == len(plans) - 1: + end = minimum_traverse_height_end + await pod._lift_channels(None if end is None else end / 10) await self._check_tips(sorted(n for plan in plans for n, _ in plan.pairs)) async def drop_tips(self, tip_spots: Sequence[TipSpot], *args: Any, **kwargs: Any) -> None: @@ -852,16 +880,17 @@ def z(group: Sequence[int], height: Mapping[int, float]) -> Dict[str, int]: below = {n: plan.z for n in probes} await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height_start) - await pod.move_axes(z(probes, below)) - speed = percent_to_field(declared.settings["DiscardSpeed"]) - for group in plan.groups: - await pod.move_axes(z(group, plan.shuck), speed) - await pod.move_axes(z(group, below), speed) - for probe in probes: - self._tips.pop(probe, None) - self._set_tips({n: None for n in probes}) - end = minimum_traverse_height_end - await pod._lift_channels(None if end is None else end / 10) + with pod.working_at(*plan.where): + await pod.move_axes(z(probes, below)) + speed = percent_to_field(declared.settings["DiscardSpeed"]) + for group in plan.groups: + await pod.move_axes(z(group, plan.shuck), speed) + await pod.move_axes(z(group, below), speed) + for probe in probes: + self._tips.pop(probe, None) + self._set_tips({n: None for n in probes}) + end = minimum_traverse_height_end + await pod._lift_channels(None if end is None else end / 10) await self._check_tips(probes) async def _check_tips(self, probes: Sequence[int]) -> None: @@ -1074,22 +1103,26 @@ async def _run_liquid( await self.set_valves({a: "output" for a in pumps}) await pod.move_axes({a: declared.to_counts(a, gap) for a in pumps}, AIR_GAP_SPEED) self._set_cutoff_velocity(cutoff_to_counts(self._pod, "D1", cutoff_velocity)) - for plan, moves in batches: + # Each batch's travel is planned, nothing exempt; its own moves work in its containers' + # positions, the last batch's through the rise out. + for i, (plan, moves) in enumerate(batches): await self._travel(plan.x, plan.y, plan.span, minimum_traverse_height_start) - for targets, speed, delay, sense in moves: - if sense: - await self._set_lls_sensitivity(lls_sensitivity) - if any(a.startswith("D") for a in targets) and any( - self._pod._valves.get(a) != "output" for a in targets if a.startswith("D") - ): - await self.set_valves({a: "output" for a in pumps}) - await pod.move_axes({a: declared.to_counts(a, v) for a, v in targets.items()}, speed) - if delay > 0: - await asyncio.sleep(delay) - # Biomek turns every valve to output after each operation (`VO 255`). - await self.set_valves({a: "output" for a in pumps}) - end = minimum_traverse_height_end - await pod._lift_channels(None if end is None else end / 10) + with pod.working_at(*(c for _, c in plan.pairs)): + for targets, speed, delay, sense in moves: + if sense: + await self._set_lls_sensitivity(lls_sensitivity) + if any(a.startswith("D") for a in targets) and any( + self._pod._valves.get(a) != "output" for a in targets if a.startswith("D") + ): + await self.set_valves({a: "output" for a in pumps}) + await pod.move_axes({a: declared.to_counts(a, v) for a, v in targets.items()}, speed) + if delay > 0: + await asyncio.sleep(delay) + # Biomek turns every valve to output after each operation (`VO 255`). + await self.set_valves({a: "output" for a in pumps}) + if i == len(batches) - 1: + end = minimum_traverse_height_end + await pod._lift_channels(None if end is None else end / 10) def _book(self, plans: List[ProbePlan], extra: float, aspirate: bool) -> List[Any]: """Move each probe's volume (+ `extra`) between its container's and its tip's trackers diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py index d124063d678..bfa6bd298d7 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/features/pod.py @@ -1,14 +1,16 @@ """One pod: an arm on the shared X rail, its ACE module, and the axes that module drives.""" import asyncio +import contextlib import logging -import math from dataclasses import dataclass, field from typing import ( TYPE_CHECKING, + Any, Callable, Dict, Iterable, + Iterator, List, Literal, Mapping, @@ -16,35 +18,50 @@ Sequence, Set, Tuple, + Union, cast, ) -from pylabrobot.beckman_coulter.biomek_i7 import units +from pylabrobot.beckman_coulter.biomek_i7 import targeting, units from pylabrobot.beckman_coulter.biomek_i7.driver import motion -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver import protocol as p from pylabrobot.beckman_coulter.biomek_i7.driver.board import AceBoard from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import ( ModuleConfiguration, PodConfiguration, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english -from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper -from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 -from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes from pylabrobot.beckman_coulter.biomek_i7.driver.module import ( read_analog_inputs, read_module, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables from pylabrobot.beckman_coulter.biomek_i7.driver.recipes.homing import ( ENABLE_ORDER, ENABLE_PREFIX, HOME_RECIPES, Homer, ) -from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail +from pylabrobot.beckman_coulter.biomek_i7.driver.features.gripper import Gripper +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import Head96 +from pylabrobot.beckman_coulter.biomek_i7.driver.features.pipettes import Pipettes +from pylabrobot.beckman_coulter.biomek_i7.driver.errors import AceError, NotHomedError, english +from pylabrobot.beckman_coulter.biomek_i7.driver.motors import Axis, AxisMove, MotorTables +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import ( + check, + destinations, + find_path, + merge, + obstacles, + pod_model, + search, + traverse, +) +from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import ( + OTHER, + RailPose, + RailCollisionError, + XRail, +) if TYPE_CHECKING: from pylabrobot.beckman_coulter.biomek_i7.driver.master import BiomekI7Driver @@ -67,9 +84,19 @@ # The axes that change what a pod takes up along the X rail. RAIL_AXES = ("X", "GR", "GG") # The gripper's axes; a move of these, or of the channels' Y or Z, is checked against the pod's own -# parts (`pod_collision`). +# parts (`planning.check`). OWN_COLLISION_AXES = {"GY", "GZ", "GR", "GG"} -GRIPPER_HEIGHT_STEP = 0.1 # cm: how finely the gripper's travel height is searched + +# How far (cm) Biomek's planner keeps a pod's bridge from the other pod's: one 1/16 cm grid cell +# and 1/64 cm. +OTHER_POD_GAP = 1 / 16 + 1 / 64 + +# Where the other pod's wall is open (cm): Biomek's boxes stand for unbounded at 500 cm. +WALL_OPEN = 500.0 + +# A planned move (axis targets, counts) and the deck positions it leaves straight up (its way out of +# them, made with them exempt); nothing for every other move. +PlanStep = Tuple[Dict[str, int], Tuple[str, ...]] # Get Homed State answers. 0x01 was read from every axis at a cold start, 0x00 from every axis of # both pods after Biomek's Home All (H1, 2026-10-24). @@ -79,8 +106,10 @@ MOVE_TIMEOUT_MS = 30000 MOVE_ALL_TIMEOUT_MS = 5000 -# Biomek's "Safe Height" (`GlobalMinSafeHeight`) at or below this is unset (it stores -100000). -UNSET_SAFE_HEIGHT = -1000.0 + +# Degrees within which GR is taken to be at an angle (`_at_angle`): well under a count's worth of +# difference matters nowhere. A whole turn away is another angle, as Biomek's GR is a line. +GR_SAME_ANGLE = 0.01 # The arm board's analog input carrying the interlocked motor supply ("+36V Interlock"). DRIVE_SUPPLY_INPUT = "+36V Interlock" @@ -152,6 +181,20 @@ def __init__( # What the gripper holds, as the rail counts it: set through `gripper.set_held_labware`; the # pod cannot sense it. self._held_labware: Optional[g.HeldLabware] = None + # The last planning world built (`_planning_world`), with what it was built from. + self._planning_cache: Optional[Tuple[Tuple[int, g.Range], obstacles.Obstacles]] = None + # What it held at its last move checked on the rail: the first move after it takes or lets go + # of labware (its range changed with it) is checked there, whatever axes it moves. + self._rail_held: Optional[g.HeldLabware] = None + # The deck positions the operation under way works in (`working_at`): the deck check leaves + # their boxes out, whole, as Biomek's moves name their target position. + self._working_at: Tuple[str, ...] = () + # How many operations are under way on the pod (a planned one, `_planning`, or a step's own + # moves, `working_at`): while any is, the other pod's clearing of its way does not move it. + self._busy = 0 + # Held for each move (`move_axes`): one move at a time on the pod's board, whichever task + # sends it (the other pod's clearing of its way moves this one from its own). + self._motion = asyncio.Lock() # Where this driver last put each axis, as the Master Controller keeps it (`cpositions`): # (position, adjusted); position None until read. Starts as after homing. self._cpositions: Dict[str, motion.CPos] = {a.name: (None, a.home_position) for a in self.axes} @@ -164,18 +207,21 @@ def __init__( # Set while the interlock is tripped, shared by the driver (`BiomekI7Driver.interlock_tripped`); # None for a pod used without one. Waits that the Master Controller abandons on a trip watch it. self.interlock_tripped: Optional[asyncio.Event] = None - # The height the channels rise to before traveling over the deck, mm of the channels' bottom - # above the deck: STAR's `default_minimum_traverse_height`. Seeded from Biomek's "Safe Height" - # (`GlobalMinSafeHeight`) when it is set; None, as on an instrument where it is not (-100000), - # means the top of travel less the park margin, which is what Biomek does with Safe Height set - # to the top. - self.default_minimum_traverse_height: Optional[float] = None - if declared is not None: - safe = declared.settings.get("GlobalMinSafeHeight") - if isinstance(safe, (int, float)) and safe > UNSET_SAFE_HEIGHT: - self.default_minimum_traverse_height = units.to_mm(float(safe)) + # How each tool (the channels, the gripper) travels by default (`Head96`/`Pipettes`/`Gripper` + # `default_minimum_traverse_height`): "safe", Biomek's safe height over its way (`_safe_heights`); + # "max", as high as it goes; or a height, mm of its lowest point above the deck. From the + # pod's `AlwaysMaxZ`: "max" for every tool when set, else "safe". + start: traverse.TraverseDefault = ( + "max" if declared is not None and declared.settings["AlwaysMaxZ"] else "safe" + ) + self.traverse_defaults: Dict[str, traverse.TraverseDefault] = { + "channels": start, + "gripper": start, + } # Who follows the position record (`add_position_listener`). self._listeners: List[Callable[["Pod"], None]] = [] + # Who follows the pod's motion (`add_motion_listener`). + self._motion_listeners: List[Callable[["Pod", str, Any], None]] = [] # What the pod carries (STAR's arm features): what its module type has (`MODULE_FEATURES`), and # a gripper where the declared configuration describes one, as the rail counts one only then. features = MODULE_FEATURES.get(module_type, ()) @@ -360,33 +406,22 @@ async def request_x_position(self) -> int: # -- the pod against itself ---------------------------------------------------- - def _own_state( + def _pose( self, positions: Optional[Mapping[str, motion.CPos]] = None - ) -> Optional[Tuple[float, pc.GripperState, pc.PipettorState]]: - """The pose the pod's own collision check takes (`pod_collision`), in Biomek's units, from - `positions` (the position record by default); None while any of its axes is unknown.""" + ) -> Optional[pod_model.PodState]: + """The pod's pose in Biomek's units from `positions` (the position record by default): X, the + gripper's (None on a pod without one) and the pipettor's; None while any axis is unknown.""" d = self.declared - if d is None or not d.gripper_model: + if d is None: return None positions = self._cpositions if positions is None else positions - channels = self.channel_z_axes - ys = [f"Y{i}" for i in range(1, 9)] if self.module_type == "span8" else ["Y"] - names = ["X", "GY", "GZ", "GR", "GG", *ys, *channels] - counts = {n: positions[n][0] for n in names} + model = pod_model.PodModel.of(d) + counts = {n: positions[n][0] for n in model.pose_axes} if any(c is None for c in counts.values()): return None - v = {n: d.to_value("Y" if n in ys else n, c) for n, c in counts.items()} # type: ignore[arg-type] - if self.module_type == "span8": - # Each probe's Y counts from its own narrowest place (`probe_y`), not probe 1's. - v.update({n: d.probe_y(i, counts[n]) for i, n in enumerate(ys, 1)}) # type: ignore[arg-type] lengths = self._carried_tip_lengths() - gripper = pc.GripperState(v["GY"], v["GZ"], v["GR"], v["GG"], self._held_labware) - pipettor = pc.PipettorState( - tuple(v[n] for n in ys), - tuple(v[z] for z in channels), - tuple(lengths.get(z, 0.0) for z in channels), - ) - return v["X"], gripper, pipettor + block = self.head96._tip_block() if self.head96 is not None and lengths else None + return model.state(cast(Dict[str, int], counts), self._held_labware, lengths, block) def _check_own_collision( self, @@ -401,75 +436,278 @@ def _check_own_collision( """ if not moving & OWN_COLLISION_AXES and not any(a[:1] in "YZ" for a in moving): return - a, b = self._own_state(start), self._own_state(end) + a, b = self._pose(start), self._pose(end) if a is None or b is None or self.declared is None: return - found = pc.swept_collisions(self.declared, (a[0], b[0]), (a[1], b[1]), (a[2], b[2])) + found = check.own_collisions(self.declared, a, b) if found: parts = ", ".join(f"the {x} and {y}" for x, y in found[:3]) - raise pc.PodCollisionError(f"{self}: the move would bring together {parts}") + raise check.PodCollisionError(f"{self}: the move would bring together {parts}") + + # -- the pod against the deck and the instrument -------------------------------- + + @contextlib.contextmanager + def working_at(self, *positions: Union[str, "Resource"]) -> Iterator[None]: + """Within it, the deck check leaves the deck positions given (names, or resources on them) + out, whole: the ones the operation works in, whose labware it goes into by design, as each of + Biomek's moves names its target position. Their own obstacles (a trash's walls) stay in.""" + names = [] + for where in positions: + if isinstance(where, str): + names.append(where) + continue + deck = self.driver.deck if self.driver is not None else None + position = targeting.deck_position_of(deck, where) if deck is not None else None + names.append(position.name if position is not None else where.name) + before = self._working_at + self._working_at = (*before, *names) + self._busy += 1 + try: + yield + finally: + self._working_at = before + self._busy -= 1 - def _gripper_traverse_height(self, gr: float) -> float: - """The GZ (cm) the gripper travels at to turn from where it is to GR `gr` (degrees): its - ceiling (`_traverse_ceilings`), or as far below it as keeps it (and what it holds) clear of the - pod's own pipettor at its traverse heights on the way, in steps of `GRIPPER_HEIGHT_STEP`. + def _check_world_collision( + self, start: Mapping[str, motion.CPos], end: Mapping[str, motion.CPos] + ) -> None: + """Refuse a move whose path brings any of the pod's parts (or what its gripper holds) into the + deck's positions, their obstacles or the instrument's structure (the driver's `obstacles`). + Nothing without them. Raises: - PodCollisionError: if no height down to the grip's travel limit is clear. + DeckCollisionError: naming the parts that would meet; nothing has been sent. """ - d = self._require_declared() - state = self._own_state() - ceiling = self._traverse_ceilings()["GZ"] - if state is None: - return ceiling - x, gripper, pipettor = state - heights = self._traverse_heights() - raised = pc.PipettorState( - pipettor.ys, - tuple(max(z, heights[n]) for z, n in zip(pipettor.zs, self.channel_z_axes)), - pipettor.tips, - ) - low = d.limits["GZ"][0] - gz = ceiling - while gz >= low: - a = pc.GripperState(gripper.gy, gz, gripper.gr, gripper.gg, gripper.held) - b = pc.GripperState(gripper.gy, gz, gr, gripper.gg, gripper.held) - if not pc.swept_collisions(d, (x, x), (a, b), (raised, raised)): - return gz - gz -= GRIPPER_HEIGHT_STEP - raise pc.PodCollisionError(f"{self}: no gripper height clears the pod's own parts at GR {gr}") - - async def _make_room_for_gripper(self, targets: Mapping[str, int]) -> None: - """Before the gripper travels to `targets` (counts: X, GY, GR): on a Span-8 whose probes - would be in its way there, narrow them to the smallest span and move them to the end of their - Y travel away from the gripper (as Biomek's path search does when it minimises the pod's Y - span). Nothing on a 96-head pod, or with the probes already clear. + if self.declared is None: + return + a, b = self._pose(start), self._pose(end) + if a is None or b is None or a == b: + return # unknown, or no part moves (a pump's stroke) + world = self._world(self.pod_number, self._working_at) + if world is None: + return + found = check.deck_collisions(self.declared, a, b, world) + if found: + parts = ", ".join(f"the {x} into {y}" for x, y in found[:3]) + raise check.DeckCollisionError(f"{self}: the move would bring {parts}") + + async def _minimize_span(self, speed: int = 1000) -> None: + """Before a gripper approach on a Span-8, as Biomek's: the probes' span to its minimum (probe + 1's Y kept), a checked move; if it is not clear, the probes as high as they go first, then the + span again. Where the probes' Y goes is left to the planned approach. Nothing on a 96-head pod, + or with the span at its minimum. Raises: - PodCollisionError: if the probes cannot be moved clear. + PodCollisionError: if the span cannot be narrowed clear even with the probes at the top. """ if self.module_type != "span8": return d = self._require_declared() - await self._read_unknown_positions() - state = self._own_state() - if state is None: - return - x, gripper, pipettor = state - gy = d.to_value("GY", targets.get("GY", self._cpositions["GY"][1])) - gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1])) - gz = self._gripper_traverse_height(gr) if gr != gripper.gr else gripper.gz - end = pc.GripperState(gy, gz, gr, gripper.gg, gripper.held) - if not pc.collisions(d, x, end, pipettor): + narrow = {"S": d.to_counts("S", d.limits["Span"][0])} + ys = [f"Y{i}" for i in range(1, 9)] + planned = self._planned(self._cpositions, narrow) + if all(planned[y] == self._cpositions[y] for y in ys): return - low, high = d.limits["Y"] - span = d.limits["Span"][0] - y = low if gy >= (low + high) / 2 else high - span - ys = tuple(y + i * span / (len(pipettor.ys) - 1) for i in range(len(pipettor.ys))) - if pc.collisions(d, x, end, pc.PipettorState(ys, pipettor.zs, pipettor.tips)): - raise pc.PodCollisionError(f"{self}: the probes cannot be moved clear of the gripper") - await self._lift_channels() - await self.move_axes({"Y": d.to_counts("Y", y), "S": d.to_counts("S", span)}) + if not self._clear([narrow]): + tops = self._max_traverse_heights() + await self._rise({n: tops[n] for n in self.channel_z_axes}, speed) + if not self._clear([narrow]): + raise check.PodCollisionError( + f"{self}: unable to narrow the probes' span for the gripper: it would collide" + ) + await self.move_axes(narrow, speed) + + async def _raise_gripper(self, speed: int = 1000) -> None: + """Raise the gripper to the height it travels at from here (`_traverse_heights`); nothing when + it is already there or above.""" + d = self._require_declared() + gz = d.to_counts("GZ", self._traverse_heights()["GZ"]) + if gz > self._cpositions["GZ"][1]: + await self.move_axes({"GZ": gz}, speed) + + def _planned( + self, start: Mapping[str, motion.CPos], targets: Mapping[str, int] + ) -> Dict[str, motion.CPos]: + """Where every axis ends from `start` as a move to `targets` would plan it (a Span-8's probes + from its Y and span, as `move_axes` sets them).""" + wanted = dict(targets) + if self.module_type == "span8" and ("Y" in wanted or "S" in wanted): + y, span = wanted.pop("Y", None), wanted.pop("S", None) + wanted.update(motion.span_targets(start, y, span)) + _, _, after = motion.plan_move(self.axes, start, wanted, 1000, self._cutoff_velocity) + return after + + def _search( + self, + targets: Mapping[str, int], + x_bounds: Optional[Tuple[float, float]] = None, + start: Optional[Mapping[str, motion.CPos]] = None, + ) -> List[merge.Move]: + """Biomek's search (`search.search`) from `start` (where the pod is by default) to `targets` + (counts), for a planned + move whose direct way is not clear. Each step moves one axis of one part to its next contact + or its destination coordinate (`search.contact_stop`): X carries both parts, Y moves the + pipettor (only with GR on a multiple of 90 degrees), GY the gripper, GR turns the gripper a + quarter turn (to the bracketing quarters off them, straight to an off-quarter destination + within one). Channel Z axes and GZ in `targets` join the search: up to the part's next contact + above (its bottom at an obstacle's top) or its target, down only near the destination (within + twice the part's footprint of its X and Y) to the next top below or its target; without them + the heights are kept (Biomek's travel stage). Every step is checked as `_clear` checks it, + and its stops come from the same boxes; cost its length + 1 per moving part, + + `RotationPenalty` per turn or per move on an axis the destination leaves free; at most + `AStarSearchLimit` expansions; ties to the first found. A Span-8's span is set first, as + Biomek sets it before planning. `x_bounds` (cm): where X may go, within its travel (a pod + moving aside keeps to its side); by default the planner's X limits (`_planning_x_limits`). + Against the planning world (`_planning_world`). + + Raises: + search.NoPathError: as `search.search`. + """ + return search.pod_search( + self._require_declared(), + self._cpositions if start is None else start, + targets, + self._planning_world(), + self._pose, + self._planned, + self._clear, + self.channel_z_axes, + self._planning_x_limits() if x_bounds is None else x_bounds, + ) + + def _world(self, pod_number: int, exempt: Sequence[str] = ()) -> Optional[obstacles.Obstacles]: + """What pod `pod_number`'s moves must clear (the driver's `obstacles`, on that pod's + calibration of the deck) with the boxes of the `exempt` positions left out; None without a + device to give them.""" + if self.driver is None or self.driver.obstacles is None: + return None + return self.driver.obstacles(pod_number).without(exempt) + + def _other_pod(self) -> Optional["Pod"]: + """The other pod on this pod's rail; None without one.""" + driver = self.driver + if driver is None or self.rail is None: + return None + other = driver.right_x_arm if self.side == "left" else driver.left_x_arm + if other is None or other is self or other.rail is not self.rail or other.declared is None: + return None + return other + + def _pushable(self, other: "Pod") -> bool: + """Whether planning may count on moving `other` out of the way: clearing the way on, and + `other` neither in an operation nor moving (a busy pod is planned around where it stands).""" + assert self.driver is not None + return self.driver.make_way and not other._busy and not other._motion.locked() + + def _range_at_limit(self, x: float) -> g.Range: + """The X this pod takes up with X at `x`, its gripper at GR 0 and GG 0 holding what it holds, + as Biomek's planner takes it at its X limit.""" + assert self.rail is not None + gripper = g.GripperPose(0.0, 0.0, self._held_labware) if self.gripper is not None else None + return self.rail.range_at(self.side, RailPose(x, gripper)) + + def _other_pod_wall(self) -> Optional[g.Range]: + """The other pod as Biomek's planner walls it off (deck X, cm; open beyond its far side): when + it can be moved out of the way (`_pushable`), its bridge at the end of its travel, 1/16 + 1/64 + cm off, or this pod's range at its own X limit if that comes first; otherwise its whole range + where it stands. None without another pod, or with its position not known.""" + other = self._other_pod() + if other is None: + return None + assert self.rail is not None and other.declared is not None + if not self._pushable(other): + return self.rail.occupied(other.side) + d, od = self._require_declared(), other.declared + if self.side == "left": + edge = g.bridge_x_range(od.geometry, od.limits["X"][1])[0] - OTHER_POD_GAP + return min(edge, self._range_at_limit(d.limits["X"][1])[1]), WALL_OPEN + edge = g.bridge_x_range(od.geometry, od.limits["X"][0])[1] + OTHER_POD_GAP + return -WALL_OPEN, max(edge, self._range_at_limit(d.limits["X"][0])[0]) + + def _planning_x_limits(self) -> Optional[Tuple[float, float]]: + """Where Biomek's planner lets X go (cm), from the other pod: when it can be moved out of the + way, this pod's bridge stays 1/16 + 1/64 cm from the other's at the end of its travel; + otherwise as far as touching the other pod's range where it stands (this pod's gripper fully + closed, turned towards it), never less than where this pod is. None: its travel.""" + other = self._other_pod() + if other is None: + return None + assert self.rail is not None and other.declared is not None + d, od = self._require_declared(), other.declared + low, high = d.limits["X"] + reach = d.geometry.bridge_to_head_x_offset + d.geometry.mandrel1_x_offset + if self._pushable(other): + if self.side == "left": + edge = g.bridge_x_range(od.geometry, od.limits["X"][1])[0] + return low, min(high, edge + reach - d.geometry.bridge_x_span - OTHER_POD_GAP) + edge = g.bridge_x_range(od.geometry, od.limits["X"][0])[1] + return max(low, edge + reach + OTHER_POD_GAP), high + taken = self.rail.occupied(other.side) + counts = self._cpositions["X"][0] + if taken is None or counts is None: + return None + x = d.to_value("X", counts) + closed = d.limits["GG"][0] + held = self._held_labware + if self.side == "left": + pose = g.GripperPose(180.0, closed, held) if self.gripper is not None else None + own = self.rail.range_at(self.side, RailPose(x, pose)) + return low, max(x, x + (taken[0] - own[1])) + pose = g.GripperPose(0.0, closed, held) if self.gripper is not None else None + own = self.rail.range_at(self.side, RailPose(x, pose)) + return min(x, x + (taken[1] - own[0])), high + + def _planning_world(self) -> Optional[obstacles.Obstacles]: + """What Biomek's planner plans this pod against: the deck's obstacles (`_world`, nothing + exempt) and the other pod as a wall over all Y and Z (`_other_pod_wall`). The move checks + leave the other pod to the rail (`XRail`).""" + world = self._world(self.pod_number) + wall = self._other_pod_wall() + if world is None or wall is None: + return world + key = (id(world), wall) + if self._planning_cache is None or self._planning_cache[0] != key: + part = obstacles.obstacle_part( + f"the {OTHER[self.side]} pod", wall, (None, None), (None, None) + ) + self._planning_cache = ( + key, + obstacles.Obstacles((*world.structure, part), world.deck, world.holders), + ) + return self._planning_cache[1] + + def _clear( + self, + moves: Sequence[merge.Move], + start: Optional[Mapping[str, motion.CPos]] = None, + ) -> bool: + """Whether each of `moves` (axis targets, counts), made in order from `start` (where the pod + is by default), passes the pod's own check and the deck check, as a sweep; planning exempts no + deck position, as Biomek's does, and plans around the other pod (`_planning_world`). A move + whose start or end is not known is left to `move_axes`.""" + d = self._require_declared() + world = self._planning_world() + positions: Dict[str, motion.CPos] = dict(self._cpositions if start is None else start) + for move in moves: + try: + after = self._planned(positions, move) + except ValueError: + return False + a, b = self._pose(positions), self._pose(after) + if a is None or b is None: + return True + if not check.move_clear(d, a, b, world): + return False + positions = after + return True + + def _at_angle(self, counts: int) -> bool: + """Whether GR is at the angle of `counts` (not a whole turn away: Biomek's GR is a line).""" + d = self._require_declared() + now = self._cpositions["GR"][0] + if now is None: + return False + return abs(d.to_value("GR", now) - d.to_value("GR", counts)) < GR_SAME_ANGLE async def _travel_gripper( self, @@ -477,30 +715,123 @@ async def _travel_gripper( speed: int = 1000, minimum_traverse_height: Optional[float] = None, ) -> MoveResult: - """Take the gripper to `targets` (counts: X, GY, GR) clear of the deck and of the pod's own - pipettor: the channels raised (`_move_over`), the probes moved out of its way - (`_make_room_for_gripper`), the gripper at the highest height that clears the pod's own parts - for the turn (`_gripper_traverse_height`), lowered to it first if it is above.""" - d = self._require_declared() + """Take the gripper to `targets` (counts: X, GY, GR) as Biomek's gripper approach does: on a + Span-8 the probes' span narrowed first (`_minimize_span`), then the planned travel + (`_move_over`): the channels and the gripper at their travel heights, the gripper turned to + the angle given, Biomek's search where the direct way is not clear. Planned: no deck position + exempt (`_planning`).""" await self._read_unknown_positions() - await self._make_room_for_gripper(targets) - gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1])) - gz = self._gripper_traverse_height(gr) - if d.to_counts("GZ", gz) < self._cpositions["GZ"][1]: - await self.move_axes({"GZ": d.to_counts("GZ", gz)}, speed) - return await self._move_over( - targets, speed, minimum_traverse_height=minimum_traverse_height, gripper_height=gz - ) + with self._planning(): + await self._minimize_span(speed) + return await self._move_over(targets, speed, minimum_traverse_height=minimum_traverse_height) # -- the shared X rail --------------------------------------------------------- - def _rail_pose(self, x: int, gr: Optional[int], gg: Optional[int]) -> PodPose: - """A pose in counts as the rail takes it: deck X, and the gripper in degrees and cm.""" + def _rail_pose( + self, + x: int, + gr: Optional[int], + gg: Optional[int], + held: Union[g.HeldLabware, None, Literal["checked"]] = "checked", + ) -> RailPose: + """A pose in counts as the rail takes it: deck X, and the gripper in degrees and cm holding + `held`; by default ("checked") what it held at its last move checked on the rail + (`_rail_held`): what the other pod is checked against changes only through a checked move of + this one.""" d = self._require_declared() gripper = None if gr is not None and gg is not None: - gripper = g.GripperPose(d.to_value("GR", gr), d.to_value("GG", gg), self._held_labware) - return PodPose(d.to_value("X", x), gripper) + what = self._rail_held if held == "checked" else held + gripper = g.GripperPose(d.to_value("GR", gr), d.to_value("GG", gg), what) + return RailPose(d.to_value("X", x), gripper) + + async def _make_way(self, start: RailPose, end: RailPose) -> None: + """Biomek's clearing of the way, before a move that changes what the pod takes up along the rail: when + the X it sweeps from `start` to `end` meets the other pod's range (edges on the 1/16 cm grid, + as the rail guard has them), the other pod moves away on its own first (`_step_aside`). Only an + idle other pod moves (`_idle`); otherwise, or with the driver's `make_way` off, the rail + guard decides (it waits for a move in flight to end, else refuses). + + Raises: + RailCollisionError: if the other pod has no way out of the zone; nothing of this move is + sent. + """ + driver, rail, other = self.driver, self.rail, self._other_pod() + if driver is None or rail is None or other is None or not driver.make_way: + return + await rail.ensure_known(other.side) # as the rail guard reads it: no motion + taken = rail.occupied(other.side) + zone = rail.swept(self.side, start, end) + if taken is None or not g.grid_overlap(zone, taken) or other._busy or other._motion.locked(): + return + async with other._motion: # as before any move of it: what it has not read yet, read + await other._read_unknown_positions() + if other._idle(): + await other._step_aside(zone) + + def _idle(self) -> bool: + """Whether the other pod's clearing of its way may move this pod: no move of its own running or waiting + (`_motion`), no operation under way (`_busy`: a travel, a step), no prime running, nothing in + flight on the rail, its pose known and clear of every deck position (not down in a well or a + wash station).""" + if self._motion.locked() or self._busy or self.declared is None: + return False + if self.pipettes is not None and self.pipettes._priming is not None: + return False + if self.rail is not None and self.rail.in_flight(self.side): + return False + pose = self._pose() + if pose is None: + return False + world = self._world(self.pod_number) + if world is None: + return True # no deck to be in: the move aside rises as high as it goes first + out = check.escape(self.declared, pose, world) + return out is not None and not out.holders + + async def _step_aside(self, zone: g.Range) -> None: + """Move this pod out of the X `zone` the other pod's move needs, as Biomek's clearing of the way moves it: + away from the other pod, so that its near edge is at the next 1/16 cm grid line past the zone + plus 1/64 cm, its gripper turned to the nearest quarter turn; if that has no path, once more + with the gripper at 0 degrees (90 if the nearest quarter was 0). A planned move (`_move_over`) + whose X stays on this pod's side of where it stands; what it holds moves at its labware + speed. + + Raises: + RailCollisionError: if neither way out has a path; the pod may have risen. + """ + self._tell("step aside", zone) + d = self._require_declared() + rail = self.rail + assert rail is not None + counts = {n: self._cpositions[n][0] for n in RAIL_AXES} + if any(c is None for c in counts.values()): + raise RailCollisionError(f"{self}: its position is not known, so it cannot move aside") + x, gr, gg = (d.to_value(n, cast(int, counts[n])) for n in RAIL_AXES) + speed = 1000 + if self.gripper is not None and self.gripper._held is not None: + speed = self.gripper._held_speed + refused: List[str] = [] + ways = destinations.step_aside( + d, self.side, x, gr, gg, self._held_labware, zone, + lambda at, gripper: rail.range_at(self.side, RailPose(at, gripper)), + ) # fmt: skip + for turn, target, bounds in ways: + if not bounds[0] <= target <= bounds[1]: + refused.append(f"GR {turn:g}: X {target:.3f} is beyond its travel") + continue + targets = {"X": d.to_counts("X", target)} + if d.gripper_model: + targets["GR"] = d.to_counts("GR", turn) + logger.info( + "%s moves aside to X %.3f, GR %g (clearing the way)", self.component, target, turn + ) + try: + await self._move_over(targets, speed, x_bounds=bounds) + return + except (RailCollisionError, check.PodCollisionError) as e: + refused.append(f"GR {turn:g}: {e}") + raise RailCollisionError(f"{self} cannot move out of the other pod's way: {'; '.join(refused)}") def _require_declared(self) -> PodConfiguration: if self.declared is None: @@ -514,6 +845,21 @@ def add_position_listener(self, listener: Callable[["Pod"], None]) -> Callable[[ self._listeners.append(listener) return lambda: self._listeners.remove(listener) + def add_motion_listener(self, listener: Callable[["Pod", str, Any], None]) -> Callable[[], None]: + """Call `listener(pod, event, detail)` as the pod moves: `"move"` with (targets, speed) for each + `move_axes` (before it is checked), `"rise out of"` with the deck positions a planned + operation leaves straight up, `"step aside"` with the X zone (cm) the other pod's move needs. + Returns what removes it. A listener that raises is logged and kept.""" + self._motion_listeners.append(listener) + return lambda: self._motion_listeners.remove(listener) + + def _tell(self, event: str, detail: Any) -> None: + for listener in list(self._motion_listeners): + try: + listener(self, event, detail) + except Exception: + logger.exception("%s: motion listener %r failed", self, listener) + def _positions_changed(self) -> None: self._tell_rail() for listener in list(self._listeners): @@ -532,7 +878,7 @@ def _tell_rail(self) -> None: pose = self._rail_pose(x, self._cpositions["GR"][0], self._cpositions["GG"][0]) self.rail.update(self.side, pose) - async def request_rail_pose(self) -> PodPose: + async def request_rail_pose(self) -> RailPose: """Where the pod is along the rail, as its drives report X, GR and GG. Moves nothing.""" axes = [self.axis(n) for n in ("X", "GR", "GG")] replies = await self.board.send_many([p.get_current_position(a.device, a.index) for a in axes]) @@ -555,10 +901,12 @@ async def move_axes( each was last set to (`pipettes.set_valves`), at the cutoff velocity last set (an aspirate's or dispense's `cutoff_velocity`), as the Master Controller carries both. - A move of X, GR or GG is checked against the other pod first (`driver/x_rail.py`). One that - would run into it is refused, and nothing is sent. One crossing only the path of the other - pod's move in flight waits for that move to finish. Whether the pod may move now (interlock - armed) is the caller's to decide. + A move of X, GR or GG, or the first move since the gripper took or let go of labware, is + checked against the other pod first (`driver/x_rail.py`). When it would run into the other + pod and that pod is idle, the other pod moves aside first, as Biomek's clearing of the way + (`_make_way`; the driver's `make_way`); otherwise it is refused, and nothing is sent. One + crossing only the path of the other pod's move in flight waits for that move to finish. + Whether the pod may move now (interlock armed) is the caller's to decide. Args: targets: target per axis name. On a Span-8, also `Y` (channel 1) and `S` (the span from @@ -584,8 +932,20 @@ async def move_axes( NotHomedError: if an axis has not been homed; its pending moves are dropped. RailCollisionError: if X, GR or GG would move into the other pod's range; nothing is sent. PodCollisionError: if the gripper (or what it holds) would meet the pod's own pipettor on - the way (`pod_collision`); nothing is sent. + the way (`planning.check`); nothing is sent. """ + self._tell("move", (dict(targets), speed)) + async with self._motion: # one move at a time, whichever task sends it + return await self._move(targets, speed, forces, sensors) + + async def _move( + self, + targets: Mapping[str, int], + speed: int, + forces: Optional[Mapping[str, float]], + sensors: Optional[Mapping[str, Tuple[int, int]]], + ) -> MoveResult: + """`move_axes`, under the pod's move lock (`_motion`).""" forces, sensors = dict(forces or {}), dict(sensors or {}) given, targets = dict(targets), dict(targets) if self.module_type == "span8" and ("Y" in targets or "S" in targets): @@ -612,6 +972,7 @@ async def move_axes( f"{self}: force {force} on {name}: not a motor, or outside 0..{p.MAX_FORCE}" ) uses_pumps = any(self.axis(n).is_pump for n in targets) + pushing = False # while the other pod moves aside: what fails there is not this pod's move try: await self._read_unknown_positions(pumps=uses_pumps) motions, timeout_ms, after = motion.plan_move( @@ -630,19 +991,30 @@ async def move_axes( if not motions: return MoveResult() self._check_own_collision(self._cpositions, after, {m.axis for m in motions}) - if self.rail is not None and any(m.axis in RAIL_AXES for m in motions): - start = self._rail_pose(*(self._cpositions[n][0] or 0 for n in RAIL_AXES)) - end_counts = [after[n][0] or 0 for n in RAIL_AXES] + self._check_world_collision(self._cpositions, after) + held = self._held_labware + if self.rail is not None and ( + any(m.axis in RAIL_AXES for m in motions) or held != self._rail_held + ): + x0, gr0, gg0 = (self._cpositions[n][0] or 0 for n in RAIL_AXES) + start = self._rail_pose(x0, gr0, gg0, held) + x1, gr1, gg1 = (after[n][0] or 0 for n in RAIL_AXES) if "GG" in forces: # stops on what it grips, short of its target: count the wider end - end_counts[2] = max(end_counts[2], self._cpositions["GG"][0] or 0) - end = self._rail_pose(*end_counts) + gg1 = max(gg1, gg0) + end = self._rail_pose(x1, gr1, gg1, held) + pushing = True + await self._make_way(start, end) + pushing = False async with self.rail.moving(self.side, start, end): completions = await self._send_motions(motions, timeout_ms, forces, sensors) + self._rail_held = held else: completions = await self._send_motions(motions, timeout_ms, forces, sensors) - except (RailCollisionError, pc.PodCollisionError): + except (RailCollisionError, check.PodCollisionError): raise # refused before anything was sent: every position is as it was except BaseException as e: + if pushing: + raise # the other pod's move aside failed (it says so itself); this pod sent nothing # As the Master Controller after a failed command, and its reply, so a # session's log reads as Biomek's: "#AM The left X motion failed: ...". self._forget_positions() @@ -675,33 +1047,77 @@ def channel_z_axes(self) -> List[str]: a.name for a in self.axes if a.name == "Z" or (a.name[0] == "Z" and a.name[1:].isdigit()) ] - def _traverse_heights(self) -> Dict[str, float]: - """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default, cm - of its bottom above the deck: its ceiling (`_traverse_ceilings`), or - `default_minimum_traverse_height` where that is lower.""" - ceilings = self._traverse_ceilings() - wanted = units.optional_cm(self.default_minimum_traverse_height) - return { - name: top if wanted is None or name == "GZ" else min(wanted, top) - for name, top in ceilings.items() - } + def _traverse_heights( + self, + targets: Optional[Mapping[str, int]] = None, + tip_lengths: Optional[Mapping[str, float]] = None, + ) -> Dict[str, float]: + """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default on + the way to `targets` (counts; None: where it stands), cm of its bottom above the deck: per + tool, its `traverse_defaults` ("safe": `_safe_heights`, and as high as it goes without a deck + to reckon from; "max": `_max_traverse_heights`; a height: its lowest point there), never above + its `_max_traverse_heights`. `tip_lengths`: per channel, cm; the pod's record when None.""" + lengths = self._carried_tip_lengths() if tip_lengths is None else dict(tip_lengths) + tops = self._max_traverse_heights() + tools = {"channels": self.channel_z_axes, "gripper": [a for a in ("GZ",) if a in tops]} + safe: Optional[Dict[str, float]] = None + out: Dict[str, float] = {} + for tool, axes in tools.items(): + mode = self.traverse_defaults[tool] + if mode == "safe" and safe is None: + safe = self._safe_heights(targets, lengths) or {} + for axis in axes: + if mode == "max": + height = tops[axis] + elif mode == "safe": + height = (safe or {}).get(axis, tops[axis]) + else: + height = units.to_cm(float(mode)) + ( + lengths.get(axis, 0.0) if axis != "GZ" else self._gripper_below() + ) + out[axis] = min(height, tops[axis]) + return out + + def _gripper_below(self) -> float: + """How far below GZ (cm) the gripper's lowest point is: its fingers, or what it holds.""" + pose = self._pose() + if self.declared is None or pose is None or pose[1] is None: + return 0.0 + return pod_model.gripper_below(self.declared, pose[0], pose[1]) + + def _safe_heights( + self, + targets: Optional[Mapping[str, int]] = None, + tip_lengths: Optional[Mapping[str, float]] = None, + ) -> Optional[Dict[str, float]]: + """Biomek's safe height for each Z-type axis on the way to `targets` (counts; None: where it + stands), cm: the tallest deck item (`traverse.deck_height`) under each tool's footprint swept + from here to there, floored by `GlobalMinSafeHeight` and the axis's lowest reach, plus the + tool's own: a channel's tip (or the 96-head's `SubMandrelSafeHeight` without one) and + `AdditionalSafeHeight`; the gripper's offset to its lowest point (what it holds included) and + `AdditionalSafeHeightGripper`; `AvoidanceMargin` on every one. None without a deck to reckon + from (no device, or an unknown position).""" + d = self.declared + own = self._world(self.pod_number) + start = self._pose() + if d is None or own is None or start is None: + return None + end = self._pose(self._planned(self._cpositions, targets or {})) + if end is None: + return None + # What the way covers, and how tall it is, from the deck check's own boxes for this pod (its + # own calibration of each position, the frame its parts are in), exempting none: a travel at + # this height is one the check passes. + lengths = self._carried_tip_lengths() if tip_lengths is None else tip_lengths + return traverse.safe_heights(d, start, end, own, lengths, self.channel_z_axes) - def _traverse_ceilings(self) -> Dict[str, float]: + def _max_traverse_heights(self) -> Dict[str, float]: """The highest each Z-type axis travels, cm of its bottom above the deck: the top of travel less the park margin (`ParkLocation` `ZMargin`, `GZMargin`), as Biomek parks them (the Multichannel's rest Z, 39.763 cm, is -256 counts). A Span-8 probe goes no higher than its top less `DiscardOffset`: above that its stripper pushes a tip off (Biomek travels carrying probes there, as its logs show).""" - d = self._require_declared() - shuck = d.settings.get("DiscardOffset") if self.module_type == "span8" else None - ceilings = {} - for name in self.channel_z_axes + ["GZ"]: - top = d.limits[name][1] - ceiling = top + d.park.get("GZMargin" if name == "GZ" else "ZMargin", 0.0) - if shuck is not None and name != "GZ": - ceiling = min(ceiling, top - shuck) - ceilings[name] = ceiling - return ceilings + return traverse.max_traverse_heights(self._require_declared(), self.channel_z_axes) async def park(self) -> None: """Biomek's park (`_park`): the channels and the gripper raised, the pod to its park X and Y, @@ -711,7 +1127,7 @@ async def park(self) -> None: async def _park(self, over: Optional[Mapping[str, int]] = None) -> None: """Biomek's park (`ParkLocation`): the channels and the gripper raised to their ceilings - (`_traverse_ceilings`), the pod to the park X (`XMargin` in from its own end of the rail) and + (`_max_traverse_heights`), the pod to the park X (`XMargin` in from its own end of the rail) and `Y`, the gripper turned and closed to its park (`GR`, `GY`, then `GG`). As logged after a prime (2026-10-09), to the count. `over`: X/Y targets (counts) for a pod whose park declares none; a Span-8 parks over its wash station (`pipettes.park`). Without either, it parks where @@ -725,37 +1141,34 @@ async def _park(self, over: Optional[Mapping[str, int]] = None) -> None: raise RuntimeError(f"{self} needs a declared configuration") if self._held_labware is not None: raise RuntimeError(f"{self}: the gripper holds labware; place it before parking") - p = d.park - targets: Dict[str, int] = dict(over or {}) - if "XMargin" in p and "X" not in targets: - low, high = d.limits["X"] - x = low + p["XMargin"] if self.side == "left" else high - p["XMargin"] - targets["X"] = d.to_counts("X", x) - if "Y" in p and "Y" not in targets: - targets["Y"] = d.to_counts("Y", p["Y"]) - targets.update({a: d.to_counts(a, p[a]) for a in ("GR", "GY") if a in p}) + targets = destinations.park_targets(d, self.side, over) + # Biomek's park raises the channels and the gripper as high as they go first, whatever the + # travel defaults (`traverse_defaults`): it is where the pod rests, not a travel. + await self._read_unknown_positions() + await self._rise(self._max_traverse_heights(), 1000) await self._move_over(targets) - # The channels rest at the top less the park margin, and on a Span-8 less `DiscardOffset` as - # well (39.1079 cm on Z1, 9029 counts: lower than the probes travel, `_traverse_ceilings`). - shuck = d.settings.get("DiscardOffset", 0.0) if self.module_type == "span8" else 0.0 - rest = { - z: d.to_counts(z, d.limits[z][1] + p.get("ZMargin", 0.0) - shuck) for z in self.channel_z_axes - } + rest = destinations.rest_heights(d, self.channel_z_axes) if any(self.cpositions[z][1] != c for z, c in rest.items()): await self.move_axes(rest) - if "GG" in p: - # Closed under the grip force, as Biomek's park closes it (it may stop on its own fingers). - force = d.settings["GripperSqueezeForce"] - await self.move_axes({"GG": d.to_counts("GG", p["GG"])}, forces={"GG": force}) - # The force leaves GG's position unknown, and the rail counts an unknown gripper as every - # pose it could take, in the other pod's way: read it back now. - await self._read_unknown_positions() + await self._close_gripper() + + async def _close_gripper(self) -> None: + """Close the empty gripper to its park width (`GG`), under the grip force, as Biomek's park + closes it (it may stop on its own fingers). Nothing without a park width.""" + d = self._require_declared() + if "GG" not in d.park: + return + force = d.settings["GripperSqueezeForce"] + await self.move_axes({"GG": d.to_counts("GG", d.park["GG"])}, forces={"GG": force}) + # The force leaves GG's position unknown, and the rail counts an unknown gripper as every + # pose it could take, in the other pod's way: read it back now. + await self._read_unknown_positions() async def move_aside(self) -> None: - """Raise the pod and take it to the end of its X travel on its own side (the left pod to its - lowest X, the right pod to its highest), leaving the other pod the most of the rail. Biomek - moves a pod out of the way itself; the rail guard here refuses instead - (`x_rail.py`), so a caller makes room with this. + """Fold the gripper where the pod stands: drawn in to its park GY, then turned to its park GR + (with what it holds), and closed to its park width when empty. Its range along the rail is + then its smallest; the X room another pod's move needs is made by clearing the way (`_make_way`), which moves an + idle pod aside on its own (`_make_way`). Raises: RuntimeError: without a declared configuration. @@ -763,8 +1176,15 @@ async def move_aside(self) -> None: d = self.declared if d is None: raise RuntimeError(f"{self} needs a declared configuration") - low, high = d.limits["X"] - await self._move_over({"X": d.to_counts("X", low if self.side == "left" else high)}) + # Drawn in first, so what it holds turns close to the pod. + for axis in ("GY", "GR"): + if d.gripper_model and axis in d.park: + target = d.to_counts(axis, d.park[axis]) + if not (self._at_angle(target) if axis == "GR" else self._cpositions[axis][1] == target): + await self._travel_gripper({axis: target}) + if self._held_labware is None and "GG" in d.park and d.gripper_model: + if self._cpositions["GG"][1] > d.to_counts("GG", d.park["GG"]): + await self._close_gripper() # open fingers reach further: closed, as parked async def _move_over( self, @@ -772,10 +1192,9 @@ async def _move_over( speed: int = 1000, minimum_traverse_height: Optional[float] = None, z_final: Optional[float] = None, - clearance: Optional[float] = None, - allow_below_clearance: bool = False, tip_lengths: Optional[Mapping[str, float]] = None, gripper_height: Optional[float] = None, + x_bounds: Optional[Tuple[float, float]] = None, ) -> MoveResult: """Travel to `targets` (X, Y and the like, in counts, as `move_axes` takes them) clear of the deck: lift the channels and the gripper to a traverse height, move, then optionally set the @@ -788,60 +1207,90 @@ async def _move_over( Args: targets: the travel's targets; channel Z axes in them are refused (use `z_final`). speed: as `move_axes`, for every step. - minimum_traverse_height: the channels' lowest points while traveling. Default: each channel - at `_traverse_heights` (as high as it goes). The gripper travels at its default - always. + minimum_traverse_height: the channels' lowest points while traveling. Default: their tool's + `traverse_defaults` (`_traverse_heights`). The gripper travels at its own default. z_final: where to set the channels' bottoms once there; None leaves them at the traverse height. - clearance: the lowest height the deck under the path allows, from the deck model - (`BiomekI7._traverse_clearance`), if known. - allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately. tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, cm. The pod's own record when None (`_carried_tip_lengths`). - gripper_height: GZ (cm) to travel at. Default: its traverse height, no higher than clears - the pod's own pipettor for the travel's GR (`_gripper_traverse_height`). + gripper_height: GZ (cm) to travel at, lowered to it first if it is above. Default: its + traverse height (`_traverse_heights`). + x_bounds: where X may go on the way (cm), within its travel; None: anywhere. Raises: - ValueError: for a channel Z axis in `targets`; for a path through a wall (a shield, a - tower, the light curtain); for a traverse height below what the path needs (unless - `allow_below_clearance`), a need above what the channels reach, or a height a channel - cannot lift its tip to (under its `_traverse_ceilings`). Nothing is sent. + ValueError: for a channel Z axis in `targets`, or a height a channel cannot lift its tip to + (under its `_max_traverse_heights`). Nothing is sent. + DeckCollisionError: for a travel the deck check refuses (too low over something, or through + a wall). Nothing is sent. """ - d = self._require_declared() - channels = self.channel_z_axes - stray = sorted(set(targets) & set(channels)) + self._require_declared() + stray = sorted(set(targets) & set(self.channel_z_axes)) if stray: raise ValueError(f"{self}: {stray} in a travel's targets; use z_final") lengths = self._carried_tip_lengths() if tip_lengths is None else dict(tip_lengths) await self._read_unknown_positions() - area = self._travel_area(targets) - need = g.obstacle_clearance(d.obstacles, *area) - if need.walls: - raise ValueError(f"{self}: the travel would pass through {', '.join(need.walls)}") - required = max(need.height, -math.inf if clearance is None else clearance) - heights, reach, traverse = self._traverse_targets(minimum_traverse_height, lengths) - if required > reach: - raise ValueError(f"{self}: the path needs {required:.3f} cm, above what the channels reach") - if traverse < required and not allow_below_clearance: - raise ValueError( - f"{self}: traverse height {traverse:.3f} cm is below the {required:.3f} cm the path needs;" - " pass allow_below_clearance=True to travel lower deliberately" - ) - if gripper_height is None: - # No higher than clears the pod's own pipettor for the gripper's angle, and its turn if the - # travel turns it; only that lowers it (an axis above its traverse height stays there). - gr = d.to_value("GR", targets.get("GR", self._cpositions["GR"][1])) - clear = self._gripper_traverse_height(gr) - if clear < heights["GZ"]: - gripper_height = clear + with self._planning(): + return await self._travel_over(targets, speed, minimum_traverse_height, z_final, lengths, + gripper_height, x_bounds) # fmt: skip + + async def _travel_over( + self, + targets: Mapping[str, int], + speed: int, + minimum_traverse_height: Optional[float], + z_final: Optional[float], + lengths: Mapping[str, float], + gripper_height: Optional[float], + x_bounds: Optional[Tuple[float, float]] = None, + ) -> MoveResult: + """`_move_over`'s travel: every stage planned (the gripper lowered to `gripper_height`, the rise + with the way out of any position the pod stands in, the travel, the descent to `z_final`), as + Biomek plans a call whole, then executed; a stage with no path refuses the whole travel and + nothing is sent. Returns the travel's last move's result.""" + d = self._require_declared() + heights, _, _ = self._traverse_targets(minimum_traverse_height, lengths, targets) + at: Dict[str, motion.CPos] = dict(self._cpositions) + plan: List[PlanStep] = [] if gripper_height is not None: heights["GZ"] = gripper_height - if d.to_counts("GZ", gripper_height) < self._cpositions["GZ"][1]: - await self.move_axes({"GZ": d.to_counts("GZ", gripper_height)}, speed) - await self._raise_to(heights, speed) - result = await self.move_axes(targets, speed) + lower = {"GZ": d.to_counts("GZ", gripper_height)} + if lower["GZ"] < at["GZ"][1]: + plan.append((lower, ())) + at = self._planned(at, lower) + escape, at = self._plan_escape(heights, at) + plan += escape + # The rise, the travel and the descent, each planned from where the one before leaves the pod, + # then merged as one path (`_merged`), as Biomek concatenates and merges its stages. + merged_from = at + path = self._plan_lift(heights, at) + for move in path: + at = self._planned(at, move) + # Biomek's direct candidate; when one of its own moves is not clear, Biomek's search. + try: + travel = find_path.travel( + targets, self._clear_from(at), lambda to: self._search(to, x_bounds, at) + ) + except search.NoPathError as e: + raise check.DeckCollisionError(f"{self}: no clear path for the travel: {e}") from e + for move in travel: + at = self._planned(at, move) + path += travel if z_final is not None: - await self.move_axes({n: d.to_counts(n, z_final) for n in channels}, speed) + # Straight down; when that is not clear, Biomek's descent stage: the search to the whole + # destination, down only near it. + final = {n: d.to_counts(n, z_final) for n in self.channel_z_axes} + path += self._direct_or_searched(final, {**targets, **final}, "the descent", x_bounds, at) + merged = self._merged(path, merged_from) + # The travel's result: its last move that moves a target's axis. + last_travel = max( + (len(plan) + i for i, move in enumerate(merged) if set(move) & set(targets)), default=-1 + ) + plan += [(move, ()) for move in merged] + result = MoveResult() + for i, step in enumerate(plan): + done = await self._run_step(step, speed) + if i == last_travel: + result = done return result async def move_over( @@ -850,8 +1299,6 @@ async def move_over( speed_fraction: float = 1.0, minimum_traverse_height: Optional[float] = None, z_final: Optional[float] = None, - clearance: Optional[float] = None, - allow_below_clearance: bool = False, tip_lengths: Optional[Mapping[str, float]] = None, gripper_height: Optional[float] = None, ) -> MoveResult: @@ -871,12 +1318,10 @@ async def move_over( `traverse_heights`. z_final: where to set the channels' bottoms once there, mm; None leaves them at the traverse height. - clearance: the lowest height the deck under the path allows, mm (`traverse_clearance`). - allow_below_clearance: travel lower than `clearance` and the obstacles allow, deliberately. tip_lengths: per channel Z axis, how far below its bottom the tip it carries ends, mm. The pod's own record when None (`carried_tip_lengths`). - gripper_height: GZ, mm, to travel at. Default: its traverse height, no higher than clears - the pod's own pipettor. + gripper_height: GZ, mm, to travel at, lowered to it first if it is above. Default: its + traverse height (`traverse_heights`). Raises: ValueError: as `_move_over`, its Biomek-unit counterpart; for a `speed_fraction` outside @@ -887,8 +1332,6 @@ async def move_over( units.fraction_to_field(speed_fraction), minimum_traverse_height=units.optional_cm(minimum_traverse_height), z_final=units.optional_cm(z_final), - clearance=units.optional_cm(clearance), - allow_below_clearance=allow_below_clearance, tip_lengths=( None if tip_lengths is None else {a: units.to_cm(v) for a, v in tip_lengths.items()} ), @@ -904,14 +1347,15 @@ def carried_tip_lengths(self) -> Dict[str, float]: return {axis: units.to_mm(v) for axis, v in self._carried_tip_lengths().items()} def traverse_heights(self) -> Dict[str, float]: - """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default, mm - of its bottom above the deck: its ceiling (`traverse_ceilings`), or - `default_minimum_traverse_height` where that is lower.""" + """The height each Z-type axis (the channels' and the gripper's GZ) travels at by default + where it stands, mm of its bottom above the deck: per tool, its `traverse_defaults` + (`_traverse_heights`).""" return {axis: units.to_mm(v) for axis, v in self._traverse_heights().items()} - def traverse_ceilings(self) -> Dict[str, float]: - """The highest each Z-type axis travels, mm of its bottom above the deck (`_traverse_ceilings`).""" - return {axis: units.to_mm(v) for axis, v in self._traverse_ceilings().items()} + def max_traverse_heights(self) -> Dict[str, float]: + """As high as each Z-type axis travels, mm of its bottom above the deck + (`_max_traverse_heights`).""" + return {axis: units.to_mm(v) for axis, v in self._max_traverse_heights().items()} def _carried_tip_lengths(self) -> Dict[str, float]: """Per channel Z axis carrying a tip, how far below the channel the tip ends, cm: from the @@ -924,7 +1368,10 @@ def _carried_tip_lengths(self) -> Dict[str, float]: return {} if feature is None else feature._carried_tip_lengths() def _traverse_targets( - self, minimum_traverse_height: Optional[float], tip_lengths: Mapping[str, float] + self, + minimum_traverse_height: Optional[float], + tip_lengths: Mapping[str, float], + targets: Optional[Mapping[str, int]] = None, ) -> Tuple[Dict[str, float], float, float]: """Where each Z-type axis's bottom goes to travel, cm; the highest every channel's lowest point reaches; and how high the lowest one travels. By default each at `_traverse_heights` @@ -936,8 +1383,8 @@ def _traverse_targets( """ channels = self.channel_z_axes lengths = {n: tip_lengths.get(n, 0.0) for n in channels} - heights = self._traverse_heights() - ceilings = self._traverse_ceilings() + heights = self._traverse_heights(targets, lengths) + ceilings = self._max_traverse_heights() reach = min(ceilings[n] - lengths[n] for n in channels) if minimum_traverse_height is None: return heights, reach, min(heights[n] - lengths[n] for n in channels) @@ -972,26 +1419,157 @@ async def _lift_channels( await self._raise_to({n: heights[n] for n in self.channel_z_axes}, speed) async def _raise_to(self, heights: Mapping[str, float], speed: int) -> None: - """Move the axes below their `heights` (cm) up to them, together.""" + """Move the axes below their `heights` (cm) up to them, together: a direct, checked move (an + operation's own rise, out of the positions it works in).""" + lift = self._lift_targets(heights) + if lift: + await self.move_axes(lift, speed) + + def _lift_targets( + self, heights: Mapping[str, float], at: Optional[Mapping[str, motion.CPos]] = None + ) -> Dict[str, int]: + """The axes below their `heights` (cm) in `at` (the position record by default), with those + heights in counts.""" d = self._require_declared() + positions = self._cpositions if at is None else at lift = {} for name, height in heights.items(): counts = d.to_counts(name, height) - if self._cpositions[name][1] < counts: # counts grow with height on every Z-type axis + if positions[name][1] < counts: # counts grow with height on every Z-type axis lift[name] = counts - if lift: - await self.move_axes(lift, speed) + return lift + + @contextlib.contextmanager + def _planning(self) -> Iterator[None]: + """Within it, a planned operation (a travel, an approach, a move to safe heights, park): no + deck position is exempt from the deck check, as Biomek's planner exempts none, whatever + operation it is part of.""" + before = self._working_at + self._working_at = () + self._busy += 1 + try: + yield + finally: + self._working_at = before + self._busy -= 1 + + async def _rise(self, heights: Mapping[str, float], speed: int) -> None: + """Biomek's planned move to safe heights: the axes below their `heights` (cm) up to them, + planned whole (the way out of any position, `_plan_escape`; the rise, `_plan_lift`, merged) + then executed, nothing exempt (`_planning`). - def _travel_area(self, targets: Mapping[str, int]) -> Tuple[g.Range, g.Range]: - """The X/Y area the pod's body covers from where it is to `targets`, cm.""" + Raises: + DeckCollisionError: as `_plan_escape` and `_plan_lift`. Nothing is sent. + """ + with self._planning(): + plan, at = self._plan_escape(heights, self._cpositions) + plan += [(move, ()) for move in self._merged(self._plan_lift(heights, at), at)] + for step in plan: + await self._run_step(step, speed) + + def _plan_escape( + self, heights: Mapping[str, float], start: Mapping[str, motion.CPos] + ) -> Tuple[List[PlanStep], Dict[str, motion.CPos]]: + """The way out of the deck positions a pod at `start` stands in (left low in one by the + operation before), as Biomek's planner leaves them when its start is in collision; and where + it leaves the pod. Each part inside them (a channel, a Span-8's probes one by one, or the + gripper) straight up until its bottom is at their tops, or to its height in `heights` (cm) if + that is higher, the others staying; one step, checked against everything but those positions + (the step names them), its end clear of everything. None for a pod inside nothing. + + Raises: + DeckCollisionError: if the pod stands inside something other than a deck position's box + (a trash's walls, the instrument), or cannot rise out within its axes' travel. + """ d = self._require_declared() - y_axis = "Y" if self.module_type == "multichannel" else "Y1" - x0 = d.to_value("X", self._cpositions["X"][1]) - y0 = d.to_value("Y", self._cpositions[y_axis][1]) - x1 = d.to_value("X", targets.get("X", self._cpositions["X"][1])) - y1 = d.to_value("Y", targets.get("Y", targets.get(y_axis, self._cpositions[y_axis][1]))) - (ax, ay), (bx, by) = g.pod_xy_box(d.geometry, x0, y0), g.pod_xy_box(d.geometry, x1, y1) - return g.union(ax, bx), g.union(ay, by) + at: Dict[str, motion.CPos] = dict(start) + plan: List[PlanStep] = [] + pose = self._pose(at) + world = self._planning_world() + if pose is not None and world is not None: + # The planner's model: the gripper padded below (`pod_model.planning_pad`). + pad = pod_model.planning_pad(d) + out = check.escape(d, pose, world, pad) + if out is None: + found = check.deck_collisions_at(d, pose, world, pad) + parts = ", ".join(f"the {x} in {y}" for x, y in found[:3]) + raise check.DeckCollisionError(f"{self}: no way out planned for {parts}") + if out.holders: + targets = find_path.escape_targets(d, pose, out, heights, self.channel_z_axes) + beyond = [n for n, t in targets.items() if t > self.axis(n).limits.max_position] + if beyond: + raise check.DeckCollisionError(f"{self}: {beyond} cannot rise out of {list(out.holders)}") + after = self._planned(at, targets) + end = self._pose(after) + assert end is not None + if check.deck_collisions_at(d, end, world, pad): + raise check.DeckCollisionError(f"{self}: rising out of {list(out.holders)} is not clear") + plan.append((targets, out.holders)) + at = after + return plan, at + + def _plan_lift( + self, heights: Mapping[str, float], start: Mapping[str, motion.CPos] + ) -> List[merge.Move]: + """The rise from `start`: the axes below their `heights` (cm) up to them, straight up, or + Biomek's rise stage (the search to the heights) when that is not clear; unmerged. + + Raises: + DeckCollisionError: when the search finds no path up. + """ + lift = self._lift_targets(heights, start) + if not lift: + return [] + return self._direct_or_searched(lift, lift, "the rise", None, start) + + def _merged( + self, path: Sequence[merge.Move], start: Mapping[str, motion.CPos] + ) -> List[merge.Move]: + """`path` from `start` merged as Biomek merges a planned path (`merge.merge_path`), every + change checked as `_clear` checks it.""" + counts = {name: c for name, (_, c) in start.items()} + if self.module_type == "span8": + # A Span-8's Y names probe 1 and S is the span, as `motion.span_targets` reads them. + counts["Y"] = counts["Y1"] + counts["S"] = max(counts["Y8"] - counts["Y1"], 0) + return merge.merge_path(path, counts, self._clear_from(start)) + + async def _run_step(self, step: PlanStep, speed: int) -> MoveResult: + """One planned move; one that leaves the positions it names (the way out of them) is made with + those positions exempt.""" + move, leaving = step + if not leaving: + return await self.move_axes(move, speed) + self._tell("rise out of", leaving) + logger.info("%s leaves %s straight up", self.component, ", ".join(leaving)) + with self.working_at(*leaving): + return await self.move_axes(move, speed) + + def _clear_from(self, start: Mapping[str, motion.CPos]) -> Callable[..., bool]: + """`_clear` with its moves made from `start` unless a call gives its own.""" + return lambda moves, at=None: self._clear(moves, start if at is None else at) + + def _direct_or_searched( + self, + move: merge.Move, + destination: Mapping[str, int], + what: str, + x_bounds: Optional[Tuple[float, float]] = None, + start: Optional[Mapping[str, motion.CPos]] = None, + ) -> List[merge.Move]: + """`move` alone from `start` (where the pod is by default) when it is clear (`_clear`); else + Biomek's search's path to `destination` (`_search`), unmerged. + + Raises: + DeckCollisionError: when the search finds no path; nothing is sent. + """ + at = self._cpositions if start is None else start + try: + return find_path.direct_or_searched( + move, destination, self._clear_from(at), lambda to: self._search(to, x_bounds, at) + ) + except search.NoPathError as e: + raise check.DeckCollisionError(f"{self}: no clear path for {what}: {e}") from e async def _send_motions( self, diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py index bf16430c79c..89ccd909dcb 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/gripper_tests.py @@ -11,12 +11,14 @@ Y_CLEARANCE, Gripper, biomek_grip_direction, + held_labware_of, ) from pylabrobot.beckman_coulter.biomek_i7.layouts import place_labware +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_labware +from pylabrobot.resources import Plate, beckman_coulter_biomek_96_wellplate_vb from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( generic_biomek, ) -from pylabrobot.resources import Plate, beckman_coulter_biomek_96_wellplate_vb # Biomek's TiterplateLid widths (open 9.401 cm, close 7.592 cm) on the lid, which PyLabRobot sizes # to its plate's 8.56 cm: per call, as the gripper's defaults are Biomek's margins for labware. @@ -107,10 +109,13 @@ def assert_logged(self, side: str, moves: List) -> None: self.assertEqual(close["GG"], logged["GG close"]) self.assertEqual(moves[i - 1][0], {"GZ": logged["GZ"]}) self.assertEqual(moves[i - 2][0], {"GG": logged["GG open"]}) - travel = moves[i - 3][0] + # Where the travel leaves the gripper (in one move or several, as the planner merges it). + at: Dict[str, int] = {} + for targets, _ in moves[: i - 2]: + at.update(targets) for axis in ("X", "GY", "GR"): if axis in logged: - self.assertAlmostEqual(travel[axis], logged[axis], delta=3, msg=axis) + self.assertAlmostEqual(at[axis], logged[axis], delta=3, msg=axis) async def test_the_left_pod_takes_the_lid_as_logged_without_checks(self) -> None: moves, checks = await self.lid_off_and_on("left") @@ -156,6 +161,7 @@ async def test_a_close_on_nothing_is_refused_on_every_pod(self) -> None: await gripper.pick_up_resource( self.lid, y_clearance=LID_Y_CLEARANCE, squeeze_mm=LID_SQUEEZE_MM ) + self.assertIsNone(gripper._pod._held_labware) # counted from the close, dropped with the grip async def test_a_plate_moves_between_positions(self) -> None: place_labware(self.biomek.deck, [{"position": "P16", "class": "Thermo96VB_PP", "name": "p2"}]) @@ -174,6 +180,16 @@ def test_the_default_widths_are_biomeks(self) -> None: self.assertAlmostEqual(plate.get_size_y() + 2 * Y_CLEARANCE, 97.06) self.assertAlmostEqual(plate.get_size_y() - 2 * SQUEEZE_MM, 78.97) + def test_what_is_held_records_the_definitions_it_was_sized_from(self) -> None: + plate = biomek_labware("Thermo96VB_PP", "plate", lid="default") + held = held_labware_of(plate) + self.assertEqual( + held.source, + "beckman_coulter_biomek_96_wellplate_vb 127.8 x 85.6 x 14.1 mm; " + f"lid beckman_coulter_biomek_lid_titerplatelid {plate.lid.get_size_x():g} x " + f"{plate.lid.get_size_y():g} x {plate.lid.get_size_z():g} mm", + ) + def test_grip_sides_follow_a1(self) -> None: plate = beckman_coulter_biomek_96_wellplate_vb("plate") # Where the fingers point: "A1 near" has the hand on A1's side, the left at rotation 0. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py index b8942adbb0b..4f663cc0ede 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/liquid_tests.py @@ -122,6 +122,13 @@ async def setup_deck(self): # type: ignore[no-untyped-def] right = self.pod(driver, "right") park = right.declared.park # type: ignore[union-attr] await right.move_axes({a: right.declared.to_counts(a, park[a]) for a in ("GR", "GY")}) # type: ignore[union-attr] + # The 96-head brought forward, in line with P8's row, as after a tip load: the tests put long + # tips on it here, and from its home corner its way to P8 would cross the washer at W3, which + # 1025 uL tips cannot clear (the deck check refuses it). + left = self.pod(driver, "left") + park = left.declared.park # type: ignore[union-attr] + await left.move_axes({a: left.declared.to_counts(a, park[a]) for a in ("GR", "GY")}) # type: ignore[union-attr] + await left.move_axes({"Y": left.declared.to_counts("Y", 37.45)}) # type: ignore[union-attr] return driver, lh def record(self, driver, side: str) -> List[Tuple[Dict[str, int], int]]: # type: ignore[no-untyped-def] @@ -274,6 +281,26 @@ def test_wall_from_the_volume_function(self) -> None: else: self.assertAlmostEqual(ours, biomeks, delta=0.001) + async def test_a_blocked_travel_takes_biomeks_search(self) -> None: + # From the home corner's Y with 1025 uL tips, X then Y would cross the washer at W3, which no + # such tip clears: the direct travel is not clear, and the search goes Y first, then X. + driver, lh = await self.setup_deck() + left = self.pod(driver, "left") + d = left.declared + assert d is not None + await left.move_axes({"Y": d.to_counts("Y", 14.45)}) + lh.head96._set_tips( + { + mandrel_name(r, c): biomek_tip("T1025F", f"t_{r}_{c}") + for r in range(ROWS) + for c in range(COLUMNS) + } + ) + moves = self.record(driver, "left") + await lh.head96.aspirate(lh.deck.get_resource("Reservoir"), 100, liquid_height=2.0) + travel = [sorted(t) for t, _ in moves if set(t) & {"X", "Y"}][:2] + self.assertEqual(travel, [["Y"], ["X"]]) + async def test_pylabrobots_own_labware(self) -> None: # A plate defined by PyLabRobot: heights from its cavity bottom, the level from its own # height <-> volume function, the touch-off to its outline less the tip's radius. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py index cb8894f60f2..9d6bd155fc4 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/master.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/master.py @@ -51,6 +51,7 @@ from pylabrobot.beckman_coulter.biomek_i7.driver.features.pod import MoveResult, Pod from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import XRail from pylabrobot.io.usb import USB +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.obstacles import Obstacles if TYPE_CHECKING: from pylabrobot.beckman_coulter.biomek_i7.deck import BiomekI7Deck @@ -141,6 +142,9 @@ def __init__( self.motor_tables = self.declared.motor_tables # Called when a head's tips change; the device saves its heads' tips on it (`state_json`). self.on_tips_changed: Callable[[], None] = lambda: None + # What a pod's moves must clear besides itself and the other pod (`Obstacles`), by pod number; + # the device gives it from its resource tree (`BiomekI7Device.obstacles`). None: no deck check. + self.obstacles: Optional[Callable[[int], Obstacles]] = None self._given_boards = list(boards) if boards is not None else None self.boards: List[AceBoard] = [] self._connected = False @@ -158,6 +162,10 @@ def __init__( self.chassis: Optional[Chassis] = None # The shared X rail (design.md I7), built at discovery from the declared pod geometry. self.rail: Optional[XRail] = None + # Biomek's clearing of the way (`Pod._make_way`): before a pod's move along the rail, an idle other pod + # in its way moves aside on its own, as Biomek's default. Off: such a move is refused by the + # rail guard instead. + self.make_way = True # The pods, named as STAR names its X-arms: each fills an X-arm's slot (design.md, The pods). self.left_x_arm: Optional[Pod] = None self.right_x_arm: Optional[Pod] = None diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py index 0e33306691d..93bdb4eb077 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/motors_tests.py @@ -66,19 +66,22 @@ async def test_each_pod_gets_its_types_axes_and_declaration(self) -> None: with self.assertRaisesRegex(ValueError, "has no axis 'Z8'"): left.axis("Z8") - async def test_the_traverse_default_follows_biomeks_safe_height(self) -> None: - driver = generic_driver() # "Safe Height" unset (-100000), as on the instrument it came from + async def test_the_traverse_defaults_follow_biomeks_always_max_z(self) -> None: + driver = generic_driver() # `AlwaysMaxZ` False on both pods, as on the instrument it came from self.addAsyncCleanup(driver.stop) await driver.discover() - assert driver.left_x_arm is not None - self.assertIsNone(driver.left_x_arm.default_minimum_traverse_height) + for pod in (driver.left_x_arm, driver.right_x_arm): + assert pod is not None + self.assertEqual(pod.traverse_defaults, {"channels": "safe", "gripper": "safe"}) config = generic_configuration() - config.pods["left"].settings["GlobalMinSafeHeight"] = 30.0 + for side in ("left", "right"): + config.pods[side].settings["AlwaysMaxZ"] = True driver = generic_driver(configuration=sealed(config)) self.addAsyncCleanup(driver.stop) await driver.discover() - assert driver.left_x_arm is not None - self.assertEqual(driver.left_x_arm.default_minimum_traverse_height, 300.0) + assert driver.left_x_arm is not None and driver.right_x_arm is not None + for pod in (driver.left_x_arm, driver.right_x_arm): + self.assertEqual(pod.traverse_defaults, {"channels": "max", "gripper": "max"}) if __name__ == "__main__": diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py index 0e3df514f47..4c2b38d71b9 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pipettes_tip_tests.py @@ -108,6 +108,10 @@ async def test_discard_shucks_in_fours_at_the_top_of_travel(self) -> None: self.assertEqual( self.from_travel(moves)[: len(LOGGED_DISCARD)], [parse(c) for c in LOGGED_DISCARD] ) + # It travels at Biomek's safe height: the trash's walls under the way + the tip + + # `AdditionalSafeHeight` + `AvoidanceMargin`. Biomek logged Z1 -19588 for this discard. + lift = next(t for t, _ in moves if "Z1" in t) + self.assertAlmostEqual(lift["Z1"], -19588, delta=40) self.assertEqual(pipettes.tips, [None] * 8) self.assertFalse(any(shaft_of(c).has_tip() for c in pipettes.resources)) with self.assertRaises(RuntimeError): @@ -155,7 +159,7 @@ async def test_carrying_probes_travel_below_the_stripper(self) -> None: pod = self.pod(driver, "right") d = pod.declared assert d is not None - ceilings = pod._traverse_ceilings() + ceilings = pod._max_traverse_heights() self.assertAlmostEqual(ceilings["Z6"], d.limits["Z6"][1] - d.settings["DiscardOffset"]) rack = lh.deck.get_resource("Tips") self.sensor(driver, LOADED) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planner_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planner_tests.py new file mode 100644 index 00000000000..bc076600880 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planner_tests.py @@ -0,0 +1,81 @@ +import unittest +from typing import Sequence + +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import merge + +START = {"X": 0, "Y": 0, "Z": 0, "GY": 0, "GZ": 0, "GR": 0} + + +def anything(moves: Sequence[merge.Move]) -> bool: + return True + + +class DirectCandidateTests(unittest.TestCase): + def test_one_axis_at_a_time_in_biomeks_order(self) -> None: + moves = merge.direct_candidate({"GR": 4, "Y": 2, "X": 1, "GY": 3, "S": 9}) + # The span is not a planned axis: it goes with the first move. + self.assertEqual(moves, [{"S": 9, "X": 1}, {"Y": 2}, {"GY": 3}, {"GR": 4}]) + + def test_nothing_to_move(self) -> None: + self.assertEqual(merge.direct_candidate({}), []) + + +class MergePathTests(unittest.TestCase): + """Biomek's merging of a planned path (spec §5.4), step by step.""" + + def test_a_clear_travel_is_one_move(self) -> None: + path = merge.direct_candidate({"X": 1, "Y": 2, "GY": 3, "GR": 4}) + self.assertEqual(merge.merge_path(path, START, anything), [{"X": 1, "Y": 2, "GY": 3, "GR": 4}]) + + def test_moves_join_only_where_the_joined_move_is_clear(self) -> None: + # X and Y together would cut a corner (not clear); Y with GR is clear. + def viable(moves: Sequence[merge.Move]) -> bool: + return not any("X" in m and "Y" in m for m in moves) + + path = [{"X": 1}, {"Y": 2}, {"GR": 4}] + self.assertEqual(merge.merge_path(path, START, viable), [{"X": 1}, {"Y": 2, "GR": 4}]) + + def test_a_vertical_move_never_joins_a_horizontal_move_of_its_part(self) -> None: + path = [{"Z": 5}, {"X": 1}, {"GZ": 5}, {"GY": 3}] + # Z up and GZ up go first (step 3) and join; X and GY join; never Z or GZ with X or GY. + self.assertEqual(merge.merge_path(path, START, anything), [{"Z": 5, "GZ": 5}, {"X": 1, "GY": 3}]) + + def test_a_later_step_on_the_same_axis_is_summed_into_an_earlier_one(self) -> None: + path = [{"X": 1}, {"GR": 4}, {"X": 3}] + # In steps: X +1, GR +4, X +2; the later X pulled forward and summed: X +3, then GR. + merged = merge.merge_path(path, START, lambda moves: not any("GR" in m and "X" in m for m in moves)) + self.assertEqual(merged, [{"X": 3}, {"GR": 4}]) + + def test_vertical_steps_are_summed_only_the_same_way(self) -> None: + path = [{"Z": 5}, {"X": 1}, {"Z": 2}] + # Up then down: not pulled together; the descent stays after the travel. + merged = merge.merge_path(path, START, anything) + self.assertEqual(merged, [{"Z": 5}, {"X": 1}, {"Z": 2}]) + + def test_a_rise_moves_earlier_while_clear(self) -> None: + path = [{"X": 1}, {"Z": 5}] + self.assertEqual(merge.merge_path(path, START, anything), [{"Z": 5}, {"X": 1}]) + + def low_x(moves: Sequence[merge.Move]) -> bool: # Z up before X is not clear + return not (moves and "Z" in moves[0]) + + self.assertEqual(merge.merge_path(path, START, low_x), [{"X": 1}, {"Z": 5}]) + + def test_x_pairs_with_a_later_y(self) -> None: + path = [{"X": 1}, {"GR": 4}, {"Y": 2}] + + def no_turn_with_x(moves: Sequence[merge.Move]) -> bool: + return not any("GR" in m and "X" in m for m in moves) + + # Y pulled forward next to X (step 4), the two joined; the turn after them. + self.assertEqual(merge.merge_path(path, START, no_turn_with_x), [{"X": 1, "Y": 2}, {"GR": 4}]) + + def test_a_span8s_probes_move_as_its_z_and_y(self) -> None: + start = {"X": 0, "Y": 0, "S": 7, **{f"Z{i}": 0 for i in range(1, 9)}} + path = [{f"Z{i}": 5 for i in range(1, 9)}, {"X": 1}, {"Y": 2, "S": 7}] + merged = merge.merge_path(path, start, anything) + self.assertEqual(merged, [{f"Z{i}": 5 for i in range(1, 9)}, {"X": 1, "Y": 2, "S": 7}]) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/__init__.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/__init__.py new file mode 100644 index 00000000000..34ff334f768 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/__init__.py @@ -0,0 +1,3 @@ +"""How a pod's motion is checked and planned, as pure functions over the pod's model and what it +must clear: no I/O, no `Pod`, no resource tree. The device gives the obstacles, the pod executes +the plans with its own `move_axes`.""" diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/check.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/check.py new file mode 100644 index 00000000000..47723a6f71a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/check.py @@ -0,0 +1,437 @@ +"""The one check of a pod's move, as pure functions: its gripper (and what it holds) against its +own pipettor, and all its parts (and its body, against the obstacles with no top) against what it +must clear (`obstacles.Obstacles`), each as a sweep; and the start-in-collision escape. + +Biomek models each part of a pod as a box in 3D and refuses a move whose sweep overlaps: its +gripper's boxes and its pipettor's (`own_collisions`), or any part and the deck's boxes, their +own obstacles and the instrument's structure (`deck_collisions`), overlaps up to +`DECK_TOLERANCE` allowed. Every move whose path would overlap is refused before anything is sent +(`Pod.move_axes`); the planner plans around them with the same check on a larger model (the +gripper padded below, `pod_model.planning_pad`; the other pod as a wall). The parts are the pod +model's (`pod_model`). +""" + +import math +from dataclasses import dataclass +from typing import List, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.obstacles import Obstacles, bounds_of +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.pod_model import ( + Bounds, + GripperState, + Part, + PipettorState, + PodModel, + PodState, + Point, + on_quarter, + planning_pad, + body_part, + bundle_part, + gripper_parts, + moving_parts, + pipettor_parts, +) + + +class PodCollisionError(ValueError): + """A move would bring a pod's gripper (or what it holds) into its own pipettor. Raised before + anything is sent.""" + + +def _axes(outline: Sequence[Point]) -> List[Point]: + n = len(outline) + return [ + (outline[i][1] - outline[(i + 1) % n][1], outline[(i + 1) % n][0] - outline[i][0]) + for i in range(n) + ] + + +def overlap(a: Part, b: Part) -> bool: + """Whether two parts share any volume (touching is clear): Z ranges, then separating axes.""" + if a.z_high <= b.z_low or b.z_high <= a.z_low: + return False + # Their bounds first: apart there, apart (the bounds hold each outline). + ax0, ax1, ay0, ay1 = a.extent + bx0, bx1, by0, by1 = b.extent + if ax1 <= bx0 or bx1 <= ax0 or ay1 <= by0 or by1 <= ay0: + return False + for ax, ay in _axes(a.outline) + _axes(b.outline): + pa = [px * ax + py * ay for px, py in a.outline] + pb = [px * ax + py * ay for px, py in b.outline] + if max(pa) <= min(pb) or max(pb) <= min(pa): + return False + return True + + +def _own_pairs( + gripper: Sequence[Part], pipettor: Sequence[Part], bundle: Optional[Part] +) -> List[Tuple[str, str]]: + """The (gripper part, pipettor part) pairs that overlap; a Span-8's tubing bundle only against + what the gripper holds, as Biomek pairs it.""" + found = [(a.name, b.name) for a in gripper for b in pipettor if overlap(a, b)] + if bundle is not None: + found += [ + (a.name, bundle.name) for a in gripper if a.name == "held labware" and overlap(a, bundle) + ] + return found + + +def own_collisions_at( + config: PodConfiguration, state: PodState, pad: float = 0.0 +) -> List[Tuple[str, str]]: + """The (gripper part, pipettor part) pairs that overlap at `state` (`_own_pairs`); none without + a gripper. `pad`: as `gripper_parts`.""" + if state.gripper is None: + return [] + gp = gripper_parts(config, state.x, state.gripper, pad) + pp = pipettor_parts(config, state.x, state.pipettor) + return _own_pairs(gp, pp, bundle_part(config, state.x, state.pipettor)) + + +# cm: the most any point moves between two checked poses. Every part is widened by +# `AvoidanceMargin` (0.2164 cm), so a contact cannot pass between two steps unseen. +SWEEP_STEP = 0.1 + + +def own_collisions( + config: PodConfiguration, start: PodState, end: PodState, pad: float = 0.0 +) -> List[Tuple[str, str]]: + """The (gripper part, pipettor part) pairs a move from `start` to `end` brings together, anywhere + along it (every axis on the same profile, scaled to its distance), checked at steps no point + covers more than `SWEEP_STEP` in; none on a pod without a gripper. The parts are widened by + `AvoidanceMargin`, more than a step; a Span-8's tubing bundle, not widened, meets only what the + gripper holds (`_own_pairs`). `pad`: as `gripper_parts`.""" + g0, g1, p0, p1 = start.gripper, end.gripper, start.pipettor, end.pipettor + if g0 is None or g1 is None: + return [] + x = (start.x, end.x) + # A turn between quarter turns: at least Biomek's box over the turning corners' arcs. + boxes = quarter_turn_parts(config, start, end, pad) + if boxes: + pipettor = [*pipettor_parts(config, start.x, p0), *pipettor_parts(config, end.x, p1)] + arcs = _own_pairs(boxes, pipettor, None) + for bundle in (bundle_part(config, start.x, p0), bundle_part(config, end.x, p1)): + arcs += _own_pairs(boxes, [], bundle) + if arcs: + return list(dict.fromkeys(arcs)) + # X carries every part alike, so only the other axes change what overlaps. + reach = config.gripper_model["Finger"]["PadsCenterToRotationCenter"] + 15.0 + travel = max( + [abs(g1.gy - g0.gy), abs(g1.gz - g0.gz), abs(g1.gg - g0.gg)] + + [reach * math.radians(abs(g1.gr - g0.gr))] + + [abs(b - a) for a, b in zip(p0.ys, p1.ys)] + + [abs(b - a) for a, b in zip(p0.zs, p1.zs)] + ) + steps = max(1, math.ceil(travel / SWEEP_STEP)) + found: List[Tuple[str, str]] = [] + # X carries both alike: checked at the start's X throughout, the pipettor's parts built once + # when only the gripper moves. + fixed = pipettor_parts(config, x[0], p0) if p0 == p1 else None + fixed_bundle = bundle_part(config, x[0], p0) if p0 == p1 else None + for i in range(steps + 1): + t = i / steps + + def lerp(a: float, b: float) -> float: + return float(a + t * (b - a)) + + gs = GripperState( + lerp(g0.gy, g1.gy), lerp(g0.gz, g1.gz), lerp(g0.gr, g1.gr), lerp(g0.gg, g1.gg), g0.held + ) + ps = PipettorState( + tuple(lerp(a, b) for a, b in zip(p0.ys, p1.ys)), + tuple(lerp(a, b) for a, b in zip(p0.zs, p1.zs)), + p0.tips, + p0.tip_block, + ) + gp = gripper_parts(config, x[0], gs, pad) + pp = fixed if fixed is not None else pipettor_parts(config, x[0], ps) + bundle = fixed_bundle if fixed is not None else bundle_part(config, x[0], ps) + for pair in _own_pairs(gp, pp, bundle): + if pair not in found: + found.append(pair) + if found: + return found + return found + + +# -- a pod against the deck and the instrument -------------------------------------------------- +# +# Biomek checks each move of a pod against its world: one box per deck position (its site, from its +# ALP's base up to the higher of its `MinSafeHeight` and what stands on it), the positions' own +# obstacles (a trash's walls), and the instrument's obstacles (widened by their buffers). The +# position an operation works in is left out of that operation's moves, whole. The heads' and the +# Span-8 probes' lower parts reach `AdditionalSafeHeight` + `AvoidanceMargin` below the tips' ends +# for this check, and overlaps up to `DECK_TOLERANCE` are allowed. + +# cm: an overlap this deep or less is clear. +DECK_TOLERANCE = 0.005 + + +class DeckCollisionError(PodCollisionError): + """A move would bring a pod's part (or what its gripper holds) into the deck, what stands on it, + or the instrument. Raised before anything is sent.""" + + +def _world_overlap(a: Part, b: Part) -> bool: + """`overlap`, an overlap of `DECK_TOLERANCE` or less counted as clear.""" + if a.z_high - DECK_TOLERANCE <= b.z_low or b.z_high - DECK_TOLERANCE <= a.z_low: + return False + for ax, ay in _axes(a.outline) + _axes(b.outline): + norm = math.hypot(ax, ay) or 1.0 + pa = [(px * ax + py * ay) / norm for px, py in a.outline] + pb = [(px * ax + py * ay) / norm for px, py in b.outline] + if max(pa) - DECK_TOLERANCE <= min(pb) or max(pb) - DECK_TOLERANCE <= min(pa): + return False + return True + + +def _hull(points: Sequence[Point]) -> Tuple[Point, ...]: + """The convex hull of `points`, counterclockwise.""" + pts = sorted(set(points)) + if len(pts) <= 2: + return tuple(pts) + + def cross(o: Point, a: Point, b: Point) -> float: + return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) + + lower: List[Point] = [] + for p in pts: + while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: + lower.pop() + lower.append(p) + upper: List[Point] = [] + for p in reversed(pts): + while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: + upper.pop() + upper.append(p) + return tuple(lower[:-1] + upper[:-1]) + + +def _near(statics: Sequence[Part], box: Tuple[float, ...], margin: float) -> List[Part]: + """The statics whose bounds meet `box` widened by `margin`.""" + x0, x1, y0, y1, z0, z1 = box + out = [] + for s in statics: + sx0, sx1, sy0, sy1, sz0, sz1 = bounds_of([s]) + if sx1 >= x0 - margin and x1 + margin >= sx0 and sy1 >= y0 - margin and y1 + margin >= sy0: + if sz1 >= z0 - margin and z1 + margin >= sz0: + out.append(s) + return out + + +def deck_collisions_at( + config: PodConfiguration, state: PodState, obstacles: Obstacles, pad: float = 0.0 +) -> List[Tuple[str, str]]: + """The (pod part, obstacle) pairs that overlap at `state`. `pad`: as `gripper_parts`.""" + body = body_part(config, state.x, state.pipettor.ys[0]) + found = _overlaps([body], obstacles.ceilings) + moving = moving_parts(config, state.x, state.gripper, state.pipettor, pad) + return found + _overlaps(moving, obstacles.everything) + + +def _overlaps( + moving: Sequence[Part], statics: Sequence[Tuple[Part, Bounds]] +) -> List[Tuple[str, str]]: + """The (moving, static) pairs that overlap: bounds first, then `_world_overlap`.""" + t = DECK_TOLERANCE + found = [] + for a in moving: + ax0, ax1, ay0, ay1, az0, az1 = bounds_of([a]) + for b, (bx0, bx1, by0, by1, bz0, bz1) in statics: + if ax1 - t <= bx0 or bx1 - t <= ax0 or ay1 - t <= by0 or by1 - t <= ay0: + continue + if az1 - t <= bz0 or bz1 - t <= az0: + continue + if _world_overlap(a, b): + found.append((a.name, b.name)) + return found + + +def deck_collisions( + config: PodConfiguration, + start: PodState, + end: PodState, + obstacles: Obstacles, + pad: float = 0.0, +) -> List[Tuple[str, str]]: + """The (pod part, obstacle) pairs a move from `start` to `end` brings together, anywhere along it + (every axis on the same profile). + + Without a gripper turn every part translates in a straight line, so each one's path is covered by + the convex hull of its start and end outlines over the union of their heights (the exact path of + a move in X and Y, an over-estimate when Z moves too). With a turn the move is checked at steps no point + covers more than `SWEEP_STEP` in, against the obstacles near its path; a turn between quarter + turns also by Biomek's box over its turning parts' arcs (`quarter_turn_parts`). `pad`: as + `gripper_parts`.""" + world = obstacles + x = (start.x, end.x) + g0, g1, p0, p1 = start.gripper, end.gripper, start.pipettor, end.pipettor + first = [body_part(config, x[0], p0.ys[0])] + moving_parts(config, x[0], g0, p0, pad) + last = [body_part(config, x[1], p1.ys[0])] + moving_parts(config, x[1], g1, p1, pad) + turning = g0 is not None and g1 is not None and (g0.gr != g1.gr or g0.held != g1.held) + if not turning: + found: List[Tuple[str, str]] = [] + for a, b in zip(first, last): + swept = Part( + a.name, _hull(a.outline + b.outline), min(a.z_low, b.z_low), max(a.z_high, b.z_high) + ) + statics = world.ceilings if a.name == "pod body" else world.everything + for pair in _overlaps([swept], statics): + if pair not in found: + found.append(pair) + return found + reach = config.gripper_model["Finger"]["PadsCenterToRotationCenter"] + 15.0 + near = Obstacles( + tuple(_near(world.structure, bounds_of(first + last), reach)), + tuple(_near(world.deck, bounds_of(first + last), reach)), + world.holders, + ) + assert g0 is not None and g1 is not None + # A turn between quarter turns: at least Biomek's box over the turning corners' arcs. + found = [] + for pair in _overlaps(quarter_turn_parts(config, start, end, pad), near.everything): + if pair not in found: + found.append(pair) + if found: + return found + travel = [abs(x[1] - x[0]), reach * math.radians(abs(g1.gr - g0.gr))] + travel += [abs(g1.gy - g0.gy), abs(g1.gz - g0.gz), abs(g1.gg - g0.gg)] + travel += [abs(b - a) for a, b in zip(p0.ys, p1.ys)] + [abs(b - a) for a, b in zip(p0.zs, p1.zs)] + steps = max(1, math.ceil(max(travel) / SWEEP_STEP)) + for i in range(steps + 1): + t = i / steps + + def lerp(a: float, b: float) -> float: + return float(a + t * (b - a)) + + gs = GripperState( + lerp(g0.gy, g1.gy), lerp(g0.gz, g1.gz), lerp(g0.gr, g1.gr), lerp(g0.gg, g1.gg), g0.held + ) + ps = PipettorState( + tuple(lerp(a, b) for a, b in zip(p0.ys, p1.ys)), + tuple(lerp(a, b) for a, b in zip(p0.zs, p1.zs)), + p0.tips, + p0.tip_block, + ) + for pair in deck_collisions_at(config, PodState(lerp(*x), gs, ps), near, pad): + if pair not in found: + found.append(pair) + if found: + return found + return found + + +# The gripper's parts that turn with GR (the upper hand does not). +TURNING = ("lower hand", "fingers", "held labware") + + +def _arc_box(outline: Sequence[Point], cx: float, cy: float, delta: float) -> Tuple[float, ...]: + """The axis-aligned box over `outline`'s corners turning by `delta` degrees about (`cx`, `cy`): + each corner at both ends, and at its radius on each axis it crosses (Biomek's box for a turn + between quarter turns).""" + xs: List[float] = [] + ys: List[float] = [] + for px, py in outline: + r = math.hypot(px - cx, py - cy) + phi = math.degrees(math.atan2(py - cy, px - cx)) + lo, hi = sorted((phi, phi + delta)) + angles = [lo, hi] + [k * 90.0 for k in range(math.ceil(lo / 90.0), math.floor(hi / 90.0) + 1)] + for a in angles: + xs.append(cx + r * math.cos(math.radians(a))) + ys.append(cy + r * math.sin(math.radians(a))) + return min(xs), max(xs), min(ys), max(ys) + + +def quarter_turn_parts( + config: PodConfiguration, start: PodState, end: PodState, pad: float = 0.0 +) -> List[Part]: + """For a gripper turn from one quarter turn to another, each turning part's box over its corners' + arcs (`_arc_box`), about the rotation centre where the move starts and where it ends, the two + joined; none for any other move. `pad`: as `gripper_parts`.""" + g0, g1 = start.gripper, end.gripper + if g0 is None or g1 is None or g0.gr == g1.gr: + return [] + if not (on_quarter(config, g0.gr) and on_quarter(config, g1.gr)): + return [] + model = PodModel.of(config).gripper_model + assert model is not None + geo = config.geometry + delta = g1.gr - g0.gr + ends = [] + for x, g, turn in ((start.x, g0, delta), (end.x, g1, -delta)): + cx = x + geo.gripper_x_offset - model.pads_center_to_rotation_center + cy = g.gy + geo.gripper_y_offset - model.finger_center_offset + parts = {p.name: p for p in gripper_parts(config, x, g, pad) if p.name in TURNING} + ends.append({n: (_arc_box(p.outline, cx, cy, turn), p) for n, p in parts.items()}) + out = [] + for name in ends[0]: + (a, pa), (b, pb) = ends[0][name], ends[1][name] + corners = [(x, y) for box in (a, b) for x in box[:2] for y in box[2:]] + out.append(Part(name, _hull(corners), min(pa.z_low, pb.z_low), max(pa.z_high, pb.z_high))) + return out + + +@dataclass(frozen=True) +class Escape: + """How a pod that stands inside deck positions leaves them, as Biomek's planner disengages: the + positions it is inside (`holders`), and how far each pipettor channel's parts (a Span-8's + probes one by one, the 96-head's as one) and the gripper's must rise straight up to clear them + (cm; 0 for parts inside none).""" + + holders: Tuple[str, ...] + pipettor: Tuple[float, ...] + gripper: float + + +def _channel(part: str) -> int: + """The pipettor channel a part rises with: a Span-8 probe's (`probe N`, its upper part too), else + the 96-head's only one.""" + return int(part.split()[1]) - 1 if part.startswith("probe ") else 0 + + +def escape( + config: PodConfiguration, state: PodState, obstacles: Obstacles, pad: float = 0.0 +) -> Optional[Escape]: + """Biomek's start-in-collision escape for a pod at this pose: the deck positions its parts are + inside, and each part's straight rise until its bottom reaches their tops (Biomek's upward stop, + the obstacle's top less the part's bottom): per channel, so a Span-8's probes inside nothing do + not rise (the logged escapes raise only the probes still in the labware). None when it is + inside anything that is not a position's box (a position's own obstacle, the instrument): no + escape is planned from those. `pad`: as `gripper_parts`.""" + x, gripper, pipettor, world = state.x, state.gripper, state.pipettor, obstacles + if _overlaps([body_part(config, x, pipettor.ys[0])], world.ceilings): + return None + positions: List[str] = [] + channels = [0.0] * len(pipettor.zs) + hand = 0.0 + parts: List[Tuple[Part, Optional[int]]] = [ + (a, _channel(a.name)) for a in moving_parts(config, x, None, pipettor) + ] + if gripper is not None: + parts += [(a, None) for a in gripper_parts(config, x, gripper, pad)] + for a, channel in parts: + for b, bounds in world.everything: + if not _overlaps([a], [(b, bounds)]): + continue + if b.name not in world.holders: + return None + if b.name not in positions: + positions.append(b.name) + if channel is None: + hand = max(hand, b.z_high - a.z_low) + else: + channels[channel] = max(channels[channel], b.z_high - a.z_low) + return Escape(tuple(positions), tuple(channels), hand) + + +def move_clear( + config: PodConfiguration, start: PodState, end: PodState, obstacles: Optional[Obstacles] +) -> bool: + """Whether a move from `start` to `end` passes both checks (the deck's only with `obstacles`) as + Biomek's planner checks it: the gripper padded below (`planning_pad`).""" + pad = planning_pad(config) + if own_collisions(config, start, end, pad): + return False + return obstacles is None or not deck_collisions(config, start, end, obstacles, pad) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/check_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/check_tests.py new file mode 100644 index 00000000000..c6b9be193c0 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/check_tests.py @@ -0,0 +1,138 @@ +import unittest +from typing import List, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import check, pod_model +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.obstacles import Obstacles, obstacle_part +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration + +Point = Tuple[float, float] + + +def inside(point: Point, outline: Sequence[Point]) -> bool: + """Whether `point` is inside the convex `outline` (either winding).""" + signs = set() + for (ax, ay), (bx, by) in zip(outline, [*outline[1:], outline[0]]): + cross = (bx - ax) * (point[1] - ay) - (by - ay) * (point[0] - ax) + signs.add(cross > 0) + return len(signs) == 1 + + +class TurnSweepTests(unittest.TestCase): + """Our sweep of a gripper turn is never smaller than Biomek's: Biomek bounds a turn between two + quarter turns by the axis-aligned box over each turning corner's arc (its corners at both ends + and the point at its radius on each axis it crosses), and any other turn by the exact turning + box.""" + + def setUp(self) -> None: + self.config = generic_configuration().pod("right") + held = g.HeldLabware(length=12.776, width=8.548, height=1.5) + self.turn = [pod_model.GripperState(40.0, 30.0, gr, 9.0, held) for gr in (0.0, 90.0)] + self.x = 100.0 + # The probes high and at the back, out of the way. + self.pipettor = pod_model.PipettorState( + tuple(10.0 + 0.9 * i for i in range(8)), (39.0,) * 8, (0.0,) * 8 + ) + + def parts_at(self, gr: float) -> List[pod_model.Part]: + a, _ = self.turn + return pod_model.gripper_parts( + self.config, self.x, pod_model.GripperState(a.gy, a.gz, gr, a.gg, a.held) + ) + + def biomeks_box(self) -> Tuple[float, float, float, float]: + """The box over the held labware's corners' arcs from 0 to 90 degrees (dense sampling of + each corner's arc reaches its bound within a micron).""" + xs: List[float] = [] + ys: List[float] = [] + for step in range(9001): + held = next(p for p in self.parts_at(step / 100) if p.name == "held labware") + xs += [px for px, _ in held.outline] + ys += [py for _, py in held.outline] + return min(xs), max(xs), min(ys), max(ys) + + def in_biomeks_box_only(self) -> Optional[Point]: + """A corner of Biomek's box (0.1 cm in) that no part of the gripper reaches on its way round.""" + x0, x1, y0, y1 = self.biomeks_box() + swept = [p.outline for gr in [i / 4 for i in range(361)] for p in self.parts_at(gr)] + corners = [(x, y) for x in (x0 + 0.1, x1 - 0.1) for y in (y0 + 0.1, y1 - 0.1)] + return next((c for c in corners if not any(inside(c, outline) for outline in swept)), None) + + def test_a_quarter_turn_is_bounded_at_least_by_biomeks_box(self) -> None: + point = self.in_biomeks_box_only() + assert point is not None + held = next(p for p in self.parts_at(0.0) if p.name == "held labware") + box = obstacle_part( + "in Biomek's box only", + (point[0] - 0.05, point[0] + 0.05), + (point[1] - 0.05, point[1] + 0.05), + (held.z_low, held.z_low + 0.5), + ) + start, end = (pod_model.PodState(self.x, s, self.pipettor) for s in self.turn) + found = check.deck_collisions(self.config, start, end, Obstacles((), (box,), ())) + self.assertTrue(found, f"a turn through {point} is not refused") + + def test_biomeks_box_holds_every_pose_of_the_turn(self) -> None: + # The reference itself: every sampled pose of the held labware lies in the box. + x0, x1, y0, y1 = self.biomeks_box() + for gr in (0.0, 30.0, 45.0, 90.0): + held = next(p for p in self.parts_at(gr) if p.name == "held labware") + for px, py in held.outline: + self.assertTrue(x0 - 1e-9 <= px <= x1 + 1e-9 and y0 - 1e-9 <= py <= y1 + 1e-9) + self.assertGreater((x1 - x0) * (y1 - y0), 0.0) + + def test_quarter_turns_read_back_from_counts_are_quarter_turns(self) -> None: + # A pose read from the boards: 0 and 90 degrees within a count, not exactly. + a, b = (self.config.to_value("GR", self.config.to_counts("GR", gr)) for gr in (0.0, 90.0)) + self.assertNotEqual((a, b), (0.0, 90.0)) + turn = [pod_model.GripperState(s.gy, s.gz, gr, s.gg, s.held) for s, gr in zip(self.turn, (a, b))] + start, end = (pod_model.PodState(self.x, s, self.pipettor) for s in turn) + self.assertTrue(check.quarter_turn_parts(self.config, start, end)) + + def test_part_of_biomeks_box_is_never_reached_by_the_turn(self) -> None: + # What the test above needs: a place in Biomek's box that the turning gripper never covers. + self.assertIsNotNone(self.in_biomeks_box_only()) + + +class BundleTests(unittest.TestCase): + """A Span-8's tubing bundle meets only what the gripper holds, as Biomek pairs it.""" + + def test_only_held_labware_meets_the_bundle(self) -> None: + square = ((0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)) + bundle = pod_model.Part("tubing bundle", square, 10.0, pod_model.OPEN) + held = pod_model.Part("held labware", square, 9.0, 11.0) + fingers = pod_model.Part("fingers", square, 9.0, 11.0) + self.assertEqual(check._own_pairs([held], [], bundle), [("held labware", "tubing bundle")]) + self.assertEqual(check._own_pairs([fingers], [], bundle), []) + below = pod_model.Part("held labware", square, 8.0, 9.5) + self.assertEqual(check._own_pairs([below], [], bundle), []) + + def test_only_a_span8_has_a_bundle(self) -> None: + pipettor = pod_model.PipettorState(tuple(10.0 + 0.9 * i for i in range(8)), (30.0,) * 8, (0.0,) * 8) + config = generic_configuration() + self.assertIsNotNone(pod_model.bundle_part(config.pod("right"), 100.0, pipettor)) + head = pod_model.PipettorState((30.0,), (30.0,), (0.0,), None) + self.assertIsNone(pod_model.bundle_part(config.pod("left"), 100.0, head)) + + +class PlanningPadTests(unittest.TestCase): + """The planner checks the gripper padded below by `AdditionalSafeHeightGripper`; a move check + does not.""" + + def test_the_planner_keeps_the_gripper_its_pad_above_a_box(self) -> None: + config = generic_configuration().pod("right") + pad = pod_model.planning_pad(config) + self.assertGreater(pad, 0.3) + pipettor = pod_model.PipettorState(tuple(10.0 + 0.9 * i for i in range(8)), (39.0,) * 8, (0.0,) * 8) + grip = pod_model.GripperState(40.0, 30.0, 0.0, 9.0, None) + start, end = (pod_model.PodState(x, grip, pipettor) for x in (100.0, 120.0)) + bottom = min(p.z_low for p in pod_model.gripper_parts(config, 100.0, grip)) + # A box under the whole travel, its top 0.3 cm below the gripper's bottom. + box = obstacle_part("P1", (60.0, 180.0), (0.0, 80.0), (bottom - 5.0, bottom - 0.3)) + world = Obstacles((), (box,), ()) + self.assertEqual(check.deck_collisions(config, start, end, world), []) + self.assertFalse(check.move_clear(config, start, end, world)) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/destinations.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/destinations.py new file mode 100644 index 00000000000..5808b8d8eb3 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/destinations.py @@ -0,0 +1,68 @@ +"""Where a pod's planned operations go: each operation's targets (counts) from the pod's +configuration and pose, as Biomek sets them. The pod plans and executes the way there.""" + +from typing import Callable, Dict, List, Literal, Mapping, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration + +# How far past the next 1/16 cm grid line a pod moved out of the other's way puts its edge (cm), +# as Biomek's clearing of the way does. +GRID_GAP = 1 / 64 + + +def park_targets( + config: PodConfiguration, side: Literal["left", "right"], over: Optional[Mapping[str, int]] +) -> Dict[str, int]: + """Biomek's park location (`ParkLocation`): X `XMargin` in from the pod's own end of the rail and + `Y` (unless `over` gives them: a pod whose park declares none, a Span-8 over its wash station), + the gripper's `GR` and `GY`.""" + p = config.park + targets: Dict[str, int] = dict(over or {}) + if "XMargin" in p and "X" not in targets: + low, high = config.limits["X"] + x = low + p["XMargin"] if side == "left" else high - p["XMargin"] + targets["X"] = config.to_counts("X", x) + if "Y" in p and "Y" not in targets: + targets["Y"] = config.to_counts("Y", p["Y"]) + targets.update({a: config.to_counts(a, p[a]) for a in ("GR", "GY") if a in p}) + return targets + + +def rest_heights(config: PodConfiguration, channels: Sequence[str]) -> Dict[str, int]: + """Where the channels rest once parked: the top less the park margin (`ZMargin`), and on a + Span-8 less `DiscardOffset` as well (39.1079 cm on Z1, 9029 counts: lower than the probes + travel).""" + shuck = config.settings["DiscardOffset"] if config.module_type == "span8" else 0.0 + margin = config.park.get("ZMargin", 0.0) + return {z: config.to_counts(z, config.limits[z][1] + margin - shuck) for z in channels} + + +def step_aside( + config: PodConfiguration, + side: Literal["left", "right"], + x: float, + gr: float, + gg: float, + held: Optional[g.HeldLabware], + zone: g.Range, + range_at: Callable[[float, g.GripperPose], g.Range], +) -> List[Tuple[float, float, Tuple[float, float]]]: + """Biomek's ways out of the X `zone` another pod's move needs, in the order it tries them: each + (GR, X target, where X may go). Away from the other pod, the pod's near edge at the next + 1/16 cm grid line past the zone plus `GRID_GAP`, its gripper turned to the nearest quarter turn; + then the same with the gripper at 0 degrees (90 if the nearest quarter was 0). `range_at`: the + pod's X range at an X and gripper pose (the rail's).""" + low, high = config.limits["X"] + nearest = round(gr / 90) * 90.0 + out = [] + for turn in (nearest, 90.0 if nearest == 0 else 0.0): + left, right = range_at(x, g.GripperPose(turn, gg, held)) + if side == "right": + target = (g.grid_cell(zone[1]) + 1) / g.GRID_PER_CM + GRID_GAP - (left - x) + bounds = (x, high) + else: + target = g.grid_cell(zone[0]) / g.GRID_PER_CM - GRID_GAP - (right - x) + bounds = (low, x) + out.append((turn, target, bounds)) + return out diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/find_path.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/find_path.py new file mode 100644 index 00000000000..05a53657348 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/find_path.py @@ -0,0 +1,73 @@ +"""How a pod's planned operation gets where it goes, stage by stage, as Biomek plans it: the rise +out of the deck positions the pod stands in (its start-in-collision escape), the rise to the +travel heights, the travel, the descent. Each stage is planned from where the one before leaves +the pod: the direct way when the check passes it (`clear`), else Biomek's search (`search_to`). +The pod merges the stages' moves as one path (`merge.merge_path`), as Biomek merges the path it +concatenates, before anything moves. + +`clear(moves, start=None)` checks moves made in order (from the pod's position record by +default) as `move_axes` checks them; `search_to(destination)` is the pod's search there +(`search.pod_search`), raising `search.NoPathError`. +""" + +from typing import Callable, Dict, List, Mapping, Sequence + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import merge +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.check import Escape +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.pod_model import PodState + +Clear = Callable[..., bool] +SearchTo = Callable[[Mapping[str, int]], List[merge.Move]] + + +def direct_or_searched( + move: merge.Move, destination: Mapping[str, int], clear: Clear, search_to: SearchTo +) -> List[merge.Move]: + """`move` alone when it is clear; else the search's path to `destination`. + + Raises: + search.NoPathError: when the search finds no path. + """ + if clear([move]): + return [move] + return search_to(destination) + + +def travel(targets: Mapping[str, int], clear: Clear, search_to: SearchTo) -> List[merge.Move]: + """The travel to `targets`, the rise made: Biomek's direct candidate (`merge.direct_candidate`) + when each of its moves is clear; else the search's path. + + Raises: + search.NoPathError: when the search finds no path. + """ + candidate = merge.direct_candidate(targets) + if clear(candidate): + return candidate + return search_to(targets) + + +def escape_targets( + config: PodConfiguration, + pose: PodState, + out: Escape, + heights: Mapping[str, float], + channels: Sequence[str], +) -> Dict[str, int]: + """The rise out of the deck positions the pod stands in (`out`, `check.escape`): each part inside + them (a channel, or the gripper) straight up until its bottom is at their tops, or to its height + in `heights` (cm) if that is higher. When a channel escapes, the other channels below their + heights rise to them in the same move, as Biomek's merged path does (the logged escapes are one + Z move of the probes); the others stay.""" + targets: Dict[str, int] = {} + + def up(name: str, now: float, rise: float) -> None: + targets[name] = config.to_counts(name, max(now + rise, heights.get(name, now))) + + escaping = any(rise > 0 for rise in out.pipettor) + for name, z, rise in zip(channels, pose.pipettor.zs, out.pipettor): + if rise > 0 or (escaping and z < heights.get(name, z)): + up(name, z, rise) + if out.gripper > 0 and pose.gripper is not None: + up("GZ", pose.gripper.gz, out.gripper) + return targets diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/merge.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/merge.py new file mode 100644 index 00000000000..8611a1133cc --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/merge.py @@ -0,0 +1,213 @@ +"""Merging a pod's planned path, as Biomek merges one: its direct candidate (each axis on its own, +in Biomek's order), and the pipeline that turns a path of single-axis moves into the moves sent +(`merge_path`). Every reordering and every joined move is kept only when the path stays clear +(`Viable`: the pod's own checks, the ones `move_axes` makes before anything is sent). + +Biomek merges in steps of each axis (deltas): a move is reordered or summed as a step, so a path +is taken apart into steps from where it starts, merged, and put back together as targets.""" + +from typing import Callable, Dict, FrozenSet, List, Mapping, Optional, Sequence + +# A move: axis targets in counts, sent together. +Move = Dict[str, int] + +# Whether the moves `moves` (in order, from where the path starts) are each clear, as `Pod._clear`. +Viable = Callable[[Sequence[Move]], bool] + +# A step: each axis's change in counts. +Step = Dict[str, int] + +# The order Biomek's direct candidate changes the travel axes in, after the rises: the pipettor's +# X and Y, then the gripper's GY and GR. Axes it does not plan (the Span-8's span) go with the +# first move. +TRAVEL_ORDER = ("X", "Y", "GY", "GR") + +# The two parts' vertical axes, and what each part moves horizontally (X carries both). +VERTICAL = ("Z", "GZ") +HORIZONTAL = {"Z": ("X", "Y"), "GZ": ("X", "GY")} + + +def direct_candidate(targets: Mapping[str, int]) -> List[Move]: + """The travel to `targets` one axis at a time, in Biomek's order (`TRAVEL_ORDER`): each move + changes one planned axis; axes it does not plan go with the first.""" + planned = [{a: targets[a]} for a in TRAVEL_ORDER if a in targets] + rest = {a: v for a, v in targets.items() if a not in TRAVEL_ORDER} + if rest: + if planned: + planned[0] = {**rest, **planned[0]} + else: + planned = [rest] + return planned + + +def axis_of(name: str) -> Optional[str]: + """The planned axis an axis belongs to: a Span-8's probes' Z (Z1-Z8) are its Z and their Y + (Y1-Y8) its Y; the span (S) is set before planning and belongs to none.""" + if name == "S": + return None + if name[0] in "YZ" and name[1:].isdigit(): + return name[0] + return name + + +def axes(step: Mapping[str, int]) -> FrozenSet[str]: + """The planned axes a step or a move changes.""" + return frozenset(a for a in map(axis_of, step) if a is not None) + + +def merge_path(moves: Sequence[Move], start: Mapping[str, int], viable: Viable) -> List[Move]: + """`moves` (from where the pod is: `start`, every axis's counts) merged as Biomek merges a planned + path: + + 1. its steps, one per move; neighbours on the same axis summed; + 2. a later step on the same axis pulled forward and summed into an earlier one (Z and GZ only + the same way), the steps between after it; + 3. each rise (Z, then GZ) moved earlier, one step at a time; + 4. X paired with a later Y or GY, and Y or GY with a later X, unless the next step already pairs + with it: the later one pulled forward next to it; + 5. two passes joining each move with the next while the joined move is clear: first moves that + change none of Z, GZ or GR; then any, never a vertical move with a horizontal move of the same + part (Z with X or Y, GZ with X or GY). + + Steps 2-4 keep a change only when the path stays clear.""" + steps = _sum_neighbours(_steps(moves, start)) + + def clear(path: Sequence[Step]) -> bool: + return viable(_moves(path, start)) + + steps = _pull_forward(steps, clear, summed=True) + for axis in VERTICAL: + steps = _rises_earlier(steps, clear, axis) + steps = _pull_forward(steps, clear, summed=False) + steps = _join(steps, clear, _neither_vertical_nor_turning) + return _moves(_join(steps, clear, _parts_apart), start) + + +def _steps(moves: Sequence[Move], start: Mapping[str, int]) -> List[Step]: + at = dict(start) + out = [] + for move in moves: + out.append({a: v - at[a] for a, v in move.items()}) + at.update(move) + return out + + +def _moves(steps: Sequence[Step], start: Mapping[str, int]) -> List[Move]: + at = dict(start) + out = [] + for step in steps: + move = {a: at[a] + d for a, d in step.items()} + at.update(move) + out.append(move) + return out + + +def _add(a: Step, b: Step) -> Step: + return {k: a.get(k, 0) + b.get(k, 0) for k in {**a, **b}} + + +def _one_axis(step: Step) -> Optional[str]: + only = axes(step) + return next(iter(only)) if len(only) == 1 else None + + +def _rising(step: Step) -> bool: + """Whether a step moves its axis up (counts grow with height on every Z-type axis).""" + return any(d > 0 for d in step.values()) + + +def _sum_neighbours(steps: Sequence[Step]) -> List[Step]: + out: List[Step] = [] + for step in steps: + if out and _one_axis(step) is not None and _one_axis(out[-1]) == _one_axis(step): + out[-1] = _add(out[-1], step) + else: + out.append(dict(step)) + return out + + +def _pulls(summed: bool, current: Step, following: Step, later: Step) -> bool: + """Whether step 2 (`summed`) or step 4 pulls `later` forward to `current`, `following` being the + step right after `current`.""" + a, b, c = _one_axis(current), _one_axis(following), _one_axis(later) + if a is None or c is None: + return False + if summed: + return a == c and (a not in VERTICAL or _rising(current) == _rising(later)) + if a == "X": + return b not in ("Y", "GY") and c in ("Y", "GY") + return a in ("Y", "GY") and b != "X" and c == "X" + + +def _pull_forward( + steps: Sequence[Step], clear: Callable[[Sequence[Step]], bool], summed: bool +) -> List[Step]: + """Steps 2 and 4: for each step, the later steps it pulls forward (`_pulls`), until one that + would leave the path not clear.""" + work = [dict(s) for s in steps] + out: List[Step] = [] + i = 0 + while i < len(work): + current = work[i] + j = i + 2 + while j < len(work): + if _pulls(summed, current, work[i + 1], work[j]): + if not clear([*out, current, work[j], *work[i + 1 : j]]): + break + if summed: + pulled = _add(current, work[j]) + else: + out.append(current) + pulled = work[j] + work[i + 1 : j + 1] = [pulled, *work[i + 1 : j]] + current = pulled + i += 1 + j += 1 + out.append(current) + i += 1 + return out + + +def _rises_earlier( + steps: Sequence[Step], clear: Callable[[Sequence[Step]], bool], axis: str +) -> List[Step]: + """Step 3: each rise on `axis` not right after another step on it, swapped earlier one step at a + time while the path up to it stays clear.""" + work = [dict(s) for s in steps] + for k in range(1, len(work)): + if _one_axis(work[k]) != axis or not _rising(work[k]) or _one_axis(work[k - 1]) == axis: + continue + m = k + while m > 0: + swapped = [*work[: m - 1], work[m], work[m - 1]] + if not clear(swapped): + break + work[m - 1], work[m] = work[m], work[m - 1] + m -= 1 + return work + + +def _neither_vertical_nor_turning(a: Step, b: Step) -> bool: + return not (axes(a) | axes(b)) & {"Z", "GZ", "GR"} + + +def _parts_apart(a: Step, b: Step) -> bool: + joined = axes(a) | axes(b) + return not any(v in joined and joined & set(HORIZONTAL[v]) for v in VERTICAL) + + +def _join( + steps: Sequence[Step], + clear: Callable[[Sequence[Step]], bool], + allowed: Callable[[Step, Step], bool], +) -> List[Step]: + """Step 5's pass: each move takes in the next while `allowed` and the joined move is clear.""" + out: List[Step] = [] + for step in steps: + if out and allowed(out[-1], step): + joined = _add(out[-1], step) + if clear([*out[:-1], joined]): + out[-1] = joined + continue + out.append(dict(step)) + return out diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles.py new file mode 100644 index 00000000000..efe2e236896 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles.py @@ -0,0 +1,85 @@ +"""What a pod's moves must clear, as Biomek lists it for a pod: the instrument's structure (each +face widened by its buffer), one box per deck position (from its ALP's base up to the higher of +its `min_safe_height` and what stands on it) and each position's own obstacles (a trash's walls), +all in Biomek's frame (cm). The device builds one list per pod (`BiomekI7Device.obstacles`); an +operation that works in positions leaves their boxes out (`Obstacles.without`), their own +obstacles staying in.""" + +from dataclasses import dataclass +from functools import cached_property +from typing import Iterable, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.pod_model import ( + OPEN, + Bounds, + Part, + _box, +) + + +def obstacle_part( + name: str, + x: Tuple[Optional[float], Optional[float]], + y: Tuple[Optional[float], Optional[float]], + z: Tuple[Optional[float], Optional[float]], + buffer: float = 0.0, +) -> Part: + """A fixed box in Biomek's frame (cm), a bound that is None open on that side, each face + widened by `buffer`, as Biomek makes an obstacle.""" + + def lo(v: Optional[float]) -> float: + return -OPEN if v is None else v - buffer + + def hi(v: Optional[float]) -> float: + return OPEN if v is None else v + buffer + + return Part(name, _box(lo(x[0]), hi(x[1]), lo(y[0]), hi(y[1])), lo(z[0]), hi(z[1])) + + +def bounds_of(parts: Sequence[Part]) -> Bounds: + """The bounds of `parts`: x0, x1, y0, y1, z0, z1 (cm).""" + xs = [px for part in parts for px, _ in part.outline] + ys = [py for part in parts for _, py in part.outline] + return ( + min(xs), + max(xs), + min(ys), + max(ys), + min(p.z_low for p in parts), + max(p.z_high for p in parts), + ) + + +@dataclass(frozen=True) +class Obstacles: + """What a pod's moves must clear, in Biomek's frame (cm): the instrument's obstacles (checked + against the pod's body as well as its parts) and the deck's boxes (positions and their own + obstacles, checked against the pipettor's and the gripper's parts, what it holds included).""" + + structure: Tuple[Part, ...] = () + deck: Tuple[Part, ...] = () + # The names of the deck's parts that are positions' boxes (the others are their own obstacles). + holders: Tuple[str, ...] = () + + @cached_property + def ceilings(self) -> Tuple[Tuple[Part, Bounds], ...]: + """The structure's parts with no top (checked against the pod's body too), with bounds.""" + return tuple((p, bounds_of([p])) for p in self.structure if p.z_high >= OPEN) + + @cached_property + def everything(self) -> Tuple[Tuple[Part, Bounds], ...]: + """Every part, with bounds.""" + return tuple((p, bounds_of([p])) for p in (*self.structure, *self.deck)) + + def without(self, holders: Iterable[str]) -> "Obstacles": + """These obstacles with the boxes of the positions named in `holders` left out (an operation + working in them); their own obstacles and the structure stay. A name that is not a position's + box leaves nothing out.""" + out = {h for h in holders if h in self.holders} + if not out: + return self + return Obstacles( + self.structure, + tuple(p for p in self.deck if p.name not in out), + tuple(n for n in self.holders if n not in out), + ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles_tests.py new file mode 100644 index 00000000000..66db9cb0b7a --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/obstacles_tests.py @@ -0,0 +1,30 @@ +import unittest + +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.obstacles import Obstacles, obstacle_part + + +class WithoutTests(unittest.TestCase): + def setUp(self) -> None: + self.structure = (obstacle_part("Shield", (150.0, None), (None, None), (None, None)),) + self.deck = ( + obstacle_part("P1", (0.0, 12.8), (0.0, 8.6), (-1.0, 17.0)), + obstacle_part("P1 wall", (0.0, 0.2), (0.0, 8.6), (None, 20.0)), + obstacle_part("P2", (14.0, 26.8), (0.0, 8.6), (-1.0, 17.0)), + ) + self.obstacles = Obstacles(self.structure, self.deck, ("P1", "P2")) + + def test_a_step_leaves_out_only_its_holders_box(self) -> None: + # A step's own moves leave the position they work in out, whole; its own obstacles (a trash's + # walls) and the instrument's structure stay. + out = self.obstacles.without(["P1"]) + self.assertEqual([p.name for p in out.deck], ["P1 wall", "P2"]) + self.assertEqual(out.structure, self.structure) + self.assertEqual(out.holders, ("P2",)) + + def test_a_name_that_is_no_holder_leaves_nothing_out(self) -> None: + self.assertIs(self.obstacles.without(["P1 wall", "nothing"]), self.obstacles) + self.assertIs(self.obstacles.without([]), self.obstacles) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/pod_model.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/pod_model.py new file mode 100644 index 00000000000..deb01ce4d30 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/pod_model.py @@ -0,0 +1,435 @@ +"""A pod's own parts at a pose, as Biomek models them, and the pose they are built from. + +`PodModel` holds one pod's configuration and builds its parts (the gripper's, what it holds, the +pipettor's, the pod's body) at a pose (`PodState`), each set of parts built once per pose: a +planner's sweeps and searches ask for the same poses many times. The parts, in Biomek's frame (cm; +X along the rail, Y towards the front, Z up from the deck): + +- the gripper, about its rotation centre (`pod_geometry`: the pod's X + `GripperXOffset` - + `PadsCenterToRotationCenter`, its GY + `GripperYOffset` - `FingerCenterOffset`), its hand's + bottom at GZ + `GripperZOffset` + the fingers' height (the deepest point of the finger profile, + `Finger/Base`), so the fingertips are at GZ + `GripperZOffset`: + - the upper hand, from the lower hand's top (`Lowerhand/ZSpan`) up without end; it does not turn; + - the lower hand with the fingers' top part, down to the top part's depth (`TopPart/ZSpan`); + - the lower fingers, down to the fingertips; + - what it holds, from its bottom (the fingertips less the grip height) to its top; + the last three turned by GR; each widened by `AvoidanceMargin` on every side, above and below + too; when planning, each bottom also `AdditionalSafeHeightGripper` lower (`planning_pad`); +- a Span-8's probes: each probe a band in Y halfway to its neighbours (the end ones out to + `Mandrel1YOffset`), below the LLS module a box `ProbeSize` wide from the end of its tip up to + `MandrelExtender` above its mandrel's bottom, widened by `AvoidanceMargin` and, in Z, by + `AdditionalSafeHeight`; above it the probe's upper part, up without end; +- the 96-head: its body (`HeadBodyXSpan` x `HeadBodyYSpan`, mandrel A1 at the pod's X and Y, + the mandrels centred), from the end of its tips up without end. + +A Span-8's tubing bundle (`LLSWireModel`, `span8_bundle_box`, `bundle_part`) is not one of the +pipettor's parts: Biomek tests it against held labware only (nothing else meets it), as the own +check does (`check.own_collisions`). +""" + +import functools +import math +from dataclasses import dataclass +from functools import cached_property +from typing import Any, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple, cast + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration + +OPEN = 1e10 # a part with no top + + +Point = Tuple[float, float] +# A part's bounds: x0, x1, y0, y1, z0, z1 (cm). +Bounds = Tuple[float, float, float, float, float, float] + + +@dataclass(frozen=True) +class Part: + """A part of a pod at a pose: a convex outline seen from above (deck cm) and its Z range.""" + + name: str + outline: Tuple[Point, ...] + z_low: float + z_high: float + + @cached_property + def extent(self) -> Tuple[float, float, float, float]: + """Its outline's bounds: x0, x1, y0, y1.""" + xs, ys = [p[0] for p in self.outline], [p[1] for p in self.outline] + return min(xs), max(xs), min(ys), max(ys) + + +@dataclass(frozen=True) +class GripperState: + """The gripper's axes in Biomek's units (cm, degrees) and what it holds.""" + + gy: float + gz: float + gr: float + gg: float + held: Optional[g.HeldLabware] = None + + +@dataclass(frozen=True) +class PipettorState: + """The pipettor's axes in Biomek's units: a Span-8's probes' Y (`ys`), mandrel bottoms (`zs`) + and tip lengths below them, or the 96-head's Y and Z (one each) and its tips' length.""" + + ys: Tuple[float, ...] + zs: Tuple[float, ...] + tips: Tuple[float, ...] + # The 96-head's loaded tips: (first column, last column, first row, last row), from 0; None + # for the whole head. + tip_block: Optional[Tuple[int, int, int, int]] = None + + +def _box(x0: float, x1: float, y0: float, y1: float) -> Tuple[Point, ...]: + return ((x0, y0), (x1, y0), (x1, y1), (x0, y1)) + + +def _place(outline: Sequence[Point], cx: float, cy: float, degrees: float) -> Tuple[Point, ...]: + c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) + return tuple((cx + x * c - y * s, cy + x * s + y * c) for x, y in outline) + + +def finger_depth(model: Dict) -> float: + """How far below the hand's bottom the fingertips are: the finger profile's deepest point.""" + return -float(min(p["Y"] for p in model["Finger"]["Base"])) + + +def _gripper_parts( + config: PodConfiguration, x: float, state: GripperState, pad: float +) -> List[Part]: + """The gripper's parts with the pod's X at `x`, each widened by `AvoidanceMargin` on every + side (as Biomek builds them: above and below too) and each bottom `pad` (cm) lower.""" + geo, model = config.geometry, config.gripper_model + gm = PodModel.of(config).gripper_model + assert gm is not None + margin = geo.avoidance_margin + cx = x + geo.gripper_x_offset - gm.pads_center_to_rotation_center + cy = state.gy + geo.gripper_y_offset - gm.finger_center_offset + depth = PodModel.of(config).finger_depth + hand = state.gz + geo.gripper_z_offset + depth # the hand's bottom + tips = hand - depth + hand_top = hand + model["Lowerhand"]["ZSpan"] + top_part = hand - model["Finger"]["TopPart"]["ZSpan"] + fixed, turning = g.gripper_boxes(gm, margin, state.gg, state.held) + parts = [Part("upper hand", _place(_box(*fixed[0]), cx, cy, 0.0), hand_top, OPEN)] + parts.append(Part("lower hand", _place(_box(*turning[0]), cx, cy, state.gr), top_part, hand_top)) + parts.append(Part("fingers", _place(_box(*turning[1]), cx, cy, state.gr), tips, top_part)) + if state.held is not None: + bottom = tips - state.held.grip_offset + for box in turning[2:]: + outline = _place(_box(*box), cx, cy, state.gr) + parts.append(Part("held labware", outline, bottom, bottom + state.held.height)) + return [ + Part( + p.name, p.outline, p.z_low - margin - pad, p.z_high if p.z_high >= OPEN else p.z_high + margin + ) + for p in parts + ] + + +def _span8_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + """A Span-8's probes with the pod's X at `x` (probe axes at X).""" + geo, s = config.geometry, config.settings + margin, lift = geo.avoidance_margin, geo.additional_safe_height + half = s["ProbeSize"] / 2 + extender = s["MandrelExtender"] + ys = state.ys + parts = [] + for i, (y, z, tip) in enumerate(zip(ys, state.zs, state.tips)): + low = y - geo.mandrel1_y_offset if i == 0 else (ys[i - 1] + y) / 2 + high = y + geo.mandrel1_y_offset if i == len(ys) - 1 else (y + ys[i + 1]) / 2 + low, high = min(low, high), max(low, high) + lower = _box(x - half - margin, x + half + margin, low - margin, high + margin) + parts.append(Part(f"probe {i + 1}", lower, z - tip - lift, z + extender)) + upper = _box(x - geo.mandrel1_x_offset - margin, x + half + margin, low - margin, high + margin) + parts.append(Part(f"probe {i + 1} upper part", upper, z + extender, OPEN)) + return parts + + +@dataclass(frozen=True) +class BundleBox: + """The space a Span-8's tubing bundle may hang in (Biomek's frame, cm), open upward.""" + + x0: float + x1: float + y0: float + y1: float + z_low: float + + +def bundle_part(config: PodConfiguration, x: float, state: PipettorState) -> Optional[Part]: + """A Span-8's tubing bundle as a part (`span8_bundle_box`: no margin, open upward), which Biomek + tests against held labware only; None for any other pod.""" + box = span8_bundle_box(config, x, state) + if box is None: + return None + return Part("tubing bundle", _box(box.x0, box.x1, box.y0, box.y1), box.z_low, OPEN) + + +def span8_bundle_box( + config: PodConfiguration, x: float, state: PipettorState +) -> Optional[BundleBox]: + """Where a Span-8's tubing bundle hangs with the probe axes at `x`, from `LLSWireModel` (None + for any other pod): + + - X: from the probes' axis + `WireStartXOffset` to + `AnchorXOffset`; + - Y: the probes' range, out to halfway towards the anchor's (`AnchorCenterY` ± + `AnchorHalfLength`); + - Z: up from the lower of where the bundle leaves the lowest probe (its mandrel's bottom + + `MandrelExtender` + `FixedTipZOriginToWireOffset`) and the loop's bottom, `WireBottomAtZMax` + less half as far as that probe is below its highest Z. The lowest probe is the one furthest + below its own highest Z (`Z1`..`Z8` limits). + No `AvoidanceMargin`: the bundle is not widened. + """ + if config.module_type != "span8": + return None + wire = config.settings["LLSWireModel"] + extender = config.settings["MandrelExtender"] + lowest = [] + for i, z in enumerate(state.zs): + low, high = config.limits.get(f"Z{i + 1}", config.limits.get("Z", (z, z))) + z = max(low, min(high, z)) + lowest.append((high - z, z + extender + wire["FixedTipZOriginToWireOffset"])) + below, leaves = max(lowest) + y0, y1 = min(state.ys), max(state.ys) + near, far = ( + wire["AnchorCenterY"] - wire["AnchorHalfLength"], + wire["AnchorCenterY"] + wire["AnchorHalfLength"], + ) + return BundleBox( + x + wire["WireStartXOffset"], + x + wire["AnchorXOffset"], + min(y0, (y0 + near) / 2), + max(y1, (y1 + far) / 2), + min(leaves, wire["WireBottomAtZMax"] - below / 2), + ) + + +def _head96_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + """The 96-head with mandrel A1 at (`x`, `state.ys[0]`), its bottom at `state.zs[0]`.""" + geo, s = config.geometry, config.settings + margin = geo.avoidance_margin + body_x, body_y = s["HeadBodyXSpan"], s["HeadBodyYSpan"] + grid_x = ((geo.mandrels_x or 1) - 1) * geo.mandrel_x_spacing + grid_y = ((geo.mandrels_y or 1) - 1) * geo.mandrel_y_spacing + left = x - (body_x - grid_x) / 2 + back = state.ys[0] - (body_y - grid_y) / 2 # A1 is the back row; Y runs to the front + outline = _box(left - margin, left + body_x + margin, back - margin, back + body_y + margin) + parts = [Part("96-head", outline, state.zs[0], OPEN)] + if state.tips[0] > 0: + # The tips as Biomek boxes them: the block of mandrels that carry one, half a pitch around it. + sx, sy = geo.mandrel_x_spacing, geo.mandrel_y_spacing + c0, c1, r0, r1 = state.tip_block or (0, (geo.mandrels_x or 1) - 1, 0, (geo.mandrels_y or 1) - 1) + block = _box( + x + (c0 - 0.5) * sx - margin, + x + (c1 + 0.5) * sx + margin, + state.ys[0] + (r0 - 0.5) * sy - margin, + state.ys[0] + (r1 + 0.5) * sy + margin, + ) + parts.append(Part("96-head tips", block, state.zs[0] - state.tips[0], state.zs[0])) + return parts + + +def _pipettor_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + if config.module_type == "span8": + return span8_parts(config, x, state) + return head96_parts(config, x, state) + + +def _body_part(config: PodConfiguration, x: float, y: float) -> Part: + """The pod's body seen from above with mandrel A1 / probe 1 at (`x`, `y`), from below the deck up + without end: what an obstacle with no top (a wall, a ceiling) must not overlap.""" + (x0, x1), (y0, y1) = g.pod_xy_box(config.geometry, x, y) + return Part("pod body", _box(x0, x1, y0, y1), -OPEN, OPEN) + + +def _moving_parts( + config: PodConfiguration, + x: float, + gripper: Optional[GripperState], + pipettor: PipettorState, + pad: float, +) -> List[Part]: + """The pod's parts the world is checked against: the pipettor's (its lower parts reaching + `AdditionalSafeHeight` + `AvoidanceMargin` below the tips' ends, the Span-8's already reaching the + first) and the gripper's.""" + geo = config.geometry + parts = [] + for part in pipettor_parts(config, x, pipettor): + if part.name.startswith("96-head"): + drop = geo.additional_safe_height + geo.avoidance_margin + elif part.name.startswith("probe ") and not part.name.endswith("upper part"): + drop = geo.avoidance_margin + else: + drop = 0.0 + parts.append(Part(part.name, part.outline, part.z_low - drop, part.z_high)) + if gripper is not None: + parts += gripper_parts(config, x, gripper, pad) + return parts + + +class PodState(NamedTuple): + """A pod's pose in Biomek's units: X, the gripper's (None on a pod without one) and the + pipettor's.""" + + x: float + gripper: Optional[GripperState] + pipettor: PipettorState + + +# How many poses' parts each model keeps. +CACHED_POSES = 4096 + + +class PodModel: + """One pod's parts at any pose, from its configuration (`of`). The configuration's figures the + parts read are taken when the model is built; `of` builds a new model when they change.""" + + def __init__(self, config: PodConfiguration): + self.config = config + model = config.gripper_model + self.gripper_model: Optional[g.GripperModel] = g.GripperModel.from_bif(model) if model else None + self.finger_depth = finger_depth(model) if model else 0.0 + self.gripper_parts = functools.lru_cache(CACHED_POSES)(self._gripper_parts) + self.pipettor_parts = functools.lru_cache(CACHED_POSES)(self._pipettor_parts) + + def _gripper_parts(self, x: float, state: GripperState, pad: float) -> Tuple[Part, ...]: + return tuple(_gripper_parts(self.config, x, state, pad)) + + def _pipettor_parts(self, x: float, state: PipettorState) -> Tuple[Part, ...]: + return tuple(_pipettor_parts(self.config, x, state)) + + @property + def channel_z_axes(self) -> List[str]: + """The axes whose height is the channels' bottom: `Z` on a Multichannel, `Z1`-`Z8` on a + Span-8.""" + return [f"Z{i}" for i in range(1, 9)] if self.config.module_type == "span8" else ["Z"] + + @property + def pose_axes(self) -> List[str]: + """The axes a pose is read from: X, the gripper's (where there is one), Y and the channels'.""" + ys = [f"Y{i}" for i in range(1, 9)] if self.config.module_type == "span8" else ["Y"] + grips = ["GY", "GZ", "GR", "GG"] if self.config.gripper_model else [] + return ["X", *grips, *ys, *self.channel_z_axes] + + def state( + self, + counts: Mapping[str, int], + held: Optional[g.HeldLabware], + tip_lengths: Mapping[str, float], + tip_block: Optional[Tuple[int, int, int, int]], + ) -> PodState: + """The pose from the position (counts) of each of `pose_axes`, what the gripper holds, the + channels' tip lengths (cm, by channel Z axis) and the 96-head's loaded tips' block.""" + d = self.config + channels = self.channel_z_axes + ys = [f"Y{i}" for i in range(1, 9)] if d.module_type == "span8" else ["Y"] + v = {n: d.to_value("Y" if n in ys else n, c) for n, c in counts.items()} # type: ignore[arg-type] + if d.module_type == "span8": + # Each probe's Y counts from its own narrowest place (`probe_y`), not probe 1's. + v.update({n: d.probe_y(i, counts[n]) for i, n in enumerate(ys, 1)}) + gripper = GripperState(v["GY"], v["GZ"], v["GR"], v["GG"], held) if d.gripper_model else None + pipettor = PipettorState( + tuple(v[n] for n in ys), + tuple(v[z] for z in channels), + tuple(tip_lengths.get(z, 0.0) for z in channels), + tip_block, + ) + return PodState(v["X"], gripper, pipettor) + + @staticmethod + def of(config: PodConfiguration) -> "PodModel": + """The model of `config`, built once and again only when a figure its parts read changes. It + is kept on the configuration (`_MODEL`), so the two are freed together.""" + signature = _signature(config) + found = config.__dict__.get(_MODEL) + if found is None or found[0] != signature: + found = (signature, PodModel(config)) + config.__dict__[_MODEL] = found + return cast(PodModel, found[1]) + + +# The attribute of a `PodConfiguration` its model is kept under: (its signature, the model). +_MODEL = "_pod_model" + + +def _signature(config: PodConfiguration) -> Tuple[Any, ...]: + """What the parts read from `config`: its module type, geometry (frozen), gripper model (by + identity) and the settings the pipettor's parts take.""" + s = config.settings + return ( + config.module_type, + config.geometry, + id(config.gripper_model), + s.get("ProbeSize"), + s.get("MandrelExtender"), + s.get("HeadBodyXSpan"), + s.get("HeadBodyYSpan"), + ) + + +def on_quarter(config: PodConfiguration, gr: float) -> bool: + """Whether the gripper at `gr` (degrees) is on a quarter turn. Biomek holds the angle it was + sent in degrees, so a quarter turn is exactly one; ours is read back from counts, a quarter + within a count of it: on a quarter turn when its counts are the quarter's.""" + quarter = round(gr / 90.0) * 90.0 + return config.to_counts("GR", gr) == config.to_counts("GR", quarter) + + +def planning_pad(config: PodConfiguration) -> float: + """How far (cm) Biomek's planner pads the gripper below (`gripper_parts`): + `AdditionalSafeHeightGripper`. Its move checks pad by 0.""" + return config.geometry.additional_safe_height_gripper + + +def gripper_below(config: PodConfiguration, x: float, state: GripperState) -> float: + """How far below GZ (cm) the gripper's lowest point is (its fingers, or what it holds): the + parts' lowest bottom without their `AvoidanceMargin`, the offset Biomek's safe height takes.""" + low = min(part.z_low for part in gripper_parts(config, x, state)) + return state.gz - (low + config.geometry.avoidance_margin) + + +def gripper_parts( + config: PodConfiguration, x: float, state: GripperState, pad: float = 0.0 +) -> List[Part]: + """The gripper's parts with the pod's X at `x`. `pad` (cm) lowers every part's bottom: Biomek's planning model pads the gripper below by + `AdditionalSafeHeightGripper`, its move checks by 0.""" + return list(PodModel.of(config).gripper_parts(x, state, pad)) + + +def pipettor_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + """The pipettor's parts (a Span-8's probes, the 96-head) with the pod's X at `x`.""" + return list(PodModel.of(config).pipettor_parts(x, state)) + + +def span8_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + """A Span-8's probes with the pod's X at `x` (probe axes at X).""" + return _span8_parts(config, x, state) + + +def head96_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: + """The 96-head with mandrel A1 at (`x`, `state.ys[0]`), its bottom at `state.zs[0]`.""" + return _head96_parts(config, x, state) + + +def body_part(config: PodConfiguration, x: float, y: float) -> Part: + """The pod's body seen from above with mandrel A1 / probe 1 at (`x`, `y`), from below the deck up + without end: what an obstacle with no top (a wall, a ceiling) must not overlap.""" + return _body_part(config, x, y) + + +def moving_parts( + config: PodConfiguration, + x: float, + gripper: Optional[GripperState], + pipettor: PipettorState, + pad: float = 0.0, +) -> List[Part]: + """The pod's parts the world is checked against: the pipettor's (its lower parts reaching + `AdditionalSafeHeight` + `AvoidanceMargin` below the tips' ends, the Span-8's already reaching the + first) and the gripper's (`gripper_parts`, with `pad`).""" + return _moving_parts(config, x, gripper, pipettor, pad) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/search.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/search.py new file mode 100644 index 00000000000..8f7ed25d6e6 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/search.py @@ -0,0 +1,444 @@ +"""Biomek's search for a pod's path, when the direct way is not clear: an A* over the pod's +positions, each step one axis of one part to its next contact or its destination coordinate +(`contact_stop`), every step checked as the move check checks it. `pod_search` builds a pod's +neighbours from its pose (`pose_of`), how its axes plan (`planned`) and the check (`clear`), the +pod's own (`Pod`) passed in.""" + +import math +from typing import ( + Callable, + Dict, + Hashable, + Iterable, + List, + Mapping, + Optional, + Sequence, + Set, + Tuple, + TypeVar, + cast, +) + +from pylabrobot.beckman_coulter.biomek_i7.driver import motion +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.obstacles import Obstacles +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import pod_model + +# A move: axis targets in counts, sent together. +Move = Dict[str, int] + +State = TypeVar("State", bound=Hashable) + + +class NoPathError(RuntimeError): + """No path to the destination: the search found none, or reached its limit. Nothing was sent.""" + + +def same_value(a: float, b: float) -> bool: + """Whether two of Biomek's values are the same: equal within 1e-12 of the smaller magnitude, + and never less than 1e-12.""" + return abs(a - b) <= max(min(abs(a), abs(b)) * 1e-12, 1e-12) + + +class OpenSet: + """Biomek's open set: a binary heap on each node's cost estimate, the same costs (`same_value`) counting as + equal. A node rises only past a strictly larger cost; one sinking takes the smaller child (the + left on a tie) and sinks below it when that child's cost is not larger. A node reached again + more cheaply has its cost lowered where it stands.""" + + def __init__(self) -> None: + self.heap: List[Hashable] = [] + self.cost: Dict[Hashable, float] = {} + self.at: Dict[Hashable, int] = {} + + def __bool__(self) -> bool: + return bool(self.heap) + + def _before(self, a: Hashable, b: Hashable) -> bool: + """Whether `a` may stand above `b`: its cost the same or less.""" + return same_value(self.cost[a], self.cost[b]) or self.cost[a] < self.cost[b] + + def _swap(self, i: int, j: int) -> None: + h = self.heap + h[i], h[j] = h[j], h[i] + self.at[h[i]], self.at[h[j]] = i, j + + def _rise(self, i: int) -> None: + while i > 0: + up = (i - 1) // 2 + if self._before(self.heap[up], self.heap[i]): + return + self._swap(i, up) + i = up + + def push(self, node: Hashable, cost: float) -> None: + """Add `node`, or lower its cost if it is open with a larger one.""" + if node in self.at: + if cost < self.cost[node]: + self.cost[node] = cost + self._rise(self.at[node]) + return + self.cost[node] = cost + self.heap.append(node) + self.at[node] = len(self.heap) - 1 + self._rise(len(self.heap) - 1) + + def pop(self) -> Hashable: + """Take the node at the top.""" + h = self.heap + top = h[0] + last = h.pop() + del self.at[top] + if h: + h[0] = last + self.at[last] = 0 + i = 0 + while True: + left, right = 2 * i + 1, 2 * i + 2 + if left >= len(h): + break + child = left + if right < len(h) and not self._before(h[left], h[right]): + child = right + if not self._before(h[child], h[i]): + break + self._swap(i, child) + i = child + return top + + +def search( + start: State, + is_destination: Callable[[State], bool], + neighbours: Callable[[State], Iterable[Tuple[State, Move, float]]], + heuristic: Callable[[State], float], + limit: int, +) -> List[Move]: + """Biomek's A*: from `start`, the cheapest moves (as `neighbours` gives them: the next state, + the move to it and its cost) to a state `is_destination` accepts, guided by `heuristic`, the + open nodes in Biomek's heap (`OpenSet`); nodes once expanded are not reopened; at most `limit` + expansions. + + Raises: + NoPathError: when the open set runs out ("no path possible") or the limit is reached ("all + possible paths exhausted or search limit reached"). + """ + g: Dict[State, float] = {start: 0.0} + parent: Dict[State, Tuple[State, Move]] = {} + open_set = OpenSet() + open_set.push(start, heuristic(start)) + closed: Set[State] = set() + expansions = 0 + while open_set: + state = cast(State, open_set.pop()) + if is_destination(state): + moves: List[Move] = [] + while state in parent: + state, move = parent[state] + moves.append(move) + return moves[::-1] + closed.add(state) + expansions += 1 + if expansions > limit: + raise NoPathError("all possible paths exhausted or search limit reached") + for following, move, cost in neighbours(state): + if following in closed: + continue + total = g[state] + cost + if total < g.get(following, math.inf): + g[following] = total + parent[following] = (state, move) + open_set.push(following, total + heuristic(following)) + raise NoPathError("no path possible") + + +def contact_stop( + value: float, + positive: bool, + near: float, + far: float, + faces: Iterable[Tuple[float, float]], + destination: Optional[float], +) -> Optional[float]: + """Where a part moving along one axis from `value` stops, as Biomek's search steps: at the next + obstacle contact (its leading edge, `far` if `positive` else `near`, touching an obstacle's near + face; else its trailing edge clearing the obstacle's far face) or at the destination coordinate, + whichever comes first; None with neither ahead. `faces`: each obstacle's (low, high) along the + axis, of those the part meets across the axis.""" + best: Optional[float] = None + + def take(c: float) -> None: + nonlocal best + if best is None or (c < best if positive else c > best): + best = c + + for low, high in faces: + if positive: + if low - far > EPSILON: + take(value + (low - far)) + elif high - near > EPSILON: + take(value + (high - near)) + else: + if near - high > EPSILON: + take(value - (near - high)) + elif far - low > EPSILON: + take(value - (far - low)) + if destination is not None and ( + destination > value + EPSILON if positive else destination < value - EPSILON + ): + take(destination) + return best + + +# Biomek's tolerance in its search (cm, degrees). +EPSILON = 1e-4 + + +def pod_search( + config: PodConfiguration, + positions: Mapping[str, motion.CPos], + targets: Mapping[str, int], + obstacles: Optional[Obstacles], + pose_of: Callable[[Mapping[str, motion.CPos]], Optional[pod_model.PodState]], + planned: Callable[[Mapping[str, motion.CPos], Mapping[str, int]], Dict[str, motion.CPos]], + clear: Callable[..., bool], + channel_z_axes: Sequence[str], + x_bounds: Optional[Tuple[float, float]] = None, +) -> List[Move]: + """Biomek's search (`search`) from where the pod is to `targets` (counts), for a planned + move whose direct way is not clear. Each step moves one axis of one part to its next contact + or its destination coordinate (`contact_stop`): X carries both parts, Y moves the + pipettor (only with GR on a multiple of 90 degrees), GY the gripper, GR turns the gripper a + quarter turn (to the bracketing quarters off them, straight to an off-quarter destination + within one). Channel Z axes and GZ in `targets` join the search: up to the part's next contact + above (its bottom at an obstacle's top) or its target, down only near the destination (within + twice the part's footprint of its X and Y) to the next top below or its target; without them + the heights are kept (Biomek's travel stage). Every step is checked as `_clear` checks it, + and its stops come from the same boxes; cost its length + 1 per moving part, + + `RotationPenalty` per turn or per move on an axis the destination leaves free; at most + `AStarSearchLimit` expansions; ties to the first found. A Span-8's span is set first, as + Biomek sets it before planning. `x_bounds` (cm): where X may go, within its travel (a pod + moving aside keeps to its side). + + Raises: + NoPathError: as `search`. + """ + d = config + pad = pod_model.planning_pad(d) # the planner's gripper, its contact stops too + eps = EPSILON + limit = int(d.settings["AStarSearchLimit"]) + penalty = float(d.settings["RotationPenalty"]) + first: List[Move] = [] + start: Dict[str, motion.CPos] = dict(positions) + wanted = dict(targets) + if "S" in wanted: + span = {"S": wanted.pop("S")} + if not clear([span], start): + raise NoPathError("the span cannot be set where the pod is") + first.append(span) + start = planned(start, span) + channels = list(channel_z_axes) + heights = {a: wanted.pop(a) for a in [*channels, "GZ"] if a in wanted} # counts + goal = pose_of(planned(start, wanted)) + world = obstacles + if goal is None or world is None: + raise NoPathError("a position is not known") + gx, gg, gp = goal + dest = { + "X": gx if "X" in wanted else None, + "Y": gp.ys[0] if "Y" in wanted or "Y1" in wanted else None, + "GY": gg.gy if gg is not None and "GY" in wanted else None, + "GR": gg.gr if gg is not None and "GR" in wanted else None, + } + zdest = {a: d.to_value(a, c) for a, c in heights.items()} # cm + statics = [(*b[:4], b[4], b[5]) for _, b in world.everything] + y_axes = [f"Y{i}" for i in range(1, 9)] if d.module_type == "span8" else ["Y"] + keyed = ["X", *y_axes, "GY", "GR", *channels, "GZ"] + states: Dict[Tuple[int, ...], Dict[str, motion.CPos]] = {} + + def key(positions: Mapping[str, motion.CPos]) -> Tuple[int, ...]: + out = tuple(int(positions[a][1] or 0) for a in keyed if a in positions) + states[out] = dict(positions) + return out + + def values(positions: Mapping[str, motion.CPos]) -> Dict[str, float]: + pose = pose_of(positions) + assert pose is not None + x, g, p = pose + out = {"X": x, "Y": p.ys[0], **dict(zip(channels, p.zs))} + if g is not None: + out.update(GY=g.gy, GR=g.gr, GZ=g.gz) + return out + + def is_destination(state: Tuple[int, ...]) -> bool: + positions = states[state] + v = values(positions) + return all( + abs(v[a] - want) <= (0.01 if a == "GR" else 0.001) + for a, want in dest.items() + if want is not None + ) and all(positions[a][1] == c for a, c in heights.items()) + + def heuristic(state: Tuple[int, ...]) -> float: + v = values(states[state]) + dx = 0.0 if dest["X"] is None else v["X"] - dest["X"] + dy = 0.0 if dest["Y"] is None else v["Y"] - dest["Y"] + dz = max((abs(v[a] - z) for a, z in zdest.items() if a != "GZ"), default=0.0) + out = math.sqrt(dx * dx + dy * dy + dz * dz) + if "GY" in v: + dgy = 0.0 if dest["GY"] is None else v["GY"] - dest["GY"] + dgz = v["GZ"] - zdest["GZ"] if "GZ" in zdest else 0.0 + out += math.sqrt(dx * dx + dgy * dgy + dgz * dgz) + return out + + def extent(parts: Sequence[pod_model.Part]) -> Tuple[float, float, float, float, float]: + return ( + min(p.extent[0] for p in parts), + max(p.extent[1] for p in parts), + min(p.extent[2] for p in parts), + max(p.extent[3] for p in parts), + min(p.z_low for p in parts), + ) + + def boxes(others: Sequence[pod_model.Part]) -> Sequence[Tuple[float, ...]]: + return [*statics, *((*o.extent, o.z_low, o.z_high) for o in others)] + + def faces( + moving: Sequence[pod_model.Part], others: Sequence[pod_model.Part], along_x: bool + ) -> Tuple[float, float, List[Tuple[float, float]]]: + x0, x1, y0, y1, bottom = extent(moving) + met = [] + for ox0, ox1, oy0, oy1, _, top in boxes(others): + if not bottom + eps < top: + continue + lo, hi = (oy0, oy1) if along_x else (ox0, ox1) + if lo - eps > (y1 if along_x else x1) or hi + eps < (y0 if along_x else x0): + continue + met.append((ox0, ox1) if along_x else (oy0, oy1)) + return (x0, x1, met) if along_x else (y0, y1, met) + + def vertical( + moving: Sequence[pod_model.Part], others: Sequence[pod_model.Part], up: bool + ) -> Optional[float]: + """How far the part goes up before its bottom meets the nearest top above it, or down onto + the nearest top below it, over the obstacles under or over its footprint; None with none + that way (an obstacle open upwards is never cleared).""" + x0, x1, y0, y1, bottom = extent(moving) + best: Optional[float] = None + for ox0, ox1, oy0, oy1, _, top in boxes(others): + if ox0 - eps > x1 or ox1 + eps < x0 or oy0 - eps > y1 or oy1 + eps < y0: + continue + if up and bottom + eps < top < pod_model.OPEN: + c = top - bottom + elif not up and top + eps < bottom: + c = bottom - top + else: + continue + best = c if best is None else min(best, c) + return best + + def near(parts: Sequence[pod_model.Part], v: Mapping[str, float], gripper: bool) -> bool: + """Biomek's "near the destination": within twice the part's footprint of each X and Y the + destination gives.""" + x0, x1, y0, y1, _ = extent(parts) + checks = [("X", x1 - x0), ("GY" if gripper else "Y", y1 - y0)] + return all( + dest[a] is None or abs(v[a] - cast(float, dest[a])) - 2 * size <= eps for a, size in checks + ) + + def neighbours(state: Tuple[int, ...]) -> List[Tuple[Tuple[int, ...], Move, float]]: + positions = states[state] + pose = pose_of(positions) + assert pose is not None + x, g, p = pose + v = values(positions) + pipettor = pod_model.moving_parts(d, x, None, p) + gripper = pod_model.gripper_parts(d, x, g, pad) if g is not None else [] + out: List[Tuple[Tuple[int, ...], Move, float]] = [] + + def take(move: Dict[str, int], cost: float) -> None: + # Through `_planned`: a Span-8's Y and S set its probes' Y1-Y8, which `positions` holds. + try: + after = planned(positions, move) + except ValueError: + return + if all(after[a] == positions[a] for a in after): + return + if not clear([move], positions): + return + out.append((key(after), move, cost)) + + def add(axis: str, value: float, cost: float) -> None: + low, high = d.limits["GR" if axis == "GR" else axis] + if axis == "X" and x_bounds is not None: + low, high = max(low, x_bounds[0]), min(high, x_bounds[1]) + counts = d.to_counts(axis, min(max(value, low), high)) + if counts != d.to_counts(axis, v[axis]): + take({axis: counts}, cost) + + def lift( + axes: Sequence[str], + parts: Sequence[pod_model.Part], + others: Sequence[pod_model.Part], + up: bool, + ) -> None: + """One part's Z-type `axes` together towards their targets, to its next contact.""" + going = [ + a for a in axes if a in zdest and (zdest[a] > v[a] + eps if up else zdest[a] < v[a] - eps) + ] + if not going: + return + stop = vertical(parts, others, up) + move = {} + for a in going: + z = zdest[a] + if stop is not None: + z = min(z, v[a] + stop) if up else max(z, v[a] - stop) + move[a] = d.to_counts(a, z) + delta = max(abs(d.to_value(a, c) - v[a]) for a, c in move.items()) + take(move, delta + 1) + + def free(axis: str) -> float: + return penalty if dest[axis] is None else 0.0 + + if g is not None and not pod_model.on_quarter(d, g.gr): + # Biomek's gripper off a quarter turn: only the turns to the two quarters either side. + assert g is not None + for turn in (math.floor(g.gr / 90) * 90.0, math.ceil(g.gr / 90) * 90.0): + add("GR", turn, 1 + penalty) + return out + for positive in (True, False): + near_x, far_x, met = faces([*pipettor, *gripper], [], True) + stop = contact_stop(x, positive, near_x, far_x, met, dest["X"]) + if stop is not None: + parts = 2 if gripper else 1 + add("X", stop, parts * (abs(stop - x) + 1) + free("X")) + for positive in (True, False): + near_y, far_y, met = faces(pipettor, gripper, False) + stop = contact_stop(p.ys[0], positive, near_y, far_y, met, dest["Y"]) + if stop is not None: + add("Y", stop, abs(stop - p.ys[0]) + 1 + free("Y")) + lift(channels, pipettor, gripper, True) + if near(pipettor, v, False): + lift(channels, pipettor, gripper, False) + if g is None: + return out + for positive in (True, False): + near_gy, far_gy, met = faces(gripper, pipettor, False) + stop = contact_stop(g.gy, positive, near_gy, far_gy, met, dest["GY"]) + if stop is not None: + add("GY", stop, abs(stop - g.gy) + 1 + free("GY")) + lift(["GZ"], gripper, pipettor, True) + if near(gripper, v, True): + lift(["GZ"], gripper, pipettor, False) + quarter = round(g.gr / 90) * 90 + turns = [quarter - 90.0, quarter + 90.0] + if dest["GR"] is not None and abs(dest["GR"] - g.gr) <= 90 + eps: + turns.append(dest["GR"]) + for turn in turns: + add("GR", turn, 1 + penalty) + return out + + found = search(key(start), is_destination, neighbours, heuristic, limit) + return first + found diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/planning/traverse.py b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/traverse.py new file mode 100644 index 00000000000..b6cc59cd263 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/planning/traverse.py @@ -0,0 +1,243 @@ +"""The height a pod's tool travels at, as Biomek computes it: one path for every tool. + +Biomek finds what lies under a tool's footprint swept from where it is to where it goes (its +deck's covered positions), takes the tallest of them (`deck_height`), and each tool adds its own +margins to that (`Pod._safe_heights`). The deck's items are the deck check's own boxes (each +position up to its safe height, each position obstacle up to its top), so travel and check agree. + +The sweep, as Biomek's deck computes it, in whole millimetres: + +- the footprint's two corners (its low X / low Y corner where it is and where it goes) ordered by + X, each rounded down; its spans grow by 2 mm and are rounded down; +- the bounding box from the left corner to the right one plus the spans, rounded outward; +- when X changes, the band between the two lines of the move's slope through the footprint's outer + corners: the exact swept hexagon of the rectangle, rounded outward; +- an item counts when its rectangle touches that area (edges included): outside the bounding box + it does not; inside, on a move in Y alone it does, otherwise when it meets the band. +""" + +import math +from typing import Dict, Iterable, List, Literal, Mapping, Optional, Sequence, Tuple, Union + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.obstacles import Obstacles +from pylabrobot.beckman_coulter.biomek_i7.driver.planning.pod_model import ( + GripperState, + PodModel, + PodState, + gripper_below, + gripper_parts, +) + +# A rectangle in Biomek's frame, cm: x0, x1, y0, y1. +Rect = Tuple[float, float, float, float] + + +def covered(start: Rect, end: Rect, items: Iterable[Tuple[Rect, float]]) -> Sequence[float]: + """The tops of the `items` ((rectangle, top), cm) that the footprint covers going from `start` + to `end` (the same footprint, where it is and where it goes; cm).""" + sx, sy = start[0] * 10, start[2] * 10 + ex, ey = end[0] * 10, end[2] * 10 + xs = math.floor(max(start[1] - start[0], end[1] - end[0]) * 10 + 2) + ys = math.floor(max(start[3] - start[2], end[3] - end[2]) * 10 + 2) + (lx, ly), (rx, ry) = sorted(((sx, sy), (ex, ey))) + lx, ly, rx, ry = math.floor(lx), math.floor(ly), math.floor(rx), math.floor(ry) + bx0, bx1 = lx, math.ceil(rx + xs) + by0, by1 = math.floor(min(ly, ry)), math.ceil(max(ly, ry) + ys) + band: Optional[Tuple[float, float, float]] = None + if rx != lx: + s = (ry - ly) / (rx - lx) + b = ly - s * lx + if s > 0: + band = (s, math.floor(b - xs * s), math.ceil(b + ys)) + else: + band = (s, math.floor(b), math.ceil(b + ys - xs * s)) + tops = [] + for rect, top in items: + x0, x1, y0, y1 = (v * 10 for v in rect) + if x0 > bx1 or x1 < bx0 or y0 > by1 or y1 < by0: + continue + if band is not None: + s, low, high = band + lows, highs = (s * x0 + low, s * x1 + low), (s * x0 + high, s * x1 + high) + if min(lows) > y1 or max(highs) < y0: + continue + tops.append(top) + return tops + + +def deck_height(start: Rect, end: Rect, items: Iterable[Tuple[Rect, float]]) -> float: + """The tallest top the footprint covers going from `start` to `end`, cm; -inf over nothing.""" + return max(covered(start, end, items), default=-math.inf) + + +def rect_of(outline: Sequence[Tuple[float, float]]) -> Rect: + """An outline's bounds.""" + xs, ys = [p[0] for p in outline], [p[1] for p in outline] + return min(xs), max(xs), min(ys), max(ys) + + +# How a tool travels by default: "safe" (Biomek's safe height over its way), "max" (as high as it +# goes), or a height, mm of its lowest point above the deck. +TraverseDefault = Union[Literal["safe", "max"], float] + + +def traverse_default(value: Union[str, float]) -> TraverseDefault: + """`value` as a tool's default traverse height. + + Raises: + ValueError: for anything but "safe", "max" or a number. + """ + if value in ("safe", "max"): + return value # type: ignore[return-value] + if isinstance(value, (int, float)) and not isinstance(value, bool): + return float(value) + raise ValueError(f"a default traverse height is 'safe', 'max' or a height in mm, not {value!r}") + + +# -- a pod's travel heights ---------------------------------------------------------------------- + + +def head_box(config: PodConfiguration, state: PodState) -> Rect: + """The 96-head's pipettor box seen from above (`PodXSpan` x `PodYSpan` from mandrel A1 less + `Mandrel1XOffset` / `Mandrel1YOffset`), widened by `AvoidanceMargin`, cm.""" + geo = config.geometry + m = geo.avoidance_margin + x0 = state.x - geo.mandrel1_x_offset + y0 = state.pipettor.ys[0] - geo.mandrel1_y_offset + return x0 - m, x0 + geo.pod_x_span + m, y0 - m, y0 + geo.pod_y_span + m + + +def tips_block(config: PodConfiguration, state: PodState) -> Rect: + """The block of the 96-head's loaded tips seen from above (half a pitch round the mandrels that + carry one; every mandrel without a block given), widened by `AvoidanceMargin`, cm.""" + geo = config.geometry + m = geo.avoidance_margin + x, y = state.x, state.pipettor.ys[0] + sx, sy = geo.mandrel_x_spacing, geo.mandrel_y_spacing + c0, c1, r0, r1 = state.pipettor.tip_block or ( + 0, + (geo.mandrels_x or 1) - 1, + 0, + (geo.mandrels_y or 1) - 1, + ) + return ( + x + (c0 - 0.5) * sx - m, x + (c1 + 0.5) * sx + m, + y + (r0 - 0.5) * sy - m, y + (r1 + 0.5) * sy + m, + ) # fmt: skip + + +def gripper_all_angles(config: PodConfiguration, x: float, state: GripperState) -> Rect: + """What the gripper (and what it holds) covers seen from above turned through every angle, cm: + its turning parts each a box over its farthest point's circle about the rotation centre, its + upper hand (which does not turn) as it is.""" + model = PodModel.of(config).gripper_model + assert model is not None + geo = config.geometry + cx = x + geo.gripper_x_offset - model.pads_center_to_rotation_center + cy = state.gy + geo.gripper_y_offset - model.finger_center_offset + parts = gripper_parts(config, x, state) + xs: List[float] = [] + ys: List[float] = [] + for part in parts: + if part.name == "upper hand": + xs += [px for px, _ in part.outline] + ys += [py for _, py in part.outline] + continue + r = max(math.hypot(px - cx, py - cy) for px, py in part.outline) + xs += [cx - r, cx + r] + ys += [cy - r, cy + r] + return min(xs), max(xs), min(ys), max(ys) + + +def channel_footprint(config: PodConfiguration, state: PodState) -> Rect: + """What the pipettor covers seen from above for its travel height, as Biomek boxes it (cm), + each widened by `AvoidanceMargin`: + + - the 96-head's pipettor box (`head_box`), joined with the block of its tips (`tips_block`) + when it carries some; + - a Span-8's band `PodXSpan` wide from probe 1's X less `Mandrel1XOffset`, across its probes + and `Mandrel1YOffset` beyond the end ones (its box starts that far behind probe 1, as the + logged heights over a tall neighbour behind the probes show). + """ + x, pipettor = state.x, state.pipettor + geo = config.geometry + m = geo.avoidance_margin + if config.module_type == "span8": + x0, dy = x - geo.mandrel1_x_offset, geo.mandrel1_y_offset + return x0 - m, x0 + geo.pod_x_span + m, min(pipettor.ys) - dy - m, max(pipettor.ys) + dy + m + box = head_box(config, state) + if pipettor.tips[0] <= 0: + return box + block = tips_block(config, state) + return ( + min(box[0], block[0]), + max(box[1], block[1]), + min(box[2], block[2]), + max(box[3], block[3]), + ) + + +def max_traverse_heights(config: PodConfiguration, channels: Sequence[str]) -> Dict[str, float]: + """The highest each Z-type axis (`channels` and GZ) travels, cm of its bottom above the deck: the + top of travel less the park margin (`ParkLocation` `ZMargin`, `GZMargin`), as Biomek parks them + (the Multichannel's rest Z, 39.763 cm, is -256 counts). A Span-8 probe goes no higher than its + top less `DiscardOffset`: above that its stripper pushes a tip off (Biomek travels carrying + probes there, as its logs show).""" + shuck = config.settings["DiscardOffset"] if config.module_type == "span8" else None + ceilings = {} + for name in [*channels, "GZ"]: + top = config.limits[name][1] + ceiling = top + config.park.get("GZMargin" if name == "GZ" else "ZMargin", 0.0) + if shuck is not None and name != "GZ": + ceiling = min(ceiling, top - shuck) + ceilings[name] = ceiling + return ceilings + + +def safe_heights( + config: PodConfiguration, + start: PodState, + end: PodState, + obstacles: Obstacles, + tip_lengths: Mapping[str, float], + channels: Sequence[str], +) -> Dict[str, float]: + """Biomek's safe height for each Z-type axis (`channels`, and GZ with a gripper) on the way + from `start` to `end`, cm: the tallest deck item (`deck_height`) under each tool's footprint + swept from here to there, floored by `GlobalMinSafeHeight` and the axis's lowest reach, plus the + tool's own: a channel's tip (`tip_lengths`; the 96-head's `SubMandrelSafeHeight` without one) + and `AdditionalSafeHeight`; the gripper, swept over every angle, its offset + to its lowest point (what it holds included) and `AdditionalSafeHeightGripper`; + `AvoidanceMargin` on every one. The items are the deck + check's own boxes (`obstacles.deck`, exempting none): a travel at this height is one the check + passes.""" + d = config + items = [(rect_of(p.outline), p.z_high) for p in obstacles.deck] + geo = d.geometry + floor = float(d.settings["GlobalMinSafeHeight"]) + margin = geo.avoidance_margin + lengths = tip_lengths + out: Dict[str, float] = {} + if d.module_type == "span8": + h = deck_height(channel_footprint(d, start), channel_footprint(d, end), items) + lowest = max(d.limits[n][0] for n in channels) + for n in channels: + out[n] = max(floor, h, lowest) + lengths.get(n, 0.0) + geo.additional_safe_height + margin + else: + # The head's box joined with its tips' block, by the tip's length (`SubMandrelSafeHeight` + # without tips): the logged heights clear what lies under the box alone by the tip's length. + h = deck_height(channel_footprint(d, start), channel_footprint(d, end), items) + tip = lengths.get("Z") or (geo.sub_mandrel_safe_height or 0.0) + out["Z"] = max(floor, h, d.limits["Z"][0]) + tip + geo.additional_safe_height + margin + g0, g1 = start.gripper, end.gripper + if g0 is not None and g1 is not None: + wide = max(g0.gg, g1.gg) + # Swept over every angle, as Biomek's planner sweeps the gripper for its travel height. + ra = gripper_all_angles(d, start.x, GripperState(g0.gy, g0.gz, g0.gr, wide, g0.held)) + rb = gripper_all_angles(d, end.x, GripperState(g1.gy, g1.gz, g1.gr, wide, g1.held)) + hg = deck_height(ra, rb, items) + below = gripper_below(d, start.x, GripperState(g0.gy, g0.gz, g0.gr, wide, g0.held)) + lowest = d.limits["GZ"][0] - below + out["GZ"] = max(floor, hg, lowest) + below + geo.additional_safe_height_gripper + margin + return out diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py deleted file mode 100644 index 444602a4932..00000000000 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision.py +++ /dev/null @@ -1,279 +0,0 @@ -"""A pod against itself: its gripper (and what it holds) against its pipettor, as Biomek keeps -them apart, as pure functions. - -Biomek models each part of a pod as a box in 3D and refuses a pose where the gripper's boxes and -the pipettor's overlap. Its path planner searches around that; here a move whose path would -overlap is refused before anything is sent (`Pod.move_axes`), and the gripper's operations make -room first (`Pod._make_room_for_gripper`). - -The parts, in Biomek's frame (cm; X along the rail, Y towards the front, Z up from the deck): - -- the gripper, about its rotation centre (`pod_geometry`: the pod's X + `GripperXOffset` − - `PadsCenterToRotationCenter`, its GY + `GripperYOffset` − `FingerCenterOffset`), its hand's - bottom at GZ + `GripperZOffset` + the fingers' height (the deepest point of the finger profile, - `Finger/Base`), so the fingertips are at GZ + `GripperZOffset`: - - the upper hand, from the lower hand's top (`Lowerhand/ZSpan`) up without end; it does not turn; - - the lower hand with the fingers' top part, down to the top part's depth (`TopPart/ZSpan`); - - the lower fingers, down to the fingertips; - - what it holds, from its bottom (the fingertips less the grip height) to its top; - the last three turned by GR; each widened by `AvoidanceMargin`; -- a Span-8's probes: each probe a band in Y halfway to its neighbours (the end ones out to - `Mandrel1YOffset`), below the LLS module a box `ProbeSize` wide from the end of its tip up to - `MandrelExtender` above its mandrel's bottom, widened by `AvoidanceMargin` and, in Z, by - `AdditionalSafeHeight`; above it the probe's upper part, up without end; -- the 96-head: its body (`HeadBodyXSpan` × `HeadBodyYSpan`, mandrel A1 at the pod's X and Y, - the mandrels centred), from the end of its tips up without end. - -A Span-8's tubing bundle (`LLSWireModel`, `span8_bundle_box`) is not one of the pipettor's parts -here: Biomek's own prime approach sweeps the probes past the gripper parked after homing through -that box, so what Biomek tests it against is not yet known. It is computed for drawing. -""" - -import math -from dataclasses import dataclass -from typing import Dict, List, Optional, Sequence, Tuple - -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g -from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodConfiguration - -OPEN = 1e10 # a part with no top - - -class PodCollisionError(ValueError): - """A move would bring a pod's gripper (or what it holds) into its own pipettor. Raised before - anything is sent.""" - - -Point = Tuple[float, float] - - -@dataclass(frozen=True) -class Part: - """A part of a pod at a pose: a convex outline seen from above (deck cm) and its Z range.""" - - name: str - outline: Tuple[Point, ...] - z_low: float - z_high: float - - -@dataclass(frozen=True) -class GripperState: - """The gripper's axes in Biomek's units (cm, degrees) and what it holds.""" - - gy: float - gz: float - gr: float - gg: float - held: Optional[g.HeldLabware] = None - - -@dataclass(frozen=True) -class PipettorState: - """The pipettor's axes in Biomek's units: a Span-8's probes' Y (`ys`), mandrel bottoms (`zs`) - and tip lengths below them, or the 96-head's Y and Z (one each) and its tips' length.""" - - ys: Tuple[float, ...] - zs: Tuple[float, ...] - tips: Tuple[float, ...] - - -def _box(x0: float, x1: float, y0: float, y1: float) -> Tuple[Point, ...]: - return ((x0, y0), (x1, y0), (x1, y1), (x0, y1)) - - -def _place(outline: Sequence[Point], cx: float, cy: float, degrees: float) -> Tuple[Point, ...]: - c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) - return tuple((cx + x * c - y * s, cy + x * s + y * c) for x, y in outline) - - -def finger_depth(model: Dict) -> float: - """How far below the hand's bottom the fingertips are: the finger profile's deepest point.""" - return -float(min(p["Y"] for p in model["Finger"]["Base"])) - - -def gripper_parts(config: PodConfiguration, x: float, state: GripperState) -> List[Part]: - """The gripper's parts with the pod's X at `x`.""" - geo, model = config.geometry, config.gripper_model - gm = g.GripperModel.from_bif(model) - margin = geo.avoidance_margin - cx = x + geo.gripper_x_offset - gm.pads_center_to_rotation_center - cy = state.gy + geo.gripper_y_offset - gm.finger_center_offset - depth = finger_depth(model) - hand = state.gz + geo.gripper_z_offset + depth # the hand's bottom - tips = hand - depth - hand_top = hand + model["Lowerhand"]["ZSpan"] - top_part = hand - model["Finger"]["TopPart"]["ZSpan"] - fixed, turning = g.gripper_boxes(gm, margin, state.gg, state.held) - parts = [Part("upper hand", _place(_box(*fixed[0]), cx, cy, 0.0), hand_top, OPEN)] - parts.append(Part("lower hand", _place(_box(*turning[0]), cx, cy, state.gr), top_part, hand_top)) - parts.append(Part("fingers", _place(_box(*turning[1]), cx, cy, state.gr), tips, top_part)) - if state.held is not None: - bottom = tips - state.held.grip_offset - for box in turning[2:]: - outline = _place(_box(*box), cx, cy, state.gr) - parts.append(Part("held labware", outline, bottom, bottom + state.held.height)) - return parts - - -def span8_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: - """A Span-8's probes with the pod's X at `x` (probe axes at X).""" - geo, s = config.geometry, config.settings - margin, lift = geo.avoidance_margin, geo.additional_safe_height - half = s["ProbeSize"] / 2 - extender = s.get("MandrelExtender", 0.0) - ys = state.ys - parts = [] - for i, (y, z, tip) in enumerate(zip(ys, state.zs, state.tips)): - low = y - geo.mandrel1_y_offset if i == 0 else (ys[i - 1] + y) / 2 - high = y + geo.mandrel1_y_offset if i == len(ys) - 1 else (y + ys[i + 1]) / 2 - low, high = min(low, high), max(low, high) - lower = _box(x - half - margin, x + half + margin, low - margin, high + margin) - parts.append(Part(f"probe {i + 1}", lower, z - tip - lift, z + extender)) - upper = _box(x - geo.mandrel1_x_offset - margin, x + half + margin, low - margin, high + margin) - parts.append(Part(f"probe {i + 1} upper part", upper, z + extender, OPEN)) - return parts - - -@dataclass(frozen=True) -class BundleBox: - """The space a Span-8's tubing bundle may hang in (Biomek's frame, cm), open upward.""" - - x0: float - x1: float - y0: float - y1: float - z_low: float - - -def span8_bundle_box( - config: PodConfiguration, x: float, state: PipettorState -) -> Optional[BundleBox]: - """Where a Span-8's tubing bundle hangs with the probe axes at `x`, from `LLSWireModel` (None - without it): - - - X: from the probes' axis + `WireStartXOffset` to + `AnchorXOffset`; - - Y: the probes' range, out to halfway towards the anchor's (`AnchorCenterY` ± - `AnchorHalfLength`); - - Z: up from the lower of where the bundle leaves the lowest probe (its mandrel's bottom + - `MandrelExtender` + `FixedTipZOriginToWireOffset`) and the loop's bottom, `WireBottomAtZMax` - less half as far as that probe is below its highest Z. The lowest probe is the one furthest - below its own highest Z (`Z1`..`Z8` limits). - No `AvoidanceMargin`: the bundle is not widened. - """ - wire = config.settings.get("LLSWireModel") - if not wire: - return None - extender = config.settings.get("MandrelExtender", 0.0) - lowest = [] - for i, z in enumerate(state.zs): - low, high = config.limits.get(f"Z{i + 1}", config.limits.get("Z", (z, z))) - z = max(low, min(high, z)) - lowest.append((high - z, z + extender + wire["FixedTipZOriginToWireOffset"])) - below, leaves = max(lowest) - y0, y1 = min(state.ys), max(state.ys) - near, far = ( - wire["AnchorCenterY"] - wire["AnchorHalfLength"], - wire["AnchorCenterY"] + wire["AnchorHalfLength"], - ) - return BundleBox( - x + wire["WireStartXOffset"], - x + wire["AnchorXOffset"], - min(y0, (y0 + near) / 2), - max(y1, (y1 + far) / 2), - min(leaves, wire["WireBottomAtZMax"] - below / 2), - ) - - -def head96_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: - """The 96-head with mandrel A1 at (`x`, `state.ys[0]`), its bottom at `state.zs[0]`.""" - geo, s = config.geometry, config.settings - margin = geo.avoidance_margin - body_x, body_y = s["HeadBodyXSpan"], s["HeadBodyYSpan"] - grid_x = ((geo.mandrels_x or 1) - 1) * geo.mandrel_x_spacing - grid_y = ((geo.mandrels_y or 1) - 1) * geo.mandrel_y_spacing - left = x - (body_x - grid_x) / 2 - back = state.ys[0] - (body_y - grid_y) / 2 # A1 is the back row; Y runs to the front - outline = _box(left - margin, left + body_x + margin, back - margin, back + body_y + margin) - return [Part("96-head", outline, state.zs[0] - state.tips[0], OPEN)] - - -def pipettor_parts(config: PodConfiguration, x: float, state: PipettorState) -> List[Part]: - if config.module_type == "span8": - return span8_parts(config, x, state) - return head96_parts(config, x, state) - - -def _axes(outline: Sequence[Point]) -> List[Point]: - n = len(outline) - return [ - (outline[i][1] - outline[(i + 1) % n][1], outline[(i + 1) % n][0] - outline[i][0]) - for i in range(n) - ] - - -def overlap(a: Part, b: Part) -> bool: - """Whether two parts share any volume (touching is clear): Z ranges, then separating axes.""" - if a.z_high <= b.z_low or b.z_high <= a.z_low: - return False - for ax, ay in _axes(a.outline) + _axes(b.outline): - pa = [px * ax + py * ay for px, py in a.outline] - pb = [px * ax + py * ay for px, py in b.outline] - if max(pa) <= min(pb) or max(pb) <= min(pa): - return False - return True - - -def collisions( - config: PodConfiguration, x: float, gripper: GripperState, pipettor: PipettorState -) -> List[Tuple[str, str]]: - """The (gripper part, pipettor part) pairs that overlap at this pose.""" - gp, pp = gripper_parts(config, x, gripper), pipettor_parts(config, x, pipettor) - return [(a.name, b.name) for a in gp for b in pp if overlap(a, b)] - - -# cm: the most any point moves between two checked poses. Every part is widened by -# `AvoidanceMargin` (0.2164 cm), so a contact cannot pass between two steps unseen. -SWEEP_STEP = 0.1 - - -def swept_collisions( - config: PodConfiguration, - x: Tuple[float, float], - gripper: Tuple[GripperState, GripperState], - pipettor: Tuple[PipettorState, PipettorState], -) -> List[Tuple[str, str]]: - """The overlaps anywhere along a coordinated move (every axis on the same profile, scaled to its - distance), checked at steps no point covers more than `SWEEP_STEP` in. The parts are widened by - `AvoidanceMargin`, more than a step.""" - (g0, g1), (p0, p1) = gripper, pipettor - # X carries every part alike, so only the other axes change what overlaps. - reach = config.gripper_model["Finger"]["PadsCenterToRotationCenter"] + 15.0 - travel = max( - [abs(g1.gy - g0.gy), abs(g1.gz - g0.gz), abs(g1.gg - g0.gg)] - + [reach * math.radians(abs(g1.gr - g0.gr))] - + [abs(b - a) for a, b in zip(p0.ys, p1.ys)] - + [abs(b - a) for a, b in zip(p0.zs, p1.zs)] - ) - steps = max(1, math.ceil(travel / SWEEP_STEP)) - found: List[Tuple[str, str]] = [] - for i in range(steps + 1): - t = i / steps - - def lerp(a: float, b: float) -> float: - return float(a + t * (b - a)) - - gs = GripperState( - lerp(g0.gy, g1.gy), lerp(g0.gz, g1.gz), lerp(g0.gr, g1.gr), lerp(g0.gg, g1.gg), g0.held - ) - ps = PipettorState( - tuple(lerp(a, b) for a, b in zip(p0.ys, p1.ys)), - tuple(lerp(a, b) for a, b in zip(p0.zs, p1.zs)), - p0.tips, - ) - for pair in collisions(config, lerp(*x), gs, ps): - if pair not in found: - found.append(pair) - if found: - return found - return found diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py index cecd76051de..72f9c95b276 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_collision_tests.py @@ -3,53 +3,55 @@ import dataclasses import unittest -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_collision as pc from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import check, pod_model class PodCollisionTests(unittest.TestCase): def setUp(self) -> None: self.right = generic_configuration().pod("right") - def probes(self, y: float, z: float, span: float = 6.3, tip: float = 0.0) -> pc.PipettorState: - return pc.PipettorState(tuple(y + i * span / 7 for i in range(8)), (z,) * 8, (tip,) * 8) + def probes(self, y: float, z: float, span: float = 6.3, tip: float = 0.0) -> pod_model.PipettorState: + return pod_model.PipettorState(tuple(y + i * span / 7 for i in range(8)), (z,) * 8, (tip,) * 8) def test_the_parked_gripper_is_clear_of_the_probes(self) -> None: # The park: GR 90, GY 48, GZ at its top, GG 7.889; the probes over the wash station. - gripper = pc.GripperState(48.0, 37.8, 90.0, 7.889) - self.assertEqual(pc.collisions(self.right, 120.0, gripper, self.probes(58.275, 39.1)), []) + gripper = pod_model.GripperState(48.0, 37.8, 90.0, 7.889) + self.assertEqual(check.own_collisions_at(self.right, pod_model.PodState(120.0, gripper, self.probes(58.275, 39.1))), []) def test_fingers_turned_under_the_probes_collide(self) -> None: # GR 0 points the fingers along +X, under the probe axes; with the probes over them in Y # and the fingers' top above the probes' tips, they meet. - gripper = pc.GripperState(30.0, 30.0, 0.0, 9.0) - found = pc.collisions(self.right, 120.0, gripper, self.probes(28.0, 20.0)) + gripper = pod_model.GripperState(30.0, 30.0, 0.0, 9.0) + found = check.own_collisions_at(self.right, pod_model.PodState(120.0, gripper, self.probes(28.0, 20.0))) self.assertIn(("fingers", "probe 1"), found) def test_probes_at_the_far_end_of_y_clear_the_turned_fingers(self) -> None: # Logged before a turn to 0 degrees with GY 61.26: the probes sent to Y 15.274, span 6.3. - gripper = pc.GripperState(61.263, 30.0, 0.0, 9.706) - self.assertEqual(pc.collisions(self.right, 120.0, gripper, self.probes(15.274, 20.0)), []) + gripper = pod_model.GripperState(61.263, 30.0, 0.0, 9.706) + self.assertEqual(check.own_collisions_at(self.right, pod_model.PodState(120.0, gripper, self.probes(15.274, 20.0))), []) def test_held_labware_counts(self) -> None: held = g.HeldLabware(12.78, 8.56, height=1.41, grip_offset=-0.23) - gripper = pc.GripperState(30.0, 30.0, 0.0, 8.5, held) - self.assertIn("held labware", [p.name for p in pc.gripper_parts(self.right, 120.0, gripper)]) + gripper = pod_model.GripperState(30.0, 30.0, 0.0, 8.5, held) + self.assertIn("held labware", [p.name for p in pod_model.gripper_parts(self.right, 120.0, gripper)]) def test_a_turn_through_the_probes_is_caught_on_its_way(self) -> None: # From 180 degrees (fingers away from the probes) to 90: never under the probes. To 0 and # back is caught at 0, the end; a sweep from 180 to -90 passes 0 only between its ends. - a = pc.GripperState(30.0, 30.0, 180.0, 9.0) - b = pc.GripperState(30.0, 30.0, -180.0, 9.0) + a = pod_model.GripperState(30.0, 30.0, 180.0, 9.0) + b = pod_model.GripperState(30.0, 30.0, -180.0, 9.0) probes = self.probes(28.0, 20.0) - self.assertEqual(pc.collisions(self.right, 120.0, a, probes), []) - self.assertEqual(pc.collisions(self.right, 120.0, b, probes), []) - found = pc.swept_collisions(self.right, (120.0, 120.0), (a, b), (probes, probes)) + self.assertEqual(check.own_collisions_at(self.right, pod_model.PodState(120.0, a, probes)), []) + self.assertEqual(check.own_collisions_at(self.right, pod_model.PodState(120.0, b, probes)), []) + found = check.own_collisions( + self.right, pod_model.PodState(120.0, a, probes), pod_model.PodState(120.0, b, probes) + ) self.assertTrue(found) - def bundle(self, z: float = 30.0) -> pc.BundleBox: - box = pc.span8_bundle_box(self.right, 120.0, self.probes(28.0, z)) + def bundle(self, z: float = 30.0) -> pod_model.BundleBox: + box = pod_model.span8_bundle_box(self.right, 120.0, self.probes(28.0, z)) assert box is not None return box @@ -69,8 +71,8 @@ def test_the_bundle_loop_drops_half_as_far_as_the_lowest_probe(self) -> None: # At the top the bundle leaves the probes below the loop's bottom. wire, s = self.right.settings["LLSWireModel"], self.right.settings top = self.right.limits["Z1"][1] - top_box = pc.span8_bundle_box( - self.right, 120.0, pc.PipettorState((28.0,) * 8, (top,) * 8, (0.0,) * 8) + top_box = pod_model.span8_bundle_box( + self.right, 120.0, pod_model.PipettorState((28.0,) * 8, (top,) * 8, (0.0,) * 8) ) assert top_box is not None self.assertLessEqual( @@ -81,23 +83,30 @@ def test_the_bundle_does_not_guard_the_gripper(self) -> None: # Biomek's prime approach sweeps the probes from Y 15.1 to 58.3 with the gripper as homing # left it (GR -2.2 degrees, GY 39.9, at its top); around Y 47 the bundle's box covers the # fingers, and Biomek sends the move all the same. - gripper = pc.GripperState(39.9, 37.931, -2.18, 7.937) + gripper = pod_model.GripperState(39.9, 37.931, -2.18, 7.937) probes = self.probes(47.86, 39.2) - box = pc.span8_bundle_box(self.right, 145.4, probes) + box = pod_model.span8_bundle_box(self.right, 145.4, probes) assert box is not None - fingers = next(p for p in pc.gripper_parts(self.right, 145.4, gripper) if p.name == "fingers") + fingers = next(p for p in pod_model.gripper_parts(self.right, 145.4, gripper) if p.name == "fingers") self.assertTrue( - pc.overlap( - fingers, pc.Part("bundle", pc._box(box.x0, box.x1, box.y0, box.y1), box.z_low, pc.OPEN) + check.overlap( + fingers, pod_model.Part("bundle", pod_model._box(box.x0, box.x1, box.y0, box.y1), box.z_low, pod_model.OPEN) ) ) - self.assertEqual(pc.collisions(self.right, 145.4, gripper, probes), []) + self.assertEqual(check.own_collisions_at(self.right, pod_model.PodState(145.4, gripper, probes)), []) - def test_a_span8_without_a_bundle_model_has_no_bundle(self) -> None: - config = dataclasses.replace( - self.right, settings={k: v for k, v in self.right.settings.items() if k != "LLSWireModel"} - ) - self.assertIsNone(pc.span8_bundle_box(config, 120.0, self.probes(28.0, 30.0))) + def test_a_span8_without_a_bundle_model_is_refused(self) -> None: + # No quiet substitution: a Span-8's entry gives its bundle model. + with self.assertRaisesRegex(ValueError, "LLSWireModel"): + dataclasses.replace( + self.right, settings={k: v for k, v in self.right.settings.items() if k != "LLSWireModel"} + ) + + def test_a_pod_without_a_setting_it_uses_is_refused(self) -> None: + for key in ("AStarSearchLimit", "GripperSqueezeForce", "ProbeSize"): + settings = {k: v for k, v in self.right.settings.items() if k != key} + with self.assertRaisesRegex(ValueError, key): + dataclasses.replace(self.right, settings=settings) if __name__ == "__main__": diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py index 22fd7b00115..1b60034aa5c 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_geometry.py @@ -31,9 +31,9 @@ import math from dataclasses import dataclass -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, Dict, List, Optional, Tuple -from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import Obstacle, PodGeometry +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import PodGeometry Range = Tuple[float, float] """An X interval in deck cm, `(lowest, highest)`.""" @@ -109,7 +109,8 @@ class HeldLabware: pads less `GrippedLabwareOffsets`, each layer above sits at its offset from the corner of the one below, and the footprint is every layer's box). The grip width is the bottom layer's. `height` is the stack's, from its bottom to its top; `grip_offset` how far above its bottom the - fingertips are (negative below it).""" + fingertips are (negative below it). `source`: the labware definitions the sizes were taken from, + with their dimensions, so a refusal or a replay can say what was counted.""" length: float width: float @@ -118,6 +119,7 @@ class HeldLabware: layers: Tuple[StackedLayer, ...] = () height: float = 0.0 grip_offset: float = 0.0 + source: str = "" @dataclass(frozen=True) @@ -331,41 +333,3 @@ def pod_xy_box(geometry: PodGeometry, x: float, y: float) -> Tuple[Range, Range] `Mandrel1XOffset` / `Mandrel1YOffset` back from that.""" x0, y0 = x - geometry.mandrel1_x_offset, y - geometry.mandrel1_y_offset return (x0, x0 + geometry.pod_x_span), (y0, y0 + geometry.pod_y_span) - - -def _open_overlap(low: Optional[float], high: Optional[float], span: Range, buffer: float) -> bool: - lo = -math.inf if low is None else low - buffer - hi = math.inf if high is None else high + buffer - return lo < span[1] and span[0] < hi - - -@dataclass(frozen=True) -class Clearance: - """What a pod's travel over an X/Y area must clear: the lowest height (cm) its channels may - travel at, and the obstacles in the way that no height clears (walls).""" - - height: float - walls: Tuple[str, ...] - - -def obstacle_clearance(obstacles: Sequence[Obstacle], x: Range, y: Range) -> Clearance: - """Over the area `x` by `y` (cm): the top (plus buffer) of every obstacle there with a top and - no floor (the pump bank), and every obstacle there with no top (a wall, or a ceiling). - - Ceilings (a bottom and no top: the I-beam from Z 37.069 behind Y 11.092, the cameras from Z 32.078 - at the front corners) count as walls. Biomek makes every obstacle a box (an open top at 1e10, - each face widened by its buffer) and checks the pod's whole part model against - them, the carriage above the channels included, so a ceiling bounds the pod's body, not its - channels' bottom; with the channels at a traverse height the body is above every ceiling. None of - the 12,321 X/Y moves Biomek logged put a pod's body under one (the furthest back was Y 14.27 cm), - so blocking them refuses nothing Biomek did.""" - height = -math.inf - walls = [] - for o in obstacles: - if not (_open_overlap(o.x1, o.x2, x, o.buffer) and _open_overlap(o.y1, o.y2, y, o.buffer)): - continue - if o.z2 is None: - walls.append(o.name) - elif o.z2 is not None and (o.z1 is None or o.z1 < 0): - height = max(height, o.z2 + o.buffer) - return Clearance(height, tuple(walls)) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py new file mode 100644 index 00000000000..a776750f034 --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py @@ -0,0 +1,279 @@ +"""The pod's planned moves on a deck (Biomek's planner, design.md I12): which moves are planned and +exempt nothing, which are an operation's own and work in its position, and the way out of a +position a pod was left standing in.""" + +import unittest +from typing import List, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import ROWS, COLUMNS, mandrel_name +from pylabrobot.beckman_coulter.biomek_i7.driver import liquid_tests +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_tip +from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import check, obstacles, pod_model, search + +Move = Tuple[dict, Tuple[str, ...]] + + +class PlannedMoveTests(PodMoveTest): + setup_deck = liquid_tests.LiquidTests.setup_deck + + def record(self, driver, side: str) -> List[Move]: # type: ignore[no-untyped-def] + """Each move the pod makes, with the deck positions exempt for it.""" + pod = self.pod(driver, side) + moves: List[Move] = [] + original = pod.move_axes + + async def move_axes(targets, speed=1000, **kwargs): # type: ignore[no-untyped-def] + moves.append((dict(targets), pod._working_at)) + return await original(targets, speed, **kwargs) + + pod.move_axes = move_axes # type: ignore[method-assign, assignment] + return moves + + def tips(self, driver) -> None: # type: ignore[no-untyped-def] + head = self.pod(driver, "left").head96 + assert head is not None + head._set_tips( + {mandrel_name(r, c): biomek_tip("T230", f"t_{r}_{c}") for r in range(ROWS) for c in range(COLUMNS)} + ) + + async def test_the_approach_exempts_nothing_and_the_descent_its_position(self) -> None: + driver, lh = await self.setup_deck() # type: ignore[misc] + self.tips(driver) + moves = self.record(driver, "left") + await lh.head96.aspirate(lh.deck.get_resource("Reservoir"), 50, liquid_height=2.0) + travel = [w for t, w in moves if {"X", "Y"} & set(t)] + self.assertTrue(travel) + self.assertEqual(set(travel), {()}) # the approach: planned, nothing exempt + descent = next(i for i, (t, _) in enumerate(moves) if {"X", "Y"} & set(t)) + 1 + self.assertEqual(set(moves[descent][0]), {"Z"}) + self.assertEqual(set(moves[descent][1]), {"P8"}) # the step's own moves: its position + + async def test_a_pod_left_in_a_position_rises_straight_out_of_it(self) -> None: + driver, lh = await self.setup_deck() # type: ignore[misc] + self.tips(driver) + left = self.pod(driver, "left") + d = left.declared + assert d is not None + reservoir = lh.deck.get_resource("Reservoir") + plan = lh.head96.plan_liquid( + "aspirate", reservoir, 10, lh.head96._settings(liquid_height=2.0), 100 + ) + await left._move_over({"X": d.to_counts("X", plan.x), "Y": d.to_counts("Y", plan.y)}) + with left.working_at(reservoir): + await left.move_axes({"Z": d.to_counts("Z", 10.0)}) # left in it, as by a low end height + with self.assertRaises(check.DeckCollisionError): + await left.move_axes({"X": d.to_counts("X", plan.x - 10.0)}) # not straight up: refused + moves = self.record(driver, "left") + await left._move_over({"X": d.to_counts("X", plan.x - 10.0)}) + # Out of P8 straight up, exempting only P8, to the travel height; then the travel, nothing + # exempt. + self.assertEqual((set(moves[0][0]), moves[0][1]), ({"Z"}, ("P8",))) + self.assertEqual(moves[0][0]["Z"], d.to_counts("Z", left._traverse_heights()["Z"])) + self.assertEqual([(set(t), w) for t, w in moves[1:]], [({"X"}, ())]) + + +class RiseAndDescentTests(PodMoveTest): + """Biomek's rise and descent stages: the search when the straight move up or down is not clear.""" + + async def pod_under_a_ledge(self): # type: ignore[no-untyped-def] + """The left pod holding a lid at GR 0 (it reaches past the fingertips, to X 66.9 with the pod + at X 60), a ledge above the lid's far end only: clear of every part where it stands.""" + driver = await self.homed() + left = self.pod(driver, "left") + d = left.declared + assert d is not None and left.gripper is not None + ledge = obstacles.obstacle_part("ledge", (63.0, 70.0), (44.0, 52.0), (14.5, 16.0)) + driver.obstacles = lambda pod: obstacles.Obstacles((), (ledge,), ()) + await left.move_axes( + {"X": d.to_counts("X", 60.0), "GY": d.to_counts("GY", 48.0), "GR": d.to_counts("GR", 0.0)} + ) + await left.move_axes({"GZ": d.to_counts("GZ", 20.0), "GG": d.to_counts("GG", 7.592)}) + left.gripper.set_held_labware(g.HeldLabware(length=12.776, width=8.548, height=0.9)) + return left, d + + async def test_a_rise_blocked_overhead_goes_out_from_under_first(self) -> None: + left, d = await self.pod_under_a_ledge() + moves = record(left) + await left._rise({"GZ": 30.0}, 1000) + self.assertEqual(moves[-1], {"GZ": d.to_counts("GZ", 30.0)}) + self.assertNotIn("GZ", moves[0]) # out from under the ledge first, then up + self.assertEqual(left.cpositions["GZ"][1], d.to_counts("GZ", 30.0)) + + async def test_a_descent_into_a_box_is_searched_then_refused(self) -> None: + driver = await self.homed() + left = self.pod(driver, "left") + d = left.declared + assert d is not None + table = obstacles.obstacle_part("P1", (0.0, 200.0), (0.0, 80.0), (-1.0, 10.0)) + driver.obstacles = lambda pod: obstacles.Obstacles((), (table,), ("P1",)) + await left._read_unknown_positions(pumps=True) # reading moves nothing + before = left.cpositions + moves = record(left) + with self.assertRaisesRegex(check.DeckCollisionError, "no clear path for the descent"): + await left._move_over({"X": d.to_counts("X", 60.0)}, z_final=5.0) + # The call is planned whole before anything moves (as Biomek's planner: no path, + # nothing moves): the descent has none, so the rise and the travel are not made either. + self.assertEqual(moves, []) + self.assertEqual(left.cpositions, before) + + +class SearchTests(PodMoveTest): + async def test_the_span8s_search_moves_its_probes_by_y(self) -> None: + driver = await self.homed() + right = self.pod(driver, "right") + d = right.declared + assert d is not None + driver.obstacles = lambda pod: obstacles.Obstacles() + await right.move_axes({"GR": d.to_counts("GR", d.park["GR"])}) # reads every position + y1 = right.cpositions["Y1"][1] + target = d.to_counts("Y", d.to_value("Y", y1) + 2.0) + # A Span-8's Y names probe 1 and moves all eight (`_planned`): the search's Y step as well. + path = right._search({"Y": target}) + self.assertEqual(path, [{"Y": target}]) + + +class OpenSetTests(unittest.TestCase): + """Biomek's open set (spec §5.3): the same costs tie; a node rises only past a strictly larger + cost and sinks below a child that is not larger.""" + + def order(self, pushes: List[Tuple[str, float]]) -> List[str]: + open_set = search.OpenSet() + for node, cost in pushes: + open_set.push(node, cost) + out = [] + while open_set: + out.append(open_set.pop()) + return out + + def test_cheapest_first_and_equal_costs_in_arrival_order(self) -> None: + self.assertEqual(self.order([("a", 2.0), ("b", 1.0), ("c", 1.0)]), ["b", "c", "a"]) + self.assertEqual(self.order([("a", 1.0), ("b", 1.0), ("c", 1.0)]), ["a", "b", "c"]) + + def test_costs_the_same_value_do_not_pass_each_other(self) -> None: + # 1e-13 apart: the same value, so the later never rises past the earlier. + self.assertEqual(self.order([("a", 1.0 + 1e-13), ("b", 1.0)]), ["a", "b"]) + + def test_a_cheaper_way_lowers_an_open_node(self) -> None: + self.assertEqual(self.order([("a", 5.0), ("b", 3.0), ("a", 1.0)]), ["a", "b"]) + self.assertEqual(self.order([("a", 1.0), ("a", 5.0)]), ["a"]) # never raised + + +class OffQuarterTests(PodMoveTest): + async def test_a_gripper_off_a_quarter_turn_first_turns_to_one(self) -> None: + driver = await self.homed() + right = self.pod(driver, "right") + d = right.declared + assert d is not None + driver.obstacles = lambda pod: obstacles.Obstacles() + await right.move_axes({"GR": d.to_counts("GR", 45.0)}) + x = d.to_value("X", right.cpositions["X"][1]) + path = right._search({"X": d.to_counts("X", x - 2.0)}) + # Off a quarter turn Biomek's search offers only the turns to the quarters either side. + self.assertEqual(set(path[0]), {"GR"}) + self.assertIn(round(d.to_value("GR", path[0]["GR"])), (0, 90)) + self.assertEqual(path[-1], {"X": d.to_counts("X", x - 2.0)}) + + +class OtherPodTests(PodMoveTest): + """The other pod in planning (Biomek's planner, spec §6.2): a wall over all Y and Z.""" + + async def test_a_pushable_pod_is_walled_at_its_bridge_at_the_end_of_its_travel(self) -> None: + driver = await self.homed() + left, right = self.pod(driver, "left"), self.pod(driver, "right") + driver.make_way = True + d, od = left.declared, right.declared + assert d is not None and od is not None + edge = g.bridge_x_range(od.geometry, od.limits["X"][1])[0] - (1 / 16 + 1 / 64) + wall = left._other_pod_wall() + assert wall is not None + self.assertAlmostEqual(wall[0], min(edge, left._range_at_limit(d.limits["X"][1])[1])) + self.assertGreaterEqual(wall[1], 500.0) + # Its own X limit: its bridge 1/16 + 1/64 cm short of the other's at the end of its travel. + limits = left._planning_x_limits() + assert limits is not None + bridge = g.bridge_x_range(d.geometry, limits[1]) + self.assertAlmostEqual(bridge[1], g.bridge_x_range(od.geometry, od.limits["X"][1])[0] - (1 / 16 + 1 / 64)) + + async def test_a_busy_pod_is_walled_where_it_stands(self) -> None: + driver = await self.homed() + left, right = self.pod(driver, "left"), self.pod(driver, "right") + driver.make_way = True + await right._read_unknown_positions() + assert left.rail is not None + with right.working_at("P1"): # in an operation: not to be moved + self.assertEqual(left._other_pod_wall(), left.rail.occupied("right")) + driver.make_way = False # clearing the way off: the same + self.assertEqual(left._other_pod_wall(), left.rail.occupied("right")) + + async def test_the_wall_is_in_the_planning_world_only(self) -> None: + driver = await self.homed() + left = self.pod(driver, "left") + driver.make_way = True + driver.obstacles = lambda pod: obstacles.Obstacles() + world = left._planning_world() + assert world is not None + self.assertEqual([p.name for p in world.structure], ["the right pod"]) + self.assertEqual(left._world(left.pod_number), obstacles.Obstacles()) + + +def record(pod) -> List[dict]: # type: ignore[no-untyped-def] + """The targets of each move `pod` makes from now on.""" + moves: List[dict] = [] + original = pod.move_axes + + async def move_axes(targets, speed=1000, **kwargs): # type: ignore[no-untyped-def] + moves.append(dict(targets)) + return await original(targets, speed, **kwargs) + + pod.move_axes = move_axes + return moves + + +class EscapeTests(unittest.TestCase): + def setUp(self) -> None: + self.config = generic_configuration().pod("left") + self.pipettor = pod_model.PipettorState((30.0,), (5.0,), (0.0,), None) + + def world(self, positions: Tuple[str, ...]) -> obstacles.Obstacles: + box = obstacles.obstacle_part("P1", (0.0, 60.0), (0.0, 60.0), (-1.0, 8.0)) + return obstacles.Obstacles((), (box,), positions) + + def test_a_part_in_a_position_rises_to_its_top(self) -> None: + out = check.escape(self.config, pod_model.PodState(30.0, None, self.pipettor), self.world(("P1",))) + assert out is not None + self.assertEqual((out.holders, out.gripper), (("P1",), 0.0)) + world = self.world(("P1",)) + + def at(z: float) -> List[Tuple[str, str]]: + state = pod_model.PipettorState((30.0,), (z,), (0.0,), None) + return check.deck_collisions_at(self.config, pod_model.PodState(30.0, None, state), world) + + self.assertEqual(at(5.0 + out.pipettor[0]), []) + self.assertNotEqual(at(5.0 + out.pipettor[0] - 0.01), []) + + def test_a_clear_pod_has_nothing_to_leave(self) -> None: + clear = pod_model.PipettorState((30.0,), (30.0,), (0.0,), None) + out = check.escape(self.config, pod_model.PodState(30.0, None, clear), self.world(("P1",))) + self.assertEqual(out, check.Escape((), (0.0,), 0.0)) + + def test_no_way_out_of_anything_but_a_position(self) -> None: + self.assertIsNone(check.escape(self.config, pod_model.PodState(30.0, None, self.pipettor), self.world(()))) + + def test_only_the_span8_probes_inside_rise(self) -> None: + # As the logged escapes: probes 2-4 left in the plate rise, the others stay. + config = generic_configuration().pod("right") + ys = tuple(20.0 + 0.9 * i for i in range(8)) + zs = (30.0, 5.0, 5.0, 5.0, 30.0, 30.0, 30.0, 30.0) + state = pod_model.PodState(30.0, None, pod_model.PipettorState(ys, zs, (0.0,) * 8)) + box = obstacles.obstacle_part("P1", (0.0, 60.0), (0.0, 60.0), (-1.0, 8.0)) + out = check.escape(config, state, obstacles.Obstacles((), (box,), ("P1",))) + assert out is not None + self.assertEqual(out.holders, ("P1",)) + self.assertEqual([i for i, rise in enumerate(out.pipettor) if rise > 0], [1, 2, 3]) + + +if __name__ == "__main__": + unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py index 9368ec7ec92..92d961ef2a9 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py @@ -2,35 +2,17 @@ keeps per pod, and the deck model's clearance.""" import unittest +from typing import List from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest +from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import traverse from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( generic_configuration, generic_deck, ) -from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb - - -class ObstacleTests(unittest.TestCase): - def setUp(self) -> None: - self.obstacles = generic_configuration().pod("left").obstacles - - def test_the_pump_bank_is_cleared_from_above(self) -> None: - # The pump bank: X from 121.044, Y to 13.447 cm, up to Z 37.069, buffer 0.2. - self.assertAlmostEqual(g.obstacle_clearance(self.obstacles, (125, 130), (5, 12)).height, 37.269) - # Elsewhere only the floor (Z to 0, buffer 0.2). - self.assertAlmostEqual(g.obstacle_clearance(self.obstacles, (50, 60), (30, 40)).height, 0.2) - - def test_walls_and_ceilings_are_not_cleared(self) -> None: - self.assertEqual( - g.obstacle_clearance(self.obstacles, (157, 160), (30, 40)).walls, ("RightShield",) - ) - # The I-beam (from Z 37.069 behind Y 11.092) bounds the pod's body: under it is refused. - self.assertEqual(g.obstacle_clearance(self.obstacles, (50, 60), (5, 10)).walls, ("IBeam",)) - # Just clear of it, with its 0.2 cm buffer. - self.assertEqual(g.obstacle_clearance(self.obstacles, (50, 60), (11.3, 20)).walls, ()) class MoveOverTests(PodMoveTest): @@ -62,58 +44,127 @@ async def test_an_override_is_checked_and_z_final_set(self) -> None: pod = self.pod(driver, "left") d = pod.declared assert d is not None - self.mark(driver) - with self.assertRaisesRegex(ValueError, "below"): - await pod._move_over({"X": 100000}, minimum_traverse_height=25.0, clearance=30.0) - self.assertNotIn("Move All", [n for n, _ in self.sent(driver, "multichannel")]) - await pod._move_over( - {"X": 100000}, - minimum_traverse_height=25.0, - clearance=30.0, - allow_below_clearance=True, - z_final=20.0, - ) + await pod._move_over({"X": 100000}, minimum_traverse_height=25.0, z_final=20.0) self.assertEqual(pod.cpositions["Z"][1], d.to_counts("Z", 20.0)) with self.assertRaisesRegex(ValueError, "z_final"): await pod._move_over({"Z": 0}) - async def test_the_default_is_biomeks_safe_height_when_set(self) -> None: + async def test_a_tools_default_is_safe_max_or_a_height(self) -> None: driver = await self.homed() pod = self.pod(driver, "left") d = pod.declared - assert d is not None - self.assertIsNone(pod.default_minimum_traverse_height) # this instrument: -100000, unset - pod.default_minimum_traverse_height = 350.0 # mm + assert d is not None and pod.head96 is not None and pod.gripper is not None + # From the instrument's `AlwaysMaxZ` (unset here): Biomek's safe height for both tools. + self.assertEqual(pod.head96.default_minimum_traverse_height, "safe") + self.assertEqual(pod.gripper.default_minimum_traverse_height, "safe") + # With no deck to reckon from (no device), "safe" travels as high as it goes. + self.assertEqual(pod._traverse_heights()["Z"], pod._max_traverse_heights()["Z"]) + pod.head96.default_minimum_traverse_height = 350.0 # mm of the head's lowest point await pod.move_axes({"Z": -20000}) await pod._move_over({"X": 100000}) self.assertEqual(pod.cpositions["Z"][1], d.to_counts("Z", 35.0)) - pod.default_minimum_traverse_height = 990.0 # mm, above the top: kept to the top of travel - self.assertEqual(pod._traverse_heights()["Z"], d.limits["Z"][1] - 0.1) + pod.head96.default_minimum_traverse_height = 990.0 # above the top: kept to the top of travel + self.assertEqual(pod._traverse_heights()["Z"], pod._max_traverse_heights()["Z"]) + pod.head96.default_minimum_traverse_height = "max" + self.assertEqual(pod._traverse_heights()["Z"], pod._max_traverse_heights()["Z"]) + with self.assertRaises(ValueError): + pod.head96.default_minimum_traverse_height = "low" # type: ignore[assignment] + + +def record(pod) -> List[dict]: # type: ignore[no-untyped-def] + """The targets of each move `pod` makes from now on.""" + moves: List[dict] = [] + original = pod.move_axes + + async def move_axes(targets, speed=1000, **kwargs): # type: ignore[no-untyped-def] + moves.append(dict(targets)) + return await original(targets, speed, **kwargs) + + pod.move_axes = move_axes + return moves -class DeckClearanceTests(PodMoveTest): - async def test_the_tallest_labware_under_the_path(self) -> None: +class TurnTests(PodMoveTest): + """The gripper's turn: to the angle given, as Biomek's GR is a line (no whole-turn twin).""" + + async def test_a_turn_goes_to_the_angle_given(self) -> None: driver = await self.homed() - lh = BiomekI7(driver=driver, deck=generic_deck()) - site = lh.deck.get_position("P6") - plate = cor_96_wellplate_360uL_Fb("plate") - site.assign_child_resource(plate) - left = self.pod(driver, "left") - assert left.declared is not None - loc = site.get_location_wrt(lh.deck) - # Biomek X/Y of the position's middle, cm. - x = (loc.x + site.get_size_x() / 2 - 100.0) / 10 # deck x = Biomek X + FRAME_X (10 cm) - y = (700.0 - (loc.y + site.get_size_y() / 2)) / 10 # deck y = FRAME_Y (70 cm) - Biomek Y - top = (loc.z + plate.get_size_z()) / 10 - safe = left.declared.geometry.additional_safe_height - self.assertAlmostEqual( - lh._traverse_clearance("left", (x - 1, x + 1), (y - 1, y + 1)), top + safe, places=4 - ) - self.assertAlmostEqual( - lh._traverse_clearance("left", (x - 1, x + 1), (y - 1, y + 1), tip_length=9.0), - top + safe + 9.0, - places=4, + pod = self.pod(driver, "left") + d = pod.declared + assert d is not None + await pod.move_axes({"GR": d.to_counts("GR", 90.0)}) + moves = record(pod) + # To -180: three quarters the long way round, not 180 a quarter turn away. + await pod._travel_gripper({"GR": d.to_counts("GR", -180.0)}) + self.assertEqual([m["GR"] for m in moves if "GR" in m], [d.to_counts("GR", -180.0)]) + + async def test_a_whole_turn_apart_is_another_angle(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "left") + d = pod.declared + assert d is not None + await pod.move_axes({"GR": d.to_counts("GR", -270.0)}) + self.assertTrue(pod._at_angle(d.to_counts("GR", -270.0))) + self.assertFalse(pod._at_angle(d.to_counts("GR", 90.0))) + + +class SpanTests(PodMoveTest): + """Before a gripper approach a Span-8 narrows its probes' span, as Biomek's: to its minimum, + with the probes raised first only when that is not clear.""" + + async def test_the_span_is_narrowed_before_the_gripper_travels(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "right") + d = pod.declared + assert d is not None + await pod.move_axes({"S": d.to_counts("S", 20.0)}) + moves = record(pod) + await pod._travel_gripper({"GY": d.to_counts("GY", 50.0)}) + self.assertEqual(moves[0], {"S": d.to_counts("S", d.limits["Span"][0])}) + self.assertEqual(set(moves[-1]), {"GY"}) + moves.clear() + await pod._travel_gripper({"GY": d.to_counts("GY", 52.0)}) # at its minimum already + self.assertFalse(any("S" in m for m in moves)) + + async def test_the_probes_rise_first_when_narrowing_is_not_clear(self) -> None: + driver = await self.homed() + pod = self.pod(driver, "right") + d = pod.declared + assert d is not None + await pod.move_axes({"S": d.to_counts("S", 20.0), "Z1": d.to_counts("Z1", 20.0)}) + tops = pod._max_traverse_heights() + clear = pod._clear + # Narrowing is not clear until the probes are at the top. + pod._clear = lambda moves, start=None: ( + ( # type: ignore[method-assign] + "S" not in moves[0] or pod.cpositions["Z1"][1] >= d.to_counts("Z1", tops["Z1"]) + ) + and clear(moves, start) ) + moves = record(pod) + await pod._travel_gripper({"GY": d.to_counts("GY", 50.0)}) + self.assertEqual(moves[0], {"Z1": d.to_counts("Z1", tops["Z1"])}) # the one below the top + self.assertEqual(moves[1], {"S": d.to_counts("S", d.limits["Span"][0])}) + + +class SafeHeightTests(unittest.TestCase): + """Biomek's travel height: the tallest deck item under the swept footprint (`travel`).""" + + def test_a_move_in_y_covers_its_bounding_box(self) -> None: + item = ((10.0, 11.0, 30.0, 31.0), 7.0) + self.assertEqual(traverse.covered((0, 2, 0, 2), (0, 2, 40, 42), [item]), []) + self.assertEqual(traverse.covered((9, 11, 0, 2), (9, 11, 40, 42), [item]), [7.0]) + + def test_a_diagonal_covers_its_band_not_its_bounding_box(self) -> None: + # From (0..2, 0..2) to (40..42, 40..42): a box in the bounding box's far corner is off the band. + off, on = ((35.0, 36.0, 0.0, 1.0), 5.0), ((20.0, 21.0, 20.0, 21.0), 6.0) + self.assertEqual(traverse.covered((0, 2, 0, 2), (40, 42, 40, 42), [off, on]), [6.0]) + + def test_touching_counts(self) -> None: + # The footprint grows by 1-3 mm (its spans + 2 mm, rounded): an item 1 mm off still counts. + self.assertEqual(traverse.covered((0, 2, 0, 2), (0, 2, 0, 2), [((2.1, 3, 0, 2), 4.0)]), [4.0]) + self.assertEqual(traverse.covered((0, 2, 0, 2), (0, 2, 0, 2), [((2.5, 3, 0, 2), 4.0)]), []) + self.assertEqual(traverse.deck_height((0, 2, 0, 2), (0, 2, 0, 2), []), float("-inf")) class PublicTravelInMillimetresTests(PodMoveTest): @@ -142,7 +193,7 @@ async def test_traverse_figures_are_mm(self) -> None: pod = self.pod(await self.homed(), "left") for axis, cm_value in pod._traverse_heights().items(): self.assertAlmostEqual(pod.traverse_heights()[axis], cm_value * 10) - for axis, cm_value in pod._traverse_ceilings().items(): - self.assertAlmostEqual(pod.traverse_ceilings()[axis], cm_value * 10) + for axis, cm_value in pod._max_traverse_heights().items(): + self.assertAlmostEqual(pod.max_traverse_heights()[axis], cm_value * 10) with self.assertRaises(ValueError): await pod.move_over({"X": 500.0}, speed_fraction=1.5) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py index 87de159982e..16fb1d7b88b 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail.py @@ -7,9 +7,10 @@ range counts its bridge, its pipettor and its gripper, turned and opened as it is, with what it holds (`driver/pod_geometry.py`). -`XRail` applies the same rule. It differs in three ways: -- **It refuses** a move into where the other pod stands, or will stand once its move ends, - rather than moving the other pod; `make_space` comes later. +`XRail` applies the same rule; the pod moves an idle other pod out of the way first, as Biomek's +clearing of the way (`Pod._make_way`). The rail itself differs in three ways: +- **It refuses** a move into where the other pod stands, or will stand once its move ends: when + the other pod is busy (a move, a step or a travel of its own), or clearing the way is off. - **It waits** when a move conflicts only with a move of the other pod still running, then checks again: the other pod is passing through, not staying (Biomek runs such moves together). - **It reserves** every move in flight, so two moves started together cannot pass through each @@ -43,7 +44,7 @@ class RailCollisionError(ValueError): @dataclass(frozen=True) -class PodPose: +class RailPose: """Where a pod is, as the rail needs it: deck X (cm) and its gripper's pose, None when not known (then every pose the gripper could take is counted).""" @@ -61,13 +62,13 @@ class XRail: def __init__(self, pods: Dict[Side, Optional[PodConfiguration]]): self.pods = pods - self._pose: Dict[Side, Optional[PodPose]] = {side: None for side in pods} + self._pose: Dict[Side, Optional[RailPose]] = {side: None for side in pods} self._reserved: Dict[Side, Optional[g.Range]] = {side: None for side in pods} self._end: Dict[Side, Optional[g.Range]] = {side: None for side in pods} self._done: Dict[Side, asyncio.Event] = {side: asyncio.Event() for side in pods} self._lock = asyncio.Lock() # How to read a pod's pose when the rail does not know it. Set by the driver. - self.readers: Dict[Side, Callable[[], Awaitable[PodPose]]] = {} + self.readers: Dict[Side, Callable[[], Awaitable[RailPose]]] = {} self._models = { side: g.GripperModel.from_bif(p.gripper_model) if p and p.gripper_model else None for side, p in pods.items() @@ -88,15 +89,15 @@ def _gripper(self, side: Side, pose: Optional[g.GripperPose]) -> Optional[g.Grip return None return g.Gripper(model, pose) - def range_at(self, side: Side, pose: PodPose) -> g.Range: + def range_at(self, side: Side, pose: RailPose) -> g.Range: """The X a pod takes up at a pose. An unknown gripper pose counts every pose it could take: the whole of GR's travel, fully open.""" pod = self._require_pod(side) if pose.gripper is not None or self._models.get(side) is None: return g.pod_x_range(pod.geometry, pose.x, self._gripper(side, pose.gripper)) - return self.swept(side, PodPose(pose.x, None), PodPose(pose.x, None)) + return self.swept(side, RailPose(pose.x, None), RailPose(pose.x, None)) - def swept(self, side: Side, start: PodPose, end: PodPose) -> g.Range: + def swept(self, side: Side, start: RailPose, end: RailPose) -> g.Range: """The X a pod takes up while moving from `start` to `end`.""" pod = self._require_pod(side) a, b = start.gripper, end.gripper @@ -111,7 +112,7 @@ def swept(self, side: Side, start: PodPose, end: PodPose) -> g.Range: pod.geometry, start.x, end.x, self._gripper(side, a), self._gripper(side, b) ) - def update(self, side: Side, pose: Optional[PodPose]) -> None: + def update(self, side: Side, pose: Optional[RailPose]) -> None: """Record where a pod is, or None when not known (after homing, or a move that failed). A known pose ends the reservation a failed move left, but never one of a move still running: a read can come back after that move started.""" @@ -124,6 +125,10 @@ def update(self, side: Side, pose: Optional[PodPose]) -> None: def _in_flight(self, side: Side) -> bool: return self._end[side] is not None + def in_flight(self, side: Side) -> bool: + """Whether a move of `side` is running (reserved on the rail).""" + return side in self.pods and self._in_flight(side) + def occupied(self, side: Side) -> Optional[g.Range]: """The X a pod takes up now: its move's reservation while one is in flight or a failed one left, else its range where it is. None when its position is not known.""" @@ -132,7 +137,7 @@ def occupied(self, side: Side) -> Optional[g.Range]: pose = self._pose.get(side) return None if pose is None else self.range_at(side, pose) - def check(self, side: Side, start: PodPose, end: PodPose) -> g.Range: + def check(self, side: Side, start: RailPose, end: RailPose) -> g.Range: """Check a move of `side` against the other pod. Returns the move's swept range. Raises: @@ -180,7 +185,7 @@ async def ensure_known(self, side: Side) -> None: self.update(side, await self.readers[side]()) @contextlib.asynccontextmanager - async def moving(self, side: Side, start: PodPose, end: PodPose) -> AsyncIterator[None]: + async def moving(self, side: Side, start: RailPose, end: RailPose) -> AsyncIterator[None]: """Hold a move's swept range for as long as the move runs. Checked and reserved together, under one lock. A move that conflicts only with the other diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py index c2809857f57..8d6cb1fd389 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/x_rail_tests.py @@ -7,7 +7,7 @@ from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g from pylabrobot.beckman_coulter.biomek_i7.driver.homing_tests import SimulatedRunTest -from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import PodPose, RailCollisionError, XRail +from pylabrobot.beckman_coulter.biomek_i7.driver.x_rail import RailPose, RailCollisionError, XRail from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration CONFIG = generic_configuration() @@ -17,10 +17,10 @@ PLATE = g.HeldLabware(length=12.776, width=8.548) # an SBS plate, held lengthwise -def pose(side: str, counts: int, gr: Optional[float] = 0.0, held=None) -> PodPose: +def pose(side: str, counts: int, gr: Optional[float] = 0.0, held=None) -> RailPose: """A pod at X `counts`, its gripper turned to `gr` degrees (None: not known).""" gripper = None if gr is None else g.GripperPose(gr, PARK_GG, held) - return PodPose(PODS[side].to_value("X", counts), gripper) + return RailPose(PODS[side].to_value("X", counts), gripper) def rail() -> XRail: @@ -181,7 +181,7 @@ async def test_an_unknown_position_is_read_first(self) -> None: r = rail() r.update("left", pose("left", 0)) - async def read_right() -> PodPose: + async def read_right() -> RailPose: return pose("right", -2560) r.readers["right"] = read_right @@ -199,8 +199,11 @@ def test_a_lone_pod_is_free(self) -> None: class RailOnTheInstrumentTests(SimulatedRunTest): + """The rail guard on its own: with clearing the way off, a move into the other pod is refused.""" + async def test_a_move_into_the_other_pod_sends_no_motion(self) -> None: driver = await self.start(True) + driver.make_way = False await driver.home() assert driver.left_x_arm and driver.right_x_arm await driver.right_x_arm.move_axes({"X": -100000}) @@ -215,6 +218,7 @@ async def test_a_move_into_the_other_pod_sends_no_motion(self) -> None: async def test_turning_a_gripper_into_the_other_pod_sends_no_motion(self) -> None: driver = await self.start(True) + driver.make_way = False await driver.home() assert driver.left_x_arm and driver.right_x_arm left, right = driver.left_x_arm, driver.right_x_arm @@ -240,5 +244,91 @@ async def test_both_pods_moving_at_once_cannot_cross(self) -> None: self.assertEqual(sum(isinstance(r, RailCollisionError) for r in results), 1) +class ClearTheWayTests(SimulatedRunTest): + """Biomek's clearing of the way: an idle other pod in a move's way moves aside on its own first, to the + next 1/16 cm grid line past the move's zone plus 1/64 cm, its gripper turned to the nearest + quarter.""" + + async def pods(self): # type: ignore[no-untyped-def] + driver = await self.start(True) + await driver.home() + assert driver.left_x_arm and driver.right_x_arm and driver.rail + return driver, driver.left_x_arm, driver.right_x_arm, driver.rail + + async def test_the_other_pod_moves_to_the_grid_edge_of_the_zone(self) -> None: + driver, left, right, rail = await self.pods() + await right.move_axes({"X": -100000}) + start = rail.occupied("left") + await left.move_axes({"X": 200000}) + assert start is not None + zone = g.union(start, rail.occupied("left") or start) + edge = (g.grid_cell(zone[1]) + 1) / 16 + 1 / 64 + low = rail.occupied("right") + assert low is not None + self.assertAlmostEqual(low[0], edge, delta=1 / 2560) # within a count of X + self.assertEqual(left.cpositions["X"][1], 200000) + self.assertFalse(g.grid_overlap(rail.occupied("left") or zone, low)) + + async def test_a_turn_towards_the_other_pod_moves_it_aside(self) -> None: + driver, left, right, rail = await self.pods() + await left.move_axes({"X": int((70 - 10.519) * 2560)}) + await right.move_axes({"X": int((110 - 146.40669375) * 2560)}) + before = left.cpositions["X"][1] + await right.move_axes({"GR": RIGHT.to_counts("GR", 180.0)}) + self.assertLess(left.cpositions["X"][1], before) # the left pod went left, out of the turn + left_range, right_range = rail.occupied("left"), rail.occupied("right") + assert left_range is not None and right_range is not None + self.assertFalse(g.grid_overlap(left_range, right_range)) + + async def test_the_other_pods_gripper_turns_to_the_nearest_quarter(self) -> None: + driver, left, right, rail = await self.pods() + await right.move_axes({"X": -100000, "GR": RIGHT.to_counts("GR", 100.0)}) + await left.move_axes({"X": 200000}) + self.assertAlmostEqual(RIGHT.to_value("GR", right.cpositions["GR"][1]), 90.0, delta=0.01) + + async def test_a_busy_pod_is_not_moved(self) -> None: + driver, left, right, rail = await self.pods() + await right.move_axes({"X": -100000}) + with right.working_at("P1"): # a step of its own under way + with self.assertRaises(RailCollisionError): + await left.move_axes({"X": 200000}) + self.assertEqual(right.cpositions["X"][1], -100000) + + async def test_no_way_out_is_refused(self) -> None: + driver, left, right, rail = await self.pods() + self.mark(driver) + with self.assertRaisesRegex(RailCollisionError, "cannot move out of the other pod's way"): + await left.move_axes({"X": LEFT.to_counts("X", LEFT.limits["X"][1])}) + sent = {m[4] for m in self.usb(driver, "multichannel").requests[self.marks["multichannel"] :]} + self.assertNotIn(0x50, sent) # the left pod sent no Move All + + async def test_labware_taken_counts_from_the_next_move_on(self) -> None: + # What the gripper takes changes the pod's range: the rail counts it only once a move with + # it is checked (the grip's close, or the first move after), which moves the other pod aside. + driver, left, right, rail = await self.pods() + await left.move_axes({"X": int((70 - 10.519) * 2560), "GR": LEFT.to_counts("GR", 0.0)}) + await right.move_axes({"X": int((112 - 146.40669375) * 2560), "GR": RIGHT.to_counts("GR", 180.0)}) + before, left_x = rail.occupied("right"), left.cpositions["X"][1] + assert right.gripper is not None + right.gripper.set_held_labware(g.HeldLabware(length=12.776, width=8.548, height=0.9)) + self.assertEqual(rail.occupied("right"), before) # not yet: no move has been checked with it + await right.move_axes({"GZ": right.cpositions["GZ"][1] - 100}) + grown = rail.occupied("right") + assert before is not None and grown is not None + self.assertLess(grown[0], before[0]) # the lid reaches further left + self.assertLess(left.cpositions["X"][1], left_x) # and the left pod moved aside for it + left_range = rail.occupied("left") + assert left_range is not None + self.assertFalse(g.grid_overlap(left_range, grown)) + + async def test_off_it_is_the_rail_guards_refusal(self) -> None: + driver, left, right, rail = await self.pods() + driver.make_way = False + await right.move_axes({"X": -100000}) + with self.assertRaises(RailCollisionError): + await left.move_axes({"X": 200000}) + self.assertEqual(right.cpositions["X"][1], -100000) + + if __name__ == "__main__": unittest.main() diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py index a18dfb41638..8e63d3bf526 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/alps.py @@ -42,6 +42,11 @@ class Site(NamedTuple): size_x: its width. size_y: its depth. adaptor_z: where labware sits from its floor (`AdaptorPlate.Z`). + min_safe_height: the least height above its floor a pod's parts stay over it, empty or not + (`MinSafeHeight`). + obstacles: fixed parts of the ALP around it, as Biomek lists them per position (`Obstacles`): + (name, `XOffset`, `XSpan`, `YOffset`, `YSpan`, `ZOffset`), from its back left corner and its + floor; each stands from below the deck up to its top. tip_disposal: where the pods discard tips, for a trash. head96_tip_loading: whether the 96-head may load tips here (the position's characteristic "Multichannel Can Load Tips": only the tip-loading ALP's, built to take the press). @@ -55,6 +60,8 @@ class Site(NamedTuple): size_x: float size_y: float adaptor_z: float = 0.0 + min_safe_height: float = 1.0 + obstacles: Tuple[Tuple[str, float, float, float, float, float], ...] = () tip_disposal: Optional["TipDisposal"] = None head96_tip_loading: bool = False @@ -80,6 +87,19 @@ class TipDisposal(NamedTuple): span8_y: float +class PositionObstacle(NamedTuple): + """A fixed part beside a deck position (a trash bin's wall), in the position's frame (mm): `x0`.. + `x1`, `y0`..`y1` from its front left corner, standing from below the deck up to `top` above its + floor.""" + + name: str + x0: float + x1: float + y0: float + y1: float + top: float + + class BiomekPosition(ResourceHolder): """A deck position on an ALP. Biomek centres the labware in it: a position is a little larger than the labware (12.819 x 8.59 cm against a tip box's 12.79 x 8.54), and Biomek's targets are the @@ -88,6 +108,10 @@ class BiomekPosition(ResourceHolder): Attributes: labware_z: where labware sits from the position's floor, mm (`Site.adaptor_z`). + min_safe_height: the least height (mm above its floor) a pod's parts stay over it, empty or + not: the deck check's box for it reaches at least this high. + obstacles: fixed parts of its ALP beside it (`PositionObstacle`), which stay in the deck check + even when the position itself is an operation's target. tip_disposal: for a trash, where the pods discard tips. head96_tip_loading: whether the 96-head may load tips here (`Site.head96_tip_loading`). """ @@ -99,6 +123,8 @@ def __init__( size_y: float, size_z: float, labware_z: float = 0.0, + min_safe_height: float = 10.0, + obstacles: Sequence[Sequence[Any]] = (), tip_disposal: Optional[Sequence[float]] = None, head96_tip_loading: bool = False, **kwargs: Any, @@ -106,6 +132,10 @@ def __init__( super().__init__(name=name, size_x=size_x, size_y=size_y, size_z=size_z, **kwargs) self.head96_tip_loading = head96_tip_loading self.labware_z = labware_z + self.min_safe_height = min_safe_height + self.obstacles: Tuple[PositionObstacle, ...] = tuple( + PositionObstacle(str(o[0]), *(float(v) for v in o[1:])) for o in obstacles + ) self.tip_disposal = None if tip_disposal is None else TipDisposal(*tip_disposal) def get_default_child_location(self, resource) -> Coordinate: # type: ignore[no-untyped-def] @@ -120,11 +150,29 @@ def serialize(self) -> dict: return { **super().serialize(), "labware_z": self.labware_z, + "min_safe_height": self.min_safe_height, + "obstacles": [list(o) for o in self.obstacles], "tip_disposal": None if self.tip_disposal is None else list(self.tip_disposal), "head96_tip_loading": self.head96_tip_loading, } +def _position_obstacle( + o: Tuple[str, float, float, float, float, float], size_y: float +) -> PositionObstacle: + """A Biomek position obstacle (offsets from the position's back left corner, Y forward, cm) in + the position's frame (from its front left corner, mm).""" + name, x_offset, x_span, y_offset, y_span, z_offset = o + return PositionObstacle( + name, + cm(x_offset), + cm(x_offset + x_span), + size_y - cm(y_offset + y_span), + size_y - cm(y_offset), + cm(z_offset), + ) + + def alp_model(alp_type: str) -> str: """The model name of an ALP type: Biomek's name, namespaced, so its mesh file is unambiguous.""" return "beckman_coulter_biomek_alp_" + alp_type.replace("-", "_") @@ -224,6 +272,8 @@ def _alp( size_y=cm(site.size_y), size_z=0, labware_z=cm(site.adaptor_z), + min_safe_height=cm(site.min_safe_height), + obstacles=[_position_obstacle(o, cm(site.size_y)) for o in site.obstacles], tip_disposal=site.tip_disposal, head96_tip_loading=site.head96_tip_loading, ) @@ -319,6 +369,7 @@ def _trash( pin_offset_x: float, site_x: float, tip_disposal: TipDisposal, + walls: Tuple[Tuple[str, float, float, float, float, float], ...], names: Names, ) -> BiomekALP: return _alp( @@ -328,7 +379,19 @@ def _trash( pin_count=(7, 7), pin_offset=(pin_offset_x, 0.961), # The chute's opening sits 6.896 cm below the top. - sites=[Site("A1", "TR", site_x, 2.9351, -6.896, *_PLATE_SITE, tip_disposal=tip_disposal)], + sites=[ + Site( + "A1", + "TR", + site_x, + 2.9351, + -6.896, + *_PLATE_SITE, + min_safe_height=0.1, + obstacles=walls, + tip_disposal=tip_disposal, + ) + ], position_names=names, ) @@ -341,6 +404,12 @@ def biomek_trash_left_bin(name: str, position_names: Names = None) -> BiomekALP: pin_offset_x=18.997, site_x=18.527, tip_disposal=TipDisposal(0.0, 1.124, 5.896, span8_x=-4.2186, span8_y=0.0), # CustomData + walls=( # Positions[A1].Obstacles + ("Back", -18.527, 32.446, -2.9351, 1.4, 6.896), + ("Front", -18.527, 32.446, 10.0829, 1.4, 6.896), + ("Left", -18.527, 9.859, -2.9351, 14.418, 6.3755), + ("Right", 13.577, 0.342, -2.9351, 14.418, 6.3755), + ), names=position_names, ) @@ -353,6 +422,12 @@ def biomek_trash_right_bin(name: str, position_names: Names = None) -> BiomekALP pin_offset_x=0.953, site_x=1.1, tip_disposal=TipDisposal(5.9995, 1.124, 5.896, span8_x=4.561, span8_y=0.0), # CustomData + walls=( # Positions[A1].Obstacles + ("Back", -1.1, 32.446, -2.9351, 1.4, 6.896), + ("Front", -1.1, 32.446, 10.0829, 1.4, 6.896), + ("Left", -1.1, 0.342, -2.9351, 14.418, 6.3755), + ("Right", 21.381, 9.965, -2.9351, 14.418, 6.3755), + ), names=position_names, ) @@ -378,7 +453,7 @@ def biomek_orbital_shaker(name: str, position_names: Names = None) -> BiomekALP: size=(14.802, 10.16, 16.134), pin_count=(7, 5), pin_offset=(1.118, 0.914), - sites=[Site("A1", "Orbital", 0.815, 0.851, 0.0, *_PLATE_SITE)], + sites=[Site("A1", "Orbital", 0.815, 0.851, 0.0, *_PLATE_SITE, min_safe_height=2.1)], position_names=position_names, ) @@ -391,7 +466,7 @@ def biomek_bioshake(name: str, position_names: Names = None) -> BiomekALP: size=(14.21, 10.0, 17.13), pin_count=(5, 5), pin_offset=(2.934, 0.834), - sites=[Site("A1", "BS", 0.696, 0.705, 0.0, *_PLATE_SITE)], + sites=[Site("A1", "BS", 0.696, 0.705, 0.0, *_PLATE_SITE, min_safe_height=2.1)], position_names=position_names, ) @@ -404,7 +479,7 @@ def biomek_cold_plate(name: str, position_names: Names = None) -> BiomekALP: size=(14.21, 10.0, 16.057), pin_count=(5, 5), pin_offset=(2.934, 0.834), - sites=[Site("A1", "CP", 0.696, 0.705, 0.0, *_PLATE_SITE)], + sites=[Site("A1", "CP", 0.696, 0.705, 0.0, *_PLATE_SITE, min_safe_height=5.0)], position_names=position_names, ) @@ -430,7 +505,7 @@ def biomek_tilting_alp(name: str, position_names: Names = None) -> BiomekALP: size=(15.2, 10.1, 15.87), pin_count=(7, 5), pin_offset=(1.35, 1.09), - sites=[Site("A1", "TA", 1.19, 0.755, 0.0, *_PLATE_SITE)], + sites=[Site("A1", "TA", 1.19, 0.755, 0.0, *_PLATE_SITE, min_safe_height=11.0)], position_names=position_names, ) @@ -447,7 +522,21 @@ def biomek_elx405dw(name: str, position_names: Names = None) -> BiomekALP: size=(41.1, 42.6, 10.6), pin_count=(11, 2), pin_offset=(10.713, 38.375), - sites=[Site("A1", "W", 23.77, 28.76, 0.0, *_PLATE_SITE)], + sites=[ + Site( + "A1", + "W", + 23.77, + 28.76, + 0.0, + *_PLATE_SITE, + min_safe_height=2.0, + obstacles=( # Positions[A1].Obstacles + ("BackObstacle", -25.5, 42.3, -28.8, 25.9, 21.7), + ("LeftObstacle", -23.8, 19.0, -3.0, 15.0, 19.9), + ), + ) + ], position_names=position_names, ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py new file mode 100644 index 00000000000..6e41611f45d --- /dev/null +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py @@ -0,0 +1,147 @@ +"""The instrument's own structure around the deck, as resources: the towers, shields, I-beam, pump +bank, cameras, floor and the light curtain's plane. + +Biomek keeps them as boxes in its frame (cm; Y towards the front, Z up from the deck surface), a +bound that is not given open on that side, each face widened by a buffer. A `BiomekObstacle` keeps +those bounds as Biomek gives them, which is what the deck check uses, and is sized as the part of +that box within the instrument, which is what it draws as. Made from the declared configuration's +obstacle list (the instrument file's), they are ordinary resources: one can be added or moved by +hand like any other. +""" + +import math +from typing import Dict, Iterable, List, Optional, Sequence, Tuple + +from pylabrobot.beckman_coulter.biomek_i7.driver.configuration import Obstacle +from pylabrobot.resources.coordinate import Coordinate +from pylabrobot.resources.resource import Resource + +from .units import MM_PER_CM + +# How far an open bound is drawn, cm in Biomek's frame: to the instrument's edges (left, right, +# back, front), from below the deck surface, and up to above the pods' tops. The deck check uses +# the open bound itself. +Extent = Tuple[float, float, float, float, float, float] + + +class BiomekObstacle(Resource): + """A fixed part of the instrument as Biomek keeps it: `x1`..`z2` its box in Biomek's frame (cm; + None open on that side), each face widened by `buffer` (cm).""" + + def __init__( + self, + name: str, + size_x: float, + size_y: float, + size_z: float, + buffer: float = 0.0, + x1: Optional[float] = None, + x2: Optional[float] = None, + y1: Optional[float] = None, + y2: Optional[float] = None, + z1: Optional[float] = None, + z2: Optional[float] = None, + category: str = "instrument_structure", + model: Optional[str] = None, + ): + super().__init__( + name=name, size_x=size_x, size_y=size_y, size_z=size_z, category=category, model=model + ) + self.buffer = buffer + self.x1, self.x2, self.y1, self.y2, self.z1, self.z2 = x1, x2, y1, y2, z1, z2 + + def obstacle(self) -> Obstacle: + """The box as Biomek keeps it.""" + return Obstacle(self.name, self.buffer, self.x1, self.x2, self.y1, self.y2, self.z1, self.z2) + + def serialize(self) -> dict: + return { + **super().serialize(), + "buffer": self.buffer, + "x1": self.x1, + "x2": self.x2, + "y1": self.y1, + "y2": self.y2, + "z1": self.z1, + "z2": self.z2, + } + + +def merge_obstacles(per_pod: Iterable[Sequence[Obstacle]]) -> List[Obstacle]: + """One obstacle per name from each pod's list (Biomek keeps a list per pod, the same parts with a + few edges measured per pod): where they differ, the larger box, and the larger buffer.""" + + def low(a: Optional[float], b: Optional[float]) -> Optional[float]: + return None if a is None or b is None else min(a, b) + + def high(a: Optional[float], b: Optional[float]) -> Optional[float]: + return None if a is None or b is None else max(a, b) + + merged: Dict[str, Obstacle] = {} + for obstacles in per_pod: + for o in obstacles: + m = merged.get(o.name) + merged[o.name] = ( + o + if m is None + else Obstacle( + o.name, + max(m.buffer, o.buffer), + low(m.x1, o.x1), + high(m.x2, o.x2), + low(m.y1, o.y1), + high(m.y2, o.y2), + low(m.z1, o.z1), + high(m.z2, o.z2), + ) + ) + return list(merged.values()) + + +def structure_resources( + obstacles: Sequence[Obstacle], extent: Extent, to_device: "FrameToDevice" +) -> List[Tuple[BiomekObstacle, Coordinate]]: + """Each obstacle as a `BiomekObstacle` and where it goes in the device: drawn as the part of its + box (unwidened) within `extent` (Biomek cm: x0, x1, y0, y1, z0, z1); one wholly outside it is + left out.""" + out = [] + x0, x1, y0, y1, z0, z1 = extent + + def clip(lo: Optional[float], hi: Optional[float], a: float, b: float) -> Tuple[float, float]: + return max(a, -math.inf if lo is None else lo), min(b, math.inf if hi is None else hi) + + for o in obstacles: + bx = clip(o.x1, o.x2, x0, x1) + by = clip(o.y1, o.y2, y0, y1) + bz = clip(o.z1, o.z2, z0, z1) + if bx[1] <= bx[0] or by[1] <= by[0] or bz[1] <= bz[0]: + continue + resource = BiomekObstacle( + name=f"structure_{o.name}", + size_x=(bx[1] - bx[0]) * MM_PER_CM, + size_y=(by[1] - by[0]) * MM_PER_CM, + size_z=(bz[1] - bz[0]) * MM_PER_CM, + buffer=o.buffer, + x1=o.x1, + x2=o.x2, + y1=o.y1, + y2=o.y2, + z1=o.z1, + z2=o.z2, + model=o.name, + ) + # Its front left bottom corner: Biomek's Y runs to the front, so the box's front is its high Y. + out.append((resource, to_device(bx[0], by[1], bz[0]))) + return out + + +class FrameToDevice: + """A point in Biomek's frame (cm) as a location in the device (mm).""" + + def __init__(self, deck_location: Coordinate, frame_x: float, frame_y: float): + self.deck_location, self.frame_x, self.frame_y = deck_location, frame_x, frame_y + + def __call__(self, x: float, y: float, z: float) -> Coordinate: + return self.deck_location + Coordinate( + x * MM_PER_CM + self.frame_x, self.frame_y - y * MM_PER_CM, z * MM_PER_CM + ) diff --git a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py index 7e42804f998..cb453a33265 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/simulation_tests.py @@ -31,12 +31,16 @@ async def test_the_tip_sensor_reports_the_recorded_tips(self) -> None: pipettes._set_tips({2: biomek_tip("T230", "t")}) self.assertEqual((await pipettes.sense_tip_presence())[:3], ["unloaded", "loaded", "unloaded"]) - async def test_a_pod_moves_aside(self) -> None: + async def test_move_aside_folds_the_gripper_where_the_pod_stands(self) -> None: pod = self.biomek.left_x_arm assert pod is not None and pod.declared is not None + d = pod.declared + await pod.move_axes({"GR": d.to_counts("GR", 0.0), "GY": d.to_counts("GY", 40.0)}) + x = pod.cpositions["X"][1] await pod.move_aside() - low, _ = pod.declared.limits["X"] - self.assertEqual(pod.cpositions["X"][1], pod.declared.to_counts("X", low)) + self.assertEqual(pod.cpositions["X"][1], x) # the X room is made by clearing the way + self.assertEqual(pod.cpositions["GY"][1], d.to_counts("GY", d.park["GY"])) + self.assertEqual(pod.cpositions["GR"][1], d.to_counts("GR", d.park["GR"])) class TimedSimulationTests(unittest.IsolatedAsyncioTestCase): diff --git a/pylabrobot/beckman_coulter/biomek_i7/targeting.py b/pylabrobot/beckman_coulter/biomek_i7/targeting.py index 3e6b042f33b..70a898275df 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/targeting.py +++ b/pylabrobot/beckman_coulter/biomek_i7/targeting.py @@ -44,14 +44,15 @@ def position_correction( configuration: DeviceConfiguration, position: ResourceHolder, pod_number: int, + location: Optional[Coordinate] = None, ) -> Tuple[float, float, float]: """How far, cm, pod `pod_number`'s calibrated corner of `position` is from where the deck model puts the position's corner (its back left bottom corner, in Biomek's frame). Zero for a position - the configuration does not hold.""" + the configuration does not hold. `location`: the position's on `deck`, when already known.""" calibrated = configuration.deck_positions.get(position.name) if calibrated is None: return 0.0, 0.0, 0.0 - loc = position.get_location_wrt(deck) + loc = position.get_location_wrt(deck) if location is None else location nominal = to_biomek(Coordinate(loc.x, loc.y + position.get_size_y(), loc.z)) x, y, z = calibrated.corner(pod_number) return x - nominal.x, y - nominal.y, z - nominal.z From 02f0beeb21c3e95e307efc31ae03e608b80e9457 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:51:35 -0500 Subject: [PATCH 26/28] `Biomek i7`: instrument obstacles are boundaries --- .../beckman_coulter/biomek_i7/resource_model/structure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py b/pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py index 6e41611f45d..101f2f8d0c3 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py +++ b/pylabrobot/beckman_coulter/biomek_i7/resource_model/structure.py @@ -41,7 +41,7 @@ def __init__( y2: Optional[float] = None, z1: Optional[float] = None, z2: Optional[float] = None, - category: str = "instrument_structure", + category: str = "boundary", model: Optional[str] = None, ): super().__init__( From e7a293bc70ce373aa4597e74263395202919dc35 Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:02:06 +0000 Subject: [PATCH 27/28] `Biomek i7`: drop unused traverse imports and satisfy mypy in planning tests --- .../biomek_i7/driver/pod_planning_tests.py | 30 +++++++++++++------ .../biomek_i7/driver/traverse_tests.py | 22 +++++--------- 2 files changed, 29 insertions(+), 23 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py index a776750f034..482d41f59f0 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py @@ -5,13 +5,13 @@ import unittest from typing import List, Tuple -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g -from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import ROWS, COLUMNS, mandrel_name from pylabrobot.beckman_coulter.biomek_i7.driver import liquid_tests +from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g +from pylabrobot.beckman_coulter.biomek_i7.driver.features.head96 import COLUMNS, ROWS, mandrel_name +from pylabrobot.beckman_coulter.biomek_i7.driver.planning import check, obstacles, pod_model, search from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest from pylabrobot.beckman_coulter.biomek_i7.resource_model.labware import biomek_tip from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import generic_configuration -from pylabrobot.beckman_coulter.biomek_i7.driver.planning import check, obstacles, pod_model, search Move = Tuple[dict, Tuple[str, ...]] @@ -36,7 +36,11 @@ def tips(self, driver) -> None: # type: ignore[no-untyped-def] head = self.pod(driver, "left").head96 assert head is not None head._set_tips( - {mandrel_name(r, c): biomek_tip("T230", f"t_{r}_{c}") for r in range(ROWS) for c in range(COLUMNS)} + { + mandrel_name(r, c): biomek_tip("T230", f"t_{r}_{c}") + for r in range(ROWS) + for c in range(COLUMNS) + } ) async def test_the_approach_exempts_nothing_and_the_descent_its_position(self) -> None: @@ -143,9 +147,11 @@ def order(self, pushes: List[Tuple[str, float]]) -> List[str]: open_set = search.OpenSet() for node, cost in pushes: open_set.push(node, cost) - out = [] + out: List[str] = [] while open_set: - out.append(open_set.pop()) + node = open_set.pop() + assert isinstance(node, str) + out.append(node) return out def test_cheapest_first_and_equal_costs_in_arrival_order(self) -> None: @@ -195,7 +201,9 @@ async def test_a_pushable_pod_is_walled_at_its_bridge_at_the_end_of_its_travel(s limits = left._planning_x_limits() assert limits is not None bridge = g.bridge_x_range(d.geometry, limits[1]) - self.assertAlmostEqual(bridge[1], g.bridge_x_range(od.geometry, od.limits["X"][1])[0] - (1 / 16 + 1 / 64)) + self.assertAlmostEqual( + bridge[1], g.bridge_x_range(od.geometry, od.limits["X"][1])[0] - (1 / 16 + 1 / 64) + ) async def test_a_busy_pod_is_walled_where_it_stands(self) -> None: driver = await self.homed() @@ -242,7 +250,9 @@ def world(self, positions: Tuple[str, ...]) -> obstacles.Obstacles: return obstacles.Obstacles((), (box,), positions) def test_a_part_in_a_position_rises_to_its_top(self) -> None: - out = check.escape(self.config, pod_model.PodState(30.0, None, self.pipettor), self.world(("P1",))) + out = check.escape( + self.config, pod_model.PodState(30.0, None, self.pipettor), self.world(("P1",)) + ) assert out is not None self.assertEqual((out.holders, out.gripper), (("P1",), 0.0)) world = self.world(("P1",)) @@ -260,7 +270,9 @@ def test_a_clear_pod_has_nothing_to_leave(self) -> None: self.assertEqual(out, check.Escape((), (0.0,), 0.0)) def test_no_way_out_of_anything_but_a_position(self) -> None: - self.assertIsNone(check.escape(self.config, pod_model.PodState(30.0, None, self.pipettor), self.world(()))) + self.assertIsNone( + check.escape(self.config, pod_model.PodState(30.0, None, self.pipettor), self.world(())) + ) def test_only_the_span8_probes_inside_rise(self) -> None: # As the logged escapes: probes 2-4 left in the plate rise, the others stay. diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py index 92d961ef2a9..672ed91aa6e 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/traverse_tests.py @@ -4,15 +4,8 @@ import unittest from typing import List -from pylabrobot.beckman_coulter.biomek_i7.device import BiomekI7 -from pylabrobot.beckman_coulter.biomek_i7.driver import pod_geometry as g -from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest -from pylabrobot.resources.corning.plates import cor_96_wellplate_360uL_Fb from pylabrobot.beckman_coulter.biomek_i7.driver.planning import traverse -from pylabrobot.beckman_coulter.biomek_i7.simulation_tests_support import ( - generic_configuration, - generic_deck, -) +from pylabrobot.beckman_coulter.biomek_i7.driver.pod_move_tests import PodMoveTest class MoveOverTests(PodMoveTest): @@ -134,13 +127,14 @@ async def test_the_probes_rise_first_when_narrowing_is_not_clear(self) -> None: await pod.move_axes({"S": d.to_counts("S", 20.0), "Z1": d.to_counts("Z1", 20.0)}) tops = pod._max_traverse_heights() clear = pod._clear - # Narrowing is not clear until the probes are at the top. - pod._clear = lambda moves, start=None: ( - ( # type: ignore[method-assign] + + def not_clear_until_probes_up(moves, start=None): # type: ignore[no-untyped-def] + return ( "S" not in moves[0] or pod.cpositions["Z1"][1] >= d.to_counts("Z1", tops["Z1"]) - ) - and clear(moves, start) - ) + ) and clear(moves, start) + + # Narrowing is not clear until the probes are at the top. + pod._clear = not_clear_until_probes_up # type: ignore[method-assign] moves = record(pod) await pod._travel_gripper({"GY": d.to_counts("GY", 50.0)}) self.assertEqual(moves[0], {"Z1": d.to_counts("Z1", tops["Z1"])}) # the one below the top From 03da30a2ea02a1c3f99a17a3bfae1aed145a3e8a Mon Sep 17 00:00:00 2001 From: Cody Moore <46687103+cmoscy@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:02:29 +0000 Subject: [PATCH 28/28] `Biomek i7`: avoid reusing OpenSet test loop variable for Hashable pops --- .../beckman_coulter/biomek_i7/driver/pod_planning_tests.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py index 482d41f59f0..fcb5d83760c 100644 --- a/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py +++ b/pylabrobot/beckman_coulter/biomek_i7/driver/pod_planning_tests.py @@ -149,9 +149,9 @@ def order(self, pushes: List[Tuple[str, float]]) -> List[str]: open_set.push(node, cost) out: List[str] = [] while open_set: - node = open_set.pop() - assert isinstance(node, str) - out.append(node) + popped = open_set.pop() + assert isinstance(popped, str) + out.append(popped) return out def test_cheapest_first_and_equal_costs_in_arrival_order(self) -> None: