pythonigraphvertexedges

How to get the vertices from an edge using igraph in python?


I am looping through the edges of a graph with:

 for es in graph.es:
         .... 
         # v = []
         # v = es.vertices()?
         ...

What method can I use to get the source and the target vertices for each edge?


Solution

  • These are the very basic functionalities of igraph, described here thoroughly. If you iterate the <EdgeSeq> object (graph.es), you will go through all <Edge> objects (here edge). <Edge> has properties source and target. These are vertex ids, simply integers. You can get the corresponding <Vertex> object by graph.vs[]:

    for edge in graph.es:
      source_vertex_id = edge.source
      target_vertex_id = edge.target
      source_vertex = graph.vs[source_vertex_id]
      target_vertex = graph.vs[target_vertex_id]
      # using get_eid() you can do the opposite:
      same_edge_id = graph.get_eid(source_vertex_id, target_vertex_id)
      same_edge = graph.es[same_edge_id]
      # by .index you get the id from the Vertex or Edge object:
      source_vertex.index == source_vertex_id
      # True
      edge.index == same_edge_id
      # True
    

    Be aware if you have directed graph, otherwise source and target are simply two equivalent endpoints. With directed graphs you may use error = False with get_eid(), which then returns -1 in case there is no edge in the given direction between the vertices.