# -*- coding: utf-8 -*-
"""
Boolean Network
================
Main class for Boolean network objects.
Naming for inputs, ``function`` / :class:`~cana.function_outputs.BooleanFunction`,
``source_nodes``, and related terms follows the glossary in
:mod:`cana.nodes_builder`.
"""
# Copyright (C) 2021 by
# Rion Brattig Correia <rionbr@gmail.com>
# Alex Gates <ajgates@indiana.edu>
# Thomas Parmer <tjparmer@indiana.edu>
# All rights reserved.
# MIT license.
import copy
import itertools
import pickle
import random
import warnings
import networkx as nx
import numpy as np
from scipy.stats import entropy
import cana.bns as bns
from cana.control import fvs, mds, sc
from cana.cutils import (
binstate_compare,
binstate_pinned_to_binstate,
binstate_to_constantbinstate,
binstate_to_statenum,
constantbinstate_to_statenum,
flip_binstate_bit,
flip_bit,
hamming_distance,
random_binstate,
recursive_map,
statenum_to_binstate,
)
# from cana.utils import *
from cana.canalization.cm_simplify import simplify_canalizing_map
from cana.graphs.activity_graph import build_activity_graph
from cana.graphs.effective_graph import (
build_conditional_effective_graph,
build_effective_graph,
)
from cana.graphs.interaction_graph import build_interaction_graph
from cana.utils import flip_binstate_bit_set
[docs]
class BooleanNetwork:
"""A Boolean network whose hub is a dense ``list[BooleanNode]``.
Every import format is converted into a ``list[BooleanNode]``; every
export format is produced from it. Each
:class:`~cana.boolean_node.BooleanNode` stores wiring (``inputs``) plus
:class:`~cana.function_outputs.BooleanFunction` (usually a dense LUT).
Hub invariant
``self.nodes`` is dense with indices ``0 .. Nnodes-1``. For all ``i``,
``nodes[i].id == i``, and every ``inputs`` entry is an index into that
list. CANA does not delete BN nodes after construction; constants
stay in the list and are only pinned / flagged.
When a dense :class:`~cana.function_outputs.bit_lut.BitLut` is present on a node, row
``s`` is the next value when the input state — interpreted in the
``inputs`` order with ``inputs[0]`` as the most significant bit —
equals ``s``. This matches
:func:`~cana.function_outputs.expression.named_expression_to_bit_lut` /
:func:`~cana.cutils.statenum_to_binstate`.
Example (AND of ``A`` then ``B``, node ids 0 and 1)::
[
BooleanNode(id=0, name="A", k=1, inputs=[0],
outputs=BooleanFunction(bit_lut=BitLut.from_sequence([0, 1]))),
BooleanNode(id=1, name="B", k=2, inputs=[0, 1],
outputs=BooleanFunction(bit_lut=BitLut.from_sequence([0, 0, 0, 1]))),
]
Constants
A node is constant when its LUT is flat (see
:meth:`~cana.boolean_node.BooleanNode.set_constant`). That is the
source of truth: ``node.constant``, :attr:`constants`,
:attr:`Nconstants`, and :meth:`get_constants` all derive from it.
``keep_constants`` does **not** decide whether nodes are constant. When
``True``, constant nodes are pinned in state-space helpers (free
``Nstates`` is ``2**(N-Nconstants)``, converters inject fixed bits) and
are included in the dynamics canalizing map. When ``False``, the full
``2**N`` state space is used and constant nodes are omitted from the DCM.
"""
def __init__(
self,
name="",
Nnodes=0,
nodes=None,
sg=None,
stg=None,
stg_r=None,
_eg=None,
_ag=None,
attractors=None,
keep_constants=True,
bin2num=None,
num2bin=None,
verbose=False,
*args,
**kwargs
):
# NOTE: *args and **kwargs don't do anything. I'm not sure why they wre added here, so I'm not going to remove them.
if "constants" in kwargs or "Nconstants" in kwargs:
warnings.warn(
"BooleanNetwork(..., constants=..., Nconstants=...) is ignored; "
"constants are derived from each node's LUT via node.constant. "
"Use keep_constants to pin them in state-space helpers.",
DeprecationWarning,
stacklevel=2,
)
kwargs.pop("constants", None)
kwargs.pop("Nconstants", None)
self.name = name # Name of the Network
self.nodes = list(nodes) if nodes is not None else []
if Nnodes == 0:
Nnodes = len(self.nodes)
self.Nnodes = Nnodes # Number of Nodes
if len(self.nodes) != Nnodes:
raise ValueError(
"Nnodes={0} does not match len(nodes)={1}".format(
Nnodes, len(self.nodes)
)
)
for i, node in enumerate(self.nodes):
if node.id != i:
raise ValueError(
"Hub invariant violated: nodes[{0}].id == {1}".format(
i, node.id
)
)
node.network = self
self._ig = sg # Interaction Graph (legacy: Structure-Graph)
self._stg = stg # State-Transition-Graph (STG)
self._stg_r = stg_r # State-Transition-Graph Reachability dict (STG-R)
self._eg = _eg # Effective Graph, computed from the effective connectivity
self._ag = _ag # Activity Graph, computed from node activities
self._attractors = attractors # Network Attractors
# Pin constant nodes in state-space / DCM helpers (see class docstring).
self.keep_constants = keep_constants
self.Nstates = 2**Nnodes # Number of possible states in the network 2^N
#
self.verbose = verbose
self.name2int = {node.name: i for i, node in enumerate(self.nodes)}
self.Nself_loops = sum(
1 for i, node in enumerate(self.nodes) if i in node.inputs
)
self.source_nodes = [
i
for i in range(Nnodes)
if (
self.nodes[i].constant
or ((self.nodes[i].k == 1) and (i in self.nodes[i].inputs))
)
]
#
self.bin2num = bin2num # Helper function. Converts binstate to statenum. It gets updated by `_update_trans_func`
self.num2bin = num2bin # Helper function. Converts statenum to binstate. It gets updated by `_update_trans_func`
self._update_trans_func() # Updates helper functions and other variables
@property
def input_nodes(self):
"""Silent alias of :attr:`source_nodes`."""
return self.source_nodes
@input_nodes.setter
def input_nodes(self, value):
self.source_nodes = value
@property
def _sg(self):
"""Deprecated alias of ``_ig`` (interaction graph cache)."""
return self._ig
@_sg.setter
def _sg(self, value):
self._ig = value
@property
def constants(self):
"""Map of constant node id → frozen state (``0`` or ``1``).
Derived from ``node.constant`` / ``node.state``; always in sync.
"""
return {
i: int(node.state)
for i, node in enumerate(self.nodes)
if node.constant
}
@property
def Nconstants(self):
"""Number of functionally constant nodes."""
return sum(1 for node in self.nodes if node.constant)
def __str__(self):
node_names = [node.name for node in self.nodes]
return (
"<BNetwork(name='{name:s}', N={number_of_nodes:d}, Nodes={nodes:})>".format(
name=self.name, number_of_nodes=self.Nnodes, nodes=node_names
)
)
#
# I/O Methods
#
# Hub constructor → string/file loaders → format wrappers → exporters →
# conversion / comparison.
#
[docs]
@classmethod
def from_nodes(self, nodes, keep_constants=True, **kwargs):
"""Instantiate a BooleanNetwork from a dense ``list[BooleanNode]``.
Args:
nodes (list[BooleanNode]) : Hub with ``nodes[i].id == i``.
See the :class:`BooleanNetwork` class docstring.
keep_constants (bool) : If True, pin functionally constant nodes
in state-space helpers and include them in the DCM. Constancy
itself always comes from each node's LUT.
Returns:
(BooleanNetwork)
See also:
:func:`from_file` :func:`from_string`
"""
if "name" in kwargs:
name = kwargs["name"]
else:
name = ""
return BooleanNetwork(
name=name,
nodes=nodes,
Nnodes=len(nodes),
keep_constants=keep_constants,
)
[docs]
@classmethod
def from_string(self, string, type="booleannet", keep_constants=True, **kwargs):
"""Load a network from a string of the given format.
Args:
string (string) : Model contents.
type (string) : Format name (``cnet``, ``booleannet``,
``bnet``, ``aeon``, ``sbml``).
keep_constants (bool) : Pin constant nodes in state-space helpers
(see :class:`BooleanNetwork`).
**kwargs : Forwarded to :meth:`from_nodes` (e.g. ``name``).
Returns:
(BooleanNetwork)
"""
from cana.io import parse_string
return self.from_nodes(
parse_string(string, type), keep_constants=keep_constants, **kwargs
)
[docs]
@classmethod
def from_file(self, file, type=None, keep_constants=True, **kwargs):
"""
Load the Boolean Network from a file.
Args:
file (string) : Path to a Boolean network file.
type (string, optional) : Format name. One of ``cnet``,
``booleannet``, ``bnet``, ``aeon``, ``sbml``. If omitted, the
format is inferred from the file suffix (``.cnet``,
``.booleannet.txt``, ``.bnet``, ``.aeon``, ``.sbml``). Ambiguous
``.txt`` files still require an explicit ``type``.
keep_constants (bool) : Pin constant nodes in state-space helpers
(see :class:`BooleanNetwork`).
**kwargs : Forwarded to :meth:`from_nodes` (e.g. ``name``).
Returns:
BooleanNetwork (object) : The boolean network object.
See also:
:func:`to_file` :func:`from_string` :func:`from_nodes`
"""
from cana.io import infer_format, normalize_format, parse_string
if type is not None:
fmt = normalize_format(type)
else:
fmt = infer_format(file)
if fmt is None:
raise ValueError(
"Cannot infer format from {0!r}; pass type= explicitly.".format(
file
)
)
with open(file, "r") as infile:
text = infile.read()
return self.from_nodes(
parse_string(text, fmt), keep_constants=keep_constants, **kwargs
)
[docs]
@classmethod
def from_string_booleannet(self, string, keep_constants=True, **kwargs):
"""Instantiate from BooleanNet / ``*.booleannet.txt`` update-rule text.
See also:
:func:`from_string` :func:`from_nodes`
"""
return self.from_string(
string, type="booleannet", keep_constants=keep_constants, **kwargs
)
[docs]
@classmethod
def from_string_bnet(self, string, keep_constants=True, **kwargs):
"""Instantiate from BoolNet / PyBoolNet ``targets,factors`` text."""
return self.from_string(
string, type="bnet", keep_constants=keep_constants, **kwargs
)
[docs]
@classmethod
def from_string_aeon(self, string, keep_constants=True, **kwargs):
"""Instantiate from AEON text (regulations + ``$var: expr``)."""
return self.from_string(
string, type="aeon", keep_constants=keep_constants, **kwargs
)
[docs]
@classmethod
def from_string_sbml(self, string, keep_constants=True, **kwargs):
"""Instantiate from SBML-qual XML text."""
return self.from_string(
string, type="sbml", keep_constants=keep_constants, **kwargs
)
[docs]
@classmethod
def from_string_cnet(self, string, keep_constants=True, **kwargs):
"""Instantiate a Boolean Network from a ``.cnet`` string.
See also:
:func:`from_file` :func:`from_nodes` :func:`from_string`
"""
return self.from_string(
string, type="cnet", keep_constants=keep_constants, **kwargs
)
[docs]
def to_string(self, type="booleannet", **kwargs):
"""Serialize this network to a format string via the ``nodes`` hub.
Args:
type (string) : Target format (``booleannet``, ``bnet``,
``aeon``, ``sbml``, ``cnet``).
**kwargs : Forwarded to the exporter (e.g. ``adjust_no_input``
for cnet, ``warn`` for expression formats).
Returns:
(string) : The serialized network.
"""
from cana.io import export_string
return export_string(self.nodes, type, **kwargs)
[docs]
def to_file(self, file, type=None, **kwargs):
"""Write this network to ``file``.
Args:
file (string) : Output path.
type (string, optional) : Format; inferred from the suffix if omitted.
**kwargs : Forwarded to the exporter (e.g. ``adjust_no_input`` for cnet).
Returns:
(string) : The written contents.
"""
from cana.io import infer_format, normalize_format
fmt = normalize_format(type) if type is not None else infer_format(file)
if fmt is None:
raise ValueError(
"Cannot infer format from {0!r}; pass type= explicitly.".format(file)
)
text = self.to_string(type=fmt, **kwargs)
with open(file, "w") as outfile:
outfile.write(text)
return text
[docs]
def fill_function_representation(self, representation):
"""Fill a missing ``BooleanFunction`` slot on every node.
Args:
representation (str) : ``"bit_lut"``, ``"one_symbol_schemata"``,
``"two_symbol_schemata"``, or ``"positional_expression"``.
Returns:
(BooleanNetwork) : ``self``.
"""
for node in self.nodes:
node.fill_function_representation(representation)
return self
[docs]
def to_cnet(
self,
file=None,
adjust_no_input=False,
one_symbol_schemata=False,
):
"""Outputs the network nodes to ``.cnet`` format (BNS / BLIF-like).
Args:
file (string, optional) : If given, write the string to this path.
adjust_no_input (bool) : Rewrite empty-input nodes as identity self-loops.
one_symbol_schemata (bool) : If True, export one-symbol (wildcard)
covers; if False (default), export dense ``2**k`` LUT rows.
Does not fill missing slots — call
:meth:`fill_function_representation` first if needed.
Returns:
(string) : The ``.cnet`` format string.
Note:
See `BNS <https://people.kth.se/~dubrova/bns.html>`_ for more information.
"""
from cana.io import nodes_to_cnet
bns_string = nodes_to_cnet(
self.nodes,
adjust_no_input=adjust_no_input,
one_symbol_schemata=one_symbol_schemata,
)
if file is None:
return bns_string
if isinstance(file, str):
with open(file, "w") as iofile:
iofile.write(bns_string)
return bns_string
raise AttributeError(
"File format not supported. Please specify a string."
)
[docs]
@classmethod
def convert_string(self, string, from_type, to_type, **kwargs):
"""Convert a model string between formats via the node-list hub.
Args:
string (string) : Source model text.
from_type, to_type (string) : Format names.
**kwargs : Forwarded to the destination exporter.
Returns:
(string) : Converted model text.
"""
from cana.io import convert
return convert(string, from_type, to_type, **kwargs)
[docs]
def equivalent_to(self, other):
"""True if ``other`` has the same name-keyed LUTs as this network."""
from cana.nodes_builder import equivalent_networks
return equivalent_networks(self, other)
#
# Methods
#
[docs]
def interaction_graph(self, remove_constants=False, signed=True):
"""Return the interaction graph of the boolean network.
Nodes are variables; an edge ``source -> target`` exists when
``source`` is an input of ``target``. Edge ``weight`` is ``1.0``
(topology only). Edge ``sign`` is an ``Optional[frozenset[int]]``:
- ``None`` when ``signed=False`` (not computed)
- ``frozenset({1})`` / ``frozenset({-1})`` — pure activation / inhibition
- ``frozenset({1, -1})`` — binate / dual-sign
- ``frozenset()`` — irrelevant (no influence)
Core construction lives in
:func:`~cana.graphs.interaction_graph.build_interaction_graph`.
Args:
remove_constants (bool) : Remove constants from the graph. Defaults to ``False``.
signed (bool) : Compute and attach interaction signs. Defaults to ``True``.
Returns:
G (networkx.DiGraph) : The boolean network interaction graph.
"""
self._ig = build_interaction_graph(
self.nodes,
name=self.name,
remove_constants=remove_constants,
signed=signed,
constant_ids=(
self.get_constants().keys() if remove_constants else None
),
)
return self._ig
[docs]
def structural_graph(self, remove_constants=False):
"""Deprecated alias of :meth:`interaction_graph` with ``signed=False``.
Prefer :meth:`interaction_graph`. Kept for cheap unsigned topology
(legacy structural-graph callers).
"""
warnings.warn(
"BooleanNetwork.structural_graph is deprecated; "
"use interaction_graph(signed=False) for unsigned topology "
"or interaction_graph() for signed interaction graphs.",
DeprecationWarning,
stacklevel=2,
)
return self.interaction_graph(
remove_constants=remove_constants, signed=False
)
[docs]
def number_interactions(self):
"""Returns the number of interactions in the interaction graph.
Practically, it returns the number of edges.
Returns:
int
"""
self._check_compute_variables(ig=True)
return nx.number_of_edges(self._ig)
[docs]
def interaction_indegrees(self):
"""Returns the in-degrees of the interaction graph. Sorted.
Returns:
(list) : in-degrees.
See also:
:func:`interaction_outdegrees`, :func:`effective_indegrees`, :func:`effective_outdegrees`
"""
self._check_compute_variables(ig=True)
return sorted([d for n, d in self._ig.in_degree()], reverse=True)
[docs]
def interaction_outdegrees(self):
"""Returns the out-degrees of the interaction graph. Sorted.
Returns:
(list) : out-degrees.
See also:
:func:`interaction_indegrees`, :func:`effective_indegrees`, :func:`effective_outdegrees`
"""
self._check_compute_variables(ig=True)
return sorted([d for n, d in self._ig.out_degree()], reverse=True)
[docs]
def structural_indegrees(self):
"""Deprecated alias of :meth:`interaction_indegrees`."""
warnings.warn(
"BooleanNetwork.structural_indegrees is deprecated; "
"use interaction_indegrees instead.",
DeprecationWarning,
stacklevel=2,
)
return self.interaction_indegrees()
[docs]
def structural_outdegrees(self):
"""Deprecated alias of :meth:`interaction_outdegrees`."""
warnings.warn(
"BooleanNetwork.structural_outdegrees is deprecated; "
"use interaction_outdegrees instead.",
DeprecationWarning,
stacklevel=2,
)
return self.interaction_outdegrees()
[docs]
def signed_interaction_graph(self):
"""Deprecated alias of :meth:`interaction_graph` with ``signed=True``.
Signs are stored on the dedicated ``sign`` edge attribute (not ``weight``).
"""
warnings.warn(
"BooleanNetwork.signed_interaction_graph is deprecated; "
"use interaction_graph(signed=True) instead.",
DeprecationWarning,
stacklevel=2,
)
return self.interaction_graph(signed=True)
[docs]
def effective_graph(self, bound="mean", threshold=None, signed=False):
"""Computes and returns the effective graph of the network.
In practice, it asks each :class:`~cana.boolean_node.BooleanNode` for their :func:`~cana.boolean_node.BooleanNode.edge_effectiveness`.
None thresholded effective graph is cached after the first computation. Thresholded effective graphs are computed from the cached
effective graph.
Core construction lives in
:func:`~cana.graphs.effective_graph.build_effective_graph`.
Args:
bound (string) : The bound to which compute input redundancy.
Can be one of : ["lower", "mean", "upper", "tuple"].
Defaults to "mean".
threshold (float) : Only return edges above a certain effective connectivity threshold.
This is usefull when computing graph measures at diffent levels.
signed (bool) : Attach interaction ``sign`` frozensets on edges.
Defaults to ``False``. The effectiveness cache is always built
unsigned; ``signed=True`` copies and fills signs.
Returns:
(networkx.DiGraph) : directed graph
See Also:
:func:`~cana.boolean_node.BooleanNode.edge_effectiveness`
"""
if self._eg is None:
self._eg = build_effective_graph(
self.nodes, name=self.name, bound=bound
)
return build_effective_graph(
self.nodes,
name=self.name,
bound=bound,
threshold=threshold,
signed=signed,
base_eg=self._eg,
)
[docs]
def conditional_effective_graph(
self, conditioned_nodes={}, bound="mean", threshold=None, signed=False
):
"""Computes and returns the BN effective graph conditioned on some known states.
Core construction lives in
:func:`~cana.graphs.effective_graph.build_conditional_effective_graph`.
Args:
conditioned_nodes (dict) : a dictionary mapping node ids to their conditioned states.
dict of form { nodeid : nodestate }
bound (string) : The bound to which compute input redundancy.
Can be one of : ["lower", "mean", "upper", "tuple"].
Defaults to "mean".
threshold (float) : Only return edges above a certain effective connectivity threshold.
This is usefull when computing graph measures at diffent levels.
signed (bool) : Attach interaction ``sign`` frozensets on remaining
edges from the conditioned LUTs. Defaults to ``False``.
Returns:
(networkx.DiGraph) : directed graph
See Also:
:func:`~cana.boolean_network.BooleanNetwork.effective_graph`
"""
return build_conditional_effective_graph(
self.nodes,
conditioned_nodes=conditioned_nodes,
bound=bound,
threshold=threshold,
signed=signed,
name=self.name,
base_eg=self.effective_graph(
bound=bound, threshold=None, signed=False
),
)
[docs]
def effective_indegrees(self):
"""Returns the in-degrees of the Effective Graph. Sorted.
Returns:
(list)
See also:
:func:`effective_outdegrees`, :func:`interaction_indegrees`, :func:`interaction_outdegrees`
"""
self._check_compute_variables(eg=True)
return sorted([d for n, d in self._eg.in_degree(weight="weight")], reverse=True)
[docs]
def effective_outdegrees(self):
"""Returns the out-degrees of the Effective Graph. Sorted.
Returns:
(list)
See also:
:func:`effective_indegrees`, :func:`interaction_indegrees`, :func:`interaction_outdegrees`
"""
self._check_compute_variables(eg=True)
return sorted(
[d for n, d in self._eg.out_degree(weight="weight")], reverse=True
)
[docs]
def activity_graph(self, threshold=None, signed=False):
"""Return the activity graph as proposed in
Ghanbarnejad & Klemm (2012) EPL, 99.
The unthresholded activity graph is cached after the first computation.
Thresholded / signed views are derived from that cache.
Core construction lives in
:func:`~cana.graphs.activity_graph.build_activity_graph`.
Args:
threshold (float) : Only return edges above a certain activity threshold.
This is usefull when computing graph measures at diffent levels.
signed (bool) : Attach interaction ``sign`` frozensets on edges.
Defaults to ``False``. The activity cache is always built
unsigned; ``signed=True`` copies and fills signs.
Returns:
(networkx.DiGraph) : directed graph
"""
if self._ag is None:
self._ag = build_activity_graph(self.nodes, name=self.name)
return build_activity_graph(
self.nodes,
name=self.name,
threshold=threshold,
signed=signed,
base_ag=self._ag,
)
[docs]
def state_transition_graph(self):
"""Creates and returns the full State Transition Graph (STG) for the Boolean Network.
Returns:
(networkx.DiGraph) : The state transition graph for the Boolean Network.
"""
self._stg = nx.DiGraph(name="STG: " + self.name)
self._stg.add_nodes_from(
(i, {"label": self.num2bin(i)}) for i in range(self.Nstates)
)
for i in range(self.Nstates):
b = self.num2bin(i)
self._stg.add_edge(i, self.bin2num(self.step(b)))
#
return self._stg
[docs]
def stg_indegree(self):
"""Returns the In-degrees of the State-Transition-Graph (STG). Sorted.
Returns:
list
"""
self._check_compute_variables(stg=True)
return sorted(self._stg.in_degree().values(), reverse=True)
[docs]
def step(self, initial):
"""Steps the boolean network from the given initial configuration.
Args:
initial (string) : the initial configuration state.
Returns:
(string) : The stepped binary state.
"""
# for every node:
# node input = breaks down initial by node input
# asks node to step with the input
# append output to list
# joins the results from each node output
assert (
len(initial) == self.Nnodes
), "The initial configuration state does not match the number of nodes"
return "".join([node.step(node.input_mask(initial)) for node in self.nodes])
[docs]
def trajectory(self, initial, length=2):
"""Computes the trajectory of ``length`` steps without the State Transition Graph (STG)."""
trajectory = [initial]
for istep in range(length):
trajectory.append(self.step(trajectory[-1]))
return trajectory
[docs]
def trajectory_to_attractor(
self, initial, precompute_attractors=True, return_attractor=False
):
"""Computes the trajectory starting at `initial` until it reaches an attracor (this is garanteed).
Args:
initial (string) : the initial binstate.
precompute_attractors (bool) : use precomputed attractors, default True.
return_attractor (bool) : also return the attractor reached, default False.
Returns:
(list) : the state trajectory between initial and the final attractor state.
if return_attractor: (list): the attractor
"""
# if the attractors are already precomputed, then we can check when we reach a known state
if precompute_attractors:
self._check_compute_variables(attractors=True)
attractor_states = [
self.num2bin(s) for att in self._attractors for s in att
]
trajectory = [initial]
while trajectory[-1] not in attractor_states:
trajectory.append(self.step(trajectory[-1]))
if return_attractor:
attractor = self.attractor(trajectory[-1])
else:
trajectory = [initial]
while trajectory[-1] not in trajectory[:-1]:
trajectory.append(self.step(trajectory[-1]))
# the attractor starts at the first occurence of the element
idxatt = trajectory.index(trajectory[-1])
if return_attractor:
attractor = [self.bin2num(s) for s in trajectory[idxatt:-1]]
trajectory = trajectory[: (idxatt + 1)]
if return_attractor:
return trajectory, attractor
else:
return trajectory
[docs]
def attractor(self, initial):
"""Computes the trajectory starting at ``initial`` until it reaches an attracor (this is garanteed)
Args:
initial (string): the initial state.
Returns:
attractor (string): the atractor state.
"""
self._check_compute_variables(attractors=True)
trajectory = self.trajectory_to_attractor(initial)
for attractor in self._attractors:
if self.bin2num(trajectory[-1]) in attractor:
return attractor
[docs]
def attractors(self, mode="stg"):
"""Find the attractors of the boolean network.
Args:
mode (string) : ``stg`` or ``sat``. Defaults to ``stg``.
``stg``: Uses the full State Transition Graph (STG) and identifies the attractors as strongly connected components.
``bns``: Uses the SAT-based :mod:`cana.bns` to find all attractors.
Returns:
attractors (list) : A list containing all attractors for the boolean network.
See also:
:mod:`cana.bns`
"""
self._check_compute_variables(stg=True)
if mode == "stg":
self._attractors = [list(a) for a in nx.attracting_components(self._stg)]
elif mode == "bns":
self._attractors = bns.attractors(
self.to_cnet(file=None, adjust_no_input=False)
)
else:
raise AttributeError(
"Could not find the specified mode. Try 'stg' or 'bns'."
)
self._attractors.sort(key=len, reverse=True)
return self._attractors
[docs]
def network_bias(self):
"""Network Bias. The sum of individual node biases divided by the number of nodes.
Practically, it asks each node for their own bias.
.. math:
TODO
See Also:
:func:`~cana.boolean_node.BooleanNode.bias`
"""
return sum([node.bias() for node in self.nodes]) / self.Nnodes
[docs]
def basin_entropy(self, base=2):
""" """
self._check_compute_variables(stg=True)
prob_vec = (
np.array([len(wcc) for wcc in nx.weakly_connected_components(self._stg)])
/ 2.0**self.Nnodes
)
return entropy(prob_vec, base=base)
[docs]
def set_constant(self, node, constant=True, state=None):
"""Sets or unsets a node as a constant.
Args:
node (int) : The node ``id`` in ``self.nodes``.
constant (Boolean) : Whether to set or unset the node as a constant.
state (str; optional) : The state value to which to set the node. Either '0' or '1'; default to current state value.
"""
self.nodes[node].set_constant(constant=constant, state=state)
self._update_trans_func()
[docs]
def get_constants(self):
"""Return ``{node_id: BooleanNode}`` for every functionally constant node.
See also :attr:`constants` for ``{node_id: int}`` frozen states.
"""
return {i: node for i, node in enumerate(self.nodes) if node.constant}
[docs]
def unset_all_constants(self):
"""Clear every node's constant flag and disable pinning."""
self.keep_constants = False
for node in self.nodes:
node.set_constant(constant=False)
self._update_trans_func()
def _update_trans_func(self):
"""Sets the correct functions to convert from binary-state format to/from numeric-state format."""
if self.keep_constants:
self.Nstates = 2 ** (self.Nnodes - self.Nconstants)
# The template is a list that identifies the values of constant nodes: [None, '1', None, '0'].
constant_template = [
None if not node.constant else node.state for node in self.nodes
]
self.bin2num = lambda bs: constantbinstate_to_statenum(
bs, constant_template
)
self.num2bin = lambda sn: binstate_to_constantbinstate(
statenum_to_binstate(sn, base=self.Nnodes - self.Nconstants),
constant_template,
)
else:
self.Nstates = 2**self.Nnodes
self.bin2num = binstate_to_statenum
self.num2bin = lambda sn: statenum_to_binstate(sn, base=self.Nnodes)
#
# Dynamical Control Methods
#
[docs]
def state_transition_graph_reachability(self, filename=None):
"""Generates a State-Transition-Graph Reachability (STG-R) dictionary.
This dict/file will be used by the State Transition Graph Control Analysis.
Args:
filename (string) : The location to a file where the STG-R will be stored.
Returns:
(dict) : The STG-R in dict format.
"""
self._check_compute_variables(stg=True)
self._stg_r = {}
if filename is None:
for source in self._stg:
self._stg_r[source] = len(self._dfs_reachable(self._stg, source)) - 1.0
else:
try:
with open(filename, "rb") as handle:
self._stg_r = pickle.load(handle)
except IOError:
print("Finding STG dict")
for source in self._stg:
self._stg_r[source] = (
len(self._dfs_reachable(self._stg, source)) - 1.0
)
with open(filename, "wb") as handle:
pickle.dump(self._stg_r, handle)
return self._stg_r
[docs]
def attractor_driver_nodes(self, min_dvs=1, max_dvs=4, verbose=False):
"""Get the minimum necessary driver nodes by iterating the combination of all possible driver nodes of length :math:`min <= x <= max`.
Args:
min_dvs (int) : Mininum number of driver nodes to search.
max_dvs (int) : Maximum number of driver nodes to search.
Returns:
(list) : The list of driver nodes found in the search.
Note:
This is an inefficient bruit force search, maybe we can think of better ways to do this?
TODO:
Parallelize the search on each combination. Each CSTG is independent and can be searched in parallel.
See also:
:func:`controlled_state_transition_graph`, :func:`controlled_attractor_graph`.
"""
nodeids = list(range(self.Nnodes))
if self.keep_constants:
for cv in self.get_constants().keys():
nodeids.remove(cv)
attractor_controllers_found = []
nr_dvs = min_dvs
while (len(attractor_controllers_found) == 0) and (nr_dvs <= max_dvs):
if verbose:
print("Trying with {:d} Driver Nodes".format(nr_dvs))
for dvs in itertools.combinations(nodeids, nr_dvs):
dvs = list(dvs)
# cstg = self.controlled_state_transition_graph(dvs)
cag = self.controlled_attractor_graph(dvs)
att_reachable_from = self.mean_reachable_attractors(cag)
if att_reachable_from == 1.0:
attractor_controllers_found.append(dvs)
# Add another driver node
nr_dvs += 1
if len(attractor_controllers_found) == 0:
warnings.warn(
"No attractor control driver variable sets found after exploring all subsets of size {:,d} to {:,d} nodes!!".format(
min_dvs, max_dvs
)
)
return attractor_controllers_found
[docs]
def controlled_state_transition_graph(self, driver_nodes=[]):
"""Returns the Controlled State-Transition-Graph (CSTG).
In practice, it copies the original STG, flips driver nodes (variables), and updates the CSTG.
Args:
driver_nodes (list) : The list of driver nodes.
Returns:
(networkx.DiGraph) : The Controlled State-Transition-Graph.
See also:
:func:`attractor_driver_nodes`, :func:`controlled_attractor_graph`.
"""
self._check_compute_variables(attractors=True)
if self.keep_constants:
for dv in driver_nodes:
if dv in self.get_constants():
warnings.warn(
"Cannot control a constant variable '%s'! Skipping"
% self.nodes[dv].name
)
# attractor_states = [s for att in self._attractors for s in att]
cstg = copy.deepcopy(self._stg)
cstg.name = (
"C-"
+ cstg.name
+ " ("
+ ",".join(map(str, [self.nodes[dv].name for dv in driver_nodes]))
+ ")"
)
# add the control pertubations applied to all other configurations
for statenum in range(self.Nstates):
binstate = self.num2bin(statenum)
controlled_states = flip_binstate_bit_set(binstate, copy.copy(driver_nodes))
controlled_states.remove(binstate)
for constate in controlled_states:
cstg.add_edge(statenum, self.bin2num(constate))
return cstg
[docs]
def pinning_controlled_state_transition_graph(self, driver_nodes=[]):
"""Returns a dictionary of Controlled State-Transition-Graph (CSTG)
under the assumptions of pinning controllability.
In practice, it copies the original STG, flips driver nodes (variables), and updates the CSTG.
Args:
driver_nodes (list) : The list of driver nodes.
Returns:
(networkx.DiGraph) : The Pinning Controlled State-Transition-Graph.
See also:
:func:`controlled_state_transition_graph`, :func:`attractor_driver_nodes`, :func:`controlled_attractor_graph`.
"""
self._check_compute_variables(attractors=True)
if self.keep_constants:
for dv in driver_nodes:
if dv in self.get_constants():
warnings.warn(
"Cannot control a constant variable {dv:s}'! Skipping".format(
dv=self.nodes[dv].name
)
)
uncontrolled_system_size = self.Nnodes - len(driver_nodes)
pcstg_dict = {}
for att in self._attractors:
dn_attractor_transitions = [
tuple(
"".join([self.num2bin(s)[dn] for dn in driver_nodes])
for s in att_edge
)
for att_edge in self._stg.subgraph(att).edges()
]
pcstg_states = [
self.bin2num(
binstate_pinned_to_binstate(
statenum_to_binstate(statenum, base=uncontrolled_system_size),
attsource,
pinned_var=driver_nodes,
)
)
for statenum in range(2**uncontrolled_system_size)
for attsource, attsink in dn_attractor_transitions
]
pcstg = nx.DiGraph(name="STG: " + self.name)
pcstg.name = (
"PC-"
+ pcstg.name
+ " ("
+ ",".join(map(str, [self.nodes[dv].name for dv in driver_nodes]))
+ ")"
)
pcstg.add_nodes_from((ps, {"label": ps}) for ps in pcstg_states)
for attsource, attsink in dn_attractor_transitions:
for statenum in range(2**uncontrolled_system_size):
initial = binstate_pinned_to_binstate(
statenum_to_binstate(statenum, base=uncontrolled_system_size),
attsource,
pinned_var=driver_nodes,
)
pcstg.add_edge(
self.bin2num(initial),
self.bin2num(
self.pinned_step(
initial,
pinned_binstate=attsink,
pinned_var=driver_nodes,
)
),
)
pcstg_dict[tuple(att)] = pcstg
return pcstg_dict
[docs]
def pinned_step(self, initial, pinned_binstate, pinned_var):
"""Steps the boolean network 1 step from the given initial input condition when the driver variables are pinned
to their controlled states.
Args:
initial (string) : the initial state.
n (int) : the number of steps.
Returns:
(string) : The stepped binary state.
"""
# for every node:
# node input = breaks down initial by node input
# asks node to step with the input
# append output to list
# joins the results from each node output
assert len(initial) == self.Nnodes
return "".join(
[
str(node.step("".join(initial[j] for j in self.nodes[i].inputs)))
if not (i in pinned_var)
else initial[i]
for i, node in enumerate(self.nodes, start=0)
]
)
[docs]
def controlled_attractor_graph(self, driver_nodes=[]):
"""
Args:
cstg (networkx.DiGraph) : A Controlled State-Transition-Graph (CSTG)
Returns:
(networkx.DiGraph) : The Controlled Attractor Graph (CAG)
See also:
:func:`attractor_driver_nodes`, :func:`controlled_state_transition_graph`.
"""
self._check_compute_variables(attractors=True)
if self.keep_constants:
for dv in driver_nodes:
if dv in self.get_constants():
warnings.warn(
"Cannot control a constant variable '%s'! Skipping"
% self.nodes[dv].name
)
attractor_states = [s for att in self._attractors for s in att]
cstg = copy.deepcopy(self._stg)
cstg.name = (
"C-"
+ cstg.name
+ " Att("
+ ",".join(map(str, [self.nodes[dv].name for dv in driver_nodes]))
+ ")"
)
# add the control pertubations applied to only attractor configurations
for statenum in attractor_states:
binstate = self.num2bin(statenum)
controlled_states = flip_binstate_bit_set(binstate, copy.copy(driver_nodes))
controlled_states.remove(binstate)
for constate in controlled_states:
cstg.add_edge(statenum, self.bin2num(constate))
Nattract = len(self._attractors)
cag = nx.DiGraph(name="CAG: " + cstg.name)
# Nodes
for i, attr in enumerate(self._attractors):
cag.add_node(i, **{"label": "|".join([self.num2bin(a) for a in attr])})
# Edges
for i in range(Nattract):
ireach = self._dfs_reachable(cstg, self._attractors[i][0])
for j in range(i + 1, Nattract):
if self._attractors[j][0] in ireach:
cag.add_edge(i, j)
if self._attractors[i][0] in self._dfs_reachable(
cstg, self._attractors[j][0]
):
cag.add_edge(j, i)
return cag
[docs]
def mean_reachable_configurations(self, cstg):
"""Returns the Mean Fraction of Reachable Configurations
Args:
cstg (networkx.DiGraph) : The Controlled State-Transition-Graph.
Returns:
(float) : Mean Fraction of Reachable Configurations
"""
reachable_from = []
for source in cstg:
control_reach = len(self._dfs_reachable(cstg, source)) - 1.0
reachable_from.append(control_reach)
norm = (2.0**self.Nnodes - 1.0) * len(reachable_from)
reachable_from = sum(reachable_from) / (norm)
return reachable_from
[docs]
def mean_controlable_configurations(self, cstg):
"""The Mean Fraction of Controlable Configurations
Args:
cstg (networkx.DiGraph) : The Controlled State-Transition-Graph.
Returns:
(float) : Mean Fraction of Controlable Configurations.
"""
self._check_compute_variables(stg_r=True)
control_from, reachable_from = [], []
for source in cstg:
control_reach = len(self._dfs_reachable(cstg, source)) - 1.0
control_from.append(control_reach - self._stg_r[source])
reachable_from.append(control_reach)
norm = (2.0**self.Nnodes - 1.0) * len(reachable_from)
control_from = sum(control_from) / (norm)
return control_from
[docs]
def mean_reachable_attractors(self, cag, norm=True):
"""The Mean Fraction of Reachable Attractors to a specific Controlled Attractor Graph (CAG).
Args:
cag (networkx.DiGraph) : A Controlled Attractor Graph (CAG).
Returns:
(float) Mean Fraction of Reachable Attractors
"""
att_norm = (float(len(cag)) - 1.0) * len(cag)
if att_norm == 0:
# if there is only one attractor everything is reachable
att_reachable_from = 1
else:
# otherwise find the reachable from each attractor
att_reachable_from = [
len(self._dfs_reachable(cag, idxatt)) - 1.0 for idxatt in cag
]
att_reachable_from = sum(att_reachable_from) / (att_norm)
return att_reachable_from
[docs]
def fraction_pinned_attractors(self, pcstg_dict):
"""Returns the Number of Accessible Attractors
Args:
pcstg_dict (dict of networkx.DiGraph) : The dictionary of Pinned Controlled State-Transition-Graphs.
Returns:
(int) : Number of Accessible Attractors
"""
reached_attractors = []
for att, pcstg in pcstg_dict.items():
pinned_att = list(nx.attracting_components(pcstg))
print(set(att), pinned_att)
reached_attractors.append(set(att) in pinned_att)
return sum(reached_attractors) / float(len(pcstg_dict))
[docs]
def fraction_pinned_configurations(self, pcstg_dict):
"""Returns the Fraction of successfully Pinned Configurations
Args:
pcstg_dict (dict of networkx.DiGraph) : The dictionary of Pinned Controlled State-Transition-Graphs.
Returns:
(list) : the Fraction of successfully Pinned Configurations to each attractor
"""
pinned_configurations = []
for att, pcstg in pcstg_dict.items():
att_reached = False
for wcc in nx.weakly_connected_components(pcstg):
if set(att) in list(nx.attracting_components(pcstg.subgraph(wcc))):
pinned_configurations.append(len(wcc) / len(pcstg))
att_reached = True
if not att_reached:
pinned_configurations.append(0)
return pinned_configurations
[docs]
def mean_fraction_pinned_configurations(self, pcstg_dict):
"""Returns the mean Fraction of successfully Pinned Configurations
Args:
pcstg_dict (dict of networkx.DiGraph) : The dictionary of Pinned Controlled State-Transition-Graphs.
Returns:
(int) : the mean Fraction of successfully Pinned Configurations
"""
return sum(self.fraction_pinned_configurations(pcstg_dict)) / len(pcstg_dict)
def _dfs_reachable(self, G, source):
"""Produce nodes in a depth-first-search pre-ordering starting from source."""
return [n for n in nx.dfs_preorder_nodes(G, source)]
def _control_digraph(self, graph, *args, **kwargs):
"""Resolve a digraph for structure-based control helpers.
``graph`` is ``"interaction"`` or ``"effective"``. ``"structural"`` is
accepted as a deprecated alias for ``"interaction"``. Signs are not
used by MDS/FVS/SC; interaction graphs are built with ``signed=False``
unless the caller overrides.
"""
if graph == "structural":
warnings.warn(
"graph='structural' is deprecated; use graph='interaction'.",
DeprecationWarning,
stacklevel=3,
)
graph = "interaction"
if graph == "interaction":
kwargs = dict(kwargs)
kwargs.setdefault("signed", False)
return self.interaction_graph(*args, **kwargs)
if graph == "effective":
eg_kwargs = {
k: kwargs[k]
for k in ("bound", "threshold", "signed")
if k in kwargs
}
eg_kwargs.setdefault("bound", "mean")
eg_kwargs.setdefault("signed", False)
return self.effective_graph(**eg_kwargs)
raise AttributeError(
"The graph type '%s' is not accepted. Try 'interaction' or 'effective'."
% graph
)
#
# Feedback Vertex Set (FVS)
#
[docs]
def feedback_vertex_set_driver_nodes(
self,
graph="interaction",
method="grasp",
max_iter=1,
max_search=11,
keep_self_loops=True,
*args,
**kwargs
):
"""The minimum set of necessary driver nodes to control the network based on Feedback Vertex Set (FVS) theory.
Args:
graph (string) : Which graph to perform computation
(``"interaction"`` or ``"effective"``; ``"structural"`` is a
deprecated alias for ``"interaction"``).
method (string) : FVS method. ``bruteforce`` or ``grasp`` (default).
max_iter (int) : The maximum number of iterations used by the grasp method.
max_search (int) : The maximum number of searched used by the bruteforce method.
keep_self_loops (bool) : Keep or remove self loop in the graph to be searched.
Returns:
(list) : A list-of-lists with FVS solution nodes.
Note:
When computing FVS on the interaction graph, you might want to use ``remove_constants=True``
to make sure the resulting set is minimal – since constants are not controlabled by definition.
Also, when computing on the effective graph, you can define the desired ``threshold`` level.
"""
self._check_compute_variables(ig=True)
dg = self._control_digraph(graph, *args, **kwargs)
#
if method == "grasp":
fvssets = fvs.fvs_grasp(
dg, max_iter=max_iter, keep_self_loops=keep_self_loops
)
elif method == "bruteforce":
fvssets = fvs.fvs_bruteforce(
dg, max_search=max_search, keep_self_loops=keep_self_loops
)
else:
raise AttributeError(
"The FVS method '%s' does not exist. Try 'grasp' or 'bruteforce'."
% method
)
fvssets = [fvc.union(set(self.source_nodes)) for fvc in fvssets]
return fvssets # [ [self.nodes[i].name for i in fvsset] for fvsset in fvssets]
#
# Minimum Dominating Set
#
[docs]
def minimum_dominating_set_driver_nodes(
self, graph="interaction", max_search=5, keep_self_loops=True, *args, **kwargs
):
"""The minimun set of necessary driver nodes to control the network based on Minimum Dominating Set (MDS) theory.
Args:
graph (string) : ``"interaction"`` or ``"effective"``
(``"structural"`` is a deprecated alias for ``"interaction"``).
max_search (int) : Maximum search of additional variables. Defaults to 5.
keep_self_loops (bool) : If self-loops are used in the computation.
Returns:
(list) : A list-of-lists with MDS solution nodes.
"""
self._check_compute_variables(ig=True)
dg = self._control_digraph(graph, *args, **kwargs)
mdssets = mds.mds(dg, max_search=max_search, keep_self_loops=keep_self_loops)
return mdssets # [ [self.nodes[i].name for i in mdsset] for mdsset in mdssets]
# Structural Controllability
#
[docs]
def structural_controllability_driver_nodes(
self, graph="interaction", keep_self_loops=True, *args, **kwargs
):
"""The minimum set of necessary driver nodes to control the network based on Structural Controlability (SC) theory.
Args:
graph (string) : ``"interaction"`` or ``"effective"``
(``"structural"`` is a deprecated alias for ``"interaction"``).
keep_self_loops (bool) : If self-loops are used in the computation.
Returns:
(list) : A list-of-lists with SC solution nodes.
"""
self._check_compute_variables(ig=True)
dg = self._control_digraph(graph, *args, **kwargs)
#
scsets = [
set(scset).union(set(self.source_nodes))
for scset in sc.sc(dg, keep_self_loops=keep_self_loops)
]
return scsets # [ [self.nodes[i].name for i in scset] for scset in scsets]
#
# Dynamical Impact
#
[docs]
def partial_derative_node(self, node, n_traj=10, t=1):
"""The partial derivative of node on all other nodes after t steps
Args:
node (int) : the node index for perturbations
t (int) : the number of time steps the system is run before impact is calculated.
n_traj (int) : the number of trajectories used to approximate the dynamical impact of a node.
if 0 then the full STG is used to calculate the true value instead of the approximation method.
Returns:
(vector) : the partial derivatives
"""
partial = np.zeros((t, self.Nnodes), dtype=float)
if n_traj == 0:
config_genderator = (
self.num2bin(statenum) for statenum in range(self.Nstates)
)
n_traj = self.Nstates
else:
# sample configurations
config_genderator = (
random_binstate(self.Nnodes) for itraj in range(n_traj)
)
for config in config_genderator:
perturbed_config = flip_binstate_bit(config, node)
for n_step in range(t):
config = self.step(config)
perturbed_config = self.step(perturbed_config)
partial[n_step] += np.logical_not(
binstate_compare(config, perturbed_config)
)
partial /= n_traj
return partial
[docs]
def approx_dynamic_impact(
self, source, n_steps=1, target_set=None, bound="mean", threshold=0.0
):
"""Use the network structure to approximate the dynamical impact of a perturbation to node for each of n_steps
for details see: Gates et al (2020).
Args:
source (int) : the source index for perturbations
n_steps (int) : the number of time steps
bound (str) : the bound for the effective graph
'mean' - edge effectiveness
'upper' - activity
Returns:
(matrix) : approximate dynamical impact for each node at each step (2 x n_steps x n_nodes)
"""
if target_set is None:
target_set = range(self.Nnodes)
Gstr = self.interaction_graph(signed=False)
Geff = self.effective_graph(bound=bound, threshold=threshold, signed=False)
# the maximum path with length given by product of weights is the same as minimal path of negative log weight
def eff_weight_func(u, v, e):
return -np.log(e["weight"])
def inv_eff_weight_func(pathlength):
return np.exp(-pathlength)
impact_matrix = np.zeros((2, n_steps + 1, len(target_set)))
impact_matrix[0, :, :] = (
self.Nnodes + 1
) # if we can't reach the node, then the paths cant be longer than the number of nodes in the graph
# note that by default: impact_matrix[1, :, :] = 0 the minimum path for nodes we cant reach in the effective graph
# in the interaction graph, calcluate the dijkstra shortest paths from the source to all targets that are shorter than the cufoff
Gstr_shortest_dist, Gstr_shortest_paths = nx.single_source_dijkstra(
Gstr, source, target=None, cutoff=n_steps
)
Gstr_shortest_dist = {n: int(l) for n, l in Gstr_shortest_dist.items()}
# in the effective graph, calcluate the dijkstra shortest paths from the source to all targets that are shorter than the cufoff
# where the edge weight is given by the effective weight function
Geff_shortest_dist, Geff_shortest_paths = nx.single_source_dijkstra(
Geff, source, target=None, cutoff=n_steps, weight=eff_weight_func
)
for itar, target in enumerate(target_set):
# we dont need to worry about a path to iteself (source==target)
# and if the target doesnt appear in the shortest path dict, then no path exists that is less than the cutoff
if target != source and not Gstr_shortest_dist.get(target, None) is None:
# the light cone is at least as big as the number of edges in the interaction shortest path
impact_matrix[
0, list(range(Gstr_shortest_dist[target], n_steps + 1)), itar
] = Gstr_shortest_dist[target]
# if the path exists, then the number of edges (timesteps) is one less than the number of nodes
if not Geff_shortest_paths.get(target, None) is None:
eff_path_steps = len(Geff_shortest_paths[target]) - 1
else:
# or the path doesnt exist
eff_path_steps = (
n_steps + 100
) # any number bigger than the longest path to represent we cannot reach the node
# start by checking if the number of timesteps is less than the maximum allowable number of steps
if eff_path_steps <= n_steps:
# now check if the most likely effective path is longer (in terms of # of timesteps) than the interaction shortest path
if eff_path_steps > Gstr_shortest_dist[target]:
# if it is, then we need to find another effective path constrained by the light-cone
# for all time steps where the most likely effective path is longer (in terms of # of timesteps)
# than the interaction shortest path
for istep in range(Gstr_shortest_dist[target], eff_path_steps):
# bc the effective graph has fully redundant edges, there may actually not be a path
try:
redo_dijkstra_dist, _ = nx.single_source_dijkstra(
Geff,
source=source,
target=target,
cutoff=istep,
weight=eff_weight_func,
)
impact_matrix[1, istep, itar] = inv_eff_weight_func(
redo_dijkstra_dist
)
except nx.NetworkXNoPath:
pass
# once the lightcone includes the target node on the effective shortest path,
# then for all other steps the effective path is the best
impact_matrix[
1, list(range(eff_path_steps, n_steps + 1)), itar
] = inv_eff_weight_func(Geff_shortest_dist[target])
return impact_matrix[:, 1:]
[docs]
def dist_from_attractor(self):
"""Find the distance from attractor for each configuration.
Returns:
distance (dict). Nodes are dictionary indexes and distances the values.
"""
self._check_compute_variables(attractors=True)
dist = {} # stores [node, distance] pair
for att in self._attractors:
dist.update({a: (0, a) for a in att})
dag = nx.bfs_tree(self._stg, att[0], reverse=True)
attractor_states = set(att)
for node in nx.topological_sort(dag):
# pairs of dist,node for all incoming edges
if node not in attractor_states:
pairs = [(dist[v][0] + 1, v) for v in dag.pred[node]]
if pairs:
dist[node] = min(pairs)
else:
dist[node] = (0, node)
return dist
[docs]
def average_dist_from_attractor(self):
dist = self.dist_from_attractor()
return np.mean([d[0] for d in dist.values() if d[0] > 0])
#
# Dynamics Canalization Map (DCM)
#
[docs]
def dynamics_canalization_map(
self, output=None, simplify=True, builder="legacy", remove_isolates=True
):
"""Computes the Dynamics Canalization Map (DCM).
In practice, it asks each node to compute their Canalization Map and then puts them together, simplifying it if possible.
Args:
output (int) : The output DCM to return. Default is ``None``, retuning both [0,1].
simplify (bool) : If ``True``, apply threshold-unit reduction via
:func:`cana.canalization.cm_simplify.simplify_canalizing_map`
(does not remove ``tau=0`` constant schemata).
builder (str or callable) : Per-node CM construction method. Default is
``'legacy'``. See :func:`cana.canalization.canalizing_map.build_canalizing_map`
and :data:`cana.canalization.canalizing_map.CM_BUILDERS`.
remove_isolates (bool) : If ``True`` (default), drop isolated nodes after
compose. Isolate cleanup is orthogonal to ``simplify``: unused
opposite-polarity variable stubs from other nodes' CMs are typically
noise for drawing/analysis. Pass ``False`` for a raw composed graph.
Returns:
DCM (networkx.DiGraph) : a directed graph representation of the DCM.
See Also:
:func:`boolean_node.canalizing_map` for the CM and :func:`drawing.draw_dynamics_canalizing_map_graphviz` for plotting.
:func:`cana.canalization.cm_simplify.simplify_canalizing_map` for the simplify rules.
:data:`cana.canalization.canalizing_map.CM_BUILDERS` for named builders.
"""
CMs = []
for node in self.nodes:
if self.keep_constants or not node.constant:
CMs.append(node.canalizing_map(output, builder=builder))
# https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.operators.all.compose_all.html
DCM = nx.compose_all(CMs)
DCM.name = "DCM: %s" % (self.name)
if simplify:
simplify_canalizing_map(DCM, copy=False, remove_isolates=remove_isolates)
elif remove_isolates:
DCM.remove_nodes_from(list(nx.isolates(DCM)))
return DCM
def _check_compute_variables(self, **kwargs):
"""Recursevely check if the requested control variables are instantiated/computed.
Otherwise computes them in order.
"""
if "ig" in kwargs or "sg" in kwargs:
if self._ig is None:
self._ig = self.interaction_graph()
elif "eg" in kwargs:
if self._eg is None:
self._eg = self.effective_graph()
elif "stg" in kwargs:
if self._stg is None:
self._check_compute_variables(ig=True)
self._stg = self.state_transition_graph()
elif "attractors" in kwargs:
if self._attractors is None:
self._check_compute_variables(stg=True)
self._attractors = self.attractors()
elif "stg_r" in kwargs:
if self._stg_r is None:
self._check_compute_variables(stg=True)
self._stg_r = self.state_transition_graph_reachability()
else:
raise Exception("Control variable name not found. %s" % kwargs)
return True
#
# Get Node Names from Ids
#
def _get_node_name(self, id):
"""Return the name of the node based on its id.
Args:
id (int): id of the node.
Returns:
name (string): name of the node.
"""
try:
node = self.nodes[id]
except Exception as error:
raise AttributeError(
"Node with id {id:d} does not exist. {error::s}".format(
id=id, error=error
)
)
else:
return node.name
[docs]
def get_node_name(self, iterable=[]):
"""Return node names. Optionally, it returns only the names of the ids requested.
Args:
iterable (int,list, optional) : The id (or list of ids) of nodes to which return their names.
Returns:
names (list) : The name of the nodes.
"""
# If only one id is passed, make it a list
if not isinstance(iterable, list):
iterable = [iterable]
# No ids requested, return all the names
if not len(iterable):
return [n.name for n in self.nodes]
# otherwise, use the recursive map to change ids to names
else:
return recursive_map(self._get_node_name, iterable)
[docs]
def average_trajectory_length(self, nsamples=10, random_seed=None, method="random"):
"""The average length of trajectories from a random initial configuration to its attractor.
Args:
nsamples (int) : The number of samples per hammimg distance to get.
random_seed (int) : The random state seed.
method (string) : specify the method you want. either 'random' or ....
Returns:
trajlen (float) : The average trajectory length to an attractor.
"""
return (
sum(
len(self.trajectory_to_attractor(random_binstate(self.Nnodes)))
for isample in range(nsamples)
)
/ nsamples
)
[docs]
def derrida_curve(
self, nsamples=10, max_hamm=None, random_seed=None, method="random"
):
"""The Derrida Curve (also reffered as criticality measure :math:`D_s`).
When "mode" is set as "random" (default), it would use random sampling to estimate Derrida value
If "mode" is set as "sensitivity", it would use c-sensitivity to calculate Derrida value (slower)
You can refer to :cite:'kadelka2017influence' about why c-sensitivity can be used to caculate Derrida value
Args:
nsamples (int) : The number of samples per hammimg distance to get.
max_hamm (int) : The maximum Hamming distance between starting states. default: self.Nnodes
random_seed (int) : The random state seed.
method (string) : specify the method you want. either 'random' or 'sensitivity'
Returns:
(dx,dy) (tuple) : The dx and dy of the curve.
"""
random.seed(random_seed)
if max_hamm is None or (max_hamm > self.Nnodes):
max_hamm = self.Nnodes
dx = np.linspace(0, 1, max_hamm, endpoint=True)
dy = np.zeros(max_hamm + 1)
if method == "random":
# for each possible hamming distance between the starting states
for hamm_dist in range(1, max_hamm + 1):
# sample nsample times
for isample in range(nsamples):
rnd_config = random_binstate(self.Nnodes)
perturbed_var = random.sample(range(self.Nnodes), hamm_dist)
perturbed_config = [
flip_bit(rnd_config[ivar])
if ivar in perturbed_var
else rnd_config[ivar]
for ivar in range(self.Nnodes)
]
dy[hamm_dist] += (
hamming_distance(
self.step(rnd_config), self.step(perturbed_config)
)
/ self.Nnodes
) # normalized Hamming Distance
dy /= nsamples
elif method == "sensitivity":
for hamm_dist in range(1, max_hamm + 1):
dy[hamm_dist] = (
sum(
[
node.c_sensitivity(
hamm_dist, mode="forceK", max_k=self.Nnodes
)
for node in self.nodes
]
)
/ self.Nnodes
)
return dx, dy
[docs]
def derrida_coefficient(self, nsamples=10, random_seed=None, method="random"):
"""The Derrida Coefficient.
When "mode" is set as "random" (default), it would use random sampling to estimate Derrida value
If "mode" is set as "sensitivity", it would use c-sensitivity to calculate Derrida value (slower)
You can refer to :cite:'kadelka2017influence' about why c-sensitivity can be used to caculate Derrida value
Args:
nsamples (int) : The number of samples per hammimg distance to get.
random_seed (int) : The random state seed.
method (string) : specify the method you want. either 'random' or 'sensitivity'
Returns:
(dx,dy) (tuple) : The dx and dy of the curve.
"""
random.seed(random_seed)
hamm_dist = 1
if method == "random":
# for each possible hamming distance between the starting states
dy = 0
# sample nsample times
for isample in range(nsamples):
rnd_config = random_binstate(self.Nnodes)
perturbed_var = random.sample(range(self.Nnodes), hamm_dist)
perturbed_config = [
flip_bit(rnd_config[ivar])
if ivar in perturbed_var
else rnd_config[ivar]
for ivar in range(self.Nnodes)
]
dy += hamming_distance(
self.step(rnd_config), self.step(perturbed_config)
)
dy /= float(nsamples)
elif method == "sensitivity":
# raise NotImplementedError
dy = sum(
[
node.c_sensitivity(hamm_dist, mode="forceK", max_k=self.Nnodes)
for node in self.nodes
]
)
return dy / float(self.Nnodes)