1
votes

Suppose we have a list with the edges, and we created with graph with igraph:

links = [[1, 2], [1, 3], [2, 4], [1, 2]]
g = ig.Graph()
for link in links:
    g.add_vertices(link)
g.add_edges(links)

print(g)
# IGRAPH UN-- 8 4 --
# + attr: name (v)
# + edges (vertex names):
# 2--1, 2--3, 1--2, 2--1

2 -- 1 is repeated. How can you create the graph to get the edge weights?

2

2 Answers

1
votes

According to igraph documentation, edges can be repeated, so, if you don't want edges duplicates, you need to remove them by your own.

This piece of code shows how to set weights (or any property you want) to edges and how to read then.

Creation of the graph

import igraph as ig

links = [[1, 2], [1, 3], [2, 4], [1, 2]]
vertices = [v for s in links for v in s]  # = [1,2,1,3,2,4,1,2]
g = ig.Graph()
g.add_vertices(vertices)
for l in links:
  g.add_edge(l[0], l[1], weight=0.5*l[0]*l[1]) # weight value is just an example

print(g)

The links list is flattered in order to get a vertices list. Not that vertices cannot be duplicated, hence there's no need to explicitly remove the duplicates elements in them.

You can specify any property you want add to the edge by specifying the relative keyword argument (weight=0.5*l[0]*l[1]).

Retriving Edges infos

You retrive the weights by simply e['weight'] where e is a single edge (igraph.Edge object). In this example it's shown how to loop over the edges set.

print("\nEdges\n")
for e in g.es():
  print("source: %s target: %d" % (e.source, e.target))
  print("multiplicity %d" % (g.count_multiple(e)))
  print("weight %f\n" % e['weight'])

The output is this:

Edges

source: 1 target: 2
multiplicity 2
weight 1.000000

source: 1 target: 3
multiplicity 1
weight 1.500000

source: 2 target: 4
multiplicity 1
weight 4.000000

source: 1 target: 2
multiplicity 2
weight 1.000000

For further details, refer to the documentation of igraph: igraph.Graph, igraph.Vertex and igraph.Edge

0
votes

I have code for this that looks for an edge to see if it already exists in the graph. So, it's something like:

edgelist = []
weights = []
for e in links:
    if e in edgelist:
        weights[edgelist.index(edge)] += 1
    else:
        edgelist.append(e)
        weights.append(1)

G = ig.Graph()
G.add_edges(edgelist)
G.es['weight'] = weights

Edit: And of course, you can access those weights with G.es['weight']