Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def key(self, direction, mechanism, purviews=False, _prefix=None):
return "subsys:{}:{}:{}:{}:{}".format(
self.subsystem_hash, _prefix, direction, mechanism, purviews) | [
"Cache key. This is the call signature of |Subsystem.find_mice()|."
] |
Please provide a description of the function: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.\n\n Only include the |MICE| which are unaffected by the subsystem cut.\n A |MICE| is affected if either the cut splits the mechanism\n or splits the connections between the purview and mechanism\n "
] |
Please provide a description of the function:def set(self, key, mice):
if (not self.subsystem.is_cut and mice.phi > 0 and
not memory_full()):
self.cache[key] = mice | [
"Set a value in the cache.\n\n Only cache if:\n - The subsystem is uncut (caches are only inherited from\n uncut subsystems so there is no reason to cache on cut\n subsystems.)\n - |small_phi| > 0. Ideally we would cache all mice, but the size\n of the cache... |
Please provide a description of the function:def key(self, direction, mechanism, purviews=False, _prefix=None):
return (_prefix, direction, mechanism, purviews) | [
"Cache key. This is the call signature of |Subsystem.find_mice()|."
] |
Please provide a description of the function:def set(self, key, value):
if config.CACHE_POTENTIAL_PURVIEWS:
self.cache[key] = value | [
"Only set if purview caching is enabled"
] |
Please provide a description of the function:def apply_boundary_conditions_to_cm(external_indices, cm):
cm = cm.copy()
cm[external_indices, :] = 0 # Zero-out row
cm[:, external_indices] = 0 # Zero-out columnt
return cm | [
"Remove connections to or from external nodes."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def relevant_connections(n, _from, to):
cm = np.zeros((n, n))
# Don't try and index with empty arrays. Older versions of NumPy
# (at least up to 1.9.3) break with empty array indices.
if not _from or not to:
return cm
cm[np.ix_(_from, to)] ... | [
"Construct a connectivity matrix.\n\n Args:\n n (int): The dimensions of the matrix\n _from (tuple[int]): Nodes with outgoing connections to ``to``\n to (tuple[int]): Nodes with incoming connections from ``_from``\n\n Returns:\n np.ndarray: An |n x n| connectivity matrix with the |... |
Please provide a description of the function: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]))
# CM helpers:
def outputs_of(nodes):
return np.where(cm[nodes, :].sum(0))[0]
de... | [
"Return whether ``cm`` can be arranged as a block connectivity matrix.\n\n If so, the corresponding mechanism/purview is trivially reducible.\n Technically, only square matrices are \"block diagonal\", but the notion of\n connectivity carries over.\n\n We test for block connectivity by trying to grow a ... |
Please provide a description of the function:def block_reducible(cm, nodes1, nodes2):
# Trivial case
if not nodes1 or not nodes2:
return True
cm = cm[np.ix_(nodes1, nodes2)]
# Validate the connectivity matrix.
if not cm.sum(0).all() or not cm.sum(1).all():
return True
if l... | [
"Return whether connections from ``nodes1`` to ``nodes2`` are reducible.\n\n Args:\n cm (np.ndarray): The network's connectivity matrix.\n nodes1 (tuple[int]): Source nodes\n nodes2 (tuple[int]): Sink nodes\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def is_full(cm, nodes1, nodes2):
if not nodes1 or not nodes2:
return True
cm = cm[np.ix_(nodes1, nodes2)]
# Do all nodes have at least one connection?
return cm.sum(0).all() and cm.sum(1).all() | [
"Test connectivity of one set of nodes to another.\n\n Args:\n cm (``np.ndarrray``): The connectivity matrix\n nodes1 (tuple[int]): The nodes whose outputs to ``nodes2`` will be\n tested.\n nodes2 (tuple[int]): The nodes whose inputs from ``nodes1`` will\n be tested.\n\... |
Please provide a description of the function:def apply_cut(self, cm):
# Invert the cut matrix, creating a matrix of preserved connections
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\n severed by this cut removed.\n\n Args:\n cm (np.ndarray): A connectivity matrix.\n "
] |
Please provide a description of the function: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``.\n\n Args:\n a (tuple[int]): A set of nodes.\n b (tuple[int]): A set of nodes.\n "
] |
Please provide a description of the function: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.\n\n Yields:\n tuple[int]: The next cut mechanism.\n "
] |
Please provide a description of the function:def cut_matrix(self, n):
return connectivity.relevant_connections(n, self.from_nodes,
self.to_nodes) | [
"Compute the cut matrix for this cut.\n\n The cut matrix is a square matrix which represents connections severed\n by the cut.\n\n Args:\n n (int): The size of the network.\n\n Example:\n >>> cut = Cut((1,), (2,))\n >>> cut.cut_matrix(3)\n array... |
Please provide a description of the function:def cut_matrix(self, n):
cm = np.zeros((n, n))
for part in self.partition:
from_, to = self.direction.order(part.mechanism, part.purview)
# All indices external to this part
external = tuple(set(self.indices) - se... | [
"The matrix of connections that are severed by this cut."
] |
Please provide a description of the function:def mechanism(self):
return tuple(sorted(
chain.from_iterable(part.mechanism for part in self))) | [
"tuple[int]: The nodes of the mechanism in the partition."
] |
Please provide a description of the function:def purview(self):
return tuple(sorted(
chain.from_iterable(part.purview for part in self))) | [
"tuple[int]: The nodes of the purview in the partition."
] |
Please provide a description of the function:def concept_distance(c1, c2):
# Calculate the sum of the cause and effect EMDs, expanding the repertoires
# to the combined purview of the two concepts, so that the EMD signatures
# are the same size.
cause_purview = tuple(set(c1.cause.purview + c2.cause... | [
"Return the distance between two concepts in concept space.\n\n Args:\n c1 (Concept): The first concept.\n c2 (Concept): The second concept.\n\n Returns:\n float: The distance between the two concepts in concept space.\n "
] |
Please provide a description of the function:def _ces_distance_simple(C1, C2):
# Make C1 refer to the bigger CES.
if len(C2) > len(C1):
C1, C2 = C2, C1
destroyed = [c1 for c1 in C1 if not any(c1.emd_eq(c2) for c2 in C2)]
return sum(c.phi * concept_distance(c, c.subsystem.null_concept)
... | [
"Return the distance between two cause-effect structures.\n\n Assumes the only difference between them is that some concepts have\n disappeared.\n "
] |
Please provide a description of the function:def _ces_distance_emd(unique_C1, unique_C2):
# Get the pairwise distances between the concepts in the unpartitioned and
# partitioned CESs.
distances = np.array([
[concept_distance(i, j) for j in unique_C2] for i in unique_C1
])
# We need dis... | [
"Return the distance between two cause-effect structures.\n\n Uses the generalized EMD.\n "
] |
Please provide a description of the function:def ces_distance(C1, C2):
if config.USE_SMALL_PHI_DIFFERENCE_FOR_CES_DISTANCE:
return round(small_phi_ces_distance(C1, C2), config.PRECISION)
concepts_only_in_C1 = [
c1 for c1 in C1 if not any(c1.emd_eq(c2) for c2 in C2)]
concepts_only_in_C2... | [
"Return the distance between two cause-effect structures.\n\n Args:\n C1 (CauseEffectStructure): The first |CauseEffectStructure|.\n C2 (CauseEffectStructure): The second |CauseEffectStructure|.\n\n Returns:\n float: The distance between the two cause-effect structures in concept\n ... |
Please provide a description of the function: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|."
] |
Please provide a description of the function: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)
... | [
"Generate |Node| objects for a subsystem.\n\n Args:\n tpm (np.ndarray): The system's TPM\n cm (np.ndarray): The corresponding CM.\n network_state (tuple): The state of the network.\n indices (tuple[int]): Indices to generate nodes for.\n\n Keyword Args:\n node_labels (|NodeL... |
Please provide a description of the function: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.\n\n This is different from broadcasting the TPM of a full system since the last\n dimension (containing the state of the node) contains only the probability\n of *this* node being on, rather than the probabilities for each node.\n "
] |
Please provide a description of the function:def condition_tpm(tpm, fixed_nodes, state):
conditioning_indices = [[slice(None)]] * len(state)
for i in fixed_nodes:
# Preserve singleton dimensions with `np.newaxis`
conditioning_indices[i] = [state[i], np.newaxis]
# Flatten the indices.
... | [
"Return a TPM conditioned on the given fixed node indices, whose states\n are fixed according to the given state-tuple.\n\n The dimensions of the new TPM that correspond to the fixed nodes are\n collapsed onto their state, making those dimensions singletons suitable for\n broadcasting. The number of dim... |
Please provide a description of the function: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\n over the full network.\n "
] |
Please provide a description of the function: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.\n\n Args:\n node_indices (list[int]): The indices of nodes to be marginalized out.\n tpm (np.ndarray): The TPM to marginalize the node out of.\n\n Returns:\n np.ndarray: A TPM with the same number of dimensions, with the nodes\n marginalized out.\... |
Please provide a description of the function: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_o... | [
"Infer the presence or absence of an edge from node A to node B.\n\n Let |S| be the set of all nodes in a network. Let |A' = S - {A}|. We call\n the state of |A'| the context |C| of |A|. There is an edge from |A| to |B|\n if there exists any context |C(A)| such that |Pr(B | C(A), A=0) != Pr(B |\n C(A), ... |
Please provide a description of the function: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 ... | [
"Infer the connectivity matrix associated with a state-by-node TPM in\n multidimensional form.\n "
] |
Please provide a description of the function: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 co... | [
"Return the number of processes to use in parallel."
] |
Please provide a description of the function:def init_progress_bar(self):
# Forked worker processes can't show progress bars.
disable = MapReduce._forked or not config.PROGRESS_BARS
# Don't materialize iterable unless we have to: huge iterables
# (e.g. of `KCuts`) eat memory.
... | [
"Initialize and return a progress bar."
] |
Please provide a description of the function: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 i... | [
"A worker process, run by ``multiprocessing.Process``."
] |
Please provide a description of the function: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()
# Used to si... | [
"Initialize all queues and start the worker processes and the log\n thread.\n "
] |
Please provide a description of the function:def initialize_tasks(self):
# Add a poison pill to shutdown each process.
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)
... | [
"Load the input queue to capacity.\n\n Overfilling causes a deadlock when `queue.put` blocks when\n full, so further tasks are enqueued as results are returned.\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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()
... | [
"Perform the computation in parallel, reading results from the output\n queue and passing them to ``process_result``.\n "
] |
Please provide a description of the function:def finish_parallel(self):
for process in self.processes:
process.join()
# Shutdown the log thread
log.debug('Joining log thread')
self.log_queue.put(POISON_PILL)
self.log_thread.join()
self.log_queue.clos... | [
"Orderly shutdown of workers."
] |
Please provide a description of the function: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.prog... | [
"Perform the computation sequentially, only holding two computed\n objects in memory at a time.\n "
] |
Please provide a description of the function:def configure_logging(conf):
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(name)s] %(levelname)s '
'%... | [
"Reconfigure PyPhi logging based on the current configuration."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def defaults(self):
return {k: v.default for k, v in self.options().items()} | [
"Return the default values of this configuration."
] |
Please provide a description of the function:def load_dict(self, dct):
for k, v in dct.items():
setattr(self, k, v) | [
"Load a dictionary of configuration values."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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 '
... | [
"Log current settings."
] |
Please provide a description of the function: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\n versa.\n\n Args:\n tpm (np.ndarray): A state-by-state TPM.\n\n Returns:\n np.ndarray: The state-by-state TPM in the other indexing format.\n\n Example:\n >>> tpm = np.arange(16).reshape([4, 4])\n >>> be2... |
Please provide a description of the function:def to_multidimensional(tpm):
# Cast to np.array.
tpm = np.array(tpm)
# Get the number of nodes.
N = tpm.shape[-1]
# Reshape. We use Fortran ordering here so that the rows use the
# little-endian convention (least-significant bits correspond to l... | [
"Reshape a state-by-node TPM to the multidimensional form.\n\n See documentation for the |Network| object for more information on TPM\n formats.\n "
] |
Please provide a description of the function:def state_by_state2state_by_node(tpm):
# Cast to np.array.
tpm = np.array(tpm)
# Get the number of states from the length of one side of the TPM.
S = tpm.shape[-1]
# Get the number of nodes from the number of states.
N = int(log2(S))
# Initia... | [
"Convert a state-by-state TPM to a state-by-node TPM.\n\n .. danger::\n Many nondeterministic state-by-state TPMs can be represented by a\n single a state-by-state TPM. However, the mapping can be made to be\n one-to-one if we assume the state-by-state TPM is conditionally\n independe... |
Please provide a description of the function:def state_by_node2state_by_state(tpm):
# Cast to np.array.
tpm = np.array(tpm)
# Convert to multidimensional form.
tpm = to_multidimensional(tpm)
# Get the number of nodes from the last dimension of the TPM.
N = tpm.shape[-1]
# Get the number... | [
"Convert a state-by-node TPM to a state-by-state TPM.\n\n .. important::\n A nondeterministic state-by-node TPM can have more than one\n representation as a state-by-state TPM. However, the mapping can be\n made to be one-to-one if we assume the TPMs to be conditionally\n independent.... |
Please provide a description of the function:def load_repertoire(name):
root = os.path.abspath(os.path.dirname(__file__))
filename = os.path.join(root, 'data', 'emd', name)
return np.load(filename) | [
"Load an array of repertoires in ./data/emd/."
] |
Please provide a description of the function: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"
] |
Please provide a description of the function:def all_network_files():
# TODO: list explicitly since some are missing?
network_types = [
'AND-circle',
'MAJ-specialized',
'MAJ-complete',
'iit-3.0-modular'
]
network_sizes = range(5, 8)
network_files = []
for n i... | [
"All network files"
] |
Please provide a description of the function: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.addHa... | [
"Profile a network.\n\n Saves PyPhi results, pstats, and logs to respective directories.\n "
] |
Please provide a description of the function: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.\n\n Args:\n tpm (np.ndarray): A state-by-node tpm.\n time_scale (int): The number of steps to run the tpm.\n\n Returns:\n np.ndarray\n "
] |
Please provide a description of the function:def run_cm(cm, time_scale):
cm = np.linalg.matrix_power(cm, time_scale)
# Round non-unitary values back to 1
cm[cm > 1] = 1
return cm | [
"Iterate a connectivity matrix the specified number of steps.\n\n Args:\n cm (np.ndarray): A connectivity matrix.\n time_scale (int): The number of steps to run.\n\n Returns:\n np.ndarray: The connectivity matrix at the new timescale.\n "
] |
Please provide a description of the function:def _reachable_subsystems(network, indices, state):
validate.is_network(network)
# Return subsystems largest to smallest to optimize parallel
# resource usage.
for subset in utils.powerset(indices, nonempty=True, reverse=True):
try:
... | [
"A generator over all subsystems in a valid state."
] |
Please provide a description of the function: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.\n\n .. note::\n Includes reducible, zero-|big_phi| complexes (which are not, strictly\n speaking, complexes at all).\n\n Args:\n network (Network): The |Network| of interest.\n state (tuple[int]): The state of the network (a bin... |
Please provide a description of the function:def complexes(network, state):
engine = FindIrreducibleComplexes(possible_complexes(network, state))
return engine.run(config.PARALLEL_COMPLEX_EVALUATION) | [
"Return all irreducible complexes of the network.\n\n Args:\n network (Network): The |Network| of interest.\n state (tuple[int]): The state of the network (a binary tuple).\n\n Yields:\n SystemIrreducibilityAnalysis: A |SIA| for each |Subsystem| of the\n |Network|, excluding those ... |
Please provide a description of the function: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_subsyst... | [
"Return the major complex of the network.\n\n Args:\n network (Network): The |Network| of interest.\n state (tuple[int]): The state of the network (a binary tuple).\n\n Returns:\n SystemIrreducibilityAnalysis: The |SIA| for the |Subsystem| with\n maximal |big_phi|.\n "
] |
Please provide a description of the function: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... | [
"Return a list of maximal non-overlapping complexes.\n\n Args:\n network (Network): The |Network| of interest.\n state (tuple[int]): The state of the network (a binary tuple).\n\n Returns:\n list[SystemIrreducibilityAnalysis]: A list of |SIA| for non-overlapping\n complexes with ma... |
Please provide a description of the function: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,... | [
"A 3-node network of logic gates.\n\n Diagram::\n\n +~~~~~~~~+\n +~~~~>| A |<~~~~+\n | | (OR) +~~~+ |\n | +~~~~~~~~+ | |\n | | |\n | v |\n +~+~~~~~~+ +~~~~~+~+\n | B |<~~~~~~+ ... |
Please provide a description of the function: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],
... | [
"Based on the basic_network, but with added selfloops and noisy edges.\n\n Nodes perform deterministic functions of their inputs, but those inputs\n may be flipped (i.e. what should be a 0 becomes a 1, and vice versa) with\n probability epsilon (eps = 0.1 here).\n\n Diagram::\n\n +~~+\... |
Please provide a description of the function: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], ... | [
"The network for the residue example.\n\n Current and previous state are all nodes OFF.\n\n Diagram::\n\n +~~~~~~~+ +~~~~~~~+\n | A | | B |\n +~~>| (AND) | | (AND) |<~~+\n | +~~~~~~~+ +~~~~~~~+ |\n | ... |
Please provide a description of the function: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 ... | [
"A version of the primary example from the IIT 3.0 paper with\n deterministic COPY gates on each connection. These copy gates essentially\n function as propagation delays on the signal between OR, AND and XOR gates\n from the original system.\n\n The current and previous states of the network are also s... |
Please provide a description of the function: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... | [
"A network of micro elements which has greater integrated information\n after coarse graining to a macro scale.\n "
] |
Please provide a description of the function: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] =... | [
"A micro-network to demonstrate blackboxing.\n\n Diagram::\n\n +----------+\n +-------------------->+ A (COPY) + <---------------+\n | +----------+ |\n | +----------+ |\n | ... |
Please provide a description of the function:def rule110_network():
tpm = np.array([[0, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
[0, 1, 1],
[1, 1, 1],
[1, 1, 1],
[0, 0, 0]]... | [
"A network of three elements which follows the logic of the Rule 110\n cellular automaton with current and previous state (0, 0, 0).\n "
] |
Please provide a description of the function:def fig16():
tpm = np.array([
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 0... | [
"The network shown in Figure 5B of the 2014 IIT 3.0 paper."
] |
Please provide a description of the function: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\n ``AND`` gate with self-loops.\n "
] |
Please provide a description of the function: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],
... | [
"The |Transition| for the prevention example from Actual Causation\n Figure 5D.\n "
] |
Please provide a description of the function:def clear_subsystem_caches(subsys):
try:
# New-style caches
subsys._repertoire_cache.clear()
subsys._mice_cache.clear()
except TypeError:
try:
# Pre cache.clear() implementation
subsys._repertoire_cache.cac... | [
"Clear subsystem caches"
] |
Please provide a description of the function: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.\n\n Args:\n n (int): The number of elements in the system.\n big_endian (bool): Whether to return the states in big-endian order\n instead of little-endian order.\n\n Yields:\n tuple[int]: The next state of an ``n``-element system, in lit... |
Please provide a description of the function:def np_hash(a):
if a is None:
return hash(None)
# Ensure that hashes are equal whatever the ordering in memory (C or
# Fortran)
a = np.ascontiguousarray(a)
# Compute the digest and return a decimal int
return int(hashlib.sha1(a.view(a.dty... | [
"Return a hash of a NumPy array."
] |
Please provide a description of the function:def combs(a, r):
# Special-case for 0-length combinations
if r == 0:
return np.asarray([])
a = np.asarray(a)
data_type = a.dtype if r == 0 else np.dtype([('', a.dtype)] * r)
b = np.fromiter(combinations(a, r), data_type)
return b.view(a.... | [
"NumPy implementation of ``itertools.combinations``.\n\n Return successive ``r``-length combinations of elements in the array ``a``.\n\n Args:\n a (np.ndarray): The array from which to get combinations.\n r (int): The length of the combinations.\n\n Returns:\n np.ndarray: An array of c... |
Please provide a description of the function:def comb_indices(n, k):
# Count the number of combinations for preallocation
count = comb(n, k, exact=True)
# Get numpy iterable from ``itertools.combinations``
indices = np.fromiter(
chain.from_iterable(combinations(range(n), k)),
int,
... | [
"``n``-dimensional version of itertools.combinations.\n\n Args:\n a (np.ndarray): The array from which to get combinations.\n k (int): The desired length of the combinations.\n\n Returns:\n np.ndarray: Indices that give the ``k``-combinations of ``n`` elements.\n\n Example:\n >>... |
Please provide a description of the function:def powerset(iterable, nonempty=False, reverse=False):
iterable = list(iterable)
if nonempty: # Don't include 0-length subsets
start = 1
else:
start = 0
seq_sizes = range(start, len(iterable) + 1)
if reverse:
seq_sizes = r... | [
"Generate the power set of an iterable.\n\n Args:\n iterable (Iterable): The iterable from which to generate the power set.\n\n Keyword Args:\n nonempty (boolean): If True, don't include the empty set.\n reverse (boolean): If True, reverse the order of the powerset.\n\n Returns:\n ... |
Please provide a description of the function:def load_data(directory, num):
root = os.path.abspath(os.path.dirname(__file__))
def get_path(i): # pylint: disable=missing-docstring
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.\n\n The files should stored in ``../data/<dir>`` and named\n ``0.npy, 1.npy, ... <num - 1>.npy``.\n\n Returns:\n list: A list of loaded data, such that ``list[i]`` contains the the\n contents of ``i.npy``.\n "
] |
Please provide a description of the function: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\n time.\n\n The result is annotated with a `time` attribute.\n "
] |
Please provide a description of the function:def _null_ria(direction, mechanism, purview, repertoire=None, phi=0.0):
# TODO Use properties here to infer mechanism and purview from
# partition yet access them with .mechanism and .partition
return RepertoireIrreducibilityAnalysis(
direction=direc... | [
"The irreducibility analysis for a reducible mechanism."
] |
Please provide a description of the function:def _relevant_connections(self, subsystem):
_from, to = self.direction.order(self.mechanism, self.purview)
return connectivity.relevant_connections(subsystem.network.size,
_from, to) | [
"Identify connections that βmatterβ to this concept.\n\n For a |MIC|, the important connections are those which connect the\n purview to the mechanism; for a |MIE| they are the connections from the\n mechanism to the purview.\n\n Returns an |N x N| matrix, where `N` is the number of node... |
Please provide a description of the function: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.\n\n The cut affects the MICE if it either splits the MICE's mechanism\n or splits the connections between the purview and mechanism.\n "
] |
Please provide a description of the function: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.\n\n .. warning::\n This only checks if the cause and effect repertoires are equal as\n arrays; mechanisms, purviews, or even the nodes that the mechanism\n and purview indices refer to, might be different.\n ... |
Please provide a description of the function: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\n an EMD calculation.\n "
] |
Please provide a description of the function:def expand_cause_repertoire(self, new_purview=None):
return self.subsystem.expand_cause_repertoire(
self.cause.repertoire, new_purview) | [
"See |Subsystem.expand_repertoire()|."
] |
Please provide a description of the function:def expand_effect_repertoire(self, new_purview=None):
return self.subsystem.expand_effect_repertoire(
self.effect.repertoire, new_purview) | [
"See |Subsystem.expand_repertoire()|."
] |
Please provide a description of the function:def directed_account(transition, direction, mechanisms=False, purviews=False,
allow_neg=False):
if mechanisms is False:
mechanisms = utils.powerset(transition.mechanism_indices(direction),
nonempty=Tru... | [
"Return the set of all |CausalLinks| of the specified direction."
] |
Please provide a description of the function:def account(transition, direction=Direction.BIDIRECTIONAL):
if direction != Direction.BIDIRECTIONAL:
return directed_account(transition, direction)
return Account(directed_account(transition, Direction.CAUSE) +
directed_account(transi... | [
"Return the set of all causal links for a |Transition|.\n\n Args:\n transition (Transition): The transition of interest.\n\n Keyword Args:\n direction (Direction): By default the account contains actual causes\n and actual effects.\n "
] |
Please provide a description of the function:def account_distance(A1, A2):
return (sum([action.alpha for action in A1]) -
sum([action.alpha for action in A2])) | [
"Return the distance between two accounts. Here that is just the\n difference in sum(alpha)\n\n Args:\n A1 (Account): The first account.\n A2 (Account): The second account\n\n Returns:\n float: The distance between the two accounts.\n "
] |
Please provide a description of the function: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)
... | [
"Find the |AcSystemIrreducibilityAnalysis| for a given cut."
] |
Please provide a description of the function: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))... | [
"A list of possible cuts to a transition."
] |
Please provide a description of the function: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 '
'... | [
"Return the minimal information partition of a transition in a specific\n direction.\n\n Args:\n transition (Transition): The candidate system.\n\n Returns:\n AcSystemIrreducibilityAnalysis: A nested structure containing all the\n data from the intermediate calculations. The top level ... |
Please provide a description of the function:def transitions(network, before_state, after_state):
# TODO: Does not return subsystems that are in an impossible transitions.
# Elements without inputs are reducibe effects,
# elements without outputs are reducible causes.
possible_causes = np.where(np... | [
"Return a generator of all **possible** transitions of a network.\n "
] |
Please provide a description of the function: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(fi... | [
"Return a tuple of all irreducible nexus of the network."
] |
Please provide a description of the function: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:
... | [
"Return the causal nexus of the network."
] |
Please provide a description of the function: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)),
... | [
"Format a true |CauseEffectStructure|."
] |
Please provide a description of the function:def events(network, previous_state, current_state, next_state, nodes,
mechanisms=False):
actual_causes = _actual_causes(network, previous_state, current_state,
nodes, mechanisms)
actual_effects = _actual_effects(netw... | [
"Find all events (mechanisms with actual causes and actual effects).",
"Filter out unidirectional occurences and return a dictionary keyed\n by the mechanism of the cause or effect.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.