Creating a weighted graph

Asked by Raj Kumar Pan

I am using igraph python interface. I have a list of edges say [(a,b,3.0),(c,d,4.0),(a,c,5.0)]. The third variable is the weight of the link. How can I make a weighted graph from this list. I know that if the list is in a file then I can use Graph.Read_Ncol(). However, is there a way to directly creating a graph instead of writing it to a file?

Thanks,

Question information

Language:
English Edit question
Status:
Solved
For:
igraph Edit question
Assignee:
Tamás Nepusz Edit question
Solved by:
Tamás Nepusz
Solved:
Last query:
Last reply:
Revision history for this message
Best Tamás Nepusz (ntamas) said :
#1

I think the easiest is as follows:

1. Recode the vertex names into unique integer IDs. igraph has a helper class called UniqueIdGenerator which is designed exactly for this.
2. Split the list into a list of vertex pairs and a list of weights.
3. Create the graph using the "ordinary" Graph constructor.

Something like this:

l = [("a", "b", 3.0), ("c", "d", 4.0), ("a", "c", 5.0)]

ids=UniqueIdGenerator()
edgelist = [(ids[u], ids[v]) for u, v, _ in l]
weights = [w for _, _, w in l]
g=Graph(edgelist, vertex_attrs=dict(name=ids.values()), edge_attrs=dict(weight=weights))

I will probably add a helper function for this in the next release.

Revision history for this message
Raj Kumar Pan (rajkrpan) said :
#2

Thanks a lot. I did not know of UniqueIdGenerator. A helper function would be really great.

Revision history for this message
Raj Kumar Pan (rajkrpan) said :
#3

Thanks Tamás Nepusz, that solved my question.

Revision history for this message
Tamás Nepusz (ntamas) said :
#4

For the record, I have added a function called Graph.TupleList which does something like this. It will be available from igraph 0.6.1. E.g.:

g=Graph.TupleList([("a", "b", 3.0), ("c", "d", 4.0), ("a", "c", 5.0)], weights=True)