corneto.graph.BaseGraph#

class corneto.graph.BaseGraph(default_edge_type=EdgeType.DIRECTED)#

Bases: ABC

Abstract base class for graphs and hypergraphs.

Defines the interface and common functionality for graph implementations. Supports directed/undirected/mixed edges and self-edges.

Parameters:

default_edge_type (EdgeType)

__init__(default_edge_type=EdgeType.DIRECTED)#

Initialize BaseGraph.

Parameters:

default_edge_type (EdgeType) – Default type for edges when not specified

Return type:

None

Methods

__init__([default_edge_type])

Initialize BaseGraph.

add_edge(source, target[, type, ...])

Add edge to the graph.

add_edges(edges[, type])

Add multiple edges to the graph.

add_vertex(v, **kwargs)

Add vertex to the graph.

add_vertices(vertices, **kwargs)

Add multiple vertices to the graph.

bfs(starting_vertices[, reverse, undirected])

Perform breadth-first search (BFS) traversal.

copy()

Create a deep copy of the graph.

edge_subgraph(edges)

Create subgraph induced by a set of edges.

edges([vertices])

Get edges in the graph.

extract_subgraph([vertices, edges])

Extract subgraph induced by a set of vertices and/or edges.

get_attr_edge(index)

Get attributes of an edge.

get_attr_edges([indexes])

Get attributes of multiple edges.

get_attr_from_edges(attr[, default])

Get specific attribute from all edges.

get_attr_vertex(v)

Get attributes of a vertex.

get_attr_vertices([vertices])

Get attributes of multiple vertices.

get_common_incident_edges(vertices)

Get common incident edges for multiple vertices.

get_edge(index)

Get edge by index.

get_edges(indexes)

Get multiple edges by their indices.

get_edges_by_attr(key, value)

Get edges by specific attribute value.

get_graph_attributes()

Get global graph attributes.

get_incident_edges(vertices)

Get incident edges for multiple vertices.

get_vertex(index)

Get vertex by its index.

get_vertex_incidence_matrix_as_lists([values])

Get vertex incidence matrix as lists.

hash()

Compute hash of the graph based on its content.

in_edges(vertices)

Get incoming edges for vertices.

is_hypergraph()

Check if the graph is a hypergraph.

load(filename[, compression])

Load graph from a saved file.

neighbors(vertex)

Get neighbors of a vertex (ignoring edge direction).

out_edges(vertices)

Get outgoing edges for vertices.

plot(**kwargs)

Plot the graph using Graphviz.

plot_values([vertex_values, edge_values, ...])

predecessors(vertices)

Get predecessor vertices for multiple vertices.

prune([source, target])

Prune the graph to include only reachable vertices.

reachability_analysis(input_nodes, output_nodes)

Perform reachability analysis from input nodes to output nodes.

reverse()

Reverse the direction of all edges in the graph.

save(filename[, compression])

Save graph to file using pickle serialization.

subgraph(vertices)

Create subgraph induced by a set of vertices.

successors(vertices)

Get successor vertices for multiple vertices.

to_dot(**kwargs)

Convert graph to DOT format.

to_graphviz(**kwargs)

Convert graph to Graphviz representation.

toposort()

Perform topological sort on the graph using Kahn's algorithm.

vertex_incidence_matrix([values, sparse])

Get vertex incidence matrix.

Attributes

E

Edges in the graph.

V

Vertices in the graph.

ne

Number of edges in the graph.

num_edges

Number of edges in the graph.

num_vertices

Number of vertices in the graph.

nv

Number of vertices in the graph.

shape

Shape of the graph (number of vertices, number of edges).

vertices

Vertices in the graph.

abstractmethod get_edge(index)#

Get edge by index.

Parameters:

index (int) – Index of the edge

Returns:

Edge at the specified index

Return type:

Tuple[FrozenSet[Any], FrozenSet[Any]]

abstractmethod get_graph_attributes()#

Get global graph attributes.

Returns:

Attributes of the graph

Return type:

Attributes

edge_subgraph(edges)#

Create subgraph induced by a set of edges.

Parameters:

edges (Iterable[int] | ndarray) – Indices of edges to include in the subgraph

Returns:

Subgraph induced by the specified edges

subgraph(vertices)#

Create subgraph induced by a set of vertices.

Parameters:

vertices (Iterable) – Vertices to include in the subgraph

Returns:

Subgraph induced by the specified vertices

abstractmethod extract_subgraph(vertices=None, edges=None)#

Extract subgraph induced by a set of vertices and/or edges.

Parameters:
  • vertices (Iterable | None) – Optional vertices to include in the subgraph

  • edges (Iterable[int] | None) – Optional edges to include in the subgraph

Returns:

Subgraph induced by the specified vertices and/or edges

property num_vertices: int#

Number of vertices in the graph.

Returns:

Number of vertices

property num_edges: int#

Number of edges in the graph.

Returns:

Number of edges

hash()#

Compute hash of the graph based on its content.

Returns:

Hash string representing the graph content

Return type:

str

get_attr_edge(index)#

Get attributes of an edge.

Parameters:

index (int) – Index of the edge

Returns:

Attributes of the edge

Return type:

Attributes

get_attr_vertex(v)#

Get attributes of a vertex.

Parameters:

v – Vertex to get attributes for

Returns:

Attributes of the vertex

Return type:

Attributes

get_attr_edges(indexes=None)#

Get attributes of multiple edges.

Parameters:

indexes (Iterable[int] | None) – Optional indices of edges to get attributes for

Returns:

List of attributes for the specified edges

Return type:

List[Attributes]

get_attr_from_edges(attr, default=None)#

Get specific attribute from all edges.

Parameters:
  • attr (str) – Attribute name to get

  • default (Any) – Default value if attribute is not present

Returns:

List of attribute values for all edges

Return type:

List[Any]

get_edges_by_attr(key, value)#

Get edges by specific attribute value.

Parameters:
  • key (str) – Attribute name to filter by

  • value (Any) – Attribute value to filter by

Returns:

Iterable of edge indices with the specified attribute value

Return type:

Iterable[int]

get_attr_vertices(vertices=None)#

Get attributes of multiple vertices.

Parameters:

vertices (Iterable | None) – Optional vertices to get attributes for

Returns:

List of attributes for the specified vertices

Return type:

List[Attributes]

get_edges(indexes)#

Get multiple edges by their indices.

Parameters:

indexes (Iterable[int]) – Indices of edges to get

Returns:

Iterable of edges at the specified indices

Return type:

Iterable[Tuple[FrozenSet[Any], FrozenSet[Any]]]

get_vertex(index)#

Get vertex by its index.

Parameters:

index (int) – Index of the vertex

Returns:

Vertex at the specified index

Raises:

IndexError – If index is out of range

Return type:

Any

get_incident_edges(vertices)#

Get incident edges for multiple vertices.

Parameters:

vertices – Vertices to get incident edges for

Returns:

Iterable of incident edge indices

Return type:

Iterable[int]

get_common_incident_edges(vertices)#

Get common incident edges for multiple vertices.

Parameters:

vertices – Vertices to get common incident edges for

Returns:

Iterable of common incident edge indices

Return type:

Iterable[int]

edges(vertices=None)#

Get edges in the graph.

Parameters:

vertices – Optional vertices to get edges for

Returns:

Iterable of edge indices and edges

Return type:

Iterable[Tuple[int, Tuple[FrozenSet[Any], FrozenSet[Any]]]]

copy()#

Create a deep copy of the graph.

Returns:

Deep copy of the graph

Return type:

BaseGraph

abstractmethod reverse()#

Reverse the direction of all edges in the graph.

Returns:

Graph with reversed edges

Return type:

BaseGraph

in_edges(vertices)#

Get incoming edges for vertices.

Parameters:

vertices – Vertices to get incoming edges for

Returns:

Iterator yielding (edge index, Edge tuple) pairs for incoming edges

Return type:

Iterable[Tuple[int, Tuple[FrozenSet[Any], FrozenSet[Any]]]]

out_edges(vertices)#

Get outgoing edges for vertices.

Parameters:

vertices – Vertices to get outgoing edges for

Returns:

Iterator yielding (edge index, Edge tuple) pairs for outgoing edges

Return type:

Iterable[Tuple[int, Tuple[FrozenSet[Any], FrozenSet[Any]]]]

successors(vertices)#

Get successor vertices for multiple vertices.

Parameters:

vertices – Vertices to get successors for

Returns:

Iterable of successor vertices

Return type:

Iterable

predecessors(vertices)#

Get predecessor vertices for multiple vertices.

Parameters:

vertices – Vertices to get predecessors for

Returns:

Iterable of predecessor vertices

Return type:

Iterable

neighbors(vertex)#

Get neighbors of a vertex (ignoring edge direction).

Parameters:

vertex – Vertex to get neighbors for

Returns:

Iterable of neighbor vertices

Return type:

Iterable

is_hypergraph()#

Check if the graph is a hypergraph.

Returns:

True if the graph is a hypergraph, False otherwise

Return type:

bool

property E: Tuple[Tuple[FrozenSet[Any], FrozenSet[Any]], ...]#

Edges in the graph.

Returns:

Tuple of edges

property V: Tuple[Any, ...]#

Vertices in the graph.

Returns:

Tuple of vertices

property vertices: Tuple[Any, ...]#

Vertices in the graph.

Returns:

Tuple of vertices

Note

Alias for V property

property nv: int#

Number of vertices in the graph.

Returns:

Number of vertices

Note

Alias for num_vertices property

property ne: int#

Number of edges in the graph.

Returns:

Number of edges

Note

Alias for num_edges property

property shape: Tuple[int, int]#

Shape of the graph (number of vertices, number of edges).

Returns:

Tuple of number of vertices and number of edges

add_edge(source, target, type=EdgeType.DIRECTED, edge_source_attr=None, edge_target_attr=None, **kwargs)#

Add edge to the graph.

Parameters:
  • source (Any | Iterable[Any]) – Source vertices

  • target (Any | Iterable[Any]) – Target vertices

  • type (EdgeType | None) – Edge type

  • edge_source_attr (Attributes | None) – Optional attributes for source vertices

  • edge_target_attr (Attributes | None) – Optional attributes for target vertices

  • **kwargs – Additional edge attributes

Returns:

Index of the new edge

Return type:

int

add_edges(edges, type=EdgeType.DIRECTED, **kwargs)#

Add multiple edges to the graph.

Parameters:
  • edges (Iterable) – Iterable of (source, target) pairs

  • type (EdgeType) – Edge type

  • **kwargs – Additional edge attributes

Returns:

List of indices of the new edges

Return type:

List[int]

add_vertex(v, **kwargs)#

Add vertex to the graph.

Parameters:
  • v (Any) – Vertex to add

  • **kwargs – Additional vertex attributes

Returns:

Index of the new vertex

Return type:

int

add_vertices(vertices, **kwargs)#

Add multiple vertices to the graph.

Parameters:
  • vertices (List) – List of vertices to add

  • **kwargs – Additional vertex attributes

Returns:

List of indices of the new vertices

Return type:

List[int]

get_vertex_incidence_matrix_as_lists(values=False)#

Get vertex incidence matrix as lists.

Parameters:

values (bool) – Whether to include edge values in the matrix

Returns:

Tuple of data, (row indices, column indices)

vertex_incidence_matrix(values=False, sparse=False)#

Get vertex incidence matrix.

Parameters:
  • values (bool) – Whether to include edge values in the matrix.

  • sparse (bool) – If True, returns the matrix as a sparse CSR matrix (default is False, which returns a dense NumPy array).

Returns:

Vertex incidence matrix as a numpy array or a sparse matrix.

bfs(starting_vertices, reverse=False, undirected=False)#

Perform breadth-first search (BFS) traversal.

Parameters:
  • starting_vertices (Any) – Starting vertices for BFS

  • reverse (bool) – Whether to traverse in reverse direction

  • undirected (bool) – Whether to treat edges as undirected

Returns:

Dictionary mapping vertices to their BFS layer

Return type:

Dict[Any, int]

prune(source=None, target=None)#

Prune the graph to include only reachable vertices.

Parameters:
  • source (List | None) – Source vertices to start pruning from

  • target (List | None) – Target vertices to reach

Returns:

Pruned subgraph

Return type:

BaseGraph

plot(**kwargs)#

Plot the graph using Graphviz.

Renders the graph structure visually using Graphviz. Falls back to Viz.js rendering if SVG+XML rendering fails.

Parameters:

**kwargs – Additional plotting options passed to Graphviz

Returns:

Graphviz plot object

Raises:

OSError – If Graphviz rendering fails

plot_values(vertex_values=None, edge_values=None, vertex_props=None, edge_props=None, edge_indexes=None)#
to_graphviz(**kwargs)#

Convert graph to Graphviz representation.

Parameters:

**kwargs – Additional options for Graphviz conversion

Returns:

Graphviz object representing the graph structure

to_dot(**kwargs)#

Convert graph to DOT format.

Parameters:

**kwargs – Additional options for DOT conversion

Returns:

DOT representation of the graph

save(filename, compression='auto')#

Save graph to file using pickle serialization.

Parameters:
  • filename (str) – Path to save graph to

  • compression (str | None) – Optional compression format (‘auto’, ‘gzip’, ‘bz2’, ‘xz’, or None)

Raises:

ValueError – If filename is empty

Return type:

None

static load(filename, compression='auto')#

Load graph from a saved file.

Parameters:
  • filename (str) – Path to saved graph file

  • compression (str | None) – Optional compression format (‘auto’, ‘gzip’, ‘bz2’, ‘xz’, or None) If ‘auto’, will detect from file extension.

Returns:

Loaded graph instance

Return type:

BaseGraph

toposort()#

Perform topological sort on the graph using Kahn’s algorithm.

Returns:

List of vertices in topological order

Raises:

ValueError – If graph contains cycles

reachability_analysis(input_nodes, output_nodes, subset_edges=None, verbose=True, early_stop=False, expand_outputs=True, max_printed_outputs=10)#

Perform reachability analysis from input nodes to output nodes.

Parameters:
  • input_nodes – Starting nodes for analysis

  • output_nodes – Target nodes to reach

  • subset_edges – Optional subset of edges to consider

  • verbose – Whether to print progress information

  • early_stop – Stop when all outputs are reached

  • expand_outputs – Continue expanding from output nodes

  • max_printed_outputs – Max outputs to show in verbose mode

Returns:

Set of edge indices used in paths from inputs to outputs