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: object

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 BooleanNode stores wiring (inputs) plus 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 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 named_expression_to_bit_lut() / 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 set_constant()). That is the source of truth: node.constant, constants, Nconstants, and 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.

property input_nodes

Silent alias of source_nodes.

property constants

Map of constant node id → frozen state (0 or 1).

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 the 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)

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 .txt files still require an explicit type.

  • 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)

classmethod from_string_booleannet(string, keep_constants=True, **kwargs)[source]

Instantiate from BooleanNet / *.booleannet.txt update-rule text.

classmethod from_string_bnet(string, keep_constants=True, **kwargs)[source]

Instantiate from BoolNet / PyBoolNet targets,factors text.

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 .cnet string.

to_string(type='booleannet', **kwargs)[source]

Serialize this network to a format string via the nodes hub.

Parameters:
  • 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:

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_input for cnet).

Returns:

The written contents.

Return type:

(string)

fill_function_representation(representation)[source]

Fill a missing BooleanFunction slot on every node.

Parameters:

representation (str) – "bit_lut", "one_symbol_schemata", "two_symbol_schemata", or "positional_expression".

Returns:

self.

Return type:

(BooleanNetwork)

to_cnet(file=None, adjust_no_input=False, one_symbol_schemata=False)[source]

Outputs the network nodes to .cnet format (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**k LUT rows. Does not fill missing slots — call fill_function_representation() first if needed.

Returns:

The .cnet format 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)

equivalent_to(other)[source]

True if other has the same name-keyed LUTs as this network.

interaction_graph(remove_constants=False, signed=True)[source]

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 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() with signed=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() with signed=True.

Signs are stored on the dedicated sign edge attribute (not weight).

effective_graph(bound='mean', threshold=None, signed=False)[source]

Computes and returns the effective graph of the network. In practice, it asks each BooleanNode for their 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 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 sign frozensets on edges. Defaults to False. The effectiveness cache is always built unsigned; signed=True copies and fills signs.

Returns:

directed graph

Return type:

(networkx.DiGraph)

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 sign frozensets on remaining edges from the conditioned LUTs. Defaults to False.

Returns:

directed graph

Return type:

(networkx.DiGraph)

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 sign frozensets on edges. Defaults to False. The activity cache is always built unsigned; signed=True copies 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 length steps 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 initial until 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) – 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 cana.bns to find all attractors.

Returns:

A list containing all attractors for the boolean network.

Return type:

attractors (list)

See also

cana.bns

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

bias()

basin_entropy(base=2)[source]
set_constant(node, constant=True, state=None)[source]

Sets or unsets a node as a constant.

Parameters:
  • 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.

get_constants()[source]

Return {node_id: BooleanNode} for every functionally constant node.

See also constants for {node_id: int} frozen states.

unset_all_constants()[source]

Clear every node’s constant flag and disable pinning.

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. 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:

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=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.

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.

average_dist_from_attractor()[source]
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:
Returns:

a directed graph representation of the DCM.

Return type:

DCM (networkx.DiGraph)

See also

boolean_node.canalizing_map() for the CM and drawing.draw_dynamics_canalizing_map_graphviz() for plotting. cana.canalization.cm_simplify.simplify_canalizing_map() for the simplify rules. cana.canalization.canalizing_map.CM_BUILDERS for 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)