|
|
@@ -115,6 +115,9 @@ class NilmDB(object): |
|
|
|
|
|
|
|
self.opened = True |
|
|
|
|
|
|
|
# Cached intervals |
|
|
|
self._cached_iset = {} |
|
|
|
|
|
|
|
def __del__(self): |
|
|
|
if "opened" in self.__dict__: # pragma: no cover |
|
|
|
fprintf(sys.stderr, |
|
|
@@ -148,22 +151,40 @@ class NilmDB(object): |
|
|
|
|
|
|
|
def _get_intervals(self, stream_id): |
|
|
|
""" |
|
|
|
Return an IntervalSet corresponding to the given stream ID. |
|
|
|
Return a mutable IntervalSet corresponding to the given stream ID. |
|
|
|
""" |
|
|
|
# Load from database if not cached |
|
|
|
if stream_id not in self._cached_iset: |
|
|
|
iset = IntervalSet() |
|
|
|
result = self.con.execute("SELECT start_time, end_time, " |
|
|
|
"start_pos, end_pos " |
|
|
|
"FROM ranges " |
|
|
|
"WHERE stream_id=?", (stream_id,)) |
|
|
|
try: |
|
|
|
for (start_time, end_time, start_pos, end_pos) in result: |
|
|
|
# XXX TODO: store start_pos, end_pos too |
|
|
|
iset += Interval(start_time, end_time) |
|
|
|
except IntervalError as e: # pragma: no cover |
|
|
|
raise NilmDBError("unexpected overlap in ranges table!") |
|
|
|
self._cached_iset[stream_id] = iset |
|
|
|
# Return cached value |
|
|
|
return self._cached_iset[stream_id] |
|
|
|
|
|
|
|
def _add_interval(self, stream_id, interval, start_pos, end_pos): |
|
|
|
""" |
|
|
|
Add interval to the internal interval cache, and to the database. |
|
|
|
Note: arguments must be ints (not numpy.int64, etc) |
|
|
|
""" |
|
|
|
# Could cache these, if it's a performance bottleneck |
|
|
|
iset = IntervalSet() |
|
|
|
result = self.con.execute("SELECT start_time, end_time " |
|
|
|
"FROM ranges " |
|
|
|
"WHERE stream_id=?", (stream_id,)) |
|
|
|
# Ensure this stream's intervals are cached, and add the new |
|
|
|
# interval to that cache. |
|
|
|
iset = self._get_intervals(stream_id) |
|
|
|
try: |
|
|
|
for (start, end) in result: |
|
|
|
iset += Interval(start, end) |
|
|
|
# XXX TODO: Intervals should hold start_pos, end_pos too |
|
|
|
iset += Interval(interval.start, interval.end) |
|
|
|
except IntervalError as e: # pragma: no cover |
|
|
|
raise NilmDBError("unexpected overlap in ranges table!") |
|
|
|
return iset |
|
|
|
raise NilmDBError("new interval overlaps existing data") |
|
|
|
|
|
|
|
def _add_interval(self, stream_id, interval, start_pos, end_pos): |
|
|
|
# Arguments must be ints (not numpy.int64, etc) |
|
|
|
# Insert into the database |
|
|
|
self.con.execute("INSERT INTO ranges " |
|
|
|
"(stream_id,start_time,end_time,start_pos,end_pos) " |
|
|
|
"VALUES (?,?,?,?,?)", |
|
|
|