idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
9,100
def load_labware_by_name ( self , labware_name : str , location : types . DeckLocation , label : str = None ) -> Labware : labware = load ( labware_name , self . _deck_layout . position_for ( location ) , label ) return self . load_labware ( labware , location )
A convenience function to specify a piece of labware by name .
9,101
def load_instrument ( self , instrument_name : str , mount : Union [ types . Mount , str ] , tip_racks : List [ Labware ] = None , replace : bool = False ) -> 'InstrumentContext' : if isinstance ( mount , str ) : try : checked_mount = types . Mount [ mount . upper ( ) ] except KeyError : raise ValueError ( "If mount is specified as a string, it should be either" "'left' or 'right' (ignoring capitalization, which the" " system strips), not {}" . format ( mount ) ) elif isinstance ( mount , types . Mount ) : checked_mount = mount else : raise TypeError ( "mount should be either an instance of opentrons.types.Mount" " or a string, but is {}." . format ( mount ) ) self . _log . info ( "Trying to load {} on {} mount" . format ( instrument_name , checked_mount . name . lower ( ) ) ) instr = self . _instruments [ checked_mount ] if instr and not replace : raise RuntimeError ( "Instrument already present in {} mount: {}" . format ( checked_mount . name . lower ( ) , instr . name ) ) attached = { att_mount : instr . get ( 'name' , None ) for att_mount , instr in self . _hw_manager . hardware . attached_instruments . items ( ) } attached [ checked_mount ] = instrument_name self . _log . debug ( "cache instruments expectation: {}" . format ( attached ) ) self . _hw_manager . hardware . cache_instruments ( attached ) new_instr = InstrumentContext ( ctx = self , hardware_mgr = self . _hw_manager , mount = checked_mount , tip_racks = tip_racks , log_parent = self . _log ) self . _instruments [ checked_mount ] = new_instr self . _log . info ( "Instrument {} loaded" . format ( new_instr ) ) return new_instr
Load a specific instrument required by the protocol .
9,102
def loaded_instruments ( self ) -> Dict [ str , Optional [ 'InstrumentContext' ] ] : return { mount . name . lower ( ) : instr for mount , instr in self . _instruments . items ( ) }
Get the instruments that have been loaded into the protocol .
9,103
def delay ( self , seconds = 0 , minutes = 0 , msg = None ) : delay_time = seconds + minutes * 60 self . _hw_manager . hardware . delay ( delay_time )
Delay protocol execution for a specific amount of time .
9,104
def home ( self ) : self . _log . debug ( "home" ) self . _location_cache = None self . _hw_manager . hardware . home ( )
Homes the robot .
9,105
def blow_out ( self , location : Union [ types . Location , Well ] = None ) -> 'InstrumentContext' : if location is None : if not self . _ctx . location_cache : raise RuntimeError ( 'No valid current location cache present' ) else : location = self . _ctx . location_cache . labware if isinstance ( location , Well ) : if location . parent . is_tiprack : self . _log . warning ( 'Blow_out being performed on a tiprack. ' 'Please re-check your code' ) target = location . top ( ) elif isinstance ( location , types . Location ) and not isinstance ( location . labware , Well ) : raise TypeError ( 'location should be a Well or None, but it is {}' . format ( location ) ) else : raise TypeError ( 'location should be a Well or None, but it is {}' . format ( location ) ) self . move_to ( target ) self . _hw_manager . hardware . blow_out ( self . _mount ) return self
Blow liquid out of the tip .
9,106
def touch_tip ( self , location : Well = None , radius : float = 1.0 , v_offset : float = - 1.0 , speed : float = 60.0 ) -> 'InstrumentContext' : if not self . hw_pipette [ 'has_tip' ] : raise hc . NoTipAttachedError ( 'Pipette has no tip to touch_tip()' ) if speed > 80.0 : self . _log . warning ( 'Touch tip speed above limit. Setting to 80mm/s' ) speed = 80.0 elif speed < 20.0 : self . _log . warning ( 'Touch tip speed below min. Setting to 20mm/s' ) speed = 20.0 if location is None : if not self . _ctx . location_cache : raise RuntimeError ( 'No valid current location cache present' ) else : location = self . _ctx . location_cache . labware if isinstance ( location , Well ) : if location . parent . is_tiprack : self . _log . warning ( 'Touch_tip being performed on a tiprack. ' 'Please re-check your code' ) self . move_to ( location . top ( ) ) else : raise TypeError ( 'location should be a Well, but it is {}' . format ( location ) ) offset_pt = types . Point ( 0 , 0 , v_offset ) well_edges = [ location . _from_center_cartesian ( x = radius , y = 0 , z = 1 ) + offset_pt , location . _from_center_cartesian ( x = - radius , y = 0 , z = 1 ) + offset_pt , location . _from_center_cartesian ( x = 0 , y = radius , z = 1 ) + offset_pt , location . _from_center_cartesian ( x = 0 , y = - radius , z = 1 ) + offset_pt ] for edge in well_edges : self . _hw_manager . hardware . move_to ( self . _mount , edge , speed ) return self
Touch the pipette tip to the sides of a well with the intent of removing left - over droplets
9,107
def air_gap ( self , volume : float = None , height : float = None ) -> 'InstrumentContext' : if not self . hw_pipette [ 'has_tip' ] : raise hc . NoTipAttachedError ( 'Pipette has no tip. Aborting air_gap' ) if height is None : height = 5 loc = self . _ctx . location_cache if not loc or not isinstance ( loc . labware , Well ) : raise RuntimeError ( 'No previous Well cached to perform air gap' ) target = loc . labware . top ( height ) self . move_to ( target ) self . aspirate ( volume ) return self
Pull air into the pipette current tip at the current location
9,108
def return_tip ( self ) -> 'InstrumentContext' : if not self . hw_pipette [ 'has_tip' ] : self . _log . warning ( 'Pipette has no tip to return' ) loc = self . _last_tip_picked_up_from if not isinstance ( loc , Well ) : raise TypeError ( 'Last tip location should be a Well but it is: ' '{}' . format ( loc ) ) bot = loc . bottom ( ) bot = bot . _replace ( point = bot . point . _replace ( z = bot . point . z + 10 ) ) self . drop_tip ( bot ) return self
If a tip is currently attached to the pipette then it will return the tip to it s location in the tiprack .
9,109
def pick_up_tip ( self , location : Union [ types . Location , Well ] = None , presses : int = 3 , increment : float = 1.0 ) -> 'InstrumentContext' : num_channels = self . channels def _select_tiprack_from_list ( tip_racks ) -> Tuple [ Labware , Well ] : try : tr = tip_racks [ 0 ] except IndexError : raise OutOfTipsError next_tip = tr . next_tip ( num_channels ) if next_tip : return tr , next_tip else : return _select_tiprack_from_list ( tip_racks [ 1 : ] ) if location and isinstance ( location , types . Location ) : if isinstance ( location . labware , Labware ) : tiprack = location . labware target : Well = tiprack . next_tip ( num_channels ) if not target : raise OutOfTipsError elif isinstance ( location . labware , Well ) : tiprack = location . labware . parent target = location . labware elif location and isinstance ( location , Well ) : tiprack = location . parent target = location elif not location : tiprack , target = _select_tiprack_from_list ( self . tip_racks ) else : raise TypeError ( "If specified, location should be an instance of " "types.Location (e.g. the return value from " "tiprack.wells()[0].top()) or a Well (e.g. tiprack.wells()[0]." " However, it is a {}" . format ( location ) ) assert tiprack . is_tiprack , "{} is not a tiprack" . format ( str ( tiprack ) ) self . move_to ( target . top ( ) ) self . _hw_manager . hardware . pick_up_tip ( self . _mount , tiprack . tip_length , presses , increment ) tiprack . use_tips ( target , num_channels ) self . _last_tip_picked_up_from = target return self
Pick up a tip for the pipette to run liquid - handling commands with
9,110
def drop_tip ( self , location : Union [ types . Location , Well ] = None ) -> 'InstrumentContext' : if location and isinstance ( location , types . Location ) : if isinstance ( location . labware , Well ) : target = location else : raise TypeError ( "If a location is specified as a types.Location (for " "instance, as the result of a call to " "tiprack.wells()[0].top()) it must be a location " "relative to a well, since that is where a tip is " "dropped. The passed location, however, is in " "reference to {}" . format ( location . labware ) ) elif location and isinstance ( location , Well ) : if 'fixedTrash' in quirks_from_any_parent ( location ) : target = location . top ( ) else : bot = location . bottom ( ) target = bot . _replace ( point = bot . point . _replace ( z = bot . point . z + 10 ) ) elif not location : target = self . trash_container . wells ( ) [ 0 ] . top ( ) else : raise TypeError ( "If specified, location should be an instance of " "types.Location (e.g. the return value from " "tiprack.wells()[0].top()) or a Well (e.g. tiprack.wells()[0]." " However, it is a {}" . format ( location ) ) self . move_to ( target ) self . _hw_manager . hardware . drop_tip ( self . _mount ) self . _last_tip_picked_up_from = None return self
Drop the current tip .
9,111
def home ( self ) -> 'InstrumentContext' : def home_dummy ( mount ) : pass cmds . do_publish ( self . broker , cmds . home , home_dummy , 'before' , None , None , self . _mount . name . lower ( ) ) self . _hw_manager . hardware . home_z ( self . _mount ) self . _hw_manager . hardware . home_plunger ( self . _mount ) cmds . do_publish ( self . broker , cmds . home , home_dummy , 'after' , self , None , self . _mount . name . lower ( ) ) return self
Home the robot .
9,112
def distribute ( self , volume : float , source : Well , dest : List [ Well ] , * args , ** kwargs ) -> 'InstrumentContext' : self . _log . debug ( "Distributing {} from {} to {}" . format ( volume , source , dest ) ) kwargs [ 'mode' ] = 'distribute' kwargs [ 'disposal_volume' ] = kwargs . get ( 'disposal_vol' , self . min_volume ) return self . transfer ( volume , source , dest , ** kwargs )
Move a volume of liquid from one source to multiple destinations .
9,113
def move_to ( self , location : types . Location , force_direct : bool = False , minimum_z_height : float = None ) -> 'InstrumentContext' : if self . _ctx . location_cache : from_lw = self . _ctx . location_cache . labware else : from_lw = None from_center = 'centerMultichannelOnWells' in quirks_from_any_parent ( from_lw ) cp_override = CriticalPoint . XY_CENTER if from_center else None from_loc = types . Location ( self . _hw_manager . hardware . gantry_position ( self . _mount , critical_point = cp_override ) , from_lw ) moves = geometry . plan_moves ( from_loc , location , self . _ctx . deck , force_direct = force_direct , minimum_z_height = minimum_z_height ) self . _log . debug ( "move_to: {}->{} via:\n\t{}" . format ( from_loc , location , moves ) ) try : for move in moves : self . _hw_manager . hardware . move_to ( self . _mount , move [ 0 ] , critical_point = move [ 1 ] ) except Exception : self . _ctx . location_cache = None raise else : self . _ctx . location_cache = location return self
Move the instrument .
9,114
def type ( self ) -> str : model = self . name if 'single' in model : return 'single' elif 'multi' in model : return 'multi' else : raise RuntimeError ( "Bad pipette model name: {}" . format ( model ) )
One of single or multi .
9,115
def hw_pipette ( self ) -> Dict [ str , Any ] : pipette = self . _hw_manager . hardware . attached_instruments [ self . _mount ] if pipette is None : raise types . PipetteNotAttachedError return pipette
View the information returned by the hardware API directly .
9,116
def load_labware ( self , labware : Labware ) -> Labware : if labware . magdeck_engage_height is None : MODULE_LOG . warning ( "This labware ({}) is not explicitly compatible with the" " Magnetic Module. You will have to specify a height when" " calling engage()." ) return super ( ) . load_labware ( labware )
Load labware onto a Magnetic Module checking if it is compatible
9,117
def engage ( self , height : float = None , offset : float = None ) : if height : dist = height elif self . labware and self . labware . magdeck_engage_height is not None : dist = self . labware . magdeck_engage_height if offset : dist += offset else : raise ValueError ( "Currently loaded labware {} does not have a known engage " "height; please specify explicitly with the height param" . format ( self . labware ) ) self . _module . engage ( dist )
Raise the Magnetic Module s magnets .
9,118
def open ( self ) : self . _geometry . lid_status = self . _module . open ( ) self . _ctx . deck . recalculate_high_z ( ) return self . _geometry . lid_status
Opens the lid
9,119
def close ( self ) : self . _geometry . lid_status = self . _module . close ( ) self . _ctx . deck . recalculate_high_z ( ) return self . _geometry . lid_status
Closes the lid
9,120
def set_temperature ( self , temp : float , hold_time : float = None , ramp_rate : float = None ) : return self . _module . set_temperature ( temp = temp , hold_time = hold_time , ramp_rate = ramp_rate )
Set the target temperature in C .
9,121
async def _port_poll ( is_old_bootloader , ports_before_switch = None ) : new_port = '' while not new_port : if is_old_bootloader : new_port = await _port_on_mode_switch ( ports_before_switch ) else : ports = await _discover_ports ( ) if ports : discovered_ports = list ( filter ( lambda x : x . endswith ( 'bootloader' ) , ports ) ) if len ( discovered_ports ) == 1 : new_port = '/dev/modules/{}' . format ( discovered_ports [ 0 ] ) await asyncio . sleep ( 0.05 ) return new_port
Checks for the bootloader port
9,122
def critical_point ( self , cp_override : CriticalPoint = None ) -> Point : if not self . has_tip or cp_override == CriticalPoint . NOZZLE : cp_type = CriticalPoint . NOZZLE tip_length = 0.0 else : cp_type = CriticalPoint . TIP tip_length = self . current_tip_length if cp_override == CriticalPoint . XY_CENTER : mod_offset_xy = [ 0 , 0 , self . config . model_offset [ 2 ] ] cp_type = CriticalPoint . XY_CENTER elif cp_override == CriticalPoint . FRONT_NOZZLE : mod_offset_xy = [ 0 , - self . config . model_offset [ 1 ] , self . config . model_offset [ 2 ] ] cp_type = CriticalPoint . FRONT_NOZZLE else : mod_offset_xy = self . config . model_offset mod_and_tip = Point ( mod_offset_xy [ 0 ] , mod_offset_xy [ 1 ] , mod_offset_xy [ 2 ] - tip_length ) cp = mod_and_tip + self . _instrument_offset . _replace ( z = 0 ) if self . _log . isEnabledFor ( logging . DEBUG ) : mo = 'model offset: {} + ' . format ( self . config . model_offset ) if cp_type != CriticalPoint . XY_CENTER else '' info_str = 'cp: {}{}: {}=({}instr offset xy: {}' . format ( cp_type , '(from override)' if cp_override else '' , cp , mo , self . _instrument_offset . _replace ( z = 0 ) ) if cp_type == CriticalPoint . TIP : info_str += '- current_tip_length: {}=(true tip length: {}' ' - inst z: {}) (z only)' . format ( self . current_tip_length , self . _current_tip_length , self . _instrument_offset . z ) info_str += ')' self . _log . debug ( info_str ) return cp
The vector from the pipette s origin to its critical point . The critical point for a pipette is the end of the nozzle if no tip is attached or the end of the tip if a tip is attached .
9,123
def connect_to_robot ( ) : print ( ) import optparse from opentrons import robot print ( 'Connecting to robot...' ) parser = optparse . OptionParser ( usage = 'usage: %prog [options] ' ) parser . add_option ( "-p" , "--p" , dest = "port" , default = '' , type = 'str' , help = 'serial port of the smoothie' ) options , _ = parser . parse_args ( args = None , values = None ) if options . port : robot . connect ( options . port ) else : robot . connect ( ) return robot
Connect over Serial to the Smoothieware motor driver
9,124
def write_identifiers ( robot , mount , new_id , new_model ) : robot . _driver . write_pipette_id ( mount , new_id ) read_id = robot . _driver . read_pipette_id ( mount ) _assert_the_same ( new_id , read_id ) robot . _driver . write_pipette_model ( mount , new_model ) read_model = robot . _driver . read_pipette_model ( mount ) _assert_the_same ( new_model , read_model )
Send a bytearray to the specified mount so that Smoothieware can save the bytes to the pipette s memory
9,125
def _user_submitted_barcode ( max_length ) : barcode = input ( 'BUTTON + SCAN: ' ) . strip ( ) if len ( barcode ) > max_length : raise Exception ( BAD_BARCODE_MESSAGE . format ( barcode ) ) barcode = barcode [ barcode . index ( 'P' ) : ] barcode = barcode . split ( '\r' ) [ 0 ] . split ( '\n' ) [ 0 ] return barcode
User can enter a serial number as a string of HEX values Length of byte array must equal num
9,126
def set_mounted ( unitname : str , mounted : bool , swallow_exc : bool = False ) : try : if mounted : LOG . info ( f"Starting {unitname}" ) interface ( ) . StartUnit ( unitname , 'replace' ) LOG . info ( f"Started {unitname}" ) else : LOG . info ( f"Stopping {unitname}" ) interface ( ) . StopUnit ( unitname , 'replace' ) LOG . info ( f"Stopped {unitname}" ) except Exception : LOG . info ( f"Exception {'starting' if mounted else 'stopping'} {unitname}" ) if not swallow_exc : raise
Mount or unmount a unit .
9,127
def require_session ( handler ) : @ functools . wraps ( handler ) async def decorated ( request : web . Request ) -> web . Response : request_session_token = request . match_info [ 'session' ] session = session_from_request ( request ) if not session or request_session_token != session . token : LOG . warning ( f"request for invalid session {request_session_token}" ) return web . json_response ( data = { 'error' : 'bad-token' , 'message' : f'No such session {request_session_token}' } , status = 404 ) return await handler ( request , session ) return decorated
Decorator to ensure a session is properly in the request
9,128
def get_version ( path ) -> str : if path and os . path . exists ( path ) : with open ( path ) as pkg : package_dict = json . load ( pkg ) version = package_dict . get ( 'version' ) else : version = 'not available' return version
Reads the version field from a package file
9,129
def calculate_tip_probe_hotspots ( tip_length : float , tip_probe_settings : tip_probe_config ) -> List [ HotSpot ] : size_x , size_y , size_z = tip_probe_settings . dimensions rel_x_start = ( size_x / 2 ) + tip_probe_settings . switch_clearance rel_y_start = ( size_y / 2 ) + tip_probe_settings . switch_clearance nozzle_safe_z = round ( ( size_z - tip_length ) + tip_probe_settings . z_clearance . normal , 3 ) z_start = max ( tip_probe_settings . z_clearance . deck , nozzle_safe_z ) switch_offset = tip_probe_settings . switch_offset neg_x = HotSpot ( 'x' , - rel_x_start , switch_offset [ 0 ] , z_start , size_x ) pos_x = HotSpot ( 'x' , rel_x_start , switch_offset [ 0 ] , z_start , - size_x ) neg_y = HotSpot ( 'y' , switch_offset [ 1 ] , - rel_y_start , z_start , size_y ) pos_y = HotSpot ( 'y' , switch_offset [ 1 ] , rel_y_start , z_start , - size_y ) z = HotSpot ( 'z' , 0 , switch_offset [ 2 ] , tip_probe_settings . center [ 2 ] + tip_probe_settings . z_clearance . start , - size_z ) return [ neg_x , pos_x , neg_y , pos_y , z ]
Generate a list of tuples describing motions for doing the xy part of tip probe based on the config s description of the tip probe box .
9,130
def init ( loop = None , hardware : 'HardwareAPILike' = None ) : app = web . Application ( loop = loop , middlewares = [ error_middleware ] ) if hardware : checked_hardware = hardware else : checked_hardware = opentrons . hardware app [ 'com.opentrons.hardware' ] = checked_hardware app [ 'com.opentrons.rpc' ] = RPCServer ( app , MainRouter ( checked_hardware ) ) app [ 'com.opentrons.http' ] = HTTPServer ( app , CONFIG [ 'log_dir' ] ) return app
Builds an application and sets up RPC and HTTP servers with it .
9,131
def run ( hostname = None , port = None , path = None , loop = None ) : if path : log . debug ( "Starting Opentrons server application on {}" . format ( path ) ) hostname , port = None , None else : log . debug ( "Starting Opentrons server application on {}:{}" . format ( hostname , port ) ) path = None web . run_app ( init ( loop ) , host = hostname , port = port , path = path )
The arguments are not all optional . Either a path or hostname + port should be specified ; you have to specify one .
9,132
def discover ( ) -> List [ Tuple [ str , str ] ] : if IS_ROBOT and os . path . isdir ( '/dev/modules' ) : devices = os . listdir ( '/dev/modules' ) else : devices = [ ] discovered_modules = [ ] module_port_regex = re . compile ( '|' . join ( MODULE_TYPES . keys ( ) ) , re . I ) for port in devices : match = module_port_regex . search ( port ) if match : name = match . group ( ) . lower ( ) if name not in MODULE_TYPES : log . warning ( "Unexpected module connected: {} on {}" . format ( name , port ) ) continue absolute_port = '/dev/modules/{}' . format ( port ) discovered_modules . append ( ( absolute_port , name ) ) log . info ( 'Discovered modules: {}' . format ( discovered_modules ) ) return discovered_modules
Scan for connected modules and instantiate handler classes
9,133
async def update_firmware ( module : AbstractModule , firmware_file : str , loop : Optional [ asyncio . AbstractEventLoop ] ) -> AbstractModule : simulating = module . is_simulated cls = type ( module ) old_port = module . port flash_port = await module . prep_for_update ( ) callback = module . interrupt_callback del module after_port , results = await update . update_firmware ( flash_port , firmware_file , loop ) await asyncio . sleep ( 1.0 ) new_port = after_port or old_port if not results [ 0 ] : raise UpdateError ( results [ 1 ] ) return await cls . build ( port = new_port , interrupt_callback = callback , simulating = simulating )
Update a module .
9,134
def move ( self , pose_tree , x = None , y = None , z = None , home_flagged_axes = True ) : def defaults ( _x , _y , _z ) : _x = _x if x is not None else 0 _y = _y if y is not None else 0 _z = _z if z is not None else 0 return _x , _y , _z dst_x , dst_y , dst_z = change_base ( pose_tree , src = self . _src , dst = self . _dst , point = Point ( * defaults ( x , y , z ) ) ) driver_target = { } if 'x' in self . _axis_mapping : assert x is not None , "Value must be set for each axis mapped" driver_target [ self . _axis_mapping [ 'x' ] ] = dst_x if 'y' in self . _axis_mapping : assert y is not None , "Value must be set for each axis mapped" driver_target [ self . _axis_mapping [ 'y' ] ] = dst_y if 'z' in self . _axis_mapping : assert z is not None , "Value must be set for each axis mapped" driver_target [ self . _axis_mapping [ 'z' ] ] = dst_z self . _driver . move ( driver_target , home_flagged_axes = home_flagged_axes ) return update ( pose_tree , self , Point ( * defaults ( dst_x , dst_y , dst_z ) ) )
Dispatch move command to the driver changing base of x y and z from source coordinate system to destination .
9,135
def validate_update ( filepath : str , progress_callback : Callable [ [ float ] , None ] ) -> Tuple [ str , str ] : filenames = [ ROOTFS_NAME , ROOTFS_HASH_NAME , BOOT_NAME , BOOT_HASH_NAME ] def zip_callback ( progress ) : progress_callback ( progress / 3.0 ) files , sizes = unzip_update ( filepath , zip_callback , filenames , filenames ) def rootfs_hash_callback ( progress ) : progress_callback ( progress / 3.0 + 0.33 ) rootfs = files . get ( ROOTFS_NAME ) assert rootfs rootfs_calc_hash = hash_file ( rootfs , rootfs_hash_callback , file_size = sizes [ ROOTFS_NAME ] ) rootfs_hashfile = files . get ( ROOTFS_HASH_NAME ) assert rootfs_hashfile rootfs_packaged_hash = open ( rootfs_hashfile , 'rb' ) . read ( ) . strip ( ) if rootfs_calc_hash != rootfs_packaged_hash : msg = f"Hash mismatch (rootfs): calculated {rootfs_calc_hash} != " f"packaged {rootfs_packaged_hash}" LOG . error ( msg ) raise HashMismatch ( msg ) def bootfs_hash_callback ( progress ) : progress_callback ( progress / 3.0 + 0.66 ) bootfs = files . get ( BOOT_NAME ) assert bootfs bootfs_calc_hash = hash_file ( bootfs , bootfs_hash_callback , file_size = sizes [ BOOT_NAME ] ) bootfs_hashfile = files . get ( BOOT_HASH_NAME ) assert bootfs_hashfile bootfs_packaged_hash = open ( bootfs_hashfile , 'rb' ) . read ( ) . strip ( ) if bootfs_calc_hash != bootfs_packaged_hash : msg = f"Hash mismatch (bootfs): calculated {bootfs_calc_hash} != " f"packged {bootfs_packaged_hash}" LOG . error ( msg ) raise HashMismatch ( msg ) return rootfs , bootfs
Like otupdate . buildroot . file_actions . validate_update but moreso
9,136
def patch_connection_file_paths ( connection : str ) -> str : new_conn_lines = [ ] for line in connection . split ( '\n' ) : if '=' in line : parts = line . split ( '=' ) path_matches = re . search ( '/mnt/data/resin-data/[0-9]+/(.*)' , parts [ 1 ] ) if path_matches : new_path = f'/data/{path_matches.group(1)}' new_conn_lines . append ( '=' . join ( [ parts [ 0 ] , new_path ] ) ) LOG . info ( f"migrate_connection_file: {parts[0]}: " f"{parts[1]}->{new_path}" ) continue new_conn_lines . append ( line ) return '\n' . join ( new_conn_lines )
Patch any paths in a connection to remove the balena host paths
9,137
def migrate ( ignore : Sequence [ str ] , name : str ) : try : with mount_data_partition ( ) as datamount : migrate_data ( ignore , datamount , DATA_DIR_NAME ) migrate_connections ( datamount ) migrate_hostname ( datamount , name ) except Exception : LOG . exception ( "Exception during data migration" ) raise
Copy everything in the app data to the root of the new partition
9,138
def migrate_data ( ignore : Sequence [ str ] , new_data_path : str , old_data_path : str ) : dest_data = os . path . join ( new_data_path , 'data' ) LOG . info ( f"migrate_data: copying {old_data_path} to {dest_data}" ) os . makedirs ( dest_data , exist_ok = True ) with os . scandir ( old_data_path ) as scanner : for entry in scanner : if entry . name in ignore : LOG . info ( f"migrate_data: ignoring {entry.name}" ) continue src = os . path . join ( old_data_path , entry . name ) dest = os . path . join ( dest_data , entry . name ) if os . path . exists ( dest ) : LOG . info ( f"migrate_data: removing dest tree {dest}" ) shutil . rmtree ( dest , ignore_errors = True ) if entry . is_dir ( ) : LOG . info ( f"migrate_data: copying tree {src}->{dest}" ) shutil . copytree ( src , dest , symlinks = True , ignore = migrate_files_to_ignore ) else : LOG . info ( f"migrate_data: copying file {src}->{dest}" ) shutil . copy2 ( src , dest )
Copy everything in the app data to the root of the main data part
9,139
def migrate_system_connections ( src_sc : str , dest_sc : str ) -> bool : found = False LOG . info ( f"migrate_system_connections: checking {dest_sc}" ) os . makedirs ( dest_sc , exist_ok = True ) with os . scandir ( src_sc ) as scanner : for entry in scanner : if entry . name . endswith ( '.ignore' ) : continue if entry . name == 'static-eth0' : continue if entry . name . startswith ( '._' ) : continue patched = patch_connection_file_paths ( open ( os . path . join ( src_sc , entry . name ) , 'r' ) . read ( ) ) open ( os . path . join ( dest_sc , entry . name ) , 'w' ) . write ( patched ) LOG . info ( f"migrate_connections: migrated {entry.name}" ) found = True return found
Migrate the contents of a system - connections dir
9,140
def migrate_connections ( new_data_path : str ) : dest_connections = os . path . join ( new_data_path , 'lib' , 'NetworkManager' , 'system-connections' ) os . makedirs ( dest_connections , exist_ok = True ) with mount_state_partition ( ) as state_path : src_connections = os . path . join ( state_path , 'root-overlay' , 'etc' , 'NetworkManager' , 'system-connections' ) LOG . info ( f"migrate_connections: moving nmcli connections from" f" {src_connections} to {dest_connections}" ) found = migrate_system_connections ( src_connections , dest_connections ) if found : return LOG . info ( "migrate_connections: No connections found in state, checking boot" ) with mount_boot_partition ( ) as boot_path : src_connections = os . path . join ( boot_path , 'system-connections' ) LOG . info ( f"migrate_connections: moving nmcli connections from" f" {src_connections} to {dest_connections}" ) found = migrate_system_connections ( src_connections , dest_connections ) if not found : LOG . info ( "migrate_connections: No connections found in boot" )
Migrate wifi connection files to new locations and patch them
9,141
def migrate_hostname ( dest_data : str , name : str ) : if name . startswith ( 'opentrons-' ) : name = name [ len ( 'opentrons-' ) : ] LOG . info ( f"migrate_hostname: writing name {name} to {dest_data}/hostname," f" {dest_data}/machine-info, {dest_data}/serial" ) with open ( os . path . join ( dest_data , 'hostname' ) , 'w' ) as hn : hn . write ( name + "\n" ) with open ( os . path . join ( dest_data , 'machine-info' ) , 'w' ) as mi : mi . write ( f'PRETTY_HOSTNAME={name}\nDEPLOYMENT=production\n' ) with open ( os . path . join ( dest_data , 'serial' ) , 'w' ) as ser : ser . write ( name )
Write the machine name to a couple different places
9,142
def infer_config_base_dir ( ) -> Path : if 'OT_API_CONFIG_DIR' in os . environ : return Path ( os . environ [ 'OT_API_CONFIG_DIR' ] ) elif IS_ROBOT : return Path ( '/data' ) else : search = ( Path . cwd ( ) , Path . home ( ) / '.opentrons' ) for path in search : if ( path / _CONFIG_FILENAME ) . exists ( ) : return path else : return search [ - 1 ]
Return the directory to store data in .
9,143
def load_and_migrate ( ) -> Dict [ str , Path ] : if IS_ROBOT : _migrate_robot ( ) base = infer_config_base_dir ( ) base . mkdir ( parents = True , exist_ok = True ) index = _load_with_overrides ( base ) return _ensure_paths_and_types ( index )
Ensure the settings directory tree is properly configured .
9,144
def _load_with_overrides ( base ) -> Dict [ str , str ] : should_write = False overrides = _get_environ_overrides ( ) try : index = json . load ( ( base / _CONFIG_FILENAME ) . open ( ) ) except ( OSError , json . JSONDecodeError ) as e : sys . stderr . write ( "Error loading config from {}: {}\nRewriting...\n" . format ( str ( base ) , e ) ) should_write = True index = generate_config_index ( overrides ) for key in CONFIG_ELEMENTS : if key . name not in index : sys . stderr . write ( f"New config index key {key.name}={key.default}" "\nRewriting...\n" ) if key . kind in ( ConfigElementType . DIR , ConfigElementType . FILE ) : index [ key . name ] = base / key . default else : index [ key . name ] = key . default should_write = True if should_write : try : write_config ( index , path = base ) except Exception as e : sys . stderr . write ( "Error writing config to {}: {}\nProceeding memory-only\n" . format ( str ( base ) , e ) ) index . update ( overrides ) return index
Load an config or write its defaults
9,145
def _ensure_paths_and_types ( index : Dict [ str , str ] ) -> Dict [ str , Path ] : configs_by_name = { ce . name : ce for ce in CONFIG_ELEMENTS } correct_types : Dict [ str , Path ] = { } for key , item in index . items ( ) : if key not in configs_by_name : continue if configs_by_name [ key ] . kind == ConfigElementType . FILE : it = Path ( item ) it . parent . mkdir ( parents = True , exist_ok = True ) correct_types [ key ] = it elif configs_by_name [ key ] . kind == ConfigElementType . DIR : it = Path ( item ) it . mkdir ( parents = True , exist_ok = True ) correct_types [ key ] = it else : raise RuntimeError ( f"unhandled kind in ConfigElements: {key}: " f"{configs_by_name[key].kind}" ) return correct_types
Take the direct results of loading the config and make sure the filesystem reflects them .
9,146
def _legacy_index ( ) -> Union [ None , Dict [ str , str ] ] : for index in _LEGACY_INDICES : if index . exists ( ) : try : return json . load ( open ( index ) ) except ( OSError , json . JSONDecodeError ) : return None return None
Try and load an index file from the various places it might exist .
9,147
def _find_most_recent_backup ( normal_path : Optional [ str ] ) -> Optional [ str ] : if normal_path is None : return None if os . path . exists ( normal_path ) : return normal_path dirname , basename = os . path . split ( normal_path ) root , ext = os . path . splitext ( basename ) backups = [ fi for fi in os . listdir ( dirname ) if fi . startswith ( root ) and fi . endswith ( ext ) ] ts_re = re . compile ( r'.*-([0-9]+)' + ext + '$' ) def ts_compare ( filename ) : match = ts_re . match ( filename ) if not match : return - 1 else : return int ( match . group ( 1 ) ) backups_sorted = sorted ( backups , key = ts_compare ) if not backups_sorted : return None return os . path . join ( dirname , backups_sorted [ - 1 ] )
Find the most recent old settings to migrate .
9,148
def generate_config_index ( defaults : Dict [ str , str ] , base_dir = None ) -> Dict [ str , Path ] : base = Path ( base_dir ) if base_dir else infer_config_base_dir ( ) def parse_or_default ( ce : ConfigElement , val : Optional [ str ] ) -> Path : if not val : return base / Path ( ce . default ) else : return Path ( val ) return { ce . name : parse_or_default ( ce , defaults . get ( ce . name ) ) for ce in CONFIG_ELEMENTS }
Determines where existing info can be found in the system and creates a corresponding data dict that can be written to index . json in the baseDataDir .
9,149
def write_config ( config_data : Dict [ str , Path ] , path : Path = None ) : path = Path ( path ) if path else infer_config_base_dir ( ) valid_names = [ ce . name for ce in CONFIG_ELEMENTS ] try : os . makedirs ( path , exist_ok = True ) with ( path / _CONFIG_FILENAME ) . open ( 'w' ) as base_f : json . dump ( { k : str ( v ) for k , v in config_data . items ( ) if k in valid_names } , base_f , indent = 2 ) except OSError as e : sys . stderr . write ( "Config index write to {} failed: {}\n" . format ( path / _CONFIG_FILENAME , e ) )
Save the config file .
9,150
def main ( ) : prompt = input ( ">>> Warning! Running this tool backup and clear any previous " "calibration data. Proceed (y/[n])? " ) if prompt not in [ 'y' , 'Y' , 'yes' ] : print ( 'Exiting--prior configuration data not changed' ) sys . exit ( ) cli = CLITool ( point_set = get_calibration_points ( ) , tip_length = 51.7 ) hardware = cli . hardware backup_configuration_and_reload ( hardware ) if not feature_flags . use_protocol_api_v2 ( ) : hardware . connect ( ) hardware . turn_on_rail_lights ( ) atexit . register ( hardware . turn_off_rail_lights ) else : hardware . set_lights ( rails = True ) cli . home ( ) cli . ui_loop . run ( ) if feature_flags . use_protocol_api_v2 ( ) : hardware . set_lights ( rails = False ) print ( 'Robot config: \n' , cli . _config )
A CLI application for performing factory calibration of an Opentrons robot
9,151
def increase_step ( self ) -> str : if self . _steps_index < len ( self . _steps ) - 1 : self . _steps_index = self . _steps_index + 1 return 'step: {}' . format ( self . current_step ( ) )
Increase the jog resolution without overrunning the list of values
9,152
def decrease_step ( self ) -> str : if self . _steps_index > 0 : self . _steps_index = self . _steps_index - 1 return 'step: {}' . format ( self . current_step ( ) )
Decrease the jog resolution without overrunning the list of values
9,153
def _jog ( self , axis , direction , step ) : jog ( axis , direction , step , self . hardware , self . _current_mount ) self . current_position = self . _position ( ) return 'Jog: {}' . format ( [ axis , str ( direction ) , str ( step ) ] )
Move the pipette on axis in direction by step and update the position tracker
9,154
def home ( self ) -> str : self . hardware . home ( ) self . current_position = self . _position ( ) return 'Homed'
Return the robot to the home position and update the position tracker
9,155
def save_point ( self ) -> str : if self . _current_mount is left : msg = self . save_mount_offset ( ) self . _current_mount = right elif self . _current_mount is types . Mount . LEFT : msg = self . save_mount_offset ( ) self . _current_mount = types . Mount . RIGHT else : pos = self . _position ( ) [ : - 1 ] self . actual_points [ self . _current_point ] = pos log . debug ( "Saving {} for point {}" . format ( pos , self . _current_point ) ) msg = 'saved #{}: {}' . format ( self . _current_point , self . actual_points [ self . _current_point ] ) return msg
Indexes the measured data with the current point as a key and saves the current position once the Enter key is pressed to the actual points vector .
9,156
def save_transform ( self ) -> str : expected = [ self . _expected_points [ p ] [ : 2 ] for p in [ 1 , 2 , 3 ] ] log . debug ( "save_transform expected: {}" . format ( expected ) ) actual = [ self . actual_points [ p ] [ : 2 ] for p in [ 1 , 2 , 3 ] ] log . debug ( "save_transform actual: {}" . format ( actual ) ) flat_matrix = solve ( expected , actual ) log . debug ( "save_transform flat_matrix: {}" . format ( flat_matrix ) ) current_z = self . calibration_matrix [ 2 ] [ 3 ] self . calibration_matrix = add_z ( flat_matrix , current_z ) gantry_calibration = list ( map ( lambda i : list ( i ) , self . calibration_matrix ) ) log . debug ( "save_transform calibration_matrix: {}" . format ( gantry_calibration ) ) self . hardware . update_config ( gantry_calibration = gantry_calibration ) res = str ( self . hardware . config ) return '{}\n{}' . format ( res , save_config ( self . hardware . config ) )
Actual is measured data Expected is based on mechanical drawings of the robot
9,157
def find_config ( prefix : str ) -> str : matches = [ conf for conf in config_models if conf . startswith ( prefix ) ] if not matches : raise KeyError ( 'No match found for prefix {}' . format ( prefix ) ) if prefix in matches : return prefix else : return sorted ( matches ) [ 0 ]
Find the most recent config matching prefix
9,158
def get_attached_instruments ( self , expected : Dict [ types . Mount , str ] ) -> Dict [ types . Mount , Dict [ str , Optional [ str ] ] ] : to_return : Dict [ types . Mount , Dict [ str , Optional [ str ] ] ] = { } for mount in types . Mount : expected_instr = expected . get ( mount , None ) init_instr = self . _attached_instruments . get ( mount , { } ) found_model = init_instr . get ( 'model' , '' ) if expected_instr and found_model and not found_model . startswith ( expected_instr ) : if self . _strict_attached : raise RuntimeError ( 'mount {}: expected instrument {} but got {}' . format ( mount . name , expected_instr , init_instr ) ) else : to_return [ mount ] = { 'model' : find_config ( expected_instr ) , 'id' : None } elif found_model and expected_instr : to_return [ mount ] = init_instr elif found_model : to_return [ mount ] = init_instr elif expected_instr : to_return [ mount ] = { 'model' : find_config ( expected_instr ) , 'id' : None } else : to_return [ mount ] = { 'model' : None , 'id' : None } return to_return
Update the internal cache of attached instruments .
9,159
def _ensure_programmer_executable ( ) : updater_executable = shutil . which ( 'lpc21isp' , mode = os . F_OK ) os . chmod ( updater_executable , 0o777 )
Find the lpc21isp executable and ensure it is executable
9,160
async def restart ( request ) : def wait_and_restart ( ) : log . info ( 'Restarting server' ) sleep ( 1 ) os . system ( 'kill 1' ) Thread ( target = wait_and_restart ) . start ( ) return web . json_response ( { "message" : "restarting" } )
Returns OK then waits approximately 1 second and restarts container
9,161
def get_app ( system_version_file : str = None , config_file_override : str = None , name_override : str = None , loop : asyncio . AbstractEventLoop = None ) -> web . Application : if not system_version_file : system_version_file = BR_BUILTIN_VERSION_FILE version = get_version ( system_version_file ) name = name_override or name_management . get_name ( ) config_obj = config . load ( config_file_override ) LOG . info ( "Setup: " + '\n\t' . join ( [ f'Device name: {name}' , f'Buildroot version: ' f'{version.get("buildroot_version", "unknown")}' , f'\t(from git sha ' f'{version.get("buildroot_sha", "unknown")}' , f'API version: ' f'{version.get("opentrons_api_version", "unknown")}' , f'\t(from git sha ' f'{version.get("opentrons_api_sha", "unknown")}' , f'Update server version: ' f'{version.get("update_server_version", "unknown")}' , f'\t(from git sha ' f'{version.get("update_server_sha", "unknown")}' , f'Smoothie firmware version: TODO' ] ) ) if not loop : loop = asyncio . get_event_loop ( ) app = web . Application ( loop = loop , middlewares = [ log_error_middleware ] ) app [ config . CONFIG_VARNAME ] = config_obj app [ constants . RESTART_LOCK_NAME ] = asyncio . Lock ( ) app [ constants . DEVICE_NAME_VARNAME ] = name app . router . add_routes ( [ web . get ( '/server/update/health' , control . build_health_endpoint ( version ) ) , web . post ( '/server/update/begin' , update . begin ) , web . post ( '/server/update/cancel' , update . cancel ) , web . get ( '/server/update/{session}/status' , update . status ) , web . post ( '/server/update/{session}/file' , update . file_upload ) , web . post ( '/server/update/{session}/commit' , update . commit ) , web . post ( '/server/restart' , control . restart ) , web . get ( '/server/ssh_keys' , ssh_key_management . list_keys ) , web . post ( '/server/ssh_keys' , ssh_key_management . add ) , web . delete ( '/server/ssh_keys/{key_md5}' , ssh_key_management . remove ) , web . post ( '/server/name' , name_management . set_name_endpoint ) , web . get ( '/server/name' , name_management . get_name_endpoint ) , ] ) return app
Build and return the aiohttp . web . Application that runs the server
9,162
async def on_shutdown ( self , app ) : for ws in self . clients . copy ( ) : await ws . close ( code = WSCloseCode . GOING_AWAY , message = 'Server shutdown' ) self . shutdown ( )
Graceful shutdown handler
9,163
async def handler ( self , request ) : def task_done ( future ) : self . tasks . remove ( future ) exception = future . exception ( ) if exception : log . warning ( 'While processing message: {0}\nDetails: {1}' . format ( exception , traceback . format_exc ( ) ) ) client = web . WebSocketResponse ( ) client_id = id ( client ) await client . prepare ( request ) log . info ( 'Opening Websocket {0}' . format ( id ( client ) ) ) log . debug ( 'Tasks: {0}' . format ( self . tasks ) ) log . debug ( 'Clients: {0}' . format ( self . clients ) ) try : log . debug ( 'Sending root info to {0}' . format ( client_id ) ) await client . send_json ( { '$' : { 'type' : CONTROL_MESSAGE , 'monitor' : True } , 'root' : self . call_and_serialize ( lambda : self . root ) , 'type' : self . call_and_serialize ( lambda : type ( self . root ) ) } ) log . debug ( 'Root info sent to {0}' . format ( client_id ) ) except Exception : log . exception ( 'While sending root info to {0}' . format ( client_id ) ) try : self . clients [ client ] = self . send_worker ( client ) async for msg in client : task = self . loop . create_task ( self . process ( msg ) ) task . add_done_callback ( task_done ) self . tasks += [ task ] except Exception : log . exception ( 'While reading from socket:' ) finally : log . info ( 'Closing WebSocket {0}' . format ( id ( client ) ) ) await client . close ( ) del self . clients [ client ] return client
Receives HTTP request and negotiates up to a Websocket session
9,164
def resolve_args ( self , args ) : def resolve ( a ) : if isinstance ( a , dict ) : _id = a . get ( 'i' , None ) return self . objects [ _id ] if _id else a [ 'v' ] if isinstance ( a , ( list , tuple ) ) : return [ resolve ( i ) for i in a ] return a return [ resolve ( a ) for a in args ]
Resolve function call arguments that have object ids into instances of these objects
9,165
async def build_hardware_controller ( cls , config : robot_configs . robot_config = None , port : str = None , loop : asyncio . AbstractEventLoop = None , force : bool = False ) -> 'API' : if None is Controller : raise RuntimeError ( 'The hardware controller may only be instantiated on a robot' ) checked_loop = loop or asyncio . get_event_loop ( ) backend = Controller ( config , checked_loop , force = force ) await backend . connect ( port ) return cls ( backend , config = config , loop = checked_loop )
Build a hardware controller that will actually talk to hardware .
9,166
def build_hardware_simulator ( cls , attached_instruments : Dict [ top_types . Mount , Dict [ str , Optional [ str ] ] ] = None , attached_modules : List [ str ] = None , config : robot_configs . robot_config = None , loop : asyncio . AbstractEventLoop = None , strict_attached_instruments : bool = True ) -> 'API' : if None is attached_instruments : attached_instruments = { } if None is attached_modules : attached_modules = [ ] return cls ( Simulator ( attached_instruments , attached_modules , config , loop , strict_attached_instruments ) , config = config , loop = loop )
Build a simulating hardware controller .
9,167
async def register_callback ( self , cb ) : self . _callbacks . add ( cb ) def unregister ( ) : self . _callbacks . remove ( cb ) return unregister
Allows the caller to register a callback and returns a closure that can be used to unregister the provided callback
9,168
def set_lights ( self , button : bool = None , rails : bool = None ) : self . _backend . set_lights ( button , rails )
Control the robot lights .
9,169
async def identify ( self , duration_s : int = 5 ) : count = duration_s * 4 on = False for sec in range ( count ) : then = self . _loop . time ( ) self . set_lights ( button = on ) on = not on now = self . _loop . time ( ) await asyncio . sleep ( max ( 0 , 0.25 - ( now - then ) ) ) self . set_lights ( button = True )
Blink the button light to identify the robot .
9,170
async def cache_instruments ( self , require : Dict [ top_types . Mount , str ] = None ) : checked_require = require or { } self . _log . info ( "Updating instrument model cache" ) found = self . _backend . get_attached_instruments ( checked_require ) for mount , instrument_data in found . items ( ) : model = instrument_data . get ( 'model' ) if model is not None : p = Pipette ( model , self . _config . instrument_offset [ mount . name . lower ( ) ] , instrument_data [ 'id' ] ) self . _attached_instruments [ mount ] = p else : self . _attached_instruments [ mount ] = None mod_log . info ( "Instruments found: {}" . format ( self . _attached_instruments ) )
- Get the attached instrument on each mount and - Cache their pipette configs from pipette - config . json
9,171
async def update_firmware ( self , firmware_file : str , loop : asyncio . AbstractEventLoop = None , explicit_modeset : bool = True ) -> str : if None is loop : checked_loop = self . _loop else : checked_loop = loop return await self . _backend . update_firmware ( firmware_file , checked_loop , explicit_modeset )
Update the firmware on the Smoothie board .
9,172
async def home_z ( self , mount : top_types . Mount = None ) : if not mount : axes = [ Axis . Z , Axis . A ] else : axes = [ Axis . by_mount ( mount ) ] await self . home ( axes )
Home the two z - axes
9,173
async def home_plunger ( self , mount : top_types . Mount ) : instr = self . _attached_instruments [ mount ] if instr : await self . home ( [ Axis . of_plunger ( mount ) ] ) await self . _move_plunger ( mount , instr . config . bottom )
Home the plunger motor for a mount and then return it to the bottom position .
9,174
def _deck_from_smoothie ( self , smoothie_pos : Dict [ str , float ] ) -> Dict [ Axis , float ] : with_enum = { Axis [ k ] : v for k , v in smoothie_pos . items ( ) } plunger_axes = { k : v for k , v in with_enum . items ( ) if k not in Axis . gantry_axes ( ) } right = ( with_enum [ Axis . X ] , with_enum [ Axis . Y ] , with_enum [ Axis . by_mount ( top_types . Mount . RIGHT ) ] ) left = ( with_enum [ Axis . X ] , with_enum [ Axis . Y ] , with_enum [ Axis . by_mount ( top_types . Mount . LEFT ) ] ) right_deck = linal . apply_reverse ( self . config . gantry_calibration , right ) left_deck = linal . apply_reverse ( self . config . gantry_calibration , left ) deck_pos = { Axis . X : right_deck [ 0 ] , Axis . Y : right_deck [ 1 ] , Axis . by_mount ( top_types . Mount . RIGHT ) : right_deck [ 2 ] , Axis . by_mount ( top_types . Mount . LEFT ) : left_deck [ 2 ] } deck_pos . update ( plunger_axes ) return deck_pos
Build a deck - abs position store from the smoothie s position
9,175
async def gantry_position ( self , mount : top_types . Mount , critical_point : CriticalPoint = None ) -> top_types . Point : cur_pos = await self . current_position ( mount , critical_point ) return top_types . Point ( x = cur_pos [ Axis . X ] , y = cur_pos [ Axis . Y ] , z = cur_pos [ Axis . by_mount ( mount ) ] )
Return the position of the critical point as pertains to the gantry
9,176
async def move_to ( self , mount : top_types . Mount , abs_position : top_types . Point , speed : float = None , critical_point : CriticalPoint = None ) : if not self . _current_position : raise MustHomeError await self . _cache_and_maybe_retract_mount ( mount ) z_axis = Axis . by_mount ( mount ) if mount == top_types . Mount . LEFT : offset = top_types . Point ( * self . config . mount_offset ) else : offset = top_types . Point ( 0 , 0 , 0 ) cp = self . _critical_point_for ( mount , critical_point ) target_position = OrderedDict ( ( ( Axis . X , abs_position . x - offset . x - cp . x ) , ( Axis . Y , abs_position . y - offset . y - cp . y ) , ( z_axis , abs_position . z - offset . z - cp . z ) ) ) await self . _move ( target_position , speed = speed )
Move the critical point of the specified mount to a location relative to the deck at the specified speed . speed sets the speed of all robot axes to the given value . So if multiple axes are to be moved they will do so at the same speed
9,177
async def move_rel ( self , mount : top_types . Mount , delta : top_types . Point , speed : float = None ) : if not self . _current_position : raise MustHomeError await self . _cache_and_maybe_retract_mount ( mount ) z_axis = Axis . by_mount ( mount ) try : target_position = OrderedDict ( ( ( Axis . X , self . _current_position [ Axis . X ] + delta . x ) , ( Axis . Y , self . _current_position [ Axis . Y ] + delta . y ) , ( z_axis , self . _current_position [ z_axis ] + delta . z ) ) ) except KeyError : raise MustHomeError await self . _move ( target_position , speed = speed )
Move the critical point of the specified mount by a specified displacement in a specified direction at the specified speed . speed sets the speed of all axes to the given value . So if multiple axes are to be moved they will do so at the same speed
9,178
async def _cache_and_maybe_retract_mount ( self , mount : top_types . Mount ) : if mount != self . _last_moved_mount and self . _last_moved_mount : await self . retract ( self . _last_moved_mount , 10 ) self . _last_moved_mount = mount
Retract the other mount if necessary
9,179
async def _move ( self , target_position : 'OrderedDict[Axis, float]' , speed : float = None , home_flagged_axes : bool = True ) : to_transform = tuple ( ( tp for ax , tp in target_position . items ( ) if ax in Axis . gantry_axes ( ) ) ) smoothie_pos = { ax . name : pos for ax , pos in target_position . items ( ) if ax not in Axis . gantry_axes ( ) } if len ( to_transform ) != 3 : self . _log . error ( "Move derived {} axes to transform from {}" . format ( len ( to_transform ) , target_position ) ) raise ValueError ( "Moves must specify either exactly an x, y, and " "(z or a) or none of them" ) transformed = linal . apply_transform ( self . config . gantry_calibration , to_transform ) bounds = self . _backend . axis_bounds for idx , ax in enumerate ( target_position . keys ( ) ) : if ax in Axis . gantry_axes ( ) : smoothie_pos [ ax . name ] = transformed [ idx ] if smoothie_pos [ ax . name ] < bounds [ ax . name ] [ 0 ] or smoothie_pos [ ax . name ] > bounds [ ax . name ] [ 1 ] : deck_mins = self . _deck_from_smoothie ( { ax : bound [ 0 ] for ax , bound in bounds . items ( ) } ) deck_max = self . _deck_from_smoothie ( { ax : bound [ 1 ] for ax , bound in bounds . items ( ) } ) self . _log . warning ( "Out of bounds move: {}={} (transformed: {}) not in" "limits ({}, {}) (transformed: ({}, {})" . format ( ax . name , target_position [ ax ] , smoothie_pos [ ax . name ] , deck_mins [ ax ] , deck_max [ ax ] , bounds [ ax . name ] [ 0 ] , bounds [ ax . name ] [ 1 ] ) ) async with self . _motion_lock : try : self . _backend . move ( smoothie_pos , speed = speed , home_flagged_axes = home_flagged_axes ) except Exception : self . _log . exception ( 'Move failed' ) self . _current_position . clear ( ) raise else : self . _current_position . update ( target_position )
Worker function to apply robot motion .
9,180
def engaged_axes ( self ) -> Dict [ Axis , bool ] : return { Axis [ ax ] : eng for ax , eng in self . _backend . engaged_axes ( ) . items ( ) }
Which axes are engaged and holding .
9,181
async def retract ( self , mount : top_types . Mount , margin : float ) : smoothie_ax = Axis . by_mount ( mount ) . name . upper ( ) async with self . _motion_lock : smoothie_pos = self . _backend . fast_home ( smoothie_ax , margin ) self . _current_position = self . _deck_from_smoothie ( smoothie_pos )
Pull the specified mount up to its home position .
9,182
def _critical_point_for ( self , mount : top_types . Mount , cp_override : CriticalPoint = None ) -> top_types . Point : pip = self . _attached_instruments [ mount ] if pip is not None and cp_override != CriticalPoint . MOUNT : return pip . critical_point ( cp_override ) else : return top_types . Point ( 0 , 0 , 0 )
Return the current critical point of the specified mount .
9,183
async def blow_out ( self , mount ) : this_pipette = self . _attached_instruments [ mount ] if not this_pipette : raise top_types . PipetteNotAttachedError ( "No pipette attached to {} mount" . format ( mount . name ) ) self . _backend . set_active_current ( Axis . of_plunger ( mount ) , this_pipette . config . plunger_current ) try : await self . _move_plunger ( mount , this_pipette . config . blow_out ) except Exception : self . _log . exception ( 'Blow out failed' ) raise finally : this_pipette . set_current_volume ( 0 )
Force any remaining liquid to dispense . The liquid will be dispensed at the current location of pipette
9,184
async def pick_up_tip ( self , mount , tip_length : float , presses : int = None , increment : float = None ) : instr = self . _attached_instruments [ mount ] assert instr assert not instr . has_tip , 'Tip already attached' instr_ax = Axis . by_mount ( mount ) plunger_ax = Axis . of_plunger ( mount ) self . _log . info ( 'Picking up tip on {}' . format ( instr . name ) ) self . _backend . set_active_current ( plunger_ax , instr . config . plunger_current ) await self . _move_plunger ( mount , instr . config . bottom ) if not presses or presses < 0 : checked_presses = instr . config . pick_up_presses else : checked_presses = presses if not increment or increment < 0 : checked_increment = instr . config . pick_up_increment else : checked_increment = increment for i in range ( checked_presses ) : with self . _backend . save_current ( ) : self . _backend . set_active_current ( instr_ax , instr . config . pick_up_current ) dist = - 1.0 * instr . config . pick_up_distance + - 1.0 * checked_increment * i target_pos = top_types . Point ( 0 , 0 , dist ) await self . move_rel ( mount , target_pos , instr . config . pick_up_speed ) backup_pos = top_types . Point ( 0 , 0 , - dist ) await self . move_rel ( mount , backup_pos ) instr . add_tip ( tip_length = tip_length ) instr . set_current_volume ( 0 ) if 'needs-pickup-shake' in instr . config . quirks : await self . _shake_off_tips ( mount ) await self . _shake_off_tips ( mount ) await self . retract ( mount , instr . config . pick_up_distance )
Pick up tip from current location .
9,185
async def drop_tip ( self , mount , home_after = True ) : instr = self . _attached_instruments [ mount ] assert instr assert instr . has_tip , 'Cannot drop tip without a tip attached' self . _log . info ( "Dropping tip off from {}" . format ( instr . name ) ) plunger_ax = Axis . of_plunger ( mount ) droptip = instr . config . drop_tip bottom = instr . config . bottom self . _backend . set_active_current ( plunger_ax , instr . config . plunger_current ) await self . _move_plunger ( mount , bottom ) self . _backend . set_active_current ( plunger_ax , instr . config . drop_tip_current ) await self . _move_plunger ( mount , droptip , speed = instr . config . drop_tip_speed ) await self . _shake_off_tips ( mount ) self . _backend . set_active_current ( plunger_ax , instr . config . plunger_current ) instr . set_current_volume ( 0 ) instr . remove_tip ( ) if home_after : safety_margin = abs ( bottom - droptip ) async with self . _motion_lock : smoothie_pos = self . _backend . fast_home ( plunger_ax . name . upper ( ) , safety_margin ) self . _current_position = self . _deck_from_smoothie ( smoothie_pos ) await self . _move_plunger ( mount , safety_margin )
Drop tip at the current location
9,186
async def update_module ( self , module : modules . AbstractModule , firmware_file : str , loop : asyncio . AbstractEventLoop = None ) -> Tuple [ bool , str ] : details = ( module . port , module . name ( ) ) mod = self . _attached_modules . pop ( details [ 0 ] + details [ 1 ] ) try : new_mod = await self . _backend . update_module ( mod , firmware_file , loop ) except modules . UpdateError as e : return False , e . msg else : new_details = new_mod . port + new_mod . device_info [ 'model' ] self . _attached_modules [ new_details ] = new_mod return True , 'firmware update successful'
Update a module s firmware .
9,187
def update_instrument_offset ( self , mount , new_offset : top_types . Point = None , from_tip_probe : top_types . Point = None ) : if from_tip_probe : new_offset = ( top_types . Point ( * self . _config . tip_probe . center ) - from_tip_probe ) elif not new_offset : raise ValueError ( "Either from_tip_probe or new_offset must be specified" ) opt_pip = self . _attached_instruments [ mount ] assert opt_pip , '{} has no pipette' . format ( mount . name . lower ( ) ) pip = opt_pip inst_offs = self . _config . instrument_offset pip_type = 'multi' if pip . config . channels > 1 else 'single' inst_offs [ mount . name . lower ( ) ] [ pip_type ] = [ new_offset . x , new_offset . y , new_offset . z ] self . update_config ( instrument_offset = inst_offs ) pip . update_instrument_offset ( new_offset ) robot_configs . save_robot_settings ( self . _config )
Update the instrument offset for a pipette on the specified mount .
9,188
def load ( pipette_model : str , pipette_id : str = None ) -> pipette_config : cfg = copy . deepcopy ( configs [ pipette_model ] ) cfg . update ( copy . deepcopy ( name_config ( ) [ cfg [ 'name' ] ] ) ) if pipette_id : try : override = load_overrides ( pipette_id ) except FileNotFoundError : save_overrides ( pipette_id , { } , pipette_model ) log . info ( "Save defaults for pipette model {} and id {}" . format ( pipette_model , pipette_id ) ) else : cfg . update ( override ) if ff . use_old_aspiration_functions ( ) : log . info ( "Using old aspiration functions" ) ul_per_mm = cfg [ 'ulPerMm' ] [ 0 ] else : log . info ( "Using new aspiration functions" ) ul_per_mm = cfg [ 'ulPerMm' ] [ - 1 ] res = pipette_config ( top = ensure_value ( cfg , 'top' , mutable_configs ) , bottom = ensure_value ( cfg , 'bottom' , mutable_configs ) , blow_out = ensure_value ( cfg , 'blowout' , mutable_configs ) , drop_tip = ensure_value ( cfg , 'dropTip' , mutable_configs ) , pick_up_current = ensure_value ( cfg , 'pickUpCurrent' , mutable_configs ) , pick_up_distance = ensure_value ( cfg , 'pickUpDistance' , mutable_configs ) , pick_up_increment = ensure_value ( cfg , 'pickUpIncrement' , mutable_configs ) , pick_up_presses = ensure_value ( cfg , 'pickUpPresses' , mutable_configs ) , pick_up_speed = ensure_value ( cfg , 'pickUpSpeed' , mutable_configs ) , aspirate_flow_rate = ensure_value ( cfg , 'defaultAspirateFlowRate' , mutable_configs ) , dispense_flow_rate = ensure_value ( cfg , 'defaultDispenseFlowRate' , mutable_configs ) , channels = ensure_value ( cfg , 'channels' , mutable_configs ) , model_offset = ensure_value ( cfg , 'modelOffset' , mutable_configs ) , plunger_current = ensure_value ( cfg , 'plungerCurrent' , mutable_configs ) , drop_tip_current = ensure_value ( cfg , 'dropTipCurrent' , mutable_configs ) , drop_tip_speed = ensure_value ( cfg , 'dropTipSpeed' , mutable_configs ) , min_volume = ensure_value ( cfg , 'minVolume' , mutable_configs ) , max_volume = ensure_value ( cfg , 'maxVolume' , mutable_configs ) , ul_per_mm = ul_per_mm , quirks = ensure_value ( cfg , 'quirks' , mutable_configs ) , tip_length = ensure_value ( cfg , 'tipLength' , mutable_configs ) , display_name = ensure_value ( cfg , 'displayName' , mutable_configs ) ) return res
Load pipette config data
9,189
def known_pipettes ( ) -> Sequence [ str ] : return [ fi . stem for fi in CONFIG [ 'pipette_config_overrides_dir' ] . iterdir ( ) if fi . is_file ( ) and '.json' in fi . suffixes ]
List pipette IDs for which we have known overrides
9,190
def load_config_dict ( pipette_id : str ) -> Dict : override = load_overrides ( pipette_id ) model = override [ 'model' ] config = copy . deepcopy ( model_config ( ) [ 'config' ] [ model ] ) config . update ( copy . deepcopy ( name_config ( ) [ config [ 'name' ] ] ) ) for top_level_key in config . keys ( ) : add_default ( config [ top_level_key ] ) config . update ( override ) return config
Give updated config with overrides for a pipette . This will add the default value for a mutable config before returning the modified config value .
9,191
def list_mutable_configs ( pipette_id : str ) -> Dict [ str , Any ] : cfg : Dict [ str , Any ] = { } if pipette_id in known_pipettes ( ) : config = load_config_dict ( pipette_id ) else : log . info ( 'Pipette id {} not found' . format ( pipette_id ) ) return cfg for key in config : if key in mutable_configs : cfg [ key ] = config [ key ] return cfg
Returns dict of mutable configs only .
9,192
def probe_plate ( self ) -> str : self . run_flag . wait ( ) try : self . _send_command ( GCODES [ 'PROBE_PLATE' ] ) except ( MagDeckError , SerialException , SerialNoResponse ) as e : return str ( e ) return ''
Probes for the deck plate and calculates the plate distance from home . To be used for calibrating MagDeck
9,193
def move ( self , position_mm ) -> str : self . run_flag . wait ( ) try : position_mm = round ( float ( position_mm ) , GCODE_ROUNDING_PRECISION ) self . _send_command ( '{0} Z{1}' . format ( GCODES [ 'MOVE' ] , position_mm ) ) except ( MagDeckError , SerialException , SerialNoResponse ) as e : return str ( e ) return ''
Move the magnets along Z axis where the home position is 0 . 0 ; position_mm - > a point along Z . Does not self - check if the position is outside of the deck s linear range
9,194
def save_calibration ( labware : Labware , delta : Point ) : calibration_path = CONFIG [ 'labware_calibration_offsets_dir_v4' ] if not calibration_path . exists ( ) : calibration_path . mkdir ( parents = True , exist_ok = True ) labware_offset_path = calibration_path / '{}.json' . format ( labware . _id ) calibration_data = _helper_offset_data_format ( str ( labware_offset_path ) , delta ) with labware_offset_path . open ( 'w' ) as f : json . dump ( calibration_data , f ) labware . set_calibration ( delta )
Function to be used whenever an updated delta is found for the first well of a given labware . If an offset file does not exist create the file using labware id as the filename . If the file does exist load it and modify the delta and the lastModified fields under the default key .
9,195
def save_tip_length ( labware : Labware , length : float ) : calibration_path = CONFIG [ 'labware_calibration_offsets_dir_v4' ] if not calibration_path . exists ( ) : calibration_path . mkdir ( parents = True , exist_ok = True ) labware_offset_path = calibration_path / '{}.json' . format ( labware . _id ) calibration_data = _helper_tip_length_data_format ( str ( labware_offset_path ) , length ) with labware_offset_path . open ( 'w' ) as f : json . dump ( calibration_data , f ) labware . tip_length = length
Function to be used whenever an updated tip length is found for of a given tip rack . If an offset file does not exist create the file using labware id as the filename . If the file does exist load it and modify the length and the lastModified fields under the tipLength key .
9,196
def load_calibration ( labware : Labware ) : calibration_path = CONFIG [ 'labware_calibration_offsets_dir_v4' ] labware_offset_path = calibration_path / '{}.json' . format ( labware . _id ) if labware_offset_path . exists ( ) : calibration_data = _read_file ( str ( labware_offset_path ) ) offset_array = calibration_data [ 'default' ] [ 'offset' ] offset = Point ( x = offset_array [ 0 ] , y = offset_array [ 1 ] , z = offset_array [ 2 ] ) labware . set_calibration ( offset ) if 'tipLength' in calibration_data . keys ( ) : tip_length = calibration_data [ 'tipLength' ] [ 'length' ] labware . tip_length = tip_length
Look up a calibration if it exists and apply it to the given labware .
9,197
def load_from_definition ( definition : dict , parent : Location , label : str = None ) -> Labware : labware = Labware ( definition , parent , label ) load_calibration ( labware ) return labware
Return a labware object constructed from a provided labware definition dict
9,198
def clear_calibrations ( ) : calibration_path = CONFIG [ 'labware_calibration_offsets_dir_v4' ] try : targets = [ f for f in calibration_path . iterdir ( ) if f . suffix == '.json' ] for target in targets : target . unlink ( ) except FileNotFoundError : pass
Delete all calibration files for labware . This includes deleting tip - length data for tipracks .
9,199
def quirks_from_any_parent ( loc : Union [ Labware , Well , str , ModuleGeometry , None ] ) -> List [ str ] : def recursive_get_quirks ( obj , found ) : if isinstance ( obj , Labware ) : return found + obj . quirks elif isinstance ( obj , Well ) : return recursive_get_quirks ( obj . parent , found ) else : return found return recursive_get_quirks ( loc , [ ] )
Walk the tree of wells and labwares and extract quirks