Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 458
giorgioca Avatar asked Jun 05 '15 07:06

giorgioca


People also ask

How do you plot a graph in an Igraph in Python?

First, you will need to install python-igraph if you do not have it already installed. You can use pip. You will also need to install cairocffi to plot the graphs. If you are using a Python package manager such as Anaconda or Miniconda, you can install python-igraph using the conda install command.

How do you connect edges in Python?

Start from a random source vertex, and then calculate the minimum weight from that vertex to all others. Then, one by one go to every vertex that the current vertex isn't connect to, and connect them with the minimum weight you calculated. Repeat this same process for all the other nodes.


2 Answers

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.

like image 132
deeenes Avatar answered Sep 22 '22 22:09

deeenes


Here is one simple way to get edge information from an igraph object using built-in function get.data.frame() in R (I did not notice the question was asking about python, sorry):

edges_data_frame <- get.data.frame(your_igraph, what = "edges")

The first two columns of edges_data_frame will be "from" and "to". The following columns will be other attributes of the edges if there are.

like image 45
TianLe Ma Avatar answered Sep 24 '22 22:09

TianLe Ma