idx
int64 0
63k
| question
stringlengths 61
4.03k
| target
stringlengths 6
1.23k
|
---|---|---|
59,800 |
def clamp ( color , min_v , max_v ) : h , s , v = rgb_to_hsv ( * map ( down_scale , color ) ) min_v , max_v = map ( down_scale , ( min_v , max_v ) ) v = min ( max ( min_v , v ) , max_v ) return tuple ( map ( up_scale , hsv_to_rgb ( h , s , v ) ) )
|
Clamps a color such that the value is between min_v and max_v .
|
59,801 |
def order_by_hue ( colors ) : hsvs = [ rgb_to_hsv ( * map ( down_scale , color ) ) for color in colors ] hsvs . sort ( key = lambda t : t [ 0 ] ) return [ tuple ( map ( up_scale , hsv_to_rgb ( * hsv ) ) ) for hsv in hsvs ]
|
Orders colors by hue .
|
59,802 |
def brighten ( color , brightness ) : h , s , v = rgb_to_hsv ( * map ( down_scale , color ) ) return tuple ( map ( up_scale , hsv_to_rgb ( h , s , v + down_scale ( brightness ) ) ) )
|
Adds or subtracts value to a color .
|
59,803 |
def colorz ( fd , n = DEFAULT_NUM_COLORS , min_v = DEFAULT_MINV , max_v = DEFAULT_MAXV , bold_add = DEFAULT_BOLD_ADD , order_colors = True ) : img = Image . open ( fd ) img . thumbnail ( THUMB_SIZE ) obs = get_colors ( img ) clamped = [ clamp ( color , min_v , max_v ) for color in obs ] clusters , _ = kmeans ( array ( clamped ) . astype ( float ) , n ) colors = order_by_hue ( clusters ) if order_colors else clusters return list ( zip ( colors , [ brighten ( c , bold_add ) for c in colors ] ) )
|
Get the n most dominant colors of an image . Clamps value to between min_v and max_v .
|
59,804 |
def long_description ( * paths ) : result = '' try : import pypandoc except ( ImportError , OSError ) as e : print ( "Unable to import pypandoc - %s" % e ) return result try : for path in paths : result += '\n' + pypandoc . convert ( path , 'rst' , format = 'markdown' ) except ( OSError , IOError ) as e : print ( "Failed to convert with pypandoc - %s" % e ) return result return result
|
Returns a RST formated string .
|
59,805 |
def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
|
Check if the memory is too full for further caching .
|
59,806 |
def cache ( cache = { } , maxmem = config . MAXIMUM_CACHE_MEMORY_PERCENTAGE , typed = False ) : sentinel = object ( ) make_key = _make_key def decorating_function ( user_function , hits = 0 , misses = 0 ) : full = False cache_get = cache . get if not maxmem : def wrapper ( * args , ** kwds ) : nonlocal hits , misses key = make_key ( args , kwds , typed ) result = cache_get ( key , sentinel ) if result is not sentinel : hits += 1 return result result = user_function ( * args , ** kwds ) cache [ key ] = result misses += 1 return result else : def wrapper ( * args , ** kwds ) : nonlocal hits , misses , full key = make_key ( args , kwds , typed ) result = cache_get ( key ) if result is not None : hits += 1 return result result = user_function ( * args , ** kwds ) if not full : cache [ key ] = result current_process = psutil . Process ( os . getpid ( ) ) full = current_process . memory_percent ( ) > maxmem misses += 1 return result def cache_info ( ) : return _CacheInfo ( hits , misses , len ( cache ) ) def cache_clear ( ) : nonlocal hits , misses , full cache . clear ( ) hits = misses = 0 full = False wrapper . cache_info = cache_info wrapper . cache_clear = cache_clear return update_wrapper ( wrapper , user_function ) return decorating_function
|
Memory - limited cache decorator .
|
59,807 |
def MICECache ( subsystem , parent_cache = None ) : if config . REDIS_CACHE : cls = RedisMICECache else : cls = DictMICECache return cls ( subsystem , parent_cache = parent_cache )
|
Construct a |MICE| cache .
|
59,808 |
def method ( cache_name , key_prefix = None ) : def decorator ( func ) : if ( func . __name__ in [ 'cause_repertoire' , 'effect_repertoire' ] and not config . CACHE_REPERTOIRES ) : return func @ wraps ( func ) def wrapper ( obj , * args , ** kwargs ) : cache = getattr ( obj , cache_name ) key = cache . key ( * args , _prefix = key_prefix , ** kwargs ) value = cache . get ( key ) if value is None : value = func ( obj , * args , ** kwargs ) cache . set ( key , value ) return value return wrapper return decorator
|
Caching decorator for object - level method caches .
|
59,809 |
def get ( self , key ) : if key in self . cache : self . hits += 1 return self . cache [ key ] self . misses += 1 return None
|
Get a value out of the cache .
|
59,810 |
def key ( self , * args , _prefix = None , ** kwargs ) : if kwargs : raise NotImplementedError ( 'kwarg cache keys not implemented' ) return ( _prefix , ) + tuple ( args )
|
Get the cache key for the given function args .
|
59,811 |
def info ( self ) : info = redis_conn . info ( ) return _CacheInfo ( info [ 'keyspace_hits' ] , info [ 'keyspace_misses' ] , self . size ( ) )
|
Return cache information .
|
59,812 |
def set ( self , key , value ) : if not self . subsystem . is_cut : super ( ) . set ( key , value )
|
Only need to set if the subsystem is uncut .
|
59,813 |
def _build ( self , parent_cache ) : for key , mice in parent_cache . cache . items ( ) : if not mice . damaged_by_cut ( self . subsystem ) : self . cache [ key ] = mice
|
Build the initial cache from the parent .
|
59,814 |
def set ( self , key , value ) : if config . CACHE_POTENTIAL_PURVIEWS : self . cache [ key ] = value
|
Only set if purview caching is enabled
|
59,815 |
def apply_boundary_conditions_to_cm ( external_indices , cm ) : cm = cm . copy ( ) cm [ external_indices , : ] = 0 cm [ : , external_indices ] = 0 return cm
|
Remove connections to or from external nodes .
|
59,816 |
def get_inputs_from_cm ( index , cm ) : return tuple ( i for i in range ( cm . shape [ 0 ] ) if cm [ i ] [ index ] )
|
Return indices of inputs to the node with the given index .
|
59,817 |
def get_outputs_from_cm ( index , cm ) : return tuple ( i for i in range ( cm . shape [ 0 ] ) if cm [ index ] [ i ] )
|
Return indices of the outputs of node with the given index .
|
59,818 |
def causally_significant_nodes ( cm ) : inputs = cm . sum ( 0 ) outputs = cm . sum ( 1 ) nodes_with_inputs_and_outputs = np . logical_and ( inputs > 0 , outputs > 0 ) return tuple ( np . where ( nodes_with_inputs_and_outputs ) [ 0 ] )
|
Return indices of nodes that have both inputs and outputs .
|
59,819 |
def relevant_connections ( n , _from , to ) : cm = np . zeros ( ( n , n ) ) if not _from or not to : return cm cm [ np . ix_ ( _from , to ) ] = 1 return cm
|
Construct a connectivity matrix .
|
59,820 |
def block_cm ( cm ) : if np . any ( cm . sum ( 1 ) == 0 ) : return True if np . all ( cm . sum ( 1 ) == 1 ) : return True outputs = list ( range ( cm . shape [ 1 ] ) ) def outputs_of ( nodes ) : return np . where ( cm [ nodes , : ] . sum ( 0 ) ) [ 0 ] def inputs_to ( nodes ) : return np . where ( cm [ : , nodes ] . sum ( 1 ) ) [ 0 ] sources = [ np . argmax ( cm . sum ( 1 ) ) ] sinks = outputs_of ( sources ) sink_inputs = inputs_to ( sinks ) while True : if np . array_equal ( sink_inputs , sources ) : return True sources = sink_inputs sinks = outputs_of ( sources ) sink_inputs = inputs_to ( sinks ) if np . array_equal ( sinks , outputs ) : return False
|
Return whether cm can be arranged as a block connectivity matrix .
|
59,821 |
def block_reducible ( cm , nodes1 , nodes2 ) : if not nodes1 or not nodes2 : return True cm = cm [ np . ix_ ( nodes1 , nodes2 ) ] if not cm . sum ( 0 ) . all ( ) or not cm . sum ( 1 ) . all ( ) : return True if len ( nodes1 ) > 1 and len ( nodes2 ) > 1 : return block_cm ( cm ) return False
|
Return whether connections from nodes1 to nodes2 are reducible .
|
59,822 |
def _connected ( cm , nodes , connection ) : if nodes is not None : cm = cm [ np . ix_ ( nodes , nodes ) ] num_components , _ = connected_components ( cm , connection = connection ) return num_components < 2
|
Test connectivity for the connectivity matrix .
|
59,823 |
def is_full ( cm , nodes1 , nodes2 ) : if not nodes1 or not nodes2 : return True cm = cm [ np . ix_ ( nodes1 , nodes2 ) ] return cm . sum ( 0 ) . all ( ) and cm . sum ( 1 ) . all ( )
|
Test connectivity of one set of nodes to another .
|
59,824 |
def apply_cut ( self , cm ) : inverse = np . logical_not ( self . cut_matrix ( cm . shape [ 0 ] ) ) . astype ( int ) return cm * inverse
|
Return a modified connectivity matrix with all connections that are severed by this cut removed .
|
59,825 |
def cuts_connections ( self , a , b ) : n = max ( self . indices ) + 1 return self . cut_matrix ( n ) [ np . ix_ ( a , b ) ] . any ( )
|
Check if this cut severs any connections from a to b .
|
59,826 |
def all_cut_mechanisms ( self ) : for mechanism in utils . powerset ( self . indices , nonempty = True ) : if self . splits_mechanism ( mechanism ) : yield mechanism
|
Return all mechanisms with elements on both sides of this cut .
|
59,827 |
def cut_matrix ( self , n ) : return connectivity . relevant_connections ( n , self . from_nodes , self . to_nodes )
|
Compute the cut matrix for this cut .
|
59,828 |
def cut_matrix ( self , n ) : cm = np . zeros ( ( n , n ) ) for part in self . partition : from_ , to = self . direction . order ( part . mechanism , part . purview ) external = tuple ( set ( self . indices ) - set ( to ) ) cm [ np . ix_ ( from_ , external ) ] = 1 return cm
|
The matrix of connections that are severed by this cut .
|
59,829 |
def concept_distance ( c1 , c2 ) : cause_purview = tuple ( set ( c1 . cause . purview + c2 . cause . purview ) ) effect_purview = tuple ( set ( c1 . effect . purview + c2 . effect . purview ) ) return ( repertoire_distance ( c1 . expand_cause_repertoire ( cause_purview ) , c2 . expand_cause_repertoire ( cause_purview ) ) + repertoire_distance ( c1 . expand_effect_repertoire ( effect_purview ) , c2 . expand_effect_repertoire ( effect_purview ) ) )
|
Return the distance between two concepts in concept space .
|
59,830 |
def small_phi_ces_distance ( C1 , C2 ) : return sum ( c . phi for c in C1 ) - sum ( c . phi for c in C2 )
|
Return the difference in |small_phi| between |CauseEffectStructure| .
|
59,831 |
def generate_nodes ( tpm , cm , network_state , indices , node_labels = None ) : if node_labels is None : node_labels = NodeLabels ( None , indices ) node_state = utils . state_of ( indices , network_state ) return tuple ( Node ( tpm , cm , index , state , node_labels ) for index , state in zip ( indices , node_state ) )
|
Generate |Node| objects for a subsystem .
|
59,832 |
def expand_node_tpm ( tpm ) : uc = np . ones ( [ 2 for node in tpm . shape ] ) return uc * tpm
|
Broadcast a node TPM over the full network .
|
59,833 |
def condition_tpm ( tpm , fixed_nodes , state ) : conditioning_indices = [ [ slice ( None ) ] ] * len ( state ) for i in fixed_nodes : conditioning_indices [ i ] = [ state [ i ] , np . newaxis ] conditioning_indices = list ( chain . from_iterable ( conditioning_indices ) ) return tpm [ tuple ( conditioning_indices ) ]
|
Return a TPM conditioned on the given fixed node indices whose states are fixed according to the given state - tuple .
|
59,834 |
def expand_tpm ( tpm ) : unconstrained = np . ones ( [ 2 ] * ( tpm . ndim - 1 ) + [ tpm . shape [ - 1 ] ] ) return tpm * unconstrained
|
Broadcast a state - by - node TPM so that singleton dimensions are expanded over the full network .
|
59,835 |
def marginalize_out ( node_indices , tpm ) : return tpm . sum ( tuple ( node_indices ) , keepdims = True ) / ( np . array ( tpm . shape ) [ list ( node_indices ) ] . prod ( ) )
|
Marginalize out nodes from a TPM .
|
59,836 |
def infer_edge ( tpm , a , b , contexts ) : def a_in_context ( context ) : a_off = context [ : a ] + OFF + context [ a : ] a_on = context [ : a ] + ON + context [ a : ] return ( a_off , a_on ) def a_affects_b_in_context ( context ) : a_off , a_on = a_in_context ( context ) return tpm [ a_off ] [ b ] != tpm [ a_on ] [ b ] return any ( a_affects_b_in_context ( context ) for context in contexts )
|
Infer the presence or absence of an edge from node A to node B .
|
59,837 |
def infer_cm ( tpm ) : network_size = tpm . shape [ - 1 ] all_contexts = tuple ( all_states ( network_size - 1 ) ) cm = np . empty ( ( network_size , network_size ) , dtype = int ) for a , b in np . ndindex ( cm . shape ) : cm [ a ] [ b ] = infer_edge ( tpm , a , b , all_contexts ) return cm
|
Infer the connectivity matrix associated with a state - by - node TPM in multidimensional form .
|
59,838 |
def get_num_processes ( ) : cpu_count = multiprocessing . cpu_count ( ) if config . NUMBER_OF_CORES == 0 : raise ValueError ( 'Invalid NUMBER_OF_CORES; value may not be 0.' ) if config . NUMBER_OF_CORES > cpu_count : log . info ( 'Requesting %s cores; only %s available' , config . NUMBER_OF_CORES , cpu_count ) return cpu_count if config . NUMBER_OF_CORES < 0 : num = cpu_count + config . NUMBER_OF_CORES + 1 if num <= 0 : raise ValueError ( 'Invalid NUMBER_OF_CORES; negative value is too negative: ' 'requesting {} cores, {} available.' . format ( num , cpu_count ) ) return num return config . NUMBER_OF_CORES
|
Return the number of processes to use in parallel .
|
59,839 |
def init_progress_bar ( self ) : disable = MapReduce . _forked or not config . PROGRESS_BARS if disable : total = None else : self . iterable = list ( self . iterable ) total = len ( self . iterable ) return tqdm ( total = total , disable = disable , leave = False , desc = self . description )
|
Initialize and return a progress bar .
|
59,840 |
def worker ( compute , task_queue , result_queue , log_queue , complete , * context ) : try : MapReduce . _forked = True log . debug ( 'Worker process starting...' ) configure_worker_logging ( log_queue ) for obj in iter ( task_queue . get , POISON_PILL ) : if complete . is_set ( ) : log . debug ( 'Worker received signal - exiting early' ) break log . debug ( 'Worker got %s' , obj ) result_queue . put ( compute ( obj , * context ) ) log . debug ( 'Worker finished %s' , obj ) result_queue . put ( POISON_PILL ) log . debug ( 'Worker process exiting' ) except Exception as e : result_queue . put ( ExceptionWrapper ( e ) )
|
A worker process run by multiprocessing . Process .
|
59,841 |
def start_parallel ( self ) : self . num_processes = get_num_processes ( ) self . task_queue = multiprocessing . Queue ( maxsize = Q_MAX_SIZE ) self . result_queue = multiprocessing . Queue ( ) self . log_queue = multiprocessing . Queue ( ) self . complete = multiprocessing . Event ( ) args = ( self . compute , self . task_queue , self . result_queue , self . log_queue , self . complete ) + self . context self . processes = [ multiprocessing . Process ( target = self . worker , args = args , daemon = True ) for i in range ( self . num_processes ) ] for process in self . processes : process . start ( ) self . log_thread = LogThread ( self . log_queue ) self . log_thread . start ( ) self . initialize_tasks ( )
|
Initialize all queues and start the worker processes and the log thread .
|
59,842 |
def initialize_tasks ( self ) : self . tasks = chain ( self . iterable , [ POISON_PILL ] * self . num_processes ) for task in islice ( self . tasks , Q_MAX_SIZE ) : log . debug ( 'Putting %s on queue' , task ) self . task_queue . put ( task )
|
Load the input queue to capacity .
|
59,843 |
def maybe_put_task ( self ) : try : task = next ( self . tasks ) except StopIteration : pass else : log . debug ( 'Putting %s on queue' , task ) self . task_queue . put ( task )
|
Enqueue the next task if there are any waiting .
|
59,844 |
def run_parallel ( self ) : try : self . start_parallel ( ) result = self . empty_result ( * self . context ) while self . num_processes > 0 : r = self . result_queue . get ( ) self . maybe_put_task ( ) if r is POISON_PILL : self . num_processes -= 1 elif isinstance ( r , ExceptionWrapper ) : r . reraise ( ) else : result = self . process_result ( r , result ) self . progress . update ( 1 ) if self . done : self . complete . set ( ) self . finish_parallel ( ) except Exception : raise finally : log . debug ( 'Removing progress bar' ) self . progress . close ( ) return result
|
Perform the computation in parallel reading results from the output queue and passing them to process_result .
|
59,845 |
def finish_parallel ( self ) : for process in self . processes : process . join ( ) log . debug ( 'Joining log thread' ) self . log_queue . put ( POISON_PILL ) self . log_thread . join ( ) self . log_queue . close ( ) log . debug ( 'Closing queues' ) self . task_queue . close ( ) self . result_queue . close ( )
|
Orderly shutdown of workers .
|
59,846 |
def run_sequential ( self ) : try : result = self . empty_result ( * self . context ) for obj in self . iterable : r = self . compute ( obj , * self . context ) result = self . process_result ( r , result ) self . progress . update ( 1 ) if self . done : break except Exception as e : raise e finally : self . progress . close ( ) return result
|
Perform the computation sequentially only holding two computed objects in memory at a time .
|
59,847 |
def configure_logging ( conf ) : logging . config . dictConfig ( { 'version' : 1 , 'disable_existing_loggers' : False , 'formatters' : { 'standard' : { 'format' : '%(asctime)s [%(name)s] %(levelname)s ' '%(processName)s: %(message)s' } } , 'handlers' : { 'file' : { 'level' : conf . LOG_FILE_LEVEL , 'filename' : conf . LOG_FILE , 'class' : 'logging.FileHandler' , 'formatter' : 'standard' , } , 'stdout' : { 'level' : conf . LOG_STDOUT_LEVEL , 'class' : 'pyphi.log.TqdmHandler' , 'formatter' : 'standard' , } } , 'root' : { 'level' : 'DEBUG' , 'handlers' : ( [ 'file' ] if conf . LOG_FILE_LEVEL else [ ] ) + ( [ 'stdout' ] if conf . LOG_STDOUT_LEVEL else [ ] ) } } )
|
Reconfigure PyPhi logging based on the current configuration .
|
59,848 |
def _validate ( self , value ) : if self . values and value not in self . values : raise ValueError ( '{} is not a valid value for {}' . format ( value , self . name ) )
|
Validate the new value .
|
59,849 |
def options ( cls ) : return { k : v for k , v in cls . __dict__ . items ( ) if isinstance ( v , Option ) }
|
Return a dictionary of the Option objects for this config .
|
59,850 |
def defaults ( self ) : return { k : v . default for k , v in self . options ( ) . items ( ) }
|
Return the default values of this configuration .
|
59,851 |
def load_dict ( self , dct ) : for k , v in dct . items ( ) : setattr ( self , k , v )
|
Load a dictionary of configuration values .
|
59,852 |
def load_file ( self , filename ) : filename = os . path . abspath ( filename ) with open ( filename ) as f : self . load_dict ( yaml . load ( f ) ) self . _loaded_files . append ( filename )
|
Load config from a YAML file .
|
59,853 |
def log ( self ) : log . info ( 'PyPhi v%s' , __about__ . __version__ ) if self . _loaded_files : log . info ( 'Loaded configuration from %s' , self . _loaded_files ) else : log . info ( 'Using default configuration (no configuration file ' 'provided)' ) log . info ( 'Current PyPhi configuration:\n %s' , str ( self ) )
|
Log current settings .
|
59,854 |
def be2le_state_by_state ( tpm ) : le = np . empty ( tpm . shape ) N = tpm . shape [ 0 ] n = int ( log2 ( N ) ) for i in range ( N ) : le [ i , : ] = tpm [ be2le ( i , n ) , : ] return le
|
Convert a state - by - state TPM from big - endian to little - endian or vice versa .
|
59,855 |
def to_multidimensional ( tpm ) : tpm = np . array ( tpm ) N = tpm . shape [ - 1 ] return tpm . reshape ( [ 2 ] * N + [ N ] , order = "F" ) . astype ( float )
|
Reshape a state - by - node TPM to the multidimensional form .
|
59,856 |
def state_by_state2state_by_node ( tpm ) : tpm = np . array ( tpm ) S = tpm . shape [ - 1 ] N = int ( log2 ( S ) ) sbn_tpm = np . zeros ( ( [ 2 ] * N + [ N ] ) ) states = { i : le_index2state ( i , N ) for i in range ( S ) } node_on = np . array ( [ [ states [ i ] [ n ] for i in range ( S ) ] for n in range ( N ) ] ) on_probabilities = [ tpm * node_on [ n ] for n in range ( N ) ] for i , state in states . items ( ) : sbn_tpm [ state ] = [ np . sum ( on_probabilities [ n ] [ i ] ) for n in range ( N ) ] return sbn_tpm
|
Convert a state - by - state TPM to a state - by - node TPM .
|
59,857 |
def state_by_node2state_by_state ( tpm ) : tpm = np . array ( tpm ) tpm = to_multidimensional ( tpm ) N = tpm . shape [ - 1 ] S = 2 ** N sbs_tpm = np . zeros ( ( S , S ) ) if not np . any ( np . logical_and ( tpm < 1 , tpm > 0 ) ) : for previous_state_index in range ( S ) : previous_state = le_index2state ( previous_state_index , N ) current_state_index = state2le_index ( tpm [ previous_state ] ) sbs_tpm [ previous_state_index , current_state_index ] = 1 else : for previous_state_index in range ( S ) : previous_state = le_index2state ( previous_state_index , N ) marginal_tpm = tpm [ previous_state ] for current_state_index in range ( S ) : current_state = np . array ( [ i for i in le_index2state ( current_state_index , N ) ] ) sbs_tpm [ previous_state_index , current_state_index ] = ( np . prod ( marginal_tpm [ current_state == 1 ] ) * np . prod ( 1 - marginal_tpm [ current_state == 0 ] ) ) return sbs_tpm
|
Convert a state - by - node TPM to a state - by - state TPM .
|
59,858 |
def load_json_network ( json_dict ) : network = pyphi . Network . from_json ( json_dict [ 'network' ] ) state = json_dict [ 'state' ] return ( network , state )
|
Load a network from a json file
|
59,859 |
def all_network_files ( ) : network_types = [ 'AND-circle' , 'MAJ-specialized' , 'MAJ-complete' , 'iit-3.0-modular' ] network_sizes = range ( 5 , 8 ) network_files = [ ] for n in network_sizes : for t in network_types : network_files . append ( '{}-{}' . format ( n , t ) ) return network_files
|
All network files
|
59,860 |
def profile_network ( filename ) : log = logging . getLogger ( filename ) logfile = os . path . join ( LOGS , filename + '.log' ) os . makedirs ( os . path . dirname ( logfile ) , exist_ok = True ) handler = logging . FileHandler ( logfile ) handler . setFormatter ( formatter ) log . addHandler ( handler ) log . setLevel ( logging . INFO ) try : with open ( os . path . join ( NETWORKS , filename + '.json' ) ) as f : network , state = load_json_network ( json . load ( f ) ) log . info ( 'Profiling %s...' , filename ) log . info ( 'PyPhi configuration:\n%s' , pyphi . config . get_config_string ( ) ) start = time ( ) pr = cProfile . Profile ( ) pr . enable ( ) results = tuple ( pyphi . compute . complexes ( network , state ) ) pr . disable ( ) end = time ( ) pstatsfile = os . path . join ( PSTATS , filename + '.pstats' ) os . makedirs ( os . path . dirname ( pstatsfile ) , exist_ok = True ) pr . dump_stats ( pstatsfile ) log . info ( 'Finished in %i seconds.' , end - start ) resultfile = os . path . join ( RESULTS , filename + '-results.pkl' ) os . makedirs ( os . path . dirname ( resultfile ) , exist_ok = True ) with open ( resultfile , 'wb' ) as f : pickle . dump ( results , f ) except Exception as e : log . error ( e ) raise e
|
Profile a network .
|
59,861 |
def run_tpm ( tpm , time_scale ) : sbs_tpm = convert . state_by_node2state_by_state ( tpm ) if sparse ( tpm ) : tpm = sparse_time ( sbs_tpm , time_scale ) else : tpm = dense_time ( sbs_tpm , time_scale ) return convert . state_by_state2state_by_node ( tpm )
|
Iterate a TPM by the specified number of time steps .
|
59,862 |
def run_cm ( cm , time_scale ) : cm = np . linalg . matrix_power ( cm , time_scale ) cm [ cm > 1 ] = 1 return cm
|
Iterate a connectivity matrix the specified number of steps .
|
59,863 |
def _reachable_subsystems ( network , indices , state ) : validate . is_network ( network ) for subset in utils . powerset ( indices , nonempty = True , reverse = True ) : try : yield Subsystem ( network , state , subset ) except exceptions . StateUnreachableError : pass
|
A generator over all subsystems in a valid state .
|
59,864 |
def all_complexes ( network , state ) : engine = FindAllComplexes ( subsystems ( network , state ) ) return engine . run ( config . PARALLEL_COMPLEX_EVALUATION )
|
Return a generator for all complexes of the network .
|
59,865 |
def complexes ( network , state ) : engine = FindIrreducibleComplexes ( possible_complexes ( network , state ) ) return engine . run ( config . PARALLEL_COMPLEX_EVALUATION )
|
Return all irreducible complexes of the network .
|
59,866 |
def major_complex ( network , state ) : log . info ( 'Calculating major complex...' ) result = complexes ( network , state ) if result : result = max ( result ) else : empty_subsystem = Subsystem ( network , state , ( ) ) result = _null_sia ( empty_subsystem ) log . info ( "Finished calculating major complex." ) return result
|
Return the major complex of the network .
|
59,867 |
def condensed ( network , state ) : result = [ ] covered_nodes = set ( ) for c in reversed ( sorted ( complexes ( network , state ) ) ) : if not any ( n in covered_nodes for n in c . subsystem . node_indices ) : result . append ( c ) covered_nodes = covered_nodes | set ( c . subsystem . node_indices ) return result
|
Return a list of maximal non - overlapping complexes .
|
59,868 |
def basic_network ( cm = False ) : tpm = np . array ( [ [ 0 , 0 , 0 ] , [ 0 , 0 , 1 ] , [ 1 , 0 , 1 ] , [ 1 , 0 , 0 ] , [ 1 , 1 , 0 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 0 ] ] ) if cm is False : cm = np . array ( [ [ 0 , 0 , 1 ] , [ 1 , 0 , 1 ] , [ 1 , 1 , 0 ] ] ) else : cm = None return Network ( tpm , cm = cm , node_labels = LABELS [ : tpm . shape [ 1 ] ] )
|
A 3 - node network of logic gates .
|
59,869 |
def basic_noisy_selfloop_network ( ) : tpm = np . array ( [ [ 0.271 , 0.19 , 0.244 ] , [ 0.919 , 0.19 , 0.756 ] , [ 0.919 , 0.91 , 0.756 ] , [ 0.991 , 0.91 , 0.244 ] , [ 0.919 , 0.91 , 0.756 ] , [ 0.991 , 0.91 , 0.244 ] , [ 0.991 , 0.99 , 0.244 ] , [ 0.999 , 0.99 , 0.756 ] ] ) cm = np . array ( [ [ 1 , 0 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] ) return Network ( tpm , cm = cm )
|
Based on the basic_network but with added selfloops and noisy edges .
|
59,870 |
def residue_network ( ) : tpm = np . array ( [ [ int ( s ) for s in bin ( x ) [ 2 : ] . zfill ( 5 ) [ : : - 1 ] ] for x in range ( 32 ) ] ) tpm [ np . where ( np . sum ( tpm [ 0 : , 2 : 4 ] , 1 ) == 2 ) , 0 ] = 1 tpm [ np . where ( np . sum ( tpm [ 0 : , 3 : 5 ] , 1 ) == 2 ) , 1 ] = 1 tpm [ np . where ( np . sum ( tpm [ 0 : , 2 : 4 ] , 1 ) < 2 ) , 0 ] = 0 tpm [ np . where ( np . sum ( tpm [ 0 : , 3 : 5 ] , 1 ) < 2 ) , 1 ] = 0 cm = np . zeros ( ( 5 , 5 ) ) cm [ 2 : 4 , 0 ] = 1 cm [ 3 : , 1 ] = 1 return Network ( tpm , cm = cm , node_labels = LABELS [ : tpm . shape [ 1 ] ] )
|
The network for the residue example .
|
59,871 |
def propagation_delay_network ( ) : num_nodes = 9 num_states = 2 ** num_nodes tpm = np . zeros ( ( num_states , num_nodes ) ) for previous_state_index , previous in enumerate ( all_states ( num_nodes ) ) : current_state = [ 0 for i in range ( num_nodes ) ] if previous [ 2 ] == 1 or previous [ 7 ] == 1 : current_state [ 0 ] = 1 if previous [ 0 ] == 1 : current_state [ 1 ] = 1 current_state [ 8 ] = 1 if previous [ 3 ] == 1 : current_state [ 2 ] = 1 current_state [ 4 ] = 1 if previous [ 1 ] == 1 ^ previous [ 5 ] == 1 : current_state [ 3 ] = 1 if previous [ 4 ] == 1 and previous [ 8 ] == 1 : current_state [ 6 ] = 1 if previous [ 6 ] == 1 : current_state [ 5 ] = 1 current_state [ 7 ] = 1 tpm [ previous_state_index , : ] = current_state cm = np . array ( [ [ 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ] ] ) return Network ( tpm , cm = cm , node_labels = LABELS [ : tpm . shape [ 1 ] ] )
|
A version of the primary example from the IIT 3 . 0 paper with deterministic COPY gates on each connection . These copy gates essentially function as propagation delays on the signal between OR AND and XOR gates from the original system .
|
59,872 |
def macro_network ( ) : tpm = np . array ( [ [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 1.0 , 1.0 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 1.0 , 1.0 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 0.3 , 0.3 ] , [ 0.3 , 0.3 , 1.0 , 1.0 ] , [ 1.0 , 1.0 , 0.3 , 0.3 ] , [ 1.0 , 1.0 , 0.3 , 0.3 ] , [ 1.0 , 1.0 , 0.3 , 0.3 ] , [ 1.0 , 1.0 , 1.0 , 1.0 ] ] ) return Network ( tpm , node_labels = LABELS [ : tpm . shape [ 1 ] ] )
|
A network of micro elements which has greater integrated information after coarse graining to a macro scale .
|
59,873 |
def blackbox_network ( ) : num_nodes = 6 num_states = 2 ** num_nodes tpm = np . zeros ( ( num_states , num_nodes ) ) for index , previous_state in enumerate ( all_states ( num_nodes ) ) : current_state = [ 0 for i in range ( num_nodes ) ] if previous_state [ 5 ] == 1 : current_state [ 0 ] = 1 current_state [ 1 ] = 1 if previous_state [ 0 ] == 1 and previous_state [ 1 ] : current_state [ 2 ] = 1 if previous_state [ 2 ] == 1 : current_state [ 3 ] = 1 current_state [ 4 ] = 1 if previous_state [ 3 ] == 1 and previous_state [ 4 ] == 1 : current_state [ 5 ] = 1 tpm [ index , : ] = current_state cm = np . array ( [ [ 0 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 1 , 0 , 0 , 0 , 0 ] ] ) return Network ( tpm , cm , node_labels = LABELS [ : tpm . shape [ 1 ] ] )
|
A micro - network to demonstrate blackboxing .
|
59,874 |
def actual_causation ( ) : tpm = np . array ( [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 1 ] ] ) cm = np . array ( [ [ 1 , 1 ] , [ 1 , 1 ] ] ) return Network ( tpm , cm , node_labels = ( 'OR' , 'AND' ) )
|
The actual causation example network consisting of an OR and AND gate with self - loops .
|
59,875 |
def prevention ( ) : tpm = np . array ( [ [ 0.5 , 0.5 , 1 ] , [ 0.5 , 0.5 , 0 ] , [ 0.5 , 0.5 , 1 ] , [ 0.5 , 0.5 , 1 ] , [ 0.5 , 0.5 , 1 ] , [ 0.5 , 0.5 , 0 ] , [ 0.5 , 0.5 , 1 ] , [ 0.5 , 0.5 , 1 ] ] ) cm = np . array ( [ [ 0 , 0 , 1 ] , [ 0 , 0 , 1 ] , [ 0 , 0 , 0 ] ] ) network = Network ( tpm , cm , node_labels = [ 'A' , 'B' , 'F' ] ) x_state = ( 1 , 1 , 1 ) y_state = ( 1 , 1 , 1 ) return Transition ( network , x_state , y_state , ( 0 , 1 ) , ( 2 , ) )
|
The |Transition| for the prevention example from Actual Causation Figure 5D .
|
59,876 |
def clear_subsystem_caches ( subsys ) : try : subsys . _repertoire_cache . clear ( ) subsys . _mice_cache . clear ( ) except TypeError : try : subsys . _repertoire_cache . cache = { } subsys . _mice_cache . cache = { } except AttributeError : subsys . _repertoire_cache = { } subsys . _repertoire_cache_info = [ 0 , 0 ] subsys . _mice_cache = { }
|
Clear subsystem caches
|
59,877 |
def all_states ( n , big_endian = False ) : if n == 0 : return for state in product ( ( 0 , 1 ) , repeat = n ) : if big_endian : yield state else : yield state [ : : - 1 ]
|
Return all binary states for a system .
|
59,878 |
def np_hash ( a ) : if a is None : return hash ( None ) a = np . ascontiguousarray ( a ) return int ( hashlib . sha1 ( a . view ( a . dtype ) ) . hexdigest ( ) , 16 )
|
Return a hash of a NumPy array .
|
59,879 |
def powerset ( iterable , nonempty = False , reverse = False ) : iterable = list ( iterable ) if nonempty : start = 1 else : start = 0 seq_sizes = range ( start , len ( iterable ) + 1 ) if reverse : seq_sizes = reversed ( seq_sizes ) iterable . reverse ( ) return chain . from_iterable ( combinations ( iterable , r ) for r in seq_sizes )
|
Generate the power set of an iterable .
|
59,880 |
def load_data ( directory , num ) : root = os . path . abspath ( os . path . dirname ( __file__ ) ) def get_path ( i ) : return os . path . join ( root , 'data' , directory , str ( i ) + '.npy' ) return [ np . load ( get_path ( i ) ) for i in range ( num ) ]
|
Load numpy data from the data directory .
|
59,881 |
def time_annotated ( func , * args , ** kwargs ) : start = time ( ) result = func ( * args , ** kwargs ) end = time ( ) result . time = round ( end - start , config . PRECISION ) return result
|
Annotate the decorated function or method with the total execution time .
|
59,882 |
def _null_ria ( direction , mechanism , purview , repertoire = None , phi = 0.0 ) : return RepertoireIrreducibilityAnalysis ( direction = direction , mechanism = mechanism , purview = purview , partition = None , repertoire = repertoire , partitioned_repertoire = None , phi = phi )
|
The irreducibility analysis for a reducible mechanism .
|
59,883 |
def damaged_by_cut ( self , subsystem ) : return ( subsystem . cut . splits_mechanism ( self . mechanism ) or np . any ( self . _relevant_connections ( subsystem ) * subsystem . cut . cut_matrix ( subsystem . network . size ) == 1 ) )
|
Return True if this MICE is affected by the subsystem s cut .
|
59,884 |
def eq_repertoires ( self , other ) : return ( np . array_equal ( self . cause_repertoire , other . cause_repertoire ) and np . array_equal ( self . effect_repertoire , other . effect_repertoire ) )
|
Return whether this concept has the same repertoires as another .
|
59,885 |
def emd_eq ( self , other ) : return ( self . phi == other . phi and self . mechanism == other . mechanism and self . eq_repertoires ( other ) )
|
Return whether this concept is equal to another in the context of an EMD calculation .
|
59,886 |
def directed_account ( transition , direction , mechanisms = False , purviews = False , allow_neg = False ) : if mechanisms is False : mechanisms = utils . powerset ( transition . mechanism_indices ( direction ) , nonempty = True ) links = [ transition . find_causal_link ( direction , mechanism , purviews = purviews , allow_neg = allow_neg ) for mechanism in mechanisms ] return DirectedAccount ( filter ( None , links ) )
|
Return the set of all |CausalLinks| of the specified direction .
|
59,887 |
def account ( transition , direction = Direction . BIDIRECTIONAL ) : if direction != Direction . BIDIRECTIONAL : return directed_account ( transition , direction ) return Account ( directed_account ( transition , Direction . CAUSE ) + directed_account ( transition , Direction . EFFECT ) )
|
Return the set of all causal links for a |Transition| .
|
59,888 |
def _evaluate_cut ( transition , cut , unpartitioned_account , direction = Direction . BIDIRECTIONAL ) : cut_transition = transition . apply_cut ( cut ) partitioned_account = account ( cut_transition , direction ) log . debug ( "Finished evaluating %s." , cut ) alpha = account_distance ( unpartitioned_account , partitioned_account ) return AcSystemIrreducibilityAnalysis ( alpha = round ( alpha , config . PRECISION ) , direction = direction , account = unpartitioned_account , partitioned_account = partitioned_account , transition = transition , cut = cut )
|
Find the |AcSystemIrreducibilityAnalysis| for a given cut .
|
59,889 |
def _get_cuts ( transition , direction ) : n = transition . network . size if direction is Direction . BIDIRECTIONAL : yielded = set ( ) for cut in chain ( _get_cuts ( transition , Direction . CAUSE ) , _get_cuts ( transition , Direction . EFFECT ) ) : cm = utils . np_hashable ( cut . cut_matrix ( n ) ) if cm not in yielded : yielded . add ( cm ) yield cut else : mechanism = transition . mechanism_indices ( direction ) purview = transition . purview_indices ( direction ) for partition in mip_partitions ( mechanism , purview , transition . node_labels ) : yield ActualCut ( direction , partition , transition . node_labels )
|
A list of possible cuts to a transition .
|
59,890 |
def sia ( transition , direction = Direction . BIDIRECTIONAL ) : validate . direction ( direction , allow_bi = True ) log . info ( "Calculating big-alpha for %s..." , transition ) if not transition : log . info ( 'Transition %s is empty; returning null SIA ' 'immediately.' , transition ) return _null_ac_sia ( transition , direction ) if not connectivity . is_weak ( transition . network . cm , transition . node_indices ) : log . info ( '%s is not strongly/weakly connected; returning null SIA ' 'immediately.' , transition ) return _null_ac_sia ( transition , direction ) log . debug ( "Finding unpartitioned account..." ) unpartitioned_account = account ( transition , direction ) log . debug ( "Found unpartitioned account." ) if not unpartitioned_account : log . info ( 'Empty unpartitioned account; returning null AC SIA ' 'immediately.' ) return _null_ac_sia ( transition , direction ) cuts = _get_cuts ( transition , direction ) engine = ComputeACSystemIrreducibility ( cuts , transition , direction , unpartitioned_account ) result = engine . run_sequential ( ) log . info ( "Finished calculating big-ac-phi data for %s." , transition ) log . debug ( "RESULT: \n%s" , result ) return result
|
Return the minimal information partition of a transition in a specific direction .
|
59,891 |
def nexus ( network , before_state , after_state , direction = Direction . BIDIRECTIONAL ) : validate . is_network ( network ) sias = ( sia ( transition , direction ) for transition in transitions ( network , before_state , after_state ) ) return tuple ( sorted ( filter ( None , sias ) , reverse = True ) )
|
Return a tuple of all irreducible nexus of the network .
|
59,892 |
def causal_nexus ( network , before_state , after_state , direction = Direction . BIDIRECTIONAL ) : validate . is_network ( network ) log . info ( "Calculating causal nexus..." ) result = nexus ( network , before_state , after_state , direction ) if result : result = max ( result ) else : null_transition = Transition ( network , before_state , after_state , ( ) , ( ) ) result = _null_ac_sia ( null_transition , direction ) log . info ( "Finished calculating causal nexus." ) log . debug ( "RESULT: \n%s" , result ) return result
|
Return the causal nexus of the network .
|
59,893 |
def nice_true_ces ( tc ) : cause_list = [ ] next_list = [ ] cause = '<--' effect = ' for event in tc : if event . direction == Direction . CAUSE : cause_list . append ( [ "{0:.4f}" . format ( round ( event . alpha , 4 ) ) , event . mechanism , cause , event . purview ] ) elif event . direction == Direction . EFFECT : next_list . append ( [ "{0:.4f}" . format ( round ( event . alpha , 4 ) ) , event . mechanism , effect , event . purview ] ) else : validate . direction ( event . direction ) true_list = [ ( cause_list [ event ] , next_list [ event ] ) for event in range ( len ( cause_list ) ) ] return true_list
|
Format a true |CauseEffectStructure| .
|
59,894 |
def true_ces ( subsystem , previous_state , next_state ) : network = subsystem . network nodes = subsystem . node_indices state = subsystem . state _events = events ( network , previous_state , state , next_state , nodes ) if not _events : log . info ( "Finished calculating, no echo events." ) return None result = tuple ( [ event . actual_cause for event in _events ] + [ event . actual_effect for event in _events ] ) log . info ( "Finished calculating true events." ) log . debug ( "RESULT: \n%s" , result ) return result
|
Set of all sets of elements that have true causes and true effects .
|
59,895 |
def true_events ( network , previous_state , current_state , next_state , indices = None , major_complex = None ) : if major_complex : nodes = major_complex . subsystem . node_indices elif indices : nodes = indices else : major_complex = compute . major_complex ( network , current_state ) nodes = major_complex . subsystem . node_indices return events ( network , previous_state , current_state , next_state , nodes )
|
Return all mechanisms that have true causes and true effects within the complex .
|
59,896 |
def extrinsic_events ( network , previous_state , current_state , next_state , indices = None , major_complex = None ) : if major_complex : mc_nodes = major_complex . subsystem . node_indices elif indices : mc_nodes = indices else : major_complex = compute . major_complex ( network , current_state ) mc_nodes = major_complex . subsystem . node_indices mechanisms = list ( utils . powerset ( mc_nodes , nonempty = True ) ) all_nodes = network . node_indices return events ( network , previous_state , current_state , next_state , all_nodes , mechanisms = mechanisms )
|
Set of all mechanisms that are in the major complex but which have true causes and effects within the entire network .
|
59,897 |
def apply_cut ( self , cut ) : return Transition ( self . network , self . before_state , self . after_state , self . cause_indices , self . effect_indices , cut )
|
Return a cut version of this transition .
|
59,898 |
def cause_repertoire ( self , mechanism , purview ) : return self . repertoire ( Direction . CAUSE , mechanism , purview )
|
Return the cause repertoire .
|
59,899 |
def effect_repertoire ( self , mechanism , purview ) : return self . repertoire ( Direction . EFFECT , mechanism , purview )
|
Return the effect repertoire .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.