简体   繁体   English

使用 networkx isomorphic 检查图是否相等

[英]Check graph equality using networkx isomorphic

I have two graphs as follows我有两个图表如下

import networkx as nx

G1, G2 = nx.DiGraph(), nx.DiGraph()
G1.add_edges_from([("s1", "s2"), ("s2", "s3"), ("s3", "s4")]) # G1: 1->2->3->4
G2.add_edges_from([("s1", "s2"), ("s2", "s3"), ("s3", "s7")]) # G2: 1->2->3->7

nx.is_isomorphic(G1, G2)

By definition, we know the above two graphs are isomorphic, so is_isomorphic returns True .根据定义,我们知道上面两个图是同构的,所以is_isomorphic返回True

However, I wish to check structure equality between two graphs, meaning nodes and edges are the same (but weights allow difference).但是,我希望检查两个图之间的结构相等性,这意味着节点和边是相同的(但权重允许不同)。 Since G1 and G2 have different last node, I am looking for the is_isomorphic function returning False .由于G1G2的最后一个节点不同,我正在寻找返回Falseis_isomorphic函数。

Q: Is it possible using is_isomorphic to identify the non-equality? Q:是否可以使用is_isomorphic来识别非等式?

PS I tried to use iso.categorical_node_match or iso.numerical_node_match or iso.numerical_edge_match as plug-in parameter in is_isomorphic :附言我试图在is_isomorphic中使用iso.categorical_node_matchiso.numerical_node_matchiso.numerical_edge_match作为插件参数:

  1. network: numerical_edge_match 网络:numerical_edge_match
  2. networkx: is_isomorphic networkx: is_isomorphic

But I am still not sure how to call these iso function correctly in node_match or edge_match.但我仍然不确定如何在 node_match 或 edge_match 中正确调用这些iso函数。

During comparison, node attributes are compared.在比较期间,比较节点属性。 By default, node attributes are a blank dictionary (and do not incorporate node label information).默认情况下,节点属性是一个空白字典(并且不包含节点标签信息)。 A quick way to fix that is to use nx.convert_node_labels_to_integers and specify the key for label attributes:一种快速解决方法是使用nx.convert_node_labels_to_integers并指定标签属性的键:

G1_int = nx.convert_node_labels_to_integers(G1, label_attribute='label')
G2_int = nx.convert_node_labels_to_integers(G2, label_attribute='label')
print(G1_int.nodes[0])
# {'label': 's1'}

Now, to make sure that nx.is_isomorphic uses the relevant attribute information, we can specify custom node_match function:现在,为了确保nx.is_isomorphic使用相关的属性信息,我们可以指定自定义node_match函数:

nx.is_isomorphic(G1_int, G2_int, node_match = lambda x,y: x==y)
# False 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM