id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
15,900
wmayner/pyphi
pyphi/actual.py
nice_true_ces
def nice_true_ces(tc): """Format a true |CauseEffectStructure|.""" cause_list = [] next_list = [] cause = '<--' effect = '-->' for event in tc: if event.direction == Direction.CAUSE: cause_list.append(["{0:.4f}".format(round(event.alpha, 4)), event.mechanism, cause, event.purview]) elif event.direction == Direction.EFFECT: next_list.append(["{0:.4f}".format(round(event.alpha, 4)), event.mechanism, effect, event.purview]) else: validate.direction(event.direction) true_list = [(cause_list[event], next_list[event]) for event in range(len(cause_list))] return true_list
python
def nice_true_ces(tc): """Format a true |CauseEffectStructure|.""" cause_list = [] next_list = [] cause = '<--' effect = '-->' for event in tc: if event.direction == Direction.CAUSE: cause_list.append(["{0:.4f}".format(round(event.alpha, 4)), event.mechanism, cause, event.purview]) elif event.direction == Direction.EFFECT: next_list.append(["{0:.4f}".format(round(event.alpha, 4)), event.mechanism, effect, event.purview]) else: validate.direction(event.direction) true_list = [(cause_list[event], next_list[event]) for event in range(len(cause_list))] return true_list
[ "def", "nice_true_ces", "(", "tc", ")", ":", "cause_list", "=", "[", "]", "next_list", "=", "[", "]", "cause", "=", "'<--'", "effect", "=", "'-->'", "for", "event", "in", "tc", ":", "if", "event", ".", "direction", "==", "Direction", ".", "CAUSE", ":", "cause_list", ".", "append", "(", "[", "\"{0:.4f}\"", ".", "format", "(", "round", "(", "event", ".", "alpha", ",", "4", ")", ")", ",", "event", ".", "mechanism", ",", "cause", ",", "event", ".", "purview", "]", ")", "elif", "event", ".", "direction", "==", "Direction", ".", "EFFECT", ":", "next_list", ".", "append", "(", "[", "\"{0:.4f}\"", ".", "format", "(", "round", "(", "event", ".", "alpha", ",", "4", ")", ")", ",", "event", ".", "mechanism", ",", "effect", ",", "event", ".", "purview", "]", ")", "else", ":", "validate", ".", "direction", "(", "event", ".", "direction", ")", "true_list", "=", "[", "(", "cause_list", "[", "event", "]", ",", "next_list", "[", "event", "]", ")", "for", "event", "in", "range", "(", "len", "(", "cause_list", ")", ")", "]", "return", "true_list" ]
Format a true |CauseEffectStructure|.
[ "Format", "a", "true", "|CauseEffectStructure|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L660-L678
15,901
wmayner/pyphi
pyphi/actual.py
true_ces
def true_ces(subsystem, previous_state, next_state): """Set of all sets of elements that have true causes and true effects. .. note:: Since the true |CauseEffectStructure| is always about the full system, the background conditions don't matter and the subsystem should be conditioned on the current state. """ network = subsystem.network nodes = subsystem.node_indices state = subsystem.state _events = events(network, previous_state, state, next_state, nodes) if not _events: log.info("Finished calculating, no echo events.") return None result = tuple([event.actual_cause for event in _events] + [event.actual_effect for event in _events]) log.info("Finished calculating true events.") log.debug("RESULT: \n%s", result) return result
python
def true_ces(subsystem, previous_state, next_state): """Set of all sets of elements that have true causes and true effects. .. note:: Since the true |CauseEffectStructure| is always about the full system, the background conditions don't matter and the subsystem should be conditioned on the current state. """ network = subsystem.network nodes = subsystem.node_indices state = subsystem.state _events = events(network, previous_state, state, next_state, nodes) if not _events: log.info("Finished calculating, no echo events.") return None result = tuple([event.actual_cause for event in _events] + [event.actual_effect for event in _events]) log.info("Finished calculating true events.") log.debug("RESULT: \n%s", result) return result
[ "def", "true_ces", "(", "subsystem", ",", "previous_state", ",", "next_state", ")", ":", "network", "=", "subsystem", ".", "network", "nodes", "=", "subsystem", ".", "node_indices", "state", "=", "subsystem", ".", "state", "_events", "=", "events", "(", "network", ",", "previous_state", ",", "state", ",", "next_state", ",", "nodes", ")", "if", "not", "_events", ":", "log", ".", "info", "(", "\"Finished calculating, no echo events.\"", ")", "return", "None", "result", "=", "tuple", "(", "[", "event", ".", "actual_cause", "for", "event", "in", "_events", "]", "+", "[", "event", ".", "actual_effect", "for", "event", "in", "_events", "]", ")", "log", ".", "info", "(", "\"Finished calculating true events.\"", ")", "log", ".", "debug", "(", "\"RESULT: \\n%s\"", ",", "result", ")", "return", "result" ]
Set of all sets of elements that have true causes and true effects. .. note:: Since the true |CauseEffectStructure| is always about the full system, the background conditions don't matter and the subsystem should be conditioned on the current state.
[ "Set", "of", "all", "sets", "of", "elements", "that", "have", "true", "causes", "and", "true", "effects", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L728-L751
15,902
wmayner/pyphi
pyphi/actual.py
true_events
def true_events(network, previous_state, current_state, next_state, indices=None, major_complex=None): """Return all mechanisms that have true causes and true effects within the complex. Args: network (Network): The network to analyze. previous_state (tuple[int]): The state of the network at ``t - 1``. current_state (tuple[int]): The state of the network at ``t``. next_state (tuple[int]): The state of the network at ``t + 1``. Keyword Args: indices (tuple[int]): The indices of the major complex. major_complex (AcSystemIrreducibilityAnalysis): The major complex. If ``major_complex`` is given then ``indices`` is ignored. Returns: tuple[Event]: List of true events in the major complex. """ # TODO: validate triplet of states if major_complex: nodes = major_complex.subsystem.node_indices elif indices: nodes = indices else: major_complex = compute.major_complex(network, current_state) nodes = major_complex.subsystem.node_indices return events(network, previous_state, current_state, next_state, nodes)
python
def true_events(network, previous_state, current_state, next_state, indices=None, major_complex=None): """Return all mechanisms that have true causes and true effects within the complex. Args: network (Network): The network to analyze. previous_state (tuple[int]): The state of the network at ``t - 1``. current_state (tuple[int]): The state of the network at ``t``. next_state (tuple[int]): The state of the network at ``t + 1``. Keyword Args: indices (tuple[int]): The indices of the major complex. major_complex (AcSystemIrreducibilityAnalysis): The major complex. If ``major_complex`` is given then ``indices`` is ignored. Returns: tuple[Event]: List of true events in the major complex. """ # TODO: validate triplet of states if major_complex: nodes = major_complex.subsystem.node_indices elif indices: nodes = indices else: major_complex = compute.major_complex(network, current_state) nodes = major_complex.subsystem.node_indices return events(network, previous_state, current_state, next_state, nodes)
[ "def", "true_events", "(", "network", ",", "previous_state", ",", "current_state", ",", "next_state", ",", "indices", "=", "None", ",", "major_complex", "=", "None", ")", ":", "# TODO: validate triplet of states", "if", "major_complex", ":", "nodes", "=", "major_complex", ".", "subsystem", ".", "node_indices", "elif", "indices", ":", "nodes", "=", "indices", "else", ":", "major_complex", "=", "compute", ".", "major_complex", "(", "network", ",", "current_state", ")", "nodes", "=", "major_complex", ".", "subsystem", ".", "node_indices", "return", "events", "(", "network", ",", "previous_state", ",", "current_state", ",", "next_state", ",", "nodes", ")" ]
Return all mechanisms that have true causes and true effects within the complex. Args: network (Network): The network to analyze. previous_state (tuple[int]): The state of the network at ``t - 1``. current_state (tuple[int]): The state of the network at ``t``. next_state (tuple[int]): The state of the network at ``t + 1``. Keyword Args: indices (tuple[int]): The indices of the major complex. major_complex (AcSystemIrreducibilityAnalysis): The major complex. If ``major_complex`` is given then ``indices`` is ignored. Returns: tuple[Event]: List of true events in the major complex.
[ "Return", "all", "mechanisms", "that", "have", "true", "causes", "and", "true", "effects", "within", "the", "complex", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L754-L783
15,903
wmayner/pyphi
pyphi/actual.py
extrinsic_events
def extrinsic_events(network, previous_state, current_state, next_state, indices=None, major_complex=None): """Set of all mechanisms that are in the major complex but which have true causes and effects within the entire network. Args: network (Network): The network to analyze. previous_state (tuple[int]): The state of the network at ``t - 1``. current_state (tuple[int]): The state of the network at ``t``. next_state (tuple[int]): The state of the network at ``t + 1``. Keyword Args: indices (tuple[int]): The indices of the major complex. major_complex (AcSystemIrreducibilityAnalysis): The major complex. If ``major_complex`` is given then ``indices`` is ignored. Returns: tuple(actions): List of extrinsic events in the major complex. """ if major_complex: mc_nodes = major_complex.subsystem.node_indices elif indices: mc_nodes = indices else: major_complex = compute.major_complex(network, current_state) mc_nodes = major_complex.subsystem.node_indices mechanisms = list(utils.powerset(mc_nodes, nonempty=True)) all_nodes = network.node_indices return events(network, previous_state, current_state, next_state, all_nodes, mechanisms=mechanisms)
python
def extrinsic_events(network, previous_state, current_state, next_state, indices=None, major_complex=None): """Set of all mechanisms that are in the major complex but which have true causes and effects within the entire network. Args: network (Network): The network to analyze. previous_state (tuple[int]): The state of the network at ``t - 1``. current_state (tuple[int]): The state of the network at ``t``. next_state (tuple[int]): The state of the network at ``t + 1``. Keyword Args: indices (tuple[int]): The indices of the major complex. major_complex (AcSystemIrreducibilityAnalysis): The major complex. If ``major_complex`` is given then ``indices`` is ignored. Returns: tuple(actions): List of extrinsic events in the major complex. """ if major_complex: mc_nodes = major_complex.subsystem.node_indices elif indices: mc_nodes = indices else: major_complex = compute.major_complex(network, current_state) mc_nodes = major_complex.subsystem.node_indices mechanisms = list(utils.powerset(mc_nodes, nonempty=True)) all_nodes = network.node_indices return events(network, previous_state, current_state, next_state, all_nodes, mechanisms=mechanisms)
[ "def", "extrinsic_events", "(", "network", ",", "previous_state", ",", "current_state", ",", "next_state", ",", "indices", "=", "None", ",", "major_complex", "=", "None", ")", ":", "if", "major_complex", ":", "mc_nodes", "=", "major_complex", ".", "subsystem", ".", "node_indices", "elif", "indices", ":", "mc_nodes", "=", "indices", "else", ":", "major_complex", "=", "compute", ".", "major_complex", "(", "network", ",", "current_state", ")", "mc_nodes", "=", "major_complex", ".", "subsystem", ".", "node_indices", "mechanisms", "=", "list", "(", "utils", ".", "powerset", "(", "mc_nodes", ",", "nonempty", "=", "True", ")", ")", "all_nodes", "=", "network", ".", "node_indices", "return", "events", "(", "network", ",", "previous_state", ",", "current_state", ",", "next_state", ",", "all_nodes", ",", "mechanisms", "=", "mechanisms", ")" ]
Set of all mechanisms that are in the major complex but which have true causes and effects within the entire network. Args: network (Network): The network to analyze. previous_state (tuple[int]): The state of the network at ``t - 1``. current_state (tuple[int]): The state of the network at ``t``. next_state (tuple[int]): The state of the network at ``t + 1``. Keyword Args: indices (tuple[int]): The indices of the major complex. major_complex (AcSystemIrreducibilityAnalysis): The major complex. If ``major_complex`` is given then ``indices`` is ignored. Returns: tuple(actions): List of extrinsic events in the major complex.
[ "Set", "of", "all", "mechanisms", "that", "are", "in", "the", "major", "complex", "but", "which", "have", "true", "causes", "and", "effects", "within", "the", "entire", "network", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L786-L817
15,904
wmayner/pyphi
pyphi/actual.py
Transition.apply_cut
def apply_cut(self, cut): """Return a cut version of this transition.""" return Transition(self.network, self.before_state, self.after_state, self.cause_indices, self.effect_indices, cut)
python
def apply_cut(self, cut): """Return a cut version of this transition.""" return Transition(self.network, self.before_state, self.after_state, self.cause_indices, self.effect_indices, cut)
[ "def", "apply_cut", "(", "self", ",", "cut", ")", ":", "return", "Transition", "(", "self", ".", "network", ",", "self", ".", "before_state", ",", "self", ".", "after_state", ",", "self", ".", "cause_indices", ",", "self", ".", "effect_indices", ",", "cut", ")" ]
Return a cut version of this transition.
[ "Return", "a", "cut", "version", "of", "this", "transition", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L176-L179
15,905
wmayner/pyphi
pyphi/actual.py
Transition.cause_repertoire
def cause_repertoire(self, mechanism, purview): """Return the cause repertoire.""" return self.repertoire(Direction.CAUSE, mechanism, purview)
python
def cause_repertoire(self, mechanism, purview): """Return the cause repertoire.""" return self.repertoire(Direction.CAUSE, mechanism, purview)
[ "def", "cause_repertoire", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "self", ".", "repertoire", "(", "Direction", ".", "CAUSE", ",", "mechanism", ",", "purview", ")" ]
Return the cause repertoire.
[ "Return", "the", "cause", "repertoire", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L181-L183
15,906
wmayner/pyphi
pyphi/actual.py
Transition.effect_repertoire
def effect_repertoire(self, mechanism, purview): """Return the effect repertoire.""" return self.repertoire(Direction.EFFECT, mechanism, purview)
python
def effect_repertoire(self, mechanism, purview): """Return the effect repertoire.""" return self.repertoire(Direction.EFFECT, mechanism, purview)
[ "def", "effect_repertoire", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "self", ".", "repertoire", "(", "Direction", ".", "EFFECT", ",", "mechanism", ",", "purview", ")" ]
Return the effect repertoire.
[ "Return", "the", "effect", "repertoire", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L185-L187
15,907
wmayner/pyphi
pyphi/actual.py
Transition.repertoire
def repertoire(self, direction, mechanism, purview): """Return the cause or effect repertoire function based on a direction. Args: direction (str): The temporal direction, specifiying the cause or effect repertoire. """ system = self.system[direction] node_labels = system.node_labels if not set(purview).issubset(self.purview_indices(direction)): raise ValueError('{} is not a {} purview in {}'.format( fmt.fmt_mechanism(purview, node_labels), direction, self)) if not set(mechanism).issubset(self.mechanism_indices(direction)): raise ValueError('{} is no a {} mechanism in {}'.format( fmt.fmt_mechanism(mechanism, node_labels), direction, self)) return system.repertoire(direction, mechanism, purview)
python
def repertoire(self, direction, mechanism, purview): """Return the cause or effect repertoire function based on a direction. Args: direction (str): The temporal direction, specifiying the cause or effect repertoire. """ system = self.system[direction] node_labels = system.node_labels if not set(purview).issubset(self.purview_indices(direction)): raise ValueError('{} is not a {} purview in {}'.format( fmt.fmt_mechanism(purview, node_labels), direction, self)) if not set(mechanism).issubset(self.mechanism_indices(direction)): raise ValueError('{} is no a {} mechanism in {}'.format( fmt.fmt_mechanism(mechanism, node_labels), direction, self)) return system.repertoire(direction, mechanism, purview)
[ "def", "repertoire", "(", "self", ",", "direction", ",", "mechanism", ",", "purview", ")", ":", "system", "=", "self", ".", "system", "[", "direction", "]", "node_labels", "=", "system", ".", "node_labels", "if", "not", "set", "(", "purview", ")", ".", "issubset", "(", "self", ".", "purview_indices", "(", "direction", ")", ")", ":", "raise", "ValueError", "(", "'{} is not a {} purview in {}'", ".", "format", "(", "fmt", ".", "fmt_mechanism", "(", "purview", ",", "node_labels", ")", ",", "direction", ",", "self", ")", ")", "if", "not", "set", "(", "mechanism", ")", ".", "issubset", "(", "self", ".", "mechanism_indices", "(", "direction", ")", ")", ":", "raise", "ValueError", "(", "'{} is no a {} mechanism in {}'", ".", "format", "(", "fmt", ".", "fmt_mechanism", "(", "mechanism", ",", "node_labels", ")", ",", "direction", ",", "self", ")", ")", "return", "system", ".", "repertoire", "(", "direction", ",", "mechanism", ",", "purview", ")" ]
Return the cause or effect repertoire function based on a direction. Args: direction (str): The temporal direction, specifiying the cause or effect repertoire.
[ "Return", "the", "cause", "or", "effect", "repertoire", "function", "based", "on", "a", "direction", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L197-L215
15,908
wmayner/pyphi
pyphi/actual.py
Transition.state_probability
def state_probability(self, direction, repertoire, purview,): """Compute the probability of the purview in its current state given the repertoire. Collapses the dimensions of the repertoire that correspond to the purview nodes onto their state. All other dimension are already singular and thus receive 0 as the conditioning index. Returns: float: A single probabilty. """ purview_state = self.purview_state(direction) index = tuple(node_state if node in purview else 0 for node, node_state in enumerate(purview_state)) return repertoire[index]
python
def state_probability(self, direction, repertoire, purview,): """Compute the probability of the purview in its current state given the repertoire. Collapses the dimensions of the repertoire that correspond to the purview nodes onto their state. All other dimension are already singular and thus receive 0 as the conditioning index. Returns: float: A single probabilty. """ purview_state = self.purview_state(direction) index = tuple(node_state if node in purview else 0 for node, node_state in enumerate(purview_state)) return repertoire[index]
[ "def", "state_probability", "(", "self", ",", "direction", ",", "repertoire", ",", "purview", ",", ")", ":", "purview_state", "=", "self", ".", "purview_state", "(", "direction", ")", "index", "=", "tuple", "(", "node_state", "if", "node", "in", "purview", "else", "0", "for", "node", ",", "node_state", "in", "enumerate", "(", "purview_state", ")", ")", "return", "repertoire", "[", "index", "]" ]
Compute the probability of the purview in its current state given the repertoire. Collapses the dimensions of the repertoire that correspond to the purview nodes onto their state. All other dimension are already singular and thus receive 0 as the conditioning index. Returns: float: A single probabilty.
[ "Compute", "the", "probability", "of", "the", "purview", "in", "its", "current", "state", "given", "the", "repertoire", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L217-L232
15,909
wmayner/pyphi
pyphi/actual.py
Transition.probability
def probability(self, direction, mechanism, purview): """Probability that the purview is in it's current state given the state of the mechanism. """ repertoire = self.repertoire(direction, mechanism, purview) return self.state_probability(direction, repertoire, purview)
python
def probability(self, direction, mechanism, purview): """Probability that the purview is in it's current state given the state of the mechanism. """ repertoire = self.repertoire(direction, mechanism, purview) return self.state_probability(direction, repertoire, purview)
[ "def", "probability", "(", "self", ",", "direction", ",", "mechanism", ",", "purview", ")", ":", "repertoire", "=", "self", ".", "repertoire", "(", "direction", ",", "mechanism", ",", "purview", ")", "return", "self", ".", "state_probability", "(", "direction", ",", "repertoire", ",", "purview", ")" ]
Probability that the purview is in it's current state given the state of the mechanism.
[ "Probability", "that", "the", "purview", "is", "in", "it", "s", "current", "state", "given", "the", "state", "of", "the", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L234-L240
15,910
wmayner/pyphi
pyphi/actual.py
Transition.purview_state
def purview_state(self, direction): """The state of the purview when we are computing coefficients in ``direction``. For example, if we are computing the cause coefficient of a mechanism in ``after_state``, the direction is``CAUSE`` and the ``purview_state`` is ``before_state``. """ return { Direction.CAUSE: self.before_state, Direction.EFFECT: self.after_state }[direction]
python
def purview_state(self, direction): """The state of the purview when we are computing coefficients in ``direction``. For example, if we are computing the cause coefficient of a mechanism in ``after_state``, the direction is``CAUSE`` and the ``purview_state`` is ``before_state``. """ return { Direction.CAUSE: self.before_state, Direction.EFFECT: self.after_state }[direction]
[ "def", "purview_state", "(", "self", ",", "direction", ")", ":", "return", "{", "Direction", ".", "CAUSE", ":", "self", ".", "before_state", ",", "Direction", ".", "EFFECT", ":", "self", ".", "after_state", "}", "[", "direction", "]" ]
The state of the purview when we are computing coefficients in ``direction``. For example, if we are computing the cause coefficient of a mechanism in ``after_state``, the direction is``CAUSE`` and the ``purview_state`` is ``before_state``.
[ "The", "state", "of", "the", "purview", "when", "we", "are", "computing", "coefficients", "in", "direction", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L246-L257
15,911
wmayner/pyphi
pyphi/actual.py
Transition.mechanism_indices
def mechanism_indices(self, direction): """The indices of nodes in the mechanism system.""" return { Direction.CAUSE: self.effect_indices, Direction.EFFECT: self.cause_indices }[direction]
python
def mechanism_indices(self, direction): """The indices of nodes in the mechanism system.""" return { Direction.CAUSE: self.effect_indices, Direction.EFFECT: self.cause_indices }[direction]
[ "def", "mechanism_indices", "(", "self", ",", "direction", ")", ":", "return", "{", "Direction", ".", "CAUSE", ":", "self", ".", "effect_indices", ",", "Direction", ".", "EFFECT", ":", "self", ".", "cause_indices", "}", "[", "direction", "]" ]
The indices of nodes in the mechanism system.
[ "The", "indices", "of", "nodes", "in", "the", "mechanism", "system", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L265-L270
15,912
wmayner/pyphi
pyphi/actual.py
Transition.purview_indices
def purview_indices(self, direction): """The indices of nodes in the purview system.""" return { Direction.CAUSE: self.cause_indices, Direction.EFFECT: self.effect_indices }[direction]
python
def purview_indices(self, direction): """The indices of nodes in the purview system.""" return { Direction.CAUSE: self.cause_indices, Direction.EFFECT: self.effect_indices }[direction]
[ "def", "purview_indices", "(", "self", ",", "direction", ")", ":", "return", "{", "Direction", ".", "CAUSE", ":", "self", ".", "cause_indices", ",", "Direction", ".", "EFFECT", ":", "self", ".", "effect_indices", "}", "[", "direction", "]" ]
The indices of nodes in the purview system.
[ "The", "indices", "of", "nodes", "in", "the", "purview", "system", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L272-L277
15,913
wmayner/pyphi
pyphi/actual.py
Transition.cause_ratio
def cause_ratio(self, mechanism, purview): """The cause ratio of the ``purview`` given ``mechanism``.""" return self._ratio(Direction.CAUSE, mechanism, purview)
python
def cause_ratio(self, mechanism, purview): """The cause ratio of the ``purview`` given ``mechanism``.""" return self._ratio(Direction.CAUSE, mechanism, purview)
[ "def", "cause_ratio", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "self", ".", "_ratio", "(", "Direction", ".", "CAUSE", ",", "mechanism", ",", "purview", ")" ]
The cause ratio of the ``purview`` given ``mechanism``.
[ "The", "cause", "ratio", "of", "the", "purview", "given", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L283-L285
15,914
wmayner/pyphi
pyphi/actual.py
Transition.effect_ratio
def effect_ratio(self, mechanism, purview): """The effect ratio of the ``purview`` given ``mechanism``.""" return self._ratio(Direction.EFFECT, mechanism, purview)
python
def effect_ratio(self, mechanism, purview): """The effect ratio of the ``purview`` given ``mechanism``.""" return self._ratio(Direction.EFFECT, mechanism, purview)
[ "def", "effect_ratio", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "self", ".", "_ratio", "(", "Direction", ".", "EFFECT", ",", "mechanism", ",", "purview", ")" ]
The effect ratio of the ``purview`` given ``mechanism``.
[ "The", "effect", "ratio", "of", "the", "purview", "given", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L287-L289
15,915
wmayner/pyphi
pyphi/actual.py
Transition.partitioned_repertoire
def partitioned_repertoire(self, direction, partition): """Compute the repertoire over the partition in the given direction.""" system = self.system[direction] return system.partitioned_repertoire(direction, partition)
python
def partitioned_repertoire(self, direction, partition): """Compute the repertoire over the partition in the given direction.""" system = self.system[direction] return system.partitioned_repertoire(direction, partition)
[ "def", "partitioned_repertoire", "(", "self", ",", "direction", ",", "partition", ")", ":", "system", "=", "self", ".", "system", "[", "direction", "]", "return", "system", ".", "partitioned_repertoire", "(", "direction", ",", "partition", ")" ]
Compute the repertoire over the partition in the given direction.
[ "Compute", "the", "repertoire", "over", "the", "partition", "in", "the", "given", "direction", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L291-L294
15,916
wmayner/pyphi
pyphi/actual.py
Transition.partitioned_probability
def partitioned_probability(self, direction, partition): """Compute the probability of the mechanism over the purview in the partition. """ repertoire = self.partitioned_repertoire(direction, partition) return self.state_probability(direction, repertoire, partition.purview)
python
def partitioned_probability(self, direction, partition): """Compute the probability of the mechanism over the purview in the partition. """ repertoire = self.partitioned_repertoire(direction, partition) return self.state_probability(direction, repertoire, partition.purview)
[ "def", "partitioned_probability", "(", "self", ",", "direction", ",", "partition", ")", ":", "repertoire", "=", "self", ".", "partitioned_repertoire", "(", "direction", ",", "partition", ")", "return", "self", ".", "state_probability", "(", "direction", ",", "repertoire", ",", "partition", ".", "purview", ")" ]
Compute the probability of the mechanism over the purview in the partition.
[ "Compute", "the", "probability", "of", "the", "mechanism", "over", "the", "purview", "in", "the", "partition", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L296-L301
15,917
wmayner/pyphi
pyphi/actual.py
Transition.find_mip
def find_mip(self, direction, mechanism, purview, allow_neg=False): """Find the ratio minimum information partition for a mechanism over a purview. Args: direction (str): |CAUSE| or |EFFECT| mechanism (tuple[int]): A mechanism. purview (tuple[int]): A purview. Keyword Args: allow_neg (boolean): If true, ``alpha`` is allowed to be negative. Otherwise, negative values of ``alpha`` will be treated as if they were 0. Returns: AcRepertoireIrreducibilityAnalysis: The irreducibility analysis for the mechanism. """ alpha_min = float('inf') probability = self.probability(direction, mechanism, purview) for partition in mip_partitions(mechanism, purview, self.node_labels): partitioned_probability = self.partitioned_probability( direction, partition) alpha = log2(probability / partitioned_probability) # First check for 0 # Default: don't count contrary causes and effects if utils.eq(alpha, 0) or (alpha < 0 and not allow_neg): return AcRepertoireIrreducibilityAnalysis( state=self.mechanism_state(direction), direction=direction, mechanism=mechanism, purview=purview, partition=partition, probability=probability, partitioned_probability=partitioned_probability, node_labels=self.node_labels, alpha=0.0 ) # Then take closest to 0 if (abs(alpha_min) - abs(alpha)) > constants.EPSILON: alpha_min = alpha acria = AcRepertoireIrreducibilityAnalysis( state=self.mechanism_state(direction), direction=direction, mechanism=mechanism, purview=purview, partition=partition, probability=probability, partitioned_probability=partitioned_probability, node_labels=self.node_labels, alpha=alpha_min ) return acria
python
def find_mip(self, direction, mechanism, purview, allow_neg=False): """Find the ratio minimum information partition for a mechanism over a purview. Args: direction (str): |CAUSE| or |EFFECT| mechanism (tuple[int]): A mechanism. purview (tuple[int]): A purview. Keyword Args: allow_neg (boolean): If true, ``alpha`` is allowed to be negative. Otherwise, negative values of ``alpha`` will be treated as if they were 0. Returns: AcRepertoireIrreducibilityAnalysis: The irreducibility analysis for the mechanism. """ alpha_min = float('inf') probability = self.probability(direction, mechanism, purview) for partition in mip_partitions(mechanism, purview, self.node_labels): partitioned_probability = self.partitioned_probability( direction, partition) alpha = log2(probability / partitioned_probability) # First check for 0 # Default: don't count contrary causes and effects if utils.eq(alpha, 0) or (alpha < 0 and not allow_neg): return AcRepertoireIrreducibilityAnalysis( state=self.mechanism_state(direction), direction=direction, mechanism=mechanism, purview=purview, partition=partition, probability=probability, partitioned_probability=partitioned_probability, node_labels=self.node_labels, alpha=0.0 ) # Then take closest to 0 if (abs(alpha_min) - abs(alpha)) > constants.EPSILON: alpha_min = alpha acria = AcRepertoireIrreducibilityAnalysis( state=self.mechanism_state(direction), direction=direction, mechanism=mechanism, purview=purview, partition=partition, probability=probability, partitioned_probability=partitioned_probability, node_labels=self.node_labels, alpha=alpha_min ) return acria
[ "def", "find_mip", "(", "self", ",", "direction", ",", "mechanism", ",", "purview", ",", "allow_neg", "=", "False", ")", ":", "alpha_min", "=", "float", "(", "'inf'", ")", "probability", "=", "self", ".", "probability", "(", "direction", ",", "mechanism", ",", "purview", ")", "for", "partition", "in", "mip_partitions", "(", "mechanism", ",", "purview", ",", "self", ".", "node_labels", ")", ":", "partitioned_probability", "=", "self", ".", "partitioned_probability", "(", "direction", ",", "partition", ")", "alpha", "=", "log2", "(", "probability", "/", "partitioned_probability", ")", "# First check for 0", "# Default: don't count contrary causes and effects", "if", "utils", ".", "eq", "(", "alpha", ",", "0", ")", "or", "(", "alpha", "<", "0", "and", "not", "allow_neg", ")", ":", "return", "AcRepertoireIrreducibilityAnalysis", "(", "state", "=", "self", ".", "mechanism_state", "(", "direction", ")", ",", "direction", "=", "direction", ",", "mechanism", "=", "mechanism", ",", "purview", "=", "purview", ",", "partition", "=", "partition", ",", "probability", "=", "probability", ",", "partitioned_probability", "=", "partitioned_probability", ",", "node_labels", "=", "self", ".", "node_labels", ",", "alpha", "=", "0.0", ")", "# Then take closest to 0", "if", "(", "abs", "(", "alpha_min", ")", "-", "abs", "(", "alpha", ")", ")", ">", "constants", ".", "EPSILON", ":", "alpha_min", "=", "alpha", "acria", "=", "AcRepertoireIrreducibilityAnalysis", "(", "state", "=", "self", ".", "mechanism_state", "(", "direction", ")", ",", "direction", "=", "direction", ",", "mechanism", "=", "mechanism", ",", "purview", "=", "purview", ",", "partition", "=", "partition", ",", "probability", "=", "probability", ",", "partitioned_probability", "=", "partitioned_probability", ",", "node_labels", "=", "self", ".", "node_labels", ",", "alpha", "=", "alpha_min", ")", "return", "acria" ]
Find the ratio minimum information partition for a mechanism over a purview. Args: direction (str): |CAUSE| or |EFFECT| mechanism (tuple[int]): A mechanism. purview (tuple[int]): A purview. Keyword Args: allow_neg (boolean): If true, ``alpha`` is allowed to be negative. Otherwise, negative values of ``alpha`` will be treated as if they were 0. Returns: AcRepertoireIrreducibilityAnalysis: The irreducibility analysis for the mechanism.
[ "Find", "the", "ratio", "minimum", "information", "partition", "for", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L307-L361
15,918
wmayner/pyphi
pyphi/actual.py
Transition.find_causal_link
def find_causal_link(self, direction, mechanism, purviews=False, allow_neg=False): """Return the maximally irreducible cause or effect ratio for a mechanism. Args: direction (str): The temporal direction, specifying cause or effect. mechanism (tuple[int]): The mechanism to be tested for irreducibility. Keyword Args: purviews (tuple[int]): Optionally restrict the possible purviews to a subset of the subsystem. This may be useful for _e.g._ finding only concepts that are "about" a certain subset of nodes. Returns: CausalLink: The maximally-irreducible actual cause or effect. """ purviews = self.potential_purviews(direction, mechanism, purviews) # Find the maximal RIA over the remaining purviews. if not purviews: max_ria = _null_ac_ria(self.mechanism_state(direction), direction, mechanism, None) else: # This max should be most positive max_ria = max(self.find_mip(direction, mechanism, purview, allow_neg) for purview in purviews) # Construct the corresponding CausalLink return CausalLink(max_ria)
python
def find_causal_link(self, direction, mechanism, purviews=False, allow_neg=False): """Return the maximally irreducible cause or effect ratio for a mechanism. Args: direction (str): The temporal direction, specifying cause or effect. mechanism (tuple[int]): The mechanism to be tested for irreducibility. Keyword Args: purviews (tuple[int]): Optionally restrict the possible purviews to a subset of the subsystem. This may be useful for _e.g._ finding only concepts that are "about" a certain subset of nodes. Returns: CausalLink: The maximally-irreducible actual cause or effect. """ purviews = self.potential_purviews(direction, mechanism, purviews) # Find the maximal RIA over the remaining purviews. if not purviews: max_ria = _null_ac_ria(self.mechanism_state(direction), direction, mechanism, None) else: # This max should be most positive max_ria = max(self.find_mip(direction, mechanism, purview, allow_neg) for purview in purviews) # Construct the corresponding CausalLink return CausalLink(max_ria)
[ "def", "find_causal_link", "(", "self", ",", "direction", ",", "mechanism", ",", "purviews", "=", "False", ",", "allow_neg", "=", "False", ")", ":", "purviews", "=", "self", ".", "potential_purviews", "(", "direction", ",", "mechanism", ",", "purviews", ")", "# Find the maximal RIA over the remaining purviews.", "if", "not", "purviews", ":", "max_ria", "=", "_null_ac_ria", "(", "self", ".", "mechanism_state", "(", "direction", ")", ",", "direction", ",", "mechanism", ",", "None", ")", "else", ":", "# This max should be most positive", "max_ria", "=", "max", "(", "self", ".", "find_mip", "(", "direction", ",", "mechanism", ",", "purview", ",", "allow_neg", ")", "for", "purview", "in", "purviews", ")", "# Construct the corresponding CausalLink", "return", "CausalLink", "(", "max_ria", ")" ]
Return the maximally irreducible cause or effect ratio for a mechanism. Args: direction (str): The temporal direction, specifying cause or effect. mechanism (tuple[int]): The mechanism to be tested for irreducibility. Keyword Args: purviews (tuple[int]): Optionally restrict the possible purviews to a subset of the subsystem. This may be useful for _e.g._ finding only concepts that are "about" a certain subset of nodes. Returns: CausalLink: The maximally-irreducible actual cause or effect.
[ "Return", "the", "maximally", "irreducible", "cause", "or", "effect", "ratio", "for", "a", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L387-L420
15,919
wmayner/pyphi
pyphi/actual.py
Transition.find_actual_cause
def find_actual_cause(self, mechanism, purviews=False): """Return the actual cause of a mechanism.""" return self.find_causal_link(Direction.CAUSE, mechanism, purviews)
python
def find_actual_cause(self, mechanism, purviews=False): """Return the actual cause of a mechanism.""" return self.find_causal_link(Direction.CAUSE, mechanism, purviews)
[ "def", "find_actual_cause", "(", "self", ",", "mechanism", ",", "purviews", "=", "False", ")", ":", "return", "self", ".", "find_causal_link", "(", "Direction", ".", "CAUSE", ",", "mechanism", ",", "purviews", ")" ]
Return the actual cause of a mechanism.
[ "Return", "the", "actual", "cause", "of", "a", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L422-L424
15,920
wmayner/pyphi
pyphi/actual.py
Transition.find_actual_effect
def find_actual_effect(self, mechanism, purviews=False): """Return the actual effect of a mechanism.""" return self.find_causal_link(Direction.EFFECT, mechanism, purviews)
python
def find_actual_effect(self, mechanism, purviews=False): """Return the actual effect of a mechanism.""" return self.find_causal_link(Direction.EFFECT, mechanism, purviews)
[ "def", "find_actual_effect", "(", "self", ",", "mechanism", ",", "purviews", "=", "False", ")", ":", "return", "self", ".", "find_causal_link", "(", "Direction", ".", "EFFECT", ",", "mechanism", ",", "purviews", ")" ]
Return the actual effect of a mechanism.
[ "Return", "the", "actual", "effect", "of", "a", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L426-L428
15,921
wmayner/pyphi
pyphi/db.py
find
def find(key): """Return the value associated with a key. If there is no value with the given key, returns ``None``. """ docs = list(collection.find({KEY_FIELD: key})) # Return None if we didn't find anything. if not docs: return None pickled_value = docs[0][VALUE_FIELD] # Unpickle and return the value. return pickle.loads(pickled_value)
python
def find(key): """Return the value associated with a key. If there is no value with the given key, returns ``None``. """ docs = list(collection.find({KEY_FIELD: key})) # Return None if we didn't find anything. if not docs: return None pickled_value = docs[0][VALUE_FIELD] # Unpickle and return the value. return pickle.loads(pickled_value)
[ "def", "find", "(", "key", ")", ":", "docs", "=", "list", "(", "collection", ".", "find", "(", "{", "KEY_FIELD", ":", "key", "}", ")", ")", "# Return None if we didn't find anything.", "if", "not", "docs", ":", "return", "None", "pickled_value", "=", "docs", "[", "0", "]", "[", "VALUE_FIELD", "]", "# Unpickle and return the value.", "return", "pickle", ".", "loads", "(", "pickled_value", ")" ]
Return the value associated with a key. If there is no value with the given key, returns ``None``.
[ "Return", "the", "value", "associated", "with", "a", "key", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/db.py#L34-L45
15,922
wmayner/pyphi
pyphi/db.py
insert
def insert(key, value): """Store a value with a key. If the key is already present in the database, this does nothing. """ # Pickle the value. value = pickle.dumps(value, protocol=constants.PICKLE_PROTOCOL) # Store the value as binary data in a document. doc = { KEY_FIELD: key, VALUE_FIELD: Binary(value) } # Pickle and store the value with its key. If the key already exists, we # don't insert (since the key is a unique index), and we don't care. try: return collection.insert(doc) except pymongo.errors.DuplicateKeyError: return None
python
def insert(key, value): """Store a value with a key. If the key is already present in the database, this does nothing. """ # Pickle the value. value = pickle.dumps(value, protocol=constants.PICKLE_PROTOCOL) # Store the value as binary data in a document. doc = { KEY_FIELD: key, VALUE_FIELD: Binary(value) } # Pickle and store the value with its key. If the key already exists, we # don't insert (since the key is a unique index), and we don't care. try: return collection.insert(doc) except pymongo.errors.DuplicateKeyError: return None
[ "def", "insert", "(", "key", ",", "value", ")", ":", "# Pickle the value.", "value", "=", "pickle", ".", "dumps", "(", "value", ",", "protocol", "=", "constants", ".", "PICKLE_PROTOCOL", ")", "# Store the value as binary data in a document.", "doc", "=", "{", "KEY_FIELD", ":", "key", ",", "VALUE_FIELD", ":", "Binary", "(", "value", ")", "}", "# Pickle and store the value with its key. If the key already exists, we", "# don't insert (since the key is a unique index), and we don't care.", "try", ":", "return", "collection", ".", "insert", "(", "doc", ")", "except", "pymongo", ".", "errors", ".", "DuplicateKeyError", ":", "return", "None" ]
Store a value with a key. If the key is already present in the database, this does nothing.
[ "Store", "a", "value", "with", "a", "key", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/db.py#L48-L65
15,923
wmayner/pyphi
pyphi/db.py
generate_key
def generate_key(filtered_args): """Get a key from some input. This function should be used whenever a key is needed, to keep keys consistent. """ # Convert the value to a (potentially singleton) tuple to be consistent # with joblib.filtered_args. if isinstance(filtered_args, Iterable): return hash(tuple(filtered_args)) return hash((filtered_args,))
python
def generate_key(filtered_args): """Get a key from some input. This function should be used whenever a key is needed, to keep keys consistent. """ # Convert the value to a (potentially singleton) tuple to be consistent # with joblib.filtered_args. if isinstance(filtered_args, Iterable): return hash(tuple(filtered_args)) return hash((filtered_args,))
[ "def", "generate_key", "(", "filtered_args", ")", ":", "# Convert the value to a (potentially singleton) tuple to be consistent", "# with joblib.filtered_args.", "if", "isinstance", "(", "filtered_args", ",", "Iterable", ")", ":", "return", "hash", "(", "tuple", "(", "filtered_args", ")", ")", "return", "hash", "(", "(", "filtered_args", ",", ")", ")" ]
Get a key from some input. This function should be used whenever a key is needed, to keep keys consistent.
[ "Get", "a", "key", "from", "some", "input", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/db.py#L69-L79
15,924
wmayner/pyphi
pyphi/memory.py
cache
def cache(ignore=None): """Decorator for memoizing a function using either the filesystem or a database. """ def decorator(func): # Initialize both cached versions joblib_cached = constants.joblib_memory.cache(func, ignore=ignore) db_cached = DbMemoizedFunc(func, ignore) @functools.wraps(func) def wrapper(*args, **kwargs): """Dynamically choose the cache at call-time, not at import.""" if func.__name__ == '_sia' and not config.CACHE_SIAS: f = func elif config.CACHING_BACKEND == 'fs': f = joblib_cached elif config.CACHING_BACKEND == 'db': f = db_cached return f(*args, **kwargs) return wrapper return decorator
python
def cache(ignore=None): """Decorator for memoizing a function using either the filesystem or a database. """ def decorator(func): # Initialize both cached versions joblib_cached = constants.joblib_memory.cache(func, ignore=ignore) db_cached = DbMemoizedFunc(func, ignore) @functools.wraps(func) def wrapper(*args, **kwargs): """Dynamically choose the cache at call-time, not at import.""" if func.__name__ == '_sia' and not config.CACHE_SIAS: f = func elif config.CACHING_BACKEND == 'fs': f = joblib_cached elif config.CACHING_BACKEND == 'db': f = db_cached return f(*args, **kwargs) return wrapper return decorator
[ "def", "cache", "(", "ignore", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "# Initialize both cached versions", "joblib_cached", "=", "constants", ".", "joblib_memory", ".", "cache", "(", "func", ",", "ignore", "=", "ignore", ")", "db_cached", "=", "DbMemoizedFunc", "(", "func", ",", "ignore", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Dynamically choose the cache at call-time, not at import.\"\"\"", "if", "func", ".", "__name__", "==", "'_sia'", "and", "not", "config", ".", "CACHE_SIAS", ":", "f", "=", "func", "elif", "config", ".", "CACHING_BACKEND", "==", "'fs'", ":", "f", "=", "joblib_cached", "elif", "config", ".", "CACHING_BACKEND", "==", "'db'", ":", "f", "=", "db_cached", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
Decorator for memoizing a function using either the filesystem or a database.
[ "Decorator", "for", "memoizing", "a", "function", "using", "either", "the", "filesystem", "or", "a", "database", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/memory.py#L18-L39
15,925
wmayner/pyphi
pyphi/memory.py
DbMemoizedFunc.get_output_key
def get_output_key(self, args, kwargs): """Return the key that the output should be cached with, given arguments, keyword arguments, and a list of arguments to ignore. """ # Get a dictionary mapping argument names to argument values where # ignored arguments are omitted. filtered_args = joblib.func_inspect.filter_args( self.func, self.ignore, args, kwargs) # Get a sorted tuple of the filtered argument. filtered_args = tuple(sorted(filtered_args.values())) # Use native hash when hashing arguments. return db.generate_key(filtered_args)
python
def get_output_key(self, args, kwargs): """Return the key that the output should be cached with, given arguments, keyword arguments, and a list of arguments to ignore. """ # Get a dictionary mapping argument names to argument values where # ignored arguments are omitted. filtered_args = joblib.func_inspect.filter_args( self.func, self.ignore, args, kwargs) # Get a sorted tuple of the filtered argument. filtered_args = tuple(sorted(filtered_args.values())) # Use native hash when hashing arguments. return db.generate_key(filtered_args)
[ "def", "get_output_key", "(", "self", ",", "args", ",", "kwargs", ")", ":", "# Get a dictionary mapping argument names to argument values where", "# ignored arguments are omitted.", "filtered_args", "=", "joblib", ".", "func_inspect", ".", "filter_args", "(", "self", ".", "func", ",", "self", ".", "ignore", ",", "args", ",", "kwargs", ")", "# Get a sorted tuple of the filtered argument.", "filtered_args", "=", "tuple", "(", "sorted", "(", "filtered_args", ".", "values", "(", ")", ")", ")", "# Use native hash when hashing arguments.", "return", "db", ".", "generate_key", "(", "filtered_args", ")" ]
Return the key that the output should be cached with, given arguments, keyword arguments, and a list of arguments to ignore.
[ "Return", "the", "key", "that", "the", "output", "should", "be", "cached", "with", "given", "arguments", "keyword", "arguments", "and", "a", "list", "of", "arguments", "to", "ignore", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/memory.py#L73-L84
15,926
wmayner/pyphi
pyphi/memory.py
DbMemoizedFunc.load_output
def load_output(self, args, kwargs): """Return cached output.""" return db.find(self.get_output_key(args, kwargs))
python
def load_output(self, args, kwargs): """Return cached output.""" return db.find(self.get_output_key(args, kwargs))
[ "def", "load_output", "(", "self", ",", "args", ",", "kwargs", ")", ":", "return", "db", ".", "find", "(", "self", ".", "get_output_key", "(", "args", ",", "kwargs", ")", ")" ]
Return cached output.
[ "Return", "cached", "output", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/memory.py#L86-L88
15,927
wmayner/pyphi
pyphi/subsystem.py
Subsystem.cache_info
def cache_info(self): """Report repertoire cache statistics.""" return { 'single_node_repertoire': self._single_node_repertoire_cache.info(), 'repertoire': self._repertoire_cache.info(), 'mice': self._mice_cache.info() }
python
def cache_info(self): """Report repertoire cache statistics.""" return { 'single_node_repertoire': self._single_node_repertoire_cache.info(), 'repertoire': self._repertoire_cache.info(), 'mice': self._mice_cache.info() }
[ "def", "cache_info", "(", "self", ")", ":", "return", "{", "'single_node_repertoire'", ":", "self", ".", "_single_node_repertoire_cache", ".", "info", "(", ")", ",", "'repertoire'", ":", "self", ".", "_repertoire_cache", ".", "info", "(", ")", ",", "'mice'", ":", "self", ".", "_mice_cache", ".", "info", "(", ")", "}" ]
Report repertoire cache statistics.
[ "Report", "repertoire", "cache", "statistics", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L171-L178
15,928
wmayner/pyphi
pyphi/subsystem.py
Subsystem.clear_caches
def clear_caches(self): """Clear the mice and repertoire caches.""" self._single_node_repertoire_cache.clear() self._repertoire_cache.clear() self._mice_cache.clear()
python
def clear_caches(self): """Clear the mice and repertoire caches.""" self._single_node_repertoire_cache.clear() self._repertoire_cache.clear() self._mice_cache.clear()
[ "def", "clear_caches", "(", "self", ")", ":", "self", ".", "_single_node_repertoire_cache", ".", "clear", "(", ")", "self", ".", "_repertoire_cache", ".", "clear", "(", ")", "self", ".", "_mice_cache", ".", "clear", "(", ")" ]
Clear the mice and repertoire caches.
[ "Clear", "the", "mice", "and", "repertoire", "caches", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L180-L184
15,929
wmayner/pyphi
pyphi/subsystem.py
Subsystem.apply_cut
def apply_cut(self, cut): """Return a cut version of this |Subsystem|. Args: cut (Cut): The cut to apply to this |Subsystem|. Returns: Subsystem: The cut subsystem. """ return Subsystem(self.network, self.state, self.node_indices, cut=cut, mice_cache=self._mice_cache)
python
def apply_cut(self, cut): """Return a cut version of this |Subsystem|. Args: cut (Cut): The cut to apply to this |Subsystem|. Returns: Subsystem: The cut subsystem. """ return Subsystem(self.network, self.state, self.node_indices, cut=cut, mice_cache=self._mice_cache)
[ "def", "apply_cut", "(", "self", ",", "cut", ")", ":", "return", "Subsystem", "(", "self", ".", "network", ",", "self", ".", "state", ",", "self", ".", "node_indices", ",", "cut", "=", "cut", ",", "mice_cache", "=", "self", ".", "_mice_cache", ")" ]
Return a cut version of this |Subsystem|. Args: cut (Cut): The cut to apply to this |Subsystem|. Returns: Subsystem: The cut subsystem.
[ "Return", "a", "cut", "version", "of", "this", "|Subsystem|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L247-L257
15,930
wmayner/pyphi
pyphi/subsystem.py
Subsystem.indices2nodes
def indices2nodes(self, indices): """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. """ 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)
python
def indices2nodes(self, indices): """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. """ 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)
[ "def", "indices2nodes", "(", "self", ",", "indices", ")", ":", "if", "set", "(", "indices", ")", "-", "set", "(", "self", ".", "node_indices", ")", ":", "raise", "ValueError", "(", "\"`indices` must be a subset of the Subsystem's indices.\"", ")", "return", "tuple", "(", "self", ".", "_index2node", "[", "n", "]", "for", "n", "in", "indices", ")" ]
Return |Nodes| for these indices. 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.
[ "Return", "|Nodes|", "for", "these", "indices", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L259-L274
15,931
wmayner/pyphi
pyphi/subsystem.py
Subsystem.cause_repertoire
def cause_repertoire(self, mechanism, purview): """Return the cause repertoire of a mechanism over a purview. Args: mechanism (tuple[int]): The mechanism for which to calculate the cause repertoire. purview (tuple[int]): The purview over which to calculate the cause repertoire. Returns: np.ndarray: The cause repertoire of the mechanism over the purview. .. note:: The returned repertoire is a distribution over purview node states, not the states of the whole network. """ # If the purview is empty, the distribution is empty; return the # multiplicative identity. if not purview: return np.array([1.0]) # If the mechanism is empty, nothing is specified about the previous # state of the purview; return the purview's maximum entropy # distribution. if not mechanism: return max_entropy_distribution(purview, self.tpm_size) # Use a frozenset so the arguments to `_single_node_cause_repertoire` # can be hashed and cached. purview = frozenset(purview) # Preallocate the repertoire with the proper shape, so that # probabilities are broadcasted appropriately. joint = np.ones(repertoire_shape(purview, self.tpm_size)) # The cause repertoire is the product of the cause repertoires of the # individual nodes. joint *= functools.reduce( np.multiply, [self._single_node_cause_repertoire(m, purview) for m in mechanism] ) # The resulting joint distribution is over previous states, which are # rows in the TPM, so the distribution is a column. The columns of a # TPM don't necessarily sum to 1, so we normalize. return distribution.normalize(joint)
python
def cause_repertoire(self, mechanism, purview): """Return the cause repertoire of a mechanism over a purview. Args: mechanism (tuple[int]): The mechanism for which to calculate the cause repertoire. purview (tuple[int]): The purview over which to calculate the cause repertoire. Returns: np.ndarray: The cause repertoire of the mechanism over the purview. .. note:: The returned repertoire is a distribution over purview node states, not the states of the whole network. """ # If the purview is empty, the distribution is empty; return the # multiplicative identity. if not purview: return np.array([1.0]) # If the mechanism is empty, nothing is specified about the previous # state of the purview; return the purview's maximum entropy # distribution. if not mechanism: return max_entropy_distribution(purview, self.tpm_size) # Use a frozenset so the arguments to `_single_node_cause_repertoire` # can be hashed and cached. purview = frozenset(purview) # Preallocate the repertoire with the proper shape, so that # probabilities are broadcasted appropriately. joint = np.ones(repertoire_shape(purview, self.tpm_size)) # The cause repertoire is the product of the cause repertoires of the # individual nodes. joint *= functools.reduce( np.multiply, [self._single_node_cause_repertoire(m, purview) for m in mechanism] ) # The resulting joint distribution is over previous states, which are # rows in the TPM, so the distribution is a column. The columns of a # TPM don't necessarily sum to 1, so we normalize. return distribution.normalize(joint)
[ "def", "cause_repertoire", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "# If the purview is empty, the distribution is empty; return the", "# multiplicative identity.", "if", "not", "purview", ":", "return", "np", ".", "array", "(", "[", "1.0", "]", ")", "# If the mechanism is empty, nothing is specified about the previous", "# state of the purview; return the purview's maximum entropy", "# distribution.", "if", "not", "mechanism", ":", "return", "max_entropy_distribution", "(", "purview", ",", "self", ".", "tpm_size", ")", "# Use a frozenset so the arguments to `_single_node_cause_repertoire`", "# can be hashed and cached.", "purview", "=", "frozenset", "(", "purview", ")", "# Preallocate the repertoire with the proper shape, so that", "# probabilities are broadcasted appropriately.", "joint", "=", "np", ".", "ones", "(", "repertoire_shape", "(", "purview", ",", "self", ".", "tpm_size", ")", ")", "# The cause repertoire is the product of the cause repertoires of the", "# individual nodes.", "joint", "*=", "functools", ".", "reduce", "(", "np", ".", "multiply", ",", "[", "self", ".", "_single_node_cause_repertoire", "(", "m", ",", "purview", ")", "for", "m", "in", "mechanism", "]", ")", "# The resulting joint distribution is over previous states, which are", "# rows in the TPM, so the distribution is a column. The columns of a", "# TPM don't necessarily sum to 1, so we normalize.", "return", "distribution", ".", "normalize", "(", "joint", ")" ]
Return the cause repertoire of a mechanism over a purview. Args: mechanism (tuple[int]): The mechanism for which to calculate the cause repertoire. purview (tuple[int]): The purview over which to calculate the cause repertoire. Returns: np.ndarray: The cause repertoire of the mechanism over the purview. .. note:: The returned repertoire is a distribution over purview node states, not the states of the whole network.
[ "Return", "the", "cause", "repertoire", "of", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L290-L330
15,932
wmayner/pyphi
pyphi/subsystem.py
Subsystem.effect_repertoire
def effect_repertoire(self, mechanism, purview): """Return the effect repertoire of a mechanism over a purview. Args: mechanism (tuple[int]): The mechanism for which to calculate the effect repertoire. purview (tuple[int]): The purview over which to calculate the effect repertoire. Returns: np.ndarray: The effect repertoire of the mechanism over the purview. .. note:: The returned repertoire is a distribution over purview node states, not the states of the whole network. """ # If the purview is empty, the distribution is empty, so return the # multiplicative identity. if not purview: return np.array([1.0]) # Use a frozenset so the arguments to `_single_node_effect_repertoire` # can be hashed and cached. mechanism = frozenset(mechanism) # Preallocate the repertoire with the proper shape, so that # probabilities are broadcasted appropriately. joint = np.ones(repertoire_shape(purview, self.tpm_size)) # The effect repertoire is the product of the effect repertoires of the # individual nodes. return joint * functools.reduce( np.multiply, [self._single_node_effect_repertoire(mechanism, p) for p in purview] )
python
def effect_repertoire(self, mechanism, purview): """Return the effect repertoire of a mechanism over a purview. Args: mechanism (tuple[int]): The mechanism for which to calculate the effect repertoire. purview (tuple[int]): The purview over which to calculate the effect repertoire. Returns: np.ndarray: The effect repertoire of the mechanism over the purview. .. note:: The returned repertoire is a distribution over purview node states, not the states of the whole network. """ # If the purview is empty, the distribution is empty, so return the # multiplicative identity. if not purview: return np.array([1.0]) # Use a frozenset so the arguments to `_single_node_effect_repertoire` # can be hashed and cached. mechanism = frozenset(mechanism) # Preallocate the repertoire with the proper shape, so that # probabilities are broadcasted appropriately. joint = np.ones(repertoire_shape(purview, self.tpm_size)) # The effect repertoire is the product of the effect repertoires of the # individual nodes. return joint * functools.reduce( np.multiply, [self._single_node_effect_repertoire(mechanism, p) for p in purview] )
[ "def", "effect_repertoire", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "# If the purview is empty, the distribution is empty, so return the", "# multiplicative identity.", "if", "not", "purview", ":", "return", "np", ".", "array", "(", "[", "1.0", "]", ")", "# Use a frozenset so the arguments to `_single_node_effect_repertoire`", "# can be hashed and cached.", "mechanism", "=", "frozenset", "(", "mechanism", ")", "# Preallocate the repertoire with the proper shape, so that", "# probabilities are broadcasted appropriately.", "joint", "=", "np", ".", "ones", "(", "repertoire_shape", "(", "purview", ",", "self", ".", "tpm_size", ")", ")", "# The effect repertoire is the product of the effect repertoires of the", "# individual nodes.", "return", "joint", "*", "functools", ".", "reduce", "(", "np", ".", "multiply", ",", "[", "self", ".", "_single_node_effect_repertoire", "(", "mechanism", ",", "p", ")", "for", "p", "in", "purview", "]", ")" ]
Return the effect repertoire of a mechanism over a purview. Args: mechanism (tuple[int]): The mechanism for which to calculate the effect repertoire. purview (tuple[int]): The purview over which to calculate the effect repertoire. Returns: np.ndarray: The effect repertoire of the mechanism over the purview. .. note:: The returned repertoire is a distribution over purview node states, not the states of the whole network.
[ "Return", "the", "effect", "repertoire", "of", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L348-L380
15,933
wmayner/pyphi
pyphi/subsystem.py
Subsystem.repertoire
def repertoire(self, direction, mechanism, purview): """Return the cause or effect repertoire based on a direction. Args: direction (Direction): |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism for which to calculate the repertoire. purview (tuple[int]): The purview over which to calculate the repertoire. Returns: np.ndarray: The cause or effect repertoire of the mechanism over the purview. Raises: ValueError: If ``direction`` is invalid. """ if direction == Direction.CAUSE: return self.cause_repertoire(mechanism, purview) elif direction == Direction.EFFECT: return self.effect_repertoire(mechanism, purview) return validate.direction(direction)
python
def repertoire(self, direction, mechanism, purview): """Return the cause or effect repertoire based on a direction. Args: direction (Direction): |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism for which to calculate the repertoire. purview (tuple[int]): The purview over which to calculate the repertoire. Returns: np.ndarray: The cause or effect repertoire of the mechanism over the purview. Raises: ValueError: If ``direction`` is invalid. """ if direction == Direction.CAUSE: return self.cause_repertoire(mechanism, purview) elif direction == Direction.EFFECT: return self.effect_repertoire(mechanism, purview) return validate.direction(direction)
[ "def", "repertoire", "(", "self", ",", "direction", ",", "mechanism", ",", "purview", ")", ":", "if", "direction", "==", "Direction", ".", "CAUSE", ":", "return", "self", ".", "cause_repertoire", "(", "mechanism", ",", "purview", ")", "elif", "direction", "==", "Direction", ".", "EFFECT", ":", "return", "self", ".", "effect_repertoire", "(", "mechanism", ",", "purview", ")", "return", "validate", ".", "direction", "(", "direction", ")" ]
Return the cause or effect repertoire based on a direction. Args: direction (Direction): |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism for which to calculate the repertoire. purview (tuple[int]): The purview over which to calculate the repertoire. Returns: np.ndarray: The cause or effect repertoire of the mechanism over the purview. Raises: ValueError: If ``direction`` is invalid.
[ "Return", "the", "cause", "or", "effect", "repertoire", "based", "on", "a", "direction", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L382-L404
15,934
wmayner/pyphi
pyphi/subsystem.py
Subsystem.partitioned_repertoire
def partitioned_repertoire(self, direction, partition): """Compute the repertoire of a partitioned mechanism and purview.""" repertoires = [ self.repertoire(direction, part.mechanism, part.purview) for part in partition ] return functools.reduce(np.multiply, repertoires)
python
def partitioned_repertoire(self, direction, partition): """Compute the repertoire of a partitioned mechanism and purview.""" repertoires = [ self.repertoire(direction, part.mechanism, part.purview) for part in partition ] return functools.reduce(np.multiply, repertoires)
[ "def", "partitioned_repertoire", "(", "self", ",", "direction", ",", "partition", ")", ":", "repertoires", "=", "[", "self", ".", "repertoire", "(", "direction", ",", "part", ".", "mechanism", ",", "part", ".", "purview", ")", "for", "part", "in", "partition", "]", "return", "functools", ".", "reduce", "(", "np", ".", "multiply", ",", "repertoires", ")" ]
Compute the repertoire of a partitioned mechanism and purview.
[ "Compute", "the", "repertoire", "of", "a", "partitioned", "mechanism", "and", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L424-L430
15,935
wmayner/pyphi
pyphi/subsystem.py
Subsystem.expand_repertoire
def expand_repertoire(self, direction, repertoire, new_purview=None): """Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview. """ if repertoire is None: return None purview = distribution.purview(repertoire) if new_purview is None: new_purview = self.node_indices # full subsystem if not set(purview).issubset(new_purview): raise ValueError("Expanded purview must contain original purview.") # Get the unconstrained repertoire over the other nodes in the network. non_purview_indices = tuple(set(new_purview) - set(purview)) uc = self.unconstrained_repertoire(direction, non_purview_indices) # Multiply the given repertoire by the unconstrained one to get a # distribution over all the nodes in the network. expanded_repertoire = repertoire * uc return distribution.normalize(expanded_repertoire)
python
def expand_repertoire(self, direction, repertoire, new_purview=None): """Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview. """ if repertoire is None: return None purview = distribution.purview(repertoire) if new_purview is None: new_purview = self.node_indices # full subsystem if not set(purview).issubset(new_purview): raise ValueError("Expanded purview must contain original purview.") # Get the unconstrained repertoire over the other nodes in the network. non_purview_indices = tuple(set(new_purview) - set(purview)) uc = self.unconstrained_repertoire(direction, non_purview_indices) # Multiply the given repertoire by the unconstrained one to get a # distribution over all the nodes in the network. expanded_repertoire = repertoire * uc return distribution.normalize(expanded_repertoire)
[ "def", "expand_repertoire", "(", "self", ",", "direction", ",", "repertoire", ",", "new_purview", "=", "None", ")", ":", "if", "repertoire", "is", "None", ":", "return", "None", "purview", "=", "distribution", ".", "purview", "(", "repertoire", ")", "if", "new_purview", "is", "None", ":", "new_purview", "=", "self", ".", "node_indices", "# full subsystem", "if", "not", "set", "(", "purview", ")", ".", "issubset", "(", "new_purview", ")", ":", "raise", "ValueError", "(", "\"Expanded purview must contain original purview.\"", ")", "# Get the unconstrained repertoire over the other nodes in the network.", "non_purview_indices", "=", "tuple", "(", "set", "(", "new_purview", ")", "-", "set", "(", "purview", ")", ")", "uc", "=", "self", ".", "unconstrained_repertoire", "(", "direction", ",", "non_purview_indices", ")", "# Multiply the given repertoire by the unconstrained one to get a", "# distribution over all the nodes in the network.", "expanded_repertoire", "=", "repertoire", "*", "uc", "return", "distribution", ".", "normalize", "(", "expanded_repertoire", ")" ]
Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview.
[ "Distribute", "an", "effect", "repertoire", "over", "a", "larger", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L432-L470
15,936
wmayner/pyphi
pyphi/subsystem.py
Subsystem.cause_info
def cause_info(self, mechanism, purview): """Return the cause information for a mechanism over a purview.""" return repertoire_distance( Direction.CAUSE, self.cause_repertoire(mechanism, purview), self.unconstrained_cause_repertoire(purview) )
python
def cause_info(self, mechanism, purview): """Return the cause information for a mechanism over a purview.""" return repertoire_distance( Direction.CAUSE, self.cause_repertoire(mechanism, purview), self.unconstrained_cause_repertoire(purview) )
[ "def", "cause_info", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "repertoire_distance", "(", "Direction", ".", "CAUSE", ",", "self", ".", "cause_repertoire", "(", "mechanism", ",", "purview", ")", ",", "self", ".", "unconstrained_cause_repertoire", "(", "purview", ")", ")" ]
Return the cause information for a mechanism over a purview.
[ "Return", "the", "cause", "information", "for", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L484-L490
15,937
wmayner/pyphi
pyphi/subsystem.py
Subsystem.effect_info
def effect_info(self, mechanism, purview): """Return the effect information for a mechanism over a purview.""" return repertoire_distance( Direction.EFFECT, self.effect_repertoire(mechanism, purview), self.unconstrained_effect_repertoire(purview) )
python
def effect_info(self, mechanism, purview): """Return the effect information for a mechanism over a purview.""" return repertoire_distance( Direction.EFFECT, self.effect_repertoire(mechanism, purview), self.unconstrained_effect_repertoire(purview) )
[ "def", "effect_info", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "repertoire_distance", "(", "Direction", ".", "EFFECT", ",", "self", ".", "effect_repertoire", "(", "mechanism", ",", "purview", ")", ",", "self", ".", "unconstrained_effect_repertoire", "(", "purview", ")", ")" ]
Return the effect information for a mechanism over a purview.
[ "Return", "the", "effect", "information", "for", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L492-L498
15,938
wmayner/pyphi
pyphi/subsystem.py
Subsystem.cause_effect_info
def cause_effect_info(self, mechanism, purview): """Return the cause-effect information for a mechanism over a purview. This is the minimum of the cause and effect information. """ return min(self.cause_info(mechanism, purview), self.effect_info(mechanism, purview))
python
def cause_effect_info(self, mechanism, purview): """Return the cause-effect information for a mechanism over a purview. This is the minimum of the cause and effect information. """ return min(self.cause_info(mechanism, purview), self.effect_info(mechanism, purview))
[ "def", "cause_effect_info", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "min", "(", "self", ".", "cause_info", "(", "mechanism", ",", "purview", ")", ",", "self", ".", "effect_info", "(", "mechanism", ",", "purview", ")", ")" ]
Return the cause-effect information for a mechanism over a purview. This is the minimum of the cause and effect information.
[ "Return", "the", "cause", "-", "effect", "information", "for", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L500-L506
15,939
wmayner/pyphi
pyphi/subsystem.py
Subsystem.evaluate_partition
def evaluate_partition(self, direction, mechanism, purview, partition, repertoire=None): """Return the |small_phi| of a mechanism over a purview for the given partition. Args: direction (Direction): |CAUSE| or |EFFECT|. mechanism (tuple[int]): The nodes in the mechanism. purview (tuple[int]): The nodes in the purview. partition (Bipartition): The partition to evaluate. Keyword Args: repertoire (np.array): The unpartitioned repertoire. If not supplied, it will be computed. Returns: tuple[int, np.ndarray]: The distance between the unpartitioned and partitioned repertoires, and the partitioned repertoire. """ if repertoire is None: repertoire = self.repertoire(direction, mechanism, purview) partitioned_repertoire = self.partitioned_repertoire(direction, partition) phi = repertoire_distance( direction, repertoire, partitioned_repertoire) return (phi, partitioned_repertoire)
python
def evaluate_partition(self, direction, mechanism, purview, partition, repertoire=None): """Return the |small_phi| of a mechanism over a purview for the given partition. Args: direction (Direction): |CAUSE| or |EFFECT|. mechanism (tuple[int]): The nodes in the mechanism. purview (tuple[int]): The nodes in the purview. partition (Bipartition): The partition to evaluate. Keyword Args: repertoire (np.array): The unpartitioned repertoire. If not supplied, it will be computed. Returns: tuple[int, np.ndarray]: The distance between the unpartitioned and partitioned repertoires, and the partitioned repertoire. """ if repertoire is None: repertoire = self.repertoire(direction, mechanism, purview) partitioned_repertoire = self.partitioned_repertoire(direction, partition) phi = repertoire_distance( direction, repertoire, partitioned_repertoire) return (phi, partitioned_repertoire)
[ "def", "evaluate_partition", "(", "self", ",", "direction", ",", "mechanism", ",", "purview", ",", "partition", ",", "repertoire", "=", "None", ")", ":", "if", "repertoire", "is", "None", ":", "repertoire", "=", "self", ".", "repertoire", "(", "direction", ",", "mechanism", ",", "purview", ")", "partitioned_repertoire", "=", "self", ".", "partitioned_repertoire", "(", "direction", ",", "partition", ")", "phi", "=", "repertoire_distance", "(", "direction", ",", "repertoire", ",", "partitioned_repertoire", ")", "return", "(", "phi", ",", "partitioned_repertoire", ")" ]
Return the |small_phi| of a mechanism over a purview for the given partition. Args: direction (Direction): |CAUSE| or |EFFECT|. mechanism (tuple[int]): The nodes in the mechanism. purview (tuple[int]): The nodes in the purview. partition (Bipartition): The partition to evaluate. Keyword Args: repertoire (np.array): The unpartitioned repertoire. If not supplied, it will be computed. Returns: tuple[int, np.ndarray]: The distance between the unpartitioned and partitioned repertoires, and the partitioned repertoire.
[ "Return", "the", "|small_phi|", "of", "a", "mechanism", "over", "a", "purview", "for", "the", "given", "partition", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L511-L539
15,940
wmayner/pyphi
pyphi/subsystem.py
Subsystem.find_mip
def find_mip(self, direction, mechanism, purview): """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: RepertoireIrreducibilityAnalysis: The irreducibility analysis for the mininum-information partition in one temporal direction. """ 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) def _mip(phi, partition, partitioned_repertoire): # Prototype of MIP with already known data # TODO: Use properties here to infer mechanism and purview from # partition yet access them with `.mechanism` and `.purview`. return RepertoireIrreducibilityAnalysis( phi=phi, direction=direction, mechanism=mechanism, purview=purview, partition=partition, repertoire=repertoire, partitioned_repertoire=partitioned_repertoire, node_labels=self.node_labels ) # State is unreachable - return 0 instead of giving nonsense results if (direction == Direction.CAUSE and np.all(repertoire == 0)): return _mip(0, None, None) mip = _null_ria(direction, mechanism, purview, phi=float('inf')) for partition in mip_partitions(mechanism, purview, self.node_labels): # Find the distance between the unpartitioned and partitioned # repertoire. phi, partitioned_repertoire = self.evaluate_partition( direction, mechanism, purview, partition, repertoire=repertoire) # Return immediately if mechanism is reducible. if phi == 0: return _mip(0.0, partition, partitioned_repertoire) # Update MIP if it's more minimal. if phi < mip.phi: mip = _mip(phi, partition, partitioned_repertoire) return mip
python
def find_mip(self, direction, mechanism, purview): """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: RepertoireIrreducibilityAnalysis: The irreducibility analysis for the mininum-information partition in one temporal direction. """ 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) def _mip(phi, partition, partitioned_repertoire): # Prototype of MIP with already known data # TODO: Use properties here to infer mechanism and purview from # partition yet access them with `.mechanism` and `.purview`. return RepertoireIrreducibilityAnalysis( phi=phi, direction=direction, mechanism=mechanism, purview=purview, partition=partition, repertoire=repertoire, partitioned_repertoire=partitioned_repertoire, node_labels=self.node_labels ) # State is unreachable - return 0 instead of giving nonsense results if (direction == Direction.CAUSE and np.all(repertoire == 0)): return _mip(0, None, None) mip = _null_ria(direction, mechanism, purview, phi=float('inf')) for partition in mip_partitions(mechanism, purview, self.node_labels): # Find the distance between the unpartitioned and partitioned # repertoire. phi, partitioned_repertoire = self.evaluate_partition( direction, mechanism, purview, partition, repertoire=repertoire) # Return immediately if mechanism is reducible. if phi == 0: return _mip(0.0, partition, partitioned_repertoire) # Update MIP if it's more minimal. if phi < mip.phi: mip = _mip(phi, partition, partitioned_repertoire) return mip
[ "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", ")", "def", "_mip", "(", "phi", ",", "partition", ",", "partitioned_repertoire", ")", ":", "# Prototype of MIP with already known data", "# TODO: Use properties here to infer mechanism and purview from", "# partition yet access them with `.mechanism` and `.purview`.", "return", "RepertoireIrreducibilityAnalysis", "(", "phi", "=", "phi", ",", "direction", "=", "direction", ",", "mechanism", "=", "mechanism", ",", "purview", "=", "purview", ",", "partition", "=", "partition", ",", "repertoire", "=", "repertoire", ",", "partitioned_repertoire", "=", "partitioned_repertoire", ",", "node_labels", "=", "self", ".", "node_labels", ")", "# State is unreachable - return 0 instead of giving nonsense results", "if", "(", "direction", "==", "Direction", ".", "CAUSE", "and", "np", ".", "all", "(", "repertoire", "==", "0", ")", ")", ":", "return", "_mip", "(", "0", ",", "None", ",", "None", ")", "mip", "=", "_null_ria", "(", "direction", ",", "mechanism", ",", "purview", ",", "phi", "=", "float", "(", "'inf'", ")", ")", "for", "partition", "in", "mip_partitions", "(", "mechanism", ",", "purview", ",", "self", ".", "node_labels", ")", ":", "# Find the distance between the unpartitioned and partitioned", "# repertoire.", "phi", ",", "partitioned_repertoire", "=", "self", ".", "evaluate_partition", "(", "direction", ",", "mechanism", ",", "purview", ",", "partition", ",", "repertoire", "=", "repertoire", ")", "# Return immediately if mechanism is reducible.", "if", "phi", "==", "0", ":", "return", "_mip", "(", "0.0", ",", "partition", ",", "partitioned_repertoire", ")", "# Update MIP if it's more minimal.", "if", "phi", "<", "mip", ".", "phi", ":", "mip", "=", "_mip", "(", "phi", ",", "partition", ",", "partitioned_repertoire", ")", "return", "mip" ]
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: RepertoireIrreducibilityAnalysis: The irreducibility analysis for the mininum-information partition in one temporal direction.
[ "Return", "the", "minimum", "information", "partition", "for", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L541-L598
15,941
wmayner/pyphi
pyphi/subsystem.py
Subsystem.cause_mip
def cause_mip(self, mechanism, purview): """Return the irreducibility analysis for the cause MIP. Alias for |find_mip()| with ``direction`` set to |CAUSE|. """ return self.find_mip(Direction.CAUSE, mechanism, purview)
python
def cause_mip(self, mechanism, purview): """Return the irreducibility analysis for the cause MIP. Alias for |find_mip()| with ``direction`` set to |CAUSE|. """ return self.find_mip(Direction.CAUSE, mechanism, purview)
[ "def", "cause_mip", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "self", ".", "find_mip", "(", "Direction", ".", "CAUSE", ",", "mechanism", ",", "purview", ")" ]
Return the irreducibility analysis for the cause MIP. Alias for |find_mip()| with ``direction`` set to |CAUSE|.
[ "Return", "the", "irreducibility", "analysis", "for", "the", "cause", "MIP", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L600-L605
15,942
wmayner/pyphi
pyphi/subsystem.py
Subsystem.effect_mip
def effect_mip(self, mechanism, purview): """Return the irreducibility analysis for the effect MIP. Alias for |find_mip()| with ``direction`` set to |EFFECT|. """ return self.find_mip(Direction.EFFECT, mechanism, purview)
python
def effect_mip(self, mechanism, purview): """Return the irreducibility analysis for the effect MIP. Alias for |find_mip()| with ``direction`` set to |EFFECT|. """ return self.find_mip(Direction.EFFECT, mechanism, purview)
[ "def", "effect_mip", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "self", ".", "find_mip", "(", "Direction", ".", "EFFECT", ",", "mechanism", ",", "purview", ")" ]
Return the irreducibility analysis for the effect MIP. Alias for |find_mip()| with ``direction`` set to |EFFECT|.
[ "Return", "the", "irreducibility", "analysis", "for", "the", "effect", "MIP", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L607-L612
15,943
wmayner/pyphi
pyphi/subsystem.py
Subsystem.phi_cause_mip
def phi_cause_mip(self, mechanism, purview): """Return the |small_phi| of the cause MIP. This is the distance between the unpartitioned cause repertoire and the MIP cause repertoire. """ mip = self.cause_mip(mechanism, purview) return mip.phi if mip else 0
python
def phi_cause_mip(self, mechanism, purview): """Return the |small_phi| of the cause MIP. This is the distance between the unpartitioned cause repertoire and the MIP cause repertoire. """ mip = self.cause_mip(mechanism, purview) return mip.phi if mip else 0
[ "def", "phi_cause_mip", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "mip", "=", "self", ".", "cause_mip", "(", "mechanism", ",", "purview", ")", "return", "mip", ".", "phi", "if", "mip", "else", "0" ]
Return the |small_phi| of the cause MIP. This is the distance between the unpartitioned cause repertoire and the MIP cause repertoire.
[ "Return", "the", "|small_phi|", "of", "the", "cause", "MIP", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L614-L621
15,944
wmayner/pyphi
pyphi/subsystem.py
Subsystem.phi_effect_mip
def phi_effect_mip(self, mechanism, purview): """Return the |small_phi| of the effect MIP. This is the distance between the unpartitioned effect repertoire and the MIP cause repertoire. """ mip = self.effect_mip(mechanism, purview) return mip.phi if mip else 0
python
def phi_effect_mip(self, mechanism, purview): """Return the |small_phi| of the effect MIP. This is the distance between the unpartitioned effect repertoire and the MIP cause repertoire. """ mip = self.effect_mip(mechanism, purview) return mip.phi if mip else 0
[ "def", "phi_effect_mip", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "mip", "=", "self", ".", "effect_mip", "(", "mechanism", ",", "purview", ")", "return", "mip", ".", "phi", "if", "mip", "else", "0" ]
Return the |small_phi| of the effect MIP. This is the distance between the unpartitioned effect repertoire and the MIP cause repertoire.
[ "Return", "the", "|small_phi|", "of", "the", "effect", "MIP", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L623-L630
15,945
wmayner/pyphi
pyphi/subsystem.py
Subsystem.phi
def phi(self, mechanism, purview): """Return the |small_phi| of a mechanism over a purview.""" return min(self.phi_cause_mip(mechanism, purview), self.phi_effect_mip(mechanism, purview))
python
def phi(self, mechanism, purview): """Return the |small_phi| of a mechanism over a purview.""" return min(self.phi_cause_mip(mechanism, purview), self.phi_effect_mip(mechanism, purview))
[ "def", "phi", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "return", "min", "(", "self", ".", "phi_cause_mip", "(", "mechanism", ",", "purview", ")", ",", "self", ".", "phi_effect_mip", "(", "mechanism", ",", "purview", ")", ")" ]
Return the |small_phi| of a mechanism over a purview.
[ "Return", "the", "|small_phi|", "of", "a", "mechanism", "over", "a", "purview", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L632-L635
15,946
wmayner/pyphi
pyphi/subsystem.py
Subsystem.find_mice
def find_mice(self, direction, mechanism, purviews=False): """Return the |MIC| or |MIE| for a mechanism. Args: direction (Direction): :|CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism to be tested for irreducibility. Keyword Args: purviews (tuple[int]): Optionally restrict the possible purviews to a subset of the subsystem. This may be useful for _e.g._ finding only concepts that are "about" a certain subset of nodes. Returns: MaximallyIrreducibleCauseOrEffect: The |MIC| or |MIE|. """ purviews = self.potential_purviews(direction, mechanism, purviews) if not purviews: max_mip = _null_ria(direction, mechanism, ()) else: max_mip = max(self.find_mip(direction, mechanism, purview) for purview in purviews) if direction == Direction.CAUSE: return MaximallyIrreducibleCause(max_mip) elif direction == Direction.EFFECT: return MaximallyIrreducibleEffect(max_mip) return validate.direction(direction)
python
def find_mice(self, direction, mechanism, purviews=False): """Return the |MIC| or |MIE| for a mechanism. Args: direction (Direction): :|CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism to be tested for irreducibility. Keyword Args: purviews (tuple[int]): Optionally restrict the possible purviews to a subset of the subsystem. This may be useful for _e.g._ finding only concepts that are "about" a certain subset of nodes. Returns: MaximallyIrreducibleCauseOrEffect: The |MIC| or |MIE|. """ purviews = self.potential_purviews(direction, mechanism, purviews) if not purviews: max_mip = _null_ria(direction, mechanism, ()) else: max_mip = max(self.find_mip(direction, mechanism, purview) for purview in purviews) if direction == Direction.CAUSE: return MaximallyIrreducibleCause(max_mip) elif direction == Direction.EFFECT: return MaximallyIrreducibleEffect(max_mip) return validate.direction(direction)
[ "def", "find_mice", "(", "self", ",", "direction", ",", "mechanism", ",", "purviews", "=", "False", ")", ":", "purviews", "=", "self", ".", "potential_purviews", "(", "direction", ",", "mechanism", ",", "purviews", ")", "if", "not", "purviews", ":", "max_mip", "=", "_null_ria", "(", "direction", ",", "mechanism", ",", "(", ")", ")", "else", ":", "max_mip", "=", "max", "(", "self", ".", "find_mip", "(", "direction", ",", "mechanism", ",", "purview", ")", "for", "purview", "in", "purviews", ")", "if", "direction", "==", "Direction", ".", "CAUSE", ":", "return", "MaximallyIrreducibleCause", "(", "max_mip", ")", "elif", "direction", "==", "Direction", ".", "EFFECT", ":", "return", "MaximallyIrreducibleEffect", "(", "max_mip", ")", "return", "validate", ".", "direction", "(", "direction", ")" ]
Return the |MIC| or |MIE| for a mechanism. Args: direction (Direction): :|CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism to be tested for irreducibility. Keyword Args: purviews (tuple[int]): Optionally restrict the possible purviews to a subset of the subsystem. This may be useful for _e.g._ finding only concepts that are "about" a certain subset of nodes. Returns: MaximallyIrreducibleCauseOrEffect: The |MIC| or |MIE|.
[ "Return", "the", "|MIC|", "or", "|MIE|", "for", "a", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L664-L693
15,947
wmayner/pyphi
pyphi/subsystem.py
Subsystem.phi_max
def phi_max(self, mechanism): """Return the |small_phi_max| of a mechanism. This is the maximum of |small_phi| taken over all possible purviews. """ return min(self.mic(mechanism).phi, self.mie(mechanism).phi)
python
def phi_max(self, mechanism): """Return the |small_phi_max| of a mechanism. This is the maximum of |small_phi| taken over all possible purviews. """ return min(self.mic(mechanism).phi, self.mie(mechanism).phi)
[ "def", "phi_max", "(", "self", ",", "mechanism", ")", ":", "return", "min", "(", "self", ".", "mic", "(", "mechanism", ")", ".", "phi", ",", "self", ".", "mie", "(", "mechanism", ")", ".", "phi", ")" ]
Return the |small_phi_max| of a mechanism. This is the maximum of |small_phi| taken over all possible purviews.
[ "Return", "the", "|small_phi_max|", "of", "a", "mechanism", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L709-L714
15,948
wmayner/pyphi
pyphi/subsystem.py
Subsystem.null_concept
def null_concept(self): """Return the null concept of this subsystem. The null concept is a point in concept space identified with the unconstrained cause and effect repertoire of this subsystem. """ # Unconstrained cause repertoire. cause_repertoire = self.cause_repertoire((), ()) # Unconstrained effect repertoire. effect_repertoire = self.effect_repertoire((), ()) # Null cause. cause = MaximallyIrreducibleCause( _null_ria(Direction.CAUSE, (), (), cause_repertoire)) # Null effect. effect = MaximallyIrreducibleEffect( _null_ria(Direction.EFFECT, (), (), effect_repertoire)) # All together now... return Concept(mechanism=(), cause=cause, effect=effect, subsystem=self)
python
def null_concept(self): """Return the null concept of this subsystem. The null concept is a point in concept space identified with the unconstrained cause and effect repertoire of this subsystem. """ # Unconstrained cause repertoire. cause_repertoire = self.cause_repertoire((), ()) # Unconstrained effect repertoire. effect_repertoire = self.effect_repertoire((), ()) # Null cause. cause = MaximallyIrreducibleCause( _null_ria(Direction.CAUSE, (), (), cause_repertoire)) # Null effect. effect = MaximallyIrreducibleEffect( _null_ria(Direction.EFFECT, (), (), effect_repertoire)) # All together now... return Concept(mechanism=(), cause=cause, effect=effect, subsystem=self)
[ "def", "null_concept", "(", "self", ")", ":", "# Unconstrained cause repertoire.", "cause_repertoire", "=", "self", ".", "cause_repertoire", "(", "(", ")", ",", "(", ")", ")", "# Unconstrained effect repertoire.", "effect_repertoire", "=", "self", ".", "effect_repertoire", "(", "(", ")", ",", "(", ")", ")", "# Null cause.", "cause", "=", "MaximallyIrreducibleCause", "(", "_null_ria", "(", "Direction", ".", "CAUSE", ",", "(", ")", ",", "(", ")", ",", "cause_repertoire", ")", ")", "# Null effect.", "effect", "=", "MaximallyIrreducibleEffect", "(", "_null_ria", "(", "Direction", ".", "EFFECT", ",", "(", ")", ",", "(", ")", ",", "effect_repertoire", ")", ")", "# All together now...", "return", "Concept", "(", "mechanism", "=", "(", ")", ",", "cause", "=", "cause", ",", "effect", "=", "effect", ",", "subsystem", "=", "self", ")" ]
Return the null concept of this subsystem. The null concept is a point in concept space identified with the unconstrained cause and effect repertoire of this subsystem.
[ "Return", "the", "null", "concept", "of", "this", "subsystem", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L720-L742
15,949
wmayner/pyphi
pyphi/subsystem.py
Subsystem.concept
def concept(self, mechanism, purviews=False, cause_purviews=False, effect_purviews=False): """Return the concept specified by a mechanism within this subsytem. Args: mechanism (tuple[int]): The candidate set of nodes. Keyword Args: purviews (tuple[tuple[int]]): Restrict the possible purviews to those in this list. cause_purviews (tuple[tuple[int]]): Restrict the possible cause purviews to those in this list. Takes precedence over ``purviews``. effect_purviews (tuple[tuple[int]]): Restrict the possible effect purviews to those in this list. Takes precedence over ``purviews``. Returns: Concept: The pair of maximally irreducible cause/effect repertoires that constitute the concept specified by the given mechanism. """ log.debug('Computing concept %s...', mechanism) # If the mechanism is empty, there is no concept. if not mechanism: log.debug('Empty concept; returning null concept') return self.null_concept # Calculate the maximally irreducible cause repertoire. cause = self.mic(mechanism, purviews=(cause_purviews or purviews)) # Calculate the maximally irreducible effect repertoire. effect = self.mie(mechanism, purviews=(effect_purviews or purviews)) log.debug('Found concept %s', mechanism) # NOTE: Make sure to expand the repertoires to the size of the # subsystem when calculating concept distance. For now, they must # remain un-expanded so the concept doesn't depend on the subsystem. return Concept(mechanism=mechanism, cause=cause, effect=effect, subsystem=self)
python
def concept(self, mechanism, purviews=False, cause_purviews=False, effect_purviews=False): """Return the concept specified by a mechanism within this subsytem. Args: mechanism (tuple[int]): The candidate set of nodes. Keyword Args: purviews (tuple[tuple[int]]): Restrict the possible purviews to those in this list. cause_purviews (tuple[tuple[int]]): Restrict the possible cause purviews to those in this list. Takes precedence over ``purviews``. effect_purviews (tuple[tuple[int]]): Restrict the possible effect purviews to those in this list. Takes precedence over ``purviews``. Returns: Concept: The pair of maximally irreducible cause/effect repertoires that constitute the concept specified by the given mechanism. """ log.debug('Computing concept %s...', mechanism) # If the mechanism is empty, there is no concept. if not mechanism: log.debug('Empty concept; returning null concept') return self.null_concept # Calculate the maximally irreducible cause repertoire. cause = self.mic(mechanism, purviews=(cause_purviews or purviews)) # Calculate the maximally irreducible effect repertoire. effect = self.mie(mechanism, purviews=(effect_purviews or purviews)) log.debug('Found concept %s', mechanism) # NOTE: Make sure to expand the repertoires to the size of the # subsystem when calculating concept distance. For now, they must # remain un-expanded so the concept doesn't depend on the subsystem. return Concept(mechanism=mechanism, cause=cause, effect=effect, subsystem=self)
[ "def", "concept", "(", "self", ",", "mechanism", ",", "purviews", "=", "False", ",", "cause_purviews", "=", "False", ",", "effect_purviews", "=", "False", ")", ":", "log", ".", "debug", "(", "'Computing concept %s...'", ",", "mechanism", ")", "# If the mechanism is empty, there is no concept.", "if", "not", "mechanism", ":", "log", ".", "debug", "(", "'Empty concept; returning null concept'", ")", "return", "self", ".", "null_concept", "# Calculate the maximally irreducible cause repertoire.", "cause", "=", "self", ".", "mic", "(", "mechanism", ",", "purviews", "=", "(", "cause_purviews", "or", "purviews", ")", ")", "# Calculate the maximally irreducible effect repertoire.", "effect", "=", "self", ".", "mie", "(", "mechanism", ",", "purviews", "=", "(", "effect_purviews", "or", "purviews", ")", ")", "log", ".", "debug", "(", "'Found concept %s'", ",", "mechanism", ")", "# NOTE: Make sure to expand the repertoires to the size of the", "# subsystem when calculating concept distance. For now, they must", "# remain un-expanded so the concept doesn't depend on the subsystem.", "return", "Concept", "(", "mechanism", "=", "mechanism", ",", "cause", "=", "cause", ",", "effect", "=", "effect", ",", "subsystem", "=", "self", ")" ]
Return the concept specified by a mechanism within this subsytem. Args: mechanism (tuple[int]): The candidate set of nodes. Keyword Args: purviews (tuple[tuple[int]]): Restrict the possible purviews to those in this list. cause_purviews (tuple[tuple[int]]): Restrict the possible cause purviews to those in this list. Takes precedence over ``purviews``. effect_purviews (tuple[tuple[int]]): Restrict the possible effect purviews to those in this list. Takes precedence over ``purviews``. Returns: Concept: The pair of maximally irreducible cause/effect repertoires that constitute the concept specified by the given mechanism.
[ "Return", "the", "concept", "specified", "by", "a", "mechanism", "within", "this", "subsytem", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L745-L785
15,950
wmayner/pyphi
pyphi/models/actual_causation.py
_null_ac_sia
def _null_ac_sia(transition, direction, alpha=0.0): """Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and empty accounts. """ return AcSystemIrreducibilityAnalysis( transition=transition, direction=direction, alpha=alpha, account=(), partitioned_account=() )
python
def _null_ac_sia(transition, direction, alpha=0.0): """Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and empty accounts. """ return AcSystemIrreducibilityAnalysis( transition=transition, direction=direction, alpha=alpha, account=(), partitioned_account=() )
[ "def", "_null_ac_sia", "(", "transition", ",", "direction", ",", "alpha", "=", "0.0", ")", ":", "return", "AcSystemIrreducibilityAnalysis", "(", "transition", "=", "transition", ",", "direction", "=", "direction", ",", "alpha", "=", "alpha", ",", "account", "=", "(", ")", ",", "partitioned_account", "=", "(", ")", ")" ]
Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and empty accounts.
[ "Return", "an", "|AcSystemIrreducibilityAnalysis|", "with", "zero", "|big_alpha|", "and", "empty", "accounts", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/actual_causation.py#L354-L364
15,951
wmayner/pyphi
pyphi/models/actual_causation.py
Event.mechanism
def mechanism(self): """The mechanism of the event.""" assert self.actual_cause.mechanism == self.actual_effect.mechanism return self.actual_cause.mechanism
python
def mechanism(self): """The mechanism of the event.""" assert self.actual_cause.mechanism == self.actual_effect.mechanism return self.actual_cause.mechanism
[ "def", "mechanism", "(", "self", ")", ":", "assert", "self", ".", "actual_cause", ".", "mechanism", "==", "self", ".", "actual_effect", ".", "mechanism", "return", "self", ".", "actual_cause", ".", "mechanism" ]
The mechanism of the event.
[ "The", "mechanism", "of", "the", "event", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/actual_causation.py#L213-L216
15,952
wmayner/pyphi
pyphi/models/actual_causation.py
Account.irreducible_causes
def irreducible_causes(self): """The set of irreducible causes in this |Account|.""" return tuple(link for link in self if link.direction is Direction.CAUSE)
python
def irreducible_causes(self): """The set of irreducible causes in this |Account|.""" return tuple(link for link in self if link.direction is Direction.CAUSE)
[ "def", "irreducible_causes", "(", "self", ")", ":", "return", "tuple", "(", "link", "for", "link", "in", "self", "if", "link", ".", "direction", "is", "Direction", ".", "CAUSE", ")" ]
The set of irreducible causes in this |Account|.
[ "The", "set", "of", "irreducible", "causes", "in", "this", "|Account|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/actual_causation.py#L248-L251
15,953
wmayner/pyphi
pyphi/models/actual_causation.py
Account.irreducible_effects
def irreducible_effects(self): """The set of irreducible effects in this |Account|.""" return tuple(link for link in self if link.direction is Direction.EFFECT)
python
def irreducible_effects(self): """The set of irreducible effects in this |Account|.""" return tuple(link for link in self if link.direction is Direction.EFFECT)
[ "def", "irreducible_effects", "(", "self", ")", ":", "return", "tuple", "(", "link", "for", "link", "in", "self", "if", "link", ".", "direction", "is", "Direction", ".", "EFFECT", ")" ]
The set of irreducible effects in this |Account|.
[ "The", "set", "of", "irreducible", "effects", "in", "this", "|Account|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/actual_causation.py#L254-L257
15,954
wmayner/pyphi
pyphi/models/fmt.py
make_repr
def make_repr(self, attrs): """Construct a repr string. If `config.REPR_VERBOSITY` is ``1`` or ``2``, this function calls the object's __str__ method. Although this breaks the convention that __repr__ should return a string which can reconstruct the object, readable reprs are invaluable since the Python interpreter calls `repr` to represent all objects in the shell. Since PyPhi is often used in the interpreter we want to have meaningful and useful representations. Args: self (obj): The object in question attrs (Iterable[str]): Attributes to include in the repr Returns: str: the ``repr``esentation of the object """ # TODO: change this to a closure so we can do # __repr__ = make_repr(attrs) ??? if config.REPR_VERBOSITY in [MEDIUM, HIGH]: return self.__str__() elif config.REPR_VERBOSITY is LOW: return '{}({})'.format( self.__class__.__name__, ', '.join(attr + '=' + repr(getattr(self, attr)) for attr in attrs)) raise ValueError('Invalid value for `config.REPR_VERBOSITY`')
python
def make_repr(self, attrs): """Construct a repr string. If `config.REPR_VERBOSITY` is ``1`` or ``2``, this function calls the object's __str__ method. Although this breaks the convention that __repr__ should return a string which can reconstruct the object, readable reprs are invaluable since the Python interpreter calls `repr` to represent all objects in the shell. Since PyPhi is often used in the interpreter we want to have meaningful and useful representations. Args: self (obj): The object in question attrs (Iterable[str]): Attributes to include in the repr Returns: str: the ``repr``esentation of the object """ # TODO: change this to a closure so we can do # __repr__ = make_repr(attrs) ??? if config.REPR_VERBOSITY in [MEDIUM, HIGH]: return self.__str__() elif config.REPR_VERBOSITY is LOW: return '{}({})'.format( self.__class__.__name__, ', '.join(attr + '=' + repr(getattr(self, attr)) for attr in attrs)) raise ValueError('Invalid value for `config.REPR_VERBOSITY`')
[ "def", "make_repr", "(", "self", ",", "attrs", ")", ":", "# TODO: change this to a closure so we can do", "# __repr__ = make_repr(attrs) ???", "if", "config", ".", "REPR_VERBOSITY", "in", "[", "MEDIUM", ",", "HIGH", "]", ":", "return", "self", ".", "__str__", "(", ")", "elif", "config", ".", "REPR_VERBOSITY", "is", "LOW", ":", "return", "'{}({})'", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "', '", ".", "join", "(", "attr", "+", "'='", "+", "repr", "(", "getattr", "(", "self", ",", "attr", ")", ")", "for", "attr", "in", "attrs", ")", ")", "raise", "ValueError", "(", "'Invalid value for `config.REPR_VERBOSITY`'", ")" ]
Construct a repr string. If `config.REPR_VERBOSITY` is ``1`` or ``2``, this function calls the object's __str__ method. Although this breaks the convention that __repr__ should return a string which can reconstruct the object, readable reprs are invaluable since the Python interpreter calls `repr` to represent all objects in the shell. Since PyPhi is often used in the interpreter we want to have meaningful and useful representations. Args: self (obj): The object in question attrs (Iterable[str]): Attributes to include in the repr Returns: str: the ``repr``esentation of the object
[ "Construct", "a", "repr", "string", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L47-L76
15,955
wmayner/pyphi
pyphi/models/fmt.py
indent
def indent(lines, amount=2, char=' '): 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 indentation. Returns: str: The indented string. Example: >>> print(indent('line1\nline2', char='*')) **line1 **line2 """ lines = str(lines) padding = amount * char return padding + ('\n' + padding).join(lines.split('\n'))
python
def indent(lines, amount=2, char=' '): 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 indentation. Returns: str: The indented string. Example: >>> print(indent('line1\nline2', char='*')) **line1 **line2 """ lines = str(lines) padding = amount * char return padding + ('\n' + padding).join(lines.split('\n'))
[ "def", "indent", "(", "lines", ",", "amount", "=", "2", ",", "char", "=", "' '", ")", ":", "lines", "=", "str", "(", "lines", ")", "padding", "=", "amount", "*", "char", "return", "padding", "+", "(", "'\\n'", "+", "padding", ")", ".", "join", "(", "lines", ".", "split", "(", "'\\n'", ")", ")" ]
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 indentation. Returns: str: The indented string. Example: >>> print(indent('line1\nline2', char='*')) **line1 **line2
[ "r", "Indent", "a", "string", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L79-L102
15,956
wmayner/pyphi
pyphi/models/fmt.py
margin
def margin(text): r"""Add a margin to both ends of each line in the string. Example: >>> margin('line1\nline2') ' line1 \n line2 ' """ lines = str(text).split('\n') return '\n'.join(' {} '.format(l) for l in lines)
python
def margin(text): r"""Add a margin to both ends of each line in the string. Example: >>> margin('line1\nline2') ' line1 \n line2 ' """ lines = str(text).split('\n') return '\n'.join(' {} '.format(l) for l in lines)
[ "def", "margin", "(", "text", ")", ":", "lines", "=", "str", "(", "text", ")", ".", "split", "(", "'\\n'", ")", "return", "'\\n'", ".", "join", "(", "' {} '", ".", "format", "(", "l", ")", "for", "l", "in", "lines", ")" ]
r"""Add a margin to both ends of each line in the string. Example: >>> margin('line1\nline2') ' line1 \n line2 '
[ "r", "Add", "a", "margin", "to", "both", "ends", "of", "each", "line", "in", "the", "string", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L105-L113
15,957
wmayner/pyphi
pyphi/models/fmt.py
box
def box(text): r"""Wrap a chunk of text in a box. Example: >>> print(box('line1\nline2')) ┌───────┐ │ line1 │ │ line2 │ └───────┘ """ lines = text.split('\n') width = max(len(l) for l in lines) top_bar = (TOP_LEFT_CORNER + HORIZONTAL_BAR * (2 + width) + TOP_RIGHT_CORNER) bottom_bar = (BOTTOM_LEFT_CORNER + HORIZONTAL_BAR * (2 + width) + BOTTOM_RIGHT_CORNER) lines = [LINES_FORMAT_STR.format(line=line, width=width) for line in lines] return top_bar + '\n' + '\n'.join(lines) + '\n' + bottom_bar
python
def box(text): r"""Wrap a chunk of text in a box. Example: >>> print(box('line1\nline2')) ┌───────┐ │ line1 │ │ line2 │ └───────┘ """ lines = text.split('\n') width = max(len(l) for l in lines) top_bar = (TOP_LEFT_CORNER + HORIZONTAL_BAR * (2 + width) + TOP_RIGHT_CORNER) bottom_bar = (BOTTOM_LEFT_CORNER + HORIZONTAL_BAR * (2 + width) + BOTTOM_RIGHT_CORNER) lines = [LINES_FORMAT_STR.format(line=line, width=width) for line in lines] return top_bar + '\n' + '\n'.join(lines) + '\n' + bottom_bar
[ "def", "box", "(", "text", ")", ":", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "width", "=", "max", "(", "len", "(", "l", ")", "for", "l", "in", "lines", ")", "top_bar", "=", "(", "TOP_LEFT_CORNER", "+", "HORIZONTAL_BAR", "*", "(", "2", "+", "width", ")", "+", "TOP_RIGHT_CORNER", ")", "bottom_bar", "=", "(", "BOTTOM_LEFT_CORNER", "+", "HORIZONTAL_BAR", "*", "(", "2", "+", "width", ")", "+", "BOTTOM_RIGHT_CORNER", ")", "lines", "=", "[", "LINES_FORMAT_STR", ".", "format", "(", "line", "=", "line", ",", "width", "=", "width", ")", "for", "line", "in", "lines", "]", "return", "top_bar", "+", "'\\n'", "+", "'\\n'", ".", "join", "(", "lines", ")", "+", "'\\n'", "+", "bottom_bar" ]
r"""Wrap a chunk of text in a box. Example: >>> print(box('line1\nline2')) ┌───────┐ │ line1 │ │ line2 │ └───────┘
[ "r", "Wrap", "a", "chunk", "of", "text", "in", "a", "box", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L119-L139
15,958
wmayner/pyphi
pyphi/models/fmt.py
side_by_side
def side_by_side(left, right): r"""Put two boxes next to each other. Assumes that all lines in the boxes are the same width. Example: >>> left = 'A \nC ' >>> right = 'B\nD' >>> print(side_by_side(left, right)) A B C D <BLANKLINE> """ left_lines = list(left.split('\n')) right_lines = list(right.split('\n')) # Pad the shorter column with whitespace diff = abs(len(left_lines) - len(right_lines)) if len(left_lines) > len(right_lines): fill = ' ' * len(right_lines[0]) right_lines += [fill] * diff elif len(right_lines) > len(left_lines): fill = ' ' * len(left_lines[0]) left_lines += [fill] * diff return '\n'.join(a + b for a, b in zip(left_lines, right_lines)) + '\n'
python
def side_by_side(left, right): r"""Put two boxes next to each other. Assumes that all lines in the boxes are the same width. Example: >>> left = 'A \nC ' >>> right = 'B\nD' >>> print(side_by_side(left, right)) A B C D <BLANKLINE> """ left_lines = list(left.split('\n')) right_lines = list(right.split('\n')) # Pad the shorter column with whitespace diff = abs(len(left_lines) - len(right_lines)) if len(left_lines) > len(right_lines): fill = ' ' * len(right_lines[0]) right_lines += [fill] * diff elif len(right_lines) > len(left_lines): fill = ' ' * len(left_lines[0]) left_lines += [fill] * diff return '\n'.join(a + b for a, b in zip(left_lines, right_lines)) + '\n'
[ "def", "side_by_side", "(", "left", ",", "right", ")", ":", "left_lines", "=", "list", "(", "left", ".", "split", "(", "'\\n'", ")", ")", "right_lines", "=", "list", "(", "right", ".", "split", "(", "'\\n'", ")", ")", "# Pad the shorter column with whitespace", "diff", "=", "abs", "(", "len", "(", "left_lines", ")", "-", "len", "(", "right_lines", ")", ")", "if", "len", "(", "left_lines", ")", ">", "len", "(", "right_lines", ")", ":", "fill", "=", "' '", "*", "len", "(", "right_lines", "[", "0", "]", ")", "right_lines", "+=", "[", "fill", "]", "*", "diff", "elif", "len", "(", "right_lines", ")", ">", "len", "(", "left_lines", ")", ":", "fill", "=", "' '", "*", "len", "(", "left_lines", "[", "0", "]", ")", "left_lines", "+=", "[", "fill", "]", "*", "diff", "return", "'\\n'", ".", "join", "(", "a", "+", "b", "for", "a", ",", "b", "in", "zip", "(", "left_lines", ",", "right_lines", ")", ")", "+", "'\\n'" ]
r"""Put two boxes next to each other. Assumes that all lines in the boxes are the same width. Example: >>> left = 'A \nC ' >>> right = 'B\nD' >>> print(side_by_side(left, right)) A B C D <BLANKLINE>
[ "r", "Put", "two", "boxes", "next", "to", "each", "other", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L142-L167
15,959
wmayner/pyphi
pyphi/models/fmt.py
header
def header(head, text, over_char=None, under_char=None, center=True): """Center a head over a block of text. The width of the text is the width of the longest line of the text. """ lines = list(text.split('\n')) width = max(len(l) for l in lines) # Center or left-justify if center: head = head.center(width) + '\n' else: head = head.ljust(width) + '\n' # Underline head if under_char: head = head + under_char * width + '\n' # 'Overline' head if over_char: head = over_char * width + '\n' + head return head + text
python
def header(head, text, over_char=None, under_char=None, center=True): """Center a head over a block of text. The width of the text is the width of the longest line of the text. """ lines = list(text.split('\n')) width = max(len(l) for l in lines) # Center or left-justify if center: head = head.center(width) + '\n' else: head = head.ljust(width) + '\n' # Underline head if under_char: head = head + under_char * width + '\n' # 'Overline' head if over_char: head = over_char * width + '\n' + head return head + text
[ "def", "header", "(", "head", ",", "text", ",", "over_char", "=", "None", ",", "under_char", "=", "None", ",", "center", "=", "True", ")", ":", "lines", "=", "list", "(", "text", ".", "split", "(", "'\\n'", ")", ")", "width", "=", "max", "(", "len", "(", "l", ")", "for", "l", "in", "lines", ")", "# Center or left-justify", "if", "center", ":", "head", "=", "head", ".", "center", "(", "width", ")", "+", "'\\n'", "else", ":", "head", "=", "head", ".", "ljust", "(", "width", ")", "+", "'\\n'", "# Underline head", "if", "under_char", ":", "head", "=", "head", "+", "under_char", "*", "width", "+", "'\\n'", "# 'Overline' head", "if", "over_char", ":", "head", "=", "over_char", "*", "width", "+", "'\\n'", "+", "head", "return", "head", "+", "text" ]
Center a head over a block of text. The width of the text is the width of the longest line of the text.
[ "Center", "a", "head", "over", "a", "block", "of", "text", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L170-L192
15,960
wmayner/pyphi
pyphi/models/fmt.py
labels
def labels(indices, node_labels=None): """Get the labels for a tuple of mechanism indices.""" if node_labels is None: return tuple(map(str, indices)) return node_labels.indices2labels(indices)
python
def labels(indices, node_labels=None): """Get the labels for a tuple of mechanism indices.""" if node_labels is None: return tuple(map(str, indices)) return node_labels.indices2labels(indices)
[ "def", "labels", "(", "indices", ",", "node_labels", "=", "None", ")", ":", "if", "node_labels", "is", "None", ":", "return", "tuple", "(", "map", "(", "str", ",", "indices", ")", ")", "return", "node_labels", ".", "indices2labels", "(", "indices", ")" ]
Get the labels for a tuple of mechanism indices.
[ "Get", "the", "labels", "for", "a", "tuple", "of", "mechanism", "indices", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L195-L199
15,961
wmayner/pyphi
pyphi/models/fmt.py
fmt_number
def fmt_number(p): """Format a number. It will be printed as a fraction if the denominator isn't too big and as a decimal otherwise. """ formatted = '{:n}'.format(p) if not config.PRINT_FRACTIONS: return formatted fraction = Fraction(p) nice = fraction.limit_denominator(128) return ( str(nice) if (abs(fraction - nice) < constants.EPSILON and nice.denominator in NICE_DENOMINATORS) else formatted )
python
def fmt_number(p): """Format a number. It will be printed as a fraction if the denominator isn't too big and as a decimal otherwise. """ formatted = '{:n}'.format(p) if not config.PRINT_FRACTIONS: return formatted fraction = Fraction(p) nice = fraction.limit_denominator(128) return ( str(nice) if (abs(fraction - nice) < constants.EPSILON and nice.denominator in NICE_DENOMINATORS) else formatted )
[ "def", "fmt_number", "(", "p", ")", ":", "formatted", "=", "'{:n}'", ".", "format", "(", "p", ")", "if", "not", "config", ".", "PRINT_FRACTIONS", ":", "return", "formatted", "fraction", "=", "Fraction", "(", "p", ")", "nice", "=", "fraction", ".", "limit_denominator", "(", "128", ")", "return", "(", "str", "(", "nice", ")", "if", "(", "abs", "(", "fraction", "-", "nice", ")", "<", "constants", ".", "EPSILON", "and", "nice", ".", "denominator", "in", "NICE_DENOMINATORS", ")", "else", "formatted", ")" ]
Format a number. It will be printed as a fraction if the denominator isn't too big and as a decimal otherwise.
[ "Format", "a", "number", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L202-L219
15,962
wmayner/pyphi
pyphi/models/fmt.py
fmt_part
def fmt_part(part, node_labels=None): """Format a |Part|. The returned string looks like:: 0,1 ─── ∅ """ def nodes(x): # pylint: disable=missing-docstring return ','.join(labels(x, node_labels)) if x else EMPTY_SET numer = nodes(part.mechanism) denom = nodes(part.purview) width = max(3, len(numer), len(denom)) divider = HORIZONTAL_BAR * width return ( '{numer:^{width}}\n' '{divider}\n' '{denom:^{width}}' ).format(numer=numer, divider=divider, denom=denom, width=width)
python
def fmt_part(part, node_labels=None): """Format a |Part|. The returned string looks like:: 0,1 ─── ∅ """ def nodes(x): # pylint: disable=missing-docstring return ','.join(labels(x, node_labels)) if x else EMPTY_SET numer = nodes(part.mechanism) denom = nodes(part.purview) width = max(3, len(numer), len(denom)) divider = HORIZONTAL_BAR * width return ( '{numer:^{width}}\n' '{divider}\n' '{denom:^{width}}' ).format(numer=numer, divider=divider, denom=denom, width=width)
[ "def", "fmt_part", "(", "part", ",", "node_labels", "=", "None", ")", ":", "def", "nodes", "(", "x", ")", ":", "# pylint: disable=missing-docstring", "return", "','", ".", "join", "(", "labels", "(", "x", ",", "node_labels", ")", ")", "if", "x", "else", "EMPTY_SET", "numer", "=", "nodes", "(", "part", ".", "mechanism", ")", "denom", "=", "nodes", "(", "part", ".", "purview", ")", "width", "=", "max", "(", "3", ",", "len", "(", "numer", ")", ",", "len", "(", "denom", ")", ")", "divider", "=", "HORIZONTAL_BAR", "*", "width", "return", "(", "'{numer:^{width}}\\n'", "'{divider}\\n'", "'{denom:^{width}}'", ")", ".", "format", "(", "numer", "=", "numer", ",", "divider", "=", "divider", ",", "denom", "=", "denom", ",", "width", "=", "width", ")" ]
Format a |Part|. The returned string looks like:: 0,1 ─── ∅
[ "Format", "a", "|Part|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L227-L249
15,963
wmayner/pyphi
pyphi/models/fmt.py
fmt_partition
def fmt_partition(partition): """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. """ 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 between = [times] * (len(parts) - 1) + [breaks] # Alternate [part, break, part, ..., end] elements = chain.from_iterable(zip(parts, between)) # Transform vertical stacks into horizontal lines return ''.join(chain.from_iterable(zip(*elements)))
python
def fmt_partition(partition): """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. """ 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 between = [times] * (len(parts) - 1) + [breaks] # Alternate [part, break, part, ..., end] elements = chain.from_iterable(zip(parts, between)) # Transform vertical stacks into horizontal lines return ''.join(chain.from_iterable(zip(*elements)))
[ "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", "between", "=", "[", "times", "]", "*", "(", "len", "(", "parts", ")", "-", "1", ")", "+", "[", "breaks", "]", "# Alternate [part, break, part, ..., end]", "elements", "=", "chain", ".", "from_iterable", "(", "zip", "(", "parts", ",", "between", ")", ")", "# Transform vertical stacks into horizontal lines", "return", "''", ".", "join", "(", "chain", ".", "from_iterable", "(", "zip", "(", "*", "elements", ")", ")", ")" ]
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.
[ "Format", "a", "|Bipartition|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L252-L283
15,964
wmayner/pyphi
pyphi/models/fmt.py
fmt_ces
def fmt_ces(c, title=None): """Format a |CauseEffectStructure|.""" if not c: return '()\n' if title is None: title = 'Cause-effect structure' concepts = '\n'.join(margin(x) for x in c) + '\n' title = '{} ({} concept{})'.format( title, len(c), '' if len(c) == 1 else 's') return header(title, concepts, HEADER_BAR_1, HEADER_BAR_1)
python
def fmt_ces(c, title=None): """Format a |CauseEffectStructure|.""" if not c: return '()\n' if title is None: title = 'Cause-effect structure' concepts = '\n'.join(margin(x) for x in c) + '\n' title = '{} ({} concept{})'.format( title, len(c), '' if len(c) == 1 else 's') return header(title, concepts, HEADER_BAR_1, HEADER_BAR_1)
[ "def", "fmt_ces", "(", "c", ",", "title", "=", "None", ")", ":", "if", "not", "c", ":", "return", "'()\\n'", "if", "title", "is", "None", ":", "title", "=", "'Cause-effect structure'", "concepts", "=", "'\\n'", ".", "join", "(", "margin", "(", "x", ")", "for", "x", "in", "c", ")", "+", "'\\n'", "title", "=", "'{} ({} concept{})'", ".", "format", "(", "title", ",", "len", "(", "c", ")", ",", "''", "if", "len", "(", "c", ")", "==", "1", "else", "'s'", ")", "return", "header", "(", "title", ",", "concepts", ",", "HEADER_BAR_1", ",", "HEADER_BAR_1", ")" ]
Format a |CauseEffectStructure|.
[ "Format", "a", "|CauseEffectStructure|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L286-L298
15,965
wmayner/pyphi
pyphi/models/fmt.py
fmt_concept
def fmt_concept(concept): """Format a |Concept|.""" def fmt_cause_or_effect(x): # pylint: disable=missing-docstring return box(indent(fmt_ria(x.ria, verbose=False, mip=True), amount=1)) cause = header('MIC', fmt_cause_or_effect(concept.cause)) effect = header('MIE', fmt_cause_or_effect(concept.effect)) ce = side_by_side(cause, effect) mechanism = fmt_mechanism(concept.mechanism, concept.node_labels) title = 'Concept: Mechanism = {}, {} = {}'.format( mechanism, SMALL_PHI, fmt_number(concept.phi)) # Only center headers for high-verbosity output center = config.REPR_VERBOSITY is HIGH return header(title, ce, HEADER_BAR_2, HEADER_BAR_2, center=center)
python
def fmt_concept(concept): """Format a |Concept|.""" def fmt_cause_or_effect(x): # pylint: disable=missing-docstring return box(indent(fmt_ria(x.ria, verbose=False, mip=True), amount=1)) cause = header('MIC', fmt_cause_or_effect(concept.cause)) effect = header('MIE', fmt_cause_or_effect(concept.effect)) ce = side_by_side(cause, effect) mechanism = fmt_mechanism(concept.mechanism, concept.node_labels) title = 'Concept: Mechanism = {}, {} = {}'.format( mechanism, SMALL_PHI, fmt_number(concept.phi)) # Only center headers for high-verbosity output center = config.REPR_VERBOSITY is HIGH return header(title, ce, HEADER_BAR_2, HEADER_BAR_2, center=center)
[ "def", "fmt_concept", "(", "concept", ")", ":", "def", "fmt_cause_or_effect", "(", "x", ")", ":", "# pylint: disable=missing-docstring", "return", "box", "(", "indent", "(", "fmt_ria", "(", "x", ".", "ria", ",", "verbose", "=", "False", ",", "mip", "=", "True", ")", ",", "amount", "=", "1", ")", ")", "cause", "=", "header", "(", "'MIC'", ",", "fmt_cause_or_effect", "(", "concept", ".", "cause", ")", ")", "effect", "=", "header", "(", "'MIE'", ",", "fmt_cause_or_effect", "(", "concept", ".", "effect", ")", ")", "ce", "=", "side_by_side", "(", "cause", ",", "effect", ")", "mechanism", "=", "fmt_mechanism", "(", "concept", ".", "mechanism", ",", "concept", ".", "node_labels", ")", "title", "=", "'Concept: Mechanism = {}, {} = {}'", ".", "format", "(", "mechanism", ",", "SMALL_PHI", ",", "fmt_number", "(", "concept", ".", "phi", ")", ")", "# Only center headers for high-verbosity output", "center", "=", "config", ".", "REPR_VERBOSITY", "is", "HIGH", "return", "header", "(", "title", ",", "ce", ",", "HEADER_BAR_2", ",", "HEADER_BAR_2", ",", "center", "=", "center", ")" ]
Format a |Concept|.
[ "Format", "a", "|Concept|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L301-L318
15,966
wmayner/pyphi
pyphi/models/fmt.py
fmt_ria
def fmt_ria(ria, verbose=True, mip=False): """Format a |RepertoireIrreducibilityAnalysis|.""" if verbose: mechanism = 'Mechanism: {}\n'.format( fmt_mechanism(ria.mechanism, ria.node_labels)) direction = '\nDirection: {}'.format(ria.direction) else: mechanism = '' direction = '' if config.REPR_VERBOSITY is HIGH: partition = '\n{}:\n{}'.format( ('MIP' if mip else 'Partition'), indent(fmt_partition(ria.partition))) repertoire = '\nRepertoire:\n{}'.format( indent(fmt_repertoire(ria.repertoire))) partitioned_repertoire = '\nPartitioned repertoire:\n{}'.format( indent(fmt_repertoire(ria.partitioned_repertoire))) else: partition = '' repertoire = '' partitioned_repertoire = '' # TODO? print the two repertoires side-by-side return ( '{SMALL_PHI} = {phi}\n' '{mechanism}' 'Purview = {purview}' '{direction}' '{partition}' '{repertoire}' '{partitioned_repertoire}').format( SMALL_PHI=SMALL_PHI, mechanism=mechanism, purview=fmt_mechanism(ria.purview, ria.node_labels), direction=direction, phi=fmt_number(ria.phi), partition=partition, repertoire=repertoire, partitioned_repertoire=partitioned_repertoire)
python
def fmt_ria(ria, verbose=True, mip=False): """Format a |RepertoireIrreducibilityAnalysis|.""" if verbose: mechanism = 'Mechanism: {}\n'.format( fmt_mechanism(ria.mechanism, ria.node_labels)) direction = '\nDirection: {}'.format(ria.direction) else: mechanism = '' direction = '' if config.REPR_VERBOSITY is HIGH: partition = '\n{}:\n{}'.format( ('MIP' if mip else 'Partition'), indent(fmt_partition(ria.partition))) repertoire = '\nRepertoire:\n{}'.format( indent(fmt_repertoire(ria.repertoire))) partitioned_repertoire = '\nPartitioned repertoire:\n{}'.format( indent(fmt_repertoire(ria.partitioned_repertoire))) else: partition = '' repertoire = '' partitioned_repertoire = '' # TODO? print the two repertoires side-by-side return ( '{SMALL_PHI} = {phi}\n' '{mechanism}' 'Purview = {purview}' '{direction}' '{partition}' '{repertoire}' '{partitioned_repertoire}').format( SMALL_PHI=SMALL_PHI, mechanism=mechanism, purview=fmt_mechanism(ria.purview, ria.node_labels), direction=direction, phi=fmt_number(ria.phi), partition=partition, repertoire=repertoire, partitioned_repertoire=partitioned_repertoire)
[ "def", "fmt_ria", "(", "ria", ",", "verbose", "=", "True", ",", "mip", "=", "False", ")", ":", "if", "verbose", ":", "mechanism", "=", "'Mechanism: {}\\n'", ".", "format", "(", "fmt_mechanism", "(", "ria", ".", "mechanism", ",", "ria", ".", "node_labels", ")", ")", "direction", "=", "'\\nDirection: {}'", ".", "format", "(", "ria", ".", "direction", ")", "else", ":", "mechanism", "=", "''", "direction", "=", "''", "if", "config", ".", "REPR_VERBOSITY", "is", "HIGH", ":", "partition", "=", "'\\n{}:\\n{}'", ".", "format", "(", "(", "'MIP'", "if", "mip", "else", "'Partition'", ")", ",", "indent", "(", "fmt_partition", "(", "ria", ".", "partition", ")", ")", ")", "repertoire", "=", "'\\nRepertoire:\\n{}'", ".", "format", "(", "indent", "(", "fmt_repertoire", "(", "ria", ".", "repertoire", ")", ")", ")", "partitioned_repertoire", "=", "'\\nPartitioned repertoire:\\n{}'", ".", "format", "(", "indent", "(", "fmt_repertoire", "(", "ria", ".", "partitioned_repertoire", ")", ")", ")", "else", ":", "partition", "=", "''", "repertoire", "=", "''", "partitioned_repertoire", "=", "''", "# TODO? print the two repertoires side-by-side", "return", "(", "'{SMALL_PHI} = {phi}\\n'", "'{mechanism}'", "'Purview = {purview}'", "'{direction}'", "'{partition}'", "'{repertoire}'", "'{partitioned_repertoire}'", ")", ".", "format", "(", "SMALL_PHI", "=", "SMALL_PHI", ",", "mechanism", "=", "mechanism", ",", "purview", "=", "fmt_mechanism", "(", "ria", ".", "purview", ",", "ria", ".", "node_labels", ")", ",", "direction", "=", "direction", ",", "phi", "=", "fmt_number", "(", "ria", ".", "phi", ")", ",", "partition", "=", "partition", ",", "repertoire", "=", "repertoire", ",", "partitioned_repertoire", "=", "partitioned_repertoire", ")" ]
Format a |RepertoireIrreducibilityAnalysis|.
[ "Format", "a", "|RepertoireIrreducibilityAnalysis|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L321-L360
15,967
wmayner/pyphi
pyphi/models/fmt.py
fmt_cut
def fmt_cut(cut): """Format a |Cut|.""" return 'Cut {from_nodes} {symbol} {to_nodes}'.format( from_nodes=fmt_mechanism(cut.from_nodes, cut.node_labels), symbol=CUT_SYMBOL, to_nodes=fmt_mechanism(cut.to_nodes, cut.node_labels))
python
def fmt_cut(cut): """Format a |Cut|.""" return 'Cut {from_nodes} {symbol} {to_nodes}'.format( from_nodes=fmt_mechanism(cut.from_nodes, cut.node_labels), symbol=CUT_SYMBOL, to_nodes=fmt_mechanism(cut.to_nodes, cut.node_labels))
[ "def", "fmt_cut", "(", "cut", ")", ":", "return", "'Cut {from_nodes} {symbol} {to_nodes}'", ".", "format", "(", "from_nodes", "=", "fmt_mechanism", "(", "cut", ".", "from_nodes", ",", "cut", ".", "node_labels", ")", ",", "symbol", "=", "CUT_SYMBOL", ",", "to_nodes", "=", "fmt_mechanism", "(", "cut", ".", "to_nodes", ",", "cut", ".", "node_labels", ")", ")" ]
Format a |Cut|.
[ "Format", "a", "|Cut|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L363-L368
15,968
wmayner/pyphi
pyphi/models/fmt.py
fmt_sia
def fmt_sia(sia, ces=True): """Format a |SystemIrreducibilityAnalysis|.""" if ces: body = ( '{ces}' '{partitioned_ces}'.format( ces=fmt_ces( sia.ces, 'Cause-effect structure'), partitioned_ces=fmt_ces( sia.partitioned_ces, 'Partitioned cause-effect structure'))) center_header = True else: body = '' center_header = False title = 'System irreducibility analysis: {BIG_PHI} = {phi}'.format( BIG_PHI=BIG_PHI, phi=fmt_number(sia.phi)) body = header(str(sia.subsystem), body, center=center_header) body = header(str(sia.cut), body, center=center_header) return box(header(title, body, center=center_header))
python
def fmt_sia(sia, ces=True): """Format a |SystemIrreducibilityAnalysis|.""" if ces: body = ( '{ces}' '{partitioned_ces}'.format( ces=fmt_ces( sia.ces, 'Cause-effect structure'), partitioned_ces=fmt_ces( sia.partitioned_ces, 'Partitioned cause-effect structure'))) center_header = True else: body = '' center_header = False title = 'System irreducibility analysis: {BIG_PHI} = {phi}'.format( BIG_PHI=BIG_PHI, phi=fmt_number(sia.phi)) body = header(str(sia.subsystem), body, center=center_header) body = header(str(sia.cut), body, center=center_header) return box(header(title, body, center=center_header))
[ "def", "fmt_sia", "(", "sia", ",", "ces", "=", "True", ")", ":", "if", "ces", ":", "body", "=", "(", "'{ces}'", "'{partitioned_ces}'", ".", "format", "(", "ces", "=", "fmt_ces", "(", "sia", ".", "ces", ",", "'Cause-effect structure'", ")", ",", "partitioned_ces", "=", "fmt_ces", "(", "sia", ".", "partitioned_ces", ",", "'Partitioned cause-effect structure'", ")", ")", ")", "center_header", "=", "True", "else", ":", "body", "=", "''", "center_header", "=", "False", "title", "=", "'System irreducibility analysis: {BIG_PHI} = {phi}'", ".", "format", "(", "BIG_PHI", "=", "BIG_PHI", ",", "phi", "=", "fmt_number", "(", "sia", ".", "phi", ")", ")", "body", "=", "header", "(", "str", "(", "sia", ".", "subsystem", ")", ",", "body", ",", "center", "=", "center_header", ")", "body", "=", "header", "(", "str", "(", "sia", ".", "cut", ")", ",", "body", ",", "center", "=", "center_header", ")", "return", "box", "(", "header", "(", "title", ",", "body", ",", "center", "=", "center_header", ")", ")" ]
Format a |SystemIrreducibilityAnalysis|.
[ "Format", "a", "|SystemIrreducibilityAnalysis|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L376-L398
15,969
wmayner/pyphi
pyphi/models/fmt.py
fmt_repertoire
def fmt_repertoire(r): """Format a repertoire.""" # TODO: will this get unwieldy with large repertoires? if r is None: return '' r = r.squeeze() lines = [] # Header: 'S P(S)' space = ' ' * 4 head = '{S:^{s_width}}{space}Pr({S})'.format( S='S', s_width=r.ndim, space=space) lines.append(head) # Lines: '001 .25' for state in utils.all_states(r.ndim): state_str = ''.join(str(i) for i in state) lines.append('{0}{1}{2}'.format(state_str, space, fmt_number(r[state]))) width = max(len(line) for line in lines) lines.insert(1, DOTTED_HEADER * (width + 1)) return box('\n'.join(lines))
python
def fmt_repertoire(r): """Format a repertoire.""" # TODO: will this get unwieldy with large repertoires? if r is None: return '' r = r.squeeze() lines = [] # Header: 'S P(S)' space = ' ' * 4 head = '{S:^{s_width}}{space}Pr({S})'.format( S='S', s_width=r.ndim, space=space) lines.append(head) # Lines: '001 .25' for state in utils.all_states(r.ndim): state_str = ''.join(str(i) for i in state) lines.append('{0}{1}{2}'.format(state_str, space, fmt_number(r[state]))) width = max(len(line) for line in lines) lines.insert(1, DOTTED_HEADER * (width + 1)) return box('\n'.join(lines))
[ "def", "fmt_repertoire", "(", "r", ")", ":", "# TODO: will this get unwieldy with large repertoires?", "if", "r", "is", "None", ":", "return", "''", "r", "=", "r", ".", "squeeze", "(", ")", "lines", "=", "[", "]", "# Header: 'S P(S)'", "space", "=", "' '", "*", "4", "head", "=", "'{S:^{s_width}}{space}Pr({S})'", ".", "format", "(", "S", "=", "'S'", ",", "s_width", "=", "r", ".", "ndim", ",", "space", "=", "space", ")", "lines", ".", "append", "(", "head", ")", "# Lines: '001 .25'", "for", "state", "in", "utils", ".", "all_states", "(", "r", ".", "ndim", ")", ":", "state_str", "=", "''", ".", "join", "(", "str", "(", "i", ")", "for", "i", "in", "state", ")", "lines", ".", "append", "(", "'{0}{1}{2}'", ".", "format", "(", "state_str", ",", "space", ",", "fmt_number", "(", "r", "[", "state", "]", ")", ")", ")", "width", "=", "max", "(", "len", "(", "line", ")", "for", "line", "in", "lines", ")", "lines", ".", "insert", "(", "1", ",", "DOTTED_HEADER", "*", "(", "width", "+", "1", ")", ")", "return", "box", "(", "'\\n'", ".", "join", "(", "lines", ")", ")" ]
Format a repertoire.
[ "Format", "a", "repertoire", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L401-L426
15,970
wmayner/pyphi
pyphi/models/fmt.py
fmt_ac_ria
def fmt_ac_ria(ria): """Format an AcRepertoireIrreducibilityAnalysis.""" causality = { Direction.CAUSE: (fmt_mechanism(ria.purview, ria.node_labels), ARROW_LEFT, fmt_mechanism(ria.mechanism, ria.node_labels)), Direction.EFFECT: (fmt_mechanism(ria.mechanism, ria.node_labels), ARROW_RIGHT, fmt_mechanism(ria.purview, ria.node_labels)) }[ria.direction] causality = ' '.join(causality) return '{ALPHA} = {alpha} {causality}'.format( ALPHA=ALPHA, alpha=round(ria.alpha, 4), causality=causality)
python
def fmt_ac_ria(ria): """Format an AcRepertoireIrreducibilityAnalysis.""" causality = { Direction.CAUSE: (fmt_mechanism(ria.purview, ria.node_labels), ARROW_LEFT, fmt_mechanism(ria.mechanism, ria.node_labels)), Direction.EFFECT: (fmt_mechanism(ria.mechanism, ria.node_labels), ARROW_RIGHT, fmt_mechanism(ria.purview, ria.node_labels)) }[ria.direction] causality = ' '.join(causality) return '{ALPHA} = {alpha} {causality}'.format( ALPHA=ALPHA, alpha=round(ria.alpha, 4), causality=causality)
[ "def", "fmt_ac_ria", "(", "ria", ")", ":", "causality", "=", "{", "Direction", ".", "CAUSE", ":", "(", "fmt_mechanism", "(", "ria", ".", "purview", ",", "ria", ".", "node_labels", ")", ",", "ARROW_LEFT", ",", "fmt_mechanism", "(", "ria", ".", "mechanism", ",", "ria", ".", "node_labels", ")", ")", ",", "Direction", ".", "EFFECT", ":", "(", "fmt_mechanism", "(", "ria", ".", "mechanism", ",", "ria", ".", "node_labels", ")", ",", "ARROW_RIGHT", ",", "fmt_mechanism", "(", "ria", ".", "purview", ",", "ria", ".", "node_labels", ")", ")", "}", "[", "ria", ".", "direction", "]", "causality", "=", "' '", ".", "join", "(", "causality", ")", "return", "'{ALPHA} = {alpha} {causality}'", ".", "format", "(", "ALPHA", "=", "ALPHA", ",", "alpha", "=", "round", "(", "ria", ".", "alpha", ",", "4", ")", ",", "causality", "=", "causality", ")" ]
Format an AcRepertoireIrreducibilityAnalysis.
[ "Format", "an", "AcRepertoireIrreducibilityAnalysis", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L429-L444
15,971
wmayner/pyphi
pyphi/models/fmt.py
fmt_account
def fmt_account(account, title=None): """Format an Account or a DirectedAccount.""" if title is None: title = account.__class__.__name__ # `Account` or `DirectedAccount` title = '{} ({} causal link{})'.format( title, len(account), '' if len(account) == 1 else 's') body = '' body += 'Irreducible effects\n' body += '\n'.join(fmt_ac_ria(m) for m in account.irreducible_effects) body += '\nIrreducible causes\n' body += '\n'.join(fmt_ac_ria(m) for m in account.irreducible_causes) return '\n' + header(title, body, under_char='*')
python
def fmt_account(account, title=None): """Format an Account or a DirectedAccount.""" if title is None: title = account.__class__.__name__ # `Account` or `DirectedAccount` title = '{} ({} causal link{})'.format( title, len(account), '' if len(account) == 1 else 's') body = '' body += 'Irreducible effects\n' body += '\n'.join(fmt_ac_ria(m) for m in account.irreducible_effects) body += '\nIrreducible causes\n' body += '\n'.join(fmt_ac_ria(m) for m in account.irreducible_causes) return '\n' + header(title, body, under_char='*')
[ "def", "fmt_account", "(", "account", ",", "title", "=", "None", ")", ":", "if", "title", "is", "None", ":", "title", "=", "account", ".", "__class__", ".", "__name__", "# `Account` or `DirectedAccount`", "title", "=", "'{} ({} causal link{})'", ".", "format", "(", "title", ",", "len", "(", "account", ")", ",", "''", "if", "len", "(", "account", ")", "==", "1", "else", "'s'", ")", "body", "=", "''", "body", "+=", "'Irreducible effects\\n'", "body", "+=", "'\\n'", ".", "join", "(", "fmt_ac_ria", "(", "m", ")", "for", "m", "in", "account", ".", "irreducible_effects", ")", "body", "+=", "'\\nIrreducible causes\\n'", "body", "+=", "'\\n'", ".", "join", "(", "fmt_ac_ria", "(", "m", ")", "for", "m", "in", "account", ".", "irreducible_causes", ")", "return", "'\\n'", "+", "header", "(", "title", ",", "body", ",", "under_char", "=", "'*'", ")" ]
Format an Account or a DirectedAccount.
[ "Format", "an", "Account", "or", "a", "DirectedAccount", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L447-L461
15,972
wmayner/pyphi
pyphi/models/fmt.py
fmt_ac_sia
def fmt_ac_sia(ac_sia): """Format a AcSystemIrreducibilityAnalysis.""" body = ( '{ALPHA} = {alpha}\n' 'direction: {ac_sia.direction}\n' 'transition: {ac_sia.transition}\n' 'before state: {ac_sia.before_state}\n' 'after state: {ac_sia.after_state}\n' 'cut:\n{ac_sia.cut}\n' '{account}\n' '{partitioned_account}'.format( ALPHA=ALPHA, alpha=round(ac_sia.alpha, 4), ac_sia=ac_sia, account=fmt_account( ac_sia.account, 'Account'), partitioned_account=fmt_account( ac_sia.partitioned_account, 'Partitioned Account'))) return box(header('AcSystemIrreducibilityAnalysis', body, under_char=HORIZONTAL_BAR))
python
def fmt_ac_sia(ac_sia): """Format a AcSystemIrreducibilityAnalysis.""" body = ( '{ALPHA} = {alpha}\n' 'direction: {ac_sia.direction}\n' 'transition: {ac_sia.transition}\n' 'before state: {ac_sia.before_state}\n' 'after state: {ac_sia.after_state}\n' 'cut:\n{ac_sia.cut}\n' '{account}\n' '{partitioned_account}'.format( ALPHA=ALPHA, alpha=round(ac_sia.alpha, 4), ac_sia=ac_sia, account=fmt_account( ac_sia.account, 'Account'), partitioned_account=fmt_account( ac_sia.partitioned_account, 'Partitioned Account'))) return box(header('AcSystemIrreducibilityAnalysis', body, under_char=HORIZONTAL_BAR))
[ "def", "fmt_ac_sia", "(", "ac_sia", ")", ":", "body", "=", "(", "'{ALPHA} = {alpha}\\n'", "'direction: {ac_sia.direction}\\n'", "'transition: {ac_sia.transition}\\n'", "'before state: {ac_sia.before_state}\\n'", "'after state: {ac_sia.after_state}\\n'", "'cut:\\n{ac_sia.cut}\\n'", "'{account}\\n'", "'{partitioned_account}'", ".", "format", "(", "ALPHA", "=", "ALPHA", ",", "alpha", "=", "round", "(", "ac_sia", ".", "alpha", ",", "4", ")", ",", "ac_sia", "=", "ac_sia", ",", "account", "=", "fmt_account", "(", "ac_sia", ".", "account", ",", "'Account'", ")", ",", "partitioned_account", "=", "fmt_account", "(", "ac_sia", ".", "partitioned_account", ",", "'Partitioned Account'", ")", ")", ")", "return", "box", "(", "header", "(", "'AcSystemIrreducibilityAnalysis'", ",", "body", ",", "under_char", "=", "HORIZONTAL_BAR", ")", ")" ]
Format a AcSystemIrreducibilityAnalysis.
[ "Format", "a", "AcSystemIrreducibilityAnalysis", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L464-L485
15,973
wmayner/pyphi
pyphi/models/fmt.py
fmt_transition
def fmt_transition(t): """Format a |Transition|.""" return "Transition({} {} {})".format( fmt_mechanism(t.cause_indices, t.node_labels), ARROW_RIGHT, fmt_mechanism(t.effect_indices, t.node_labels))
python
def fmt_transition(t): """Format a |Transition|.""" return "Transition({} {} {})".format( fmt_mechanism(t.cause_indices, t.node_labels), ARROW_RIGHT, fmt_mechanism(t.effect_indices, t.node_labels))
[ "def", "fmt_transition", "(", "t", ")", ":", "return", "\"Transition({} {} {})\"", ".", "format", "(", "fmt_mechanism", "(", "t", ".", "cause_indices", ",", "t", ".", "node_labels", ")", ",", "ARROW_RIGHT", ",", "fmt_mechanism", "(", "t", ".", "effect_indices", ",", "t", ".", "node_labels", ")", ")" ]
Format a |Transition|.
[ "Format", "a", "|Transition|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L488-L493
15,974
wmayner/pyphi
pyphi/validate.py
direction
def direction(direction, allow_bi=False): """Validate that the given direction is one of the allowed constants. If ``allow_bi`` is ``True`` then ``Direction.BIDIRECTIONAL`` is acceptable. """ valid = [Direction.CAUSE, Direction.EFFECT] if allow_bi: valid.append(Direction.BIDIRECTIONAL) if direction not in valid: raise ValueError('`direction` must be one of {}'.format(valid)) return True
python
def direction(direction, allow_bi=False): """Validate that the given direction is one of the allowed constants. If ``allow_bi`` is ``True`` then ``Direction.BIDIRECTIONAL`` is acceptable. """ valid = [Direction.CAUSE, Direction.EFFECT] if allow_bi: valid.append(Direction.BIDIRECTIONAL) if direction not in valid: raise ValueError('`direction` must be one of {}'.format(valid)) return True
[ "def", "direction", "(", "direction", ",", "allow_bi", "=", "False", ")", ":", "valid", "=", "[", "Direction", ".", "CAUSE", ",", "Direction", ".", "EFFECT", "]", "if", "allow_bi", ":", "valid", ".", "append", "(", "Direction", ".", "BIDIRECTIONAL", ")", "if", "direction", "not", "in", "valid", ":", "raise", "ValueError", "(", "'`direction` must be one of {}'", ".", "format", "(", "valid", ")", ")", "return", "True" ]
Validate that the given direction is one of the allowed constants. If ``allow_bi`` is ``True`` then ``Direction.BIDIRECTIONAL`` is acceptable.
[ "Validate", "that", "the", "given", "direction", "is", "one", "of", "the", "allowed", "constants", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L18-L31
15,975
wmayner/pyphi
pyphi/validate.py
tpm
def tpm(tpm, check_independence=True): """Validate a TPM. The TPM can be in * 2-dimensional state-by-state form, * 2-dimensional state-by-node form, or * multidimensional state-by-node form. """ see_tpm_docs = ( 'See the documentation on TPM conventions and the `pyphi.Network` ' 'object for more information on TPM forms.' ) # Cast to np.array. tpm = np.array(tpm) # Get the number of nodes from the state-by-node TPM. N = tpm.shape[-1] if tpm.ndim == 2: if not ((tpm.shape[0] == 2**N and tpm.shape[1] == N) or (tpm.shape[0] == tpm.shape[1])): raise ValueError( 'Invalid shape for 2-D TPM: {}\nFor a state-by-node TPM, ' 'there must be ' '2^N rows and N columns, where N is the ' 'number of nodes. State-by-state TPM must be square. ' '{}'.format(tpm.shape, see_tpm_docs)) if tpm.shape[0] == tpm.shape[1] and check_independence: conditionally_independent(tpm) elif tpm.ndim == (N + 1): if tpm.shape != tuple([2] * N + [N]): raise ValueError( 'Invalid shape for multidimensional state-by-node TPM: {}\n' 'The shape should be {} for {} nodes. {}'.format( tpm.shape, ([2] * N) + [N], N, see_tpm_docs)) else: raise ValueError( 'Invalid TPM: Must be either 2-dimensional or multidimensional. ' '{}'.format(see_tpm_docs)) return True
python
def tpm(tpm, check_independence=True): """Validate a TPM. The TPM can be in * 2-dimensional state-by-state form, * 2-dimensional state-by-node form, or * multidimensional state-by-node form. """ see_tpm_docs = ( 'See the documentation on TPM conventions and the `pyphi.Network` ' 'object for more information on TPM forms.' ) # Cast to np.array. tpm = np.array(tpm) # Get the number of nodes from the state-by-node TPM. N = tpm.shape[-1] if tpm.ndim == 2: if not ((tpm.shape[0] == 2**N and tpm.shape[1] == N) or (tpm.shape[0] == tpm.shape[1])): raise ValueError( 'Invalid shape for 2-D TPM: {}\nFor a state-by-node TPM, ' 'there must be ' '2^N rows and N columns, where N is the ' 'number of nodes. State-by-state TPM must be square. ' '{}'.format(tpm.shape, see_tpm_docs)) if tpm.shape[0] == tpm.shape[1] and check_independence: conditionally_independent(tpm) elif tpm.ndim == (N + 1): if tpm.shape != tuple([2] * N + [N]): raise ValueError( 'Invalid shape for multidimensional state-by-node TPM: {}\n' 'The shape should be {} for {} nodes. {}'.format( tpm.shape, ([2] * N) + [N], N, see_tpm_docs)) else: raise ValueError( 'Invalid TPM: Must be either 2-dimensional or multidimensional. ' '{}'.format(see_tpm_docs)) return True
[ "def", "tpm", "(", "tpm", ",", "check_independence", "=", "True", ")", ":", "see_tpm_docs", "=", "(", "'See the documentation on TPM conventions and the `pyphi.Network` '", "'object for more information on TPM forms.'", ")", "# Cast to np.array.", "tpm", "=", "np", ".", "array", "(", "tpm", ")", "# Get the number of nodes from the state-by-node TPM.", "N", "=", "tpm", ".", "shape", "[", "-", "1", "]", "if", "tpm", ".", "ndim", "==", "2", ":", "if", "not", "(", "(", "tpm", ".", "shape", "[", "0", "]", "==", "2", "**", "N", "and", "tpm", ".", "shape", "[", "1", "]", "==", "N", ")", "or", "(", "tpm", ".", "shape", "[", "0", "]", "==", "tpm", ".", "shape", "[", "1", "]", ")", ")", ":", "raise", "ValueError", "(", "'Invalid shape for 2-D TPM: {}\\nFor a state-by-node TPM, '", "'there must be '", "'2^N rows and N columns, where N is the '", "'number of nodes. State-by-state TPM must be square. '", "'{}'", ".", "format", "(", "tpm", ".", "shape", ",", "see_tpm_docs", ")", ")", "if", "tpm", ".", "shape", "[", "0", "]", "==", "tpm", ".", "shape", "[", "1", "]", "and", "check_independence", ":", "conditionally_independent", "(", "tpm", ")", "elif", "tpm", ".", "ndim", "==", "(", "N", "+", "1", ")", ":", "if", "tpm", ".", "shape", "!=", "tuple", "(", "[", "2", "]", "*", "N", "+", "[", "N", "]", ")", ":", "raise", "ValueError", "(", "'Invalid shape for multidimensional state-by-node TPM: {}\\n'", "'The shape should be {} for {} nodes. {}'", ".", "format", "(", "tpm", ".", "shape", ",", "(", "[", "2", "]", "*", "N", ")", "+", "[", "N", "]", ",", "N", ",", "see_tpm_docs", ")", ")", "else", ":", "raise", "ValueError", "(", "'Invalid TPM: Must be either 2-dimensional or multidimensional. '", "'{}'", ".", "format", "(", "see_tpm_docs", ")", ")", "return", "True" ]
Validate a TPM. The TPM can be in * 2-dimensional state-by-state form, * 2-dimensional state-by-node form, or * multidimensional state-by-node form.
[ "Validate", "a", "TPM", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L34-L71
15,976
wmayner/pyphi
pyphi/validate.py
conditionally_independent
def conditionally_independent(tpm): """Validate that the TPM is conditionally independent.""" if not config.VALIDATE_CONDITIONAL_INDEPENDENCE: return True tpm = np.array(tpm) if is_state_by_state(tpm): there_and_back_again = convert.state_by_node2state_by_state( convert.state_by_state2state_by_node(tpm)) else: there_and_back_again = convert.state_by_state2state_by_node( convert.state_by_node2state_by_state(tpm)) if np.any((tpm - there_and_back_again) >= EPSILON): raise exceptions.ConditionallyDependentError( 'TPM is not conditionally independent.\n' 'See the conditional independence example in the documentation ' 'for more info.') return True
python
def conditionally_independent(tpm): """Validate that the TPM is conditionally independent.""" if not config.VALIDATE_CONDITIONAL_INDEPENDENCE: return True tpm = np.array(tpm) if is_state_by_state(tpm): there_and_back_again = convert.state_by_node2state_by_state( convert.state_by_state2state_by_node(tpm)) else: there_and_back_again = convert.state_by_state2state_by_node( convert.state_by_node2state_by_state(tpm)) if np.any((tpm - there_and_back_again) >= EPSILON): raise exceptions.ConditionallyDependentError( 'TPM is not conditionally independent.\n' 'See the conditional independence example in the documentation ' 'for more info.') return True
[ "def", "conditionally_independent", "(", "tpm", ")", ":", "if", "not", "config", ".", "VALIDATE_CONDITIONAL_INDEPENDENCE", ":", "return", "True", "tpm", "=", "np", ".", "array", "(", "tpm", ")", "if", "is_state_by_state", "(", "tpm", ")", ":", "there_and_back_again", "=", "convert", ".", "state_by_node2state_by_state", "(", "convert", ".", "state_by_state2state_by_node", "(", "tpm", ")", ")", "else", ":", "there_and_back_again", "=", "convert", ".", "state_by_state2state_by_node", "(", "convert", ".", "state_by_node2state_by_state", "(", "tpm", ")", ")", "if", "np", ".", "any", "(", "(", "tpm", "-", "there_and_back_again", ")", ">=", "EPSILON", ")", ":", "raise", "exceptions", ".", "ConditionallyDependentError", "(", "'TPM is not conditionally independent.\\n'", "'See the conditional independence example in the documentation '", "'for more info.'", ")", "return", "True" ]
Validate that the TPM is conditionally independent.
[ "Validate", "that", "the", "TPM", "is", "conditionally", "independent", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L74-L90
15,977
wmayner/pyphi
pyphi/validate.py
connectivity_matrix
def connectivity_matrix(cm): """Validate the given connectivity matrix.""" # Special case for empty matrices. if cm.size == 0: return True if cm.ndim != 2: raise ValueError("Connectivity matrix must be 2-dimensional.") if cm.shape[0] != cm.shape[1]: raise ValueError("Connectivity matrix must be square.") if not np.all(np.logical_or(cm == 1, cm == 0)): raise ValueError("Connectivity matrix must contain only binary " "values.") return True
python
def connectivity_matrix(cm): """Validate the given connectivity matrix.""" # Special case for empty matrices. if cm.size == 0: return True if cm.ndim != 2: raise ValueError("Connectivity matrix must be 2-dimensional.") if cm.shape[0] != cm.shape[1]: raise ValueError("Connectivity matrix must be square.") if not np.all(np.logical_or(cm == 1, cm == 0)): raise ValueError("Connectivity matrix must contain only binary " "values.") return True
[ "def", "connectivity_matrix", "(", "cm", ")", ":", "# Special case for empty matrices.", "if", "cm", ".", "size", "==", "0", ":", "return", "True", "if", "cm", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"Connectivity matrix must be 2-dimensional.\"", ")", "if", "cm", ".", "shape", "[", "0", "]", "!=", "cm", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "\"Connectivity matrix must be square.\"", ")", "if", "not", "np", ".", "all", "(", "np", ".", "logical_or", "(", "cm", "==", "1", ",", "cm", "==", "0", ")", ")", ":", "raise", "ValueError", "(", "\"Connectivity matrix must contain only binary \"", "\"values.\"", ")", "return", "True" ]
Validate the given connectivity matrix.
[ "Validate", "the", "given", "connectivity", "matrix", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L93-L105
15,978
wmayner/pyphi
pyphi/validate.py
node_labels
def node_labels(node_labels, node_indices): """Validate that there is a label for each node.""" if len(node_labels) != len(node_indices): raise ValueError("Labels {0} must label every node {1}.".format( node_labels, node_indices)) if len(node_labels) != len(set(node_labels)): raise ValueError("Labels {0} must be unique.".format(node_labels))
python
def node_labels(node_labels, node_indices): """Validate that there is a label for each node.""" if len(node_labels) != len(node_indices): raise ValueError("Labels {0} must label every node {1}.".format( node_labels, node_indices)) if len(node_labels) != len(set(node_labels)): raise ValueError("Labels {0} must be unique.".format(node_labels))
[ "def", "node_labels", "(", "node_labels", ",", "node_indices", ")", ":", "if", "len", "(", "node_labels", ")", "!=", "len", "(", "node_indices", ")", ":", "raise", "ValueError", "(", "\"Labels {0} must label every node {1}.\"", ".", "format", "(", "node_labels", ",", "node_indices", ")", ")", "if", "len", "(", "node_labels", ")", "!=", "len", "(", "set", "(", "node_labels", ")", ")", ":", "raise", "ValueError", "(", "\"Labels {0} must be unique.\"", ".", "format", "(", "node_labels", ")", ")" ]
Validate that there is a label for each node.
[ "Validate", "that", "there", "is", "a", "label", "for", "each", "node", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L108-L115
15,979
wmayner/pyphi
pyphi/validate.py
network
def network(n): """Validate a |Network|. Checks the TPM and connectivity matrix. """ tpm(n.tpm) connectivity_matrix(n.cm) if n.cm.shape[0] != n.size: raise ValueError("Connectivity matrix must be NxN, where N is the " "number of nodes in the network.") return True
python
def network(n): """Validate a |Network|. Checks the TPM and connectivity matrix. """ tpm(n.tpm) connectivity_matrix(n.cm) if n.cm.shape[0] != n.size: raise ValueError("Connectivity matrix must be NxN, where N is the " "number of nodes in the network.") return True
[ "def", "network", "(", "n", ")", ":", "tpm", "(", "n", ".", "tpm", ")", "connectivity_matrix", "(", "n", ".", "cm", ")", "if", "n", ".", "cm", ".", "shape", "[", "0", "]", "!=", "n", ".", "size", ":", "raise", "ValueError", "(", "\"Connectivity matrix must be NxN, where N is the \"", "\"number of nodes in the network.\"", ")", "return", "True" ]
Validate a |Network|. Checks the TPM and connectivity matrix.
[ "Validate", "a", "|Network|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L118-L128
15,980
wmayner/pyphi
pyphi/validate.py
state_length
def state_length(state, size): """Check that the state is the given size.""" if len(state) != size: raise ValueError('Invalid state: there must be one entry per ' 'node in the network; this state has {} entries, but ' 'there are {} nodes.'.format(len(state), size)) return True
python
def state_length(state, size): """Check that the state is the given size.""" if len(state) != size: raise ValueError('Invalid state: there must be one entry per ' 'node in the network; this state has {} entries, but ' 'there are {} nodes.'.format(len(state), size)) return True
[ "def", "state_length", "(", "state", ",", "size", ")", ":", "if", "len", "(", "state", ")", "!=", "size", ":", "raise", "ValueError", "(", "'Invalid state: there must be one entry per '", "'node in the network; this state has {} entries, but '", "'there are {} nodes.'", ".", "format", "(", "len", "(", "state", ")", ",", "size", ")", ")", "return", "True" ]
Check that the state is the given size.
[ "Check", "that", "the", "state", "is", "the", "given", "size", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L147-L153
15,981
wmayner/pyphi
pyphi/validate.py
state_reachable
def state_reachable(subsystem): """Return whether a state can be reached according to the network's TPM.""" # If there is a row `r` in the TPM such that all entries of `r - state` are # between -1 and 1, then the given state has a nonzero probability of being # reached from some state. # First we take the submatrix of the conditioned TPM that corresponds to # the nodes that are actually in the subsystem... tpm = subsystem.tpm[..., subsystem.node_indices] # Then we do the subtraction and test. test = tpm - np.array(subsystem.proper_state) if not np.any(np.logical_and(-1 < test, test < 1).all(-1)): raise exceptions.StateUnreachableError(subsystem.state)
python
def state_reachable(subsystem): """Return whether a state can be reached according to the network's TPM.""" # If there is a row `r` in the TPM such that all entries of `r - state` are # between -1 and 1, then the given state has a nonzero probability of being # reached from some state. # First we take the submatrix of the conditioned TPM that corresponds to # the nodes that are actually in the subsystem... tpm = subsystem.tpm[..., subsystem.node_indices] # Then we do the subtraction and test. test = tpm - np.array(subsystem.proper_state) if not np.any(np.logical_and(-1 < test, test < 1).all(-1)): raise exceptions.StateUnreachableError(subsystem.state)
[ "def", "state_reachable", "(", "subsystem", ")", ":", "# If there is a row `r` in the TPM such that all entries of `r - state` are", "# between -1 and 1, then the given state has a nonzero probability of being", "# reached from some state.", "# First we take the submatrix of the conditioned TPM that corresponds to", "# the nodes that are actually in the subsystem...", "tpm", "=", "subsystem", ".", "tpm", "[", "...", ",", "subsystem", ".", "node_indices", "]", "# Then we do the subtraction and test.", "test", "=", "tpm", "-", "np", ".", "array", "(", "subsystem", ".", "proper_state", ")", "if", "not", "np", ".", "any", "(", "np", ".", "logical_and", "(", "-", "1", "<", "test", ",", "test", "<", "1", ")", ".", "all", "(", "-", "1", ")", ")", ":", "raise", "exceptions", ".", "StateUnreachableError", "(", "subsystem", ".", "state", ")" ]
Return whether a state can be reached according to the network's TPM.
[ "Return", "whether", "a", "state", "can", "be", "reached", "according", "to", "the", "network", "s", "TPM", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L156-L167
15,982
wmayner/pyphi
pyphi/validate.py
cut
def cut(cut, node_indices): """Check that the cut is for only the given nodes.""" if cut.indices != node_indices: raise ValueError('{} nodes are not equal to subsystem nodes ' '{}'.format(cut, node_indices))
python
def cut(cut, node_indices): """Check that the cut is for only the given nodes.""" if cut.indices != node_indices: raise ValueError('{} nodes are not equal to subsystem nodes ' '{}'.format(cut, node_indices))
[ "def", "cut", "(", "cut", ",", "node_indices", ")", ":", "if", "cut", ".", "indices", "!=", "node_indices", ":", "raise", "ValueError", "(", "'{} nodes are not equal to subsystem nodes '", "'{}'", ".", "format", "(", "cut", ",", "node_indices", ")", ")" ]
Check that the cut is for only the given nodes.
[ "Check", "that", "the", "cut", "is", "for", "only", "the", "given", "nodes", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L170-L174
15,983
wmayner/pyphi
pyphi/validate.py
subsystem
def subsystem(s): """Validate a |Subsystem|. Checks its state and cut. """ node_states(s.state) cut(s.cut, s.cut_indices) if config.VALIDATE_SUBSYSTEM_STATES: state_reachable(s) return True
python
def subsystem(s): """Validate a |Subsystem|. Checks its state and cut. """ node_states(s.state) cut(s.cut, s.cut_indices) if config.VALIDATE_SUBSYSTEM_STATES: state_reachable(s) return True
[ "def", "subsystem", "(", "s", ")", ":", "node_states", "(", "s", ".", "state", ")", "cut", "(", "s", ".", "cut", ",", "s", ".", "cut_indices", ")", "if", "config", ".", "VALIDATE_SUBSYSTEM_STATES", ":", "state_reachable", "(", "s", ")", "return", "True" ]
Validate a |Subsystem|. Checks its state and cut.
[ "Validate", "a", "|Subsystem|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L177-L186
15,984
wmayner/pyphi
pyphi/validate.py
partition
def partition(partition): """Validate a partition - used by blackboxes and coarse grains.""" nodes = set() for part in partition: for node in part: if node in nodes: raise ValueError( 'Micro-element {} may not be partitioned into multiple ' 'macro-elements'.format(node)) nodes.add(node)
python
def partition(partition): """Validate a partition - used by blackboxes and coarse grains.""" nodes = set() for part in partition: for node in part: if node in nodes: raise ValueError( 'Micro-element {} may not be partitioned into multiple ' 'macro-elements'.format(node)) nodes.add(node)
[ "def", "partition", "(", "partition", ")", ":", "nodes", "=", "set", "(", ")", "for", "part", "in", "partition", ":", "for", "node", "in", "part", ":", "if", "node", "in", "nodes", ":", "raise", "ValueError", "(", "'Micro-element {} may not be partitioned into multiple '", "'macro-elements'", ".", "format", "(", "node", ")", ")", "nodes", ".", "add", "(", "node", ")" ]
Validate a partition - used by blackboxes and coarse grains.
[ "Validate", "a", "partition", "-", "used", "by", "blackboxes", "and", "coarse", "grains", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L195-L204
15,985
wmayner/pyphi
pyphi/validate.py
coarse_grain
def coarse_grain(coarse_grain): """Validate a macro coarse-graining.""" partition(coarse_grain.partition) if len(coarse_grain.partition) != len(coarse_grain.grouping): raise ValueError('output and state groupings must be the same size') for part, group in zip(coarse_grain.partition, coarse_grain.grouping): if set(range(len(part) + 1)) != set(group[0] + group[1]): # Check that all elements in the partition are in one of the two # state groupings raise ValueError('elements in output grouping {0} do not match ' 'elements in state grouping {1}'.format( part, group))
python
def coarse_grain(coarse_grain): """Validate a macro coarse-graining.""" partition(coarse_grain.partition) if len(coarse_grain.partition) != len(coarse_grain.grouping): raise ValueError('output and state groupings must be the same size') for part, group in zip(coarse_grain.partition, coarse_grain.grouping): if set(range(len(part) + 1)) != set(group[0] + group[1]): # Check that all elements in the partition are in one of the two # state groupings raise ValueError('elements in output grouping {0} do not match ' 'elements in state grouping {1}'.format( part, group))
[ "def", "coarse_grain", "(", "coarse_grain", ")", ":", "partition", "(", "coarse_grain", ".", "partition", ")", "if", "len", "(", "coarse_grain", ".", "partition", ")", "!=", "len", "(", "coarse_grain", ".", "grouping", ")", ":", "raise", "ValueError", "(", "'output and state groupings must be the same size'", ")", "for", "part", ",", "group", "in", "zip", "(", "coarse_grain", ".", "partition", ",", "coarse_grain", ".", "grouping", ")", ":", "if", "set", "(", "range", "(", "len", "(", "part", ")", "+", "1", ")", ")", "!=", "set", "(", "group", "[", "0", "]", "+", "group", "[", "1", "]", ")", ":", "# Check that all elements in the partition are in one of the two", "# state groupings", "raise", "ValueError", "(", "'elements in output grouping {0} do not match '", "'elements in state grouping {1}'", ".", "format", "(", "part", ",", "group", ")", ")" ]
Validate a macro coarse-graining.
[ "Validate", "a", "macro", "coarse", "-", "graining", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L207-L220
15,986
wmayner/pyphi
pyphi/validate.py
blackbox
def blackbox(blackbox): """Validate a macro blackboxing.""" if tuple(sorted(blackbox.output_indices)) != blackbox.output_indices: raise ValueError('Output indices {} must be ordered'.format( blackbox.output_indices)) partition(blackbox.partition) for part in blackbox.partition: if not set(part) & set(blackbox.output_indices): raise ValueError( 'Every blackbox must have an output - {} does not'.format( part))
python
def blackbox(blackbox): """Validate a macro blackboxing.""" if tuple(sorted(blackbox.output_indices)) != blackbox.output_indices: raise ValueError('Output indices {} must be ordered'.format( blackbox.output_indices)) partition(blackbox.partition) for part in blackbox.partition: if not set(part) & set(blackbox.output_indices): raise ValueError( 'Every blackbox must have an output - {} does not'.format( part))
[ "def", "blackbox", "(", "blackbox", ")", ":", "if", "tuple", "(", "sorted", "(", "blackbox", ".", "output_indices", ")", ")", "!=", "blackbox", ".", "output_indices", ":", "raise", "ValueError", "(", "'Output indices {} must be ordered'", ".", "format", "(", "blackbox", ".", "output_indices", ")", ")", "partition", "(", "blackbox", ".", "partition", ")", "for", "part", "in", "blackbox", ".", "partition", ":", "if", "not", "set", "(", "part", ")", "&", "set", "(", "blackbox", ".", "output_indices", ")", ":", "raise", "ValueError", "(", "'Every blackbox must have an output - {} does not'", ".", "format", "(", "part", ")", ")" ]
Validate a macro blackboxing.
[ "Validate", "a", "macro", "blackboxing", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L223-L235
15,987
wmayner/pyphi
pyphi/validate.py
blackbox_and_coarse_grain
def blackbox_and_coarse_grain(blackbox, coarse_grain): """Validate that a coarse-graining properly combines the outputs of a blackboxing. """ if blackbox is None: return for box in blackbox.partition: # Outputs of the box outputs = set(box) & set(blackbox.output_indices) if coarse_grain is None and len(outputs) > 1: raise ValueError( 'A blackboxing with multiple outputs per box must be ' 'coarse-grained.') if (coarse_grain and not any(outputs.issubset(part) for part in coarse_grain.partition)): raise ValueError( 'Multiple outputs from a blackbox must be partitioned into ' 'the same macro-element of the coarse-graining')
python
def blackbox_and_coarse_grain(blackbox, coarse_grain): """Validate that a coarse-graining properly combines the outputs of a blackboxing. """ if blackbox is None: return for box in blackbox.partition: # Outputs of the box outputs = set(box) & set(blackbox.output_indices) if coarse_grain is None and len(outputs) > 1: raise ValueError( 'A blackboxing with multiple outputs per box must be ' 'coarse-grained.') if (coarse_grain and not any(outputs.issubset(part) for part in coarse_grain.partition)): raise ValueError( 'Multiple outputs from a blackbox must be partitioned into ' 'the same macro-element of the coarse-graining')
[ "def", "blackbox_and_coarse_grain", "(", "blackbox", ",", "coarse_grain", ")", ":", "if", "blackbox", "is", "None", ":", "return", "for", "box", "in", "blackbox", ".", "partition", ":", "# Outputs of the box", "outputs", "=", "set", "(", "box", ")", "&", "set", "(", "blackbox", ".", "output_indices", ")", "if", "coarse_grain", "is", "None", "and", "len", "(", "outputs", ")", ">", "1", ":", "raise", "ValueError", "(", "'A blackboxing with multiple outputs per box must be '", "'coarse-grained.'", ")", "if", "(", "coarse_grain", "and", "not", "any", "(", "outputs", ".", "issubset", "(", "part", ")", "for", "part", "in", "coarse_grain", ".", "partition", ")", ")", ":", "raise", "ValueError", "(", "'Multiple outputs from a blackbox must be partitioned into '", "'the same macro-element of the coarse-graining'", ")" ]
Validate that a coarse-graining properly combines the outputs of a blackboxing.
[ "Validate", "that", "a", "coarse", "-", "graining", "properly", "combines", "the", "outputs", "of", "a", "blackboxing", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/validate.py#L238-L258
15,988
wmayner/pyphi
pyphi/registry.py
Registry.register
def register(self, name): """Decorator for registering a function with PyPhi. Args: name (string): The name of the function """ def register_func(func): self.store[name] = func return func return register_func
python
def register(self, name): """Decorator for registering a function with PyPhi. Args: name (string): The name of the function """ def register_func(func): self.store[name] = func return func return register_func
[ "def", "register", "(", "self", ",", "name", ")", ":", "def", "register_func", "(", "func", ")", ":", "self", ".", "store", "[", "name", "]", "=", "func", "return", "func", "return", "register_func" ]
Decorator for registering a function with PyPhi. Args: name (string): The name of the function
[ "Decorator", "for", "registering", "a", "function", "with", "PyPhi", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/registry.py#L23-L32
15,989
wmayner/pyphi
pyphi/compute/subsystem.py
ces
def ces(subsystem, mechanisms=False, purviews=False, cause_purviews=False, effect_purviews=False, parallel=False): """Return the conceptual structure of this subsystem, optionally restricted to concepts with the mechanisms and purviews given in keyword arguments. If you don't need the full |CauseEffectStructure|, restricting the possible mechanisms and purviews can make this function much faster. Args: subsystem (Subsystem): The subsystem for which to determine the |CauseEffectStructure|. Keyword Args: mechanisms (tuple[tuple[int]]): Restrict possible mechanisms to those in this list. purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. cause_purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. effect_purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. parallel (bool): Whether to compute concepts in parallel. If ``True``, overrides :data:`config.PARALLEL_CONCEPT_EVALUATION`. Returns: CauseEffectStructure: A tuple of every |Concept| in the cause-effect structure. """ if mechanisms is False: mechanisms = utils.powerset(subsystem.node_indices, nonempty=True) engine = ComputeCauseEffectStructure(mechanisms, subsystem, purviews, cause_purviews, effect_purviews) return CauseEffectStructure(engine.run(parallel or config.PARALLEL_CONCEPT_EVALUATION), subsystem=subsystem)
python
def ces(subsystem, mechanisms=False, purviews=False, cause_purviews=False, effect_purviews=False, parallel=False): """Return the conceptual structure of this subsystem, optionally restricted to concepts with the mechanisms and purviews given in keyword arguments. If you don't need the full |CauseEffectStructure|, restricting the possible mechanisms and purviews can make this function much faster. Args: subsystem (Subsystem): The subsystem for which to determine the |CauseEffectStructure|. Keyword Args: mechanisms (tuple[tuple[int]]): Restrict possible mechanisms to those in this list. purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. cause_purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. effect_purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. parallel (bool): Whether to compute concepts in parallel. If ``True``, overrides :data:`config.PARALLEL_CONCEPT_EVALUATION`. Returns: CauseEffectStructure: A tuple of every |Concept| in the cause-effect structure. """ if mechanisms is False: mechanisms = utils.powerset(subsystem.node_indices, nonempty=True) engine = ComputeCauseEffectStructure(mechanisms, subsystem, purviews, cause_purviews, effect_purviews) return CauseEffectStructure(engine.run(parallel or config.PARALLEL_CONCEPT_EVALUATION), subsystem=subsystem)
[ "def", "ces", "(", "subsystem", ",", "mechanisms", "=", "False", ",", "purviews", "=", "False", ",", "cause_purviews", "=", "False", ",", "effect_purviews", "=", "False", ",", "parallel", "=", "False", ")", ":", "if", "mechanisms", "is", "False", ":", "mechanisms", "=", "utils", ".", "powerset", "(", "subsystem", ".", "node_indices", ",", "nonempty", "=", "True", ")", "engine", "=", "ComputeCauseEffectStructure", "(", "mechanisms", ",", "subsystem", ",", "purviews", ",", "cause_purviews", ",", "effect_purviews", ")", "return", "CauseEffectStructure", "(", "engine", ".", "run", "(", "parallel", "or", "config", ".", "PARALLEL_CONCEPT_EVALUATION", ")", ",", "subsystem", "=", "subsystem", ")" ]
Return the conceptual structure of this subsystem, optionally restricted to concepts with the mechanisms and purviews given in keyword arguments. If you don't need the full |CauseEffectStructure|, restricting the possible mechanisms and purviews can make this function much faster. Args: subsystem (Subsystem): The subsystem for which to determine the |CauseEffectStructure|. Keyword Args: mechanisms (tuple[tuple[int]]): Restrict possible mechanisms to those in this list. purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. cause_purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. effect_purviews (tuple[tuple[int]]): Same as in |Subsystem.concept()|. parallel (bool): Whether to compute concepts in parallel. If ``True``, overrides :data:`config.PARALLEL_CONCEPT_EVALUATION`. Returns: CauseEffectStructure: A tuple of every |Concept| in the cause-effect structure.
[ "Return", "the", "conceptual", "structure", "of", "this", "subsystem", "optionally", "restricted", "to", "concepts", "with", "the", "mechanisms", "and", "purviews", "given", "in", "keyword", "arguments", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L66-L99
15,990
wmayner/pyphi
pyphi/compute/subsystem.py
conceptual_info
def conceptual_info(subsystem): """Return the conceptual information for a |Subsystem|. This is the distance from the subsystem's |CauseEffectStructure| to the null concept. """ ci = ces_distance(ces(subsystem), CauseEffectStructure((), subsystem=subsystem)) return round(ci, config.PRECISION)
python
def conceptual_info(subsystem): """Return the conceptual information for a |Subsystem|. This is the distance from the subsystem's |CauseEffectStructure| to the null concept. """ ci = ces_distance(ces(subsystem), CauseEffectStructure((), subsystem=subsystem)) return round(ci, config.PRECISION)
[ "def", "conceptual_info", "(", "subsystem", ")", ":", "ci", "=", "ces_distance", "(", "ces", "(", "subsystem", ")", ",", "CauseEffectStructure", "(", "(", ")", ",", "subsystem", "=", "subsystem", ")", ")", "return", "round", "(", "ci", ",", "config", ".", "PRECISION", ")" ]
Return the conceptual information for a |Subsystem|. This is the distance from the subsystem's |CauseEffectStructure| to the null concept.
[ "Return", "the", "conceptual", "information", "for", "a", "|Subsystem|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L102-L110
15,991
wmayner/pyphi
pyphi/compute/subsystem.py
evaluate_cut
def evaluate_cut(uncut_subsystem, cut, unpartitioned_ces): """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: SystemIrreducibilityAnalysis: The |SystemIrreducibilityAnalysis| for that cut. """ 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 they were concepts in the # original system, or the cut divides the mechanism. mechanisms = set( unpartitioned_ces.mechanisms + list(cut_subsystem.cut_mechanisms)) partitioned_ces = ces(cut_subsystem, mechanisms) log.debug('Finished evaluating %s.', cut) phi_ = ces_distance(unpartitioned_ces, partitioned_ces) return SystemIrreducibilityAnalysis( phi=phi_, ces=unpartitioned_ces, partitioned_ces=partitioned_ces, subsystem=uncut_subsystem, cut_subsystem=cut_subsystem)
python
def evaluate_cut(uncut_subsystem, cut, unpartitioned_ces): """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: SystemIrreducibilityAnalysis: The |SystemIrreducibilityAnalysis| for that cut. """ 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 they were concepts in the # original system, or the cut divides the mechanism. mechanisms = set( unpartitioned_ces.mechanisms + list(cut_subsystem.cut_mechanisms)) partitioned_ces = ces(cut_subsystem, mechanisms) log.debug('Finished evaluating %s.', cut) phi_ = ces_distance(unpartitioned_ces, partitioned_ces) return SystemIrreducibilityAnalysis( phi=phi_, ces=unpartitioned_ces, partitioned_ces=partitioned_ces, subsystem=uncut_subsystem, cut_subsystem=cut_subsystem)
[ "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 they were concepts in the", "# original system, or the cut divides the mechanism.", "mechanisms", "=", "set", "(", "unpartitioned_ces", ".", "mechanisms", "+", "list", "(", "cut_subsystem", ".", "cut_mechanisms", ")", ")", "partitioned_ces", "=", "ces", "(", "cut_subsystem", ",", "mechanisms", ")", "log", ".", "debug", "(", "'Finished evaluating %s.'", ",", "cut", ")", "phi_", "=", "ces_distance", "(", "unpartitioned_ces", ",", "partitioned_ces", ")", "return", "SystemIrreducibilityAnalysis", "(", "phi", "=", "phi_", ",", "ces", "=", "unpartitioned_ces", ",", "partitioned_ces", "=", "partitioned_ces", ",", "subsystem", "=", "uncut_subsystem", ",", "cut_subsystem", "=", "cut_subsystem", ")" ]
Compute the system irreducibility for a given cut. 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: SystemIrreducibilityAnalysis: The |SystemIrreducibilityAnalysis| for that cut.
[ "Compute", "the", "system", "irreducibility", "for", "a", "given", "cut", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L113-L150
15,992
wmayner/pyphi
pyphi/compute/subsystem.py
sia_bipartitions
def sia_bipartitions(nodes, node_labels=None): """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. """ 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(bipartition[0], bipartition[1], node_labels) for bipartition in bipartitions]
python
def sia_bipartitions(nodes, node_labels=None): """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. """ 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(bipartition[0], bipartition[1], node_labels) for bipartition in bipartitions]
[ "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", "(", "bipartition", "[", "0", "]", ",", "bipartition", "[", "1", "]", ",", "node_labels", ")", "for", "bipartition", "in", "bipartitions", "]" ]
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.
[ "Return", "all", "|big_phi|", "cuts", "for", "the", "given", "nodes", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L184-L201
15,993
wmayner/pyphi
pyphi/compute/subsystem.py
_sia
def _sia(cache_key, subsystem): """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 irreducibility information for the given 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 strongly connected; # - empty; # - an elementary micro mechanism (i.e. no nontrivial bipartitions). # So in those cases we immediately return a null SIA. if not subsystem: log.info('Subsystem %s is empty; returning null SIA ' 'immediately.', subsystem) return _null_sia(subsystem) if not connectivity.is_strong(subsystem.cm, subsystem.node_indices): log.info('%s is not strongly connected; returning null SIA ' 'immediately.', subsystem) return _null_sia(subsystem) # Handle elementary micro mechanism cases. # Single macro element systems have nontrivial bipartitions because their # bipartitions are over their micro elements. if len(subsystem.cut_indices) == 1: # If the node lacks a self-loop, phi is trivially zero. if not subsystem.cm[subsystem.node_indices][subsystem.node_indices]: log.info('Single micro nodes %s without selfloops cannot have ' 'phi; returning null SIA immediately.', subsystem) return _null_sia(subsystem) # Even if the node has a self-loop, we may still define phi to be zero. elif not config.SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI: log.info('Single micro nodes %s with selfloops cannot have ' 'phi; returning null SIA immediately.', subsystem) return _null_sia(subsystem) # ========================================================================= log.debug('Finding unpartitioned CauseEffectStructure...') unpartitioned_ces = _ces(subsystem) if not unpartitioned_ces: log.info('Empty unpartitioned CauseEffectStructure; returning null ' 'SIA immediately.') # Short-circuit if there are no concepts in the unpartitioned CES. return _null_sia(subsystem) log.debug('Found unpartitioned CauseEffectStructure.') # TODO: move this into sia_bipartitions? # Only True if SINGLE_MICRO_NODES...=True, no? if len(subsystem.cut_indices) == 1: cuts = [Cut(subsystem.cut_indices, subsystem.cut_indices, subsystem.cut_node_labels)] else: cuts = sia_bipartitions(subsystem.cut_indices, subsystem.cut_node_labels) engine = ComputeSystemIrreducibility( cuts, subsystem, unpartitioned_ces) result = engine.run(config.PARALLEL_CUT_EVALUATION) if config.CLEAR_SUBSYSTEM_CACHES_AFTER_COMPUTING_SIA: log.debug('Clearing subsystem caches.') subsystem.clear_caches() log.info('Finished calculating big-phi data for %s.', subsystem) return result
python
def _sia(cache_key, subsystem): """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 irreducibility information for the given 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 strongly connected; # - empty; # - an elementary micro mechanism (i.e. no nontrivial bipartitions). # So in those cases we immediately return a null SIA. if not subsystem: log.info('Subsystem %s is empty; returning null SIA ' 'immediately.', subsystem) return _null_sia(subsystem) if not connectivity.is_strong(subsystem.cm, subsystem.node_indices): log.info('%s is not strongly connected; returning null SIA ' 'immediately.', subsystem) return _null_sia(subsystem) # Handle elementary micro mechanism cases. # Single macro element systems have nontrivial bipartitions because their # bipartitions are over their micro elements. if len(subsystem.cut_indices) == 1: # If the node lacks a self-loop, phi is trivially zero. if not subsystem.cm[subsystem.node_indices][subsystem.node_indices]: log.info('Single micro nodes %s without selfloops cannot have ' 'phi; returning null SIA immediately.', subsystem) return _null_sia(subsystem) # Even if the node has a self-loop, we may still define phi to be zero. elif not config.SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI: log.info('Single micro nodes %s with selfloops cannot have ' 'phi; returning null SIA immediately.', subsystem) return _null_sia(subsystem) # ========================================================================= log.debug('Finding unpartitioned CauseEffectStructure...') unpartitioned_ces = _ces(subsystem) if not unpartitioned_ces: log.info('Empty unpartitioned CauseEffectStructure; returning null ' 'SIA immediately.') # Short-circuit if there are no concepts in the unpartitioned CES. return _null_sia(subsystem) log.debug('Found unpartitioned CauseEffectStructure.') # TODO: move this into sia_bipartitions? # Only True if SINGLE_MICRO_NODES...=True, no? if len(subsystem.cut_indices) == 1: cuts = [Cut(subsystem.cut_indices, subsystem.cut_indices, subsystem.cut_node_labels)] else: cuts = sia_bipartitions(subsystem.cut_indices, subsystem.cut_node_labels) engine = ComputeSystemIrreducibility( cuts, subsystem, unpartitioned_ces) result = engine.run(config.PARALLEL_CUT_EVALUATION) if config.CLEAR_SUBSYSTEM_CACHES_AFTER_COMPUTING_SIA: log.debug('Clearing subsystem caches.') subsystem.clear_caches() log.info('Finished calculating big-phi data for %s.', subsystem) return result
[ "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 strongly connected;", "# - empty;", "# - an elementary micro mechanism (i.e. no nontrivial bipartitions).", "# So in those cases we immediately return a null SIA.", "if", "not", "subsystem", ":", "log", ".", "info", "(", "'Subsystem %s is empty; returning null SIA '", "'immediately.'", ",", "subsystem", ")", "return", "_null_sia", "(", "subsystem", ")", "if", "not", "connectivity", ".", "is_strong", "(", "subsystem", ".", "cm", ",", "subsystem", ".", "node_indices", ")", ":", "log", ".", "info", "(", "'%s is not strongly connected; returning null SIA '", "'immediately.'", ",", "subsystem", ")", "return", "_null_sia", "(", "subsystem", ")", "# Handle elementary micro mechanism cases.", "# Single macro element systems have nontrivial bipartitions because their", "# bipartitions are over their micro elements.", "if", "len", "(", "subsystem", ".", "cut_indices", ")", "==", "1", ":", "# If the node lacks a self-loop, phi is trivially zero.", "if", "not", "subsystem", ".", "cm", "[", "subsystem", ".", "node_indices", "]", "[", "subsystem", ".", "node_indices", "]", ":", "log", ".", "info", "(", "'Single micro nodes %s without selfloops cannot have '", "'phi; returning null SIA immediately.'", ",", "subsystem", ")", "return", "_null_sia", "(", "subsystem", ")", "# Even if the node has a self-loop, we may still define phi to be zero.", "elif", "not", "config", ".", "SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI", ":", "log", ".", "info", "(", "'Single micro nodes %s with selfloops cannot have '", "'phi; returning null SIA immediately.'", ",", "subsystem", ")", "return", "_null_sia", "(", "subsystem", ")", "# =========================================================================", "log", ".", "debug", "(", "'Finding unpartitioned CauseEffectStructure...'", ")", "unpartitioned_ces", "=", "_ces", "(", "subsystem", ")", "if", "not", "unpartitioned_ces", ":", "log", ".", "info", "(", "'Empty unpartitioned CauseEffectStructure; returning null '", "'SIA immediately.'", ")", "# Short-circuit if there are no concepts in the unpartitioned CES.", "return", "_null_sia", "(", "subsystem", ")", "log", ".", "debug", "(", "'Found unpartitioned CauseEffectStructure.'", ")", "# TODO: move this into sia_bipartitions?", "# Only True if SINGLE_MICRO_NODES...=True, no?", "if", "len", "(", "subsystem", ".", "cut_indices", ")", "==", "1", ":", "cuts", "=", "[", "Cut", "(", "subsystem", ".", "cut_indices", ",", "subsystem", ".", "cut_indices", ",", "subsystem", ".", "cut_node_labels", ")", "]", "else", ":", "cuts", "=", "sia_bipartitions", "(", "subsystem", ".", "cut_indices", ",", "subsystem", ".", "cut_node_labels", ")", "engine", "=", "ComputeSystemIrreducibility", "(", "cuts", ",", "subsystem", ",", "unpartitioned_ces", ")", "result", "=", "engine", ".", "run", "(", "config", ".", "PARALLEL_CUT_EVALUATION", ")", "if", "config", ".", "CLEAR_SUBSYSTEM_CACHES_AFTER_COMPUTING_SIA", ":", "log", ".", "debug", "(", "'Clearing subsystem caches.'", ")", "subsystem", ".", "clear_caches", "(", ")", "log", ".", "info", "(", "'Finished calculating big-phi data for %s.'", ",", "subsystem", ")", "return", "result" ]
Return the minimal information partition of a subsystem. 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 irreducibility information for the given subsystem.
[ "Return", "the", "minimal", "information", "partition", "of", "a", "subsystem", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L214-L292
15,994
wmayner/pyphi
pyphi/compute/subsystem.py
_sia_cache_key
def _sia_cache_key(subsystem): """The cache key of the subsystem. This includes the native hash of the subsystem and all configuration values which change the results of ``sia``. """ return ( hash(subsystem), config.ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS, config.CUT_ONE_APPROXIMATION, config.MEASURE, config.PRECISION, config.VALIDATE_SUBSYSTEM_STATES, config.SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI, config.PARTITION_TYPE, )
python
def _sia_cache_key(subsystem): """The cache key of the subsystem. This includes the native hash of the subsystem and all configuration values which change the results of ``sia``. """ return ( hash(subsystem), config.ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS, config.CUT_ONE_APPROXIMATION, config.MEASURE, config.PRECISION, config.VALIDATE_SUBSYSTEM_STATES, config.SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI, config.PARTITION_TYPE, )
[ "def", "_sia_cache_key", "(", "subsystem", ")", ":", "return", "(", "hash", "(", "subsystem", ")", ",", "config", ".", "ASSUME_CUTS_CANNOT_CREATE_NEW_CONCEPTS", ",", "config", ".", "CUT_ONE_APPROXIMATION", ",", "config", ".", "MEASURE", ",", "config", ".", "PRECISION", ",", "config", ".", "VALIDATE_SUBSYSTEM_STATES", ",", "config", ".", "SINGLE_MICRO_NODES_WITH_SELFLOOPS_HAVE_PHI", ",", "config", ".", "PARTITION_TYPE", ",", ")" ]
The cache key of the subsystem. This includes the native hash of the subsystem and all configuration values which change the results of ``sia``.
[ "The", "cache", "key", "of", "the", "subsystem", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L297-L312
15,995
wmayner/pyphi
pyphi/compute/subsystem.py
concept_cuts
def concept_cuts(direction, node_indices, node_labels=None): """Generator over all concept-syle cuts for these nodes.""" for partition in mip_partitions(node_indices, node_indices): yield KCut(direction, partition, node_labels)
python
def concept_cuts(direction, node_indices, node_labels=None): """Generator over all concept-syle cuts for these nodes.""" for partition in mip_partitions(node_indices, node_indices): yield KCut(direction, partition, node_labels)
[ "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.
[ "Generator", "over", "all", "concept", "-", "syle", "cuts", "for", "these", "nodes", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L390-L393
15,996
wmayner/pyphi
pyphi/compute/subsystem.py
directional_sia
def directional_sia(subsystem, direction, unpartitioned_ces=None): """Calculate a concept-style SystemIrreducibilityAnalysisCause or SystemIrreducibilityAnalysisEffect. """ if unpartitioned_ces is None: unpartitioned_ces = _ces(subsystem) c_system = ConceptStyleSystem(subsystem, direction) cuts = concept_cuts(direction, c_system.cut_indices, subsystem.node_labels) # Run the default SIA engine # TODO: verify that short-cutting works correctly? engine = ComputeSystemIrreducibility( cuts, c_system, unpartitioned_ces) return engine.run(config.PARALLEL_CUT_EVALUATION)
python
def directional_sia(subsystem, direction, unpartitioned_ces=None): """Calculate a concept-style SystemIrreducibilityAnalysisCause or SystemIrreducibilityAnalysisEffect. """ if unpartitioned_ces is None: unpartitioned_ces = _ces(subsystem) c_system = ConceptStyleSystem(subsystem, direction) cuts = concept_cuts(direction, c_system.cut_indices, subsystem.node_labels) # Run the default SIA engine # TODO: verify that short-cutting works correctly? engine = ComputeSystemIrreducibility( cuts, c_system, unpartitioned_ces) return engine.run(config.PARALLEL_CUT_EVALUATION)
[ "def", "directional_sia", "(", "subsystem", ",", "direction", ",", "unpartitioned_ces", "=", "None", ")", ":", "if", "unpartitioned_ces", "is", "None", ":", "unpartitioned_ces", "=", "_ces", "(", "subsystem", ")", "c_system", "=", "ConceptStyleSystem", "(", "subsystem", ",", "direction", ")", "cuts", "=", "concept_cuts", "(", "direction", ",", "c_system", ".", "cut_indices", ",", "subsystem", ".", "node_labels", ")", "# Run the default SIA engine", "# TODO: verify that short-cutting works correctly?", "engine", "=", "ComputeSystemIrreducibility", "(", "cuts", ",", "c_system", ",", "unpartitioned_ces", ")", "return", "engine", ".", "run", "(", "config", ".", "PARALLEL_CUT_EVALUATION", ")" ]
Calculate a concept-style SystemIrreducibilityAnalysisCause or SystemIrreducibilityAnalysisEffect.
[ "Calculate", "a", "concept", "-", "style", "SystemIrreducibilityAnalysisCause", "or", "SystemIrreducibilityAnalysisEffect", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L396-L410
15,997
wmayner/pyphi
pyphi/compute/subsystem.py
sia_concept_style
def sia_concept_style(subsystem): """Compute a concept-style SystemIrreducibilityAnalysis""" unpartitioned_ces = _ces(subsystem) sia_cause = directional_sia(subsystem, Direction.CAUSE, unpartitioned_ces) sia_effect = directional_sia(subsystem, Direction.EFFECT, unpartitioned_ces) return SystemIrreducibilityAnalysisConceptStyle(sia_cause, sia_effect)
python
def sia_concept_style(subsystem): """Compute a concept-style SystemIrreducibilityAnalysis""" unpartitioned_ces = _ces(subsystem) sia_cause = directional_sia(subsystem, Direction.CAUSE, unpartitioned_ces) sia_effect = directional_sia(subsystem, Direction.EFFECT, unpartitioned_ces) return SystemIrreducibilityAnalysisConceptStyle(sia_cause, sia_effect)
[ "def", "sia_concept_style", "(", "subsystem", ")", ":", "unpartitioned_ces", "=", "_ces", "(", "subsystem", ")", "sia_cause", "=", "directional_sia", "(", "subsystem", ",", "Direction", ".", "CAUSE", ",", "unpartitioned_ces", ")", "sia_effect", "=", "directional_sia", "(", "subsystem", ",", "Direction", ".", "EFFECT", ",", "unpartitioned_ces", ")", "return", "SystemIrreducibilityAnalysisConceptStyle", "(", "sia_cause", ",", "sia_effect", ")" ]
Compute a concept-style SystemIrreducibilityAnalysis
[ "Compute", "a", "concept", "-", "style", "SystemIrreducibilityAnalysis" ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L447-L456
15,998
wmayner/pyphi
pyphi/compute/subsystem.py
ComputeCauseEffectStructure.compute
def compute(mechanism, subsystem, purviews, cause_purviews, effect_purviews): """Compute a |Concept| for a mechanism, in this |Subsystem| with the provided purviews. """ concept = subsystem.concept(mechanism, purviews=purviews, cause_purviews=cause_purviews, effect_purviews=effect_purviews) # Don't serialize the subsystem. # This is replaced on the other side of the queue, and ensures # that all concepts in the CES reference the same subsystem. concept.subsystem = None return concept
python
def compute(mechanism, subsystem, purviews, cause_purviews, effect_purviews): """Compute a |Concept| for a mechanism, in this |Subsystem| with the provided purviews. """ concept = subsystem.concept(mechanism, purviews=purviews, cause_purviews=cause_purviews, effect_purviews=effect_purviews) # Don't serialize the subsystem. # This is replaced on the other side of the queue, and ensures # that all concepts in the CES reference the same subsystem. concept.subsystem = None return concept
[ "def", "compute", "(", "mechanism", ",", "subsystem", ",", "purviews", ",", "cause_purviews", ",", "effect_purviews", ")", ":", "concept", "=", "subsystem", ".", "concept", "(", "mechanism", ",", "purviews", "=", "purviews", ",", "cause_purviews", "=", "cause_purviews", ",", "effect_purviews", "=", "effect_purviews", ")", "# Don't serialize the subsystem.", "# This is replaced on the other side of the queue, and ensures", "# that all concepts in the CES reference the same subsystem.", "concept", ".", "subsystem", "=", "None", "return", "concept" ]
Compute a |Concept| for a mechanism, in this |Subsystem| with the provided purviews.
[ "Compute", "a", "|Concept|", "for", "a", "mechanism", "in", "this", "|Subsystem|", "with", "the", "provided", "purviews", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L39-L52
15,999
wmayner/pyphi
pyphi/compute/subsystem.py
ComputeCauseEffectStructure.process_result
def process_result(self, new_concept, concepts): """Save all concepts with non-zero |small_phi| to the |CauseEffectStructure|. """ if new_concept.phi > 0: # Replace the subsystem new_concept.subsystem = self.subsystem concepts.append(new_concept) return concepts
python
def process_result(self, new_concept, concepts): """Save all concepts with non-zero |small_phi| to the |CauseEffectStructure|. """ if new_concept.phi > 0: # Replace the subsystem new_concept.subsystem = self.subsystem concepts.append(new_concept) return concepts
[ "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 |CauseEffectStructure|.
[ "Save", "all", "concepts", "with", "non", "-", "zero", "|small_phi|", "to", "the", "|CauseEffectStructure|", "." ]
deeca69a084d782a6fde7bf26f59e93b593c5d77
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L54-L62