code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
cmdline = _get_proc_cmdline() match = re.search(b'root=([/a-zA-Z0-9.]+)', cmdline) if not match: raise RuntimeError(f"Couldn't find bootpart from {cmdline}") return match.group(1).decode()
def find_active_sysroot() -> str
Parse /proc/cmdline to find the active sysroot. Return the path
5.667603
4.310857
1.314728
new_conn_lines = [] for line in connection.split('\n'): if '=' in line: parts = line.split('=') path_matches = re.search( '/mnt/data/resin-data/[0-9]+/(.*)', parts[1]) if path_matches: new_path = f'/data/{path_matches.group(1)}' ...
def patch_connection_file_paths(connection: str) -> str
Patch any paths in a connection to remove the balena host paths Undoes the changes applied by :py:meth:`opentrons.system.nmcli._rewrite_key_path_to_host_path` :param connection: The contents of a NetworkManager connection file :return: The patches contents, suitable for writing somewher
3.180194
3.118736
1.019706
try: with mount_data_partition() as datamount: migrate_data(ignore, datamount, DATA_DIR_NAME) migrate_connections(datamount) migrate_hostname(datamount, name) except Exception: LOG.exception("Exception during data migration") raise
def migrate(ignore: Sequence[str], name: str)
Copy everything in the app data to the root of the new partition :param ignore: Files to ignore in the root. This should be populated with the names (with no directory elements) of the migration update zipfile and everything unzipped from it. :param str: The name of the ro...
7.854969
7.706888
1.019214
# the new ’data’ path is actually /var and /data is in /var/data dest_data = os.path.join(new_data_path, 'data') LOG.info(f"migrate_data: copying {old_data_path} to {dest_data}") os.makedirs(dest_data, exist_ok=True) with os.scandir(old_data_path) as scanner: for entry in scanner: ...
def migrate_data(ignore: Sequence[str], new_data_path: str, old_data_path: str)
Copy everything in the app data to the root of the main data part :param ignore: A list of files that should be ignored in the root of /data :param new_data_path: Where the new data partition is mounted :param old_data_path: Where the old date files are
2.190773
2.205006
0.993545
found = False LOG.info(f"migrate_system_connections: checking {dest_sc}") os.makedirs(dest_sc, exist_ok=True) with os.scandir(src_sc) as scanner: for entry in scanner: # ignore readme and sample if entry.name.endswith('.ignore'): continue ...
def migrate_system_connections(src_sc: str, dest_sc: str) -> bool
Migrate the contents of a system-connections dir :param dest_sc: The system-connections to copy to. Will be created if it does not exist :param src_sc: The system-connections to copy from :return: True if anything was moved
4.412597
4.426437
0.996873
dest_connections = os.path.join( new_data_path, 'lib', 'NetworkManager', 'system-connections') os.makedirs(dest_connections, exist_ok=True) with mount_state_partition() as state_path: src_connections = os.path.join( state_path, 'root-overlay', 'etc', 'NetworkManager', ...
def migrate_connections(new_data_path: str)
Migrate wifi connection files to new locations and patch them :param new_data_path: The path to where the new data partition is mounted
2.767341
2.808856
0.98522
if name.startswith('opentrons-'): name = name[len('opentrons-'):] LOG.info( f"migrate_hostname: writing name {name} to {dest_data}/hostname," f" {dest_data}/machine-info, {dest_data}/serial") with open(os.path.join(dest_data, 'hostname'), 'w') as hn: hn.write(name + "\n"...
def migrate_hostname(dest_data: str, name: str)
Write the machine name to a couple different places :param dest_data: The path to the root of ``/var`` in buildroot :param name: The name The hostname gets written to: - dest_path/hostname (bind mounted to /etc/hostname) (https://www.freedesktop.org/software/systemd/man/hostname.html#) - dest_...
2.808664
2.160751
1.299855
flow_rate_param = params['flowRate'] if not (flow_rate_param > 0): raise RuntimeError('Positive flowRate param required') pipette.flow_rate = { 'aspirate': flow_rate_param, 'dispense': flow_rate_param }
def _set_flow_rate(pipette, params) -> None
Set flow rate in uL/mm, to value obtained from command's params.
3.550851
3.18842
1.113671
if 'OT_API_CONFIG_DIR' in os.environ: return Path(os.environ['OT_API_CONFIG_DIR']) elif IS_ROBOT: return Path('/data') else: search = (Path.cwd(), Path.home()/'.opentrons') for path in search: if (path/_CONFIG_FILENAME).exists(): ...
def infer_config_base_dir() -> Path
Return the directory to store data in. Defaults are ~/.opentrons if not on a pi; OT_API_CONFIG_DIR is respected here. When this module is imported, this function is called automatically and the result stored in :py:attr:`APP_DATA_DIR`. This directory may not exist when the module is imported. Eve...
4.708955
3.910089
1.204309
if IS_ROBOT: _migrate_robot() base = infer_config_base_dir() base.mkdir(parents=True, exist_ok=True) index = _load_with_overrides(base) return _ensure_paths_and_types(index)
def load_and_migrate() -> Dict[str, Path]
Ensure the settings directory tree is properly configured. This function does most of its work on the actual robot. It will move all settings files from wherever they happen to be to the proper place. On non-robots, this mostly just loads. In addition, it writes a default config and makes sure all dire...
8.574779
8.453311
1.014369
should_write = False overrides = _get_environ_overrides() try: index = json.load((base/_CONFIG_FILENAME).open()) except (OSError, json.JSONDecodeError) as e: sys.stderr.write("Error loading config from {}: {}\nRewriting...\n" .format(str(base), e)) s...
def _load_with_overrides(base) -> Dict[str, str]
Load an config or write its defaults
3.716908
3.617933
1.027357
configs_by_name = {ce.name: ce for ce in CONFIG_ELEMENTS} correct_types: Dict[str, Path] = {} for key, item in index.items(): if key not in configs_by_name: # old config, ignore continue if configs_by_name[key].kind == ConfigElementType.FILE: it = Path(item) ...
def _ensure_paths_and_types(index: Dict[str, str]) -> Dict[str, Path]
Take the direct results of loading the config and make sure the filesystem reflects them.
2.599415
2.559329
1.015663
return { ce.name: os.environ['OT_API_' + ce.name.upper()] for ce in CONFIG_ELEMENTS if 'OT_API_' + ce.name.upper() in os.environ}
def _get_environ_overrides() -> Dict[str, str]
Pull any overrides for the config elements from the environ and return a mapping from the names to the values (as strings). Config elements that are not overridden will not be in the mapping.
5.291615
4.415512
1.198415
for index in _LEGACY_INDICES: if index.exists(): try: return json.load(open(index)) except (OSError, json.JSONDecodeError): return None return None
def _legacy_index() -> Union[None, Dict[str, str]]
Try and load an index file from the various places it might exist. If the legacy file cannot be found or cannot be parsed, return None. This method should only be called on a robot.
3.543252
3.498967
1.012656
if normal_path is None: return None if os.path.exists(normal_path): return normal_path dirname, basename = os.path.split(normal_path) root, ext = os.path.splitext(basename) backups = [fi for fi in os.listdir(dirname) if fi.startswith(root) and fi.endswith(ext)] ...
def _find_most_recent_backup(normal_path: Optional[str]) -> Optional[str]
Find the most recent old settings to migrate. The input is the path to an unqualified settings file - e.g. /mnt/usbdrive/config/robotSettings.json This will return - None if the input is None (to support chaining from dict.get()) - The input if it exists, or - The file named normal_path-TIMEST...
2.107268
2.243629
0.939223
base = Path(base_dir) if base_dir else infer_config_base_dir() def parse_or_default( ce: ConfigElement, val: Optional[str]) -> Path: if not val: return base / Path(ce.default) else: return Path(val) return { ce.name: parse_or_default(ce, ...
def generate_config_index(defaults: Dict[str, str], base_dir=None) -> Dict[str, Path]
Determines where existing info can be found in the system, and creates a corresponding data dict that can be written to index.json in the baseDataDir. The information in the files defined by the config index is information required by the API itself and nothing else - labware definitions, feature f...
3.39051
4.528963
0.748628
path = Path(path) if path else infer_config_base_dir() valid_names = [ce.name for ce in CONFIG_ELEMENTS] try: os.makedirs(path, exist_ok=True) with (path/_CONFIG_FILENAME).open('w') as base_f: json.dump({k: str(v) for k, v in config_data.items() if k i...
def write_config(config_data: Dict[str, Path], path: Path = None)
Save the config file. :param config_data: The index to save :param base_dir: The place to save the file. If ``None``, :py:meth:`infer_config_base_dir()` will be used Only keys that are in the config elements will be saved.
3.601264
3.141099
1.146498
prompt = input( ">>> Warning! Running this tool backup and clear any previous " "calibration data. Proceed (y/[n])? ") if prompt not in ['y', 'Y', 'yes']: print('Exiting--prior configuration data not changed') sys.exit() # Notes: # - 200ul tip is 51.7mm long when at...
def main()
A CLI application for performing factory calibration of an Opentrons robot Instructions: - Robot must be set up with two 300ul or 50ul single-channel pipettes installed on the right-hand and left-hand mount. - Put a GEB 300ul tip onto the pipette. - Use the arrow keys to jog the r...
9.198596
7.937253
1.158914
if self._steps_index < len(self._steps) - 1: self._steps_index = self._steps_index + 1 return 'step: {}'.format(self.current_step())
def increase_step(self) -> str
Increase the jog resolution without overrunning the list of values
3.582803
3.119169
1.14864
if self._steps_index > 0: self._steps_index = self._steps_index - 1 return 'step: {}'.format(self.current_step())
def decrease_step(self) -> str
Decrease the jog resolution without overrunning the list of values
4.363355
3.694084
1.181174
jog(axis, direction, step, self.hardware, self._current_mount) self.current_position = self._position() return 'Jog: {}'.format([axis, str(direction), str(step)])
def _jog(self, axis, direction, step)
Move the pipette on `axis` in `direction` by `step` and update the position tracker
7.537193
7.720767
0.976223
self.hardware.home() self.current_position = self._position() return 'Homed'
def home(self) -> str
Return the robot to the home position and update the position tracker
12.234701
7.231584
1.691843
if self._current_mount is left: msg = self.save_mount_offset() self._current_mount = right elif self._current_mount is types.Mount.LEFT: msg = self.save_mount_offset() self._current_mount = types.Mount.RIGHT else: pos = self._p...
def save_point(self) -> str
Indexes the measured data with the current point as a key and saves the current position once the 'Enter' key is pressed to the 'actual points' vector.
4.482875
4.114515
1.089527
expected = [self._expected_points[p][:2] for p in [1, 2, 3]] log.debug("save_transform expected: {}".format(expected)) actual = [self.actual_points[p][:2] for p in [1, 2, 3]] log.debug("save_transform actual: {}".format(actual)) # Generate a 2 dimensional transform matri...
def save_transform(self) -> str
Actual is measured data Expected is based on mechanical drawings of the robot This method computes the transformation matrix from actual -> expected. Saves this transform to disc.
4.061242
3.826042
1.061473
_, _, cz = self._driver_to_deck_coords(self._position()) if self._current_mount != pipette_mount and cz < SAFE_HEIGHT: self.move_to_safe_height() self._current_mount = pipette_mount self._current_point = point_num _, _, cz = self._driver_to_deck_coords(self...
def validate( self, point: Tuple[float, float, float], point_num: int, pipette_mount) -> str
:param point: Expected values from mechanical drawings :param point_num: The current position attempting to be validated :param pipette: 'Z' for left mount or 'A' for right mount :return:
3.661744
3.611524
1.013906
matches = [conf for conf in config_models if conf.startswith(prefix)] if not matches: raise KeyError('No match found for prefix {}'.format(prefix)) if prefix in matches: return prefix else: return sorted(matches)[0]
def find_config(prefix: str) -> str
Find the most recent config matching `prefix`
4.905045
3.891013
1.260609
to_return: Dict[types.Mount, Dict[str, Optional[str]]] = {} for mount in types.Mount: expected_instr = expected.get(mount, None) init_instr = self._attached_instruments.get(mount, {}) found_model = init_instr.get('model', '') if expected_instr and...
def get_attached_instruments( self, expected: Dict[types.Mount, str])\ -> Dict[types.Mount, Dict[str, Optional[str]]]
Update the internal cache of attached instruments. This method allows after-init-time specification of attached simulated instruments. The method will return - the instruments specified at init-time, or if those do not exists, - the instruments specified in expected, or if that is not p...
2.713056
2.863484
0.947467
return {ax: (0, pos+0.5) for ax, pos in _HOME_POSITION.items() if ax not in 'BC'}
def axis_bounds(self) -> Dict[str, Tuple[float, float]]
The (minimum, maximum) bounds for each axis.
15.91506
15.145202
1.050832
''' Queries Temp-Deck for it's build version, model, and serial number returns: dict Where keys are the strings 'version', 'model', and 'serial', and each value is a string identifier { 'serial': '1aa11bb22', 'model': '1aa11bb...
def get_device_info(self) -> Mapping[str, str]
Queries Temp-Deck for it's build version, model, and serial number returns: dict Where keys are the strings 'version', 'model', and 'serial', and each value is a string identifier { 'serial': '1aa11bb22', 'model': '1aa11bb22', ...
6.535275
1.938134
3.371941
# Find the lpc21isp executable, explicitly allowing the case where it # is not executable (since that’s exactly what we’re trying to fix) updater_executable = shutil.which('lpc21isp', mode=os.F_OK) # updater_executable might be None; we’re passing it here unche...
def _ensure_programmer_executable()
Find the lpc21isp executable and ensure it is executable
11.100028
7.683066
1.444739
data = {'version': version} with open(filepath, 'w') as data_file: json.dump(data, data_file)
def _set_ignored_version(version)
Private helper function that writes the most updated API version that was ignored by a user in the app :param version: Most recent ignored API update
3.571383
4.436504
0.804999
if os.path.exists(filepath): with open(filepath) as data_file: data = json.load(data_file) version = data.get('version') else: version = None return version
def _get_ignored_version()
:return: Most recently ignored API version
2.640959
2.448666
1.07853
data = await request.json() if 'version' in data.keys(): ignored_version = data.get('version') log.debug('Set Ignore Version to {}'.format(ignored_version)) if ignored_version == '': status = 400 res = {'version': None} else: _set_ignored_...
async def set_ignore_version(request)
This handler expects a POST request of form application/json. The request body should be formatted as: {"version": version_ignored} The POST will 400 in the following scenarios: 1. Sending an empty dict 2. Sending a dict with an empty string
2.290849
2.408531
0.951139
log.debug('Update request received') data = await request.post() try: res0 = await install_py( data['whl'], request.loop) reslist = [res0] if 'serverlib' in data.keys(): res1 = await install_py( data['serverlib'], request.loop) ...
async def update_api(request: web.Request) -> web.Response
This handler accepts a POST request with Content-Type: multipart/form-data and file fields in the body named "whl", "serverlib", and "fw". The "whl" and "serverlib" files should be valid Python wheels to be installed ("whl" is expected generally to be the API server wheel, and "serverlib" is expected to...
3.517368
2.6546
1.325009
log.debug('Update Firmware request received') data = await request.post() try: res = await install_smoothie_firmware(data['hex'], request.loop) status = 200 except Exception as e: log.exception("Exception during firmware update:") res = {'message': 'Exception {} rais...
async def update_firmware(request)
This handler accepts a POST request with Content-Type: multipart/form-data and a file field in the body named "hex". The file should be a valid HEX image to be flashed to the LPC1769. The received file is flashed using lpc21isp, and then deleted and a success code is returned.
4.632166
4.233665
1.094127
def wait_and_restart(): log.info('Restarting server') sleep(1) os.system('kill 1') Thread(target=wait_and_restart).start() return web.json_response({"message": "restarting"})
async def restart(request)
Returns OK, then waits approximately 1 second and restarts container
5.194666
4.653667
1.116252
if not system_version_file: system_version_file = BR_BUILTIN_VERSION_FILE version = get_version(system_version_file) name = name_override or name_management.get_name() config_obj = config.load(config_file_override) LOG.info("Setup: " + '\n\t'.join([ f'Device name: {name}', ...
def get_app(system_version_file: str = None, config_file_override: str = None, name_override: str = None, loop: asyncio.AbstractEventLoop = None) -> web.Application
Build and return the aiohttp.web.Application that runs the server The params can be overloaded for testing.
2.809344
2.784232
1.009019
for ws in self.clients.copy(): await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown') self.shutdown()
async def on_shutdown(self, app)
Graceful shutdown handler See https://docs.aiohttp.org/en/stable/web.html#graceful-shutdown
4.56023
4.86343
0.937657
def task_done(future): self.tasks.remove(future) exception = future.exception() if exception: log.warning( 'While processing message: {0}\nDetails: {1}'.format( exception, traceback....
async def handler(self, request)
Receives HTTP request and negotiates up to a Websocket session
3.285353
3.285802
0.999863
def resolve(a): if isinstance(a, dict): _id = a.get('i', None) # If it's a compound type (including dict) # Check if it has id (i) to determine that it has # a reference in object storage. If it's None, then it's ...
def resolve_args(self, args)
Resolve function call arguments that have object ids into instances of these objects
6.71398
6.376589
1.052911
default_aspirate = default_values.get( 'aspirate-flow-rate', {}).get(pipette_name) default_dispense = default_values.get( 'dispense-flow-rate', {}).get(pipette_name) flow_rate_param = params.get('flow-rate') if flow_rate_param is not None: if command_type == 'aspirate': ...
def _set_flow_rate( pipette_name, pipette, command_type, params, default_values)
Set flow rate in uL/mm, to value obtained from command's params, or if unspecified in command params, then from protocol's "default-values".
1.750822
1.730523
1.01173
if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif (sys.platform.startswith('linux') or sys.platform.startswith('cygwin')): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty*') elif sys.platform.startswith...
def get_serial_ports_list()
Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system
2.13603
2.242854
0.952372
if None is Controller: raise RuntimeError( 'The hardware controller may only be instantiated on a robot') checked_loop = loop or asyncio.get_event_loop() backend = Controller(config, checked_loop, force=force) await backend.connect(port) retur...
async def build_hardware_controller( cls, config: robot_configs.robot_config = None, port: str = None, loop: asyncio.AbstractEventLoop = None, force: bool = False) -> 'API'
Build a hardware controller that will actually talk to hardware. This method should not be used outside of a real robot, and on a real robot only one true hardware controller may be active at one time. :param config: A config to preload. If not specified, load the default. :par...
5.813252
6.563203
0.885734
if None is attached_instruments: attached_instruments = {} if None is attached_modules: attached_modules = [] return cls(Simulator(attached_instruments, attached_modules, config, loop, ...
def build_hardware_simulator( cls, attached_instruments: Dict[top_types.Mount, Dict[str, Optional[str]]] = None, # noqa E501 attached_modules: List[str] = None, config: robot_configs.robot_config = None, loop: asyncio.AbstractEventLoop = None, str...
Build a simulating hardware controller. This method may be used both on a real robot and on dev machines. Multiple simulating hardware controllers may be active at one time.
2.818596
3.145412
0.896098
self._callbacks.add(cb) def unregister(): self._callbacks.remove(cb) return unregister
async def register_callback(self, cb)
Allows the caller to register a callback, and returns a closure that can be used to unregister the provided callback
4.201512
3.846567
1.092276
self._backend.set_lights(button, rails)
def set_lights(self, button: bool = None, rails: bool = None)
Control the robot lights. :param button: If specified, turn the button light on (`True`) or off (`False`). If not specified, do not change the button light. :param rails: If specified, turn the rail lights on (`True`) or off (`False`)....
12.128123
9.232082
1.313693
count = duration_s * 4 on = False for sec in range(count): then = self._loop.time() self.set_lights(button=on) on = not on now = self._loop.time() await asyncio.sleep(max(0, 0.25-(now-then))) self.set_lights(button=True...
async def identify(self, duration_s: int = 5)
Blink the button light to identify the robot. :param int duration_s: The duration to blink for, in seconds.
4.65982
4.612604
1.010236
checked_require = require or {} self._log.info("Updating instrument model cache") found = self._backend.get_attached_instruments(checked_require) for mount, instrument_data in found.items(): model = instrument_data.get('model') if model is not None: ...
async def cache_instruments(self, require: Dict[top_types.Mount, str] = None)
- Get the attached instrument on each mount and - Cache their pipette configs from pipette-config.json If specified, the require element should be a dict of mounts to instrument models describing the instruments expected to be present. This can save a subsequent of :py:attr:`attached_i...
4.458453
3.965438
1.124328
if None is loop: checked_loop = self._loop else: checked_loop = loop return await self._backend.update_firmware(firmware_file, checked_loop, explicit_modeset)
async def update_firmware( self, firmware_file: str, loop: asyncio.AbstractEventLoop = None, explicit_modeset: bool = True) -> str
Update the firmware on the Smoothie board. :param firmware_file: The path to the firmware file. :param explicit_modeset: `True` to force the smoothie into programming mode; `False` to assume it is already in programming mode. :pa...
4.903122
6.786069
0.722528
if not mount: axes = [Axis.Z, Axis.A] else: axes = [Axis.by_mount(mount)] await self.home(axes)
async def home_z(self, mount: top_types.Mount = None)
Home the two z-axes
6.676823
4.274839
1.561889
instr = self._attached_instruments[mount] if instr: await self.home([Axis.of_plunger(mount)]) await self._move_plunger(mount, instr.config.bottom)
async def home_plunger(self, mount: top_types.Mount)
Home the plunger motor for a mount, and then return it to the 'bottom' position. :param mount: the mount associated with the target plunger :type mount: :py:class:`.top_types.Mount`
16.053677
12.881271
1.24628
# Initialize/update current_position checked_axes = axes or [ax for ax in Axis] gantry = [ax for ax in checked_axes if ax in Axis.gantry_axes()] smoothie_gantry = [ax.name.upper() for ax in gantry] smoothie_pos = {} plungers = [ax for ax in checked_axes ...
async def home(self, axes: List[Axis] = None)
Home the entire robot and initialize current position. :param axes: A list of axes to home. Default is `None`, which will home everything.
3.527194
3.482945
1.012704
with_enum = {Axis[k]: v for k, v in smoothie_pos.items()} plunger_axes = {k: v for k, v in with_enum.items() if k not in Axis.gantry_axes()} right = (with_enum[Axis.X], with_enum[Axis.Y], with_enum[Axis.by_mount(top_types.Mount.RIGHT)]) #...
def _deck_from_smoothie( self, smoothie_pos: Dict[str, float]) -> Dict[Axis, float]
Build a deck-abs position store from the smoothie's position This should take the smoothie style position {'X': float, etc} and turn it into the position dict used here {Axis.X: float} in deck-absolute coordinates. It runs the reverse deck transformation for the axes that require it. ...
3.373739
3.263609
1.033745
if not self._current_position: raise MustHomeError async with self._motion_lock: if mount == mount.RIGHT: offset = top_types.Point(0, 0, 0) else: offset = top_types.Point(*self.config.mount_offset) z_ax = Axis.by_mo...
async def current_position( self, mount: top_types.Mount, critical_point: CriticalPoint = None) -> Dict[Axis, float]
Return the postion (in deck coords) of the critical point of the specified mount. This returns cached position to avoid hitting the smoothie driver unless ``refresh`` is ``True``. If `critical_point` is specified, that critical point will be applied instead of the default one. ...
2.784511
2.769034
1.005589
cur_pos = await self.current_position(mount, critical_point) return top_types.Point(x=cur_pos[Axis.X], y=cur_pos[Axis.Y], z=cur_pos[Axis.by_mount(mount)])
async def gantry_position( self, mount: top_types.Mount, critical_point: CriticalPoint = None) -> top_types.Point
Return the position of the critical point as pertains to the gantry This ignores the plunger position and gives the Z-axis a predictable name (as :py:attr:`.Point.z`). `critical_point` specifies an override to the current critical point to use (see :py:meth:`current_position`).
3.460148
3.495144
0.989987
if not self._current_position: raise MustHomeError await self._cache_and_maybe_retract_mount(mount) z_axis = Axis.by_mount(mount) if mount == top_types.Mount.LEFT: offset = top_types.Point(*self.config.mount_offset) else: offset = top...
async def move_to( self, mount: top_types.Mount, abs_position: top_types.Point, speed: float = None, critical_point: CriticalPoint = None)
Move the critical point of the specified mount to a location relative to the deck, at the specified speed. 'speed' sets the speed of all robot axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed The critical point of the mount depends on the ...
3.577097
3.367601
1.062209
if not self._current_position: raise MustHomeError await self._cache_and_maybe_retract_mount(mount) z_axis = Axis.by_mount(mount) try: target_position = OrderedDict( ((Axis.X, self._current_position[Axis.X] + delta.x), ...
async def move_rel(self, mount: top_types.Mount, delta: top_types.Point, speed: float = None)
Move the critical point of the specified mount by a specified displacement in a specified direction, at the specified speed. 'speed' sets the speed of all axes to the given value. So, if multiple axes are to be moved, they will do so at the same speed
3.816597
3.782544
1.009003
if mount != self._last_moved_mount and self._last_moved_mount: await self.retract(self._last_moved_mount, 10) self._last_moved_mount = mount
async def _cache_and_maybe_retract_mount(self, mount: top_types.Mount)
Retract the 'other' mount if necessary If `mount` does not match the value in :py:attr:`_last_moved_mount` (and :py:attr:`_last_moved_mount` exists) then retract the mount in :py:attr:`_last_moved_mount`. Also unconditionally update :py:attr:`_last_moved_mount` to contain `mount`.
4.025257
2.828952
1.422879
# Transform only the x, y, and (z or a) axes specified since this could # get the b or c axes as well to_transform = tuple((tp for ax, tp in target_position.items() if ax in Axis.gantry_axes())) # Pre-fill the dict we’...
async def _move(self, target_position: 'OrderedDict[Axis, float]', speed: float = None, home_flagged_axes: bool = True)
Worker function to apply robot motion. Robot motion means the kind of motions that are relevant to the robot, i.e. only one pipette plunger and mount move at the same time, and an XYZ move in the coordinate frame of one of the pipettes. ``target_position`` should be an ordered dict (or...
4.932198
4.870122
1.012746
return {Axis[ax]: eng for ax, eng in self._backend.engaged_axes().items()}
def engaged_axes(self) -> Dict[Axis, bool]
Which axes are engaged and holding.
7.600775
6.508369
1.167846
smoothie_ax = Axis.by_mount(mount).name.upper() async with self._motion_lock: smoothie_pos = self._backend.fast_home(smoothie_ax, margin) self._current_position = self._deck_from_smoothie(smoothie_pos)
async def retract(self, mount: top_types.Mount, margin: float)
Pull the specified mount up to its home position. Works regardless of critical point or home status.
9.298985
8.602441
1.080971
pip = self._attached_instruments[mount] if pip is not None and cp_override != CriticalPoint.MOUNT: return pip.critical_point(cp_override) else: # TODO: The smoothie’s z/a home position is calculated to provide # the offset for a P300 single. Here we s...
def _critical_point_for( self, mount: top_types.Mount, cp_override: CriticalPoint = None) -> top_types.Point
Return the current critical point of the specified mount. The mount's critical point is the position of the mount itself, if no pipette is attached, or the pipette's critical point (which depends on tip status). If `cp_override` is specified, and that critical point actually exists, ...
11.79986
10.102924
1.167965
this_pipette = self._attached_instruments[mount] if not this_pipette: raise top_types.PipetteNotAttachedError( "No pipette attached to {} mount".format(mount.name)) if volume is None: asp_vol = this_pipette.available_volume mod_log.deb...
async def aspirate(self, mount: top_types.Mount, volume: float = None, rate: float = 1.0)
Aspirate a volume of liquid (in microliters/uL) using this pipette from the *current location*. If no volume is passed, `aspirate` will default to max available volume (after taking into account the volume already present in the tip). mount : Mount.LEFT or Mount.RIGHT volume : [...
3.6269
3.558727
1.019156
this_pipette = self._attached_instruments[mount] if not this_pipette: raise top_types.PipetteNotAttachedError( "No pipette attached to {} mount".format(mount.name)) if volume is None: disp_vol = this_pipette.current_volume mod_log.debu...
async def dispense(self, mount: top_types.Mount, volume: float = None, rate: float = 1.0)
Dispense a volume of liquid in microliters(uL) using this pipette at the current location. If no volume is specified, `dispense` will dispense all volume currently present in pipette mount : Mount.LEFT or Mount.RIGHT volume : [float] The number of microliters to dispense rate : ...
3.425404
3.33863
1.025991
this_pipette = self._attached_instruments[mount] if not this_pipette: raise top_types.PipetteNotAttachedError( "No pipette attached to {} mount".format(mount.name)) self._backend.set_active_current(Axis.of_plunger(mount), ...
async def blow_out(self, mount)
Force any remaining liquid to dispense. The liquid will be dispensed at the current location of pipette
4.49752
4.235111
1.06196
instr = self._attached_instruments[mount] assert instr assert not instr.has_tip, 'Tip already attached' instr_ax = Axis.by_mount(mount) plunger_ax = Axis.of_plunger(mount) self._log.info('Picking up tip on {}'.format(instr.name)) # Initialize plunger to b...
async def pick_up_tip(self, mount, tip_length: float, presses: int = None, increment: float = None)
Pick up tip from current location. If ``presses`` or ``increment`` is not specified (or is ``None``), their value is taken from the pipette configuration
4.535977
4.374826
1.036836
instr = self._attached_instruments[mount] assert instr assert instr.has_tip, 'Cannot drop tip without a tip attached' self._log.info("Dropping tip off from {}".format(instr.name)) plunger_ax = Axis.of_plunger(mount) droptip = instr.config.drop_tip bottom ...
async def drop_tip(self, mount, home_after=True)
Drop tip at the current location :param Mount mount: The mount to drop a tip from :param bool home_after: Home the plunger motor after dropping tip. This is used in case the plunger motor skipped while dropping the tip, and is also used to...
4.120891
3.980278
1.035327
instr = self._attached_instruments[mount] if not instr: raise top_types.PipetteNotAttachedError( "No pipette attached to {} mount".format(mount.name)) pos_dict: Dict = { 'top': instr.config.top, 'bottom': instr.config.bottom, ...
def calibrate_plunger(self, mount: top_types.Mount, top: float = None, bottom: float = None, blow_out: float = None, drop_tip: float = None)
Set calibration values for the pipette plunger. This can be called multiple times as the user sets each value, or you can set them all at once. :param top: Touching but not engaging the plunger. :param bottom: Must be above the pipette's physical hard-stop, while still leaving en...
2.24087
2.221592
1.008677
details = (module.port, module.name()) mod = self._attached_modules.pop(details[0] + details[1]) try: new_mod = await self._backend.update_module( mod, firmware_file, loop) except modules.UpdateError as e: return False, e.msg else:...
async def update_module( self, module: modules.AbstractModule, firmware_file: str, loop: asyncio.AbstractEventLoop = None) -> Tuple[bool, str]
Update a module's firmware. Returns (ok, message) where ok is True if the update succeeded and message is a human readable message.
3.992806
4.169971
0.957514
# Clear the old offset during calibration pip.update_instrument_offset(top_types.Point()) # Hotspots based on our expectation of tip length and config hotspots = robot_configs.calculate_tip_probe_hotspots( pip.current_tip_length, self._config.tip_probe) new_p...
async def _do_tp(self, pip, mount) -> top_types.Point
Execute the work of tip probe. This is a separate function so that it can be encapsulated in a context manager that ensures the state of the pipette tip tracking is reset properly. It should not be called outside of :py:meth:`locate_tip_probe_center`. :param pip: The pipette to...
4.670041
4.48907
1.040314
opt_pip = self._attached_instruments[mount] assert opt_pip, '{} has no pipette'.format(mount.name.lower()) pip = opt_pip if pip.has_tip and tip_length: pip.remove_tip() if not tip_length: assert pip.has_tip,\ 'If pipette has no t...
async def locate_tip_probe_center( self, mount, tip_length=None) -> top_types.Point
Use the specified mount (which should have a tip) to find the position of the tip probe target center relative to its definition :param mount: The mount to use for the probe :param tip_length: If specified (it should usually be specified), the length of the tip assume...
4.141258
3.998748
1.035639
if from_tip_probe: new_offset = (top_types.Point(*self._config.tip_probe.center) - from_tip_probe) elif not new_offset: raise ValueError( "Either from_tip_probe or new_offset must be specified") opt_pip = self._attached_i...
def update_instrument_offset(self, mount, new_offset: top_types.Point = None, from_tip_probe: top_types.Point = None)
Update the instrument offset for a pipette on the specified mount. This will update both the stored value in the robot settings and the live value in the currently-loaded pipette. This can be specified either directly by using the new_offset arg or using the result of a previous call t...
4.008424
3.616455
1.108385
# Required for old bootloader ports_before_dfu_mode = await _discover_ports() module._driver.enter_programming_mode() module.disconnect() new_port = '' try: new_port = await asyncio.wait_for( _port_poll(_has_old_bootloader(module), ports_before_dfu_mode), PO...
async def enter_bootloader(module)
Using the driver method, enter bootloader mode of the atmega32u4. The bootloader mode opens a new port on the uC to upload the hex file. After receiving a 'dfu' command, the firmware provides a 3-second window to close the current port so as to do a clean switch to the bootloader port. The new port show...
7.320935
6.066468
1.206787
# TODO: Make sure the module isn't in the middle of operation ports_before_update = await _discover_ports() config_file_path = os.path.join(package_root, 'config', 'modules', 'avrdude.conf') proc = await asyncio.create_subprocess_exec( 'avrdude', '-C{}'....
async def update_firmware(module, firmware_file_path, loop)
Run avrdude firmware upload command. Switch back to normal module port Note: For modules with old bootloader, the kernel could assign the module a new port after the update (since the board is automatically reset). Scan for such a port change and use the appropriate port
4.188907
3.868322
1.082874
# pick the first item from the seq for which the target is less than # the bracketing element i = list(filter(lambda x: ul <= x[0], sequence))[0] # use that element to calculate the movement distance in mm return i[1]*ul + i[2]
def piecewise_volume_conversion( ul: float, sequence: List[List[float]]) -> float
Takes a volume in microliters and a sequence representing a piecewise function for the slope and y-intercept of a ul/mm function, where each sub-list in the sequence contains: - the max volume for the piece of the function (minimum implied from the max of the previous item or 0 - the slope ...
10.13769
10.436759
0.971345
if not isinstance(name, tuple): path: Tuple[str, ...] = (name,) else: path = name for element in path[:-1]: config = config[element] value = config[path[-1]] if path[-1] in mutable_config_list: value = value['value'] return value
def ensure_value( config: dict, name: Union[str, Tuple[str, ...]], mutable_config_list: List[str])
Pull value of config data from file. Shape can either be a dictionary with a value key -- indicating that it can be changed -- or another data structure such as an array.
2.977152
2.672647
1.113934
return [fi.stem for fi in CONFIG['pipette_config_overrides_dir'].iterdir() if fi.is_file() and '.json' in fi.suffixes]
def known_pipettes() -> Sequence[str]
List pipette IDs for which we have known overrides
7.852673
6.252919
1.255841
override = load_overrides(pipette_id) model = override['model'] config = copy.deepcopy(model_config()['config'][model]) config.update(copy.deepcopy(name_config()[config['name']])) for top_level_key in config.keys(): add_default(config[top_level_key]) config.update(override) r...
def load_config_dict(pipette_id: str) -> Dict
Give updated config with overrides for a pipette. This will add the default value for a mutable config before returning the modified config value.
5.811663
5.298043
1.096945
cfg: Dict[str, Any] = {} if pipette_id in known_pipettes(): config = load_config_dict(pipette_id) else: log.info('Pipette id {} not found'.format(pipette_id)) return cfg for key in config: if key in mutable_configs: cfg[key] = config[key] return cfg
def list_mutable_configs(pipette_id: str) -> Dict[str, Any]
Returns dict of mutable configs only.
3.089545
2.897168
1.066402
''' Returns the key in the expected string "N:12.3", where "N" is the key, and "12.3" is a floating point value ''' try: return substring.split(':')[0] except (ValueError, IndexError, TypeError, AttributeError): log.exception('Unexpected argument to _parse_key_from_substring:') ...
def _parse_key_from_substring(substring) -> str
Returns the key in the expected string "N:12.3", where "N" is the key, and "12.3" is a floating point value
4.728377
2.585902
1.828521
''' Parse the mag-deck's device information response. Example response from temp-deck: "serial:aa11 model:bb22 version:cc33" ''' error_msg = 'Unexpected argument to _parse_device_information: {}'.format( device_info_string) if not device_info_string or \ not isinstance(device...
def _parse_device_information(device_info_string) -> dict
Parse the mag-deck's device information response. Example response from temp-deck: "serial:aa11 model:bb22 version:cc33"
3.662489
2.20744
1.659157
''' Parse responses of 'GET_PLATE_HEIGHT' & 'GET_CURRENT_POSITION' Example response of- GET_PLATE_HEIGHT: "height:12.34" GET_CURRENT_POSITION: "Z:12.34" ''' err_msg = 'Unexpected argument to _parse_distance_response: {}'.format( distance_string) if not distance_string or \ ...
def _parse_distance_response(distance_string) -> float
Parse responses of 'GET_PLATE_HEIGHT' & 'GET_CURRENT_POSITION' Example response of- GET_PLATE_HEIGHT: "height:12.34" GET_CURRENT_POSITION: "Z:12.34"
4.485936
2.38059
1.88438
''' :param port: '/dev/modules/ttyn_magdeck' NOTE: Using the symlink above to connect makes sure that the robot connects/reconnects to the module even after a device reset/reconnection ''' if environ.get('ENABLE_VIRTUAL_SMOOTHIE', '').lower() == 'true': ...
def connect(self, port=None) -> str
:param port: '/dev/modules/ttyn_magdeck' NOTE: Using the symlink above to connect makes sure that the robot connects/reconnects to the module even after a device reset/reconnection
12.197628
3.50163
3.483414
''' Probes for the deck plate and calculates the plate distance from home. To be used for calibrating MagDeck ''' self.run_flag.wait() try: self._send_command(GCODES['PROBE_PLATE']) except (MagDeckError, SerialException, SerialNoResponse) as e...
def probe_plate(self) -> str
Probes for the deck plate and calculates the plate distance from home. To be used for calibrating MagDeck
12.556272
5.424827
2.314594
''' Move the magnets along Z axis where the home position is 0.0; position_mm-> a point along Z. Does not self-check if the position is outside of the deck's linear range ''' self.run_flag.wait() try: position_mm = round(float(position_mm), GCODE_ROUN...
def move(self, position_mm) -> str
Move the magnets along Z axis where the home position is 0.0; position_mm-> a point along Z. Does not self-check if the position is outside of the deck's linear range
9.819561
3.616187
2.715446
''' Queries Temp-Deck for it's build version, model, and serial number returns: dict Where keys are the strings 'version', 'model', and 'serial', and each value is a string identifier { 'serial': '1aa11bb22', 'model': '1aa11bb...
def get_device_info(self) -> dict
Queries Temp-Deck for it's build version, model, and serial number returns: dict Where keys are the strings 'version', 'model', and 'serial', and each value is a string identifier { 'serial': '1aa11bb22', 'model': '1aa11bb22', ...
7.148058
2.216518
3.224904
calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] if not calibration_path.exists(): calibration_path.mkdir(parents=True, exist_ok=True) labware_offset_path = calibration_path/'{}.json'.format(labware._id) calibration_data = _helper_offset_data_format( str(labware_offse...
def save_calibration(labware: Labware, delta: Point)
Function to be used whenever an updated delta is found for the first well of a given labware. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the delta and the lastModified fields under the "default" key.
3.623929
3.469793
1.044422
calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] if not calibration_path.exists(): calibration_path.mkdir(parents=True, exist_ok=True) labware_offset_path = calibration_path/'{}.json'.format(labware._id) calibration_data = _helper_tip_length_data_format( str(labware_o...
def save_tip_length(labware: Labware, length: float)
Function to be used whenever an updated tip length is found for of a given tip rack. If an offset file does not exist, create the file using labware id as the filename. If the file does exist, load it and modify the length and the lastModified fields under the "tipLength" key.
3.726023
3.517148
1.059388
calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] labware_offset_path = calibration_path/'{}.json'.format(labware._id) if labware_offset_path.exists(): calibration_data = _read_file(str(labware_offset_path)) offset_array = calibration_data['default']['offset'] offs...
def load_calibration(labware: Labware)
Look up a calibration if it exists and apply it to the given labware.
3.298675
3.117759
1.058028
def_path = 'shared_data/definitions2/{}.json'.format(name.lower()) labware_def = json.loads(pkgutil.get_data('opentrons', def_path)) # type: ignore # NOQA return labware_def
def load_definition_by_name(name: str) -> dict
Look up and return a definition by name (name is expected to correspond to the filename of the definition, with the .json extension) and return it or raise an exception :param name: A string to use for looking up a labware defintion previously saved to disc. The definition file must have been saved...
6.196933
5.415378
1.144321
definition = load_definition_by_name(name) return load_from_definition(definition, parent, label)
def load(name: str, parent: Location, label: str = None) -> Labware
Return a labware object constructed from a labware definition dict looked up by name (definition must have been previously stored locally on the robot) :param name: A string to use for looking up a labware definition previously saved to disc. The definition file must have been saved in a known ...
4.80193
9.569114
0.501816
labware = Labware(definition, parent, label) load_calibration(labware) return labware
def load_from_definition( definition: dict, parent: Location, label: str = None) -> Labware
Return a labware object constructed from a provided labware definition dict :param definition: A dict representing all required data for a labware, including metadata such as the display name of the labware, a definition of the order to iterate over wells, the shape of wells (shape, physica...
6.385278
13.519326
0.472307
calibration_path = CONFIG['labware_calibration_offsets_dir_v4'] try: targets = [ f for f in calibration_path.iterdir() if f.suffix == '.json'] for target in targets: target.unlink() except FileNotFoundError: pass
def clear_calibrations()
Delete all calibration files for labware. This includes deleting tip-length data for tipracks.
6.199735
5.392804
1.149631
mod_name = definition['loadName'] if mod_name == 'thermocycler' or mod_name == 'semithermocycler': mod: Union[ModuleGeometry, ThermocyclerGeometry] = \ ThermocyclerGeometry(definition, parent) else: mod = ModuleGeometry(definition, parent) # TODO: calibration ret...
def load_module_from_definition( definition: dict, parent: Location) -> \ Union[ModuleGeometry, ThermocyclerGeometry]
Return a :py:class:`ModuleGeometry` object from a specified definition :param definition: A dict representing all required data for a module's geometry. :param parent: A :py:class:`.Location` representing the location where the front and left most point of the outside ...
3.231549
3.823791
0.845117
def_path = 'shared_data/robot-data/moduleSpecs.json' module_def = json.loads( # type: ignore pkgutil.get_data('opentrons', def_path)) return load_module_from_definition(module_def[name], parent)
def load_module(name: str, parent: Location) -> ModuleGeometry
Return a :py:class:`ModuleGeometry` object from a definition looked up by name. :param name: A string to use for looking up the definition. The string must be present as a top-level key in moduleSpecs.json. :param parent: A :py:class:`.Location` representing the location where ...
6.963947
5.660771
1.230212
def recursive_get_quirks(obj, found): if isinstance(obj, Labware): return found + obj.quirks elif isinstance(obj, Well): return recursive_get_quirks(obj.parent, found) else: return found return recursive_get_quirks(loc, [])
def quirks_from_any_parent( loc: Union[Labware, Well, str, ModuleGeometry, None]) -> List[str]
Walk the tree of wells and labwares and extract quirks
2.881056
2.600688
1.107805
return Location(self._position + Point(0, 0, z), self)
def top(self, z: float = 0.0) -> Location
:param z: the z distance in mm :return: a Point corresponding to the absolute position of the top-center of the well relative to the deck (with the front-left corner of slot 1 as (0,0,0)). If z is specified, returns a point offset by z mm from top-center
10.058092
9.757547
1.030801
top = self.top() bottom_z = top.point.z - self._depth + z return Location(Point(x=top.point.x, y=top.point.y, z=bottom_z), self)
def bottom(self, z: float = 0.0) -> Location
:param z: the z distance in mm :return: a Point corresponding to the absolute position of the bottom-center of the well (with the front-left corner of slot 1 as (0,0,0)). If z is specified, returns a point offset by z mm from bottom-center
3.677339
3.565569
1.031347
top = self.top() center_z = top.point.z - (self._depth / 2.0) return Location(Point(x=top.point.x, y=top.point.y, z=center_z), self)
def center(self) -> Location
:return: a Point corresponding to the absolute position of the center of the well relative to the deck (with the front-left corner of slot 1 as (0,0,0))
4.025782
3.288842
1.224073
center = self.center() if self._shape is WellShape.RECTANGULAR: x_size = self._length y_size = self._width else: x_size = self._diameter y_size = self._diameter z_size = self._depth return Point( x=center.point...
def _from_center_cartesian( self, x: float, y: float, z: float) -> Point
Specifies an arbitrary point relative to the center of the well based on percentages of the radius in each axis. For example, to specify the back-right corner of a well at 1/4 of the well depth from the bottom, the call would be `_from_center_cartesian(1, 1, -0.5)`. No checks are perfor...
2.390589
2.434118
0.982117