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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,000
|
wmayner/pyphi
|
pyphi/compute/subsystem.py
|
ComputeSystemIrreducibility.process_result
|
def process_result(self, new_sia, min_sia):
"""Check if the new SIA has smaller |big_phi| than the standing
result.
"""
if new_sia.phi == 0:
self.done = True # Short-circuit
return new_sia
elif new_sia < min_sia:
return new_sia
return min_sia
|
python
|
def process_result(self, new_sia, min_sia):
"""Check if the new SIA has smaller |big_phi| than the standing
result.
"""
if new_sia.phi == 0:
self.done = True # Short-circuit
return new_sia
elif new_sia < min_sia:
return new_sia
return min_sia
|
[
"def",
"process_result",
"(",
"self",
",",
"new_sia",
",",
"min_sia",
")",
":",
"if",
"new_sia",
".",
"phi",
"==",
"0",
":",
"self",
".",
"done",
"=",
"True",
"# Short-circuit",
"return",
"new_sia",
"elif",
"new_sia",
"<",
"min_sia",
":",
"return",
"new_sia",
"return",
"min_sia"
] |
Check if the new SIA has smaller |big_phi| than the standing
result.
|
[
"Check",
"if",
"the",
"new",
"SIA",
"has",
"smaller",
"|big_phi|",
"than",
"the",
"standing",
"result",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L170-L181
|
16,001
|
wmayner/pyphi
|
pyphi/compute/subsystem.py
|
ConceptStyleSystem.concept
|
def concept(self, mechanism, purviews=False, cause_purviews=False,
effect_purviews=False):
"""Compute a concept, using the appropriate system for each side of the
cut.
"""
cause = self.cause_system.mic(
mechanism, purviews=(cause_purviews or purviews))
effect = self.effect_system.mie(
mechanism, purviews=(effect_purviews or purviews))
return Concept(mechanism=mechanism, cause=cause, effect=effect,
subsystem=self)
|
python
|
def concept(self, mechanism, purviews=False, cause_purviews=False,
effect_purviews=False):
"""Compute a concept, using the appropriate system for each side of the
cut.
"""
cause = self.cause_system.mic(
mechanism, purviews=(cause_purviews or purviews))
effect = self.effect_system.mie(
mechanism, purviews=(effect_purviews or purviews))
return Concept(mechanism=mechanism, cause=cause, effect=effect,
subsystem=self)
|
[
"def",
"concept",
"(",
"self",
",",
"mechanism",
",",
"purviews",
"=",
"False",
",",
"cause_purviews",
"=",
"False",
",",
"effect_purviews",
"=",
"False",
")",
":",
"cause",
"=",
"self",
".",
"cause_system",
".",
"mic",
"(",
"mechanism",
",",
"purviews",
"=",
"(",
"cause_purviews",
"or",
"purviews",
")",
")",
"effect",
"=",
"self",
".",
"effect_system",
".",
"mie",
"(",
"mechanism",
",",
"purviews",
"=",
"(",
"effect_purviews",
"or",
"purviews",
")",
")",
"return",
"Concept",
"(",
"mechanism",
"=",
"mechanism",
",",
"cause",
"=",
"cause",
",",
"effect",
"=",
"effect",
",",
"subsystem",
"=",
"self",
")"
] |
Compute a concept, using the appropriate system for each side of the
cut.
|
[
"Compute",
"a",
"concept",
"using",
"the",
"appropriate",
"system",
"for",
"each",
"side",
"of",
"the",
"cut",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L372-L384
|
16,002
|
wmayner/pyphi
|
pyphi/labels.py
|
NodeLabels.coerce_to_indices
|
def coerce_to_indices(self, nodes):
"""Return the nodes indices for nodes, where ``nodes`` is either
already integer indices or node labels.
"""
if nodes is None:
return self.node_indices
if all(isinstance(node, str) for node in nodes):
indices = self.labels2indices(nodes)
else:
indices = map(int, nodes)
return tuple(sorted(set(indices)))
|
python
|
def coerce_to_indices(self, nodes):
"""Return the nodes indices for nodes, where ``nodes`` is either
already integer indices or node labels.
"""
if nodes is None:
return self.node_indices
if all(isinstance(node, str) for node in nodes):
indices = self.labels2indices(nodes)
else:
indices = map(int, nodes)
return tuple(sorted(set(indices)))
|
[
"def",
"coerce_to_indices",
"(",
"self",
",",
"nodes",
")",
":",
"if",
"nodes",
"is",
"None",
":",
"return",
"self",
".",
"node_indices",
"if",
"all",
"(",
"isinstance",
"(",
"node",
",",
"str",
")",
"for",
"node",
"in",
"nodes",
")",
":",
"indices",
"=",
"self",
".",
"labels2indices",
"(",
"nodes",
")",
"else",
":",
"indices",
"=",
"map",
"(",
"int",
",",
"nodes",
")",
"return",
"tuple",
"(",
"sorted",
"(",
"set",
"(",
"indices",
")",
")",
")"
] |
Return the nodes indices for nodes, where ``nodes`` is either
already integer indices or node labels.
|
[
"Return",
"the",
"nodes",
"indices",
"for",
"nodes",
"where",
"nodes",
"is",
"either",
"already",
"integer",
"indices",
"or",
"node",
"labels",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/labels.py#L82-L93
|
16,003
|
wmayner/pyphi
|
pyphi/models/subsystem.py
|
_null_sia
|
def _null_sia(subsystem, phi=0.0):
"""Return a |SystemIrreducibilityAnalysis| with zero |big_phi| and empty
cause-effect structures.
This is the analysis result for a reducible subsystem.
"""
return SystemIrreducibilityAnalysis(subsystem=subsystem,
cut_subsystem=subsystem,
phi=phi,
ces=_null_ces(subsystem),
partitioned_ces=_null_ces(subsystem))
|
python
|
def _null_sia(subsystem, phi=0.0):
"""Return a |SystemIrreducibilityAnalysis| with zero |big_phi| and empty
cause-effect structures.
This is the analysis result for a reducible subsystem.
"""
return SystemIrreducibilityAnalysis(subsystem=subsystem,
cut_subsystem=subsystem,
phi=phi,
ces=_null_ces(subsystem),
partitioned_ces=_null_ces(subsystem))
|
[
"def",
"_null_sia",
"(",
"subsystem",
",",
"phi",
"=",
"0.0",
")",
":",
"return",
"SystemIrreducibilityAnalysis",
"(",
"subsystem",
"=",
"subsystem",
",",
"cut_subsystem",
"=",
"subsystem",
",",
"phi",
"=",
"phi",
",",
"ces",
"=",
"_null_ces",
"(",
"subsystem",
")",
",",
"partitioned_ces",
"=",
"_null_ces",
"(",
"subsystem",
")",
")"
] |
Return a |SystemIrreducibilityAnalysis| with zero |big_phi| and empty
cause-effect structures.
This is the analysis result for a reducible subsystem.
|
[
"Return",
"a",
"|SystemIrreducibilityAnalysis|",
"with",
"zero",
"|big_phi|",
"and",
"empty",
"cause",
"-",
"effect",
"structures",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/subsystem.py#L179-L189
|
16,004
|
wmayner/pyphi
|
pyphi/models/subsystem.py
|
CauseEffectStructure.labeled_mechanisms
|
def labeled_mechanisms(self):
"""The labeled mechanism of each concept."""
label = self.subsystem.node_labels.indices2labels
return tuple(list(label(mechanism)) for mechanism in self.mechanisms)
|
python
|
def labeled_mechanisms(self):
"""The labeled mechanism of each concept."""
label = self.subsystem.node_labels.indices2labels
return tuple(list(label(mechanism)) for mechanism in self.mechanisms)
|
[
"def",
"labeled_mechanisms",
"(",
"self",
")",
":",
"label",
"=",
"self",
".",
"subsystem",
".",
"node_labels",
".",
"indices2labels",
"return",
"tuple",
"(",
"list",
"(",
"label",
"(",
"mechanism",
")",
")",
"for",
"mechanism",
"in",
"self",
".",
"mechanisms",
")"
] |
The labeled mechanism of each concept.
|
[
"The",
"labeled",
"mechanism",
"of",
"each",
"concept",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/subsystem.py#L69-L72
|
16,005
|
wmayner/pyphi
|
pyphi/direction.py
|
Direction.order
|
def order(self, mechanism, purview):
"""Order the mechanism and purview in time.
If the direction is ``CAUSE``, then the purview is at |t-1| and the
mechanism is at time |t|. If the direction is ``EFFECT``, then the
mechanism is at time |t| and the purview is at |t+1|.
"""
if self is Direction.CAUSE:
return purview, mechanism
elif self is Direction.EFFECT:
return mechanism, purview
from . import validate
return validate.direction(self)
|
python
|
def order(self, mechanism, purview):
"""Order the mechanism and purview in time.
If the direction is ``CAUSE``, then the purview is at |t-1| and the
mechanism is at time |t|. If the direction is ``EFFECT``, then the
mechanism is at time |t| and the purview is at |t+1|.
"""
if self is Direction.CAUSE:
return purview, mechanism
elif self is Direction.EFFECT:
return mechanism, purview
from . import validate
return validate.direction(self)
|
[
"def",
"order",
"(",
"self",
",",
"mechanism",
",",
"purview",
")",
":",
"if",
"self",
"is",
"Direction",
".",
"CAUSE",
":",
"return",
"purview",
",",
"mechanism",
"elif",
"self",
"is",
"Direction",
".",
"EFFECT",
":",
"return",
"mechanism",
",",
"purview",
"from",
".",
"import",
"validate",
"return",
"validate",
".",
"direction",
"(",
"self",
")"
] |
Order the mechanism and purview in time.
If the direction is ``CAUSE``, then the purview is at |t-1| and the
mechanism is at time |t|. If the direction is ``EFFECT``, then the
mechanism is at time |t| and the purview is at |t+1|.
|
[
"Order",
"the",
"mechanism",
"and",
"purview",
"in",
"time",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/direction.py#L31-L44
|
16,006
|
wmayner/pyphi
|
pyphi/models/cmp.py
|
sametype
|
def sametype(func):
"""Method decorator to return ``NotImplemented`` if the args of the wrapped
method are of different types.
When wrapping a rich model comparison method this will delegate (reflect)
the comparison to the right-hand-side object, or fallback by passing it up
the inheritance tree.
"""
@functools.wraps(func)
def wrapper(self, other): # pylint: disable=missing-docstring
if type(other) is not type(self):
return NotImplemented
return func(self, other)
return wrapper
|
python
|
def sametype(func):
"""Method decorator to return ``NotImplemented`` if the args of the wrapped
method are of different types.
When wrapping a rich model comparison method this will delegate (reflect)
the comparison to the right-hand-side object, or fallback by passing it up
the inheritance tree.
"""
@functools.wraps(func)
def wrapper(self, other): # pylint: disable=missing-docstring
if type(other) is not type(self):
return NotImplemented
return func(self, other)
return wrapper
|
[
"def",
"sametype",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
"# pylint: disable=missing-docstring",
"if",
"type",
"(",
"other",
")",
"is",
"not",
"type",
"(",
"self",
")",
":",
"return",
"NotImplemented",
"return",
"func",
"(",
"self",
",",
"other",
")",
"return",
"wrapper"
] |
Method decorator to return ``NotImplemented`` if the args of the wrapped
method are of different types.
When wrapping a rich model comparison method this will delegate (reflect)
the comparison to the right-hand-side object, or fallback by passing it up
the inheritance tree.
|
[
"Method",
"decorator",
"to",
"return",
"NotImplemented",
"if",
"the",
"args",
"of",
"the",
"wrapped",
"method",
"are",
"of",
"different",
"types",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/cmp.py#L19-L32
|
16,007
|
wmayner/pyphi
|
pyphi/models/cmp.py
|
general_eq
|
def general_eq(a, b, attributes):
"""Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared with
:func:`numpy_aware_eq`.
"""
try:
for attr in attributes:
_a, _b = getattr(a, attr), getattr(b, attr)
if attr in ['phi', 'alpha']:
if not utils.eq(_a, _b):
return False
elif attr in ['mechanism', 'purview']:
if _a is None or _b is None:
if _a != _b:
return False
elif not set(_a) == set(_b):
return False
else:
if not numpy_aware_eq(_a, _b):
return False
return True
except AttributeError:
return False
|
python
|
def general_eq(a, b, attributes):
"""Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared with
:func:`numpy_aware_eq`.
"""
try:
for attr in attributes:
_a, _b = getattr(a, attr), getattr(b, attr)
if attr in ['phi', 'alpha']:
if not utils.eq(_a, _b):
return False
elif attr in ['mechanism', 'purview']:
if _a is None or _b is None:
if _a != _b:
return False
elif not set(_a) == set(_b):
return False
else:
if not numpy_aware_eq(_a, _b):
return False
return True
except AttributeError:
return False
|
[
"def",
"general_eq",
"(",
"a",
",",
"b",
",",
"attributes",
")",
":",
"try",
":",
"for",
"attr",
"in",
"attributes",
":",
"_a",
",",
"_b",
"=",
"getattr",
"(",
"a",
",",
"attr",
")",
",",
"getattr",
"(",
"b",
",",
"attr",
")",
"if",
"attr",
"in",
"[",
"'phi'",
",",
"'alpha'",
"]",
":",
"if",
"not",
"utils",
".",
"eq",
"(",
"_a",
",",
"_b",
")",
":",
"return",
"False",
"elif",
"attr",
"in",
"[",
"'mechanism'",
",",
"'purview'",
"]",
":",
"if",
"_a",
"is",
"None",
"or",
"_b",
"is",
"None",
":",
"if",
"_a",
"!=",
"_b",
":",
"return",
"False",
"elif",
"not",
"set",
"(",
"_a",
")",
"==",
"set",
"(",
"_b",
")",
":",
"return",
"False",
"else",
":",
"if",
"not",
"numpy_aware_eq",
"(",
"_a",
",",
"_b",
")",
":",
"return",
"False",
"return",
"True",
"except",
"AttributeError",
":",
"return",
"False"
] |
Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared with
:func:`numpy_aware_eq`.
|
[
"Return",
"whether",
"two",
"objects",
"are",
"equal",
"up",
"to",
"the",
"given",
"attributes",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/cmp.py#L108-L133
|
16,008
|
wmayner/pyphi
|
benchmarks/time_emd.py
|
time_emd
|
def time_emd(emd_type, data):
"""Time an EMD command with the given data as arguments"""
emd = {
'cause': _CAUSE_EMD,
'effect': pyphi.subsystem.effect_emd,
'hamming': pyphi.utils.hamming_emd
}[emd_type]
def statement():
for (d1, d2) in data:
emd(d1, d2)
results = timeit.repeat(statement, number=NUMBER, repeat=REPEAT)
return min(results)
|
python
|
def time_emd(emd_type, data):
"""Time an EMD command with the given data as arguments"""
emd = {
'cause': _CAUSE_EMD,
'effect': pyphi.subsystem.effect_emd,
'hamming': pyphi.utils.hamming_emd
}[emd_type]
def statement():
for (d1, d2) in data:
emd(d1, d2)
results = timeit.repeat(statement, number=NUMBER, repeat=REPEAT)
return min(results)
|
[
"def",
"time_emd",
"(",
"emd_type",
",",
"data",
")",
":",
"emd",
"=",
"{",
"'cause'",
":",
"_CAUSE_EMD",
",",
"'effect'",
":",
"pyphi",
".",
"subsystem",
".",
"effect_emd",
",",
"'hamming'",
":",
"pyphi",
".",
"utils",
".",
"hamming_emd",
"}",
"[",
"emd_type",
"]",
"def",
"statement",
"(",
")",
":",
"for",
"(",
"d1",
",",
"d2",
")",
"in",
"data",
":",
"emd",
"(",
"d1",
",",
"d2",
")",
"results",
"=",
"timeit",
".",
"repeat",
"(",
"statement",
",",
"number",
"=",
"NUMBER",
",",
"repeat",
"=",
"REPEAT",
")",
"return",
"min",
"(",
"results",
")"
] |
Time an EMD command with the given data as arguments
|
[
"Time",
"an",
"EMD",
"command",
"with",
"the",
"given",
"data",
"as",
"arguments"
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/benchmarks/time_emd.py#L320-L335
|
16,009
|
wmayner/pyphi
|
pyphi/distribution.py
|
marginal_zero
|
def marginal_zero(repertoire, node_index):
"""Return the marginal probability that the node is OFF."""
index = [slice(None)] * repertoire.ndim
index[node_index] = 0
return repertoire[tuple(index)].sum()
|
python
|
def marginal_zero(repertoire, node_index):
"""Return the marginal probability that the node is OFF."""
index = [slice(None)] * repertoire.ndim
index[node_index] = 0
return repertoire[tuple(index)].sum()
|
[
"def",
"marginal_zero",
"(",
"repertoire",
",",
"node_index",
")",
":",
"index",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"repertoire",
".",
"ndim",
"index",
"[",
"node_index",
"]",
"=",
"0",
"return",
"repertoire",
"[",
"tuple",
"(",
"index",
")",
"]",
".",
"sum",
"(",
")"
] |
Return the marginal probability that the node is OFF.
|
[
"Return",
"the",
"marginal",
"probability",
"that",
"the",
"node",
"is",
"OFF",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L50-L55
|
16,010
|
wmayner/pyphi
|
pyphi/distribution.py
|
marginal
|
def marginal(repertoire, node_index):
"""Get the marginal distribution for a node."""
index = tuple(i for i in range(repertoire.ndim) if i != node_index)
return repertoire.sum(index, keepdims=True)
|
python
|
def marginal(repertoire, node_index):
"""Get the marginal distribution for a node."""
index = tuple(i for i in range(repertoire.ndim) if i != node_index)
return repertoire.sum(index, keepdims=True)
|
[
"def",
"marginal",
"(",
"repertoire",
",",
"node_index",
")",
":",
"index",
"=",
"tuple",
"(",
"i",
"for",
"i",
"in",
"range",
"(",
"repertoire",
".",
"ndim",
")",
"if",
"i",
"!=",
"node_index",
")",
"return",
"repertoire",
".",
"sum",
"(",
"index",
",",
"keepdims",
"=",
"True",
")"
] |
Get the marginal distribution for a node.
|
[
"Get",
"the",
"marginal",
"distribution",
"for",
"a",
"node",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L58-L62
|
16,011
|
wmayner/pyphi
|
pyphi/distribution.py
|
independent
|
def independent(repertoire):
"""Check whether the repertoire is independent."""
marginals = [marginal(repertoire, i) for i in range(repertoire.ndim)]
# TODO: is there a way to do without an explicit iteration?
joint = marginals[0]
for m in marginals[1:]:
joint = joint * m
# TODO: should we round here?
# repertoire = repertoire.round(config.PRECISION)
# joint = joint.round(config.PRECISION)
return np.array_equal(repertoire, joint)
|
python
|
def independent(repertoire):
"""Check whether the repertoire is independent."""
marginals = [marginal(repertoire, i) for i in range(repertoire.ndim)]
# TODO: is there a way to do without an explicit iteration?
joint = marginals[0]
for m in marginals[1:]:
joint = joint * m
# TODO: should we round here?
# repertoire = repertoire.round(config.PRECISION)
# joint = joint.round(config.PRECISION)
return np.array_equal(repertoire, joint)
|
[
"def",
"independent",
"(",
"repertoire",
")",
":",
"marginals",
"=",
"[",
"marginal",
"(",
"repertoire",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"repertoire",
".",
"ndim",
")",
"]",
"# TODO: is there a way to do without an explicit iteration?",
"joint",
"=",
"marginals",
"[",
"0",
"]",
"for",
"m",
"in",
"marginals",
"[",
"1",
":",
"]",
":",
"joint",
"=",
"joint",
"*",
"m",
"# TODO: should we round here?",
"# repertoire = repertoire.round(config.PRECISION)",
"# joint = joint.round(config.PRECISION)",
"return",
"np",
".",
"array_equal",
"(",
"repertoire",
",",
"joint",
")"
] |
Check whether the repertoire is independent.
|
[
"Check",
"whether",
"the",
"repertoire",
"is",
"independent",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L65-L78
|
16,012
|
wmayner/pyphi
|
pyphi/distribution.py
|
purview
|
def purview(repertoire):
"""The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over.
"""
if repertoire is None:
return None
return tuple(i for i, dim in enumerate(repertoire.shape) if dim == 2)
|
python
|
def purview(repertoire):
"""The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over.
"""
if repertoire is None:
return None
return tuple(i for i, dim in enumerate(repertoire.shape) if dim == 2)
|
[
"def",
"purview",
"(",
"repertoire",
")",
":",
"if",
"repertoire",
"is",
"None",
":",
"return",
"None",
"return",
"tuple",
"(",
"i",
"for",
"i",
",",
"dim",
"in",
"enumerate",
"(",
"repertoire",
".",
"shape",
")",
"if",
"dim",
"==",
"2",
")"
] |
The purview of the repertoire.
Args:
repertoire (np.ndarray): A repertoire
Returns:
tuple[int]: The purview that the repertoire was computed over.
|
[
"The",
"purview",
"of",
"the",
"repertoire",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L81-L93
|
16,013
|
wmayner/pyphi
|
pyphi/distribution.py
|
flatten
|
def flatten(repertoire, big_endian=False):
"""Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the repertoire in big-endian
order.
Returns:
np.ndarray: The flattened repertoire.
"""
if repertoire is None:
return None
order = 'C' if big_endian else 'F'
# For efficiency, use `ravel` (which returns a view of the array) instead
# of `np.flatten` (which copies the whole array).
return repertoire.squeeze().ravel(order=order)
|
python
|
def flatten(repertoire, big_endian=False):
"""Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the repertoire in big-endian
order.
Returns:
np.ndarray: The flattened repertoire.
"""
if repertoire is None:
return None
order = 'C' if big_endian else 'F'
# For efficiency, use `ravel` (which returns a view of the array) instead
# of `np.flatten` (which copies the whole array).
return repertoire.squeeze().ravel(order=order)
|
[
"def",
"flatten",
"(",
"repertoire",
",",
"big_endian",
"=",
"False",
")",
":",
"if",
"repertoire",
"is",
"None",
":",
"return",
"None",
"order",
"=",
"'C'",
"if",
"big_endian",
"else",
"'F'",
"# For efficiency, use `ravel` (which returns a view of the array) instead",
"# of `np.flatten` (which copies the whole array).",
"return",
"repertoire",
".",
"squeeze",
"(",
")",
".",
"ravel",
"(",
"order",
"=",
"order",
")"
] |
Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the repertoire in big-endian
order.
Returns:
np.ndarray: The flattened repertoire.
|
[
"Flatten",
"a",
"repertoire",
"removing",
"empty",
"dimensions",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L130-L151
|
16,014
|
wmayner/pyphi
|
pyphi/distribution.py
|
max_entropy_distribution
|
def max_entropy_distribution(node_indices, number_of_nodes):
"""Return the maximum entropy distribution over a set of nodes.
This is different from the network's uniform distribution because nodes
outside ``node_indices`` are fixed and treated as if they have only 1
state.
Args:
node_indices (tuple[int]): The set of node indices over which to take
the distribution.
number_of_nodes (int): The total number of nodes in the network.
Returns:
np.ndarray: The maximum entropy distribution over the set of nodes.
"""
distribution = np.ones(repertoire_shape(node_indices, number_of_nodes))
return distribution / distribution.size
|
python
|
def max_entropy_distribution(node_indices, number_of_nodes):
"""Return the maximum entropy distribution over a set of nodes.
This is different from the network's uniform distribution because nodes
outside ``node_indices`` are fixed and treated as if they have only 1
state.
Args:
node_indices (tuple[int]): The set of node indices over which to take
the distribution.
number_of_nodes (int): The total number of nodes in the network.
Returns:
np.ndarray: The maximum entropy distribution over the set of nodes.
"""
distribution = np.ones(repertoire_shape(node_indices, number_of_nodes))
return distribution / distribution.size
|
[
"def",
"max_entropy_distribution",
"(",
"node_indices",
",",
"number_of_nodes",
")",
":",
"distribution",
"=",
"np",
".",
"ones",
"(",
"repertoire_shape",
"(",
"node_indices",
",",
"number_of_nodes",
")",
")",
"return",
"distribution",
"/",
"distribution",
".",
"size"
] |
Return the maximum entropy distribution over a set of nodes.
This is different from the network's uniform distribution because nodes
outside ``node_indices`` are fixed and treated as if they have only 1
state.
Args:
node_indices (tuple[int]): The set of node indices over which to take
the distribution.
number_of_nodes (int): The total number of nodes in the network.
Returns:
np.ndarray: The maximum entropy distribution over the set of nodes.
|
[
"Return",
"the",
"maximum",
"entropy",
"distribution",
"over",
"a",
"set",
"of",
"nodes",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L155-L172
|
16,015
|
wmayner/pyphi
|
pyphi/macro.py
|
run_tpm
|
def run_tpm(system, steps, blackbox):
"""Iterate the TPM for the given number of timesteps.
Returns:
np.ndarray: tpm * (noise_tpm^(t-1))
"""
# Generate noised TPM
# Noise the connections from every output element to elements in other
# boxes.
node_tpms = []
for node in system.nodes:
node_tpm = node.tpm_on
for input_node in node.inputs:
if not blackbox.in_same_box(node.index, input_node):
if input_node in blackbox.output_indices:
node_tpm = marginalize_out([input_node], node_tpm)
node_tpms.append(node_tpm)
noised_tpm = rebuild_system_tpm(node_tpms)
noised_tpm = convert.state_by_node2state_by_state(noised_tpm)
tpm = convert.state_by_node2state_by_state(system.tpm)
# Muliply by noise
tpm = np.dot(tpm, np.linalg.matrix_power(noised_tpm, steps - 1))
return convert.state_by_state2state_by_node(tpm)
|
python
|
def run_tpm(system, steps, blackbox):
"""Iterate the TPM for the given number of timesteps.
Returns:
np.ndarray: tpm * (noise_tpm^(t-1))
"""
# Generate noised TPM
# Noise the connections from every output element to elements in other
# boxes.
node_tpms = []
for node in system.nodes:
node_tpm = node.tpm_on
for input_node in node.inputs:
if not blackbox.in_same_box(node.index, input_node):
if input_node in blackbox.output_indices:
node_tpm = marginalize_out([input_node], node_tpm)
node_tpms.append(node_tpm)
noised_tpm = rebuild_system_tpm(node_tpms)
noised_tpm = convert.state_by_node2state_by_state(noised_tpm)
tpm = convert.state_by_node2state_by_state(system.tpm)
# Muliply by noise
tpm = np.dot(tpm, np.linalg.matrix_power(noised_tpm, steps - 1))
return convert.state_by_state2state_by_node(tpm)
|
[
"def",
"run_tpm",
"(",
"system",
",",
"steps",
",",
"blackbox",
")",
":",
"# Generate noised TPM",
"# Noise the connections from every output element to elements in other",
"# boxes.",
"node_tpms",
"=",
"[",
"]",
"for",
"node",
"in",
"system",
".",
"nodes",
":",
"node_tpm",
"=",
"node",
".",
"tpm_on",
"for",
"input_node",
"in",
"node",
".",
"inputs",
":",
"if",
"not",
"blackbox",
".",
"in_same_box",
"(",
"node",
".",
"index",
",",
"input_node",
")",
":",
"if",
"input_node",
"in",
"blackbox",
".",
"output_indices",
":",
"node_tpm",
"=",
"marginalize_out",
"(",
"[",
"input_node",
"]",
",",
"node_tpm",
")",
"node_tpms",
".",
"append",
"(",
"node_tpm",
")",
"noised_tpm",
"=",
"rebuild_system_tpm",
"(",
"node_tpms",
")",
"noised_tpm",
"=",
"convert",
".",
"state_by_node2state_by_state",
"(",
"noised_tpm",
")",
"tpm",
"=",
"convert",
".",
"state_by_node2state_by_state",
"(",
"system",
".",
"tpm",
")",
"# Muliply by noise",
"tpm",
"=",
"np",
".",
"dot",
"(",
"tpm",
",",
"np",
".",
"linalg",
".",
"matrix_power",
"(",
"noised_tpm",
",",
"steps",
"-",
"1",
")",
")",
"return",
"convert",
".",
"state_by_state2state_by_node",
"(",
"tpm",
")"
] |
Iterate the TPM for the given number of timesteps.
Returns:
np.ndarray: tpm * (noise_tpm^(t-1))
|
[
"Iterate",
"the",
"TPM",
"for",
"the",
"given",
"number",
"of",
"timesteps",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L61-L88
|
16,016
|
wmayner/pyphi
|
pyphi/macro.py
|
_partitions_list
|
def _partitions_list(N):
"""Return a list of partitions of the |N| binary nodes.
Args:
N (int): The number of nodes under consideration.
Returns:
list[list]: A list of lists, where each inner list is the set of
micro-elements corresponding to a macro-element.
Example:
>>> _partitions_list(3)
[[[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], [[0], [1], [2]]]
"""
if N < (_NUM_PRECOMPUTED_PARTITION_LISTS):
return list(_partition_lists[N])
else:
raise ValueError(
'Partition lists not yet available for system with {} '
'nodes or more'.format(_NUM_PRECOMPUTED_PARTITION_LISTS))
|
python
|
def _partitions_list(N):
"""Return a list of partitions of the |N| binary nodes.
Args:
N (int): The number of nodes under consideration.
Returns:
list[list]: A list of lists, where each inner list is the set of
micro-elements corresponding to a macro-element.
Example:
>>> _partitions_list(3)
[[[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], [[0], [1], [2]]]
"""
if N < (_NUM_PRECOMPUTED_PARTITION_LISTS):
return list(_partition_lists[N])
else:
raise ValueError(
'Partition lists not yet available for system with {} '
'nodes or more'.format(_NUM_PRECOMPUTED_PARTITION_LISTS))
|
[
"def",
"_partitions_list",
"(",
"N",
")",
":",
"if",
"N",
"<",
"(",
"_NUM_PRECOMPUTED_PARTITION_LISTS",
")",
":",
"return",
"list",
"(",
"_partition_lists",
"[",
"N",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Partition lists not yet available for system with {} '",
"'nodes or more'",
".",
"format",
"(",
"_NUM_PRECOMPUTED_PARTITION_LISTS",
")",
")"
] |
Return a list of partitions of the |N| binary nodes.
Args:
N (int): The number of nodes under consideration.
Returns:
list[list]: A list of lists, where each inner list is the set of
micro-elements corresponding to a macro-element.
Example:
>>> _partitions_list(3)
[[[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], [[0], [1], [2]]]
|
[
"Return",
"a",
"list",
"of",
"partitions",
"of",
"the",
"|N|",
"binary",
"nodes",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L665-L684
|
16,017
|
wmayner/pyphi
|
pyphi/macro.py
|
all_partitions
|
def all_partitions(indices):
"""Return a list of all possible coarse grains of a network.
Args:
indices (tuple[int]): The micro indices to partition.
Yields:
tuple[tuple]: A possible partition. Each element of the tuple
is a tuple of micro-elements which correspond to macro-elements.
"""
n = len(indices)
partitions = _partitions_list(n)
if n > 0:
partitions[-1] = [list(range(n))]
for partition in partitions:
yield tuple(tuple(indices[i] for i in part)
for part in partition)
|
python
|
def all_partitions(indices):
"""Return a list of all possible coarse grains of a network.
Args:
indices (tuple[int]): The micro indices to partition.
Yields:
tuple[tuple]: A possible partition. Each element of the tuple
is a tuple of micro-elements which correspond to macro-elements.
"""
n = len(indices)
partitions = _partitions_list(n)
if n > 0:
partitions[-1] = [list(range(n))]
for partition in partitions:
yield tuple(tuple(indices[i] for i in part)
for part in partition)
|
[
"def",
"all_partitions",
"(",
"indices",
")",
":",
"n",
"=",
"len",
"(",
"indices",
")",
"partitions",
"=",
"_partitions_list",
"(",
"n",
")",
"if",
"n",
">",
"0",
":",
"partitions",
"[",
"-",
"1",
"]",
"=",
"[",
"list",
"(",
"range",
"(",
"n",
")",
")",
"]",
"for",
"partition",
"in",
"partitions",
":",
"yield",
"tuple",
"(",
"tuple",
"(",
"indices",
"[",
"i",
"]",
"for",
"i",
"in",
"part",
")",
"for",
"part",
"in",
"partition",
")"
] |
Return a list of all possible coarse grains of a network.
Args:
indices (tuple[int]): The micro indices to partition.
Yields:
tuple[tuple]: A possible partition. Each element of the tuple
is a tuple of micro-elements which correspond to macro-elements.
|
[
"Return",
"a",
"list",
"of",
"all",
"possible",
"coarse",
"grains",
"of",
"a",
"network",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L687-L704
|
16,018
|
wmayner/pyphi
|
pyphi/macro.py
|
all_coarse_grains
|
def all_coarse_grains(indices):
"""Generator over all possible |CoarseGrains| of these indices.
Args:
indices (tuple[int]): Node indices to coarse grain.
Yields:
CoarseGrain: The next |CoarseGrain| for ``indices``.
"""
for partition in all_partitions(indices):
for grouping in all_groupings(partition):
yield CoarseGrain(partition, grouping)
|
python
|
def all_coarse_grains(indices):
"""Generator over all possible |CoarseGrains| of these indices.
Args:
indices (tuple[int]): Node indices to coarse grain.
Yields:
CoarseGrain: The next |CoarseGrain| for ``indices``.
"""
for partition in all_partitions(indices):
for grouping in all_groupings(partition):
yield CoarseGrain(partition, grouping)
|
[
"def",
"all_coarse_grains",
"(",
"indices",
")",
":",
"for",
"partition",
"in",
"all_partitions",
"(",
"indices",
")",
":",
"for",
"grouping",
"in",
"all_groupings",
"(",
"partition",
")",
":",
"yield",
"CoarseGrain",
"(",
"partition",
",",
"grouping",
")"
] |
Generator over all possible |CoarseGrains| of these indices.
Args:
indices (tuple[int]): Node indices to coarse grain.
Yields:
CoarseGrain: The next |CoarseGrain| for ``indices``.
|
[
"Generator",
"over",
"all",
"possible",
"|CoarseGrains|",
"of",
"these",
"indices",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L734-L745
|
16,019
|
wmayner/pyphi
|
pyphi/macro.py
|
all_coarse_grains_for_blackbox
|
def all_coarse_grains_for_blackbox(blackbox):
"""Generator over all |CoarseGrains| for the given blackbox.
If a box has multiple outputs, those outputs are partitioned into the same
coarse-grain macro-element.
"""
for partition in all_partitions(blackbox.output_indices):
for grouping in all_groupings(partition):
coarse_grain = CoarseGrain(partition, grouping)
try:
validate.blackbox_and_coarse_grain(blackbox, coarse_grain)
except ValueError:
continue
yield coarse_grain
|
python
|
def all_coarse_grains_for_blackbox(blackbox):
"""Generator over all |CoarseGrains| for the given blackbox.
If a box has multiple outputs, those outputs are partitioned into the same
coarse-grain macro-element.
"""
for partition in all_partitions(blackbox.output_indices):
for grouping in all_groupings(partition):
coarse_grain = CoarseGrain(partition, grouping)
try:
validate.blackbox_and_coarse_grain(blackbox, coarse_grain)
except ValueError:
continue
yield coarse_grain
|
[
"def",
"all_coarse_grains_for_blackbox",
"(",
"blackbox",
")",
":",
"for",
"partition",
"in",
"all_partitions",
"(",
"blackbox",
".",
"output_indices",
")",
":",
"for",
"grouping",
"in",
"all_groupings",
"(",
"partition",
")",
":",
"coarse_grain",
"=",
"CoarseGrain",
"(",
"partition",
",",
"grouping",
")",
"try",
":",
"validate",
".",
"blackbox_and_coarse_grain",
"(",
"blackbox",
",",
"coarse_grain",
")",
"except",
"ValueError",
":",
"continue",
"yield",
"coarse_grain"
] |
Generator over all |CoarseGrains| for the given blackbox.
If a box has multiple outputs, those outputs are partitioned into the same
coarse-grain macro-element.
|
[
"Generator",
"over",
"all",
"|CoarseGrains|",
"for",
"the",
"given",
"blackbox",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L748-L761
|
16,020
|
wmayner/pyphi
|
pyphi/macro.py
|
all_blackboxes
|
def all_blackboxes(indices):
"""Generator over all possible blackboxings of these indices.
Args:
indices (tuple[int]): Nodes to blackbox.
Yields:
Blackbox: The next |Blackbox| of ``indices``.
"""
for partition in all_partitions(indices):
# TODO? don't consider the empty set here
# (pass `nonempty=True` to `powerset`)
for output_indices in utils.powerset(indices):
blackbox = Blackbox(partition, output_indices)
try: # Ensure every box has at least one output
validate.blackbox(blackbox)
except ValueError:
continue
yield blackbox
|
python
|
def all_blackboxes(indices):
"""Generator over all possible blackboxings of these indices.
Args:
indices (tuple[int]): Nodes to blackbox.
Yields:
Blackbox: The next |Blackbox| of ``indices``.
"""
for partition in all_partitions(indices):
# TODO? don't consider the empty set here
# (pass `nonempty=True` to `powerset`)
for output_indices in utils.powerset(indices):
blackbox = Blackbox(partition, output_indices)
try: # Ensure every box has at least one output
validate.blackbox(blackbox)
except ValueError:
continue
yield blackbox
|
[
"def",
"all_blackboxes",
"(",
"indices",
")",
":",
"for",
"partition",
"in",
"all_partitions",
"(",
"indices",
")",
":",
"# TODO? don't consider the empty set here",
"# (pass `nonempty=True` to `powerset`)",
"for",
"output_indices",
"in",
"utils",
".",
"powerset",
"(",
"indices",
")",
":",
"blackbox",
"=",
"Blackbox",
"(",
"partition",
",",
"output_indices",
")",
"try",
":",
"# Ensure every box has at least one output",
"validate",
".",
"blackbox",
"(",
"blackbox",
")",
"except",
"ValueError",
":",
"continue",
"yield",
"blackbox"
] |
Generator over all possible blackboxings of these indices.
Args:
indices (tuple[int]): Nodes to blackbox.
Yields:
Blackbox: The next |Blackbox| of ``indices``.
|
[
"Generator",
"over",
"all",
"possible",
"blackboxings",
"of",
"these",
"indices",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L764-L782
|
16,021
|
wmayner/pyphi
|
pyphi/macro.py
|
coarse_graining
|
def coarse_graining(network, state, internal_indices):
"""Find the maximal coarse-graining of a micro-system.
Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-system.
Returns:
tuple[int, CoarseGrain]: The phi-value of the maximal |CoarseGrain|.
"""
max_phi = float('-inf')
max_coarse_grain = CoarseGrain((), ())
for coarse_grain in all_coarse_grains(internal_indices):
try:
subsystem = MacroSubsystem(network, state, internal_indices,
coarse_grain=coarse_grain)
except ConditionallyDependentError:
continue
phi = compute.phi(subsystem)
if (phi - max_phi) > constants.EPSILON:
max_phi = phi
max_coarse_grain = coarse_grain
return (max_phi, max_coarse_grain)
|
python
|
def coarse_graining(network, state, internal_indices):
"""Find the maximal coarse-graining of a micro-system.
Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-system.
Returns:
tuple[int, CoarseGrain]: The phi-value of the maximal |CoarseGrain|.
"""
max_phi = float('-inf')
max_coarse_grain = CoarseGrain((), ())
for coarse_grain in all_coarse_grains(internal_indices):
try:
subsystem = MacroSubsystem(network, state, internal_indices,
coarse_grain=coarse_grain)
except ConditionallyDependentError:
continue
phi = compute.phi(subsystem)
if (phi - max_phi) > constants.EPSILON:
max_phi = phi
max_coarse_grain = coarse_grain
return (max_phi, max_coarse_grain)
|
[
"def",
"coarse_graining",
"(",
"network",
",",
"state",
",",
"internal_indices",
")",
":",
"max_phi",
"=",
"float",
"(",
"'-inf'",
")",
"max_coarse_grain",
"=",
"CoarseGrain",
"(",
"(",
")",
",",
"(",
")",
")",
"for",
"coarse_grain",
"in",
"all_coarse_grains",
"(",
"internal_indices",
")",
":",
"try",
":",
"subsystem",
"=",
"MacroSubsystem",
"(",
"network",
",",
"state",
",",
"internal_indices",
",",
"coarse_grain",
"=",
"coarse_grain",
")",
"except",
"ConditionallyDependentError",
":",
"continue",
"phi",
"=",
"compute",
".",
"phi",
"(",
"subsystem",
")",
"if",
"(",
"phi",
"-",
"max_phi",
")",
">",
"constants",
".",
"EPSILON",
":",
"max_phi",
"=",
"phi",
"max_coarse_grain",
"=",
"coarse_grain",
"return",
"(",
"max_phi",
",",
"max_coarse_grain",
")"
] |
Find the maximal coarse-graining of a micro-system.
Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-system.
Returns:
tuple[int, CoarseGrain]: The phi-value of the maximal |CoarseGrain|.
|
[
"Find",
"the",
"maximal",
"coarse",
"-",
"graining",
"of",
"a",
"micro",
"-",
"system",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L827-L853
|
16,022
|
wmayner/pyphi
|
pyphi/macro.py
|
all_macro_systems
|
def all_macro_systems(network, state, do_blackbox=False, do_coarse_grain=False,
time_scales=None):
"""Generator over all possible macro-systems for the network."""
if time_scales is None:
time_scales = [1]
def blackboxes(system):
# Returns all blackboxes to evaluate
if not do_blackbox:
return [None]
return all_blackboxes(system)
def coarse_grains(blackbox, system):
# Returns all coarse-grains to test
if not do_coarse_grain:
return [None]
if blackbox is None:
return all_coarse_grains(system)
return all_coarse_grains_for_blackbox(blackbox)
# TODO? don't consider the empty set here
# (pass `nonempty=True` to `powerset`)
for system in utils.powerset(network.node_indices):
for time_scale in time_scales:
for blackbox in blackboxes(system):
for coarse_grain in coarse_grains(blackbox, system):
try:
yield MacroSubsystem(
network, state, system,
time_scale=time_scale,
blackbox=blackbox,
coarse_grain=coarse_grain)
except (StateUnreachableError,
ConditionallyDependentError):
continue
|
python
|
def all_macro_systems(network, state, do_blackbox=False, do_coarse_grain=False,
time_scales=None):
"""Generator over all possible macro-systems for the network."""
if time_scales is None:
time_scales = [1]
def blackboxes(system):
# Returns all blackboxes to evaluate
if not do_blackbox:
return [None]
return all_blackboxes(system)
def coarse_grains(blackbox, system):
# Returns all coarse-grains to test
if not do_coarse_grain:
return [None]
if blackbox is None:
return all_coarse_grains(system)
return all_coarse_grains_for_blackbox(blackbox)
# TODO? don't consider the empty set here
# (pass `nonempty=True` to `powerset`)
for system in utils.powerset(network.node_indices):
for time_scale in time_scales:
for blackbox in blackboxes(system):
for coarse_grain in coarse_grains(blackbox, system):
try:
yield MacroSubsystem(
network, state, system,
time_scale=time_scale,
blackbox=blackbox,
coarse_grain=coarse_grain)
except (StateUnreachableError,
ConditionallyDependentError):
continue
|
[
"def",
"all_macro_systems",
"(",
"network",
",",
"state",
",",
"do_blackbox",
"=",
"False",
",",
"do_coarse_grain",
"=",
"False",
",",
"time_scales",
"=",
"None",
")",
":",
"if",
"time_scales",
"is",
"None",
":",
"time_scales",
"=",
"[",
"1",
"]",
"def",
"blackboxes",
"(",
"system",
")",
":",
"# Returns all blackboxes to evaluate",
"if",
"not",
"do_blackbox",
":",
"return",
"[",
"None",
"]",
"return",
"all_blackboxes",
"(",
"system",
")",
"def",
"coarse_grains",
"(",
"blackbox",
",",
"system",
")",
":",
"# Returns all coarse-grains to test",
"if",
"not",
"do_coarse_grain",
":",
"return",
"[",
"None",
"]",
"if",
"blackbox",
"is",
"None",
":",
"return",
"all_coarse_grains",
"(",
"system",
")",
"return",
"all_coarse_grains_for_blackbox",
"(",
"blackbox",
")",
"# TODO? don't consider the empty set here",
"# (pass `nonempty=True` to `powerset`)",
"for",
"system",
"in",
"utils",
".",
"powerset",
"(",
"network",
".",
"node_indices",
")",
":",
"for",
"time_scale",
"in",
"time_scales",
":",
"for",
"blackbox",
"in",
"blackboxes",
"(",
"system",
")",
":",
"for",
"coarse_grain",
"in",
"coarse_grains",
"(",
"blackbox",
",",
"system",
")",
":",
"try",
":",
"yield",
"MacroSubsystem",
"(",
"network",
",",
"state",
",",
"system",
",",
"time_scale",
"=",
"time_scale",
",",
"blackbox",
"=",
"blackbox",
",",
"coarse_grain",
"=",
"coarse_grain",
")",
"except",
"(",
"StateUnreachableError",
",",
"ConditionallyDependentError",
")",
":",
"continue"
] |
Generator over all possible macro-systems for the network.
|
[
"Generator",
"over",
"all",
"possible",
"macro",
"-",
"systems",
"for",
"the",
"network",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L857-L891
|
16,023
|
wmayner/pyphi
|
pyphi/macro.py
|
emergence
|
def emergence(network, state, do_blackbox=False, do_coarse_grain=True,
time_scales=None):
"""Check for the emergence of a micro-system into a macro-system.
Checks all possible blackboxings and coarse-grainings of a system to find
the spatial scale with maximum integrated information.
Use the ``do_blackbox`` and ``do_coarse_grain`` args to specifiy whether to
use blackboxing, coarse-graining, or both. The default is to just
coarse-grain the system.
Args:
network (Network): The network of the micro-system under investigation.
state (tuple[int]): The state of the network.
do_blackbox (bool): Set to ``True`` to enable blackboxing. Defaults to
``False``.
do_coarse_grain (bool): Set to ``True`` to enable coarse-graining.
Defaults to ``True``.
time_scales (list[int]): List of all time steps over which to check
for emergence.
Returns:
MacroNetwork: The maximal macro-system generated from the
micro-system.
"""
micro_phi = compute.major_complex(network, state).phi
max_phi = float('-inf')
max_network = None
for subsystem in all_macro_systems(network, state, do_blackbox=do_blackbox,
do_coarse_grain=do_coarse_grain,
time_scales=time_scales):
phi = compute.phi(subsystem)
if (phi - max_phi) > constants.EPSILON:
max_phi = phi
max_network = MacroNetwork(
network=network,
macro_phi=phi,
micro_phi=micro_phi,
system=subsystem.micro_node_indices,
time_scale=subsystem.time_scale,
blackbox=subsystem.blackbox,
coarse_grain=subsystem.coarse_grain)
return max_network
|
python
|
def emergence(network, state, do_blackbox=False, do_coarse_grain=True,
time_scales=None):
"""Check for the emergence of a micro-system into a macro-system.
Checks all possible blackboxings and coarse-grainings of a system to find
the spatial scale with maximum integrated information.
Use the ``do_blackbox`` and ``do_coarse_grain`` args to specifiy whether to
use blackboxing, coarse-graining, or both. The default is to just
coarse-grain the system.
Args:
network (Network): The network of the micro-system under investigation.
state (tuple[int]): The state of the network.
do_blackbox (bool): Set to ``True`` to enable blackboxing. Defaults to
``False``.
do_coarse_grain (bool): Set to ``True`` to enable coarse-graining.
Defaults to ``True``.
time_scales (list[int]): List of all time steps over which to check
for emergence.
Returns:
MacroNetwork: The maximal macro-system generated from the
micro-system.
"""
micro_phi = compute.major_complex(network, state).phi
max_phi = float('-inf')
max_network = None
for subsystem in all_macro_systems(network, state, do_blackbox=do_blackbox,
do_coarse_grain=do_coarse_grain,
time_scales=time_scales):
phi = compute.phi(subsystem)
if (phi - max_phi) > constants.EPSILON:
max_phi = phi
max_network = MacroNetwork(
network=network,
macro_phi=phi,
micro_phi=micro_phi,
system=subsystem.micro_node_indices,
time_scale=subsystem.time_scale,
blackbox=subsystem.blackbox,
coarse_grain=subsystem.coarse_grain)
return max_network
|
[
"def",
"emergence",
"(",
"network",
",",
"state",
",",
"do_blackbox",
"=",
"False",
",",
"do_coarse_grain",
"=",
"True",
",",
"time_scales",
"=",
"None",
")",
":",
"micro_phi",
"=",
"compute",
".",
"major_complex",
"(",
"network",
",",
"state",
")",
".",
"phi",
"max_phi",
"=",
"float",
"(",
"'-inf'",
")",
"max_network",
"=",
"None",
"for",
"subsystem",
"in",
"all_macro_systems",
"(",
"network",
",",
"state",
",",
"do_blackbox",
"=",
"do_blackbox",
",",
"do_coarse_grain",
"=",
"do_coarse_grain",
",",
"time_scales",
"=",
"time_scales",
")",
":",
"phi",
"=",
"compute",
".",
"phi",
"(",
"subsystem",
")",
"if",
"(",
"phi",
"-",
"max_phi",
")",
">",
"constants",
".",
"EPSILON",
":",
"max_phi",
"=",
"phi",
"max_network",
"=",
"MacroNetwork",
"(",
"network",
"=",
"network",
",",
"macro_phi",
"=",
"phi",
",",
"micro_phi",
"=",
"micro_phi",
",",
"system",
"=",
"subsystem",
".",
"micro_node_indices",
",",
"time_scale",
"=",
"subsystem",
".",
"time_scale",
",",
"blackbox",
"=",
"subsystem",
".",
"blackbox",
",",
"coarse_grain",
"=",
"subsystem",
".",
"coarse_grain",
")",
"return",
"max_network"
] |
Check for the emergence of a micro-system into a macro-system.
Checks all possible blackboxings and coarse-grainings of a system to find
the spatial scale with maximum integrated information.
Use the ``do_blackbox`` and ``do_coarse_grain`` args to specifiy whether to
use blackboxing, coarse-graining, or both. The default is to just
coarse-grain the system.
Args:
network (Network): The network of the micro-system under investigation.
state (tuple[int]): The state of the network.
do_blackbox (bool): Set to ``True`` to enable blackboxing. Defaults to
``False``.
do_coarse_grain (bool): Set to ``True`` to enable coarse-graining.
Defaults to ``True``.
time_scales (list[int]): List of all time steps over which to check
for emergence.
Returns:
MacroNetwork: The maximal macro-system generated from the
micro-system.
|
[
"Check",
"for",
"the",
"emergence",
"of",
"a",
"micro",
"-",
"system",
"into",
"a",
"macro",
"-",
"system",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L894-L940
|
16,024
|
wmayner/pyphi
|
pyphi/macro.py
|
effective_info
|
def effective_info(network):
"""Return the effective information of the given network.
.. note::
For details, see:
Hoel, Erik P., Larissa Albantakis, and Giulio Tononi.
“Quantifying causal emergence shows that macro can beat micro.”
Proceedings of the
National Academy of Sciences 110.49 (2013): 19790-19795.
Available online: `doi: 10.1073/pnas.1314922110
<http://www.pnas.org/content/110/49/19790.abstract>`_.
"""
validate.is_network(network)
sbs_tpm = convert.state_by_node2state_by_state(network.tpm)
avg_repertoire = np.mean(sbs_tpm, 0)
return np.mean([entropy(repertoire, avg_repertoire, 2.0)
for repertoire in sbs_tpm])
|
python
|
def effective_info(network):
"""Return the effective information of the given network.
.. note::
For details, see:
Hoel, Erik P., Larissa Albantakis, and Giulio Tononi.
“Quantifying causal emergence shows that macro can beat micro.”
Proceedings of the
National Academy of Sciences 110.49 (2013): 19790-19795.
Available online: `doi: 10.1073/pnas.1314922110
<http://www.pnas.org/content/110/49/19790.abstract>`_.
"""
validate.is_network(network)
sbs_tpm = convert.state_by_node2state_by_state(network.tpm)
avg_repertoire = np.mean(sbs_tpm, 0)
return np.mean([entropy(repertoire, avg_repertoire, 2.0)
for repertoire in sbs_tpm])
|
[
"def",
"effective_info",
"(",
"network",
")",
":",
"validate",
".",
"is_network",
"(",
"network",
")",
"sbs_tpm",
"=",
"convert",
".",
"state_by_node2state_by_state",
"(",
"network",
".",
"tpm",
")",
"avg_repertoire",
"=",
"np",
".",
"mean",
"(",
"sbs_tpm",
",",
"0",
")",
"return",
"np",
".",
"mean",
"(",
"[",
"entropy",
"(",
"repertoire",
",",
"avg_repertoire",
",",
"2.0",
")",
"for",
"repertoire",
"in",
"sbs_tpm",
"]",
")"
] |
Return the effective information of the given network.
.. note::
For details, see:
Hoel, Erik P., Larissa Albantakis, and Giulio Tononi.
“Quantifying causal emergence shows that macro can beat micro.”
Proceedings of the
National Academy of Sciences 110.49 (2013): 19790-19795.
Available online: `doi: 10.1073/pnas.1314922110
<http://www.pnas.org/content/110/49/19790.abstract>`_.
|
[
"Return",
"the",
"effective",
"information",
"of",
"the",
"given",
"network",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L969-L989
|
16,025
|
wmayner/pyphi
|
pyphi/macro.py
|
SystemAttrs.node_labels
|
def node_labels(self):
"""Return the labels for macro nodes."""
assert list(self.node_indices)[0] == 0
labels = list("m{}".format(i) for i in self.node_indices)
return NodeLabels(labels, self.node_indices)
|
python
|
def node_labels(self):
"""Return the labels for macro nodes."""
assert list(self.node_indices)[0] == 0
labels = list("m{}".format(i) for i in self.node_indices)
return NodeLabels(labels, self.node_indices)
|
[
"def",
"node_labels",
"(",
"self",
")",
":",
"assert",
"list",
"(",
"self",
".",
"node_indices",
")",
"[",
"0",
"]",
"==",
"0",
"labels",
"=",
"list",
"(",
"\"m{}\"",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"self",
".",
"node_indices",
")",
"return",
"NodeLabels",
"(",
"labels",
",",
"self",
".",
"node_indices",
")"
] |
Return the labels for macro nodes.
|
[
"Return",
"the",
"labels",
"for",
"macro",
"nodes",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L99-L103
|
16,026
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem._squeeze
|
def _squeeze(system):
"""Squeeze out all singleton dimensions in the Subsystem.
Reindexes the subsystem so that the nodes are ``0..n`` where ``n`` is
the number of internal indices in the system.
"""
assert system.node_indices == tpm_indices(system.tpm)
internal_indices = tpm_indices(system.tpm)
tpm = remove_singleton_dimensions(system.tpm)
# The connectivity matrix is the network's connectivity matrix, with
# cut applied, with all connections to/from external nodes severed,
# shrunk to the size of the internal nodes.
cm = system.cm[np.ix_(internal_indices, internal_indices)]
state = utils.state_of(internal_indices, system.state)
# Re-index the subsystem nodes with the external nodes removed
node_indices = reindex(internal_indices)
nodes = generate_nodes(tpm, cm, state, node_indices)
# Re-calcuate the tpm based on the results of the cut
tpm = rebuild_system_tpm(node.tpm_on for node in nodes)
return SystemAttrs(tpm, cm, node_indices, state)
|
python
|
def _squeeze(system):
"""Squeeze out all singleton dimensions in the Subsystem.
Reindexes the subsystem so that the nodes are ``0..n`` where ``n`` is
the number of internal indices in the system.
"""
assert system.node_indices == tpm_indices(system.tpm)
internal_indices = tpm_indices(system.tpm)
tpm = remove_singleton_dimensions(system.tpm)
# The connectivity matrix is the network's connectivity matrix, with
# cut applied, with all connections to/from external nodes severed,
# shrunk to the size of the internal nodes.
cm = system.cm[np.ix_(internal_indices, internal_indices)]
state = utils.state_of(internal_indices, system.state)
# Re-index the subsystem nodes with the external nodes removed
node_indices = reindex(internal_indices)
nodes = generate_nodes(tpm, cm, state, node_indices)
# Re-calcuate the tpm based on the results of the cut
tpm = rebuild_system_tpm(node.tpm_on for node in nodes)
return SystemAttrs(tpm, cm, node_indices, state)
|
[
"def",
"_squeeze",
"(",
"system",
")",
":",
"assert",
"system",
".",
"node_indices",
"==",
"tpm_indices",
"(",
"system",
".",
"tpm",
")",
"internal_indices",
"=",
"tpm_indices",
"(",
"system",
".",
"tpm",
")",
"tpm",
"=",
"remove_singleton_dimensions",
"(",
"system",
".",
"tpm",
")",
"# The connectivity matrix is the network's connectivity matrix, with",
"# cut applied, with all connections to/from external nodes severed,",
"# shrunk to the size of the internal nodes.",
"cm",
"=",
"system",
".",
"cm",
"[",
"np",
".",
"ix_",
"(",
"internal_indices",
",",
"internal_indices",
")",
"]",
"state",
"=",
"utils",
".",
"state_of",
"(",
"internal_indices",
",",
"system",
".",
"state",
")",
"# Re-index the subsystem nodes with the external nodes removed",
"node_indices",
"=",
"reindex",
"(",
"internal_indices",
")",
"nodes",
"=",
"generate_nodes",
"(",
"tpm",
",",
"cm",
",",
"state",
",",
"node_indices",
")",
"# Re-calcuate the tpm based on the results of the cut",
"tpm",
"=",
"rebuild_system_tpm",
"(",
"node",
".",
"tpm_on",
"for",
"node",
"in",
"nodes",
")",
"return",
"SystemAttrs",
"(",
"tpm",
",",
"cm",
",",
"node_indices",
",",
"state",
")"
] |
Squeeze out all singleton dimensions in the Subsystem.
Reindexes the subsystem so that the nodes are ``0..n`` where ``n`` is
the number of internal indices in the system.
|
[
"Squeeze",
"out",
"all",
"singleton",
"dimensions",
"in",
"the",
"Subsystem",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L199-L225
|
16,027
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem._blackbox_partial_noise
|
def _blackbox_partial_noise(blackbox, system):
"""Noise connections from hidden elements to other boxes."""
# Noise inputs from non-output elements hidden in other boxes
node_tpms = []
for node in system.nodes:
node_tpm = node.tpm_on
for input_node in node.inputs:
if blackbox.hidden_from(input_node, node.index):
node_tpm = marginalize_out([input_node], node_tpm)
node_tpms.append(node_tpm)
tpm = rebuild_system_tpm(node_tpms)
return system._replace(tpm=tpm)
|
python
|
def _blackbox_partial_noise(blackbox, system):
"""Noise connections from hidden elements to other boxes."""
# Noise inputs from non-output elements hidden in other boxes
node_tpms = []
for node in system.nodes:
node_tpm = node.tpm_on
for input_node in node.inputs:
if blackbox.hidden_from(input_node, node.index):
node_tpm = marginalize_out([input_node], node_tpm)
node_tpms.append(node_tpm)
tpm = rebuild_system_tpm(node_tpms)
return system._replace(tpm=tpm)
|
[
"def",
"_blackbox_partial_noise",
"(",
"blackbox",
",",
"system",
")",
":",
"# Noise inputs from non-output elements hidden in other boxes",
"node_tpms",
"=",
"[",
"]",
"for",
"node",
"in",
"system",
".",
"nodes",
":",
"node_tpm",
"=",
"node",
".",
"tpm_on",
"for",
"input_node",
"in",
"node",
".",
"inputs",
":",
"if",
"blackbox",
".",
"hidden_from",
"(",
"input_node",
",",
"node",
".",
"index",
")",
":",
"node_tpm",
"=",
"marginalize_out",
"(",
"[",
"input_node",
"]",
",",
"node_tpm",
")",
"node_tpms",
".",
"append",
"(",
"node_tpm",
")",
"tpm",
"=",
"rebuild_system_tpm",
"(",
"node_tpms",
")",
"return",
"system",
".",
"_replace",
"(",
"tpm",
"=",
"tpm",
")"
] |
Noise connections from hidden elements to other boxes.
|
[
"Noise",
"connections",
"from",
"hidden",
"elements",
"to",
"other",
"boxes",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L228-L242
|
16,028
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem._blackbox_time
|
def _blackbox_time(time_scale, blackbox, system):
"""Black box the CM and TPM over the given time_scale."""
blackbox = blackbox.reindex()
tpm = run_tpm(system, time_scale, blackbox)
# Universal connectivity, for now.
n = len(system.node_indices)
cm = np.ones((n, n))
return SystemAttrs(tpm, cm, system.node_indices, system.state)
|
python
|
def _blackbox_time(time_scale, blackbox, system):
"""Black box the CM and TPM over the given time_scale."""
blackbox = blackbox.reindex()
tpm = run_tpm(system, time_scale, blackbox)
# Universal connectivity, for now.
n = len(system.node_indices)
cm = np.ones((n, n))
return SystemAttrs(tpm, cm, system.node_indices, system.state)
|
[
"def",
"_blackbox_time",
"(",
"time_scale",
",",
"blackbox",
",",
"system",
")",
":",
"blackbox",
"=",
"blackbox",
".",
"reindex",
"(",
")",
"tpm",
"=",
"run_tpm",
"(",
"system",
",",
"time_scale",
",",
"blackbox",
")",
"# Universal connectivity, for now.",
"n",
"=",
"len",
"(",
"system",
".",
"node_indices",
")",
"cm",
"=",
"np",
".",
"ones",
"(",
"(",
"n",
",",
"n",
")",
")",
"return",
"SystemAttrs",
"(",
"tpm",
",",
"cm",
",",
"system",
".",
"node_indices",
",",
"system",
".",
"state",
")"
] |
Black box the CM and TPM over the given time_scale.
|
[
"Black",
"box",
"the",
"CM",
"and",
"TPM",
"over",
"the",
"given",
"time_scale",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L245-L255
|
16,029
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem._blackbox_space
|
def _blackbox_space(self, blackbox, system):
"""Blackbox the TPM and CM in space.
Conditions the TPM on the current value of the hidden nodes. The CM is
set to universal connectivity.
.. TODO: change this ^
This shrinks the size of the TPM by the number of hidden indices; now
there is only `len(output_indices)` dimensions in the TPM and in the
state of the subsystem.
"""
tpm = marginalize_out(blackbox.hidden_indices, system.tpm)
assert blackbox.output_indices == tpm_indices(tpm)
tpm = remove_singleton_dimensions(tpm)
n = len(blackbox)
cm = np.zeros((n, n))
for i, j in itertools.product(range(n), repeat=2):
# TODO: don't pull cm from self
outputs = self.blackbox.outputs_of(i)
to = self.blackbox.partition[j]
if self.cm[np.ix_(outputs, to)].sum() > 0:
cm[i, j] = 1
state = blackbox.macro_state(system.state)
node_indices = blackbox.macro_indices
return SystemAttrs(tpm, cm, node_indices, state)
|
python
|
def _blackbox_space(self, blackbox, system):
"""Blackbox the TPM and CM in space.
Conditions the TPM on the current value of the hidden nodes. The CM is
set to universal connectivity.
.. TODO: change this ^
This shrinks the size of the TPM by the number of hidden indices; now
there is only `len(output_indices)` dimensions in the TPM and in the
state of the subsystem.
"""
tpm = marginalize_out(blackbox.hidden_indices, system.tpm)
assert blackbox.output_indices == tpm_indices(tpm)
tpm = remove_singleton_dimensions(tpm)
n = len(blackbox)
cm = np.zeros((n, n))
for i, j in itertools.product(range(n), repeat=2):
# TODO: don't pull cm from self
outputs = self.blackbox.outputs_of(i)
to = self.blackbox.partition[j]
if self.cm[np.ix_(outputs, to)].sum() > 0:
cm[i, j] = 1
state = blackbox.macro_state(system.state)
node_indices = blackbox.macro_indices
return SystemAttrs(tpm, cm, node_indices, state)
|
[
"def",
"_blackbox_space",
"(",
"self",
",",
"blackbox",
",",
"system",
")",
":",
"tpm",
"=",
"marginalize_out",
"(",
"blackbox",
".",
"hidden_indices",
",",
"system",
".",
"tpm",
")",
"assert",
"blackbox",
".",
"output_indices",
"==",
"tpm_indices",
"(",
"tpm",
")",
"tpm",
"=",
"remove_singleton_dimensions",
"(",
"tpm",
")",
"n",
"=",
"len",
"(",
"blackbox",
")",
"cm",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
")",
"for",
"i",
",",
"j",
"in",
"itertools",
".",
"product",
"(",
"range",
"(",
"n",
")",
",",
"repeat",
"=",
"2",
")",
":",
"# TODO: don't pull cm from self",
"outputs",
"=",
"self",
".",
"blackbox",
".",
"outputs_of",
"(",
"i",
")",
"to",
"=",
"self",
".",
"blackbox",
".",
"partition",
"[",
"j",
"]",
"if",
"self",
".",
"cm",
"[",
"np",
".",
"ix_",
"(",
"outputs",
",",
"to",
")",
"]",
".",
"sum",
"(",
")",
">",
"0",
":",
"cm",
"[",
"i",
",",
"j",
"]",
"=",
"1",
"state",
"=",
"blackbox",
".",
"macro_state",
"(",
"system",
".",
"state",
")",
"node_indices",
"=",
"blackbox",
".",
"macro_indices",
"return",
"SystemAttrs",
"(",
"tpm",
",",
"cm",
",",
"node_indices",
",",
"state",
")"
] |
Blackbox the TPM and CM in space.
Conditions the TPM on the current value of the hidden nodes. The CM is
set to universal connectivity.
.. TODO: change this ^
This shrinks the size of the TPM by the number of hidden indices; now
there is only `len(output_indices)` dimensions in the TPM and in the
state of the subsystem.
|
[
"Blackbox",
"the",
"TPM",
"and",
"CM",
"in",
"space",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L257-L286
|
16,030
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem._coarsegrain_space
|
def _coarsegrain_space(coarse_grain, is_cut, system):
"""Spatially coarse-grain the TPM and CM."""
tpm = coarse_grain.macro_tpm(
system.tpm, check_independence=(not is_cut))
node_indices = coarse_grain.macro_indices
state = coarse_grain.macro_state(system.state)
# Universal connectivity, for now.
n = len(node_indices)
cm = np.ones((n, n))
return SystemAttrs(tpm, cm, node_indices, state)
|
python
|
def _coarsegrain_space(coarse_grain, is_cut, system):
"""Spatially coarse-grain the TPM and CM."""
tpm = coarse_grain.macro_tpm(
system.tpm, check_independence=(not is_cut))
node_indices = coarse_grain.macro_indices
state = coarse_grain.macro_state(system.state)
# Universal connectivity, for now.
n = len(node_indices)
cm = np.ones((n, n))
return SystemAttrs(tpm, cm, node_indices, state)
|
[
"def",
"_coarsegrain_space",
"(",
"coarse_grain",
",",
"is_cut",
",",
"system",
")",
":",
"tpm",
"=",
"coarse_grain",
".",
"macro_tpm",
"(",
"system",
".",
"tpm",
",",
"check_independence",
"=",
"(",
"not",
"is_cut",
")",
")",
"node_indices",
"=",
"coarse_grain",
".",
"macro_indices",
"state",
"=",
"coarse_grain",
".",
"macro_state",
"(",
"system",
".",
"state",
")",
"# Universal connectivity, for now.",
"n",
"=",
"len",
"(",
"node_indices",
")",
"cm",
"=",
"np",
".",
"ones",
"(",
"(",
"n",
",",
"n",
")",
")",
"return",
"SystemAttrs",
"(",
"tpm",
",",
"cm",
",",
"node_indices",
",",
"state",
")"
] |
Spatially coarse-grain the TPM and CM.
|
[
"Spatially",
"coarse",
"-",
"grain",
"the",
"TPM",
"and",
"CM",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L289-L301
|
16,031
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem.cut_mechanisms
|
def cut_mechanisms(self):
"""The mechanisms of this system that are currently cut.
Note that although ``cut_indices`` returns micro indices, this
returns macro mechanisms.
Yields:
tuple[int]
"""
for mechanism in utils.powerset(self.node_indices, nonempty=True):
micro_mechanism = self.macro2micro(mechanism)
if self.cut.splits_mechanism(micro_mechanism):
yield mechanism
|
python
|
def cut_mechanisms(self):
"""The mechanisms of this system that are currently cut.
Note that although ``cut_indices`` returns micro indices, this
returns macro mechanisms.
Yields:
tuple[int]
"""
for mechanism in utils.powerset(self.node_indices, nonempty=True):
micro_mechanism = self.macro2micro(mechanism)
if self.cut.splits_mechanism(micro_mechanism):
yield mechanism
|
[
"def",
"cut_mechanisms",
"(",
"self",
")",
":",
"for",
"mechanism",
"in",
"utils",
".",
"powerset",
"(",
"self",
".",
"node_indices",
",",
"nonempty",
"=",
"True",
")",
":",
"micro_mechanism",
"=",
"self",
".",
"macro2micro",
"(",
"mechanism",
")",
"if",
"self",
".",
"cut",
".",
"splits_mechanism",
"(",
"micro_mechanism",
")",
":",
"yield",
"mechanism"
] |
The mechanisms of this system that are currently cut.
Note that although ``cut_indices`` returns micro indices, this
returns macro mechanisms.
Yields:
tuple[int]
|
[
"The",
"mechanisms",
"of",
"this",
"system",
"that",
"are",
"currently",
"cut",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L313-L325
|
16,032
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem.apply_cut
|
def apply_cut(self, cut):
"""Return a cut version of this |MacroSubsystem|.
Args:
cut (Cut): The cut to apply to this |MacroSubsystem|.
Returns:
MacroSubsystem: The cut version of this |MacroSubsystem|.
"""
# TODO: is the MICE cache reusable?
return MacroSubsystem(
self.network,
self.network_state,
self.micro_node_indices,
cut=cut,
time_scale=self.time_scale,
blackbox=self.blackbox,
coarse_grain=self.coarse_grain)
|
python
|
def apply_cut(self, cut):
"""Return a cut version of this |MacroSubsystem|.
Args:
cut (Cut): The cut to apply to this |MacroSubsystem|.
Returns:
MacroSubsystem: The cut version of this |MacroSubsystem|.
"""
# TODO: is the MICE cache reusable?
return MacroSubsystem(
self.network,
self.network_state,
self.micro_node_indices,
cut=cut,
time_scale=self.time_scale,
blackbox=self.blackbox,
coarse_grain=self.coarse_grain)
|
[
"def",
"apply_cut",
"(",
"self",
",",
"cut",
")",
":",
"# TODO: is the MICE cache reusable?",
"return",
"MacroSubsystem",
"(",
"self",
".",
"network",
",",
"self",
".",
"network_state",
",",
"self",
".",
"micro_node_indices",
",",
"cut",
"=",
"cut",
",",
"time_scale",
"=",
"self",
".",
"time_scale",
",",
"blackbox",
"=",
"self",
".",
"blackbox",
",",
"coarse_grain",
"=",
"self",
".",
"coarse_grain",
")"
] |
Return a cut version of this |MacroSubsystem|.
Args:
cut (Cut): The cut to apply to this |MacroSubsystem|.
Returns:
MacroSubsystem: The cut version of this |MacroSubsystem|.
|
[
"Return",
"a",
"cut",
"version",
"of",
"this",
"|MacroSubsystem|",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L335-L352
|
16,033
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem.potential_purviews
|
def potential_purviews(self, direction, mechanism, purviews=False):
"""Override Subsystem implementation using Network-level indices."""
all_purviews = utils.powerset(self.node_indices)
return irreducible_purviews(
self.cm, direction, mechanism, all_purviews)
|
python
|
def potential_purviews(self, direction, mechanism, purviews=False):
"""Override Subsystem implementation using Network-level indices."""
all_purviews = utils.powerset(self.node_indices)
return irreducible_purviews(
self.cm, direction, mechanism, all_purviews)
|
[
"def",
"potential_purviews",
"(",
"self",
",",
"direction",
",",
"mechanism",
",",
"purviews",
"=",
"False",
")",
":",
"all_purviews",
"=",
"utils",
".",
"powerset",
"(",
"self",
".",
"node_indices",
")",
"return",
"irreducible_purviews",
"(",
"self",
".",
"cm",
",",
"direction",
",",
"mechanism",
",",
"all_purviews",
")"
] |
Override Subsystem implementation using Network-level indices.
|
[
"Override",
"Subsystem",
"implementation",
"using",
"Network",
"-",
"level",
"indices",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L354-L358
|
16,034
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem.macro2micro
|
def macro2micro(self, macro_indices):
"""Return all micro indices which compose the elements specified by
``macro_indices``.
"""
def from_partition(partition, macro_indices):
micro_indices = itertools.chain.from_iterable(
partition[i] for i in macro_indices)
return tuple(sorted(micro_indices))
if self.blackbox and self.coarse_grain:
cg_micro_indices = from_partition(self.coarse_grain.partition,
macro_indices)
return from_partition(self.blackbox.partition,
reindex(cg_micro_indices))
elif self.blackbox:
return from_partition(self.blackbox.partition, macro_indices)
elif self.coarse_grain:
return from_partition(self.coarse_grain.partition, macro_indices)
return macro_indices
|
python
|
def macro2micro(self, macro_indices):
"""Return all micro indices which compose the elements specified by
``macro_indices``.
"""
def from_partition(partition, macro_indices):
micro_indices = itertools.chain.from_iterable(
partition[i] for i in macro_indices)
return tuple(sorted(micro_indices))
if self.blackbox and self.coarse_grain:
cg_micro_indices = from_partition(self.coarse_grain.partition,
macro_indices)
return from_partition(self.blackbox.partition,
reindex(cg_micro_indices))
elif self.blackbox:
return from_partition(self.blackbox.partition, macro_indices)
elif self.coarse_grain:
return from_partition(self.coarse_grain.partition, macro_indices)
return macro_indices
|
[
"def",
"macro2micro",
"(",
"self",
",",
"macro_indices",
")",
":",
"def",
"from_partition",
"(",
"partition",
",",
"macro_indices",
")",
":",
"micro_indices",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"partition",
"[",
"i",
"]",
"for",
"i",
"in",
"macro_indices",
")",
"return",
"tuple",
"(",
"sorted",
"(",
"micro_indices",
")",
")",
"if",
"self",
".",
"blackbox",
"and",
"self",
".",
"coarse_grain",
":",
"cg_micro_indices",
"=",
"from_partition",
"(",
"self",
".",
"coarse_grain",
".",
"partition",
",",
"macro_indices",
")",
"return",
"from_partition",
"(",
"self",
".",
"blackbox",
".",
"partition",
",",
"reindex",
"(",
"cg_micro_indices",
")",
")",
"elif",
"self",
".",
"blackbox",
":",
"return",
"from_partition",
"(",
"self",
".",
"blackbox",
".",
"partition",
",",
"macro_indices",
")",
"elif",
"self",
".",
"coarse_grain",
":",
"return",
"from_partition",
"(",
"self",
".",
"coarse_grain",
".",
"partition",
",",
"macro_indices",
")",
"return",
"macro_indices"
] |
Return all micro indices which compose the elements specified by
``macro_indices``.
|
[
"Return",
"all",
"micro",
"indices",
"which",
"compose",
"the",
"elements",
"specified",
"by",
"macro_indices",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L360-L378
|
16,035
|
wmayner/pyphi
|
pyphi/macro.py
|
MacroSubsystem.macro2blackbox_outputs
|
def macro2blackbox_outputs(self, macro_indices):
"""Given a set of macro elements, return the blackbox output elements
which compose these elements.
"""
if not self.blackbox:
raise ValueError('System is not blackboxed')
return tuple(sorted(set(
self.macro2micro(macro_indices)
).intersection(self.blackbox.output_indices)))
|
python
|
def macro2blackbox_outputs(self, macro_indices):
"""Given a set of macro elements, return the blackbox output elements
which compose these elements.
"""
if not self.blackbox:
raise ValueError('System is not blackboxed')
return tuple(sorted(set(
self.macro2micro(macro_indices)
).intersection(self.blackbox.output_indices)))
|
[
"def",
"macro2blackbox_outputs",
"(",
"self",
",",
"macro_indices",
")",
":",
"if",
"not",
"self",
".",
"blackbox",
":",
"raise",
"ValueError",
"(",
"'System is not blackboxed'",
")",
"return",
"tuple",
"(",
"sorted",
"(",
"set",
"(",
"self",
".",
"macro2micro",
"(",
"macro_indices",
")",
")",
".",
"intersection",
"(",
"self",
".",
"blackbox",
".",
"output_indices",
")",
")",
")"
] |
Given a set of macro elements, return the blackbox output elements
which compose these elements.
|
[
"Given",
"a",
"set",
"of",
"macro",
"elements",
"return",
"the",
"blackbox",
"output",
"elements",
"which",
"compose",
"these",
"elements",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L380-L389
|
16,036
|
wmayner/pyphi
|
pyphi/macro.py
|
CoarseGrain.micro_indices
|
def micro_indices(self):
"""Indices of micro elements represented in this coarse-graining."""
return tuple(sorted(idx for part in self.partition for idx in part))
|
python
|
def micro_indices(self):
"""Indices of micro elements represented in this coarse-graining."""
return tuple(sorted(idx for part in self.partition for idx in part))
|
[
"def",
"micro_indices",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"idx",
"for",
"part",
"in",
"self",
".",
"partition",
"for",
"idx",
"in",
"part",
")",
")"
] |
Indices of micro elements represented in this coarse-graining.
|
[
"Indices",
"of",
"micro",
"elements",
"represented",
"in",
"this",
"coarse",
"-",
"graining",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L430-L432
|
16,037
|
wmayner/pyphi
|
pyphi/macro.py
|
CoarseGrain.reindex
|
def reindex(self):
"""Re-index this coarse graining to use squeezed indices.
The output grouping is translated to use indices ``0..n``, where ``n``
is the number of micro indices in the coarse-graining. Re-indexing does
not effect the state grouping, which is already index-independent.
Returns:
CoarseGrain: A new |CoarseGrain| object, indexed from ``0..n``.
Example:
>>> partition = ((1, 2),)
>>> grouping = (((0,), (1, 2)),)
>>> coarse_grain = CoarseGrain(partition, grouping)
>>> coarse_grain.reindex()
CoarseGrain(partition=((0, 1),), grouping=(((0,), (1, 2)),))
"""
_map = dict(zip(self.micro_indices, reindex(self.micro_indices)))
partition = tuple(
tuple(_map[index] for index in group)
for group in self.partition
)
return CoarseGrain(partition, self.grouping)
|
python
|
def reindex(self):
"""Re-index this coarse graining to use squeezed indices.
The output grouping is translated to use indices ``0..n``, where ``n``
is the number of micro indices in the coarse-graining. Re-indexing does
not effect the state grouping, which is already index-independent.
Returns:
CoarseGrain: A new |CoarseGrain| object, indexed from ``0..n``.
Example:
>>> partition = ((1, 2),)
>>> grouping = (((0,), (1, 2)),)
>>> coarse_grain = CoarseGrain(partition, grouping)
>>> coarse_grain.reindex()
CoarseGrain(partition=((0, 1),), grouping=(((0,), (1, 2)),))
"""
_map = dict(zip(self.micro_indices, reindex(self.micro_indices)))
partition = tuple(
tuple(_map[index] for index in group)
for group in self.partition
)
return CoarseGrain(partition, self.grouping)
|
[
"def",
"reindex",
"(",
"self",
")",
":",
"_map",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"micro_indices",
",",
"reindex",
"(",
"self",
".",
"micro_indices",
")",
")",
")",
"partition",
"=",
"tuple",
"(",
"tuple",
"(",
"_map",
"[",
"index",
"]",
"for",
"index",
"in",
"group",
")",
"for",
"group",
"in",
"self",
".",
"partition",
")",
"return",
"CoarseGrain",
"(",
"partition",
",",
"self",
".",
"grouping",
")"
] |
Re-index this coarse graining to use squeezed indices.
The output grouping is translated to use indices ``0..n``, where ``n``
is the number of micro indices in the coarse-graining. Re-indexing does
not effect the state grouping, which is already index-independent.
Returns:
CoarseGrain: A new |CoarseGrain| object, indexed from ``0..n``.
Example:
>>> partition = ((1, 2),)
>>> grouping = (((0,), (1, 2)),)
>>> coarse_grain = CoarseGrain(partition, grouping)
>>> coarse_grain.reindex()
CoarseGrain(partition=((0, 1),), grouping=(((0,), (1, 2)),))
|
[
"Re",
"-",
"index",
"this",
"coarse",
"graining",
"to",
"use",
"squeezed",
"indices",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L442-L464
|
16,038
|
wmayner/pyphi
|
pyphi/macro.py
|
CoarseGrain.macro_state
|
def macro_state(self, micro_state):
"""Translate a micro state to a macro state
Args:
micro_state (tuple[int]): The state of the micro nodes in this
coarse-graining.
Returns:
tuple[int]: The state of the macro system, translated as specified
by this coarse-graining.
Example:
>>> coarse_grain = CoarseGrain(((1, 2),), (((0,), (1, 2)),))
>>> coarse_grain.macro_state((0, 0))
(0,)
>>> coarse_grain.macro_state((1, 0))
(1,)
>>> coarse_grain.macro_state((1, 1))
(1,)
"""
assert len(micro_state) == len(self.micro_indices)
# TODO: only reindex if this coarse grain is not already from 0..n?
# make_mapping calls this in a tight loop so it might be more efficient
# to reindex conditionally.
reindexed = self.reindex()
micro_state = np.array(micro_state)
return tuple(0 if sum(micro_state[list(reindexed.partition[i])])
in self.grouping[i][0] else 1
for i in self.macro_indices)
|
python
|
def macro_state(self, micro_state):
"""Translate a micro state to a macro state
Args:
micro_state (tuple[int]): The state of the micro nodes in this
coarse-graining.
Returns:
tuple[int]: The state of the macro system, translated as specified
by this coarse-graining.
Example:
>>> coarse_grain = CoarseGrain(((1, 2),), (((0,), (1, 2)),))
>>> coarse_grain.macro_state((0, 0))
(0,)
>>> coarse_grain.macro_state((1, 0))
(1,)
>>> coarse_grain.macro_state((1, 1))
(1,)
"""
assert len(micro_state) == len(self.micro_indices)
# TODO: only reindex if this coarse grain is not already from 0..n?
# make_mapping calls this in a tight loop so it might be more efficient
# to reindex conditionally.
reindexed = self.reindex()
micro_state = np.array(micro_state)
return tuple(0 if sum(micro_state[list(reindexed.partition[i])])
in self.grouping[i][0] else 1
for i in self.macro_indices)
|
[
"def",
"macro_state",
"(",
"self",
",",
"micro_state",
")",
":",
"assert",
"len",
"(",
"micro_state",
")",
"==",
"len",
"(",
"self",
".",
"micro_indices",
")",
"# TODO: only reindex if this coarse grain is not already from 0..n?",
"# make_mapping calls this in a tight loop so it might be more efficient",
"# to reindex conditionally.",
"reindexed",
"=",
"self",
".",
"reindex",
"(",
")",
"micro_state",
"=",
"np",
".",
"array",
"(",
"micro_state",
")",
"return",
"tuple",
"(",
"0",
"if",
"sum",
"(",
"micro_state",
"[",
"list",
"(",
"reindexed",
".",
"partition",
"[",
"i",
"]",
")",
"]",
")",
"in",
"self",
".",
"grouping",
"[",
"i",
"]",
"[",
"0",
"]",
"else",
"1",
"for",
"i",
"in",
"self",
".",
"macro_indices",
")"
] |
Translate a micro state to a macro state
Args:
micro_state (tuple[int]): The state of the micro nodes in this
coarse-graining.
Returns:
tuple[int]: The state of the macro system, translated as specified
by this coarse-graining.
Example:
>>> coarse_grain = CoarseGrain(((1, 2),), (((0,), (1, 2)),))
>>> coarse_grain.macro_state((0, 0))
(0,)
>>> coarse_grain.macro_state((1, 0))
(1,)
>>> coarse_grain.macro_state((1, 1))
(1,)
|
[
"Translate",
"a",
"micro",
"state",
"to",
"a",
"macro",
"state"
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L466-L496
|
16,039
|
wmayner/pyphi
|
pyphi/macro.py
|
CoarseGrain.make_mapping
|
def make_mapping(self):
"""Return a mapping from micro-state to the macro-states based on the
partition and state grouping of this coarse-grain.
Return:
(nd.ndarray): A mapping from micro-states to macro-states. The
|ith| entry in the mapping is the macro-state corresponding to the
|ith| micro-state.
"""
micro_states = utils.all_states(len(self.micro_indices))
# Find the corresponding macro-state for each micro-state.
# The i-th entry in the mapping is the macro-state corresponding to the
# i-th micro-state.
mapping = [convert.state2le_index(self.macro_state(micro_state))
for micro_state in micro_states]
return np.array(mapping)
|
python
|
def make_mapping(self):
"""Return a mapping from micro-state to the macro-states based on the
partition and state grouping of this coarse-grain.
Return:
(nd.ndarray): A mapping from micro-states to macro-states. The
|ith| entry in the mapping is the macro-state corresponding to the
|ith| micro-state.
"""
micro_states = utils.all_states(len(self.micro_indices))
# Find the corresponding macro-state for each micro-state.
# The i-th entry in the mapping is the macro-state corresponding to the
# i-th micro-state.
mapping = [convert.state2le_index(self.macro_state(micro_state))
for micro_state in micro_states]
return np.array(mapping)
|
[
"def",
"make_mapping",
"(",
"self",
")",
":",
"micro_states",
"=",
"utils",
".",
"all_states",
"(",
"len",
"(",
"self",
".",
"micro_indices",
")",
")",
"# Find the corresponding macro-state for each micro-state.",
"# The i-th entry in the mapping is the macro-state corresponding to the",
"# i-th micro-state.",
"mapping",
"=",
"[",
"convert",
".",
"state2le_index",
"(",
"self",
".",
"macro_state",
"(",
"micro_state",
")",
")",
"for",
"micro_state",
"in",
"micro_states",
"]",
"return",
"np",
".",
"array",
"(",
"mapping",
")"
] |
Return a mapping from micro-state to the macro-states based on the
partition and state grouping of this coarse-grain.
Return:
(nd.ndarray): A mapping from micro-states to macro-states. The
|ith| entry in the mapping is the macro-state corresponding to the
|ith| micro-state.
|
[
"Return",
"a",
"mapping",
"from",
"micro",
"-",
"state",
"to",
"the",
"macro",
"-",
"states",
"based",
"on",
"the",
"partition",
"and",
"state",
"grouping",
"of",
"this",
"coarse",
"-",
"grain",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L498-L514
|
16,040
|
wmayner/pyphi
|
pyphi/macro.py
|
CoarseGrain.macro_tpm_sbs
|
def macro_tpm_sbs(self, state_by_state_micro_tpm):
"""Create a state-by-state coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The state-by-state TPM of the micro-system.
Returns:
np.ndarray: The state-by-state TPM of the macro-system.
"""
validate.tpm(state_by_state_micro_tpm, check_independence=False)
mapping = self.make_mapping()
num_macro_states = 2 ** len(self.macro_indices)
macro_tpm = np.zeros((num_macro_states, num_macro_states))
micro_states = range(2 ** len(self.micro_indices))
micro_state_transitions = itertools.product(micro_states, repeat=2)
# For every possible micro-state transition, get the corresponding
# previous and next macro-state using the mapping and add that
# probability to the state-by-state macro TPM.
for previous_state, current_state in micro_state_transitions:
macro_tpm[mapping[previous_state], mapping[current_state]] += (
state_by_state_micro_tpm[previous_state, current_state])
# Re-normalize each row because we're going from larger to smaller TPM
return np.array([distribution.normalize(row) for row in macro_tpm])
|
python
|
def macro_tpm_sbs(self, state_by_state_micro_tpm):
"""Create a state-by-state coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The state-by-state TPM of the micro-system.
Returns:
np.ndarray: The state-by-state TPM of the macro-system.
"""
validate.tpm(state_by_state_micro_tpm, check_independence=False)
mapping = self.make_mapping()
num_macro_states = 2 ** len(self.macro_indices)
macro_tpm = np.zeros((num_macro_states, num_macro_states))
micro_states = range(2 ** len(self.micro_indices))
micro_state_transitions = itertools.product(micro_states, repeat=2)
# For every possible micro-state transition, get the corresponding
# previous and next macro-state using the mapping and add that
# probability to the state-by-state macro TPM.
for previous_state, current_state in micro_state_transitions:
macro_tpm[mapping[previous_state], mapping[current_state]] += (
state_by_state_micro_tpm[previous_state, current_state])
# Re-normalize each row because we're going from larger to smaller TPM
return np.array([distribution.normalize(row) for row in macro_tpm])
|
[
"def",
"macro_tpm_sbs",
"(",
"self",
",",
"state_by_state_micro_tpm",
")",
":",
"validate",
".",
"tpm",
"(",
"state_by_state_micro_tpm",
",",
"check_independence",
"=",
"False",
")",
"mapping",
"=",
"self",
".",
"make_mapping",
"(",
")",
"num_macro_states",
"=",
"2",
"**",
"len",
"(",
"self",
".",
"macro_indices",
")",
"macro_tpm",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_macro_states",
",",
"num_macro_states",
")",
")",
"micro_states",
"=",
"range",
"(",
"2",
"**",
"len",
"(",
"self",
".",
"micro_indices",
")",
")",
"micro_state_transitions",
"=",
"itertools",
".",
"product",
"(",
"micro_states",
",",
"repeat",
"=",
"2",
")",
"# For every possible micro-state transition, get the corresponding",
"# previous and next macro-state using the mapping and add that",
"# probability to the state-by-state macro TPM.",
"for",
"previous_state",
",",
"current_state",
"in",
"micro_state_transitions",
":",
"macro_tpm",
"[",
"mapping",
"[",
"previous_state",
"]",
",",
"mapping",
"[",
"current_state",
"]",
"]",
"+=",
"(",
"state_by_state_micro_tpm",
"[",
"previous_state",
",",
"current_state",
"]",
")",
"# Re-normalize each row because we're going from larger to smaller TPM",
"return",
"np",
".",
"array",
"(",
"[",
"distribution",
".",
"normalize",
"(",
"row",
")",
"for",
"row",
"in",
"macro_tpm",
"]",
")"
] |
Create a state-by-state coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The state-by-state TPM of the micro-system.
Returns:
np.ndarray: The state-by-state TPM of the macro-system.
|
[
"Create",
"a",
"state",
"-",
"by",
"-",
"state",
"coarse",
"-",
"grained",
"macro",
"TPM",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L516-L543
|
16,041
|
wmayner/pyphi
|
pyphi/macro.py
|
CoarseGrain.macro_tpm
|
def macro_tpm(self, micro_tpm, check_independence=True):
"""Create a coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The TPM of the micro-system.
check_independence (bool): Whether to check that the macro TPM is
conditionally independent.
Raises:
ConditionallyDependentError: If ``check_independence`` is ``True``
and the macro TPM is not conditionally independent.
Returns:
np.ndarray: The state-by-node TPM of the macro-system.
"""
if not is_state_by_state(micro_tpm):
micro_tpm = convert.state_by_node2state_by_state(micro_tpm)
macro_tpm = self.macro_tpm_sbs(micro_tpm)
if check_independence:
validate.conditionally_independent(macro_tpm)
return convert.state_by_state2state_by_node(macro_tpm)
|
python
|
def macro_tpm(self, micro_tpm, check_independence=True):
"""Create a coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The TPM of the micro-system.
check_independence (bool): Whether to check that the macro TPM is
conditionally independent.
Raises:
ConditionallyDependentError: If ``check_independence`` is ``True``
and the macro TPM is not conditionally independent.
Returns:
np.ndarray: The state-by-node TPM of the macro-system.
"""
if not is_state_by_state(micro_tpm):
micro_tpm = convert.state_by_node2state_by_state(micro_tpm)
macro_tpm = self.macro_tpm_sbs(micro_tpm)
if check_independence:
validate.conditionally_independent(macro_tpm)
return convert.state_by_state2state_by_node(macro_tpm)
|
[
"def",
"macro_tpm",
"(",
"self",
",",
"micro_tpm",
",",
"check_independence",
"=",
"True",
")",
":",
"if",
"not",
"is_state_by_state",
"(",
"micro_tpm",
")",
":",
"micro_tpm",
"=",
"convert",
".",
"state_by_node2state_by_state",
"(",
"micro_tpm",
")",
"macro_tpm",
"=",
"self",
".",
"macro_tpm_sbs",
"(",
"micro_tpm",
")",
"if",
"check_independence",
":",
"validate",
".",
"conditionally_independent",
"(",
"macro_tpm",
")",
"return",
"convert",
".",
"state_by_state2state_by_node",
"(",
"macro_tpm",
")"
] |
Create a coarse-grained macro TPM.
Args:
micro_tpm (nd.array): The TPM of the micro-system.
check_independence (bool): Whether to check that the macro TPM is
conditionally independent.
Raises:
ConditionallyDependentError: If ``check_independence`` is ``True``
and the macro TPM is not conditionally independent.
Returns:
np.ndarray: The state-by-node TPM of the macro-system.
|
[
"Create",
"a",
"coarse",
"-",
"grained",
"macro",
"TPM",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L545-L568
|
16,042
|
wmayner/pyphi
|
pyphi/macro.py
|
Blackbox.hidden_indices
|
def hidden_indices(self):
"""All elements hidden inside the blackboxes."""
return tuple(sorted(set(self.micro_indices) -
set(self.output_indices)))
|
python
|
def hidden_indices(self):
"""All elements hidden inside the blackboxes."""
return tuple(sorted(set(self.micro_indices) -
set(self.output_indices)))
|
[
"def",
"hidden_indices",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"set",
"(",
"self",
".",
"micro_indices",
")",
"-",
"set",
"(",
"self",
".",
"output_indices",
")",
")",
")"
] |
All elements hidden inside the blackboxes.
|
[
"All",
"elements",
"hidden",
"inside",
"the",
"blackboxes",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L582-L585
|
16,043
|
wmayner/pyphi
|
pyphi/macro.py
|
Blackbox.outputs_of
|
def outputs_of(self, partition_index):
"""The outputs of the partition at ``partition_index``.
Note that this returns a tuple of element indices, since coarse-
grained blackboxes may have multiple outputs.
"""
partition = self.partition[partition_index]
outputs = set(partition).intersection(self.output_indices)
return tuple(sorted(outputs))
|
python
|
def outputs_of(self, partition_index):
"""The outputs of the partition at ``partition_index``.
Note that this returns a tuple of element indices, since coarse-
grained blackboxes may have multiple outputs.
"""
partition = self.partition[partition_index]
outputs = set(partition).intersection(self.output_indices)
return tuple(sorted(outputs))
|
[
"def",
"outputs_of",
"(",
"self",
",",
"partition_index",
")",
":",
"partition",
"=",
"self",
".",
"partition",
"[",
"partition_index",
"]",
"outputs",
"=",
"set",
"(",
"partition",
")",
".",
"intersection",
"(",
"self",
".",
"output_indices",
")",
"return",
"tuple",
"(",
"sorted",
"(",
"outputs",
")",
")"
] |
The outputs of the partition at ``partition_index``.
Note that this returns a tuple of element indices, since coarse-
grained blackboxes may have multiple outputs.
|
[
"The",
"outputs",
"of",
"the",
"partition",
"at",
"partition_index",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L600-L608
|
16,044
|
wmayner/pyphi
|
pyphi/macro.py
|
Blackbox.reindex
|
def reindex(self):
"""Squeeze the indices of this blackboxing to ``0..n``.
Returns:
Blackbox: a new, reindexed |Blackbox|.
Example:
>>> partition = ((3,), (2, 4))
>>> output_indices = (2, 3)
>>> blackbox = Blackbox(partition, output_indices)
>>> blackbox.reindex()
Blackbox(partition=((1,), (0, 2)), output_indices=(0, 1))
"""
_map = dict(zip(self.micro_indices, reindex(self.micro_indices)))
partition = tuple(
tuple(_map[index] for index in group)
for group in self.partition
)
output_indices = tuple(_map[i] for i in self.output_indices)
return Blackbox(partition, output_indices)
|
python
|
def reindex(self):
"""Squeeze the indices of this blackboxing to ``0..n``.
Returns:
Blackbox: a new, reindexed |Blackbox|.
Example:
>>> partition = ((3,), (2, 4))
>>> output_indices = (2, 3)
>>> blackbox = Blackbox(partition, output_indices)
>>> blackbox.reindex()
Blackbox(partition=((1,), (0, 2)), output_indices=(0, 1))
"""
_map = dict(zip(self.micro_indices, reindex(self.micro_indices)))
partition = tuple(
tuple(_map[index] for index in group)
for group in self.partition
)
output_indices = tuple(_map[i] for i in self.output_indices)
return Blackbox(partition, output_indices)
|
[
"def",
"reindex",
"(",
"self",
")",
":",
"_map",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"micro_indices",
",",
"reindex",
"(",
"self",
".",
"micro_indices",
")",
")",
")",
"partition",
"=",
"tuple",
"(",
"tuple",
"(",
"_map",
"[",
"index",
"]",
"for",
"index",
"in",
"group",
")",
"for",
"group",
"in",
"self",
".",
"partition",
")",
"output_indices",
"=",
"tuple",
"(",
"_map",
"[",
"i",
"]",
"for",
"i",
"in",
"self",
".",
"output_indices",
")",
"return",
"Blackbox",
"(",
"partition",
",",
"output_indices",
")"
] |
Squeeze the indices of this blackboxing to ``0..n``.
Returns:
Blackbox: a new, reindexed |Blackbox|.
Example:
>>> partition = ((3,), (2, 4))
>>> output_indices = (2, 3)
>>> blackbox = Blackbox(partition, output_indices)
>>> blackbox.reindex()
Blackbox(partition=((1,), (0, 2)), output_indices=(0, 1))
|
[
"Squeeze",
"the",
"indices",
"of",
"this",
"blackboxing",
"to",
"0",
"..",
"n",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L610-L630
|
16,045
|
wmayner/pyphi
|
pyphi/macro.py
|
Blackbox.macro_state
|
def macro_state(self, micro_state):
"""Compute the macro-state of this blackbox.
This is just the state of the blackbox's output indices.
Args:
micro_state (tuple[int]): The state of the micro-elements in the
blackbox.
Returns:
tuple[int]: The state of the output indices.
"""
assert len(micro_state) == len(self.micro_indices)
reindexed = self.reindex()
return utils.state_of(reindexed.output_indices, micro_state)
|
python
|
def macro_state(self, micro_state):
"""Compute the macro-state of this blackbox.
This is just the state of the blackbox's output indices.
Args:
micro_state (tuple[int]): The state of the micro-elements in the
blackbox.
Returns:
tuple[int]: The state of the output indices.
"""
assert len(micro_state) == len(self.micro_indices)
reindexed = self.reindex()
return utils.state_of(reindexed.output_indices, micro_state)
|
[
"def",
"macro_state",
"(",
"self",
",",
"micro_state",
")",
":",
"assert",
"len",
"(",
"micro_state",
")",
"==",
"len",
"(",
"self",
".",
"micro_indices",
")",
"reindexed",
"=",
"self",
".",
"reindex",
"(",
")",
"return",
"utils",
".",
"state_of",
"(",
"reindexed",
".",
"output_indices",
",",
"micro_state",
")"
] |
Compute the macro-state of this blackbox.
This is just the state of the blackbox's output indices.
Args:
micro_state (tuple[int]): The state of the micro-elements in the
blackbox.
Returns:
tuple[int]: The state of the output indices.
|
[
"Compute",
"the",
"macro",
"-",
"state",
"of",
"this",
"blackbox",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L632-L647
|
16,046
|
wmayner/pyphi
|
pyphi/macro.py
|
Blackbox.in_same_box
|
def in_same_box(self, a, b):
"""Return ``True`` if nodes ``a`` and ``b``` are in the same box."""
assert a in self.micro_indices
assert b in self.micro_indices
for part in self.partition:
if a in part and b in part:
return True
return False
|
python
|
def in_same_box(self, a, b):
"""Return ``True`` if nodes ``a`` and ``b``` are in the same box."""
assert a in self.micro_indices
assert b in self.micro_indices
for part in self.partition:
if a in part and b in part:
return True
return False
|
[
"def",
"in_same_box",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"assert",
"a",
"in",
"self",
".",
"micro_indices",
"assert",
"b",
"in",
"self",
".",
"micro_indices",
"for",
"part",
"in",
"self",
".",
"partition",
":",
"if",
"a",
"in",
"part",
"and",
"b",
"in",
"part",
":",
"return",
"True",
"return",
"False"
] |
Return ``True`` if nodes ``a`` and ``b``` are in the same box.
|
[
"Return",
"True",
"if",
"nodes",
"a",
"and",
"b",
"are",
"in",
"the",
"same",
"box",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L649-L658
|
16,047
|
wmayner/pyphi
|
pyphi/macro.py
|
Blackbox.hidden_from
|
def hidden_from(self, a, b):
"""Return True if ``a`` is hidden in a different box than ``b``."""
return a in self.hidden_indices and not self.in_same_box(a, b)
|
python
|
def hidden_from(self, a, b):
"""Return True if ``a`` is hidden in a different box than ``b``."""
return a in self.hidden_indices and not self.in_same_box(a, b)
|
[
"def",
"hidden_from",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"return",
"a",
"in",
"self",
".",
"hidden_indices",
"and",
"not",
"self",
".",
"in_same_box",
"(",
"a",
",",
"b",
")"
] |
Return True if ``a`` is hidden in a different box than ``b``.
|
[
"Return",
"True",
"if",
"a",
"is",
"hidden",
"in",
"a",
"different",
"box",
"than",
"b",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L660-L662
|
16,048
|
wmayner/pyphi
|
pyphi/network.py
|
irreducible_purviews
|
def irreducible_purviews(cm, direction, mechanism, purviews):
"""Return all purviews which are irreducible for the mechanism.
Args:
cm (np.ndarray): An |N x N| connectivity matrix.
direction (Direction): |CAUSE| or |EFFECT|.
purviews (list[tuple[int]]): The purviews to check.
mechanism (tuple[int]): The mechanism in question.
Returns:
list[tuple[int]]: All purviews in ``purviews`` which are not reducible
over ``mechanism``.
Raises:
ValueError: If ``direction`` is invalid.
"""
def reducible(purview):
"""Return ``True`` if purview is trivially reducible."""
_from, to = direction.order(mechanism, purview)
return connectivity.block_reducible(cm, _from, to)
return [purview for purview in purviews if not reducible(purview)]
|
python
|
def irreducible_purviews(cm, direction, mechanism, purviews):
"""Return all purviews which are irreducible for the mechanism.
Args:
cm (np.ndarray): An |N x N| connectivity matrix.
direction (Direction): |CAUSE| or |EFFECT|.
purviews (list[tuple[int]]): The purviews to check.
mechanism (tuple[int]): The mechanism in question.
Returns:
list[tuple[int]]: All purviews in ``purviews`` which are not reducible
over ``mechanism``.
Raises:
ValueError: If ``direction`` is invalid.
"""
def reducible(purview):
"""Return ``True`` if purview is trivially reducible."""
_from, to = direction.order(mechanism, purview)
return connectivity.block_reducible(cm, _from, to)
return [purview for purview in purviews if not reducible(purview)]
|
[
"def",
"irreducible_purviews",
"(",
"cm",
",",
"direction",
",",
"mechanism",
",",
"purviews",
")",
":",
"def",
"reducible",
"(",
"purview",
")",
":",
"\"\"\"Return ``True`` if purview is trivially reducible.\"\"\"",
"_from",
",",
"to",
"=",
"direction",
".",
"order",
"(",
"mechanism",
",",
"purview",
")",
"return",
"connectivity",
".",
"block_reducible",
"(",
"cm",
",",
"_from",
",",
"to",
")",
"return",
"[",
"purview",
"for",
"purview",
"in",
"purviews",
"if",
"not",
"reducible",
"(",
"purview",
")",
"]"
] |
Return all purviews which are irreducible for the mechanism.
Args:
cm (np.ndarray): An |N x N| connectivity matrix.
direction (Direction): |CAUSE| or |EFFECT|.
purviews (list[tuple[int]]): The purviews to check.
mechanism (tuple[int]): The mechanism in question.
Returns:
list[tuple[int]]: All purviews in ``purviews`` which are not reducible
over ``mechanism``.
Raises:
ValueError: If ``direction`` is invalid.
|
[
"Return",
"all",
"purviews",
"which",
"are",
"irreducible",
"for",
"the",
"mechanism",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/network.py#L214-L235
|
16,049
|
wmayner/pyphi
|
pyphi/network.py
|
Network._build_tpm
|
def _build_tpm(tpm):
"""Validate the TPM passed by the user and convert to multidimensional
form.
"""
tpm = np.array(tpm)
validate.tpm(tpm)
# Convert to multidimensional state-by-node form
if is_state_by_state(tpm):
tpm = convert.state_by_state2state_by_node(tpm)
else:
tpm = convert.to_multidimensional(tpm)
utils.np_immutable(tpm)
return (tpm, utils.np_hash(tpm))
|
python
|
def _build_tpm(tpm):
"""Validate the TPM passed by the user and convert to multidimensional
form.
"""
tpm = np.array(tpm)
validate.tpm(tpm)
# Convert to multidimensional state-by-node form
if is_state_by_state(tpm):
tpm = convert.state_by_state2state_by_node(tpm)
else:
tpm = convert.to_multidimensional(tpm)
utils.np_immutable(tpm)
return (tpm, utils.np_hash(tpm))
|
[
"def",
"_build_tpm",
"(",
"tpm",
")",
":",
"tpm",
"=",
"np",
".",
"array",
"(",
"tpm",
")",
"validate",
".",
"tpm",
"(",
"tpm",
")",
"# Convert to multidimensional state-by-node form",
"if",
"is_state_by_state",
"(",
"tpm",
")",
":",
"tpm",
"=",
"convert",
".",
"state_by_state2state_by_node",
"(",
"tpm",
")",
"else",
":",
"tpm",
"=",
"convert",
".",
"to_multidimensional",
"(",
"tpm",
")",
"utils",
".",
"np_immutable",
"(",
"tpm",
")",
"return",
"(",
"tpm",
",",
"utils",
".",
"np_hash",
"(",
"tpm",
")",
")"
] |
Validate the TPM passed by the user and convert to multidimensional
form.
|
[
"Validate",
"the",
"TPM",
"passed",
"by",
"the",
"user",
"and",
"convert",
"to",
"multidimensional",
"form",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/network.py#L77-L93
|
16,050
|
wmayner/pyphi
|
pyphi/network.py
|
Network._build_cm
|
def _build_cm(self, cm):
"""Convert the passed CM to the proper format, or construct the
unitary CM if none was provided.
"""
if cm is None:
# Assume all are connected.
cm = np.ones((self.size, self.size))
else:
cm = np.array(cm)
utils.np_immutable(cm)
return (cm, utils.np_hash(cm))
|
python
|
def _build_cm(self, cm):
"""Convert the passed CM to the proper format, or construct the
unitary CM if none was provided.
"""
if cm is None:
# Assume all are connected.
cm = np.ones((self.size, self.size))
else:
cm = np.array(cm)
utils.np_immutable(cm)
return (cm, utils.np_hash(cm))
|
[
"def",
"_build_cm",
"(",
"self",
",",
"cm",
")",
":",
"if",
"cm",
"is",
"None",
":",
"# Assume all are connected.",
"cm",
"=",
"np",
".",
"ones",
"(",
"(",
"self",
".",
"size",
",",
"self",
".",
"size",
")",
")",
"else",
":",
"cm",
"=",
"np",
".",
"array",
"(",
"cm",
")",
"utils",
".",
"np_immutable",
"(",
"cm",
")",
"return",
"(",
"cm",
",",
"utils",
".",
"np_hash",
"(",
"cm",
")",
")"
] |
Convert the passed CM to the proper format, or construct the
unitary CM if none was provided.
|
[
"Convert",
"the",
"passed",
"CM",
"to",
"the",
"proper",
"format",
"or",
"construct",
"the",
"unitary",
"CM",
"if",
"none",
"was",
"provided",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/network.py#L104-L116
|
16,051
|
wmayner/pyphi
|
pyphi/network.py
|
Network.potential_purviews
|
def potential_purviews(self, direction, mechanism):
"""All purviews which are not clearly reducible for mechanism.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism which all purviews are
checked for reducibility over.
Returns:
list[tuple[int]]: All purviews which are irreducible over
``mechanism``.
"""
all_purviews = utils.powerset(self._node_indices)
return irreducible_purviews(self.cm, direction, mechanism,
all_purviews)
|
python
|
def potential_purviews(self, direction, mechanism):
"""All purviews which are not clearly reducible for mechanism.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism which all purviews are
checked for reducibility over.
Returns:
list[tuple[int]]: All purviews which are irreducible over
``mechanism``.
"""
all_purviews = utils.powerset(self._node_indices)
return irreducible_purviews(self.cm, direction, mechanism,
all_purviews)
|
[
"def",
"potential_purviews",
"(",
"self",
",",
"direction",
",",
"mechanism",
")",
":",
"all_purviews",
"=",
"utils",
".",
"powerset",
"(",
"self",
".",
"_node_indices",
")",
"return",
"irreducible_purviews",
"(",
"self",
".",
"cm",
",",
"direction",
",",
"mechanism",
",",
"all_purviews",
")"
] |
All purviews which are not clearly reducible for mechanism.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
mechanism (tuple[int]): The mechanism which all purviews are
checked for reducibility over.
Returns:
list[tuple[int]]: All purviews which are irreducible over
``mechanism``.
|
[
"All",
"purviews",
"which",
"are",
"not",
"clearly",
"reducible",
"for",
"mechanism",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/network.py#L155-L169
|
16,052
|
wmayner/pyphi
|
pyphi/jsonify.py
|
_loadable_models
|
def _loadable_models():
"""A dictionary of loadable PyPhi models.
These are stored in this function (instead of module scope) to resolve
circular import issues.
"""
classes = [
pyphi.Direction,
pyphi.Network,
pyphi.Subsystem,
pyphi.Transition,
pyphi.labels.NodeLabels,
pyphi.models.Cut,
pyphi.models.KCut,
pyphi.models.NullCut,
pyphi.models.Part,
pyphi.models.Bipartition,
pyphi.models.KPartition,
pyphi.models.Tripartition,
pyphi.models.RepertoireIrreducibilityAnalysis,
pyphi.models.MaximallyIrreducibleCauseOrEffect,
pyphi.models.MaximallyIrreducibleCause,
pyphi.models.MaximallyIrreducibleEffect,
pyphi.models.Concept,
pyphi.models.CauseEffectStructure,
pyphi.models.SystemIrreducibilityAnalysis,
pyphi.models.ActualCut,
pyphi.models.AcRepertoireIrreducibilityAnalysis,
pyphi.models.CausalLink,
pyphi.models.Account,
pyphi.models.AcSystemIrreducibilityAnalysis
]
return {cls.__name__: cls for cls in classes}
|
python
|
def _loadable_models():
"""A dictionary of loadable PyPhi models.
These are stored in this function (instead of module scope) to resolve
circular import issues.
"""
classes = [
pyphi.Direction,
pyphi.Network,
pyphi.Subsystem,
pyphi.Transition,
pyphi.labels.NodeLabels,
pyphi.models.Cut,
pyphi.models.KCut,
pyphi.models.NullCut,
pyphi.models.Part,
pyphi.models.Bipartition,
pyphi.models.KPartition,
pyphi.models.Tripartition,
pyphi.models.RepertoireIrreducibilityAnalysis,
pyphi.models.MaximallyIrreducibleCauseOrEffect,
pyphi.models.MaximallyIrreducibleCause,
pyphi.models.MaximallyIrreducibleEffect,
pyphi.models.Concept,
pyphi.models.CauseEffectStructure,
pyphi.models.SystemIrreducibilityAnalysis,
pyphi.models.ActualCut,
pyphi.models.AcRepertoireIrreducibilityAnalysis,
pyphi.models.CausalLink,
pyphi.models.Account,
pyphi.models.AcSystemIrreducibilityAnalysis
]
return {cls.__name__: cls for cls in classes}
|
[
"def",
"_loadable_models",
"(",
")",
":",
"classes",
"=",
"[",
"pyphi",
".",
"Direction",
",",
"pyphi",
".",
"Network",
",",
"pyphi",
".",
"Subsystem",
",",
"pyphi",
".",
"Transition",
",",
"pyphi",
".",
"labels",
".",
"NodeLabels",
",",
"pyphi",
".",
"models",
".",
"Cut",
",",
"pyphi",
".",
"models",
".",
"KCut",
",",
"pyphi",
".",
"models",
".",
"NullCut",
",",
"pyphi",
".",
"models",
".",
"Part",
",",
"pyphi",
".",
"models",
".",
"Bipartition",
",",
"pyphi",
".",
"models",
".",
"KPartition",
",",
"pyphi",
".",
"models",
".",
"Tripartition",
",",
"pyphi",
".",
"models",
".",
"RepertoireIrreducibilityAnalysis",
",",
"pyphi",
".",
"models",
".",
"MaximallyIrreducibleCauseOrEffect",
",",
"pyphi",
".",
"models",
".",
"MaximallyIrreducibleCause",
",",
"pyphi",
".",
"models",
".",
"MaximallyIrreducibleEffect",
",",
"pyphi",
".",
"models",
".",
"Concept",
",",
"pyphi",
".",
"models",
".",
"CauseEffectStructure",
",",
"pyphi",
".",
"models",
".",
"SystemIrreducibilityAnalysis",
",",
"pyphi",
".",
"models",
".",
"ActualCut",
",",
"pyphi",
".",
"models",
".",
"AcRepertoireIrreducibilityAnalysis",
",",
"pyphi",
".",
"models",
".",
"CausalLink",
",",
"pyphi",
".",
"models",
".",
"Account",
",",
"pyphi",
".",
"models",
".",
"AcSystemIrreducibilityAnalysis",
"]",
"return",
"{",
"cls",
".",
"__name__",
":",
"cls",
"for",
"cls",
"in",
"classes",
"}"
] |
A dictionary of loadable PyPhi models.
These are stored in this function (instead of module scope) to resolve
circular import issues.
|
[
"A",
"dictionary",
"of",
"loadable",
"PyPhi",
"models",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/jsonify.py#L51-L83
|
16,053
|
wmayner/pyphi
|
pyphi/jsonify.py
|
jsonify
|
def jsonify(obj): # pylint: disable=too-many-return-statements
"""Return a JSON-encodable representation of an object, recursively using
any available ``to_json`` methods, converting NumPy arrays and datatypes to
native lists and types along the way.
"""
# Call the `to_json` method if available and add metadata.
if hasattr(obj, 'to_json'):
d = obj.to_json()
_push_metadata(d, obj)
return jsonify(d)
# If we have a numpy array, convert it to a list.
if isinstance(obj, np.ndarray):
return obj.tolist()
# If we have NumPy datatypes, convert them to native types.
if isinstance(obj, (np.int32, np.int64)):
return int(obj)
if isinstance(obj, np.float64):
return float(obj)
# Recurse over dictionaries.
if isinstance(obj, dict):
return _jsonify_dict(obj)
# Recurse over object dictionaries.
if hasattr(obj, '__dict__'):
return _jsonify_dict(obj.__dict__)
# Recurse over lists and tuples.
if isinstance(obj, (list, tuple)):
return [jsonify(item) for item in obj]
# Otherwise, give up and hope it's serializable.
return obj
|
python
|
def jsonify(obj): # pylint: disable=too-many-return-statements
"""Return a JSON-encodable representation of an object, recursively using
any available ``to_json`` methods, converting NumPy arrays and datatypes to
native lists and types along the way.
"""
# Call the `to_json` method if available and add metadata.
if hasattr(obj, 'to_json'):
d = obj.to_json()
_push_metadata(d, obj)
return jsonify(d)
# If we have a numpy array, convert it to a list.
if isinstance(obj, np.ndarray):
return obj.tolist()
# If we have NumPy datatypes, convert them to native types.
if isinstance(obj, (np.int32, np.int64)):
return int(obj)
if isinstance(obj, np.float64):
return float(obj)
# Recurse over dictionaries.
if isinstance(obj, dict):
return _jsonify_dict(obj)
# Recurse over object dictionaries.
if hasattr(obj, '__dict__'):
return _jsonify_dict(obj.__dict__)
# Recurse over lists and tuples.
if isinstance(obj, (list, tuple)):
return [jsonify(item) for item in obj]
# Otherwise, give up and hope it's serializable.
return obj
|
[
"def",
"jsonify",
"(",
"obj",
")",
":",
"# pylint: disable=too-many-return-statements",
"# Call the `to_json` method if available and add metadata.",
"if",
"hasattr",
"(",
"obj",
",",
"'to_json'",
")",
":",
"d",
"=",
"obj",
".",
"to_json",
"(",
")",
"_push_metadata",
"(",
"d",
",",
"obj",
")",
"return",
"jsonify",
"(",
"d",
")",
"# If we have a numpy array, convert it to a list.",
"if",
"isinstance",
"(",
"obj",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"obj",
".",
"tolist",
"(",
")",
"# If we have NumPy datatypes, convert them to native types.",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"np",
".",
"int32",
",",
"np",
".",
"int64",
")",
")",
":",
"return",
"int",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"np",
".",
"float64",
")",
":",
"return",
"float",
"(",
"obj",
")",
"# Recurse over dictionaries.",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"_jsonify_dict",
"(",
"obj",
")",
"# Recurse over object dictionaries.",
"if",
"hasattr",
"(",
"obj",
",",
"'__dict__'",
")",
":",
"return",
"_jsonify_dict",
"(",
"obj",
".",
"__dict__",
")",
"# Recurse over lists and tuples.",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"jsonify",
"(",
"item",
")",
"for",
"item",
"in",
"obj",
"]",
"# Otherwise, give up and hope it's serializable.",
"return",
"obj"
] |
Return a JSON-encodable representation of an object, recursively using
any available ``to_json`` methods, converting NumPy arrays and datatypes to
native lists and types along the way.
|
[
"Return",
"a",
"JSON",
"-",
"encodable",
"representation",
"of",
"an",
"object",
"recursively",
"using",
"any",
"available",
"to_json",
"methods",
"converting",
"NumPy",
"arrays",
"and",
"datatypes",
"to",
"native",
"lists",
"and",
"types",
"along",
"the",
"way",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/jsonify.py#L107-L141
|
16,054
|
wmayner/pyphi
|
pyphi/jsonify.py
|
_check_version
|
def _check_version(version):
"""Check whether the JSON version matches the PyPhi version."""
if version != pyphi.__version__:
raise pyphi.exceptions.JSONVersionError(
'Cannot load JSON from a different version of PyPhi. '
'JSON version = {0}, current version = {1}.'.format(
version, pyphi.__version__))
|
python
|
def _check_version(version):
"""Check whether the JSON version matches the PyPhi version."""
if version != pyphi.__version__:
raise pyphi.exceptions.JSONVersionError(
'Cannot load JSON from a different version of PyPhi. '
'JSON version = {0}, current version = {1}.'.format(
version, pyphi.__version__))
|
[
"def",
"_check_version",
"(",
"version",
")",
":",
"if",
"version",
"!=",
"pyphi",
".",
"__version__",
":",
"raise",
"pyphi",
".",
"exceptions",
".",
"JSONVersionError",
"(",
"'Cannot load JSON from a different version of PyPhi. '",
"'JSON version = {0}, current version = {1}.'",
".",
"format",
"(",
"version",
",",
"pyphi",
".",
"__version__",
")",
")"
] |
Check whether the JSON version matches the PyPhi version.
|
[
"Check",
"whether",
"the",
"JSON",
"version",
"matches",
"the",
"PyPhi",
"version",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/jsonify.py#L176-L182
|
16,055
|
wmayner/pyphi
|
pyphi/jsonify.py
|
PyPhiJSONDecoder._load_object
|
def _load_object(self, obj):
"""Recursively load a PyPhi object.
PyPhi models are recursively loaded, using the model metadata to
recreate the original object relations. Lists are cast to tuples
because most objects in PyPhi which are serialized to lists (eg.
mechanisms and purviews) are ultimately tuples. Other lists (tpms,
repertoires) should be cast to the correct type in init methods.
"""
if isinstance(obj, dict):
obj = {k: self._load_object(v) for k, v in obj.items()}
# Load a serialized PyPhi model
if _is_model(obj):
return self._load_model(obj)
elif isinstance(obj, list):
return tuple(self._load_object(item) for item in obj)
return obj
|
python
|
def _load_object(self, obj):
"""Recursively load a PyPhi object.
PyPhi models are recursively loaded, using the model metadata to
recreate the original object relations. Lists are cast to tuples
because most objects in PyPhi which are serialized to lists (eg.
mechanisms and purviews) are ultimately tuples. Other lists (tpms,
repertoires) should be cast to the correct type in init methods.
"""
if isinstance(obj, dict):
obj = {k: self._load_object(v) for k, v in obj.items()}
# Load a serialized PyPhi model
if _is_model(obj):
return self._load_model(obj)
elif isinstance(obj, list):
return tuple(self._load_object(item) for item in obj)
return obj
|
[
"def",
"_load_object",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"obj",
"=",
"{",
"k",
":",
"self",
".",
"_load_object",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
"}",
"# Load a serialized PyPhi model",
"if",
"_is_model",
"(",
"obj",
")",
":",
"return",
"self",
".",
"_load_model",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"_load_object",
"(",
"item",
")",
"for",
"item",
"in",
"obj",
")",
"return",
"obj"
] |
Recursively load a PyPhi object.
PyPhi models are recursively loaded, using the model metadata to
recreate the original object relations. Lists are cast to tuples
because most objects in PyPhi which are serialized to lists (eg.
mechanisms and purviews) are ultimately tuples. Other lists (tpms,
repertoires) should be cast to the correct type in init methods.
|
[
"Recursively",
"load",
"a",
"PyPhi",
"object",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/jsonify.py#L212-L230
|
16,056
|
wmayner/pyphi
|
pyphi/jsonify.py
|
PyPhiJSONDecoder._load_model
|
def _load_model(self, dct):
"""Load a serialized PyPhi model.
The object is memoized for reuse elsewhere in the object graph.
"""
classname, version, _ = _pop_metadata(dct)
_check_version(version)
cls = self._models[classname]
# Use `from_json` if available
if hasattr(cls, 'from_json'):
return cls.from_json(dct)
# Default to object constructor
return cls(**dct)
|
python
|
def _load_model(self, dct):
"""Load a serialized PyPhi model.
The object is memoized for reuse elsewhere in the object graph.
"""
classname, version, _ = _pop_metadata(dct)
_check_version(version)
cls = self._models[classname]
# Use `from_json` if available
if hasattr(cls, 'from_json'):
return cls.from_json(dct)
# Default to object constructor
return cls(**dct)
|
[
"def",
"_load_model",
"(",
"self",
",",
"dct",
")",
":",
"classname",
",",
"version",
",",
"_",
"=",
"_pop_metadata",
"(",
"dct",
")",
"_check_version",
"(",
"version",
")",
"cls",
"=",
"self",
".",
"_models",
"[",
"classname",
"]",
"# Use `from_json` if available",
"if",
"hasattr",
"(",
"cls",
",",
"'from_json'",
")",
":",
"return",
"cls",
".",
"from_json",
"(",
"dct",
")",
"# Default to object constructor",
"return",
"cls",
"(",
"*",
"*",
"dct",
")"
] |
Load a serialized PyPhi model.
The object is memoized for reuse elsewhere in the object graph.
|
[
"Load",
"a",
"serialized",
"PyPhi",
"model",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/jsonify.py#L233-L248
|
16,057
|
wmayner/pyphi
|
pyphi/distance.py
|
_compute_hamming_matrix
|
def _compute_hamming_matrix(N):
"""Compute and store a Hamming matrix for |N| nodes.
Hamming matrices have the following sizes::
N MBs
== ===
9 2
10 8
11 32
12 128
13 512
Given these sizes and the fact that large matrices are needed infrequently,
we store computed matrices using the Joblib filesystem cache instead of
adding computed matrices to the ``_hamming_matrices`` global and clogging
up memory.
This function is only called when |N| >
``_NUM_PRECOMPUTED_HAMMING_MATRICES``. Don't call this function directly;
use |_hamming_matrix| instead.
"""
possible_states = np.array(list(utils.all_states((N))))
return cdist(possible_states, possible_states, 'hamming') * N
|
python
|
def _compute_hamming_matrix(N):
"""Compute and store a Hamming matrix for |N| nodes.
Hamming matrices have the following sizes::
N MBs
== ===
9 2
10 8
11 32
12 128
13 512
Given these sizes and the fact that large matrices are needed infrequently,
we store computed matrices using the Joblib filesystem cache instead of
adding computed matrices to the ``_hamming_matrices`` global and clogging
up memory.
This function is only called when |N| >
``_NUM_PRECOMPUTED_HAMMING_MATRICES``. Don't call this function directly;
use |_hamming_matrix| instead.
"""
possible_states = np.array(list(utils.all_states((N))))
return cdist(possible_states, possible_states, 'hamming') * N
|
[
"def",
"_compute_hamming_matrix",
"(",
"N",
")",
":",
"possible_states",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"utils",
".",
"all_states",
"(",
"(",
"N",
")",
")",
")",
")",
"return",
"cdist",
"(",
"possible_states",
",",
"possible_states",
",",
"'hamming'",
")",
"*",
"N"
] |
Compute and store a Hamming matrix for |N| nodes.
Hamming matrices have the following sizes::
N MBs
== ===
9 2
10 8
11 32
12 128
13 512
Given these sizes and the fact that large matrices are needed infrequently,
we store computed matrices using the Joblib filesystem cache instead of
adding computed matrices to the ``_hamming_matrices`` global and clogging
up memory.
This function is only called when |N| >
``_NUM_PRECOMPUTED_HAMMING_MATRICES``. Don't call this function directly;
use |_hamming_matrix| instead.
|
[
"Compute",
"and",
"store",
"a",
"Hamming",
"matrix",
"for",
"|N|",
"nodes",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L107-L130
|
16,058
|
wmayner/pyphi
|
pyphi/distance.py
|
effect_emd
|
def effect_emd(d1, d2):
"""Compute the EMD between two effect repertoires.
Because the nodes are independent, the EMD between effect repertoires is
equal to the sum of the EMDs between the marginal distributions of each
node, and the EMD between marginal distribution for a node is the absolute
difference in the probabilities that the node is OFF.
Args:
d1 (np.ndarray): The first repertoire.
d2 (np.ndarray): The second repertoire.
Returns:
float: The EMD between ``d1`` and ``d2``.
"""
return sum(abs(marginal_zero(d1, i) - marginal_zero(d2, i))
for i in range(d1.ndim))
|
python
|
def effect_emd(d1, d2):
"""Compute the EMD between two effect repertoires.
Because the nodes are independent, the EMD between effect repertoires is
equal to the sum of the EMDs between the marginal distributions of each
node, and the EMD between marginal distribution for a node is the absolute
difference in the probabilities that the node is OFF.
Args:
d1 (np.ndarray): The first repertoire.
d2 (np.ndarray): The second repertoire.
Returns:
float: The EMD between ``d1`` and ``d2``.
"""
return sum(abs(marginal_zero(d1, i) - marginal_zero(d2, i))
for i in range(d1.ndim))
|
[
"def",
"effect_emd",
"(",
"d1",
",",
"d2",
")",
":",
"return",
"sum",
"(",
"abs",
"(",
"marginal_zero",
"(",
"d1",
",",
"i",
")",
"-",
"marginal_zero",
"(",
"d2",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"d1",
".",
"ndim",
")",
")"
] |
Compute the EMD between two effect repertoires.
Because the nodes are independent, the EMD between effect repertoires is
equal to the sum of the EMDs between the marginal distributions of each
node, and the EMD between marginal distribution for a node is the absolute
difference in the probabilities that the node is OFF.
Args:
d1 (np.ndarray): The first repertoire.
d2 (np.ndarray): The second repertoire.
Returns:
float: The EMD between ``d1`` and ``d2``.
|
[
"Compute",
"the",
"EMD",
"between",
"two",
"effect",
"repertoires",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L147-L163
|
16,059
|
wmayner/pyphi
|
pyphi/distance.py
|
entropy_difference
|
def entropy_difference(d1, d2):
"""Return the difference in entropy between two distributions."""
d1, d2 = flatten(d1), flatten(d2)
return abs(entropy(d1, base=2.0) - entropy(d2, base=2.0))
|
python
|
def entropy_difference(d1, d2):
"""Return the difference in entropy between two distributions."""
d1, d2 = flatten(d1), flatten(d2)
return abs(entropy(d1, base=2.0) - entropy(d2, base=2.0))
|
[
"def",
"entropy_difference",
"(",
"d1",
",",
"d2",
")",
":",
"d1",
",",
"d2",
"=",
"flatten",
"(",
"d1",
")",
",",
"flatten",
"(",
"d2",
")",
"return",
"abs",
"(",
"entropy",
"(",
"d1",
",",
"base",
"=",
"2.0",
")",
"-",
"entropy",
"(",
"d2",
",",
"base",
"=",
"2.0",
")",
")"
] |
Return the difference in entropy between two distributions.
|
[
"Return",
"the",
"difference",
"in",
"entropy",
"between",
"two",
"distributions",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L196-L199
|
16,060
|
wmayner/pyphi
|
pyphi/distance.py
|
psq2
|
def psq2(d1, d2):
"""Compute the PSQ2 measure.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution.
"""
d1, d2 = flatten(d1), flatten(d2)
def f(p):
return sum((p ** 2) * np.nan_to_num(np.log(p * len(p))))
return abs(f(d1) - f(d2))
|
python
|
def psq2(d1, d2):
"""Compute the PSQ2 measure.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution.
"""
d1, d2 = flatten(d1), flatten(d2)
def f(p):
return sum((p ** 2) * np.nan_to_num(np.log(p * len(p))))
return abs(f(d1) - f(d2))
|
[
"def",
"psq2",
"(",
"d1",
",",
"d2",
")",
":",
"d1",
",",
"d2",
"=",
"flatten",
"(",
"d1",
")",
",",
"flatten",
"(",
"d2",
")",
"def",
"f",
"(",
"p",
")",
":",
"return",
"sum",
"(",
"(",
"p",
"**",
"2",
")",
"*",
"np",
".",
"nan_to_num",
"(",
"np",
".",
"log",
"(",
"p",
"*",
"len",
"(",
"p",
")",
")",
")",
")",
"return",
"abs",
"(",
"f",
"(",
"d1",
")",
"-",
"f",
"(",
"d2",
")",
")"
] |
Compute the PSQ2 measure.
Args:
d1 (np.ndarray): The first distribution.
d2 (np.ndarray): The second distribution.
|
[
"Compute",
"the",
"PSQ2",
"measure",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L204-L216
|
16,061
|
wmayner/pyphi
|
pyphi/distance.py
|
mp2q
|
def mp2q(p, q):
"""Compute the MP2Q measure.
Args:
p (np.ndarray): The unpartitioned repertoire
q (np.ndarray): The partitioned repertoire
"""
p, q = flatten(p), flatten(q)
entropy_dist = 1 / len(p)
return sum(entropy_dist * np.nan_to_num((p ** 2) / q * np.log(p / q)))
|
python
|
def mp2q(p, q):
"""Compute the MP2Q measure.
Args:
p (np.ndarray): The unpartitioned repertoire
q (np.ndarray): The partitioned repertoire
"""
p, q = flatten(p), flatten(q)
entropy_dist = 1 / len(p)
return sum(entropy_dist * np.nan_to_num((p ** 2) / q * np.log(p / q)))
|
[
"def",
"mp2q",
"(",
"p",
",",
"q",
")",
":",
"p",
",",
"q",
"=",
"flatten",
"(",
"p",
")",
",",
"flatten",
"(",
"q",
")",
"entropy_dist",
"=",
"1",
"/",
"len",
"(",
"p",
")",
"return",
"sum",
"(",
"entropy_dist",
"*",
"np",
".",
"nan_to_num",
"(",
"(",
"p",
"**",
"2",
")",
"/",
"q",
"*",
"np",
".",
"log",
"(",
"p",
"/",
"q",
")",
")",
")"
] |
Compute the MP2Q measure.
Args:
p (np.ndarray): The unpartitioned repertoire
q (np.ndarray): The partitioned repertoire
|
[
"Compute",
"the",
"MP2Q",
"measure",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L221-L230
|
16,062
|
wmayner/pyphi
|
pyphi/distance.py
|
klm
|
def klm(p, q):
"""Compute the KLM divergence."""
p, q = flatten(p), flatten(q)
return max(abs(p * np.nan_to_num(np.log(p / q))))
|
python
|
def klm(p, q):
"""Compute the KLM divergence."""
p, q = flatten(p), flatten(q)
return max(abs(p * np.nan_to_num(np.log(p / q))))
|
[
"def",
"klm",
"(",
"p",
",",
"q",
")",
":",
"p",
",",
"q",
"=",
"flatten",
"(",
"p",
")",
",",
"flatten",
"(",
"q",
")",
"return",
"max",
"(",
"abs",
"(",
"p",
"*",
"np",
".",
"nan_to_num",
"(",
"np",
".",
"log",
"(",
"p",
"/",
"q",
")",
")",
")",
")"
] |
Compute the KLM divergence.
|
[
"Compute",
"the",
"KLM",
"divergence",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L236-L239
|
16,063
|
wmayner/pyphi
|
pyphi/distance.py
|
directional_emd
|
def directional_emd(direction, d1, d2):
"""Compute the EMD between two repertoires for a given direction.
The full EMD computation is used for cause repertoires. A fast analytic
solution is used for effect repertoires.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
d1 (np.ndarray): The first repertoire.
d2 (np.ndarray): The second repertoire.
Returns:
float: The EMD between ``d1`` and ``d2``, rounded to |PRECISION|.
Raises:
ValueError: If ``direction`` is invalid.
"""
if direction == Direction.CAUSE:
func = hamming_emd
elif direction == Direction.EFFECT:
func = effect_emd
else:
# TODO: test that ValueError is raised
validate.direction(direction)
return round(func(d1, d2), config.PRECISION)
|
python
|
def directional_emd(direction, d1, d2):
"""Compute the EMD between two repertoires for a given direction.
The full EMD computation is used for cause repertoires. A fast analytic
solution is used for effect repertoires.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
d1 (np.ndarray): The first repertoire.
d2 (np.ndarray): The second repertoire.
Returns:
float: The EMD between ``d1`` and ``d2``, rounded to |PRECISION|.
Raises:
ValueError: If ``direction`` is invalid.
"""
if direction == Direction.CAUSE:
func = hamming_emd
elif direction == Direction.EFFECT:
func = effect_emd
else:
# TODO: test that ValueError is raised
validate.direction(direction)
return round(func(d1, d2), config.PRECISION)
|
[
"def",
"directional_emd",
"(",
"direction",
",",
"d1",
",",
"d2",
")",
":",
"if",
"direction",
"==",
"Direction",
".",
"CAUSE",
":",
"func",
"=",
"hamming_emd",
"elif",
"direction",
"==",
"Direction",
".",
"EFFECT",
":",
"func",
"=",
"effect_emd",
"else",
":",
"# TODO: test that ValueError is raised",
"validate",
".",
"direction",
"(",
"direction",
")",
"return",
"round",
"(",
"func",
"(",
"d1",
",",
"d2",
")",
",",
"config",
".",
"PRECISION",
")"
] |
Compute the EMD between two repertoires for a given direction.
The full EMD computation is used for cause repertoires. A fast analytic
solution is used for effect repertoires.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
d1 (np.ndarray): The first repertoire.
d2 (np.ndarray): The second repertoire.
Returns:
float: The EMD between ``d1`` and ``d2``, rounded to |PRECISION|.
Raises:
ValueError: If ``direction`` is invalid.
|
[
"Compute",
"the",
"EMD",
"between",
"two",
"repertoires",
"for",
"a",
"given",
"direction",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L242-L267
|
16,064
|
wmayner/pyphi
|
pyphi/distance.py
|
repertoire_distance
|
def repertoire_distance(direction, r1, r2):
"""Compute the distance between two repertoires for the given direction.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``d1`` and ``d2``, rounded to |PRECISION|.
"""
if config.MEASURE == 'EMD':
dist = directional_emd(direction, r1, r2)
else:
dist = measures[config.MEASURE](r1, r2)
return round(dist, config.PRECISION)
|
python
|
def repertoire_distance(direction, r1, r2):
"""Compute the distance between two repertoires for the given direction.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``d1`` and ``d2``, rounded to |PRECISION|.
"""
if config.MEASURE == 'EMD':
dist = directional_emd(direction, r1, r2)
else:
dist = measures[config.MEASURE](r1, r2)
return round(dist, config.PRECISION)
|
[
"def",
"repertoire_distance",
"(",
"direction",
",",
"r1",
",",
"r2",
")",
":",
"if",
"config",
".",
"MEASURE",
"==",
"'EMD'",
":",
"dist",
"=",
"directional_emd",
"(",
"direction",
",",
"r1",
",",
"r2",
")",
"else",
":",
"dist",
"=",
"measures",
"[",
"config",
".",
"MEASURE",
"]",
"(",
"r1",
",",
"r2",
")",
"return",
"round",
"(",
"dist",
",",
"config",
".",
"PRECISION",
")"
] |
Compute the distance between two repertoires for the given direction.
Args:
direction (Direction): |CAUSE| or |EFFECT|.
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``d1`` and ``d2``, rounded to |PRECISION|.
|
[
"Compute",
"the",
"distance",
"between",
"two",
"repertoires",
"for",
"the",
"given",
"direction",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L270-L286
|
16,065
|
wmayner/pyphi
|
pyphi/distance.py
|
system_repertoire_distance
|
def system_repertoire_distance(r1, r2):
"""Compute the distance between two repertoires of a system.
Args:
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``r1`` and ``r2``.
"""
if config.MEASURE in measures.asymmetric():
raise ValueError(
'{} is asymmetric and cannot be used as a system-level '
'irreducibility measure.'.format(config.MEASURE))
return measures[config.MEASURE](r1, r2)
|
python
|
def system_repertoire_distance(r1, r2):
"""Compute the distance between two repertoires of a system.
Args:
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``r1`` and ``r2``.
"""
if config.MEASURE in measures.asymmetric():
raise ValueError(
'{} is asymmetric and cannot be used as a system-level '
'irreducibility measure.'.format(config.MEASURE))
return measures[config.MEASURE](r1, r2)
|
[
"def",
"system_repertoire_distance",
"(",
"r1",
",",
"r2",
")",
":",
"if",
"config",
".",
"MEASURE",
"in",
"measures",
".",
"asymmetric",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'{} is asymmetric and cannot be used as a system-level '",
"'irreducibility measure.'",
".",
"format",
"(",
"config",
".",
"MEASURE",
")",
")",
"return",
"measures",
"[",
"config",
".",
"MEASURE",
"]",
"(",
"r1",
",",
"r2",
")"
] |
Compute the distance between two repertoires of a system.
Args:
r1 (np.ndarray): The first repertoire.
r2 (np.ndarray): The second repertoire.
Returns:
float: The distance between ``r1`` and ``r2``.
|
[
"Compute",
"the",
"distance",
"between",
"two",
"repertoires",
"of",
"a",
"system",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L289-L304
|
16,066
|
wmayner/pyphi
|
pyphi/distance.py
|
MeasureRegistry.register
|
def register(self, name, asymmetric=False):
"""Decorator for registering a measure with PyPhi.
Args:
name (string): The name of the measure.
Keyword Args:
asymmetric (boolean): ``True`` if the measure is asymmetric.
"""
def register_func(func):
if asymmetric:
self._asymmetric.append(name)
self.store[name] = func
return func
return register_func
|
python
|
def register(self, name, asymmetric=False):
"""Decorator for registering a measure with PyPhi.
Args:
name (string): The name of the measure.
Keyword Args:
asymmetric (boolean): ``True`` if the measure is asymmetric.
"""
def register_func(func):
if asymmetric:
self._asymmetric.append(name)
self.store[name] = func
return func
return register_func
|
[
"def",
"register",
"(",
"self",
",",
"name",
",",
"asymmetric",
"=",
"False",
")",
":",
"def",
"register_func",
"(",
"func",
")",
":",
"if",
"asymmetric",
":",
"self",
".",
"_asymmetric",
".",
"append",
"(",
"name",
")",
"self",
".",
"store",
"[",
"name",
"]",
"=",
"func",
"return",
"func",
"return",
"register_func"
] |
Decorator for registering a measure with PyPhi.
Args:
name (string): The name of the measure.
Keyword Args:
asymmetric (boolean): ``True`` if the measure is asymmetric.
|
[
"Decorator",
"for",
"registering",
"a",
"measure",
"with",
"PyPhi",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distance.py#L46-L60
|
16,067
|
wmayner/pyphi
|
pyphi/partition.py
|
partitions
|
def partitions(collection):
"""Generate all set partitions of a collection.
Example:
>>> list(partitions(range(3))) # doctest: +NORMALIZE_WHITESPACE
[[[0, 1, 2]],
[[0], [1, 2]],
[[0, 1], [2]],
[[1], [0, 2]],
[[0], [1], [2]]]
"""
collection = list(collection)
# Special cases
if not collection:
return
if len(collection) == 1:
yield [collection]
return
first = collection[0]
for smaller in partitions(collection[1:]):
for n, subset in enumerate(smaller):
yield smaller[:n] + [[first] + subset] + smaller[n+1:]
yield [[first]] + smaller
|
python
|
def partitions(collection):
"""Generate all set partitions of a collection.
Example:
>>> list(partitions(range(3))) # doctest: +NORMALIZE_WHITESPACE
[[[0, 1, 2]],
[[0], [1, 2]],
[[0, 1], [2]],
[[1], [0, 2]],
[[0], [1], [2]]]
"""
collection = list(collection)
# Special cases
if not collection:
return
if len(collection) == 1:
yield [collection]
return
first = collection[0]
for smaller in partitions(collection[1:]):
for n, subset in enumerate(smaller):
yield smaller[:n] + [[first] + subset] + smaller[n+1:]
yield [[first]] + smaller
|
[
"def",
"partitions",
"(",
"collection",
")",
":",
"collection",
"=",
"list",
"(",
"collection",
")",
"# Special cases",
"if",
"not",
"collection",
":",
"return",
"if",
"len",
"(",
"collection",
")",
"==",
"1",
":",
"yield",
"[",
"collection",
"]",
"return",
"first",
"=",
"collection",
"[",
"0",
"]",
"for",
"smaller",
"in",
"partitions",
"(",
"collection",
"[",
"1",
":",
"]",
")",
":",
"for",
"n",
",",
"subset",
"in",
"enumerate",
"(",
"smaller",
")",
":",
"yield",
"smaller",
"[",
":",
"n",
"]",
"+",
"[",
"[",
"first",
"]",
"+",
"subset",
"]",
"+",
"smaller",
"[",
"n",
"+",
"1",
":",
"]",
"yield",
"[",
"[",
"first",
"]",
"]",
"+",
"smaller"
] |
Generate all set partitions of a collection.
Example:
>>> list(partitions(range(3))) # doctest: +NORMALIZE_WHITESPACE
[[[0, 1, 2]],
[[0], [1, 2]],
[[0, 1], [2]],
[[1], [0, 2]],
[[0], [1], [2]]]
|
[
"Generate",
"all",
"set",
"partitions",
"of",
"a",
"collection",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L18-L43
|
16,068
|
wmayner/pyphi
|
pyphi/partition.py
|
bipartition_indices
|
def bipartition_indices(N):
"""Return indices for undirected bipartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list: A list of tuples containing the indices for each of the two
parts.
Example:
>>> N = 3
>>> bipartition_indices(N)
[((), (0, 1, 2)), ((0,), (1, 2)), ((1,), (0, 2)), ((0, 1), (2,))]
"""
result = []
if N <= 0:
return result
for i in range(2**(N - 1)):
part = [[], []]
for n in range(N):
bit = (i >> n) & 1
part[bit].append(n)
result.append((tuple(part[1]), tuple(part[0])))
return result
|
python
|
def bipartition_indices(N):
"""Return indices for undirected bipartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list: A list of tuples containing the indices for each of the two
parts.
Example:
>>> N = 3
>>> bipartition_indices(N)
[((), (0, 1, 2)), ((0,), (1, 2)), ((1,), (0, 2)), ((0, 1), (2,))]
"""
result = []
if N <= 0:
return result
for i in range(2**(N - 1)):
part = [[], []]
for n in range(N):
bit = (i >> n) & 1
part[bit].append(n)
result.append((tuple(part[1]), tuple(part[0])))
return result
|
[
"def",
"bipartition_indices",
"(",
"N",
")",
":",
"result",
"=",
"[",
"]",
"if",
"N",
"<=",
"0",
":",
"return",
"result",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
"(",
"N",
"-",
"1",
")",
")",
":",
"part",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"n",
"in",
"range",
"(",
"N",
")",
":",
"bit",
"=",
"(",
"i",
">>",
"n",
")",
"&",
"1",
"part",
"[",
"bit",
"]",
".",
"append",
"(",
"n",
")",
"result",
".",
"append",
"(",
"(",
"tuple",
"(",
"part",
"[",
"1",
"]",
")",
",",
"tuple",
"(",
"part",
"[",
"0",
"]",
")",
")",
")",
"return",
"result"
] |
Return indices for undirected bipartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list: A list of tuples containing the indices for each of the two
parts.
Example:
>>> N = 3
>>> bipartition_indices(N)
[((), (0, 1, 2)), ((0,), (1, 2)), ((1,), (0, 2)), ((0, 1), (2,))]
|
[
"Return",
"indices",
"for",
"undirected",
"bipartitions",
"of",
"a",
"sequence",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L47-L72
|
16,069
|
wmayner/pyphi
|
pyphi/partition.py
|
bipartition
|
def bipartition(seq):
"""Return a list of bipartitions for a sequence.
Args:
a (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> bipartition((1,2,3))
[((), (1, 2, 3)), ((1,), (2, 3)), ((2,), (1, 3)), ((1, 2), (3,))]
"""
return [(tuple(seq[i] for i in part0_idx),
tuple(seq[j] for j in part1_idx))
for part0_idx, part1_idx in bipartition_indices(len(seq))]
|
python
|
def bipartition(seq):
"""Return a list of bipartitions for a sequence.
Args:
a (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> bipartition((1,2,3))
[((), (1, 2, 3)), ((1,), (2, 3)), ((2,), (1, 3)), ((1, 2), (3,))]
"""
return [(tuple(seq[i] for i in part0_idx),
tuple(seq[j] for j in part1_idx))
for part0_idx, part1_idx in bipartition_indices(len(seq))]
|
[
"def",
"bipartition",
"(",
"seq",
")",
":",
"return",
"[",
"(",
"tuple",
"(",
"seq",
"[",
"i",
"]",
"for",
"i",
"in",
"part0_idx",
")",
",",
"tuple",
"(",
"seq",
"[",
"j",
"]",
"for",
"j",
"in",
"part1_idx",
")",
")",
"for",
"part0_idx",
",",
"part1_idx",
"in",
"bipartition_indices",
"(",
"len",
"(",
"seq",
")",
")",
"]"
] |
Return a list of bipartitions for a sequence.
Args:
a (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> bipartition((1,2,3))
[((), (1, 2, 3)), ((1,), (2, 3)), ((2,), (1, 3)), ((1, 2), (3,))]
|
[
"Return",
"a",
"list",
"of",
"bipartitions",
"for",
"a",
"sequence",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L76-L92
|
16,070
|
wmayner/pyphi
|
pyphi/partition.py
|
directed_bipartition
|
def directed_bipartition(seq, nontrivial=False):
"""Return a list of directed bipartitions for a sequence.
Args:
seq (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
parts.
Example:
>>> directed_bipartition((1, 2, 3)) # doctest: +NORMALIZE_WHITESPACE
[((), (1, 2, 3)),
((1,), (2, 3)),
((2,), (1, 3)),
((1, 2), (3,)),
((3,), (1, 2)),
((1, 3), (2,)),
((2, 3), (1,)),
((1, 2, 3), ())]
"""
bipartitions = [
(tuple(seq[i] for i in part0_idx), tuple(seq[j] for j in part1_idx))
for part0_idx, part1_idx in directed_bipartition_indices(len(seq))
]
if nontrivial:
# The first and last partitions have a part that is empty; skip them.
# NOTE: This depends on the implementation of
# `directed_partition_indices`.
return bipartitions[1:-1]
return bipartitions
|
python
|
def directed_bipartition(seq, nontrivial=False):
"""Return a list of directed bipartitions for a sequence.
Args:
seq (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
parts.
Example:
>>> directed_bipartition((1, 2, 3)) # doctest: +NORMALIZE_WHITESPACE
[((), (1, 2, 3)),
((1,), (2, 3)),
((2,), (1, 3)),
((1, 2), (3,)),
((3,), (1, 2)),
((1, 3), (2,)),
((2, 3), (1,)),
((1, 2, 3), ())]
"""
bipartitions = [
(tuple(seq[i] for i in part0_idx), tuple(seq[j] for j in part1_idx))
for part0_idx, part1_idx in directed_bipartition_indices(len(seq))
]
if nontrivial:
# The first and last partitions have a part that is empty; skip them.
# NOTE: This depends on the implementation of
# `directed_partition_indices`.
return bipartitions[1:-1]
return bipartitions
|
[
"def",
"directed_bipartition",
"(",
"seq",
",",
"nontrivial",
"=",
"False",
")",
":",
"bipartitions",
"=",
"[",
"(",
"tuple",
"(",
"seq",
"[",
"i",
"]",
"for",
"i",
"in",
"part0_idx",
")",
",",
"tuple",
"(",
"seq",
"[",
"j",
"]",
"for",
"j",
"in",
"part1_idx",
")",
")",
"for",
"part0_idx",
",",
"part1_idx",
"in",
"directed_bipartition_indices",
"(",
"len",
"(",
"seq",
")",
")",
"]",
"if",
"nontrivial",
":",
"# The first and last partitions have a part that is empty; skip them.",
"# NOTE: This depends on the implementation of",
"# `directed_partition_indices`.",
"return",
"bipartitions",
"[",
"1",
":",
"-",
"1",
"]",
"return",
"bipartitions"
] |
Return a list of directed bipartitions for a sequence.
Args:
seq (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
parts.
Example:
>>> directed_bipartition((1, 2, 3)) # doctest: +NORMALIZE_WHITESPACE
[((), (1, 2, 3)),
((1,), (2, 3)),
((2,), (1, 3)),
((1, 2), (3,)),
((3,), (1, 2)),
((1, 3), (2,)),
((2, 3), (1,)),
((1, 2, 3), ())]
|
[
"Return",
"a",
"list",
"of",
"directed",
"bipartitions",
"for",
"a",
"sequence",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L123-L153
|
16,071
|
wmayner/pyphi
|
pyphi/partition.py
|
bipartition_of_one
|
def bipartition_of_one(seq):
"""Generate bipartitions where one part is of length 1."""
seq = list(seq)
for i, elt in enumerate(seq):
yield ((elt,), tuple(seq[:i] + seq[(i + 1):]))
|
python
|
def bipartition_of_one(seq):
"""Generate bipartitions where one part is of length 1."""
seq = list(seq)
for i, elt in enumerate(seq):
yield ((elt,), tuple(seq[:i] + seq[(i + 1):]))
|
[
"def",
"bipartition_of_one",
"(",
"seq",
")",
":",
"seq",
"=",
"list",
"(",
"seq",
")",
"for",
"i",
",",
"elt",
"in",
"enumerate",
"(",
"seq",
")",
":",
"yield",
"(",
"(",
"elt",
",",
")",
",",
"tuple",
"(",
"seq",
"[",
":",
"i",
"]",
"+",
"seq",
"[",
"(",
"i",
"+",
"1",
")",
":",
"]",
")",
")"
] |
Generate bipartitions where one part is of length 1.
|
[
"Generate",
"bipartitions",
"where",
"one",
"part",
"is",
"of",
"length",
"1",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L156-L160
|
16,072
|
wmayner/pyphi
|
pyphi/partition.py
|
directed_bipartition_of_one
|
def directed_bipartition_of_one(seq):
"""Generate directed bipartitions where one part is of length 1.
Args:
seq (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> partitions = directed_bipartition_of_one((1, 2, 3))
>>> list(partitions) # doctest: +NORMALIZE_WHITESPACE
[((1,), (2, 3)),
((2,), (1, 3)),
((3,), (1, 2)),
((2, 3), (1,)),
((1, 3), (2,)),
((1, 2), (3,))]
"""
bipartitions = list(bipartition_of_one(seq))
return chain(bipartitions, reverse_elements(bipartitions))
|
python
|
def directed_bipartition_of_one(seq):
"""Generate directed bipartitions where one part is of length 1.
Args:
seq (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> partitions = directed_bipartition_of_one((1, 2, 3))
>>> list(partitions) # doctest: +NORMALIZE_WHITESPACE
[((1,), (2, 3)),
((2,), (1, 3)),
((3,), (1, 2)),
((2, 3), (1,)),
((1, 3), (2,)),
((1, 2), (3,))]
"""
bipartitions = list(bipartition_of_one(seq))
return chain(bipartitions, reverse_elements(bipartitions))
|
[
"def",
"directed_bipartition_of_one",
"(",
"seq",
")",
":",
"bipartitions",
"=",
"list",
"(",
"bipartition_of_one",
"(",
"seq",
")",
")",
"return",
"chain",
"(",
"bipartitions",
",",
"reverse_elements",
"(",
"bipartitions",
")",
")"
] |
Generate directed bipartitions where one part is of length 1.
Args:
seq (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> partitions = directed_bipartition_of_one((1, 2, 3))
>>> list(partitions) # doctest: +NORMALIZE_WHITESPACE
[((1,), (2, 3)),
((2,), (1, 3)),
((3,), (1, 2)),
((2, 3), (1,)),
((1, 3), (2,)),
((1, 2), (3,))]
|
[
"Generate",
"directed",
"bipartitions",
"where",
"one",
"part",
"is",
"of",
"length",
"1",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L169-L190
|
16,073
|
wmayner/pyphi
|
pyphi/partition.py
|
directed_tripartition_indices
|
def directed_tripartition_indices(N):
"""Return indices for directed tripartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list[tuple]: A list of tuples containing the indices for each
partition.
Example:
>>> N = 1
>>> directed_tripartition_indices(N)
[((0,), (), ()), ((), (0,), ()), ((), (), (0,))]
"""
result = []
if N <= 0:
return result
base = [0, 1, 2]
for key in product(base, repeat=N):
part = [[], [], []]
for i, location in enumerate(key):
part[location].append(i)
result.append(tuple(tuple(p) for p in part))
return result
|
python
|
def directed_tripartition_indices(N):
"""Return indices for directed tripartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list[tuple]: A list of tuples containing the indices for each
partition.
Example:
>>> N = 1
>>> directed_tripartition_indices(N)
[((0,), (), ()), ((), (0,), ()), ((), (), (0,))]
"""
result = []
if N <= 0:
return result
base = [0, 1, 2]
for key in product(base, repeat=N):
part = [[], [], []]
for i, location in enumerate(key):
part[location].append(i)
result.append(tuple(tuple(p) for p in part))
return result
|
[
"def",
"directed_tripartition_indices",
"(",
"N",
")",
":",
"result",
"=",
"[",
"]",
"if",
"N",
"<=",
"0",
":",
"return",
"result",
"base",
"=",
"[",
"0",
",",
"1",
",",
"2",
"]",
"for",
"key",
"in",
"product",
"(",
"base",
",",
"repeat",
"=",
"N",
")",
":",
"part",
"=",
"[",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"i",
",",
"location",
"in",
"enumerate",
"(",
"key",
")",
":",
"part",
"[",
"location",
"]",
".",
"append",
"(",
"i",
")",
"result",
".",
"append",
"(",
"tuple",
"(",
"tuple",
"(",
"p",
")",
"for",
"p",
"in",
"part",
")",
")",
"return",
"result"
] |
Return indices for directed tripartitions of a sequence.
Args:
N (int): The length of the sequence.
Returns:
list[tuple]: A list of tuples containing the indices for each
partition.
Example:
>>> N = 1
>>> directed_tripartition_indices(N)
[((0,), (), ()), ((), (0,), ()), ((), (), (0,))]
|
[
"Return",
"indices",
"for",
"directed",
"tripartitions",
"of",
"a",
"sequence",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L194-L221
|
16,074
|
wmayner/pyphi
|
pyphi/partition.py
|
directed_tripartition
|
def directed_tripartition(seq):
"""Generator over all directed tripartitions of a sequence.
Args:
seq (Iterable): a sequence.
Yields:
tuple[tuple]: A tripartition of ``seq``.
Example:
>>> seq = (2, 5)
>>> list(directed_tripartition(seq)) # doctest: +NORMALIZE_WHITESPACE
[((2, 5), (), ()),
((2,), (5,), ()),
((2,), (), (5,)),
((5,), (2,), ()),
((), (2, 5), ()),
((), (2,), (5,)),
((5,), (), (2,)),
((), (5,), (2,)),
((), (), (2, 5))]
"""
for a, b, c in directed_tripartition_indices(len(seq)):
yield (tuple(seq[i] for i in a),
tuple(seq[j] for j in b),
tuple(seq[k] for k in c))
|
python
|
def directed_tripartition(seq):
"""Generator over all directed tripartitions of a sequence.
Args:
seq (Iterable): a sequence.
Yields:
tuple[tuple]: A tripartition of ``seq``.
Example:
>>> seq = (2, 5)
>>> list(directed_tripartition(seq)) # doctest: +NORMALIZE_WHITESPACE
[((2, 5), (), ()),
((2,), (5,), ()),
((2,), (), (5,)),
((5,), (2,), ()),
((), (2, 5), ()),
((), (2,), (5,)),
((5,), (), (2,)),
((), (5,), (2,)),
((), (), (2, 5))]
"""
for a, b, c in directed_tripartition_indices(len(seq)):
yield (tuple(seq[i] for i in a),
tuple(seq[j] for j in b),
tuple(seq[k] for k in c))
|
[
"def",
"directed_tripartition",
"(",
"seq",
")",
":",
"for",
"a",
",",
"b",
",",
"c",
"in",
"directed_tripartition_indices",
"(",
"len",
"(",
"seq",
")",
")",
":",
"yield",
"(",
"tuple",
"(",
"seq",
"[",
"i",
"]",
"for",
"i",
"in",
"a",
")",
",",
"tuple",
"(",
"seq",
"[",
"j",
"]",
"for",
"j",
"in",
"b",
")",
",",
"tuple",
"(",
"seq",
"[",
"k",
"]",
"for",
"k",
"in",
"c",
")",
")"
] |
Generator over all directed tripartitions of a sequence.
Args:
seq (Iterable): a sequence.
Yields:
tuple[tuple]: A tripartition of ``seq``.
Example:
>>> seq = (2, 5)
>>> list(directed_tripartition(seq)) # doctest: +NORMALIZE_WHITESPACE
[((2, 5), (), ()),
((2,), (5,), ()),
((2,), (), (5,)),
((5,), (2,), ()),
((), (2, 5), ()),
((), (2,), (5,)),
((5,), (), (2,)),
((), (5,), (2,)),
((), (), (2, 5))]
|
[
"Generator",
"over",
"all",
"directed",
"tripartitions",
"of",
"a",
"sequence",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L224-L249
|
16,075
|
wmayner/pyphi
|
pyphi/partition.py
|
k_partitions
|
def k_partitions(collection, k):
"""Generate all ``k``-partitions of a collection.
Example:
>>> list(k_partitions(range(3), 2))
[[[0, 1], [2]], [[0], [1, 2]], [[0, 2], [1]]]
"""
collection = list(collection)
n = len(collection)
# Special cases
if n == 0 or k < 1:
return []
if k == 1:
return [[collection]]
a = [0] * (n + 1)
for j in range(1, k + 1):
a[n - k + j] = j - 1
return _f(k, n, 0, n, a, k, collection)
|
python
|
def k_partitions(collection, k):
"""Generate all ``k``-partitions of a collection.
Example:
>>> list(k_partitions(range(3), 2))
[[[0, 1], [2]], [[0], [1, 2]], [[0, 2], [1]]]
"""
collection = list(collection)
n = len(collection)
# Special cases
if n == 0 or k < 1:
return []
if k == 1:
return [[collection]]
a = [0] * (n + 1)
for j in range(1, k + 1):
a[n - k + j] = j - 1
return _f(k, n, 0, n, a, k, collection)
|
[
"def",
"k_partitions",
"(",
"collection",
",",
"k",
")",
":",
"collection",
"=",
"list",
"(",
"collection",
")",
"n",
"=",
"len",
"(",
"collection",
")",
"# Special cases",
"if",
"n",
"==",
"0",
"or",
"k",
"<",
"1",
":",
"return",
"[",
"]",
"if",
"k",
"==",
"1",
":",
"return",
"[",
"[",
"collection",
"]",
"]",
"a",
"=",
"[",
"0",
"]",
"*",
"(",
"n",
"+",
"1",
")",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"k",
"+",
"1",
")",
":",
"a",
"[",
"n",
"-",
"k",
"+",
"j",
"]",
"=",
"j",
"-",
"1",
"return",
"_f",
"(",
"k",
",",
"n",
",",
"0",
",",
"n",
",",
"a",
",",
"k",
",",
"collection",
")"
] |
Generate all ``k``-partitions of a collection.
Example:
>>> list(k_partitions(range(3), 2))
[[[0, 1], [2]], [[0], [1, 2]], [[0, 2], [1]]]
|
[
"Generate",
"all",
"k",
"-",
"partitions",
"of",
"a",
"collection",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L335-L354
|
16,076
|
wmayner/pyphi
|
pyphi/partition.py
|
mip_partitions
|
def mip_partitions(mechanism, purview, node_labels=None):
"""Return a generator over all mechanism-purview partitions, based on the
current configuration.
"""
func = partition_types[config.PARTITION_TYPE]
return func(mechanism, purview, node_labels)
|
python
|
def mip_partitions(mechanism, purview, node_labels=None):
"""Return a generator over all mechanism-purview partitions, based on the
current configuration.
"""
func = partition_types[config.PARTITION_TYPE]
return func(mechanism, purview, node_labels)
|
[
"def",
"mip_partitions",
"(",
"mechanism",
",",
"purview",
",",
"node_labels",
"=",
"None",
")",
":",
"func",
"=",
"partition_types",
"[",
"config",
".",
"PARTITION_TYPE",
"]",
"return",
"func",
"(",
"mechanism",
",",
"purview",
",",
"node_labels",
")"
] |
Return a generator over all mechanism-purview partitions, based on the
current configuration.
|
[
"Return",
"a",
"generator",
"over",
"all",
"mechanism",
"-",
"purview",
"partitions",
"based",
"on",
"the",
"current",
"configuration",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L378-L383
|
16,077
|
wmayner/pyphi
|
pyphi/partition.py
|
mip_bipartitions
|
def mip_bipartitions(mechanism, purview, node_labels=None):
r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
A ∅
─── ✕ ───
∅ B
is.
Args:
mechanism (tuple[int]): The mechanism to partition
purview (tuple[int]): The purview to partition
Yields:
Bipartition: Where each bipartition is::
bipart[0].mechanism bipart[1].mechanism
─────────────────── ✕ ───────────────────
bipart[0].purview bipart[1].purview
Example:
>>> mechanism = (0,)
>>> purview = (2, 3)
>>> for partition in mip_bipartitions(mechanism, purview):
... print(partition, '\n') # doctest: +NORMALIZE_WHITESPACE
∅ 0
─── ✕ ───
2 3
<BLANKLINE>
∅ 0
─── ✕ ───
3 2
<BLANKLINE>
∅ 0
─── ✕ ───
2,3 ∅
"""
numerators = bipartition(mechanism)
denominators = directed_bipartition(purview)
for n, d in product(numerators, denominators):
if (n[0] or d[0]) and (n[1] or d[1]):
yield Bipartition(Part(n[0], d[0]), Part(n[1], d[1]),
node_labels=node_labels)
|
python
|
def mip_bipartitions(mechanism, purview, node_labels=None):
r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
A ∅
─── ✕ ───
∅ B
is.
Args:
mechanism (tuple[int]): The mechanism to partition
purview (tuple[int]): The purview to partition
Yields:
Bipartition: Where each bipartition is::
bipart[0].mechanism bipart[1].mechanism
─────────────────── ✕ ───────────────────
bipart[0].purview bipart[1].purview
Example:
>>> mechanism = (0,)
>>> purview = (2, 3)
>>> for partition in mip_bipartitions(mechanism, purview):
... print(partition, '\n') # doctest: +NORMALIZE_WHITESPACE
∅ 0
─── ✕ ───
2 3
<BLANKLINE>
∅ 0
─── ✕ ───
3 2
<BLANKLINE>
∅ 0
─── ✕ ───
2,3 ∅
"""
numerators = bipartition(mechanism)
denominators = directed_bipartition(purview)
for n, d in product(numerators, denominators):
if (n[0] or d[0]) and (n[1] or d[1]):
yield Bipartition(Part(n[0], d[0]), Part(n[1], d[1]),
node_labels=node_labels)
|
[
"def",
"mip_bipartitions",
"(",
"mechanism",
",",
"purview",
",",
"node_labels",
"=",
"None",
")",
":",
"numerators",
"=",
"bipartition",
"(",
"mechanism",
")",
"denominators",
"=",
"directed_bipartition",
"(",
"purview",
")",
"for",
"n",
",",
"d",
"in",
"product",
"(",
"numerators",
",",
"denominators",
")",
":",
"if",
"(",
"n",
"[",
"0",
"]",
"or",
"d",
"[",
"0",
"]",
")",
"and",
"(",
"n",
"[",
"1",
"]",
"or",
"d",
"[",
"1",
"]",
")",
":",
"yield",
"Bipartition",
"(",
"Part",
"(",
"n",
"[",
"0",
"]",
",",
"d",
"[",
"0",
"]",
")",
",",
"Part",
"(",
"n",
"[",
"1",
"]",
",",
"d",
"[",
"1",
"]",
")",
",",
"node_labels",
"=",
"node_labels",
")"
] |
r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
A ∅
─── ✕ ───
∅ B
is.
Args:
mechanism (tuple[int]): The mechanism to partition
purview (tuple[int]): The purview to partition
Yields:
Bipartition: Where each bipartition is::
bipart[0].mechanism bipart[1].mechanism
─────────────────── ✕ ───────────────────
bipart[0].purview bipart[1].purview
Example:
>>> mechanism = (0,)
>>> purview = (2, 3)
>>> for partition in mip_bipartitions(mechanism, purview):
... print(partition, '\n') # doctest: +NORMALIZE_WHITESPACE
∅ 0
─── ✕ ───
2 3
<BLANKLINE>
∅ 0
─── ✕ ───
3 2
<BLANKLINE>
∅ 0
─── ✕ ───
2,3 ∅
|
[
"r",
"Return",
"an",
"generator",
"of",
"all",
"|small_phi|",
"bipartitions",
"of",
"a",
"mechanism",
"over",
"a",
"purview",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L387-L439
|
16,078
|
wmayner/pyphi
|
pyphi/partition.py
|
wedge_partitions
|
def wedge_partitions(mechanism, purview, node_labels=None):
"""Return an iterator over all wedge partitions.
These are partitions which strictly split the mechanism and allow a subset
of the purview to be split into a third partition, e.g.::
A B ∅
─── ✕ ─── ✕ ───
B C D
See |PARTITION_TYPE| in |config| for more information.
Args:
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Yields:
Tripartition: all unique tripartitions of this mechanism and purview.
"""
numerators = bipartition(mechanism)
denominators = directed_tripartition(purview)
yielded = set()
def valid(factoring):
"""Return whether the factoring should be considered."""
# pylint: disable=too-many-boolean-expressions
numerator, denominator = factoring
return (
(numerator[0] or denominator[0]) and
(numerator[1] or denominator[1]) and
((numerator[0] and numerator[1]) or
not denominator[0] or
not denominator[1])
)
for n, d in filter(valid, product(numerators, denominators)):
# Normalize order of parts to remove duplicates.
tripart = Tripartition(
Part(n[0], d[0]),
Part(n[1], d[1]),
Part((), d[2]),
node_labels=node_labels
).normalize() # pylint: disable=bad-whitespace
def nonempty(part):
"""Check that the part is not empty."""
return part.mechanism or part.purview
def compressible(tripart):
"""Check if the tripartition can be transformed into a causally
equivalent partition by combing two of its parts; e.g., A/∅ × B/∅ ×
∅/CD is equivalent to AB/∅ × ∅/CD so we don't include it.
"""
pairs = [
(tripart[0], tripart[1]),
(tripart[0], tripart[2]),
(tripart[1], tripart[2])
]
for x, y in pairs:
if (nonempty(x) and nonempty(y) and
(x.mechanism + y.mechanism == () or
x.purview + y.purview == ())):
return True
return False
if not compressible(tripart) and tripart not in yielded:
yielded.add(tripart)
yield tripart
|
python
|
def wedge_partitions(mechanism, purview, node_labels=None):
"""Return an iterator over all wedge partitions.
These are partitions which strictly split the mechanism and allow a subset
of the purview to be split into a third partition, e.g.::
A B ∅
─── ✕ ─── ✕ ───
B C D
See |PARTITION_TYPE| in |config| for more information.
Args:
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Yields:
Tripartition: all unique tripartitions of this mechanism and purview.
"""
numerators = bipartition(mechanism)
denominators = directed_tripartition(purview)
yielded = set()
def valid(factoring):
"""Return whether the factoring should be considered."""
# pylint: disable=too-many-boolean-expressions
numerator, denominator = factoring
return (
(numerator[0] or denominator[0]) and
(numerator[1] or denominator[1]) and
((numerator[0] and numerator[1]) or
not denominator[0] or
not denominator[1])
)
for n, d in filter(valid, product(numerators, denominators)):
# Normalize order of parts to remove duplicates.
tripart = Tripartition(
Part(n[0], d[0]),
Part(n[1], d[1]),
Part((), d[2]),
node_labels=node_labels
).normalize() # pylint: disable=bad-whitespace
def nonempty(part):
"""Check that the part is not empty."""
return part.mechanism or part.purview
def compressible(tripart):
"""Check if the tripartition can be transformed into a causally
equivalent partition by combing two of its parts; e.g., A/∅ × B/∅ ×
∅/CD is equivalent to AB/∅ × ∅/CD so we don't include it.
"""
pairs = [
(tripart[0], tripart[1]),
(tripart[0], tripart[2]),
(tripart[1], tripart[2])
]
for x, y in pairs:
if (nonempty(x) and nonempty(y) and
(x.mechanism + y.mechanism == () or
x.purview + y.purview == ())):
return True
return False
if not compressible(tripart) and tripart not in yielded:
yielded.add(tripart)
yield tripart
|
[
"def",
"wedge_partitions",
"(",
"mechanism",
",",
"purview",
",",
"node_labels",
"=",
"None",
")",
":",
"numerators",
"=",
"bipartition",
"(",
"mechanism",
")",
"denominators",
"=",
"directed_tripartition",
"(",
"purview",
")",
"yielded",
"=",
"set",
"(",
")",
"def",
"valid",
"(",
"factoring",
")",
":",
"\"\"\"Return whether the factoring should be considered.\"\"\"",
"# pylint: disable=too-many-boolean-expressions",
"numerator",
",",
"denominator",
"=",
"factoring",
"return",
"(",
"(",
"numerator",
"[",
"0",
"]",
"or",
"denominator",
"[",
"0",
"]",
")",
"and",
"(",
"numerator",
"[",
"1",
"]",
"or",
"denominator",
"[",
"1",
"]",
")",
"and",
"(",
"(",
"numerator",
"[",
"0",
"]",
"and",
"numerator",
"[",
"1",
"]",
")",
"or",
"not",
"denominator",
"[",
"0",
"]",
"or",
"not",
"denominator",
"[",
"1",
"]",
")",
")",
"for",
"n",
",",
"d",
"in",
"filter",
"(",
"valid",
",",
"product",
"(",
"numerators",
",",
"denominators",
")",
")",
":",
"# Normalize order of parts to remove duplicates.",
"tripart",
"=",
"Tripartition",
"(",
"Part",
"(",
"n",
"[",
"0",
"]",
",",
"d",
"[",
"0",
"]",
")",
",",
"Part",
"(",
"n",
"[",
"1",
"]",
",",
"d",
"[",
"1",
"]",
")",
",",
"Part",
"(",
"(",
")",
",",
"d",
"[",
"2",
"]",
")",
",",
"node_labels",
"=",
"node_labels",
")",
".",
"normalize",
"(",
")",
"# pylint: disable=bad-whitespace",
"def",
"nonempty",
"(",
"part",
")",
":",
"\"\"\"Check that the part is not empty.\"\"\"",
"return",
"part",
".",
"mechanism",
"or",
"part",
".",
"purview",
"def",
"compressible",
"(",
"tripart",
")",
":",
"\"\"\"Check if the tripartition can be transformed into a causally\n equivalent partition by combing two of its parts; e.g., A/∅ × B/∅ ×\n ∅/CD is equivalent to AB/∅ × ∅/CD so we don't include it.\n \"\"\"",
"pairs",
"=",
"[",
"(",
"tripart",
"[",
"0",
"]",
",",
"tripart",
"[",
"1",
"]",
")",
",",
"(",
"tripart",
"[",
"0",
"]",
",",
"tripart",
"[",
"2",
"]",
")",
",",
"(",
"tripart",
"[",
"1",
"]",
",",
"tripart",
"[",
"2",
"]",
")",
"]",
"for",
"x",
",",
"y",
"in",
"pairs",
":",
"if",
"(",
"nonempty",
"(",
"x",
")",
"and",
"nonempty",
"(",
"y",
")",
"and",
"(",
"x",
".",
"mechanism",
"+",
"y",
".",
"mechanism",
"==",
"(",
")",
"or",
"x",
".",
"purview",
"+",
"y",
".",
"purview",
"==",
"(",
")",
")",
")",
":",
"return",
"True",
"return",
"False",
"if",
"not",
"compressible",
"(",
"tripart",
")",
"and",
"tripart",
"not",
"in",
"yielded",
":",
"yielded",
".",
"add",
"(",
"tripart",
")",
"yield",
"tripart"
] |
Return an iterator over all wedge partitions.
These are partitions which strictly split the mechanism and allow a subset
of the purview to be split into a third partition, e.g.::
A B ∅
─── ✕ ─── ✕ ───
B C D
See |PARTITION_TYPE| in |config| for more information.
Args:
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Yields:
Tripartition: all unique tripartitions of this mechanism and purview.
|
[
"Return",
"an",
"iterator",
"over",
"all",
"wedge",
"partitions",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L443-L511
|
16,079
|
wmayner/pyphi
|
pyphi/partition.py
|
all_partitions
|
def all_partitions(mechanism, purview, node_labels=None):
"""Return all possible partitions of a mechanism and purview.
Partitions can consist of any number of parts.
Args:
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Yields:
KPartition: A partition of this mechanism and purview into ``k`` parts.
"""
for mechanism_partition in partitions(mechanism):
mechanism_partition.append([])
n_mechanism_parts = len(mechanism_partition)
max_purview_partition = min(len(purview), n_mechanism_parts)
for n_purview_parts in range(1, max_purview_partition + 1):
n_empty = n_mechanism_parts - n_purview_parts
for purview_partition in k_partitions(purview, n_purview_parts):
purview_partition = [tuple(_list)
for _list in purview_partition]
# Extend with empty tuples so purview partition has same size
# as mechanism purview
purview_partition.extend([()] * n_empty)
# Unique permutations to avoid duplicates empties
for purview_permutation in set(
permutations(purview_partition)):
parts = [
Part(tuple(m), tuple(p))
for m, p in zip(mechanism_partition,
purview_permutation)
]
# Must partition the mechanism, unless the purview is fully
# cut away from the mechanism.
if parts[0].mechanism == mechanism and parts[0].purview:
continue
yield KPartition(*parts, node_labels=node_labels)
|
python
|
def all_partitions(mechanism, purview, node_labels=None):
"""Return all possible partitions of a mechanism and purview.
Partitions can consist of any number of parts.
Args:
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Yields:
KPartition: A partition of this mechanism and purview into ``k`` parts.
"""
for mechanism_partition in partitions(mechanism):
mechanism_partition.append([])
n_mechanism_parts = len(mechanism_partition)
max_purview_partition = min(len(purview), n_mechanism_parts)
for n_purview_parts in range(1, max_purview_partition + 1):
n_empty = n_mechanism_parts - n_purview_parts
for purview_partition in k_partitions(purview, n_purview_parts):
purview_partition = [tuple(_list)
for _list in purview_partition]
# Extend with empty tuples so purview partition has same size
# as mechanism purview
purview_partition.extend([()] * n_empty)
# Unique permutations to avoid duplicates empties
for purview_permutation in set(
permutations(purview_partition)):
parts = [
Part(tuple(m), tuple(p))
for m, p in zip(mechanism_partition,
purview_permutation)
]
# Must partition the mechanism, unless the purview is fully
# cut away from the mechanism.
if parts[0].mechanism == mechanism and parts[0].purview:
continue
yield KPartition(*parts, node_labels=node_labels)
|
[
"def",
"all_partitions",
"(",
"mechanism",
",",
"purview",
",",
"node_labels",
"=",
"None",
")",
":",
"for",
"mechanism_partition",
"in",
"partitions",
"(",
"mechanism",
")",
":",
"mechanism_partition",
".",
"append",
"(",
"[",
"]",
")",
"n_mechanism_parts",
"=",
"len",
"(",
"mechanism_partition",
")",
"max_purview_partition",
"=",
"min",
"(",
"len",
"(",
"purview",
")",
",",
"n_mechanism_parts",
")",
"for",
"n_purview_parts",
"in",
"range",
"(",
"1",
",",
"max_purview_partition",
"+",
"1",
")",
":",
"n_empty",
"=",
"n_mechanism_parts",
"-",
"n_purview_parts",
"for",
"purview_partition",
"in",
"k_partitions",
"(",
"purview",
",",
"n_purview_parts",
")",
":",
"purview_partition",
"=",
"[",
"tuple",
"(",
"_list",
")",
"for",
"_list",
"in",
"purview_partition",
"]",
"# Extend with empty tuples so purview partition has same size",
"# as mechanism purview",
"purview_partition",
".",
"extend",
"(",
"[",
"(",
")",
"]",
"*",
"n_empty",
")",
"# Unique permutations to avoid duplicates empties",
"for",
"purview_permutation",
"in",
"set",
"(",
"permutations",
"(",
"purview_partition",
")",
")",
":",
"parts",
"=",
"[",
"Part",
"(",
"tuple",
"(",
"m",
")",
",",
"tuple",
"(",
"p",
")",
")",
"for",
"m",
",",
"p",
"in",
"zip",
"(",
"mechanism_partition",
",",
"purview_permutation",
")",
"]",
"# Must partition the mechanism, unless the purview is fully",
"# cut away from the mechanism.",
"if",
"parts",
"[",
"0",
"]",
".",
"mechanism",
"==",
"mechanism",
"and",
"parts",
"[",
"0",
"]",
".",
"purview",
":",
"continue",
"yield",
"KPartition",
"(",
"*",
"parts",
",",
"node_labels",
"=",
"node_labels",
")"
] |
Return all possible partitions of a mechanism and purview.
Partitions can consist of any number of parts.
Args:
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
Yields:
KPartition: A partition of this mechanism and purview into ``k`` parts.
|
[
"Return",
"all",
"possible",
"partitions",
"of",
"a",
"mechanism",
"and",
"purview",
"."
] |
deeca69a084d782a6fde7bf26f59e93b593c5d77
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/partition.py#L515-L555
|
16,080
|
openstack/pyghmi
|
pyghmi/ipmi/oem/lenovo/imm.py
|
naturalize_string
|
def naturalize_string(key):
"""Analyzes string in a human way to enable natural sort
:param nodename: The node name to analyze
:returns: A structure that can be consumed by 'sorted'
"""
return [int(text) if text.isdigit() else text.lower()
for text in re.split(numregex, key)]
|
python
|
def naturalize_string(key):
"""Analyzes string in a human way to enable natural sort
:param nodename: The node name to analyze
:returns: A structure that can be consumed by 'sorted'
"""
return [int(text) if text.isdigit() else text.lower()
for text in re.split(numregex, key)]
|
[
"def",
"naturalize_string",
"(",
"key",
")",
":",
"return",
"[",
"int",
"(",
"text",
")",
"if",
"text",
".",
"isdigit",
"(",
")",
"else",
"text",
".",
"lower",
"(",
")",
"for",
"text",
"in",
"re",
".",
"split",
"(",
"numregex",
",",
"key",
")",
"]"
] |
Analyzes string in a human way to enable natural sort
:param nodename: The node name to analyze
:returns: A structure that can be consumed by 'sorted'
|
[
"Analyzes",
"string",
"in",
"a",
"human",
"way",
"to",
"enable",
"natural",
"sort"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/oem/lenovo/imm.py#L52-L59
|
16,081
|
openstack/pyghmi
|
pyghmi/ipmi/events.py
|
EventHandler.fetch_sel
|
def fetch_sel(self, ipmicmd, clear=False):
"""Fetch SEL entries
Return an iterable of SEL entries. If clearing is requested,
the fetch and clear will be done as an atomic operation, assuring
no entries are dropped.
:param ipmicmd: The Command object to use to interrogate
:param clear: Whether to clear the entries upon retrieval.
"""
records = []
# First we do a fetch all without reservation, reducing the risk
# of having a long lived reservation that gets canceled in the middle
endat = self._fetch_entries(ipmicmd, 0, records)
if clear and records: # don't bother clearing if there were no records
# To do clear, we make a reservation first...
rsp = ipmicmd.xraw_command(netfn=0xa, command=0x42)
rsvid = struct.unpack_from('<H', rsp['data'])[0]
# Then we refetch the tail with reservation (check for change)
del records[-1] # remove the record that's about to be duplicated
self._fetch_entries(ipmicmd, endat, records, rsvid)
# finally clear the SEL
# 0XAA means start initiate, 0x524c43 is 'RCL' or 'CLR' backwards
clrdata = bytearray(struct.pack('<HI', rsvid, 0xAA524C43))
ipmicmd.xraw_command(netfn=0xa, command=0x47, data=clrdata)
# Now to fixup the record timestamps... first we need to get the BMC
# opinion of current time
_fix_sel_time(records, ipmicmd)
return records
|
python
|
def fetch_sel(self, ipmicmd, clear=False):
"""Fetch SEL entries
Return an iterable of SEL entries. If clearing is requested,
the fetch and clear will be done as an atomic operation, assuring
no entries are dropped.
:param ipmicmd: The Command object to use to interrogate
:param clear: Whether to clear the entries upon retrieval.
"""
records = []
# First we do a fetch all without reservation, reducing the risk
# of having a long lived reservation that gets canceled in the middle
endat = self._fetch_entries(ipmicmd, 0, records)
if clear and records: # don't bother clearing if there were no records
# To do clear, we make a reservation first...
rsp = ipmicmd.xraw_command(netfn=0xa, command=0x42)
rsvid = struct.unpack_from('<H', rsp['data'])[0]
# Then we refetch the tail with reservation (check for change)
del records[-1] # remove the record that's about to be duplicated
self._fetch_entries(ipmicmd, endat, records, rsvid)
# finally clear the SEL
# 0XAA means start initiate, 0x524c43 is 'RCL' or 'CLR' backwards
clrdata = bytearray(struct.pack('<HI', rsvid, 0xAA524C43))
ipmicmd.xraw_command(netfn=0xa, command=0x47, data=clrdata)
# Now to fixup the record timestamps... first we need to get the BMC
# opinion of current time
_fix_sel_time(records, ipmicmd)
return records
|
[
"def",
"fetch_sel",
"(",
"self",
",",
"ipmicmd",
",",
"clear",
"=",
"False",
")",
":",
"records",
"=",
"[",
"]",
"# First we do a fetch all without reservation, reducing the risk",
"# of having a long lived reservation that gets canceled in the middle",
"endat",
"=",
"self",
".",
"_fetch_entries",
"(",
"ipmicmd",
",",
"0",
",",
"records",
")",
"if",
"clear",
"and",
"records",
":",
"# don't bother clearing if there were no records",
"# To do clear, we make a reservation first...",
"rsp",
"=",
"ipmicmd",
".",
"xraw_command",
"(",
"netfn",
"=",
"0xa",
",",
"command",
"=",
"0x42",
")",
"rsvid",
"=",
"struct",
".",
"unpack_from",
"(",
"'<H'",
",",
"rsp",
"[",
"'data'",
"]",
")",
"[",
"0",
"]",
"# Then we refetch the tail with reservation (check for change)",
"del",
"records",
"[",
"-",
"1",
"]",
"# remove the record that's about to be duplicated",
"self",
".",
"_fetch_entries",
"(",
"ipmicmd",
",",
"endat",
",",
"records",
",",
"rsvid",
")",
"# finally clear the SEL",
"# 0XAA means start initiate, 0x524c43 is 'RCL' or 'CLR' backwards",
"clrdata",
"=",
"bytearray",
"(",
"struct",
".",
"pack",
"(",
"'<HI'",
",",
"rsvid",
",",
"0xAA524C43",
")",
")",
"ipmicmd",
".",
"xraw_command",
"(",
"netfn",
"=",
"0xa",
",",
"command",
"=",
"0x47",
",",
"data",
"=",
"clrdata",
")",
"# Now to fixup the record timestamps... first we need to get the BMC",
"# opinion of current time",
"_fix_sel_time",
"(",
"records",
",",
"ipmicmd",
")",
"return",
"records"
] |
Fetch SEL entries
Return an iterable of SEL entries. If clearing is requested,
the fetch and clear will be done as an atomic operation, assuring
no entries are dropped.
:param ipmicmd: The Command object to use to interrogate
:param clear: Whether to clear the entries upon retrieval.
|
[
"Fetch",
"SEL",
"entries"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/events.py#L553-L581
|
16,082
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.oem_init
|
def oem_init(self):
"""Initialize the command object for OEM capabilities
A number of capabilities are either totally OEM defined or
else augmented somehow by knowledge of the OEM. This
method does an interrogation to identify the OEM.
"""
if self._oemknown:
return
self._oem, self._oemknown = get_oem_handler(self._get_device_id(),
self)
|
python
|
def oem_init(self):
"""Initialize the command object for OEM capabilities
A number of capabilities are either totally OEM defined or
else augmented somehow by knowledge of the OEM. This
method does an interrogation to identify the OEM.
"""
if self._oemknown:
return
self._oem, self._oemknown = get_oem_handler(self._get_device_id(),
self)
|
[
"def",
"oem_init",
"(",
"self",
")",
":",
"if",
"self",
".",
"_oemknown",
":",
"return",
"self",
".",
"_oem",
",",
"self",
".",
"_oemknown",
"=",
"get_oem_handler",
"(",
"self",
".",
"_get_device_id",
"(",
")",
",",
"self",
")"
] |
Initialize the command object for OEM capabilities
A number of capabilities are either totally OEM defined or
else augmented somehow by knowledge of the OEM. This
method does an interrogation to identify the OEM.
|
[
"Initialize",
"the",
"command",
"object",
"for",
"OEM",
"capabilities"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L228-L239
|
16,083
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.reset_bmc
|
def reset_bmc(self):
"""Do a cold reset in BMC
"""
response = self.raw_command(netfn=6, command=2)
if 'error' in response:
raise exc.IpmiException(response['error'])
|
python
|
def reset_bmc(self):
"""Do a cold reset in BMC
"""
response = self.raw_command(netfn=6, command=2)
if 'error' in response:
raise exc.IpmiException(response['error'])
|
[
"def",
"reset_bmc",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"raw_command",
"(",
"netfn",
"=",
"6",
",",
"command",
"=",
"2",
")",
"if",
"'error'",
"in",
"response",
":",
"raise",
"exc",
".",
"IpmiException",
"(",
"response",
"[",
"'error'",
"]",
")"
] |
Do a cold reset in BMC
|
[
"Do",
"a",
"cold",
"reset",
"in",
"BMC"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L364-L369
|
16,084
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.xraw_command
|
def xraw_command(self, netfn, command, bridge_request=(), data=(),
delay_xmit=None, retry=True, timeout=None):
"""Send raw ipmi command to BMC, raising exception on error
This is identical to raw_command, except it raises exceptions
on IPMI errors and returns data as a buffer. This is the recommend
function to use. The response['data'] being a buffer allows
traditional indexed access as well as works nicely with
struct.unpack_from when certain data is coming back.
:param netfn: Net function number
:param command: Command value
:param bridge_request: The target slave address and channel number for
the bridge request.
:param data: Command data as a tuple or list
:param retry: Whether to retry this particular payload or not, defaults
to true.
:param timeout: A custom time to wait for initial reply, useful for
a slow command. This may interfere with retry logic.
:returns: dict -- The response from IPMI device
"""
rsp = self.ipmi_session.raw_command(netfn=netfn, command=command,
bridge_request=bridge_request,
data=data, delay_xmit=delay_xmit,
retry=retry, timeout=timeout)
if 'error' in rsp:
raise exc.IpmiException(rsp['error'], rsp['code'])
rsp['data'] = buffer(rsp['data'])
return rsp
|
python
|
def xraw_command(self, netfn, command, bridge_request=(), data=(),
delay_xmit=None, retry=True, timeout=None):
"""Send raw ipmi command to BMC, raising exception on error
This is identical to raw_command, except it raises exceptions
on IPMI errors and returns data as a buffer. This is the recommend
function to use. The response['data'] being a buffer allows
traditional indexed access as well as works nicely with
struct.unpack_from when certain data is coming back.
:param netfn: Net function number
:param command: Command value
:param bridge_request: The target slave address and channel number for
the bridge request.
:param data: Command data as a tuple or list
:param retry: Whether to retry this particular payload or not, defaults
to true.
:param timeout: A custom time to wait for initial reply, useful for
a slow command. This may interfere with retry logic.
:returns: dict -- The response from IPMI device
"""
rsp = self.ipmi_session.raw_command(netfn=netfn, command=command,
bridge_request=bridge_request,
data=data, delay_xmit=delay_xmit,
retry=retry, timeout=timeout)
if 'error' in rsp:
raise exc.IpmiException(rsp['error'], rsp['code'])
rsp['data'] = buffer(rsp['data'])
return rsp
|
[
"def",
"xraw_command",
"(",
"self",
",",
"netfn",
",",
"command",
",",
"bridge_request",
"=",
"(",
")",
",",
"data",
"=",
"(",
")",
",",
"delay_xmit",
"=",
"None",
",",
"retry",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"rsp",
"=",
"self",
".",
"ipmi_session",
".",
"raw_command",
"(",
"netfn",
"=",
"netfn",
",",
"command",
"=",
"command",
",",
"bridge_request",
"=",
"bridge_request",
",",
"data",
"=",
"data",
",",
"delay_xmit",
"=",
"delay_xmit",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
")",
"if",
"'error'",
"in",
"rsp",
":",
"raise",
"exc",
".",
"IpmiException",
"(",
"rsp",
"[",
"'error'",
"]",
",",
"rsp",
"[",
"'code'",
"]",
")",
"rsp",
"[",
"'data'",
"]",
"=",
"buffer",
"(",
"rsp",
"[",
"'data'",
"]",
")",
"return",
"rsp"
] |
Send raw ipmi command to BMC, raising exception on error
This is identical to raw_command, except it raises exceptions
on IPMI errors and returns data as a buffer. This is the recommend
function to use. The response['data'] being a buffer allows
traditional indexed access as well as works nicely with
struct.unpack_from when certain data is coming back.
:param netfn: Net function number
:param command: Command value
:param bridge_request: The target slave address and channel number for
the bridge request.
:param data: Command data as a tuple or list
:param retry: Whether to retry this particular payload or not, defaults
to true.
:param timeout: A custom time to wait for initial reply, useful for
a slow command. This may interfere with retry logic.
:returns: dict -- The response from IPMI device
|
[
"Send",
"raw",
"ipmi",
"command",
"to",
"BMC",
"raising",
"exception",
"on",
"error"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L418-L446
|
16,085
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.raw_command
|
def raw_command(self, netfn, command, bridge_request=(), data=(),
delay_xmit=None, retry=True, timeout=None):
"""Send raw ipmi command to BMC
This allows arbitrary IPMI bytes to be issued. This is commonly used
for certain vendor specific commands.
Example: ipmicmd.raw_command(netfn=0,command=4,data=(5))
:param netfn: Net function number
:param command: Command value
:param bridge_request: The target slave address and channel number for
the bridge request.
:param data: Command data as a tuple or list
:param retry: Whether or not to retry command if no response received.
Defaults to True
:param timeout: A custom amount of time to wait for initial reply
:returns: dict -- The response from IPMI device
"""
rsp = self.ipmi_session.raw_command(netfn=netfn, command=command,
bridge_request=bridge_request,
data=data, delay_xmit=delay_xmit,
retry=retry, timeout=timeout)
if 'data' in rsp:
rsp['data'] = list(rsp['data'])
return rsp
|
python
|
def raw_command(self, netfn, command, bridge_request=(), data=(),
delay_xmit=None, retry=True, timeout=None):
"""Send raw ipmi command to BMC
This allows arbitrary IPMI bytes to be issued. This is commonly used
for certain vendor specific commands.
Example: ipmicmd.raw_command(netfn=0,command=4,data=(5))
:param netfn: Net function number
:param command: Command value
:param bridge_request: The target slave address and channel number for
the bridge request.
:param data: Command data as a tuple or list
:param retry: Whether or not to retry command if no response received.
Defaults to True
:param timeout: A custom amount of time to wait for initial reply
:returns: dict -- The response from IPMI device
"""
rsp = self.ipmi_session.raw_command(netfn=netfn, command=command,
bridge_request=bridge_request,
data=data, delay_xmit=delay_xmit,
retry=retry, timeout=timeout)
if 'data' in rsp:
rsp['data'] = list(rsp['data'])
return rsp
|
[
"def",
"raw_command",
"(",
"self",
",",
"netfn",
",",
"command",
",",
"bridge_request",
"=",
"(",
")",
",",
"data",
"=",
"(",
")",
",",
"delay_xmit",
"=",
"None",
",",
"retry",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"rsp",
"=",
"self",
".",
"ipmi_session",
".",
"raw_command",
"(",
"netfn",
"=",
"netfn",
",",
"command",
"=",
"command",
",",
"bridge_request",
"=",
"bridge_request",
",",
"data",
"=",
"data",
",",
"delay_xmit",
"=",
"delay_xmit",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
")",
"if",
"'data'",
"in",
"rsp",
":",
"rsp",
"[",
"'data'",
"]",
"=",
"list",
"(",
"rsp",
"[",
"'data'",
"]",
")",
"return",
"rsp"
] |
Send raw ipmi command to BMC
This allows arbitrary IPMI bytes to be issued. This is commonly used
for certain vendor specific commands.
Example: ipmicmd.raw_command(netfn=0,command=4,data=(5))
:param netfn: Net function number
:param command: Command value
:param bridge_request: The target slave address and channel number for
the bridge request.
:param data: Command data as a tuple or list
:param retry: Whether or not to retry command if no response received.
Defaults to True
:param timeout: A custom amount of time to wait for initial reply
:returns: dict -- The response from IPMI device
|
[
"Send",
"raw",
"ipmi",
"command",
"to",
"BMC"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L462-L487
|
16,086
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_power
|
def get_power(self):
"""Get current power state of the managed system
The response, if successful, should contain 'powerstate' key and
either 'on' or 'off' to indicate current state.
:returns: dict -- {'powerstate': value}
"""
response = self.raw_command(netfn=0, command=1)
if 'error' in response:
raise exc.IpmiException(response['error'])
assert (response['command'] == 1 and response['netfn'] == 1)
powerstate = 'on' if (response['data'][0] & 1) else 'off'
return {'powerstate': powerstate}
|
python
|
def get_power(self):
"""Get current power state of the managed system
The response, if successful, should contain 'powerstate' key and
either 'on' or 'off' to indicate current state.
:returns: dict -- {'powerstate': value}
"""
response = self.raw_command(netfn=0, command=1)
if 'error' in response:
raise exc.IpmiException(response['error'])
assert (response['command'] == 1 and response['netfn'] == 1)
powerstate = 'on' if (response['data'][0] & 1) else 'off'
return {'powerstate': powerstate}
|
[
"def",
"get_power",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"raw_command",
"(",
"netfn",
"=",
"0",
",",
"command",
"=",
"1",
")",
"if",
"'error'",
"in",
"response",
":",
"raise",
"exc",
".",
"IpmiException",
"(",
"response",
"[",
"'error'",
"]",
")",
"assert",
"(",
"response",
"[",
"'command'",
"]",
"==",
"1",
"and",
"response",
"[",
"'netfn'",
"]",
"==",
"1",
")",
"powerstate",
"=",
"'on'",
"if",
"(",
"response",
"[",
"'data'",
"]",
"[",
"0",
"]",
"&",
"1",
")",
"else",
"'off'",
"return",
"{",
"'powerstate'",
":",
"powerstate",
"}"
] |
Get current power state of the managed system
The response, if successful, should contain 'powerstate' key and
either 'on' or 'off' to indicate current state.
:returns: dict -- {'powerstate': value}
|
[
"Get",
"current",
"power",
"state",
"of",
"the",
"managed",
"system"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L489-L502
|
16,087
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_event_log
|
def get_event_log(self, clear=False):
"""Retrieve the log of events, optionally clearing
The contents of the SEL are returned as an iterable. Timestamps
are given as local time, ISO 8601 (whether the target has an accurate
clock or not). Timestamps may be omitted for events that cannot be
given a timestamp, leaving only the raw timecode to provide relative
time information. clear set to true will result in the log being
cleared as it is returned. This allows an atomic fetch and clear
behavior so that no log entries will be lost between the fetch and
clear actions. There is no 'clear_event_log' function to encourage
users to create code that is not at risk for losing events.
:param clear: Whether to remove the SEL entries from the target BMC
"""
self.oem_init()
return sel.EventHandler(self.init_sdr(), self).fetch_sel(self, clear)
|
python
|
def get_event_log(self, clear=False):
"""Retrieve the log of events, optionally clearing
The contents of the SEL are returned as an iterable. Timestamps
are given as local time, ISO 8601 (whether the target has an accurate
clock or not). Timestamps may be omitted for events that cannot be
given a timestamp, leaving only the raw timecode to provide relative
time information. clear set to true will result in the log being
cleared as it is returned. This allows an atomic fetch and clear
behavior so that no log entries will be lost between the fetch and
clear actions. There is no 'clear_event_log' function to encourage
users to create code that is not at risk for losing events.
:param clear: Whether to remove the SEL entries from the target BMC
"""
self.oem_init()
return sel.EventHandler(self.init_sdr(), self).fetch_sel(self, clear)
|
[
"def",
"get_event_log",
"(",
"self",
",",
"clear",
"=",
"False",
")",
":",
"self",
".",
"oem_init",
"(",
")",
"return",
"sel",
".",
"EventHandler",
"(",
"self",
".",
"init_sdr",
"(",
")",
",",
"self",
")",
".",
"fetch_sel",
"(",
"self",
",",
"clear",
")"
] |
Retrieve the log of events, optionally clearing
The contents of the SEL are returned as an iterable. Timestamps
are given as local time, ISO 8601 (whether the target has an accurate
clock or not). Timestamps may be omitted for events that cannot be
given a timestamp, leaving only the raw timecode to provide relative
time information. clear set to true will result in the log being
cleared as it is returned. This allows an atomic fetch and clear
behavior so that no log entries will be lost between the fetch and
clear actions. There is no 'clear_event_log' function to encourage
users to create code that is not at risk for losing events.
:param clear: Whether to remove the SEL entries from the target BMC
|
[
"Retrieve",
"the",
"log",
"of",
"events",
"optionally",
"clearing"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L559-L575
|
16,088
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.decode_pet
|
def decode_pet(self, specifictrap, petdata):
"""Decode PET to an event
In IPMI, the alert format are PET alerts. It is a particular set of
data put into an SNMPv1 trap and sent. It bears no small resemblence
to the SEL entries. This function takes data that would have been
received by an SNMP trap handler, and provides an event decode, similar
to one entry of get_event_log.
:param specifictrap: The specific trap, as either a bytearray or int
:param petdata: An iterable of the octet data of varbind for
1.3.6.1.4.1.3183.1.1.1
:returns: A dict event similar to one iteration of get_event_log
"""
self.oem_init()
return sel.EventHandler(self.init_sdr(), self).decode_pet(specifictrap,
petdata)
|
python
|
def decode_pet(self, specifictrap, petdata):
"""Decode PET to an event
In IPMI, the alert format are PET alerts. It is a particular set of
data put into an SNMPv1 trap and sent. It bears no small resemblence
to the SEL entries. This function takes data that would have been
received by an SNMP trap handler, and provides an event decode, similar
to one entry of get_event_log.
:param specifictrap: The specific trap, as either a bytearray or int
:param petdata: An iterable of the octet data of varbind for
1.3.6.1.4.1.3183.1.1.1
:returns: A dict event similar to one iteration of get_event_log
"""
self.oem_init()
return sel.EventHandler(self.init_sdr(), self).decode_pet(specifictrap,
petdata)
|
[
"def",
"decode_pet",
"(",
"self",
",",
"specifictrap",
",",
"petdata",
")",
":",
"self",
".",
"oem_init",
"(",
")",
"return",
"sel",
".",
"EventHandler",
"(",
"self",
".",
"init_sdr",
"(",
")",
",",
"self",
")",
".",
"decode_pet",
"(",
"specifictrap",
",",
"petdata",
")"
] |
Decode PET to an event
In IPMI, the alert format are PET alerts. It is a particular set of
data put into an SNMPv1 trap and sent. It bears no small resemblence
to the SEL entries. This function takes data that would have been
received by an SNMP trap handler, and provides an event decode, similar
to one entry of get_event_log.
:param specifictrap: The specific trap, as either a bytearray or int
:param petdata: An iterable of the octet data of varbind for
1.3.6.1.4.1.3183.1.1.1
:returns: A dict event similar to one iteration of get_event_log
|
[
"Decode",
"PET",
"to",
"an",
"event"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L577-L593
|
16,089
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_inventory_descriptions
|
def get_inventory_descriptions(self):
"""Retrieve list of things that could be inventoried
This permits a caller to examine the available items
without actually causing the inventory data to be gathered. It
returns an iterable of string descriptions
"""
yield "System"
self.init_sdr()
for fruid in sorted(self._sdr.fru):
yield self._sdr.fru[fruid].fru_name
self.oem_init()
for compname in self._oem.get_oem_inventory_descriptions():
yield compname
|
python
|
def get_inventory_descriptions(self):
"""Retrieve list of things that could be inventoried
This permits a caller to examine the available items
without actually causing the inventory data to be gathered. It
returns an iterable of string descriptions
"""
yield "System"
self.init_sdr()
for fruid in sorted(self._sdr.fru):
yield self._sdr.fru[fruid].fru_name
self.oem_init()
for compname in self._oem.get_oem_inventory_descriptions():
yield compname
|
[
"def",
"get_inventory_descriptions",
"(",
"self",
")",
":",
"yield",
"\"System\"",
"self",
".",
"init_sdr",
"(",
")",
"for",
"fruid",
"in",
"sorted",
"(",
"self",
".",
"_sdr",
".",
"fru",
")",
":",
"yield",
"self",
".",
"_sdr",
".",
"fru",
"[",
"fruid",
"]",
".",
"fru_name",
"self",
".",
"oem_init",
"(",
")",
"for",
"compname",
"in",
"self",
".",
"_oem",
".",
"get_oem_inventory_descriptions",
"(",
")",
":",
"yield",
"compname"
] |
Retrieve list of things that could be inventoried
This permits a caller to examine the available items
without actually causing the inventory data to be gathered. It
returns an iterable of string descriptions
|
[
"Retrieve",
"list",
"of",
"things",
"that",
"could",
"be",
"inventoried"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L595-L608
|
16,090
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_inventory_of_component
|
def get_inventory_of_component(self, component):
"""Retrieve inventory of a component
Retrieve detailed inventory information for only the requested
component.
"""
self.oem_init()
if component == 'System':
return self._get_zero_fru()
self.init_sdr()
for fruid in self._sdr.fru:
if self._sdr.fru[fruid].fru_name == component:
return self._oem.process_fru(fru.FRU(
ipmicmd=self, fruid=fruid, sdr=self._sdr.fru[fruid]).info,
component)
return self._oem.get_inventory_of_component(component)
|
python
|
def get_inventory_of_component(self, component):
"""Retrieve inventory of a component
Retrieve detailed inventory information for only the requested
component.
"""
self.oem_init()
if component == 'System':
return self._get_zero_fru()
self.init_sdr()
for fruid in self._sdr.fru:
if self._sdr.fru[fruid].fru_name == component:
return self._oem.process_fru(fru.FRU(
ipmicmd=self, fruid=fruid, sdr=self._sdr.fru[fruid]).info,
component)
return self._oem.get_inventory_of_component(component)
|
[
"def",
"get_inventory_of_component",
"(",
"self",
",",
"component",
")",
":",
"self",
".",
"oem_init",
"(",
")",
"if",
"component",
"==",
"'System'",
":",
"return",
"self",
".",
"_get_zero_fru",
"(",
")",
"self",
".",
"init_sdr",
"(",
")",
"for",
"fruid",
"in",
"self",
".",
"_sdr",
".",
"fru",
":",
"if",
"self",
".",
"_sdr",
".",
"fru",
"[",
"fruid",
"]",
".",
"fru_name",
"==",
"component",
":",
"return",
"self",
".",
"_oem",
".",
"process_fru",
"(",
"fru",
".",
"FRU",
"(",
"ipmicmd",
"=",
"self",
",",
"fruid",
"=",
"fruid",
",",
"sdr",
"=",
"self",
".",
"_sdr",
".",
"fru",
"[",
"fruid",
"]",
")",
".",
"info",
",",
"component",
")",
"return",
"self",
".",
"_oem",
".",
"get_inventory_of_component",
"(",
"component",
")"
] |
Retrieve inventory of a component
Retrieve detailed inventory information for only the requested
component.
|
[
"Retrieve",
"inventory",
"of",
"a",
"component"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L610-L625
|
16,091
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_inventory
|
def get_inventory(self):
"""Retrieve inventory of system
Retrieve inventory of the targeted system. This frequently includes
serial numbers, sometimes hardware addresses, sometimes memory modules
This function will retrieve whatever the underlying platform provides
and apply some structure. Iterating over the return yields tuples
of a name for the inventoried item and dictionary of descriptions
or None for items not present.
"""
self.oem_init()
yield ("System", self._get_zero_fru())
self.init_sdr()
for fruid in sorted(self._sdr.fru):
fruinf = fru.FRU(
ipmicmd=self, fruid=fruid, sdr=self._sdr.fru[fruid]).info
if fruinf is not None:
fruinf = self._oem.process_fru(fruinf,
self._sdr.fru[fruid].fru_name)
yield (self._sdr.fru[fruid].fru_name, fruinf)
for componentpair in self._oem.get_oem_inventory():
yield componentpair
|
python
|
def get_inventory(self):
"""Retrieve inventory of system
Retrieve inventory of the targeted system. This frequently includes
serial numbers, sometimes hardware addresses, sometimes memory modules
This function will retrieve whatever the underlying platform provides
and apply some structure. Iterating over the return yields tuples
of a name for the inventoried item and dictionary of descriptions
or None for items not present.
"""
self.oem_init()
yield ("System", self._get_zero_fru())
self.init_sdr()
for fruid in sorted(self._sdr.fru):
fruinf = fru.FRU(
ipmicmd=self, fruid=fruid, sdr=self._sdr.fru[fruid]).info
if fruinf is not None:
fruinf = self._oem.process_fru(fruinf,
self._sdr.fru[fruid].fru_name)
yield (self._sdr.fru[fruid].fru_name, fruinf)
for componentpair in self._oem.get_oem_inventory():
yield componentpair
|
[
"def",
"get_inventory",
"(",
"self",
")",
":",
"self",
".",
"oem_init",
"(",
")",
"yield",
"(",
"\"System\"",
",",
"self",
".",
"_get_zero_fru",
"(",
")",
")",
"self",
".",
"init_sdr",
"(",
")",
"for",
"fruid",
"in",
"sorted",
"(",
"self",
".",
"_sdr",
".",
"fru",
")",
":",
"fruinf",
"=",
"fru",
".",
"FRU",
"(",
"ipmicmd",
"=",
"self",
",",
"fruid",
"=",
"fruid",
",",
"sdr",
"=",
"self",
".",
"_sdr",
".",
"fru",
"[",
"fruid",
"]",
")",
".",
"info",
"if",
"fruinf",
"is",
"not",
"None",
":",
"fruinf",
"=",
"self",
".",
"_oem",
".",
"process_fru",
"(",
"fruinf",
",",
"self",
".",
"_sdr",
".",
"fru",
"[",
"fruid",
"]",
".",
"fru_name",
")",
"yield",
"(",
"self",
".",
"_sdr",
".",
"fru",
"[",
"fruid",
"]",
".",
"fru_name",
",",
"fruinf",
")",
"for",
"componentpair",
"in",
"self",
".",
"_oem",
".",
"get_oem_inventory",
"(",
")",
":",
"yield",
"componentpair"
] |
Retrieve inventory of system
Retrieve inventory of the targeted system. This frequently includes
serial numbers, sometimes hardware addresses, sometimes memory modules
This function will retrieve whatever the underlying platform provides
and apply some structure. Iterating over the return yields tuples
of a name for the inventoried item and dictionary of descriptions
or None for items not present.
|
[
"Retrieve",
"inventory",
"of",
"system"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L651-L672
|
16,092
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_health
|
def get_health(self):
"""Summarize health of managed system
This provides a summary of the health of the managed system.
It additionally provides an iterable list of reasons for
warning, critical, or failed assessments.
"""
summary = {'badreadings': [], 'health': const.Health.Ok}
fallbackreadings = []
try:
self.oem_init()
fallbackreadings = self._oem.get_health(summary)
for reading in self.get_sensor_data():
if reading.health != const.Health.Ok:
summary['health'] |= reading.health
summary['badreadings'].append(reading)
except exc.BypassGenericBehavior:
pass
if not summary['badreadings']:
summary['badreadings'] = fallbackreadings
return summary
|
python
|
def get_health(self):
"""Summarize health of managed system
This provides a summary of the health of the managed system.
It additionally provides an iterable list of reasons for
warning, critical, or failed assessments.
"""
summary = {'badreadings': [], 'health': const.Health.Ok}
fallbackreadings = []
try:
self.oem_init()
fallbackreadings = self._oem.get_health(summary)
for reading in self.get_sensor_data():
if reading.health != const.Health.Ok:
summary['health'] |= reading.health
summary['badreadings'].append(reading)
except exc.BypassGenericBehavior:
pass
if not summary['badreadings']:
summary['badreadings'] = fallbackreadings
return summary
|
[
"def",
"get_health",
"(",
"self",
")",
":",
"summary",
"=",
"{",
"'badreadings'",
":",
"[",
"]",
",",
"'health'",
":",
"const",
".",
"Health",
".",
"Ok",
"}",
"fallbackreadings",
"=",
"[",
"]",
"try",
":",
"self",
".",
"oem_init",
"(",
")",
"fallbackreadings",
"=",
"self",
".",
"_oem",
".",
"get_health",
"(",
"summary",
")",
"for",
"reading",
"in",
"self",
".",
"get_sensor_data",
"(",
")",
":",
"if",
"reading",
".",
"health",
"!=",
"const",
".",
"Health",
".",
"Ok",
":",
"summary",
"[",
"'health'",
"]",
"|=",
"reading",
".",
"health",
"summary",
"[",
"'badreadings'",
"]",
".",
"append",
"(",
"reading",
")",
"except",
"exc",
".",
"BypassGenericBehavior",
":",
"pass",
"if",
"not",
"summary",
"[",
"'badreadings'",
"]",
":",
"summary",
"[",
"'badreadings'",
"]",
"=",
"fallbackreadings",
"return",
"summary"
] |
Summarize health of managed system
This provides a summary of the health of the managed system.
It additionally provides an iterable list of reasons for
warning, critical, or failed assessments.
|
[
"Summarize",
"health",
"of",
"managed",
"system"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L698-L718
|
16,093
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_sensor_reading
|
def get_sensor_reading(self, sensorname):
"""Get a sensor reading by name
Returns a single decoded sensor reading per the name
passed in
:param sensorname: Name of the desired sensor
:returns: sdr.SensorReading object
"""
self.init_sdr()
for sensor in self._sdr.get_sensor_numbers():
if self._sdr.sensors[sensor].name == sensorname:
rsp = self.raw_command(command=0x2d, netfn=4, data=(sensor,))
if 'error' in rsp:
raise exc.IpmiException(rsp['error'], rsp['code'])
return self._sdr.sensors[sensor].decode_sensor_reading(
rsp['data'])
self.oem_init()
return self._oem.get_sensor_reading(sensorname)
|
python
|
def get_sensor_reading(self, sensorname):
"""Get a sensor reading by name
Returns a single decoded sensor reading per the name
passed in
:param sensorname: Name of the desired sensor
:returns: sdr.SensorReading object
"""
self.init_sdr()
for sensor in self._sdr.get_sensor_numbers():
if self._sdr.sensors[sensor].name == sensorname:
rsp = self.raw_command(command=0x2d, netfn=4, data=(sensor,))
if 'error' in rsp:
raise exc.IpmiException(rsp['error'], rsp['code'])
return self._sdr.sensors[sensor].decode_sensor_reading(
rsp['data'])
self.oem_init()
return self._oem.get_sensor_reading(sensorname)
|
[
"def",
"get_sensor_reading",
"(",
"self",
",",
"sensorname",
")",
":",
"self",
".",
"init_sdr",
"(",
")",
"for",
"sensor",
"in",
"self",
".",
"_sdr",
".",
"get_sensor_numbers",
"(",
")",
":",
"if",
"self",
".",
"_sdr",
".",
"sensors",
"[",
"sensor",
"]",
".",
"name",
"==",
"sensorname",
":",
"rsp",
"=",
"self",
".",
"raw_command",
"(",
"command",
"=",
"0x2d",
",",
"netfn",
"=",
"4",
",",
"data",
"=",
"(",
"sensor",
",",
")",
")",
"if",
"'error'",
"in",
"rsp",
":",
"raise",
"exc",
".",
"IpmiException",
"(",
"rsp",
"[",
"'error'",
"]",
",",
"rsp",
"[",
"'code'",
"]",
")",
"return",
"self",
".",
"_sdr",
".",
"sensors",
"[",
"sensor",
"]",
".",
"decode_sensor_reading",
"(",
"rsp",
"[",
"'data'",
"]",
")",
"self",
".",
"oem_init",
"(",
")",
"return",
"self",
".",
"_oem",
".",
"get_sensor_reading",
"(",
"sensorname",
")"
] |
Get a sensor reading by name
Returns a single decoded sensor reading per the name
passed in
:param sensorname: Name of the desired sensor
:returns: sdr.SensorReading object
|
[
"Get",
"a",
"sensor",
"reading",
"by",
"name"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L720-L738
|
16,094
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command._fetch_lancfg_param
|
def _fetch_lancfg_param(self, channel, param, prefixlen=False):
"""Internal helper for fetching lan cfg parameters
If the parameter revison != 0x11, bail. Further, if 4 bytes, return
string with ipv4. If 6 bytes, colon delimited hex (mac address). If
one byte, return the int value
"""
fetchcmd = bytearray((channel, param, 0, 0))
fetched = self.xraw_command(0xc, 2, data=fetchcmd)
fetchdata = fetched['data']
if ord(fetchdata[0]) != 17:
return None
if len(fetchdata) == 5: # IPv4 address
if prefixlen:
return _mask_to_cidr(fetchdata[1:])
else:
ip = socket.inet_ntoa(fetchdata[1:])
if ip == '0.0.0.0':
return None
return ip
elif len(fetchdata) == 7: # MAC address
mac = '{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}'.format(
*bytearray(fetchdata[1:]))
if mac == '00:00:00:00:00:00':
return None
return mac
elif len(fetchdata) == 2:
return ord(fetchdata[1])
else:
raise Exception("Unrecognized data format " + repr(fetchdata))
|
python
|
def _fetch_lancfg_param(self, channel, param, prefixlen=False):
"""Internal helper for fetching lan cfg parameters
If the parameter revison != 0x11, bail. Further, if 4 bytes, return
string with ipv4. If 6 bytes, colon delimited hex (mac address). If
one byte, return the int value
"""
fetchcmd = bytearray((channel, param, 0, 0))
fetched = self.xraw_command(0xc, 2, data=fetchcmd)
fetchdata = fetched['data']
if ord(fetchdata[0]) != 17:
return None
if len(fetchdata) == 5: # IPv4 address
if prefixlen:
return _mask_to_cidr(fetchdata[1:])
else:
ip = socket.inet_ntoa(fetchdata[1:])
if ip == '0.0.0.0':
return None
return ip
elif len(fetchdata) == 7: # MAC address
mac = '{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}'.format(
*bytearray(fetchdata[1:]))
if mac == '00:00:00:00:00:00':
return None
return mac
elif len(fetchdata) == 2:
return ord(fetchdata[1])
else:
raise Exception("Unrecognized data format " + repr(fetchdata))
|
[
"def",
"_fetch_lancfg_param",
"(",
"self",
",",
"channel",
",",
"param",
",",
"prefixlen",
"=",
"False",
")",
":",
"fetchcmd",
"=",
"bytearray",
"(",
"(",
"channel",
",",
"param",
",",
"0",
",",
"0",
")",
")",
"fetched",
"=",
"self",
".",
"xraw_command",
"(",
"0xc",
",",
"2",
",",
"data",
"=",
"fetchcmd",
")",
"fetchdata",
"=",
"fetched",
"[",
"'data'",
"]",
"if",
"ord",
"(",
"fetchdata",
"[",
"0",
"]",
")",
"!=",
"17",
":",
"return",
"None",
"if",
"len",
"(",
"fetchdata",
")",
"==",
"5",
":",
"# IPv4 address",
"if",
"prefixlen",
":",
"return",
"_mask_to_cidr",
"(",
"fetchdata",
"[",
"1",
":",
"]",
")",
"else",
":",
"ip",
"=",
"socket",
".",
"inet_ntoa",
"(",
"fetchdata",
"[",
"1",
":",
"]",
")",
"if",
"ip",
"==",
"'0.0.0.0'",
":",
"return",
"None",
"return",
"ip",
"elif",
"len",
"(",
"fetchdata",
")",
"==",
"7",
":",
"# MAC address",
"mac",
"=",
"'{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}'",
".",
"format",
"(",
"*",
"bytearray",
"(",
"fetchdata",
"[",
"1",
":",
"]",
")",
")",
"if",
"mac",
"==",
"'00:00:00:00:00:00'",
":",
"return",
"None",
"return",
"mac",
"elif",
"len",
"(",
"fetchdata",
")",
"==",
"2",
":",
"return",
"ord",
"(",
"fetchdata",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unrecognized data format \"",
"+",
"repr",
"(",
"fetchdata",
")",
")"
] |
Internal helper for fetching lan cfg parameters
If the parameter revison != 0x11, bail. Further, if 4 bytes, return
string with ipv4. If 6 bytes, colon delimited hex (mac address). If
one byte, return the int value
|
[
"Internal",
"helper",
"for",
"fetching",
"lan",
"cfg",
"parameters"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L740-L769
|
16,095
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.set_net_configuration
|
def set_net_configuration(self, ipv4_address=None, ipv4_configuration=None,
ipv4_gateway=None, channel=None):
"""Set network configuration data.
Apply desired network configuration data, leaving unspecified
parameters alone.
:param ipv4_address: CIDR notation for IP address and netmask
Example: '192.168.0.10/16'
:param ipv4_configuration: Method to use to configure the network.
'DHCP' or 'Static'.
:param ipv4_gateway: IP address of gateway to use.
:param channel: LAN channel to configure, defaults to autodetect
"""
if channel is None:
channel = self.get_network_channel()
if ipv4_configuration is not None:
cmddata = [channel, 4, 0]
if ipv4_configuration.lower() == 'dhcp':
cmddata[-1] = 2
elif ipv4_configuration.lower() == 'static':
cmddata[-1] = 1
else:
raise Exception('Unrecognized ipv4cfg parameter {0}'.format(
ipv4_configuration))
self.xraw_command(netfn=0xc, command=1, data=cmddata)
if ipv4_address is not None:
netmask = None
if '/' in ipv4_address:
ipv4_address, prefix = ipv4_address.split('/')
netmask = _cidr_to_mask(int(prefix))
cmddata = bytearray((channel, 3)) + socket.inet_aton(ipv4_address)
self.xraw_command(netfn=0xc, command=1, data=cmddata)
if netmask is not None:
cmddata = bytearray((channel, 6)) + netmask
self.xraw_command(netfn=0xc, command=1, data=cmddata)
if ipv4_gateway is not None:
cmddata = bytearray((channel, 12)) + socket.inet_aton(ipv4_gateway)
self.xraw_command(netfn=0xc, command=1, data=cmddata)
|
python
|
def set_net_configuration(self, ipv4_address=None, ipv4_configuration=None,
ipv4_gateway=None, channel=None):
"""Set network configuration data.
Apply desired network configuration data, leaving unspecified
parameters alone.
:param ipv4_address: CIDR notation for IP address and netmask
Example: '192.168.0.10/16'
:param ipv4_configuration: Method to use to configure the network.
'DHCP' or 'Static'.
:param ipv4_gateway: IP address of gateway to use.
:param channel: LAN channel to configure, defaults to autodetect
"""
if channel is None:
channel = self.get_network_channel()
if ipv4_configuration is not None:
cmddata = [channel, 4, 0]
if ipv4_configuration.lower() == 'dhcp':
cmddata[-1] = 2
elif ipv4_configuration.lower() == 'static':
cmddata[-1] = 1
else:
raise Exception('Unrecognized ipv4cfg parameter {0}'.format(
ipv4_configuration))
self.xraw_command(netfn=0xc, command=1, data=cmddata)
if ipv4_address is not None:
netmask = None
if '/' in ipv4_address:
ipv4_address, prefix = ipv4_address.split('/')
netmask = _cidr_to_mask(int(prefix))
cmddata = bytearray((channel, 3)) + socket.inet_aton(ipv4_address)
self.xraw_command(netfn=0xc, command=1, data=cmddata)
if netmask is not None:
cmddata = bytearray((channel, 6)) + netmask
self.xraw_command(netfn=0xc, command=1, data=cmddata)
if ipv4_gateway is not None:
cmddata = bytearray((channel, 12)) + socket.inet_aton(ipv4_gateway)
self.xraw_command(netfn=0xc, command=1, data=cmddata)
|
[
"def",
"set_net_configuration",
"(",
"self",
",",
"ipv4_address",
"=",
"None",
",",
"ipv4_configuration",
"=",
"None",
",",
"ipv4_gateway",
"=",
"None",
",",
"channel",
"=",
"None",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"self",
".",
"get_network_channel",
"(",
")",
"if",
"ipv4_configuration",
"is",
"not",
"None",
":",
"cmddata",
"=",
"[",
"channel",
",",
"4",
",",
"0",
"]",
"if",
"ipv4_configuration",
".",
"lower",
"(",
")",
"==",
"'dhcp'",
":",
"cmddata",
"[",
"-",
"1",
"]",
"=",
"2",
"elif",
"ipv4_configuration",
".",
"lower",
"(",
")",
"==",
"'static'",
":",
"cmddata",
"[",
"-",
"1",
"]",
"=",
"1",
"else",
":",
"raise",
"Exception",
"(",
"'Unrecognized ipv4cfg parameter {0}'",
".",
"format",
"(",
"ipv4_configuration",
")",
")",
"self",
".",
"xraw_command",
"(",
"netfn",
"=",
"0xc",
",",
"command",
"=",
"1",
",",
"data",
"=",
"cmddata",
")",
"if",
"ipv4_address",
"is",
"not",
"None",
":",
"netmask",
"=",
"None",
"if",
"'/'",
"in",
"ipv4_address",
":",
"ipv4_address",
",",
"prefix",
"=",
"ipv4_address",
".",
"split",
"(",
"'/'",
")",
"netmask",
"=",
"_cidr_to_mask",
"(",
"int",
"(",
"prefix",
")",
")",
"cmddata",
"=",
"bytearray",
"(",
"(",
"channel",
",",
"3",
")",
")",
"+",
"socket",
".",
"inet_aton",
"(",
"ipv4_address",
")",
"self",
".",
"xraw_command",
"(",
"netfn",
"=",
"0xc",
",",
"command",
"=",
"1",
",",
"data",
"=",
"cmddata",
")",
"if",
"netmask",
"is",
"not",
"None",
":",
"cmddata",
"=",
"bytearray",
"(",
"(",
"channel",
",",
"6",
")",
")",
"+",
"netmask",
"self",
".",
"xraw_command",
"(",
"netfn",
"=",
"0xc",
",",
"command",
"=",
"1",
",",
"data",
"=",
"cmddata",
")",
"if",
"ipv4_gateway",
"is",
"not",
"None",
":",
"cmddata",
"=",
"bytearray",
"(",
"(",
"channel",
",",
"12",
")",
")",
"+",
"socket",
".",
"inet_aton",
"(",
"ipv4_gateway",
")",
"self",
".",
"xraw_command",
"(",
"netfn",
"=",
"0xc",
",",
"command",
"=",
"1",
",",
"data",
"=",
"cmddata",
")"
] |
Set network configuration data.
Apply desired network configuration data, leaving unspecified
parameters alone.
:param ipv4_address: CIDR notation for IP address and netmask
Example: '192.168.0.10/16'
:param ipv4_configuration: Method to use to configure the network.
'DHCP' or 'Static'.
:param ipv4_gateway: IP address of gateway to use.
:param channel: LAN channel to configure, defaults to autodetect
|
[
"Set",
"network",
"configuration",
"data",
"."
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L787-L825
|
16,096
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_net_configuration
|
def get_net_configuration(self, channel=None, gateway_macs=True):
"""Get network configuration data
Retrieve network configuration from the target
:param channel: Channel to configure, defaults to None for 'autodetect'
:param gateway_macs: Whether to retrieve mac addresses for gateways
:returns: A dictionary of network configuration data
"""
if channel is None:
channel = self.get_network_channel()
retdata = {}
v4addr = self._fetch_lancfg_param(channel, 3)
if v4addr is None:
retdata['ipv4_address'] = None
else:
v4masklen = self._fetch_lancfg_param(channel, 6, prefixlen=True)
retdata['ipv4_address'] = '{0}/{1}'.format(v4addr, v4masklen)
v4cfgmethods = {
0: 'Unspecified',
1: 'Static',
2: 'DHCP',
3: 'BIOS',
4: 'Other',
}
retdata['ipv4_configuration'] = v4cfgmethods[self._fetch_lancfg_param(
channel, 4)]
retdata['mac_address'] = self._fetch_lancfg_param(channel, 5)
retdata['ipv4_gateway'] = self._fetch_lancfg_param(channel, 12)
retdata['ipv4_backup_gateway'] = self._fetch_lancfg_param(channel, 14)
if gateway_macs:
retdata['ipv4_gateway_mac'] = self._fetch_lancfg_param(channel, 13)
retdata['ipv4_backup_gateway_mac'] = self._fetch_lancfg_param(
channel, 15)
self.oem_init()
self._oem.add_extra_net_configuration(retdata)
return retdata
|
python
|
def get_net_configuration(self, channel=None, gateway_macs=True):
"""Get network configuration data
Retrieve network configuration from the target
:param channel: Channel to configure, defaults to None for 'autodetect'
:param gateway_macs: Whether to retrieve mac addresses for gateways
:returns: A dictionary of network configuration data
"""
if channel is None:
channel = self.get_network_channel()
retdata = {}
v4addr = self._fetch_lancfg_param(channel, 3)
if v4addr is None:
retdata['ipv4_address'] = None
else:
v4masklen = self._fetch_lancfg_param(channel, 6, prefixlen=True)
retdata['ipv4_address'] = '{0}/{1}'.format(v4addr, v4masklen)
v4cfgmethods = {
0: 'Unspecified',
1: 'Static',
2: 'DHCP',
3: 'BIOS',
4: 'Other',
}
retdata['ipv4_configuration'] = v4cfgmethods[self._fetch_lancfg_param(
channel, 4)]
retdata['mac_address'] = self._fetch_lancfg_param(channel, 5)
retdata['ipv4_gateway'] = self._fetch_lancfg_param(channel, 12)
retdata['ipv4_backup_gateway'] = self._fetch_lancfg_param(channel, 14)
if gateway_macs:
retdata['ipv4_gateway_mac'] = self._fetch_lancfg_param(channel, 13)
retdata['ipv4_backup_gateway_mac'] = self._fetch_lancfg_param(
channel, 15)
self.oem_init()
self._oem.add_extra_net_configuration(retdata)
return retdata
|
[
"def",
"get_net_configuration",
"(",
"self",
",",
"channel",
"=",
"None",
",",
"gateway_macs",
"=",
"True",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"self",
".",
"get_network_channel",
"(",
")",
"retdata",
"=",
"{",
"}",
"v4addr",
"=",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"3",
")",
"if",
"v4addr",
"is",
"None",
":",
"retdata",
"[",
"'ipv4_address'",
"]",
"=",
"None",
"else",
":",
"v4masklen",
"=",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"6",
",",
"prefixlen",
"=",
"True",
")",
"retdata",
"[",
"'ipv4_address'",
"]",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"v4addr",
",",
"v4masklen",
")",
"v4cfgmethods",
"=",
"{",
"0",
":",
"'Unspecified'",
",",
"1",
":",
"'Static'",
",",
"2",
":",
"'DHCP'",
",",
"3",
":",
"'BIOS'",
",",
"4",
":",
"'Other'",
",",
"}",
"retdata",
"[",
"'ipv4_configuration'",
"]",
"=",
"v4cfgmethods",
"[",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"4",
")",
"]",
"retdata",
"[",
"'mac_address'",
"]",
"=",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"5",
")",
"retdata",
"[",
"'ipv4_gateway'",
"]",
"=",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"12",
")",
"retdata",
"[",
"'ipv4_backup_gateway'",
"]",
"=",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"14",
")",
"if",
"gateway_macs",
":",
"retdata",
"[",
"'ipv4_gateway_mac'",
"]",
"=",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"13",
")",
"retdata",
"[",
"'ipv4_backup_gateway_mac'",
"]",
"=",
"self",
".",
"_fetch_lancfg_param",
"(",
"channel",
",",
"15",
")",
"self",
".",
"oem_init",
"(",
")",
"self",
".",
"_oem",
".",
"add_extra_net_configuration",
"(",
"retdata",
")",
"return",
"retdata"
] |
Get network configuration data
Retrieve network configuration from the target
:param channel: Channel to configure, defaults to None for 'autodetect'
:param gateway_macs: Whether to retrieve mac addresses for gateways
:returns: A dictionary of network configuration data
|
[
"Get",
"network",
"configuration",
"data"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L880-L916
|
16,097
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_sensor_data
|
def get_sensor_data(self):
"""Get sensor reading objects
Iterates sensor reading objects pertaining to the currently
managed BMC.
:returns: Iterator of sdr.SensorReading objects
"""
self.init_sdr()
for sensor in self._sdr.get_sensor_numbers():
rsp = self.raw_command(command=0x2d, netfn=4, data=(sensor,))
if 'error' in rsp:
if rsp['code'] == 203: # Sensor does not exist, optional dev
continue
raise exc.IpmiException(rsp['error'], code=rsp['code'])
yield self._sdr.sensors[sensor].decode_sensor_reading(rsp['data'])
self.oem_init()
for reading in self._oem.get_sensor_data():
yield reading
|
python
|
def get_sensor_data(self):
"""Get sensor reading objects
Iterates sensor reading objects pertaining to the currently
managed BMC.
:returns: Iterator of sdr.SensorReading objects
"""
self.init_sdr()
for sensor in self._sdr.get_sensor_numbers():
rsp = self.raw_command(command=0x2d, netfn=4, data=(sensor,))
if 'error' in rsp:
if rsp['code'] == 203: # Sensor does not exist, optional dev
continue
raise exc.IpmiException(rsp['error'], code=rsp['code'])
yield self._sdr.sensors[sensor].decode_sensor_reading(rsp['data'])
self.oem_init()
for reading in self._oem.get_sensor_data():
yield reading
|
[
"def",
"get_sensor_data",
"(",
"self",
")",
":",
"self",
".",
"init_sdr",
"(",
")",
"for",
"sensor",
"in",
"self",
".",
"_sdr",
".",
"get_sensor_numbers",
"(",
")",
":",
"rsp",
"=",
"self",
".",
"raw_command",
"(",
"command",
"=",
"0x2d",
",",
"netfn",
"=",
"4",
",",
"data",
"=",
"(",
"sensor",
",",
")",
")",
"if",
"'error'",
"in",
"rsp",
":",
"if",
"rsp",
"[",
"'code'",
"]",
"==",
"203",
":",
"# Sensor does not exist, optional dev",
"continue",
"raise",
"exc",
".",
"IpmiException",
"(",
"rsp",
"[",
"'error'",
"]",
",",
"code",
"=",
"rsp",
"[",
"'code'",
"]",
")",
"yield",
"self",
".",
"_sdr",
".",
"sensors",
"[",
"sensor",
"]",
".",
"decode_sensor_reading",
"(",
"rsp",
"[",
"'data'",
"]",
")",
"self",
".",
"oem_init",
"(",
")",
"for",
"reading",
"in",
"self",
".",
"_oem",
".",
"get_sensor_data",
"(",
")",
":",
"yield",
"reading"
] |
Get sensor reading objects
Iterates sensor reading objects pertaining to the currently
managed BMC.
:returns: Iterator of sdr.SensorReading objects
|
[
"Get",
"sensor",
"reading",
"objects"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L918-L936
|
16,098
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_sensor_descriptions
|
def get_sensor_descriptions(self):
"""Get available sensor names
Iterates over the available sensor descriptions
:returns: Iterator of dicts describing each sensor
"""
self.init_sdr()
for sensor in self._sdr.get_sensor_numbers():
yield {'name': self._sdr.sensors[sensor].name,
'type': self._sdr.sensors[sensor].sensor_type}
self.oem_init()
for sensor in self._oem.get_sensor_descriptions():
yield sensor
|
python
|
def get_sensor_descriptions(self):
"""Get available sensor names
Iterates over the available sensor descriptions
:returns: Iterator of dicts describing each sensor
"""
self.init_sdr()
for sensor in self._sdr.get_sensor_numbers():
yield {'name': self._sdr.sensors[sensor].name,
'type': self._sdr.sensors[sensor].sensor_type}
self.oem_init()
for sensor in self._oem.get_sensor_descriptions():
yield sensor
|
[
"def",
"get_sensor_descriptions",
"(",
"self",
")",
":",
"self",
".",
"init_sdr",
"(",
")",
"for",
"sensor",
"in",
"self",
".",
"_sdr",
".",
"get_sensor_numbers",
"(",
")",
":",
"yield",
"{",
"'name'",
":",
"self",
".",
"_sdr",
".",
"sensors",
"[",
"sensor",
"]",
".",
"name",
",",
"'type'",
":",
"self",
".",
"_sdr",
".",
"sensors",
"[",
"sensor",
"]",
".",
"sensor_type",
"}",
"self",
".",
"oem_init",
"(",
")",
"for",
"sensor",
"in",
"self",
".",
"_oem",
".",
"get_sensor_descriptions",
"(",
")",
":",
"yield",
"sensor"
] |
Get available sensor names
Iterates over the available sensor descriptions
:returns: Iterator of dicts describing each sensor
|
[
"Get",
"available",
"sensor",
"names"
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L938-L951
|
16,099
|
openstack/pyghmi
|
pyghmi/ipmi/command.py
|
Command.get_network_channel
|
def get_network_channel(self):
"""Get a reasonable 'default' network channel.
When configuring/examining network configuration, it's desirable to
find the correct channel. Here we run with the 'real' number of the
current channel if it is a LAN channel, otherwise it evaluates
all of the channels to find the first workable LAN channel and returns
that
"""
if self._netchannel is None:
for channel in chain((0xe,), range(1, 0xc)):
try:
rsp = self.xraw_command(
netfn=6, command=0x42, data=(channel,))
except exc.IpmiException as ie:
if ie.ipmicode == 0xcc:
# We have hit an invalid channel, move on to next
# candidate
continue
else:
raise
chantype = ord(rsp['data'][1]) & 0b1111111
if chantype in (4, 6):
try:
# Some implementations denote an inactive channel
# by refusing to do parameter retrieval
if channel != 0xe:
# skip checking if channel is active if we are
# actively using the channel
self.xraw_command(
netfn=0xc, command=2, data=(channel, 5, 0, 0))
# If still here, the channel seems serviceable...
# However some implementations may still have
# ambiguous channel info, that will need to be
# picked up on an OEM extension...
self._netchannel = ord(rsp['data'][0]) & 0b1111
break
except exc.IpmiException as ie:
# This means the attempt to fetch parameter 5 failed,
# therefore move on to next candidate channel
continue
return self._netchannel
|
python
|
def get_network_channel(self):
"""Get a reasonable 'default' network channel.
When configuring/examining network configuration, it's desirable to
find the correct channel. Here we run with the 'real' number of the
current channel if it is a LAN channel, otherwise it evaluates
all of the channels to find the first workable LAN channel and returns
that
"""
if self._netchannel is None:
for channel in chain((0xe,), range(1, 0xc)):
try:
rsp = self.xraw_command(
netfn=6, command=0x42, data=(channel,))
except exc.IpmiException as ie:
if ie.ipmicode == 0xcc:
# We have hit an invalid channel, move on to next
# candidate
continue
else:
raise
chantype = ord(rsp['data'][1]) & 0b1111111
if chantype in (4, 6):
try:
# Some implementations denote an inactive channel
# by refusing to do parameter retrieval
if channel != 0xe:
# skip checking if channel is active if we are
# actively using the channel
self.xraw_command(
netfn=0xc, command=2, data=(channel, 5, 0, 0))
# If still here, the channel seems serviceable...
# However some implementations may still have
# ambiguous channel info, that will need to be
# picked up on an OEM extension...
self._netchannel = ord(rsp['data'][0]) & 0b1111
break
except exc.IpmiException as ie:
# This means the attempt to fetch parameter 5 failed,
# therefore move on to next candidate channel
continue
return self._netchannel
|
[
"def",
"get_network_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_netchannel",
"is",
"None",
":",
"for",
"channel",
"in",
"chain",
"(",
"(",
"0xe",
",",
")",
",",
"range",
"(",
"1",
",",
"0xc",
")",
")",
":",
"try",
":",
"rsp",
"=",
"self",
".",
"xraw_command",
"(",
"netfn",
"=",
"6",
",",
"command",
"=",
"0x42",
",",
"data",
"=",
"(",
"channel",
",",
")",
")",
"except",
"exc",
".",
"IpmiException",
"as",
"ie",
":",
"if",
"ie",
".",
"ipmicode",
"==",
"0xcc",
":",
"# We have hit an invalid channel, move on to next",
"# candidate",
"continue",
"else",
":",
"raise",
"chantype",
"=",
"ord",
"(",
"rsp",
"[",
"'data'",
"]",
"[",
"1",
"]",
")",
"&",
"0b1111111",
"if",
"chantype",
"in",
"(",
"4",
",",
"6",
")",
":",
"try",
":",
"# Some implementations denote an inactive channel",
"# by refusing to do parameter retrieval",
"if",
"channel",
"!=",
"0xe",
":",
"# skip checking if channel is active if we are",
"# actively using the channel",
"self",
".",
"xraw_command",
"(",
"netfn",
"=",
"0xc",
",",
"command",
"=",
"2",
",",
"data",
"=",
"(",
"channel",
",",
"5",
",",
"0",
",",
"0",
")",
")",
"# If still here, the channel seems serviceable...",
"# However some implementations may still have",
"# ambiguous channel info, that will need to be",
"# picked up on an OEM extension...",
"self",
".",
"_netchannel",
"=",
"ord",
"(",
"rsp",
"[",
"'data'",
"]",
"[",
"0",
"]",
")",
"&",
"0b1111",
"break",
"except",
"exc",
".",
"IpmiException",
"as",
"ie",
":",
"# This means the attempt to fetch parameter 5 failed,",
"# therefore move on to next candidate channel",
"continue",
"return",
"self",
".",
"_netchannel"
] |
Get a reasonable 'default' network channel.
When configuring/examining network configuration, it's desirable to
find the correct channel. Here we run with the 'real' number of the
current channel if it is a LAN channel, otherwise it evaluates
all of the channels to find the first workable LAN channel and returns
that
|
[
"Get",
"a",
"reasonable",
"default",
"network",
"channel",
"."
] |
f710b1d30a8eed19a9e86f01f9351c737666f3e5
|
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L953-L994
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.