Note

This is the documentation for the current state of the development branch of rustworkx. The documentation or APIs here can change prior to being released.

rustworkx.PyGraph.compose#

PyGraph.compose(other, node_map, /, node_map_func=None, edge_map_func=None)#

Add another PyGraph object into this PyGraph

Parameters:
  • other (PyGraph) – The other PyGraph object to add onto this graph.

  • node_map (dict) –

    A dictionary mapping node indices from this PyGraph object to node indices in the other PyGraph object. The keys are a node index in this graph and the value is a tuple of the node index in the other graph to add an edge to and the weight of that edge. For example:

    {
        1: (2, "weight"),
        2: (4, "weight2")
    }
    

  • node_map_func – An optional python callable that will take in a single node weight/data object and return a new node weight/data object that will be used when adding an node from other onto this graph.

  • edge_map_func – An optional python callabble that will take in a single edge weight/data object and return a new edge weight/data object that will be used when adding an edge from other onto this graph.

Returns:

new_node_ids: A dictionary mapping node index from the other PyGraph to the equivalent node index in this PyDAG after they’ve been combined

Return type:

dict

For example, start by building a graph:

import os
import tempfile

import pydot
from PIL import Image

import rustworkx as rx
from rustworkx.visualization import mpl_draw

# Build first graph and visualize:
graph = rx.PyGraph()
node_a, node_b, node_c = graph.add_nodes_from(['A', 'B', 'C'])
graph.add_edges_from([(node_a, node_b, 'A to B'),
                      (node_b, node_c, 'B to C')])
mpl_draw(graph, with_labels=True, labels=str, edge_labels=str)
../_images/rustworkx.PyGraph.compose_0_0.png

Then build a second one:

# Build second graph and visualize:
other_graph = rx.PyGraph()
node_d, node_e = other_graph.add_nodes_from(['D', 'E'])
other_graph.add_edge(node_d, node_e, 'D to E')
mpl_draw(other_graph, with_labels=True, labels=str, edge_labels=str)
../_images/rustworkx.PyGraph.compose_1_0.png

Finally compose the other_graph onto graph

node_map = {node_b: (node_d, 'B to D')}
graph.compose(other_graph, node_map)
mpl_draw(graph, with_labels=True, labels=str, edge_labels=str)
../_images/rustworkx.PyGraph.compose_2_0.png