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