簡體   English   中英

如何使用NetworkX查找“有符號網絡”的平衡三角形和不平衡三角形?

[英]How to find balanced triangles and unbalanced triangles of a “signed network” using NetworkX?

networkX中是否有任何內置的API可用,以找到“符號網絡”中的平衡三角形和不平衡三角形

這是一個解決方案。 首先讓我們創建一個圖形並繪制它。

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)

在此處輸入圖片說明

然后,我們可以使用以下答案中的代碼來提取三角形: 查找圖中的3個節點(或三角形)的周期 對於每個三角形,我們將邊緣關系值相乘在一起。 如果奇數為-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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM