P-M P-M - 2 months ago 15
Python Question

Find minimum value of edge property for all edges connected to a given node

I have a network where each of my edges is labelled with a date. I want to now also label my vertices so that each vertex has a date assigned to it corresponding to the minimum date of all edges incident and emanating from it. Is there an inbuilt function to find this which would be faster than me looping over all vertices and then all edges for each vertex manually? In other words: I am after a function to find the minimum value of a given edge property for a given subset of edges.

My current code idea is:

lowest_year = 2016
for v in g.vertices():
for e in v.in_edges():
year = g.ep.year[e]
lowest_year = min(year,lowest_year)
for e in v.out_edges():
year = g.ep.year[e]
lowest_year = min(year,lowest_year)
g.vp.year[v]=lowest_year
lowest_year = 2016

Answer

There is hardly any solution that would not need to check all the edges to find the minimum.

You could however optimize your calls to min by making a single call on the entire data instead of multiple calls and you also wouldn't need lowest_year any longer:

from itertools import chain

for v in g.vertices():
    g.vp.year[v] = min(map(g.ep.year.__getitem__, chain(v.in_edges(), v.out_edges())))

Methods in_edges and out_edges both returns lists which you can easily merge with the + operator.

In a more general case, you would use itertools.chain when oblivious of the types you're merging, but + is better in this case since we know the items are lists.

Comments