docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Construct a |MICE| cache.
Uses either a Redis-backed cache or a local dict cache on the object.
Args:
subsystem (Subsystem): The subsystem that this is a cache for.
Kwargs:
parent_cache (MICECache): The cache generated by the uncut
version of ``subsystem``. Any cached |MICE| w... | def MICECache(subsystem, parent_cache=None):
if config.REDIS_CACHE:
cls = RedisMICECache
else:
cls = DictMICECache
return cls(subsystem, parent_cache=parent_cache) | 481,551 |
Caching decorator for object-level method caches.
Cache key generation is delegated to the cache.
Args:
cache_name (str): The name of the (already-instantiated) cache
on the decorated object which should be used to store results
of this method.
*key_prefix: A constant t... | 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... | 481,552 |
Construct a connectivity matrix.
Args:
n (int): The dimensions of the matrix
_from (tuple[int]): Nodes with outgoing connections to ``to``
to (tuple[int]): Nodes with incoming connections from ``_from``
Returns:
np.ndarray: An |n x n| connectivity matrix with the |i,jth| entry ... | 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)] = 1
return cm | 481,571 |
Return whether connections from ``nodes1`` to ``nodes2`` are reducible.
Args:
cm (np.ndarray): The network's connectivity matrix.
nodes1 (tuple[int]): Source nodes
nodes2 (tuple[int]): Sink nodes | 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 len(nodes1) > 1 and len(nodes2) > 1:
r... | 481,573 |
Return a modified connectivity matrix with all connections that are
severed by this cut removed.
Args:
cm (np.ndarray): A connectivity matrix. | 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 | 481,576 |
Check if this cut severs any connections from ``a`` to ``b``.
Args:
a (tuple[int]): A set of nodes.
b (tuple[int]): A set of nodes. | def cuts_connections(self, a, b):
n = max(self.indices) + 1
return self.cut_matrix(n)[np.ix_(a, b)].any() | 481,577 |
Compute the cut matrix for this cut.
The cut matrix is a square matrix which represents connections severed
by the cut.
Args:
n (int): The size of the network.
Example:
>>> cut = Cut((1,), (2,))
>>> cut.cut_matrix(3)
array([[0., 0., 0.],
... | def cut_matrix(self, n):
return connectivity.relevant_connections(n, self.from_nodes,
self.to_nodes) | 481,581 |
Return the distance between two concepts in concept space.
Args:
c1 (Concept): The first concept.
c2 (Concept): The second concept.
Returns:
float: The distance between the two concepts in concept space. | 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.purview))
effect_purview = tuple(set(c1.... | 481,592 |
Return the distance between two cause-effect structures.
Args:
C1 (CauseEffectStructure): The first |CauseEffectStructure|.
C2 (CauseEffectStructure): The second |CauseEffectStructure|.
Returns:
float: The distance between the two cause-effect structures in concept
space. | 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 = [
c2 for c2 in C2 if not any(c2.em... | 481,595 |
Generate |Node| objects for a subsystem.
Args:
tpm (np.ndarray): The system's TPM
cm (np.ndarray): The corresponding CM.
network_state (tuple): The state of the network.
indices (tuple[int]): Indices to generate nodes for.
Keyword Args:
node_labels (|NodeLabels|): Textu... | 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, no... | 481,597 |
Marginalize out nodes from a TPM.
Args:
node_indices (list[int]): The indices of nodes to be marginalized out.
tpm (np.ndarray): The TPM to marginalize the node out of.
Returns:
np.ndarray: A TPM with the same number of dimensions, with the nodes
marginalized out. | def marginalize_out(node_indices, tpm):
return tpm.sum(tuple(node_indices), keepdims=True) / (
np.array(tpm.shape)[list(node_indices)].prod()) | 481,601 |
Convert a state-by-state TPM from big-endian to little-endian or vice
versa.
Args:
tpm (np.ndarray): A state-by-state TPM.
Returns:
np.ndarray: The state-by-state TPM in the other indexing format.
Example:
>>> tpm = np.arange(16).reshape([4, 4])
>>> be2le_state_by_stat... | 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 | 481,632 |
Iterate a TPM by the specified number of time steps.
Args:
tpm (np.ndarray): A state-by-node tpm.
time_scale (int): The number of steps to run the tpm.
Returns:
np.ndarray | 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) | 481,642 |
Iterate a connectivity matrix the specified number of steps.
Args:
cm (np.ndarray): A connectivity matrix.
time_scale (int): The number of steps to run.
Returns:
np.ndarray: The connectivity matrix at the new timescale. | 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 | 481,643 |
Return a generator for all complexes of the network.
.. note::
Includes reducible, zero-|big_phi| complexes (which are not, strictly
speaking, complexes at all).
Args:
network (Network): The |Network| of interest.
state (tuple[int]): The state of the network (a binary tuple).
... | def all_complexes(network, state):
engine = FindAllComplexes(subsystems(network, state))
return engine.run(config.PARALLEL_COMPLEX_EVALUATION) | 481,645 |
Return all irreducible complexes of the network.
Args:
network (Network): The |Network| of interest.
state (tuple[int]): The state of the network (a binary tuple).
Yields:
SystemIrreducibilityAnalysis: A |SIA| for each |Subsystem| of the
|Network|, excluding those with |big_phi... | def complexes(network, state):
engine = FindIrreducibleComplexes(possible_complexes(network, state))
return engine.run(config.PARALLEL_COMPLEX_EVALUATION) | 481,646 |
Return the major complex of the network.
Args:
network (Network): The |Network| of interest.
state (tuple[int]): The state of the network (a binary tuple).
Returns:
SystemIrreducibilityAnalysis: The |SIA| for the |Subsystem| with
maximal |big_phi|. | 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... | 481,647 |
Return a list of maximal non-overlapping complexes.
Args:
network (Network): The |Network| of interest.
state (tuple[int]): The state of the network (a binary tuple).
Returns:
list[SystemIrreducibilityAnalysis]: A list of |SIA| for non-overlapping
complexes with maximal |big_ph... | 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)
r... | 481,648 |
Return all binary states for a system.
Args:
n (int): The number of elements in the system.
big_endian (bool): Whether to return the states in big-endian order
instead of little-endian order.
Yields:
tuple[int]: The next state of an ``n``-element system, in little-endian
... | 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] | 481,671 |
NumPy implementation of ``itertools.combinations``.
Return successive ``r``-length combinations of elements in the array ``a``.
Args:
a (np.ndarray): The array from which to get combinations.
r (int): The length of the combinations.
Returns:
np.ndarray: An array of combinations. | 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.dtype).reshape(-1, r) | 481,673 |
Return the set of all causal links for a |Transition|.
Args:
transition (Transition): The transition of interest.
Keyword Args:
direction (Direction): By default the account contains actual causes
and actual effects. | 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)) | 481,695 |
Return the distance between two accounts. Here that is just the
difference in sum(alpha)
Args:
A1 (Account): The first account.
A2 (Account): The second account
Returns:
float: The distance between the two accounts. | def account_distance(A1, A2):
return (sum([action.alpha for action in A1]) -
sum([action.alpha for action in A2])) | 481,696 |
Return the minimal information partition of a transition in a specific
direction.
Args:
transition (Transition): The candidate system.
Returns:
AcSystemIrreducibilityAnalysis: A nested structure containing all the
data from the intermediate calculations. The top level contains the
... | 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 _nu... | 481,699 |
Return the cause or effect repertoire function based on a direction.
Args:
direction (str): The temporal direction, specifiying the cause or
effect repertoire. | 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(pur... | 481,717 |
Return all purviews that could belong to the |MIC|/|MIE|.
Filters out trivially-reducible purviews.
Args:
direction (str): Either |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism of interest.
Keyword Args:
purviews (tuple[int]): Optional subset of... | def potential_purviews(self, direction, mechanism, purviews=False):
system = self.system[direction]
return [
purview for purview in system.potential_purviews(
direction, mechanism, purviews)
if set(purview).issubset(self.purview_indices(direction))
... | 481,729 |
Return a cut version of this |Subsystem|.
Args:
cut (Cut): The cut to apply to this |Subsystem|.
Returns:
Subsystem: The cut subsystem. | def apply_cut(self, cut):
return Subsystem(self.network, self.state, self.node_indices,
cut=cut, mice_cache=self._mice_cache) | 481,749 |
Return |Nodes| for these indices.
Args:
indices (tuple[int]): The indices in question.
Returns:
tuple[Node]: The |Node| objects corresponding to these indices.
Raises:
ValueError: If requested indices are not in the subsystem. | 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) | 481,750 |
Return the minimum information partition for a mechanism over a
purview.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The nodes in the mechanism.
purview (tuple[int]): The nodes in the purview.
Returns:
RepertoireIrre... | def find_mip(self, direction, mechanism, purview):
if not purview:
return _null_ria(direction, mechanism, purview)
# Calculate the unpartitioned repertoire to compare against the
# partitioned ones.
repertoire = self.repertoire(direction, mechanism, purview)
... | 481,764 |
Return all purviews that could belong to the |MIC|/|MIE|.
Filters out trivially-reducible purviews.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism of interest.
Keyword Args:
purviews (tuple[int]): Optional subset of ... | def potential_purviews(self, direction, mechanism, purviews=False):
if purviews is False:
purviews = self.network.potential_purviews(direction, mechanism)
# Filter out purviews that aren't in the subsystem
purviews = [purview for purview in purviews
... | 481,770 |
r"""Indent a string.
Prepends whitespace to every line in the passed string. (Lines are
separated by newline characters.)
Args:
lines (str): The string to indent.
Keyword Args:
amount (int): The number of columns to indent by.
char (str): The character to to use as the indenta... | def indent(lines, amount=2, char=' '):
r
lines = str(lines)
padding = amount * char
return padding + ('\n' + padding).join(lines.split('\n')) | 481,788 |
Format a |Bipartition|.
The returned string looks like::
0,1 ∅
─── ✕ ───
2 0,1
Args:
partition (Bipartition): The partition in question.
Returns:
str: A human-readable string representation of the partition. | 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', '') # No newline at the end of string
... | 481,796 |
Decorator for registering a function with PyPhi.
Args:
name (string): The name of the function | def register(self, name):
def register_func(func):
self.store[name] = func
return func
return register_func | 481,821 |
Compute the system irreducibility for a given cut.
Args:
uncut_subsystem (Subsystem): The subsystem without the cut applied.
cut (Cut): The cut to evaluate.
unpartitioned_ces (CauseEffectStructure): The cause-effect structure of
the uncut subsystem.
Returns:
SystemI... | 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 can only produce concepts if ... | 481,828 |
Return all |big_phi| cuts for the given nodes.
This value changes based on :const:`config.CUT_ONE_APPROXIMATION`.
Args:
nodes (tuple[int]): The node indices to partition.
Returns:
list[Cut]: All unidirectional partitions. | def sia_bipartitions(nodes, node_labels=None):
if config.CUT_ONE_APPROXIMATION:
bipartitions = directed_bipartition_of_one(nodes)
else:
# Don't consider trivial partitions where one part is empty
bipartitions = directed_bipartition(nodes, nontrivial=True)
return [Cut(bipartitio... | 481,829 |
Return the minimal information partition of a subsystem.
Args:
subsystem (Subsystem): The candidate set of nodes.
Returns:
SystemIrreducibilityAnalysis: A nested structure containing all the
data from the intermediate calculations. The top level contains the
basic irreducibilit... | def _sia(cache_key, subsystem):
# pylint: disable=unused-argument
log.info('Calculating big-phi data for %s...', subsystem)
# Check for degenerate cases
# =========================================================================
# Phi is necessarily zero if the subsystem is:
# - not str... | 481,830 |
Return the uniform distribution for a set of binary nodes, indexed by state
(so there is one dimension per node, the size of which is the number of
possible states for that node).
Args:
nodes (np.ndarray): A set of indices of binary nodes.
Returns:
np.ndarray: The uniform distribution ... | def uniform_distribution(number_of_nodes):
# The size of the state space for binary nodes is 2^(number of nodes).
number_of_states = 2 ** number_of_nodes
# Generate the maximum entropy distribution
# TODO extend to nonbinary nodes
return (np.ones(number_of_states) /
number_of_states... | 481,870 |
The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over. | def purview(repertoire):
if repertoire is None:
return None
return tuple(i for i, dim in enumerate(repertoire.shape) if dim == 2) | 481,874 |
Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the repertoire in big-endian
order.
Retu... | def flatten(repertoire, big_endian=False):
if repertoire is None:
return None
order = 'C' if big_endian else 'F'
# For efficiency, use `ravel` (which returns a view of the array) instead
# of `np.flatten` (which copies the whole array).
return repertoire.squeeze().ravel(order=order) | 481,875 |
Return a list of partitions of the |N| binary nodes.
Args:
N (int): The number of nodes under consideration.
Returns:
list[list]: A list of lists, where each inner list is the set of
micro-elements corresponding to a macro-element.
Example:
>>> _partitions_list(3)
... | def _partitions_list(N):
if N < (_NUM_PRECOMPUTED_PARTITION_LISTS):
return list(_partition_lists[N])
else:
raise ValueError(
'Partition lists not yet available for system with {} '
'nodes or more'.format(_NUM_PRECOMPUTED_PARTITION_LISTS)) | 481,878 |
Return a list of all possible coarse grains of a network.
Args:
indices (tuple[int]): The micro indices to partition.
Yields:
tuple[tuple]: A possible partition. Each element of the tuple
is a tuple of micro-elements which correspond to macro-elements. | def all_partitions(indices):
n = len(indices)
partitions = _partitions_list(n)
if n > 0:
partitions[-1] = [list(range(n))]
for partition in partitions:
yield tuple(tuple(indices[i] for i in part)
for part in partition) | 481,879 |
Return all possible groupings of states for a particular coarse graining
(partition) of a network.
Args:
partition (tuple[tuple]): A partition of micro-elements into macro
elements.
Yields:
tuple[tuple[tuple]]: A grouping of micro-states into macro states of
system.
... | def all_groupings(partition):
if not all(partition):
raise ValueError('Each part of the partition must have at least one '
'element.')
micro_groupings = [_partitions_list(len(part) + 1) if len(part) > 1
else [[[0], [1]]] for part in partition]
f... | 481,880 |
Generator over all possible |CoarseGrains| of these indices.
Args:
indices (tuple[int]): Node indices to coarse grain.
Yields:
CoarseGrain: The next |CoarseGrain| for ``indices``. | def all_coarse_grains(indices):
for partition in all_partitions(indices):
for grouping in all_groupings(partition):
yield CoarseGrain(partition, grouping) | 481,881 |
Generator over all possible blackboxings of these indices.
Args:
indices (tuple[int]): Nodes to blackbox.
Yields:
Blackbox: The next |Blackbox| of ``indices``. | def all_blackboxes(indices):
for partition in all_partitions(indices):
# TODO? don't consider the empty set here
# (pass `nonempty=True` to `powerset`)
for output_indices in utils.powerset(indices):
blackbox = Blackbox(partition, output_indices)
try: # Ensure ev... | 481,883 |
Find the maximal coarse-graining of a micro-system.
Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-system.
Returns:
tuple[int, CoarseGrain]: The phi-value of the maximal |CoarseGr... | def coarse_graining(network, state, internal_indices):
max_phi = float('-inf')
max_coarse_grain = CoarseGrain((), ())
for coarse_grain in all_coarse_grains(internal_indices):
try:
subsystem = MacroSubsystem(network, state, internal_indices,
co... | 481,884 |
Return a cut version of this |MacroSubsystem|.
Args:
cut (Cut): The cut to apply to this |MacroSubsystem|.
Returns:
MacroSubsystem: The cut version of this |MacroSubsystem|. | def apply_cut(self, cut):
# TODO: is the MICE cache reusable?
return MacroSubsystem(
self.network,
self.network_state,
self.micro_node_indices,
cut=cut,
time_scale=self.time_scale,
blackbox=self.blackbox,
coarse... | 481,900 |
Create a state-by-state coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The state-by-state TPM of the micro-system.
Returns:
np.ndarray: The state-by-state TPM of the macro-system. | def macro_tpm_sbs(self, state_by_state_micro_tpm):
validate.tpm(state_by_state_micro_tpm, check_independence=False)
mapping = self.make_mapping()
num_macro_states = 2 ** len(self.macro_indices)
macro_tpm = np.zeros((num_macro_states, num_macro_states))
micro_states = ... | 481,910 |
Create a coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The TPM of the micro-system.
check_independence (bool): Whether to check that the macro TPM is
conditionally independent.
Raises:
ConditionallyDependentError: If ``check_independence`` is... | def macro_tpm(self, micro_tpm, check_independence=True):
if not is_state_by_state(micro_tpm):
micro_tpm = convert.state_by_node2state_by_state(micro_tpm)
macro_tpm = self.macro_tpm_sbs(micro_tpm)
if check_independence:
validate.conditionally_independent(macro_t... | 481,911 |
Compute the macro-state of this blackbox.
This is just the state of the blackbox's output indices.
Args:
micro_state (tuple[int]): The state of the micro-elements in the
blackbox.
Returns:
tuple[int]: The state of the output indices. | def macro_state(self, micro_state):
assert len(micro_state) == len(self.micro_indices)
reindexed = self.reindex()
return utils.state_of(reindexed.output_indices, micro_state) | 481,915 |
Return all purviews which are irreducible for the mechanism.
Args:
cm (np.ndarray): An |N x N| connectivity matrix.
direction (Direction): |CAUSE| or |EFFECT|.
purviews (list[tuple[int]]): The purviews to check.
mechanism (tuple[int]): The mechanism in question.
Returns:
... | def irreducible_purviews(cm, direction, mechanism, purviews):
def reducible(purview):
_from, to = direction.order(mechanism, purview)
return connectivity.block_reducible(cm, _from, to)
return [purview for purview in purviews if not reducible(purview)] | 481,919 |
All purviews which are not clearly reducible for mechanism.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism which all purviews are
checked for reducibility over.
Returns:
list[tuple[int]]: All purviews which ar... | def potential_purviews(self, direction, mechanism):
all_purviews = utils.powerset(self._node_indices)
return irreducible_purviews(self.cm, direction, mechanism,
all_purviews) | 481,923 |
Return the Kullback-Leibler Divergence (KLD) between two distributions.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution.
Returns:
float: The KLD of ``d1`` from ``d2``. | def kld(d1, d2):
d1, d2 = flatten(d1), flatten(d2)
return entropy(d1, d2, 2.0) | 481,938 |
Compute the PSQ2 measure.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution. | def psq2(d1, d2):
d1, d2 = flatten(d1), flatten(d2)
def f(p):
return sum((p ** 2) * np.nan_to_num(np.log(p * len(p))))
return abs(f(d1) - f(d2)) | 481,940 |
Compute the MP2Q measure.
Args:
p (np.ndarray): The unpartitioned repertoire
q (np.ndarray): The partitioned repertoire | def mp2q(p, q):
p, q = flatten(p), flatten(q)
entropy_dist = 1 / len(p)
return sum(entropy_dist * np.nan_to_num((p ** 2) / q * np.log(p / q))) | 481,941 |
Compute the EMD between two repertoires for a given direction.
The full EMD computation is used for cause repertoires. A fast analytic
solution is used for effect repertoires.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
d1 (np.ndarray): The first repertoire.
d2 (np.ndarray): ... | def directional_emd(direction, d1, d2):
if direction == Direction.CAUSE:
func = hamming_emd
elif direction == Direction.EFFECT:
func = effect_emd
else:
# TODO: test that ValueError is raised
validate.direction(direction)
return round(func(d1, d2), config.PRECISION) | 481,943 |
Compute the distance between two repertoires for the given direction.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``d1`` and ``d2``, rounded to |PRECISION|. | def repertoire_distance(direction, r1, r2):
if config.MEASURE == 'EMD':
dist = directional_emd(direction, r1, r2)
else:
dist = measures[config.MEASURE](r1, r2)
return round(dist, config.PRECISION) | 481,944 |
Compute the distance between two repertoires of a system.
Args:
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``r1`` and ``r2``. | def system_repertoire_distance(r1, r2):
if config.MEASURE in measures.asymmetric():
raise ValueError(
'{} is asymmetric and cannot be used as a system-level '
'irreducibility measure.'.format(config.MEASURE))
return measures[config.MEASURE](r1, r2) | 481,945 |
Decorator for registering a measure with PyPhi.
Args:
name (string): The name of the measure.
Keyword Args:
asymmetric (boolean): ``True`` if the measure is asymmetric. | def register(self, name, asymmetric=False):
def register_func(func):
if asymmetric:
self._asymmetric.append(name)
self.store[name] = func
return func
return register_func | 481,946 |
Return indices for undirected bipartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list: A list of tuples containing the indices for each of the two
parts.
Example:
>>> N = 3
>>> bipartition_indices(N)
[((), (0, 1, 2)), ((0,), (1,... | def bipartition_indices(N):
result = []
if N <= 0:
return result
for i in range(2**(N - 1)):
part = [[], []]
for n in range(N):
bit = (i >> n) & 1
part[bit].append(n)
result.append((tuple(part[1]), tuple(part[0])))
return result | 481,948 |
Return a list of bipartitions for a sequence.
Args:
a (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> bipartition((1,2,3))
[((), (1, 2, 3)), ((1,), (2, 3)), ((2,), (1, 3)), ((1... | def bipartition(seq):
return [(tuple(seq[i] for i in part0_idx),
tuple(seq[j] for j in part1_idx))
for part0_idx, part1_idx in bipartition_indices(len(seq))] | 481,949 |
Return indices for directed tripartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list[tuple]: A list of tuples containing the indices for each
partition.
Example:
>>> N = 1
>>> directed_tripartition_indices(N)
[((0,), (), ()), ((... | def directed_tripartition_indices(N):
result = []
if N <= 0:
return result
base = [0, 1, 2]
for key in product(base, repeat=N):
part = [[], [], []]
for i, location in enumerate(key):
part[location].append(i)
result.append(tuple(tuple(p) for p in part))
... | 481,953 |
Return all possible partitions of a mechanism and purview.
Partitions can consist of any number of parts.
Args:
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Yields:
KPartition: A partition of this mechanism and purview into ``k`` parts. | def all_partitions(mechanism, purview, node_labels=None):
for mechanism_partition in partitions(mechanism):
mechanism_partition.append([])
n_mechanism_parts = len(mechanism_partition)
max_purview_partition = min(len(purview), n_mechanism_parts)
for n_purview_parts in range(1, ma... | 481,961 |
Return only those data rows that should be printed, based on slicing and sorting.
Arguments:
options - dictionary of option settings. | def _get_rows(self, options):
if options["oldsortslice"]:
rows = copy.deepcopy(self._rows[options["start"]:options["end"]])
else:
rows = copy.deepcopy(self._rows)
# Sort
if options["sortby"]:
sortindex = self._field_names.index(options["sort... | 482,676 |
Search tweets by keyword.
Args:
q: keyword
Returns:
list: tweet list | def search(self, q):
results = self._api.search(q=q)
return results | 482,772 |
Search tweets by user.
Args:
screen_name: screen name
count: the number of tweets
Returns:
list: tweet list | def search_by_user(self, screen_name, count=100):
results = self._api.user_timeline(screen_name=screen_name, count=count)
return results | 482,773 |
This function returns the ADFS authorization URL.
Args:
request(django.http.request.HttpRequest): A django Request object
disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt.
Returns:
str: The redirect URI | def build_authorization_endpoint(self, request, disable_sso=None):
self.load_config()
redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None)
if not redirect_to:
redirect_to = django_settings.LOGIN_REDIRECT_URL
redirect_to = base64.urlsafe_b64encode(redirect_to.enco... | 483,114 |
Create the user if it doesn't exist yet
Args:
claims (dict): claims from the access token
Returns:
django.contrib.auth.models.User: A Django user | def create_user(self, claims):
# Create the user
username_claim = settings.USERNAME_CLAIM
usermodel = get_user_model()
user, created = usermodel.objects.get_or_create(**{
usermodel.USERNAME_FIELD: claims[username_claim]
})
if created or not user.passw... | 483,120 |
Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token | def update_user_attributes(self, user, claims):
required_fields = [field.name for field in user._meta.fields if field.blank is False]
for field, claim in settings.CLAIM_MAPPING.items():
if hasattr(user, field):
if claim in claims:
setattr(user, ... | 483,121 |
Updates user group memberships based on the GROUPS_CLAIM setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token | def update_user_groups(self, user, claims):
if settings.GROUPS_CLAIM is not None:
# Update the user's group memberships
django_groups = [group.name for group in user.groups.all()]
if settings.GROUPS_CLAIM in claims:
claim_groups = claims[settings.GRO... | 483,122 |
Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token | def update_user_flags(self, user, claims):
if settings.GROUPS_CLAIM is not None:
if settings.GROUPS_CLAIM in claims:
access_token_groups = claims[settings.GROUPS_CLAIM]
if not isinstance(access_token_groups, list):
access_token_groups = [a... | 483,123 |
Handles the redirect from ADFS to our site.
We try to process the passed authorization code and login the user.
Args:
request (django.http.request.HttpRequest): A Django Request object | def get(self, request):
code = request.GET.get("code")
if not code:
# Return an error message
return render(request, 'django_auth_adfs/login_failed.html', {
'error_message': "No authorization code was provided.",
}, status=400)
redir... | 483,126 |
Create a System made of a series of random molecules.
Parameters:
total:
molecules:
proportions: | def random_box(molecules, total=None, proportions=None, size=[1.,1.,1.], maxtries=100):
# Setup proportions to be right
if proportions is None:
proportions = np.ones(len(molecules)) / len(molecules)
else:
proportions = np.array(proportions)
size = np.array(size)
t... | 483,585 |
Create a rotation matrix corresponding to the rotation around a general
axis by a specified angle.
R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d)
Parameters:
angle : float a
direction : array d | def rotation_matrix(angle, direction):
d = numpy.array(direction, dtype=numpy.float64)
d /= numpy.linalg.norm(d)
eye = numpy.eye(3, dtype=numpy.float64)
ddt = numpy.outer(d, d)
skew = numpy.array([[ 0, d[2], -d[1]],
[-d[2], 0, d[0]],
... | 483,685 |
Given the parameters for a frustum returns a 4x4 perspective
projection matrix
Parameters:
float scale:
float znear,zfar: near/far plane z, float
Return: a 4x4 perspective matrix | def simple_clip_matrix(scale, znear, zfar, aspectratio=1.0):
m = numpy.zeros((4,4))
m[0,0] = scale/aspectratio
m[1,1] = scale
m[2,2] = (zfar + znear) / (znear - zfar)
m[2,3] = 2*zfar*znear / (znear - zfar)
m[3,2] = -1
return m | 483,689 |
Generates a url-safe base64 encoded encypted message together with current timestamp (to the second).
Throws in some random number of characters to prenvent ecryption chill exploit
Args:
message_list: the message to be encrypted
Returns: | def get_otp(self, message_list):
if isinstance(message_list, six.string_types):
message_list = [message_list, ]
for x in message_list:
if self.separator in x:
raise ValueError('Messages cannot contain separator')
message_list = self.separator.join... | 485,705 |
Will decrypt the url safe base64 encoded crypted str or bytes array.
Args:
cipher_text: the encrypted text
max_timedelta: maximum timedelta in seconds
Returns:
the original message list | def validate(self, cipher_text, max_timedelta=None):
if isinstance(cipher_text, six.string_types):
cipher_text.encode()
cipher_text = base64.urlsafe_b64decode(cipher_text)
decrypted = self.encryption_suite.decrypt(cipher_text).decode().split(self.separator)
message_l... | 485,706 |
Compute two dataframes with value for start and end
Args:
totals(dataframe):
Returns: Dataframe, Dataframe | def _compute_start_end(df, start, end):
result = {}
time_dict = {'start': start, 'end': end}
totals = df.groupby('date').agg({'value': sum}).reset_index()
for time_name, time in time_dict.items():
if not totals[totals['date'] == time['id']].empty:
value = totals.loc[
... | 486,144 |
Compute diff value between start and end
Args:
df(dataframe):
Returns: Dataframe | def _compute_value_diff(df, start, end, groups):
start_values = df[df['date'] == start['id']].copy()
end_values = df[df['date'] == end['id']].copy()
merge_on = []
for key, group in groups.items():
merge_on = merge_on + [key, f'{key}_label', f'{key}_order']
df = start_values.merge(end_... | 486,145 |
Compute inside Group
Args:
df(dataframe):
Returns: Dataframe | def _compute_inside_group(df):
inside_group = df.copy()
inside_group['type'] = 'child'
inside_group['variation'] = inside_group['value'] / inside_group[
'value_start']
inside_group.drop(['upperGroup_label', 'insideGroup', 'value_start'],
axis=1, inplace=True)
insid... | 486,146 |
Compute upperGroup
Args:
df (Dataframe):
Returns: Dataframe | def _compute_upper_group(df):
upper_group = df.groupby(['groups']).agg({
'value': sum,
'value_start': sum,
'upperGroup_label': 'first',
'upperGroup_order': 'first'
}).reset_index()
upper_group['type'] = 'parent'
upper_group['variation'] = upper_group['value'] / upper... | 486,147 |
Delete a list of paths that are files or directories.
If a file/directory does not exist, skip it.
Arguments:
----------
paths : list<str>, names of files/directories to remove. | def delete_paths(paths):
for path in paths:
if exists(path):
if isfile(path):
remove(path)
else:
rmtree(path) | 486,346 |
Tries to recover the label inside a string
of the form '(3 hello)' where 3 is the label,
and hello is the string. Label is not assigned
if the string does not follow the expected
format.
Arguments:
----------
node : LabeledTree, current node that should
possibly receive a la... | def attribute_text_label(node, current_word):
node.text = normalize_string(current_word)
node.text = node.text.strip(" ")
node.udepth = 1
if len(node.text) > 0 and node.text[0].isdigit():
split_sent = node.text.split(" ", 1)
label = split_sent[0]
if len(split_sent) > 1:
... | 486,353 |
Parse and convert a string representation
of an example into a LabeledTree datastructure.
Arguments:
----------
line : str, string version of the tree.
Returns:
--------
LabeledTree : parsed tree. | def create_tree_from_string(line):
depth = 0
current_word = ""
root = None
current_node = root
for char in line:
if char == '(':
if current_node is not None and len(current_word) > 0:
attribute_text_label(current_node, current_word)
... | 486,354 |
Import a text file of treebank trees.
Arguments:
----------
path : str, filename for tree corpus.
Returns:
--------
list<LabeledTree> : loaded examples. | def import_tree_corpus(path):
tree_list = LabeledTreeCorpus()
with codecs.open(path, "r", "UTF-8") as f:
for line in f:
tree_list.append(create_tree_from_string(line))
return tree_list | 486,355 |
Save the corpus to a text file in the
original format.
Arguments:
----------
path : str, where to save the corpus.
mode : str, how to open the file. | def to_file(self, path, mode="w"):
with open(path, mode=mode) as f:
for tree in self:
for label, line in tree.to_labeled_lines():
f.write(line + "\n") | 486,358 |
Returns the profile with the received ID as a dict
If a local copy of the profile exists, it'll be returned. If not, it'll
be downloaded from the web. The results are cached, so any subsequent
calls won't hit the filesystem or the web.
Args:
profile_id (str): The ID of the ... | def get(self, profile_id):
if profile_id not in self._profiles:
try:
self._profiles[profile_id] = self._get_profile(profile_id)
except (ValueError,
IOError) as e:
six.raise_from(RegistryError(e), e)
return self._profile... | 486,833 |
Push Data Package to storage.
All parameters should be used as keyword arguments.
Args:
descriptor (str): path to descriptor
backend (str): backend name like `sql` or `bigquery`
backend_options (dict): backend options mentioned in backend docs | def push_datapackage(descriptor, backend, **backend_options):
# Deprecated
warnings.warn(
'Functions "push/pull_datapackage" are deprecated. '
'Please use "Package" class',
UserWarning)
# Init maps
tables = []
schemas = []
datamap = {}
mapping = {}
# Init ... | 486,887 |
Pull Data Package from storage.
All parameters should be used as keyword arguments.
Args:
descriptor (str): path where to store descriptor
name (str): name of the pulled datapackage
backend (str): backend name like `sql` or `bigquery`
backend_options (dict): backend options men... | def pull_datapackage(descriptor, name, backend, **backend_options):
# Deprecated
warnings.warn(
'Functions "push/pull_datapackage" are deprecated. '
'Please use "Package" class',
UserWarning)
# Save datapackage name
datapackage_name = name
# Get storage
plugin = i... | 486,888 |
Convert resource's path and name to storage's table name.
Args:
path (str): resource path
name (str): resource name
Returns:
str: table name | def _convert_path(path, name):
table = os.path.splitext(path)[0]
table = table.replace(os.path.sep, '__')
if name is not None:
table = '___'.join([table, name])
table = re.sub('[^0-9a-zA-Z_]+', '_', table)
table = table.lower()
return table | 486,889 |
Restore resource's path and name from storage's table.
Args:
table (str): table name
Returns:
(str, str): resource path and name | def _restore_path(table):
name = None
splited = table.split('___')
path = splited[0]
if len(splited) == 2:
name = splited[1]
path = path.replace('__', os.path.sep)
path += '.csv'
return path, name | 486,890 |
Convert schemas to be compatible with storage schemas.
Foreign keys related operations.
Args:
mapping (dict): mapping between resource name and table name
schemas (list): schemas
Raises:
ValueError: if there is no resource
for some foreign key in given mapping
Ret... | def _convert_schemas(mapping, schemas):
schemas = deepcopy(schemas)
for schema in schemas:
for fk in schema.get('foreignKeys', []):
resource = fk['reference']['resource']
if resource != 'self':
if resource not in mapping:
message = 'Not re... | 486,891 |
Restore schemas from being compatible with storage schemas.
Foreign keys related operations.
Args:
list: resources from storage
Returns:
list: restored resources | def _restore_resources(resources):
resources = deepcopy(resources)
for resource in resources:
schema = resource['schema']
for fk in schema.get('foreignKeys', []):
_, name = _restore_path(fk['reference']['resource'])
fk['reference']['resource'] = name
return resou... | 486,892 |
Get parsed response list from string output
Args:
raw_output (unicode): gdb output to parse
stream (str): either stdout or stderr | def _get_responses_list(self, raw_output, stream):
responses = []
raw_output, self._incomplete_output[stream] = _buffer_incomplete_responses(
raw_output, self._incomplete_output.get(stream)
)
if not raw_output:
return responses
response_list = ... | 487,328 |
Parse gdb mi text and turn it into a dictionary.
See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records
for details on types of gdb mi output.
Args:
gdb_mi_text (str): String output from gdb
Returns:
dict with the following keys:
... | def parse_response(gdb_mi_text):
stream = StringStream(gdb_mi_text, debug=_DEBUG)
if _GDB_MI_NOTIFY_RE.match(gdb_mi_text):
token, message, payload = _get_notify_msg_and_payload(gdb_mi_text, stream)
return {
"type": "notify",
"message": message,
"payload"... | 487,337 |
Formata CEP, removendo qualquer caractere não numérico.
Arguments:
cep {str} -- CEP a ser formatado.
Raises:
ValueError -- Quando a string esta vazia ou não contem numeros.
Returns:
str -- string contendo o CEP formatado. | def formatar_cep(cep):
if not isinstance(cep, str) or not cep:
raise ValueError('CEP deve ser uma string não vazia '
'contendo somente numeros')
return CARACTERES_NUMERICOS.sub('', cep) | 487,943 |
Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block.
Args:
key (str): The key to identify the block.
shape (list of int): The shape of the numpy array to allocate.
dtype (type): The numpy data type (e.g. np.float32).
... | def malloc(self, key, shape, dtype):
if key not in self._memory or self._memory[key].shape != shape or self._memory[key].dtype != dtype:
self._memory[key] = Shmem(key, shape, dtype, self._uuid)
return self._memory[key].np_array | 487,947 |
Prints the information of a package.
Args:
pkg_name (str): The name of the desired package to get information | def package_info(pkg_name):
indent = " "
for config, _ in _iter_packages():
if pkg_name == config["name"]:
print("Package:", pkg_name)
print(indent, "Platform:", config["platform"])
print(indent, "Version:", config["version"])
print(indent, "Path:", ... | 487,948 |
Gets and prints the information of a world.
Args:
world_name (str): the name of the world to retrieve information for
world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None.
initial_indent (str optional): This indent w... | def world_info(world_name, world_config=None, initial_indent="", next_indent=" "):
if world_config is None:
for config, _ in _iter_packages():
for world in config["maps"]:
if world["name"] == world_name:
world_config = world
if world_config is None:... | 487,949 |
Installs a holodeck package.
Args:
package_name (str): The name of the package to install | def install(package_name):
holodeck_path = util.get_holodeck_path()
binary_website = "https://s3.amazonaws.com/holodeckworlds/"
if package_name not in packages:
raise HolodeckException("Unknown package name " + package_name)
package_url = packages[package_name]
print("Installing " + p... | 487,950 |
Removes a holodeck package.
Args:
package_name (str): the name of the package to remove | def remove(package_name):
if package_name not in packages:
raise HolodeckException("Unknown package name " + package_name)
for config, path in _iter_packages():
if config["name"] == package_name:
shutil.rmtree(path) | 487,951 |
Add given number parameters to the internal list.
Args:
number (list of int or list of float): A number or list of numbers to add to the parameters. | def add_number_parameters(self, number):
if isinstance(number, list):
for x in number:
self.add_number_parameters(x)
return
self._parameters.append("{ \"value\": " + str(number) + " }") | 487,965 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.