idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
50,600 | def _get_next_nn_id ( self ) : self . _nn_id = self . _nn_id + 1 if self . _nn_id < 126 else 1 return self . _nn_id * 2 | Get the next nearest neighbour ID . |
50,601 | def _send_ffs ( self , pid , n_blocks , fr ) : sfr = fr | ( 1 << 31 ) self . _send_scp ( 255 , 255 , 0 , SCPCommands . nearest_neighbour_packet , ( NNCommands . flood_fill_start << 24 ) | ( pid << 16 ) | ( n_blocks << 8 ) , 0x0 , sfr ) | Send a flood - fill start packet . |
50,602 | def _send_ffcs ( self , region , core_mask , fr ) : arg1 = ( NNCommands . flood_fill_core_select << 24 ) | core_mask arg2 = region self . _send_scp ( 255 , 255 , 0 , SCPCommands . nearest_neighbour_packet , arg1 , arg2 , fr ) | Send a flood - fill core select packet . |
50,603 | def _send_ffd ( self , pid , aplx_data , address ) : block = 0 pos = 0 aplx_size = len ( aplx_data ) while pos < aplx_size : data = aplx_data [ pos : pos + self . scp_data_length ] data_size = len ( data ) size = data_size // 4 - 1 arg1 = ( NNConstants . forward << 24 | NNConstants . retry << 16 | pid ) arg2 = ( block << 16 ) | ( size << 8 ) self . _send_scp ( 255 , 255 , 0 , SCPCommands . flood_fill_data , arg1 , arg2 , address , data ) block += 1 address += data_size pos += data_size | Send flood - fill data packets . |
50,604 | def _send_ffe ( self , pid , app_id , app_flags , fr ) : arg1 = ( NNCommands . flood_fill_end << 24 ) | pid arg2 = ( app_id << 24 ) | ( app_flags << 18 ) self . _send_scp ( 255 , 255 , 0 , SCPCommands . nearest_neighbour_packet , arg1 , arg2 , fr ) | Send a flood - fill end packet . |
50,605 | def flood_fill_aplx ( self , * args , ** kwargs ) : application_map = { } if len ( args ) == 1 : application_map = args [ 0 ] elif len ( args ) == 2 : application_map = { args [ 0 ] : args [ 1 ] } else : raise TypeError ( "flood_fill_aplx: accepts either 1 or 2 positional arguments: " "a map of filenames to targets OR a single filename and its" "targets" ) app_id = kwargs . pop ( "app_id" ) flags = 0x0000 if kwargs . pop ( "wait" ) : flags |= AppFlags . wait fr = NNConstants . forward << 8 | NNConstants . retry for ( aplx , targets ) in iteritems ( application_map ) : fills = regions . compress_flood_fill_regions ( targets ) with open ( aplx , "rb" ) as f : aplx_data = f . read ( ) n_blocks = ( ( len ( aplx_data ) + self . scp_data_length - 1 ) // self . scp_data_length ) pid = self . _get_next_nn_id ( ) self . _send_ffs ( pid , n_blocks , fr ) for ( region , cores ) in fills : self . _send_ffcs ( region , cores , fr ) base_address = self . read_struct_field ( "sv" , "sdram_sys" , 255 , 255 ) self . _send_ffd ( pid , aplx_data , base_address ) self . _send_ffe ( pid , app_id , flags , fr ) | Unreliably flood - fill APLX to a set of application cores . |
50,606 | def load_application ( self , * args , ** kwargs ) : app_id = kwargs . pop ( "app_id" ) wait = kwargs . pop ( "wait" ) n_tries = kwargs . pop ( "n_tries" ) app_start_delay = kwargs . pop ( "app_start_delay" ) use_count = kwargs . pop ( "use_count" , True ) application_map = { } if len ( args ) == 1 : application_map = args [ 0 ] elif len ( args ) == 2 : application_map = { args [ 0 ] : args [ 1 ] } else : raise TypeError ( "load_application: accepts either 1 or 2 positional arguments:" "a map of filenames to targets OR a single filename and its" "targets" ) core_count = sum ( len ( cores ) for ts in six . itervalues ( application_map ) for cores in six . itervalues ( ts ) ) unloaded = application_map tries = 0 while unloaded != { } and tries <= n_tries : tries += 1 self . flood_fill_aplx ( unloaded , app_id = app_id , wait = True ) time . sleep ( app_start_delay ) if ( use_count and core_count == self . count_cores_in_state ( "wait" , app_id ) ) : unloaded = { } continue new_unloadeds = dict ( ) for app_name , targets in iteritems ( unloaded ) : unloaded_targets = { } for ( x , y ) , cores in iteritems ( targets ) : unloaded_cores = set ( ) for p in cores : state = consts . AppState ( self . read_vcpu_struct_field ( "cpu_state" , x , y , p ) ) if state is not consts . AppState . wait : unloaded_cores . add ( p ) if len ( unloaded_cores ) > 0 : unloaded_targets [ ( x , y ) ] = unloaded_cores if len ( unloaded_targets ) > 0 : new_unloadeds [ app_name ] = unloaded_targets unloaded = new_unloadeds if unloaded != { } : raise SpiNNakerLoadingError ( unloaded ) if not wait : self . send_signal ( "start" , app_id ) | Load an application to a set of application cores . |
50,607 | def send_signal ( self , signal , app_id ) : if isinstance ( signal , str ) : try : signal = getattr ( consts . AppSignal , signal ) except AttributeError : pass if signal not in consts . AppSignal : raise ValueError ( "send_signal: Cannot transmit signal of type {}" . format ( repr ( signal ) ) ) arg1 = consts . signal_types [ signal ] arg2 = ( signal << 16 ) | 0xff00 | app_id arg3 = 0x0000ffff self . _send_scp ( 255 , 255 , 0 , SCPCommands . signal , arg1 , arg2 , arg3 ) | Transmit a signal to applications . |
50,608 | def count_cores_in_state ( self , state , app_id ) : if ( isinstance ( state , collections . Iterable ) and not isinstance ( state , str ) ) : return sum ( self . count_cores_in_state ( s , app_id ) for s in state ) if isinstance ( state , str ) : try : state = getattr ( consts . AppState , state ) except AttributeError : pass if state not in consts . AppState : raise ValueError ( "count_cores_in_state: Unknown state {}" . format ( repr ( state ) ) ) region = 0x0000ffff level = ( region >> 16 ) & 0x3 mask = region & 0x0000ffff arg1 = consts . diagnostic_signal_types [ consts . AppDiagnosticSignal . count ] arg2 = ( ( level << 26 ) | ( 1 << 22 ) | ( consts . AppDiagnosticSignal . count << 20 ) | ( state << 16 ) | ( 0xff << 8 ) | app_id ) arg3 = mask return self . _send_scp ( 255 , 255 , 0 , SCPCommands . signal , arg1 , arg2 , arg3 ) . arg1 | Count the number of cores in a given state . |
50,609 | def wait_for_cores_to_reach_state ( self , state , count , app_id , poll_interval = 0.1 , timeout = None ) : if timeout is not None : timeout_time = time . time ( ) + timeout while True : cur_count = self . count_cores_in_state ( state , app_id ) if cur_count >= count : break if timeout is not None and time . time ( ) > timeout_time : break time . sleep ( poll_interval ) return cur_count | Block until the specified number of cores reach the specified state . |
50,610 | def load_routing_tables ( self , routing_tables , app_id ) : for ( x , y ) , table in iteritems ( routing_tables ) : self . load_routing_table_entries ( table , x = x , y = y , app_id = app_id ) | Allocate space for an load multicast routing tables . |
50,611 | def load_routing_table_entries ( self , entries , x , y , app_id ) : count = len ( entries ) rv = self . _send_scp ( x , y , 0 , SCPCommands . alloc_free , ( app_id << 8 ) | consts . AllocOperations . alloc_rtr , count ) rtr_base = rv . arg1 if rtr_base == 0 : raise SpiNNakerRouterError ( count , x , y ) buf = self . read_struct_field ( "sv" , "sdram_sys" , x , y ) data = bytearray ( 16 * len ( entries ) ) for i , entry in enumerate ( entries ) : route = 0x00000000 for r in entry . route : route |= 1 << r struct . pack_into ( consts . RTE_PACK_STRING , data , i * 16 , i , 0 , route , entry . key , entry . mask ) self . write ( buf , data , x , y ) self . _send_scp ( x , y , 0 , SCPCommands . router , ( count << 16 ) | ( app_id << 8 ) | consts . RouterOperations . load , buf , rtr_base ) | Allocate space for and load multicast routing table entries into the router of a SpiNNaker chip . |
50,612 | def get_routing_table_entries ( self , x , y ) : rtr_addr = self . read_struct_field ( "sv" , "rtr_copy" , x , y ) read_size = struct . calcsize ( consts . RTE_PACK_STRING ) rtr_data = self . read ( rtr_addr , consts . RTR_ENTRIES * read_size , x , y ) table = list ( ) while len ( rtr_data ) > 0 : entry , rtr_data = rtr_data [ : read_size ] , rtr_data [ read_size : ] table . append ( unpack_routing_table_entry ( entry ) ) return table | Dump the multicast routing table of a given chip . |
50,613 | def clear_routing_table_entries ( self , x , y , app_id ) : arg1 = ( app_id << 8 ) | consts . AllocOperations . free_rtr_by_app self . _send_scp ( x , y , 0 , SCPCommands . alloc_free , arg1 , 0x1 ) | Clear the routing table entries associated with a given application . |
50,614 | def get_p2p_routing_table ( self , x , y ) : table = { } p2p_dims = self . read_struct_field ( "sv" , "p2p_dims" , x , y ) width = ( p2p_dims >> 8 ) & 0xFF height = ( p2p_dims >> 0 ) & 0xFF col_words = ( ( ( height + 7 ) // 8 ) * 4 ) for col in range ( width ) : raw_table_col = self . read ( consts . SPINNAKER_RTR_P2P + ( ( ( 256 * col ) // 8 ) * 4 ) , col_words , x , y ) row = 0 while row < height : raw_word , raw_table_col = raw_table_col [ : 4 ] , raw_table_col [ 4 : ] word , = struct . unpack ( "<I" , raw_word ) for entry in range ( min ( 8 , height - row ) ) : table [ ( col , row ) ] = consts . P2PTableEntry ( ( word >> ( 3 * entry ) ) & 0b111 ) row += 1 return table | Dump the contents of a chip s P2P routing table . |
50,615 | def get_chip_info ( self , x , y ) : info = self . _send_scp ( x , y , 0 , SCPCommands . info , expected_args = 3 ) num_cores = info . arg1 & 0x1F working_links = set ( link for link in Links if ( info . arg1 >> ( 8 + link ) ) & 1 ) largest_free_rtr_mc_block = ( info . arg1 >> 14 ) & 0x7FF ethernet_up = bool ( info . arg1 & ( 1 << 25 ) ) data = struct . unpack_from ( "<18BHI" , info . data ) core_states = [ consts . AppState ( c ) for c in data [ : 18 ] ] local_ethernet_chip = ( ( data [ 18 ] >> 8 ) & 0xFF , ( data [ 18 ] >> 0 ) & 0xFF ) ip_address = "." . join ( str ( ( data [ 19 ] >> i ) & 0xFF ) for i in range ( 0 , 32 , 8 ) ) return ChipInfo ( num_cores = num_cores , core_states = core_states [ : num_cores ] , working_links = working_links , largest_free_sdram_block = info . arg2 , largest_free_sram_block = info . arg3 , largest_free_rtr_mc_block = largest_free_rtr_mc_block , ethernet_up = ethernet_up , ip_address = ip_address , local_ethernet_chip = local_ethernet_chip , ) | Get general information about the resources available on a chip . |
50,616 | def get_system_info ( self , x = 255 , y = 255 ) : p2p_tables = self . get_p2p_routing_table ( x , y ) max_x = max ( x_ for ( x_ , y_ ) , r in iteritems ( p2p_tables ) if r != consts . P2PTableEntry . none ) max_y = max ( y_ for ( x_ , y_ ) , r in iteritems ( p2p_tables ) if r != consts . P2PTableEntry . none ) sys_info = SystemInfo ( max_x + 1 , max_y + 1 ) for ( x , y ) , p2p_route in iteritems ( p2p_tables ) : if p2p_route != consts . P2PTableEntry . none : try : sys_info [ ( x , y ) ] = self . get_chip_info ( x , y ) except SCPError : pass return sys_info | Discover the integrity and resource availability of a whole SpiNNaker system . |
50,617 | def ethernet_connected_chips ( self ) : for xy , chip_info in six . iteritems ( self ) : if chip_info . ethernet_up : yield ( xy , chip_info . ip_address ) | Iterate over the coordinates of Ethernet connected chips . |
50,618 | def dead_chips ( self ) : for x in range ( self . width ) : for y in range ( self . height ) : if ( x , y ) not in self : yield ( x , y ) | Generate the coordinates of all dead chips . |
50,619 | def links ( self ) : for ( x , y ) , chip_info in iteritems ( self ) : for link in chip_info . working_links : yield ( x , y , link ) | Generate the coordinates of all working links . |
50,620 | def dead_links ( self ) : for ( x , y ) , chip_info in iteritems ( self ) : for link in Links : if link not in chip_info . working_links : yield ( x , y , link ) | Generate the coordinates of all dead links leaving working chips . |
50,621 | def cores ( self ) : for ( x , y ) , chip_info in iteritems ( self ) : for p , state in enumerate ( chip_info . core_states ) : yield ( x , y , p , state ) | Generate the set of all cores in the system . |
50,622 | def read ( self , n_bytes = - 1 ) : if n_bytes < 0 : n_bytes = self . _end_address - self . address if self . address + n_bytes > self . _end_address : new_n_bytes = self . _end_address - self . address warnings . warn ( "read truncated from {} to {} bytes" . format ( n_bytes , new_n_bytes ) , TruncationWarning , stacklevel = 3 ) n_bytes = new_n_bytes if n_bytes <= 0 : return b'' data = self . _parent . _perform_read ( self . address , n_bytes ) self . _offset += n_bytes return data | Read a number of bytes from the memory . |
50,623 | def write ( self , bytes ) : if self . address + len ( bytes ) > self . _end_address : n_bytes = self . _end_address - self . address warnings . warn ( "write truncated from {} to {} bytes" . format ( len ( bytes ) , n_bytes ) , TruncationWarning , stacklevel = 3 ) bytes = bytes [ : n_bytes ] if len ( bytes ) == 0 : return 0 self . _parent . _perform_write ( self . address , bytes ) self . _offset += len ( bytes ) return len ( bytes ) | Write data to the memory . |
50,624 | def seek ( self , n_bytes , from_what = os . SEEK_SET ) : if from_what == 0 : self . _offset = n_bytes elif from_what == 1 : self . _offset += n_bytes elif from_what == 2 : self . _offset = ( self . _end_address - self . _start_address ) - n_bytes else : raise ValueError ( "from_what: can only take values 0 (from start), " "1 (from current) or 2 (from end) not {}" . format ( from_what ) ) | Seek to a new position in the memory region . |
50,625 | def free ( self ) : self . _machine_controller . sdram_free ( self . _start_address , self . _x , self . _y ) self . _freed = True | Free the memory referred to by the file - like any subsequent operations on this file - like or slices of it will fail . |
50,626 | def _perform_read ( self , addr , size ) : return self . _machine_controller . read ( addr , size , self . _x , self . _y , 0 ) | Perform a read using the machine controller . |
50,627 | def _perform_write ( self , addr , data ) : return self . _machine_controller . write ( addr , data , self . _x , self . _y , 0 ) | Perform a write using the machine controller . |
50,628 | def _unpack_sdp_into_packet ( packet , bytestring ) : packet . data = bytestring [ 10 : ] ( flags , packet . tag , dest_cpu_port , src_cpu_port , packet . dest_y , packet . dest_x , packet . src_y , packet . src_x ) = struct . unpack_from ( '<2x8B' , bytestring ) packet . reply_expected = flags == FLAG_REPLY packet . dest_cpu = dest_cpu_port & 0x1f packet . dest_port = ( dest_cpu_port >> 5 ) packet . src_cpu = src_cpu_port & 0x1f packet . src_port = ( src_cpu_port >> 5 ) | Unpack the SDP header from a bytestring into a packet . |
50,629 | def packed_data ( self ) : scp_header = struct . pack ( "<2H" , self . cmd_rc , self . seq ) if self . arg1 is not None : scp_header += struct . pack ( '<I' , self . arg1 ) if self . arg2 is not None : scp_header += struct . pack ( '<I' , self . arg2 ) if self . arg3 is not None : scp_header += struct . pack ( '<I' , self . arg3 ) return scp_header + self . data | Pack the data for the SCP packet . |
50,630 | def hash64 ( key , seed ) : hash_val = mmh3 . hash64 ( key , seed ) [ 0 ] return struct . unpack ( '>Q' , struct . pack ( 'q' , hash_val ) ) [ 0 ] | Wrapper around mmh3 . hash64 to get us single 64 - bit value . |
50,631 | def generate_hashfunctions ( nbr_bits , nbr_slices ) : def _make_hashfuncs ( key ) : if isinstance ( key , text_type ) : key = key . encode ( 'utf-8' ) else : key = str ( key ) rval = [ ] current_hash = 0 for i in range ( nbr_slices ) : seed = current_hash current_hash = hash64 ( key , seed ) rval . append ( current_hash % nbr_bits ) return rval return _make_hashfuncs | Generate a set of hash functions . |
50,632 | def get_context_arguments ( self ) : cargs = { } for context in self . __context_stack : cargs . update ( context . context_arguments ) return cargs | Return a dictionary containing the current context arguments . |
50,633 | def use_contextual_arguments ( ** kw_only_args_defaults ) : def decorator ( f ) : arg_names , varargs , keywords , defaults = inspect . getargspec ( f ) assert set ( keywords or { } ) . isdisjoint ( set ( kw_only_args_defaults ) ) if defaults is None : defaults = [ ] defaults = ( ( [ Required ] * ( len ( arg_names ) - len ( defaults ) ) ) + list ( defaults ) ) @ add_signature_to_docstring ( f , kw_only_args = kw_only_args_defaults ) @ functools . wraps ( f ) def f_ ( self , * args , ** kwargs ) : new_kwargs = dict ( zip ( arg_names [ 1 + len ( args ) : ] , defaults [ 1 + len ( args ) : ] ) ) new_kwargs . update ( kw_only_args_defaults ) context = self . get_context_arguments ( ) for name , val in iteritems ( context ) : if name in new_kwargs : new_kwargs [ name ] = val new_kwargs . update ( kwargs ) for k , v in iteritems ( new_kwargs ) : if v is Required : raise TypeError ( "{!s}: missing argument {}" . format ( f . __name__ , k ) ) return f ( self , * args , ** new_kwargs ) return f_ return decorator | Decorator function which allows the wrapped function to accept arguments not specified in the call from the context . |
50,634 | def minimise ( routing_table , target_length ) : table , _ = ordered_covering ( routing_table , target_length , no_raise = True ) return remove_default_routes ( table , target_length ) | Reduce the size of a routing table by merging together entries where possible and by removing any remaining default routes . |
50,635 | def ordered_covering ( routing_table , target_length , aliases = dict ( ) , no_raise = False ) : aliases = dict ( aliases ) routing_table = sorted ( routing_table , key = lambda entry : _get_generality ( entry . key , entry . mask ) ) while target_length is None or len ( routing_table ) > target_length : merge = _get_best_merge ( routing_table , aliases ) if merge . goodness <= 0 : break routing_table , aliases = merge . apply ( aliases ) if ( not no_raise and target_length is not None and len ( routing_table ) > target_length ) : raise MinimisationFailedError ( target_length , len ( routing_table ) ) return routing_table , aliases | Reduce the size of a routing table by merging together entries where possible . |
50,636 | def _get_generality ( key , mask ) : xs = ( ~ key ) & ( ~ mask ) return sum ( 1 for i in range ( 32 ) if xs & ( 1 << i ) ) | Count the number of Xs in the key - mask pair . |
50,637 | def _get_best_merge ( routing_table , aliases ) : best_merge = _Merge ( routing_table ) best_goodness = 0 for merge in _get_all_merges ( routing_table ) : if merge . goodness <= best_goodness : continue merge = _refine_merge ( merge , aliases , min_goodness = best_goodness ) if merge . goodness > best_goodness : best_merge = merge best_goodness = merge . goodness return best_merge | Inspect all possible merges for the routing table and return the merge which would combine the greatest number of entries . |
50,638 | def _get_all_merges ( routing_table ) : considered_entries = set ( ) for i , entry in enumerate ( routing_table ) : if i in considered_entries : continue merge = set ( [ i ] ) merge . update ( j for j , other_entry in enumerate ( routing_table [ i + 1 : ] , start = i + 1 ) if entry . route == other_entry . route ) considered_entries . update ( merge ) if len ( merge ) > 1 : yield _Merge ( routing_table , merge ) | Get possible sets of entries to merge . |
50,639 | def _get_insertion_index ( routing_table , generality ) : generality -= 1 def gg ( entry ) : return _get_generality ( entry . key , entry . mask ) bottom = 0 top = len ( routing_table ) pos = ( top - bottom ) // 2 pg = gg ( routing_table [ pos ] ) while pg != generality and bottom < pos < top : if pg < generality : bottom = pos else : top = pos pos = bottom + ( top - bottom ) // 2 pg = gg ( routing_table [ pos ] ) while ( pos < len ( routing_table ) and gg ( routing_table [ pos ] ) <= generality ) : pos += 1 return pos | Determine the index in the routing table where a new entry should be inserted . |
50,640 | def _refine_merge ( merge , aliases , min_goodness ) : merge = _refine_downcheck ( merge , aliases , min_goodness ) if merge . goodness > min_goodness : merge , changed = _refine_upcheck ( merge , min_goodness ) if changed and merge . goodness > min_goodness : merge = _refine_downcheck ( merge , aliases , min_goodness ) return merge | Remove entries from a merge to generate a valid merge which may be applied to the routing table . |
50,641 | def _refine_upcheck ( merge , min_goodness ) : changed = False for i in sorted ( merge . entries , reverse = True ) : entry = merge . routing_table [ i ] key , mask = entry . key , entry . mask if any ( intersect ( key , mask , other . key , other . mask ) for other in merge . routing_table [ i + 1 : merge . insertion_index ] ) : merge = _Merge ( merge . routing_table , merge . entries - { i } ) changed = True if merge . goodness <= min_goodness : merge = _Merge ( merge . routing_table ) break return merge , changed | Remove from the merge any entries which would be covered by entries between their current position and the merge insertion position . |
50,642 | def _refine_downcheck ( merge , aliases , min_goodness ) : all_bits = tuple ( 1 << i for i in range ( 32 ) ) while merge . goodness > min_goodness : covered = list ( _get_covered_keys_and_masks ( merge , aliases ) ) if not covered : break most_stringent = 33 bits_and_vals = set ( ) for key , mask in covered : settable = mask & ~ merge . mask n_settable = sum ( 1 for bit in all_bits if bit & settable ) if n_settable <= most_stringent : if n_settable < most_stringent : most_stringent = n_settable bits_and_vals = set ( ) bits_and_vals . update ( ( bit , not ( key & bit ) ) for bit in all_bits if bit & settable ) if most_stringent == 0 : merge = _Merge ( merge . routing_table , set ( ) ) break else : remove = set ( ) for bit , val in sorted ( bits_and_vals , reverse = True ) : working_remove = set ( ) for i in merge . entries : entry = merge . routing_table [ i ] if ( ( not entry . mask & bit ) or ( bool ( entry . key & bit ) is ( not val ) ) ) : working_remove . add ( i ) if not remove or len ( working_remove ) < len ( remove ) : remove = working_remove merge = _Merge ( merge . routing_table , merge . entries - remove ) else : merge = _Merge ( merge . routing_table , set ( ) ) return merge | Prune the merge to avoid it covering up any entries which are below the merge insertion position . |
50,643 | def _get_covered_keys_and_masks ( merge , aliases ) : for entry in merge . routing_table [ merge . insertion_index : ] : key_mask = ( entry . key , entry . mask ) keys_masks = aliases . get ( key_mask , [ key_mask ] ) for key , mask in keys_masks : if intersect ( merge . key , merge . mask , key , mask ) : yield key , mask | Get keys and masks which would be covered by the entry resulting from the merge . |
50,644 | def apply ( self , aliases ) : new_size = len ( self . routing_table ) - len ( self . entries ) + 1 new_table = [ None for _ in range ( new_size ) ] aliases = dict ( aliases ) new_entry = RoutingTableEntry ( route = self . routing_table [ next ( iter ( self . entries ) ) ] . route , key = self . key , mask = self . mask , sources = self . sources ) aliases [ ( self . key , self . mask ) ] = our_aliases = set ( [ ] ) insert = 0 for i , entry in enumerate ( self . routing_table ) : if i == self . insertion_index : new_table [ insert ] = new_entry insert += 1 if i not in self . entries : new_table [ insert ] = entry insert += 1 else : km = ( entry . key , entry . mask ) our_aliases . update ( aliases . pop ( km , { km } ) ) if self . insertion_index == len ( self . routing_table ) : new_table [ insert ] = new_entry return new_table , aliases | Apply the merge to the routing table it is defined against and get a new routing table and alias dictionary . |
50,645 | def find_packages ( name , pkg_dir ) : for c in ( FileSystemPackageBuilder , ZipPackageBuilder , ExcelPackageBuilder ) : package_path , cache_path = c . make_package_path ( pkg_dir , name ) if package_path . exists ( ) : yield c . type_code , package_path , cache_path | Locate pre - built packages in the _packages directory |
50,646 | def initialize_bitarray ( self ) : self . bitarray = bitarray . bitarray ( self . nbr_bits ) self . current_day_bitarray = bitarray . bitarray ( self . nbr_bits ) self . bitarray . setall ( False ) self . current_day_bitarray . setall ( False ) | Initialize both bitarray . |
50,647 | def initialize_period ( self , period = None ) : if not period : self . current_period = dt . datetime . now ( ) else : self . current_period = period self . current_period = dt . datetime ( self . current_period . year , self . current_period . month , self . current_period . day ) self . date = self . current_period . strftime ( "%Y-%m-%d" ) | Initialize the period of BF . |
50,648 | def warm ( self , jittering_ratio = 0.2 ) : if self . snapshot_to_load == None : last_period = self . current_period - dt . timedelta ( days = self . expiration - 1 ) self . compute_refresh_period ( ) self . snapshot_to_load = [ ] base_filename = "%s/%s_%s_*.dat" % ( self . snapshot_path , self . name , self . expiration ) availables_snapshots = glob . glob ( base_filename ) for filename in availables_snapshots : snapshot_period = dt . datetime . strptime ( filename . split ( '_' ) [ - 1 ] . strip ( '.dat' ) , "%Y-%m-%d" ) if snapshot_period >= last_period : self . snapshot_to_load . append ( filename ) self . ready = False if self . snapshot_to_load and self . _should_warm ( ) : filename = self . snapshot_to_load . pop ( ) self . _union_bf_from_file ( filename ) jittering = self . warm_period * ( np . random . random ( ) - 0.5 ) * jittering_ratio self . next_snapshot_load = time . time ( ) + self . warm_period + jittering if not self . snapshot_to_load : self . ready = True | Progressively load the previous snapshot during the day . |
50,649 | def restore_from_disk ( self , clean_old_snapshot = False ) : base_filename = "%s/%s_%s_*.dat" % ( self . snapshot_path , self . name , self . expiration ) availables_snapshots = glob . glob ( base_filename ) last_period = self . current_period - dt . timedelta ( days = self . expiration - 1 ) for filename in availables_snapshots : snapshot_period = dt . datetime . strptime ( filename . split ( '_' ) [ - 1 ] . strip ( '.dat' ) , "%Y-%m-%d" ) if snapshot_period < last_period and not clean_old_snapshot : continue else : self . _union_bf_from_file ( filename ) if snapshot_period == self . current_period : self . _union_bf_from_file ( filename , current = True ) if snapshot_period < last_period and clean_old_snapshot : os . remove ( filename ) self . ready = True | Restore the state of the BF using previous snapshots . |
50,650 | def save_snaphot ( self ) : filename = "%s/%s_%s_%s.dat" % ( self . snapshot_path , self . name , self . expiration , self . date ) with open ( filename , 'w' ) as f : f . write ( zlib . compress ( pickle . dumps ( self . current_day_bitarray , protocol = pickle . HIGHEST_PROTOCOL ) ) ) | Save the current state of the current day bitarray on disk . |
50,651 | def place ( vertices_resources , nets , machine , constraints , vertex_order = None , chip_order = None ) : if len ( vertices_resources ) == 0 : return { } machine = machine . copy ( ) placements = { } vertices_resources , nets , constraints , substitutions = apply_same_chip_constraints ( vertices_resources , nets , constraints ) for constraint in constraints : if isinstance ( constraint , LocationConstraint ) : location = constraint . location if location not in machine : raise InvalidConstraintError ( "Chip requested by {} unavailable" . format ( machine ) ) vertex = constraint . vertex placements [ vertex ] = location resources = vertices_resources [ vertex ] machine [ location ] = subtract_resources ( machine [ location ] , resources ) if overallocated ( machine [ location ] ) : raise InsufficientResourceError ( "Cannot meet {}" . format ( constraint ) ) elif isinstance ( constraint , ReserveResourceConstraint ) : apply_reserve_resource_constraint ( machine , constraint ) if vertex_order is not None : vertex_order = list ( vertex_order ) for merged_vertex in substitutions : vertex_order [ vertex_order . index ( merged_vertex . vertices [ 0 ] ) ] = merged_vertex already_removed = set ( [ merged_vertex . vertices [ 0 ] ] ) for vertex in merged_vertex . vertices [ 1 : ] : if vertex not in already_removed : vertex_order . remove ( vertex ) already_removed . add ( vertex ) movable_vertices = ( v for v in ( vertices_resources if vertex_order is None else vertex_order ) if v not in placements ) chips = cycle ( c for c in ( machine if chip_order is None else chip_order ) if c in machine ) chips_iter = iter ( chips ) try : cur_chip = next ( chips_iter ) except StopIteration : raise InsufficientResourceError ( "No working chips in machine." ) last_successful_chip = cur_chip for vertex in movable_vertices : while True : resources_if_placed = subtract_resources ( machine [ cur_chip ] , vertices_resources [ vertex ] ) if not overallocated ( resources_if_placed ) : placements [ vertex ] = cur_chip machine [ cur_chip ] = resources_if_placed last_successful_chip = cur_chip break else : cur_chip = next ( chips_iter ) if cur_chip == last_successful_chip : raise InsufficientResourceError ( "Ran out of chips while attempting to place vertex " "{}" . format ( vertex ) ) finalise_same_chip_constraints ( substitutions , placements ) return placements | Blindly places vertices in sequential order onto chips in the machine . |
50,652 | def place_and_route_wrapper ( vertices_resources , vertices_applications , nets , net_keys , system_info , constraints = [ ] , place = default_place , place_kwargs = { } , allocate = default_allocate , allocate_kwargs = { } , route = default_route , route_kwargs = { } , minimise_tables_methods = ( remove_default_entries , ordered_covering ) , core_resource = Cores , sdram_resource = SDRAM , sram_resource = SRAM ) : machine = build_machine ( system_info , core_resource = core_resource , sdram_resource = sdram_resource , sram_resource = sram_resource ) base_constraints = build_core_constraints ( system_info , core_resource ) constraints = base_constraints + constraints placements = place ( vertices_resources , nets , machine , constraints , ** place_kwargs ) allocations = allocate ( vertices_resources , nets , machine , constraints , placements , ** allocate_kwargs ) routes = route ( vertices_resources , nets , machine , constraints , placements , allocations , core_resource , ** route_kwargs ) application_map = build_application_map ( vertices_applications , placements , allocations , core_resource ) routing_tables = routing_tree_to_tables ( routes , net_keys ) target_lengths = build_routing_table_target_lengths ( system_info ) routing_tables = minimise_tables ( routing_tables , target_lengths , minimise_tables_methods ) return placements , allocations , application_map , routing_tables | Wrapper for core place - and - route tasks for the common case . |
50,653 | def wrapper ( vertices_resources , vertices_applications , nets , net_keys , machine , constraints = [ ] , reserve_monitor = True , align_sdram = True , place = default_place , place_kwargs = { } , allocate = default_allocate , allocate_kwargs = { } , route = default_route , route_kwargs = { } , core_resource = Cores , sdram_resource = SDRAM ) : warnings . warn ( "rig.place_and_route.wrapper is deprecated " "use rig.place_and_route.place_and_route_wrapper instead in " "new applications." , DeprecationWarning ) constraints = constraints [ : ] if reserve_monitor : constraints . append ( ReserveResourceConstraint ( core_resource , slice ( 0 , 1 ) ) ) if align_sdram : constraints . append ( AlignResourceConstraint ( sdram_resource , 4 ) ) placements = place ( vertices_resources , nets , machine , constraints , ** place_kwargs ) allocations = allocate ( vertices_resources , nets , machine , constraints , placements , ** allocate_kwargs ) routes = route ( vertices_resources , nets , machine , constraints , placements , allocations , core_resource , ** route_kwargs ) application_map = build_application_map ( vertices_applications , placements , allocations , core_resource ) from rig . place_and_route . utils import build_routing_tables routing_tables = build_routing_tables ( routes , net_keys ) return placements , allocations , application_map , routing_tables | Wrapper for core place - and - route tasks for the common case . At a high level this function essentially takes a set of vertices and nets and produces placements memory allocations routing tables and application loading information . |
50,654 | def get_region_for_chip ( x , y , level = 3 ) : shift = 6 - 2 * level bit = ( ( x >> shift ) & 3 ) + 4 * ( ( y >> shift ) & 3 ) mask = 0xffff ^ ( ( 4 << shift ) - 1 ) nx = x & mask ny = y & mask region = ( nx << 24 ) | ( ny << 16 ) | ( level << 16 ) | ( 1 << bit ) return region | Get the region word for the given chip co - ordinates . |
50,655 | def compress_flood_fill_regions ( targets ) : t = RegionCoreTree ( ) for ( x , y ) , cores in iteritems ( targets ) : for p in cores : t . add_core ( x , y , p ) return sorted ( t . get_regions_and_coremasks ( ) ) | Generate a reduced set of flood fill parameters . |
50,656 | def get_regions_and_coremasks ( self ) : region_code = ( ( self . base_x << 24 ) | ( self . base_y << 16 ) | ( self . level << 16 ) ) subregions_cores = collections . defaultdict ( lambda : 0x0 ) for core , subregions in enumerate ( self . locally_selected ) : if subregions : subregions_cores [ subregions ] |= 1 << core for ( subregions , coremask ) in sorted ( subregions_cores . items ( ) ) : yield ( region_code | subregions ) , coremask if self . level < 3 : for i in ( 4 * x + y for y in range ( 4 ) for x in range ( 4 ) ) : subregion = self . subregions [ i ] if subregion is not None : for ( region , coremask ) in subregion . get_regions_and_coremasks ( ) : yield ( region , coremask ) | Generate a set of ordered paired region and core mask representations . |
50,657 | def add_core ( self , x , y , p ) : if ( ( p < 0 or p > 17 ) or ( x < self . base_x or x >= self . base_x + self . scale ) or ( y < self . base_y or y >= self . base_y + self . scale ) ) : raise ValueError ( ( x , y , p ) ) subregion = ( ( x >> self . shift ) & 0x3 ) + 4 * ( ( y >> self . shift ) & 0x3 ) if self . level == 3 : self . locally_selected [ p ] |= 1 << subregion elif not self . locally_selected [ p ] & ( 1 << subregion ) : if self . subregions [ subregion ] is None : base_x = int ( self . base_x + ( self . scale / 4 ) * ( subregion % 4 ) ) base_y = int ( self . base_y + ( self . scale / 4 ) * ( subregion // 4 ) ) self . subregions [ subregion ] = RegionCoreTree ( base_x , base_y , self . level + 1 ) if self . subregions [ subregion ] . add_core ( x , y , p ) : self . locally_selected [ p ] |= 1 << subregion if self . locally_selected [ p ] == 0xffff and self . level != 0 : self . locally_selected [ p ] = 0x0 return True else : return False | Add a new core to the region tree . |
50,658 | def send_scp ( self , * args , ** kwargs ) : cabinet = kwargs . pop ( "cabinet" ) frame = kwargs . pop ( "frame" ) board = kwargs . pop ( "board" ) return self . _send_scp ( cabinet , frame , board , * args , ** kwargs ) | Transmit an SCP Packet to a specific board . |
50,659 | def get_software_version ( self , cabinet , frame , board ) : sver = self . _send_scp ( cabinet , frame , board , SCPCommands . sver ) code_block = ( sver . arg1 >> 24 ) & 0xff frame_id = ( sver . arg1 >> 16 ) & 0xff can_id = ( sver . arg1 >> 8 ) & 0xff board_id = sver . arg1 & 0xff buffer_size = ( sver . arg2 & 0xffff ) software_name , version , version_labels = unpack_sver_response_version ( sver ) return BMPInfo ( code_block , frame_id , can_id , board_id , version , buffer_size , sver . arg3 , software_name , version_labels ) | Get the software version for a given BMP . |
50,660 | def set_power ( self , state , cabinet , frame , board , delay = 0.0 , post_power_on_delay = 5.0 ) : if isinstance ( board , int ) : boards = [ board ] else : boards = list ( board ) arg1 = int ( delay * 1000 ) << 16 | ( 1 if state else 0 ) arg2 = sum ( 1 << b for b in boards ) self . _send_scp ( cabinet , frame , 0 , SCPCommands . power , arg1 = arg1 , arg2 = arg2 , timeout = consts . BMP_POWER_ON_TIMEOUT if state else 0.0 , expected_args = 0 ) if state : time . sleep ( post_power_on_delay ) | Control power to the SpiNNaker chips and FPGAs on a board . |
50,661 | def read_adc ( self , cabinet , frame , board ) : response = self . _send_scp ( cabinet , frame , board , SCPCommands . bmp_info , arg1 = BMPInfoType . adc , expected_args = 0 ) data = struct . unpack ( "<" "8H" "4h" "4h" "4h" "I" "I" , response . data ) return ADCInfo ( voltage_1_2c = data [ 1 ] * BMP_V_SCALE_2_5 , voltage_1_2b = data [ 2 ] * BMP_V_SCALE_2_5 , voltage_1_2a = data [ 3 ] * BMP_V_SCALE_2_5 , voltage_1_8 = data [ 4 ] * BMP_V_SCALE_2_5 , voltage_3_3 = data [ 6 ] * BMP_V_SCALE_3_3 , voltage_supply = data [ 7 ] * BMP_V_SCALE_12 , temp_top = float ( data [ 8 ] ) * BMP_TEMP_SCALE , temp_btm = float ( data [ 9 ] ) * BMP_TEMP_SCALE , temp_ext_0 = ( ( float ( data [ 12 ] ) * BMP_TEMP_SCALE ) if data [ 12 ] != BMP_MISSING_TEMP else None ) , temp_ext_1 = ( ( float ( data [ 13 ] ) * BMP_TEMP_SCALE ) if data [ 13 ] != BMP_MISSING_TEMP else None ) , fan_0 = float ( data [ 16 ] ) if data [ 16 ] != BMP_MISSING_FAN else None , fan_1 = float ( data [ 17 ] ) if data [ 17 ] != BMP_MISSING_FAN else None , ) | Read ADC data from the BMP including voltages and temperature . |
50,662 | def add_resources ( res_a , res_b ) : return { resource : value + res_b . get ( resource , 0 ) for resource , value in iteritems ( res_a ) } | Return the resources after adding res_b s resources to res_a . |
50,663 | def subtract_resources ( res_a , res_b ) : return { resource : value - res_b . get ( resource , 0 ) for resource , value in iteritems ( res_a ) } | Return the resources remaining after subtracting res_b s resources from res_a . |
50,664 | def resources_after_reservation ( res , constraint ) : res = res . copy ( ) res [ constraint . resource ] -= ( constraint . reservation . stop - constraint . reservation . start ) return res | Return the resources available after a specified ReserveResourceConstraint has been applied . |
50,665 | def apply_reserve_resource_constraint ( machine , constraint ) : if constraint . location is None : machine . chip_resources = resources_after_reservation ( machine . chip_resources , constraint ) if overallocated ( machine . chip_resources ) : raise InsufficientResourceError ( "Cannot meet {}" . format ( constraint ) ) for location in machine . chip_resource_exceptions : machine . chip_resource_exceptions [ location ] = resources_after_reservation ( machine . chip_resource_exceptions [ location ] , constraint ) if overallocated ( machine [ location ] ) : raise InsufficientResourceError ( "Cannot meet {}" . format ( constraint ) ) else : machine [ constraint . location ] = resources_after_reservation ( machine [ constraint . location ] , constraint ) if overallocated ( machine [ constraint . location ] ) : raise InsufficientResourceError ( "Cannot meet {}" . format ( constraint ) ) | Apply the changes implied by a reserve resource constraint to a machine model . |
50,666 | def apply_same_chip_constraints ( vertices_resources , nets , constraints ) : vertices_resources = vertices_resources . copy ( ) nets = nets [ : ] constraints = constraints [ : ] substitutions = [ ] for same_chip_constraint in constraints : if not isinstance ( same_chip_constraint , SameChipConstraint ) : continue if len ( same_chip_constraint . vertices ) <= 1 : continue merged_vertex = MergedVertex ( same_chip_constraint . vertices ) substitutions . append ( merged_vertex ) merged_vertices = set ( same_chip_constraint . vertices ) total_resources = { } for vertex in merged_vertices : resources = vertices_resources . pop ( vertex ) for resource , value in iteritems ( resources ) : total_resources [ resource ] = ( total_resources . get ( resource , 0 ) + value ) vertices_resources [ merged_vertex ] = total_resources for net_num , net in enumerate ( nets ) : net_changed = False if net . source in merged_vertices : net_changed = True net = Net ( merged_vertex , net . sinks , net . weight ) for sink_num , sink in enumerate ( net . sinks ) : if sink in merged_vertices : if not net_changed : net = Net ( net . source , net . sinks , net . weight ) net_changed = True net . sinks [ sink_num ] = merged_vertex if net_changed : nets [ net_num ] = net for constraint_num , constraint in enumerate ( constraints ) : if isinstance ( constraint , LocationConstraint ) : if constraint . vertex in merged_vertices : constraints [ constraint_num ] = LocationConstraint ( merged_vertex , constraint . location ) elif isinstance ( constraint , SameChipConstraint ) : if not set ( constraint . vertices ) . isdisjoint ( merged_vertices ) : constraints [ constraint_num ] = SameChipConstraint ( [ merged_vertex if v in merged_vertices else v for v in constraint . vertices ] ) elif isinstance ( constraint , RouteEndpointConstraint ) : if constraint . vertex in merged_vertices : constraints [ constraint_num ] = RouteEndpointConstraint ( merged_vertex , constraint . route ) return ( vertices_resources , nets , constraints , substitutions ) | Modify a set of vertices_resources nets and constraints to account for all SameChipConstraints . |
50,667 | def join_resource_name ( self , v ) : d = self . dict d [ 'fragment' ] = [ v , None ] return MetapackResourceUrl ( downloader = self . _downloader , ** d ) | Return a MetapackResourceUrl that includes a reference to the resource . Returns a MetapackResourceUrl which will have a fragment |
50,668 | def search_json_indexed_directory ( directory ) : from metapack . index import SearchIndex , search_index_file idx = SearchIndex ( search_index_file ( ) ) def _search_function ( url ) : packages = idx . search ( url , format = 'issued' ) if not packages : return None package = packages . pop ( 0 ) try : resource_str = '#' + url . target_file if url . fragment [ 0 ] else '' return parse_app_url ( package [ 'url' ] + resource_str , downloader = url . downloader ) except KeyError as e : return None return _search_function | Return a search function for searching a directory of packages which has an index . json file created by the mp install file command . |
50,669 | def search ( self ) : for cb in SearchUrl . search_callbacks : try : v = cb ( self ) if v is not None : return v except Exception as e : raise | Search for a url by returning the value from the first callback that returns a non - None value |
50,670 | def ensure_source_package_dir ( nb_path , pkg_name ) : pkg_path = join ( dirname ( nb_path ) , pkg_name ) makedirs ( join ( pkg_path , 'notebooks' ) , exist_ok = True ) makedirs ( join ( pkg_path , 'docs' ) , exist_ok = True ) return pkg_path | Ensure all of the important directories in a source package exist |
50,671 | def get_metatab_doc ( nb_path ) : from metatab . generate import CsvDataRowGenerator from metatab . rowgenerators import TextRowGenerator from metatab import MetatabDoc with open ( nb_path ) as f : nb = nbformat . reads ( f . read ( ) , as_version = 4 ) for cell in nb . cells : source = '' . join ( cell [ 'source' ] ) . strip ( ) if source . startswith ( '%%metatab' ) : return MetatabDoc ( TextRowGenerator ( source ) ) | Read a notebook and extract the metatab document . Only returns the first document |
50,672 | def process_schema ( doc , resource , df ) : from rowgenerators import SourceError from requests . exceptions import ConnectionError from metapack . cli . core import extract_path_name , alt_col_name , type_map from tableintuit import TypeIntuiter from rowgenerators . generator . python import PandasDataframeSource from appurl import parse_app_url try : doc [ 'Schema' ] except KeyError : doc . new_section ( 'Schema' , [ 'DataType' , 'Altname' , 'Description' ] ) schema_name = resource . get_value ( 'schema' , resource . get_value ( 'name' ) ) schema_term = doc . find_first ( term = 'Table' , value = schema_name , section = 'Schema' ) if schema_term : logger . info ( "Found table for '{}'; skipping" . format ( schema_name ) ) return path , name = extract_path_name ( resource . url ) logger . info ( "Processing {}" . format ( resource . url ) ) si = PandasDataframeSource ( parse_app_url ( resource . url ) , df , cache = doc . _cache , ) try : ti = TypeIntuiter ( ) . run ( si ) except SourceError as e : logger . warn ( "Failed to process '{}'; {}" . format ( path , e ) ) return except ConnectionError as e : logger . warn ( "Failed to download '{}'; {}" . format ( path , e ) ) return table = doc [ 'Schema' ] . new_term ( 'Table' , schema_name ) logger . info ( "Adding table '{}' to metatab schema" . format ( schema_name ) ) for i , c in enumerate ( ti . to_rows ( ) ) : raw_alt_name = alt_col_name ( c [ 'header' ] , i ) alt_name = raw_alt_name if raw_alt_name != c [ 'header' ] else '' t = table . new_child ( 'Column' , c [ 'header' ] , datatype = type_map . get ( c [ 'resolved_type' ] , c [ 'resolved_type' ] ) , altname = alt_name , description = df [ c [ 'header' ] ] . description if hasattr ( df , 'description' ) and df [ c [ 'header' ] ] . description else '' ) return table | Add schema entiries to a metatab doc from a dataframe |
50,673 | def boot ( hostname , boot_port = consts . BOOT_PORT , scamp_binary = None , sark_struct = None , boot_delay = 0.05 , post_boot_delay = 2.0 , sv_overrides = dict ( ) , ** kwargs ) : scamp_binary = ( scamp_binary if scamp_binary is not None else pkg_resources . resource_filename ( "rig" , "boot/scamp.boot" ) ) sark_struct = ( sark_struct if sark_struct is not None else pkg_resources . resource_filename ( "rig" , "boot/sark.struct" ) ) with open ( scamp_binary , "rb" ) as f : boot_data = f . read ( ) with open ( sark_struct , "rb" ) as f : struct_data = f . read ( ) structs = struct_file . read_struct_file ( struct_data ) sv = structs [ b"sv" ] sv_overrides . update ( kwargs ) sv . update_default_values ( ** sv_overrides ) sv . update_default_values ( unix_time = int ( time . time ( ) ) , boot_sig = int ( time . time ( ) ) , root_chip = 1 ) struct_packed = sv . pack ( ) assert len ( struct_packed ) >= 128 buf = bytearray ( boot_data ) buf [ BOOT_DATA_OFFSET : BOOT_DATA_OFFSET + BOOT_DATA_LENGTH ] = struct_packed [ : BOOT_DATA_LENGTH ] assert len ( buf ) < DTCM_SIZE boot_data = bytes ( buf ) sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) sock . connect ( ( hostname , boot_port ) ) n_blocks = ( len ( buf ) + BOOT_BYTE_SIZE - 1 ) // BOOT_BYTE_SIZE assert n_blocks <= BOOT_MAX_BLOCKS boot_packet ( sock , BootCommand . start , arg3 = n_blocks - 1 ) time . sleep ( boot_delay ) block = 0 while len ( boot_data ) > 0 : data , boot_data = ( boot_data [ : BOOT_BYTE_SIZE ] , boot_data [ BOOT_BYTE_SIZE : ] ) a1 = ( ( BOOT_WORD_SIZE - 1 ) << 8 ) | block boot_packet ( sock , BootCommand . send_block , a1 , data = data ) time . sleep ( boot_delay ) block += 1 boot_packet ( sock , BootCommand . end , 1 ) sock . close ( ) time . sleep ( post_boot_delay ) return structs | Boot a SpiNNaker machine of the given size . |
50,674 | def boot_packet ( sock , cmd , arg1 = 0 , arg2 = 0 , arg3 = 0 , data = b"" ) : PROTOCOL_VERSION = 1 header = struct . pack ( "!H4I" , PROTOCOL_VERSION , cmd , arg1 , arg2 , arg3 ) assert len ( data ) % 4 == 0 fdata = b"" while len ( data ) > 0 : word , data = ( data [ : 4 ] , data [ 4 : ] ) fdata += struct . pack ( "!I" , struct . unpack ( "<I" , word ) [ 0 ] ) sock . send ( header + fdata ) | Create and transmit a packet to boot the machine . |
50,675 | def copy ( self ) : return Machine ( self . width , self . height , self . chip_resources , self . chip_resource_exceptions , self . dead_chips , self . dead_links ) | Produce a copy of this datastructure . |
50,676 | def iter_links ( self ) : for x in range ( self . width ) : for y in range ( self . height ) : for link in Links : if ( x , y , link ) in self : yield ( x , y , link ) | An iterator over the working links in the machine . |
50,677 | def has_wrap_around_links ( self , minimum_working = 0.9 ) : working = 0 for x in range ( self . width ) : if ( x , 0 , Links . south ) in self : working += 1 if ( x , self . height - 1 , Links . north ) in self : working += 1 if ( x , 0 , Links . south_west ) in self : working += 1 if ( x , self . height - 1 , Links . north_east ) in self : working += 1 for y in range ( self . height ) : if ( 0 , y , Links . west ) in self : working += 1 if ( self . width - 1 , y , Links . east ) in self : working += 1 if y != 0 and ( 0 , y , Links . south_west ) in self : working += 1 if ( y != self . height - 1 and ( self . width - 1 , y , Links . north_east ) in self ) : working += 1 total = ( 4 * self . width ) + ( 4 * self . height ) - 2 return ( float ( working ) / float ( total ) ) >= minimum_working | Test if a machine has wrap - around connections installed . |
50,678 | def update_resource_properties ( r , orig_columns = { } , force = False ) : added = [ ] schema_term = r . schema_term if not schema_term : warn ( "No schema term for " , r . name ) return rg = r . raw_row_generator upstream_columns = { e [ 'name' ] . lower ( ) if e [ 'name' ] else '' : e for e in r . columns ( ) or { } } schema_columns = { e [ 'name' ] . lower ( ) if e [ 'name' ] else '' : e for e in r . schema_columns or { } } generator_columns = { e [ 'name' ] . lower ( ) if e [ 'name' ] else '' : e for e in rg . columns or { } } def get_col_value ( col_name , value_name ) : v = None if not col_name : return None for d in [ generator_columns , upstream_columns , orig_columns , schema_columns ] : v_ = d . get ( col_name . lower ( ) , { } ) . get ( value_name ) if v_ : v = v_ return v extra_properties = set ( ) for d in [ generator_columns , upstream_columns , orig_columns , schema_columns ] : for k , v in d . items ( ) : for kk , vv in v . items ( ) : extra_properties . add ( kk ) extra_properties = extra_properties - { 'pos' , 'header' , 'name' , '' } for ep in extra_properties : r . doc [ 'Schema' ] . add_arg ( ep ) for c in schema_term . find ( 'Table.Column' ) : for ep in extra_properties : t = c . get_or_new_child ( ep ) v = get_col_value ( c . name , ep ) if v : t . value = v added . append ( ( c . name , ep , v ) ) prt ( 'Updated schema for {}. Set {} properties' . format ( r . name , len ( added ) ) ) | Get descriptions and other properties from this or upstream packages and add them to the schema . |
50,679 | def get_config ( ) : from os import environ from os . path import expanduser from pathlib import Path import yaml def pexp ( p ) : try : return Path ( p ) . expanduser ( ) except AttributeError : return Path ( expanduser ( p ) ) paths = [ environ . get ( "METAPACK_CONFIG" ) , '~/.metapack.yaml' , '/etc/metapack.yaml' ] for p in paths : if not p : continue p = pexp ( p ) if p . exists ( ) : with p . open ( ) as f : config = yaml . safe_load ( f ) if not config : config = { } config [ '_loaded_from' ] = str ( p ) return config return None | Return a configuration dict |
50,680 | def find_csv_packages ( m , downloader ) : from metapack . package import CsvPackageBuilder pkg_dir = m . package_root name = m . doc . get_value ( 'Root.Name' ) package_path , cache_path = CsvPackageBuilder . make_package_path ( pkg_dir , name ) if package_path . exists ( ) : return open_package ( package_path , downloader = downloader ) | Locate the build CSV package which will have distributions if it was generated as and S3 package |
50,681 | def serialize_email_messages ( messages : List [ EmailMessage ] ) : return [ base64 . b64encode ( zlib . compress ( pickle . dumps ( m , protocol = 4 ) ) ) . decode ( ) for m in messages ] | Serialize EmailMessages to be passed as task argument . |
50,682 | def deserialize_email_messages ( messages : List [ str ] ) : return [ pickle . loads ( zlib . decompress ( base64 . b64decode ( m ) ) ) for m in messages ] | Deserialize EmailMessages passed as task argument . |
50,683 | def _estimate_count ( self ) : if self . estimate_z == 0 : self . estimate_z = ( 1.0 / self . nbr_bits ) self . estimate_z = min ( self . estimate_z , 0.999999 ) self . count = int ( - ( self . nbr_bits / self . nbr_slices ) * np . log ( 1 - self . estimate_z ) ) | Update the count number using the estimation of the unset ratio |
50,684 | def compute_refresh_time ( self ) : if self . z == 0 : self . z = 1E-10 s = float ( self . expiration ) * ( 1.0 / ( self . nbr_bits ) ) * ( 1.0 / ( self . counter_init - 1 + ( 1.0 / ( self . z * ( self . nbr_slices + 1 ) ) ) ) ) return s | Compute the refresh period for the given expiration delay |
50,685 | def allocate ( vertices_resources , nets , machine , constraints , placements ) : allocation = { } globally_reserved = defaultdict ( list ) locally_reserved = defaultdict ( lambda : defaultdict ( list ) ) alignments = defaultdict ( lambda : 1 ) for constraint in constraints : if isinstance ( constraint , ReserveResourceConstraint ) : if constraint . location is None : globally_reserved [ constraint . resource ] . append ( constraint . reservation ) else : locally_reserved [ constraint . location ] [ constraint . resource ] . append ( constraint . reservation ) elif isinstance ( constraint , AlignResourceConstraint ) : alignments [ constraint . resource ] = constraint . alignment chip_contents = defaultdict ( list ) for vertex , xy in iteritems ( placements ) : chip_contents [ xy ] . append ( vertex ) for xy , chip_vertices in iteritems ( chip_contents ) : resource_pointers = { resource : 0 for resource in machine . chip_resources } for vertex in chip_vertices : vertex_allocation = { } for resource , requirement in iteritems ( vertices_resources [ vertex ] ) : proposed_allocation = None proposal_overlaps = True while proposal_overlaps : start = align ( resource_pointers [ resource ] , alignments [ resource ] ) proposed_allocation = slice ( start , start + requirement ) proposal_overlaps = False if proposed_allocation . stop > machine [ xy ] [ resource ] : raise InsufficientResourceError ( "{} over-allocated on chip {}" . format ( resource , xy ) ) for reservation in globally_reserved [ resource ] : if slices_overlap ( proposed_allocation , reservation ) : resource_pointers [ resource ] = reservation . stop proposal_overlaps = True local_reservations = locally_reserved . get ( xy , { } ) . get ( resource , [ ] ) for reservation in local_reservations : if slices_overlap ( proposed_allocation , reservation ) : resource_pointers [ resource ] = reservation . stop proposal_overlaps = True vertex_allocation [ resource ] = proposed_allocation resource_pointers [ resource ] = proposed_allocation . stop allocation [ vertex ] = vertex_allocation return allocation | Allocate resources to vertices on cores arbitrarily using a simple greedy algorithm . |
50,686 | def create ( self , port , qos_policy ) : LOG . info ( "Setting QoS policy %(qos_policy)s on port %(port)s" , dict ( qos_policy = qos_policy , port = port ) ) policy_data = self . _get_policy_values ( qos_policy ) self . _utils . set_port_qos_rule ( port [ "port_id" ] , policy_data ) | Apply QoS rules on port for the first time . |
50,687 | def delete ( self , port , qos_policy = None ) : LOG . info ( "Deleting QoS policy %(qos_policy)s on port %(port)s" , dict ( qos_policy = qos_policy , port = port ) ) self . _utils . remove_port_qos_rule ( port [ "port_id" ] ) | Remove QoS rules from port . |
50,688 | def task ( self , func : Optional [ Callable ] = None , name : Optional [ str ] = None , queue : Optional [ str ] = None , max_retries : Optional [ Number ] = None , periodicity : Optional [ timedelta ] = None ) : if func is None : return functools . partial ( self . task , name = name , queue = queue , max_retries = max_retries , periodicity = periodicity ) self . add ( func , name = name , queue = queue , max_retries = max_retries , periodicity = periodicity ) func . task_name = name return func | Decorator to register a task function . |
50,689 | def add ( self , func : Callable , name : Optional [ str ] = None , queue : Optional [ str ] = None , max_retries : Optional [ Number ] = None , periodicity : Optional [ timedelta ] = None ) : if not name : raise ValueError ( 'Each Spinach task needs a name' ) if name in self . _tasks : raise ValueError ( 'A task named {} already exists' . format ( name ) ) if queue is None : if self . queue : queue = self . queue else : queue = const . DEFAULT_QUEUE if max_retries is None : if self . max_retries : max_retries = self . max_retries else : max_retries = const . DEFAULT_MAX_RETRIES if periodicity is None : periodicity = self . periodicity if queue and queue . startswith ( '_' ) : raise ValueError ( 'Queues starting with "_" are reserved by ' 'Spinach for internal use' ) self . _tasks [ name ] = Task ( func , name , queue , max_retries , periodicity ) | Register a task function . |
50,690 | def schedule ( self , task : Schedulable , * args , ** kwargs ) : self . _require_attached_tasks ( ) self . _spin . schedule ( task , * args , ** kwargs ) | Schedule a job to be executed as soon as possible . |
50,691 | def schedule ( self , task : Schedulable , * args , ** kwargs ) : at = datetime . now ( timezone . utc ) self . schedule_at ( task , at , * args , ** kwargs ) | Add a job to be executed ASAP to the batch . |
50,692 | def schedule_at ( self , task : Schedulable , at : datetime , * args , ** kwargs ) : self . jobs_to_create . append ( ( task , at , args , kwargs ) ) | Add a job to be executed in the future to the batch . |
50,693 | def _locate_file ( f , base_dir ) : if base_dir == None : return f file_name = os . path . join ( base_dir , f ) real = os . path . realpath ( file_name ) return real | Utility method for finding full path to a filename as string |
50,694 | def check_to_generate_or_run ( argv , sim ) : print_v ( "Checking arguments: %s to see whether anything should be run in simulation %s (net: %s)..." % ( argv , sim . id , sim . network ) ) if len ( argv ) == 1 : print_v ( "No arguments found. Currently supported export formats:" ) print_v ( " -nml | -nmlh5 | -jnml | -jnmlnrn | -jnmlnetpyne | -netpyne | -pynnnrn " + "| -pynnnest | -pynnbrian | -pynnneuroml | -sonata | -matrix[1-2] | -graph[1-6 n/d/f/c]" ) if '-pynnnest' in argv : generate_and_run ( sim , simulator = 'PyNN_NEST' ) elif '-pynnnrn' in argv : generate_and_run ( sim , simulator = 'PyNN_NEURON' ) elif '-pynnbrian' in argv : generate_and_run ( sim , simulator = 'PyNN_Brian' ) elif '-jnml' in argv : generate_and_run ( sim , simulator = 'jNeuroML' ) elif '-jnmlnrn' in argv : generate_and_run ( sim , simulator = 'jNeuroML_NEURON' ) elif '-netpyne' in argv : generate_and_run ( sim , simulator = 'NetPyNE' ) elif '-pynnneuroml' in argv : generate_and_run ( sim , simulator = 'PyNN_NeuroML' ) elif '-sonata' in argv : generate_and_run ( sim , simulator = 'sonata' ) elif '-nml' in argv or '-neuroml' in argv : network = load_network_json ( sim . network ) generate_neuroml2_from_network ( network , validate = True ) elif '-nmlh5' in argv or '-neuromlh5' in argv : network = load_network_json ( sim . network ) generate_neuroml2_from_network ( network , validate = True , format = 'hdf5' ) else : for a in argv : if '-jnmlnetpyne' in a : num_processors = 1 if len ( a ) > len ( '-jnmlnetpyne' ) : num_processors = int ( a [ 12 : ] ) generate_and_run ( sim , simulator = 'jNeuroML_NetPyNE' , num_processors = num_processors ) elif 'graph' in a : generate_and_run ( sim , simulator = a [ 1 : ] ) elif 'matrix' in a : generate_and_run ( sim , simulator = a [ 1 : ] ) | Useful method for calling in main method after network and simulation are generated to handle some standard export options like - jnml - graph etc . |
50,695 | def connect_input ( self , name , wire ) : self . _inputs [ name ] = wire wire . sinks . append ( self ) | Connect the specified input to a wire . |
50,696 | def _write_config ( self , memory ) : memory . seek ( 0 ) memory . write ( struct . pack ( "<5I" , self . _simulator . length , self . _inputs [ "a" ] . routing_key if self . _inputs [ "a" ] is not None else 0xFFFFFFFF , self . _inputs [ "b" ] . routing_key if self . _inputs [ "b" ] is not None else 0xFFFFFFFF , self . output . routing_key , self . _lookup_table ) ) | Write the configuration for this gate to memory . |
50,697 | def connect_input ( self , wire ) : self . _input = wire wire . sinks . append ( self ) | Probe the specified wire . |
50,698 | def _write_config ( self , memory ) : memory . seek ( 0 ) memory . write ( struct . pack ( "<II" , self . _simulator . length , self . _input . routing_key if self . _input is not None else 0xFFFFFFFF ) ) | Write the configuration for this probe to memory . |
50,699 | def _read_results ( self , memory ) : memory . seek ( 8 ) bits = bitarray ( endian = "little" ) bits . frombytes ( memory . read ( ) ) self . recorded_data = bits . to01 ( ) | Read back the probed results . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.