Reputation: 11
I created a graph using MultiDiGraph function in networkx and add Weights to Edges by Frequency of Edge Occurance. Now I am thinking to create a DiGraph graph and remove all the multiple edges and self-loops while still reserving the weight of multiple edges and self-loops. For example, if one of the edge occurs 5 times in the MultiDiGraph and the corresponding weight is 5, then the weight of this edge should still be 5 when creating the DiGraph and removing all the multiple edges and self-loops. How can do to make that happen? Thank you so much!
create two graphs separately
G1 = nx.MultiDiGraph()
G1.add_edges_from(
[(3,4),(3,5),(3,7),(4,7),(6,7),(4,5),(5,6),(3,6),(4,5),(4,5),(6,3),(3,3)],
color='red'
)
G2 = nx.MultiDiGraph()
G2.add_edges_from(
[(2,5),(2,8),(4,8),(6,8),(4,5),(4,5),(5,6),(2,6),(6,2)],
color='red'
)
Extract union of nodes and edges of these two graphs
union_nodes=list(set(list(G1.nodes)+list(G2.nodes)))
union_edges=list(list(G1.edges())+list(G2.edges()))
create a new graph combing these two graphs
G=nx.MultiDiGraph()
G.add_nodes_from(union_nodes)
G.add_edges_from(union_edges)
Adding weight to edge by the frequency of edge occurrence
from collections import Counter
c = Counter(G.edges())
for u, v, d in G.edges(data=True):
d['weight'] = c[u, v]
print(list(G.edges(data=True)))
nx.draw_networkx(G, width=[d['weight'] for _, _, d in G.edges(data=True)])
Upvotes: 1
Views: 742
Reputation: 3001
You can create the edges of the DiGraph
directly assigning them the corresponding weight:
c = Counter(G.edges())
simple_digraph = nx.DiGraph()
for u, v, d in G.edges(data=True):
# avoid repeating edges and self-loops
if not simple_digraph.has_edge(u, v) and u != v:
simple_digraph.add_edge(u, v, weight=c[u, v])
print(list(simple_digraph.edges(data=True)))
Output:
[
(2, 5, {'weight': 1}), (2, 8, {'weight': 1}), (2, 6, {'weight': 1}),
(5, 6, {'weight': 2}), (6, 7, {'weight': 1}), (6, 3, {'weight': 1}),
(6, 8, {'weight': 1}), (6, 2, {'weight': 1}), (3, 4, {'weight': 1}),
(3, 5, {'weight': 1}), (3, 7, {'weight': 1}), (3, 6, {'weight': 1}),
(4, 7, {'weight': 1}), (4, 5, {'weight': 5}), (4, 8, {'weight': 1})
]
Upvotes: 2