Repository navigation
Expand file tree
/
Copy pathdata_reader.py
More file actions
1884 lines (1696 loc) · 70.9 KB
/
Copy pathdata_reader.py
File metadata and controls
1884 lines (1696 loc) · 70.9 KB
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 re
import os
import warnings
from copy import deepcopy
from pathlib import Path
from collections import defaultdict
from abc import abstractmethod
from typing import Union, Optional, Any, List, Dict, Tuple, Sequence
import numpy as np
import pandas as pd
import wfdb
try:
import librosa
except Exception:
librosa = None
import torch
try:
import torchaudio
except Exception:
torchaudio = None
import scipy.signal as SS # noqa: F401
import scipy.io as sio
try:
import scipy.io.wavfile as sio_wav
except Exception:
sio_wav = None
import IPython
from tqdm.auto import tqdm
from torch_ecg.databases.base import PhysioNetDataBase, DataBaseInfo
from torch_ecg.utils.utils_signal import butter_bandpass_filter
from torch_ecg.utils.misc import (
get_record_list_recursive,
get_record_list_recursive3,
ReprMixin,
list_sum,
add_docstring,
)
from torch_ecg.utils.download import http_get
from cfg import BaseCfg
from utils.schmidt_spike_removal import schmidt_spike_removal
__all__ = [
"PCGDataBase",
"CINC2022Reader",
"CINC2016Reader",
"EPHNOGRAMReader",
"CompositeReader",
]
_BACKEND_PRIORITY = [
"torchaudio",
"librosa",
"scipy",
"wfdb",
]
_HeartMurmurInfo = """
About Heart Murmur
------------------
1. A heart murmur is a blowing, whooshing, or rasping sound heard **during a heartbeat**. The sound is caused by turbulent (rough) blood flow through the heart valves or near the heart. ([source](https://medlineplus.gov/ency/article/003266.htm))
2. A murmur is a series of vibrations of variable duration, audible with a stethoscope at the chest wall, that emanates from the heart or great vessels. A **systolic murmur** is a murmur that begins during or after the first heart sound and ends before or during the second heart sound. ([source](https://www.ncbi.nlm.nih.gov/books/NBK345/)) A **diastolic murmur** is a sound of some duration occurring during diastole. ([source](https://www.ncbi.nlm.nih.gov/books/NBK346/))
3. ([Wikipedia](https://en.wikipedia.org/wiki/Heart_murmur)) Heart murmurs may have a distinct pitch, duration and timing. Murmurs have seven main characteristics. These include timing, shape, location, radiation, intensity, pitch and quality
- Timing refers to whether the murmur is a
* systolic murmur
* diastolic murmur. Diastolic murmurs are usually abnormal, and may be early, mid or late diastolic ([source](https://www.utmb.edu/pedi_ed/CoreV2/Cardiology/cardiologyV2/cardiologyV24.html))
* continuous murmur
- Shape refers to the intensity over time. Murmurs can be crescendo, decrescendo or crescendo-decrescendo
* Crescendo murmurs increase in intensity over time
* Decrescendo murmurs decrease in intensity over time
* Crescendo-decrescendo murmurs have both shapes over time, resembling a diamond or kite shape
- Location refers to where the heart murmur is usually heard best. There are **four** places on the anterior chest wall to listen for heart murmurs. Each location roughly corresponds to a specific part of the heart.
| Region | Location | Heart Valve Association|
|-----------|-------------------------------------------|------------------------|
| Aortic | 2nd right intercostal space | Aortic valve |
| Pulmonic | 2nd left intercostal spaces | Pulmonic valve |
| Tricuspid | 4th left intercostal space | Tricuspid valve |
| Mitral | 5th left mid-clavicular intercostal space | Mitral valve |
- Radiation refers to where the sound of the murmur travels.
- Intensity refers to the loudness of the murmur with grades according to the [Levine scale](https://en.wikipedia.org/wiki/Levine_scale), from 1 to 6
| Levine scale | Murmur Description |
|--------------|---------------------------------------------------------------------------------------------------------|
| 1 | only audible on listening carefully for some time |
| 2 | faint but immediately audible on placing the stethoscope on the chest |
| 3 | loud, readily audible but with no palpable thrill |
| 4 | loud with a palpable thrill |
| 5 | loud with a palpable thrill, audible with only the rim of the stethoscope touching the chest |
| 6 | loud with a palpable thrill, audible with the stethoscope not touching the chest but lifted just off it |
- Pitch may be
* low
* medium
* high
This depends on whether auscultation is best with the bell or diaphragm of a stethoscope.
- Quality refers to **unusual characteristics** of a murmur. For example
* blowing
* harsh
* rumbling
* musical
4. Heart sounds usually has frequency lower than 500 Hz (mostly lower than 300 Hz) (inferred from [source](https://biologicalproceduresonline.biomedcentral.com/articles/10.1186/1480-9222-13-7) Figure 2). frequency of heart sounds is low in range between 20 and 150 Hz.
5. Instantaneous dominant heart sound frequencies ranged from 130 to 410 Hz (mean ± standard deviation 282 ± 70 Hz). Peak murmur frequencies ranged from 200 to 410 Hz (308 ± 70 Hz) ([source](https://www.ajconline.org/article/0002-9149(89)90491-8/pdf))
6. innocent murmurs had lower frequencies (below 200 Hz) and a frequency spectrum with a more harmonic structure than pathological cases ([source](https://bmcpediatr.biomedcentral.com/articles/10.1186/1471-2431-7-23)). [Table 4](https://bmcpediatr.biomedcentral.com/articles/10.1186/1471-2431-7-23/tables/4) is very important and copied as follows
| Group | Amplitude (%) | Low freq limit (Hz) | High freq limit (Hz) |
|--------------|---------------|---------------------|----------------------|
| Vibratory | 23 ± 9 | 72 ± 15 | 161 ± 22 |
| Ejection | 20 ± 9 | 60 ± 9 | 142 ± 51 |
| Pathological | 30 ± 20 | 52 ± 19 | 299 ± 133 |
| p-value | 0.013 | < 0.001 | < 0.001 |
7. the principal frequencies of heart sounds and murmurs are at the lower end of this range, from 20 to 500 Hz; The murmur containing the highest frequency sound is aortic regurgitation, whose dominant frequencies are approximately 400 Hz. The principal frequencies of other sounds and murmurs are between 100 and 400 Hz ([source1](https://www.sciencedirect.com/science/article/pii/B9780323392761000391), [source2](https://www.sciencedirect.com/topics/agricultural-and-biological-sciences/heart-sounds))
"""
@add_docstring(_HeartMurmurInfo)
class PCGDataBase(PhysioNetDataBase):
""" """
__name__ = "PCGDataBase"
def __init__(
self,
db_name: str,
db_dir: Optional[str] = None,
fs: int = 1000,
audio_backend: str = "torchaudio",
working_dir: Optional[str] = None,
verbose: int = 2,
**kwargs: Any,
) -> None:
"""
Parameters
----------
db_name: str,
name of the database
db_dir: str, optional,
storage path of the database
fs: int, default 1000,
(re-)sampling frequency of the audio
audio_backend: str, default "torchaudio",
audio backend to use, can be one of
"librosa", "torchaudio", "scipy", "wfdb",
case insensitive.
"librosa" or "torchaudio" is recommended.
working_dir: str, optional,
working directory, to store intermediate files and log file
verbose: int, default 2,
log verbosity
kwargs: auxilliary key word arguments
"""
super().__init__(db_name, db_dir, working_dir, verbose, **kwargs)
self.db_dir = (
Path(self.db_dir).resolve().absolute()
) # will be fixed in `torch_ecg`
self.fs = fs
self.dtype = kwargs.get("dtype", BaseCfg.np_dtype)
self.audio_backend = audio_backend.lower()
if self.audio_backend not in self.available_backends():
self.audio_backend = self.available_backends()[0]
warnings.warn(
f"audio backend {audio_backend.lower()} is not available, "
f"using {self.audio_backend} instead"
)
if self.audio_backend == "torchaudio":
def torchaudio_load(file: str, fs: int) -> Tuple[torch.Tensor, int]:
try:
data, new_fs = torchaudio.load(file, normalize=True)
except Exception:
data, new_fs = torchaudio.load(file, normalization=True)
return data, new_fs
self._audio_load_func = torchaudio_load
elif self.audio_backend == "librosa":
def librosa_load(file: str, fs: int) -> Tuple[torch.Tensor, int]:
data, _ = librosa.load(file, sr=fs, mono=False)
return torch.from_numpy(data.reshape((-1, data.shape[-1]))), fs
self._audio_load_func = librosa_load
elif self.audio_backend == "scipy":
def scipy_load(file: str, fs: int) -> Tuple[torch.Tensor, int]:
new_fs, data = sio_wav.read(file)
data = (data / (2**15)).astype(self.dtype)[np.newaxis, :]
return torch.from_numpy(data), new_fs
self._audio_load_func = scipy_load
elif self.audio_backend == "wfdb":
warnings.warn(
"loading result using wfdb is inconsistent with other backends"
)
def wfdb_load(file: str, fs: int) -> Tuple[torch.Tensor, int]:
record = wfdb.rdrecord(file, physical=True) # channel last
sig = record.p_signal.T.astype(self.dtype)
return torch.from_numpy(sig), record.fs[0]
self._audio_load_func = wfdb_load
self.data_ext = None
self.ann_ext = None
self.header_ext = "hea"
self._all_records = None
@staticmethod
def available_backends() -> List[str]:
""" """
ab = ["wfdb"]
if torchaudio is not None:
ab.append("torchaudio")
if librosa is not None:
ab.append("librosa")
if sio_wav is not None:
ab.append("scipy")
ab = sorted(ab, key=lambda x: _BACKEND_PRIORITY.index(x))
return ab
def _auto_infer_units(self) -> None:
"""
disable this function implemented in the base class
"""
print("DO NOT USE THIS FUNCTION for a PCG database!")
@abstractmethod
def play(self, rec: str, **kwargs) -> IPython.display.Audio:
""" """
raise NotImplementedError
def _reset_fs(self, new_fs: int) -> None:
""" """
self.fs = new_fs
_CINC2022_INFO = DataBaseInfo(
title="""
The CirCor DigiScope Phonocardiogram Dataset (main resource for CinC2022)
""",
about="""
1. 5272 heart sound recordings (.wav format, sampling rate 4000 Hz) were collected from the main 4 auscultation locations of 1568 subjects, aged between 0 and 21 years (mean ± STD = 6.1 ± 4.3 years), with a duration between 4.8 to 80.4 seconds (mean ± STD = 22.9 ± 7.4 s)
2. segmentation annotations (.tsv format) regarding the location of fundamental heart sounds (S1 and S2) in the recordings have been obtained using a semi-supervised scheme. The annotation files are composed of three distinct columns: the first column corresponds to the time instant (in seconds) where the wave was detected for the first time, the second column corresponds to the time instant (in seconds) where the wave was detected for the last time, and the third column corresponds to an identifier that uniquely identifies the detected wave. Here, we use the following convention:
- The S1 wave is identified by the integer 1.
- The systolic period is identified by the integer 2.
- The S2 wave is identified by the integer 3.
- The diastolic period is identified by the integer 4.
- The unannotated segments of the signal are identified by the integer 0.
""",
usage=[
"Heart murmur detection",
"Heart sound segmentation",
],
note="""
1. the "Murmur" column (records whether heart murmur can be heard or not) and the "Outcome" column (the expert cardiologist's overall diagnosis using **clinical history, physical examination, analog auscultation, echocardiogram, etc.**) are **NOT RELATED**. All of the 6 combinations (["Present", "Absent", "Unknown"] x ["Abnormal", "Normal"]) occur in the dataset.
2. the segmentation files do NOT in general (totally 132 such files) have the same length (namely the second column of the last row of these .tsv files) as the audio files.
""",
issues="""
1. the segmentation file `50782_MV_1.tsv` (versions 1.0.2, 1.0.3) is broken.
2. the challenge website states that the `Age` variable takes values in `Neonate`, `Infant`, `Child`, `Adolescent`, and `Young adult`. However, from the statistics csv file (training_data.csv), there's no subject whose `Age` column has value `Young adult`. Instead, there are 74 subject with null `Age` value, which only indicates that their ages were not recorded and may or may not belong to the “Young adult” age group.
""",
references=[
"https://moody-challenge.physionet.org/2022/",
"https://physionet.org/content/circor-heart-sound/1.0.3/",
],
doi=[
"10.1109/JBHI.2021.3137048",
"10.13026/tshs-mw03",
],
)
@add_docstring(f"\n{_HeartMurmurInfo}\n", mode="append")
@add_docstring(_CINC2022_INFO.format_database_docstring())
class CINC2022Reader(PCGDataBase):
""" """
__name__ = "CINC2022Reader"
stats_fillna_val = "NA"
def __init__(
self,
db_dir: Optional[str] = None,
fs: int = 4000,
audio_backend: str = "torchaudio",
working_dir: Optional[str] = None,
verbose: int = 2,
**kwargs: Any,
) -> None:
"""
Parameters
----------
db_dir : str, optional
storage path of the database
fs : int, default 4000
(re-)sampling frequency of the audio
audio_backend : str, default "torchaudio"
audio backend to use, can be one of
"librosa", "torchaudio", "scipy", "wfdb",
case insensitive.
"librosa" or "torchaudio" is recommended.
working_dir : str, optional
working directory, to store intermediate files and log file
verbose : int, default 2
log verbosity
kwargs : dict, optional
auxilliary key word arguments
"""
super().__init__(
db_name="circor-heart-sound",
db_dir=db_dir,
fs=fs,
audio_backend=audio_backend,
working_dir=working_dir,
verbose=verbose,
**kwargs,
)
self._version = "1.0.3"
if "training_data" in os.listdir(self.db_dir):
self.data_dir = self.db_dir / "training_data"
else:
self.data_dir = self.db_dir
self.data_ext = "wav"
self.ann_ext = "hea"
self.segmentation_ext = "tsv"
self.segmentation_states = deepcopy(BaseCfg.states)
self.ignore_unannotated = kwargs.get("ignore_unannotated", True)
if self.ignore_unannotated:
self.segmentation_states = [
s for s in self.segmentation_states if s != "unannotated"
]
self.segmentation_map = {n: s for n, s in enumerate(self.segmentation_states)}
if self.ignore_unannotated:
self.segmentation_map[BaseCfg.ignore_index] = "unannotated"
self.auscultation_locations = {
"PV",
"AV",
"MV",
"TV",
"Phc",
}
self._rec_pattern = f"(?P<sid>[\\d]+)\\_(?P<loc>{'|'.join(self.auscultation_locations)})((?:\\_)(?P<num>\\d))?"
self._all_records = None
self._all_subjects = None
self._subject_records = None
self._exceptional_records = ["50782_MV_1"]
self._ls_rec()
self._df_stats = None
self._stats_cols = [
"Patient ID",
"Locations",
"Age",
"Sex",
"Height",
"Weight",
"Pregnancy status",
"Outcome", # added in version 1.0.2 in the official phase
"Murmur",
"Murmur locations",
"Most audible location",
"Systolic murmur timing",
"Systolic murmur shape",
"Systolic murmur grading",
"Systolic murmur pitch",
"Systolic murmur quality",
"Diastolic murmur timing",
"Diastolic murmur shape",
"Diastolic murmur grading",
"Diastolic murmur pitch",
"Diastolic murmur quality",
"Campaign",
"Additional ID",
]
self._df_stats_records = None
self._stats_records_cols = [
"Patient ID",
"Location",
"rec",
"siglen",
"siglen_sec",
"Murmur",
]
self._load_stats()
# attributes for plot
self.palette = {
"systolic": "#d62728",
"diastolic": "#2ca02c",
"S1": "#17becf",
"S2": "#bcbd22",
"default": "#7f7f7f",
}
def _ls_rec(self) -> None:
"""
list all records in the database
"""
write_file = False
self._df_records = pd.DataFrame(columns=["record", "path"])
records_file = self.db_dir / "RECORDS"
if records_file.exists():
self._df_records["record"] = records_file.read_text().splitlines()
self._df_records["path"] = self._df_records["record"].apply(
lambda x: self.db_dir / x
)
else:
write_file = True
# self._all_records = wfdb.get_record_list(self.db_name)
if len(self._df_records) == 0:
write_file = True
self._df_records["path"] = get_record_list_recursive3(
self.db_dir, f"{self._rec_pattern}\\.{self.data_ext}", relative=False
)
self._df_records["path"] = self._df_records["path"].apply(lambda x: Path(x))
data_dir = self._df_records["path"].apply(lambda x: x.parent).unique()
assert len(data_dir) <= 1, "data_dir should be a single directory"
if len(data_dir) == 1: # in case no data found
self.data_dir = data_dir[0]
self._df_records["record"] = self._df_records["path"].apply(lambda x: x.stem)
self._df_records = self._df_records[
~self._df_records["record"].isin(self._exceptional_records)
]
self._df_records.set_index("record", inplace=True)
self._all_records = [
item
for item in self._df_records.index.tolist()
if item not in self._exceptional_records
]
self._all_subjects = sorted(
set([item.split("_")[0] for item in self._all_records]),
key=lambda x: int(x),
)
self._subject_records = defaultdict(list)
for rec in self._all_records:
self._subject_records[self.get_subject(rec)].append(rec)
self._subject_records = dict(self._subject_records)
if write_file:
records_file.write_text(
"\n".join(
self._df_records["path"]
.apply(lambda x: x.relative_to(self.db_dir).as_posix())
.tolist()
)
)
def _load_stats(self) -> None:
"""
collect statistics of the database
"""
print("Reading the statistics from local file...")
stats_file = self.db_dir / "training_data.csv"
if stats_file.exists():
self._df_stats = pd.read_csv(stats_file)
elif self._all_records is not None and len(self._all_records) > 0:
print("No cached statistics found, gathering from scratch...")
self._df_stats = pd.DataFrame()
with tqdm(
self.all_subjects, total=len(self.all_subjects), desc="loading stats"
) as pbar:
for s in pbar:
f = self.data_dir / f"{s}.txt"
content = f.read_text().splitlines()
new_row = {"Patient ID": s}
locations = set()
for line in content:
if not line.startswith("#"):
if line.split()[0] in self.auscultation_locations:
locations.add(line.split()[0])
continue
k, v = line.replace("#", "").split(":")
k, v = k.strip(), v.strip()
if v == "nan":
v = self.stats_fillna_val
new_row[k] = v
new_row["Recording locations:"] = "+".join(locations)
self._df_stats = pd.concat(
[self._df_stats, pd.DataFrame(new_row, index=[0])],
ignore_index=True,
)
self._df_stats.to_csv(stats_file, index=False)
else:
print("No data found locally!")
return
self._df_stats = self._df_stats.fillna(self.stats_fillna_val)
try:
# the column "Locations" is changed to "Recording locations:" in version 1.0.2
self._df_stats.Locations = self._df_stats.Locations.apply(
lambda s: s.split("+")
)
except AttributeError:
self._df_stats["Locations"] = self._df_stats["Recording locations:"].apply(
lambda s: s.split("+")
)
self._df_stats["Murmur locations"] = self._df_stats["Murmur locations"].apply(
lambda s: s.split("+") if s != self.stats_fillna_val else []
)
self._df_stats["Patient ID"] = self._df_stats["Patient ID"].astype(str)
self._df_stats = self._df_stats[self._stats_cols]
for idx, row in self._df_stats.iterrows():
for c in ["Height", "Weight"]:
if row[c] == self.stats_fillna_val:
self._df_stats.at[idx, c] = np.nan
# load stats of the records
print("Reading the statistics of the records from local file...")
stats_file = self.db_dir / "stats_records.csv"
if stats_file.exists():
self._df_stats_records = pd.read_csv(stats_file)
else:
self._df_stats_records = pd.DataFrame(columns=self._stats_records_cols)
with tqdm(
self._df_stats.iterrows(),
total=len(self._df_stats),
desc="loading record stats",
) as pbar:
for _, row in pbar:
sid = row["Patient ID"]
for loc in row["Locations"]:
rec = f"{sid}_{loc}"
if rec not in self._all_records:
continue
header = wfdb.rdheader(str(self.data_dir / f"{rec}"))
if row["Murmur"] == "Unknown":
murmur = "Unknown"
if loc in row["Murmur locations"]:
murmur = "Present"
else:
murmur = "Absent"
new_row = {
"Patient ID": sid,
"Location": loc,
"rec": rec,
"siglen": header.sig_len,
"siglen_sec": header.sig_len / header.fs,
"Murmur": murmur,
}
self._df_stats_records = pd.concat(
[self._df_stats_records, pd.DataFrame(new_row, index=[0])],
ignore_index=True,
)
self._df_stats_records.to_csv(stats_file, index=False)
self._df_stats_records = self._df_stats_records.fillna(self.stats_fillna_val)
def _decompose_rec(self, rec: Union[str, int]) -> Dict[str, str]:
"""
decompose a record name into its components (subject, location, and number)
Parameters
----------
rec: str or int,
the record name or the index of the record in `self.all_records`
Returns
-------
dict,
the components (subject, location, and number) of the record,
with keys "sid", "loc", and "num" respectively
"""
if isinstance(rec, int):
rec = self[rec]
return list(re.finditer(self._rec_pattern, rec))[0].groupdict()
def get_absolute_path(
self, rec: Union[str, int], extension: Optional[str] = None
) -> Path:
"""
get the absolute path of the record `rec`
Parameters
----------
rec: str or int,
record name or index of the record in `self.all_records`
extension: str, optional,
extension of the file
Returns
-------
Path,
absolute path of the file
"""
if isinstance(rec, int):
rec = self[rec]
path = self._df_records.loc[rec, "path"]
if extension is not None and not extension.startswith("."):
extension = f".{extension}"
return path.with_suffix(extension or "").resolve()
def load_data(
self,
rec: Union[str, int],
fs: Optional[int] = None,
data_format: str = "channel_first",
data_type: str = "np",
) -> np.ndarray:
"""
load data from the record `rec`
Parameters
----------
rec: str or int,
the record name or the index of the record in `self.all_records`
fs: int, optional,
the sampling frequency of the record, defaults to `self.fs`,
-1 for the sampling frequency from the audio file
data_format: str, optional,
the format of the returned data, defaults to `channel_first`
can be `channel_last`, `channel_first`, `flat`,
case insensitive
data_type: str, default "np",
the type of the returned data, can be one of "pt", "np",
case insensitive
Returns
-------
data: np.ndarray,
the data of the record
"""
if isinstance(rec, int):
rec = self[rec]
fs = fs or self.fs
if fs == -1:
fs = None
data_file = self.get_absolute_path(rec, self.data_ext)
data, data_fs = self._audio_load_func(data_file, fs)
# data of shape (n_channels, n_samples), of type torch.Tensor
if fs is not None and data_fs != fs:
data = torchaudio.transforms.Resample(data_fs, fs)(data)
if data_format.lower() == "channel_last":
data = data.T
elif data_format.lower() == "flat":
data = data.reshape(-1)
if data_type.lower() == "np":
data = data.numpy()
elif data_type.lower() != "pt":
raise ValueError(f"Unsupported data type: {data_type}")
return data
@add_docstring(load_data.__doc__)
def load_pcg(
self,
rec: Union[str, int],
fs: Optional[int] = None,
data_format: str = "channel_first",
data_type: str = "np",
) -> np.ndarray:
"""alias of `load_data`"""
return self.load_data(rec, fs, data_format, data_type)
def load_ann(
self, rec_or_sid: Union[str, int], class_map: Optional[Dict[str, int]] = None
) -> Union[str, int]:
"""
load classification annotation of the record `rec` or the subject `sid`
Parameters
----------
rec_or_sid: str or int,
the record name or the index of the record in `self.all_records`
or the subject id
class_map: dict, optional,
the mapping of the annotation classes
Returns
-------
ann: str or int,
the class of the record,
or the number of the class if `class_map` is provided
"""
if isinstance(rec_or_sid, int):
rec_or_sid = self[rec_or_sid]
_class_map = class_map or {}
if rec_or_sid in self.all_subjects:
ann = self.df_stats[self.df_stats["Patient ID"] == rec_or_sid].iloc[0][
"Murmur"
]
elif rec_or_sid in self.all_records:
decom = self._decompose_rec(rec_or_sid)
sid, loc = decom["sid"], decom["loc"]
row = self.df_stats[self.df_stats["Patient ID"] == sid].iloc[0]
if row["Murmur"] == "Unknown":
ann = "Unknown"
else:
ann = None
if ann is None:
if loc in row["Murmur locations"]:
ann = "Present"
else:
ann = "Absent"
else:
raise ValueError(f"{rec_or_sid} is not a valid record or patient ID")
ann = _class_map.get(ann, ann)
return ann
@add_docstring(load_ann.__doc__)
def load_murmur(
self, rec_or_sid: Union[str, int], class_map: Optional[Dict[str, int]] = None
) -> Union[str, int]:
"""alias of `load_ann`"""
return self.load_ann(rec_or_sid, class_map)
def load_segmentation(
self,
rec: Union[str, int],
seg_format: str = "df",
ensure_same_len: bool = True,
fs: Optional[int] = None,
) -> Union[pd.DataFrame, np.ndarray, dict]:
"""
load the segmentation of the record `rec`
Parameters
----------
rec: str or int,
the record name or the index of the record in `self.all_records`
seg_format: str, default `df`,
the format of the returned segmentation,
can be `df`, `dict`, `mask`, `binary`,
case insensitive
ensure_same_len: bool, default True,
if True, the length of the segmentation will be
the same as the length of the audio data
fs: int, optional,
the sampling frequency, defaults to `self.fs`,
-1 for the sampling frequency from the audio file
Returns
-------
pd.DataFrame or np.ndarray or dict,
the segmentation of the record
NOTE
----
segmentation files do NOT have the same length (namely the second column of the last row of these .tsv files) as the audio files.
"""
if isinstance(rec, int):
rec = self[rec]
fs = fs or self.fs
if fs == -1:
fs = self.get_fs(rec)
segmentation_file = self.get_absolute_path(rec, self.segmentation_ext)
df_seg = pd.read_csv(segmentation_file, sep="\t", header=None)
df_seg.columns = ["start_t", "end_t", "label"]
if self.ignore_unannotated:
df_seg["label"] = df_seg["label"].apply(
lambda x: x - 1 if x > 0 else BaseCfg.ignore_index
)
df_seg["wave"] = df_seg["label"].apply(lambda s: self.segmentation_map[s])
df_seg["start"] = (fs * df_seg["start_t"]).apply(round)
df_seg["end"] = (fs * df_seg["end_t"]).apply(round)
if ensure_same_len:
sig_len = wfdb.rdheader(str(self.get_absolute_path(rec))).sig_len
if sig_len != df_seg["end"].max():
df_seg = pd.concat(
[
df_seg,
pd.DataFrame(
dict(
start_t=df_seg["end"].max() / fs,
end_t=sig_len / fs,
start=df_seg["end"].max(),
end=sig_len,
wave="unannotated",
label=BaseCfg.ignore_index,
),
index=[0],
),
],
ignore_index=True,
)
if seg_format.lower() in [
"dataframe",
"df",
]:
return df_seg
elif seg_format.lower() in [
"dict",
"dicts",
]:
# dict of intervals
return {
k: [
[row["start"], row["end"]]
for _, row in df_seg[df_seg["wave"] == k].iterrows()
]
for _, k in self.segmentation_map.items()
}
elif seg_format.lower() in [
"mask",
]:
# mask = np.zeros(df_seg.end.values[-1], dtype=int)
mask = np.full(df_seg.end.values[-1], BaseCfg.ignore_index, dtype=int)
for _, row in df_seg.iterrows():
mask[row["start"] : row["end"]] = int(row["label"])
return mask
elif seg_format.lower() in [
"binary",
]:
bin_mask = np.zeros(
(df_seg.end.values[-1], len(self.segmentation_states)), dtype=self.dtype
)
for _, row in df_seg.iterrows():
if row["wave"] in self.segmentation_states:
bin_mask[
row["start"] : row["end"],
self.segmentation_states.index(row["wave"]),
] = 1
return bin_mask
else:
raise ValueError(f"{seg_format} is not a valid format")
def load_meta_data(
self,
subject: str,
keys: Optional[Union[Sequence[str], str]] = None,
) -> Union[dict, str, float, int]:
"""
load meta data of the subject `subject`
Parameters
----------
subject: str,
the subject id
keys: str or sequence of str, optional,
the keys of the meta data to be returned,
if None, return all meta data
Returns
-------
meta_data: dict or str or float or int,
the meta data of the subject
"""
row = self._df_stats[self._df_stats["Patient ID"] == subject].iloc[0]
meta_data = row.to_dict()
if keys:
if isinstance(keys, str):
for k, v in meta_data.items():
if k.lower() == keys.lower():
return v
else:
_keys = [k.lower() for k in keys]
return {k: v for k, v in meta_data.items() if k.lower() in _keys}
return meta_data
def load_outcome(self, rec_or_subject: Union[str, int]) -> str:
"""
load the outcome of the subject or the subject related to the record
Parameters
----------
rec_or_subject: str or int,
the record name or the index of the record in `self.all_records`,
or the subject id (Patient ID)
Returns
-------
outcome: str,
the outcome of the record
"""
if isinstance(rec_or_subject, int):
rec_or_subject = self[rec_or_subject]
if rec_or_subject in self.all_subjects:
pass
elif rec_or_subject in self.all_records:
decom = self._decompose_rec(rec_or_subject)
rec_or_subject = decom["sid"]
else:
raise ValueError(f"{rec_or_subject} is not a valid record or patient ID")
outcome = self.load_outcome_(rec_or_subject)
return outcome
def load_outcome_(self, subject: str) -> str:
"""
load the expert cardiologist's overall diagnosis of of the subject `subject`
Parameters
----------
subject: str,
the subject id
Returns
-------
str,
the expert cardiologist's overall diagnosis,
one of `Normal`, `Abnormal`
"""
if isinstance(subject, int) or subject in self.all_records:
raise ValueError("subject should be chosen from `self.all_subjects`")
row = self._df_stats[self._df_stats["Patient ID"] == subject].iloc[0]
return row.Outcome
def _load_preprocessed_data(
self,
rec: Union[str, int],
fs: Optional[int] = None,
data_format: str = "channel_first",
passband: Sequence[int] = BaseCfg.passband,
order: int = BaseCfg.filter_order,
spike_removal: bool = True,
) -> np.ndarray:
"""
load preprocessed data of the record `rec`,
with preprocessing procedure:
- resample to `fs` (if `fs` is not None)
- bandpass filter
- spike removal
Parameters
----------
rec: str or int,
the record name or the index of the record in `self.all_records`
fs: int, optional,
the sampling frequency of the returned data
data_format: str, default `channel_first`,
the format of the returned data,
can be `channel_first`, `channel_last` or `flat`,
case insensitive
passband: sequence of int, default `BaseCfg.passband`,
the passband of the bandpass filter
order: int, default `BaseCfg.filter_order`,
the order of the bandpass filter
spike_removal: bool, default True,
whether to remove spikes using the Schmmidt algorithm
Returns
-------
data: np.ndarray,
the preprocessed data of the record
"""
fs = fs or self.fs
data = butter_bandpass_filter(
self.load_data(rec, fs=fs, data_format="flat"),
lowcut=passband[0],
highcut=passband[1],
fs=fs,
order=order,
).astype(self.dtype)
if spike_removal:
data = schmidt_spike_removal(data, fs=fs)
if data_format.lower() == "flat":
return data
data = np.atleast_2d(data)
if data_format.lower() == "channel_last":
data = data.T
return data
def get_fs(self, rec: Union[str, int]) -> int:
"""
get the original sampling frequency of the record `rec`
Parameters
----------
rec: str or int,
the record name or the index of the record in `self.all_records`
Returns
-------
int,
the original sampling frequency of the record
"""
return wfdb.rdheader(str(self.get_absolute_path(rec))).fs
def get_subject(self, rec: Union[str, int]) -> str:
"""
get the subject id (Patient ID) of the record `rec`
Parameters
----------
rec: str or int,