networkX中是否有任何内置的API可用,以找到“符号网络”中的平衡三角形和非平衡三角形
答案 0 :(得分:1)
这是一个解决方案。首先让我们创建一个图形并绘制它。
import networkx as nx
G = nx.Graph()
G.add_edges_from([(1,2),(2,3),(1,3),(2,4)], relationship=1)
G.add_edges_from([(3,4)], relationship=-1)
labels = {e[0:2]:e[2]['relationship'] for e in G.edges(data=True)}
layout = nx.spring_layout(G)
nx.draw(G,pos=layout, with_labels=True, node_size=300)
nx.draw_networkx_edge_labels(G,pos=layout, edge_labels=labels,font_size=15)
然后,我们可以使用以下答案中的代码来提取三角形: Finding cycle of 3 nodes ( or triangles) in a graph。对于每个三角形,我们将边缘关系值相乘在一起。如果奇数为-1,则我们有一个不平衡的三角形。此代码输出所有三角形的字典,如果平衡,则返回值= 1,如果不平衡,则返回值-1。
import numpy as np
triangles = [c for c in nx.cycle_basis(G) if len(c)==3]
triangle_types={}
for triangle in triangles:
tri=nx.subgraph(G,triangle)
#take the product of the edge relationships. If there are an odd number of -1s, the triangle is unbalanced.
triangle_types[tuple(tri.nodes())]=np.product([x[2]['relationship'] for x in tri.edges(data=True)])
print(triangle_types)