-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpreprocess.py
More file actions
1831 lines (1479 loc) · 65.4 KB
/
preprocess.py
File metadata and controls
1831 lines (1479 loc) · 65.4 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 os, re
import ast,math, sys
import pywt, wfdb
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
import pandas as pd
import torch
import pickle
import pandas as pd
import random
from collections import Counter
import neurokit2 as nk
def setup_seed(seed=2023):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
def normalize(ecg):
min_val = np.min(ecg)
max_val = np.max(ecg)
if (max_val - min_val) == 0:
return ecg
# Apply min-max normalization
normalized_ecg = (ecg - min_val) / (max_val - min_val)
return (normalized_ecg - 0.5) * 2
def denoising(data):
# Initialize an empty matrix to store processed data
ecg_cleaned = np.zeros_like(data)
# Process each channel in a loop
for i in range(data.shape[1]):
channel_data = data[:, i]
ecg_cleaned[:, i] = nk.ecg_clean(channel_data, sampling_rate=500)
return ecg_cleaned
def padding_varying_length(data):
for i in range(data.shape[0]):
for j in range(data.shape[1]):
data[i, j, :][np.isnan(data[i, j, :])] = 0
return data
def pro_ecg(ecg):
# filtered_data = denoising(ecg)
normalize_data = normalize(ecg)
return normalize_data
def trans_code(label_list):
code_mapping = {
733534002: 164909002,
713427006: 59118001,
284470004: 63593006,
427172004: 17338001
}
# Use list comprehension for efficiency
# If a code is not in the mapping, keep it unchanged
new_labelist = [code_mapping.get(code, code) for code in label_list]
return new_labelist
def get_dict_ptb(Path='./data/ptb-xl-a-large-publicly-available-electrocardiography-dataset-1.0.1/scp_statements.csv', few=False):
mapping_file = Path
mapping_data = pd.read_csv(mapping_file)
annotation_to_condition = {}
for index, row in mapping_data.iterrows():
if few:
annotation_to_condition[row['diagnostic_class']] = index
else:
annotation_to_condition[row['description']] = index
return annotation_to_condition
# def pro_text(comments, diction, only_label):
# ann = comments[2]
# snomed_ct_matches = re.findall(r'\d+', ann)
# prefix = "Please provide a description of potential health problems, symptoms that the patient might be facing based on the provided information.\n"
# new_snomed_ct_codes = ''
# label_text = '['
# for full_name in diction.values():
# label_text += full_name + ','
# if label_text.endswith(','):
# label_text = label_text[:-1]
# label_text += ']\nPlease select some symptoms from the table above for description.\n'
# for snomed_ct_code in snomed_ct_matches:
# label = diction.get(int(snomed_ct_code))
# if label:
# new_snomed_ct_codes += label + ','
# else:
# continue
# if new_snomed_ct_codes.endswith(','):
# new_snomed_ct_codes = new_snomed_ct_codes[:-1]
# if new_snomed_ct_codes == '':
# return ''
# suffix = "This patient's symptoms include "
# comments[2] = prefix + label_text + suffix + new_snomed_ct_codes
# colon_index = comments[0].find(":")
# if colon_index != -1:
# comments[0] = "Age:" + comments[0][colon_index + 1:]
# else:
# return ''
# colon_index = comments[1].find(":")
# if colon_index != -1:
# comments[1] = "Gender:" + comments[1][colon_index + 1:]
# else:
# return ''
# ann = comments[0]
# age_matches = re.findall(r'\d+', ann)
# for age_code in age_matches:
# age_code_int = int(age_code)
# if age_code_int <= 6:
# ann = ann.replace(age_code, 'adolescence')
# elif age_code_int <= 17:
# ann = ann.replace(age_code, 'juvenile')
# elif age_code_int <= 40:
# ann = ann.replace(age_code, 'youths')
# elif age_code_int <= 65:
# ann = ann.replace(age_code, 'middle-age')
# else:
# ann = ann.replace(age_code, 'the elderly')
# comments[0] = ann
# if only_label:
# text = comments[2]
# else:
# text = comments[0] + '\n' + comments[1] + '\n' + comments[2]
# return text
def remove_before_colon(input_string):
index = input_string.find(": ")
if index != -1:
return input_string[index+2:]
else:
return input_string
def get_dictionaries(path='C:/Users/ROG/Desktop/ConditionNames_SNOMED-CT.csv'):
try:
# Load only the required columns to reduce memory usage
mapping_data = pd.read_csv(path, usecols=['Snomed_CT', 'Full Name'])
# Use pandas to_dict for fast conversion
dict_snomed_to_name = mapping_data.set_index('Snomed_CT')['Full Name'].to_dict()
dict_snomed_to_index = dict_snomed_to_index = mapping_data.reset_index().set_index('Snomed_CT')['index'].to_dict()
except FileNotFoundError:
raise FileNotFoundError(f"Unable to find the file at the specified path: {path}")
except Exception as e:
raise Exception(f"An error occurred while processing the file: {e}")
return dict_snomed_to_name, dict_snomed_to_index
def process_12_lead_shot(data_folder='./data/12-lead/WFDBRecords/', only_label=False):
diction1, diction2 = get_dictionaries('./data/12-lead.csv')
label_frequency = {} # Step 1: Create a label frequency dictionary
num_classes = len(diction1)
# Step 2: First pass to fill the frequency dictionary
for file_out in os.scandir(data_folder):
if file_out.is_dir():
path_in = file_out.path
for file_in in os.scandir(path_in):
if file_in.is_dir():
data_path = file_in.path
for entry in os.scandir(data_path):
if entry.is_file() and entry.name.endswith('.hea'):
header = wfdb.rdheader(entry.path[:-4])
label = header.comments[2]
label = remove_before_colon(label)
label_frequency[label] = label_frequency.get(label, 0) + 1
samples = []
samples_fewshot = []
samples_oneshot = []
samples_zeroshot = []
for file_out in os.scandir(data_folder):
if file_out.is_dir():
path_in = file_out.path
for file_in in os.scandir(path_in):
if file_in.is_dir():
data_path = file_in.path
for entry in os.scandir(data_path):
if entry.is_file() and entry.name.endswith('.hea'):
label_file = entry.path
record_name = label_file[:label_file.rfind('.')]
signals, _ = wfdb.rdsamp(record_name)
header = wfdb.rdheader(record_name)
if np.isnan(signals).any():
continue # Skip NaN values
label = header.comments[2]
label = remove_before_colon(label)
label_list = label.split(',')
label_indices = [diction2[int(snomed_ct_code)] for snomed_ct_code in label_list if int(snomed_ct_code) in diction2]
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
if not any(label_vector):
continue
text = pro_text(header.comments, diction1, only_label)
ecg = pro_ecg(signals)
if label_frequency[label] > 20:
samples.append((text, ecg, label_vector))
elif label_frequency[label] <= 20 and label_frequency[label] > 10:
samples_fewshot.append((text, ecg, label_vector))
elif label_frequency[label] <= 10 and label_frequency[label] > 1:
samples_oneshot.append((text, ecg, label_vector))
elif label_frequency[label] == 1:
samples_zeroshot.append((text, ecg, label_vector))
label_to_samples_map_fewshot = {}
for sample in samples_fewshot:
text, ecg, label_vector = sample
label_index = label_vector.index(1)
if label_index not in label_to_samples_map_fewshot:
label_to_samples_map_fewshot[label_index] = []
label_to_samples_map_fewshot[label_index].append(sample)
test_fewshot = []
for label_index, samples_list in label_to_samples_map_fewshot.items():
# Select seven samples from each class and keep them as test samples
selected_samples = samples_list[-7:]
test_fewshot.extend(selected_samples)
train_fewshot = [sample for samples_list in label_to_samples_map_fewshot.values() for sample in samples_list[:-7]]
np.random.shuffle(train_fewshot)
label_to_samples_map_oneshot = {}
for sample in samples_oneshot:
text, ecg, label_vector = sample
label_index = label_vector.index(1)
if label_index not in label_to_samples_map_oneshot:
label_to_samples_map_oneshot[label_index] = []
label_to_samples_map_oneshot[label_index].append(sample)
train_oneshot = []
for label_index, samples_fewshot in label_to_samples_map_oneshot.items():
# Select one sample from each class and keep it as a training sample
selected_sample = samples_fewshot.pop()
train_oneshot.append(selected_sample)
test_oneshot = [sample for samples_list in label_to_samples_map_oneshot.values() for sample in samples_list]
np.random.shuffle(train_oneshot)
# Shuffle and split the samples as before
index = [i for i in range(len(samples))]
np.random.shuffle(index)
split = int(0.9 * len(samples))
samples_train = [samples[i] for i in index[:split]]
samples_test = [samples[i] for i in index[split:]]
samples_train = samples_train + train_oneshot + train_fewshot
print(len(samples_train + samples_test))
print(len(test_fewshot))
print(len(test_oneshot))
print(len(samples_zeroshot))
# Save the filtered samples as before
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
with open('test_fewshot.pkl', 'wb') as file:
pickle.dump(test_fewshot, file)
with open('test_oneshot.pkl', 'wb') as file:
pickle.dump(test_oneshot, file)
with open('samples_test_zeroshot.pkl', 'wb') as file:
pickle.dump(samples_zeroshot, file)
return samples_train, samples_test
def process_12_lead(data_folder='./data/12-lead/WFDBRecords/', only_label=False):
diction1, diction2 = get_dictionaries('./data/12-lead.csv')
num_classes = len(diction1)
samples = []
for file_out in os.scandir(data_folder):
if file_out.is_dir():
path_in = file_out.path
for file_in in os.scandir(path_in):
if file_in.is_dir():
data_path = file_in.path
for entry in os.scandir(data_path):
if entry.is_file() and entry.name.endswith('.hea'):
label_file = entry.path
record_name = label_file[:label_file.rfind('.')]
signals, _ = wfdb.rdsamp(record_name)
header = wfdb.rdheader(record_name)
if np.isnan(signals).any():
continue # Skip NaN values
label = header.comments[2]
label = remove_before_colon(label)
label_list = label.split(',')
label_indices = [diction2[int(snomed_ct_code)] for snomed_ct_code in label_list if int(snomed_ct_code) in diction2]
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
if not any(label_vector):
continue
text = pro_text(header.comments, diction1, only_label)
ecg = pro_ecg(signals)
if label_indices:
samples.append((text, ecg, label_vector))
# Shuffle and split the samples as before
index = [i for i in range(len(samples))]
np.random.shuffle(index)
split = int(0.9 * len(samples))
samples_train = [samples[i] for i in index[:split]]
samples_test = [samples[i] for i in index[split:]]
print(len(samples_train + samples_test))
# Save the filtered samples as before
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
return samples_train, samples_test
def pro_pd(label, label_dict, few=False):
prefix = "Please provide a description of potential health problems, symptoms, and conditions that the patient might be facing based on the provided information.\nThis patient's symptoms include "
if few:
if not label['diagnostic_superclass']:
return '', 0
prefix += label['diagnostic_superclass'][0]
else:
if not label['description']:
return '', 0
prefix += label['description'][0]
gender = 'Gender: '
if label['sex'] == 1:
gender += 'male\n'
else:
gender += 'female\n'
age = 'Age: '
if label['age'] <= 6:
age += 'adolescence\n'
elif label['age'] <= 17:
age += 'juvenile\n'
elif label['age'] <= 40:
age += 'youths\n'
elif label['age'] <= 65:
age += 'middle-age\n'
else:
age += 'the elderly\n'
height = 'Height: '
if label['height'] is not None:
height += str(label['height'])
height += ' cm\n'
else:
height += 'unknown\n'
weight = 'Weight: '
if label['weight'] is not None:
weight += str(label['weight'])
weight += ' kg\n'
else:
weight += 'unknown\n'
text = gender + age + height + weight + prefix
if few:
if label['diagnostic_superclass'][0] == 'NORM':
vector = 0
elif label['diagnostic_superclass'][0] == 'STTC':
vector = 1
elif label['diagnostic_superclass'][0] == 'MI':
vector = 2
elif label['diagnostic_superclass'][0] == 'CD':
vector = 3
elif label['diagnostic_superclass'][0] == 'HYP':
vector = 4
else:
vector = label_dict[label['description'][0]]
return text, vector
def process_ptbxl(data_folder='./data/ptb-xl-a-large-publicly-available-electrocardiography-dataset-1.0.1/', few=True):
def aggregate_description(y_dic):
tmp = []
for key in y_dic.keys():
if key in agg_df.index:
tmp.append(agg_df.loc[key].description)
return list(set(tmp))
def aggregate_diagnostic(y_dic):
tmp = []
for key in y_dic.keys():
if key in agg_df.index:
tmp.append(agg_df.loc[key].diagnostic_class)
return list(set(tmp))
samples = []
diction = get_dict_ptb(few=few)
# Load and convert annotation data
Y = pd.read_csv(data_folder + 'ptbxl_database.csv', index_col='ecg_id')
Y.scp_codes = Y.scp_codes.apply(lambda x: ast.literal_eval(x))
# data = [wfdb.rdsamp(data_folder + f) for f in Y.filename_hr]
# data = np.array([signal for signal, meta in data]).astype(np.float32)
# Load scp_statements.csv for diagnostic aggregation
agg_df = pd.read_csv(data_folder + 'scp_statements.csv', index_col=0)
agg_df = agg_df[agg_df.diagnostic == 1]
# Apply diagnostic superclass
Y['description'] = Y.scp_codes.apply(aggregate_description)
Y['diagnostic_superclass'] = Y.scp_codes.apply(aggregate_diagnostic)
for _, item in Y.iterrows():
signals, _ = wfdb.rdsamp(data_folder + item.filename_hr)
# header = wfdb.rdheader(data_folder + f)
if np.isnan(signals).any():
continue # Skip NaN values
text, vector = pro_pd(item, diction, few=few)
ecg = pro_ecg(signals)
if ecg.shape == (5000, 12) and text != '':
samples.append((text, ecg, vector))
# Shuffle and split the samples as before
index = [i for i in range(len(samples))]
np.random.shuffle(index)
split = int(0.9 * len(samples))
samples_train = [samples[i] for i in index[:split]]
samples_test = [samples[i] for i in index[split:]]
# Save the filtered samples as before
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
return samples_train, samples_test
def process_Georgia(data_folder='./data/georgia/', only_label=False):
if only_label:
diction1, diction2 = get_dictionaries('./data/geo-score.csv')
else:
diction1, diction2 = get_dictionaries('./data/essy.csv')
num_classes = len(diction1)
print(num_classes)
samples = []
for file_in in os.scandir(data_folder):
if file_in.is_dir():
data_path = file_in.path
for entry in os.scandir(data_path):
if entry.is_file() and entry.name.endswith('.hea'):
label_file = entry.path
header = wfdb.rdheader(label_file[:label_file.rfind('.')])
label = remove_before_colon(header.comments[2])
signals, _ = wfdb.rdsamp(label_file[:label_file.rfind('.')])
if np.isnan(signals).any():
continue # Skip NaN values
label_list = label.split(',')
label_list = [int(item) for item in label_list]
# print(label_list)
# if only_label:
# label_list = trans_code(label_list)
label_indices = [diction2[code] for code in label_list if code in diction2]
# print(diction2)
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
# print(label_indices)
if not any(label_vector):
continue
text = pro_text(header.comments, diction1)
# print(text)
# break
ecg = pro_ecg(signals)
if ecg.shape == (5000, 12):
samples.append((text, ecg, label_vector))
np.random.shuffle(samples)
split = int(0.9 * len(samples))
samples_train = samples[:split]
samples_test = samples[split:]
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
return samples_train, samples_test
def process_ecg(data_folder1='./data/georgia', data_folder2='./data/cpsc_2018', only_label=False):
if only_label:
diction1, diction2 = get_dictionaries('./data/geo-score.csv')
else:
diction1, diction2 = get_dictionaries('./data/essy.csv')
num_classes = len(diction1)
samples = []
for file_in in os.scandir(data_folder1):
if file_in.is_dir():
data_path = file_in.path
for entry in os.scandir(data_path):
if entry.is_file() and entry.name.endswith('.hea'):
label_file = entry.path
header = wfdb.rdheader(label_file[:label_file.rfind('.')])
label = remove_before_colon(header.comments[2])
signals, _ = wfdb.rdsamp(label_file[:label_file.rfind('.')])
if np.isnan(signals).any():
continue # Skip NaN values
label_list = label.split(',')
label_list = [int(item) for item in label_list]
# print(label_list)
# if only_label:
# label_list = trans_code(label_list)
label_indices = [diction2[code] for code in label_list if code in diction2]
# print(diction2)
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
# print(label_indices)
if not any(label_vector):
continue
text = pro_text(header.comments, diction1)
# print(text)
# break
ecg = pro_ecg(signals)
if ecg.shape == (5000, 12):
samples.append((text, ecg, label_vector))
for file_out in os.scandir(data_folder2):
if file_out.is_dir():
path_in = file_out.path
for entry in os.scandir(path_in):
if entry.is_file() and entry.name.endswith('.hea'):
label_file = entry.path
record_name = label_file[:label_file.rfind('.')]
signals, _ = wfdb.rdsamp(record_name)
header = wfdb.rdheader(record_name)
if np.isnan(signals).any():
continue # Skip NaN values
label = header.comments[2]
label = remove_before_colon(label)
label_list = label.split(',')
label_list = [int(item) for item in label_list]
label_indices = [diction2[snomed_ct_code] for snomed_ct_code in label_list if snomed_ct_code in diction2]
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
if not any(label_vector):
continue
text = pro_text(header.comments, diction1)
ecg = pro_ecg(signals)
if ecg.shape == (5000, 12):
samples.append((text, ecg, label_vector))
np.random.shuffle(samples)
split = int(0.9 * len(samples))
samples_train = samples[:split]
samples_test = samples[split:]
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
return samples_train, samples_test
def process_ptb_xl_mul(data_folder='./data/ptb-xl-multi/', only_label=False):
if only_label:
diction1, diction2 = get_dictionaries('./data/ptbxl-score.csv')
else:
diction1, diction2 = get_dictionaries('./data/ptbxl.csv')
num_classes = len(diction1)
samples = []
for file_out in os.scandir(data_folder):
if file_out.is_dir():
path_in = file_out.path
for entry in os.scandir(path_in):
if entry.is_file() and entry.name.endswith('.hea'):
record_name = entry.path[:-4]
header = wfdb.rdheader(record_name)
label = remove_before_colon(header.comments[2])
signals, _ = wfdb.rdsamp(record_name)
if np.isnan(signals).any():
continue
label_list = label.split(',')
label_indices = [diction2[int(code)] for code in label_list if int(code) in diction2]
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
if not any(label_vector):
continue
text = pro_text(header.comments, diction1)
ecg = pro_ecg(signals)
if ecg.shape == (5000, 12):
samples.append((text, ecg, label_vector))
np.random.shuffle(samples)
split = int(0.9 * len(samples))
samples_train = samples[:split]
samples_test = samples[split:]
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
return samples_train, samples_test
def process_cpsc_mul(data_folder='./data/cpsc_2018/', only_label=False):
if only_label:
diction1, diction2 = get_dictionaries('./data/cpsc-score.csv')
else:
diction1, diction2 = get_dictionaries('./data/essy.csv')
num_classes = len(diction1)
samples = []
for file_out in os.scandir(data_folder):
if file_out.is_dir():
path_in = file_out.path
for entry in os.scandir(path_in):
if entry.is_file() and entry.name.endswith('.hea'):
label_file = entry.path
record_name = label_file[:label_file.rfind('.')]
signals, _ = wfdb.rdsamp(record_name)
header = wfdb.rdheader(record_name)
if np.isnan(signals).any():
continue # Skip NaN values
label = header.comments[2]
label = remove_before_colon(label)
label_list = label.split(',')
label_list = [int(item) for item in label_list]
label_indices = [diction2[snomed_ct_code] for snomed_ct_code in label_list if snomed_ct_code in diction2]
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
if not any(label_vector):
continue
text = pro_text(header.comments, diction1)
ecg = pro_ecg(signals)
if ecg.shape == (5000, 12):
samples.append((text, ecg, label_vector))
# Shuffle and split the samples as before
index = [i for i in range(len(samples))]
np.random.shuffle(index)
split = int(0.9 * len(samples))
samples_train = [samples[i] for i in index[:split]]
samples_test = [samples[i] for i in index[split:]]
# Save the filtered samples as before
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
with open('zeroshot.pkl', 'wb') as file:
pickle.dump(samples, file)
print(len(samples))
return samples_train, samples_test
def pro_text(comments, diction, only_label=False):
ann = comments[2]
snomed_ct_matches = re.findall(r'\d+', ann)
prefix = "Describe the potential health issue(s) and associated symptom(s) the patient may be experiencing based on the provided information.\nThe symptom(s) exhibited by this patient include(s) "
new_snomed_ct_codes = ''
for snomed_ct_code in snomed_ct_matches:
label = diction.get(int(snomed_ct_code))
if label:
new_snomed_ct_codes += label + ','
else:
continue
if new_snomed_ct_codes.endswith(','):
new_snomed_ct_codes = new_snomed_ct_codes[:-1]
if new_snomed_ct_codes == '':
return ''
comments[2] = prefix + new_snomed_ct_codes
colon_index = comments[0].find(":")
if colon_index != -1:
comments[0] = "Age:" + comments[0][colon_index + 1:]
else:
return ''
colon_index = comments[1].find(":")
if colon_index != -1:
comments[1] = "Gender:" + comments[1][colon_index + 1:]
else:
return ''
ann = comments[0]
age_matches = re.findall(r'\d+', ann)
for age_code in age_matches:
age_code_int = int(age_code)
if age_code_int <= 6:
ann = ann.replace(age_code, 'adolescence')
elif age_code_int <= 17:
ann = ann.replace(age_code, 'juvenile')
elif age_code_int <= 40:
ann = ann.replace(age_code, 'youths')
elif age_code_int <= 65:
ann = ann.replace(age_code, 'middle-age')
else:
ann = ann.replace(age_code, 'the elderly')
comments[0] = ann
if only_label:
text = comments[2]
else:
text = comments[0] + '\n' + comments[1] + '\n' + comments[2]
return text
def process_ecg_data(data_folder, dict_path, multi_folder=False, only_label=False):
diction1, diction2 = get_dictionaries(dict_path)
label_frequency = {}
num_classes = len(diction1)
samples = []
def process_entry(entry):
if entry.is_file() and entry.name.endswith('.hea'):
record_name = entry.path[:-4]
header = wfdb.rdheader(record_name)
label = remove_before_colon(header.comments[2])
label_frequency[label] = label_frequency.get(label, 0) + 1
signals, _ = wfdb.rdsamp(record_name)
if np.isnan(signals).any():
return None
label_list = label.split(',')
label_indices = [diction2[int(code)] for code in label_list if int(code) in diction2]
label_vector = [1 if i in label_indices else 0 for i in range(num_classes)]
if not any(label_vector):
return None
text = pro_text(header.comments, diction1, only_label)
ecg = pro_ecg(signals)
if ecg.shape == (5000, 12):
return (text, ecg.transpose(-1, 0), label_vector)
else:
return None
for file_out in os.scandir(data_folder):
if multi_folder and file_out.is_dir():
path_in = file_out.path
for entry in os.scandir(path_in):
result = process_entry(entry)
if result:
samples.append(result)
elif not multi_folder:
result = process_entry(file_out)
if result:
samples.append(result)
np.random.shuffle(samples)
split = int(0.9 * len(samples))
samples_train = samples[:split]
samples_test = samples[split:]
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
return samples_train, samples_test
def process_eeg(data_folder='./data/sleep-edf-database-1.0.0'):
samples = []
labels = np.load(os.path.join(data_folder, 'label.npy'))
ecgs = np.load(os.path.join(data_folder, 'data.npy'))
# Iterate over the array and normalize
prefix = "Select a previously mentioned sleep pattern and report on the person's sleep using the provided information.\nThe person's sleep pattern is "
midfix = 'The sleep patterns include waking up, rapid eye movement sleep, and sleep stages one through four, as well as periods of movement and unidentified stages.\n'
for ecg, label in zip(ecgs, labels):
# Check whether values are NaN
if np.isnan(ecg).any():
continue # Drop ECG samples that contain NaN values
# Normalize the data and append the result to the list
ecg = normalize(ecg) # Using the normalize() helper
# print(label)
if int(label) == 0:
text = 'waking up'
elif int(label) == 1:
text = 'rapid eye movement sleep'
elif int(label) == 2:
text = 'sleep stage one'
elif int(label) == 3:
text = 'sleep stage two'
elif int(label) == 4:
text = 'sleep stage three'
elif int(label) == 5:
text = 'sleep stage four'
elif int(label) == 6:
text = 'period of movement'
elif int(label) == 7:
text = 'unidentified stage'
else:
text = ''
if text == '':
continue
text = midfix + prefix + text
label_vector = label
samples.append((text, ecg, label_vector))
# samples = samples[:10000]
np.random.shuffle(samples)
split = int(0.9 * len(samples))
samples_train = samples[:split]
samples_test = samples[split:]
with open('samples_train.pkl', 'wb') as file:
pickle.dump(samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(samples_test, file)
return samples_train, samples_test
def process_har(data_folder='./data/HAR'):
normalized_samples_train = []
normalized_samples_test = []
data_val = torch.load('./data/HAR/val.pt')
data_train = torch.load('./data/HAR/train.pt')
data_test = torch.load('./data/HAR/test.pt')
samples_train = data_train['samples'].numpy()
labels_train = data_train['labels'].numpy()
samples_test = data_test['samples'].numpy()
labels_test = data_test['labels'].numpy()
samples_val = data_val['samples'].numpy()
labels_val = data_val['labels'].numpy()
samples = np.concatenate([samples_train, samples_val], axis=0)
labels = np.concatenate([labels_train, labels_val], axis=0)
# Iterate over the array and normalize
prefix = "Please choose one activity from the previously mentioned six options and analyze the individual's physical activity based on the provided information.\nThe individual is currently engaged in "
midfix = 'Physical activities such as walking, ascending stairs, descending stairs, sitting, standing, and lying down are recorded using mobile phone sensors.\n'
for ecg, label in zip(samples, labels):
# Check whether values are NaN
if np.isnan(ecg).any():
continue # Drop ECG samples that contain NaN values
# Normalize the data and append the result to the list
ecg = normalize(ecg.astype(np.float32)) # Using the normalize() helper
ecg = ecg.transpose()
if int(label) == 0:
text = 'walking'
elif int(label) == 1:
text = 'ascending stairs'
elif int(label) == 2:
text = 'descending stairs'
elif int(label) == 3:
text = 'sitting'
elif int(label) == 4:
text = 'standing'
elif int(label) == 5:
text = 'lying down'
else:
text = ''
if text == '':
continue
text = midfix + prefix + text
label_vector = label
if ecg.shape == (128, 9):
normalized_samples_train.append((text, ecg, label_vector))
for ecg, label in zip(samples_test, labels_test):
# Check whether values are NaN
if np.isnan(ecg).any():
continue # Drop ECG samples that contain NaN values
# Normalize the data and append the result to the list
ecg = normalize(ecg.astype(np.float32)) # Using the normalize() helper
ecg = ecg.transpose()
if int(label) == 0:
text = 'walking'
elif int(label) == 1:
text = 'ascending stairs'
elif int(label) == 2:
text = 'descending stairs'
elif int(label) == 3:
text = 'sitting'
elif int(label) == 4:
text = 'standing'
elif int(label) == 5:
text = 'lying down'
else:
text = ''
if text == '':
continue
text = midfix + prefix + text
label_vector = label
if ecg.shape == (128, 9):
normalized_samples_test.append((text, ecg, label_vector))
# np.random.shuffle(normalized_samples)
# split = int(0.8 * len(normalized_samples))
# samples_train = normalized_samples[:split]
# samples_test = normalized_samples[split:]
with open('samples_train.pkl', 'wb') as file:
pickle.dump(normalized_samples_train, file)
with open('samples_test.pkl', 'wb') as file:
pickle.dump(normalized_samples_test, file)
return normalized_samples_train, normalized_samples_test
def padding_varying_length(data):
data[np.isnan(data)] = 0
return data
def process_ad(data_folder='./datas/AD_data'):
normalized_samples_train = []
normalized_samples_test = []
data_train = torch.load('./datas/AD_data/train.pt')
data_test = torch.load('./datas/AD_data/test.pt')
samples_train = data_train['samples'].numpy()
labels_train = data_train['labels'].numpy()
samples_test = data_test['samples'].numpy()
labels_test = data_test['labels'].numpy()
# Iterate over the array and normalize
prefix = "Please select one activity from the previously mentioned ten digits and analyze the individual's handwriting based on the provided information.\nThe person is currently writing the digit "
midfix = 'Physical activities that specifically involve using a pen to write digits, which range from one to ten.\n'
for ecg, label in zip(samples_train, labels_train):
# # Check whether values are NaN
# padding_varying_length(ecg)
# Normalize the data and append the result to the list