Utility methods for HORNET. Includes functions to deal with time (hornet.util.make_periods()) and decorators (hornet.util.memoize())
Module author: John Paulett <john.paulett -at- vanderbilt.edu>
Simple data structure representing a period in time with a start and end. This class provides formatting for the period.
>>> p = Period(datetime.date(2008, 1, 1), datetime.date(2008, 1, 8))
>>> repr(p)
'<Period(datetime.date(2008, 1, 1), datetime.date(2008, 1, 8))>'
>>> str(p)
'20080101-20080108'
Computes the integral of data. data is a dictionary. Returns a dictionary with the same keys as in data. It is assumed that all values greater or equal than a given key before the next highest key value are the same as the value at the given key.
>>> data = {0.25: 1, 0.5: 2, 0.75: 4, 1: 8}
>>> accumulate(data)
{0.25: 1, 0.5: 3, 0.75: 7, 1: 15}
Finds the count of each value in list. Returns a dictionary with the key as a unique value, and the value as the number of occurrences of that value in the values.
>>> count_unique([1, 2, 3, 1, 1, 2])
{1: 3, 2: 2, 3: 1}
Applies the function value_func to every value in the dictionary, data. Returns a new copy of the dict, leaving the original unmodified.
>>> dict_apply({'a': 1, 'b': 'c'}, lambda x: x * 3)
{'a': 3, 'b': 'ccc'}
Takes an iterable, such as a list, and pulls out the attribute of each object, specified by attr. Returns a list.
>>> extract_attr([object(), list(), dict()], '__class__')
[<type 'object'>, <type 'list'>, <type 'dict'>]
With a start and an end date, splits the time range up into sub-periods of size period_size. start and end must be date objects and period_size must be a timedelta object
>>> import datetime
>>> make_periods(datetime.date(2008, 1, 1), datetime.date(2008, 1, 9), datetime.timedelta(7))
[<Period(datetime.date(2008, 1, 1), datetime.date(2008, 1, 8))>, <Period(datetime.date(2008, 1, 8), datetime.date(2008, 1, 9))>]
Decorator that caches a function’s return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. From the Python Decorator Library and the decorator module
>>> i = iter([1, 10, 100])
>>> f = memoize(lambda x: x * i.next())
>>> f(4)
4
>>> f(7)
70
>>> f(4) # notice how 4 * 1 is returned and not 4 * 100
4