rustworkx.PyGraph.compose#

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

将另一个PyGraph对象添加到这个PyGraph中

Parameters:
  • other (PyGraph) – 要添加到此图上的另一个PyGraph对象。

  • node_map (dict[int, tuple[int, tuple[int, T]]]) –

    一个字典, 将当前PyGraph对象中的节点索引映射到 另一个PyGraph对象中的节点索引。 键是此图中的节点索引,值是一个元组, 包含要在另一图中添加边的目标节点索引 以及该边的权重。例如:

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

  • node_map_func (可调用对象) – 一个可选的Python可调用对象,它将接收单个节点权重/数据对象,并返回一个新的节点权重/数据对象,该对象将在从其他图添加节点到本图时使用。

  • edge_map_func (Callable) – 一个可选的Python可调用对象,该对象将接收单个边的权重/数据对象,并返回一个新的边的权重/数据对象,该对象将在向此图中添加来自其他对象的边时使用。

Returns:
new_node_ids: 一个字典,将另一个PyGraph中的节点索引映射到合并后该PyDAG中的等效节点索引
Return type:

字典[整型, 整型]

举个例子,首先构建一个图:

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

接下来构建第二个:

# 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

最后将 other_graph 合并到 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