-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdata_reader.py
2123 lines (1962 loc) · 77.1 KB
/
data_reader.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 os
import io
import sys
import re
import json
import time
import logging
import warnings
from copy import deepcopy
from datetime import datetime
from typing import Union, Optional, Any, List, Dict, Tuple, Sequence
from numbers import Real
import numpy as np
np.set_printoptions(precision=5, suppress=True)
import pandas as pd
import wfdb
from scipy.io import loadmat
from scipy.signal import resample_poly
from easydict import EasyDict as ED
import utils
from utils.misc import ( # noqa: F401
get_record_list_recursive,
get_record_list_recursive2,
get_record_list_recursive3,
dict_to_str,
ms2samples,
list_sum,
)
from utils.utils_signal import ensure_siglen
from utils.scoring_aux_data import ( # noqa: F401
dx_mapping_all,
dx_mapping_scored,
dx_mapping_unscored,
normalize_class,
abbr_to_snomed_ct_code,
df_weights_abbr,
equiv_class_dict,
)
from utils import ecg_arrhythmia_knowledge as EAK # noqa: F401
from cfg import ( # noqa: F401
PlotCfg,
Standard12Leads,
BaseCfg,
six_leads,
four_leads,
three_leads,
two_leads,
)
if BaseCfg.torch_dtype == "float":
_DTYPE = np.float32
else:
_DTYPE = np.float64
__all__ = [
"CINC2021Reader",
]
class CINC2021Reader(object):
"""finished, checked, to improve,
Will Two Do? Varying Dimensions in Electrocardiography:
The PhysioNet/Computing in Cardiology Challenge 2021
ABOUT CinC2021
--------------
0. goal: build an algorithm that can classify cardiac abnormalities from either
- twelve-lead (I, II, III, aVR, aVL, aVF, V1, V2, V3, V4, V5, V6)
- six-lead (I, II, III, aVL, aVR, aVF),
- four-lead (I, II, III, V2)
- three-lead (I, II, V2)
- two-lead (I, II)
ECG recordings.
1. tranches of data:
- CPSC2018 (tranches A and B of CinC2020):
contains 13,256 ECGs (6,877 from tranche A, 3,453 from tranche B),
10,330 ECGs shared as training data, 1,463 retained as validation data,
and 1,463 retained as test data.
Each recording is between 6 and 144 seconds long with a sampling frequency of 500 Hz
- INCARTDB (tranche C of CinC2020):
contains 75 annotated ECGs,
all shared as training data, extracted from 32 Holter monitor recordings.
Each recording is 30 minutes long with a sampling frequency of 257 Hz
- PTB (PTB and PTB-XL, tranches D and E of CinC2020):
contains 22,353 ECGs,
516 + 21,837, all shared as training data.
Each recording is between 10 and 120 seconds long,
with a sampling frequency of either 500 (PTB-XL) or 1,000 (PTB) Hz
- Georgia (tranche F of CinC2020):
contains 20,678 ECGs,
10,334 ECGs shared as training data, 5,167 retained as validation data,
and 5,167 retained as test data.
Each recording is between 5 and 10 seconds long with a sampling frequency of 500 Hz
- American (NEW, UNDISCLOSED):
contains 10,000 ECGs,
all retained as test data,
geographically distinct from the Georgia database.
Perhaps is the main part of the hidden test set of CinC2020
- CUSPHNFH (NEW, the Chapman University, Shaoxing People’s Hospital and Ningbo First Hospital database)
contains 45,152 ECGS,
all shared as training data.
Each recording is 10 seconds long with a sampling frequency of 500 Hz
this tranche contains two subsets:
- Chapman_Shaoxing: "JS00001" - "JS10646"
- Ningbo: "JS10647" - "JS45551"
2. only a part of diagnosis_abbr (diseases that appear in the labels of the 6 tranches of training data) are used in the scoring function, while others are ignored. The scored diagnoses were chosen based on prevalence of the diagnoses in the training data, the severity of the diagnoses, and the ability to determine the diagnoses from ECG recordings. The ignored diagnosis_abbr can be put in a a "non-class" group.
3. the (updated) scoring function has a scoring matrix with nonzero off-diagonal elements. This scoring function reflects the clinical reality that some misdiagnoses are more harmful than others and should be scored accordingly. Moreover, it reflects the fact that confusing some classes is much less harmful than confusing other classes.
4. all data are recorded in the leads ordering of
["I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6"]
using for example the following code:
>>> db_dir = "/media/cfs/wenhao71/data/CinC2021/"
>>> working_dir = "./working_dir"
>>> dr = CINC2021Reader(db_dir=db_dir,working_dir=working_dir)
>>> set_leads = []
>>> for tranche, l_rec in dr.all_records.items():
... for rec in l_rec:
... ann = dr.load_ann(rec)
... leads = ann["df_leads"]["lead_name"].values.tolist()
... if leads not in set_leads:
... set_leads.append(leads)
NOTE
----
1. The datasets have been roughly processed to have a uniform format, hence differ from their original resource (e.g. differe in sampling frequency, sample duration, etc.)
2. The original datasets might have richer metadata (especially those from PhysioNet), which can be fetched from corresponding reader's docstring or website of the original source
3. Each sub-dataset might have its own organizing scheme of data, which should be carefully dealt with
4. There are few "absolute" diagnoses in 12 lead ECGs, where large discrepancies in the interpretation of the ECG can be found even inspected by experts. There is inevitably something lost in translation, especially when you do not have the context. This doesn"t mean making an algorithm isn't important
5. The labels are noisy, which one has to deal with in all real world data
6. each line of the following classes are considered the same (in the scoring matrix):
- RBBB, CRBBB (NOT including IRBBB)
- PAC, SVPB
- PVC, VPB
7. unfortunately, the newly added tranches (C - F) have baseline drift and are much noisier. In contrast, CPSC data have had baseline removed and have higher SNR
8. on Aug. 1, 2020, adc gain (including "resolution", "ADC"? in .hea files) of datasets INCART, PTB, and PTB-xl (tranches C, D, E) are corrected. After correction, (the .tar files of) the 3 datasets are all put in a "WFDB" subfolder. In order to keep the structures consistant, they are moved into "Training_StPetersburg", "Training_PTB", "WFDB" as previously. Using the following code, one can check the adc_gain and baselines of each tranche:
>>> db_dir = "/media/cfs/wenhao71/data/CinC2021/"
>>> working_dir = "./working_dir"
>>> dr = CINC2021(db_dir=db_dir,working_dir=working_dir)
>>> resolution = {tranche: set() for tranche in "ABCDEF"}
>>> baseline = {tranche: set() for tranche in "ABCDEF"}
>>> for tranche, l_rec in dr.all_records.items():
... for rec in l_rec:
... ann = dr.load_ann(rec)
... resolution[tranche] = resolution[tranche].union(set(ann["df_leads"]["adc_gain"]))
... baseline[tranche] = baseline[tranche].union(set(ann["df_leads"]["baseline"]))
>>> print(resolution, baseline)
{"A": {1000.0}, "B": {1000.0}, "C": {1000.0}, "D": {1000.0}, "E": {1000.0}, "F": {1000.0}} {"A": {0}, "B": {0}, "C": {0}, "D": {0}, "E": {0}, "F": {0}}
9. the .mat files all contain digital signals, which has to be converted to physical values using adc gain, basesline, etc. in corresponding .hea files. `wfdb.rdrecord` has already done this conversion, hence greatly simplifies the data loading process.
NOTE that there"s a difference when using `wfdb.rdrecord`: data from `loadmat` are in "channel_first" format, while `wfdb.rdrecord.p_signal` produces data in the "channel_last" format
10. there"re 3 equivalent (2 classes are equivalent if the corr. value in the scoring matrix is 1):
(RBBB, CRBBB), (PAC, SVPB), (PVC, VPB)
11. in the newly (Feb., 2021) created dataset (ref. [7]), header files of each subset were gathered into one separate compressed file. This is due to the fact that updates on the dataset are almost always done in the header files. The correct usage of ref. [7], after uncompressing, is replacing the header files in the folder `All_training_WFDB` by header files from the 6 folders containing all header files from the 6 subsets. This procedure has to be done, since `All_training_WFDB` contains the very original headers with baselines: {"A": {1000.0}, "B": {1000.0}, "C": {1000.0}, "D": {2000000.0}, "E": {200.0}, "F": {4880.0}} (the last 3 are NOT correct)
12. IMPORTANT: organization of the total dataset:
either one moves all training records into ONE folder,
or at least one moves the subsets Chapman_Shaoxing (WFDB_ChapmanShaoxing) and Ningbo (WFDB_Ningbo) into ONE folder, or use the data WFDB_ShaoxingUniv which is the union of WFDB_ChapmanShaoxing and WFDB_Ningbo
Usage
-----
1. ECG arrhythmia detection
ISSUES: (all in CinC2021, left unfixed)
-------
1. reading the .hea files, baselines of all records are 0, however it is not the case if one plot the signal
2. about half of the LAD records satisfy the "2-lead" criteria, but fail for the "3-lead" criteria, which means that their axis is (-30°, 0°) which is not truely LAD
3. (Aug. 15, 2020; resolved, and changed to 1000) tranche F, the Georgia subset, has ADC gain 4880 which might be too high. Thus obtained voltages are too low. 1000 might be a suitable (correct) value of ADC gain for this tranche just as the other tranches.
4. "E04603" (all leads), "E06072" (chest leads, epecially V1-V3), "E06909" (lead V2), "E07675" (lead V3), "E07941" (lead V6), "E08321" (lead V6) has exceptionally large values at rpeaks, reading (`load_data`) these two records using `wfdb` would bring in `nan` values. One can check using the following code
>>> rec = "E04603"
>>> dr.plot(rec, dr.load_data(rec, backend="scipy", units="uv")) # currently raising error
5. many records (headers) have duplicate labels. For example, many records in the Georgia subset has duplicate "PAC" ("284470004") label
6. some records in tranche G has #Dx ending with "," (at least "JS00344"), or consecutive "," (at least "JS03287") in corresponding .hea file
7. tranche G has 2 Dx ("251238007", "6180003") which are listed in neither of dx_mapping_scored.csv nor dx_mapping_unscored.csv
8. about 68 records from tranche G has `nan` values loaded via `wfdb.rdrecord`, which might be caused by motion artefact in some leads
9. "Q0400", "Q2961" are completely flat (constant), while many other records have flat leads, especially V1-V6 leads
References
----------
[0] https://physionetchallenges.github.io/2021/
[1] https://physionetchallenges.github.io/2020/
[2] http://2018.icbeb.org/#
[3] https://physionet.org/content/incartdb/1.0.0/
[4] https://physionet.org/content/ptbdb/1.0.0/
[5] https://physionet.org/content/ptb-xl/1.0.1/
[6] (deprecated) https://storage.cloud.google.com/physionet-challenge-2020-12-lead-ecg-public/
[7] (recommended) https://storage.cloud.google.com/physionetchallenge2021-public-datasets/
"""
def __init__(
self,
db_dir: str,
working_dir: Optional[str] = None,
verbose: int = 2,
**kwargs: Any,
) -> None:
"""
Parameters
----------
db_dir: str,
storage path of the database
working_dir: str, optional,
working directory, to store intermediate files and log file
verbose: int, default 2,
print and log verbosity
"""
self.db_name = "CinC2021"
self.working_dir = os.path.join(working_dir or os.getcwd(), "working_dir")
os.makedirs(self.working_dir, exist_ok=True)
self.verbose = verbose
self.logger = None
self._set_logger(prefix=self.db_name)
self.rec_ext = "mat"
self.ann_ext = "hea"
self.db_tranches = list("ABCDEFG")
self.tranche_names = ED(
{
"A": "CPSC",
"B": "CPSC_Extra",
"C": "StPetersburg",
"D": "PTB",
"E": "PTB_XL",
"F": "Georgia",
"G": "CUSPHNFH",
}
)
self.rec_prefix = ED(
{
"A": "A",
"B": "Q",
"C": "I",
"D": "S",
"E": "HR",
"F": "E",
"G": "JS",
}
)
self.db_dir_base = db_dir
self.db_dirs = ED({tranche: "" for tranche in self.db_tranches})
self._all_records = None
self._stats = pd.DataFrame()
self._stats_columns = {
"record",
"tranche",
"tranche_name",
"nb_leads",
"fs",
"nb_samples",
"age",
"sex",
"medical_prescription",
"history",
"symptom_or_surgery",
"diagnosis",
"diagnosis_scored", # in the form of abbreviations
}
self._ls_rec() # loads file system structures into self.db_dirs and self._all_records
self._aggregate_stats(fast=True)
self._diagnoses_records_list = None
# self._ls_diagnoses_records()
self.fs = ED(
{
"A": 500,
"B": 500,
"C": 257,
"D": 1000,
"E": 500,
"F": 500,
"G": 500,
}
)
self.spacing = ED({t: 1000 / f for t, f in self.fs.items()})
self.all_leads = deepcopy(Standard12Leads)
self._all_leads_set = set(self.all_leads)
self.df_ecg_arrhythmia = dx_mapping_all[["Dx", "SNOMEDCTCode", "Abbreviation"]]
self.ann_items = [
"rec_name",
"nb_leads",
"fs",
"nb_samples",
"datetime",
"age",
"sex",
"diagnosis",
"df_leads",
"medical_prescription",
"history",
"symptom_or_surgery",
]
self.label_trans_dict = equiv_class_dict.copy()
# self.value_correction_factor = ED({tranche:1 for tranche in self.db_tranches})
# self.value_correction_factor.F = 4.88 # ref. ISSUES 3
self.exceptional_records = [
"I0002",
"I0069",
"E04603",
"E06072",
"E06909",
"E07675",
"E07941",
"E08321",
] # ref. ISSUES 4
self.exceptional_records += [ # ref. ISSUE 8
"JS10765",
"JS10767",
"JS10890",
"JS10951",
"JS11887",
"JS11897",
"JS11956",
"JS12751",
"JS13181",
"JS14161",
"JS14343",
"JS14627",
"JS14659",
"JS15624",
"JS16169",
"JS16222",
"JS16813",
"JS19309",
"JS19708",
"JS20330",
"JS20656",
"JS21144",
"JS21617",
"JS21668",
"JS21701",
"JS21853",
"JS21881",
"JS23116",
"JS23450",
"JS23482",
"JS23588",
"JS23786",
"JS23950",
"JS24016",
"JS25106",
"JS25322",
"JS25458",
"JS26009",
"JS26130",
"JS26145",
"JS26245",
"JS26605",
"JS26793",
"JS26843",
"JS26977",
"JS27034",
"JS27170",
"JS27271",
"JS27278",
"JS27407",
"JS27460",
"JS27835",
"JS27985",
"JS28075",
"JS28648",
"JS28757",
"JS33280",
"JS34479",
"JS34509",
"JS34788",
"JS34868",
"JS34879",
"JS35050",
"JS35065",
"JS35192",
"JS35654",
"JS35727",
"JS36015",
"JS36018",
"JS36189",
"JS36244",
"JS36568",
"JS36731",
"JS37105",
"JS37173",
"JS37176",
"JS37439",
"JS37592",
"JS37609",
"JS37781",
"JS38231",
"JS38252",
"JS41844",
"JS41908",
"JS41935",
"JS42026",
"JS42330",
]
self.exceptional_records += [
"Q0400",
"Q2961",
] # ref. ISSUE 9
# TODO: exceptional records can be resolved via reading using `scipy` backend,
# with noise removal using `remove_spikes_naive` from `signal_processing` module
# currently for simplicity, exceptional records would be ignored
def get_subject_id(self, rec: str) -> int:
"""finished, checked,
Parameters
----------
rec: str,
name of the record
Returns
-------
sid: int,
the `subject_id` corr. to `rec`
"""
s2d = {
"A": "11",
"B": "12",
"C": "21",
"D": "31",
"E": "32",
"F": "41",
"G": "51",
}
s2d = {self.rec_prefix[k]: v for k, v in s2d.items()}
prefix = "".join(re.findall(r"[A-Z]", rec))
n = rec.replace(prefix, "")
sid = int(f"{s2d[prefix]}{'0'*(8-len(n))}{n}")
return sid
def _ls_rec(self) -> None:
"""finished, checked,
list all the records and load into `self._all_records`,
facilitating further uses
"""
filename = "record_list.json"
record_list_fp = os.path.join(self.db_dir_base, filename)
if not os.path.isfile(record_list_fp):
record_list_fp = os.path.join(utils._BASE_DIR, "utils", filename)
if os.path.isfile(record_list_fp):
with open(record_list_fp, "r") as f:
self._all_records = json.load(f)
for tranche in self.db_tranches:
# self.db_dirs[tranche] = os.path.join(
# self.db_dir_base, os.path.dirname(self._all_records[tranche][0])
# )
self._all_records[tranche] = [
os.path.basename(f) for f in self._all_records[tranche]
]
self.db_dirs[tranche] = self._find_dir(self.db_dir_base, tranche, 0)
if not self.db_dirs[tranche]:
print(
f"failed to find the directory containing tranche {self.tranche_names[tranche]}"
)
# raise FileNotFoundError(f"failed to find the directory containing tranche {self.tranche_names[tranche]}")
self._all_records[tranche] = [
os.path.basename(f)
for f in self._all_records[tranche]
if os.path.isfile(
os.path.join(self.db_dirs[tranche], f"{f}.{self.rec_ext}")
)
]
else:
print(
"Please wait patiently to let the reader find all records of all the tranches..."
)
start = time.time()
rec_patterns_with_ext = {
tranche: f"^{self.rec_prefix[tranche]}(?:\\d+).{self.rec_ext}$"
for tranche in self.db_tranches
}
self._all_records = get_record_list_recursive3(
self.db_dir_base, rec_patterns_with_ext
)
to_save = deepcopy(self._all_records)
for tranche in self.db_tranches:
tmp_dirname = [os.path.dirname(f) for f in self._all_records[tranche]]
if len(set(tmp_dirname)) != 1:
if len(set(tmp_dirname)) > 1:
print(
f"records of tranche {tranche} are stored in several folders!"
)
# raise ValueError(f"records of tranche {tranche} are stored in several folders!")
else:
print(f"no record found for tranche {tranche}!")
# raise ValueError(f"no record found for tranche {tranche}!")
self.db_dirs[tranche] = os.path.join(self.db_dir_base, tmp_dirname[0])
self._all_records[tranche] = [
os.path.basename(f) for f in self._all_records[tranche]
]
print(f"Done in {time.time() - start:.5f} seconds!")
with open(os.path.join(self.db_dir_base, filename), "w") as f:
json.dump(to_save, f)
with open(os.path.join(utils._BASE_DIR, "utils", filename), "w") as f:
json.dump(to_save, f)
self._all_records = ED(self._all_records)
def _aggregate_stats(self, fast: bool = False) -> None:
"""finished, checked,
aggregate stats on the whole dataset
Parameters
----------
fast: bool, default False,
if True, only load the cached stats,
otherwise aggregate from scratch
"""
stats_file = "stats.csv"
list_sep = ";"
stats_file_fp = os.path.join(self.db_dir_base, stats_file)
stats_file_fp_aux = os.path.join(utils._BASE_DIR, "utils", stats_file)
if os.path.isfile(stats_file_fp):
self._stats = pd.read_csv(stats_file_fp, keep_default_na=False)
elif os.path.isfile(stats_file_fp_aux):
self._stats = pd.read_csv(stats_file_fp_aux, keep_default_na=False)
if not fast and (
self._stats.empty or self._stats_columns != set(self._stats.columns)
):
print(
"Please wait patiently to let the reader collect statistics on the whole dataset..."
)
start = time.time()
self._stats = pd.DataFrame(
list_sum(self._all_records.values()), columns=["record"]
)
self._stats["tranche"] = self._stats["record"].apply(
lambda rec: self._get_tranche(rec)
)
self._stats["tranche_name"] = self._stats["tranche"].apply(
lambda t: self.tranche_names[t]
)
for k in [
"diagnosis",
"diagnosis_scored",
]:
self._stats[
k
] = "" # otherwise cells in the first row would be str instead of list
for idx, row in self._stats.iterrows():
ann_dict = self.load_ann(row["record"])
for k in [
"nb_leads",
"fs",
"nb_samples",
"age",
"sex",
"medical_prescription",
"history",
"symptom_or_surgery",
]:
self._stats.at[idx, k] = ann_dict[k]
for k in [
"diagnosis",
"diagnosis_scored",
]:
self._stats.at[idx, k] = ann_dict[k]["diagnosis_abbr"]
self.logger.debug(
f"stats of {row.tranche_name} -- {row.record} --> ({idx+1} / {len(self._stats)}) gathered"
)
for k in ["nb_leads", "fs", "nb_samples"]:
self._stats[k] = self._stats[k].astype(int)
_stats_to_save = self._stats.copy()
for k in [
"diagnosis",
"diagnosis_scored",
]:
_stats_to_save[k] = _stats_to_save[k].apply(
lambda ln: list_sep.join(ln)
)
_stats_to_save.to_csv(stats_file_fp, index=False)
_stats_to_save.to_csv(stats_file_fp_aux, index=False)
print(f"Done in {time.time() - start:.5f} seconds!")
else:
print("converting dtypes of columns `diagnosis` and `diagnosis_scored`...")
for k in [
"diagnosis",
"diagnosis_scored",
]:
for idx, row in self._stats.iterrows():
self._stats.at[idx, k] = list(
filter(lambda v: len(v) > 0, row[k].split(list_sep))
)
def _find_dir(self, root: str, tranche: str, level: int = 0) -> str:
"""finished, checked,
Parameters
----------
root: str,
the root directory at which the data reader is searching
tranche: str,
the tranche to locate the directory containing it
level: int, default 0,
an identifier for ternimation of the search, regardless of finding the target directory or not
Returns
-------
res: str,
the directory containing the tranche,
if is "", then not found
"""
# print(f"searching for dir for tranche {self.tranche_names[tranche]} with root {root} at level {level}")
if level > 2:
print(
f"failed to find the directory containing tranche {self.tranche_names[tranche]}"
)
return
# raise FileNotFoundError(f"failed to find the directory containing tranche {self.tranche_names[tranche]}")
rec_pattern = f"^{self.rec_prefix[tranche]}(?:\\d+).{self.rec_ext}$"
res = ""
candidates = os.listdir(root)
if len(list(filter(re.compile(rec_pattern).search, candidates))) > 0:
res = root
return res
new_roots = [
os.path.join(root, item)
for item in candidates
if os.path.isdir(os.path.join(root, item))
]
for r in new_roots:
tmp = self._find_dir(r, tranche, level + 1)
if tmp:
res = tmp
return res
return res
@property
def all_records(self):
"""finished, checked"""
if self._all_records is None:
self._ls_rec()
return self._all_records
@property
def df_stats(self):
""" """
if self._stats.empty:
warnings.warn("the dataframe of stats is empty, try using _aggregate_stats")
return self._stats
def _ls_diagnoses_records(self) -> None:
"""finished, checked,
list all the records for all diagnoses
"""
filename = "diagnoses_records_list.json"
dr_fp = os.path.join(self.db_dir_base, filename)
if not os.path.isfile(dr_fp):
dr_fp = os.path.join(utils._BASE_DIR, "utils", filename)
if os.path.isfile(dr_fp):
with open(dr_fp, "r") as f:
self._diagnoses_records_list = json.load(f)
else:
print(
"Please wait several minutes patiently to let the reader list records for each diagnosis..."
)
start = time.time()
self._diagnoses_records_list = {
d: [] for d in df_weights_abbr.columns.values.tolist()
}
if not self._stats.empty:
for d in df_weights_abbr.columns.values.tolist():
self._diagnoses_records_list[d] = sorted(
self._stats[
self._stats["diagnosis_scored"].apply(lambda ln: d in ln)
]["record"].tolist()
)
else:
for tranche, l_rec in self.all_records.items():
for rec in l_rec:
ann = self.load_ann(rec)
ld = ann["diagnosis_scored"]["diagnosis_abbr"]
for d in ld:
self._diagnoses_records_list[d].append(rec)
print(f"Done in {time.time() - start:.5f} seconds!")
with open(os.path.join(self.db_dir_base, filename), "w") as f:
json.dump(self._diagnoses_records_list, f)
with open(os.path.join(utils._BASE_DIR, "utils", filename), "w") as f:
json.dump(self._diagnoses_records_list, f)
self._diagnoses_records_list = ED(self._diagnoses_records_list)
@property
def diagnoses_records_list(self):
"""finished, checked"""
if self._diagnoses_records_list is None:
self._ls_diagnoses_records()
return self._diagnoses_records_list
def _set_logger(self, prefix: Optional[str] = None) -> None:
"""finished, checked,
config the logger,
currently NOT used,
Parameters
----------
prefix: str, optional,
prefix (for each line) of the logger, and its file name
"""
_prefix = prefix + "-" if prefix else ""
self.logger = logging.getLogger(f"{_prefix}-{self.db_name}-logger")
log_filepath = os.path.join(self.working_dir, f"{_prefix}{self.db_name}.log")
print(f"log file path is set {log_filepath}")
c_handler = logging.StreamHandler(sys.stdout)
f_handler = logging.FileHandler(log_filepath)
if self.verbose >= 2:
print("levels of c_handler and f_handler are set DEBUG")
c_handler.setLevel(logging.DEBUG)
f_handler.setLevel(logging.DEBUG)
self.logger.setLevel(logging.DEBUG)
elif self.verbose >= 1:
print("level of c_handler is set INFO, level of f_handler is set DEBUG")
c_handler.setLevel(logging.INFO)
f_handler.setLevel(logging.DEBUG)
self.logger.setLevel(logging.DEBUG)
else:
print("levels of c_handler and f_handler are set WARNING")
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.WARNING)
self.logger.setLevel(logging.WARNING)
# Create formatters and add it to handlers
c_format = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
f_format = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)
self.logger.addHandler(c_handler)
self.logger.addHandler(f_handler)
def _get_tranche(self, rec: str) -> str:
"""finished, checked,
get the tranche's symbol (one of "A","B","C","D","E","F") of a record via its name
Parameters
----------
rec: str,
name of the record
Returns
-------
tranche, str,
symbol of the tranche, ref. `self.rec_prefix`
"""
prefix = "".join(re.findall(r"[A-Z]", rec))
tranche = {v: k for k, v in self.rec_prefix.items()}[prefix]
return tranche
def get_data_filepath(self, rec: str, with_ext: bool = True) -> str:
"""finished, checked,
get the absolute file path of the data file of `rec`
Parameters
----------
rec: str,
name of the record
with_ext: bool, default True,
if True, the returned file path comes with file extension,
otherwise without file extension,
which is useful for `wfdb` functions
Returns
-------
fp: str,
absolute file path of the data file of the record
"""
tranche = self._get_tranche(rec)
fp = os.path.join(self.db_dirs[tranche], f"{rec}.{self.rec_ext}")
if not with_ext:
fp = os.path.splitext(fp)[0]
return fp
def get_header_filepath(self, rec: str, with_ext: bool = True) -> str:
"""finished, checked,
get the absolute file path of the header file of `rec`
Parameters
----------
rec: str,
name of the record
with_ext: bool, default True,
if True, the returned file path comes with file extension,
otherwise without file extension,
which is useful for `wfdb` functions
Returns
-------
fp: str,
absolute file path of the header file of the record
"""
tranche = self._get_tranche(rec)
fp = os.path.join(self.db_dirs[tranche], f"{rec}.{self.ann_ext}")
if not with_ext:
fp = os.path.splitext(fp)[0]
return fp
def get_ann_filepath(self, rec: str, with_ext: bool = True) -> str:
"""finished, checked,
alias for `get_header_filepath`
"""
fp = self.get_header_filepath(rec, with_ext=with_ext)
return fp
def load_data(
self,
rec: str,
leads: Optional[Union[str, List[str]]] = None,
data_format: str = "channel_first",
backend: str = "wfdb",
units: str = "mV",
fs: Optional[Real] = None,
) -> np.ndarray:
"""finished, checked,
load physical (converted from digital) ecg data,
which is more understandable for humans
Parameters
----------
rec: str,
name of the record
leads: str or list of str, optional,
the leads to load
data_format: str, default "channel_first",
format of the ecg data,
"channel_last" (alias "lead_last"), or
"channel_first" (alias "lead_first")
backend: str, default "wfdb",
the backend data reader, can also be "scipy"
units: str, default "mV",
units of the output signal, can also be "μV", with an alias of "uV"
fs: real number, optional,
if not None, the loaded data will be resampled to this frequency
Returns
-------
data: ndarray,
the ecg data
"""
assert data_format.lower() in [
"channel_first",
"lead_first",
"channel_last",
"lead_last",
]
# tranche = self._get_tranche(rec)
if leads is None or leads == "all":
_leads = self.all_leads
elif isinstance(leads, str):
_leads = [leads]
else:
_leads = leads
# if tranche in "CD" and fs == 500: # resample will be done at the end of the function
# data = self.load_resampled_data(rec)
if backend.lower() == "wfdb":
rec_fp = self.get_data_filepath(rec, with_ext=False)
# p_signal of "lead_last" format
wfdb_rec = wfdb.rdrecord(rec_fp, physical=True, channel_names=_leads)
data = np.asarray(wfdb_rec.p_signal.T, dtype=_DTYPE)
# lead_units = np.vectorize(lambda s: s.lower())(wfdb_rec.units)
elif backend.lower() == "scipy":
# loadmat of "lead_first" format
rec_fp = self.get_data_filepath(rec, with_ext=True)
data = loadmat(rec_fp)["val"]
header_info = self.load_ann(rec, raw=False)["df_leads"]
baselines = header_info["baseline"].values.reshape(data.shape[0], -1)
adc_gain = header_info["adc_gain"].values.reshape(data.shape[0], -1)
data = np.asarray(data - baselines, dtype=_DTYPE) / adc_gain
leads_ind = [self.all_leads.index(item) for item in _leads]
data = data[leads_ind, :]
# lead_units = np.vectorize(lambda s: s.lower())(header_info["df_leads"]["adc_units"].values)
else:
raise ValueError(
f"backend `{backend.lower()}` not supported for loading data"
)
# ref. ISSUES 3, for multiplying `value_correction_factor`
# data = data * self.value_correction_factor[tranche]
if units.lower() in ["uv", "μv"]:
data = data * 1000
rec_fs = self.get_fs(rec, from_hea=True)
if fs is not None and fs != rec_fs:
data = resample_poly(data, fs, rec_fs, axis=1).astype(_DTYPE)
# if fs is not None and fs != self.fs[tranche]:
# data = resample_poly(data, fs, self.fs[tranche], axis=1)
if data_format.lower() in ["channel_last", "lead_last"]:
data = data.T
return data
def load_ann(
self, rec: str, raw: bool = False, backend: str = "wfdb"
) -> Union[dict, str]:
"""finished, checked,
load annotations (header) stored in the .hea files
Parameters
----------
rec: str,
name of the record
raw: bool, default False,
if True, the raw annotations without parsing will be returned
backend: str, default "wfdb", case insensitive,
if is "wfdb", `wfdb.rdheader` will be used to load the annotations;
if is "naive", annotations will be parsed from the lines read from the header files
Returns
-------
ann_dict, dict or str,
the annotations with items: ref. `self.ann_items`
"""
# tranche = self._get_tranche(rec)
ann_fp = self.get_ann_filepath(rec, with_ext=True)
with open(ann_fp, "r") as f:
header_data = f.read().splitlines()
if raw:
ann_dict = "\n".join(header_data)
return ann_dict
if backend.lower() == "wfdb":
ann_dict = self._load_ann_wfdb(rec, header_data)
elif backend.lower() == "naive":
ann_dict = self._load_ann_naive(header_data)
else:
raise ValueError(
f"backend `{backend.lower()}` not supported for loading annotations"
)
return ann_dict
def _load_ann_wfdb(self, rec: str, header_data: List[str]) -> dict:
"""finished, checked,
Parameters
----------
rec: str,
name of the record
header_data: list of str,
list of lines read directly from a header file,
complementary to data read using `wfdb.rdheader` if applicable,
this data will be used, since `datetime` is not well parsed by `wfdb.rdheader`
Returns
-------
ann_dict, dict,
the annotations with items: ref. `self.ann_items`
"""
header_fp = self.get_header_filepath(rec, with_ext=False)
header_reader = wfdb.rdheader(header_fp)
ann_dict = {}
(
ann_dict["rec_name"],
ann_dict["nb_leads"],
ann_dict["fs"],
ann_dict["nb_samples"],
ann_dict["datetime"],
daytime,
) = header_data[0].split(" ")
ann_dict["nb_leads"] = int(ann_dict["nb_leads"])
ann_dict["fs"] = int(ann_dict["fs"])
ann_dict["nb_samples"] = int(ann_dict["nb_samples"])
try:
ann_dict["datetime"] = datetime.strptime(
" ".join([ann_dict["datetime"], daytime]), "%d-%b-%Y %H:%M:%S"
)
except Exception:
pass
try: # see NOTE. 1.
ann_dict["age"] = int(
[ln for ln in header_reader.comments if "Age" in ln][0]
.split(":")[-1]
.strip()
)
except Exception:
ann_dict["age"] = np.nan
try: # only "10726" has "NaN" sex