ragraph.graph#

Graph module. Contains Graph class definitions.

The Graph class is the core of this package. It is the internal storage format that facilitates all conversions. These class definitions are designed to accommodate a wide range of graph formats.

Module Contents#

Classes#

Graph

Graph of Node objects and Edge objects between them.

GraphView

A view on a Graph object. It works exactly like the Graph object,

Attributes#

np

ragraph.graph.np#
exception ragraph.graph.ConsistencyError#

Bases: Exception

Common base class for all non-exit exceptions.

class ragraph.graph.Graph(nodes: Optional[Iterable[ragraph.node.Node]] = None, edges: Optional[Iterable[ragraph.edge.Edge]] = None, add_parents: bool = False, add_children: bool = False, name: Optional[str] = None, kind: Optional[str] = None, labels: Optional[List[str]] = None, weights: Optional[Dict[str, Union[int, float]]] = None, annotations: Optional[Union[ragraph.generic.Annotations, Dict[str, Any]]] = None, uuid: Optional[Union[str, uuid.UUID]] = None)#

Bases: ragraph.generic.Metadata

Graph of Node objects and Edge objects between them.

Parameters:
  • nodes – Iterable of graph nodes.

  • edges – Iterable of graph edges.

  • add_parents – Recursively add parent nodes of the provided nodes.

  • add_children – Recursively add child nodes of the provided nodes.

  • name – Instance name. Given a UUID if none provided.

  • kind – Kind or main category of this instance.

  • labels – Labels categorizing this instance.

  • weights – Dictionary of weights attached to this instance.

  • annotations – Miscellaneous properties of this instance.

  • uuid – Fixed UUID if desired, generated when left set to None.

property nodes: List[ragraph.node.Node]#

Nodes as a list.

property node_count: int#

Number of nodes in the graph.

property node_list: List[ragraph.node.Node]#

Nodes as a list.

property node_dict: Dict[str, ragraph.node.Node]#

Node dictionary by node name.

property node_uuid_dict: Dict[uuid.UUID, ragraph.node.Node]#

Node dictionary by node UUID.

property node_gen: Generator[ragraph.node.Node, None, None]#

Yield nodes.

property edges: List[ragraph.edge.Edge]#

Edges as a list.

property edge_list: List[ragraph.edge.Edge]#

Edges as a list.

property edge_dict: Dict[str, ragraph.edge.Edge]#

Edge dictionary by edge name.

property edge_uuid_dict: Dict[uuid.UUID, ragraph.edge.Edge]#

Edge dictionary by node UUID.

property directed_edges: Dict[str, Dict[str, List[ragraph.edge.Edge]]]#

Nested edge dictionary from source name to target name to a list of edges.

property reversed_edges: Dict[str, Dict[str, List[ragraph.edge.Edge]]]#

Nested edge dictionary from target name to source name to a list of edges.

property edge_gen: Generator[ragraph.edge.Edge, None, None]#

Yield edges.

property edge_count: int#

Number of edges in the graph.

property node_kinds: List[str]#

List of unique node kinds in the graph.

property edge_kinds: List[str]#

List of unique edge kinds in the graph.

property node_weight_labels: List[str]#

List of unique node weight labels in the graph.

property edge_weight_labels: List[str]#

List of unique edge weight labels in the graph.

property node_labels: List[str]#

Alphabetically sorted list of unique node labels in the graph.

property edge_labels: List[str]#

Alphabetically sorted list of unique edge labels in the graph.

property roots: List[ragraph.node.Node]#

List of roots in the graph.

property leafs: List[ragraph.node.Node]#

List of roots in the graph.

property max_depth: int#

Maximum node depth in the graph.

property json_dict: Dict[str, Any]#

JSON dictionary representation.

__str__() str#

Return str(self).

__repr__() str#

Return repr(self).

__eq__(other) bool#

Return self==value.

__getitem__(key: Union[str, uuid.UUID, Tuple[str, str]])#
__contains__(key: Union[str, uuid.UUID, Tuple[str, str]])#
__copy__()#
__deepcopy__(memo)#
add_node(node: ragraph.node.Node)#

Add a new node to this graph.

If the node instance already exists in the graph, it is ignored.

Parameters:

node – Node to add.

del_node(node: Union[ragraph.node.Node, str, uuid.UUID], inherit: bool = False)#

Remove a node and related edges from the graph by name or Node instance.

Parameters:
  • node – Node to remove.

  • inherit – Whether to inherit hierarchy for underlying nodes to the parent.

add_edge(edge: ragraph.edge.Edge)#

Add a new edge to the graph. Source and target need to exist in the graph.

Parameters:

edge – Edge to add.

Raises:
  • A ValueError if the source or target doesn't exist or the edge instance

  • already does.

del_edge(edge: Union[ragraph.edge.Edge, str, uuid.UUID])#

Remove an edge from the graph.

get_kinds(elements: Union[Iterable[ragraph.node.Node], Iterable[ragraph.edge.Edge]]) List[str]#

Get an alphabetically sorted list of unique node/edge kinds in the graph.

get_nodes_by_kind(kind: str) List[ragraph.node.Node]#

Get nodes/edges by kind.

get_edges_by_kind(kind: str) List[ragraph.edge.Edge]#

Get edges by kind.

get_weight_labels(elements: Union[Iterable[ragraph.node.Node], Iterable[ragraph.edge.Edge]]) List[str]#

Get an alphabetically sorted list of unique labels of node/edge weights.

edges_from(source: Union[str, ragraph.node.Node]) Generator[ragraph.edge.Edge, None, None]#

Yield edges originating from a given source node.

targets_of(source: Union[str, ragraph.node.Node]) Generator[ragraph.node.Node, None, None]#

Yield target nodes of a given source node.

edges_to(target: Union[str, ragraph.node.Node]) Generator[ragraph.edge.Edge, None, None]#

Yield edges towards a given target node.

sources_of(target: Union[str, ragraph.node.Node]) Generator[ragraph.node.Node, None, None]#

Yield source nodes of a given target node.

edges_between(source: Union[str, ragraph.node.Node], target: Union[str, ragraph.node.Node], inherit: bool = False, loops: bool = True) Generator[ragraph.edge.Edge, None, None]#

Yield edges between source and target node.

Parameters:
  • sources – Source nodes.

  • targets – Target nodes.

  • inherit – Whether to include edges between descendants of given nodes.

  • loops – Whether to include self-loop edges.

edges_between_all(sources: Iterable[Union[str, ragraph.node.Node]], targets: Iterable[Union[str, ragraph.node.Node]], inherit: bool = False, loops: bool = True) Generator[ragraph.edge.Edge, None, None]#

Yield all edges between a set of source and a set of target nodes.

Parameters:
  • sources – Source nodes.

  • targets – Target nodes.

  • inherit – Whether to include edges between descendants of given nodes.

  • loops – Whether to include self-loop edges.

get_graph_slice(nodes: Optional[Iterable[ragraph.node.Node]] = None, edges: Optional[Iterable[ragraph.edge.Edge]] = None, inherit: bool = False) Graph#

Return the graph slice with only the given nodes and the edges between those.

Parameters:
  • nodes – Optional set of nodes to include in the new deep copy. Defaults to all.

  • edges – Optional set of edges to include in the new deep copy. Defaults to all between selected nodes.

  • inherit – Whether to include child nodes of the given nodes and edges between them (unless edges are explicitly specified).

Note

This returns a deepcopy, so the copied nodes and edges do NOT share any changes! All parent and child nodes not in the list are excluded.

get_node_selection(node_kinds: Optional[List[str]] = None, edge_kinds: Optional[List[str]] = None, depth: int = 2, selection_mode: str = 'dependent') List[ragraph.node.Node]#

Select specific nodes from this graph in a structured order.

Parameters:
  • node_kinds – The kind of nodes to be selected.

  • edge_kinds – The kind of edges to be selected.

  • depth – The maximum depth of node to be selected.

  • selection_mode – The selection mode. Either ‘dependent’ or ‘independent’.

Note

The selection mode argument determines how nodes of different kinds are selected. If the selection mode is set to ‘dependent’, the first node kind in the node_kinds list is considered to be the ‘lead node kind’. Nodes of different kind than the lead node kind, are only selected if they have a dependency with at least one of the selected nodes of the lead node kind. If the selection mode is set to ‘independent’ this dependency condition is dropped.

get_edge_selection(nodes: Optional[List[ragraph.node.Node]] = None, edge_kinds: Optional[List[str]] = None) List[ragraph.edge.Edge]#

Select specific edges from this graph.

Parameters:
  • nodes – The list of nodes between which the edges must be selected.

  • edge_kinds – The kinds of edges to be selected.

Returns:

List of selected edges.

get_node_and_edge_selection(node_kinds: Optional[List[str]] = None, edge_kinds: Optional[List[str]] = None, depth: int = 2, selection_mode: str = 'dependent') Tuple[List[ragraph.node.Node], List[ragraph.edge.Edge]]#

Select specific nodes and edges from this graph in a structured order.

Parameters:
  • node_kinds – The kind of nodes to be selected.

  • edge_kinds – The kind of edges to be selected.

  • depth – The maximum depth of node to be selected.

  • selection_mode – The selection mode. Either ‘dependent’ or ‘independent’.

Note

The selection mode argument determines how nodes of different kinds are selected. If the selection mode is set to ‘dependent’, the first node kind in the node_kinds list is considered to be the ‘lead node kind’. Nodes of different kind than the lead node kind, are only selected if they have a dependency with at least one of the selected nodes of the lead node kind. If the selection mode is set to ‘independent’ this dependency condition is dropped.

get_hierarchy_dict(roots: Optional[List[ragraph.node.Node]] = None, levels: Optional[int] = None)#

Return a dictionary of the (partial) hierarchical node structure.

Parameters:
  • roots – Root nodes of the hierarchy to calculate.

  • levels – Number of levels to include below the roots.

get_adjacency_matrix(nodes: Optional[Union[List[ragraph.node.Node], List[str]]] = None, inherit: bool = False, loops: bool = False, only: Optional[List[str]] = None) Union[numpy.ndarray, List[List[float]]]#

Convert graph data into a numerical adjacency matrix.

Parameters:
  • nodes – Optional list of nodes for which to get the adjacency matrix.

  • inherit – Whether to count weights between children of the given nodes.

  • loops – Whether to calculate self-loops from a node to itself.

  • only – Optional subset of edge weights to consider. See Edge for default edge weight implementation.

Returns:

Adjacency matrix as a 2D numpy array if numpy is present. Otherwise it will return a 2D nested list.

get_mapping_matrix(rows: Optional[Union[List[ragraph.node.Node], List[str]]] = None, cols: Optional[Union[List[ragraph.node.Node], List[str]]] = None, inherit: bool = False, loops: bool = False, only: Optional[List[str]] = None) Union[numpy.ndarray, List[List[float]]]#

Convert graph data into a numerical mapping matrix.

Parameters:
  • graph – Graph to fetch data from.

  • rows – Nodes representing the matrix rows.

  • cols – Nodes representing the matrix columns if different from the rows.

  • inherit – Whether to count weights between children of the given nodes.

  • loops – Whether to calculate self-loops from a node to itself.

  • only – Optional subset of edge weights to consider. See Edge for default edge weight implementation.

Returns:

Adjacency matrix as a 2D numpy array if numpy is present. Otherwise it will return a 2D nested list.

get_ascii_art(nodes: Optional[List[ragraph.node.Node]] = None, edge: str = 'X', diag: str = '■', show: bool = True) Optional[str]#

Get a unicode ASCII art representation of a binary adjacency matrix for a given set of nodes.

Parameters:
  • nodes – Nodes to include in the art.

  • edge – Mark to use when there’s an edge between nodes. (X by default)

  • diag – Mark to use on the diagonal.

  • show – Whether to directly print the ASCII art.

Returns:

ASCII art representation of this graph.

as_dict(use_uuid: bool = False) Dict[str, Any]#

Return a copy as a (serializable) dictionary.

Parameters:

use_uuid – Whether to use UUIDs instead of names.

Returns:

Node names or UUIDs to Node dictionaries. kind: Kind as str. labels: Labels as list of str. weights: Weights as dict. annotations: Annotations as a dictionary. uuid: UUID as str if toggled.

Return type:

nodes

check_consistency(raise_error: bool = True) bool#

Check the consistency of this graph.

Parameters:

raise_error – Whether to raise an error instead of returning a bool.

Returns:

Whether nodes aren’t their own ancestor/descendant and if all their children and parents exist in the graph. Raises an error for inconsistencies if raise_error is set to True.

class ragraph.graph.GraphView(graph: Graph, view_func: Optional[Callable[[Any], Tuple[Union[Iterable[ragraph.node.Node], Dict[str, ragraph.node.Node]], Union[Iterable[ragraph.edge.Edge], Dict[str, ragraph.edge.Edge]]]]] = None, view_kwargs: Optional[Dict[str, Any]] = None)#

Bases: Graph

A view on a Graph object. It works exactly like the Graph object, except for that the nodes and edges are filtered according to the view function.

Parameters:
  • graph – Graph to provide a view on.

  • view_func – View function that filters the Graph’s nodes and edges.

  • view_kwargs – Optional arguments to pass to the view function.

property graph: Graph#

Graph to provide a view on.

property view_func: Optional[Callable[[Any], Tuple[Union[Iterable[ragraph.node.Node], Dict[str, ragraph.node.Node]], Union[Iterable[ragraph.edge.Edge], Dict[str, ragraph.edge.Edge]]]]]#

View function that filters the Graph’s nodes and edges.

property view_kwargs: Dict[str, Any]#

Optional arguments to pass to the view function.

property _nodes: Optional[Dict[str, ragraph.node.Node]]#
property node_uuid_dict: Optional[Dict[uuid.UUID, ragraph.node.Node]]#

Node dictionary by node UUID.

property _edges: Optional[Dict[str, ragraph.edge.Edge]]#
property edge_uuid_dict: Optional[Dict[uuid.UUID, ragraph.edge.Edge]]#

Edge dictionary by node UUID.

property _directed_edges: collections.defaultdict#
property _reversed_edges: collections.defaultdict#
update(**kwargs)#

Apply the set view function with arguments.

proxy()#

Undo any filtering and just set this view to proxy the Graph 1:1.

reset()#

Reset the private properties after the original graph might have changed.

add_node(node: ragraph.node.Node)#

Add a new node to this graph.

If the node instance already exists in the graph, it is ignored.

Parameters:

node – Node to add.

del_node(node: Union[ragraph.node.Node, str, uuid.UUID], inherit: bool = False)#

Remove a node and related edges from the graph by name or Node instance.

Parameters:
  • node – Node to remove.

  • inherit – Whether to inherit hierarchy for underlying nodes to the parent.

add_edge(edge: ragraph.edge.Edge)#

Add a new edge to the graph. Source and target need to exist in the graph.

Parameters:

edge – Edge to add.

Raises:
  • A ValueError if the source or target doesn't exist or the edge instance

  • already does.

del_edge(edge: Union[ragraph.edge.Edge, str, uuid.UUID])#

Remove an edge from the graph.