flowy/timeindex.py

62 lines
2 KiB
Python
Raw Normal View History

2010-11-05 17:57:01 +00:00
#from pytables import FlowRecordsTable
#from pytables import create_table_file
#from tables import UIntAtom
from math import floor
#class TimeIndex(object):
# def __init__(self, start_time, delta, id_size_bytes=4):
# self.start_time = start_time
# self.delta = delta
# self.id_size = id_size_bytes
# self.index = self.get_index_file()
#
# def get_index_file(self):
# if self.index: return self.index
# create_table_file(self.file, {'t': UIntAtom(self.id_size)})
#
# self.index = FlowRecordsTable(self.file)
# self.index.
# return self.index
class TimeIndex(object):
def __init__(self, interval=1000, maxsize=10**5):
self.interval = float(interval)
self.index = {}
self.maxsize = maxsize
self.mintime = float('inf') # later replaced with int
self.maxtime = float('-inf') # later replaced with int
@property
def len(self):
return len(self.index)
2014-06-26 06:47:04 +00:00
def get_interval(self, First, Last):
start = int(floor(First/self.interval))
end = int(floor(Last/self.interval) + 1)
2010-11-05 17:57:01 +00:00
return xrange(start, end)
def update_min_max_time(self, record):
2014-06-26 06:47:04 +00:00
if self.mintime > record.First:
self.mintime = record.First
if self.maxtime < record.Last:
self.maxtime = record.Last
2010-11-05 17:57:01 +00:00
def get_total_interval(self):
return self.get_interval(self.mintime, self.maxtime)
def add(self, record):
2014-06-26 06:47:04 +00:00
interval = self.get_interval(record.First, record.Last)
2010-11-05 17:57:01 +00:00
for i in interval:
self.index.setdefault(i, set()).add(record.rec_id)
self.update_min_max_time(record)
if self.len > self.maxsize:
print "Warning large index"
2014-06-26 06:47:04 +00:00
def get_interval_records(self, First, Last):
2010-11-05 17:57:01 +00:00
res = set()
2014-06-26 06:47:04 +00:00
for i in self.get_interval(First, Last):
2010-11-05 17:57:01 +00:00
res |= self.index.setdefault(i, set()) # set union
return sorted(res)