Is there any built-in API available in networkX to find balanced triangles and unbalanced triangles a "signed network"
Asked
Active
Viewed 1,210 times
1 Answers
3
Here is a solution. First lets create a graph and draw it.
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)
Then we can use code from the following answer to extract triangles: Finding cycle of 3 nodes ( or triangles) in a graph. For each triangle we multiple the edge relationship values together. If there are an odd number of -1s, we have an unbalanced triangle. This code outputs a dictionary of all triangles, with value =1 if it is balanced, =-1 if unbalanced.
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)

Johannes Wachs
- 1,270
- 11
- 15