File size: 16,795 Bytes
35f60b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import shutil
import numpy as np
import pandas as pd

from scipy.signal import iirnotch, lfilter
from data_utils import butter_bandpass_filter, correct_ecg_inversion

import matplotlib.pyplot as plt
from tqdm import tqdm
import shutil
import librosa
import pickle
import gc

BASE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'datasets')
SAMPLING_RATE = 200
TARGET_RESAMPLE = 100
NOTCH_FREQ = 60
EEG_LOWCUT = 0.3
EEG_HIGHCUT = 40
EMG_LOWCUT = 10
EMG_HIGHCUT = 1000
ECG_LOWCUT = 0.3
ECG_HIGHCUT = 70
FLOW_LOWCUT = 0
FLOW_HIGHCUT = 15

do_resample = (SAMPLING_RATE != TARGET_RESAMPLE)

NUM_PROCESS = 4

import argparse
import multiprocessing

def process_ecg(args):
    sig, chn_grp, chn, split = args
    sig_path = os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn, sig)
    data = np.load(sig_path)
    # data = data.reshape(-1, 1)
    data = data.reshape(-1,)
    # Apply bandpass filter
    filtered = butter_bandpass_filter(data, ECG_LOWCUT, ECG_HIGHCUT, SAMPLING_RATE)
    b_notch, a_notch = iirnotch(NOTCH_FREQ, 30, SAMPLING_RATE)
    filtered = lfilter(b_notch, a_notch, filtered)   

    filtered = filtered.reshape(-1, SAMPLING_RATE*30)
    
    filtered_epochs = []
    
    for epoch in filtered:
        inv_epoch, _ = correct_ecg_inversion(epoch, SAMPLING_RATE)
        filtered_epochs.append(inv_epoch)                
    
    filtered = np.stack(filtered_epochs, axis=0)

    if do_resample:
        filtered = np.reshape(filtered, (-1,1))
        filtered = librosa.resample(filtered, orig_sr=SAMPLING_RATE, target_sr=TARGET_RESAMPLE, axis=0, res_type='soxr_qq')
        filtered = filtered.reshape(-1, TARGET_RESAMPLE*30)
    
    if cfg.save_type == 'npy':
        # Save processed data
        output_path = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, chn, sig)
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        np.save(output_path, filtered.astype(np.float32))
        return
    else:
        return filtered


def process_eeg(args):
    sig, chn_grp, chn, split = args
    sig_path = os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn, sig)
    data = np.load(sig_path)
    # data = data.reshape(-1, 1)
    data = data.reshape(-1,)
    # Apply bandpass filter
    filtered = butter_bandpass_filter(data, EEG_LOWCUT, EEG_HIGHCUT, SAMPLING_RATE)
    b_notch, a_notch = iirnotch(NOTCH_FREQ, 30, SAMPLING_RATE)
    filtered = lfilter(b_notch, a_notch, filtered)

    if do_resample:        
        filtered = librosa.resample(filtered, orig_sr=SAMPLING_RATE, target_sr=TARGET_RESAMPLE, axis=0, res_type='soxr_qq')

    filtered = filtered.reshape(-1, TARGET_RESAMPLE*30)
    
    if cfg.save_type == 'npy':
        # Save processed data
        output_path = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, chn, sig)
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        np.save(output_path, filtered.astype(np.float32))
        return
    else:
        return filtered

def process_emg(args):
    sig, chn_grp, chn, split = args
    sig_path = os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn, sig)
    data = np.load(sig_path)
    # data = data.reshape(-1, 1)
    data = data.reshape(-1,)
    # Apply bandpass filter
    filtered = butter_bandpass_filter(data, EMG_LOWCUT, EMG_HIGHCUT, SAMPLING_RATE)
    b_notch, a_notch = iirnotch(NOTCH_FREQ, 30, SAMPLING_RATE)
    filtered = lfilter(b_notch, a_notch, filtered)

    if do_resample:        
        filtered = librosa.resample(filtered, orig_sr=SAMPLING_RATE, target_sr=TARGET_RESAMPLE, axis=0, res_type='soxr_qq')

    filtered = filtered.reshape(-1, TARGET_RESAMPLE*30)
    
    if cfg.save_type == 'npy':
        # Save processed data
        output_path = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, chn, sig)
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        np.save(output_path, filtered.astype(np.float32))
        return
    else:
        return filtered

def process_flow(args):
    sig, chn_grp, chn, split = args
    sig_path = os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn, sig)
    data = np.load(sig_path)
    # data = data.reshape(-1, 1)
    data = data.reshape(-1,)
    # Apply bandpass filter
    filtered = butter_bandpass_filter(data, FLOW_LOWCUT, FLOW_HIGHCUT, SAMPLING_RATE)    
    
    # median filter?

    if do_resample:        
        filtered = librosa.resample(filtered, orig_sr=SAMPLING_RATE, target_sr=TARGET_RESAMPLE, axis=0, res_type='soxr_qq')

    filtered = filtered.reshape(-1, TARGET_RESAMPLE*30)

    if cfg.save_type == 'npy':
        # Save processed data
        output_path = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, chn, sig)
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        np.save(output_path, filtered.astype(np.float32))
        return
    else:
        return filtered

def save_mmap(results, sig_list, chn_grp, chn, split='train'):
    signame_list = [sig.split('.')[0] for sig in sig_list]
    epoch_lengths = [sig.shape[0] for sig in results]
    metadata = dict()
    sig_info = dict()    
    start, end = 0, 0    
    for signame, sig in zip(signame_list, results):
        length  = sig.shape[0]
        end = start + length
        info = dict()
        info['pos'] = (start, end)
        info['stats'] = {'sum': float(np.sum(sig)), 'sumsq': float(np.sum(sig ** 2))}
        sig_info[signame] = info
        start = end
    

    mmap_path = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, f'{chn}.mmap')
    signals_cat = np.concatenate(results, axis=0).astype(np.float32)    
    os.makedirs(os.path.dirname(mmap_path), exist_ok=True)
    data = np.memmap(mmap_path, dtype=np.float32, mode='w+', shape=signals_cat.shape)
    data[:] = signals_cat
    data.flush()
        
    metadata['sig_info'] = sig_info
    metadata['data_shape'] = signals_cat.shape
    info_path = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, f'{chn}.pickle')
    with open(info_path, 'wb') as f:
       pickle.dump(metadata, f)

    del data



    

def preprocess(sig_list, chn_grp=None, chn=None, split='train'):
    def _process(sig_list, chn_grp, chn, split):
        print(f"Processing {chn_grp}/{chn}")
        if chn_grp in ['EEG','EOG']:        
            # sig_list = sorted(os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)))
            input_list = [(sig, chn_grp, chn, split) for sig in sig_list]

            with multiprocessing.Pool(NUM_PROCESS) as pool:
                results = list(tqdm(pool.imap(process_eeg, input_list), total=len(input_list)))

            if cfg.save_type == 'mmap':
                save_mmap(results, sig_list, chn_grp, chn, split)
            del results

        elif chn_grp in ['EMG']:
            # sig_list = sorted(os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)))
            input_list = [(sig, chn_grp, chn, split) for sig in sig_list]
            with multiprocessing.Pool(NUM_PROCESS) as pool:
                results = list(tqdm(pool.imap(process_emg, input_list), total=len(input_list)))
            
            if cfg.save_type == 'mmap':
                save_mmap(results, sig_list, chn_grp, chn, split)
            del results

        elif chn_grp in ['ECG']:            

            # sig_list = sorted(os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)))
            input_list = [(sig, chn_grp, chn, split) for sig in sig_list]
            with multiprocessing.Pool(NUM_PROCESS) as pool:
                results = list(tqdm(pool.imap(process_ecg, input_list), total=len(input_list)))
            if cfg.save_type == 'mmap':
                save_mmap(results, sig_list, chn_grp, chn, split)
            del results

        elif chn_grp in ['ABD', 'CHEST', 'AIRFLOW']:
            # sig_list = sorted(os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)))
            input_list = [(sig, chn_grp, chn, split) for sig in sig_list]
            with multiprocessing.Pool(NUM_PROCESS) as pool:
                results = list(tqdm(pool.imap(process_flow, input_list), total=len(input_list)))
            if cfg.save_type == 'mmap':
                save_mmap(results, sig_list, chn_grp, chn, split)
            del results
        else:        
            results = []
            for sig in tqdm(sig_list):
                sig_path = os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn, sig)
                data = np.load(sig_path)
                if do_resample or chn == 'SaO2':
                    data = data.reshape(-1, 1)
                    if chn == 'SaO2':
                        data = librosa.resample(data, orig_sr=SAMPLING_RATE, target_sr=1, axis=0, res_type='soxr_qq')
                        data = data / 1e8
                        if round(np.max(data)) > 1 or round(np.min(data)) < 0:
                            print(f"Warning: SaO2 values out of range: {sig} with min {np.min(data)} and max {np.max(data)}")
                        data = data.reshape(-1, 1*30)
                    else:
                        data = librosa.resample(data, orig_sr=SAMPLING_RATE, target_sr=TARGET_RESAMPLE, axis=0, res_type='soxr_qq')
                        data = data.reshape(-1, TARGET_RESAMPLE*30)
                # output_path = os.path.join(BASE_PATH, cfg.output_dir, chn_grp, chn, sig)
                # shutil.copy(sig_path, output_path)
                if cfg.save_type == 'npy':
                    # Save processed data
                    output_path = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, chn, sig)
                    os.makedirs(os.path.dirname(output_path), exist_ok=True)
                    np.save(output_path, data)
                elif cfg.save_type == 'mmap':
                    results.append(data)
            # sig_list = sorted(os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)))
            save_mmap(results, sig_list, chn_grp, chn, split)
            del results
        gc.collect()
    
    
    if chn_grp is not None and chn is not None:
        _process(sig_list, chn_grp, chn, split)
        return
    else:
        for chn_grp in os.listdir(os.path.join(BASE_PATH, cfg.data_dir)):
            if not os.path.isdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp)):
                continue
            for chn in os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp)):  
                if not os.path.isdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)):
                    continue
                _process(sig_list, chn_grp, chn, split)  
                
                
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', default='isruc_all/signals_MAE', help='Physionet 2018 raw data location')
parser.add_argument('--output_dir', default='isruc_all/mmap_signals_MAE_processed', help='Physionet 2018 processed data location')
parser.add_argument('--save_type', default='mmap', help='Which data type to save. "npy" or "mmap"')
parser.add_argument('--chn_grp', default=None, help='If specified, only preprocess this channel group')
parser.add_argument('--chn', default=None, help='If specified, only preprocess this channel')
parser.add_argument('--ann_split', action='store_true', help='To split annotation files into train/val/test')
parser.add_argument('--num_train', type=int, default=50, help='Number of training samples')

cfg = parser.parse_args()

def get_isruc_filename(ids, ds_id):
    if ds_id == 2:
        return  [f"sg{ds_id}_{id:03d}_1.npy" for id in ids] + [f"sg{ds_id}_{id:03d}_2.npy" for id in ids]
    else:    
        return [f"sg{ds_id}_{id:03d}.npy" for id in ids]


if __name__ == "__main__":   
    skip_val, skip_test = False, False
    if cfg.num_train < 90:        
        if os.path.exists(os.path.join(BASE_PATH, cfg.output_dir, 'val')):
            skip_val = True
        if os.path.exists(os.path.join(BASE_PATH, cfg.output_dir, 'test')):
            skip_test = True
        cfg.output_dir += f"_train{cfg.num_train}"
    
    
    list_files_train = sorted(get_isruc_filename(list(range(1,93)), ds_id=1)) # subjet 8, 40 are missing
    list_files_val = sorted(get_isruc_filename(list(range(93,101)), ds_id=1))
    list_files_test = sorted(get_isruc_filename(list(range(1,9)), ds_id=2))
    list_files_test += sorted(get_isruc_filename(list(range(1,11)), ds_id=3))
    
    sig_list = sorted(os.listdir(os.path.join(BASE_PATH, cfg.data_dir, "EEG", "C3-A2")))    
    
    for chn_grp in os.listdir(os.path.join(BASE_PATH, cfg.data_dir)):
        # Skip any files that are not directories
        if not os.path.isdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp)):
            continue
        for chn in os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp)):    
            # Skip any files that are not directories
            if not os.path.isdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)):
                continue
            sig_list_chn = sorted(os.listdir(os.path.join(BASE_PATH, cfg.data_dir, chn_grp, chn)))
            print(f"Number of records in {chn_grp}/{chn}:", len(sig_list_chn))
            sig_list = list(set(sig_list).intersection(set(sig_list_chn)))
            
    print(f"Number of records that exist in all chns:", len(sig_list)) # Total 7698 -> 7579 records
    
    list_files_train = sorted(list(set(list_files_train).intersection(set(sig_list))))
    list_files_val = sorted(list(set(list_files_val).intersection(set(sig_list))))
    list_files_test = sorted(list(set(list_files_test).intersection(set(sig_list))))
    
    # if cfg.num_train < 50:    
    list_files_train = list_files_train[:cfg.num_train]

    print("Number of records in training set:", len(list_files_train)) 
    print("Number of records in validation set:", len(list_files_val)) 
    print("Number of records in test set:", len(list_files_test)) 
   
    
    print("Processing training set...")
    preprocess(list_files_train, cfg.chn_grp, cfg.chn, split='train')
    
    if skip_val:
        val_output_dir = cfg.output_dir
        val_output_dir = val_output_dir.replace(f"_train{cfg.num_train}","")
        os.symlink(os.path.join(BASE_PATH, val_output_dir, 'val'), os.path.join(BASE_PATH, cfg.output_dir, 'val'))
    else:
        print("Processing evaluation set...")
        preprocess(list_files_val, cfg.chn_grp, cfg.chn, split='val')
    
    if skip_test:
        test_output_dir = cfg.output_dir
        test_output_dir = test_output_dir.replace(f"_train{cfg.num_train}","")
        os.symlink(os.path.join(BASE_PATH, test_output_dir, 'test'), os.path.join(BASE_PATH, cfg.output_dir, 'test'))
    else:
        print("Processing test set...")
        preprocess(list_files_test, cfg.chn_grp, cfg.chn, split='test')
        
    if cfg.ann_split:
        # Reorganize annotations files
        ANN_PATH = os.path.join(BASE_PATH, 'ISRUC_SG1/annotations')
        NEW_ANN_PATH = os.path.join(BASE_PATH, 'ISRUC_SG1/annotations_split')
        os.makedirs(NEW_ANN_PATH, exist_ok=True)
        os.makedirs(os.path.join(NEW_ANN_PATH,'train'), exist_ok=True)
        os.makedirs(os.path.join(NEW_ANN_PATH,'val'), exist_ok=True)
        os.makedirs(os.path.join(NEW_ANN_PATH,'test'), exist_ok=True)

        for fname in list_files_train:
            ann_fname = fname.replace('.npy', '_ann.npy')
            shutil.copy(os.path.join(ANN_PATH, ann_fname), os.path.join(NEW_ANN_PATH, 'train', ann_fname))
        for fname in list_files_val:
            ann_fname = fname.replace('.npy', '_ann.npy')
            shutil.copy(os.path.join(ANN_PATH, ann_fname), os.path.join(NEW_ANN_PATH, 'val', ann_fname))
        for fname in list_files_test:
            ann_fname = fname.replace('.npy', '_ann.npy')
            shutil.copy(os.path.join(ANN_PATH, ann_fname), os.path.join(NEW_ANN_PATH, 'test', ann_fname))


    for split in ['train', 'val', 'test']:
        #  create link files to respiratory channels
        os.makedirs(os.path.join(BASE_PATH, cfg.output_dir, split, 'RESP'), exist_ok=True)
        for chn_grp in ['ABD', 'CHEST', 'AIRFLOW']:
            chns = [f.split('.')[0] for f in os.listdir(os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp))]
            for chn in chns:
                src_mmap = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, f'{chn}.mmap')
                src_pickle = os.path.join(BASE_PATH, cfg.output_dir, split, chn_grp, f'{chn}.pickle')
                dst_mmap = os.path.join(BASE_PATH, cfg.output_dir, split, 'RESP', f'{chn}.mmap')
                dst_pickle = os.path.join(BASE_PATH, cfg.output_dir, split, 'RESP', f'{chn}.pickle')
                if not os.path.exists(dst_mmap):
                    os.symlink(src_mmap, dst_mmap)
                if not os.path.exists(dst_pickle):
                    os.symlink(src_pickle, dst_pickle)