forked from greydongilmore/edf-epoch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.py
1584 lines (1317 loc) · 61.2 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import numpy as np
import pandas as pd
pd.set_option('precision', 6)
import json
import datetime
import warnings
import re
from struct import unpack
from math import floor
import shutil
import glob
from collections import OrderedDict
import sys
##############################################################################
# HELPERS #
##############################################################################
def padtrim(buf, num):
"""
Adds padding to string data.
:param buf: input string to pad
:type buf: string
:param num: Length of desired output buffer.
:type num: integer
:return buffer: The input string padded to desired size.
:type butter: string
"""
num -= len(buf)
if num>=0:
# pad the input to the specified length
buffer = (str(buf) + ' ' * num)
else:
# trim the input to the specified length
buffer = (buf[0:num])
return bytes(buffer, 'latin-1')
def sorted_nicely(lst):
"""
Sorts the given iterable in the way that is expected.
:param lst: The iterable to be sorted.
:type lst: list
:return sorted_lst: The input string padded to desired size.
:type sorted_lst: list
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
sorted_lst = sorted(lst, key = alphanum_key)
return sorted_lst
def partition(iterable):
"""
Seperates list of strings into alpha and digit.
:param iterable: The iterable to seperated.
:type iterable: list
:return values: List of lists containing seperated input strings.
:type values: list
"""
values = []
for item in iterable:
if len(re.findall(r"([a-zA-Z]+)([0-9]+)",item))>1:
first = "".join(list(re.findall(r"([a-zA-Z]+)([0-9]+)([a-zA-Z]+)",item)[0]))
second = list(re.findall(r"([a-zA-Z]+)([0-9]+)",item)[-1])[-1]
values.append([first, second])
elif list(re.findall(r"([a-zA-Z]+)([0-9]+)",item)):
values.append(list(re.findall(r"([a-zA-Z]+)([0-9]+)",item)[0]))
else:
values.append(["".join(x for x in item if not x.isdigit()), "".join(sorted(x for x in item if x.isdigit()))])
return values
def determine_groups(iterable):
"""
Identifies unique strings in a list of strings which include alphas.
:param iterable: The iterable to seperated into unique groups.
:type iterable: list
:return values: List of lists ccontaining seperated string groups.
:type values: list
"""
values = []
for item in iterable:
if len(re.findall(r"([a-zA-Z]+)([0-9]+)",item))>1:
first = "".join(list(re.findall(r"([a-zA-Z]+)([0-9]+)([a-zA-Z]+)",item)[0]))
values.append(first)
else:
values.append("".join(x for x in item if not x.isdigit()))
values = list(set(values))
return values
def sec2time(sec, n_msec=3):
''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
if hasattr(sec,'__len__'):
return [sec2time(s) for s in sec]
neg=False
if sec <0:
neg=True
sec = sec*-1
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if n_msec > 0:
pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
else:
pattern = r'%02d:%02d:%02d'
if d == 0:
if neg:
return '-' + pattern % (h, m, s)
else:
return pattern % (h, m, s)
return ('%d days, ' + pattern) % (d, h, m, s)
##############################################################################
# EDF READER #
##############################################################################
class EDFReader():
"""
This class will read the edf file format.
:param fname: filename to read.
:type fname: string
"""
def __init__(self, fname=None):
self.fname = None
self.meas_info = None
self.chan_info = None
self.calibrate = None
self.offset = None
if fname:
self.fname = fname
self.readHeader()
def open(self, fname):
self.fname = fname
return self.readHeader()
def readHeader(self):
# the following is copied over from MNE-Python and subsequently modified
# to more closely reflect the native EDF standard
meas_info = {}
chan_info = {}
with open(self.fname, 'r+b') as fid:
assert(fid.tell() == 0)
meas_info['magic'] = fid.read(8).strip().decode()
subject_id = fid.read(80).strip().decode() # subject id
meas_info['subject_code'] = subject_id.split(' ')[0]
meas_info['gender'] = subject_id.split(' ')[1]
meas_info['birthdate'] = subject_id.split(' ')[2]
meas_info['subject_id'] = subject_id.split(' ')[-1]
meas_info['firstname'] = None
meas_info['lastname'] = None
if not any(substring in meas_info['subject_id'].lower() for substring in {'x,x','x_x','x'}):
meas_info['firstname'] = meas_info['subject_id'].replace('_',',').replace('-',',').split(',')[-1]
meas_info['lastname'] = meas_info['subject_id'].replace('_',',').replace('-',',').split(',')[0]
if meas_info['lastname'] == 'sub':
meas_info['lastname']=meas_info['firstname']
meas_info['firstname']='sub'
else:
filen = os.path.basename(self.fname).replace(' ','')
if any(substring in filen for substring in {'~','_'}) and not filen.startswith('sub'):
firstname = filen.replace('_',' ').replace('~',' ').split()[1]
meas_info['firstname'] = firstname if firstname.lower() != 'x' else None
lastname = filen.replace('_',' ').replace('~',' ').split()[0]
meas_info['lastname'] = lastname if lastname.lower() != 'x' else None
meas_info['recording_id'] = fid.read(80).strip().decode() # recording id
day, month, year = [int(x) for x in re.findall('(\d+)', fid.read(8).decode())]
hour, minute, second = [int(x) for x in re.findall('(\d+)', fid.read(8).decode())]
meas_info['day'] = day
meas_info['month'] = month
meas_info['year'] = year
meas_info['hour'] = hour
meas_info['minute'] = minute
meas_info['second'] = second
meas_info['meas_date'] = datetime.datetime(year + 2000, month, day, hour, minute, second).strftime('%Y-%m-%d %H:%M:%S')
meas_info['data_offset'] = header_nbytes = int(fid.read(8).decode())
subtype = fid.read(44).strip().decode()[:5]
if len(subtype) > 0:
meas_info['subtype'] = subtype
else:
meas_info['subtype'] = os.path.splitext(self.fname)[1][1:].lower()
if meas_info['subtype'] in ('24BIT', 'bdf'):
meas_info['data_size'] = 3 # 24-bit (3 byte) integers
else:
meas_info['data_size'] = 2 # 16-bit (2 byte) integers
meas_info['n_records'] = int(fid.read(8).decode())
# record length in seconds
record_length = float(fid.read(8).decode())
if record_length == 0:
meas_info['record_length'] = record_length = 1.
warnings.warn('Headermeas_information is incorrect for record length. '
'Default record length set to 1.')
else:
meas_info['record_length'] = record_length
meas_info['nchan'] = nchan = int(fid.read(4).decode())
channels = list(range(nchan))
chan_info['ch_names'] = [fid.read(16).strip().decode() for ch in channels]
chan_info['transducers'] = [fid.read(80).strip().decode() for ch in channels]
chan_info['units'] = [fid.read(8).strip().decode() for ch in channels]
chan_info['physical_min'] = np.array([float(fid.read(8).decode()) for ch in channels])
chan_info['physical_max'] = np.array([float(fid.read(8).decode()) for ch in channels])
chan_info['digital_min'] = np.array([float(fid.read(8).decode()) for ch in channels])
chan_info['digital_max'] = np.array([float(fid.read(8).decode()) for ch in channels])
prefiltering = [fid.read(80).strip().decode() for ch in channels][:-1]
highpass = np.ravel([re.findall('HP:\s+(\w+)', filt) for filt in prefiltering])
lowpass = np.ravel([re.findall('LP:\s+(\w+)', filt) for filt in prefiltering])
high_pass_default = 0.
if highpass.size == 0:
meas_info['highpass'] = high_pass_default
elif all(highpass):
if highpass[0] == 'NaN':
meas_info['highpass'] = high_pass_default
elif highpass[0] == 'DC':
meas_info['highpass'] = 0.
else:
meas_info['highpass'] = float(highpass[0])
else:
meas_info['highpass'] = float(np.max(highpass))
warnings.warn('Channels contain different highpass filters. '
'Highest filter setting will be stored.')
if lowpass.size == 0:
meas_info['lowpass'] = None
elif all(lowpass):
if lowpass[0] == 'NaN':
meas_info['lowpass'] = None
else:
meas_info['lowpass'] = float(lowpass[0])
else:
meas_info['lowpass'] = float(np.min(lowpass))
warnings.warn('%s' % ('Channels contain different lowpass filters.'
' Lowest filter setting will be stored.'))
# number of samples per record
chan_info['n_samps'] = n_samps = np.array([int(fid.read(8).decode()) for ch in channels])
meas_info['sampling_frequency'] = int(chan_info['n_samps'][0]/meas_info['record_length'])
fid.read(32 *meas_info['nchan']).decode() # reserved
assert fid.tell() == header_nbytes
if meas_info['n_records']==-1:
# this happens if the n_records is not updated at the end of recording
tot_samps = (os.path.getsize(self.fname)-meas_info['data_offset'])/meas_info['data_size']
meas_info['n_records'] = tot_samps/sum(n_samps)
self.calibrate = (chan_info['physical_max'] - chan_info['physical_min'])/(chan_info['digital_max'] - chan_info['digital_min'])
self.offset = chan_info['physical_min'] - self.calibrate * chan_info['digital_min']
chan_info['calibrate'] = self.calibrate
chan_info['offset'] = self.offset
for ch in channels:
if self.calibrate[ch]<0:
self.calibrate[ch] = 1
self.offset[ch] = 0
self.header = {}
self.header['meas_info'] = meas_info
self.header['chan_info'] = chan_info
self.meas_info = meas_info
self.chan_info = chan_info
tal_indx = [i for i,x in enumerate(self.header['chan_info']['ch_names']) if x.endswith('Annotations')][0]
self.header['meas_info']['millisecond'] = meas_info['millisecond'] = self.read_annotation_block(0, tal_indx)[0][0][0]
return self.header
def _read_annotations_apply_offset(self, triggers):
events = []
offset = 0.
for k, ev in enumerate(triggers):
onset = float(ev[0]) + offset
duration = float(ev[2]) if ev[2] else 0
for description in ev[3].split('\x14')[1:]:
if description:
events.append([onset, duration, description, ev[4]])
elif k==0:
# "The startdate/time of a file is specified in the EDF+ header
# fields 'startdate of recording' and 'starttime of recording'.
# These fields must indicate the absolute second in which the
# start of the first data record falls. So, the first TAL in
# the first data record always starts with +0.X2020, indicating
# that the first data record starts a fraction, X, of a second
# after the startdate/time that is specified in the EDF+
# header. If X=0, then the .X may be omitted."
offset = -onset
return events if events else list()
def read_annotation_block(self, block, tal_indx):
pat = '([+-]\\d+\\.?\\d*)(\x15(\\d+\\.?\\d*))?(\x14.*?)\x14\x00'
assert(block>=0)
data = []
with open(self.fname, 'rb') as fid:
assert(fid.tell() == 0)
blocksize = np.sum(self.header['chan_info']['n_samps']) * self.header['meas_info']['data_size']
fid.seek(np.int64(self.header['meas_info']['data_offset']) + np.int64(block) * np.int64(blocksize))
read_idx = 0
for i in range(self.header['meas_info']['nchan']):
read_idx += np.int64(self.header['chan_info']['n_samps'][i]*self.header['meas_info']['data_size'])
buf = fid.read(np.int64(self.header['chan_info']['n_samps'][i]*self.header['meas_info']['data_size']))
if i==tal_indx:
raw = re.findall(pat, buf.decode('latin-1'))
if raw:
data.append(list(map(list, [x+(block,) for x in raw])))
return data
def overwrite_annotations(self, events, identity_idx, tal_indx, strings, action):
pat = '([+-]\\d+\\.?\\d*)(\x15(\\d+\\.?\\d*))?(\x14.*?)\x14\x00'
indexes = []
for ident in identity_idx:
block_chk = events[ident][-1]
replace_idx = [i for i,x in enumerate(strings) if x.lower() in events[ident][2].lower()]
for irep in replace_idx:
assert(block_chk>=0)
new_block=[]
with open(self.fname, 'rb') as fid:
assert(fid.tell() == 0)
blocksize = np.sum(self.header['chan_info']['n_samps']) * self.header['meas_info']['data_size']
fid.seek(np.int64(self.header['meas_info']['data_offset']) + np.int64(block_chk) * np.int64(blocksize))
for i in range(self.header['meas_info']['nchan']):
buf = fid.read(np.int64(self.header['chan_info']['n_samps'][i]*self.header['meas_info']['data_size']))
if i==tal_indx:
if action == 'replace':
new_block = buf.lower().replace(bytes(strings[irep],'latin-1').lower(), bytes(''.join(np.repeat('X', len(strings[irep]))),'latin-1'))
events[ident][2] = events[ident][2].lower().replace(strings[irep].lower(), ''.join(np.repeat('X', len(strings[irep]))))
assert(len(new_block)==len(buf))
elif action == 'replaceWhole':
_idx = [i for i,x in enumerate(strings.keys()) if x.lower() in events[ident][2].lower()]
replace_string = list(strings.values())[_idx[0]]
new_block = buf.lower().replace(bytes(events[ident][2],'latin-1').lower(), bytes(replace_string,'latin-1'))
events[ident][2] = replace_string
new_block = new_block+bytes('\x00'*(len(buf)-len(new_block)),'latin-1')
assert(len(new_block)==len(buf))
elif action == 'remove':
raw = re.findall(pat, buf.decode('latin-1'))[0][0] +'\x14\x14'
new_block = raw + ('\x00'*(len(buf)-len(raw)))
indexes.append(ident)
assert(len(new_block)==len(buf))
if new_block:
with open(self.fname, 'r+b') as fid:
assert(fid.tell() == 0)
blocksize = np.sum(self.header['chan_info']['n_samps']) * self.header['meas_info']['data_size']
fid.seek(np.int64(self.header['meas_info']['data_offset']) + np.int64(block_chk) * np.int64(blocksize))
read_idx = 0
for i in range(self.header['meas_info']['nchan']):
read_idx += np.int64(self.header['chan_info']['n_samps'][i]*self.header['meas_info']['data_size'])
buf = fid.read(np.int64(self.header['chan_info']['n_samps'][i]*self.header['meas_info']['data_size']))
if i==tal_indx:
back = fid.seek(-np.int64(self.header['chan_info']['n_samps'][i]*self.header['meas_info']['data_size']), 1)
assert(fid.tell()==back)
fid.write(new_block)
if indexes:
for index in sorted(indexes, reverse=True):
del events[index]
return events
def annotations(self):
"""
Constructs an annotations data tsv file about patient specific events from edf file.
:param file_info_run: File header information for specific recording.
:type file_info_run: dictionary
:param annotation_fname: Filename for the annotations tsv file.
:type annotation_fname: string
:param data_fname: Path to the raw data file for specific recording.
:type data_fname: string
:param overwrite: If duplicate data is present in the output directory overwrite it.
:type overwrite: boolean
:param verbose: Print out process steps.
:type verbose: boolean
"""
file_in = EDFReader()
self.header = file_in.open(self.fname)
tal_indx = [i for i,x in enumerate(self.header['chan_info']['ch_names']) if x.endswith('Annotations')][0]
start_time = 0
end_time = self.header['meas_info']['n_records']*self.header['meas_info']['record_length']
begsample = int(self.header['meas_info']['sampling_frequency']*float(start_time))
endsample = int(self.header['meas_info']['sampling_frequency']*float(end_time))
n_samps = max(set(list(self.header['chan_info']['n_samps'])), key = list(self.header['chan_info']['n_samps']).count)
begblock = int(np.floor((begsample) / n_samps))
endblock = int(np.floor((endsample) / n_samps))
update_cnt = int((endblock+1)/10)
annotations = []
for block in range(begblock, endblock):
data_temp = self.read_annotation_block(block, tal_indx)
if data_temp:
annotations.append(data_temp[0])
if block == update_cnt and block < (endblock-(int((endblock+1)/20))):
print('{}%'.format(int(np.ceil((update_cnt/endblock)*100))))
update_cnt += int((endblock+1)/10)
events = self._read_annotations_apply_offset([item for sublist in annotations for item in sublist])
annotation_data = pd.DataFrame({})
if events:
fulldate = datetime.datetime.strptime(self.header['meas_info']['meas_date'], '%Y-%m-%d %H:%M:%S')
for i, annot in enumerate(events):
data_temp = {'onset': annot[0],
'duration': annot[1],
'time_abs': (fulldate + datetime.timedelta(seconds=annot[0]+float(self.header['meas_info']['millisecond']))).strftime('%H:%M:%S.%f'),
'time_rel': sec2time(annot[0], 6),
'event': annot[2]}
annotation_data = pd.concat([annotation_data, pd.DataFrame([data_temp])], axis = 0)
return annotation_data
def chnames_update(self, channel_file, bids_settings, write=False):
with open(self.fname, 'r+b') as fid:
fid.seek(252)
channels = list(range(int(fid.read(4).decode())))
ch_names_orig= [fid.read(16).strip().decode() for ch in channels]
chan_idx = [i for i, x in enumerate(ch_names_orig) if not any(x.startswith(substring) for substring in list(bids_settings['natus_info']['ChannelInfo'].keys()))]
chan_label_new = np.genfromtxt(channel_file, dtype='str')
if len(chan_label_new) >1:
chan_label_new=[x[1] if isinstance(x,np.ndarray) else x.split(',')[1] for x in chan_label_new]
if len(chan_label_new)<=len(chan_idx):
replace_chan = [str(x) for x in list(range(len(chan_label_new)+1,len(chan_idx)+1))]
chan_label_new.extend([''.join(list(item)) for item in list(zip(['C']*len(replace_chan), replace_chan))])
assert len(chan_label_new)==len(chan_idx)
elif len(chan_label_new)>len(chan_idx):
add_chans = (len(chan_label_new)-len(chan_idx))+1
if not chan_idx:
chan_idx=list(range(1, add_chans))
else:
chan_idx+=list(range(chan_idx[-1]+1, (chan_idx[-1]+add_chans)))
assert len(chan_label_new)==len(chan_idx)
ch_names_new=ch_names_orig
for (index, replacement) in zip(chan_idx, chan_label_new):
ch_names_new[index] = replacement
if write:
with open(self.fname, 'r+b') as fid:
assert(fid.tell() == 0)
fid.seek(256)
for ch in ch_names_new:
fid.write(padtrim(ch,16))
return ch_names_new
def readBlock(self, block):
assert(block>=0)
data = []
with open(self.fname, 'rb') as fid:
assert(fid.tell() == 0)
blocksize = np.sum(self.header['chan_info']['n_samps']) * self.header['meas_info']['data_size']
fid.seek(self.header['meas_info']['data_offset'] + block * blocksize)
for i in range(self.header['meas_info']['nchan']):
buf = fid.read(self.header['chan_info']['n_samps'][i]*self.header['meas_info']['data_size'])
raw = np.asarray(unpack('<{}h'.format(self.header['chan_info']['n_samps'][i]), buf), dtype=np.float32)
raw *= self.calibrate[i]
raw += self.offset[i] # FIXME I am not sure about the order of calibrate and offset
data.append(raw)
return (data)
##############################################################################
# BIDS HELPER #
##############################################################################
class bidsHelper():
def __init__(self, subject_id=None, session_id=None, task_id=None, run_num=None,
kind=None, suffix=None, output_path=None, bids_settings=None, make_sub_dir=False):
self.subject_id = subject_id
self.session_id = session_id
self.task_id = task_id
self.run_num = run_num
self.kind = kind
self.suffix = suffix
self.output_path = output_path
self.bids_settings = bids_settings
if make_sub_dir:
self.make_bids_folders(make_dir=True)
def write_scans(self, file_name, file_info_run, date_offset):
# Add scans json file for each subject
self.scans_fname = self.make_bids_filename(suffix='scans.tsv', exclude_ses=True, exclude_task=True, exclude_run=True,
path_override=os.path.join(self.output_path,self.subject_id))
self.scans_json_fname = self.make_bids_filename(suffix='scans.json', exclude_ses=True, exclude_task=True, exclude_run=True,
path_override=os.path.join(self.output_path,self.subject_id))
if not os.path.exists(self.scans_json_fname):
self._scans_json()
self._scans_data(file_name, file_info_run, date_offset)
def write_channels(self, file_info_run, overwrite=False, verbose=False):
self.channels_fname = self.make_bids_filename(suffix='channels.tsv')
self._channels_data(file_info_run, overwrite, verbose)
def write_sidecar(self, file_info_run, overwrite=False, verbose=False):
self.sidecar_fname = self.make_bids_filename(suffix=self.kind + '.json')
self._sidecar_json(file_info_run, overwrite, verbose)
def write_electrodes(self, file_info_run, coordinates, overwrite=False, verbose=False):
self.electrodes_fname = self.make_bids_filename(suffix='electrodes.tsv',
exclude_task=True, exclude_run=True)
self._electrodes_data(file_info_run, coordinates, overwrite, verbose)
def write_participants(self, data=None, return_fname=False):
self.participants_fname = self.make_bids_filename(suffix='participants.tsv', exclude_sub=True, exclude_ses=True,
exclude_task=True, exclude_run=True, path_override=self.output_path)
self.participants_json_fname = self.make_bids_filename(suffix='participants.json', exclude_sub=True, exclude_ses=True,
exclude_task=True, exclude_run=True, path_override=self.output_path)
if not return_fname:
self._participants_data(data)
if not os.path.exists(self.participants_json_fname):
self._participants_json()
else:
return self.participants_fname
def write_dataset(self, return_fname=False):
self.dataset_fname = self.make_bids_filename(suffix='dataset_description.json', exclude_sub=True, exclude_ses=True,
exclude_task=True, exclude_run=True, path_override=self.output_path)
if not return_fname:
self._dataset_json()
else:
return self.dataset_fname
def make_bids_filename(self, suffix, exclude_sub=False, exclude_ses=False, exclude_task=False, exclude_run=False, path_override=None):
"""
Constructs a BIDsified filename.
:param subject_id: Subject identifier.
:type subject_id: string or None
:param session_id: Session identifier.
:type session_id: string or None
:param run_num: Run identifier.
:type run_num: string or None
:param suffix: Extension for the file.
:type suffix: string
:param prefix: Path to where the file is to be saved.
:type prefix: string
:return filename: BIDsified filename.
:type filename: string
"""
ses=self.session_id
if exclude_ses:
ses=None
elif isinstance(self.session_id, str):
if 'ses' in self.session_id:
ses=self.session_id.split('-')[1]
if exclude_task:
task=None
else:
task=self.task_id
if exclude_run:
run=None
else:
run=self.run_num
order = OrderedDict([('ses', ses if ses is not None else None),
('task', task if task is not None else None),
('run', run if run is not None else None)])
filename = []
if not exclude_sub:
if self.subject_id is not None:
filename.append(self.subject_id)
for key, val in order.items():
if val is not None:
filename.append('%s-%s' % (key, val))
if isinstance(suffix, str):
filename.append(suffix)
filename = '_'.join(filename)
if path_override is not None:
filename = os.path.join(path_override, filename)
else:
prefix=self.make_bids_folders()
filename = os.path.join(prefix, filename)
return filename
def make_bids_folders(self, path_override=None, make_dir=False, overwrite=False):
"""
Constructs a BIDsified folder structure.
:param subject_id: Subject identifier.
:type subject_id: string or None
:param session_id: Session identifier.
:type session_id: string or None
:param kind: Type of input data (e.g. anat, ieeg etc.).
:type kind: string
:param output_path: Path to where the file is to be saved.
:type output_path: string
:param make_dir: Make the directory
:type make_dir: boolean
:param overwrite: If duplicate data is present in the output directory overwrite it.
:type overwrite: boolean
:return path: BIDsified folder path.
:type path: string
"""
path = []
path.append(self.subject_id)
if isinstance(self.session_id, str):
if 'ses' not in self.session_id:
path.append('ses-%s' % self.session_id)
else:
path.append(self.session_id)
if path_override is None:
if isinstance(self.kind, str):
path.append(self.kind)
path = os.path.join(*path)
if path_override is not None:
path = os.path.join(path_override, path)
else:
path = os.path.join(self.output_path, path)
if make_dir == True:
if not os.path.exists(path):
os.makedirs(path)
elif overwrite:
os.makedirs(path)
return path
def _write_tsv(self, fname, data, float_form=None, overwrite=False, verbose=False, append = False):
"""
Writes input dataframe to a .tsv file
:param fname: Filename given to the output tsv file.
:type fname: string
:param data: Dataframe containing the information to write.
:type data: dataframe
:param overwrite: If duplicate data is present in the output directory overwrite it.
:type overwrite: boolean
:param verbose: Print out process steps.
:type verbose: boolean
:param append: Append data to file if it exists.
:type append: boolean
"""
if sys.platform == 'win32':
if os.path.exists(fname) and not overwrite:
pass
if os.path.exists(fname) and append:
with open(fname,'a') as f:
if float_form is not None:
data.to_csv(f, sep='\t', index=False, header = False, na_rep='n/a', mode='a', line_terminator="", float_format=float_form)
else:
data.to_csv(f, sep='\t', index=False, header = False, na_rep='n/a', mode='a', line_terminator="")
with open(fname) as f:
lines = f.readlines()
last = len(lines) - 1
lines[last] = lines[last].replace('\r','').replace('\n','')
with open(fname, 'w') as wr:
wr.writelines(lines)
else:
data1 = data.iloc[0:len(data)-1]
data2 = data.iloc[[len(data)-1]]
data1.to_csv(fname, sep='\t', encoding='utf-8', index = False)
if float_form is not None:
data2.to_csv(fname, sep='\t', encoding='utf-8', index=False, header = False, na_rep='n/a', mode='a', line_terminator="", float_format=float_form)
else:
data2.to_csv(fname, sep='\t', encoding='utf-8', index=False, header = False, na_rep='n/a', mode='a', line_terminator="")
else:
if os.path.exists(fname) and not overwrite:
pass
if os.path.exists(fname) and append:
with open(fname,'a') as f:
if float_form is not None:
data.to_csv(f, sep='\t', encoding='utf-8', index=False, header = False, na_rep='n/a', mode='a', line_terminator="", float_format=float_form)
else:
data.to_csv(f, sep='\t', encoding='utf-8', index=False, header = False, na_rep='n/a', mode='a', line_terminator="")
else:
data1 = data.iloc[0:len(data)-1]
data2 = data.iloc[[len(data)-1]]
data1.to_csv(fname, sep='\t', encoding='utf-8', index = False)
if float_form is not None:
data2.to_csv(fname, sep='\t', encoding='utf-8', header= False, index = False, na_rep='n/a', mode='a',line_terminator="", float_format=float_form)
else:
data2.to_csv(fname, sep='\t', encoding='utf-8', header= False, index = False, na_rep='n/a', mode='a',line_terminator="")
def _write_json(self, data, fname, overwrite=False, verbose=False):
"""
Writes input data to a .json file
:param fname: Filename given to the output json file.
:type fname: string
:param dictionary: Dictionary containing the information to write.
:type dictionary: dictionary
:param overwrite: If duplicate data is present in the output directory overwrite it.
:type overwrite: boolean
:param verbose: Print out process steps.
:type verbose: boolean
"""
json_output = json.dumps(data, indent=4)
with open(fname, 'w') as fid:
fid.write(json_output)
fid.write('\n')
if verbose is True:
print(os.linesep + "Writing '%s'..." % fname + os.linesep)
print(json_output)
def _dataset_json(self):
"""
Constructs a dataset description JSON file.
:param dataset_fname: Filename for the BIDS dataset description.
:type dataset_fname: string
"""
info_dataset_json = OrderedDict([
('Name', self.bids_settings['json_metadata']['DatasetName']),
('BIDSVersion', ''),
('License', ''),
('Authors', self.bids_settings['json_metadata']['Experimenter'][0]),
('Acknowledgements', 'say here what are your acknowledgments'),
('HowToAcknowledge', 'say here how you would like to be acknowledged'),
('Funding', ["list your funding sources"]),
('ReferencesAndLinks', ["a data paper", "a resource to be cited when using the data"]),
('DatasetDOI', '')])
self._write_json(info_dataset_json, self.dataset_fname)
def _participants_json(self):
"""
Constructs a participant description JSON file.
:param participants_fname: Filename for the BIDS participant description.
:type participants_fname: string
"""
info_participant_json = OrderedDict([
('age',
{'Description': 'age of the participants.',
'Units': 'years.'}),
('sex',
{'Description': 'sex of the participants.',
'Levels': {'m': 'male',
'f': 'female'}}),
('group',
{'Description': 'group the patient belongs to',
})
])
self._write_json(info_participant_json, self.participants_json_fname)
def _participants_data(self, file_info_sub):
"""
Constructs a participant tsv file.
:param subject_id: Subject identifier.
:type subject_id: string or None
:param file_info_sub: File header information from subjects recordings.
:type file_info_sub: dictionary
:param participants_fname: Filename for the BIDS participant description.
:type participants_fname: string
"""
if self.subject_id is None:
with open(self.participants_fname, 'w') as writeFile:
writeFile.write("\t".join(['participant_id','age','sex','group']))
writeFile.write( "\n" )
else:
# Parse edf files for age and gender (not all files will contain this info)
age = []
gender = []
for ifile in file_info_sub:
if isinstance(ifile['Age'], int):
age = ifile['Age']
if isinstance(ifile['Gender'], str):
gender = ifile['Gender']
df = pd.DataFrame(OrderedDict([
('participant_id', self.subject_id if self.subject_id is not None else ''),
('age', age if age else 'n/a'),
('sex', gender if gender else 'n/a'),
('group', 'patient')]), index= [0])
self._write_tsv(self.participants_fname, df, overwrite=False, verbose=False, append = True)
def _scans_json(self):
"""
Constructs a scans JSON file containing list of all data files stored in patient directory.
:param scans_fname: Filename for the scans JSON file.
:type scans_fname: string
"""
info_scans_json = OrderedDict([
('duration',
{'Description': 'total duration of the recording.',
'Units': 'hours.'}),
('edf_type',
{'Description': 'type of EDF file.',
'Units': 'EDF+D or EDF+C.'})
])
self._write_json(info_scans_json, self.scans_json_fname)
def _scans_data(self, file_name, file_info_run, date_offset):
"""
Constructs a scans tsv file containing list of all data files stored in patient directory.
:param file_name: Filename for the specific recording.
:type file_name: string
:param file_info_run: File header information for specific recording.
:type file_info_run: dictionary
:param scans_fname: Filename for the scans tsv file.
:type scans_fname: string
"""
date = datetime.datetime.strptime(file_info_run['Date'], '%Y-%m-%d')
if date_offset:
date = date - datetime.timedelta(5856)
acq_time = 'T'.join([date.strftime('%Y-%m-%d'), file_info_run['Time']])
df = pd.DataFrame(OrderedDict([
('filename', file_name),
('acq_time', acq_time),
('duration', file_info_run['TotalRecordTime']),
('edf_type', file_info_run['EDF_type'])
]), index=[0])
self._write_tsv(self.scans_fname, df, float_form='%.3f', overwrite=False, verbose=False, append = True)
def _electrodes_data(self, file_info_run, coordinates, overwrite, verbose):
"""
Constructs a tsv file containing electrode information for recording.
:param file_info_run: File header information for specific recording.
:type file_info_run: dictionary
:param electrodes_fname: Filename for the electrode tsv file.
:type electrodes_fname: string
:param coordinates: List of electrode coordinates (x,y,z).
:type coordinates: list or None
:param electrode_imp: Lst of electrode impedances.
:type electrode_imp: list or None
:param overwrite: If duplicate data is present in the output directory overwrite it.
:type overwrite: boolean
:param verbose: Print out process steps.
:type verbose: boolean
"""
include_chans = ['SEEG','EEG']
chan_idx = [i for i, x in enumerate(list(file_info_run['ChanInfo'].keys())) if x in include_chans]
check_cnt=0
for ichan in chan_idx:
check_cnt += file_info_run['ChanInfo'][list(file_info_run['ChanInfo'].keys())[ichan]]['ChannelCount']
if check_cnt==0:
chan_idx = [i for i, x in enumerate(list(file_info_run['ChanInfo'].keys())) if x in {'C'}]
mainDF = pd.DataFrame([])
for ichan in range(len(chan_idx)):
info_temp = file_info_run['ChanInfo'][list(file_info_run['ChanInfo'].keys())[chan_idx[ichan]]]
if 'SEEG' in info_temp['Type']:
values = []
material = []
manu = []
size = []
typ = []
for item in info_temp['ChanName']:
value_temp = 'n/a'
if [x for x in file_info_run['Groups'] if item.startswith(x)]:
value_temp = [x for x in file_info_run['Groups'] if item.startswith(x)][0]
values.append(value_temp)
material.append(self.bids_settings['natus_info']['iEEGElectrodeInfo']['Material'])
manu.append(self.bids_settings['natus_info']['iEEGElectrodeInfo']['Manufacturer'])
size.append(self.bids_settings['natus_info']['iEEGElectrodeInfo']['Diameter'])
typ.append('depth')
elif 'EEG' in info_temp['Type']:
values = []
material = []
manu = []
size = []
typ = []
for item in info_temp['ChanName']:
value_temp = 'n/a'
if [x for x in file_info_run['Groups'] if item.startswith(x)]:
value_temp = [x for x in file_info_run['Groups'] if item.startswith(x)][0]
values.append(value_temp)
material.append(self.bids_settings['natus_info']['EEGElectrodeInfo']['Material'])
manu.append(self.bids_settings['natus_info']['EEGElectrodeInfo']['Manufacturer'])
size.append(self.bids_settings['natus_info']['EEGElectrodeInfo']['Diameter'])
typ.append('scalp')
else:
values = np.repeat('n/a', len(info_temp['ChanName']))
material = np.repeat('n/a', len(info_temp['ChanName']))
manu = np.repeat('n/a', len(info_temp['ChanName']))
size = np.repeat('n/a', len(info_temp['ChanName']))
typ = np.repeat('n/a', len(info_temp['ChanName']))
df = pd.DataFrame(OrderedDict([
('name', info_temp['ChanName']),
('x', coordinates[0] if coordinates is not None else 'n/a'),
('y', coordinates[1] if coordinates is not None else 'n/a'),
('z', coordinates[2] if coordinates is not None else 'n/a'),
('size', size),
('type', typ),
('material', material),
('manufacturer', manu)]))
mainDF = pd.concat([mainDF, df], ignore_index = True, axis = 0)
df_electrodes = []
for key, val in mainDF.items():
if val is not None:
df_electrodes.append((key, val))
df_electrodes = pd.DataFrame(OrderedDict(df_electrodes))
self._write_tsv(self.electrodes_fname, df_electrodes, overwrite=False, verbose=False, append = True)
def _channels_data(self, file_info_run, overwrite, verbose):
"""
Constructs a tsv file containing channel information for recording.
:param file_info_run: File header information for specific recording.
:type file_info_run: dictionary
:param channels_fname: Filename for the channels tsv file.
:type channels_fname: string
:param overwrite: If duplicate data is present in the output directory overwrite it.
:type overwrite: boolean
:param verbose: Print out process steps.
:type verbose: boolean
"""
include_chans = ['SEEG','EEG']
chan_idx = [i for i, x in enumerate(list(file_info_run['ChanInfo'].keys())) if x in include_chans]
check_cnt=0
for ichan in chan_idx:
check_cnt += file_info_run['ChanInfo'][list(file_info_run['ChanInfo'].keys())[ichan]]['ChannelCount']
if check_cnt==0:
chan_idx = [i for i, x in enumerate(list(file_info_run['ChanInfo'].keys())) if x in {'C'}]
mainDF = pd.DataFrame([])