Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function: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,...
[ "Return all |big_phi| cuts for the given nodes.\n\n This value changes based on :const:`config.CUT_ONE_APPROXIMATION`.\n\n Args:\n nodes (tuple[int]): The node indices to partition.\n Returns:\n list[Cut]: All unidirectional partitions.\n " ]
Please provide a description of the function:def _sia(cache_key, subsystem): # pylint: disable=unused-argument log.info('Calculating big-phi data for %s...', subsystem) # Check for degenerate cases # ========================================================================= # Phi is necessaril...
[ "Return the minimal information partition of a subsystem.\n\n Args:\n subsystem (Subsystem): The candidate set of nodes.\n\n Returns:\n SystemIrreducibilityAnalysis: A nested structure containing all the\n data from the intermediate calculations. The top level contains the\n basic ...
Please provide a description of the function: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.S...
[ "The cache key of the subsystem.\n\n This includes the native hash of the subsystem and all configuration values\n which change the results of ``sia``.\n " ]
Please provide a description of the function: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." ]
Please provide a description of the function: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.n...
[ "Calculate a concept-style SystemIrreducibilityAnalysisCause or\n SystemIrreducibilityAnalysisEffect.\n " ]
Please provide a description of the function: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, ...
[ "Compute a concept-style SystemIrreducibilityAnalysis" ]
Please provide a description of the function:def compute(mechanism, subsystem, purviews, cause_purviews, effect_purviews): concept = subsystem.concept(mechanism, purviews=purviews, cause_purviews=cause_purviews, ...
[ "Compute a |Concept| for a mechanism, in this |Subsystem| with the\n provided purviews.\n " ]
Please provide a description of the function:def process_result(self, new_concept, concepts): if new_concept.phi > 0: # Replace the subsystem new_concept.subsystem = self.subsystem concepts.append(new_concept) return concepts
[ "Save all concepts with non-zero |small_phi| to the\n |CauseEffectStructure|.\n " ]
Please provide a description of the function:def process_result(self, new_sia, min_sia): if new_sia.phi == 0: self.done = True # Short-circuit 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\n result.\n " ]
Please provide a description of the function: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( mech...
[ "Compute a concept, using the appropriate system for each side of the\n cut.\n " ]
Please provide a description of the function: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 the nodes indices for nodes, where ``nodes`` is either\n already integer indices or node labels.\n " ]
Please provide a description of the function:def _null_sia(subsystem, phi=0.0): return SystemIrreducibilityAnalysis(subsystem=subsystem, cut_subsystem=subsystem, phi=phi, ces=_null_ces(subsys...
[ "Return a |SystemIrreducibilityAnalysis| with zero |big_phi| and empty\n cause-effect structures.\n\n This is the analysis result for a reducible subsystem.\n " ]
Please provide a description of the function: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." ]
Please provide a description of the function: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.\n\n If the direction is ``CAUSE``, then the purview is at |t-1| and the\n mechanism is at time |t|. If the direction is ``EFFECT``, then the\n mechanism is at time |t| and the purview is at |t+1|.\n " ]
Please provide a description of the function:def sametype(func): @functools.wraps(func) def wrapper(self, other): # pylint: disable=missing-docstring 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\n method are of different types.\n\n When wrapping a rich model comparison method this will delegate (reflect)\n the comparison to the right-hand-side object, or fallback by passing it up\n the inheritance tree.\n " ]
Please provide a description of the function:def numpy_aware_eq(a, b): if isinstance(a, np.ndarray) or isinstance(b, np.ndarray): return np.array_equal(a, b) if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and not isinstance(a, str) and not isinstance(b, str)): if len(...
[ "Return whether two objects are equal via recursion, using\n :func:`numpy.array_equal` for comparing numpy arays.\n " ]
Please provide a description of the function:def general_eq(a, b, attributes): try: for attr in attributes: _a, _b = getattr(a, attr), getattr(b, attr) if attr in ['phi', 'alpha']: if not utils.eq(_a, _b): return False elif attr in...
[ "Return whether two objects are equal up to the given attributes.\n\n If an attribute is called ``'phi'``, it is compared up to |PRECISION|.\n If an attribute is called ``'mechanism'`` or ``'purview'``, it is\n compared using set equality. All other attributes are compared with\n :func:`numpy_aware_eq`...
Please provide a description of the function:def eight_node(cm=False): tpm = np.array([ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0...
[ "Eight-node network." ]
Please provide a description of the function:def time_emd(emd_type, data): emd = { 'cause': _CAUSE_EMD, 'effect': pyphi.subsystem.effect_emd, 'hamming': pyphi.utils.hamming_emd }[emd_type] def statement(): for (d1, d2) in data: emd(d1, d2) results = ti...
[ "Time an EMD command with the given data as arguments" ]
Please provide a description of the function: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(num...
[ "\n Return the uniform distribution for a set of binary nodes, indexed by state\n (so there is one dimension per node, the size of which is the number of\n possible states for that node).\n\n Args:\n nodes (np.ndarray): A set of indices of binary nodes.\n\n Returns:\n np.ndarray: The un...
Please provide a description of the function:def marginal_zero(repertoire, node_index): index = [slice(None)] * repertoire.ndim index[node_index] = 0 return repertoire[tuple(index)].sum()
[ "Return the marginal probability that the node is OFF." ]
Please provide a description of the function:def marginal(repertoire, node_index): index = tuple(i for i in range(repertoire.ndim) if i != node_index) return repertoire.sum(index, keepdims=True)
[ "Get the marginal distribution for a node." ]
Please provide a description of the function:def independent(repertoire): marginals = [marginal(repertoire, i) for i in range(repertoire.ndim)] # TODO: is there a way to do without an explicit iteration? joint = marginals[0] for m in marginals[1:]: joint = joint * m # TODO: should we ...
[ "Check whether the repertoire is independent." ]
Please provide a description of the function:def purview(repertoire): if repertoire is None: return None return tuple(i for i, dim in enumerate(repertoire.shape) if dim == 2)
[ "The purview of the repertoire.\n\n Args:\n repertoire (np.ndarray): A repertoire\n\n Returns:\n tuple[int]: The purview that the repertoire was computed over.\n " ]
Please provide a description of the function: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). retu...
[ "Flatten a repertoire, removing empty dimensions.\n\n By default, the flattened repertoire is returned in little-endian order.\n\n Args:\n repertoire (np.ndarray or None): A repertoire.\n\n Keyword Args:\n big_endian (boolean): If ``True``, flatten the repertoire in big-endian\n or...
Please provide a description of the function:def max_entropy_distribution(node_indices, number_of_nodes): distribution = np.ones(repertoire_shape(node_indices, number_of_nodes)) return distribution / distribution.size
[ "Return the maximum entropy distribution over a set of nodes.\n\n This is different from the network's uniform distribution because nodes\n outside ``node_indices`` are fixed and treated as if they have only 1\n state.\n\n Args:\n node_indices (tuple[int]): The set of node indices over which to t...
Please provide a description of the function:def run_tpm(system, steps, blackbox): # Generate noised TPM # Noise the connections from every output element to elements in other # boxes. node_tpms = [] for node in system.nodes: node_tpm = node.tpm_on for input_node in node.inputs:...
[ "Iterate the TPM for the given number of timesteps.\n\n Returns:\n np.ndarray: tpm * (noise_tpm^(t-1))\n " ]
Please provide a description of the function: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_P...
[ "Return a list of partitions of the |N| binary nodes.\n\n Args:\n N (int): The number of nodes under consideration.\n\n Returns:\n list[list]: A list of lists, where each inner list is the set of\n micro-elements corresponding to a macro-element.\n\n Example:\n >>> _partitions_l...
Please provide a description of the function: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...
[ "Return a list of all possible coarse grains of a network.\n\n Args:\n indices (tuple[int]): The micro indices to partition.\n\n Yields:\n tuple[tuple]: A possible partition. Each element of the tuple\n is a tuple of micro-elements which correspond to macro-elements.\n " ]
Please provide a description of the function: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 el...
[ "Return all possible groupings of states for a particular coarse graining\n (partition) of a network.\n\n Args:\n partition (tuple[tuple]): A partition of micro-elements into macro\n elements.\n\n Yields:\n tuple[tuple[tuple]]: A grouping of micro-states into macro states of\n ...
Please provide a description of the function:def all_coarse_grains(indices): for partition in all_partitions(indices): for grouping in all_groupings(partition): yield CoarseGrain(partition, grouping)
[ "Generator over all possible |CoarseGrains| of these indices.\n\n Args:\n indices (tuple[int]): Node indices to coarse grain.\n\n Yields:\n CoarseGrain: The next |CoarseGrain| for ``indices``.\n " ]
Please provide a description of the function:def all_coarse_grains_for_blackbox(blackbox): for partition in all_partitions(blackbox.output_indices): for grouping in all_groupings(partition): coarse_grain = CoarseGrain(partition, grouping) try: validate.blackbox_a...
[ "Generator over all |CoarseGrains| for the given blackbox.\n\n If a box has multiple outputs, those outputs are partitioned into the same\n coarse-grain macro-element.\n " ]
Please provide a description of the function: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, ...
[ "Generator over all possible blackboxings of these indices.\n\n Args:\n indices (tuple[int]): Nodes to blackbox.\n\n Yields:\n Blackbox: The next |Blackbox| of ``indices``.\n " ]
Please provide a description of the function: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_indic...
[ "Find the maximal coarse-graining of a micro-system.\n\n Args:\n network (Network): The network in question.\n state (tuple[int]): The state of the network.\n internal_indices (tuple[int]): Nodes in the micro-system.\n\n Returns:\n tuple[int, CoarseGrain]: The phi-value of the maxi...
Please provide a description of the function:def all_macro_systems(network, state, do_blackbox=False, do_coarse_grain=False, time_scales=None): if time_scales is None: time_scales = [1] def blackboxes(system): # Returns all blackboxes to evaluate if not do_bla...
[ "Generator over all possible macro-systems for the network." ]
Please provide a description of the function:def emergence(network, state, do_blackbox=False, do_coarse_grain=True, time_scales=None): micro_phi = compute.major_complex(network, state).phi max_phi = float('-inf') max_network = None for subsystem in all_macro_systems(network, state, ...
[ "Check for the emergence of a micro-system into a macro-system.\n\n Checks all possible blackboxings and coarse-grainings of a system to find\n the spatial scale with maximum integrated information.\n\n Use the ``do_blackbox`` and ``do_coarse_grain`` args to specifiy whether to\n use blackboxing, coarse...
Please provide a description of the function:def effective_info(network): validate.is_network(network) sbs_tpm = convert.state_by_node2state_by_state(network.tpm) avg_repertoire = np.mean(sbs_tpm, 0) return np.mean([entropy(repertoire, avg_repertoire, 2.0) for repertoire in sb...
[ "Return the effective information of the given network.\n\n .. note::\n For details, see:\n\n Hoel, Erik P., Larissa Albantakis, and Giulio Tononi.\n β€œQuantifying causal emergence shows that macro can beat micro.”\n Proceedings of the\n National Academy of Sciences 110.49 (2013...
Please provide a description of the function:def node_labels(self): assert list(self.node_indices)[0] == 0 labels = list("m{}".format(i) for i in self.node_indices) return NodeLabels(labels, self.node_indices)
[ "Return the labels for macro nodes." ]
Please provide a description of the function:def _squeeze(system): assert system.node_indices == tpm_indices(system.tpm) internal_indices = tpm_indices(system.tpm) tpm = remove_singleton_dimensions(system.tpm) # The connectivity matrix is the network's connectivity matrix, wi...
[ "Squeeze out all singleton dimensions in the Subsystem.\n\n Reindexes the subsystem so that the nodes are ``0..n`` where ``n`` is\n the number of internal indices in the system.\n " ]
Please provide a description of the function:def _blackbox_partial_noise(blackbox, system): # Noise inputs from non-output elements hidden in other boxes node_tpms = [] for node in system.nodes: node_tpm = node.tpm_on for input_node in node.inputs: ...
[ "Noise connections from hidden elements to other boxes." ]
Please provide a description of the function:def _blackbox_time(time_scale, blackbox, system): blackbox = blackbox.reindex() tpm = run_tpm(system, time_scale, blackbox) # Universal connectivity, for now. n = len(system.node_indices) cm = np.ones((n, n)) return...
[ "Black box the CM and TPM over the given time_scale." ]
Please provide a description of the function:def _blackbox_space(self, blackbox, system): tpm = marginalize_out(blackbox.hidden_indices, system.tpm) assert blackbox.output_indices == tpm_indices(tpm) tpm = remove_singleton_dimensions(tpm) n = len(blackbox) cm = np.zero...
[ "Blackbox the TPM and CM in space.\n\n Conditions the TPM on the current value of the hidden nodes. The CM is\n set to universal connectivity.\n\n .. TODO: change this ^\n\n This shrinks the size of the TPM by the number of hidden indices; now\n there is only `len(output_indices)`...
Please provide a description of the function:def _coarsegrain_space(coarse_grain, is_cut, system): tpm = coarse_grain.macro_tpm( system.tpm, check_independence=(not is_cut)) node_indices = coarse_grain.macro_indices state = coarse_grain.macro_state(system.state) # ...
[ "Spatially coarse-grain the TPM and CM." ]
Please provide a description of the function:def cut_mechanisms(self): for mechanism in utils.powerset(self.node_indices, nonempty=True): micro_mechanism = self.macro2micro(mechanism) if self.cut.splits_mechanism(micro_mechanism): yield mechanism
[ "The mechanisms of this system that are currently cut.\n\n Note that although ``cut_indices`` returns micro indices, this\n returns macro mechanisms.\n\n Yields:\n tuple[int]\n " ]
Please provide a description of the function: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, ...
[ "Return a cut version of this |MacroSubsystem|.\n\n Args:\n cut (Cut): The cut to apply to this |MacroSubsystem|.\n\n Returns:\n MacroSubsystem: The cut version of this |MacroSubsystem|.\n " ]
Please provide a description of the function:def potential_purviews(self, direction, mechanism, purviews=False): all_purviews = utils.powerset(self.node_indices) return irreducible_purviews( self.cm, direction, mechanism, all_purviews)
[ "Override Subsystem implementation using Network-level indices." ]
Please provide a description of the function:def macro2micro(self, macro_indices): def from_partition(partition, macro_indices): micro_indices = itertools.chain.from_iterable( partition[i] for i in macro_indices) return tuple(sorted(micro_indices)) if se...
[ "Return all micro indices which compose the elements specified by\n ``macro_indices``.\n " ]
Please provide a description of the function:def macro2blackbox_outputs(self, macro_indices): if not self.blackbox: raise ValueError('System is not blackboxed') return tuple(sorted(set( self.macro2micro(macro_indices) ).intersection(self.blackbox.output_indices)...
[ "Given a set of macro elements, return the blackbox output elements\n which compose these elements.\n " ]
Please provide a description of the function:def micro_indices(self): return tuple(sorted(idx for part in self.partition for idx in part))
[ "Indices of micro elements represented in this coarse-graining." ]
Please provide a description of the function:def reindex(self): _map = dict(zip(self.micro_indices, reindex(self.micro_indices))) partition = tuple( tuple(_map[index] for index in group) for group in self.partition ) return CoarseGrain(partition, self.gro...
[ "Re-index this coarse graining to use squeezed indices.\n\n The output grouping is translated to use indices ``0..n``, where ``n``\n is the number of micro indices in the coarse-graining. Re-indexing does\n not effect the state grouping, which is already index-independent.\n\n Returns:\n...
Please provide a description of the function:def macro_state(self, micro_state): assert len(micro_state) == len(self.micro_indices) # TODO: only reindex if this coarse grain is not already from 0..n? # make_mapping calls this in a tight loop so it might be more efficient # to r...
[ "Translate a micro state to a macro state\n\n Args:\n micro_state (tuple[int]): The state of the micro nodes in this\n coarse-graining.\n\n Returns:\n tuple[int]: The state of the macro system, translated as specified\n by this coarse-graining.\n\n ...
Please provide a description of the function:def make_mapping(self): micro_states = utils.all_states(len(self.micro_indices)) # Find the corresponding macro-state for each micro-state. # The i-th entry in the mapping is the macro-state corresponding to the # i-th micro-state. ...
[ "Return a mapping from micro-state to the macro-states based on the\n partition and state grouping of this coarse-grain.\n\n Return:\n (nd.ndarray): A mapping from micro-states to macro-states. The\n |ith| entry in the mapping is the macro-state corresponding to the\n ...
Please provide a description of the function: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...
[ "Create a state-by-state coarse-grained macro TPM.\n\n Args:\n micro_tpm (nd.array): The state-by-state TPM of the micro-system.\n\n Returns:\n np.ndarray: The state-by-state TPM of the macro-system.\n " ]
Please provide a description of the function: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: ...
[ "Create a coarse-grained macro TPM.\n\n Args:\n micro_tpm (nd.array): The TPM of the micro-system.\n check_independence (bool): Whether to check that the macro TPM is\n conditionally independent.\n\n Raises:\n ConditionallyDependentError: If ``check_inde...
Please provide a description of the function:def hidden_indices(self): return tuple(sorted(set(self.micro_indices) - set(self.output_indices)))
[ "All elements hidden inside the blackboxes." ]
Please provide a description of the function:def outputs_of(self, partition_index): partition = self.partition[partition_index] outputs = set(partition).intersection(self.output_indices) return tuple(sorted(outputs))
[ "The outputs of the partition at ``partition_index``.\n\n Note that this returns a tuple of element indices, since coarse-\n grained blackboxes may have multiple outputs.\n " ]
Please provide a description of the function:def reindex(self): _map = dict(zip(self.micro_indices, reindex(self.micro_indices))) partition = tuple( tuple(_map[index] for index in group) for group in self.partition ) output_indices = tuple(_map[i] for i i...
[ "Squeeze the indices of this blackboxing to ``0..n``.\n\n Returns:\n Blackbox: a new, reindexed |Blackbox|.\n\n Example:\n >>> partition = ((3,), (2, 4))\n >>> output_indices = (2, 3)\n >>> blackbox = Blackbox(partition, output_indices)\n >>> blac...
Please provide a description of the function: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)
[ "Compute the macro-state of this blackbox.\n\n This is just the state of the blackbox's output indices.\n\n Args:\n micro_state (tuple[int]): The state of the micro-elements in the\n blackbox.\n\n Returns:\n tuple[int]: The state of the output indices.\n ...
Please provide a description of the function:def in_same_box(self, a, b): assert a in self.micro_indices assert b in self.micro_indices for part in self.partition: if a in part and b in part: return True return False
[ "Return ``True`` if nodes ``a`` and ``b``` are in the same box." ]
Please provide a description of the function:def hidden_from(self, a, b): return a in self.hidden_indices and not self.in_same_box(a, b)
[ "Return True if ``a`` is hidden in a different box than ``b``." ]
Please provide a description of the function: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 redu...
[ "Return all purviews which are irreducible for the mechanism.\n\n Args:\n cm (np.ndarray): An |N x N| connectivity matrix.\n direction (Direction): |CAUSE| or |EFFECT|.\n purviews (list[tuple[int]]): The purviews to check.\n mechanism (tuple[int]): The mechanism in question.\n\n Re...
Please provide a description of the function:def _build_tpm(tpm): tpm = np.array(tpm) validate.tpm(tpm) # Convert to multidimensional state-by-node form if is_state_by_state(tpm): tpm = convert.state_by_state2state_by_node(tpm) else: tpm = conve...
[ "Validate the TPM passed by the user and convert to multidimensional\n form.\n " ]
Please provide a description of the function:def _build_cm(self, cm): if cm is None: # Assume all are connected. cm = np.ones((self.size, self.size)) else: cm = np.array(cm) utils.np_immutable(cm) return (cm, utils.np_hash(cm))
[ "Convert the passed CM to the proper format, or construct the\n unitary CM if none was provided.\n " ]
Please provide a description of the function:def potential_purviews(self, direction, mechanism): all_purviews = utils.powerset(self._node_indices) return irreducible_purviews(self.cm, direction, mechanism, all_purviews)
[ "All purviews which are not clearly reducible for mechanism.\n\n Args:\n direction (Direction): |CAUSE| or |EFFECT|.\n mechanism (tuple[int]): The mechanism which all purviews are\n checked for reducibility over.\n\n Returns:\n list[tuple[int]]: All purv...
Please provide a description of the function:def to_json(self): return { 'tpm': self.tpm, 'cm': self.cm, 'size': self.size, 'node_labels': self.node_labels }
[ "Return a JSON-serializable representation." ]
Please provide a description of the function:def _loadable_models(): classes = [ pyphi.Direction, pyphi.Network, pyphi.Subsystem, pyphi.Transition, pyphi.labels.NodeLabels, pyphi.models.Cut, pyphi.models.KCut, pyphi.models.NullCut, pyphi.m...
[ "A dictionary of loadable PyPhi models.\n\n These are stored in this function (instead of module scope) to resolve\n circular import issues.\n " ]
Please provide a description of the function:def jsonify(obj): # pylint: disable=too-many-return-statements # Call the `to_json` method if available and add metadata. if hasattr(obj, 'to_json'): d = obj.to_json() _push_metadata(d, obj) return jsonify(d) # If we have a numpy ar...
[ "Return a JSON-encodable representation of an object, recursively using\n any available ``to_json`` methods, converting NumPy arrays and datatypes to\n native lists and types along the way.\n " ]
Please provide a description of the function:def dump(obj, fp, **user_kwargs): return json.dump(obj, fp, **_encoder_kwargs(user_kwargs))
[ "Serialize ``obj`` as a JSON-formatted stream and write to ``fp`` (a\n ``.write()``-supporting file-like object.\n " ]
Please provide a description of the function:def _check_version(version): if version != pyphi.__version__: raise pyphi.exceptions.JSONVersionError( 'Cannot load JSON from a different version of PyPhi. ' 'JSON version = {0}, current version = {1}.'.format( version...
[ "Check whether the JSON version matches the PyPhi version." ]
Please provide a description of the function:def _load_object(self, obj): if isinstance(obj, dict): obj = {k: self._load_object(v) for k, v in obj.items()} # Load a serialized PyPhi model if _is_model(obj): return self._load_model(obj) elif i...
[ "Recursively load a PyPhi object.\n\n PyPhi models are recursively loaded, using the model metadata to\n recreate the original object relations. Lists are cast to tuples\n because most objects in PyPhi which are serialized to lists (eg.\n mechanisms and purviews) are ultimately tuples. O...
Please provide a description of the function:def _load_model(self, dct): classname, version, _ = _pop_metadata(dct) _check_version(version) cls = self._models[classname] # Use `from_json` if available if hasattr(cls, 'from_json'): return cls.from_json(dct) ...
[ "Load a serialized PyPhi model.\n\n The object is memoized for reuse elsewhere in the object graph.\n " ]
Please provide a description of the function:def _compute_hamming_matrix(N): possible_states = np.array(list(utils.all_states((N)))) return cdist(possible_states, possible_states, 'hamming') * N
[ "Compute and store a Hamming matrix for |N| nodes.\n\n Hamming matrices have the following sizes::\n\n N MBs\n == ===\n 9 2\n 10 8\n 11 32\n 12 128\n 13 512\n\n Given these sizes and the fact that large matrices are needed infrequently,\n we store c...
Please provide a description of the function:def hamming_emd(d1, d2): N = d1.squeeze().ndim d1, d2 = flatten(d1), flatten(d2) return emd(d1, d2, _hamming_matrix(N))
[ "Return the Earth Mover's Distance between two distributions (indexed\n by state, one dimension per node) using the Hamming distance between states\n as the transportation cost function.\n\n Singleton dimensions are sqeezed out.\n " ]
Please provide a description of the function:def effect_emd(d1, d2): return sum(abs(marginal_zero(d1, i) - marginal_zero(d2, i)) for i in range(d1.ndim))
[ "Compute the EMD between two effect repertoires.\n\n Because the nodes are independent, the EMD between effect repertoires is\n equal to the sum of the EMDs between the marginal distributions of each\n node, and the EMD between marginal distribution for a node is the absolute\n difference in the probabi...
Please provide a description of the function:def kld(d1, d2): d1, d2 = flatten(d1), flatten(d2) return entropy(d1, d2, 2.0)
[ "Return the Kullback-Leibler Divergence (KLD) between two distributions.\n\n Args:\n d1 (np.ndarray): The first distribution.\n d2 (np.ndarray): The second distribution.\n\n Returns:\n float: The KLD of ``d1`` from ``d2``.\n " ]
Please provide a description of the function:def entropy_difference(d1, d2): d1, d2 = flatten(d1), flatten(d2) return abs(entropy(d1, base=2.0) - entropy(d2, base=2.0))
[ "Return the difference in entropy between two distributions." ]
Please provide a description of the function: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))
[ "Compute the PSQ2 measure.\n\n Args:\n d1 (np.ndarray): The first distribution.\n d2 (np.ndarray): The second distribution.\n " ]
Please provide a description of the function: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)))
[ "Compute the MP2Q measure.\n\n Args:\n p (np.ndarray): The unpartitioned repertoire\n q (np.ndarray): The partitioned repertoire\n " ]
Please provide a description of the function:def klm(p, q): p, q = flatten(p), flatten(q) return max(abs(p * np.nan_to_num(np.log(p / q))))
[ "Compute the KLM divergence." ]
Please provide a description of the function: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) ...
[ "Compute the EMD between two repertoires for a given direction.\n\n The full EMD computation is used for cause repertoires. A fast analytic\n solution is used for effect repertoires.\n\n Args:\n direction (Direction): |CAUSE| or |EFFECT|.\n d1 (np.ndarray): The first repertoire.\n d2 (...
Please provide a description of the function: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)
[ "Compute the distance between two repertoires for the given direction.\n\n Args:\n direction (Direction): |CAUSE| or |EFFECT|.\n r1 (np.ndarray): The first repertoire.\n r2 (np.ndarray): The second repertoire.\n\n Returns:\n float: The distance between ``d1`` and ``d2``, rounded to...
Please provide a description of the function: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[conf...
[ "Compute the distance between two repertoires of a system.\n\n Args:\n r1 (np.ndarray): The first repertoire.\n r2 (np.ndarray): The second repertoire.\n\n Returns:\n float: The distance between ``r1`` and ``r2``.\n " ]
Please provide a description of the function: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
[ "Decorator for registering a measure with PyPhi.\n\n Args:\n name (string): The name of the measure.\n\n Keyword Args:\n asymmetric (boolean): ``True`` if the measure is asymmetric.\n " ]
Please provide a description of the function:def partitions(collection): collection = list(collection) # Special cases if not collection: return if len(collection) == 1: yield [collection] return first = collection[0] for smaller in partitions(collection[1:]): ...
[ "Generate all set partitions of a collection.\n\n Example:\n >>> list(partitions(range(3))) # doctest: +NORMALIZE_WHITESPACE\n [[[0, 1, 2]],\n [[0], [1, 2]],\n [[0, 1], [2]],\n [[1], [0, 2]],\n [[0], [1], [2]]]\n " ]
Please provide a description of the function: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]), tup...
[ "Return indices for undirected bipartitions of a sequence.\n\n Args:\n N (int): The length of the sequence.\n\n Returns:\n list: A list of tuples containing the indices for each of the two\n parts.\n\n Example:\n >>> N = 3\n >>> bipartition_indices(N)\n [((), (0, 1...
Please provide a description of the function: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))]
[ "Return a list of bipartitions for a sequence.\n\n Args:\n a (Iterable): The sequence to partition.\n\n Returns:\n list[tuple[tuple]]: A list of tuples containing each of the two\n partitions.\n\n Example:\n >>> bipartition((1,2,3))\n [((), (1, 2, 3)), ((1,), (2, 3)), ((2...
Please provide a description of the function:def directed_bipartition(seq, nontrivial=False): bipartitions = [ (tuple(seq[i] for i in part0_idx), tuple(seq[j] for j in part1_idx)) for part0_idx, part1_idx in directed_bipartition_indices(len(seq)) ] if nontrivial: # The first and...
[ "Return a list of directed bipartitions for a sequence.\n\n Args:\n seq (Iterable): The sequence to partition.\n\n Returns:\n list[tuple[tuple]]: A list of tuples containing each of the two\n parts.\n\n Example:\n >>> directed_bipartition((1, 2, 3)) # doctest: +NORMALIZE_WHITES...
Please provide a description of the function:def bipartition_of_one(seq): seq = list(seq) for i, elt in enumerate(seq): yield ((elt,), tuple(seq[:i] + seq[(i + 1):]))
[ "Generate bipartitions where one part is of length 1." ]
Please provide a description of the function:def directed_bipartition_of_one(seq): bipartitions = list(bipartition_of_one(seq)) return chain(bipartitions, reverse_elements(bipartitions))
[ "Generate directed bipartitions where one part is of length 1.\n\n Args:\n seq (Iterable): The sequence to partition.\n\n Returns:\n list[tuple[tuple]]: A list of tuples containing each of the two\n partitions.\n\n Example:\n >>> partitions = directed_bipartition_of_one((1, 2, 3...
Please provide a description of the function: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) ...
[ "Return indices for directed tripartitions of a sequence.\n\n Args:\n N (int): The length of the sequence.\n\n Returns:\n list[tuple]: A list of tuples containing the indices for each\n partition.\n\n Example:\n >>> N = 1\n >>> directed_tripartition_indices(N)\n [(...
Please provide a description of the function:def directed_tripartition(seq): for a, b, c in directed_tripartition_indices(len(seq)): yield (tuple(seq[i] for i in a), tuple(seq[j] for j in b), tuple(seq[k] for k in c))
[ "Generator over all directed tripartitions of a sequence.\n\n Args:\n seq (Iterable): a sequence.\n\n Yields:\n tuple[tuple]: A tripartition of ``seq``.\n\n Example:\n >>> seq = (2, 5)\n >>> list(directed_tripartition(seq)) # doctest: +NORMALIZE_WHITESPACE\n [((2, 5), ()...
Please provide a description of the function:def k_partitions(collection, k): collection = list(collection) n = len(collection) # Special cases if n == 0 or k < 1: return [] if k == 1: return [[collection]] a = [0] * (n + 1) for j in range(1, k + 1): a[n - k + ...
[ "Generate all ``k``-partitions of a collection.\n\n Example:\n >>> list(k_partitions(range(3), 2))\n [[[0, 1], [2]], [[0], [1, 2]], [[0, 2], [1]]]\n " ]
Please provide a description of the function:def mip_partitions(mechanism, purview, node_labels=None): func = partition_types[config.PARTITION_TYPE] return func(mechanism, purview, node_labels)
[ "Return a generator over all mechanism-purview partitions, based on the\n current configuration.\n " ]
Please provide a description of the function:def mip_bipartitions(mechanism, purview, node_labels=None): r numerators = bipartition(mechanism) denominators = directed_bipartition(purview) for n, d in product(numerators, denominators): if (n[0] or d[0]) and (n[1] or d[1]): yield Bipa...
[ "Return an generator of all |small_phi| bipartitions of a mechanism over\n a purview.\n\n Excludes all bipartitions where one half is entirely empty, *e.g*::\n\n A βˆ…\n ─── βœ• ───\n B βˆ…\n\n is not valid, but ::\n\n A βˆ…\n ─── βœ• ───\n βˆ… B\n\n is....
Please provide a description of the function:def wedge_partitions(mechanism, purview, node_labels=None): numerators = bipartition(mechanism) denominators = directed_tripartition(purview) yielded = set() def valid(factoring): # pylint: disable=too-many-boolean-expressions ...
[ "Return an iterator over all wedge partitions.\n\n These are partitions which strictly split the mechanism and allow a subset\n of the purview to be split into a third partition, e.g.::\n\n A B βˆ…\n ─── βœ• ─── βœ• ───\n B C D\n\n See |PARTITION_TYPE| in |config| for more ...
Please provide a description of the function: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_part...
[ "Return all possible partitions of a mechanism and purview.\n\n Partitions can consist of any number of parts.\n\n Args:\n mechanism (tuple[int]): A mechanism.\n purview (tuple[int]): A purview.\n\n Yields:\n KPartition: A partition of this mechanism and purview into ``k`` parts.\n ...
Please provide a description of the function:def get_bootdev(self): result = self._do_web_request(self.sysurl) overridestate = result.get('Boot', {}).get( 'BootSourceOverrideEnabled', None) if overridestate == 'Disabled': return {'bootdev': 'default', 'persistent...
[ "Get current boot device override information.\n\n :raises: PyghmiException on error\n :returns: dict\n " ]
Please provide a description of the function:def set_bootdev(self, bootdev, persist=False, uefiboot=None): reqbootdev = bootdev if (bootdev not in boot_devices_write and bootdev not in boot_devices_read): raise exc.InvalidParameterValue('Unsupported device ' ...
[ "Set boot device to use on next reboot\n\n :param bootdev:\n *network -- Request network boot\n *hd -- Boot from hard drive\n *safe -- Boot from hard drive, requesting 'safe mode'\n *optical -- boot from CD/DVD/BD dri...
Please provide a description of the function:def clear_system_configuration(self): biosinfo = self._do_web_request(self._biosurl) rb = biosinfo.get('Actions', {}).get('#Bios.ResetBios', {}) rb = rb.get('target', '') if not rb: raise Exception('BIOS reset not detected...
[ "Clear the BIOS/UEFI configuration\n\n " ]
Please provide a description of the function:def naturalize_string(key): return [int(text) if text.isdigit() else text.lower() for text in re.split(numregex, key)]
[ "Analyzes string in a human way to enable natural sort\n\n :param nodename: The node name to analyze\n :returns: A structure that can be consumed by 'sorted'\n " ]