-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdata_recorder.py
1278 lines (1155 loc) · 52.4 KB
/
data_recorder.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
# Copyright 2018 Jetperch LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from joulescope.v0.calibration import Calibration
from joulescope.v0.stream_buffer import reduction_downsample, Statistics, stats_to_api, \
stats_invalidate, \
stats_factory, stats_array_factory, stats_array_clear, stats_array_invalidate, \
STATS_FIELD_NAMES, NP_STATS_NAMES, \
I_RANGE_MISSING, SUPPRESS_SAMPLES_MAX, RawProcessor, stats_compute
from joulescope.v0 import array_storage
from joulescope import datafile
import json
import numpy as np
import datetime
import logging
log = logging.getLogger(__name__)
DATA_RECORDER_FORMAT_VERSION = '2'
SAMPLES_PER_REDUCTION = 20000 # 100 Hz @ 2 MSPS
REDUCTIONS_PER_TLV = 20 # 5 Hz @ 2 MSPS
TLVS_PER_BLOCK = 5 # 1 Hz @ 2 MSPS
_STATS_VALUES_V1 = 4
_SIGNALS_UNITS = {
'current': 'A',
'voltage': 'V',
'power': 'W',
'raw_current': 'LSBs',
'raw_voltage': 'LSBs',
'raw': '',
'bits': '',
'current_range': '',
'current_lsb': '',
'voltage_lsb': '',
}
_DOWNSAMPLE_FORMATTERS = {
0: lambda x: x.astype(dtype=np.float32),
1: lambda x: x.astype(dtype=np.float32),
2: lambda x: x.astype(dtype=np.float32),
3: lambda x: (x * 16).astype(dtype=np.uint8),
4: lambda x: (x * 15).astype(dtype=np.uint8),
5: lambda x: (x * 15).astype(dtype=np.uint8),
}
_DOWNSAMPLE_UNFORMATTERS = {
0: lambda x: x,
1: lambda x: x,
2: lambda x: x,
3: lambda x: x.astype(dtype=np.float32) * (1.0 / 16),
4: lambda x: x.astype(dtype=np.float32) * (1.0 / 15),
5: lambda x: x.astype(dtype=np.float32) * (1.0 / 15),
}
def construct_record_filename():
time_start = datetime.datetime.utcnow()
timestamp_str = time_start.strftime('%Y%m%d_%H%M%S')
return f'{timestamp_str}.jls'
class DataRecorder:
"""Record Joulescope data to a file.
:param filehandle: The file-like object or file name.
:param calibration: The calibration bytes in datafile format.
None (default) uses the unit gain calibration.
:param user_data: Arbitrary JSON-serializable user data that is
added to the file.
"""
def __init__(self, filehandle, calibration=None, user_data=None):
log.info('init')
if isinstance(filehandle, str):
self._fh = open(filehandle, 'wb')
filehandle = self._fh
else:
self._fh = None
self._sampling_frequency = 0
self._samples_per_tlv = 0
self._samples_per_block = 0
self._samples_per_reduction = 0
self._reductions_per_tlv = 0
self._reduction = None
self._sample_id_tlv = None # sample id for start of next TLV
self._sample_id_block = None # sample id for start of current block, None if not started yet
self._stream_buffer = None # to ensure same
self._sb_sample_id_last = None
self._voltage_range = None
self._data_buffer = []
self._sample_buffers = {}
self._writer = datafile.DataFileWriter(filehandle)
self._closed = False
self._total_size = 0
if user_data is not None:
b = json.dumps(user_data).encode('utf-8')
self._writer.append(datafile.TAG_USER_JSON, b)
if calibration is not None:
if isinstance(calibration, Calibration):
calibration = calibration.data
self._writer.append_subfile('calibration', calibration)
def _initialize(self, sampling_frequency, data_format):
self._sampling_frequency = sampling_frequency
self._samples_per_reduction = SAMPLES_PER_REDUCTION
self._samples_per_tlv = self._samples_per_reduction * REDUCTIONS_PER_TLV
self._samples_per_block = self._samples_per_tlv * TLVS_PER_BLOCK
# dependent vars
self._reductions_per_tlv = self._samples_per_tlv // self._samples_per_reduction
reduction_block_size = self._samples_per_block // self._samples_per_reduction
self._reduction = stats_array_factory(reduction_block_size)
self._append_configuration(data_format)
self._writer.collection_start(0, 0)
def _append_configuration(self, data_format=None):
data_format = 'none' if data_format is None else str(data_format)
config = {
'type': 'config',
'data_recorder_format_version': DATA_RECORDER_FORMAT_VERSION,
'sampling_frequency': self._sampling_frequency,
'samples_per_reduction': self._samples_per_reduction,
'samples_per_tlv': self._samples_per_tlv,
'samples_per_block': self._samples_per_block,
'reduction_fields': ['current', 'voltage', 'power',
'current_range', 'current_lsb', 'voltage_lsb'],
'data_format': data_format,
'reduction_format': 'v2',
}
cfg_data = json.dumps(config).encode('utf-8')
self._writer.append(datafile.TAG_META_JSON, cfg_data)
def _collection_start(self, data=None):
log.debug('_collection_start()')
c = self._writer.collection_start(1, 0, data=data)
c.metadata = {'start_sample_id': self._sample_id_tlv}
c.on_end = self._collection_end
self._sample_id_block = self._sample_id_tlv
def _collection_end(self, collection):
sample_count = (self._sample_id_tlv - self._sample_id_block)
r_stop = sample_count // self._samples_per_reduction
log.debug('_collection_end(%s, %s)', r_stop, len(self._reduction))
data = self._reduction[:r_stop, :]
arrays = {0x00: data[:, 0]['length'].astype(np.uint64)}
for field_idx, field in enumerate(STATS_FIELD_NAMES):
for stat_idx, stat in enumerate(NP_STATS_NAMES[1:]):
x_id = ((field_idx & 0x0f) << 4) | ((stat_idx + 1) & 0x0f)
x = data[:, field_idx][stat]
arrays[x_id] = x.astype(np.float32)
value = array_storage.pack(arrays, r_stop)
value = value.tobytes()
self._writer.collection_end(collection, value)
self._sample_id_block = None
stats_array_clear(self._reduction)
def stream_notify(self, stream_buffer):
"""Process data from a stream buffer.
:param stream_buffer: The stream_buffer instance which has:
* "output_sampling_frequency" member -> float
* "has_raw" member -> in [True, False]
* "sample_id_range" member => (start, stop)
* "voltage_range" member -> in [0, 1]
* samples_get(start_sample_id, stop_sample_id, dtype)
* data_get(start_sample_id, stop_sample_id, increment, out)
* __len__ : maximum number of samples that stream_buffer holds
"""
finalize = False
if stream_buffer is None:
if self._stream_buffer is None:
return
finalize = True
stream_buffer = self._stream_buffer
sb_start, sb_stop = stream_buffer.sample_id_range
if self._stream_buffer is None:
self._stream_buffer = stream_buffer
data_format = 'raw' if stream_buffer.has_raw else 'float32_v2'
self._initialize(stream_buffer.output_sampling_frequency, data_format)
self._sample_id_tlv = sb_stop
self._sample_id_block = None
if self._samples_per_tlv > len(stream_buffer):
raise ValueError('stream_buffer length too small. %s > %s' %
(self._samples_per_tlv, len(stream_buffer)))
elif self._stream_buffer != stream_buffer:
raise ValueError('Supports only a single stream_buffer instance')
if sb_start > self._sample_id_tlv:
raise ValueError('stream_buffer does not contain sample_id')
while True:
finalize_now = False
sample_id_next = self._sample_id_tlv + self._samples_per_tlv
if sb_stop < sample_id_next:
if finalize and self._sample_id_tlv < sb_stop:
finalize_now = True
sample_id_next = sb_stop
else:
break
self._voltage_range = stream_buffer.voltage_range
if self._sample_id_block is None:
collection_data = {
'v_range': self._voltage_range,
'sample_id': self._sample_id_tlv,
}
collection_data = json.dumps(collection_data).encode('utf-8')
self._collection_start(data=collection_data)
log.debug('_process() add tlv %d', self._sample_id_tlv)
if stream_buffer.has_raw:
self._append_raw_data(self._sample_id_tlv, sample_id_next)
else:
self._append_float_data(self._sample_id_tlv, sample_id_next)
self._total_size += (sample_id_next - self._sample_id_tlv)
tlv_offset = (self._sample_id_tlv - self._sample_id_block) // self._samples_per_tlv
r_start = tlv_offset * self._reductions_per_tlv
r_stop = r_start + self._reductions_per_tlv
stream_buffer.data_get(self._sample_id_tlv, sample_id_next,
self._samples_per_reduction, out=self._reduction[r_start:r_stop, :])
self._sample_id_tlv = sample_id_next
if finalize_now or self._sample_id_tlv - self._sample_id_block >= self._samples_per_block:
self._collection_end(self._writer.collections[-1])
def _append_raw_data(self, start, stop):
if self._closed:
return
b = self._stream_buffer.samples_get(start, stop, fields='raw')
data = b.tobytes()
self._writer.append(datafile.TAG_DATA_BINARY, data, compress=False)
def _append_float_data(self, start, stop):
if self._closed:
return
data = self._stream_buffer.samples_get(start, stop, fields=STATS_FIELD_NAMES)
arrays = {}
for field_idx, field in enumerate(STATS_FIELD_NAMES):
x_id = (field_idx << 4) | 0x01 # stat_idx=mean
x = data['signals'][field]['value']
x = _DOWNSAMPLE_FORMATTERS[field_idx](x)
arrays[x_id] = x
data = array_storage.pack(arrays, stop - start)
data = data.tobytes()
self._writer.append(datafile.TAG_DATA_BINARY, data, compress=False)
def _insert_remove_processed_data(self):
while len(self._data_buffer) and self._data_buffer[0]['time']['sample_id_range']['value'][1] < self._sample_id_tlv:
self._data_buffer.pop()
def _insert_size_pending(self):
self._insert_remove_processed_data()
if not len(self._data_buffer):
return 0
sz = np.sum([x['time']['samples']['value'] for x in self._data_buffer])
start_idx = self._data_buffer[0]['time']['sample_id_range']['value'][0]
sz -= self._sample_id_tlv - start_idx
return sz
def _insert_next(self):
# Will write any pending data up to a full data TLV
# WARNING: does not check for sufficient data to fill a data TLV
# since it needs to also handle the final partial.
if self._sample_id_block is None:
if not len(self._data_buffer):
return
has_raw = 'raw' in self._data_buffer[0]['signals']
collection_data = {'sample_id': self._sample_id_tlv}
if has_raw:
collection_data['v_range'] = self._data_buffer[0]['signals']['raw']['voltage_range']
collection_data = json.dumps(collection_data).encode('utf-8')
self._collection_start(data=collection_data)
offset = 0
finalize_now = True
while len(self._data_buffer):
do_pop = True
data = self._data_buffer[0]
s0, s1 = data['time']['sample_id_range']['value'] # samples, not indices
assert(self._sample_id_tlv + offset >= s0)
idx0 = self._sample_id_tlv + offset - s0 # input buffer starting index
idx1 = s1 - s0 # input buffer ending index
if s1 > self._sample_id_tlv + self._samples_per_tlv:
idx1 = self._sample_id_tlv + self._samples_per_tlv - s0
do_pop = False
idx_end = offset + idx1 - idx0
for field, d in self._sample_buffers.items():
if field == 'raw':
self._sample_buffers[field][offset:idx_end, :] = data['signals'][field]['value'][idx0:idx1, :]
else:
self._sample_buffers[field][offset:idx_end] = data['signals'][field]['value'][idx0:idx1]
offset += idx1 - idx0
if do_pop:
self._data_buffer.pop(0)
if offset >= self._samples_per_tlv:
finalize_now = False
break
# write the data TLV
if 'raw' in self._sample_buffers:
data = self._sample_buffers['raw'][:offset, :].tobytes()
self._writer.append(datafile.TAG_DATA_BINARY, data, compress=False)
else:
arrays = {}
for field_idx, field in enumerate(STATS_FIELD_NAMES):
x_id = (field_idx << 4) | 0x01 # stat_idx=mean
x = self._sample_buffers[field][:offset]
x = _DOWNSAMPLE_FORMATTERS[field_idx](x)
arrays[x_id] = x
data = array_storage.pack(arrays, self._samples_per_tlv)
data = data.tobytes()
self._writer.append(datafile.TAG_DATA_BINARY, data, compress=False)
# update reductions
tlv_offset = (self._sample_id_tlv - self._sample_id_block) // self._samples_per_tlv
r_start = tlv_offset * self._reductions_per_tlv
r_stop = r_start + (offset * self._reductions_per_tlv) // self._samples_per_tlv
for field_idx, field in enumerate(STATS_FIELD_NAMES):
d = self._sample_buffers[field]
for idx in range(0, r_stop - r_start):
r = r_start + idx
k0 = idx * self._samples_per_reduction
k1 = k0 + self._samples_per_reduction
stats_compute(d[k0:k1], self._reduction[r, field_idx:field_idx + 1])
self._sample_id_tlv += self._samples_per_tlv
self._total_size += offset
if finalize_now or self._sample_id_tlv - self._sample_id_block >= self._samples_per_block:
self._collection_end(self._writer.collections[-1])
return
def insert(self, data):
"""Insert sample data.
:param data: A dict in the :meth:`StreamBuffer.samples_get` format.
"""
if self._sample_id_tlv is None: # first call
data_format = 'raw' if 'raw' in data['signals'] else 'float32_v2'
self._initialize(data['time']['sampling_frequency']['value'], data_format)
self._sample_id_tlv = data['time']['sample_id_range']['value'][0]
self._sample_buffers = {}
for field in data['signals'].keys():
if field == 'raw':
d = np.empty((self._samples_per_tlv, 2), dtype=np.uint16)
else:
d = np.empty(self._samples_per_tlv, dtype=np.float32)
self._sample_buffers[field] = d
if data is not None:
self._data_buffer.append(data)
while True:
if self._insert_size_pending() < self._samples_per_tlv:
break
self._insert_next()
if data is None:
self._insert_next() # short data finalize
def _append_meta(self, footer_user_data=None):
index = {
'type': 'footer',
'size': self._total_size, # in samples
}
data = json.dumps(index).encode('utf-8')
self._writer.append(datafile.TAG_META_JSON, data)
if footer_user_data is not None:
data = json.dumps(footer_user_data).encode('utf-8')
self._writer.append(datafile.TAG_USER_JSON, data)
def close(self, footer_user_data=None):
"""Finalize and close the recording."""
if self._closed:
return
if self._sample_id_tlv is None:
self._append_configuration()
if self._stream_buffer:
self.stream_notify(None)
if self._data_buffer:
self.insert(None)
self._closed = True
while len(self._writer.collections):
collection = self._writer.collections[-1]
if len(collection.metadata):
self._collection_end(collection)
else:
self._writer.collection_end()
self._append_meta(footer_user_data)
self._writer.finalize()
if self._fh is not None:
self._fh.close()
self._fh = None
class DataReader:
"""Read Joulescope data from a file."""
def __init__(self):
self.calibration = None
self.config = None
self.footer = None
self._fh_close = False
self._fh = None
self._f = None # type: datafile.DataFileReader
self._data_start_position = 0
self._voltage_range = 0
self._sample_cache = None
self._data_get_handler = None
self._reduction_handler = None
self._samples_get_handler = None
self._statistics_get_handler = None
self.raw_processor = RawProcessor()
self.user_data = None
self.footer_user_data = None
def __str__(self):
if self._f is not None:
return 'DataReader %.2f seconds (%d samples)' % (self.duration, self.footer['size'])
def close(self):
"""Close the recording file."""
if self._fh_close:
self._fh.close()
self._fh_close = False
self._fh = None
self._f = None
self._sample_cache = None
self._reduction_cache = None
def open(self, filehandle):
"""Open a recording file.
:param filehandle: The seekable filehandle or filename string.
"""
self.close()
self.calibration = Calibration() # default calibration
self.config = None
self.footer = None
self._data_start_position = 0
if isinstance(filehandle, str):
log.info('DataReader(%s)', filehandle)
self._fh = open(filehandle, 'rb')
self._fh_close = True
else:
self._fh = filehandle
self._fh_close = False
self._f = datafile.DataFileReader(self._fh)
while True:
tag, value = self._f.peek()
if tag is None:
if self._data_start_position and self.config is not None:
log.warning('Unexpected file truncation, attempting recovery')
sample_count = self._sample_count()
log.warning('Recovery found %d samples', sample_count)
self.footer = {
'type': 'footer',
'size': sample_count, # in samples
}
else:
raise ValueError('could not read file')
break
elif tag == datafile.TAG_SUBFILE:
name, data = datafile.subfile_split(value)
if name == 'calibration':
self.calibration = Calibration().load(data)
elif tag == datafile.TAG_COLLECTION_START:
self._data_start_position = self._f.tell()
elif tag == datafile.TAG_META_JSON:
meta = json.loads(value.decode('utf-8'))
type_ = meta.get('type')
if type_ == 'config':
self._configure(meta)
elif type_ == 'footer':
self.footer = meta
else:
log.warning('Unknown JSON section type=%s', type_)
elif tag == datafile.TAG_USER_JSON:
if self.footer is None:
self.user_data = json.loads(value.decode('utf-8'))
else:
self.footer_user_data = json.loads(value.decode('utf-8'))
elif tag == datafile.TAG_END:
break
self._f.skip()
if self.config is None or self.footer is None:
raise ValueError('could not read file')
log.info('DataReader with %d samples:\n%s', self.footer['size'], json.dumps(self.config, indent=2))
if self._data_start_position == 0 and self.footer['size']:
raise ValueError(f"data not found, but expect {self.footer['size']} samples")
if int(self.config['data_recorder_format_version']) > int(DATA_RECORDER_FORMAT_VERSION):
raise ValueError('Invalid file format')
self.config.setdefault('reduction_fields', ['current', 'voltage', 'power'])
cal = self.calibration
self.raw_processor.calibration_set(cal.current_offset, cal.current_gain, cal.voltage_offset, cal.voltage_gain)
return self
def _configure(self, config):
config.setdefault('data_format', 'raw')
config.setdefault('reduction_format', 'v1')
self.config = config
self._samples_get_handler = getattr(self, '_samples_get_handler_' + config['data_format'])
self._data_get_handler = getattr(self, '_data_get_handler_' + config['data_format'])
self._statistics_get_handler = getattr(self, '_statistics_get_handler_' + config['data_format'])
self._reduction_handler = getattr(self, '_reduction_handler_' + config['reduction_format'])
@property
def sample_id_range(self):
"""The sample ID range.
:return: [start, stop] sample identifiers.
"""
if self._f is not None:
s_start = 0
s_end = int(s_start + self.footer['size'])
return [s_start, s_end]
return [0, 0]
@property
def sampling_frequency(self):
"""The output sampling frequency."""
f = 0.0
if self._f is not None:
f = float(self.config['sampling_frequency'])
if f <= 0.0:
log.warning('Invalid sampling frequency %r, assume 1.0 Hz.', f)
f = 1.0
return f
@property
def input_sampling_frequency(self):
"""The original input sampling frequency."""
f = 0.0
if self._f is None:
pass
elif 'input_sampling_frequency' in self.config:
f = float(self.config['sampling_frequency'])
else:
f = self.sampling_frequency
if f <= 0.0:
log.warning('Invalid input sampling frequency %r, assume 1.0 Hz.', f)
f = 1.0
return f
@property
def output_sampling_frequency(self):
"""The output sampling frequency."""
return self.sampling_frequency
@property
def reduction_frequency(self):
"""The reduction frequency or 1 if no reduction."""
f = 0.0
try:
if self._f is not None:
f = self.config['sampling_frequency'] / self.config['samples_per_reduction']
except Exception:
log.warning('Could not get reduction frequency.')
if f <= 0.0:
log.warning('Invalid input sampling frequency %r, assume 1.0 Hz.', f)
f = 1.0
return f
@property
def duration(self):
"""The data file duration, in seconds."""
f = self.sampling_frequency
if f > 0:
r = self.sample_id_range
return (r[1] - r[0]) / f
return 0.0
@property
def voltage_range(self):
"""The data file voltage range."""
return self._voltage_range
def _sample_count(self):
"""Count the actual samples in the file.
WARNING: this operation may be slow. Use footer when possible.
"""
samples_per_block = self.config['samples_per_block']
sample_count = 0
self._fh.seek(self._data_start_position)
while True:
tag, _ = self._f.peek_tag_length()
if tag is None:
break
if tag == datafile.TAG_COLLECTION_START:
self._f.skip()
sample_count += samples_per_block
else:
self._f.advance()
return sample_count
def _validate_range(self, start=None, stop=None, increment=None):
idx_start, idx_end = self.sample_id_range
if increment is not None:
idx_end = ((idx_end + increment - 1) // increment) * increment
# log.debug('[%d, %d] : [%d, %d]', start, stop, idx_start, idx_end)
if start == idx_start and start == stop:
pass # empty is allowed
elif not idx_start <= start < idx_end:
raise ValueError('start out of range: %d <= %d < %d' % (idx_start, start, idx_end))
elif not idx_start <= stop <= idx_end:
raise ValueError('stop out of range: %d <= %d <= %d: %s' %
(idx_start, stop, idx_end, increment))
if stop < start:
stop = start
return start, stop
def _sample_tlv(self, sample_idx):
"""Get the sample data entry for the TLV containing sample_idx.
:param sample_idx: The sample index.
:return: The dict containing the data.
"""
if self._sample_cache and self._sample_cache['start'] <= sample_idx < self._sample_cache['stop']:
# cache hit
return self._sample_cache
idx_start, idx_end = self.sample_id_range
if not idx_start <= sample_idx < idx_end:
raise ValueError('sample index out of range: %d <= %d < %d' % (idx_start, sample_idx, idx_end))
if self._sample_cache is not None:
log.debug('_sample_cache cache miss: %s : %s %s',
sample_idx, self._sample_cache['start'], self._sample_cache['stop'])
# seek
samples_per_tlv = self.config['samples_per_tlv']
samples_per_block = self.config['samples_per_block']
tgt_block = sample_idx // samples_per_block
if self._sample_cache is not None and sample_idx > self._sample_cache['start']:
# continue forward
self._fh.seek(self._sample_cache['tlv_pos'])
voltage_range = self._sample_cache['voltage_range']
block_fh_pos = self._sample_cache['block_pos']
current_sample_idx = self._sample_cache['start']
block_counter = current_sample_idx // samples_per_block
else: # add case for rewind?
log.debug('_sample_tlv resync to beginning')
self._fh.seek(self._data_start_position)
voltage_range = 0
block_fh_pos = 0
block_counter = 0
current_sample_idx = 0
if self._f.advance() != datafile.TAG_COLLECTION_START:
raise ValueError('data section must be single collection')
while True:
tag, _ = self._f.peek_tag_length()
if tag is None:
log.error('sample_tlv not found before end of file: %s > %s', sample_idx, current_sample_idx)
break
if tag == datafile.TAG_COLLECTION_START:
if block_counter < tgt_block:
self._f.skip()
block_counter += 1
else:
block_fh_pos = self._f.tell()
tag, collection_bytes = next(self._f)
c = datafile.Collection.decode(collection_bytes)
if c.data:
collection_start_meta = json.loads(c.data)
voltage_range = collection_start_meta.get('v_range', 0)
self._voltage_range = voltage_range
current_sample_idx = block_counter * samples_per_block
elif tag == datafile.TAG_COLLECTION_END:
block_counter += 1
self._f.advance()
elif tag == datafile.TAG_DATA_BINARY:
tlv_stop = current_sample_idx + samples_per_tlv
if current_sample_idx <= sample_idx < tlv_stop:
# found it!
tlv_pos = self._f.tell()
tag, value = next(self._f)
self._sample_cache = {
'voltage_range': voltage_range,
'start': current_sample_idx,
'stop': tlv_stop,
'value': value,
'tlv_pos': tlv_pos,
'block_pos': block_fh_pos,
}
return self._sample_cache
else:
self._f.advance()
current_sample_idx = tlv_stop
else:
self._f.advance()
def _raw(self, start=None, stop=None):
"""Get the raw data.
:param start: The starting sample (must already be validated).
:param stop: The ending sample (must already be validated).
:return: The output which is (out_raw, bits, out_cal).
"""
x_start, x_stop = self.sample_id_range
self._fh.seek(self._data_start_position)
self._validate_range(start, stop)
length = stop - start
if length <= 0:
return np.empty((0, 2), dtype=np.uint16)
# process extra before & after to handle filtering
if start > SUPPRESS_SAMPLES_MAX:
sample_idx = start - SUPPRESS_SAMPLES_MAX
prefix_count = SUPPRESS_SAMPLES_MAX
else:
sample_idx = 0
prefix_count = start
if stop + SUPPRESS_SAMPLES_MAX <= x_stop:
end_idx = stop + SUPPRESS_SAMPLES_MAX
else:
end_idx = x_stop
out_idx = 0
d_raw = np.empty((end_idx - sample_idx, 2), dtype=np.uint16)
if self._f.advance() != datafile.TAG_COLLECTION_START:
raise ValueError('data section must be single collection')
while sample_idx < end_idx:
sample_cache = self._sample_tlv(sample_idx)
if sample_cache is None:
break
value = sample_cache['value']
data = np.frombuffer(value, dtype=np.uint16).reshape((-1, 2))
b_start = sample_idx - sample_cache['start']
length = sample_cache['stop'] - sample_cache['start'] - b_start
out_remaining = end_idx - sample_idx
length = min(length, out_remaining)
if length <= 0:
break
b_stop = b_start + length
d = data[b_start:b_stop, :]
d_raw[out_idx:(out_idx + length), :] = d
out_idx += length
sample_idx += length
d_raw = d_raw[:out_idx, :]
self.raw_processor.reset()
self.raw_processor.voltage_range = self._voltage_range
d_cal, d_bits = self.raw_processor.process_bulk(d_raw.reshape((-1, )))
j = prefix_count
k = min(prefix_count + stop - start, out_idx)
return d_raw[j:k, :], d_bits[j:k], d_cal[j:k, :]
def _downsampled(self, start, stop, fields):
"""Get the _downsampled data.
:param start: The starting sample (must already be validated).
:param stop: The ending sample (must already be validated).
:return: The output which is dict of field name to values.
"""
self._fh.seek(self._data_start_position)
start, stop = self._validate_range(start, stop)
length = stop - start
field_idxs = []
if fields is None:
fields = ['current', 'voltage', 'power', 'current_range', 'current_lsb', 'voltage_lsb']
for field in fields:
if field not in STATS_FIELD_NAMES:
raise ValueError(f'Field {field} not available')
idx = (STATS_FIELD_NAMES.index(field) << 4) | 1
field_idxs.append((field, idx))
rv = {}
for _, field_idx in field_idxs:
rv[field_idx] = np.empty(length, dtype=np.float32)
out_idx = 0
while start < stop:
sample_cache = self._sample_tlv(start)
if sample_cache is None:
break
v = np.frombuffer(sample_cache['value'], dtype=np.uint8)
value, sample_count = array_storage.unpack(v)
b_start = start - sample_cache['start']
length = sample_cache['stop'] - sample_cache['start'] - b_start
out_remaining = stop - start
length = min(length, out_remaining)
if length <= 0:
break
b_stop = b_start + length
for _, field_idx in field_idxs:
rv[field_idx][out_idx:(out_idx + length)] = value[field_idx][b_start:b_stop]
out_idx += length
start += length
result = {}
for field, field_idx in field_idxs:
x = rv[field_idx][:out_idx]
idx = STATS_FIELD_NAMES.index(field)
fn = _DOWNSAMPLE_UNFORMATTERS[idx]
result[field] = fn(x)
return result
def _reduction_tlv(self, reduction_idx):
sz = self.config['samples_per_reduction']
incr = self.config['samples_per_block'] // sz
tgt_r_idx = reduction_idx
if self._reduction_cache and self._reduction_cache['r_start'] <= tgt_r_idx < self._reduction_cache['r_stop']:
return self._reduction_cache
if self._reduction_cache is not None:
log.debug('_reduction_tlv cache miss: %s : %s %s',
tgt_r_idx, self._reduction_cache['r_start'], self._reduction_cache['r_stop'])
idx_start, idx_end = self.sample_id_range
r_start = idx_start // sz
r_stop = idx_end // sz
if not r_start <= tgt_r_idx < r_stop:
raise ValueError('reduction index out of range: %d <= %d < %d', r_start, tgt_r_idx, r_stop)
if self._reduction_cache is not None and tgt_r_idx > self._reduction_cache['r_start']:
# continue forward
self._fh.seek(self._reduction_cache['next_collection_pos'])
r_idx = self._reduction_cache['r_stop']
else: # add case for rewind?
log.debug('_reduction_tlv resync to beginning')
self._fh.seek(self._data_start_position)
r_idx = 0
if self._f.advance() != datafile.TAG_COLLECTION_START:
raise ValueError('data section must be single collection')
self._fh.seek(self._data_start_position)
if self._f.advance() != datafile.TAG_COLLECTION_START:
raise ValueError('data section must be single collection')
while True:
tag, _ = self._f.peek_tag_length()
if tag is None or tag == datafile.TAG_COLLECTION_END:
log.error('reduction_tlv not found before end of file: %s > %s', r_stop, r_idx)
break
elif tag != datafile.TAG_COLLECTION_START:
raise ValueError('invalid file format: not collection start')
r_idx_next = r_idx + incr
if tgt_r_idx >= r_idx_next:
self._f.skip()
r_idx = r_idx_next
continue
self._f.collection_goto_end()
tag, value = next(self._f)
if tag != datafile.TAG_COLLECTION_END:
raise ValueError('invalid file format: not collection end')
data = self._reduction_handler(value)
self._reduction_cache = {
'r_start': r_idx,
'r_stop': r_idx_next,
'buffer': data,
'next_collection_pos': self._f.tell()
}
return self._reduction_cache
def _reduction_handler_v1(self, value):
field_count = len(self.config['reduction_fields'])
b = np.frombuffer(value, dtype=np.float32).reshape((-1, field_count, _STATS_VALUES_V1))
data = stats_array_factory(len(b))
stats_array_invalidate(data)
samples_per_reduction = self.config['samples_per_reduction']
data[:, :]['length'] = samples_per_reduction
for idx in range(field_count):
data[:, idx]['mean'] = b[:, 0, 0]
data[:, idx]['variance'] = (samples_per_reduction - 1) * b[:, 0, 1] * b[:, 0, 1]
data[:, idx]['min'] = b[:, 0, 2]
data[:, idx]['min'] = b[:, 0, 3]
return data
def _reduction_handler_v2(self, value):
value = np.frombuffer(value, dtype=np.uint8)
data, sample_count = array_storage.unpack(value)
stats_array = stats_array_factory(sample_count)
stats_array_invalidate(stats_array)
for key, x in data.items():
field_idx = (key >> 4) & 0x0f
stats_idx = key & 0x0f
stats_name = NP_STATS_NAMES[stats_idx]
stats_array[:, field_idx][stats_name] = x # .astype(dtype=np.float64)
for idx in range(1, len(STATS_FIELD_NAMES)):
stats_array[:, idx]['length'] = stats_array[:, 0]['length']
return stats_array
def get_reduction(self, start=None, stop=None, units=None, out=None):
"""Get the fixed reduction with statistics.
:param start: The starting sample identifier (inclusive).
:param stop: The ending sample identifier (exclusive).
:param units: The units for start and stop.
'seconds' or None is in floating point seconds relative to the view.
'samples' is in stream buffer sample indices.
:return: The The np.ndarray((N, STATS_FIELD_COUNT), dtype=DTYPE)
reduction data which normally is memory mapped to the underlying
data, but will be copied on rollover.
"""
start, stop = self.normalize_time_arguments(start, stop, units)
self._fh.seek(self._data_start_position)
self._validate_range(start, stop)
sz = self.config['samples_per_reduction']
if sz < 1:
sz = 1
r_start = start // sz
total_length = (stop - start) // sz
r_stop = r_start + total_length
log.info('DataReader.get_reduction(r_start=%r,r_stop=%r)', r_start, r_stop)
if total_length <= 0:
return stats_array_factory(0)
if out is None:
out = stats_array_factory(total_length)
elif len(out) < total_length:
raise ValueError('out too small')
r_idx = r_start
out_idx = 0
while r_idx < r_stop:
reduction_cache = self._reduction_tlv(r_idx)
if reduction_cache is None:
break
data = reduction_cache['buffer']
b_start = r_idx - reduction_cache['r_start']
length = reduction_cache['r_stop'] - reduction_cache['r_start'] - b_start
out_remaining = r_stop - r_idx
length = min(length, out_remaining)
if length <= 0:
break
out[out_idx:(out_idx + length), :] = data[b_start:(b_start + length), :]
out_idx += length
r_idx += length
if out_idx != total_length:
log.warning('DataReader length mismatch: out_idx=%s, length=%s', out_idx, total_length)
total_length = min(out_idx, total_length)
return out[:total_length, :]
def _get_reduction_stats(self, start, stop):
"""Get statistics over the reduction
:param start: The starting sample identifier (inclusive).
:param stop: The ending sample identifier (exclusive).
:return: The tuple of ((sample_start, sample_stop), :class:`Statistics`).
"""
# log.debug('_get_reduction_stats(%s, %s)', start, stop)
s = Statistics()
sz = self.config['samples_per_reduction']
incr = self.config['samples_per_block'] // sz
r_start = start // sz
if (r_start * sz) < start:
r_start += 1
r_stop = stop // sz
if r_start >= r_stop: # cannot use the reductions
s_start = r_start * sz
return (s_start, s_start), s
r_idx = r_start
while r_idx < r_stop:
reduction_cache = self._reduction_tlv(r_idx)
if reduction_cache is None:
break
data = reduction_cache['buffer']
b_start = r_idx - reduction_cache['r_start']
length = reduction_cache['r_stop'] - reduction_cache['r_start'] - b_start
out_remaining = r_stop - r_idx
length = min(length, out_remaining)
if length <= 0:
break
r = reduction_downsample(data, b_start, b_start + length, length)
s.combine(Statistics(stats=r[0, :]))
r_idx += length
return (r_start * sz, r_stop * sz), s
def _data_get_handler_none(self, start, stop, out):
return None
def _data_get_handler_raw(self, start, stop, out):
_, d_bits, d_cal = self._raw(start, stop)
i, v = d_cal[:, 0], d_cal[:, 1]
out[:, 0]['mean'] = i
out[:, 1]['mean'] = v
out[:, 2]['mean'] = i * v
out[:, 3]['mean'] = np.bitwise_and(d_bits, 0x0f)