Search code examples
pythonpython-3.xgraphgraph-tool

How to access graph-tool edges? Why graph-tool edges don't have ids?


I am trying to access graph-tool edges. Example: Assume following graph.

from graph_tool.all import *

g = Graph()

eprop = g.new_edge_property("int")
g.edge_properties["distance"] = eprop

v0 = g.add_vertex()
v1 = g.add_vertex()
v2 = g.add_vertex()
v3 = g.add_vertex()
v4 = g.add_vertex()

e0 = g.add_edge(v0, v1) 
g.ep.distance[e0] = 1
e1 = g.add_edge(v1, v2)
g.ep.distance[e1] = 1
e2 = g.add_edge(v2, v3)
g.ep.distance[e2] = 1
e3 = g.add_edge(v3, v4)
g.ep.distance[e3] = 1
e4 = g.add_edge(v0, v4)
g.ep.distance[e4] = 1
e5 = g.add_edge(v0, v4)
g.ep.distance[e5] = 2

graph_draw(g, vertex_text=g.vertex_index, vertex_font_size=18, output_size=(200, 200), output="Test.png")

Image

There are two edges going from vertex 0 to vertex 4, one with length 1 and one with length 2.

My question is now how to select a specific edge, knowing the edge index. Sadly the graph-tool documentation now states: "...Edges cannot be directly obtained by its index, but if the source and target vertices of a given edge is known, it can be obtained with the edge() method..."

But after saving and loading the graph the variables v0,v1,... aswell as e0,e1,... are not available anymore. Trying to access the edges in the graph as the documentation states:

e = g.edge(0,4)
print(g.edge_index[e])
# > Returns 4

Just returns one of the edges from vertex 0 to vertex 4. How to access the other one? Knowing the edge indices are 4 and 5.

Thanks for help in advance!


Solution

  • You can get all parallel edges between nodes u and v with:

    g.edge(u, v, all_edges=True)
    

    You can iterate through all the edges with:

    for e in g.edges():
        print(e)
    

    And you can search for an edge with a specific index with:

    find_edge(g, g.edge_index, 33)