text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_engaged_axes(request): """ Query driver for engaged state by axis. Response keys will be axes XYZABC and keys will be True for engaged and False for disengaged. Axes must be manually disengaged, and are automatically re-engaged whenever a "move" or "home" command is called on that axis. Response shape example: """
hw = hw_from_req(request) return web.json_response( {str(k).lower(): {'enabled': v} for k, v in hw.engaged_axes.items()})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def move(request): """ Moves the robot to the specified position as provided by the `control.info` endpoint response Post body must include the following keys: - 'target': either 'mount' or 'pipette' - 'point': a tuple of 3 floats for x, y, z - 'mount': must be 'left' or 'right' If 'target' is 'pipette', body must also contain: - 'model': must be a valid pipette model (as defined in `pipette_config`) """
hw = hw_from_req(request) req = await request.text() data = json.loads(req) target, point, mount, model, message, error = _validate_move_data(data) if error: status = 400 else: status = 200 if ff.use_protocol_api_v2(): await hw.cache_instruments() if target == 'mount': critical_point = CriticalPoint.MOUNT else: critical_point = None mount = Mount[mount.upper()] target = Point(*point) await hw.home_z() pos = await hw.gantry_position(mount, critical_point) await hw.move_to(mount, target._replace(z=pos.z), critical_point=critical_point) await hw.move_to(mount, target, critical_point=critical_point) pos = await hw.gantry_position(mount) message = 'Move complete. New position: {}'.format(pos) else: if target == 'mount': message = _move_mount(hw, mount, point) elif target == 'pipette': message = _move_pipette(hw, mount, model, point) return web.json_response({"message": message}, status=status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _move_mount(robot, mount, point): """ The carriage moves the mount in the Z axis, and the gantry moves in X and Y Mount movements do not have the same protections calculated in to an existing `move` command like Pipette does, so the safest thing is to home the Z axis, then move in X and Y, then move down to the specified Z height """
carriage = robot._actuators[mount]['carriage'] # Home both carriages, to prevent collisions and to ensure that the other # mount doesn't block the one being moved (mount moves are primarily for # changing pipettes, so we don't want the other pipette blocking access) robot.poses = carriage.home(robot.poses) other_mount = 'left' if mount == 'right' else 'right' robot.poses = robot._actuators[other_mount]['carriage'].home(robot.poses) robot.gantry.move( robot.poses, x=point[0], y=point[1]) robot.poses = carriage.move( robot.poses, z=point[2]) # These x and y values are hard to interpret because of some internals of # pose tracker. It's mostly z that matters for this operation anyway x, y, _ = tuple( pose_tracker.absolute( robot.poses, robot._actuators[mount]['carriage'])) _, _, z = tuple( pose_tracker.absolute( robot.poses, robot.gantry)) new_position = (x, y, z) return "Move complete. New position: {}".format(new_position)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _eap_check_config(eap_config: Dict[str, Any]) -> Dict[str, Any]: """ Check the eap specific args, and replace values where needed. Similar to _check_configure_args but for only EAP. """
eap_type = eap_config.get('eapType') for method in EAP_CONFIG_SHAPE['options']: if method['name'] == eap_type: options = method['options'] break else: raise ConfigureArgsError('EAP method {} is not valid'.format(eap_type)) _eap_check_no_extra_args(eap_config, options) for opt in options: # type: ignore # Ignoring most types to do with EAP_CONFIG_SHAPE because of issues # wth type inference for dict comprehensions _eap_check_option_ok(opt, eap_config) if opt['type'] == 'file' and opt['name'] in eap_config: # Special work for file: rewrite from key id to path eap_config[opt['name']] = _get_key_file(eap_config[opt['name']]) return eap_config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES: """ Make sure that the security_type is known, or throw. """
# Security should be one of our valid strings sec_translation = { 'wpa-psk': nmcli.SECURITY_TYPES.WPA_PSK, 'none': nmcli.SECURITY_TYPES.NONE, 'wpa-eap': nmcli.SECURITY_TYPES.WPA_EAP, } if not kwargs.get('securityType'): if kwargs.get('psk') and kwargs.get('eapConfig'): raise ConfigureArgsError( 'Cannot deduce security type: psk and eap both passed') elif kwargs.get('psk'): kwargs['securityType'] = 'wpa-psk' elif kwargs.get('eapConfig'): kwargs['securityType'] = 'wpa-eap' else: kwargs['securityType'] = 'none' try: return sec_translation[kwargs['securityType']] except KeyError: raise ConfigureArgsError('securityType must be one of {}' .format(','.join(sec_translation.keys())))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_configure_args(configure_args: Dict[str, Any]) -> Dict[str, Any]: """ Check the arguments passed to configure. Raises an exception on failure. On success, returns a dict of configure_args with any necessary mutations. """
# SSID must always be present if not configure_args.get('ssid')\ or not isinstance(configure_args['ssid'], str): raise ConfigureArgsError("SSID must be specified") # If specified, hidden must be a bool if not configure_args.get('hidden'): configure_args['hidden'] = False elif not isinstance(configure_args['hidden'], bool): raise ConfigureArgsError('If specified, hidden must be a bool') configure_args['securityType'] = _deduce_security(configure_args) # If we have wpa2-personal, we need a psk if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_PSK: if not configure_args.get('psk'): raise ConfigureArgsError( 'If securityType is wpa-psk, psk must be specified') return configure_args # If we have wpa2-enterprise, we need eap config, and we need to check # it if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_EAP: if not configure_args.get('eapConfig'): raise ConfigureArgsError( 'If securityType is wpa-eap, eapConfig must be specified') configure_args['eapConfig']\ = _eap_check_config(configure_args['eapConfig']) return configure_args # If we’re still here we have no security and we’re done return configure_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def status(request: web.Request) -> web.Response: """ Get request will return the status of the machine's connection to the internet as well as the status of its network interfaces. The body of the response is a json dict containing 'status': internet connectivity status, where the options are: "none" - no connection to router or network "portal" - device behind a captive portal and cannot reach full internet "limited" - connection to router but not internet "full" - connection to router and internet "unknown" - an exception occured while trying to determine status 'interfaces': JSON object of networking interfaces, keyed by device name, where the value of each entry is another object with the keys: - 'type': "ethernet" or "wifi" - 'state': state string, e.g. "disconnected", "connecting", "connected" - 'ipAddress': the ip address, if it exists (null otherwise); this also contains the subnet mask in CIDR notation, e.g. 10.2.12.120/16 - 'macAddress': the MAC address of the interface device - 'gatewayAddress': the address of the current gateway, if it exists (null otherwise) Example request: ``` GET /networking/status ``` Example response: ``` 200 OK { "status": "full", "interfaces": { "wlan0": { "ipAddress": "192.168.43.97/24", "macAddress": "B8:27:EB:6C:95:CF", "gatewayAddress": "192.168.43.161", "state": "connected", "type": "wifi" }, "eth0": { "ipAddress": "169.254.229.173/16", "macAddress": "B8:27:EB:39:C0:9A", "gatewayAddress": null, "state": "connected", "type": "ethernet" } } } ``` """
connectivity = {'status': 'none', 'interfaces': {}} try: connectivity['status'] = await nmcli.is_connected() connectivity['interfaces'] = { i.value: await nmcli.iface_info(i) for i in nmcli.NETWORK_IFACES } log.debug("Connectivity: {}".format(connectivity['status'])) log.debug("Interfaces: {}".format(connectivity['interfaces'])) status = 200 except subprocess.CalledProcessError as e: log.error("CalledProcessError: {}".format(e.stdout)) status = 500 except FileNotFoundError as e: log.error("FileNotFoundError: {}".format(e)) status = 500 return web.json_response(connectivity, status=status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def list_keys(request: web.Request) -> web.Response: """ List the key files installed in the system. This responds with a list of the same objects as key: ``` GET /wifi/keys -> 200 OK { keys: [ { uri: '/wifi/keys/some-hex-digest', id: 'some-hex-digest', name: 'keyfile.pem' }, ] } ``` """
keys_dir = CONFIG['wifi_keys_dir'] keys: List[Dict[str, str]] = [] # TODO(mc, 2018-10-24): add last modified info to keys for sort purposes for path in os.listdir(keys_dir): full_path = os.path.join(keys_dir, path) if os.path.isdir(full_path): in_path = os.listdir(full_path) if len(in_path) > 1: log.warning("Garbage in key dir for key {}".format(path)) keys.append( {'uri': '/wifi/keys/{}'.format(path), 'id': path, 'name': os.path.basename(in_path[0])}) else: log.warning("Garbage in wifi keys dir: {}".format(full_path)) return web.json_response({'keys': keys}, status=200)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def remove_key(request: web.Request) -> web.Response: """ Remove a key. ``` DELETE /wifi/keys/:id -> 200 OK {message: 'Removed key keyfile.pem'} ``` """
keys_dir = CONFIG['wifi_keys_dir'] available_keys = os.listdir(keys_dir) requested_hash = request.match_info['key_uuid'] if requested_hash not in available_keys: return web.json_response( {'message': 'No such key file {}' .format(requested_hash)}, status=404) key_path = os.path.join(keys_dir, requested_hash) name = os.listdir(key_path)[0] shutil.rmtree(key_path) return web.json_response( {'message': 'Key file {} deleted'.format(name)}, status=200)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def eap_options(request: web.Request) -> web.Response: """ Get request returns the available configuration options for WPA-EAP. Because the options for connecting to WPA-EAP secured networks are quite complex, to avoid duplicating logic this endpoint returns a json object describing the structure of arguments and options for the eap_config arg to /wifi/configure. The object is shaped like this: { options: [ // Supported EAP methods and their options. One of these // method names must be passed in the eapConfig dict { name: str // i.e. TTLS-EAPMSCHAPv2. Should be in the eapType // key of eapConfig when sent to /configure. options: [ { name: str // i.e. "username" displayName: str // i.e. "Username" required: bool, type: str } ] } ] } The ``type`` keys denote the semantic kind of the argument. Valid types are: password: This is some kind of password. It may be a psk for the network, an Active Directory password, or the passphrase for a private key string: A generic string; perhaps a username, or a subject-matches domain name for server validation file: A file that the user must provide. This should be the id of a file previously uploaded via POST /wifi/keys. Although the arguments are described hierarchically, they should be specified in eap_config as a flat dict. For instance, a /configure invocation for TTLS/EAP-TLS might look like ``` POST { ssid: "my-ssid", securityType: "wpa-eap", hidden: false, eapConfig : { eapType: "TTLS/EAP-TLS", // One of the method options identity: "alice@example.com", // And then its arguments anonymousIdentity: "anonymous@example.com", password: "testing123", caCert: "12d1f180f081b", phase2CaCert: "12d1f180f081b", phase2ClientCert: "009909fd9fa", phase2PrivateKey: "081009fbcbc" phase2PrivateKeyPassword: "testing321" } } ``` """
return web.json_response(EAP_CONFIG_SHAPE, status=200)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_publish(broker, cmd, f, when, res, meta, *args, **kwargs): """ Implement the publish so it can be called outside the decorator """
publish_command = functools.partial( broker.publish, topic=command_types.COMMAND) call_args = _get_args(f, args, kwargs) if when == 'before': broker.logger.info("{}: {}".format( f.__qualname__, {k: v for k, v in call_args.items() if str(k) != 'self'})) command_args = dict( zip( reversed(inspect.getfullargspec(cmd).args), reversed(inspect.getfullargspec(cmd).defaults or []))) # TODO (artyom, 20170927): we are doing this to be able to use # the decorator in Instrument class methods, in which case # self is effectively an instrument. # To narrow the scope of this hack, we are checking if the # command is expecting instrument first. if 'instrument' in inspect.getfullargspec(cmd).args: # We are also checking if call arguments have 'self' and # don't have instruments specified, in which case # instruments should take precedence. if 'self' in call_args and 'instrument' not in call_args: call_args['instrument'] = call_args['self'] command_args.update({ key: call_args[key] for key in (set(inspect.getfullargspec(cmd).args) & call_args.keys()) }) if meta: command_args['meta'] = meta payload = cmd(**command_args) message = {**payload, '$': when} if when == 'after': message['return'] = res publish_command( message={**payload, '$': when})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def position(axis, hardware, cp=None): """ Read position from driver into a tuple and map 3-rd value to the axis of a pipette currently used """
if not ff.use_protocol_api_v2(): p = hardware._driver.position return (p['X'], p['Y'], p[axis]) else: p = hardware.gantry_position(axis, critical_point=cp) return (p.x, p.y, p.z)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def setup_hostname() -> str: """ Intended to be run when the server starts. Sets the machine hostname. The machine hostname is set from the systemd-generated machine-id, which changes at every boot. Once the hostname is set, we restart avahi. This is a separate task from establishing and changing the opentrons machine name, which is UTF-8 and stored in /etc/machine-info as the PRETTY_HOSTNAME and used in the avahi service name. :returns: the hostname """
machine_id = open('/etc/machine-id').read().strip() hostname = machine_id[:6] with open('/etc/hostname', 'w') as ehn: ehn.write(f'{hostname}\n') # First, we run hostnamed which will set the transient hostname # and loaded static hostname from the value we just wrote to # /etc/hostname LOG.debug("Setting hostname") proc = await asyncio.create_subprocess_exec( 'hostname', '-F', '/etc/hostname', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await proc.communicate() ret = proc.returncode if ret != 0: LOG.error( f'Error starting hostname: {ret} ' f'stdout: {stdout} stderr: {stderr}') raise RuntimeError("Couldn't run hostname") # Then, with the hostname set, we can restart avahi LOG.debug("Restarting avahi") proc = await asyncio.create_subprocess_exec( 'systemctl', 'restart', 'avahi-daemon', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await proc.communicate() ret = proc.returncode if ret != 0: LOG.error( f'Error restarting avahi-daemon: {ret} ' f'stdout: {stdout} stderr: {stderr}') raise RuntimeError("Error restarting avahi") LOG.debug("Updated hostname and restarted avahi OK") return hostname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_pretty_hostname(new_val: str): """ Write a new value for the pretty hostname. :raises OSError: If the new value could not be written. """
try: with open('/etc/machine-info') as emi: contents = emi.read() except OSError: LOG.exception("Couldn't read /etc/machine-info") contents = '' new_contents = '' for line in contents.split('\n'): if not line.startswith('PRETTY_HOSTNAME'): new_contents += f'{line}\n' new_contents += f'PRETTY_HOSTNAME={new_val}\n' with open('/etc/machine-info', 'w') as emi: emi.write(new_contents)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_name(default: str = 'no name set'): """ Get the currently-configured name of the machine """
try: with open('/etc/machine-info') as emi: contents = emi.read() except OSError: LOG.exception( "Couldn't read /etc/machine-info") contents = '' for line in contents.split('\n'): if line.startswith('PRETTY_HOSTNAME='): return '='.join(line.split('=')[1:]) LOG.warning(f"No PRETTY_HOSTNAME in {contents}, defaulting to {default}") try: _update_pretty_hostname(default) except OSError: LOG.exception("Could not write new pretty hostname!") return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def set_name_endpoint(request: web.Request) -> web.Response: """ Set the name of the robot. Request with POST /server/name {"name": new_name} Responds with 200 OK {"hostname": new_name, "prettyname": pretty_name} or 400 Bad Request In general, the new pretty name will be the specified name. The true hostname will be capped to 53 letters, and have any characters other than ascii letters or dashes replaced with dashes to fit the requirements here https://www.freedesktop.org/software/systemd/man/hostname.html#. """
def build_400(msg: str) -> web.Response: return web.json_response( data={'message': msg}, status=400) body = await request.json() if 'name' not in body or not isinstance(body['name'], str): return build_400('Body has no "name" key with a string') new_name = await set_name(body['name']) request.app[DEVICE_NAME_VARNAME] = new_name return web.json_response(data={'name': new_name}, status=200)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_name_endpoint(request: web.Request) -> web.Response: """ Get the name of the robot. This information is also accessible in /server/update/health, but this endpoint provides symmetry with POST /server/name. GET /server/name -> 200 OK, {'name': robot name} """
return web.json_response( data={'name': request.app[DEVICE_NAME_VARNAME]}, status=200)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, point: Point) -> 'Location': """ Alter the point stored in the location while preserving the labware. This returns a new Location and does not alter the current one. It should be used like .. code-block:: python """
return self._replace(point=self.point + point)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_weird_container(container_name): """ Load a container from persisted containers, whatever that is """
# First must populate "get persisted container" list old_container_loading.load_all_containers_from_disk() # Load container from old json file container = old_container_loading.get_persisted_container( container_name) # Rotate coordinates to fit the new deck map rotated_container = database_migration.rotate_container_for_alpha( container) # Save to the new database database.save_new_container(rotated_container, container_name) return container
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_container(container_name): """ Try and find a container in a variety of methods """
for meth in (database.load_container, load_new_labware, _load_weird_container): log.debug( f"Trying to load container {container_name} via {meth.__name__}") try: container = meth(container_name) if meth == _load_weird_container: container.properties['type'] = container_name log.info(f"Loaded {container_name} from {meth.__name__}") break except (ValueError, KeyError): log.info(f"{container_name} not in {meth.__name__}") else: raise KeyError(f"Unknown labware {container_name}") container_x, container_y, container_z = container._coordinates # infer z from height if container_z == 0 and 'height' in container[0].properties: container_z = container[0].properties['height'] from opentrons.util.vector import Vector container._coordinates = Vector( container_x, container_y, container_z) return container
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_tips(self): """ If reset is called with a tip attached, the tip must be removed before the poses and _instruments members are cleared. If the tip is not removed, the effective length of the pipette remains increased by the length of the tip, and subsequent `_add_tip` calls will increase the length in addition to this. This should be fixed by changing pose tracking to that it tracks the tip as a separate node rather than adding and subtracting the tip length to the pipette length. """
for instrument in self._instruments.values(): if instrument.tip_attached: instrument._remove_tip(instrument._tip_length)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def identify(self, seconds): """ Identify a robot by flashing the light around the frame button for 10s """
from time import sleep for i in range(seconds): self.turn_off_button_light() sleep(0.25) self.turn_on_button_light() sleep(0.25)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_instrument(self, mount, instrument): """ Adds instrument to a robot. Parameters mount : str Specifies which axis the instruments is attached to. Valid options are "left" or "right". instrument : Instrument An instance of a :class:`Pipette` to attached to the axis. Notes ----- A canonical way to add to add a Pipette to a robot is: :: from opentrons import instruments m300 = instruments.P300_Multi(mount='left') This will create a pipette and call :func:`add_instrument` to attach the instrument. """
if mount in self._instruments: prev_instr = self._instruments[mount] raise RuntimeError('Instrument {0} already on {1} mount'.format( prev_instr.name, mount)) self._instruments[mount] = instrument instrument.instrument_actuator = self._actuators[mount]['plunger'] instrument.instrument_mover = self._actuators[mount]['carriage'] # instrument_offset is the distance found (with tip-probe) between # the pipette's expected position, and the actual position # this is expected to be no greater than ~3mm # Z is not included, because Z offsets found during tip-probe are used # to determined the tip's length cx, cy, _ = self.config.instrument_offset[mount][instrument.type] # model_offset is the expected position of the pipette, determined # by designed dimensions of that model (eg: p10-multi vs p300-single) mx, my, mz = instrument.model_offset # combine each offset to get the pipette's position relative to gantry _x, _y, _z = ( mx + cx, my + cy, mz ) # if it's the left mount, apply the offset from right pipette if mount == 'left': _x, _y, _z = ( _x + self.config.mount_offset[0], _y + self.config.mount_offset[1], _z + self.config.mount_offset[2] ) self.poses = pose_tracker.add( self.poses, instrument, parent=mount, point=(_x, _y, _z) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, port=None, options=None): """ Connects the robot to a serial port. Parameters port : str OS-specific port name or ``'Virtual Smoothie'`` options : dict if :attr:`port` is set to ``'Virtual Smoothie'``, provide the list of options to be passed to :func:`get_virtual_device` Returns ------- ``True`` for success, ``False`` for failure. Note ---- If you wish to connect to the robot without using the OT App, you will need to use this function. Examples -------- """
self._driver.connect(port=port) self.fw_version = self._driver.get_fw_version() # the below call to `cache_instrument_models` is relied upon by # `Session._simulate()`, which calls `robot.connect()` after exec'ing a # protocol. That protocol could very well have different pipettes than # what are physically attached to the robot self.cache_instrument_models()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def home(self, *args, **kwargs): """ Home robot's head and plunger motors. """
# Home gantry first to avoid colliding with labware # and to make sure tips are not in the liquid while # homing plungers. Z/A axis will automatically home before X/Y self.poses = self.gantry.home(self.poses) # Then plungers self.poses = self._actuators['left']['plunger'].home(self.poses) self.poses = self._actuators['right']['plunger'].home(self.poses) # next move should not use any previously used instrument or labware # to prevent robot.move_to() from using risky path optimization self._previous_instrument = None self._prev_container = None # explicitly update carriage Mover positions in pose tree # because their Mover.home() commands aren't used here for a in self._actuators.values(): self.poses = a['carriage'].update_pose_from_driver(self.poses)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to( self, location, instrument, strategy='arc', **kwargs): """ Move an instrument to a coordinate, container or a coordinate within a container. Parameters location : one of the following: 1. :class:`Placeable` (i.e. Container, Deck, Slot, Well) — will move to the origin of a container. 2. :class:`Vector` move to the given coordinate in Deck coordinate system. 3. (:class:`Placeable`, :class:`Vector`) move to a given coordinate within object's coordinate system. instrument : Instrument to move relative to. If ``None``, move relative to the center of a gantry. strategy : {'arc', 'direct'} ``arc`` : move to the point using arc trajectory avoiding obstacles. ``direct`` : move to the point in a straight line. """
placeable, coordinates = containers.unpack_location(location) # because the top position is what is tracked, # this checks if coordinates doesn't equal top offset = subtract(coordinates, placeable.top()[1]) if isinstance(placeable, containers.WellSeries): placeable = placeable[0] target = add( pose_tracker.absolute( self.poses, placeable ), offset.coordinates ) if self._previous_instrument: if self._previous_instrument != instrument: self._previous_instrument.retract() # because we're switching pipettes, this ensures a large (safe) # Z arc height will be used for the new pipette self._prev_container = None self._previous_instrument = instrument if strategy == 'arc': arc_coords = self._create_arc(instrument, target, placeable) for coord in arc_coords: self.poses = instrument._move( self.poses, **coord) elif strategy == 'direct': position = {'x': target[0], 'y': target[1], 'z': target[2]} self.poses = instrument._move( self.poses, **position) else: raise RuntimeError( 'Unknown move strategy: {}'.format(strategy))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_arc(self, inst, destination, placeable=None): """ Returns a list of coordinates to arrive to the destination coordinate """
this_container = None if isinstance(placeable, containers.Well): this_container = placeable.get_parent() elif isinstance(placeable, containers.WellSeries): this_container = placeable.get_parent() elif isinstance(placeable, containers.Container): this_container = placeable if this_container and self._prev_container == this_container: # movements that stay within the same container do not need to # avoid other containers on the deck, so the travel height of # arced movements can be relative to just that one container arc_top = self.max_placeable_height_on_deck(this_container) arc_top += TIP_CLEARANCE_LABWARE elif self._use_safest_height: # bring the pipettes up as high as possible while calibrating arc_top = inst._max_deck_height() else: # bring pipette up above the tallest container currently on deck arc_top = self.max_deck_height() + TIP_CLEARANCE_DECK self._prev_container = this_container # if instrument is currently taller than arc_top, don't move down _, _, pip_z = pose_tracker.absolute(self.poses, inst) arc_top = max(arc_top, destination[2], pip_z) arc_top = min(arc_top, inst._max_deck_height()) strategy = [ {'z': arc_top}, {'x': destination[0], 'y': destination[1]}, {'z': destination[2]} ] return strategy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self): """ Disconnects from the robot. """
if self._driver: self._driver.disconnect() self.axis_homed = { 'x': False, 'y': False, 'z': False, 'a': False, 'b': False}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_slot_offsets(self): """ col_offset - from bottom left corner of 1 to bottom corner of 2 row_offset - from bottom left corner of 1 to bottom corner of 4 TODO: figure out actual X and Y offsets (from origin) """
SLOT_OFFSETS = { 'slots': { 'col_offset': 132.50, 'row_offset': 90.5 } } slot_settings = SLOT_OFFSETS.get(self.get_deck_slot_types()) row_offset = slot_settings.get('row_offset') col_offset = slot_settings.get('col_offset') return (row_offset, col_offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_attached_pipettes(self): """ Gets model names of attached pipettes :return: :dict with keys 'left' and 'right' and a model string for each mount, or 'uncommissioned' if no model string available """
left_data = { 'mount_axis': 'z', 'plunger_axis': 'b', 'model': self.model_by_mount['left']['model'], 'id': self.model_by_mount['left']['id'] } left_model = left_data.get('model') if left_model: tip_length = pipette_config.load( left_model, left_data['id']).tip_length left_data.update({'tip_length': tip_length}) right_data = { 'mount_axis': 'a', 'plunger_axis': 'c', 'model': self.model_by_mount['right']['model'], 'id': self.model_by_mount['right']['id'] } right_model = right_data.get('model') if right_model: tip_length = pipette_config.load( right_model, right_data['id']).tip_length right_data.update({'tip_length': tip_length}) return { 'left': left_data, 'right': right_data }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calibrate_container_with_instrument(self, container: Container, instrument, save: bool ): '''Calibrates a container using the bottom of the first well''' well = container[0] # Get the relative position of well with respect to instrument delta = pose_tracker.change_base( self.poses, src=instrument, dst=well ) if fflags.calibrate_to_bottom(): delta_x = delta[0] delta_y = delta[1] if 'tiprack' in container.get_type(): delta_z = delta[2] else: delta_z = delta[2] + well.z_size() else: delta_x = delta[0] delta_y = delta[1] delta_z = delta[2] self.poses = self._calibrate_container_with_delta( self.poses, container, delta_x, delta_y, delta_z, save ) self.max_deck_height.cache_clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _begin_write(session: UpdateSession, loop: asyncio.AbstractEventLoop, rootfs_file_path: str): """ Start the write process. """
session.set_progress(0) session.set_stage(Stages.WRITING) write_future = asyncio.ensure_future(loop.run_in_executor( None, file_actions.write_update, rootfs_file_path, session.set_progress)) def write_done(fut): exc = fut.exception() if exc: session.set_error(getattr(exc, 'short', str(type(exc))), str(exc)) else: session.set_stage(Stages.DONE) write_future.add_done_callback(write_done)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calibrate(self): ''' Calibration involves probing for top plate to get the plate height ''' if self._driver and self._driver.is_connected(): self._driver.probe_plate() # return if successful or not? self._engaged = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def disengage(self): ''' Home the magnet ''' if self._driver and self._driver.is_connected(): self._driver.home() self._engaged = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def connect(self): ''' Connect to the serial port ''' if self._port: self._driver = MagDeckDriver() self._driver.connect(self._port) self._device_info = self._driver.get_device_info() else: # Sanity check: Should never happen, because connect should # never be called without a port on Module raise MissingDevicePortError( "MagDeck couldnt connect to port {}".format(self._port) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_globals(version=None, loop=None): """ Reinitialize the global singletons with a given API version. :param version: 1 or 2. If `None`, pulled from the `useProtocolApiV2` advanced setting. """
global containers global instruments global labware global robot global reset global modules global hardware robot, reset, instruments, containers, labware, modules, hardware\ = build_globals(version, loop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_protocol_error(tb, proto_name): """Return the FrameInfo for the lowest frame in the traceback from the protocol. """
tb_info = traceback.extract_tb(tb) for frame in reversed(tb_info): if frame.filename == proto_name: return frame else: raise KeyError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_protocol(protocol_code: Any = None, protocol_json: Dict[Any, Any] = None, simulate: bool = False, context: ProtocolContext = None): """ Create a ProtocolRunner instance from one of a variety of protocol sources. :param protocol_bytes: If the protocol is a Python protocol, pass the file contents here. :param protocol_json: If the protocol is a json file, pass the contents here. :param simulate: True to simulate; False to execute. If this is not an OT2, ``simulate`` will be forced ``True``. :param context: The context to use. If ``None``, create a new ProtocolContext. """
if not config.IS_ROBOT: simulate = True # noqa - will be used later if None is context and simulate: true_context = ProtocolContext() true_context.home() MODULE_LOG.info("Generating blank protocol context for simulate") elif context: true_context = context else: raise RuntimeError( 'Will not automatically generate hardware controller') if None is not protocol_code: _run_python(protocol_code, true_context) elif None is not protocol_json: protocol_version = get_protocol_schema_version(protocol_json) if protocol_version > 3: raise RuntimeError( f'JSON Protocol version {protocol_version} is not yet ' + 'supported in this version of the API') validate_protocol(protocol_json) if protocol_version >= 3: ins = execute_v3.load_pipettes_from_json( true_context, protocol_json) lw = execute_v3.load_labware_from_json_defs( true_context, protocol_json) execute_v3.dispatch_json(true_context, protocol_json, ins, lw) else: ins = execute_v1.load_pipettes_from_json( true_context, protocol_json) lw = execute_v1.load_labware_from_json_loadnames( true_context, protocol_json) execute_v1.dispatch_json(true_context, protocol_json, ins, lw) else: raise RuntimeError("run_protocol must have either code or json")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_ports_by_name(device_name): '''Returns all serial devices with a given name''' filtered_devices = filter( lambda device: device_name in device[1], list_ports.comports() ) device_ports = [device[0] for device in filtered_devices] return device_ports
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serial_with_temp_timeout(serial_connection, timeout): '''Implements a temporary timeout for a serial connection''' saved_timeout = serial_connection.timeout if timeout is not None: serial_connection.timeout = timeout yield serial_connection serial_connection.timeout = saved_timeout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _write_to_device_and_return(cmd, ack, device_connection): '''Writes to a serial device. - Formats command - Wait for ack return - return parsed response''' log.debug('Write -> {}'.format(cmd.encode())) device_connection.write(cmd.encode()) response = device_connection.read_until(ack.encode()) log.debug('Read <- {}'.format(response)) if ack.encode() not in response: raise SerialNoResponse( 'No response from serial port after {} second(s)'.format( device_connection.timeout)) clean_response = _parse_serial_response(response, ack.encode()) if clean_response: return clean_response.decode() return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write_and_return( command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT): '''Write a command and return the response''' clear_buffer(serial_connection) with serial_with_temp_timeout( serial_connection, timeout) as device_connection: response = _write_to_device_and_return(command, ack, device_connection) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_advanced_settings(request: web.Request) -> web.Response: """ Handles a GET request and returns a json body with the key "settings" and a value that is a list of objects where each object has keys "id", "title", "description", and "value" """
res = _get_adv_settings() return web.json_response(res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def set_advanced_setting(request: web.Request) -> web.Response: """ Handles a POST request with a json body that has keys "id" and "value", where the value of "id" must correspond to an id field of a setting in `opentrons.config.advanced_settings.settings`. Saves the value of "value" for the setting that matches the supplied id. """
data = await request.json() key = data.get('id') value = data.get('value') if key and key in advs.settings_by_id.keys(): advs.set_adv_setting(key, value) res = _get_adv_settings() status = 200 else: res = {'message': 'ID {} not found in settings list'.format(key)} status = 400 return web.json_response(res, status=status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def reset(request: web.Request) -> web.Response: """ Execute a reset of the requested parts of the user configuration. """
data = await request.json() ok, bad_key = _check_reset(data) if not ok: return web.json_response( {'message': '{} is not a valid reset option' .format(bad_key)}, status=400) log.info("Reset requested for {}".format(', '.join(data.keys()))) if data.get('tipProbe'): config = rc.load() if ff.use_protocol_api_v2(): config = config._replace( instrument_offset=rc.build_fallback_instrument_offset({})) else: config.tip_length.clear() rc.save_robot_settings(config) if data.get('labwareCalibration'): if ff.use_protocol_api_v2(): labware.clear_calibrations() else: db.reset() if data.get('bootScripts'): if IS_ROBOT: if os.path.exists('/data/boot.d'): shutil.rmtree('/data/boot.d') else: log.debug('Not on pi, not removing /data/boot.d') return web.json_response({}, status=200)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def available_resets(request: web.Request) -> web.Response: """ Indicate what parts of the user configuration are available for reset. """
return web.json_response({'options': _settings_reset_options}, status=200)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def connections( for_type: Optional[CONNECTION_TYPES] = None) -> List[Dict[str, str]]: """ Return the list of configured connections. This is all connections that nmcli knows about and manages. Each connection is a dict containing some basic information - the information retrievable from nmcli connection show. Further information should be queried on a connection by connection basis. If for_type is not None, it should be a str containing an element of CONNECTION_TYPES, and results will be limited to that connection type. """
fields = ['name', 'type', 'active'] res, _ = await _call(['-t', '-f', ','.join(fields), 'connection', 'show']) found = _dict_from_terse_tabular( fields, res, # ’ethernet’ or ’wireless’ from ’802-11-wireless’ or ’802-4-ethernet’ # and bools from ’yes’ or ’no transformers={'type': lambda s: s.split('-')[-1], 'active': lambda s: s.lower() == 'yes'} ) if for_type is not None: should_return = [] for c in found: if c['type'] == for_type.value: should_return.append(c) return should_return else: return found
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def connection_exists(ssid: str) -> Optional[str]: """ If there is already a connection for this ssid, return the name of the connection; if there is not, return None. """
nmcli_conns = await connections() for wifi in [c['name'] for c in nmcli_conns if c['type'] == 'wireless']: res, _ = await _call(['-t', '-f', '802-11-wireless.ssid', '-m', 'tabular', 'connection', 'show', wifi]) if res == ssid: return wifi return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _trim_old_connections( new_name: str, con_type: CONNECTION_TYPES) -> Tuple[bool, str]: """ Delete all connections of con_type but the one specified. """
existing_cons = await connections(for_type=con_type) not_us = [c['name'] for c in existing_cons if c['name'] != new_name] ok = True res = [] for c in not_us: this_ok, remove_res = await remove(name=c) ok = ok and this_ok if not this_ok: # This is not a failure case for connection, and indeed the new # connection is already established, so just warn about it log.warning("Could not remove wifi connection {}: {}" .format(c, remove_res)) res.append(remove_res) else: log.debug("Removed old wifi connection {}".format(c)) return ok, ';'.join(res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_eap_args(eap_args: Dict[str, str]) -> List[str]: """ Add configuration options suitable for an nmcli con add command for WPA-EAP configuration. These options are mostly in the 802-1x group. The eap_args dict should be a flat structure of arguments. They must contain at least 'eapType', specifying the EAP type to use (the qualified_name() of one of the members of EAP_TYPES) and the required arguments for that EAP type. """
args = ['wifi-sec.key-mgmt', 'wpa-eap'] eap_type = EAP_TYPES.by_qualified_name(eap_args['eapType']) type_args = eap_type.args() args += ['802-1x.eap', eap_type.outer.value.name] if eap_type.inner: args += ['802-1x.phase2-autheap', eap_type.inner.value.name] for ta in type_args: if ta['name'] in eap_args: if ta['type'] == 'file': # Keyfiles must be prepended with file:// so nm-cli # knows that we’re not giving it DER-encoded blobs _make_host_symlink_if_necessary() path = _rewrite_key_path_to_host_path(eap_args[ta['name']]) val = 'file://' + path else: val = eap_args[ta['name']] args += ['802-1x.' + ta['nmName'], val] return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_con_add_cmd(ssid: str, security_type: SECURITY_TYPES, psk: Optional[str], hidden: bool, eap_args: Optional[Dict[str, Any]]) -> List[str]: """ Build the nmcli connection add command to configure the new network. The parameters are the same as configure but without the defaults; this should be called only by configure. """
configure_cmd = ['connection', 'add', 'save', 'yes', 'autoconnect', 'yes', 'ifname', 'wlan0', 'type', 'wifi', 'con-name', ssid, 'wifi.ssid', ssid] if hidden: configure_cmd += ['wifi.hidden', 'true'] if security_type == SECURITY_TYPES.WPA_PSK: configure_cmd += ['wifi-sec.key-mgmt', security_type.value] if psk is None: raise ValueError('wpa-psk security type requires psk') configure_cmd += ['wifi-sec.psk', psk] elif security_type == SECURITY_TYPES.WPA_EAP: if eap_args is None: raise ValueError('wpa-eap security type requires eap_args') configure_cmd += _add_eap_args(eap_args) elif security_type == SECURITY_TYPES.NONE: pass else: raise ValueError("Bad security_type {}".format(security_type)) return configure_cmd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def iface_info(which_iface: NETWORK_IFACES) -> Dict[str, Optional[str]]: """ Get the basic network configuration of an interface. Returns a dict containing the info: { 'ipAddress': 'xx.xx.xx.xx/yy' (ip4 addr with subnet as CIDR) or None 'macAddress': 'aa:bb:cc:dd:ee:ff' or None 'gatewayAddress: 'zz.zz.zz.zz' or None } which_iface should be a string in IFACE_NAMES. """
# example device info lines # GENERAL.HWADDR:B8:27:EB:24:D1:D0 # IP4.ADDRESS[1]:10.10.2.221/22 # capture the field name (without the number in brackets) and the value # using regex instead of split because there may be ":" in the value _DEV_INFO_LINE_RE = re.compile(r'([\w.]+)(?:\[\d+])?:(.*)') # example device info: 30 (disconnected) # capture the string without the number _IFACE_STATE_RE = re.compile(r'\d+ \((.+)\)') info: Dict[str, Optional[str]] = {'ipAddress': None, 'macAddress': None, 'gatewayAddress': None, 'state': None, 'type': None} fields = ['GENERAL.HWADDR', 'IP4.ADDRESS', 'IP4.GATEWAY', 'GENERAL.TYPE', 'GENERAL.STATE'] # Note on this specific command: Most nmcli commands default to a tabular # output mode, where if there are multiple things to pull a couple specific # fields from it you’ll get a table where rows are, say, connections, and # columns are field name. However, specifically ‘con show <con-name>‘ and # ‘dev show <dev-name>’ default to a multiline representation, and even if # explicitly ask for it to be tabular, it’s not quite the same as the other # commands. So we have to special-case the parsing. res, err = await _call(['--mode', 'multiline', '--escape', 'no', '--terse', '--fields', ','.join(fields), 'dev', 'show', which_iface.value]) field_map = {} for line in res.split('\n'): # pull the key (without brackets) and the value out of the line match = _DEV_INFO_LINE_RE.fullmatch(line) if match is None: raise ValueError( "Bad nmcli result; out: {}; err: {}".format(res, err)) key, val = match.groups() # nmcli can put "--" instead of "" for None field_map[key] = None if val == '--' else val info['macAddress'] = field_map.get('GENERAL.HWADDR') info['ipAddress'] = field_map.get('IP4.ADDRESS') info['gatewayAddress'] = field_map.get('IP4.GATEWAY') info['type'] = field_map.get('GENERAL.TYPE') state_val = field_map.get('GENERAL.STATE') if state_val: state_match = _IFACE_STATE_RE.fullmatch(state_val) if state_match: info['state'] = state_match.group(1) return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanitize_args(cmd: List[str]) -> List[str]: """ Filter the command so that it no longer contains passwords """
sanitized = [] for idx, fieldname in enumerate(cmd): def _is_password(cmdstr): return 'wifi-sec.psk' in cmdstr\ or 'password' in cmdstr.lower() if idx > 0 and _is_password(cmd[idx-1]): sanitized.append('****') else: sanitized.append(fieldname) return sanitized
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dict_from_terse_tabular( names: List[str], inp: str, transformers: Dict[str, Callable[[str], Any]] = {})\ -> List[Dict[str, Any]]: """ Parse NMCLI terse tabular output into a list of Python dict. ``names`` is a list of strings of field names to apply to the input data, which is assumed to be colon separated. ``inp`` is the input as a string (i.e. already decode()d) from nmcli ``transformers`` is a dict mapping field names to callables of the form f: str -> any. If a fieldname is in transformers, that callable will be invoked on the field matching the name and the result stored. The return value is a list with one element per valid line of input, where each element is a dict with keys taken from names and values from the input """
res = [] for n in names: if n not in transformers: transformers[n] = lambda s: s for line in inp.split('\n'): if len(line) < 3: continue fields = line.split(':') res.append(dict([ (elem[0], transformers[elem[0]](elem[1])) for elem in zip(names, fields)])) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Resets the state of this pipette, removing associated placeables, setting current volume to zero, and resetting tip tracking """
self.tip_attached = False self.placeables = [] self.previous_placeable = None self.current_volume = 0 self.reset_tip_tracking()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _associate_placeable(self, location): """ Saves a reference to a placeable """
if not location: return placeable, _ = unpack_location(location) self.previous_placeable = placeable if not self.placeables or (placeable != self.placeables[-1]): self.placeables.append(placeable)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def retract(self, safety_margin=10): ''' Move the pipette's mount upwards and away from the deck Parameters ---------- safety_margin: int Distance in millimeters awey from the limit switch, used during the mount's `fast_home()` method ''' self.previous_placeable = None # it is no longer inside a placeable self.robot.poses = self.instrument_mover.fast_home( self.robot.poses, safety_margin) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blow_out(self, location=None): """ Force any remaining liquid to dispense, by moving this pipette's plunger to the calibrated `blow_out` position Notes ----- If no `location` is passed, the pipette will blow_out from it's current position. Parameters location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`) The :any:`Placeable` (:any:`Well`) to perform the blow_out. Can also be a tuple with first item :any:`Placeable`, second item relative :any:`Vector` Returns ------- This instance of :class:`Pipette`. Examples -------- .. """
if not self.tip_attached: log.warning("Cannot 'blow out' without a tip attached.") self.move_to(location) self.instrument_actuator.set_active_current(self._plunger_current) self.robot.poses = self.instrument_actuator.move( self.robot.poses, x=self._get_plunger_position('blow_out') ) self.current_volume = 0 return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_tip(self, home_after=True): """ Drop the pipette's current tip to it's originating tip rack Notes ----- This method requires one or more tip-rack :any:`Container` to be in this Pipette's `tip_racks` list (see :any:`Pipette`) Returns ------- This instance of :class:`Pipette`. Examples -------- .. """
if not self.tip_attached: log.warning("Cannot return tip without tip attached.") if not self.current_tip(): self.robot.add_warning( 'Pipette has no tip to return, dropping in place') self.drop_tip(self.current_tip(), home_after=home_after) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick_up_tip(self, location=None, presses=None, increment=None): """ Pick up a tip for the Pipette to run liquid-handling commands with Notes ----- A tip can be manually set by passing a `location`. If no location is passed, the Pipette will pick up the next available tip in it's `tip_racks` list (see :any:`Pipette`) Parameters location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`) The :any:`Placeable` (:any:`Well`) to perform the pick_up_tip. Can also be a tuple with first item :any:`Placeable`, second item relative :any:`Vector` presses : :any:int The number of times to lower and then raise the pipette when picking up a tip, to ensure a good seal (0 [zero] will result in the pipette hovering over the tip but not picking it up--generally not desireable, but could be used for dry-run). Default: 3 presses increment: :int The additional distance to travel on each successive press (e.g.: if presses=3 and increment=1, then the first press will travel down into the tip by 3.5mm, the second by 4.5mm, and the third by 5.5mm. Default: 1mm Returns ------- This instance of :class:`Pipette`. Examples -------- .. # `pick_up_tip` will automatically go to tiprack[1] """
if self.tip_attached: log.warning("There is already a tip attached to this pipette.") if not location: location = self.get_next_tip() self.current_tip(None) if location: placeable, _ = unpack_location(location) self.current_tip(placeable) presses = (self._pick_up_presses if not helpers.is_number(presses) else presses) increment = (self._pick_up_increment if not helpers.is_number(increment) else increment) def _pick_up_tip( self, location, presses, increment): self.instrument_actuator.set_active_current(self._plunger_current) self.robot.poses = self.instrument_actuator.move( self.robot.poses, x=self._get_plunger_position('bottom') ) self.current_volume = 0 self.move_to(self.current_tip().top(0)) for i in range(int(presses)): # move nozzle down into the tip self.instrument_mover.push_speed() self.instrument_mover.push_active_current() self.instrument_mover.set_active_current(self._pick_up_current) self.instrument_mover.set_speed(self._pick_up_speed) dist = (-1 * self._pick_up_distance) + (-1 * increment * i) self.move_to( self.current_tip().top(dist), strategy='direct') # move nozzle back up self.instrument_mover.pop_active_current() self.instrument_mover.pop_speed() self.move_to( self.current_tip().top(0), strategy='direct') self._add_tip( length=self._tip_length ) # neighboring tips tend to get stuck in the space between # the volume chamber and the drop-tip sleeve on p1000. # This extra shake ensures those tips are removed if 'needs-pickup-shake' in self.quirks: self._shake_off_tips(location) self._shake_off_tips(location) self.previous_placeable = None # no longer inside a placeable self.robot.poses = self.instrument_mover.fast_home( self.robot.poses, self._pick_up_distance) return self do_publish(self.broker, commands.pick_up_tip, self.pick_up_tip, 'before', None, None, self, location, presses, increment) _pick_up_tip( self, location=location, presses=presses, increment=increment) do_publish(self.broker, commands.pick_up_tip, self.pick_up_tip, 'after', self, None, self, location, presses, increment) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop_tip(self, location=None, home_after=True): """ Drop the pipette's current tip Notes ----- If no location is passed, the pipette defaults to its `trash_container` (see :any:`Pipette`) Parameters location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`) The :any:`Placeable` (:any:`Well`) to perform the drop_tip. Can also be a tuple with first item :any:`Placeable`, second item relative :any:`Vector` Returns ------- This instance of :class:`Pipette`. Examples -------- .. # drops the tip in the fixed trash # drops the tip back at its tip rack """
if not self.tip_attached: log.warning("Cannot drop tip without a tip attached.") if not location and self.trash_container: location = self.trash_container if isinstance(location, Placeable): # give space for the drop-tip mechanism # @TODO (Laura & Andy 2018261) # When container typing is implemented, make sure that # when returning to a tiprack, tips are dropped within the rack if 'rack' in location.get_parent().get_type(): half_tip_length = self._tip_length / 2 location = location.top(-half_tip_length) elif 'trash' in location.get_parent().get_type(): loc, coords = location.top() location = (loc, coords + (0, self.model_offset[1], 0)) else: location = location.top() def _drop_tip(location, instrument=self): if location: self.move_to(location) pos_bottom = self._get_plunger_position('bottom') pos_drop_tip = self._get_plunger_position('drop_tip') self.instrument_actuator.set_active_current(self._plunger_current) self.robot.poses = self.instrument_actuator.move( self.robot.poses, x=pos_bottom ) self.instrument_actuator.set_active_current(self._drop_tip_current) self.instrument_actuator.push_speed() self.instrument_actuator.set_speed(self._drop_tip_speed) self.robot.poses = self.instrument_actuator.move( self.robot.poses, x=pos_drop_tip ) self.instrument_actuator.pop_speed() self._shake_off_tips(location) if home_after: self._home_after_drop_tip() self.current_volume = 0 self.current_tip(None) self._remove_tip( length=self._tip_length ) do_publish(self.broker, commands.drop_tip, self.drop_tip, 'before', None, None, self, location) _drop_tip(location) do_publish(self.broker, commands.drop_tip, self.drop_tip, 'after', self, None, self, location) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def home(self): """ Home the pipette's plunger axis during a protocol run Notes ----- `Pipette.home()` homes the `Robot` Returns ------- This instance of :class:`Pipette`. Examples -------- .. """
def _home(mount): self.current_volume = 0 self.instrument_actuator.set_active_current(self._plunger_current) self.robot.poses = self.instrument_actuator.home( self.robot.poses) self.robot.poses = self.instrument_mover.home(self.robot.poses) self.previous_placeable = None # no longer inside a placeable do_publish(self.broker, commands.home, _home, 'before', None, None, self.mount) _home(self.mount) do_publish(self.broker, commands.home, _home, 'after', self, None, self.mount) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calibrate_plunger( self, top=None, bottom=None, blow_out=None, drop_tip=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. Parameters top : int Touching but not engaging the plunger. bottom: int Must be above the pipette's physical hard-stop, while still leaving enough room for 'blow_out' blow_out : int Plunger has been pushed down enough to expell all liquids. drop_tip : int This position that causes the tip to be released from the pipette. """
if top is not None: self.plunger_positions['top'] = top if bottom is not None: self.plunger_positions['bottom'] = bottom if blow_out is not None: self.plunger_positions['blow_out'] = blow_out if drop_tip is not None: self.plunger_positions['drop_tip'] = drop_tip return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_plunger_position(self, position): """ Returns the calibrated coordinate of a given plunger position Raises exception if the position has not been calibrated yet """
try: value = self.plunger_positions[position] if helpers.is_number(value): return value else: raise RuntimeError( 'Plunger position "{}" not yet calibrated'.format( position)) except KeyError: raise RuntimeError( 'Plunger position "{}" does not exist'.format( position))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def engage(self, height): """ Move the magnet to a specific height, in mm from home position """
if height > MAX_ENGAGE_HEIGHT or height < 0: raise ValueError('Invalid engage height. Should be 0 to {}'.format( MAX_ENGAGE_HEIGHT)) self._driver.move(height) self._engaged = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def break_down_travel(p1, target, increment=5, mode='absolute'): """ given two points p1 and target, this returns a list of incremental positions or relative steps """
heading = target - p1 if mode == 'relative': heading = target length = heading.length() length_steps = length / increment length_remainder = length % increment vector_step = Vector(0, 0, 0) if length_steps > 0: vector_step = heading / length_steps vector_remainder = vector_step * (length_remainder / increment) res = [] if mode == 'absolute': for i in range(int(length_steps)): p1 = p1 + vector_step res.append(p1) p1 = p1 + vector_remainder res.append(p1) else: for i in range(int(length_steps)): res.append(vector_step) res.append(vector_remainder) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expand_for_carryover(max_vol, plan, **kwargs): """ Divide volumes larger than maximum volume into separate transfers """
max_vol = float(max_vol) carryover = kwargs.get('carryover', True) if not carryover: return plan new_transfer_plan = [] for p in plan: source = p['aspirate']['location'] target = p['dispense']['location'] volume = float(p['aspirate']['volume']) while volume > max_vol * 2: new_transfer_plan.append({ 'aspirate': {'location': source, 'volume': max_vol}, 'dispense': {'location': target, 'volume': max_vol} }) volume -= max_vol if volume > max_vol: volume /= 2 new_transfer_plan.append({ 'aspirate': {'location': source, 'volume': float(volume)}, 'dispense': {'location': target, 'volume': float(volume)} }) new_transfer_plan.append({ 'aspirate': {'location': source, 'volume': float(volume)}, 'dispense': {'location': target, 'volume': float(volume)} }) return new_transfer_plan
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compress_for_repeater(max_vol, plan, **kwargs): """ Reduce size of transfer plan, if mode is distribute or consolidate """
max_vol = float(max_vol) mode = kwargs.get('mode', 'transfer') if mode == 'distribute': # combine target volumes into single aspirate return _compress_for_distribute(max_vol, plan, **kwargs) if mode == 'consolidate': # combine target volumes into multiple aspirates return _compress_for_consolidate(max_vol, plan, **kwargs) else: return plan
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compress_for_distribute(max_vol, plan, **kwargs): """ Combines as many dispenses as can fit within the maximum volume """
source = None new_source = None a_vol = 0 temp_dispenses = [] new_transfer_plan = [] disposal_vol = kwargs.get('disposal_vol', 0) max_vol = max_vol - disposal_vol def _append_dispenses(): nonlocal a_vol, temp_dispenses, new_transfer_plan, source if not temp_dispenses: return added_volume = 0 if len(temp_dispenses) > 1: added_volume = disposal_vol new_transfer_plan.append({ 'aspirate': { 'location': source, 'volume': a_vol + added_volume } }) for d in temp_dispenses: new_transfer_plan.append({ 'dispense': { 'location': d['location'], 'volume': d['volume'] } }) a_vol = 0 temp_dispenses = [] for p in plan: this_vol = p['aspirate']['volume'] new_source = p['aspirate']['location'] if (new_source is not source) or (this_vol + a_vol > max_vol): _append_dispenses() source = new_source a_vol += this_vol temp_dispenses.append(p['dispense']) _append_dispenses() return new_transfer_plan
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compress_for_consolidate(max_vol, plan, **kwargs): """ Combines as many aspirates as can fit within the maximum volume """
target = None new_target = None d_vol = 0 temp_aspirates = [] new_transfer_plan = [] def _append_aspirates(): nonlocal d_vol, temp_aspirates, new_transfer_plan, target if not temp_aspirates: return for a in temp_aspirates: new_transfer_plan.append({ 'aspirate': { 'location': a['location'], 'volume': a['volume'] } }) new_transfer_plan.append({ 'dispense': { 'location': target, 'volume': d_vol } }) d_vol = 0 temp_aspirates = [] for i, p in enumerate(plan): this_vol = p['aspirate']['volume'] new_target = p['dispense']['location'] if (new_target is not target) or (this_vol + d_vol > max_vol): _append_aspirates() target = new_target d_vol += this_vol temp_aspirates.append(p['aspirate']) _append_aspirates() return new_transfer_plan
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _migrate0to1(previous: Mapping[str, Any]) -> SettingsMap: """ Migrate to version 1 of the feature flags file. Replaces old IDs with new IDs and sets any False values to None """
next: SettingsMap = {} for s in settings: id = s.id old_id = s.old_id if previous.get(id) is True: next[id] = True elif previous.get(old_id) is True: next[id] = True else: next[id] = None return next
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _migrate(data: Mapping[str, Any]) -> SettingsData: """ Check the version integer of the JSON file data a run any necessary migrations to get us to the latest file format. Returns dictionary of settings and version migrated to """
next = dict(data) version = next.pop('_version', 0) target_version = len(_MIGRATIONS) migrations = _MIGRATIONS[version:] if len(migrations) > 0: log.info( "Migrating advanced settings from version {} to {}" .format(version, target_version)) for m in migrations: next = m(next) return next, target_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_values(data: Mapping[str, Any]) -> Tuple[Dict[str, Any], bool]: """ Make sure we have appropriate keys and say if we should write """
to_return = {} should_write = False for keyname, typekind, default in REQUIRED_DATA: if keyname not in data: LOG.debug(f"Defaulted config value {keyname} to {default}") to_return[keyname] = default should_write = True elif not isinstance(data[keyname], typekind): LOG.warning( f"Config value {keyname} was {type(data[keyname])} not" f" {typekind}, defaulted to {default}") to_return[keyname] = default should_write = True else: to_return[keyname] = data[keyname] return to_return, should_write
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_from_path(path: str) -> Config: """ Load a config from a file and ensure its structure. Writes a default if necessary """
data = _ensure_load(path) if not data: data = {} values, should_write = _ensure_values(data) values.update({'path': path}) config = Config(**values) if config.signature_required: if not os.path.exists(config.update_cert_path): LOG.warning( f"No signing cert is present in {config.update_cert_path}, " "code signature checking disabled") config = config._replace(signature_required=False) config = config._replace(update_cert_path=DEFAULT_CERT_PATH) if should_write: save_to_path(path, config) return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_path(args_path: Optional[str]) -> str: """ Find the valid path from args then env then default """
env_path = os.getenv(PATH_ENVIRONMENT_VARIABLE) for path, source in ((args_path, 'arg'), (env_path, 'env')): if not path: LOG.debug(f"config.load: skipping {source} (path None)") continue else: LOG.debug(f"config.load: using config path {path} from {source}") return path return DEFAULT_PATH
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_stage(self, stage: Stages): """ Convenience method to set the stage and lookup message """
assert stage in Stages LOG.info(f'Update session: stage {self._stage.name}->{stage.name}') self._stage = stage
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_error(self, error_shortmsg: str, error_longmsg: str): """ Set the stage to error and add a message """
LOG.error(f"Update session: error in stage {self._stage.name}: " f"{error_shortmsg}: {error_longmsg}") self._error = Value(error_shortmsg, error_longmsg) self.set_stage(Stages.ERROR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(self) -> str: """ The human readable message of the current stage """
if self.is_error: assert self._error return self._error.human else: return self._stage.value.human
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def descendants(state, obj, level=0): """ Returns a flattened list tuples of DFS traversal of subtree from object that contains descendant object and it's depth """
return sum([ [(child, level)] + descendants(state, child, level + 1) for child in state[obj].children ], [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gantry_axes(cls) -> Tuple['Axis', 'Axis', 'Axis', 'Axis']: """ The axes which are tied to the gantry and require the deck calibration transform """
return (cls.X, cls.Y, cls.Z, cls.A)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_instrument_config( instrument, measured_center) -> Tuple[Point, float]: """ Update config and pose tree with instrument's x and y offsets and tip length based on delta between probe center and measured_center, persist updated config and return it """
from copy import deepcopy from opentrons.trackers.pose_tracker import update robot = instrument.robot config = robot.config instrument_offset = deepcopy(config.instrument_offset) dx, dy, dz = array(measured_center) - config.tip_probe.center log.debug("This is measured probe center dx {}".format(Point(dx, dy, dz))) # any Z offset will adjust the tip length, so instruments have Z=0 offset old_x, old_y, _ = instrument_offset[instrument.mount][instrument.type] instrument_offset[instrument.mount][instrument.type] = \ (old_x - dx, old_y - dy, 0.0) tip_length = deepcopy(config.tip_length) tip_length[instrument.name] = tip_length[instrument.name] + dz config = config \ ._replace(instrument_offset=instrument_offset) \ ._replace(tip_length=tip_length) robot.config = config log.debug("Updating config for {} instrument".format(instrument.mount)) robot_configs.save_robot_settings(config) new_coordinates = change_base( robot.poses, src=instrument, dst=instrument.instrument_mover) - Point(dx, dy, 0.0) robot.poses = update(robot.poses, instrument, new_coordinates) return robot.config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read_pipette_id(self, mount) -> Optional[str]: ''' Reads in an attached pipette's ID The ID is unique to this pipette, and is a string of unknown length :param mount: string with value 'left' or 'right' :return id string, or None ''' res: Optional[str] = None if self.simulating: res = '1234567890' else: try: res = self._read_from_pipette( GCODES['READ_INSTRUMENT_ID'], mount) except UnicodeDecodeError: log.exception("Failed to decode pipette ID string:") res = None return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read_pipette_model(self, mount) -> Optional[str]: ''' Reads an attached pipette's MODEL The MODEL is a unique string for this model of pipette :param mount: string with value 'left' or 'right' :return model string, or None ''' if self.simulating: res = None else: res = self._read_from_pipette( GCODES['READ_INSTRUMENT_MODEL'], mount) if res and '_v' not in res: # Backward compatibility for pipettes programmed with model # strings that did not include the _v# designation res = res + '_v1' elif res and '_v13' in res: # Backward compatibility for pipettes programmed with model # strings that did not include the "." to seperate version # major and minor values res = res.replace('_v13', '_v1.3') return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_fw_version(self): ''' Queries Smoothieware for it's build version, and returns the parsed response. returns: str Current version of attached Smoothi-driver. Versions are derived from git branch-hash (eg: edge-66ec883NOMSD) Example Smoothieware response: Build version: edge-66ec883NOMSD, Build date: Jan 28 2018 15:26:57, MCU: LPC1769, System Clock: 120MHz # NOQA CNC Build NOMSD Build 6 axis ''' version = 'Virtual Smoothie' if not self.simulating: version = self._send_command('version') version = version.split(',')[0].split(':')[-1].strip() version = version.replace('NOMSD', '') return version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def position(self): """ Instead of sending M114.2 we are storing target values in self._position since movement and home commands are blocking and assumed to go the correct place. Cases where Smoothie would not be in the correct place (such as if a belt slips) would not be corrected by getting position with M114.2 because Smoothie would also not be aware of slippage. """
return {k.upper(): v for k, v in self._position.items()}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_active_current(self, settings): ''' Sets the amperage of each motor for when it is activated by driver. Values are initialized from the `robot_config.high_current` values, and can then be changed through this method by other parts of the API. For example, `Pipette` setting the active-current of it's pipette, depending on what model pipette it is, and what action it is performing settings Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C') and floating point number for current (generally between 0.1 and 2) ''' self._active_current_settings['now'].update(settings) # if an axis specified in the `settings` is currently active, # reset it's current to the new active-current value active_axes_to_update = { axis: amperage for axis, amperage in self._active_current_settings['now'].items() if self._active_axes.get(axis) is True if self.current[axis] != amperage } if active_axes_to_update: self._save_current(active_axes_to_update, axes_active=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_dwelling_current(self, settings): ''' Sets the amperage of each motor for when it is dwelling. Values are initialized from the `robot_config.log_current` values, and can then be changed through this method by other parts of the API. For example, `Pipette` setting the dwelling-current of it's pipette, depending on what model pipette it is. settings Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C') and floating point number for current (generally between 0.1 and 2) ''' self._dwelling_current_settings['now'].update(settings) # if an axis specified in the `settings` is currently dwelling, # reset it's current to the new dwelling-current value dwelling_axes_to_update = { axis: amps for axis, amps in self._dwelling_current_settings['now'].items() if self._active_axes.get(axis) is False if self.current[axis] != amps } if dwelling_axes_to_update: self._save_current(dwelling_axes_to_update, axes_active=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _generate_current_command(self): ''' Returns a constructed GCode string that contains this driver's axis-current settings, plus a small delay to wait for those settings to take effect. ''' values = ['{}{}'.format(axis, value) for axis, value in sorted(self.current.items())] current_cmd = '{} {}'.format( GCODES['SET_CURRENT'], ' '.join(values) ) command = '{currents} {code}P{seconds}'.format( currents=current_cmd, code=GCODES['DWELL'], seconds=CURRENT_CHANGE_DELAY ) log.debug("_generate_current_command: {}".format(command)) return command
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def disengage_axis(self, axes): ''' Disable the stepper-motor-driver's 36v output to motor This is a safe GCODE to send to Smoothieware, as it will automatically re-engage the motor if it receives a home or move command axes String containing the axes to be disengaged (e.g.: 'XY' or 'ZA' or 'XYZABC') ''' axes = ''.join(set(axes.upper()) & set(AXES)) if axes: log.debug("disengage_axis: {}".format(axes)) self._send_command(GCODES['DISENGAGE_MOTOR'] + axes) for axis in axes: self.engaged_axes[axis] = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dwell_axes(self, axes): ''' Sets motors to low current, for when they are not moving. Dwell for XYZA axes is only called after HOMING Dwell for BC axes is called after both HOMING and MOVING axes: String containing the axes to set to low current (eg: 'XYZABC') ''' axes = ''.join(set(axes) & set(AXES) - set(DISABLE_AXES)) dwelling_currents = { ax: self._dwelling_current_settings['now'][ax] for ax in axes if self._active_axes[ax] is True } if dwelling_currents: self._save_current(dwelling_currents, axes_active=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _read_from_pipette(self, gcode, mount) -> Optional[str]: ''' Read from an attached pipette's internal memory. The gcode used determines which portion of memory is read and returned. All motors must be disengaged to consistently read over I2C lines gcode: String (str) containing a GCode either 'READ_INSTRUMENT_ID' or 'READ_INSTRUMENT_MODEL' mount: String (str) with value 'left' or 'right' ''' allowed_mounts = {'left': 'L', 'right': 'R'} mount = allowed_mounts.get(mount) if not mount: raise ValueError('Unexpected mount: {}'.format(mount)) try: # EMI interference from both plunger motors has been found to # prevent the I2C lines from communicating between Smoothieware and # pipette's onboard EEPROM. To avoid, turn off both plunger motors self.disengage_axis('BC') self.delay(CURRENT_CHANGE_DELAY) # request from Smoothieware the information from that pipette res = self._send_command(gcode + mount) if res: res = _parse_instrument_data(res) assert mount in res # data is read/written as strings of HEX characters # to avoid firmware weirdness in how it parses GCode arguments return _byte_array_to_ascii_string(res[mount]) except (ParseError, AssertionError, SmoothieError): pass return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _write_to_pipette(self, gcode, mount, data_string): ''' Write to an attached pipette's internal memory. The gcode used determines which portion of memory is written to. NOTE: To enable write-access to the pipette, it's button must be held gcode: String (str) containing a GCode either 'WRITE_INSTRUMENT_ID' or 'WRITE_INSTRUMENT_MODEL' mount: String (str) with value 'left' or 'right' data_string: String (str) that is of unkown length ''' allowed_mounts = {'left': 'L', 'right': 'R'} mount = allowed_mounts.get(mount) if not mount: raise ValueError('Unexpected mount: {}'.format(mount)) if not isinstance(data_string, str): raise ValueError( 'Expected {0}, not {1}'.format(str, type(data_string))) # EMI interference from both plunger motors has been found to # prevent the I2C lines from communicating between Smoothieware and # pipette's onboard EEPROM. To avoid, turn off both plunger motors self.disengage_axis('BC') self.delay(CURRENT_CHANGE_DELAY) # data is read/written as strings of HEX characters # to avoid firmware weirdness in how it parses GCode arguments byte_string = _byte_array_to_hex_string( bytearray(data_string.encode())) command = gcode + mount + byte_string log.debug("_write_to_pipette: {}".format(command)) self._send_command(command)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def move(self, target, home_flagged_axes=False): ''' Move to the `target` Smoothieware coordinate, along any of the size axes, XYZABC. target: dict dict setting the coordinate that Smoothieware will be at when `move()` returns. `target` keys are the axis in upper-case, and the values are the coordinate in millimeters (float) home_flagged_axes: boolean (default=False) If set to `True`, each axis included within the target coordinate may be homed before moving, determined by Smoothieware's internal homing-status flags (`True` means it has already homed). All axes' flags are set to `False` by Smoothieware under three conditions: 1) Smoothieware boots or resets, 2) if a HALT gcode or signal is sent, or 3) a homing/limitswitch error occured. ''' from numpy import isclose self.run_flag.wait() def valid_movement(coords, axis): return not ( (axis in DISABLE_AXES) or (coords is None) or isclose(coords, self.position[axis]) ) def create_coords_list(coords_dict): return [ axis + str(round(coords, GCODE_ROUNDING_PRECISION)) for axis, coords in sorted(coords_dict.items()) if valid_movement(coords, axis) ] backlash_target = target.copy() backlash_target.update({ axis: value + PLUNGER_BACKLASH_MM for axis, value in sorted(target.items()) if axis in 'BC' and self.position[axis] < value }) target_coords = create_coords_list(target) backlash_coords = create_coords_list(backlash_target) if target_coords: non_moving_axes = ''.join([ ax for ax in AXES if ax not in target.keys() ]) self.dwell_axes(non_moving_axes) self.activate_axes(target.keys()) # include the current-setting gcodes within the moving gcode string # to reduce latency, since we're setting current so much command = self._generate_current_command() if backlash_coords != target_coords: command += ' ' + GCODES['MOVE'] + ''.join(backlash_coords) command += ' ' + GCODES['MOVE'] + ''.join(target_coords) try: for axis in target.keys(): self.engaged_axes[axis] = True if home_flagged_axes: self.home_flagged_axes(''.join(list(target.keys()))) log.debug("move: {}".format(command)) # TODO (andy) a movement's timeout should be calculated by # how long the movement is expected to take. A default timeout # of 30 seconds prevents any movements that take longer self._send_command(command, timeout=DEFAULT_MOVEMENT_TIMEOUT) finally: # dwell pipette motors because they get hot plunger_axis_moved = ''.join(set('BC') & set(target.keys())) if plunger_axis_moved: self.dwell_axes(plunger_axis_moved) self._set_saved_current() self._update_position(target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fast_home(self, axis, safety_margin): ''' home after a controlled motor stall Given a known distance we have just stalled along an axis, move that distance away from the homing switch. Then finish with home. ''' # move some mm distance away from the target axes endstop switch(es) destination = { ax: self.homed_position.get(ax) - abs(safety_margin) for ax in axis.upper() } # there is a chance the axis will hit it's home switch too soon # if this happens, catch the error and continue with homing afterwards try: self.move(destination) except SmoothieError: pass # then home once we're closer to the endstop(s) disabled = ''.join([ax for ax in AXES if ax not in axis.upper()]) return self.home(axis=axis, disabled=disabled)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def unstick_axes(self, axes, distance=None, speed=None): ''' The plunger axes on OT2 can build up static friction over time and when it's cold. To get over this, the robot can move that plunger at normal current and a very slow speed to increase the torque, removing the static friction axes: String containing each axis to be moved. Ex: 'BC' or 'ZABC' distance: Distance to travel in millimeters (default is 1mm) speed: Millimeters-per-second to travel to travel at (default is 1mm/sec) ''' for ax in axes: if ax not in AXES: raise ValueError('Unknown axes: {}'.format(axes)) if distance is None: distance = UNSTICK_DISTANCE if speed is None: speed = UNSTICK_SPEED self.push_active_current() self.set_active_current({ ax: self._config.high_current[ax] for ax in axes }) self.push_axis_max_speed() self.set_axis_max_speed({ax: speed for ax in axes}) # only need to request switch state once state_of_switches = {ax: False for ax in AXES} if not self.simulating: state_of_switches = self.switch_state # incase axes is pressing endstop, home it slowly instead of moving homing_axes = ''.join([ax for ax in axes if state_of_switches[ax]]) moving_axes = { ax: self.position[ax] - distance # retract for ax in axes if (not state_of_switches[ax]) and (ax not in homing_axes) } try: if moving_axes: self.move(moving_axes) if homing_axes: self.home(homing_axes) finally: self.pop_active_current() self.pop_axis_max_speed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill(self): """ In order to terminate Smoothie motion immediately (including interrupting a command in progress, we set the reset pin low and then back to high, then call `_setup` method to send the RESET_FROM_ERROR Smoothie code to return Smoothie to a normal waiting state and reset any other state needed for the driver. """
log.debug("kill") self._smoothie_hard_halt() self._reset_from_error() self._setup()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def home_flagged_axes(self, axes_string): ''' Given a list of axes to check, this method will home each axis if Smoothieware's internal flag sets it as needing to be homed ''' axes_that_need_to_home = [ axis for axis, already_homed in self.homed_flags.items() if (not already_homed) and (axis in axes_string) ] if axes_that_need_to_home: axes_string = ''.join(axes_that_need_to_home) self.home(axes_string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def update_firmware(self, filename: str, loop: asyncio.AbstractEventLoop = None, explicit_modeset: bool = True) -> str: """ Program the smoothie board with a given hex file. If explicit_modeset is True (default), explicitly place the smoothie in programming mode. If explicit_modeset is False, assume the smoothie is already in programming mode. """
# ensure there is a reference to the port if self.simulating: return 'Did nothing (simulating)' smoothie_update._ensure_programmer_executable() if not self.is_connected(): self._connect_to_port() # get port name port = self._connection.port if explicit_modeset: # set smoothieware into programming mode self._smoothie_programming_mode() # close the port so other application can access it self._connection.close() # run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format( filename, port, self._config.serial_speed) kwargs: Dict[str, Any] = {'stdout': asyncio.subprocess.PIPE} if loop: kwargs['loop'] = loop proc = await asyncio.create_subprocess_shell( update_cmd, **kwargs) rd: bytes = await proc.stdout.read() # type: ignore res = rd.decode().strip() await proc.communicate() # re-open the port self._connection.open() # reset smoothieware self._smoothie_reset() # run setup gcodes self._setup() return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_new_labware(container_name): """ Load a labware in the new schema into a placeable. :raises KeyError: If the labware name is not found """
defn = new_labware.load_definition_by_name(container_name) labware_id = defn['otId'] saved_offset = _look_up_offsets(labware_id) container = Container() log.info(f"Container name {container_name}") container.properties['type'] = container_name container.properties['otId'] = labware_id format = defn['parameters']['format'] container._coordinates = Vector(defn['cornerOffsetFromSlot']) for well_name in itertools.chain(*defn['ordering']): well_obj, well_pos = _load_new_well( defn['wells'][well_name], saved_offset, format) container.add(well_obj, well_name, well_pos) return container
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_yaml(cls, config, compact=False, indent=2, level=0): """Convert HOCON input into a YAML output :return: YAML string representation :type return: basestring """
lines = "" if isinstance(config, ConfigTree): if len(config) > 0: if level > 0: lines += '\n' bet_lines = [] for key, item in config.items(): bet_lines.append('{indent}{key}: {value}'.format( indent=''.rjust(level * indent, ' '), key=key.strip('"'), # for dotted keys enclosed with "" to not be interpreted as nested key, value=cls.to_yaml(item, compact, indent, level + 1)) ) lines += '\n'.join(bet_lines) elif isinstance(config, list): config_list = [line for line in config if line is not None] if len(config_list) == 0: lines += '[]' else: lines += '\n' bet_lines = [] for item in config_list: bet_lines.append('{indent}- {value}'.format(indent=''.rjust(level * indent, ' '), value=cls.to_yaml(item, compact, indent, level + 1))) lines += '\n'.join(bet_lines) elif isinstance(config, basestring): # if it contains a \n then it's multiline lines = config.split('\n') if len(lines) == 1: lines = config else: lines = '|\n' + '\n'.join([line.rjust(level * indent, ' ') for line in lines]) elif config is None or isinstance(config, NoneValue): lines = 'null' elif config is True: lines = 'true' elif config is False: lines = 'false' else: lines = str(config) return lines