-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathbase.py
3262 lines (2908 loc) · 111 KB
/
base.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
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import os
import shutil
from collections import defaultdict
from contextlib import nullcontext
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import timedelta
from inspect import getfullargspec
from pathlib import Path
import numpy as np
from .._fiff.compensator import make_compensator, set_current_comp
from .._fiff.constants import FIFF
from .._fiff.meas_info import (
ContainsMixin,
SetChannelsMixin,
_ensure_infos_match,
_unit2human,
write_meas_info,
)
from .._fiff.pick import (
_picks_to_idx,
channel_type,
pick_channels,
pick_info,
pick_types,
)
from .._fiff.proj import ProjMixin, _proj_equal, activate_proj, setup_proj
from .._fiff.utils import _check_orig_units, _make_split_fnames
from .._fiff.write import (
_NEXT_FILE_BUFFER,
_get_split_size,
end_block,
start_and_end_file,
start_block,
write_complex64,
write_complex128,
write_dau_pack16,
write_double,
write_float,
write_id,
write_int,
write_string,
)
from ..annotations import (
Annotations,
_annotations_starts_stops,
_combine_annotations,
_handle_meas_date,
_sync_onset,
_write_annotations,
)
from ..channels.channels import InterpolationMixin, ReferenceMixin, UpdateChannelsMixin
from ..defaults import _handle_default
from ..event import concatenate_events, find_events
from ..filter import (
FilterMixin,
_check_fun,
_check_resamp_noop,
_resamp_ratio_len,
_resample_stim_channels,
notch_filter,
resample,
)
from ..html_templates import _get_html_template
from ..parallel import parallel_func
from ..time_frequency.spectrum import Spectrum, SpectrumMixin, _validate_method
from ..time_frequency.tfr import RawTFR
from ..utils import (
SizeMixin,
TimeMixin,
_arange_div,
_build_data_frame,
_check_fname,
_check_option,
_check_pandas_index_arguments,
_check_pandas_installed,
_check_preload,
_check_time_format,
_convert_times,
_file_like,
_get_argvalues,
_get_stim_channel,
_pl,
_scale_dataframe_data,
_stamp_to_dt,
_time_mask,
_validate_type,
check_fname,
copy_doc,
copy_function_doc_to_method_doc,
fill_doc,
logger,
repr_html,
sizeof_fmt,
verbose,
warn,
)
from ..viz import _RAW_CLIP_DEF, plot_raw
@fill_doc
class BaseRaw(
ProjMixin,
ContainsMixin,
UpdateChannelsMixin,
ReferenceMixin,
SetChannelsMixin,
InterpolationMixin,
TimeMixin,
SizeMixin,
FilterMixin,
SpectrumMixin,
):
"""Base class for Raw data.
Parameters
----------
%(info_not_none)s
preload : bool | str | ndarray
Preload data into memory for data manipulation and faster indexing.
If True, the data will be preloaded into memory (fast, requires
large amount of memory). If preload is a string, preload is the
file name of a memory-mapped file which is used to store the data
on the hard drive (slower, requires less memory). If preload is an
ndarray, the data are taken from that array. If False, data are not
read until save.
first_samps : iterable
Iterable of the first sample number from each raw file. For unsplit raw
files this should be a length-one list or tuple.
last_samps : iterable | None
Iterable of the last sample number from each raw file. For unsplit raw
files this should be a length-one list or tuple. If None, then preload
must be an ndarray.
filenames : tuple | None
Tuple of length one (for unsplit raw files) or length > 1 (for split
raw files).
raw_extras : list of dict
The data necessary for on-demand reads for the given reader format.
Should be the same length as ``filenames``. Will have the entry
``raw_extras['orig_nchan']`` added to it for convenience.
orig_format : str
The data format of the original raw file (e.g., ``'double'``).
dtype : dtype | None
The dtype of the raw data. If preload is an ndarray, its dtype must
match what is passed here.
buffer_size_sec : float
The buffer size in seconds that should be written by default using
:meth:`mne.io.Raw.save`.
orig_units : dict | None
Dictionary mapping channel names to their units as specified in
the header file. Example: {'FC1': 'nV'}.
.. versionadded:: 0.17
%(verbose)s
See Also
--------
mne.io.Raw : Documentation of attributes and methods.
Notes
-----
This class is public to allow for stable type-checking in user
code (i.e., ``isinstance(my_raw_object, BaseRaw)``) but should not be used
as a constructor for `Raw` objects (use instead one of the subclass
constructors, or one of the ``mne.io.read_raw_*`` functions).
Subclasses must provide the following methods:
* _read_segment_file(self, data, idx, fi, start, stop, cals, mult)
(only needed for types that support on-demand disk reads)
"""
# NOTE: If you add a new attribute to this class and get a Sphinx warning like:
# docstring of mne.io.base.BaseRaw:71:
# WARNING: py:obj reference target not found: duration [ref.obj]
# You need to add the attribute to doc/conf.py nitpick_ignore_regex. You should also
# consider adding it to the Attributes list for Raw in mne/io/fiff/raw.py.
_extra_attributes = ()
@verbose
def __init__(
self,
info,
preload=False,
first_samps=(0,),
last_samps=None,
filenames=None,
raw_extras=(None,),
orig_format="double",
dtype=np.float64,
buffer_size_sec=1.0,
orig_units=None,
*,
verbose=None,
):
# wait until the end to preload data, but triage here
if isinstance(preload, np.ndarray):
# some functions (e.g., filtering) only work w/64-bit data
if preload.dtype not in (np.float64, np.complex128):
raise RuntimeError(
f"datatype must be float64 or complex128, not {preload.dtype}"
)
if preload.dtype != dtype:
raise ValueError("preload and dtype must match")
self._data = preload
self.preload = True
assert len(first_samps) == 1
last_samps = [first_samps[0] + self._data.shape[1] - 1]
load_from_disk = False
else:
if last_samps is None:
raise ValueError(
"last_samps must be given unless preload is an ndarray"
)
if not preload:
self.preload = False
load_from_disk = False
else:
load_from_disk = True
self._last_samps = np.array(last_samps)
self._first_samps = np.array(first_samps)
orig_ch_names = info["ch_names"]
with info._unlock(check_after=True):
# be permissive of old code
if isinstance(info["meas_date"], tuple):
info["meas_date"] = _stamp_to_dt(info["meas_date"])
self.info = info
self.buffer_size_sec = float(buffer_size_sec)
cals = np.empty(info["nchan"])
for k in range(info["nchan"]):
cals[k] = info["chs"][k]["range"] * info["chs"][k]["cal"]
bad = np.where(cals == 0)[0]
if len(bad) > 0:
raise ValueError(
f"Bad cals for channels {dict((ii, self.ch_names[ii]) for ii in bad)}"
)
self._cals = cals
if raw_extras is None:
raw_extras = [None] * len(first_samps)
self._raw_extras = list(dict() if r is None else r for r in raw_extras)
for r in self._raw_extras:
r["orig_nchan"] = info["nchan"]
self._read_picks = [np.arange(info["nchan"]) for _ in range(len(raw_extras))]
# deal with compensation (only relevant for CTF data, either CTF
# reader or MNE-C converted CTF->FIF files)
self._read_comp_grade = self.compensation_grade # read property
if self._read_comp_grade is not None and len(info["comps"]):
logger.info("Current compensation grade : %d", self._read_comp_grade)
self._comp = None
if filenames is None:
filenames = [None] * len(first_samps)
self.filenames = list(filenames)
_validate_type(orig_format, str, "orig_format")
_check_option("orig_format", orig_format, ("double", "single", "int", "short"))
self.orig_format = orig_format
# Sanity check and set original units, if provided by the reader:
if orig_units:
if not isinstance(orig_units, dict):
raise ValueError(
f"orig_units must be of type dict, but got {type(orig_units)}"
)
# original units need to be truncated to 15 chars or renamed
# to match MNE conventions (channel name unique and less than
# 15 characters).
orig_units = deepcopy(orig_units)
for old_ch, new_ch in zip(orig_ch_names, info["ch_names"]):
if old_ch in orig_units:
this_unit = orig_units[old_ch]
del orig_units[old_ch]
orig_units[new_ch] = this_unit
# STI 014 channel is native only to fif ... for all other formats
# this was artificially added by the IO procedure, so remove it
ch_names = list(info["ch_names"])
if "STI 014" in ch_names and self.filenames[0].suffix != ".fif":
ch_names.remove("STI 014")
# Each channel in the data must have a corresponding channel in
# the original units.
ch_correspond = [ch in orig_units for ch in ch_names]
if not all(ch_correspond):
ch_without_orig_unit = ch_names[ch_correspond.index(False)]
raise ValueError(
f"Channel {ch_without_orig_unit} has no associated original unit."
)
# Final check of orig_units, editing a unit if it is not a valid
# unit
orig_units = _check_orig_units(orig_units)
self._orig_units = orig_units or dict() # always a dict
self._projector = None
self._dtype_ = dtype
self.set_annotations(None)
self._cropped_samp = first_samps[0]
# If we have True or a string, actually do the preloading
if load_from_disk:
self._preload_data(preload)
self._init_kwargs = _get_argvalues()
@verbose
def apply_gradient_compensation(self, grade, verbose=None):
"""Apply CTF gradient compensation.
.. warning:: The compensation matrices are stored with single
precision, so repeatedly switching between different
of compensation (e.g., 0->1->3->2) can increase
numerical noise, especially if data are saved to
disk in between changing grades. It is thus best to
only use a single gradient compensation level in
final analyses.
Parameters
----------
grade : int
CTF gradient compensation level.
%(verbose)s
Returns
-------
raw : instance of Raw
The modified Raw instance. Works in-place.
"""
grade = int(grade)
current_comp = self.compensation_grade
if current_comp != grade:
if self.proj:
raise RuntimeError(
"Cannot change compensation on data where projectors have been "
"applied."
)
# Figure out what operator to use (varies depending on preload)
from_comp = current_comp if self.preload else self._read_comp_grade
comp = make_compensator(self.info, from_comp, grade)
logger.info(
"Compensator constructed to change %d -> %d", current_comp, grade
)
set_current_comp(self.info, grade)
# We might need to apply it to our data now
if self.preload:
logger.info("Applying compensator to loaded data")
lims = np.concatenate(
[np.arange(0, len(self.times), 10000), [len(self.times)]]
)
for start, stop in zip(lims[:-1], lims[1:]):
self._data[:, start:stop] = np.dot(comp, self._data[:, start:stop])
else:
self._comp = comp # store it for later use
return self
@property
def _dtype(self):
"""Datatype for loading data (property so subclasses can override)."""
# most classes only store real data, they won't need anything special
return self._dtype_
@verbose
def _read_segment(
self, start=0, stop=None, sel=None, data_buffer=None, *, verbose=None
):
"""Read a chunk of raw data.
Parameters
----------
start : int, (optional)
first sample to include (first is 0). If omitted, defaults to the
first sample in data.
stop : int, (optional)
First sample to not include.
If omitted, data is included to the end.
sel : array, optional
Indices of channels to select.
data_buffer : array or str, optional
numpy array to fill with data read, must have the correct shape.
If str, a np.memmap with the correct data type will be used
to store the data.
projector : array
SSP operator to apply to the data.
%(verbose)s
Returns
-------
data : array, [channels x samples]
the data matrix (channels x samples).
"""
# Initial checks
start = int(start)
stop = self.n_times if stop is None else min([int(stop), self.n_times])
if start >= stop:
raise ValueError("No data in this range")
# Initialize the data and calibration vector
if sel is None:
n_out = self.info["nchan"]
idx = slice(None)
else:
n_out = len(sel)
idx = _convert_slice(sel)
del sel
assert n_out <= self.info["nchan"]
data_shape = (n_out, stop - start)
dtype = self._dtype
if isinstance(data_buffer, np.ndarray):
if data_buffer.shape != data_shape:
raise ValueError(
f"data_buffer has incorrect shape: "
f"{data_buffer.shape} != {data_shape}"
)
data = data_buffer
else:
data = _allocate_data(data_buffer, data_shape, dtype)
# deal with having multiple files accessed by the raw object
cumul_lens = np.concatenate(([0], np.array(self._raw_lengths, dtype="int")))
cumul_lens = np.cumsum(cumul_lens)
files_used = np.logical_and(
np.less(start, cumul_lens[1:]), np.greater_equal(stop - 1, cumul_lens[:-1])
)
# set up cals and mult (cals, compensation, and projector)
n_out = len(np.arange(len(self.ch_names))[idx])
cals = self._cals.ravel()
projector, comp = self._projector, self._comp
if comp is not None:
mult = comp
if projector is not None:
mult = projector @ mult
else:
mult = projector
del projector, comp
if mult is None:
cals = cals[idx, np.newaxis]
assert cals.shape == (n_out, 1)
need_idx = idx # sufficient just to read the given channels
else:
mult = mult[idx] * cals
cals = None # shouldn't be used
assert mult.shape == (n_out, len(self.ch_names))
# read all necessary for proj
need_idx = np.where(np.any(mult, axis=0))[0]
mult = mult[:, need_idx]
logger.debug(
f"Reading {len(need_idx)}/{len(self.ch_names)} channels "
f"due to projection"
)
assert (mult is None) ^ (cals is None) # xor
# read from necessary files
offset = 0
for fi in np.nonzero(files_used)[0]:
start_file = self._first_samps[fi]
# first iteration (only) could start in the middle somewhere
if offset == 0:
start_file += start - cumul_lens[fi]
stop_file = np.min(
[
stop - cumul_lens[fi] + self._first_samps[fi],
self._last_samps[fi] + 1,
]
)
if start_file < self._first_samps[fi] or stop_file < start_file:
raise ValueError("Bad array indexing, could be a bug")
n_read = stop_file - start_file
this_sl = slice(offset, offset + n_read)
# reindex back to original file
orig_idx = _convert_slice(self._read_picks[fi][need_idx])
_ReadSegmentFileProtector(self)._read_segment_file(
data[:, this_sl],
orig_idx,
fi,
int(start_file),
int(stop_file),
cals,
mult,
)
offset += n_read
return data
def _read_segment_file(self, data, idx, fi, start, stop, cals, mult):
"""Read a segment of data from a file.
Only needs to be implemented for readers that support
``preload=False``. Any implementation should only make use of:
- self._raw_extras[fi]
- self.filenames[fi]
So be sure to store any information necessary for reading raw data
in self._raw_extras[fi]. Things like ``info`` can be decoupled
from the original data (e.g., different subsets of channels) due
to picking before preload, for example.
Parameters
----------
data : ndarray, shape (n_out, stop - start + 1)
The data array. Should be modified inplace.
idx : ndarray | slice
The requested channel indices.
fi : int
The file index that must be read from.
start : int
The start sample in the given file.
stop : int
The stop sample in the given file (inclusive).
cals : ndarray, shape (len(idx), 1)
Channel calibrations (already sub-indexed).
mult : ndarray, shape (n_out, len(idx) | None
The compensation + projection + cals matrix, if applicable.
"""
raise NotImplementedError
def _check_bad_segment(
self, start, stop, picks, reject_start, reject_stop, reject_by_annotation=False
):
"""Check if data segment is bad.
If the slice is good, returns the data in desired range.
If rejected based on annotation, returns description of the
bad segment as a string.
Parameters
----------
start : int
First sample of the slice.
stop : int
End of the slice.
picks : array of int
Channel picks.
reject_start : int
First sample to check for overlaps with bad annotations.
reject_stop : int
Last sample to check for overlaps with bad annotations.
reject_by_annotation : bool
Whether to perform rejection based on annotations.
False by default.
Returns
-------
data : array | str
Data in the desired range (good segment) or description of the bad
segment.
"""
if start < 0:
return None
if reject_by_annotation and len(self.annotations) > 0:
annot = self.annotations
sfreq = self.info["sfreq"]
onset = _sync_onset(self, annot.onset)
overlaps = np.where(onset < reject_stop / sfreq)
overlaps = np.where(
onset[overlaps] + annot.duration[overlaps] > reject_start / sfreq
)
for descr in annot.description[overlaps]:
if descr.lower().startswith("bad"):
return descr
return self._getitem((picks, slice(start, stop)), return_times=False)
@verbose
def load_data(self, verbose=None):
"""Load raw data.
Parameters
----------
%(verbose)s
Returns
-------
raw : instance of Raw
The raw object with data.
Notes
-----
This function will load raw data if it was not already preloaded.
If data were already preloaded, it will do nothing.
.. versionadded:: 0.10.0
"""
if not self.preload:
self._preload_data(True)
return self
def _preload_data(self, preload):
"""Actually preload the data."""
data_buffer = preload
if isinstance(preload, bool | np.bool_) and not preload:
data_buffer = None
t = self.times
logger.info(
f"Reading 0 ... {len(t) - 1} = {0.0:9.3f} ... {t[-1]:9.3f} secs..."
)
self._data = self._read_segment(data_buffer=data_buffer)
assert len(self._data) == self.info["nchan"]
self.preload = True
self._comp = None # no longer needed
self.close()
@property
def _first_time(self):
return self.first_samp / float(self.info["sfreq"])
@property
def first_samp(self):
"""The first data sample.
See :term:`first_samp`.
"""
return self._cropped_samp
@property
def first_time(self):
"""The first time point (including first_samp but not meas_date)."""
return self._first_time
@property
def last_samp(self):
"""The last data sample."""
return self.first_samp + sum(self._raw_lengths) - 1
@property
def _last_time(self):
return self.last_samp / float(self.info["sfreq"])
def time_as_index(self, times, use_rounding=False, origin=None):
"""Convert time to indices.
Parameters
----------
times : list-like | float | int
List of numbers or a number representing points in time.
use_rounding : bool
If True, use rounding (instead of truncation) when converting
times to indices. This can help avoid non-unique indices.
origin : datetime | float | int | None
Time reference for times. If None, ``times`` are assumed to be
relative to :term:`first_samp`.
.. versionadded:: 0.17.0
Returns
-------
index : ndarray
Indices relative to :term:`first_samp` corresponding to the times
supplied.
"""
origin = _handle_meas_date(origin)
if origin is None:
delta = 0
elif self.info["meas_date"] is None:
raise ValueError(
f'origin must be None when info["meas_date"] is None, got {origin}'
)
else:
first_samp_in_abs_time = self.info["meas_date"] + timedelta(
0, self._first_time
)
delta = (origin - first_samp_in_abs_time).total_seconds()
times = np.atleast_1d(times) + delta
return super().time_as_index(times, use_rounding)
@property
def _raw_lengths(self):
return [
last - first + 1 for first, last in zip(self._first_samps, self._last_samps)
]
@property
def annotations(self): # noqa: D401
""":class:`~mne.Annotations` for marking segments of data."""
return self._annotations
@property
def filenames(self) -> tuple[Path | None, ...]:
"""The filenames used.
:type: :class:`tuple` of :class:`pathlib.Path` | ``None``
"""
return tuple(self._filenames)
@filenames.setter
def filenames(self, value):
"""The filenames used, cast to list of paths.""" # noqa: D401
_validate_type(value, (list, tuple), "filenames")
if isinstance(value, tuple):
value = list(value)
for k, elt in enumerate(value):
if elt is not None:
value[k] = _check_fname(elt, overwrite="read", must_exist=False)
if not value[k].exists():
# check existence separately from _check_fname since some
# fileformats use directories instead of files and '_check_fname'
# does not handle it correctly.
raise FileNotFoundError(f"File {value[k]} not found.")
self._filenames = list(value)
@verbose
def set_annotations(
self, annotations, emit_warning=True, on_missing="raise", *, verbose=None
):
"""Setter for annotations.
This setter checks if they are inside the data range.
Parameters
----------
annotations : instance of mne.Annotations | None
Annotations to set. If None, the annotations is defined
but empty.
%(emit_warning)s
The default is True.
%(on_missing_ch_names)s
%(verbose)s
Returns
-------
self : instance of Raw
The raw object with annotations.
"""
meas_date = _handle_meas_date(self.info["meas_date"])
if annotations is None:
self._annotations = Annotations([], [], [], meas_date)
else:
_validate_type(annotations, Annotations, "annotations")
if meas_date is None and annotations.orig_time is not None:
raise RuntimeError(
"Ambiguous operation. Setting an Annotation object with known "
"``orig_time`` to a raw object which has ``meas_date`` set to None "
"is ambiguous. Please, either set a meaningful ``meas_date`` to "
"the raw object; or set ``orig_time`` to None in which case the "
"annotation onsets would be taken in reference to the first sample "
"of the raw object."
)
delta = 1.0 / self.info["sfreq"]
new_annotations = annotations.copy()
new_annotations._prune_ch_names(self.info, on_missing)
if annotations.orig_time is None:
new_annotations.crop(
0, self.times[-1] + delta, emit_warning=emit_warning
)
new_annotations.onset += self._first_time
else:
tmin = meas_date + timedelta(0, self._first_time)
tmax = tmin + timedelta(seconds=self.times[-1] + delta)
new_annotations.crop(tmin=tmin, tmax=tmax, emit_warning=emit_warning)
new_annotations.onset -= (
meas_date - new_annotations.orig_time
).total_seconds()
new_annotations._orig_time = meas_date
self._annotations = new_annotations
return self
def __del__(self): # noqa: D105
# remove file for memmap
if hasattr(self, "_data") and getattr(self._data, "filename", None) is not None:
# First, close the file out; happens automatically on del
filename = self._data.filename
del self._data
# Now file can be removed
try:
os.remove(filename)
except OSError:
pass # ignore file that no longer exists
def __enter__(self):
"""Entering with block."""
return self
def __exit__(self, exception_type, exception_val, trace):
"""Exit with block."""
try:
self.close()
except Exception:
return exception_type, exception_val, trace
def _parse_get_set_params(self, item):
"""Parse the __getitem__ / __setitem__ tuples."""
# make sure item is a tuple
if not isinstance(item, tuple): # only channel selection passed
item = (item, slice(None, None, None))
if len(item) != 2: # should be channels and time instants
raise RuntimeError(
"Unable to access raw data (need both channels and time)"
)
sel = _picks_to_idx(self.info, item[0])
if isinstance(item[1], slice):
time_slice = item[1]
start, stop, step = (time_slice.start, time_slice.stop, time_slice.step)
else:
item1 = item[1]
# Let's do automated type conversion to integer here
if np.array(item[1]).dtype.kind == "i":
item1 = int(item1)
if isinstance(item1, int | np.integer):
start, stop, step = item1, item1 + 1, 1
# Need to special case -1, because -1:0 will be empty
if start == -1:
stop = None
else:
raise ValueError("Must pass int or slice to __getitem__")
if start is None:
start = 0
if step is not None and step != 1:
raise ValueError(f"step needs to be 1 : {step} given")
if isinstance(sel, int | np.integer):
sel = np.array([sel])
if sel is not None and len(sel) == 0:
raise ValueError("Empty channel list")
return sel, start, stop
def __getitem__(self, item):
"""Get raw data and times.
Parameters
----------
item : tuple or array-like
See below for use cases.
Returns
-------
data : ndarray, shape (n_channels, n_times)
The raw data.
times : ndarray, shape (n_times,)
The times associated with the data.
Examples
--------
Generally raw data is accessed as::
>>> data, times = raw[picks, time_slice] # doctest: +SKIP
To get all data, you can thus do either of::
>>> data, times = raw[:] # doctest: +SKIP
Which will be equivalent to:
>>> data, times = raw[:, :] # doctest: +SKIP
To get only the good MEG data from 10-20 seconds, you could do::
>>> picks = mne.pick_types(raw.info, meg=True, exclude='bads') # doctest: +SKIP
>>> t_idx = raw.time_as_index([10., 20.]) # doctest: +SKIP
>>> data, times = raw[picks, t_idx[0]:t_idx[1]] # doctest: +SKIP
""" # noqa: E501
return self._getitem(item)
def _getitem(self, item, return_times=True):
sel, start, stop = self._parse_get_set_params(item)
if self.preload:
data = self._data[sel, start:stop]
else:
data = self._read_segment(start=start, stop=stop, sel=sel)
if return_times:
# Rather than compute the entire thing just compute the subset
# times = self.times[start:stop]
# stop can be None here so don't use it directly
times = np.arange(start, start + data.shape[1], dtype=float)
times /= self.info["sfreq"]
return data, times
else:
return data
def __setitem__(self, item, value):
"""Set raw data content."""
_check_preload(self, "Modifying data of Raw")
sel, start, stop = self._parse_get_set_params(item)
# set the data
self._data[sel, start:stop] = value
@verbose
def get_data(
self,
picks=None,
start=0,
stop=None,
reject_by_annotation=None,
return_times=False,
units=None,
*,
tmin=None,
tmax=None,
verbose=None,
):
"""Get data in the given range.
Parameters
----------
%(picks_all)s
start : int
The first sample to include. Defaults to 0.
stop : int | None
End sample (first not to include). If None (default), the end of
the data is used.
reject_by_annotation : None | 'omit' | 'NaN'
Whether to reject by annotation. If None (default), no rejection is
done. If 'omit', segments annotated with description starting with
'bad' are omitted. If 'NaN', the bad samples are filled with NaNs.
return_times : bool
Whether to return times as well. Defaults to False.
%(units)s
tmin : int | float | None
Start time of data to get in seconds. The ``tmin`` parameter is
ignored if the ``start`` parameter is bigger than 0.
.. versionadded:: 0.24.0
tmax : int | float | None
End time of data to get in seconds. The ``tmax`` parameter is
ignored if the ``stop`` parameter is defined.
.. versionadded:: 0.24.0
%(verbose)s
Returns
-------
data : ndarray, shape (n_channels, n_times)
Copy of the data in the given range.
times : ndarray, shape (n_times,)
Times associated with the data samples. Only returned if
return_times=True.
Notes
-----
.. versionadded:: 0.14.0
"""
# validate types
_validate_type(start, types=("int-like"), item_name="start", type_name="int")
_validate_type(
stop, types=("int-like", None), item_name="stop", type_name="int, None"
)
picks = _picks_to_idx(self.info, picks, "all", exclude=())
# Get channel factors for conversion into specified unit
# (vector of ones if no conversion needed)
if units is not None:
ch_factors = _get_ch_factors(self, units, picks)
# convert to ints
picks = np.atleast_1d(np.arange(self.info["nchan"])[picks])
# handle start/tmin stop/tmax
tmin_start, tmax_stop = self._handle_tmin_tmax(tmin, tmax)
# tmin/tmax are ignored if start/stop are defined to
# something other than their defaults
start = tmin_start if start == 0 else start
stop = tmax_stop if stop is None else stop
# truncate start/stop to the open interval [0, n_times]
start = min(max(0, start), self.n_times)
stop = min(max(0, stop), self.n_times)
if len(self.annotations) == 0 or reject_by_annotation is None:
getitem = self._getitem(
(picks, slice(start, stop)), return_times=return_times
)
if return_times:
data, times = getitem
if units is not None:
data *= ch_factors[:, np.newaxis]
return data, times
if units is not None:
getitem *= ch_factors[:, np.newaxis]
return getitem
_check_option(
"reject_by_annotation", reject_by_annotation.lower(), ["omit", "nan"]
)
onsets, ends = _annotations_starts_stops(self, ["BAD"])
keep = (onsets < stop) & (ends > start)
onsets = np.maximum(onsets[keep], start)
ends = np.minimum(ends[keep], stop)
if len(onsets) == 0:
data, times = self[picks, start:stop]
if units is not None:
data *= ch_factors[:, np.newaxis]
if return_times:
return data, times