2

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
P-M
  • 1,279
  • 2
  • 21
  • 35

2 Answers2

2

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.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Running that I get the following error: `TypeError: unsupported operand type(s) for +: 'InEdgeIterator' and 'OutEdgeIterator'` It looks like the methods return iterators, not lists. – P-M Sep 16 '16 at 13:24
  • @P-M That docs is deprecated/misleading. Use `itertools.chain` instead. Answer has been updated. – Moses Koledoye Sep 16 '16 at 13:29
  • That now works and is far more elegant than my initial approach. Thank you very much. – P-M Sep 16 '16 at 13:39
0

This discussion (http://main-discussion-list-for-the-graph-tool-project.982480.n3.nabble.com/Find-minimum-value-of-edge-property-for-all-edges-connected-to-a-given-node-td4026722.html ) contains some useful suggestions for this topic too. It also highlights that there is actually an inbuilt method in graph-tool for finding the lowest value across all outgoing, say, edges (https://graph-tool.skewed.de/static/doc/graph_tool.html#graph_tool.incident_edges_op ):

g.vp.year = incident_edges_op(g, "out", "min", g.ep.year)

This would need repeating for the ingoing edges too and the minimum value between the two would then have to be found.

P-M
  • 1,279
  • 2
  • 21
  • 35