# HG changeset patch # User Paul Boddie # Date 1417102161 -3600 # Node ID 9d5fb143d88bc0c196afce85a1492a7513fb066e # Parent 875956967918ab99a97a0683b0b76a447084bdd4 Added functions to arrange periods in a grid/table layout. diff -r 875956967918 -r 9d5fb143d88b imiptools/period.py --- a/imiptools/period.py Tue Nov 25 23:14:03 2014 +0100 +++ b/imiptools/period.py Thu Nov 27 16:29:21 2014 +0100 @@ -78,4 +78,70 @@ else: return False +# Period layout. + +def get_scale(l): + + """ + Return an ordered time scale from the given list 'l' of tuples, with the + first two elements of each tuple being start and end times. + """ + + scale = {} + + for t in l: + start, end = t[:2] + + # Add a point and this event to the starting list. + + if not scale.has_key(start): + scale[start] = [], [] + scale[start][0].append(t) + + # Add a point and this event to the ending list. + + if not scale.has_key(end): + scale[end] = [], [] + scale[end][1].append(t) + + scale = scale.items() + scale.sort() + return scale + +def get_slots(l): + + """ + Return an ordered list of time slots from the given list 'l' of tuples, with + the first two elements of each tuple being start and end times. + + Each slot is a tuple containing a point in time for the start of the slot, + together with a list of parallel event tuples, each tuple containing the + original details of an event. + """ + + slots = [] + active = [] + + for point, (starting, ending) in get_scale(l): + + # Discard all active events ending at or before this start time. + + for t in ending: + i = active.index(t) + active[i] = None + + for t in starting: + try: + i = active.index(None) + active[i] = t + except ValueError: + active.append(t) + + while active and active[-1] is None: + active.pop() + + slots.append((point, active[:])) + + return slots + # vim: tabstop=4 expandtab shiftwidth=4