-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtslite.py
1582 lines (1429 loc) · 46.4 KB
/
tslite.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/bin/python
''' tslite - Light and portable time series library
v2.0.0
22 April 2022
Author: Gunnar Leffler
'''
import sys, os, time, datetime, struct, math, re, json
import dateutil.parser as dateparser
from functools import wraps
##Load optional libraries
try:
import numpy as np
from math import factorial ## Factorial not in Jython 2.5.x math module
except:
_NUMPY_AVAILABLE = False
else:
_NUMPY_AVAILABLE = True
try:
import sqlite3
except:
_SQLITE3_AVAILABLE = False
else:
_SQLITE3_AVAILABLE = True
def requires_numpy(f):
""" Initial stab at the requires_numpy function - raises a warning """
@wraps(f)
def wrapper(*args, **kwargs):
if _NUMPY_AVAILABLE:
return f(*args, **kwargs)
else:
raise Warning("Numpy not available. Cannot call %s" % f.__name__)
return f(*args, **kwargs)
return wrapper
def requires_SQLITE3(f):
@wraps(f)
def wrapper(*args, **kwargs):
if _SQLITE3_AVAILABLE:
return f(*args, **kwargs)
else:
raise Warning("SQLITE3 not availible Cannot call %s" % f.__name__)
return f(*args, **kwargs)
return wrapper
def requires_heclib(f):
@wraps(f)
def wrapper(*args, **kwargs):
if _HECLIB_AVAILABLE:
return f(*args, **kwargs)
else:
raise Warning("HEC/Jython not available. Cannot call %s" % f.__name__)
return f(*args, **kwargs)
return wrapper
class timeseries:
def __init__(self, data=None):
'''"overloaded" timeseries constructor
expects data to be tuple of (datetime obj, observation value)
'''
self.status = "OK"
#Data is a nested list with the following structure [datetime, float value,``]
self.data = []
self.decimals = 3
if data != None:
#set internal data member to data and filter out blanks
for row in data:
if len(row) > 1:
if row[1] != None:
self.safeinsert(row[0], row[1])
#========================================================================
# IO and data manipulation methods
#========================================================================
def __str__(self):
'''Equivalent to toString() in other languages
returns a tab delineated timeseries'''
output = ""
template = "%s\t%.3f\n"
for line in self.data:
try:
output += template % (line[0].strftime("%d-%b-%Y %H%M"), line[1])
except:
output += "%s\t\t\n" % line[0].strftime("%d-%b-%Y %H%M")
return output
def __getitem__(self, idx):
''' returns (gets) a timeslice from self.data from supplied index.
Example : ts[1] would return [datetime,value]'''
if idx >= len(self.data):
return [None, None]
return self.data[idx]
def __len__(self):
return (len(self.data))
def __eq__(self, other, precision=6):
'''Checks to see if a timeseries is equal to another
you can specify how many decimal places to check.
default is six decimals"
'''
fmt = '.' + str(precision) + 'f'
if other == None:
return False
if len(self.data) == 0 and len(other.data) == 0:
return True
if len(self.data) != len(other.data):
return False
for i in range(len(self.data)):
if format(self.data[i][1], fmt) != format(other.data[i][1], fmt):
return False
return True
def toDict(self):
'''Turns self.data into a dictionary for efficiency purposes'''
output = {}
for i in range(len(self.data)):
output[self.data[i][0]] = i
return output
def timestamps(self):
output = []
for i in range(len(self.data)):
output.append(self.data[i][0])
return output
def values(self):
output = []
for i in range(len(self.data)):
output.append(self.data[i][1])
return output
def toPlot(self):
'''Format timeseries for plotting by returning:
x: Timestamps
y: Values
Matplotlib Example: plt.plot(*timeseries.toPlot())
'''
return self.timestamps(), list(self.values())
def saveTSV(self, path):
'''Outputs the timeseries to a tab separated file'''
f = open(path, "w")
f.write(str(self))
f.close()
def loadTSV(self, path):
'''Reads a timeseries from a tsv file. Hash (#) can be used as comments
Format <Datetime>\t<value>
This method mutates the object, and also returns a pointer to self.
'''
lines = (line.rstrip("\n") for line in open(path, "r"))
return self.fromTSV(lines)
def fromTSV(self, lines):
'''reads a timeseries from a TSV string
This method mutates the object, and also returns a pointer to self.
'''
count = 0
for s in lines:
count += 1
s = re.sub(r'#.*', '', s) # Strip comments
if re.match(r'\S', s): # Ignore blank lines
tokens = s.split("\t")
try:
if len(tokens) > 1:
self.safeinsert(tokens[0], float(tokens[1]))
except:
self.status = "Error Parsing line %u" % (count)
return self
def saveBinary(self, path):
'''Outputs the timeseries to a binary file'''
f = open(path, "wb")
f.write(self.toBinary())
f.close()
def toBinary(self):
'''Outputs the timeseries to a binary bytearray
Uses doubles for time and
'''
o = bytearray()
for line in self.data:
a, b = (time.mktime(line[0].timetuple()), line[1])
o.extend(struct.pack("dd", a, b))
return o
def loadBinary(self, path):
'''Reads the timeseries from a binary file and inserts values into self'''
buf = bytearray(os.path.getsize(path))
with open(path, "rb") as f:
f.readinto(buf)
self.fromBinary(buf)
f.close()
return self
def fromBinary(self, buf):
'''Reads the timeseries from a binary buffer'''
size = struct.calcsize("dd")
buflen = len(buf)
if buflen >= size:
i = 0
while i < buflen:
d = struct.unpack("dd", buf[i:i + size])
self.insert(datetime.datetime.fromtimestamp(d[0]), d[1])
i += size
return self
def loadBinaryV1(self, path):
'''Reads the timeseries from a binary file and inserts values into self'''
buf = bytearray(os.path.getsize(path))
with open(path, "rb") as f:
f.readinto(buf)
self.fromBinaryV1(buf)
f.close()
return self
def fromBinaryV1(self, buf):
'''Reads the timeseries from a binary buffer'''
size = struct.calcsize("iff")
buflen = len(buf)
if buflen >= size:
i = 0
while i < buflen:
d = struct.unpack("iff", buf[i:i + size])
self.insert(datetime.datetime.fromtimestamp(d[0]), d[1])
i += size
return self
@requires_SQLITE3
def SQLITE3connect(self, dbPath):
'''
Get a SQLITE 3 database connection
dbPath - path to the database file
'''
#initialize with Default Configuration
self.status = "OK"
#Database Cursors
dbconn = None
try:
dbconn = sqlite3.connect(dbPath)
if not dbconn:
self.status = f"\nCould not connect to {dbPath}\n"
except Exception as e:
self.status = f"\nCould not connect to {dbPath}\n {str (e)}"
return dbconn
@requires_SQLITE3
def SQLITE3disconnect(self, dbconn):
'''Disconnect from a SQLITE3 database connection '''
dbconn.close()
@requires_SQLITE3
def loadSQLITE3(self, conn, tsid, start_time=None, end_time=None):
'''loads a timeseries from a SQLITE3 database
Reads a time series from the database#
conn - SQLITE3 connection
tsid - string LOC_PARAM
start_time - datetime
end_time - datetime
Timestamps are stored in milliseconds after the unix epoch
'''
cur = conn.cursor()
ts = timeseries()
sqltxt = "SELECT * FROM " + tsid
if start_time != None and end_time != None:
start = time.mktime(start_time.timetuple()*1000)
end = time.mktime(end_time.timetuple()*1000)
sqltxt += " WHERE timestamp >= " + str(
start) + " AND timestamp <= " + str(end)
try:
cur.execute(sqltxt)
rows = cur.fetchall()
for d in rows:
ts.insert(datetime.datetime.fromtimestamp(d[0]/1000), d[1])
except Exception as e:
self.status = "\nCould not read %s\n" % tsid
self.status += "\n%s" + str(e)
cur.close()
return ts
@requires_SQLITE3
def loadSQLITE3v1(self, conn, tsid, start_time=None, end_time=None):
'''loads a timeseries from a SQLITE3 database from version 1 tables
Reads a time series from the database#
conn - SQLITE3 connection
tsid - string LOC_PARAM
start_time - datetime
end_time - datetime
in v1 Timestamps are stored in seconds after the unix epoch
'''
cur = conn.cursor()
ts = timeseries()
sqltxt = "SELECT * FROM " + tsid
if start_time != None and end_time != None:
start = time.mktime(start_time.timetuple())
end = time.mktime(end_time.timetuple())
sqltxt += " WHERE timestamp >= " + str(
start) + " AND timestamp <= " + str(end)
try:
cur.execute(sqltxt)
rows = cur.fetchall()
for d in rows:
ts.insert(datetime.datetime.fromtimestamp(d[0]), d[1])
except Exception as e:
self.status = "\nCould not read %s\n" % tsid
self.status += "\n%s" + str(e)
cur.close()
return ts
@requires_SQLITE3
def saveSQLITE3(self, conn, tsid, replace_table=False):
'''saves a timeseries from to SQLITE3 database
Reads a time series from the database#
conn - SQLITE3 connection
tsid - string LOC_PARAM
replace_table = False - Set to true to replace the ts in the database
Timestamps are stored in milliseconds after the unix epoch
'''
tsid = tsid.upper()
try:
cur = conn.cursor()
if replace_table == True:
cur.execute("CREATE TABLE IF NOT EXISTS {}(timestamp INTEGER PRIMARY KEY, val REAL)".format(tsid))
cur.execute("DROP TABLE {}".format(tsid))
cur.execute("CREATE TABLE IF NOT EXISTS {}(timestamp INTEGER PRIMARY KEY, val REAL)".format(tsid))
for line in self.data:
sqltxt = "INSERT OR REPLACE INTO {} VALUES(?, ?)".format(tsid)
cur.execute(sqltxt,(int(time.mktime(line[0].timetuple()) * 1000), line[1]))
conn.commit()
cur.close()
except Exception as e:
self.status = "\nCould not store " + tsid
self.status += "\n%s" % str(e)
def getStatus(self):
'''exceptions get dropped into self.status
This method gets status message of object and resets self.status to "OK" '''
s = self.status
self.status = "OK"
return s
def findValue(self, timestamp):
''' returns a value at a given timestamp
returns None type if not found'''
idx = self.findIndex(timestamp)
if idx != -1:
return self.data[idx][1]
else:
return None
def findIndex(self, key):
''' returns the index of a given timestamp
returns -1 if not found'''
imin = 0
imax = len(self.data) - 1
while (imax >= imin):
imid = imin + ((imax - imin) // 2)
if (self.data[imid][0] == key):
return imid
elif (self.data[imid][0] < key):
imin = imid + 1 #change min index to search upper subarray
else:
imax = imid - 1
#change max index to search lower subarray
return -1 # Key not found
def findClosestIndex(self, key):
''' returns the index of a given timestamp
returns closest index if not found'''
imin = 0
imax = len(self.data) - 1
while (imax >= imin):
imid = imin + ((imax - imin) // 2)
if (self.data[imid][0] == key):
return imid
elif (self.data[imid][0] < key):
imin = imid + 1 #change min index to search upper subarray
else:
imax = imid - 1
#change max index to search lower subarray
return imid # Key not found
def safeinsert(self, datestamp, value):
'''takes raw input and attempts to make it work'''
if isinstance(datestamp, str):
datestamp = dateparser.parse(datestamp, fuzzy=True)
self.insert(datestamp, float(value))
def insert(self, datestamp, value, quality=0):
'''Inserts a timestamp, value into the timseries.
this module assumes that datetimes are in acending order, as such please use this method when adding data'''
l = len(self.data)
if l == 0:
self.data.append([datestamp, value])
return
if datestamp > self.data[-1][0]:
self.data.append([datestamp, value])
return
i = self.findClosestIndex(datestamp)
if datestamp == self.data[i][0]:
self.data[i] = [datestamp, value]
return
i -= 2
if i < 0:
i = 0
while i < l:
if datestamp < self.data[i][0]:
self.data.insert(i, [datestamp, value])
return
i += 1
self.data.append([datestamp, value])
def truncate(self, precision):
'''Truncates values in timeseries to a given number of decimal places
'''
fmt = f'.{str(precision)}f'
output = timeseries()
for slice in self.data:
output.insert(slice[0], float(format(slice[1], fmt)))
return output
def round(self, precision):
'''Rounds values in timeseries to a given number of decimal places
'''
output = timeseries()
for slice in self.data:
output.insert(slice[0], round(slice[1], precision))
return output
def merge(self, other):
'''Merges another timeseries into self, retruns resultant timeseries'''
output = timeseries(self.data)
for line in other.data:
output.insert(line[0], line[1])
return output
def diff(self, other):
'''Returns the differences between self and timeseries other governs'''
output = timeseries()
for slice in self.data:
i = other.findIndex(slice[0])
if i == -1:
continue
oslice = other.data[i]
if format(slice[1], '.6f') != format(oslice[1], '.6f'):
output.insert(oslice[0], oslice[1])
for slice in other.data:
i = self.findIndex(slice[0])
if i == -1:
output.insert(slice[0], slice[1])
return output
def toHTML(self, css="", thead=""):
'''like __str__ only it outputs a HTML table'''
output = "<table " + css + ">"
output += thead
for line in self.data:
try:
output += "<tr><td>%s</td><td> %.2f</td></tr>" % (
line[0].strftime("%d-%b-%Y %H%M"), line[1])
except:
output += "<tr><td>%s</td><td> </td></tr>" % line[0].strftime(
"%d-%b-%Y %H%M")
return output + "</table>"
def toJS(self, var, timefmt="%m/%d/%Y %k:%M:%S"):
'''returns self as a JS array'''
return "var %s = %s;\n" % (var, self.toJSON(timefmt=timefmt))
def toJSON(self, timefmt="%m/%d/%Y %k:%M:%S"):
'''returns self as a JSON object'''
output = []
for line in self.data:
try:
output.append(' ["%s",%.2f]' % (line[0].strftime(timefmt), line[1]))
except:
output.append(' ["%s", undefined]' % line[0].strftime(timefmt))
return "[\n%s\n]" % ",\n".join(output)
def fromJSON(self,s):
ts = timeseries()
try:
j = json.loads(s)
ts = timeseries(j)
except Exception as e:
self.status = str(e)
return ts
def minDate(self, timefmt="%m/%d/%Y %k:%M:%S"):
try:
return self.data[0][0].strftime(timefmt)
except:
return ""
#========================================================================
# computational methods
#========================================================================
def interpolateValue(self, x0, y0, x1, y1, x):
'''interpolate values'''
m = (y1 - y0) / (x1 - x0)
output = y0 + (x - x0) * m
return output
def interpolate(self, interval):
'''interpolates timeseries based on a given interval of type timedelta
returns a timeseries object
'''
interval = self.TD(interval)
_data = []
try:
for i in range(0, len(self.data) - 1):
startTime = self.data[i][0]
deltaT = (self.data[i + 1][0] - startTime)
steps = int(deltaT.total_seconds() / interval.total_seconds())
for j in range(0, steps):
value = self.interpolateValue(0, self.data[i][1],
deltaT.total_seconds(),
self.data[i + 1][1],
j * interval.total_seconds())
_data.append([startTime + (interval * j), value])
except Exception as e:
self.status = str(e)
return timeseries(_data)
def average(self, interval):
'''averages timeseries based on a given interval of type timedelta
returns a timeseries object
'''
interval = self.TD(interval)
_data = []
if self.data == []:
return timeseries()
try:
i = 0
count = len(self.data)
endTime = self.data[i][0]
while i < count:
startTime = endTime
endTime = startTime + interval
n = 0
sum = 0
while self.data[i][0] < endTime:
sum += self.data[i][1]
n += 1
i += 1
if i >= count:
break
if n != 0:
_data.append([endTime, sum / n])
except Exception as e:
self.status = str(e)
return timeseries(_data)
def globalAverage(self):
'''averages entire timeseries returns a timeslice'''
if len(self.data) != 0:
interval = self.data[-1][0] - self.data[0][0]
return self.average(interval).data[0]
return None
def globalMax(self):
'''finds the max of a timeseries returns a timeslice'''
if len(self.data) != 0:
interval = self.data[-1][0] - self.data[0][0]
return self.maxmin(interval, lambda x, y: x > y).data[0]
return None
def globalMin(self):
'''averages minimum of a timeseries returns a timeslice'''
if len(self.data) != 0:
interval = self.data[-1][0] - self.data[0][0]
return self.maxmin(interval, lambda x, y: x < y).data[0]
return None
def linreg(self):
''' returns a tuple of linear regression cooeficinets (m,b,r)
for a line defined as y = mx+b
m - slope
b - slope intercept
r - correlation coeeficient
NOTE: x is in seconds past the epoch
'''
sumx = 0.0 #sum of x
sumx2 = 0.0 #sum of x**2
sumxy = 0.0 #sum of x * y
sumy = 0.0 #sum of y
sumy2 = 0.0 #sum of y**2
n = 0
for tmslice in self.data:
if tmslice[1] != None:
x = time.mktime(tmslice[0].timetuple())
y = tmslice[1]
sumx += x
sumx2 += x**2
sumxy += x * y
sumy += y
sumy2 += y**2
n += 1
denom = (n * sumx2 - (sumx**2))
if (denom == 0): # singular matrix. can't solve the problem.
return (0, 0, 0)
m = (n * sumxy - sumx * sumy) / denom
b = (sumy * sumx2 - sumx * sumxy) / denom
#compute correlation coeff
r = (sumxy - sumx * sumy / n) / math.sqrt(
(sumx2 - (sumx**2) / n) * (sumy2 - (sumy**2) / n))
return (m, b, r)
def trendline(self):
'''trendline performs a least squares regression on self.
Return a timeseries that contains the best fit values for each timeslice '''
output = timeseries()
coeff = self.linreg()
m = coeff[0]
b = coeff[1]
for slice in self.data:
x = time.mktime(slice[0].timetuple())
output.insert(slice[0], m * x + b)
return output
def variance(self):
'''returns the variance of the timeseries as a timeslice'''
ss = 0
mu = self.globalAverage()
if mu != None:
n = 0
for t in self.data:
n += 1
ss += math.pow(t[1] - mu[1], 2)
return [mu[0], ss / n, 0]
return None
def stddev(self):
'''returns the standard deviation of a timeseries as a timeslice'''
s = self.variance()
if s != None:
s[1] = math.sqrt(s[1])
return s
def movingstddev(self, interval):
'''Returns a moving standard deviaton over specified interval.
returns a timeseries object'''
output = timeseries()
interval = self.TD(interval)
if self.data != [] and interval.total_seconds != 0:
pointer = self.data[0][0]
while pointer < self.data[-1][0]:
stddev = self.subSlice(pointer, pointer + interval).stddev()
output.data.append(stddev)
pointer += interval
return output
def subSlice(self, starttime, endtime):
'''returns a timeseries betweeen the specified start and end datetimes'''
output = timeseries()
if self.data == []:
return output
if 1 == 1:
pos = self.findClosestIndex(starttime)
a = pos - 2 #subtract a few to be sure
if a < 0:
a = 0
while a < len(self.data):
line = self.data[a]
if line[0] > endtime:
break
if line[0] >= starttime:
output.insert(line[0], line[1])
a += 1
return output
def getWY(self, WY):
'''Gets a water year'''
starttime = datetime.datetime(year=WY - 1, month=10, day=1)
endtime = datetime.datetime(year=WY, month=9, day=30)
return self.subSlice(starttime, endtime)
def averageWY(self):
'''averages each element in the timeseries in previous water years
returns a timeseries object
'''
def toWY(t):
output = t.year
if t.month > 9:
output += 1
return output
def fromWY(year, month):
output = year
if month > 9:
output -= 1
return output
def inWY(WY, t):
if t.month < 10 and WY == t.year:
return True
if t.month > 9 and WY == (t.year + 1):
return True
return False
_data = []
if self.data == []:
return timeseries()
dd = self.toDict()
try:
i = 0
startWY = toWY(self.data[0][0])
endWY = toWY(self.data[-1][0])
count = len(self.data)
#advance to the latest WY
while i < count and not inWY(endWY, self.data[i][0]):
i += 1
#average current timeslice
while i < count:
sum = 0
t = self.data[i][0]
n = 0
for WY in range(startWY, endWY + 1):
try:
t2 = datetime.datetime(
year=fromWY(WY, t.month),
month=t.month,
day=t.day,
hour=t.hour,
minute=t.minute)
if t2 in dd:
val = self.data[dd[t2]][1]
n += 1
sum += val
except:
pass
if n != 0:
_data.append([t, sum / n])
i += 1
except Exception as e:
self.status = str(e)
return timeseries(_data)
def runningTotal(self, override_startTime=None):
'''Creates a timeseries containing a running total (partial sum)
returns a timeseries object'''
output = timeseries()
sum = 0
for row in self.data:
sum += row[1]
output.insert (row[0],sum)
return output
def accumulate(self, interval, override_startTime=None):
'''accumulates timeseries based on a given interval of type timedelta
returns a timeseries object'''
interval = self.TD(interval)
_data = []
if self.data == []:
return timeseries()
try:
i = 0
count = len(self.data)
if override_startTime != None:
endTime = override_startTime
else:
endTime = self.data[i][0]
while i < count:
startTime = endTime
endTime = startTime + interval
n = 0
sum = 0
while self.data[i][0] < endTime:
sum += self.data[i][1]
n += 1
i += 1
if i >= count:
break
if n != 0:
_data.append([endTime, sum])
except Exception as e:
self.status = str(e)
return timeseries(_data)
def accumulateWY(self, interval, incrTS, offset=datetime.timedelta(days=0)):
'''
accumulates input timeseries and adds to self on an interval of type timedelta
this resets every wateryear
self is assumed to be an accumulated timeseries
returns a timeseries object
'''
interval = self.TD(interval)
lastResetYear = 0
output = timeseries() #output timeseries, don't want to mutate self
if incrTS.data == []:
return self
if self.data == []:
output.data = [incrTS.data[0]]
else:
output.data = self.data
try:
#advance to the first timeslice in the incremental timeseries that is
#greater than or equal the last time in self
i = 0
count = len(incrTS.data)
endTime = output.data[-1][0]
while i < count:
if incrTS.data[i][0] >= endTime:
break
i += 1
t = timeseries()
t.data = incrTS.data[i:]
t = t.accumulate(interval, override_startTime=endTime)
#loop through accumulated timeseries and accumulate timeslices onto output
total = output.data[-1][1]
for slice in t.data:
if slice[0].day == 1 and slice[0].month == 10 and (
slice[0].hour + slice[0].minute / 60.0) >= (
(offset.seconds + interval.seconds
) / 3600.0) and lastResetYear != slice[0].year:
total = 0
lastResetYear = slice[0].year
total += slice[1]
output.insert(slice[0], total)
#print "%s\t %f\t %f" %(str(slice[0]),slice[1],total)
except Exception as e:
self.status = str(e)
return output.timeshift(interval * -1)
def firstdifference(self):
return self.simpledelta()
def simpledelta(self):
'''calculates the delta between successive, results are in the same units as the time series
returns a timeseries object'''
output = timeseries()
if len(self.data) < 2:
return output
try:
for i in range(1, len(self.data)):
d = self.data[i][1] - self.data[i - 1][1]
output.insert(self.data[i][0], d)
except Exception as e:
self.status = str(e)
return output
def maxmin(self, interval, cmp):
'''returns a max or a min based for a given interval of type datetime
returns a timeseries object
'''
interval = self.TD(interval)
_data = []
if self.data == []:
return timeseries()
try:
i = 0
count = len(self.data)
endTime = self.data[i][0]
while i < count:
startTime = endTime
endTime = startTime + interval
n = 0
probe = self.data[i][1]
while self.data[i][0] < endTime:
if cmp(self.data[i][1], probe):
probe = self.data[i][1]
i += 1
if i >= count:
break
_data.append([endTime, probe])
except Exception as e:
self.status = str(e)
return timeseries(_data)
@requires_numpy
def savitzky_golay(self, window_size, order, deriv=0, rate=1):
'''Savitzky-Golay Smoothing filter using numpy
window_size: number of items in window integer
order: polynomial order
deriv: defaults to 0
rate : defaults to 1
'''
try:
window_size = np.abs(np.int(window_size))
order = np.abs(np.int(order))
except ValueError:
raise ValueError("SGFilter:window size and order must be of type int")
if window_size % 2 != 1 or window_size < 1:
raise TypeError("SGFilter:window size must be positive number")
if window_size < order + 2:
raise TypeError(
"SGFilter:window size is too small for the polynomials order")
y = []
_data = self.data
for x in range(0, len(_data) - 1):
yy = _data[x][1]
y.append(yy)
order_range = list(range(order + 1))
half_window = (window_size - 1) // 2
# precompute coefficients
b = np.mat([[k**i for i in order_range]
for k in range(-half_window, half_window + 1)])
m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
# pad the signal at the extremes with values taken from the signal itself
#firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
firstvals = []
v = y[0]
for i in range(half_window):
firstvals.append(v)
#lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
lastvals = []
v = (y[len(y) - 1:])[0]
for i in range(half_window):
lastvals.append(v)
y = np.concatenate((firstvals, y, lastvals))
tsd = np.convolve(m[::-1], y, mode='same')
# remove the appended/padded values at beginning/end of data
tsd = tsd[(window_size - 1) / 2:len(tsd) - (window_size - 1) / 2]
_data = []
for x in range(0, len(self.data) - 1):
_data.append([self.data[x][0], tsd[x], 0])
return timeseries(_data)
@requires_numpy
def remove_stddev_outliers(self, threshold=1.5):
'''Remove Outliers using Standard Deviation'''
good = []
_data = []
a = []
# get the slice of values from timeseries
# y = np.array(self.data)
# a = y[:,1]
for rec in self.data:
a.append(rec[1])
avg = np.average(a)
# pad the first element with average
a = [avg] + a
out = [None] * len(a)
good.append(a[0])
std = np.std(a)
stdm = std * threshold
for n in range(1, len(a)):
dev = abs(a[n] - good[-1])
if dev < stdm:
good.append(a[n])
out[n] = a[n]
else:
out[n] = None
# remove the first (avg) element
out = out[1:]
# replace the values, only non nulls
# these will get interpolated later
for x in range(0, len(self.data)):
if out[x] != None:
_data.append([self.data[x][0], out[x]])
return timeseries(_data)
def rollingaverage(self, interval):
'''averages timeseries based on a given interval of type timedelta. Moving average looking forward.
returns a timeseries object'''
interval = self.TD(interval)
_data = []