-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
edf.py
1454 lines (1246 loc) · 59.1 KB
/
edf.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
# -*- coding: utf-8 -*-
"""Reading tools from EDF, EDF+, BDF, and GDF."""
# Authors: Teon Brooks <teon.brooks@gmail.com>
# Martin Billinger <martin.billinger@tugraz.at>
# Nicolas Barascud <nicolas.barascud@ens.fr>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
# Joan Massich <mailsik@gmail.com>
# Clemens Brunner <clemens.brunner@gmail.com>
# Jeroen Van Der Donckt (IDlab - imec) <jeroen.vanderdonckt@ugent.be>
#
# License: BSD (3-clause)
from datetime import datetime, timezone, timedelta
import os
import re
import numpy as np
from ...utils import verbose, logger, warn
from ..utils import _blk_read_lims, _mult_cal_one
from ..base import BaseRaw
from ..meas_info import _empty_info, _unique_channel_names
from ..constants import FIFF
from ...filter import resample
from ...utils import fill_doc
from ...annotations import Annotations
@fill_doc
class RawEDF(BaseRaw):
"""Raw object from EDF, EDF+ or BDF file.
Parameters
----------
input_fname : str
Path to the EDF, EDF+ or BDF file.
eog : list or tuple
Names of channels or list of indices that should be designated EOG
channels. Values should correspond to the electrodes in the file.
Default is None.
misc : list or tuple
Names of channels or list of indices that should be designated MISC
channels. Values should correspond to the electrodes in the file.
Default is None.
stim_channel : 'auto' | str | list of str | int | list of int
Defaults to 'auto', which means that channels named 'status' or
'trigger' (case insensitive) are set to STIM. If str (or list of str),
all channels matching the name(s) are set to STIM. If int (or list of
ints), the channels corresponding to the indices are set to STIM.
.. warning:: 0.18 does not allow for stim channel synthesis from TAL
channels called 'EDF Annotations' or 'BDF Annotations'
anymore. Instead, TAL channels are parsed and extracted
annotations are stored in raw.annotations. Use
:func:`mne.events_from_annotations` to obtain events from
these annotations.
exclude : list of str
Channel names to exclude. This can help when reading data with
different sampling rates to avoid unnecessary resampling.
%(preload)s
%(verbose)s
See Also
--------
mne.io.Raw : Documentation of attributes and methods.
mne.io.read_raw_edf : Recommended way to read EDF/EDF+ files.
mne.io.read_raw_bdf : Recommended way to read BDF files.
Notes
-----
Biosemi devices trigger codes are encoded in 16-bit format, whereas system
codes (CMS in/out-of range, battery low, etc.) are coded in bits 16-23 of
the status channel (see http://www.biosemi.com/faq/trigger_signals.htm).
To retrieve correct event values (bits 1-16), one could do:
>>> events = mne.find_events(...) # doctest:+SKIP
>>> events[:, 2] &= (2**16 - 1) # doctest:+SKIP
The above operation can be carried out directly in :func:`mne.find_events`
using the ``mask`` and ``mask_type`` parameters (see
:func:`mne.find_events` for more details).
It is also possible to retrieve system codes, but no particular effort has
been made to decode these in MNE. In case it is necessary, for instance to
check the CMS bit, the following operation can be carried out:
>>> cms_bit = 20 # doctest:+SKIP
>>> cms_high = (events[:, 2] & (1 << cms_bit)) != 0 # doctest:+SKIP
It is worth noting that in some special cases, it may be necessary to shift
event values in order to retrieve correct event triggers. This depends on
the triggering device used to perform the synchronization. For instance, in
some files events need to be shifted by 8 bits:
>>> events[:, 2] >>= 8 # doctest:+SKIP
TAL channels called 'EDF Annotations' or 'BDF Annotations' are parsed and
extracted annotations are stored in raw.annotations. Use
:func:`mne.events_from_annotations` to obtain events from these
annotations.
If channels named 'status' or 'trigger' are present, they are considered as
STIM channels by default. Use func:`mne.find_events` to parse events
encoded in such analog stim channels.
"""
@verbose
def __init__(self, input_fname, eog=None, misc=None,
stim_channel='auto', exclude=(), preload=False, verbose=None):
logger.info('Extracting EDF parameters from {}...'.format(input_fname))
input_fname = os.path.abspath(input_fname)
info, edf_info, orig_units = _get_info(input_fname,
stim_channel, eog, misc,
exclude, preload)
logger.info('Creating raw.info structure...')
# Raw attributes
last_samps = [edf_info['nsamples'] - 1]
super().__init__(info, preload, filenames=[input_fname],
raw_extras=[edf_info], last_samps=last_samps,
orig_format='int', orig_units=orig_units,
verbose=verbose)
# Read annotations from file and set it
onset, duration, desc = list(), list(), list()
if len(edf_info['tal_idx']) > 0:
# Read TAL data exploiting the header info (no regexp)
idx = np.empty(0, int)
tal_data = self._read_segment_file(
np.empty((0, self.n_times)), idx, 0, 0, int(self.n_times),
np.ones((len(idx), 1)), None)
onset, duration, desc = _read_annotations_edf(tal_data[0])
self.set_annotations(Annotations(onset=onset, duration=duration,
description=desc, orig_time=None))
def _read_segment_file(self, data, idx, fi, start, stop, cals, mult):
"""Read a chunk of raw data."""
return _read_segment_file(data, idx, fi, start, stop,
self._raw_extras[fi], self._filenames[fi],
cals, mult)
@fill_doc
class RawGDF(BaseRaw):
"""Raw object from GDF file.
Parameters
----------
input_fname : str
Path to the GDF file.
eog : list or tuple
Names of channels or list of indices that should be designated EOG
channels. Values should correspond to the electrodes in the file.
Default is None.
misc : list or tuple
Names of channels or list of indices that should be designated MISC
channels. Values should correspond to the electrodes in the file.
Default is None.
stim_channel : 'auto' | str | list of str | int | list of int
Defaults to 'auto', which means that channels named 'status' or
'trigger' (case insensitive) are set to STIM. If str (or list of str),
all channels matching the name(s) are set to STIM. If int (or list of
ints), channels corresponding to the indices are set to STIM.
exclude : list of str
Channel names to exclude. This can help when reading data with
different sampling rates to avoid unnecessary resampling.
%(preload)s
%(verbose)s
See Also
--------
mne.io.Raw : Documentation of attributes and methods.
mne.io.read_raw_gdf : Recommended way to read GDF files.
Notes
-----
If channels named 'status' or 'trigger' are present, they are considered as
STIM channels by default. Use func:`mne.find_events` to parse events
encoded in such analog stim channels.
"""
@verbose
def __init__(self, input_fname, eog=None, misc=None,
stim_channel='auto', exclude=(), preload=False, verbose=None):
logger.info('Extracting EDF parameters from {}...'.format(input_fname))
input_fname = os.path.abspath(input_fname)
info, edf_info, orig_units = _get_info(input_fname,
stim_channel, eog, misc,
exclude, preload)
logger.info('Creating raw.info structure...')
# Raw attributes
last_samps = [edf_info['nsamples'] - 1]
super().__init__(info, preload, filenames=[input_fname],
raw_extras=[edf_info], last_samps=last_samps,
orig_format='int', orig_units=orig_units,
verbose=verbose)
# Read annotations from file and set it
onset, duration, desc = _get_annotations_gdf(edf_info,
self.info['sfreq'])
self.set_annotations(Annotations(onset=onset, duration=duration,
description=desc, orig_time=None))
def _read_segment_file(self, data, idx, fi, start, stop, cals, mult):
"""Read a chunk of raw data."""
return _read_segment_file(data, idx, fi, start, stop,
self._raw_extras[fi], self._filenames[fi],
cals, mult)
def _read_ch(fid, subtype, samp, dtype_byte, dtype=None):
"""Read a number of samples for a single channel."""
# BDF
if subtype == 'bdf':
ch_data = np.fromfile(fid, dtype=dtype, count=samp * dtype_byte)
ch_data = ch_data.reshape(-1, 3).astype(INT32)
ch_data = ((ch_data[:, 0]) +
(ch_data[:, 1] << 8) +
(ch_data[:, 2] << 16))
# 24th bit determines the sign
ch_data[ch_data >= (1 << 23)] -= (1 << 24)
# GDF data and EDF data
else:
ch_data = np.fromfile(fid, dtype=dtype, count=samp)
return ch_data
def _read_segment_file(data, idx, fi, start, stop, raw_extras, filenames,
cals, mult):
"""Read a chunk of raw data."""
from scipy.interpolate import interp1d
n_samps = raw_extras['n_samps']
buf_len = int(raw_extras['max_samp'])
dtype = raw_extras['dtype_np']
dtype_byte = raw_extras['dtype_byte']
data_offset = raw_extras['data_offset']
stim_channel_idxs = raw_extras['stim_channel_idxs']
orig_sel = raw_extras['sel']
tal_idx = raw_extras.get('tal_idx', np.empty(0, int))
subtype = raw_extras['subtype']
cal = raw_extras['cal']
offsets = raw_extras['offsets']
gains = raw_extras['units']
read_sel = np.concatenate([orig_sel[idx], tal_idx])
tal_data = []
# only try to read the stim channel if it's not None and it's
# actually one of the requested channels
idx_arr = np.arange(idx.start, idx.stop) if isinstance(idx, slice) else idx
# We could read this one EDF block at a time, which would be this:
ch_offsets = np.cumsum(np.concatenate([[0], n_samps]), dtype=np.int64)
block_start_idx, r_lims, d_lims = _blk_read_lims(start, stop, buf_len)
# But to speed it up, we really need to read multiple blocks at once,
# Otherwise we can end up with e.g. 18,181 chunks for a 20 MB file!
# Let's do ~10 MB chunks:
n_per = max(10 * 1024 * 1024 // (ch_offsets[-1] * dtype_byte), 1)
with open(filenames, 'rb', buffering=0) as fid:
# Extract data
start_offset = (data_offset +
block_start_idx * ch_offsets[-1] * dtype_byte)
for ai in range(0, len(r_lims), n_per):
block_offset = ai * ch_offsets[-1] * dtype_byte
n_read = min(len(r_lims) - ai, n_per)
fid.seek(start_offset + block_offset, 0)
# Read and reshape to (n_chunks_read, ch0_ch1_ch2_ch3...)
many_chunk = _read_ch(fid, subtype, ch_offsets[-1] * n_read,
dtype_byte, dtype).reshape(n_read, -1)
r_sidx = r_lims[ai][0]
r_eidx = (buf_len * (n_read - 1) + r_lims[ai + n_read - 1][1])
d_sidx = d_lims[ai][0]
d_eidx = d_lims[ai + n_read - 1][1]
one = np.zeros((len(orig_sel), d_eidx - d_sidx), dtype=data.dtype)
for ii, ci in enumerate(read_sel):
# This now has size (n_chunks_read, n_samp[ci])
ch_data = many_chunk[:, ch_offsets[ci]:ch_offsets[ci + 1]]
if ci in tal_idx:
tal_data.append(ch_data)
continue
orig_idx = idx_arr[ii]
ch_data = ch_data * cal[orig_idx]
ch_data += offsets[orig_idx]
ch_data *= gains[orig_idx]
assert ci == orig_sel[orig_idx]
if n_samps[ci] != buf_len:
if orig_idx in stim_channel_idxs:
# Stim channel will be interpolated
old = np.linspace(0, 1, n_samps[ci] + 1, True)
new = np.linspace(0, 1, buf_len, False)
ch_data = np.append(
ch_data, np.zeros((len(ch_data), 1)), -1)
ch_data = interp1d(old, ch_data,
kind='zero', axis=-1)(new)
else:
# XXX resampling each chunk isn't great,
# it forces edge artifacts to appear at
# each buffer boundary :(
# it can also be very slow...
ch_data = resample(
ch_data.astype(np.float64), buf_len, n_samps[ci],
npad=0, axis=-1)
elif orig_idx in stim_channel_idxs:
ch_data = np.bitwise_and(ch_data.astype(int), 2**17 - 1)
one[orig_idx] = ch_data.ravel()[r_sidx:r_eidx]
_mult_cal_one(data[:, d_sidx:d_eidx], one, idx, cals, mult)
if len(tal_data) > 1:
tal_data = np.concatenate([tal.ravel() for tal in tal_data])
tal_data = tal_data[np.newaxis, :]
return tal_data
def _read_header(fname, exclude):
"""Unify edf, bdf and gdf _read_header call.
Parameters
----------
fname : str
Path to the EDF+, BDF, or GDF file.
exclude : list of str
Channel names to exclude. This can help when reading data with
different sampling rates to avoid unnecessary resampling.
Returns
-------
(edf_info, orig_units) : tuple
"""
ext = os.path.splitext(fname)[1][1:].lower()
logger.info('%s file detected' % ext.upper())
if ext in ('bdf', 'edf'):
return _read_edf_header(fname, exclude)
elif ext == 'gdf':
return _read_gdf_header(fname, exclude), None
else:
raise NotImplementedError(
f'Only GDF, EDF, and BDF files are supported, got {ext}.')
def _get_info(fname, stim_channel, eog, misc, exclude, preload):
"""Extract all the information from the EDF+, BDF or GDF file."""
eog = eog if eog is not None else []
misc = misc if misc is not None else []
edf_info, orig_units = _read_header(fname, exclude)
# XXX: `tal_ch_names` to pass to `_check_stim_channel` should be computed
# from `edf_info['ch_names']` and `edf_info['tal_idx']` but 'tal_idx'
# contains stim channels that are not TAL.
stim_channel_idxs, _ = _check_stim_channel(
stim_channel, edf_info['ch_names'])
sel = edf_info['sel'] # selection of channels not excluded
ch_names = edf_info['ch_names'] # of length len(sel)
n_samps = edf_info['n_samps'][sel]
nchan = edf_info['nchan']
physical_ranges = edf_info['physical_max'] - edf_info['physical_min']
cals = edf_info['digital_max'] - edf_info['digital_min']
bad_idx = np.where((~np.isfinite(cals)) | (cals == 0))[0]
if len(bad_idx) > 0:
warn('Scaling factor is not defined in following channels:\n' +
', '.join(ch_names[i] for i in bad_idx))
cals[bad_idx] = 1
bad_idx = np.where(physical_ranges == 0)[0]
if len(bad_idx) > 0:
warn('Physical range is not defined in following channels:\n' +
', '.join(ch_names[i] for i in bad_idx))
physical_ranges[bad_idx] = 1
# Creates a list of dicts of eeg channels for raw.info
logger.info('Setting channel info structure...')
chs = list()
pick_mask = np.ones(len(ch_names))
for idx, ch_name in enumerate(ch_names):
chan_info = {}
chan_info['cal'] = 1.
chan_info['logno'] = idx + 1
chan_info['scanno'] = idx + 1
chan_info['range'] = 1.
chan_info['unit_mul'] = FIFF.FIFF_UNITM_NONE
chan_info['ch_name'] = ch_name
chan_info['unit'] = FIFF.FIFF_UNIT_V
chan_info['coord_frame'] = FIFF.FIFFV_COORD_HEAD
chan_info['coil_type'] = FIFF.FIFFV_COIL_EEG
chan_info['kind'] = FIFF.FIFFV_EEG_CH
chan_info['loc'] = np.zeros(12)
if ch_name in eog or idx in eog or idx - nchan in eog:
chan_info['coil_type'] = FIFF.FIFFV_COIL_NONE
chan_info['kind'] = FIFF.FIFFV_EOG_CH
pick_mask[idx] = False
elif ch_name in misc or idx in misc or idx - nchan in misc:
chan_info['coil_type'] = FIFF.FIFFV_COIL_NONE
chan_info['kind'] = FIFF.FIFFV_MISC_CH
pick_mask[idx] = False
elif idx in stim_channel_idxs:
chan_info['coil_type'] = FIFF.FIFFV_COIL_NONE
chan_info['unit'] = FIFF.FIFF_UNIT_NONE
chan_info['kind'] = FIFF.FIFFV_STIM_CH
pick_mask[idx] = False
chan_info['ch_name'] = ch_name
ch_names[idx] = chan_info['ch_name']
edf_info['units'][idx] = 1
chs.append(chan_info)
edf_info['stim_channel_idxs'] = stim_channel_idxs
if any(pick_mask):
picks = [item for item, mask in zip(range(nchan), pick_mask) if mask]
edf_info['max_samp'] = max_samp = n_samps[picks].max()
else:
edf_info['max_samp'] = max_samp = n_samps.max()
# Info structure
# -------------------------------------------------------------------------
not_stim_ch = [x for x in range(n_samps.shape[0])
if x not in stim_channel_idxs]
sfreq = np.take(n_samps, not_stim_ch).max() * \
edf_info['record_length'][1] / edf_info['record_length'][0]
info = _empty_info(sfreq)
info['meas_date'] = edf_info['meas_date']
info['chs'] = chs
info['ch_names'] = ch_names
# Filter settings
highpass = edf_info['highpass']
lowpass = edf_info['lowpass']
if highpass.size == 0:
pass
elif all(highpass):
if highpass[0] == 'NaN':
pass # Placeholder for future use. Highpass set in _empty_info.
elif highpass[0] == 'DC':
info['highpass'] = 0.
else:
hp = highpass[0]
try:
hp = float(hp)
except Exception:
hp = 0.
info['highpass'] = hp
else:
info['highpass'] = float(np.max(highpass))
warn('Channels contain different highpass filters. Highest filter '
'setting will be stored.')
if np.isnan(info['highpass']):
info['highpass'] = 0.
if lowpass.size == 0:
pass # Placeholder for future use. Lowpass set in _empty_info.
elif all(lowpass):
if lowpass[0] in ('NaN', '0', '0.0'):
pass # Placeholder for future use. Lowpass set in _empty_info.
else:
info['lowpass'] = float(lowpass[0])
else:
info['lowpass'] = float(np.min(lowpass))
warn('Channels contain different lowpass filters. Lowest filter '
'setting will be stored.')
if np.isnan(info['lowpass']):
info['lowpass'] = info['sfreq'] / 2.
if info['highpass'] > info['lowpass']:
warn(f'Highpass cutoff frequency {info["highpass"]} is greater than '
f'lowpass cutoff frequency {info["lowpass"]}, '
'setting values to 0 and Nyquist.')
info['highpass'] = 0.
info['lowpass'] = info['sfreq'] / 2.
# Some keys to be consistent with FIF measurement info
info['description'] = None
edf_info['nsamples'] = int(edf_info['n_records'] * max_samp)
info._update_redundant()
# Later used for reading
edf_info['cal'] = physical_ranges / cals
# physical dimension in µV
edf_info['offsets'] = (
edf_info['physical_min'] - edf_info['digital_min'] * edf_info['cal'])
del edf_info['physical_min']
del edf_info['digital_min']
if edf_info['subtype'] == 'bdf':
edf_info['cal'][stim_channel_idxs] = 1
edf_info['offsets'][stim_channel_idxs] = 0
edf_info['units'][stim_channel_idxs] = 1
return info, edf_info, orig_units
def _parse_prefilter_string(prefiltering):
"""Parse prefilter string from EDF+ and BDF headers."""
highpass = np.array(
[v for hp in [re.findall(r'HP:\s*([0-9]+[.]*[0-9]*)', filt)
for filt in prefiltering] for v in hp]
)
lowpass = np.array(
[v for hp in [re.findall(r'LP:\s*([0-9]+[.]*[0-9]*)', filt)
for filt in prefiltering] for v in hp]
)
return highpass, lowpass
def _edf_str(x):
return x.decode('latin-1').split('\x00')[0]
def _read_edf_header(fname, exclude):
"""Read header information from EDF+ or BDF file."""
edf_info = {'events': []}
with open(fname, 'rb') as fid:
fid.read(8) # version (unused here)
# patient ID
patient = {}
id_info = fid.read(80).decode('latin-1').rstrip()
id_info = id_info.split(' ')
if len(id_info):
patient['id'] = id_info[0]
if len(id_info) == 4:
try:
birthdate = datetime.strptime(id_info[2], "%d-%b-%Y")
except ValueError:
birthdate = "X"
patient['sex'] = id_info[1]
patient['birthday'] = birthdate
patient['name'] = id_info[3]
# Recording ID
meas_id = {}
rec_info = fid.read(80).decode('latin-1').rstrip().split(' ')
valid_startdate = False
if len(rec_info) == 5:
try:
startdate = datetime.strptime(rec_info[1], "%d-%b-%Y")
except ValueError:
startdate = "X"
else:
valid_startdate = True
meas_id['startdate'] = startdate
meas_id['study_id'] = rec_info[2]
meas_id['technician'] = rec_info[3]
meas_id['equipment'] = rec_info[4]
# If startdate available in recording info, use it instead of the
# file's meas_date since it contains all 4 digits of the year
if valid_startdate:
day = meas_id['startdate'].day
month = meas_id['startdate'].month
year = meas_id['startdate'].year
fid.read(8) # skip file's meas_date
else:
meas_date = fid.read(8).decode('latin-1')
day, month, year = [int(x) for x in meas_date.split('.')]
year = year + 2000 if year < 85 else year + 1900
meas_time = fid.read(8).decode('latin-1')
hour, minute, sec = [int(x) for x in meas_time.split('.')]
try:
meas_date = datetime(year, month, day, hour, minute, sec,
tzinfo=timezone.utc)
except ValueError:
warn(f'Invalid date encountered ({year:04d}-{month:02d}-'
f'{day:02d} {hour:02d}:{minute:02d}:{sec:02d}).')
meas_date = None
header_nbytes = int(_edf_str(fid.read(8)))
# The following 44 bytes sometimes identify the file type, but this is
# not guaranteed. Therefore, we skip this field and use the file
# extension to determine the subtype (EDF or BDF, which differ in the
# number of bytes they use for the data records; EDF uses 2 bytes
# whereas BDF uses 3 bytes).
fid.read(44)
subtype = os.path.splitext(fname)[1][1:].lower()
n_records = int(_edf_str(fid.read(8)))
record_length = float(_edf_str(fid.read(8)))
record_length = np.array([record_length, 1.]) # in seconds
if record_length[0] == 0:
record_length = record_length[0] = 1.
warn('Header information is incorrect for record length. Default '
'record length set to 1.')
nchan = int(_edf_str(fid.read(4)))
channels = list(range(nchan))
ch_names = [fid.read(16).strip().decode('latin-1') for ch in channels]
exclude = _find_exclude_idx(ch_names, exclude)
tal_idx = _find_tal_idx(ch_names)
exclude = np.concatenate([exclude, tal_idx])
sel = np.setdiff1d(np.arange(len(ch_names)), exclude)
for ch in channels:
fid.read(80) # transducer
units = [fid.read(8).strip().decode('latin-1') for ch in channels]
edf_info['units'] = list()
for i, unit in enumerate(units):
if i in exclude:
continue
if unit == 'uV':
edf_info['units'].append(1e-6)
elif unit == 'mV':
edf_info['units'].append(1e-3)
else:
edf_info['units'].append(1)
edf_info['units'] = np.array(edf_info['units'], float)
ch_names = [ch_names[idx] for idx in sel]
units = [units[idx] for idx in sel]
# make sure channel names are unique
ch_names = _unique_channel_names(ch_names)
orig_units = dict(zip(ch_names, units))
physical_min = np.array(
[float(_edf_str(fid.read(8))) for ch in channels])[sel]
physical_max = np.array(
[float(_edf_str(fid.read(8))) for ch in channels])[sel]
digital_min = np.array(
[float(_edf_str(fid.read(8))) for ch in channels])[sel]
digital_max = np.array(
[float(_edf_str(fid.read(8))) for ch in channels])[sel]
prefiltering = [_edf_str(fid.read(80)).strip() for ch in channels][:-1]
highpass, lowpass = _parse_prefilter_string(prefiltering)
# number of samples per record
n_samps = np.array([int(_edf_str(fid.read(8))) for ch in channels])
# Populate edf_info
edf_info.update(
ch_names=ch_names, data_offset=header_nbytes,
digital_max=digital_max, digital_min=digital_min,
highpass=highpass, sel=sel, lowpass=lowpass, meas_date=meas_date,
n_records=n_records, n_samps=n_samps, nchan=nchan,
subject_info=patient, physical_max=physical_max,
physical_min=physical_min, record_length=record_length,
subtype=subtype, tal_idx=tal_idx)
fid.read(32 * nchan).decode() # reserved
assert fid.tell() == header_nbytes
fid.seek(0, 2)
n_bytes = fid.tell()
n_data_bytes = n_bytes - header_nbytes
total_samps = (n_data_bytes // 3 if subtype == 'bdf'
else n_data_bytes // 2)
read_records = total_samps // np.sum(n_samps)
if n_records != read_records:
warn('Number of records from the header does not match the file '
'size (perhaps the recording was not stopped before exiting).'
' Inferring from the file size.')
edf_info['n_records'] = read_records
del n_records
if subtype == 'bdf':
edf_info['dtype_byte'] = 3 # 24-bit (3 byte) integers
edf_info['dtype_np'] = UINT8
else:
edf_info['dtype_byte'] = 2 # 16-bit (2 byte) integers
edf_info['dtype_np'] = INT16
return edf_info, orig_units
INT8 = '<i1'
UINT8 = '<u1'
INT16 = '<i2'
UINT16 = '<u2'
INT32 = '<i4'
UINT32 = '<u4'
INT64 = '<i8'
UINT64 = '<u8'
FLOAT32 = '<f4'
FLOAT64 = '<f8'
GDFTYPE_NP = (None, INT8, UINT8, INT16, UINT16, INT32, UINT32,
INT64, UINT64, None, None, None, None,
None, None, None, FLOAT32, FLOAT64)
GDFTYPE_BYTE = tuple(np.dtype(x).itemsize if x is not None else 0
for x in GDFTYPE_NP)
def _check_dtype_byte(types):
assert sum(GDFTYPE_BYTE) == 42
dtype_byte = [GDFTYPE_BYTE[t] for t in types]
dtype_np = [GDFTYPE_NP[t] for t in types]
if len(np.unique(dtype_byte)) > 1:
# We will not read it properly, so this should be an error
raise RuntimeError("Reading multiple data types not supported")
return dtype_np[0], dtype_byte[0]
def _read_gdf_header(fname, exclude):
"""Read GDF 1.x and GDF 2.x header info."""
edf_info = dict()
events = None
with open(fname, 'rb') as fid:
version = fid.read(8).decode()
edf_info['type'] = edf_info['subtype'] = version[:3]
edf_info['number'] = float(version[4:])
meas_date = None
# GDF 1.x
# ---------------------------------------------------------------------
if edf_info['number'] < 1.9:
# patient ID
pid = fid.read(80).decode('latin-1')
pid = pid.split(' ', 2)
patient = {}
if len(pid) >= 2:
patient['id'] = pid[0]
patient['name'] = pid[1]
# Recording ID
meas_id = {}
meas_id['recording_id'] = _edf_str(fid.read(80)).strip()
# date
tm = _edf_str(fid.read(16)).strip()
try:
if tm[14:16] == ' ':
tm = tm[:14] + '00' + tm[16:]
meas_date = datetime(
int(tm[0:4]), int(tm[4:6]),
int(tm[6:8]), int(tm[8:10]),
int(tm[10:12]), int(tm[12:14]),
int(tm[14:16]) * pow(10, 4),
tzinfo=timezone.utc)
except Exception:
pass
header_nbytes = np.fromfile(fid, INT64, 1)[0]
meas_id['equipment'] = np.fromfile(fid, UINT8, 8)[0]
meas_id['hospital'] = np.fromfile(fid, UINT8, 8)[0]
meas_id['technician'] = np.fromfile(fid, UINT8, 8)[0]
fid.seek(20, 1) # 20bytes reserved
n_records = np.fromfile(fid, INT64, 1)[0]
# record length in seconds
record_length = np.fromfile(fid, UINT32, 2)
if record_length[0] == 0:
record_length[0] = 1.
warn('Header information is incorrect for record length. '
'Default record length set to 1.')
nchan = np.fromfile(fid, UINT32, 1)[0]
channels = list(range(nchan))
ch_names = [_edf_str(fid.read(16)).strip() for ch in channels]
exclude = _find_exclude_idx(ch_names, exclude)
sel = np.setdiff1d(np.arange(len(ch_names)), exclude)
fid.seek(80 * len(channels), 1) # transducer
units = [_edf_str(fid.read(8)).strip() for ch in channels]
edf_info['units'] = list()
for i, unit in enumerate(units):
if i in exclude:
continue
if unit[:2] == 'uV':
edf_info['units'].append(1e-6)
else:
edf_info['units'].append(1)
edf_info['units'] = np.array(edf_info['units'], float)
ch_names = [ch_names[idx] for idx in sel]
physical_min = np.fromfile(fid, FLOAT64, len(channels))
physical_max = np.fromfile(fid, FLOAT64, len(channels))
digital_min = np.fromfile(fid, INT64, len(channels))
digital_max = np.fromfile(fid, INT64, len(channels))
prefiltering = [_edf_str(fid.read(80)) for ch in channels][:-1]
highpass, lowpass = _parse_prefilter_string(prefiltering)
# n samples per record
n_samps = np.fromfile(fid, INT32, len(channels))
# channel data type
dtype = np.fromfile(fid, INT32, len(channels))
# total number of bytes for data
bytes_tot = np.sum([GDFTYPE_BYTE[t] * n_samps[i]
for i, t in enumerate(dtype)])
# Populate edf_info
dtype_np, dtype_byte = _check_dtype_byte(dtype)
edf_info.update(
bytes_tot=bytes_tot, ch_names=ch_names,
data_offset=header_nbytes, digital_min=digital_min,
digital_max=digital_max,
dtype_byte=dtype_byte, dtype_np=dtype_np, exclude=exclude,
highpass=highpass, sel=sel, lowpass=lowpass,
meas_date=meas_date,
meas_id=meas_id, n_records=n_records, n_samps=n_samps,
nchan=nchan, subject_info=patient, physical_max=physical_max,
physical_min=physical_min, record_length=record_length)
fid.seek(32 * edf_info['nchan'], 1) # reserved
assert fid.tell() == header_nbytes
# Event table
# -----------------------------------------------------------------
etp = header_nbytes + n_records * edf_info['bytes_tot']
# skip data to go to event table
fid.seek(etp)
etmode = np.fromfile(fid, UINT8, 1)[0]
if etmode in (1, 3):
sr = np.fromfile(fid, UINT8, 3)
event_sr = sr[0]
for i in range(1, len(sr)):
event_sr = event_sr + sr[i] * 2 ** (i * 8)
n_events = np.fromfile(fid, UINT32, 1)[0]
pos = np.fromfile(fid, UINT32, n_events) - 1 # 1-based inds
typ = np.fromfile(fid, UINT16, n_events)
if etmode == 3:
chn = np.fromfile(fid, UINT16, n_events)
dur = np.fromfile(fid, UINT32, n_events)
else:
chn = np.zeros(n_events, dtype=np.int32)
dur = np.ones(n_events, dtype=UINT32)
np.maximum(dur, 1, out=dur)
events = [n_events, pos, typ, chn, dur]
# GDF 2.x
# ---------------------------------------------------------------------
else:
# FIXED HEADER
handedness = ('Unknown', 'Right', 'Left', 'Equal')
gender = ('Unknown', 'Male', 'Female')
scale = ('Unknown', 'No', 'Yes', 'Corrected')
# date
pid = fid.read(66).decode()
pid = pid.split(' ', 2)
patient = {}
if len(pid) >= 2:
patient['id'] = pid[0]
patient['name'] = pid[1]
fid.seek(10, 1) # 10bytes reserved
# Smoking / Alcohol abuse / drug abuse / medication
sadm = np.fromfile(fid, UINT8, 1)[0]
patient['smoking'] = scale[sadm % 4]
patient['alcohol_abuse'] = scale[(sadm >> 2) % 4]
patient['drug_abuse'] = scale[(sadm >> 4) % 4]
patient['medication'] = scale[(sadm >> 6) % 4]
patient['weight'] = np.fromfile(fid, UINT8, 1)[0]
if patient['weight'] == 0 or patient['weight'] == 255:
patient['weight'] = None
patient['height'] = np.fromfile(fid, UINT8, 1)[0]
if patient['height'] == 0 or patient['height'] == 255:
patient['height'] = None
# Gender / Handedness / Visual Impairment
ghi = np.fromfile(fid, UINT8, 1)[0]
patient['sex'] = gender[ghi % 4]
patient['handedness'] = handedness[(ghi >> 2) % 4]
patient['visual'] = scale[(ghi >> 4) % 4]
# Recording identification
meas_id = {}
meas_id['recording_id'] = _edf_str(fid.read(64)).strip()
vhsv = np.fromfile(fid, UINT8, 4)
loc = {}
if vhsv[3] == 0:
loc['vertpre'] = 10 * int(vhsv[0] >> 4) + int(vhsv[0] % 16)
loc['horzpre'] = 10 * int(vhsv[1] >> 4) + int(vhsv[1] % 16)
loc['size'] = 10 * int(vhsv[2] >> 4) + int(vhsv[2] % 16)
else:
loc['vertpre'] = 29
loc['horzpre'] = 29
loc['size'] = 29
loc['version'] = 0
loc['latitude'] = \
float(np.fromfile(fid, UINT32, 1)[0]) / 3600000
loc['longitude'] = \
float(np.fromfile(fid, UINT32, 1)[0]) / 3600000
loc['altitude'] = float(np.fromfile(fid, INT32, 1)[0]) / 100
meas_id['loc'] = loc
meas_date = np.fromfile(fid, UINT64, 1)[0]
if meas_date != 0:
meas_date = (datetime(1, 1, 1, tzinfo=timezone.utc) +
timedelta(meas_date * pow(2, -32) - 367))
else:
meas_date = None
birthday = np.fromfile(fid, UINT64, 1).tolist()[0]
if birthday == 0:
birthday = datetime(1, 1, 1, tzinfo=timezone.utc)
else:
birthday = (datetime(1, 1, 1, tzinfo=timezone.utc) +
timedelta(birthday * pow(2, -32) - 367))
patient['birthday'] = birthday
if patient['birthday'] != datetime(1, 1, 1, 0, 0,
tzinfo=timezone.utc):
today = datetime.now(tz=timezone.utc)
patient['age'] = today.year - patient['birthday'].year
today = today.replace(year=patient['birthday'].year)
if today < patient['birthday']:
patient['age'] -= 1
else:
patient['age'] = None
header_nbytes = np.fromfile(fid, UINT16, 1)[0] * 256
fid.seek(6, 1) # 6 bytes reserved
meas_id['equipment'] = np.fromfile(fid, UINT8, 8)
meas_id['ip'] = np.fromfile(fid, UINT8, 6)
patient['headsize'] = np.fromfile(fid, UINT16, 3)
patient['headsize'] = np.asarray(patient['headsize'], np.float32)
patient['headsize'] = np.ma.masked_array(
patient['headsize'],
np.equal(patient['headsize'], 0), None).filled()
ref = np.fromfile(fid, FLOAT32, 3)
gnd = np.fromfile(fid, FLOAT32, 3)
n_records = np.fromfile(fid, INT64, 1)[0]
# record length in seconds
record_length = np.fromfile(fid, UINT32, 2)
if record_length[0] == 0:
record_length[0] = 1.
warn('Header information is incorrect for record length. '
'Default record length set to 1.')
nchan = np.fromfile(fid, UINT16, 1)[0]
fid.seek(2, 1) # 2bytes reserved
# Channels (variable header)
channels = list(range(nchan))
ch_names = [_edf_str(fid.read(16)).strip() for ch in channels]
exclude = _find_exclude_idx(ch_names, exclude)
sel = np.setdiff1d(np.arange(len(ch_names)), exclude)
fid.seek(80 * len(channels), 1) # reserved space
fid.seek(6 * len(channels), 1) # phys_dim, obsolete
"""The Physical Dimensions are encoded as int16, according to:
- Units codes :
https://sourceforge.net/p/biosig/svn/HEAD/tree/trunk/biosig/doc/units.csv
- Decimal factors codes:
https://sourceforge.net/p/biosig/svn/HEAD/tree/trunk/biosig/doc/DecimalFactors.txt
""" # noqa
units = np.fromfile(fid, UINT16, len(channels)).tolist()
unitcodes = np.array(units[:])
edf_info['units'] = list()
for i, unit in enumerate(units):
if i in exclude:
continue
if unit == 4275: # microvolts
edf_info['units'].append(1e-6)
elif unit == 4274: # millivolts
edf_info['units'].append(1e-3)
elif unit == 512: # dimensionless
edf_info['units'].append(1)
elif unit == 0:
edf_info['units'].append(1) # unrecognized
else:
warn('Unsupported physical dimension for channel %d '
'(assuming dimensionless). Please contact the '
'MNE-Python developers for support.' % i)
edf_info['units'].append(1)
edf_info['units'] = np.array(edf_info['units'], float)
ch_names = [ch_names[idx] for idx in sel]
physical_min = np.fromfile(fid, FLOAT64, len(channels))
physical_max = np.fromfile(fid, FLOAT64, len(channels))
digital_min = np.fromfile(fid, FLOAT64, len(channels))
digital_max = np.fromfile(fid, FLOAT64, len(channels))
fid.seek(68 * len(channels), 1) # obsolete
lowpass = np.fromfile(fid, FLOAT32, len(channels))
highpass = np.fromfile(fid, FLOAT32, len(channels))
notch = np.fromfile(fid, FLOAT32, len(channels))
# number of samples per record
n_samps = np.fromfile(fid, INT32, len(channels))
# data type
dtype = np.fromfile(fid, INT32, len(channels))
channel = {}
channel['xyz'] = [np.fromfile(fid, FLOAT32, 3)[0]
for ch in channels]
if edf_info['number'] < 2.19:
impedance = np.fromfile(fid, UINT8,