/
timeseries.py
3453 lines (3122 loc) · 112 KB
/
timeseries.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/bin/env python3
#
# pylint: disable=too-many-lines
''' Efficient portable machine native columnar file storage of time
series data for double float and signed 64-bit integers.
The core purpose is to provide time series data storage; there
are assorted convenience methods to export arbitrary subsets
of the data for use by other libraries in common forms, such
as dataframes or series, numpy arrays and simple lists.
There are also some simple plot methods for plotting graphs.
Three levels of storage are defined here:
- `TimeSeriesFile`: a single file containing a binary list of
float64 or signed int64 values
- `TimeSeriesPartitioned`: a directory containing multiple
`TimeSeriesFile` files, each covering a separate time span
according to a supplied policy, for example a calendar month
- `TimeSeriesDataDir`: a directory containing multiple
`TimeSeriesPartitioned` subdirectories, each for a different
time series, for example one subdirectory for grid voltage
and another for grid power
Together these provide a hierarchy for finite sized files storing
unbounded time series data for multiple parameters.
On a personal basis, I use this as efficient storage of time
series data from my solar inverter, which reports in a slightly
clunky time limited CSV format; I import those CSVs into
time series data directories which contain the overall accrued
data; see my `cs.splink` module which is built on this module.
'''
from abc import ABC, abstractmethod
from array import array, typecodes # pylint: disable=no-name-in-module
from collections import defaultdict, namedtuple
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timedelta, tzinfo
from fnmatch import fnmatch
from functools import partial
from getopt import GetoptError
from math import nan # pylint: disable=no-name-in-module
from mmap import (
mmap,
ALLOCATIONGRANULARITY,
MAP_PRIVATE,
PROT_READ,
PROT_WRITE,
) # pylint: disable=no-name-in-module,c-extension-no-member
import os
from os.path import (
basename,
exists as existspath,
isdir as isdirpath,
isfile as isfilepath,
join as joinpath,
splitext,
)
from pprint import pformat
from struct import pack # pylint: disable=no-name-in-module
import sys
from tempfile import TemporaryDirectory
import time
from typing import (
Any,
Callable,
Iterable,
List,
Optional,
Tuple,
Union,
)
import arrow
from arrow import Arrow
import dateutil
from dateutil.tz import tzlocal
from icontract import ensure, require, DBC
from matplotlib.figure import Axes, Figure
import numpy as np
from numpy import datetime64, timedelta64
from typeguard import typechecked
from cs.binary import BinarySingleStruct, SimpleBinary
from cs.buffer import CornuCopyBuffer
from cs.cmdutils import BaseCommand
from cs.configutils import HasConfigIni
from cs.csvutils import csv_import
from cs.deco import cachedmethod, decorator, promote, Promotable
from cs.fileutils import atomic_filename
from cs.fs import HasFSPath, fnmatchdir, needdir, shortpath
from cs.fstags import FSTags, uses_fstags
from cs.lex import is_identifier, s, r
from cs.logutils import warning
from cs.mappings import column_name_to_identifier
from cs.mplutils import axes, remove_decorations, print_figure, save_figure
from cs.pfx import Pfx, pfx, pfx_call, pfx_method
from cs.progress import progressbar
from cs.py.modules import import_extra
from cs.resources import MultiOpenMixin, RunState, uses_runstate
from cs.result import CancellationError
from cs.upd import print, run_task # pylint: disable=redefined-builtin
__version__ = '20240316-post'
DISTINFO = {
'keywords': ["python3"],
'classifiers': [
"Development Status :: 3 - Alpha",
"Programming Language :: Python :: 3",
],
'install_requires': [
'arrow',
'cs.binary',
'cs.buffer',
'cs.cmdutils',
'cs.configutils>=HasConfigIni',
'cs.context',
'cs.csvutils',
'cs.deco>=promote_optional',
'cs.fileutils>=atomic_filename',
'cs.fs',
'cs.fstags',
'cs.lex',
'cs.logutils',
'cs.mappings',
'cs.mplutils',
'cs.pfx',
'cs.progress',
'cs.py.modules',
'cs.resources',
'cs.result',
'cs.upd',
'python-dateutil',
'icontract',
'matplotlib',
'numpy',
'typeguard',
],
'entry_points': {
'console_scripts': {
'csts': 'cs.timeseries:main',
},
},
'extras_requires': {
'pandas': ['pandas'],
},
}
numeric_types = int, float
Numeric = Union[numeric_types]
def main(argv=None):
''' Run the command line tool for `TimeSeries` data.
'''
return TimeSeriesCommand(argv).run()
pfx_listdir = partial(pfx_call, os.listdir)
pfx_mkdir = partial(pfx_call, os.mkdir)
pfx_open = partial(pfx_call, open)
class TypeCode(str, Promotable):
''' A valid `array` typecode with convenience methods.
'''
TYPES = ('q', int), ('d', float)
BY_CODE = {code: type_ for code, type_ in TYPES} # pylint: disable=unnecessary-comprehension
BY_TYPE = {type_: code for code, type_ in TYPES}
assert all(map(lambda typecode: typecode in typecodes, BY_CODE.keys()))
def __new__(cls, t):
''' Return a new `TypeCode` instance from `t`, which may be:
* a `str`: expected to be an `array` type code
* `int`: `array` type code `q` (signed 64 bit)
* `float`: `array` type code `d` (double float)
'''
if isinstance(t, str):
if t not in cls.BY_CODE:
raise ValueError(
"invalid typecode %r, I know %r" % (t, sorted(cls.BY_CODE.keys()))
)
elif isinstance(t, type):
try:
t = cls.BY_TYPE[t]
except KeyError:
# pylint: disable=raise-missing-from
raise ValueError(
"invalid type %r, I know %r" % (t, sorted(cls.BY_TYPE.keys()))
)
else:
raise TypeError("unsupported type for %s, should be str or type" % r(t))
return super().__new__(cls, t)
@classmethod
def promote(cls, t: 'TypeCodeish') -> 'TypeCode':
''' Promote `t` to a `TypeCode`.
The follow values of `t` are accepted:
* a subclass of `TypeCode`, returned unchanged
* a `str`: expected to be an `array` type code
* `int`: `array` type code `q` (signed 64 bit)
* `float`: `array` type code `d` (double float)
'''
if isinstance(t, cls):
return t
if isinstance(t, (str, type)):
return cls(t)
raise TypeError(
"%s.promote: cannot promote %s, expect str or type" %
(cls.__name__, r(t))
)
@property
def type(self):
''' The Python type for this `TypeCode`.
'''
return self.BY_CODE[self]
def struct_format(self, bigendian):
''' Return a `struct` format string for the supplied big endianness.
'''
return ('>' if bigendian else '<') + self
@property
def default_fill(self):
''' The default fill for the type code.
'''
if self == 'd':
return nan
if self == 'q':
return 0
raise RuntimeError('no default fill value for %r' % (self,))
TypeCodeish = Union[(TypeCode, str, *TypeCode.BY_TYPE.keys())]
@typechecked
def deduce_type_bigendianness(typecode: str) -> bool:
''' Deduce the native endianness for `typecode`,
an array/struct typecode character.
'''
test_value = TypeCode(typecode).type(1)
bs_a = array(typecode, (test_value,)).tobytes()
bs_s_be = pack('>' + typecode, test_value)
bs_s_le = pack('<' + typecode, test_value)
if bs_a == bs_s_be:
return True
if bs_a == bs_s_le:
return False
raise RuntimeError(
"cannot infer byte order: array(%r,(1,))=%r, pack(>%s,1)=%r, pack(<%s,1)=%r"
% (typecode, bs_a, typecode, bs_s_be, typecode, bs_s_le)
)
NATIVE_BIGENDIANNESS = {
typecode: deduce_type_bigendianness(typecode)
for typecode in TypeCode.BY_CODE.keys()
}
DT64_0 = datetime64(0, 's')
TD_1S = timedelta64(1, 's')
# functions producing ints from seconds for various datetime64 flavours
DT64_FROM_SECONDS = {
's': int,
'ms': lambda f: int(f * 1000),
'us': lambda f: int(f * 1000000),
'ns': lambda f: int(f * 1000000000),
}
def as_datetime64s(times, unit='s', utcoffset=0):
''' Return a Numpy array of `datetime64` values
computed from an iterable of `int`/`float` UNIX timestamp values.
The optional `unit` parameter (default `'s'`) may be one of:
- `'s'`: seconds
- `'ms'`: milliseconds
- `'us'`: microseconds
- `'ns'`: nanoseconds
and represents the precision to preserve in the source time
when converting to a `datetime64`.
Less precision gives greater time range.
'''
# select scaling function
try:
scale = DT64_FROM_SECONDS[unit]
except KeyError:
# pylint: disable=raise-missing-from
raise ValueError("as_datetime64s: unhandled unit %r" % (unit,))
# apply optional utcoffset shift
if utcoffset != 0:
times = [t + utcoffset for t in times]
return np.array([scale(t) for t in times]).astype(f'datetime64[{unit}]')
def datetime64_as_timestamp(dt64: datetime64):
''' Return the UNIX timestamp for the `datetime64` value `dt64`.
'''
return dt64 / TD_1S
class TimeSeriesBaseCommand(BaseCommand, ABC):
''' Abstract base class for command line interfaces to `TimeSeries` data files.
'''
# TODO: also arbitrary timedeltas eg 100d20h
@staticmethod
@typechecked
def parsetime(timespec: str) -> float:
''' Parse `timespec` into a UNIX timestamp.
`timespec` may be one of the following:
* an integer number of days, indicating a time before _now_
* a float, an absolute UNIX timestamp in seconds
* any format recognised by `dateutil.parser.parse`, assuming the
system local time if no timezone is specified in `timespec`.
'''
try:
days = int(timespec)
except ValueError:
try:
return float(timespec)
except ValueError:
try:
dt = dateutil.parser.parse(timespec)
except dateutil.parser.ParserError as e:
raise ValueError(
"%r: neither int nor float nor dateutil.parser.parse format: %s"
% (timespec, e)
) from e
if dt.tzinfo is None:
# assume local time if we get a naive datetime
dt = dt.replace(tzinfo=tzlocal())
else:
# days
dt = datetime.now(tzlocal()) - timedelta(days=days)
return dt.timestamp()
@typechecked
def poptime(self, argv: List[str], argname: str = 'timespec', **kw):
''' Pop a _days_ or _timespec_ argument from the command line,
return an aware `datetime`.
'''
return self.poparg(
argv, argname, self.parsetime,
'expected days or dateutil.parser.parse string', **kw
)
def cmd_fetch(self, argv):
''' Usage: {cmd} ...
Fetch raw data files from the primary source to a local spool.
To be implemented in subclasses.
'''
raise GetoptError(
f"the {type(self).__name__} class"
f" does not provide a \"{self.cmd}\" subcommand"
)
@abstractmethod
def cmd_import(self, argv):
''' Usage: {cmd} ...
Import data into the time series.
To be implemented in subclasses.
'''
raise NotImplementedError
@abstractmethod
def cmd_info(self, argv):
''' Usage: {cmd}
Report information.
'''
raise NotImplementedError
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
@uses_runstate
def cmd_plot(self, argv, *, runstate: RunState):
''' Usage: {cmd} [-f] [-o imgpath.png] [--show] [--tz tzspec] start-time [stop-time] [{{glob|fields}}...]
Plot the data from specified fields for the specified time range.
Options:
--bare Strip axes and padding from the plot.
-f Force. -o will overwrite an existing image file.
-o imgpath.png File system path to which to save the plot.
--show Show the image in the GUI.
--tz tzspec Skew the UTC times presented on the graph
The default skew is 0 i.e. UTC.
to emulate the timezone specified by tzspec.
--stacked Stack the plot lines/areas.
start-time An integer number of days before the current time
or any datetime specification recognised by
dateutil.parser.parse.
stop-time Optional stop time, default now.
An integer number of days before the current time
or any datetime specification recognised by
dateutil.parser.parse.
glob|fields If glob is supplied, constrain the keys of
a TimeSeriesDataDir by the glob.
'''
options = self.options
options.bare = False
options.show_image = False
options.imgpath = None
options.multi = False
options.stacked = False
options.tz = None
self.popopts(
argv,
options,
bare='bare',
f='force',
multi=None,
o_='imgpath',
show='show_image',
stacked=None,
tz_=('tz', tzfor),
)
# mandatory start time
start = self.poptime(argv, 'start-time')
# check for optional stop-time, default now
if argv:
try:
stop = self.poptime(argv, 'stop-time', unpop_on_error=True)
except GetoptError:
stop = time.time()
bare = options.bare
force = options.force
imgpath = options.imgpath
tz = options.tz
if imgpath and not force and existspath(imgpath):
raise GetoptError("imgpath exists: %r" % (imgpath,))
xit = 0
ts = options.ts
plot_dx = 14
plot_dy = 8
figure = Figure(figsize=(plot_dx, plot_dy), dpi=100)
figure.add_subplot()
ax = figure.axes[0]
plot_kw = {}
if isinstance(ts, TimeSeries):
# a single timeseries, no key
if argv:
raise GetoptError(
"fields:%r should not be suppplied for a %s" % (argv, s(ts))
)
ax = ts.plot(
start, stop, ax=ax, tz=tz, figsize=(plot_dx, plot_dy), **plot_kw
) # pylint: disable=missing-kwoa
elif isinstance(ts, TimeSeriesMapping):
# multiple timeseries each with their own key
if argv:
keys = ts.keys(argv)
if not keys:
raise GetoptError(
"no matching keys, I know: %s" % (', '.join(sorted(ts.keys())),)
)
else:
keys = ts.keys()
if not keys:
raise GetoptError("no keys in %s" % (ts,))
plot_kw.update(
stacked=options.stacked,
subplots=options.multi,
sharex=options.multi,
)
ax = ts.plot(
start,
stop,
keys,
tz=tz,
ax=ax,
**plot_kw,
) # pylint: too-many-function-args.disable=missing-kwoa
figure = (ax[0] if options.multi else ax).figure
else:
raise RuntimeError("unhandled type %s" % (s(ts),))
if runstate.cancelled:
return 1
if bare:
remove_decorations(figure)
if imgpath:
save_figure(figure, imgpath, force=force)
else:
print_figure(figure)
if options.show_image:
figure.show()
return xit
class TimeSeriesCommand(TimeSeriesBaseCommand):
''' Command line interface to `TimeSeries` data files.
'''
USAGE_FORMAT = r'''Usage: {cmd} [-s ts-step] tspath subcommand...
-s ts-step Specify the UNIX time step for the time series,
used if the time series is new and checked otherwise.
tspath The filesystem path to the time series;
this may refer to a single .csts TimeSeriesFile, a
TimeSeriesPartitioned directory of such files, or
a TimeSeriesDataDir containing partitions for
multiple keys.'''
GETOPT_SPEC = 's:'
SUBCOMMAND_ARGV_DEFAULT = 'info'
# conversion functions for a date column
DATE_CONV_MAP = {
'int': int,
'float': float,
'date': lambda d: pfx_call(arrow.get, d, tzinfo='local').timestamp(),
'iso8601': lambda d: pfx_call(arrow.get, d, tzinfo='local').timestamp(),
}
@dataclass
class Options(BaseCommand.Options):
ts_step: Optional[float] = None # the time series step
ts: Optional["TimeSeries"] = None
def apply_opt(self, opt, val):
if opt == '-s':
try:
ts_step = pfx_call(float, val)
except ValueError as e:
raise GetoptError("not a floating point value: %s" % (e,)) from e
if ts_step <= 0:
raise GetoptError("ts-step must be >0, got %s" % (ts_step,))
self.options.ts_step = ts_step
else:
raise RuntimeError("unhandled option")
def apply_preargv(self, argv):
''' Parse a leading time series filesystem path from `argv`,
set `self.options.ts` to the time series,
return modified `argv`.
'''
argv = list(argv)
options = self.options
if argv and argv[0] in ('test',):
pass
else:
options.ts = self.poparg(
argv,
'tspath',
partial(timeseries_from_path, epoch=options.ts_step),
)
if options.ts_step is not None and options.ts.step != options.ts_step:
warning(
"tspath step=%s but -s ts-step specified %s", options.ts.step,
options.ts_step
)
return argv
@contextmanager
def run_context(self):
with super().run_context():
if self.options.ts is None:
yield
else:
with self.options.ts:
yield
def cmd_dump(self, argv):
''' Usage: {cmd}
Dump the contents of tspath.
'''
if argv:
raise GetoptError("extra arguments: %r" % (argv,))
options = self.options
ts = options.ts
if isinstance(ts, TimeSeries):
npary = ts.as_pd_series()
print(npary)
elif isinstance(ts, TimeSeriesMapping):
df = ts.as_pd_dataframe()
print(df)
else:
raise GetoptError("unhandled time series: %s" % ts)
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
@uses_runstate
def cmd_import(self, argv, *, runstate: RunState):
''' Usage: {cmd} csvpath datecol[:conv] [import_columns...]
Import data into the time series.
csvpath The CSV file to import.
datecol[:conv]
Specify the timestamp column and optional
conversion function.
"datecol" can be either the column header name
or a numeric column index counting from 0.
If "conv" is omitted, the column should contain
a UNIX seconds timestamp. Otherwise "conv"
should be either an identifier naming one of
the known conversion functions or an "arrow.get"
compatible time format string.
import_columns
An optional list of column names or their derived
attribute names. The default is to import every
numeric column except for the datecol.
'''
options = self.options
ts = options.ts
badopts = False
csvpath = self.poparg(
argv,
'csvpath',
str,
lambda csvp: csvp.lower().endswith('.csv') and isfilepath(csvp),
'not an existing .csv file',
)
datecolspec = self.poparg(argv, 'datecol[:conv]', str)
with Pfx("datecol[:conv] %r", datecolspec):
try:
datecol, dateconv = datecolspec.split(':', 1)
except ValueError:
datecol, dateconv = datecolspec, float
else:
with Pfx("conv %r", dateconv):
try:
dateconv = self.DATE_CONV_MAP[dateconv]
except KeyError:
if is_identifier(dateconv):
warning(
"unknown conversion function; I know: %s",
", ".join(sorted(self.DATE_CONV_MAP.keys()))
)
badopts = True
else:
dateconv_format = dateconv
dateconv = lambda datestr: arrow.get(
datestr, dateconv_format, tzinfo='local'
).timestamp()
# see if the column is numeric
try:
datecol = int(datecol)
except ValueError:
pass
if badopts:
raise GetoptError("invalid arguments")
with Pfx("import %s", shortpath(csvpath)):
unixtimes = []
data = defaultdict(list)
rowcls, rows = csv_import(csvpath, snake_case=True)
attrlist = rowcls.name_attributes_
if argv:
attrindices = list(range(len(rowcls.name_attributes_)))
else:
attrindices = [rowcls.index_of_[attr] for attr in argv]
if isinstance(datecol, int):
if datecol >= len(rowcls.names_):
raise GetoptError(
"date column index %d exceeds the width of the CSV data" %
(datecol,)
)
dateindex = datecol
else:
try:
dateindex = rowcls.index_of_[datecol]
except KeyError:
warning(
"date column %r is not present in the row class, which knows:\n %s"
% (datecol, "\n ".join(sorted(rowcls.index_of_.keys())))
)
# pylint: disable=raise-missing-from
raise GetoptError("date column %r is not recognised" % (datecol,))
# load the data, store the numeric values
for i in attrindices:
if i != dateindex:
ts.makeitem(attrlist[i])
for row in progressbar(
rows,
"parse " + shortpath(csvpath),
report_print=True,
runstate=runstate,
):
when = pfx_call(dateconv, row[datecol])
unixtimes.append(when)
for i, value in enumerate(row):
if i == dateindex:
continue
attr = attrlist[i]
try:
value = int(value)
except ValueError:
try:
value = float(value)
except ValueError:
value = None
data[attrlist[i]].append(value)
# store the data into the time series
for attr, values in progressbar(
sorted(data.items()),
"set subseries",
report_print=True,
runstate=runstate,
):
with Pfx("%s: store %d values", attr, len(values)):
with run_task("%s: %d values..." % (attr, len(values))):
ts[attr].setitems(unixtimes, values, skipNone=True)
if runstate.cancelled:
return 1
return 0
def cmd_info(self, argv):
''' Usage: {cmd}
Report information about the time series stored at tspath.
'''
if argv:
raise GetoptError("extra arguments: %r" % (argv,))
ts = self.options.ts
print(ts)
print(pformat(ts.info_dict(), compact=True))
# pylint: disable=no-self-use
def cmd_test(self, argv):
''' Usage: {cmd} [testnames...]
Run some tests of functionality.
'''
def test_pandas(tmpdirpath):
t0 = 1649552238
fspath = joinpath(tmpdirpath, f'foo--from-{t0}.dat')
now = time.time()
ts = TimeSeriesFile(fspath, 'd', epoch=(now, 60))
ts.pad_to(now + 300)
print("len(ts.array) =", len(ts.array))
pds = ts.as_pd_series()
print(type(pds), pds.memory_usage())
print(pds)
# pylint: disable=unused-argument
def test_partitioned_spans(tmpdirpath):
# a daily partition with 1 minute time slots
policy = TimespanPolicyDaily(epoch=60)
now = time.time()
start = now
stop = now + 7 * 24 * 3600
print("start =", Arrow.fromtimestamp(start))
print("stop =", Arrow.fromtimestamp(stop))
prev_stop = None
for span in policy.partitioned_spans(start, stop):
print(
span,
Arrow.fromtimestamp(span.start),
Arrow.fromtimestamp(span.stop),
)
if prev_stop is not None:
assert prev_stop == span.start
prev_stop = span.stop
def test_datadir(tmpdirpath):
with TimeSeriesDataDir(
joinpath(tmpdirpath, 'tsdatadir'),
policy='daily',
epoch=30,
) as datadir:
ts = datadir.make_ts('key1')
ts[time.time()] = 9.0
# pylint: disable=unused-argument
def test_timespan_policy(tmpdirpath):
policy = TimespanPolicyMonthly(epoch=60)
print(policy.span_for_time(time.time()))
def test_timeseries(tmpdirpath):
now = time.time()
fspath = joinpath(tmpdirpath, 'foo.dat')
ts = TimeSeriesFile(fspath, 'd', epoch=(now, 1))
ary = ts.array
print(ary)
ts.pad_to(now + 300)
print(ary)
ts.save()
testfunc_map = {
'datadir': test_datadir,
'pandas': test_pandas,
'partitioned_spans': test_partitioned_spans,
'timeseries': test_timeseries,
'timespan_policy': test_timespan_policy,
}
if not argv:
argv = sorted(testfunc_map.keys())
ok = True
for testname in argv:
with Pfx(testname):
if testname not in testfunc_map:
warning("unknown test name")
ok = False
if not ok:
raise GetoptError(
"unknown test names, I know: %s" %
(", ".join(sorted(testfunc_map.keys())),)
)
for testname in argv:
with Pfx(testname):
with TemporaryDirectory(
dir='.',
prefix=f'{self.cmd}--test--{testname}--',
) as tmpdirpath:
testfunc_map[testname](tmpdirpath)
@decorator
def _with_utcoffset(func):
''' Decorator to wrap a function with this signature:
func(start, stop, *a, utcoffset, kw)
to present this signature:
func(start, stop, *a, tz=None, utcoffset=None, kw)
by computing a `utcoffset` from `stop`, `tz` and `utcoffset`.
'''
def with_utcoffset_wrapper(start, stop, *a, tz=None, utcoffset=None, **kw):
if utcoffset is None:
if tz is None:
utcoffset = 0.0
else:
tz = tzfor(tz)
assert isinstance(tz, tzinfo)
# DF hack: compute the timezone offset for "stop",
# use it to skew the UNIX timestamps so that UTC tick marks and
# placements look "local"
dt = datetime.fromtimestamp(stop, tz=tz)
utcoffset = tz.utcoffset(dt).total_seconds()
elif tz is not None:
raise ValueError(
"may not supply both utcoffset:%s and tz:%s" % (r(utcoffset), r(tz))
)
return func(start, stop, *a, utcoffset=utcoffset, **kw)
with_utcoffset_wrapper.__doc__ = getattr(
func, '__doc__', ''
) + '''
The `utcoffset` or `tz` parameters may be used to provide
an offset from UTC in seconds for the timestamps _as presented
on the index/x-axis_. It is an error to specify both.
Specifying neither uses an offset of `0.0`.
The `utcoffset` parameter is a plain offset from UTC in seconds.
The timezone parameter is a little idiosyncratic.
`DataFrame.plot` _has no timezone support_. It uses its own
locators and formatters, which render UTC.
For most scientific data that is a sound practice, so that
graphs have a common time reference for people in different
time zones.
For some data a timezone _is_ relevant, for example my
originating use case which plots my solar inverter data -
the curves are correlated with the position of the sun,
which is closely correlated with the local timezone; for
this use case `dateutil.tz.tzlocal()` is a good choice.
When you supply a `tzinfo` object it will be used to compute
the offset from UTC for the rightmost timestamp on the graph
(`stop`) and that offset will be applied to all the timestamps
on the graph.'''
return with_utcoffset_wrapper
# TODO: accept a reference `datetime` for `tz`, use its offset for `utcoffset`
@decorator
def timerange(method, needs_start=False, needs_stop=False):
''' A decorator intended for plotting functions or methods which
presents optional `start` and `stop` leading positional
parameters and optional `tz` or `utcoffset` keyword parameters.
The decorated function will be called with leading `start`
and `stop` positional parameters and a specific `utcoffset`
keyword parameter.
The as-decorated function is called with the following parameters:
* `start`: an optional UNIX timestamp positional for the
start of the range; if omitted the default is `self.start`;
this is a required parameter if the decorator has `needs_start=True`
* `stop`: an optional UNIX timestamp positional parameter for the end
of the range; if omitted the default is `self.stop`;
this is a required parameter if the decorator has `needs_stop=True`
* `tz`: optional timezone `datetime.tzinfo` object or
specification as for `tzfor()`;
this is used to infer a UTC offset in seconds
* `utcoffset`: an optional offset from UTC time in seconds
Other parameters are passed through to the deocrated function.
A decorated *method* is then called as:
method(self, start, stop, *a, utcoffset=utcoffset, **kw)
where `*a` and `**kw` are the additional positional and keyword
parameters respectively, if any.
A decorated *function* is called as:
function(start, stop, *a, utcoffset=utcoffset, **kw)
The `utcoffset` is an offset to apply to UTC-based time data
for _presentation_ on the graph, largely because the plotting
functions use `DataFrame.plot` which broadly ignores attempts
to set locators or formatters because it supplies its own.
The plotting function would shift the values of the `DataFrame`
index using this value.
If neither `utcoffset` or `tz` is supplied by the caller, the
`utcoffset` is `0.0`.
A specified `utcoffset` is passed through.
A `tz` is promoted to a `tzinfo` instance via the `tzfor()`
function and applied to the `stop` timestamp to obtain a
`datetime` from which the `utcoffset` will be derived.
It is an error to specify both `utcoffset` and `tz`.
'''
# pylint: disable=keyword-arg-before-vararg,too-many-branches
@typechecked
def timerange_method_wrapper(
*a,
tz: Optional[tzinfo] = None,
utcoffset: Optional[Numeric] = None,
**kw,
):
a = list(a)
if a and not isinstance(a[0], numeric_types):
self = a.pop(0)
else:
self = None
if a:
start = a.pop(0)
assert start is None or isinstance(start, numeric_types)
elif needs_start:
raise ValueError("missing start parameter")
else:
start = None
if a:
stop = a.pop(0)
assert stop is None or isinstance(stop, numeric_types)
elif needs_stop:
raise ValueError("missing stop parameter")
else:
stop = None
if start is None:
start = self.start
if stop is None:
stop = self.stop
tzutc_method = _with_utcoffset(method)
if self is None:
# not a method, call as a function
return tzutc_method(start, stop, *a, tz=tz, utcoffset=utcoffset, **kw)
return tzutc_method(
self, start, stop, *a, tz=tz, utcoffset=utcoffset, **kw
)
return timerange_method_wrapper
# TODO: optional `utcoffset`/`tz` parameters for presentation
# pylint: disable=too-many-locals
@timerange
@typechecked
def plot_events(
start,
stop,
events,
value_func,
*,
utcoffset,
figure=None,
ax=None,
**scatter_kw
) -> Axes:
''' Plot `events`, an iterable of objects with `.unixtime`
attributes such as an `SQLTagSet`.
Return the `Axes` on which the plot was made.
Parameters:
* `events`: an iterable of objects with `.unixtime` attributes
* `value_func`: a callable to compute the y-axis value from an event
* `start`: optional start UNIX time, used to crop the events plotted
* `stop`: optional stop UNIX time, used to crop the events plotted
* `figure`,`ax`: optional arguments as for `cs.mplutils.axes`
* `utcoffset`: optional UTC offset for presentation
Other keyword parameters are passed to `Axes.scatter`.
'''
ax = axes(figure, ax)
xaxis = []
yaxis = []
for event in (ev for ev in events
if (start is None or ev.unixtime >= start) and (
stop is None or ev.unixtime < stop)):
# not using bulk as_datetime64s because we want to individually
# handle event time conversion failure
try:
x = datetime64(int(event.unixtime + utcoffset), 's')
except ValueError as e:
warning(
"cannot convert event.unixtime=%s+utcoffset=%s to datetime64: %s",
r(event.unixtime), r(utcoffset), e
)
continue
xaxis.append(x)
yaxis.append(value_func(event))
ax.scatter(xaxis, yaxis, **scatter_kw)
return ax
class PlotSeries(namedtuple('PlotSeries', 'label series extra'), Promotable):
''' Information about a series to be plotted: