cana.boolean_network module
Boolean Network
Main class for Boolean network objects.
Naming for inputs, function / BooleanFunction,
source_nodes, and related terms follows the glossary in
cana.nodes_builder.
- class cana.boolean_network.BooleanNetwork(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)[source]
Bases:
objectA 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. EachBooleanNodestores wiring (inputs) plusBooleanFunction(usually a dense LUT).- Hub invariant
self.nodesis dense with indices0 .. Nnodes-1. For alli,nodes[i].id == i, and everyinputsentry 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
BitLutis present on a node, rowsis the next value when the input state — interpreted in theinputsorder withinputs[0]as the most significant bit — equalss. This matchesnamed_expression_to_bit_lut()/statenum_to_binstate().Example (AND of
AthenB, 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
set_constant()). That is the source of truth:node.constant,constants,Nconstants, andget_constants()all derive from it.keep_constantsdoes not decide whether nodes are constant. WhenTrue, constant nodes are pinned in state-space helpers (freeNstatesis2**(N-Nconstants), converters inject fixed bits) and are included in the dynamics canalizing map. WhenFalse, the full2**Nstate space is used and constant nodes are omitted from the DCM.
- property input_nodes
Silent alias of
source_nodes.
- property constants
Map of constant node id → frozen state (
0or1).Derived from
node.constant/node.state; always in sync.
- property Nconstants
Number of functionally constant nodes.
- classmethod from_nodes(nodes, keep_constants=True, **kwargs)[source]
Instantiate a BooleanNetwork from a dense
list[BooleanNode].- Parameters:
nodes (list[BooleanNode]) – Hub with
nodes[i].id == i. See theBooleanNetworkclass 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
- classmethod from_string(string, type='booleannet', keep_constants=True, **kwargs)[source]
Load a network from a string of the given format.
- Parameters:
string (string) – Model contents.
type (string) – Format name (
cnet,booleannet,bnet,aeon,sbml).keep_constants (bool) – Pin constant nodes in state-space helpers (see
BooleanNetwork).**kwargs – Forwarded to
from_nodes()(e.g.name).
- Returns:
(BooleanNetwork)
- classmethod from_file(file, type=None, keep_constants=True, **kwargs)[source]
Load the Boolean Network from a file.
- Parameters:
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.txtfiles still require an explicittype.keep_constants (bool) – Pin constant nodes in state-space helpers (see
BooleanNetwork).**kwargs – Forwarded to
from_nodes()(e.g.name).
- Returns:
The boolean network object.
- Return type:
BooleanNetwork (object)
See also
- classmethod from_string_booleannet(string, keep_constants=True, **kwargs)[source]
Instantiate from BooleanNet /
*.booleannet.txtupdate-rule text.See also
- classmethod from_string_bnet(string, keep_constants=True, **kwargs)[source]
Instantiate from BoolNet / PyBoolNet
targets,factorstext.
- classmethod from_string_aeon(string, keep_constants=True, **kwargs)[source]
Instantiate from AEON text (regulations +
$var: expr).
- classmethod from_string_sbml(string, keep_constants=True, **kwargs)[source]
Instantiate from SBML-qual XML text.
- classmethod from_string_cnet(string, keep_constants=True, **kwargs)[source]
Instantiate a Boolean Network from a
.cnetstring.See also
- to_string(type='booleannet', **kwargs)[source]
Serialize this network to a format string via the
nodeshub.- Parameters:
type (string) – Target format (
booleannet,bnet,aeon,sbml,cnet).**kwargs – Forwarded to the exporter (e.g.
adjust_no_inputfor cnet,warnfor expression formats).
- Returns:
The serialized network.
- Return type:
(string)
- to_file(file, type=None, **kwargs)[source]
Write this network to
file.- Parameters:
file (string) – Output path.
type (string, optional) – Format; inferred from the suffix if omitted.
**kwargs – Forwarded to the exporter (e.g.
adjust_no_inputfor cnet).
- Returns:
The written contents.
- Return type:
(string)
- fill_function_representation(representation)[source]
Fill a missing
BooleanFunctionslot on every node.- Parameters:
representation (str) –
"bit_lut","one_symbol_schemata","two_symbol_schemata", or"positional_expression".- Returns:
self.- Return type:
- to_cnet(file=None, adjust_no_input=False, one_symbol_schemata=False)[source]
Outputs the network nodes to
.cnetformat (BNS / BLIF-like).- Parameters:
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**kLUT rows. Does not fill missing slots — callfill_function_representation()first if needed.
- Returns:
The
.cnetformat string.- Return type:
(string)
Note
See BNS for more information.
- classmethod convert_string(string, from_type, to_type, **kwargs)[source]
Convert a model string between formats via the node-list hub.
- Parameters:
string (string) – Source model text.
from_type (string) – Format names.
to_type (string) – Format names.
**kwargs – Forwarded to the destination exporter.
- Returns:
Converted model text.
- Return type:
(string)
- interaction_graph(remove_constants=False, signed=True)[source]
Return the interaction graph of the boolean network.
Nodes are variables; an edge
source -> targetexists whensourceis an input oftarget. Edgeweightis1.0(topology only). Edgesignis anOptional[frozenset[int]]:Nonewhensigned=False(not computed)frozenset({1})/frozenset({-1})— pure activation / inhibitionfrozenset({1, -1})— binate / dual-signfrozenset()— irrelevant (no influence)
Core construction lives in
build_interaction_graph().- Parameters:
remove_constants (bool) – Remove constants from the graph. Defaults to
False.signed (bool) – Compute and attach interaction signs. Defaults to
True.
- Returns:
The boolean network interaction graph.
- Return type:
G (networkx.DiGraph)
- structural_graph(remove_constants=False)[source]
Deprecated alias of
interaction_graph()withsigned=False.Prefer
interaction_graph(). Kept for cheap unsigned topology (legacy structural-graph callers).
- number_interactions()[source]
Returns the number of interactions in the interaction graph. Practically, it returns the number of edges.
- Returns:
int
- interaction_indegrees()[source]
Returns the in-degrees of the interaction graph. Sorted.
- Returns:
in-degrees.
- Return type:
(list)
- interaction_outdegrees()[source]
Returns the out-degrees of the interaction graph. Sorted.
- Returns:
out-degrees.
- Return type:
(list)
- structural_indegrees()[source]
Deprecated alias of
interaction_indegrees().
- structural_outdegrees()[source]
Deprecated alias of
interaction_outdegrees().
- signed_interaction_graph()[source]
Deprecated alias of
interaction_graph()withsigned=True.Signs are stored on the dedicated
signedge attribute (notweight).
- effective_graph(bound='mean', threshold=None, signed=False)[source]
Computes and returns the effective graph of the network. In practice, it asks each
BooleanNodefor theiredge_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
build_effective_graph().- Parameters:
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
signfrozensets on edges. Defaults toFalse. The effectiveness cache is always built unsigned;signed=Truecopies and fills signs.
- Returns:
directed graph
- Return type:
(networkx.DiGraph)
See also
- conditional_effective_graph(conditioned_nodes={}, bound='mean', threshold=None, signed=False)[source]
Computes and returns the BN effective graph conditioned on some known states.
Core construction lives in
build_conditional_effective_graph().- Parameters:
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
signfrozensets on remaining edges from the conditioned LUTs. Defaults toFalse.
- Returns:
directed graph
- Return type:
(networkx.DiGraph)
See also
- effective_indegrees()[source]
Returns the in-degrees of the Effective Graph. Sorted.
- Returns:
(list)
- effective_outdegrees()[source]
Returns the out-degrees of the Effective Graph. Sorted.
- Returns:
(list)
- activity_graph(threshold=None, signed=False)[source]
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
build_activity_graph().- Parameters:
threshold (float) – Only return edges above a certain activity threshold. This is usefull when computing graph measures at diffent levels.
signed (bool) – Attach interaction
signfrozensets on edges. Defaults toFalse. The activity cache is always built unsigned;signed=Truecopies and fills signs.
- Returns:
directed graph
- Return type:
(networkx.DiGraph)
- state_transition_graph()[source]
Creates and returns the full State Transition Graph (STG) for the Boolean Network.
- Returns:
The state transition graph for the Boolean Network.
- Return type:
(networkx.DiGraph)
- stg_indegree()[source]
Returns the In-degrees of the State-Transition-Graph (STG). Sorted.
- Returns:
list
- step(initial)[source]
Steps the boolean network from the given initial configuration.
- Parameters:
initial (string) – the initial configuration state.
- Returns:
The stepped binary state.
- Return type:
(string)
- trajectory(initial, length=2)[source]
Computes the trajectory of
lengthsteps without the State Transition Graph (STG).
- trajectory_to_attractor(initial, precompute_attractors=True, return_attractor=False)[source]
Computes the trajectory starting at initial until it reaches an attracor (this is garanteed).
- Parameters:
initial (string) – the initial binstate.
precompute_attractors (bool) – use precomputed attractors, default True.
return_attractor (bool) – also return the attractor reached, default False.
- Returns:
the state trajectory between initial and the final attractor state. if return_attractor: (list): the attractor
- Return type:
(list)
- attractor(initial)[source]
Computes the trajectory starting at
initialuntil it reaches an attracor (this is garanteed)- Parameters:
initial (string) – the initial state.
- Returns:
the atractor state.
- Return type:
attractor (string)
- attractors(mode='stg')[source]
Find the attractors of the boolean network.
- Parameters:
mode (string) –
stgorsat. Defaults tostg.stg: Uses the full State Transition Graph (STG) and identifies the attractors as strongly connected components.bns: Uses the SAT-basedcana.bnsto find all attractors.- Returns:
A list containing all attractors for the boolean network.
- Return type:
attractors (list)
See also
- network_bias()[source]
Network Bias. The sum of individual node biases divided by the number of nodes. Practically, it asks each node for their own bias.
See also
- set_constant(node, constant=True, state=None)[source]
Sets or unsets a node as a constant.
- Parameters:
node (int) – The node
idinself.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.
- get_constants()[source]
Return
{node_id: BooleanNode}for every functionally constant node.See also
constantsfor{node_id: int}frozen states.
- state_transition_graph_reachability(filename=None)[source]
Generates a State-Transition-Graph Reachability (STG-R) dictionary. This dict/file will be used by the State Transition Graph Control Analysis.
- Parameters:
filename (string) – The location to a file where the STG-R will be stored.
- Returns:
The STG-R in dict format.
- Return type:
(dict)
- attractor_driver_nodes(min_dvs=1, max_dvs=4, verbose=False)[source]
Get the minimum necessary driver nodes by iterating the combination of all possible driver nodes of length \(min <= x <= max\).
- Parameters:
min_dvs (int) – Mininum number of driver nodes to search.
max_dvs (int) – Maximum number of driver nodes to search.
- Returns:
The list of driver nodes found in the search.
- Return type:
(list)
Note
This is an inefficient bruit force search, maybe we can think of better ways to do this?
- controlled_state_transition_graph(driver_nodes=[])[source]
Returns the Controlled State-Transition-Graph (CSTG). In practice, it copies the original STG, flips driver nodes (variables), and updates the CSTG.
- Parameters:
driver_nodes (list) – The list of driver nodes.
- Returns:
The Controlled State-Transition-Graph.
- Return type:
(networkx.DiGraph)
- pinning_controlled_state_transition_graph(driver_nodes=[])[source]
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.
- Parameters:
driver_nodes (list) – The list of driver nodes.
- Returns:
The Pinning Controlled State-Transition-Graph.
- Return type:
(networkx.DiGraph)
- pinned_step(initial, pinned_binstate, pinned_var)[source]
Steps the boolean network 1 step from the given initial input condition when the driver variables are pinned to their controlled states.
- Parameters:
initial (string) – the initial state.
n (int) – the number of steps.
- Returns:
The stepped binary state.
- Return type:
(string)
- controlled_attractor_graph(driver_nodes=[])[source]
- Parameters:
cstg (networkx.DiGraph) – A Controlled State-Transition-Graph (CSTG)
- Returns:
The Controlled Attractor Graph (CAG)
- Return type:
(networkx.DiGraph)
- mean_reachable_configurations(cstg)[source]
Returns the Mean Fraction of Reachable Configurations
- Parameters:
cstg (networkx.DiGraph) – The Controlled State-Transition-Graph.
- Returns:
Mean Fraction of Reachable Configurations
- Return type:
(float)
- mean_controlable_configurations(cstg)[source]
The Mean Fraction of Controlable Configurations
- Parameters:
cstg (networkx.DiGraph) – The Controlled State-Transition-Graph.
- Returns:
Mean Fraction of Controlable Configurations.
- Return type:
(float)
- mean_reachable_attractors(cag, norm=True)[source]
The Mean Fraction of Reachable Attractors to a specific Controlled Attractor Graph (CAG).
- Parameters:
cag (networkx.DiGraph) – A Controlled Attractor Graph (CAG).
- Returns:
(float) Mean Fraction of Reachable Attractors
- fraction_pinned_attractors(pcstg_dict)[source]
Returns the Number of Accessible Attractors
- Parameters:
pcstg_dict (dict of networkx.DiGraph) – The dictionary of Pinned Controlled State-Transition-Graphs.
- Returns:
Number of Accessible Attractors
- Return type:
(int)
- fraction_pinned_configurations(pcstg_dict)[source]
Returns the Fraction of successfully Pinned Configurations
- Parameters:
pcstg_dict (dict of networkx.DiGraph) – The dictionary of Pinned Controlled State-Transition-Graphs.
- Returns:
the Fraction of successfully Pinned Configurations to each attractor
- Return type:
(list)
- mean_fraction_pinned_configurations(pcstg_dict)[source]
Returns the mean Fraction of successfully Pinned Configurations
- Parameters:
pcstg_dict (dict of networkx.DiGraph) – The dictionary of Pinned Controlled State-Transition-Graphs.
- Returns:
the mean Fraction of successfully Pinned Configurations
- Return type:
(int)
- feedback_vertex_set_driver_nodes(graph='interaction', method='grasp', max_iter=1, max_search=11, keep_self_loops=True, *args, **kwargs)[source]
The minimum set of necessary driver nodes to control the network based on Feedback Vertex Set (FVS) theory.
- Parameters:
graph (string) – Which graph to perform computation (
"interaction"or"effective";"structural"is a deprecated alias for"interaction").method (string) – FVS method.
bruteforceorgrasp(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:
A list-of-lists with FVS solution nodes.
- Return type:
(list)
Note
When computing FVS on the interaction graph, you might want to use
remove_constants=Trueto 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 desiredthresholdlevel.
- minimum_dominating_set_driver_nodes(graph='interaction', max_search=5, keep_self_loops=True, *args, **kwargs)[source]
The minimun set of necessary driver nodes to control the network based on Minimum Dominating Set (MDS) theory.
- Parameters:
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:
A list-of-lists with MDS solution nodes.
- Return type:
(list)
- structural_controllability_driver_nodes(graph='interaction', keep_self_loops=True, *args, **kwargs)[source]
The minimum set of necessary driver nodes to control the network based on Structural Controlability (SC) theory.
- Parameters:
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:
A list-of-lists with SC solution nodes.
- Return type:
(list)
- partial_derative_node(node, n_traj=10, t=1)[source]
The partial derivative of node on all other nodes after t steps
- Parameters:
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:
the partial derivatives
- Return type:
(vector)
- approx_dynamic_impact(source, n_steps=1, target_set=None, bound='mean', threshold=0.0)[source]
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).
- Parameters:
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:
approximate dynamical impact for each node at each step (2 x n_steps x n_nodes)
- Return type:
(matrix)
- dist_from_attractor()[source]
Find the distance from attractor for each configuration.
- Returns:
distance (dict). Nodes are dictionary indexes and distances the values.
- dynamics_canalization_map(output=None, simplify=True, builder='legacy', remove_isolates=True)[source]
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.
- Parameters:
output (int) – The output DCM to return. Default is
None, retuning both [0,1].simplify (bool) – If
True, apply threshold-unit reduction viacana.canalization.cm_simplify.simplify_canalizing_map()(does not removetau=0constant schemata).builder (str or callable) – Per-node CM construction method. Default is
'legacy'. Seecana.canalization.canalizing_map.build_canalizing_map()andcana.canalization.canalizing_map.CM_BUILDERS.remove_isolates (bool) – If
True(default), drop isolated nodes after compose. Isolate cleanup is orthogonal tosimplify: unused opposite-polarity variable stubs from other nodes’ CMs are typically noise for drawing/analysis. PassFalsefor a raw composed graph.
- Returns:
a directed graph representation of the DCM.
- Return type:
DCM (networkx.DiGraph)
See also
boolean_node.canalizing_map()for the CM anddrawing.draw_dynamics_canalizing_map_graphviz()for plotting.cana.canalization.cm_simplify.simplify_canalizing_map()for the simplify rules.cana.canalization.canalizing_map.CM_BUILDERSfor named builders.
- get_node_name(iterable=[])[source]
Return node names. Optionally, it returns only the names of the ids requested.
- Parameters:
iterable (int,list, optional) – The id (or list of ids) of nodes to which return their names.
- Returns:
The name of the nodes.
- Return type:
names (list)
- average_trajectory_length(nsamples=10, random_seed=None, method='random')[source]
The average length of trajectories from a random initial configuration to its attractor.
- Parameters:
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:
The average trajectory length to an attractor.
- Return type:
trajlen (float)
- derrida_curve(nsamples=10, max_hamm=None, random_seed=None, method='random')[source]
The Derrida Curve (also reffered as criticality measure \(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
- Parameters:
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:
The dx and dy of the curve.
- Return type:
(dx,dy) (tuple)
- derrida_coefficient(nsamples=10, random_seed=None, method='random')[source]
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
- Parameters:
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:
The dx and dy of the curve.
- Return type:
(dx,dy) (tuple)