0

I have a graph with four nodes with two directional edges betweeen each node (a to b and b to a), so I use a multi Digraph. The graph already has the 'weight' attribute defined by default which for my case represent the capacity of each edge for traffic flow. I need to define two more attributes for each edge, let's say tcv1 and tcv2.

Being a beginner with Python and networkx I am not able to figure this out. Some google search took me here but I could not use it correctly.

add_attribute_to_edge(router_matrix, tmp_path[0][0], tmp_path[0][1], 'tcv1', traffic_cv[0])

I used code above where router_matrix is graph, tmp_path[x][x] will represent a node name like 'a' or 'b', tcv1 is the attribute and traffic_cv[0] in code will be an integer calculated. Printing tcv1 only gives {}.

Can someone suggest a solution or point out where I go wrong.

Community
  • 1
  • 1
Sanchayan Maity
  • 637
  • 6
  • 19

1 Answers1

1

You could use the add_edge function to add new attributes to existing edges in a MultiDiGraph, but you need to watch out for the key keyword (its value needs to be 0).

In my example I add the tcv1 attribute the first "a" -> "b" edge (I use your variable names and my example graph created with add_edges_from):

import networkx as nx

router_matrix = nx.MultiDiGraph()

# add two weighted edges ("a" -> "b" and "b" -> "a")
router_matrix.add_edges_from([
    ("a", "b", {"weight": 0.5}),
    ("b", "a", {"weight": 0.99})
    ])

# print list of edges with all data
print(router_matrix.edges(data=True))

tmp_path = [["a", "b"], ["b", "a"]]
traffic_cv = [42, 66]

# add "tcv1" for only the first edge of tmp_path
router_matrix.add_edge(tmp_path[0][0], tmp_path[0][1], key=0, tcv1=traffic_cv[0])

print(router_matrix.edges(data=True))

To add tcv1 to all edges, you could use router_matrix.edges() to iterate trough all edges (note that here I use the G[src_node][dest_node][key][attribute] syntax instead of add_edge):

# add new attribute to all edges
counter = 0
for src, dest in router_matrix.edges():
    router_matrix[src][dest][0]['tcv1'] = traffic_cv[counter]
    counter += 1

print(router_matrix.edges(data=True))
edo
  • 1,712
  • 1
  • 18
  • 19