idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
59,900
def repertoire ( self , direction , mechanism , purview ) : system = self . system [ direction ] node_labels = system . node_labels if not set ( purview ) . issubset ( self . purview_indices ( direction ) ) : raise ValueError ( '{} is not a {} purview in {}' . format ( fmt . fmt_mechanism ( purview , node_labels ) , direction , self ) ) if not set ( mechanism ) . issubset ( self . mechanism_indices ( direction ) ) : raise ValueError ( '{} is no a {} mechanism in {}' . format ( fmt . fmt_mechanism ( mechanism , node_labels ) , direction , self ) ) return system . repertoire ( direction , mechanism , purview )
Return the cause or effect repertoire function based on a direction .
59,901
def state_probability ( self , direction , repertoire , purview , ) : purview_state = self . purview_state ( direction ) index = tuple ( node_state if node in purview else 0 for node , node_state in enumerate ( purview_state ) ) return repertoire [ index ]
Compute the probability of the purview in its current state given the repertoire .
59,902
def probability ( self , direction , mechanism , purview ) : repertoire = self . repertoire ( direction , mechanism , purview ) return self . state_probability ( direction , repertoire , purview )
Probability that the purview is in it s current state given the state of the mechanism .
59,903
def purview_state ( self , direction ) : return { Direction . CAUSE : self . before_state , Direction . EFFECT : self . after_state } [ direction ]
The state of the purview when we are computing coefficients in direction .
59,904
def mechanism_indices ( self , direction ) : return { Direction . CAUSE : self . effect_indices , Direction . EFFECT : self . cause_indices } [ direction ]
The indices of nodes in the mechanism system .
59,905
def purview_indices ( self , direction ) : return { Direction . CAUSE : self . cause_indices , Direction . EFFECT : self . effect_indices } [ direction ]
The indices of nodes in the purview system .
59,906
def cause_ratio ( self , mechanism , purview ) : return self . _ratio ( Direction . CAUSE , mechanism , purview )
The cause ratio of the purview given mechanism .
59,907
def effect_ratio ( self , mechanism , purview ) : return self . _ratio ( Direction . EFFECT , mechanism , purview )
The effect ratio of the purview given mechanism .
59,908
def partitioned_repertoire ( self , direction , partition ) : system = self . system [ direction ] return system . partitioned_repertoire ( direction , partition )
Compute the repertoire over the partition in the given direction .
59,909
def partitioned_probability ( self , direction , partition ) : repertoire = self . partitioned_repertoire ( direction , partition ) return self . state_probability ( direction , repertoire , partition . purview )
Compute the probability of the mechanism over the purview in the partition .
59,910
def find_mip ( self , direction , mechanism , purview , allow_neg = False ) : alpha_min = float ( 'inf' ) probability = self . probability ( direction , mechanism , purview ) for partition in mip_partitions ( mechanism , purview , self . node_labels ) : partitioned_probability = self . partitioned_probability ( direction , partition ) alpha = log2 ( probability / partitioned_probability ) if utils . eq ( alpha , 0 ) or ( alpha < 0 and not allow_neg ) : return AcRepertoireIrreducibilityAnalysis ( state = self . mechanism_state ( direction ) , direction = direction , mechanism = mechanism , purview = purview , partition = partition , probability = probability , partitioned_probability = partitioned_probability , node_labels = self . node_labels , alpha = 0.0 ) if ( abs ( alpha_min ) - abs ( alpha ) ) > constants . EPSILON : alpha_min = alpha acria = AcRepertoireIrreducibilityAnalysis ( state = self . mechanism_state ( direction ) , direction = direction , mechanism = mechanism , purview = purview , partition = partition , probability = probability , partitioned_probability = partitioned_probability , node_labels = self . node_labels , alpha = alpha_min ) return acria
Find the ratio minimum information partition for a mechanism over a purview .
59,911
def find_causal_link ( self , direction , mechanism , purviews = False , allow_neg = False ) : purviews = self . potential_purviews ( direction , mechanism , purviews ) if not purviews : max_ria = _null_ac_ria ( self . mechanism_state ( direction ) , direction , mechanism , None ) else : max_ria = max ( self . find_mip ( direction , mechanism , purview , allow_neg ) for purview in purviews ) return CausalLink ( max_ria )
Return the maximally irreducible cause or effect ratio for a mechanism .
59,912
def find_actual_cause ( self , mechanism , purviews = False ) : return self . find_causal_link ( Direction . CAUSE , mechanism , purviews )
Return the actual cause of a mechanism .
59,913
def find_actual_effect ( self , mechanism , purviews = False ) : return self . find_causal_link ( Direction . EFFECT , mechanism , purviews )
Return the actual effect of a mechanism .
59,914
def find ( key ) : docs = list ( collection . find ( { KEY_FIELD : key } ) ) if not docs : return None pickled_value = docs [ 0 ] [ VALUE_FIELD ] return pickle . loads ( pickled_value )
Return the value associated with a key .
59,915
def insert ( key , value ) : value = pickle . dumps ( value , protocol = constants . PICKLE_PROTOCOL ) doc = { KEY_FIELD : key , VALUE_FIELD : Binary ( value ) } try : return collection . insert ( doc ) except pymongo . errors . DuplicateKeyError : return None
Store a value with a key .
59,916
def generate_key ( filtered_args ) : if isinstance ( filtered_args , Iterable ) : return hash ( tuple ( filtered_args ) ) return hash ( ( filtered_args , ) )
Get a key from some input .
59,917
def cache ( ignore = None ) : def decorator ( func ) : joblib_cached = constants . joblib_memory . cache ( func , ignore = ignore ) db_cached = DbMemoizedFunc ( func , ignore ) @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : if func . __name__ == '_sia' and not config . CACHE_SIAS : f = func elif config . CACHING_BACKEND == 'fs' : f = joblib_cached elif config . CACHING_BACKEND == 'db' : f = db_cached return f ( * args , ** kwargs ) return wrapper return decorator
Decorator for memoizing a function using either the filesystem or a database .
59,918
def get_output_key ( self , args , kwargs ) : filtered_args = joblib . func_inspect . filter_args ( self . func , self . ignore , args , kwargs ) filtered_args = tuple ( sorted ( filtered_args . values ( ) ) ) return db . generate_key ( filtered_args )
Return the key that the output should be cached with given arguments keyword arguments and a list of arguments to ignore .
59,919
def load_output ( self , args , kwargs ) : return db . find ( self . get_output_key ( args , kwargs ) )
Return cached output .
59,920
def cache_info ( self ) : return { 'single_node_repertoire' : self . _single_node_repertoire_cache . info ( ) , 'repertoire' : self . _repertoire_cache . info ( ) , 'mice' : self . _mice_cache . info ( ) }
Report repertoire cache statistics .
59,921
def clear_caches ( self ) : self . _single_node_repertoire_cache . clear ( ) self . _repertoire_cache . clear ( ) self . _mice_cache . clear ( )
Clear the mice and repertoire caches .
59,922
def apply_cut ( self , cut ) : return Subsystem ( self . network , self . state , self . node_indices , cut = cut , mice_cache = self . _mice_cache )
Return a cut version of this |Subsystem| .
59,923
def indices2nodes ( self , indices ) : if set ( indices ) - set ( self . node_indices ) : raise ValueError ( "`indices` must be a subset of the Subsystem's indices." ) return tuple ( self . _index2node [ n ] for n in indices )
Return |Nodes| for these indices .
59,924
def cause_repertoire ( self , mechanism , purview ) : if not purview : return np . array ( [ 1.0 ] ) if not mechanism : return max_entropy_distribution ( purview , self . tpm_size ) purview = frozenset ( purview ) joint = np . ones ( repertoire_shape ( purview , self . tpm_size ) ) joint *= functools . reduce ( np . multiply , [ self . _single_node_cause_repertoire ( m , purview ) for m in mechanism ] ) return distribution . normalize ( joint )
Return the cause repertoire of a mechanism over a purview .
59,925
def effect_repertoire ( self , mechanism , purview ) : if not purview : return np . array ( [ 1.0 ] ) mechanism = frozenset ( mechanism ) joint = np . ones ( repertoire_shape ( purview , self . tpm_size ) ) return joint * functools . reduce ( np . multiply , [ self . _single_node_effect_repertoire ( mechanism , p ) for p in purview ] )
Return the effect repertoire of a mechanism over a purview .
59,926
def repertoire ( self , direction , mechanism , purview ) : if direction == Direction . CAUSE : return self . cause_repertoire ( mechanism , purview ) elif direction == Direction . EFFECT : return self . effect_repertoire ( mechanism , purview ) return validate . direction ( direction )
Return the cause or effect repertoire based on a direction .
59,927
def partitioned_repertoire ( self , direction , partition ) : repertoires = [ self . repertoire ( direction , part . mechanism , part . purview ) for part in partition ] return functools . reduce ( np . multiply , repertoires )
Compute the repertoire of a partitioned mechanism and purview .
59,928
def expand_repertoire ( self , direction , repertoire , new_purview = None ) : if repertoire is None : return None purview = distribution . purview ( repertoire ) if new_purview is None : new_purview = self . node_indices if not set ( purview ) . issubset ( new_purview ) : raise ValueError ( "Expanded purview must contain original purview." ) non_purview_indices = tuple ( set ( new_purview ) - set ( purview ) ) uc = self . unconstrained_repertoire ( direction , non_purview_indices ) expanded_repertoire = repertoire * uc return distribution . normalize ( expanded_repertoire )
Distribute an effect repertoire over a larger purview .
59,929
def cause_info ( self , mechanism , purview ) : return repertoire_distance ( Direction . CAUSE , self . cause_repertoire ( mechanism , purview ) , self . unconstrained_cause_repertoire ( purview ) )
Return the cause information for a mechanism over a purview .
59,930
def effect_info ( self , mechanism , purview ) : return repertoire_distance ( Direction . EFFECT , self . effect_repertoire ( mechanism , purview ) , self . unconstrained_effect_repertoire ( purview ) )
Return the effect information for a mechanism over a purview .
59,931
def cause_effect_info ( self , mechanism , purview ) : return min ( self . cause_info ( mechanism , purview ) , self . effect_info ( mechanism , purview ) )
Return the cause - effect information for a mechanism over a purview .
59,932
def evaluate_partition ( self , direction , mechanism , purview , partition , repertoire = None ) : if repertoire is None : repertoire = self . repertoire ( direction , mechanism , purview ) partitioned_repertoire = self . partitioned_repertoire ( direction , partition ) phi = repertoire_distance ( direction , repertoire , partitioned_repertoire ) return ( phi , partitioned_repertoire )
Return the |small_phi| of a mechanism over a purview for the given partition .
59,933
def find_mip ( self , direction , mechanism , purview ) : if not purview : return _null_ria ( direction , mechanism , purview ) repertoire = self . repertoire ( direction , mechanism , purview ) def _mip ( phi , partition , partitioned_repertoire ) : return RepertoireIrreducibilityAnalysis ( phi = phi , direction = direction , mechanism = mechanism , purview = purview , partition = partition , repertoire = repertoire , partitioned_repertoire = partitioned_repertoire , node_labels = self . node_labels ) if ( direction == Direction . CAUSE and np . all ( repertoire == 0 ) ) : return _mip ( 0 , None , None ) mip = _null_ria ( direction , mechanism , purview , phi = float ( 'inf' ) ) for partition in mip_partitions ( mechanism , purview , self . node_labels ) : phi , partitioned_repertoire = self . evaluate_partition ( direction , mechanism , purview , partition , repertoire = repertoire ) if phi == 0 : return _mip ( 0.0 , partition , partitioned_repertoire ) if phi < mip . phi : mip = _mip ( phi , partition , partitioned_repertoire ) return mip
Return the minimum information partition for a mechanism over a purview .
59,934
def cause_mip ( self , mechanism , purview ) : return self . find_mip ( Direction . CAUSE , mechanism , purview )
Return the irreducibility analysis for the cause MIP .
59,935
def effect_mip ( self , mechanism , purview ) : return self . find_mip ( Direction . EFFECT , mechanism , purview )
Return the irreducibility analysis for the effect MIP .
59,936
def phi_cause_mip ( self , mechanism , purview ) : mip = self . cause_mip ( mechanism , purview ) return mip . phi if mip else 0
Return the |small_phi| of the cause MIP .
59,937
def phi_effect_mip ( self , mechanism , purview ) : mip = self . effect_mip ( mechanism , purview ) return mip . phi if mip else 0
Return the |small_phi| of the effect MIP .
59,938
def phi ( self , mechanism , purview ) : return min ( self . phi_cause_mip ( mechanism , purview ) , self . phi_effect_mip ( mechanism , purview ) )
Return the |small_phi| of a mechanism over a purview .
59,939
def find_mice ( self , direction , mechanism , purviews = False ) : purviews = self . potential_purviews ( direction , mechanism , purviews ) if not purviews : max_mip = _null_ria ( direction , mechanism , ( ) ) else : max_mip = max ( self . find_mip ( direction , mechanism , purview ) for purview in purviews ) if direction == Direction . CAUSE : return MaximallyIrreducibleCause ( max_mip ) elif direction == Direction . EFFECT : return MaximallyIrreducibleEffect ( max_mip ) return validate . direction ( direction )
Return the |MIC| or |MIE| for a mechanism .
59,940
def phi_max ( self , mechanism ) : return min ( self . mic ( mechanism ) . phi , self . mie ( mechanism ) . phi )
Return the |small_phi_max| of a mechanism .
59,941
def null_concept ( self ) : cause_repertoire = self . cause_repertoire ( ( ) , ( ) ) effect_repertoire = self . effect_repertoire ( ( ) , ( ) ) cause = MaximallyIrreducibleCause ( _null_ria ( Direction . CAUSE , ( ) , ( ) , cause_repertoire ) ) effect = MaximallyIrreducibleEffect ( _null_ria ( Direction . EFFECT , ( ) , ( ) , effect_repertoire ) ) return Concept ( mechanism = ( ) , cause = cause , effect = effect , subsystem = self )
Return the null concept of this subsystem .
59,942
def concept ( self , mechanism , purviews = False , cause_purviews = False , effect_purviews = False ) : log . debug ( 'Computing concept %s...' , mechanism ) if not mechanism : log . debug ( 'Empty concept; returning null concept' ) return self . null_concept cause = self . mic ( mechanism , purviews = ( cause_purviews or purviews ) ) effect = self . mie ( mechanism , purviews = ( effect_purviews or purviews ) ) log . debug ( 'Found concept %s' , mechanism ) return Concept ( mechanism = mechanism , cause = cause , effect = effect , subsystem = self )
Return the concept specified by a mechanism within this subsytem .
59,943
def _null_ac_sia ( transition , direction , alpha = 0.0 ) : return AcSystemIrreducibilityAnalysis ( transition = transition , direction = direction , alpha = alpha , account = ( ) , partitioned_account = ( ) )
Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and empty accounts .
59,944
def mechanism ( self ) : assert self . actual_cause . mechanism == self . actual_effect . mechanism return self . actual_cause . mechanism
The mechanism of the event .
59,945
def irreducible_causes ( self ) : return tuple ( link for link in self if link . direction is Direction . CAUSE )
The set of irreducible causes in this |Account| .
59,946
def irreducible_effects ( self ) : return tuple ( link for link in self if link . direction is Direction . EFFECT )
The set of irreducible effects in this |Account| .
59,947
def make_repr ( self , attrs ) : if config . REPR_VERBOSITY in [ MEDIUM , HIGH ] : return self . __str__ ( ) elif config . REPR_VERBOSITY is LOW : return '{}({})' . format ( self . __class__ . __name__ , ', ' . join ( attr + '=' + repr ( getattr ( self , attr ) ) for attr in attrs ) ) raise ValueError ( 'Invalid value for `config.REPR_VERBOSITY`' )
Construct a repr string .
59,948
def indent ( lines , amount = 2 , char = ' ' ) : r lines = str ( lines ) padding = amount * char return padding + ( '\n' + padding ) . join ( lines . split ( '\n' ) )
r Indent a string .
59,949
def margin ( text ) : r lines = str ( text ) . split ( '\n' ) return '\n' . join ( ' {} ' . format ( l ) for l in lines )
r Add a margin to both ends of each line in the string .
59,950
def box ( text ) : r lines = text . split ( '\n' ) width = max ( len ( l ) for l in lines ) top_bar = ( TOP_LEFT_CORNER + HORIZONTAL_BAR * ( 2 + width ) + TOP_RIGHT_CORNER ) bottom_bar = ( BOTTOM_LEFT_CORNER + HORIZONTAL_BAR * ( 2 + width ) + BOTTOM_RIGHT_CORNER ) lines = [ LINES_FORMAT_STR . format ( line = line , width = width ) for line in lines ] return top_bar + '\n' + '\n' . join ( lines ) + '\n' + bottom_bar
r Wrap a chunk of text in a box .
59,951
def side_by_side ( left , right ) : r left_lines = list ( left . split ( '\n' ) ) right_lines = list ( right . split ( '\n' ) ) diff = abs ( len ( left_lines ) - len ( right_lines ) ) if len ( left_lines ) > len ( right_lines ) : fill = ' ' * len ( right_lines [ 0 ] ) right_lines += [ fill ] * diff elif len ( right_lines ) > len ( left_lines ) : fill = ' ' * len ( left_lines [ 0 ] ) left_lines += [ fill ] * diff return '\n' . join ( a + b for a , b in zip ( left_lines , right_lines ) ) + '\n'
r Put two boxes next to each other .
59,952
def header ( head , text , over_char = None , under_char = None , center = True ) : lines = list ( text . split ( '\n' ) ) width = max ( len ( l ) for l in lines ) if center : head = head . center ( width ) + '\n' else : head = head . ljust ( width ) + '\n' if under_char : head = head + under_char * width + '\n' if over_char : head = over_char * width + '\n' + head return head + text
Center a head over a block of text .
59,953
def labels ( indices , node_labels = None ) : if node_labels is None : return tuple ( map ( str , indices ) ) return node_labels . indices2labels ( indices )
Get the labels for a tuple of mechanism indices .
59,954
def fmt_number ( p ) : formatted = '{:n}' . format ( p ) if not config . PRINT_FRACTIONS : return formatted fraction = Fraction ( p ) nice = fraction . limit_denominator ( 128 ) return ( str ( nice ) if ( abs ( fraction - nice ) < constants . EPSILON and nice . denominator in NICE_DENOMINATORS ) else formatted )
Format a number .
59,955
def fmt_part ( part , node_labels = None ) : def nodes ( x ) : return ',' . join ( labels ( x , node_labels ) ) if x else EMPTY_SET numer = nodes ( part . mechanism ) denom = nodes ( part . purview ) width = max ( 3 , len ( numer ) , len ( denom ) ) divider = HORIZONTAL_BAR * width return ( '{numer:^{width}}\n' '{divider}\n' '{denom:^{width}}' ) . format ( numer = numer , divider = divider , denom = denom , width = width )
Format a |Part| .
59,956
def fmt_partition ( partition ) : if not partition : return '' parts = [ fmt_part ( part , partition . node_labels ) . split ( '\n' ) for part in partition ] times = ( ' ' , ' {} ' . format ( MULTIPLY ) , ' ' ) breaks = ( '\n' , '\n' , '' ) between = [ times ] * ( len ( parts ) - 1 ) + [ breaks ] elements = chain . from_iterable ( zip ( parts , between ) ) return '' . join ( chain . from_iterable ( zip ( * elements ) ) )
Format a |Bipartition| .
59,957
def fmt_ces ( c , title = None ) : if not c : return '()\n' if title is None : title = 'Cause-effect structure' concepts = '\n' . join ( margin ( x ) for x in c ) + '\n' title = '{} ({} concept{})' . format ( title , len ( c ) , '' if len ( c ) == 1 else 's' ) return header ( title , concepts , HEADER_BAR_1 , HEADER_BAR_1 )
Format a |CauseEffectStructure| .
59,958
def fmt_concept ( concept ) : def fmt_cause_or_effect ( x ) : return box ( indent ( fmt_ria ( x . ria , verbose = False , mip = True ) , amount = 1 ) ) cause = header ( 'MIC' , fmt_cause_or_effect ( concept . cause ) ) effect = header ( 'MIE' , fmt_cause_or_effect ( concept . effect ) ) ce = side_by_side ( cause , effect ) mechanism = fmt_mechanism ( concept . mechanism , concept . node_labels ) title = 'Concept: Mechanism = {}, {} = {}' . format ( mechanism , SMALL_PHI , fmt_number ( concept . phi ) ) center = config . REPR_VERBOSITY is HIGH return header ( title , ce , HEADER_BAR_2 , HEADER_BAR_2 , center = center )
Format a |Concept| .
59,959
def fmt_ria ( ria , verbose = True , mip = False ) : if verbose : mechanism = 'Mechanism: {}\n' . format ( fmt_mechanism ( ria . mechanism , ria . node_labels ) ) direction = '\nDirection: {}' . format ( ria . direction ) else : mechanism = '' direction = '' if config . REPR_VERBOSITY is HIGH : partition = '\n{}:\n{}' . format ( ( 'MIP' if mip else 'Partition' ) , indent ( fmt_partition ( ria . partition ) ) ) repertoire = '\nRepertoire:\n{}' . format ( indent ( fmt_repertoire ( ria . repertoire ) ) ) partitioned_repertoire = '\nPartitioned repertoire:\n{}' . format ( indent ( fmt_repertoire ( ria . partitioned_repertoire ) ) ) else : partition = '' repertoire = '' partitioned_repertoire = '' return ( '{SMALL_PHI} = {phi}\n' '{mechanism}' 'Purview = {purview}' '{direction}' '{partition}' '{repertoire}' '{partitioned_repertoire}' ) . format ( SMALL_PHI = SMALL_PHI , mechanism = mechanism , purview = fmt_mechanism ( ria . purview , ria . node_labels ) , direction = direction , phi = fmt_number ( ria . phi ) , partition = partition , repertoire = repertoire , partitioned_repertoire = partitioned_repertoire )
Format a |RepertoireIrreducibilityAnalysis| .
59,960
def fmt_cut ( cut ) : return 'Cut {from_nodes} {symbol} {to_nodes}' . format ( from_nodes = fmt_mechanism ( cut . from_nodes , cut . node_labels ) , symbol = CUT_SYMBOL , to_nodes = fmt_mechanism ( cut . to_nodes , cut . node_labels ) )
Format a |Cut| .
59,961
def fmt_sia ( sia , ces = True ) : if ces : body = ( '{ces}' '{partitioned_ces}' . format ( ces = fmt_ces ( sia . ces , 'Cause-effect structure' ) , partitioned_ces = fmt_ces ( sia . partitioned_ces , 'Partitioned cause-effect structure' ) ) ) center_header = True else : body = '' center_header = False title = 'System irreducibility analysis: {BIG_PHI} = {phi}' . format ( BIG_PHI = BIG_PHI , phi = fmt_number ( sia . phi ) ) body = header ( str ( sia . subsystem ) , body , center = center_header ) body = header ( str ( sia . cut ) , body , center = center_header ) return box ( header ( title , body , center = center_header ) )
Format a |SystemIrreducibilityAnalysis| .
59,962
def fmt_repertoire ( r ) : if r is None : return '' r = r . squeeze ( ) lines = [ ] space = ' ' * 4 head = '{S:^{s_width}}{space}Pr({S})' . format ( S = 'S' , s_width = r . ndim , space = space ) lines . append ( head ) for state in utils . all_states ( r . ndim ) : state_str = '' . join ( str ( i ) for i in state ) lines . append ( '{0}{1}{2}' . format ( state_str , space , fmt_number ( r [ state ] ) ) ) width = max ( len ( line ) for line in lines ) lines . insert ( 1 , DOTTED_HEADER * ( width + 1 ) ) return box ( '\n' . join ( lines ) )
Format a repertoire .
59,963
def fmt_ac_ria ( ria ) : causality = { Direction . CAUSE : ( fmt_mechanism ( ria . purview , ria . node_labels ) , ARROW_LEFT , fmt_mechanism ( ria . mechanism , ria . node_labels ) ) , Direction . EFFECT : ( fmt_mechanism ( ria . mechanism , ria . node_labels ) , ARROW_RIGHT , fmt_mechanism ( ria . purview , ria . node_labels ) ) } [ ria . direction ] causality = ' ' . join ( causality ) return '{ALPHA} = {alpha} {causality}' . format ( ALPHA = ALPHA , alpha = round ( ria . alpha , 4 ) , causality = causality )
Format an AcRepertoireIrreducibilityAnalysis .
59,964
def fmt_account ( account , title = None ) : if title is None : title = account . __class__ . __name__ title = '{} ({} causal link{})' . format ( title , len ( account ) , '' if len ( account ) == 1 else 's' ) body = '' body += 'Irreducible effects\n' body += '\n' . join ( fmt_ac_ria ( m ) for m in account . irreducible_effects ) body += '\nIrreducible causes\n' body += '\n' . join ( fmt_ac_ria ( m ) for m in account . irreducible_causes ) return '\n' + header ( title , body , under_char = '*' )
Format an Account or a DirectedAccount .
59,965
def fmt_ac_sia ( ac_sia ) : body = ( '{ALPHA} = {alpha}\n' 'direction: {ac_sia.direction}\n' 'transition: {ac_sia.transition}\n' 'before state: {ac_sia.before_state}\n' 'after state: {ac_sia.after_state}\n' 'cut:\n{ac_sia.cut}\n' '{account}\n' '{partitioned_account}' . format ( ALPHA = ALPHA , alpha = round ( ac_sia . alpha , 4 ) , ac_sia = ac_sia , account = fmt_account ( ac_sia . account , 'Account' ) , partitioned_account = fmt_account ( ac_sia . partitioned_account , 'Partitioned Account' ) ) ) return box ( header ( 'AcSystemIrreducibilityAnalysis' , body , under_char = HORIZONTAL_BAR ) )
Format a AcSystemIrreducibilityAnalysis .
59,966
def fmt_transition ( t ) : return "Transition({} {} {})" . format ( fmt_mechanism ( t . cause_indices , t . node_labels ) , ARROW_RIGHT , fmt_mechanism ( t . effect_indices , t . node_labels ) )
Format a |Transition| .
59,967
def direction ( direction , allow_bi = False ) : valid = [ Direction . CAUSE , Direction . EFFECT ] if allow_bi : valid . append ( Direction . BIDIRECTIONAL ) if direction not in valid : raise ValueError ( '`direction` must be one of {}' . format ( valid ) ) return True
Validate that the given direction is one of the allowed constants .
59,968
def tpm ( tpm , check_independence = True ) : see_tpm_docs = ( 'See the documentation on TPM conventions and the `pyphi.Network` ' 'object for more information on TPM forms.' ) tpm = np . array ( tpm ) N = tpm . shape [ - 1 ] if tpm . ndim == 2 : if not ( ( tpm . shape [ 0 ] == 2 ** N and tpm . shape [ 1 ] == N ) or ( tpm . shape [ 0 ] == tpm . shape [ 1 ] ) ) : raise ValueError ( 'Invalid shape for 2-D TPM: {}\nFor a state-by-node TPM, ' 'there must be ' '2^N rows and N columns, where N is the ' 'number of nodes. State-by-state TPM must be square. ' '{}' . format ( tpm . shape , see_tpm_docs ) ) if tpm . shape [ 0 ] == tpm . shape [ 1 ] and check_independence : conditionally_independent ( tpm ) elif tpm . ndim == ( N + 1 ) : if tpm . shape != tuple ( [ 2 ] * N + [ N ] ) : raise ValueError ( 'Invalid shape for multidimensional state-by-node TPM: {}\n' 'The shape should be {} for {} nodes. {}' . format ( tpm . shape , ( [ 2 ] * N ) + [ N ] , N , see_tpm_docs ) ) else : raise ValueError ( 'Invalid TPM: Must be either 2-dimensional or multidimensional. ' '{}' . format ( see_tpm_docs ) ) return True
Validate a TPM .
59,969
def conditionally_independent ( tpm ) : if not config . VALIDATE_CONDITIONAL_INDEPENDENCE : return True tpm = np . array ( tpm ) if is_state_by_state ( tpm ) : there_and_back_again = convert . state_by_node2state_by_state ( convert . state_by_state2state_by_node ( tpm ) ) else : there_and_back_again = convert . state_by_state2state_by_node ( convert . state_by_node2state_by_state ( tpm ) ) if np . any ( ( tpm - there_and_back_again ) >= EPSILON ) : raise exceptions . ConditionallyDependentError ( 'TPM is not conditionally independent.\n' 'See the conditional independence example in the documentation ' 'for more info.' ) return True
Validate that the TPM is conditionally independent .
59,970
def connectivity_matrix ( cm ) : if cm . size == 0 : return True if cm . ndim != 2 : raise ValueError ( "Connectivity matrix must be 2-dimensional." ) if cm . shape [ 0 ] != cm . shape [ 1 ] : raise ValueError ( "Connectivity matrix must be square." ) if not np . all ( np . logical_or ( cm == 1 , cm == 0 ) ) : raise ValueError ( "Connectivity matrix must contain only binary " "values." ) return True
Validate the given connectivity matrix .
59,971
def node_labels ( node_labels , node_indices ) : if len ( node_labels ) != len ( node_indices ) : raise ValueError ( "Labels {0} must label every node {1}." . format ( node_labels , node_indices ) ) if len ( node_labels ) != len ( set ( node_labels ) ) : raise ValueError ( "Labels {0} must be unique." . format ( node_labels ) )
Validate that there is a label for each node .
59,972
def network ( n ) : tpm ( n . tpm ) connectivity_matrix ( n . cm ) if n . cm . shape [ 0 ] != n . size : raise ValueError ( "Connectivity matrix must be NxN, where N is the " "number of nodes in the network." ) return True
Validate a |Network| .
59,973
def state_length ( state , size ) : if len ( state ) != size : raise ValueError ( 'Invalid state: there must be one entry per ' 'node in the network; this state has {} entries, but ' 'there are {} nodes.' . format ( len ( state ) , size ) ) return True
Check that the state is the given size .
59,974
def state_reachable ( subsystem ) : tpm = subsystem . tpm [ ... , subsystem . node_indices ] test = tpm - np . array ( subsystem . proper_state ) if not np . any ( np . logical_and ( - 1 < test , test < 1 ) . all ( - 1 ) ) : raise exceptions . StateUnreachableError ( subsystem . state )
Return whether a state can be reached according to the network s TPM .
59,975
def cut ( cut , node_indices ) : if cut . indices != node_indices : raise ValueError ( '{} nodes are not equal to subsystem nodes ' '{}' . format ( cut , node_indices ) )
Check that the cut is for only the given nodes .
59,976
def subsystem ( s ) : node_states ( s . state ) cut ( s . cut , s . cut_indices ) if config . VALIDATE_SUBSYSTEM_STATES : state_reachable ( s ) return True
Validate a |Subsystem| .
59,977
def partition ( partition ) : nodes = set ( ) for part in partition : for node in part : if node in nodes : raise ValueError ( 'Micro-element {} may not be partitioned into multiple ' 'macro-elements' . format ( node ) ) nodes . add ( node )
Validate a partition - used by blackboxes and coarse grains .
59,978
def coarse_grain ( coarse_grain ) : partition ( coarse_grain . partition ) if len ( coarse_grain . partition ) != len ( coarse_grain . grouping ) : raise ValueError ( 'output and state groupings must be the same size' ) for part , group in zip ( coarse_grain . partition , coarse_grain . grouping ) : if set ( range ( len ( part ) + 1 ) ) != set ( group [ 0 ] + group [ 1 ] ) : raise ValueError ( 'elements in output grouping {0} do not match ' 'elements in state grouping {1}' . format ( part , group ) )
Validate a macro coarse - graining .
59,979
def blackbox ( blackbox ) : if tuple ( sorted ( blackbox . output_indices ) ) != blackbox . output_indices : raise ValueError ( 'Output indices {} must be ordered' . format ( blackbox . output_indices ) ) partition ( blackbox . partition ) for part in blackbox . partition : if not set ( part ) & set ( blackbox . output_indices ) : raise ValueError ( 'Every blackbox must have an output - {} does not' . format ( part ) )
Validate a macro blackboxing .
59,980
def blackbox_and_coarse_grain ( blackbox , coarse_grain ) : if blackbox is None : return for box in blackbox . partition : outputs = set ( box ) & set ( blackbox . output_indices ) if coarse_grain is None and len ( outputs ) > 1 : raise ValueError ( 'A blackboxing with multiple outputs per box must be ' 'coarse-grained.' ) if ( coarse_grain and not any ( outputs . issubset ( part ) for part in coarse_grain . partition ) ) : raise ValueError ( 'Multiple outputs from a blackbox must be partitioned into ' 'the same macro-element of the coarse-graining' )
Validate that a coarse - graining properly combines the outputs of a blackboxing .
59,981
def register ( self , name ) : def register_func ( func ) : self . store [ name ] = func return func return register_func
Decorator for registering a function with PyPhi .
59,982
def ces ( subsystem , mechanisms = False , purviews = False , cause_purviews = False , effect_purviews = False , parallel = False ) : if mechanisms is False : mechanisms = utils . powerset ( subsystem . node_indices , nonempty = True ) engine = ComputeCauseEffectStructure ( mechanisms , subsystem , purviews , cause_purviews , effect_purviews ) return CauseEffectStructure ( engine . run ( parallel or config . PARALLEL_CONCEPT_EVALUATION ) , subsystem = subsystem )
Return the conceptual structure of this subsystem optionally restricted to concepts with the mechanisms and purviews given in keyword arguments .
59,983
def conceptual_info ( subsystem ) : ci = ces_distance ( ces ( subsystem ) , CauseEffectStructure ( ( ) , subsystem = subsystem ) ) return round ( ci , config . PRECISION )
Return the conceptual information for a |Subsystem| .
59,984
def evaluate_cut ( uncut_subsystem , cut , unpartitioned_ces ) : log . debug ( 'Evaluating %s...' , cut ) cut_subsystem = uncut_subsystem . apply_cut ( cut ) if config . ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS : mechanisms = unpartitioned_ces . mechanisms else : mechanisms = set ( unpartitioned_ces . mechanisms + list ( cut_subsystem . cut_mechanisms ) ) partitioned_ces = ces ( cut_subsystem , mechanisms ) log . debug ( 'Finished evaluating %s.' , cut ) phi_ = ces_distance ( unpartitioned_ces , partitioned_ces ) return SystemIrreducibilityAnalysis ( phi = phi_ , ces = unpartitioned_ces , partitioned_ces = partitioned_ces , subsystem = uncut_subsystem , cut_subsystem = cut_subsystem )
Compute the system irreducibility for a given cut .
59,985
def sia_bipartitions ( nodes , node_labels = None ) : if config . CUT_ONE_APPROXIMATION : bipartitions = directed_bipartition_of_one ( nodes ) else : bipartitions = directed_bipartition ( nodes , nontrivial = True ) return [ Cut ( bipartition [ 0 ] , bipartition [ 1 ] , node_labels ) for bipartition in bipartitions ]
Return all |big_phi| cuts for the given nodes .
59,986
def _sia ( cache_key , subsystem ) : log . info ( 'Calculating big-phi data for %s...' , subsystem ) if not subsystem : log . info ( 'Subsystem %s is empty; returning null SIA ' 'immediately.' , subsystem ) return _null_sia ( subsystem ) if not connectivity . is_strong ( subsystem . cm , subsystem . node_indices ) : log . info ( '%s is not strongly connected; returning null SIA ' 'immediately.' , subsystem ) return _null_sia ( subsystem ) if len ( subsystem . cut_indices ) == 1 : if not subsystem . cm [ subsystem . node_indices ] [ subsystem . node_indices ] : log . info ( 'Single micro nodes %s without selfloops cannot have ' 'phi; returning null SIA immediately.' , subsystem ) return _null_sia ( subsystem ) elif not config . SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI : log . info ( 'Single micro nodes %s with selfloops cannot have ' 'phi; returning null SIA immediately.' , subsystem ) return _null_sia ( subsystem ) log . debug ( 'Finding unpartitioned CauseEffectStructure...' ) unpartitioned_ces = _ces ( subsystem ) if not unpartitioned_ces : log . info ( 'Empty unpartitioned CauseEffectStructure; returning null ' 'SIA immediately.' ) return _null_sia ( subsystem ) log . debug ( 'Found unpartitioned CauseEffectStructure.' ) if len ( subsystem . cut_indices ) == 1 : cuts = [ Cut ( subsystem . cut_indices , subsystem . cut_indices , subsystem . cut_node_labels ) ] else : cuts = sia_bipartitions ( subsystem . cut_indices , subsystem . cut_node_labels ) engine = ComputeSystemIrreducibility ( cuts , subsystem , unpartitioned_ces ) result = engine . run ( config . PARALLEL_CUT_EVALUATION ) if config . CLEAR_SUBSYSTEM_CACHES_AFTER_COMPUTING_SIA : log . debug ( 'Clearing subsystem caches.' ) subsystem . clear_caches ( ) log . info ( 'Finished calculating big-phi data for %s.' , subsystem ) return result
Return the minimal information partition of a subsystem .
59,987
def _sia_cache_key ( subsystem ) : return ( hash ( subsystem ) , config . ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS , config . CUT_ONE_APPROXIMATION , config . MEASURE , config . PRECISION , config . VALIDATE_SUBSYSTEM_STATES , config . SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI , config . PARTITION_TYPE , )
The cache key of the subsystem .
59,988
def concept_cuts ( direction , node_indices , node_labels = None ) : for partition in mip_partitions ( node_indices , node_indices ) : yield KCut ( direction , partition , node_labels )
Generator over all concept - syle cuts for these nodes .
59,989
def directional_sia ( subsystem , direction , unpartitioned_ces = None ) : if unpartitioned_ces is None : unpartitioned_ces = _ces ( subsystem ) c_system = ConceptStyleSystem ( subsystem , direction ) cuts = concept_cuts ( direction , c_system . cut_indices , subsystem . node_labels ) engine = ComputeSystemIrreducibility ( cuts , c_system , unpartitioned_ces ) return engine . run ( config . PARALLEL_CUT_EVALUATION )
Calculate a concept - style SystemIrreducibilityAnalysisCause or SystemIrreducibilityAnalysisEffect .
59,990
def sia_concept_style ( subsystem ) : unpartitioned_ces = _ces ( subsystem ) sia_cause = directional_sia ( subsystem , Direction . CAUSE , unpartitioned_ces ) sia_effect = directional_sia ( subsystem , Direction . EFFECT , unpartitioned_ces ) return SystemIrreducibilityAnalysisConceptStyle ( sia_cause , sia_effect )
Compute a concept - style SystemIrreducibilityAnalysis
59,991
def compute ( mechanism , subsystem , purviews , cause_purviews , effect_purviews ) : concept = subsystem . concept ( mechanism , purviews = purviews , cause_purviews = cause_purviews , effect_purviews = effect_purviews ) concept . subsystem = None return concept
Compute a |Concept| for a mechanism in this |Subsystem| with the provided purviews .
59,992
def process_result ( self , new_concept , concepts ) : if new_concept . phi > 0 : new_concept . subsystem = self . subsystem concepts . append ( new_concept ) return concepts
Save all concepts with non - zero |small_phi| to the |CauseEffectStructure| .
59,993
def process_result ( self , new_sia , min_sia ) : if new_sia . phi == 0 : self . done = True return new_sia elif new_sia < min_sia : return new_sia return min_sia
Check if the new SIA has smaller |big_phi| than the standing result .
59,994
def concept ( self , mechanism , purviews = False , cause_purviews = False , effect_purviews = False ) : cause = self . cause_system . mic ( mechanism , purviews = ( cause_purviews or purviews ) ) effect = self . effect_system . mie ( mechanism , purviews = ( effect_purviews or purviews ) ) return Concept ( mechanism = mechanism , cause = cause , effect = effect , subsystem = self )
Compute a concept using the appropriate system for each side of the cut .
59,995
def coerce_to_indices ( self , nodes ) : if nodes is None : return self . node_indices if all ( isinstance ( node , str ) for node in nodes ) : indices = self . labels2indices ( nodes ) else : indices = map ( int , nodes ) return tuple ( sorted ( set ( indices ) ) )
Return the nodes indices for nodes where nodes is either already integer indices or node labels .
59,996
def _null_sia ( subsystem , phi = 0.0 ) : return SystemIrreducibilityAnalysis ( subsystem = subsystem , cut_subsystem = subsystem , phi = phi , ces = _null_ces ( subsystem ) , partitioned_ces = _null_ces ( subsystem ) )
Return a |SystemIrreducibilityAnalysis| with zero |big_phi| and empty cause - effect structures .
59,997
def labeled_mechanisms ( self ) : label = self . subsystem . node_labels . indices2labels return tuple ( list ( label ( mechanism ) ) for mechanism in self . mechanisms )
The labeled mechanism of each concept .
59,998
def order ( self , mechanism , purview ) : if self is Direction . CAUSE : return purview , mechanism elif self is Direction . EFFECT : return mechanism , purview from . import validate return validate . direction ( self )
Order the mechanism and purview in time .
59,999
def sametype ( func ) : @ functools . wraps ( func ) def wrapper ( self , other ) : if type ( other ) is not type ( self ) : return NotImplemented return func ( self , other ) return wrapper
Method decorator to return NotImplemented if the args of the wrapped method are of different types .