-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreprocessing.py
More file actions
2021 lines (1599 loc) · 81.2 KB
/
Copy pathpreprocessing.py
File metadata and controls
2021 lines (1599 loc) · 81.2 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
# Copyright (C) 2023 Daniel Enériz and Antonio Rodriguez-Almeida
#
# This file is part of PCG Segmentation Model Optimization.
#
# PCG Segmentation Model Optimization is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PCG Segmentation Model Optimization is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PCG Segmentation Model Optimization. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
from typing import Tuple, Dict
import scipy.signal
import pywt
import warnings
from tensorflow.keras.utils import to_categorical
from tqdm import tqdm
import os
import pandas as pd
import copy
import json
import librosa
import matplotlib.pyplot as plt
from scipy import io as sio
DATASET2022_PATH = "../physionet.org/files/circor-heart-sound/1.0.3"
DATASET2016_PATH = "../physionet.org/files/hss/1.0/extracted_files"
# Load patient data as a string.
def load_patient_data(filename : str) -> str:
"""This function loads the patient data from a file. This function is taken
from the [PhysioNet 2022 Challenge repository](https://github.com/physionetchallenges/python-classifier-2022).
Args:
-----
filename (str): The path to the file containing the patient data.
Returns:
--------
str: The patient data.
"""
with open(filename, 'r') as f:
data = f.read()
return data
# Define the spike removal function
def schmidt_spike_removal(original_data: np.ndarray, fs: float) -> np.ndarray:
"""This function removes the spikes from the data as described in [1]. It is
based on the [MATLAB implementation of David Springer](https://github.com/davidspringer/Schmidt-Segmentation-Code/blob/master/schmidt_spike_removal.m)
and the [Python implementation of Mutasem Aldmour](https://github.com/mutdmour/mlnd_heartsound/blob/master/project/sampleModel/schmidt_spike_removal.py)
Args:
-----
data (np.ndarray): The data to be preprocessed.
fs (float): The sampling frequency of the data.
Returns:
--------
np.ndarray: The preprocessed data.
References:
-----------
[1] S. E. Schmidt et al., "Segmentation of heart sound recordings by a
duration-dependent hidden Markov model," Physiol. Meas., vol. 31, no. 4,
pp. 513-29, Apr. 2010
"""
# Find the window size to be 500ms
window_size = int(np.round(fs*0.5))
# Find any samples outside of a integer number of windows
trailing_samples = int(np.mod(original_data.size, window_size))
# Reshape the singal into a number of windows
#sample_frames = original_data[:original_data.size-trailing_samples].reshape(window_size, -1)
sample_frames = np.array(np.split(original_data[:original_data.size-trailing_samples], round((original_data.size-trailing_samples)/window_size), axis=0))
# Find the MAAs (Maximum Absolute Amplitude) of each window
maa = np.max(np.abs(sample_frames), axis=1)
# While there are still samples greater than 3* the median value of the MAAs,
# then remove those spikes
while np.any(maa > 3*np.median(maa)):
# Find the window with the maximum MAAs
window_num = np.argmax(maa)
# Find the position of the spike within that window
spike_idx = np.argmax(np.abs(sample_frames[window_num, :]))
# Finding zero crossings (where there may not be actual 0 values, just
# a change from positive to negative or vice versa)):
zero_crossings = np.abs(np.diff(np.sign(sample_frames[window_num][:])))
if (len(zero_crossings) == 0):
zero_crossings = [0]
zero_crossings = [1 if i > 1 else 0 for i in zero_crossings ] + [0]
#Find the start of the spike, finding the last zero crossing before
# spike position. If that is empty, take the start of the window:
spike_start = np.nonzero(zero_crossings[0:spike_idx+1])[0]
# print spike_start
if (len(spike_start) > 0):
spike_start = spike_start[-1]
else:
spike_start = 0
# Find the end of the spike, finding the first zero crossing after spike
# position. If that is empty, take the end of the window:
zero_crossings[0:spike_idx+1] = [0]*(spike_idx+1)
spike_end = np.nonzero(zero_crossings)[0]
if (len(spike_end) > 0):
spike_end = spike_end[0] + 1
else:
spike_end = window_size
# Set to zero the samples within the spike
sample_frames[window_num, spike_start:spike_end] = 0.0001
# Recalculate the MAAs
maa = np.max(np.abs(sample_frames), axis=1)
# Reshape the signal back into a single vector
data = sample_frames.reshape(-1)
# Add the trailing samples back to the signal
if trailing_samples:
data = np.append(data, original_data[-trailing_samples:])
return data
# Get number of recording locations from patient data.
def get_num_locations(data) -> int:
"""This function gets the number of recording locations from the patient
data. This function is taken from the [PhysioNet 2022 Challenge repository](https://github.com/physionetchallenges/python-classifier-2022).
Args:
-----
data (str): The patient data.
Returns:
--------
int: The number of recording locations.
"""
num_locations = None
for i, l in enumerate(data.split('\n')):
if i==0:
try:
num_locations = int(l.split(' ')[1])
except:
pass
else:
break
return num_locations
def load_recordings(data_folder: str, data: str, get_frequencies: bool = False,
get_filenames: bool = False) -> Tuple:
"""This function loads the recordings from the patient included in `data`.
It is based on (a function of the PhysioNet Challenge 2022 example
code)[https://github.com/physionetchallenges/python-classifier-2022/blob/edf2c64cdbc8d467ac69253d31ff76243c96e041/helper_code.py#L66]
but adapted to use librosa to read the wavs and to optionally output the
filenames.
Args:
-----
data_folder (str): The folder where the data is stored.
data (str): The patient data. This must be loaded using `helper_code.load_patient_data`.
get_frequencies (bool): Whether to output the frequencies of the recordings.
get_filenames (bool): Whether to output the filenames of the recordings.
Returns:
--------
A tuple containing these elements zipped:
Tuple of np.ndarray: The recordings.
Tuple of sampling frequencies. (Optional)
Tuple of filenames. (Optional)
"""
num_locations = get_num_locations(data)
recording_information = data.split('\n')[1:num_locations+1]
recordings = list()
frequencies = list()
filenames = list()
for i in range(num_locations):
entries = recording_information[i].split(' ')
recording_file = entries[2]
filename = os.path.join(data_folder, recording_file)
recording, frequency = librosa.load(filename, sr=None)
# If the recording lentgh is odd, remove the last sample
if len(recording) % 2 == 1:
recording = recording[:-1]
recordings.append(recording)
frequencies.append(frequency)
filenames.append(filename)
if get_frequencies:
if get_filenames:
return zip(recordings, frequencies, filenames)
else:
return zip(recordings, frequencies)
else:
if get_filenames:
return zip(recordings, filenames)
else:
return recordings
# Filter the BadCoefficients warning
warnings.filterwarnings('ignore', category=scipy.signal.BadCoefficients)
# Define the function to compute the Homomorphic Envelope and the Hilbert envelope:
def homomorphic_envelogram_with_hilbert(input_signal: np.ndarray, fs: float, lpf_frequency=8) -> Tuple[np.ndarray, np.ndarray]:
"""Calculate the homomorphic envelope of a signal based on the Hilbert's
envelope, which is also returned. This implementation is based on Mutasem
Aldmour's work https://github.com/mutdmour/mlnd_heartsound which is a
reimplementation of the MATLAB version published by David Springer
https://github.com/davidspringer/Schmidt-Segmentation-Code.
In [1-3], the researchers found the homomorphic envelope of Shannon energy.
However, in [4], the authors state that the singularity at 0 when using the
natural logarithm (resulting in values of -inf) can be fixed by using a
complex valued signal. They motivate the use of the Hilbert transform to
find the analytic signal, which is a converstion of a real-valued signal to
a complex-valued signal, which is unaffected by the singularity.
The usage of the Hilbert transform is explained in [5].
Args:
-----
input_signal: 1D numpy array containing the input signal.
fs: Sampling frequency of the input signal.
lpf_frequency: Cutoff frequency of the low-pass filter. Default is 8 Hz.
Returns:
--------
hilbert_envelope: 1D numpy array containing the Hilbert envelope.
homomorphic_envelope: 1D numpy array containing the homomorphic envelope
of the input signal.
References:
-----------
[1] S. E. Schmidt et al., Segmentation of heart sound recordings by a
duration-dependent hidden Markov model., Physiol. Meas., vol. 31, no. 4,
pp. 513?29, Apr. 2010.
[2] C. Gupta et al., Neural network classification of homomorphic segmented
heart sounds, Appl. Soft Comput., vol. 7, no. 1, pp. 286-297, Jan. 2007.
[3] D. Gill et al., Detection and identification of heart sounds using
homomorphic envelogram and self-organizing probabilistic model, in
Computers in Cardiology, 2005, pp. 957-960.
[4] I. Rezek and S. Roberts, Envelope Extraction via Complex Homomorphic
Filtering. Technical Report TR-98-9, London, 1998
[5] Choi et al, Comparison of envelope extraction algorithms for cardiac
sound signal segmentation, Expert Systems with Applications, 2008.
"""
# Check if the input signal is a 1D numpy array:
if not isinstance(input_signal, np.ndarray) or len(input_signal.shape) != 1:
raise ValueError('The input signal must be a 1D numpy array.')
#8Hz, 1st order, Butterworth LPF
B_low, A_low = scipy.signal.butter(1,2*lpf_frequency/fs,'low')
# Obtain the Hilbert transform:
hilbert_envelope = np.abs(scipy.signal.hilbert(input_signal))
# Calculate the homomorphic envelope of the signal using the Hilbert transform to obtain the analytic signal.
homomorphic_envelope = np.exp(scipy.signal.filtfilt(B_low, A_low, np.log(hilbert_envelope)))
return hilbert_envelope, homomorphic_envelope
# Define the function to compute the PSD envelope:
def psd(input_signal: np.ndarray, fs: float, fl_low: float = 40, fl_high: float = 60, resample: bool = True) -> np.ndarray:
"""Calculate the PSD envelope of a signal between fl_low and fl_high. This
implementation is based on the description available at [1].
Args:
-----
input_signal: 1D numpy array containing the input signal.
fs: Sampling frequency of the input signal
fl_low: Lower frequency limit of the PSD envelope. Defaults to 40 Hz.
fl_high: Higher frequency limit of the PSD envelope. Defaults to 60 Hz.
resample: If True, the signal is resampled to fs. Defaults to True.
Returns:
--------
psd_envelope: 1D numpy array containing the PSD envelope of the input
signal.
References:
-----------
[1] D. Springer et al., "Logistic Regression-HSMM-based Heart Sound
Segmentation," IEEE Trans. Biomed. Eng., In Press, 2015.
"""
# * It reduces significantly the equivalent sampling frecuency
# Check if the input is a 1D numpy array
if not isinstance(input_signal, np.ndarray) or len(input_signal.shape) != 1:
raise ValueError('The input signal must be a 1D numpy array.')
# Check if frecuecy limits are valid
if fl_low < 0 or fl_low > fs/2:
raise ValueError('The lower frequency limit must be between 0 and fs/2.')
if fl_high < 0 or fl_high > fs/2:
raise ValueError('The higher frequency limit must be between 0 and fs/2.')
if fl_low > fl_high:
raise ValueError('The lower frequency limit must be smaller than the higher frequency limit.')
# Find the spectrogram of the signal. The window width is set to 0.05
# seconds, with 50% overlap.
f, t, Sxx = scipy.signal.spectrogram(input_signal, fs, nperseg=int(fs*0.5*0.05), noverlap=int(fs*0.05*0.5*0.5), nfft=int(fs))
# Find the lower and higher frequency limits of the PSD envelope
fl_low_index = np.argmin(np.abs(f-fl_low))
fl_high_index = np.argmin(np.abs(f-fl_high))
# Find the mean PSD over the frequency range
psd_envelope = np.mean(Sxx[fl_low_index:fl_high_index,:], axis=0)
if resample:
# Resample the PSD envelope to the input signal's sampling frequency
psd_envelope = scipy.signal.resample(psd_envelope, len(input_signal))
return psd_envelope
# Partially extracted from: https://github.com/cmescobar/Heart_sound_prediction/blob/master/hsp_utils/envelope_functions.py
def wavelet(signal_in, wavelet='db1', levels=[4],
start_level=1, end_level=5, erase_pad=True)-> np.ndarray:
"""Calculates and returns the Wavelet envelope of a signal based on Shannon's
energy [1,2]. This implementation is based on Christian Escobar Arcer's work
https://github.com/cmescobar/Heart_sound_prediction. He used the Stationary Wavelet
Decomposition, that corresponds to the Discrete Wavelet Transform without
decimating the signal.
In [3], the researches used a similar method to produce one of the four different
envelopes that would be the input of a segmentation Convolutional Neural Network
(CNN).
Args:
-----
signal_in: 1D numpy array containing the input signal.
wavelet: used wavelet (https://www.pybytes.com/pywavelets/ref/wavelets.html)
levels: selected levels for
start_level: Wavelet decomposition start level
end_level: Wavelet decomposition end level
erase_pad: boolean that indicates is padding to compute the
Stationary Wavelet Transform is erased or not
Returns:
--------
DWT_envs: n-D numpy array containing the Shannon envelope for the selected
Wavelet decomposition levels (i.e., "levels" values).
References:
-----------
[1] L. Huiying et al., A Heart Sound Segmentation Algorithm using Wavelet
Decomposition and Reconstruction, 19th International Conference -
IEEE/EMBS, 1997.
[2] Choi et al, Comparison of envelope extraction algorithms for cardiac
sound signal segmentation, Expert Systems with Applications, 2008.
[3] Renna et al., Deep Convolutional Neural Network for Heart Sound Segmentation,
IEEE Journal of Biomedical and Health Informatics, 2019.
"""
# Original data points number
N = signal_in.shape[0]
# If N is odd, delete the last point
if N % 2 == 1:
signal_in = signal_in[:-1]
N = N - 1
add_a_zero = True
else:
add_a_zero = False
# Amount of desired points
points_desired = 2 ** int(np.ceil(np.log2(N)))
# Padding points number definition
pad_points = (points_desired-N) // 2
# Padding to reach the needed power of two Paddeando
audio_pad = np.pad(signal_in, pad_width=pad_points,
constant_values=0)
# Stationary Wavelet Decomposition
coeffs = pywt.swt(audio_pad, wavelet=wavelet, level=end_level,
start_level=start_level)
# Array to store decomposition levels
wav_coeffs = np.zeros((len(coeffs[0][1]), 0))
for level in levels:
# Indexes according to pywt.swt(.) output
coef_i = np.expand_dims(coeffs[-level + start_level][1], -1)
# Coefficients concatenation
wav_coeffs = np.concatenate((wav_coeffs, coef_i), axis=1)
# Erase padding points if needed.
# The pad_points is added to skip pad_points = 0 cases
if erase_pad and pad_points:
wav_coeffs_out = wav_coeffs[pad_points:-pad_points]
else:
wav_coeffs_out = wav_coeffs
# Normalization of decomposition coefficients
coeffs_norm = wav_coeffs_out/np.max(wav_coeffs_out)
# Substitute zero values with an small number to avoid log(0)
coeffs_norm[coeffs_norm == 0] = 1e-10
# Computation of Shannon Energy
DWT_envs = -(np.square(coeffs_norm)*np.log(np.square(coeffs_norm)))
# Supress second dimension of array
DWT_envs = DWT_envs[:, 0]
# Add a zero if needed
if add_a_zero:
DWT_envs = np.concatenate((DWT_envs, np.zeros(1)))
return np.abs(DWT_envs)
# Define a dictionary with the default parameters for the envelope/envelogram
# extraction functions
default_envelope_config = {
'homomorphic_envelogram_with_hilbert': {'lpf_frequency': 8},
'psd': {'fl_low': 40, 'fl_high': 60, 'resample': True},
'wavelet': {'wavelet': 'db1',
'levels': [4],
'start_level': 1,
'end_level': 6,
'erase_pad': True}
}
def get_envelopes(input_signal: np.ndarray, fs: float,
config_dict: Dict = default_envelope_config) -> np.ndarray:
"""Gets the envelopes and evelograms from the input signal, using the
parameters defined in config_dict.
Args:
-----
input_signal (np.ndarray): 1D numpy array containing the input signal.
fs (float): Sampling frequency of the input signal.
config_dict (Dict): Dictionary with the configuration of the
envelopes.
Returns:
--------
x (np.ndarray): Stack of the selected the envelopes/envelograms. The
default order is homomorphic, hilbert, psd, and wavelet.
"""
# Check if the input is a 1D numpy array
if not isinstance(input_signal, np.ndarray) or len(input_signal.shape) != 1:
raise ValueError('The input signal must be a 1D numpy array.')
# Check if the dictionary is valid
if not isinstance(config_dict, dict):
raise ValueError('The config_dict must be a dictionary.')
# Get the envelopes
envelopes = []
for key, value in config_dict.items():
if key == 'homomorphic_envelogram_with_hilbert':
hilbert_envelope, homomorphic_envelope = homomorphic_envelogram_with_hilbert(input_signal, fs, config_dict[key]['lpf_frequency'])
envelopes.append(homomorphic_envelope)
envelopes.append(hilbert_envelope)
elif key == 'psd':
psd_envelope = psd(input_signal, fs, config_dict[key]['fl_low'], config_dict[key]['fl_high'], config_dict[key]['resample'])
envelopes.append(psd_envelope)
elif key == 'wavelet':
wavelet_envelope = wavelet(input_signal, config_dict[key]['wavelet'], config_dict[key]['levels'], config_dict[key]['start_level'],config_dict[key]['end_level'],config_dict[key]['erase_pad'])
envelopes.append(wavelet_envelope)
# Stack the envelopes
x = np.stack(envelopes, axis=0)
return x
def renna_preprocess_wave(input_signal: np.ndarray, fs: float,
config_dict: Dict = default_envelope_config) -> np.ndarray:
"""This function preprocess the data as described in [1]. First a bandpass
filter is applied to the signal between 25 and 400Hz. Then the spike removal
method described in [2] is used, which is followed by the envelogram
generation used in [3]. After this, the envelograms are downsampled to 50 Hz.
Finally, a standardization (normalization with mean 0 and deviation 1) is used.
Args:
-----
input_signal (np.ndarray): The data to be preprocessed.
fs (float): Sampling frecuency of the signal.
config_dict (Dict): Configuration dictionary for the envelopes
generation.
Returns:
--------
x, an np.ndarray containing the envelograms, with shape (4, 50*T), where
T is the duration of input_signal.
References:
-----------
[1] Renna, F., Oliveira, J., & Coimbra, M. T. (2019). Deep Convolutional
Neural Networks for Heart Sound Segmentation. IEEE journal of biomedical
and health informatics, 23(6), 2435-2445.
https://doi.org/10.1109/JBHI.2019.2894222
[2] S. E. Schmidt et al., "Segmentation of heart sound recordings by
a duration-dependent hidden Markov model," Physiol. Meas., vol. 31, no.
4, pp. 513-29, Apr. 2010
[3] D. Springer et al., "Logistic Regression-HSMM-based Heart Sound
Segmentation," IEEE Trans. Biomed. Eng., In Press, 2015.
"""
# Check if the input is a 1D numpy array
if not isinstance(input_signal, np.ndarray) or len(input_signal.shape) != 1:
raise ValueError('The input signal must be a 1D numpy array.')
# Desing a BP filter between 25 and 400 Hz.
filter = scipy.signal.butter(4, [25, 400], btype='bandpass', fs=fs, output='sos')
# Apply the filter
data = scipy.signal.sosfilt(filter, input_signal)
# Spike removal from Schmidt et al. 2010 https://pubmed.ncbi.nlm.nih.gov/20208091/
data = schmidt_spike_removal(data, fs)
# Generate the envelograms
x = get_envelopes(data, fs, config_dict)
# Downsample the envelograms to 50 Hz.
x = scipy.signal.decimate(x, int(fs/50))
# Standardize the envelograms
x = (x - x.mean(axis=1, keepdims=True)) / x.std(axis=1, keepdims=True)
return x
def renna_preprocess_circor_annotations(input_data: np.ndarray) -> np.ndarray:
"""Takes the raw read annotations from the .tsv file of the CirCor dataset
[1] and generates the s array, containing the labels of the heart states at
50 Hz. Note that here s(t) is in the range (0 - 4), where 0 is the
unclassified label and the values 1 to 4 represent each heart state.
Args:
-----
input_data (np.ndarray): The raw annotations from the .tsv file.
Returns:
--------
s (np.ndarray): The heart states at 50 Hz.
References:
-----------
[1] J. H. Oliveira et al., "The CirCor DigiScope Dataset: From Murmur
Detection to Murmur Classification," in IEEE Journal of Biomedical and
Health Informatics, doi: 10.1109/JBHI.2021.3137048.
"""
# Check if the input is a 2D numpy array with the second dimension of size 3
if not isinstance(input_data, np.ndarray) or len(input_data.shape) != 2 or input_data.shape[1] != 3:
raise ValueError('The input data must be a 2D numpy array with the second dimension of size 3.')
# Find the duration in seconds of the recording (last value of the second column)
T = input_data[-1,1]
# Generate a time array with 50 Hz sampling rate
t = np.arange(0, T, 1.0/50.0)
# Generate the s array
s = np.zeros_like(t)
# For each time instant, find its heart state and assign it to the s array
for i in range(len(t)):
# Find the first value greater than t(i)
j = np.argmax(input_data[:,1] > t[i])
# Assign the heart state to s(i)
s[i] = input_data[j,2]
return s
def rolling_strided_window(x: np.ndarray, N: int, tau: int) -> np.ndarray:
"""Takes the input 2D array and extracts windows of size N and stride tau
along de second dimension. If the input array is 1D another dimesion is
expanded to perform de operation.
Args:
-----
x (np.ndarray): Input 2D array.
N (int): Size of the windows.
tau (int): Stride of the windows.
Returns:
--------
x_windows (np.ndarray): 2D array with the windows.
"""
orig_input_1D = False
# Check if the input is 1D
if x.ndim == 1:
x = x[np.newaxis, :]
orig_input_1D = True
# Check if the input is 2D
if x.ndim != 2:
raise ValueError("The input array must be 2D or 1D to be expanded.")
# Check if the stride is a positive integer
if not isinstance(tau, int) or tau <= 0:
raise ValueError("The stride must be a positive integer.")
# Check if the window size is a positive integer
if not isinstance(N, int) or N <= 0:
raise ValueError("The window size must be a positive integer.")
x_windows = np.lib.stride_tricks.sliding_window_view(x, (x.shape[0],N))[:, 0::tau]
# Remove the first dimension since it always outputs a 4D if the input is 2D
x_windows = x_windows[0,:,:,:]
# If the input was 1D, remove the extra dimension added at the beginning
if orig_input_1D:
x_windows = x_windows[:,0,:]
return x_windows
def check_valid_sequence(x: np.ndarray, s: np.ndarray, verbose: int) -> Tuple[np.ndarray, np.ndarray]:
"""As there are annotations that have illegal heart state transitions, as
the first 3 -> 1 in the 500086_MV.tsv file, this function checks if the
heart state sequence of each window in s is valid, removing the windows
that are not. Also it removes the windows with less than 3 heart
transitions.
Args:
-----
x (np.ndarray): The signal of the recording.
s (np.ndarray): The heart state sequence of the recording.
verbose (int): Verbosity level.
Returns:
--------
x_valid (np.ndarray): The signal of the recording with only the valid
windows.
s_valid (np.ndarray): The heart state sequence of the recording with
only the valid windows.
"""
# Check if the first dimension is the same in x and s
if x.shape[0] != s.shape[0]:
raise ValueError('The first dimension of x and s must be the same.')
# Iterate over the windows
invalid_idxs = []
for i in range(s.shape[0]):
# Check if the heart state sequence is valid
if np.unique(s[i, :]).shape[0] < 4:
invalid_idxs.append(i)
if verbose >= 2:
warnings.warn('Window {} has less than 3 heart transitions'.format(i), RuntimeWarning)
else:
for j in range(1, s.shape[1]):
if not (s[i, j] == s[i, j-1] or s[i, j] == s[i, j-1] % 4 + 1):
invalid_idxs.append(i)
if verbose >= 2:
warnings.warn('Invalid transition from {} to {} in window {}.'.format(s[i, j-1], s[i, j], i), RuntimeWarning)
break
# Remove the invalid windows
x_valid = np.delete(x, invalid_idxs, axis=0)
s_valid = np.delete(s, invalid_idxs, axis=0)
return x_valid, s_valid
def generate_X_S_2022(filenames: list, data_folder: str, N: int, tau: int,
verbose: int) -> Tuple[np.ndarray, np.ndarray]:
"""Generates the X and S arrays for the CirCor dataset [1]. The X array
contains windows of size N and stride tau of the envelograms of the
recordings sampled at 50 Hz, as done in Renna et al. [2]. The S array
contains the heart state sequence of the recordings.
Args:
-----
filenames (list): List of strings with the filenames of patient data
(`.txt` files).
data_folder (str): Path to the folder containing the data.
N (int): Size of the windows.
tau (int): Stride of the windows.
verbose (int): Verbosity level.
Returns:
--------
X (np.ndarray): 3D array with the windows of the recordings. Its shape
is (number of windows, N, number of envelograms).
S (np.ndarray): 3D array with the heart state sequence of the
recordings. Its shape is (number of windows, N, number of heart states).
"""
# Generate an XS vector from x and s with length N and stride tau
# Initialize the X and S arrays
X = np.zeros((0, 4, N))
S = np.zeros((0, N))
# Extract all recording for each patient
for name in tqdm(filenames, desc='Iterating over patients') if verbose >=1 else filenames:
data = load_patient_data(name)
for recording, filename in load_recordings(data_folder, data, get_filenames=True):
# Get envelopes
x_global = renna_preprocess_wave(recording, fs = 4000)
annotations = np.loadtxt(filename[:-4] + '.tsv')
try:
# Extract segmentation anotation from .tsv
s_global = renna_preprocess_circor_annotations(annotations)
except ValueError:
# If the annotations are not valid, skip this recording
continue
# Extract the indexes of the s elements with heart state information
labeled_idxs_global = np.where(s_global!=0)[0]
# Find 0 intervals between heart state changes
zero_intervals = np.diff(labeled_idxs_global)-1 != 0
# Split x and s between those intervals
x_split = np.split(x_global, labeled_idxs_global[1:][zero_intervals], axis=1)
s_split = np.split(s_global, labeled_idxs_global[1:][zero_intervals])
for k in range(len(x_split)):
# Extract the indexes of the s elements with heart state information
labeled_idxs = np.where(s_split[k]!=0)[0]
# Use only data with heart state information
x = x_split[k][:, labeled_idxs]
s = s_split[k][labeled_idxs]
if x.shape[1] < N:
# If the window is smaller than N, discard it
continue
x = rolling_strided_window(x, N, tau)
s = rolling_strided_window(s, N, tau)
x, s = check_valid_sequence(x, s, verbose)
# Stack the windows
X = np.vstack((X, x))
S = np.vstack((S, s))
# Create a new axis in S and concatenate X and S
S = S[:, np.newaxis, :]
XS = np.concatenate((X, S), axis=1)
# Shuffle the samples
np.random.shuffle(XS)
# Return the X and S arrays
X = XS[:, :x.shape[1], :]
S = XS[:, x.shape[1]:, :]
# Swap axes to format the data as channels_last
X = np.swapaxes(X, 1, 2)
S = np.swapaxes(S, 1, 2)
# Transform S to categorical
S = to_categorical(S-1)
return X, S
def read_single_wav_2022(patient : int, location : str,
multirecording_id : int = 0) -> Tuple[np.ndarray, float, str]:
"""Reads a single wav file.
Args:
-----
patient: The patient ID.
location: The location of the recording.
multirecording_id: The ID of the recording if there are more than one
recording in the same location per subject. Defaults to 0, that implies
just one recording exists.
Returns:
--------
The data, its sampling frequency and the path to the file accesed.
"""
if multirecording_id:
file_subpath = '/training_data/{}_{}_{}.wav'.format(patient, location, multirecording_id)
# Check the OS
if os.name == 'nt':
file_path = DATASET2022_PATH.replace('/', '\\') + file_subpath.replace('/', '\\')
wav_data, fs = librosa.load(file_path, sr=None)
else:
file_path = DATASET2022_PATH + file_subpath
wav_data, fs = librosa.load(file_path, sr=None)
else:
file_subpath = '/training_data/{}_{}.wav'.format(patient, location)
# Check the OS
if os.name == 'nt':
file_path = DATASET2022_PATH.replace('/', '\\') + file_subpath.replace('/', '\\')
wav_data, fs = librosa.load(file_path, sr=None)
else:
file_path = DATASET2022_PATH + file_subpath
wav_data, fs = librosa.load(file_path, sr=None)
# Check if wav_data has even length and remove last element if it is odd.
if len(wav_data) % 2 == 1:
wav_data = wav_data[:-1]
return wav_data, fs, file_path
def read_single_tsv_2022(patient : int, location : str,
multirecording_id : int = 0) -> Tuple[np.ndarray, str]:
"""This function reads a single tsv file.
Args:
-----
patient: The patient ID.
location: The location of the recording.
multirecording_id: The ID of the recording if there are more than one
recording in the same location per subject. Defaults to 0, that implies
just one recording exists.
Returns:
--------
The data and the path to the file accesed.
"""
if multirecording_id:
# Read the tsv file.
file_subpath = '/training_data/{}_{}_{}.tsv'.format(patient, location, multirecording_id)
# Check the OS
if os.name == 'nt':
file_path = DATASET2022_PATH.replace('/', '\\') + file_subpath.replace('/', '\\')
tsv_data = np.loadtxt(file_path)
else:
file_path = DATASET2022_PATH + file_subpath
tsv_data = np.loadtxt(file_path)
else:
file_subpath = '/training_data/{}_{}.tsv'.format(patient, location)
# Check the OS
if os.name == 'nt':
file_path = DATASET2022_PATH.replace('/', '\\') + file_subpath.replace('/', '\\')
tsv_data = np.loadtxt(file_path)
else:
file_path = DATASET2022_PATH + file_subpath
tsv_data = np.loadtxt(file_path)
return tsv_data, file_path
def prepare_dataset_2022(dataset_path: str = DATASET2022_PATH,
preprocesed_path: str = './circor-segmentation',
save_dict_name : str = '/data_dict.json',
verbose: bool = True) -> Dict:
"""This function prepares the data of the dataset [1] for the segmentation
model. The data of each recording is read from the dataset path,
preprocessed and saved in a npz file containing the envelograms (np.ndarray
x) and the fundamental heart states (np.ndarray s) at a frecuency of 50 Hz.
Args:
-----
dataset_path (str): Path to the dataset.
preprocesed_path (str): Path to the directory where the preprocessed
data is saved. Default is './circor-segmentation'.
save_dict_name (str): Filename to save the data dictionary. Default is
data_dict.json.
verbose (bool): If True, prints the progress of the function. Default is
True.
Returns:
--------
data_dict (Dict): Dictionary containing the .npz file names in function
of the patient ID, the location, the multirecording id and the split id,
and othe useful data.
References:
-----------
[1] J. H. Oliveira et al., "The CirCor DigiScope Dataset: From Murmur
Detection to Murmur Classification," in IEEE Journal of Biomedical and
Health Informatics, doi: 10.1109/JBHI.2021.3137048.
"""
# Set the subpath of the .csv file containing a summary of the recordings
csv_subpath = '/training_data.csv'
# Check if the OS is Windows and reformat the paths if so
if os.name == 'nt':
dataset_path = dataset_path.replace('/', '\\')
preprocesed_path = preprocesed_path.replace('/', '\\')
csv_subpath = csv_subpath.replace('/', '\\')
save_dict_name = save_dict_name.replace('/', '\\')
no_labeled_recording = no_labeled_recording.replace('/', '\\')
# Create the new folder
if not os.path.exists(preprocesed_path):
os.mkdir(preprocesed_path)
# Read the .csv file containing a summary of the recordings
df = pd.read_csv(dataset_path + csv_subpath)
# Initialize the data dictionary
data_dict = {}
posible_locations = ['AV', 'TV', 'PV', 'MV', 'Phc']
# Iterate over the rows in the dataframe
for index, row in tqdm(df.iterrows(), total=df.shape[0]) if verbose else df.iterrows():
# Save the patient id
patient_id = str(row['Patient ID'])
# Obtain existing locations of patient data
existing_locations = row['Recording locations:'].split('+')
# Count the number of recordings for each location
locations_count = np.zeros(len(posible_locations), dtype=int)
for i, location in enumerate(posible_locations):
locations_count[i] = existing_locations.count(location)
# Save the patient general data
data_dict[patient_id] = {"Existing locations": existing_locations,
"Location count": locations_count.tolist(),
"Unique locations": np.unique(existing_locations).tolist(),}
# Iterate over posible locations
for i, location in enumerate(posible_locations):
data_dict[patient_id][location] = {"Count": int(locations_count[i])}
# Iterate over the number of recordings for each location
for j in range(locations_count[i]):
# Read the recording data
# If more than one recording for the same location use this line
if locations_count[i] > 1:
data, fs, audio_file = read_single_wav_2022(patient_id, location, j+1)
else:
data, fs, audio_file = read_single_wav_2022(patient_id, location)
# Read the annotations data
if locations_count[i] > 1:
annotations, _ = read_single_tsv_2022(patient_id, location, j+1)
else:
annotations, _ = read_single_tsv_2022(patient_id, location)
try: # Try de feature and label generation
# Preprocess the data
x_global = renna_preprocess_wave(data, fs)
# Preprocess the annotations
s_global = renna_preprocess_circor_annotations(annotations)
except ValueError:
# Go to the next recording
continue
# Extract the indexes of the s elements with heart state information
labeled_idxs_global = np.where(s_global!=0)[0]
# Find 0 intervals between heart state changes
zero_intervals = np.diff(labeled_idxs_global)-1 != 0
# Split x and s between those intervals
x_split = np.split(x_global, labeled_idxs_global[1:][zero_intervals], axis=1)
s_split = np.split(s_global, labeled_idxs_global[1:][zero_intervals])
data_dict[patient_id][location][str(j)] = {"Number of splits": len(x_split)}
for k in range(len(x_split)):
# Extract the indexes of the s elements with heart state information
labeled_idxs = np.where(s_split[k]!=0)[0]
# Use only data with heart state information
x = x_split[k][:, labeled_idxs]
s = s_split[k][labeled_idxs]
# Save the data
# If more than one recording for the same location use this format:
if locations_count[i] > 1: