I am using the igraph library in python. I would like to know if there is a way of using strings as vertices indices. I know about the 'name' property and that I can write
g = igraph.Graph(directed=True)
g.add_vertex('hello')
g.add_vertex('world')
g.add_edge('hello','world')
and everything works fine. Except that if I add the same vertex twice, e.g.:
g = igraph.Graph(directed=True)
g.add_vertex('world')
g.add_vertex('hello')
g.add_vertex('hello')
two distinct vertices are created and if I now add an edge:
g.add_edge('hello','world')
the edge is added to the first vertex matching 'hello' as a name. This also suggests that such form of indexing has O(n) complexity instead of O(1) (i.e. the whole list of vertices is scanned until a vertex v such that v['name'] == 'hello' is found).
So I was thinking about keeping a mapping between vertices names and indexes, for example:
mapping = {}
g = igraph.Graph(directed=True)
g.add_vertex('hello')
mapping['hello'] = len(g.vs)-1
g.add_vertex('world')
mapping['world'] = len(g.vs)-1
g.add_edge(mapping['hello'],mapping['world'])
I assume this should work since I never delete vertices so I guess the indices should remain constant. It also has average speed O(1) for lookup which should be better than the previous solution. However I was wondering:
- am I always guaranteed that
g.vs[i].index == i? (i.e. can I always use the position of a vertex in the vs array to refer to that vertex in functions likeadd_edge()?) - am I always guaranteed that when I add a new vertex to the graph its index is going to be
len(g.vs)-1?
EDIT: Same questions about edges: am I guaranteed that I will find the last added edge in g.es[len(g.es)-1]?