Reputation: 45
I have a network of Twitter users and their followers which I am modelling using NetworkX. I am trying to find a bidirectional link between users, i.e. if one node follows one of its neighbors, does that neighbor also follow that node.
Is there a built in function within NetworkX that would accomplish this? I tried using nx.reciprocity()
but it just returns a single value rather than a dictionary.
Upvotes: 3
Views: 2490
Reputation: 24104
You can determine if there is an edge connection between two nodes with networkx.Graph.has_edge
. This could then be used to test if there are opposite directed edges between nodes.
import networkx as nx
def have_bidirectional_relationship(G, node1, node2):
return G.has_edge(node1, node2) and G.has_edge(node2, node1)
G = nx.DiGraph()
G.add_edge(1, 2)
G.add_edge(2, 1)
G.add_edge(3, 4)
print(f"Nodes 1, 2 have opposite edges: {have_bidirectional_relationship(G, 1, 2)}")
print(f"Nodes 3, 4 have opposite edges: {have_bidirectional_relationship(G, 3, 4)}")
Nodes 1, 2 have opposite edges: True
Nodes 3, 4 have opposite edges: False
biconnections = set()
for u, v in G.edges():
if u > v: # Avoid duplicates, such as (1, 2) and (2, 1)
v, u = u, v
if have_bidirectional_relationship(G, u, v):
biconnections.add((u, v))
print(biconnections)
{(1, 2)}
Upvotes: 2