Search code examples
pythonigraphedge-list

iGraph Python, convert edge list to tuple and add.edges


I have a Graph G1 with 50 nodes and 100 edges. All edges are weighted. I have created a list of edges (sorted by a pre-defined order, removing specific edges with large values), and they are indexed like:

Edgelist: [75, 35, 32, 1, ...]

I want to add the edges to a different graph G2 in batches of 10 (to save computation time), but add.edges seems to want a tuple list of vertex pairs. So,

  1. How can I convert the Edge list above into a tuple list, e.g. [(40,2),(10,1),(10,11),(0,0),...]. I've tried a loop with G1.es[edge].tuple, but iGraph reads the [edge] variable as an attribute, whereas if you just write G1.es[75].tuple, it works fine.

  2. How can I look up weights from G1 and add them to G2 in batches of 10?


Solution

    1. You have to be aware that indexing G1.es with a single number will return an object of type Edge, while indexing it with a list of numbers will return an object of type EdgeSeq. Edge objects have a property named tuple, but EdgeSeq objects don't, so that's why G1.es[edgelist].tuple does not work However, you can do this:

      sorted_tuples = [edge.tuple for edge in G1.es[edgelist]]
      

      You can also extract the value of the weight attribute directly from the EdgeSeq object:

      sorted_weights = G1.es[edgelist]["weight"]
      
    2. Here you can make use of the fact that if G2 has M edges and you add m extra edges, then the IDs of these new edges will be in the range from M (inclusive) to M+m (exclusive):

      M = G2.ecount()
      m = len(sorted_tuples)
      G2.add_edges(sorted_tuples)
      G2.es[M:(M+m)] = sorted_weights