idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
232,600 | def start ( self ) : log . debug ( 'Creating the TCP server' ) if ':' in self . address : self . skt = socket . socket ( socket . AF_INET6 , socket . SOCK_STREAM ) else : self . skt = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) if self . reuse_port : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) if hasattr ( socket , 'SO_REUSEPORT' ) : self . skt . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEPORT , 1 ) else : log . error ( 'SO_REUSEPORT not supported' ) try : self . skt . bind ( ( self . address , int ( self . port ) ) ) except socket . error as msg : error_string = 'Unable to bind to port {} on {}: {}' . format ( self . port , self . address , msg ) log . error ( error_string , exc_info = True ) raise BindException ( error_string ) log . debug ( 'Accepting max %d parallel connections' , self . max_clients ) self . skt . listen ( self . max_clients ) self . thread_serve = threading . Thread ( target = self . _serve_clients ) self . thread_serve . start ( ) | Start listening for messages . | 321 | 5 |
232,601 | def receive ( self ) : while self . buffer . empty ( ) and self . __up : # This sequence is skipped when the buffer is not empty. sleep_ms = random . randint ( 0 , 1000 ) # log.debug('The message queue is empty, waiting %d miliseconds', sleep_ms) # disabled ^ as it was too noisy time . sleep ( sleep_ms / 1000.0 ) if not self . buffer . empty ( ) : return self . buffer . get ( block = False ) return '' , '' | Return one message dequeued from the listen buffer . | 112 | 11 |
232,602 | def stop ( self ) : log . info ( 'Stopping the TCP listener' ) self . __up = False try : self . skt . shutdown ( socket . SHUT_RDWR ) except socket . error : log . error ( 'The following error may not be critical:' , exc_info = True ) self . skt . close ( ) | Closing the socket . | 74 | 5 |
232,603 | def _setup_ipc ( self ) : log . debug ( 'Setting up the listener IPC pusher' ) self . ctx = zmq . Context ( ) self . pub = self . ctx . socket ( zmq . PUSH ) self . pub . connect ( LST_IPC_URL ) log . debug ( 'Setting HWM for the listener: %d' , self . opts [ 'hwm' ] ) try : self . pub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) # zmq 2 except AttributeError : # zmq 3 self . pub . setsockopt ( zmq . SNDHWM , self . opts [ 'hwm' ] ) | Setup the listener ICP pusher . | 167 | 8 |
232,604 | def make_update_loop ( thread , update_func ) : while not thread . should_stop ( ) : if thread . should_pause ( ) : thread . wait_to_resume ( ) start = time . time ( ) if hasattr ( thread , '_updated' ) : thread . _updated . clear ( ) update_func ( ) if hasattr ( thread , '_updated' ) : thread . _updated . set ( ) end = time . time ( ) dt = thread . period - ( end - start ) if dt > 0 : time . sleep ( dt ) | Makes a run loop which calls an update function at a predefined frequency . | 127 | 16 |
232,605 | def start ( self ) : if self . running : self . stop ( ) self . _thread = threading . Thread ( target = self . _wrapped_target ) self . _thread . daemon = True self . _thread . start ( ) | Start the run method as a new thread . | 52 | 9 |
232,606 | def wait_to_start ( self , allow_failure = False ) : self . _started . wait ( ) if self . _crashed and not allow_failure : self . _thread . join ( ) raise RuntimeError ( 'Setup failed, see {} Traceback' 'for details.' . format ( self . _thread . name ) ) | Wait for the thread to actually starts . | 74 | 8 |
232,607 | def from_vrep ( config , vrep_host = '127.0.0.1' , vrep_port = 19997 , scene = None , tracked_objects = [ ] , tracked_collisions = [ ] , id = None , shared_vrep_io = None ) : if shared_vrep_io is None : vrep_io = VrepIO ( vrep_host , vrep_port ) else : vrep_io = shared_vrep_io vreptime = vrep_time ( vrep_io ) pypot_time . time = vreptime . get_time pypot_time . sleep = vreptime . sleep if isinstance ( config , basestring ) : with open ( config ) as f : config = json . load ( f , object_pairs_hook = OrderedDict ) motors = [ motor_from_confignode ( config , name ) for name in config [ 'motors' ] . keys ( ) ] vc = VrepController ( vrep_io , scene , motors , id = id ) vc . _init_vrep_streaming ( ) sensor_controllers = [ ] if tracked_objects : sensors = [ ObjectTracker ( name ) for name in tracked_objects ] vot = VrepObjectTracker ( vrep_io , sensors ) sensor_controllers . append ( vot ) if tracked_collisions : sensors = [ VrepCollisionDetector ( name ) for name in tracked_collisions ] vct = VrepCollisionTracker ( vrep_io , sensors ) sensor_controllers . append ( vct ) robot = Robot ( motor_controllers = [ vc ] , sensor_controllers = sensor_controllers ) for m in robot . motors : m . goto_behavior = 'minjerk' init_pos = { m : m . goal_position for m in robot . motors } make_alias ( config , robot ) def start_simu ( ) : vrep_io . start_simulation ( ) for m , p in init_pos . iteritems ( ) : m . goal_position = p vc . start ( ) if tracked_objects : vot . start ( ) if tracked_collisions : vct . start ( ) while vrep_io . get_simulation_current_time ( ) < 1. : sys_time . sleep ( 0.1 ) def stop_simu ( ) : if tracked_objects : vot . stop ( ) if tracked_collisions : vct . stop ( ) vc . stop ( ) vrep_io . stop_simulation ( ) def reset_simu ( ) : stop_simu ( ) sys_time . sleep ( 0.5 ) start_simu ( ) robot . start_simulation = start_simu robot . stop_simulation = stop_simu robot . reset_simulation = reset_simu def current_simulation_time ( robot ) : return robot . _controllers [ 0 ] . io . get_simulation_current_time ( ) Robot . current_simulation_time = property ( lambda robot : current_simulation_time ( robot ) ) def get_object_position ( robot , object , relative_to_object = None ) : return vrep_io . get_object_position ( object , relative_to_object ) Robot . get_object_position = partial ( get_object_position , robot ) def get_object_orientation ( robot , object , relative_to_object = None ) : return vrep_io . get_object_orientation ( object , relative_to_object ) Robot . get_object_orientation = partial ( get_object_orientation , robot ) return robot | Create a robot from a V - REP instance . | 811 | 11 |
232,608 | def set_wheel_mode ( self , ids ) : self . set_control_mode ( dict ( zip ( ids , itertools . repeat ( 'wheel' ) ) ) ) | Sets the specified motors to wheel mode . | 41 | 9 |
232,609 | def set_joint_mode ( self , ids ) : self . set_control_mode ( dict ( zip ( ids , itertools . repeat ( 'joint' ) ) ) ) | Sets the specified motors to joint mode . | 43 | 9 |
232,610 | def set_angle_limit ( self , limit_for_id , * * kwargs ) : convert = kwargs [ 'convert' ] if 'convert' in kwargs else self . _convert if 'wheel' in self . get_control_mode ( limit_for_id . keys ( ) ) : raise ValueError ( 'can not change the angle limit of a motor in wheel mode' ) if ( 0 , 0 ) in limit_for_id . values ( ) : raise ValueError ( 'can not set limit to (0, 0)' ) self . _set_angle_limit ( limit_for_id , convert = convert ) | Sets the angle limit to the specified motors . | 143 | 10 |
232,611 | def close ( self ) : self . stop_sync ( ) [ c . io . close ( ) for c in self . _controllers if c . io is not None ] | Cleans the robot by stopping synchronization and all controllers . | 37 | 11 |
232,612 | def goto_position ( self , position_for_motors , duration , control = None , wait = False ) : for i , ( motor_name , position ) in enumerate ( position_for_motors . iteritems ( ) ) : w = False if i < len ( position_for_motors ) - 1 else wait m = getattr ( self , motor_name ) m . goto_position ( position , duration , control , wait = w ) | Moves a subset of the motors to a position within a specific duration . | 98 | 15 |
232,613 | def power_up ( self ) : for m in self . motors : m . compliant = False m . moving_speed = 0 m . torque_limit = 100.0 | Changes all settings to guarantee the motors will be used at their maximum power . | 36 | 15 |
232,614 | def to_config ( self ) : from . . dynamixel . controller import DxlController dxl_controllers = [ c for c in self . _controllers if isinstance ( c , DxlController ) ] config = { } config [ 'controllers' ] = { } for i , c in enumerate ( dxl_controllers ) : name = 'dxl_controller_{}' . format ( i ) config [ 'controllers' ] [ name ] = { 'port' : c . io . port , 'sync_read' : c . io . _sync_read , 'attached_motors' : [ m . name for m in c . motors ] , } config [ 'motors' ] = { } for m in self . motors : config [ 'motors' ] [ m . name ] = { 'id' : m . id , 'type' : m . model , 'offset' : m . offset , 'orientation' : 'direct' if m . direct else 'indirect' , 'angle_limit' : m . angle_limit , } if m . angle_limit == ( 0 , 0 ) : config [ 'motors' ] [ 'wheel_mode' ] = True config [ 'motorgroups' ] = { } return config | Generates the config for the current robot . | 278 | 9 |
232,615 | def update ( self ) : # Read all the angle limits h , _ , l , _ = self . io . call_remote_api ( 'simxGetObjectGroupData' , remote_api . sim_object_joint_type , 16 , streaming = True ) limits4handle = { hh : ( ll , lr ) for hh , ll , lr in zip ( h , l [ : : 2 ] , l [ 1 : : 2 ] ) } for m in self . motors : tmax = torque_max [ m . model ] # Read values from V-REP and set them to the Motor p = round ( rad2deg ( self . io . get_motor_position ( motor_name = self . _motor_name ( m ) ) ) , 1 ) m . __dict__ [ 'present_position' ] = p l = 100. * self . io . get_motor_force ( motor_name = self . _motor_name ( m ) ) / tmax m . __dict__ [ 'present_load' ] = l m . __dict__ [ '_load_fifo' ] . append ( abs ( l ) ) m . __dict__ [ 'present_temperature' ] = 25 + round ( 2.5 * sum ( m . __dict__ [ '_load_fifo' ] ) / len ( m . __dict__ [ '_load_fifo' ] ) , 1 ) ll , lr = limits4handle [ self . io . _object_handles [ self . _motor_name ( m ) ] ] m . __dict__ [ 'lower_limit' ] = rad2deg ( ll ) m . __dict__ [ 'upper_limit' ] = rad2deg ( ll ) + rad2deg ( lr ) # Send new values from Motor to V-REP p = deg2rad ( round ( m . __dict__ [ 'goal_position' ] , 1 ) ) self . io . set_motor_position ( motor_name = self . _motor_name ( m ) , position = p ) t = m . __dict__ [ 'torque_limit' ] * tmax / 100. if m . __dict__ [ 'compliant' ] : t = 0. self . io . set_motor_force ( motor_name = self . _motor_name ( m ) , force = t ) | Synchronization update loop . | 523 | 6 |
232,616 | def update ( self ) : for s in self . sensors : s . position = self . io . get_object_position ( object_name = s . name ) s . orientation = self . io . get_object_orientation ( object_name = s . name ) | Updates the position and orientation of the tracked objects . | 58 | 11 |
232,617 | def update ( self ) : for s in self . sensors : s . colliding = self . io . get_collision_state ( collision_name = s . name ) | Update the state of the collision detectors . | 37 | 8 |
232,618 | def get_transformation_matrix ( self , theta ) : ct = numpy . cos ( theta + self . theta ) st = numpy . sin ( theta + self . theta ) ca = numpy . cos ( self . alpha ) sa = numpy . sin ( self . alpha ) return numpy . matrix ( ( ( ct , - st * ca , st * sa , self . a * ct ) , ( st , ct * ca , - ct * sa , self . a * st ) , ( 0 , sa , ca , self . d ) , ( 0 , 0 , 0 , 1 ) ) ) | Computes the homogeneous transformation matrix for this link . | 140 | 11 |
232,619 | def forward_kinematics ( self , q ) : q = numpy . array ( q ) . flatten ( ) if len ( q ) != len ( self . links ) : raise ValueError ( 'q must contain as element as the number of links' ) tr = self . base . copy ( ) l = [ ] for link , theta in zip ( self . links , q ) : tr = tr * link . get_transformation_matrix ( theta ) l . append ( tr ) tr = tr * self . tool l . append ( tr ) return tr , numpy . asarray ( l ) | Computes the homogeneous transformation matrix of the end effector of the chain . | 131 | 16 |
232,620 | def inverse_kinematics ( self , end_effector_transformation , q = None , max_iter = 1000 , tolerance = 0.05 , mask = numpy . ones ( 6 ) , use_pinv = False ) : if q is None : q = numpy . zeros ( ( len ( self . links ) , 1 ) ) q = numpy . matrix ( q . reshape ( - 1 , 1 ) ) best_e = numpy . ones ( 6 ) * numpy . inf best_q = None alpha = 1.0 for _ in range ( max_iter ) : e = numpy . multiply ( transform_difference ( self . forward_kinematics ( q ) [ 0 ] , end_effector_transformation ) , mask ) d = numpy . linalg . norm ( e ) if d < numpy . linalg . norm ( best_e ) : best_e = e . copy ( ) best_q = q . copy ( ) alpha *= 2.0 ** ( 1.0 / 8.0 ) else : q = best_q . copy ( ) e = best_e . copy ( ) alpha *= 0.5 if use_pinv : dq = numpy . linalg . pinv ( self . _jacob0 ( q ) ) * e . reshape ( ( - 1 , 1 ) ) else : dq = self . _jacob0 ( q ) . T * e . reshape ( ( - 1 , 1 ) ) q += alpha * dq # d = numpy.linalg.norm(dq) if d < tolerance : return q else : raise ValueError ( 'could not converge d={}' . format ( numpy . linalg . norm ( best_e ) ) ) | Computes the joint angles corresponding to the end effector transformation . | 386 | 13 |
232,621 | def _get_available_ports ( ) : if platform . system ( ) == 'Darwin' : return glob . glob ( '/dev/tty.usb*' ) elif platform . system ( ) == 'Linux' : return glob . glob ( '/dev/ttyACM*' ) + glob . glob ( '/dev/ttyUSB*' ) + glob . glob ( '/dev/ttyAMA*' ) elif sys . platform . lower ( ) == 'cygwin' : return glob . glob ( '/dev/com*' ) elif platform . system ( ) == 'Windows' : import _winreg import itertools ports = [ ] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg . OpenKey ( _winreg . HKEY_LOCAL_MACHINE , path ) for i in itertools . count ( ) : try : ports . append ( str ( _winreg . EnumValue ( key , i ) [ 1 ] ) ) except WindowsError : return ports else : raise EnvironmentError ( '{} is an unsupported platform, cannot find serial ports !' . format ( platform . system ( ) ) ) return [ ] | Tries to find the available serial ports on your system . | 257 | 12 |
232,622 | def find_port ( ids , strict = True ) : ids_founds = [ ] for port in get_available_ports ( ) : for DxlIOCls in ( DxlIO , Dxl320IO ) : try : with DxlIOCls ( port ) as dxl : _ids_founds = dxl . scan ( ids ) ids_founds += _ids_founds if strict and len ( _ids_founds ) == len ( ids ) : return port if not strict and len ( _ids_founds ) >= len ( ids ) / 2 : logger . warning ( 'Missing ids: {}' . format ( ids , list ( set ( ids ) - set ( _ids_founds ) ) ) ) return port if len ( ids_founds ) > 0 : logger . warning ( 'Port:{} ids found:{}' . format ( port , _ids_founds ) ) except DxlError : logger . warning ( 'DxlError on port {}' . format ( port ) ) continue raise IndexError ( 'No suitable port found for ids {}. These ids are missing {} !' . format ( ids , list ( set ( ids ) - set ( ids_founds ) ) ) ) | Find the port with the specified attached motor ids . | 284 | 11 |
232,623 | def _filter ( self , data ) : filtered_data = [ ] for queue , data in zip ( self . _raw_data_queues , data ) : queue . append ( data ) filtered_data . append ( numpy . median ( queue ) ) return filtered_data | Apply a filter to reduce noisy data . | 59 | 8 |
232,624 | def setup ( self ) : [ c . start ( ) for c in self . controllers ] [ c . wait_to_start ( ) for c in self . controllers ] | Starts all the synchronization loops . | 36 | 7 |
232,625 | def from_poppy_creature ( cls , poppy , motors , passiv , tip , reversed_motors = [ ] ) : chain_elements = get_chain_from_joints ( poppy . urdf_file , [ m . name for m in motors ] ) activ = [ False ] + [ m not in passiv for m in motors ] + [ True ] chain = cls . from_urdf_file ( poppy . urdf_file , base_elements = chain_elements , last_link_vector = tip , active_links_mask = activ ) chain . motors = [ getattr ( poppy , l . name ) for l in chain . links [ 1 : - 1 ] ] for m , l in zip ( chain . motors , chain . links [ 1 : - 1 ] ) : # Force an access to angle limit to retrieve real values # This is quite an ugly fix and should be handled better m . angle_limit bounds = m . __dict__ [ 'lower_limit' ] , m . __dict__ [ 'upper_limit' ] l . bounds = tuple ( map ( rad2deg , bounds ) ) chain . _reversed = array ( [ ( - 1 if m in reversed_motors else 1 ) for m in motors ] ) return chain | Creates an kinematic chain from motors of a Poppy Creature . | 280 | 15 |
232,626 | def goto ( self , position , duration , wait = False , accurate = False ) : if len ( position ) != 3 : raise ValueError ( 'Position should be a list [x, y, z]!' ) M = eye ( 4 ) M [ : 3 , 3 ] = position self . _goto ( M , duration , wait , accurate ) | Goes to a given cartesian position . | 74 | 9 |
232,627 | def _goto ( self , pose , duration , wait , accurate ) : kwargs = { } if not accurate : kwargs [ 'max_iter' ] = 3 q0 = self . convert_to_ik_angles ( self . joints_position ) q = self . inverse_kinematics ( pose , initial_position = q0 , * * kwargs ) joints = self . convert_from_ik_angles ( q ) last = self . motors [ - 1 ] for m , pos in list ( zip ( self . motors , joints ) ) : m . goto_position ( pos , duration , wait = False if m != last else wait ) | Goes to a given cartesian pose . | 142 | 9 |
232,628 | def convert_to_ik_angles ( self , joints ) : if len ( joints ) != len ( self . motors ) : raise ValueError ( 'Incompatible data, len(joints) should be {}!' . format ( len ( self . motors ) ) ) raw_joints = [ ( j + m . offset ) * ( 1 if m . direct else - 1 ) for j , m in zip ( joints , self . motors ) ] raw_joints *= self . _reversed return [ 0 ] + [ deg2rad ( j ) for j in raw_joints ] + [ 0 ] | Convert from poppy representation to IKPY internal representation . | 134 | 13 |
232,629 | def convert_from_ik_angles ( self , joints ) : if len ( joints ) != len ( self . motors ) + 2 : raise ValueError ( 'Incompatible data, len(joints) should be {}!' . format ( len ( self . motors ) + 2 ) ) joints = [ rad2deg ( j ) for j in joints [ 1 : - 1 ] ] joints *= self . _reversed return [ ( j * ( 1 if m . direct else - 1 ) ) - m . offset for j , m in zip ( joints , self . motors ) ] | Convert from IKPY internal representation to poppy representation . | 124 | 13 |
232,630 | def factory_reset ( self , ids , except_ids = False , except_baudrate_and_ids = False ) : mode = ( 0x02 if except_baudrate_and_ids else 0x01 if except_ids else 0xFF ) for id in ids : try : self . _send_packet ( self . _protocol . DxlResetPacket ( id , mode ) ) except ( DxlTimeoutError , DxlCommunicationError ) : pass | Reset all motors on the bus to their factory default settings . | 110 | 13 |
232,631 | def stop ( self , wait = True ) : logger . info ( "Primitive %s stopped." , self ) StoppableThread . stop ( self , wait ) | Requests the primitive to stop . | 34 | 7 |
232,632 | def recent_update_frequencies ( self ) : return list ( reversed ( [ ( 1.0 / p ) for p in numpy . diff ( self . _recent_updates ) ] ) ) | Returns the 10 most recent update frequencies . | 44 | 8 |
232,633 | def goto_position ( self , position , duration , control = None , wait = False ) : if control is None : control = self . goto_behavior if control == 'minjerk' : goto_min_jerk = GotoMinJerk ( self , position , duration ) goto_min_jerk . start ( ) if wait : goto_min_jerk . wait_to_stop ( ) elif control == 'dummy' : dp = abs ( self . present_position - position ) speed = ( dp / float ( duration ) ) if duration > 0 else numpy . inf self . moving_speed = speed self . goal_position = position if wait : time . sleep ( duration ) | Automatically sets the goal position and the moving speed to reach the desired position within the duration . | 152 | 19 |
232,634 | def add_tracked_motors ( self , tracked_motors ) : new_mockup_motors = map ( self . get_mockup_motor , tracked_motors ) self . tracked_motors = list ( set ( self . tracked_motors + new_mockup_motors ) ) | Add new motors to the recording | 72 | 6 |
232,635 | def update ( self ) : with self . syncing : for m in self . _motors : to_set = defaultdict ( list ) for p in self . _prim : for key , val in getattr ( p . robot , m . name ) . _to_set . iteritems ( ) : to_set [ key ] . append ( val ) for key , val in to_set . iteritems ( ) : if key == 'led' : colors = set ( val ) if len ( colors ) > 1 : colors -= { 'off' } filtred_val = colors . pop ( ) else : filtred_val = self . _filter ( val ) logger . debug ( 'Combined %s.%s from %s to %s' , m . name , key , val , filtred_val ) setattr ( m , key , filtred_val ) [ p . _synced . set ( ) for p in self . _prim ] | Combined at a predefined frequency the request orders and affect them to the real motors . | 209 | 18 |
232,636 | def stop ( self ) : for p in self . primitives [ : ] : p . stop ( ) StoppableLoopThread . stop ( self ) | Stop the primitive manager . | 31 | 5 |
232,637 | def load_scene ( self , scene_path , start = False ) : self . stop_simulation ( ) if not os . path . exists ( scene_path ) : raise IOError ( "No such file or directory: '{}'" . format ( scene_path ) ) self . call_remote_api ( 'simxLoadScene' , scene_path , True ) if start : self . start_simulation ( ) | Loads a scene on the V - REP server . | 92 | 12 |
232,638 | def get_motor_position ( self , motor_name ) : return self . call_remote_api ( 'simxGetJointPosition' , self . get_object_handle ( motor_name ) , streaming = True ) | Gets the motor current position . | 50 | 7 |
232,639 | def set_motor_position ( self , motor_name , position ) : self . call_remote_api ( 'simxSetJointTargetPosition' , self . get_object_handle ( motor_name ) , position , sending = True ) | Sets the motor target position . | 54 | 7 |
232,640 | def set_motor_force ( self , motor_name , force ) : self . call_remote_api ( 'simxSetJointForce' , self . get_object_handle ( motor_name ) , force , sending = True ) | Sets the maximum force or torque that a joint can exert . | 53 | 13 |
232,641 | def get_object_position ( self , object_name , relative_to_object = None ) : h = self . get_object_handle ( object_name ) relative_handle = ( - 1 if relative_to_object is None else self . get_object_handle ( relative_to_object ) ) return self . call_remote_api ( 'simxGetObjectPosition' , h , relative_handle , streaming = True ) | Gets the object position . | 94 | 6 |
232,642 | def set_object_position ( self , object_name , position = [ 0 , 0 , 0 ] ) : h = self . get_object_handle ( object_name ) return self . call_remote_api ( 'simxSetObjectPosition' , h , - 1 , position , sending = True ) | Sets the object position . | 66 | 6 |
232,643 | def get_object_handle ( self , obj ) : if obj not in self . _object_handles : self . _object_handles [ obj ] = self . _get_object_handle ( obj = obj ) return self . _object_handles [ obj ] | Gets the vrep object handle . | 59 | 8 |
232,644 | def get_collision_state ( self , collision_name ) : return self . call_remote_api ( 'simxReadCollision' , self . get_collision_handle ( collision_name ) , streaming = True ) | Gets the collision state . | 50 | 6 |
232,645 | def get_collision_handle ( self , collision ) : if collision not in self . _object_handles : h = self . _get_collision_handle ( collision ) self . _object_handles [ collision ] = h return self . _object_handles [ collision ] | Gets a vrep collisions handle . | 62 | 8 |
232,646 | def change_object_name ( self , old_name , new_name ) : h = self . _get_object_handle ( old_name ) if old_name in self . _object_handles : self . _object_handles . pop ( old_name ) lua_code = "simSetObjectName({}, '{}')" . format ( h , new_name ) self . _inject_lua_code ( lua_code ) | Change object name | 101 | 3 |
232,647 | def _create_pure_shape ( self , primitive_type , options , sizes , mass , precision ) : lua_code = "simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})" . format ( primitive_type , options , sizes [ 0 ] , sizes [ 1 ] , sizes [ 2 ] , mass , precision [ 0 ] , precision [ 1 ] ) self . _inject_lua_code ( lua_code ) | Create Pure Shape | 104 | 3 |
232,648 | def _inject_lua_code ( self , lua_code ) : msg = ( ctypes . c_ubyte * len ( lua_code ) ) . from_buffer_copy ( lua_code . encode ( ) ) self . call_remote_api ( 'simxWriteStringStream' , 'my_lua_code' , msg ) | Sends raw lua code and evaluate it wihtout any checking! | 79 | 15 |
232,649 | def call_remote_api ( self , func_name , * args , * * kwargs ) : f = getattr ( remote_api , func_name ) mode = self . _extract_mode ( kwargs ) kwargs [ 'operationMode' ] = vrep_mode [ mode ] # hard_retry = True if '_force' in kwargs : del kwargs [ '_force' ] _force = True else : _force = False for _ in range ( VrepIO . MAX_ITER ) : with self . _lock : ret = f ( self . client_id , * args , * * kwargs ) if _force : return if mode == 'sending' or isinstance ( ret , int ) : err , res = ret , None else : err , res = ret [ 0 ] , ret [ 1 : ] res = res [ 0 ] if len ( res ) == 1 else res err = [ bool ( ( err >> i ) & 1 ) for i in range ( len ( vrep_error ) ) ] if remote_api . simx_return_novalue_flag not in err : break time . sleep ( VrepIO . TIMEOUT ) # if any(err) and hard_retry: # print "HARD RETRY" # self.stop_simulation() #nope # # notconnected = True # while notconnected: # self.close() # close_all_connections() # time.sleep(0.5) # try: # self.open_io() # notconnected = False # except: # print 'CONNECTION ERROR' # pass # # self.start_simulation() # # with self._lock: # ret = f(self.client_id, *args, **kwargs) # # if mode == 'sending' or isinstance(ret, int): # err, res = ret, None # else: # err, res = ret[0], ret[1:] # res = res[0] if len(res) == 1 else res # # err = [bool((err >> i) & 1) for i in range(len(vrep_error))] # # return res if any ( err ) : msg = ' ' . join ( [ vrep_error [ 2 ** i ] for i , e in enumerate ( err ) if e ] ) raise VrepIOErrors ( msg ) return res | Calls any remote API func in a thread_safe way . | 523 | 13 |
232,650 | def run ( self , * * kwargs ) : try : loop = IOLoop ( ) app = self . make_app ( ) app . listen ( self . port ) loop . start ( ) except socket . error as serr : # Re raise the socket error if not "[Errno 98] Address already in use" if serr . errno != errno . EADDRINUSE : raise serr else : logger . warning ( 'The webserver port {} is already used. May be the HttpRobotServer is already running or another software is using this port.' . format ( self . port ) ) | Start the tornado server run forever | 132 | 6 |
232,651 | def close ( self , _force_lock = False ) : if not self . closed : with self . __force_lock ( _force_lock ) or self . _serial_lock : self . _serial . close ( ) self . __used_ports . remove ( self . port ) logger . info ( "Closing port '%s'" , self . port , extra = { 'port' : self . port , 'baudrate' : self . baudrate , 'timeout' : self . timeout } ) | Closes the serial communication if opened . | 110 | 8 |
232,652 | def ping ( self , id ) : pp = self . _protocol . DxlPingPacket ( id ) try : self . _send_packet ( pp , error_handler = None ) return True except DxlTimeoutError : return False | Pings the motor with the specified id . | 54 | 9 |
232,653 | def scan ( self , ids = range ( 254 ) ) : return [ id for id in ids if self . ping ( id ) ] | Pings all ids within the specified list by default it finds all the motors connected to the bus . | 30 | 21 |
232,654 | def get_model ( self , ids ) : to_get_ids = [ i for i in ids if i not in self . _known_models ] models = [ dxl_to_model ( m ) for m in self . _get_model ( to_get_ids , convert = False ) ] self . _known_models . update ( zip ( to_get_ids , models ) ) return tuple ( self . _known_models [ id ] for id in ids ) | Gets the model for the specified motors . | 106 | 9 |
232,655 | def change_baudrate ( self , baudrate_for_ids ) : self . _change_baudrate ( baudrate_for_ids ) for motor_id in baudrate_for_ids : if motor_id in self . _known_models : del self . _known_models [ motor_id ] if motor_id in self . _known_mode : del self . _known_mode [ motor_id ] | Changes the baudrate of the specified motors . | 96 | 10 |
232,656 | def get_status_return_level ( self , ids , * * kwargs ) : convert = kwargs [ 'convert' ] if 'convert' in kwargs else self . _convert srl = [ ] for id in ids : try : srl . extend ( self . _get_status_return_level ( ( id , ) , error_handler = None , convert = convert ) ) except DxlTimeoutError as e : if self . ping ( id ) : srl . append ( 'never' if convert else 0 ) else : if self . _error_handler : self . _error_handler . handle_timeout ( e ) return ( ) else : raise e return tuple ( srl ) | Gets the status level for the specified motors . | 158 | 10 |
232,657 | def set_status_return_level ( self , srl_for_id , * * kwargs ) : convert = kwargs [ 'convert' ] if 'convert' in kwargs else self . _convert if convert : srl_for_id = dict ( zip ( srl_for_id . keys ( ) , [ ( 'never' , 'read' , 'always' ) . index ( s ) for s in srl_for_id . values ( ) ] ) ) self . _set_status_return_level ( srl_for_id , convert = False ) | Sets status return level to the specified motors . | 133 | 10 |
232,658 | def switch_led_on ( self , ids ) : self . _set_LED ( dict ( zip ( ids , itertools . repeat ( True ) ) ) ) | Switches on the LED of the motors with the specified ids . | 38 | 14 |
232,659 | def switch_led_off ( self , ids ) : self . _set_LED ( dict ( zip ( ids , itertools . repeat ( False ) ) ) ) | Switches off the LED of the motors with the specified ids . | 38 | 14 |
232,660 | def enable_torque ( self , ids ) : self . _set_torque_enable ( dict ( zip ( ids , itertools . repeat ( True ) ) ) ) | Enables torque of the motors with the specified ids . | 40 | 12 |
232,661 | def disable_torque ( self , ids ) : self . _set_torque_enable ( dict ( zip ( ids , itertools . repeat ( False ) ) ) ) | Disables torque of the motors with the specified ids . | 40 | 12 |
232,662 | def get_pid_gain ( self , ids , * * kwargs ) : return tuple ( [ tuple ( reversed ( t ) ) for t in self . _get_pid_gain ( ids , * * kwargs ) ] ) | Gets the pid gain for the specified motors . | 53 | 10 |
232,663 | def set_pid_gain ( self , pid_for_id , * * kwargs ) : pid_for_id = dict ( itertools . izip ( pid_for_id . iterkeys ( ) , [ tuple ( reversed ( t ) ) for t in pid_for_id . values ( ) ] ) ) self . _set_pid_gain ( pid_for_id , * * kwargs ) | Sets the pid gain to the specified motors . | 93 | 10 |
232,664 | def get_control_table ( self , ids , * * kwargs ) : error_handler = kwargs [ 'error_handler' ] if ( 'error_handler' in kwargs ) else self . _error_handler convert = kwargs [ 'convert' ] if ( 'convert' in kwargs ) else self . _convert bl = ( 'goal position speed load' , 'present position speed load' ) controls = [ c for c in self . _AbstractDxlIO__controls if c . name not in bl ] res = [ ] for id , model in zip ( ids , self . get_model ( ids ) ) : controls = [ c for c in controls if model in c . models ] controls = sorted ( controls , key = lambda c : c . address ) address = controls [ 0 ] . address length = controls [ - 1 ] . address + controls [ - 1 ] . nb_elem * controls [ - 1 ] . length rp = self . _protocol . DxlReadDataPacket ( id , address , length ) sp = self . _send_packet ( rp , error_handler = error_handler ) d = OrderedDict ( ) for c in controls : v = dxl_decode_all ( sp . parameters [ c . address : c . address + c . nb_elem * c . length ] , c . nb_elem ) d [ c . name ] = c . dxl_to_si ( v , model ) if convert else v res . append ( d ) return tuple ( res ) | Gets the full control table for the specified motors . | 350 | 11 |
232,665 | def check_motor_eprom_configuration ( config , dxl_io , motor_names ) : changed_angle_limits = { } changed_return_delay_time = { } for name in motor_names : m = config [ 'motors' ] [ name ] id = m [ 'id' ] try : old_limits = dxl_io . get_angle_limit ( ( id , ) ) [ 0 ] old_return_delay_time = dxl_io . get_return_delay_time ( ( id , ) ) [ 0 ] except IndexError : # probably a broken motor so we just skip continue if old_return_delay_time != 0 : logger . warning ( "Return delay time of %s changed from %s to 0" , name , old_return_delay_time ) changed_return_delay_time [ id ] = 0 new_limits = m [ 'angle_limit' ] if 'wheel_mode' in m and m [ 'wheel_mode' ] : dxl_io . set_wheel_mode ( [ m [ 'id' ] ] ) time . sleep ( 0.5 ) else : # TODO: we probably need a better fix for this. # dxl_io.set_joint_mode([m['id']]) d = numpy . linalg . norm ( numpy . asarray ( new_limits ) - numpy . asarray ( old_limits ) ) if d > 1 : logger . warning ( "Limits of '%s' changed from %s to %s" , name , old_limits , new_limits , extra = { 'config' : config } ) changed_angle_limits [ id ] = new_limits if changed_angle_limits : dxl_io . set_angle_limit ( changed_angle_limits ) time . sleep ( 0.5 ) if changed_return_delay_time : dxl_io . set_return_delay_time ( changed_return_delay_time ) time . sleep ( 0.5 ) | Change the angles limits depanding on the robot configuration ; Check if the return delay time is set to 0 . | 442 | 22 |
232,666 | def _get_gdcmconv ( ) : gdcmconv_executable = settings . gdcmconv_path if gdcmconv_executable is None : gdcmconv_executable = _which ( 'gdcmconv' ) if gdcmconv_executable is None : gdcmconv_executable = _which ( 'gdcmconv.exe' ) if gdcmconv_executable is None : raise ConversionError ( 'GDCMCONV_NOT_FOUND' ) return gdcmconv_executable | Get the full path to gdcmconv . If not found raise error | 120 | 15 |
232,667 | def compress_directory ( dicom_directory ) : if _is_compressed ( dicom_directory ) : return logger . info ( 'Compressing dicom files in %s' % dicom_directory ) for root , _ , files in os . walk ( dicom_directory ) : for dicom_file in files : if is_dicom_file ( os . path . join ( root , dicom_file ) ) : _compress_dicom ( os . path . join ( root , dicom_file ) ) | This function can be used to convert a folder of jpeg compressed images to an uncompressed ones | 124 | 19 |
232,668 | def is_dicom_file ( filename ) : file_stream = open ( filename , 'rb' ) file_stream . seek ( 128 ) data = file_stream . read ( 4 ) file_stream . close ( ) if data == b'DICM' : return True if settings . pydicom_read_force : try : dicom_headers = pydicom . read_file ( filename , defer_size = "1 KB" , stop_before_pixels = True , force = True ) if dicom_headers is not None : return True except : pass return False | Util function to check if file is a dicom file the first 128 bytes are preamble the next 4 bytes should contain DICM otherwise it is not a dicom | 131 | 38 |
232,669 | def _is_compressed ( dicom_file , force = False ) : header = pydicom . read_file ( dicom_file , defer_size = "1 KB" , stop_before_pixels = True , force = force ) uncompressed_types = [ "1.2.840.10008.1.2" , "1.2.840.10008.1.2.1" , "1.2.840.10008.1.2.1.99" , "1.2.840.10008.1.2.2" ] if 'TransferSyntaxUID' in header . file_meta and header . file_meta . TransferSyntaxUID in uncompressed_types : return False return True | Check if dicoms are compressed or not | 165 | 9 |
232,670 | def _decompress_dicom ( dicom_file , output_file ) : gdcmconv_executable = _get_gdcmconv ( ) subprocess . check_output ( [ gdcmconv_executable , '-w' , dicom_file , output_file ] ) | This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion | 69 | 20 |
232,671 | def dicom_diff ( file1 , file2 ) : datasets = compressed_dicom . read_file ( file1 ) , compressed_dicom . read_file ( file2 ) rep = [ ] for dataset in datasets : lines = ( str ( dataset . file_meta ) + "\n" + str ( dataset ) ) . split ( '\n' ) lines = [ line + '\n' for line in lines ] # add the newline to the end rep . append ( lines ) diff = difflib . Differ ( ) for line in diff . compare ( rep [ 0 ] , rep [ 1 ] ) : if ( line [ 0 ] == '+' ) or ( line [ 0 ] == '-' ) : sys . stdout . write ( line ) | Shows the fields that differ between two DICOM images . | 167 | 13 |
232,672 | def _get_number_of_slices ( self , slice_type ) : if slice_type == SliceType . AXIAL : return self . dimensions [ self . axial_orientation . normal_component ] elif slice_type == SliceType . SAGITTAL : return self . dimensions [ self . sagittal_orientation . normal_component ] elif slice_type == SliceType . CORONAL : return self . dimensions [ self . coronal_orientation . normal_component ] | Get the number of slices in a certain direction | 111 | 9 |
232,673 | def _get_first_header ( dicom_directory ) : # looping over all files for root , _ , file_names in os . walk ( dicom_directory ) : # go over all the files and try to read the dicom header for file_name in file_names : file_path = os . path . join ( root , file_name ) # check wither it is a dicom file if not compressed_dicom . is_dicom_file ( file_path ) : continue # read the headers return compressed_dicom . read_file ( file_path , stop_before_pixels = True , force = dicom2nifti . settings . pydicom_read_force ) # no dicom files found raise ConversionError ( 'NO_DICOM_FILES_FOUND' ) | Function to get the first dicom file form a directory and return the header Useful to determine the type of data to convert | 188 | 25 |
232,674 | def _reorient_3d ( image ) : # Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size # of the array in each direction is the same with the corresponding direction of the input image. new_image = numpy . zeros ( [ image . dimensions [ image . sagittal_orientation . normal_component ] , image . dimensions [ image . coronal_orientation . normal_component ] , image . dimensions [ image . axial_orientation . normal_component ] ] , dtype = image . nifti_data . dtype ) # Fill the new image with the values of the input image but with matching the orientation with x,y,z if image . coronal_orientation . y_inverted : for i in range ( new_image . shape [ 2 ] ) : new_image [ : , : , i ] = numpy . fliplr ( numpy . squeeze ( image . get_slice ( SliceType . AXIAL , new_image . shape [ 2 ] - 1 - i ) . original_data ) ) else : for i in range ( new_image . shape [ 2 ] ) : new_image [ : , : , i ] = numpy . fliplr ( numpy . squeeze ( image . get_slice ( SliceType . AXIAL , i ) . original_data ) ) return new_image | Reorganize the data for a 3d nifti | 311 | 12 |
232,675 | def dicom_to_nifti ( dicom_input , output_file = None ) : assert common . is_philips ( dicom_input ) if common . is_multiframe_dicom ( dicom_input ) : _assert_explicit_vr ( dicom_input ) logger . info ( 'Found multiframe dicom' ) if _is_multiframe_4d ( dicom_input ) : logger . info ( 'Found sequence type: MULTIFRAME 4D' ) return _multiframe_to_nifti ( dicom_input , output_file ) if _is_multiframe_anatomical ( dicom_input ) : logger . info ( 'Found sequence type: MULTIFRAME ANATOMICAL' ) return _multiframe_to_nifti ( dicom_input , output_file ) else : logger . info ( 'Found singleframe dicom' ) grouped_dicoms = _get_grouped_dicoms ( dicom_input ) if _is_singleframe_4d ( dicom_input ) : logger . info ( 'Found sequence type: SINGLEFRAME 4D' ) return _singleframe_to_nifti ( grouped_dicoms , output_file ) logger . info ( 'Assuming anatomical data' ) return convert_generic . dicom_to_nifti ( dicom_input , output_file ) | This is the main dicom to nifti conversion fuction for philips images . As input philips images are required . It will then determine the type of images and do the correct conversion | 327 | 40 |
232,676 | def _assert_explicit_vr ( dicom_input ) : if settings . validate_multiframe_implicit : header = dicom_input [ 0 ] if header . file_meta [ 0x0002 , 0x0010 ] . value == '1.2.840.10008.1.2' : raise ConversionError ( 'IMPLICIT_VR_ENHANCED_DICOM' ) | Assert that explicit vr is used | 91 | 8 |
232,677 | def _is_multiframe_4d ( dicom_input ) : # check if it is multi frame dicom if not common . is_multiframe_dicom ( dicom_input ) : return False header = dicom_input [ 0 ] # check if there are multiple stacks number_of_stack_slices = common . get_ss_value ( header [ Tag ( 0x2001 , 0x105f ) ] [ 0 ] [ Tag ( 0x2001 , 0x102d ) ] ) number_of_stacks = int ( int ( header . NumberOfFrames ) / number_of_stack_slices ) if number_of_stacks <= 1 : return False return True | Use this function to detect if a dicom series is a philips multiframe 4D dataset | 157 | 20 |
232,678 | def _is_singleframe_4d ( dicom_input ) : header = dicom_input [ 0 ] # check if there are stack information slice_number_mr_tag = Tag ( 0x2001 , 0x100a ) if slice_number_mr_tag not in header : return False # check if there are multiple timepoints grouped_dicoms = _get_grouped_dicoms ( dicom_input ) if len ( grouped_dicoms ) <= 1 : return False return True | Use this function to detect if a dicom series is a philips singleframe 4D dataset | 113 | 20 |
232,679 | def _is_bval_type_a ( grouped_dicoms ) : bval_tag = Tag ( 0x2001 , 0x1003 ) bvec_x_tag = Tag ( 0x2005 , 0x10b0 ) bvec_y_tag = Tag ( 0x2005 , 0x10b1 ) bvec_z_tag = Tag ( 0x2005 , 0x10b2 ) for group in grouped_dicoms : if bvec_x_tag in group [ 0 ] and _is_float ( common . get_fl_value ( group [ 0 ] [ bvec_x_tag ] ) ) and bvec_y_tag in group [ 0 ] and _is_float ( common . get_fl_value ( group [ 0 ] [ bvec_y_tag ] ) ) and bvec_z_tag in group [ 0 ] and _is_float ( common . get_fl_value ( group [ 0 ] [ bvec_z_tag ] ) ) and bval_tag in group [ 0 ] and _is_float ( common . get_fl_value ( group [ 0 ] [ bval_tag ] ) ) and common . get_fl_value ( group [ 0 ] [ bval_tag ] ) != 0 : return True return False | Check if the bvals are stored in the first of 2 currently known ways for single frame dti | 283 | 20 |
232,680 | def _is_bval_type_b ( grouped_dicoms ) : bval_tag = Tag ( 0x0018 , 0x9087 ) bvec_tag = Tag ( 0x0018 , 0x9089 ) for group in grouped_dicoms : if bvec_tag in group [ 0 ] and bval_tag in group [ 0 ] : bvec = common . get_fd_array_value ( group [ 0 ] [ bvec_tag ] , 3 ) bval = common . get_fd_value ( group [ 0 ] [ bval_tag ] ) if _is_float ( bvec [ 0 ] ) and _is_float ( bvec [ 1 ] ) and _is_float ( bvec [ 2 ] ) and _is_float ( bval ) and bval != 0 : return True return False | Check if the bvals are stored in the second of 2 currently known ways for single frame dti | 186 | 20 |
232,681 | def _multiframe_to_nifti ( dicom_input , output_file ) : # Read the multiframe dicom file logger . info ( 'Read dicom file' ) multiframe_dicom = dicom_input [ 0 ] # Create mosaic block logger . info ( 'Creating data block' ) full_block = _multiframe_to_block ( multiframe_dicom ) logger . info ( 'Creating affine' ) # Create the nifti header info affine = _create_affine_multiframe ( multiframe_dicom ) logger . info ( 'Creating nifti' ) # Convert to nifti nii_image = nibabel . Nifti1Image ( full_block , affine ) timing_parameters = multiframe_dicom . SharedFunctionalGroupsSequence [ 0 ] . MRTimingAndRelatedParametersSequence [ 0 ] first_frame = multiframe_dicom [ Tag ( 0x5200 , 0x9230 ) ] [ 0 ] common . set_tr_te ( nii_image , float ( timing_parameters . RepetitionTime ) , float ( first_frame [ 0x2005 , 0x140f ] [ 0 ] . EchoTime ) ) # Save to disk if output_file is not None : logger . info ( 'Saving nifti to disk %s' % output_file ) nii_image . to_filename ( output_file ) if _is_multiframe_diffusion_imaging ( dicom_input ) : bval_file = None bvec_file = None if output_file is not None : # Create the bval en bvec files base_path = os . path . dirname ( output_file ) base_name = os . path . splitext ( os . path . splitext ( os . path . basename ( output_file ) ) [ 0 ] ) [ 0 ] logger . info ( 'Creating bval en bvec files' ) bval_file = '%s/%s.bval' % ( base_path , base_name ) bvec_file = '%s/%s.bvec' % ( base_path , base_name ) bval , bvec , bval_file , bvec_file = _create_bvals_bvecs ( multiframe_dicom , bval_file , bvec_file , nii_image , output_file ) return { 'NII_FILE' : output_file , 'BVAL_FILE' : bval_file , 'BVEC_FILE' : bvec_file , 'NII' : nii_image , 'BVAL' : bval , 'BVEC' : bvec } return { 'NII_FILE' : output_file , 'NII' : nii_image } | This function will convert philips 4D or anatomical multiframe series to a nifti | 628 | 18 |
232,682 | def _singleframe_to_nifti ( grouped_dicoms , output_file ) : # Create mosaic block logger . info ( 'Creating data block' ) full_block = _singleframe_to_block ( grouped_dicoms ) logger . info ( 'Creating affine' ) # Create the nifti header info affine , slice_increment = common . create_affine ( grouped_dicoms [ 0 ] ) logger . info ( 'Creating nifti' ) # Convert to nifti nii_image = nibabel . Nifti1Image ( full_block , affine ) common . set_tr_te ( nii_image , float ( grouped_dicoms [ 0 ] [ 0 ] . RepetitionTime ) , float ( grouped_dicoms [ 0 ] [ 0 ] . EchoTime ) ) if output_file is not None : # Save to disk logger . info ( 'Saving nifti to disk %s' % output_file ) nii_image . to_filename ( output_file ) if _is_singleframe_diffusion_imaging ( grouped_dicoms ) : bval_file = None bvec_file = None # Create the bval en bvec files if output_file is not None : base_name = os . path . splitext ( output_file ) [ 0 ] if base_name . endswith ( '.nii' ) : base_name = os . path . splitext ( base_name ) [ 0 ] logger . info ( 'Creating bval en bvec files' ) bval_file = '%s.bval' % base_name bvec_file = '%s.bvec' % base_name nii_image , bval , bvec , bval_file , bvec_file = _create_singleframe_bvals_bvecs ( grouped_dicoms , bval_file , bvec_file , nii_image , output_file ) return { 'NII_FILE' : output_file , 'BVAL_FILE' : bval_file , 'BVEC_FILE' : bvec_file , 'NII' : nii_image , 'BVAL' : bval , 'BVEC' : bvec , 'MAX_SLICE_INCREMENT' : slice_increment } return { 'NII_FILE' : output_file , 'NII' : nii_image , 'MAX_SLICE_INCREMENT' : slice_increment } | This function will convert a philips singleframe series to a nifti | 556 | 15 |
232,683 | def _create_affine_multiframe ( multiframe_dicom ) : first_frame = multiframe_dicom [ Tag ( 0x5200 , 0x9230 ) ] [ 0 ] last_frame = multiframe_dicom [ Tag ( 0x5200 , 0x9230 ) ] [ - 1 ] # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine) image_orient1 = numpy . array ( first_frame . PlaneOrientationSequence [ 0 ] . ImageOrientationPatient ) [ 0 : 3 ] . astype ( float ) image_orient2 = numpy . array ( first_frame . PlaneOrientationSequence [ 0 ] . ImageOrientationPatient ) [ 3 : 6 ] . astype ( float ) normal = numpy . cross ( image_orient1 , image_orient2 ) delta_r = float ( first_frame [ 0x2005 , 0x140f ] [ 0 ] . PixelSpacing [ 0 ] ) delta_c = float ( first_frame [ 0x2005 , 0x140f ] [ 0 ] . PixelSpacing [ 1 ] ) image_pos = numpy . array ( first_frame . PlanePositionSequence [ 0 ] . ImagePositionPatient ) . astype ( float ) last_image_pos = numpy . array ( last_frame . PlanePositionSequence [ 0 ] . ImagePositionPatient ) . astype ( float ) number_of_stack_slices = int ( common . get_ss_value ( multiframe_dicom [ Tag ( 0x2001 , 0x105f ) ] [ 0 ] [ Tag ( 0x2001 , 0x102d ) ] ) ) delta_s = abs ( numpy . linalg . norm ( last_image_pos - image_pos ) ) / ( number_of_stack_slices - 1 ) return numpy . array ( [ [ - image_orient1 [ 0 ] * delta_c , - image_orient2 [ 0 ] * delta_r , - delta_s * normal [ 0 ] , - image_pos [ 0 ] ] , [ - image_orient1 [ 1 ] * delta_c , - image_orient2 [ 1 ] * delta_r , - delta_s * normal [ 1 ] , - image_pos [ 1 ] ] , [ image_orient1 [ 2 ] * delta_c , image_orient2 [ 2 ] * delta_r , delta_s * normal [ 2 ] , image_pos [ 2 ] ] , [ 0 , 0 , 0 , 1 ] ] ) | Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4D if in mosaic format | 592 | 30 |
232,684 | def _multiframe_to_block ( multiframe_dicom ) : # Calculate the amount of stacks and slices in the stack number_of_stack_slices = int ( common . get_ss_value ( multiframe_dicom [ Tag ( 0x2001 , 0x105f ) ] [ 0 ] [ Tag ( 0x2001 , 0x102d ) ] ) ) number_of_stacks = int ( int ( multiframe_dicom . NumberOfFrames ) / number_of_stack_slices ) # We create a numpy array size_x = multiframe_dicom . pixel_array . shape [ 2 ] size_y = multiframe_dicom . pixel_array . shape [ 1 ] size_z = number_of_stack_slices size_t = number_of_stacks # get the format format_string = common . get_numpy_type ( multiframe_dicom ) # get header info needed for ordering frame_info = multiframe_dicom [ 0x5200 , 0x9230 ] data_4d = numpy . zeros ( ( size_z , size_y , size_x , size_t ) , dtype = format_string ) # loop over each slice and insert in datablock t_location_index = _get_t_position_index ( multiframe_dicom ) for slice_index in range ( 0 , size_t * size_z ) : z_location = frame_info [ slice_index ] . FrameContentSequence [ 0 ] . InStackPositionNumber - 1 if t_location_index is None : t_location = frame_info [ slice_index ] . FrameContentSequence [ 0 ] . TemporalPositionIndex - 1 else : t_location = frame_info [ slice_index ] . FrameContentSequence [ 0 ] . DimensionIndexValues [ t_location_index ] - 1 block_data = multiframe_dicom . pixel_array [ slice_index , : , : ] # apply scaling rescale_intercept = frame_info [ slice_index ] . PixelValueTransformationSequence [ 0 ] . RescaleIntercept rescale_slope = frame_info [ slice_index ] . PixelValueTransformationSequence [ 0 ] . RescaleSlope block_data = common . do_scaling ( block_data , rescale_slope , rescale_intercept ) # switch to float if needed if block_data . dtype != data_4d . dtype : data_4d = data_4d . astype ( block_data . dtype ) data_4d [ z_location , : , : , t_location ] = block_data full_block = numpy . zeros ( ( size_x , size_y , size_z , size_t ) , dtype = data_4d . dtype ) # loop over each stack and reorganize the data for t_index in range ( 0 , size_t ) : # transpose the block so the directions are correct data_3d = numpy . transpose ( data_4d [ : , : , : , t_index ] , ( 2 , 1 , 0 ) ) # add the block the the full data full_block [ : , : , : , t_index ] = data_3d return full_block | Generate a full datablock containing all stacks | 737 | 10 |
232,685 | def _fix_diffusion_images ( bvals , bvecs , nifti , nifti_file ) : # if all zero continue of if the last bvec is not all zero continue if numpy . count_nonzero ( bvecs ) == 0 or not numpy . count_nonzero ( bvals [ - 1 ] ) == 0 : # nothing needs to be done here return nifti , bvals , bvecs # remove last elements from bvals and bvecs bvals = bvals [ : - 1 ] bvecs = bvecs [ : - 1 ] # remove last elements from the nifti new_nifti = nibabel . Nifti1Image ( nifti . get_data ( ) [ : , : , : , : - 1 ] , nifti . affine ) new_nifti . to_filename ( nifti_file ) return new_nifti , bvals , bvecs | This function will remove the last timepoint from the nifti bvals and bvecs if the last vector is 0 0 0 This is sometimes added at the end by philips | 210 | 37 |
232,686 | def dicom_to_nifti ( dicom_input , output_file ) : if len ( dicom_input ) <= 0 : raise ConversionError ( 'NO_DICOM_FILES_FOUND' ) # remove duplicate slices based on position and data dicom_input = _remove_duplicate_slices ( dicom_input ) # remove localizers based on image type dicom_input = _remove_localizers_by_imagetype ( dicom_input ) if settings . validate_slicecount : # remove_localizers based on image orientation (only valid if slicecount is validated) dicom_input = _remove_localizers_by_orientation ( dicom_input ) # validate all the dicom files for correct orientations common . validate_slicecount ( dicom_input ) if settings . validate_orientation : # validate that all slices have the same orientation common . validate_orientation ( dicom_input ) if settings . validate_orthogonal : # validate that we have an orthogonal image (to detect gantry tilting etc) common . validate_orthogonal ( dicom_input ) # sort the dicoms dicom_input = common . sort_dicoms ( dicom_input ) # validate slice increment inconsistent slice_increment_inconsistent = False if settings . validate_slice_increment : # validate that all slices have a consistent slice increment common . validate_slice_increment ( dicom_input ) elif common . is_slice_increment_inconsistent ( dicom_input ) : slice_increment_inconsistent = True # if inconsistent increment and we allow resampling then do the resampling based conversion to maintain the correct geometric shape if slice_increment_inconsistent and settings . resample : nii_image , max_slice_increment = _convert_slice_incement_inconsistencies ( dicom_input ) # do the normal conversion else : # Get data; originally z,y,x, transposed to x,y,z data = common . get_volume_pixeldata ( dicom_input ) affine , max_slice_increment = common . create_affine ( dicom_input ) # Convert to nifti nii_image = nibabel . Nifti1Image ( data , affine ) # Set TR and TE if available if Tag ( 0x0018 , 0x0081 ) in dicom_input [ 0 ] and Tag ( 0x0018 , 0x0081 ) in dicom_input [ 0 ] : common . set_tr_te ( nii_image , float ( dicom_input [ 0 ] . RepetitionTime ) , float ( dicom_input [ 0 ] . EchoTime ) ) # Save to disk if output_file is not None : logger . info ( 'Saving nifti to disk %s' % output_file ) nii_image . to_filename ( output_file ) return { 'NII_FILE' : output_file , 'NII' : nii_image , 'MAX_SLICE_INCREMENT' : max_slice_increment } | This function will convert an anatomical dicom series to a nifti | 717 | 15 |
232,687 | def _convert_slice_incement_inconsistencies ( dicom_input ) : # Estimate the "first" slice increment based on the 2 first slices increment = numpy . array ( dicom_input [ 0 ] . ImagePositionPatient ) - numpy . array ( dicom_input [ 1 ] . ImagePositionPatient ) # Create as many volumes as many changes in slice increment. NB Increments might be repeated in different volumes max_slice_increment = 0 slice_incement_groups = [ ] current_group = [ dicom_input [ 0 ] , dicom_input [ 1 ] ] previous_image_position = numpy . array ( dicom_input [ 1 ] . ImagePositionPatient ) for dicom in dicom_input [ 2 : ] : current_image_position = numpy . array ( dicom . ImagePositionPatient ) current_increment = previous_image_position - current_image_position max_slice_increment = max ( max_slice_increment , numpy . linalg . norm ( current_increment ) ) if numpy . allclose ( increment , current_increment , rtol = 0.05 , atol = 0.1 ) : current_group . append ( dicom ) if not numpy . allclose ( increment , current_increment , rtol = 0.05 , atol = 0.1 ) : slice_incement_groups . append ( current_group ) current_group = [ current_group [ - 1 ] , dicom ] increment = current_increment previous_image_position = current_image_position slice_incement_groups . append ( current_group ) # Create nibabel objects for each volume based on the corresponding headers slice_incement_niftis = [ ] for dicom_slices in slice_incement_groups : data = common . get_volume_pixeldata ( dicom_slices ) affine , _ = common . create_affine ( dicom_slices ) slice_incement_niftis . append ( nibabel . Nifti1Image ( data , affine ) ) nifti_volume = resample . resample_nifti_images ( slice_incement_niftis ) return nifti_volume , max_slice_increment | If there is slice increment inconsistency detected for the moment CT images then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment | 525 | 40 |
232,688 | def is_hitachi ( dicom_input ) : # read dicom header header = dicom_input [ 0 ] if 'Manufacturer' not in header or 'Modality' not in header : return False # we try generic conversion in these cases # check if Modality is mr if header . Modality . upper ( ) != 'MR' : return False # check if manufacturer is hitachi if 'HITACHI' not in header . Manufacturer . upper ( ) : return False return True | Use this function to detect if a dicom series is a hitachi dataset | 108 | 16 |
232,689 | def is_ge ( dicom_input ) : # read dicom header header = dicom_input [ 0 ] if 'Manufacturer' not in header or 'Modality' not in header : return False # we try generic conversion in these cases # check if Modality is mr if header . Modality . upper ( ) != 'MR' : return False # check if manufacturer is GE if 'GE MEDICAL SYSTEMS' not in header . Manufacturer . upper ( ) : return False return True | Use this function to detect if a dicom series is a GE dataset | 107 | 15 |
232,690 | def is_philips ( dicom_input ) : # read dicom header header = dicom_input [ 0 ] if 'Manufacturer' not in header or 'Modality' not in header : return False # we try generic conversion in these cases # check if Modality is mr if header . Modality . upper ( ) != 'MR' : return False # check if manufacturer is Philips if 'PHILIPS' not in header . Manufacturer . upper ( ) : return False return True | Use this function to detect if a dicom series is a philips dataset | 106 | 16 |
232,691 | def is_siemens ( dicom_input ) : # read dicom header header = dicom_input [ 0 ] # check if manufacturer is Siemens if 'Manufacturer' not in header or 'Modality' not in header : return False # we try generic conversion in these cases # check if Modality is mr if header . Modality . upper ( ) != 'MR' : return False if 'SIEMENS' not in header . Manufacturer . upper ( ) : return False return True | Use this function to detect if a dicom series is a siemens dataset | 108 | 17 |
232,692 | def _get_slice_pixeldata ( dicom_slice ) : data = dicom_slice . pixel_array # fix overflow issues for signed data where BitsStored is lower than BitsAllocated and PixelReprentation = 1 (signed) # for example a hitachi mri scan can have BitsAllocated 16 but BitsStored is 12 and HighBit 11 if dicom_slice . BitsAllocated != dicom_slice . BitsStored and dicom_slice . HighBit == dicom_slice . BitsStored - 1 and dicom_slice . PixelRepresentation == 1 : if dicom_slice . BitsAllocated == 16 : data = data . astype ( numpy . int16 ) # assert that it is a signed type max_value = pow ( 2 , dicom_slice . HighBit ) - 1 invert_value = - 1 ^ max_value data [ data > max_value ] = numpy . bitwise_or ( data [ data > max_value ] , invert_value ) pass return apply_scaling ( data , dicom_slice ) | the slice and intercept calculation can cause the slices to have different dtypes we should get the correct dtype that can cover all of them | 246 | 27 |
232,693 | def set_fd_value ( tag , value ) : if tag . VR == 'OB' or tag . VR == 'UN' : value = struct . pack ( 'd' , value ) tag . value = value | Setters for data that also work with implicit transfersyntax | 46 | 12 |
232,694 | def set_ss_value ( tag , value ) : if tag . VR == 'OB' or tag . VR == 'UN' : value = struct . pack ( 'h' , value ) tag . value = value | Setter for data that also work with implicit transfersyntax | 46 | 12 |
232,695 | def apply_scaling ( data , dicom_headers ) : # Apply the rescaling if needed private_scale_slope_tag = Tag ( 0x2005 , 0x100E ) private_scale_intercept_tag = Tag ( 0x2005 , 0x100D ) if 'RescaleSlope' in dicom_headers or 'RescaleIntercept' in dicom_headers or private_scale_slope_tag in dicom_headers or private_scale_intercept_tag in dicom_headers : rescale_slope = 1 rescale_intercept = 0 if 'RescaleSlope' in dicom_headers : rescale_slope = dicom_headers . RescaleSlope if 'RescaleIntercept' in dicom_headers : rescale_intercept = dicom_headers . RescaleIntercept # try: # # this section can sometimes fail due to unknown private fields # if private_scale_slope_tag in dicom_headers: # private_scale_slope = float(dicom_headers[private_scale_slope_tag].value) # if private_scale_slope_tag in dicom_headers: # private_scale_slope = float(dicom_headers[private_scale_slope_tag].value) # except: # pass return do_scaling ( data , rescale_slope , rescale_intercept ) else : return data | Rescale the data based on the RescaleSlope and RescaleOffset Based on the scaling from pydicomseries | 329 | 26 |
232,696 | def write_bvec_file ( bvecs , bvec_file ) : if bvec_file is None : return logger . info ( 'Saving BVEC file: %s' % bvec_file ) with open ( bvec_file , 'w' ) as text_file : # Map a dicection to string join them using a space and write to the file text_file . write ( '%s\n' % ' ' . join ( map ( str , bvecs [ : , 0 ] ) ) ) text_file . write ( '%s\n' % ' ' . join ( map ( str , bvecs [ : , 1 ] ) ) ) text_file . write ( '%s\n' % ' ' . join ( map ( str , bvecs [ : , 2 ] ) ) ) | Write an array of bvecs to a bvec file | 182 | 12 |
232,697 | def write_bval_file ( bvals , bval_file ) : if bval_file is None : return logger . info ( 'Saving BVAL file: %s' % bval_file ) with open ( bval_file , 'w' ) as text_file : # join the bvals using a space and write to the file text_file . write ( '%s\n' % ' ' . join ( map ( str , bvals ) ) ) | Write an array of bvals to a bval file | 103 | 11 |
232,698 | def sort_dicoms ( dicoms ) : # find most significant axis to use during sorting # the original way of sorting (first x than y than z) does not work in certain border situations # where for exampe the X will only slightly change causing the values to remain equal on multiple slices # messing up the sorting completely) dicom_input_sorted_x = sorted ( dicoms , key = lambda x : ( x . ImagePositionPatient [ 0 ] ) ) dicom_input_sorted_y = sorted ( dicoms , key = lambda x : ( x . ImagePositionPatient [ 1 ] ) ) dicom_input_sorted_z = sorted ( dicoms , key = lambda x : ( x . ImagePositionPatient [ 2 ] ) ) diff_x = abs ( dicom_input_sorted_x [ - 1 ] . ImagePositionPatient [ 0 ] - dicom_input_sorted_x [ 0 ] . ImagePositionPatient [ 0 ] ) diff_y = abs ( dicom_input_sorted_y [ - 1 ] . ImagePositionPatient [ 1 ] - dicom_input_sorted_y [ 0 ] . ImagePositionPatient [ 1 ] ) diff_z = abs ( dicom_input_sorted_z [ - 1 ] . ImagePositionPatient [ 2 ] - dicom_input_sorted_z [ 0 ] . ImagePositionPatient [ 2 ] ) if diff_x >= diff_y and diff_x >= diff_z : return dicom_input_sorted_x if diff_y >= diff_x and diff_y >= diff_z : return dicom_input_sorted_y if diff_z >= diff_x and diff_z >= diff_y : return dicom_input_sorted_z | Sort the dicoms based om the image possition patient | 408 | 12 |
232,699 | def validate_orientation ( dicoms ) : first_image_orient1 = numpy . array ( dicoms [ 0 ] . ImageOrientationPatient ) [ 0 : 3 ] first_image_orient2 = numpy . array ( dicoms [ 0 ] . ImageOrientationPatient ) [ 3 : 6 ] for dicom_ in dicoms : # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine) image_orient1 = numpy . array ( dicom_ . ImageOrientationPatient ) [ 0 : 3 ] image_orient2 = numpy . array ( dicom_ . ImageOrientationPatient ) [ 3 : 6 ] if not numpy . allclose ( image_orient1 , first_image_orient1 , rtol = 0.001 , atol = 0.001 ) or not numpy . allclose ( image_orient2 , first_image_orient2 , rtol = 0.001 , atol = 0.001 ) : logger . warning ( 'Image orientations not consistent through all slices' ) logger . warning ( '---------------------------------------------------------' ) logger . warning ( '%s %s' % ( image_orient1 , first_image_orient1 ) ) logger . warning ( '%s %s' % ( image_orient2 , first_image_orient2 ) ) logger . warning ( '---------------------------------------------------------' ) raise ConversionValidationError ( 'IMAGE_ORIENTATION_INCONSISTENT' ) | Validate that all dicoms have the same orientation | 353 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.