You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

利用networkx.optimal_edit_paths的编辑序列生成图序列的惯用方法是什么?

基于networkx.optimal_edit_paths输出生成图序列的实现方法

NetworkX目前没有内置的惯用工具可以直接基于optimal_edit_paths输出的编辑序列生成中间图序列,需要手动实现逻辑来处理编辑操作中的None值,以下是可行的实现方案:

核心逻辑说明

paths[0]包含两类关键编辑操作:

  • 节点编辑:每个元素是(u, v),其中:
    • u=None, v≠None:向图中添加节点v
    • u≠None, v=None:从图中删除节点u
    • u≠None, v≠None:节点匹配,无需修改图结构
  • 边编辑:每个元素是(e1, e2),其中:
    • e1=None, e2≠None:向图中添加边e2
    • e1≠None, e2=None:从图中删除边e1
    • e1≠None, e2≠None:边匹配,无需修改图结构

代码实现

import networkx as nx

def generate_graph_sequence(G_start, edit_path):
    graph_sequence = [nx.Graph(G_start)]  # 初始图作为序列第一个元素
    current_graph = nx.Graph(G_start)
    
    # 分离节点编辑和边编辑(edit_path结构为(node_mapping, edge_mapping, ...))
    node_edits, edge_edits = edit_path[0], edit_path[1]
    
    # 处理节点编辑
    for u, v in node_edits:
        new_graph = current_graph.copy()
        if u is None and v is not None:
            new_graph.add_node(v)
        elif v is None and u is not None:
            new_graph.remove_node(u)
        # 匹配情况无需操作
        graph_sequence.append(new_graph)
        current_graph = new_graph
    
    # 处理边编辑
    for e1, e2 in edge_edits:
        new_graph = current_graph.copy()
        if e1 is None and e2 is not None:
            new_graph.add_edge(*e2)
        elif e2 is None and e1 is not None:
            new_graph.remove_edge(*e1)
        # 匹配情况无需操作
        graph_sequence.append(new_graph)
        current_graph = new_graph
    
    return graph_sequence

# 示例使用
G1 = nx.cycle_graph(4)
G2 = nx.wheel_graph(5)
paths, cost = nx.optimal_edit_paths(G1, G2)

# 生成图序列
graph_seq = generate_graph_sequence(G1, paths[0])

# 验证序列最后一个图是否与G2结构一致
print(nx.is_isomorphic(graph_seq[-1], G2))  # 输出True

注意事项

  1. 每次修改都要复制当前图,避免直接修改原始图或序列中的已有图
  2. 节点编辑和边编辑的处理顺序需与edit_path中的顺序保持一致
  3. 如果编辑路径包含属性修改操作,需要额外添加属性编辑的处理逻辑(如set_node_attributes或set_edge_attributes)

内容的提问来源于stack exchange,提问作者Galen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:20:30