Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding weights to MultiDiGraph edges

I have a multidigraph in which edges have no weight. I would like to add some weights

G=MultiDiGraph():

......

  for u, v, data in G.edges_iter(data=True):
     G.edge[u][v]['weight'] = None

And I get the following for the edges:

('08B', '09B', {}),
('08B', '09B', {}),
('08B', '09B', {}),
('08B', '09B', 1),
('03P', '05T', {}),
('03P', '05T', 1)]

That is, it adds weights only in one instance. How can I add weight to all edges?

like image 319
Aidis Avatar asked Dec 19 '25 01:12

Aidis


1 Answers

The issue you're having is that you access the attributes of edges using an additional dictionary in multi-graphs. In particular, each edge has a dictionary of copies, so you access the attributes for a given edge as follows:

G.edge[u][v][replicate][attr] = val

So if you wanted to update the attributes for all between a pair (u, v) of nodes, you could define a function like this:

def set_multi_edge_attr(u, v, attr, val):
    for repl in G.edge[u][v].keys():
       G.edge[u][v][repl][attr] = val

where repl represents the copy of an individual edge. Here's a simple example:

>>> import networkx as nx
>>> G = nx.MultiDiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (0, 1)])
>>> G.edges(data=True)
[(0, 1, {}), (0, 1, {}), (0, 1, {})]
>>> set_multi_edge_attr(0, 1, 'weight', 1)
>>> G.edges(data=True)
[(0, 1, {'weight': 1}), (0, 1, {'weight': 1}), (0, 1, {'weight': 1})]
like image 182
mdml Avatar answered Dec 20 '25 15:12

mdml