-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathedf.py
More file actions
2354 lines (2067 loc) · 87 KB
/
edf.py
File metadata and controls
2354 lines (2067 loc) · 87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Reading tools from EDF, EDF+, BDF, and GDF."""
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import os
import re
from datetime import date, datetime, timedelta, timezone
from enum import Enum
from pathlib import Path
import numpy as np
from scipy.interpolate import interp1d
from ..._edf.open import _gdf_edf_get_fid
from ..._fiff.constants import FIFF
from ..._fiff.meas_info import _empty_info, _unique_channel_names
from ..._fiff.utils import _blk_read_lims, _mult_cal_one
from ...annotations import Annotations
from ...filter import resample
from ...fixes import read_from_file_or_buffer
from ...utils import (
_check_fname,
_file_like,
_validate_type,
fill_doc,
logger,
verbose,
warn,
)
from ..base import BaseRaw, _get_scaling
class FileType(Enum):
"""Enumeration to differentiate files when the extension is not known."""
GDF = 1
EDF = 2
BDF = 3
# common channel type names mapped to internal ch types
CH_TYPE_MAPPING = {
"EEG": FIFF.FIFFV_EEG_CH,
"SEEG": FIFF.FIFFV_SEEG_CH,
"ECOG": FIFF.FIFFV_ECOG_CH,
"DBS": FIFF.FIFFV_DBS_CH,
"EOG": FIFF.FIFFV_EOG_CH,
"ECG": FIFF.FIFFV_ECG_CH,
"EMG": FIFF.FIFFV_EMG_CH,
"BIO": FIFF.FIFFV_BIO_CH,
"RESP": FIFF.FIFFV_RESP_CH,
"TEMP": FIFF.FIFFV_TEMPERATURE_CH,
"MISC": FIFF.FIFFV_MISC_CH,
"SAO2": FIFF.FIFFV_BIO_CH,
"STIM": FIFF.FIFFV_STIM_CH,
}
@fill_doc
class RawEDF(BaseRaw):
"""Raw object from EDF, EDF+ file.
Parameters
----------
input_fname : path-like | file-like
Path to the EDF, EDF+ file. If a file-like object is provided,
preloading must be used.
.. versionchanged:: 1.10
Added support for file-like objects
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.
exclude : list of str
Channel names to exclude. This can help when reading data with
different sampling rates to avoid unnecessary resampling.
infer_types : bool
If True, try to infer channel types from channel labels. If a channel
label starts with a known type (such as 'EEG') followed by a space and
a name (such as 'Fp1'), the channel type will be set accordingly, and
the channel will be renamed to the original label without the prefix.
For unknown prefixes, the type will be 'EEG' and the name will not be
modified. If False, do not infer types and assume all channels are of
type 'EEG'.
.. versionadded:: 0.24.1
include : list of str | str
Channel names to be included. A str is interpreted as a regular
expression. 'exclude' must be empty if include is assigned.
.. versionadded:: 1.1
%(preload)s
%(units_edf_bdf_io)s
%(encoding_edf)s
%(exclude_after_unique)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.
Notes
-----
%(edf_resamp_note)s
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' 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=(),
infer_types=False,
preload=False,
include=None,
units=None,
encoding="utf8",
exclude_after_unique=False,
*,
verbose=None,
):
if not _file_like(input_fname):
logger.info(f"Extracting EDF parameters from {input_fname}...")
input_fname = os.path.abspath(input_fname)
info, edf_info, orig_units = _get_info(
input_fname,
stim_channel,
eog,
misc,
exclude,
infer_types,
FileType.EDF,
include,
exclude_after_unique,
)
logger.info("Creating raw.info structure...")
edf_info["blob"] = input_fname if _file_like(input_fname) else None
_validate_type(units, (str, None, dict), "units")
if units is None:
units = dict()
elif isinstance(units, str):
units = {ch_name: units for ch_name in info["ch_names"]}
for k, (this_ch, this_unit) in enumerate(orig_units.items()):
if this_ch not in units:
continue
if this_unit not in ("", units[this_ch]):
raise ValueError(
f"Unit for channel {this_ch} is present in the file as "
f"{repr(this_unit)}, cannot overwrite it with the units "
f"argument {repr(units[this_ch])}."
)
if this_unit == "":
orig_units[this_ch] = units[this_ch]
ch_type = edf_info["ch_types"][k]
scaling = _get_scaling(ch_type.lower(), orig_units[this_ch])
edf_info["units"][k] /= scaling
# Raw attributes
last_samps = [edf_info["nsamples"] - 1]
super().__init__(
info,
preload,
filenames=[_path_from_fname(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
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,
)
annotations = _read_annotations_edf(
tal_data[0],
ch_names=info["ch_names"],
encoding=encoding,
)
self.set_annotations(annotations, on_missing="warn")
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]
if self._raw_extras[fi]["blob"] is None
else self._raw_extras[fi]["blob"],
cals,
mult,
)
def _path_from_fname(fname) -> Path | None:
if isinstance(fname, str | Path):
return Path(fname)
# Try to get a filename from the file-like object
try:
return Path(fname.name)
except Exception:
return None
@fill_doc
class RawBDF(BaseRaw):
"""Raw object from BDF file.
Parameters
----------
input_fname : path-like | file-like
Path to the BDF file. If a file-like object is provided,
preloading must be used.
.. versionchanged:: 1.10
Added support for file-like objects
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.
exclude : list of str
Channel names to exclude. This can help when reading data with
different sampling rates to avoid unnecessary resampling.
infer_types : bool
If True, try to infer channel types from channel labels. If a channel
label starts with a known type (such as 'EEG') followed by a space and
a name (such as 'Fp1'), the channel type will be set accordingly, and
the channel will be renamed to the original label without the prefix.
For unknown prefixes, the type will be 'EEG' and the name will not be
modified. If False, do not infer types and assume all channels are of
type 'EEG'.
.. versionadded:: 0.24.1
include : list of str | str
Channel names to be included. A str is interpreted as a regular
expression. 'exclude' must be empty if include is assigned.
.. versionadded:: 1.1
%(preload)s
%(units_edf_bdf_io)s
%(encoding_edf)s
%(exclude_after_unique)s
%(verbose)s
See Also
--------
mne.io.Raw : Documentation of attributes and methods.
mne.io.read_raw_bdf : Recommended way to read BDF files.
Notes
-----
%(edf_resamp_note)s
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 '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=(),
infer_types=False,
preload=False,
include=None,
units=None,
encoding="utf8",
exclude_after_unique=False,
*,
verbose=None,
):
if not _file_like(input_fname):
logger.info(f"Extracting BDF parameters from {input_fname}...")
input_fname = os.path.abspath(input_fname)
info, edf_info, orig_units = _get_info(
input_fname,
stim_channel,
eog,
misc,
exclude,
infer_types,
FileType.BDF,
include,
exclude_after_unique,
)
logger.info("Creating raw.info structure...")
edf_info["blob"] = input_fname if _file_like(input_fname) else None
_validate_type(units, (str, None, dict), "units")
if units is None:
units = dict()
elif isinstance(units, str):
units = {ch_name: units for ch_name in info["ch_names"]}
for k, (this_ch, this_unit) in enumerate(orig_units.items()):
if this_ch not in units:
continue
if this_unit not in ("", units[this_ch]):
raise ValueError(
f"Unit for channel {this_ch} is present in the file as "
f"{repr(this_unit)}, cannot overwrite it with the units "
f"argument {repr(units[this_ch])}."
)
if this_unit == "":
orig_units[this_ch] = units[this_ch]
ch_type = edf_info["ch_types"][k]
scaling = _get_scaling(ch_type.lower(), orig_units[this_ch])
edf_info["units"][k] /= scaling
# Raw attributes
last_samps = [edf_info["nsamples"] - 1]
super().__init__(
info,
preload,
filenames=[_path_from_fname(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
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,
)
annotations = _read_annotations_edf(
tal_data[0],
ch_names=info["ch_names"],
encoding=encoding,
)
self.set_annotations(annotations, on_missing="warn")
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]
if self._raw_extras[fi]["blob"] is None
else self._raw_extras[fi]["blob"],
cals,
mult,
)
@fill_doc
class RawGDF(BaseRaw):
"""Raw object from GDF file.
Parameters
----------
input_fname : path-like | file-like
Path to the GDF file. If a file-like object is provided,
preloading must be used.
.. versionchanged:: 1.10
Added support for file-like objects
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.
.. versionadded:: 0.24.1
include : list of str | str
Channel names to be included. A str is interpreted as a regular
expression. 'exclude' must be empty if include is assigned.
.. versionadded:: 1.1
%(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,
include=None,
verbose=None,
):
if not _file_like(input_fname):
logger.info(f"Extracting GDF parameters from {input_fname}...")
input_fname = os.path.abspath(input_fname)
info, edf_info, orig_units = _get_info(
input_fname,
stim_channel,
eog,
misc,
exclude,
True,
FileType.GDF,
include,
)
logger.info("Creating raw.info structure...")
edf_info["blob"] = input_fname if _file_like(input_fname) else None
# Raw attributes
last_samps = [edf_info["nsamples"] - 1]
super().__init__(
info,
preload,
filenames=[_path_from_fname(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]
if self._raw_extras[fi]["blob"] is None
else self._raw_extras[fi]["blob"],
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 = read_from_file_or_buffer(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 = read_from_file_or_buffer(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."""
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, _ = _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 _gdf_edf_get_fid(filenames, buffering=0) as fid:
# Extract data
start_offset = data_offset + block_start_idx * ch_offsets[-1] * dtype_byte
# first read everything into the `ones` array. For channels with
# lower sampling frequency, there will be zeros left at the end of the
# row. Ignore TAL/annotations channel and only store `orig_sel`
ones = np.zeros((len(orig_sel), data.shape[-1]), dtype=data.dtype)
# save how many samples have already been read per channel
n_smp_read = [0 for _ in range(len(orig_sel))]
# read data in chunks
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]
# loop over selected channels, ci=channel selection
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]].copy()
# annotation channel has to be treated separately
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)
elif orig_idx in stim_channel_idxs:
ch_data = np.bitwise_and(ch_data.astype(int), 2**17 - 1)
one_i = ch_data.ravel()[r_sidx:r_eidx]
# note how many samples have been read
smp_read = n_smp_read[orig_idx]
ones[orig_idx, smp_read : smp_read + len(one_i)] = one_i
n_smp_read[orig_idx] += len(one_i)
# resample channels with lower sample frequency
# skip if no data was requested, ie. only annotations were read
if any(n_smp_read) > 0:
# expected number of samples, equals maximum sfreq
smp_exp = data.shape[-1]
# resample data after loading all chunks to prevent edge artifacts
resampled = False
for i, smp_read in enumerate(n_smp_read):
# nothing read, nothing to resample
if smp_read == 0:
continue
# upsample if n_samples is lower than from highest sfreq
if smp_read != smp_exp:
# sanity check that we read exactly how much we expected
assert (ones[i, smp_read:] == 0).all()
ones[i, :] = resample(
ones[i, :smp_read].astype(np.float64),
smp_exp,
smp_read,
npad=0,
axis=-1,
)
resampled = True
# give warning if we resampled a subselection
if resampled and raw_extras["nsamples"] != (stop - start):
warn(
"Loading an EDF with mixed sampling frequencies and "
"preload=False will result in edge artifacts. "
"It is recommended to use preload=True."
"See also https://github.com/mne-tools/mne-python/issues/10635"
)
_mult_cal_one(data[:, :], ones, 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
@fill_doc
def _read_header(
fname,
exclude,
infer_types,
file_type,
include=None,
exclude_after_unique=False,
):
"""Unify EDF, BDF and GDF _read_header call.
Parameters
----------
fname : str
Path to the EDF+, BDF, or GDF file or file-like object.
exclude : list of str | str
Channel names to exclude. This can help when reading data with
different sampling rates to avoid unnecessary resampling. A str is
interpreted as a regular expression.
infer_types : bool
If True, try to infer channel types from channel labels. If a channel
label starts with a known type (such as 'EEG') followed by a space and
a name (such as 'Fp1'), the channel type will be set accordingly, and
the channel will be renamed to the original label without the prefix.
For unknown prefixes, the type will be 'EEG' and the name will not be
modified. If False, do not infer types and assume all channels are of
type 'EEG'.
include : list of str | str
Channel names to be included. A str is interpreted as a regular
expression. 'exclude' must be empty if include is assigned.
%(exclude_after_unique)s
Returns
-------
(edf_info, orig_units) : tuple
"""
if file_type in (FileType.BDF, FileType.EDF):
return _read_edf_header(
fname,
exclude,
infer_types,
file_type,
include,
exclude_after_unique,
)
elif file_type == FileType.GDF:
return _read_gdf_header(fname, exclude, include), None
else:
raise NotImplementedError("Only GDF, EDF, and BDF files are supported.")
def _get_info(
fname,
stim_channel,
eog,
misc,
exclude,
infer_types,
file_type,
include=None,
exclude_after_unique=False,
):
"""Extract information from 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, infer_types, file_type, include, exclude_after_unique
)
# 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)
if "ch_types" in edf_info:
ch_types = edf_info["ch_types"] # of length len(sel)
else:
ch_types = [None] * len(sel)
if len(sel) == 0: # only want stim channels
n_samps = edf_info["n_samps"][[0]]
else:
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))
chs_without_types = list()
for idx, ch_name in enumerate(ch_names):
chan_info = {}
chan_info["cal"] = 1.0
chan_info["logno"] = idx + 1
chan_info["scanno"] = idx + 1
chan_info["range"] = 1.0
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
# montage can't be stored in EDF so channel locs are unknown:
chan_info["loc"] = np.full(12, np.nan)
# if the edf info contained channel type information
# set it now
ch_type = ch_types[idx]
if ch_type is not None and ch_type in CH_TYPE_MAPPING:
chan_info["kind"] = CH_TYPE_MAPPING.get(ch_type)
if ch_type not in ["EEG", "ECOG", "SEEG", "DBS"]:
chan_info["coil_type"] = FIFF.FIFFV_COIL_NONE
pick_mask[idx] = False
# if user passes in explicit mapping for eog, misc and stim
# channels set them here
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
elif ch_type not in CH_TYPE_MAPPING:
chs_without_types.append(ch_name)
chs.append(chan_info)
# warn if channel type was not inferable
if len(chs_without_types):
msg = (
"Could not determine channel type of the following channels, "
f"they will be set as EEG:\n{', '.join(chs_without_types)}"
)
logger.info(msg)
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]
if len(not_stim_ch) == 0: # only loading stim channels
not_stim_ch = list(range(len(n_samps)))
sfreq = (
np.take(n_samps, not_stim_ch).max()
* edf_info["record_length"][1]
/ edf_info["record_length"][0]
)
del n_samps
info = _empty_info(sfreq)
info["meas_date"] = edf_info["meas_date"]
info["chs"] = chs
info["ch_names"] = ch_names
# Subject information
info["subject_info"] = {}
# String subject identifier
if edf_info["subject_info"].get("id") is not None:
info["subject_info"]["his_id"] = edf_info["subject_info"]["id"]
# Subject sex (0=unknown, 1=male, 2=female)
if edf_info["subject_info"].get("sex") is not None:
if edf_info["subject_info"]["sex"] == "M":
info["subject_info"]["sex"] = 1
elif edf_info["subject_info"]["sex"] == "F":
info["subject_info"]["sex"] = 2
else:
info["subject_info"]["sex"] = 0
# Subject names (first, middle, last).
if edf_info["subject_info"].get("name") is not None:
sub_names = edf_info["subject_info"]["name"].split("_")
if len(sub_names) < 2 or len(sub_names) > 3:
info["subject_info"]["last_name"] = edf_info["subject_info"]["name"]
elif len(sub_names) == 2:
info["subject_info"]["first_name"] = sub_names[0]
info["subject_info"]["last_name"] = sub_names[1]
else:
info["subject_info"]["first_name"] = sub_names[0]
info["subject_info"]["middle_name"] = sub_names[1]
info["subject_info"]["last_name"] = sub_names[2]
# Birthday in (year, month, day) format.
if isinstance(edf_info["subject_info"].get("birthday"), datetime):
info["subject_info"]["birthday"] = date(
edf_info["subject_info"]["birthday"].year,
edf_info["subject_info"]["birthday"].month,
edf_info["subject_info"]["birthday"].day,
)
# Handedness (1=right, 2=left, 3=ambidextrous).
if edf_info["subject_info"].get("hand") is not None:
info["subject_info"]["hand"] = int(edf_info["subject_info"]["hand"])
# Height in meters.
if edf_info["subject_info"].get("height") is not None:
info["subject_info"]["height"] = float(edf_info["subject_info"]["height"])
# Weight in kilograms.
if edf_info["subject_info"].get("weight") is not None:
info["subject_info"]["weight"] = float(edf_info["subject_info"]["weight"])
# Remove values after conversion to help with in-memory anonymization
for key in ("subject_info", "meas_date"):
del edf_info[key]
# Filter settings
if filt_ch_idxs := [x for x in range(len(sel)) if x not in stim_channel_idxs]:
_set_prefilter(info, edf_info, filt_ch_idxs, "highpass")
_set_prefilter(info, edf_info, filt_ch_idxs, "lowpass")
if np.isnan(info["lowpass"]):
info["lowpass"] = info["sfreq"] / 2.0
if info["highpass"] > info["lowpass"]:
warn(
f"Highpass cutoff frequency {info['highpass']} is greater "
f"than lowpass cutoff frequency {info['lowpass']}, "
"setting values to 0 and Nyquist."
)
info["highpass"] = 0.0
info["lowpass"] = info["sfreq"] / 2.0
# Some keys to be consistent with FIF measurement info
info["description"] = None
edf_info["nsamples"] = int(edf_info["n_records"] * max_samp)
info._unlocked = False
info._update_redundant()
# Later used for reading
edf_info["cal"] = physical_ranges / cals
# physical dimension in µV