-
Notifications
You must be signed in to change notification settings - Fork 310
/
Copy path_signal.py
2615 lines (2266 loc) · 88.7 KB
/
_signal.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
import math
import os
import sys
import numpy as np
from wfdb.io import download, _coreio, util
MAX_I32 = 2147483647
MIN_I32 = -2147483648
# Formats in which all samples align with integer (power-of-two) boundaries
ALIGNED_FMTS = ["8", "16", "32", "61", "80", "160"]
# Formats in which not all samples align with integer boundaries
UNALIGNED_FMTS = ["212", "310", "311", "24"]
# Formats in which samples are encoded in a variable number of bits
COMPRESSED_FMTS = ["508", "516", "524"]
# Formats which are stored in offset binary form
OFFSET_FMTS = ["80", "160"]
# All WFDB dat formats - https://www.physionet.org/physiotools/wag/signal-5.htm
DAT_FMTS = ALIGNED_FMTS + UNALIGNED_FMTS + COMPRESSED_FMTS
# Bytes required to hold each sample (including wasted space) for each
# WFDB dat formats
BYTES_PER_SAMPLE = {
"8": 1,
"16": 2,
"24": 3,
"32": 4,
"61": 2,
"80": 1,
"160": 2,
"212": 1.5,
"310": 4 / 3.0,
"311": 4 / 3.0,
"508": 0,
"516": 0,
"524": 0,
}
# The bit resolution of each WFDB dat format
BIT_RES = {
"8": 8,
"16": 16,
"24": 24,
"32": 32,
"61": 16,
"80": 8,
"160": 16,
"212": 12,
"310": 10,
"311": 10,
"508": 8,
"516": 16,
"524": 24,
}
# Numpy dtypes used to load dat files of each format.
DATA_LOAD_TYPES = {
"8": "<i1",
"16": "<i2",
"24": "<u1",
"32": "<i4",
"61": ">i2",
"80": "<u1",
"160": "<u2",
"212": "<u1",
"310": "<u1",
"311": "<u1",
}
# Minimum and maximum digital sample values for each of the WFDB dat
# formats.
SAMPLE_VALUE_RANGE = {
"80": (-(2**7), 2**7 - 1),
"508": (-(2**7), 2**7 - 1),
"310": (-(2**9), 2**9 - 1),
"311": (-(2**9), 2**9 - 1),
"212": (-(2**11), 2**11 - 1),
"16": (-(2**15), 2**15 - 1),
"61": (-(2**15), 2**15 - 1),
"160": (-(2**15), 2**15 - 1),
"516": (-(2**15), 2**15 - 1),
"24": (-(2**23), 2**23 - 1),
"524": (-(2**23), 2**23 - 1),
"32": (-(2**31), 2**31 - 1),
"8": (-(2**31), 2**31 - 1),
}
# Digital value used to represent a missing/invalid sample, in each of the
# WFDB dat formats.
INVALID_SAMPLE_VALUE = {
"80": -(2**7),
"508": -(2**7),
"310": -(2**9),
"311": -(2**9),
"212": -(2**11),
"16": -(2**15),
"61": -(2**15),
"160": -(2**15),
"516": -(2**15),
"24": -(2**23),
"524": -(2**23),
"32": -(2**31),
"8": None,
}
class SignalMixin(object):
"""
Mixin class with signal methods. Inherited by Record class.
Attributes
----------
N/A
"""
def wr_dats(self, expanded, write_dir):
"""
Write all dat files associated with a record
expanded=True to use e_d_signal instead of d_signal.
Parameters
----------
expanded : bool
Whether to transform the `e_d_signal` attribute (True) or
the `d_signal` attribute (False).
write_dir : str
The directory to write the output file to.
Returns
-------
N/A
"""
if not self.n_sig:
return
# Get all the fields used to write the header
# Assuming this method was called through wrsamp,
# these will have already been checked in wrheader()
_, _ = self.get_write_fields()
if expanded:
# Using list of arrays e_d_signal
self.check_field("e_d_signal")
else:
# Check the validity of the d_signal field
self.check_field("d_signal")
# Check the cohesion of the d_signal field against the other
# fields used to write the header. (Note that for historical
# reasons, this doesn't actually check any of the optional
# header fields.)
self.check_sig_cohesion([], expanded)
# Write each of the specified dat files
self.wr_dat_files(expanded=expanded, write_dir=write_dir)
def check_sig_cohesion(self, write_fields, expanded):
"""
Check the cohesion of the d_signal/e_d_signal field with the other
fields used to write the record.
Parameters
----------
write_fields : list
All the fields used to write the header.
expanded : bool
Whether to transform the `e_d_signal` attribute (True) or
the `d_signal` attribute (False).
Returns
-------
N/A
"""
# Using list of arrays e_d_signal
if expanded:
# Set default samps_per_frame
spf = self.samps_per_frame
for ch in range(len(spf)):
if spf[ch] is None:
spf[ch] = 1
# Match the actual signal shape against stated length and number of channels
if self.n_sig != len(self.e_d_signal):
raise ValueError(
"n_sig does not match the length of e_d_signal"
)
for ch in range(self.n_sig):
if len(self.e_d_signal[ch]) != spf[ch] * self.sig_len:
raise ValueError(
f"Length of channel {ch} does not match "
f"samps_per_frame[{ch}]*sig_len"
)
# For each channel (if any), make sure the digital format has no values out of bounds
for ch in range(self.n_sig):
fmt = self.fmt[ch]
dmin, dmax = _digi_bounds(self.fmt[ch])
chmin = min(self.e_d_signal[ch])
chmax = max(self.e_d_signal[ch])
if (chmin < dmin) or (chmax > dmax):
raise IndexError(
"Channel "
+ str(ch)
+ " contain values outside allowed range ["
+ str(dmin)
+ ", "
+ str(dmax)
+ "] for fmt "
+ str(fmt)
)
# Ensure that the checksums and initial value fields match the digital signal (if the fields are present)
if self.n_sig > 0:
if "checksum" in write_fields:
realchecksum = self.calc_checksum(expanded)
if self.checksum != realchecksum:
print(
"The actual checksum of e_d_signal is: ",
realchecksum,
)
raise ValueError(
"checksum field does not match actual checksum of e_d_signal"
)
if "init_value" in write_fields:
realinit_value = [
self.e_d_signal[ch][0] for ch in range(self.n_sig)
]
if self.init_value != realinit_value:
print(
"The actual init_value of e_d_signal is: ",
realinit_value,
)
raise ValueError(
"init_value field does not match actual init_value of e_d_signal"
)
# Using uniform d_signal
else:
# Match the actual signal shape against stated length and number of channels
if (self.sig_len, self.n_sig) != self.d_signal.shape:
print("sig_len: ", self.sig_len)
print("n_sig: ", self.n_sig)
print("d_signal.shape: ", self.d_signal.shape)
raise ValueError(
"sig_len and n_sig do not match shape of d_signal"
)
# For each channel (if any), make sure the digital format has no values out of bounds
for ch in range(self.n_sig):
fmt = self.fmt[ch]
dmin, dmax = _digi_bounds(self.fmt[ch])
chmin = min(self.d_signal[:, ch])
chmax = max(self.d_signal[:, ch])
if (chmin < dmin) or (chmax > dmax):
raise IndexError(
"Channel "
+ str(ch)
+ " contain values outside allowed range ["
+ str(dmin)
+ ", "
+ str(dmax)
+ "] for fmt "
+ str(fmt)
)
# Ensure that the checksums and initial value fields match the digital signal (if the fields are present)
if self.n_sig > 0:
if "checksum" in write_fields:
realchecksum = self.calc_checksum()
if self.checksum != realchecksum:
print(
"The actual checksum of d_signal is: ", realchecksum
)
raise ValueError(
"checksum field does not match actual checksum of d_signal"
)
if "init_value" in write_fields:
realinit_value = list(self.d_signal[0, :])
if self.init_value != realinit_value:
print(
"The actual init_value of d_signal is: ",
realinit_value,
)
raise ValueError(
"init_value field does not match actual init_value of d_signal"
)
def set_p_features(self, do_dac=False, expanded=False):
"""
Use properties of the physical signal field to set the following
features: n_sig, sig_len.
Parameters
----------
do_dac : bool, optional
Whether to use the digital signal field to perform dac
conversion to get the physical signal field beforehand.
expanded : bool, optional
Whether to transform the `e_p_signal` attribute (True) or
the `p_signal` attribute (False). If True, the `samps_per_frame`
attribute is also required.
Returns
-------
N/A
Notes
-----
Regarding dac conversion:
- fmt, gain, and baseline must all be set in order to perform
dac.
- Unlike with adc, there is no way to infer these fields.
- Using the fmt, gain and baseline fields, dac is performed,
and (e_)p_signal is set.
*Developer note: Seems this function will be very infrequently used.
The set_d_features function seems far more useful.
"""
if expanded:
if do_dac:
self.check_field("e_d_signal")
self.check_field("fmt", "all")
self.check_field("adc_gain", "all")
self.check_field("baseline", "all")
self.check_field("samps_per_frame", "all")
# All required fields are present and valid. Perform DAC
self.e_p_signal = self.dac(expanded)
# Use e_p_signal to set fields
self.check_field("e_p_signal", "all")
self.sig_len = int(
len(self.e_p_signal[0]) / self.samps_per_frame[0]
)
self.n_sig = len(self.e_p_signal)
else:
if do_dac:
self.check_field("d_signal")
self.check_field("fmt", "all")
self.check_field("adc_gain", "all")
self.check_field("baseline", "all")
# All required fields are present and valid. Perform DAC
self.p_signal = self.dac()
# Use p_signal to set fields
self.check_field("p_signal")
self.sig_len = self.p_signal.shape[0]
self.n_sig = self.p_signal.shape[1]
def set_d_features(self, do_adc=False, single_fmt=True, expanded=False):
"""
Use properties of the digital signal field to set the following
features: n_sig, sig_len, init_value, checksum, and possibly
*(fmt, adc_gain, baseline).
Parameters
----------
do_adc : bools, optional
Whether to use the physical signal field to perform adc
conversion to get the digital signal field beforehand.
single_fmt : bool, optional
Whether to use a single digital format during adc, if it is
performed.
expanded : bool, optional
Whether to transform the `e_p_signal` attribute (True) or
the `p_signal` attribute (False).
Returns
-------
N/A
Notes
-----
Regarding adc conversion:
- If fmt is unset:
- Neither adc_gain nor baseline may be set. If the digital values
used to store the signal are known, then the file format should
also be known.
- The most appropriate fmt for the signals will be calculated and the
`fmt` attribute will be set. Given that neither `adc_gain` nor
`baseline` is allowed to be set, optimal values for those fields will
then be calculated and set as well.
- If fmt is set:
- If both adc_gain and baseline are unset, optimal values for those
fields will be calculated the fields will be set.
- If both adc_gain and baseline are set, the function will continue.
- If only one of adc_gain and baseline are set, this function will
raise an error. It makes no sense to know only one of those fields.
- ADC will occur after valid values for fmt, adc_gain, and baseline are
present, using all three fields.
"""
if expanded:
# adc is performed.
if do_adc:
self.check_field("e_p_signal", "all")
# If there is no fmt set it, adc_gain, and baseline
if self.fmt is None:
# Make sure that neither adc_gain nor baseline are set
if self.adc_gain is not None or self.baseline is not None:
raise Exception(
"If fmt is not set, gain and baseline may not be set either."
)
# Choose appropriate fmts based on estimated signal resolutions.
res = est_res(self.e_p_signal)
self.fmt = _wfdb_fmt(res, single_fmt)
# If there is a fmt set
else:
self.check_field("fmt", "all")
# Neither field set
if self.adc_gain is None and self.baseline is None:
# Calculate and set optimal gain and baseline values to convert physical signals
self.adc_gain, self.baseline = self.calc_adc_params()
# Exactly one field set
elif (self.adc_gain is None) ^ (self.baseline is None):
raise Exception(
"If fmt is set, gain and baseline should both be set or not set."
)
self.check_field("adc_gain", "all")
self.check_field("baseline", "all")
# All required fields are present and valid. Perform ADC
self.e_d_signal = self.adc(expanded)
# Use e_d_signal to set fields
self.check_field("e_d_signal", "all")
self.sig_len = int(
len(self.e_d_signal[0]) / self.samps_per_frame[0]
)
self.n_sig = len(self.e_d_signal)
self.init_value = [sig[0] for sig in self.e_d_signal]
self.checksum = self.calc_checksum(expanded)
else:
# adc is performed.
if do_adc:
self.check_field("p_signal")
# If there is no fmt set
if self.fmt is None:
# Make sure that neither adc_gain nor baseline are set
if self.adc_gain is not None or self.baseline is not None:
raise Exception(
"If fmt is not set, gain and baseline may not be set either."
)
# Choose appropriate fmts based on estimated signal resolutions.
res = est_res(self.p_signal)
self.fmt = _wfdb_fmt(res, single_fmt)
# Calculate and set optimal gain and baseline values to convert physical signals
self.adc_gain, self.baseline = self.calc_adc_params()
# If there is a fmt set
else:
self.check_field("fmt", "all")
# Neither field set
if self.adc_gain is None and self.baseline is None:
# Calculate and set optimal gain and baseline values to convert physical signals
self.adc_gain, self.baseline = self.calc_adc_params()
# Exactly one field set
elif (self.adc_gain is None) ^ (self.baseline is None):
raise Exception(
"If fmt is set, gain and baseline should both be set or not set."
)
self.check_field("adc_gain", "all")
self.check_field("baseline", "all")
# All required fields are present and valid. Perform ADC
self.d_signal = self.adc()
# Use d_signal to set fields
self.check_field("d_signal")
self.sig_len = self.d_signal.shape[0]
self.n_sig = self.d_signal.shape[1]
self.init_value = list(self.d_signal[0, :])
self.checksum = self.calc_checksum()
def adc(self, expanded=False, inplace=False):
"""
Performs analogue to digital conversion of the physical signal stored
in p_signal if expanded is False, or e_p_signal if expanded is True.
The p_signal/e_p_signal, fmt, gain, and baseline fields must all be
valid.
If inplace is True, the adc will be performed inplace on the variable,
the d_signal/e_d_signal attribute will be set, and the
p_signal/e_p_signal field will be set to None.
Parameters
----------
expanded : bool, optional
Whether to transform the `e_p_signal` attribute (True) or
the `p_signal` attribute (False).
inplace : bool, optional
Whether to automatically set the object's corresponding
digital signal attribute and set the physical
signal attribute to None (True), or to return the converted
signal as a separate variable without changing the original
physical signal attribute (False).
Returns
-------
d_signal : ndarray, optional
The digital conversion of the signal. Either a 2d numpy
array or a list of 1d numpy arrays.
Examples:
---------
>>> import wfdb
>>> record = wfdb.rdsamp('sample-data/100')
>>> d_signal = record.adc()
>>> record.adc(inplace=True)
>>> record.dac(inplace=True)
"""
# The digital NAN values for each channel
d_nans = _digi_nan(self.fmt)
# To do: choose the minimum return res needed
intdtype = "int64"
# Convert a physical (1D or 2D) signal array to digital. Note that
# the input array is modified!
def adc_inplace(p_signal, adc_gain, baseline, d_nan):
nanlocs = np.isnan(p_signal)
np.multiply(p_signal, adc_gain, p_signal)
np.add(p_signal, baseline, p_signal)
np.round(p_signal, 0, p_signal)
np.copyto(p_signal, d_nan, where=nanlocs)
d_signal = p_signal.astype(intdtype, copy=False)
return d_signal
# Do inplace conversion and set relevant variables.
if inplace:
if expanded:
for ch, ch_p_signal in enumerate(self.e_p_signal):
ch_d_signal = adc_inplace(
ch_p_signal,
self.adc_gain[ch],
self.baseline[ch],
d_nans[ch],
)
self.e_p_signal[ch] = ch_d_signal
self.e_d_signal = self.e_p_signal
self.e_p_signal = None
else:
self.d_signal = adc_inplace(
self.p_signal,
self.adc_gain,
self.baseline,
d_nans,
)
self.p_signal = None
# Return the variable
else:
if expanded:
e_d_signal = []
for ch, ch_p_signal in enumerate(self.e_p_signal):
ch_d_signal = adc_inplace(
ch_p_signal.copy(),
self.adc_gain[ch],
self.baseline[ch],
d_nans[ch],
)
e_d_signal.append(ch_d_signal)
return e_d_signal
else:
return adc_inplace(
self.p_signal.copy(),
self.adc_gain,
self.baseline,
d_nans,
)
def dac(self, expanded=False, return_res=64, inplace=False):
"""
Performs the digital to analogue conversion of the signal stored
in `d_signal` if expanded is False, or `e_d_signal` if expanded
is True.
The d_signal/e_d_signal, fmt, gain, and baseline fields must all be
valid.
If inplace is True, the dac will be performed inplace on the
variable, the p_signal/e_p_signal attribute will be set, and the
d_signal/e_d_signal field will be set to None.
Parameters
----------
expanded : bool, optional
Whether to transform the `e_d_signal attribute` (True) or
the `d_signal` attribute (False).
return_res : int, optional
The numpy array dtype of the returned signals. Options are: 64,
32, 16, and 8, where the value represents the numpy int or float
dtype. Note that the value cannot be 8 when physical is True
since there is no float8 format.
inplace : bool, optional
Whether to automatically set the object's corresponding
physical signal attribute and set the digital signal
attribute to None (True), or to return the converted
signal as a separate variable without changing the original
digital signal attribute (False).
Returns
-------
p_signal : ndarray, optional
The physical conversion of the signal. Either a 2d numpy
array or a list of 1d numpy arrays.
Examples
--------
>>> import wfdb
>>> record = wfdb.rdsamp('sample-data/100', physical=False)
>>> p_signal = record.dac()
>>> record.dac(inplace=True)
>>> record.adc(inplace=True)
"""
# The digital NAN values for each channel
d_nans = _digi_nan(self.fmt)
# Get the appropriate float dtype
if return_res == 64:
floatdtype = "float64"
elif return_res == 32:
floatdtype = "float32"
else:
floatdtype = "float16"
# Do inplace conversion and set relevant variables.
if inplace:
if expanded:
for ch in range(self.n_sig):
# NAN locations for the channel
ch_nanlocs = self.e_d_signal[ch] == d_nans[ch]
self.e_d_signal[ch] = self.e_d_signal[ch].astype(
floatdtype, copy=False
)
np.subtract(
self.e_d_signal[ch],
self.baseline[ch],
self.e_d_signal[ch],
)
np.divide(
self.e_d_signal[ch],
self.adc_gain[ch],
self.e_d_signal[ch],
)
self.e_d_signal[ch][ch_nanlocs] = np.nan
self.e_p_signal = self.e_d_signal
self.e_d_signal = None
else:
nanlocs = self.d_signal == d_nans
# Do float conversion immediately to avoid potential under/overflow
# of efficient int dtype
self.d_signal = self.d_signal.astype(floatdtype, copy=False)
np.subtract(self.d_signal, self.baseline, self.d_signal)
np.divide(self.d_signal, self.adc_gain, self.d_signal)
self.d_signal[nanlocs] = np.nan
self.p_signal = self.d_signal
self.d_signal = None
# Return the variable
else:
if expanded:
p_signal = []
for ch in range(self.n_sig):
# NAN locations for the channel
ch_nanlocs = self.e_d_signal[ch] == d_nans[ch]
ch_p_signal = self.e_d_signal[ch].astype(
floatdtype, copy=False
)
np.subtract(ch_p_signal, self.baseline[ch], ch_p_signal)
np.divide(ch_p_signal, self.adc_gain[ch], ch_p_signal)
ch_p_signal[ch_nanlocs] = np.nan
p_signal.append(ch_p_signal)
else:
nanlocs = self.d_signal == d_nans
p_signal = self.d_signal.astype(floatdtype, copy=False)
np.subtract(p_signal, self.baseline, p_signal)
np.divide(p_signal, self.adc_gain, p_signal)
p_signal[nanlocs] = np.nan
return p_signal
def calc_adc_gain_baseline(self, ch, minvals, maxvals):
"""
Compute adc_gain and baseline parameters for a given channel.
Parameters
----------
ch: int
The channel that the adc_gain and baseline are being computed for.
minvals: list
The minimum values for each channel.
maxvals: list
The maximum values for each channel.
Returns
-------
adc_gain : float
Calculated `adc_gain` value for a given channel.
baseline : int
Calculated `baseline` value for a given channel.
Notes
-----
This is the mapping equation:
`digital - baseline / adc_gain = physical`
`physical * adc_gain + baseline = digital`
The original WFDB library stores `baseline` as int32.
Constrain abs(adc_gain) <= 2**31 == 2147483648.
This function does carefully deal with overflow for calculated
int32 `baseline` values, but does not consider over/underflow
for calculated float `adc_gain` values.
"""
# Get the minimum and maximum (valid) storage values
dmin, dmax = _digi_bounds(self.fmt[ch])
# add 1 because the lowest value is used to store nans
dmin = dmin + 1
pmin = minvals[ch]
pmax = maxvals[ch]
# Figure out digital samples used to store physical samples
# If the entire signal is NAN, gain/baseline won't be used
if pmin == np.nan:
adc_gain = 1
baseline = 1
# If the signal is just one value, store one digital value.
elif pmin == pmax:
if pmin == 0:
adc_gain = 1
baseline = 1
else:
# All digital values are +1 or -1. Keep adc_gain > 0
adc_gain = abs(1 / pmin)
baseline = 0
# Regular varied signal case.
else:
# The equation is: p = (d - b) / g
# Approximately, pmax maps to dmax, and pmin maps to
# dmin. Gradient will be equal to, or close to
# delta(d) / delta(p), since intercept baseline has
# to be an integer.
# Constraint: baseline must be between +/- 2**31
adc_gain = (dmax - dmin) / (pmax - pmin)
baseline = dmin - adc_gain * pmin
# Make adjustments for baseline to be an integer
# This up/down round logic of baseline is to ensure
# there is no overshoot of dmax. Now pmax will map
# to dmax or dmax-1 which is also fine.
if pmin > 0:
baseline = int(np.ceil(baseline))
else:
baseline = int(np.floor(baseline))
# After baseline is set, adjust gain correspondingly.Set
# the gain to map pmin to dmin, and p==0 to baseline.
# In the case where pmin == 0 and dmin == baseline,
# adc_gain is already correct. Avoid dividing by 0.
if dmin != baseline:
adc_gain = (dmin - baseline) / pmin
# Remap signal if baseline exceeds boundaries.
# This may happen if pmax < 0
if baseline > MAX_I32:
# pmin maps to dmin, baseline maps to 2**31 - 1
# pmax will map to a lower value than before
adc_gain = (MAX_I32) - dmin / abs(pmin)
baseline = MAX_I32
# This may happen if pmin > 0
elif baseline < MIN_I32:
# pmax maps to dmax, baseline maps to -2**31 + 1
adc_gain = (dmax - MIN_I32) / pmax
baseline = MIN_I32
return adc_gain, baseline
def calc_adc_params(self):
"""
Compute appropriate adc_gain and baseline parameters for adc
conversion, given the physical signal and the fmts.
Parameters
----------
N/A
Returns
-------
adc_gains : list
List of calculated `adc_gain` values for each channel.
baselines : list
List of calculated `baseline` values for each channel
"""
adc_gains = []
baselines = []
if self.p_signal is not None:
if np.where(np.isinf(self.p_signal))[0].size:
raise ValueError("Signal contains inf. Cannot perform adc.")
# min and max ignoring nans, unless whole channel is NAN.
# Should suppress warning message.
minvals = np.nanmin(self.p_signal, axis=0)
maxvals = np.nanmax(self.p_signal, axis=0)
for ch in range(np.shape(self.p_signal)[1]):
adc_gain, baseline = self.calc_adc_gain_baseline(
ch, minvals, maxvals
)
adc_gains.append(adc_gain)
baselines.append(baseline)
elif self.e_p_signal is not None:
minvals = []
maxvals = []
for ch in self.e_p_signal:
minvals.append(np.nanmin(ch))
maxvals.append(np.nanmax(ch))
if any(x == math.inf for x in minvals) or any(
x == math.inf for x in maxvals
):
raise ValueError("Signal contains inf. Cannot perform adc.")
for ch, _ in enumerate(self.e_p_signal):
adc_gain, baseline = self.calc_adc_gain_baseline(
ch, minvals, maxvals
)
adc_gains.append(adc_gain)
baselines.append(baseline)
else:
raise Exception(
"Must supply p_signal or e_p_signal to calc_adc_params"
)
return (adc_gains, baselines)
def convert_dtype(self, physical, return_res, smooth_frames):
"""
Convert the dtype of the signal.
Parameters
----------
physical : bool
Specifies whether to return dtype in physical (float) units in the
`p_signal` field (True), or digital (int) units in the `d_signal`
field (False).
return_res : int
The numpy array dtype of the returned signals. Options are: 64,
32, 16, and 8, where the value represents the numpy int or float
dtype. Note that the value cannot be 8 when physical is True
since there is no float8 format.
smooth_frames : bool
Used when reading records with signals having multiple samples
per frame. Specifies whether to smooth the samples in signals
with more than one sample per frame and return an (MxN) uniform
numpy array as the `d_signal` or `p_signal` field (True), or to
return a list of 1d numpy arrays containing every expanded
sample as the `e_d_signal` or `e_p_signal` field (False).
Returns
-------
N/A
"""
if physical:
return_dtype = "float" + str(return_res)
if smooth_frames:
current_dtype = self.p_signal.dtype
if current_dtype != return_dtype:
self.p_signal = self.p_signal.astype(
return_dtype, copy=False
)
else:
for ch in range(self.n_sig):
if self.e_p_signal[ch].dtype != return_dtype:
self.e_p_signal[ch] = self.e_p_signal[ch].astype(
return_dtype, copy=False
)
else:
return_dtype = "int" + str(return_res)
if smooth_frames:
current_dtype = self.d_signal.dtype
if current_dtype != return_dtype:
# Do not allow changing integer dtype to lower value due to over/underflow
if int(str(current_dtype)[3:]) > int(str(return_dtype)[3:]):
raise Exception(
"Cannot convert digital samples to lower dtype. Risk of overflow/underflow."
)
self.d_signal = self.d_signal.astype(
return_dtype, copy=False
)
else:
for ch in range(self.n_sig):
current_dtype = self.e_d_signal[ch].dtype
if current_dtype != return_dtype:
# Do not allow changing integer dtype to lower value due to over/underflow
if int(str(current_dtype)[3:]) > int(
str(return_dtype)[3:]
):
raise Exception(
"Cannot convert digital samples to lower dtype. Risk of overflow/underflow."
)
self.e_d_signal[ch] = self.e_d_signal[ch].astype(
return_dtype, copy=False
)
return
def calc_checksum(self, expanded=False):
"""
Calculate the checksum(s) of the input signal.
Parameters
----------
expanded : bool, optional
Whether to transform the `e_d_signal` attribute (True) or
the `d_signal` attribute (False).
Returns
-------
cs : list
The resulting checksum-ed signal.
"""
if expanded:
cs = [int(np.sum(s) % 65536) for s in self.e_d_signal]
else:
cs = np.sum(self.d_signal, 0) % 65536
cs = [int(c) for c in cs]
return cs
def wr_dat_files(self, expanded=False, write_dir=""):
"""
Write each of the specified dat files.
Parameters
----------
expanded : bool, optional
Whether to transform the `e_d_signal` attribute (True) or
the `d_signal` attribute (False).
write_dir : str, optional
The directory to write the output file to.
Returns
-------
N/A
"""
# Get the set of dat files to be written, and
# the channels to be written to each file.
file_names, dat_channels = describe_list_indices(self.file_name)
# Get the fmt and byte offset corresponding to each dat file
DAT_FMTS = {}
dat_offsets = {}
for fn in file_names:
DAT_FMTS[fn] = self.fmt[dat_channels[fn][0]]
# byte_offset may not be present
if self.byte_offset is None:
dat_offsets[fn] = 0
else:
dat_offsets[fn] = self.byte_offset[dat_channels[fn][0]]
# Write the dat files
if expanded:
for fn in file_names:
wr_dat_file(
fn,
DAT_FMTS[fn],
None,
dat_offsets[fn],
True,