简体   繁体   中英

Select individual edges by source-target-tuple in python igraph

For a given graph g I'd like to change a property, say 'color' , for a given individual edge, which can be done like this

g.es[0]['color'] = some_color

However, this requires to know the list index of the edge, here 0 . Assume I only know the source-target-tuple of the edge, say (0,1) , is there a simple way to do the above using that tuple, or do I have to iterate throught the whole graph to determine the edge index?

Use the get_eid method of the graph object to get the ID of an arbitrary edge between two given vertices; eg:

g.es[g.get_eid(0, 1)]["color"] = "red"

You can build a dict of all source-target tuples pointing at the indexes, this would increase access time greatly. Of course it only makes sense if you want to do that often; otherwise iterating should be faster.

d = { node['source-target']: index for index, node in enumerate(g.es) }
print d[(0,1)]  # will print 0

Note: I haven't found the igraph stuff, so I have to guess how to get the source-target tuple out of the nodes; my guess was node['source-target'] which you probably will have to adjust.

Note also that there might be more than one node which has the same source-target tuple. In this case you will get only one of them. If you need all (as a list for instance), we can change that. Just specify more clearly :)

The fastest way I've found is to do it this way:

g.es.find(_between=((v_src.index,), (v_dest.index,)))

Yes, it is weird... the source and target in the _between tuple are tuples themselves (and if you use search instead of find , and multiple start/end vertices are specified, it will return a list of all qualifying edges). If you have an igraph.Vertex, you can get the indices like that; if you already have indices, just use them directly.

There is also a way to do this:

# DON'T DO THIS!
g.es.find(_source=v_src.index, _target=v_dest.index)

but for some reason, that is a couple of orders of magnitude (!) slower...

In [23]: %timeit G.g.es.find(_between=((0,), (4,)))
10000 loops, best of 3: 128 µs per loop

In [24]: %timeit G.g.es.find(_source=0, _target=4)
100 loops, best of 3: 1.72 ms per loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM