DAG#
- class causalbase.graph.DAG(num_nodes)[source]#
A directed acyclic graph over integer nodes
0..num_nodes-1.- Parameters:
- num_nodesint
Number of nodes in the graph. Nodes are addressed by the integer indices
0, 1, ..., num_nodes - 1.
- Attributes:
- num_nodesint
Number of nodes in the graph.
- num_edgesint
Current number of directed edges in the graph.
- add_edge(u, v)[source]#
Add the directed edge u -> v.
- Parameters:
- uint
Source node index.
- vint
Target node index.
- Raises:
- IndexError
If u or v is not a node.
- CycleError
If u == v (self-loop), or if a path v -> … -> u already exists, which means adding u -> v would create a cycle. The graph is left unchanged when this is raised.
Notes
Adding an edge that already exists is a no-op: it does not raise and does not affect num_edges.
- remove_edge(u, v)[source]#
Remove the directed edge u -> v.
- Parameters:
- uint
Source node index.
- vint
Target node index.
- Raises:
- KeyError
If u -> v is not an edge of the graph.
- topological_order()[source]#
Return a deterministic topological order of the nodes.
Uses Kahn’s algorithm with a min-heap over ready nodes, so the result is deterministic (lowest-index-first among ties).
- Returns:
- list[int]
Node indices such that every edge u -> v has u appearing before v.
- ancestors(v)[source]#
Return all ancestors of node v.
- Parameters:
- vint
Node index.
- Returns:
- frozenset[int]
All nodes u != v from which there is a directed path to v.
- has_path(u, v)[source]#
Return whether a directed path u -> … -> v exists.
- Parameters:
- uint
Source node index.
- vint
Target node index.
- Returns:
- bool
Trueiff there is a nonempty directed path from u to v. AlwaysFalsewhen u == v, since a self-loop is not a valid path in an acyclic graph.
- copy()[source]#
Return an independent deep copy of this graph.
- Returns:
- DAG
A new DAG with the same nodes and edges, sharing no mutable state with the original.
- classmethod from_edges(num_nodes, edges)[source]#
Build a DAG from a node count and an iterable of edges.
- Parameters:
- num_nodesint
Number of nodes in the graph.
- edgesIterable[tuple[int, int]]
Edges (u, v) to add, in order.
- Returns:
- DAG
A new DAG with the given edges added.
- Raises:
- IndexError
If an edge names a node outside
0..num_nodes-1.- CycleError
If adding the edges in order would create a cycle or a self-loop.
- classmethod from_amat(A)[source]#
Build a DAG from a square boolean (or 0/1) adjacency matrix.
- Parameters:
- Anp.ndarray
Square matrix where a truthy A[u, v] denotes the edge u -> v.
- Returns:
- DAG
A new DAG with edges taken from the nonzero entries of A.
- Raises:
- ValueError
If A is not a square matrix.
- CycleError
If A encodes a self-loop or a cycle.