/
base.py
2690 lines (2347 loc) · 110 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
# -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Matti Hamalainen <msh@nmr.mgh.harvard.edu>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Denis Engemann <denis.engemann@gmail.com>
# Teon Brooks <teon.brooks@gmail.com>
# Marijn van Vliet <w.m.vanvliet@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)
from copy import deepcopy
import os
import os.path as op
import numpy as np
from .constants import FIFF
from .utils import _construct_bids_filename, _check_orig_units
from .pick import pick_types, channel_type, pick_channels, pick_info
from .pick import _pick_data_channels, _pick_data_or_ica
from .meas_info import write_meas_info
from .proj import setup_proj, activate_proj, _proj_equal, ProjMixin
from ..channels.channels import (ContainsMixin, UpdateChannelsMixin,
SetChannelsMixin, InterpolationMixin)
from ..channels.montage import read_montage, _set_montage, Montage
from .compensator import set_current_comp, make_compensator
from .write import (start_file, end_file, start_block, end_block,
write_dau_pack16, write_float, write_double,
write_complex64, write_complex128, write_int,
write_id, write_string, _get_split_size)
from ..annotations import (_annotations_starts_stops, _write_annotations,
_handle_meas_date)
from ..filter import (filter_data, notch_filter, resample, next_fast_len,
_resample_stim_channels, _filt_check_picks,
_filt_update_info)
from ..parallel import parallel_func
from ..utils import (_check_fname, _check_pandas_installed, sizeof_fmt,
_check_pandas_index_arguments,
check_fname, _get_stim_channel,
logger, verbose, _time_mask, warn, SizeMixin,
copy_function_doc_to_method_doc,
_check_preload, _get_argvalues)
from ..viz import plot_raw, plot_raw_psd, plot_raw_psd_topo
from ..defaults import _handle_default
from ..externals.six import string_types
from ..event import find_events, concatenate_events
from ..annotations import Annotations, _combine_annotations, _sync_onset
from ..annotations import _ensure_annotation_object
class ToDataFrameMixin(object):
"""Class to add to_data_frame capabilities to certain classes."""
def _get_check_picks(self, picks, picks_check):
"""Get and check picks."""
if picks is None:
picks = list(range(self.info['nchan']))
else:
if not np.in1d(picks, np.arange(len(picks_check))).all():
raise ValueError('At least one picked channel is not present '
'in this object instance.')
return picks
def to_data_frame(self, picks=None, index=None, scaling_time=1e3,
scalings=None, copy=True, start=None, stop=None):
"""Export data in tabular structure as a pandas DataFrame.
Columns and indices will depend on the object being converted.
Generally this will include as much relevant information as
possible for the data type being converted. This makes it easy
to convert data for use in packages that utilize dataframes,
such as statsmodels or seaborn.
Parameters
----------
picks : array-like of int | None
If None only MEG and EEG channels are kept
otherwise the channels indices in picks are kept.
index : tuple of str | None
Column to be used as index for the data. Valid string options
are 'epoch', 'time' and 'condition'. If None, all three info
columns will be included in the table as categorial data.
scaling_time : float
Scaling to be applied to time units.
scalings : dict | None
Scaling to be applied to the channels picked. If None, defaults to
``scalings=dict(eeg=1e6, grad=1e13, mag=1e15, misc=1.0)``.
copy : bool
If true, data will be copied. Else data may be modified in place.
start : int | None
If it is a Raw object, this defines a starting index for creating
the dataframe from a slice. The times will be interpolated from the
index and the sampling rate of the signal.
stop : int | None
If it is a Raw object, this defines a stop index for creating
the dataframe from a slice. The times will be interpolated from the
index and the sampling rate of the signal.
Returns
-------
df : instance of pandas.core.DataFrame
A dataframe suitable for usage with other
statistical/plotting/analysis packages. Column/Index values will
depend on the object type being converted, but should be
human-readable.
"""
from ..epochs import BaseEpochs
from ..evoked import Evoked
from ..source_estimate import _BaseSourceEstimate
pd = _check_pandas_installed()
mindex = list()
# Treat SourceEstimates special because they don't have the same info
if isinstance(self, _BaseSourceEstimate):
if self.subject is None:
default_index = ['time']
else:
default_index = ['subject', 'time']
data = self.data.T
times = self.times
shape = data.shape
mindex.append(('subject', np.repeat(self.subject, shape[0])))
if isinstance(self.vertices, list):
# surface source estimates
col_names = [i for e in [
['{0} {1}'.format('LH' if ii < 1 else 'RH', vert)
for vert in vertno]
for ii, vertno in enumerate(self.vertices)]
for i in e]
else:
# volume source estimates
col_names = ['VOL {0}'.format(vert) for vert in self.vertices]
elif isinstance(self, (BaseEpochs, BaseRaw, Evoked)):
picks = self._get_check_picks(picks, self.ch_names)
if isinstance(self, BaseEpochs):
default_index = ['condition', 'epoch', 'time']
data = self.get_data()[:, picks, :]
times = self.times
n_epochs, n_picks, n_times = data.shape
data = np.hstack(data).T # (time*epochs) x signals
# Multi-index creation
times = np.tile(times, n_epochs)
id_swapped = dict((v, k) for k, v in self.event_id.items())
names = [id_swapped[k] for k in self.events[:, 2]]
mindex.append(('condition', np.repeat(names, n_times)))
mindex.append(('epoch',
np.repeat(np.arange(n_epochs), n_times)))
col_names = [self.ch_names[k] for k in picks]
elif isinstance(self, (BaseRaw, Evoked)):
default_index = ['time']
if isinstance(self, BaseRaw):
data, times = self[picks, start:stop]
elif isinstance(self, Evoked):
data = self.data[picks, :]
times = self.times
data = data.T
col_names = [self.ch_names[k] for k in picks]
types = [channel_type(self.info, idx) for idx in picks]
n_channel_types = 0
ch_types_used = []
scalings = _handle_default('scalings', scalings)
for t in scalings.keys():
if t in types:
n_channel_types += 1
ch_types_used.append(t)
for t in ch_types_used:
scaling = scalings[t]
idx = [i for i in range(len(picks)) if types[i] == t]
if len(idx) > 0:
data[:, idx] *= scaling
else:
# In case some other object gets this mixin w/o an explicit check
raise NameError('Object must be one of Raw, Epochs, Evoked, or ' +
'SourceEstimate. This is {0}'.format(type(self)))
# Make sure that the time index is scaled correctly
times = np.round(times * scaling_time)
mindex.append(('time', times))
if index is not None:
_check_pandas_index_arguments(index, default_index)
else:
index = default_index
if copy is True:
data = data.copy()
assert all(len(mdx) == len(mindex[0]) for mdx in mindex)
df = pd.DataFrame(data, columns=col_names)
for i, (k, v) in enumerate(mindex):
df.insert(i, k, v)
if index is not None:
if 'time' in index:
logger.info('Converting time column to int64...')
df['time'] = df['time'].astype(np.int64)
df.set_index(index, inplace=True)
if all(i in default_index for i in index):
df.columns.name = 'signal'
return df
class TimeMixin(object):
"""Class to add sfreq and time_as_index capabilities to certain classes."""
def time_as_index(self, times, use_rounding=False):
"""Convert time to indices.
Parameters
----------
times : list-like | float | int
List of numbers or a number representing points in time.
use_rounding : boolean
If True, use rounding (instead of truncation) when converting
times to indices. This can help avoid non-unique indices.
Returns
-------
index : ndarray
Indices corresponding to the times supplied.
"""
from ..source_estimate import _BaseSourceEstimate
if isinstance(self, _BaseSourceEstimate):
sfreq = 1. / self.tstep
else:
sfreq = self.info['sfreq']
index = (np.atleast_1d(times) - self.times[0]) * sfreq
if use_rounding:
index = np.round(index)
return index.astype(int)
def _check_fun(fun, d, *args, **kwargs):
"""Check shapes."""
want_shape = d.shape
d = fun(d, *args, **kwargs)
if not isinstance(d, np.ndarray):
raise TypeError('Return value must be an ndarray')
if d.shape != want_shape:
raise ValueError('Return data must have shape %s not %s'
% (want_shape, d.shape))
return d
class BaseRaw(ProjMixin, ContainsMixin, UpdateChannelsMixin,
SetChannelsMixin, InterpolationMixin, ToDataFrameMixin,
TimeMixin, SizeMixin):
"""Base class for Raw data.
Parameters
----------
info : dict
A dict passed from the subclass.
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
Tuple of length one (for unsplit raw files) or length > 1 (for split
raw files).
raw_extras : list
Whatever data is necessary for on-demand reads. For `RawFIF` this means
a list of variables formerly known as ``_rawdirs``.
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 : bool, str, int, or None
If not None, override default verbose level (see :func:`mne.verbose`
and :ref:`Logging documentation <tut_logging>` for more).
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)
See Also
--------
mne.io.Raw : Documentation of attribute and methods.
"""
@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., orig_units=None,
verbose=None): # noqa: D102
# 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('datatype must be float64 or complex128, '
'not %s' % 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 preload is False:
self.preload = False
load_from_disk = False
elif preload is not True and not isinstance(preload, string_types):
raise ValueError('bad preload: %s' % preload)
else:
load_from_disk = True
self._last_samps = np.array(last_samps)
self._first_samps = np.array(first_samps)
info._check_consistency() # make sure subclass did a good job
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('Bad cals for channels %s'
% dict((ii, self.ch_names[ii]) for ii in bad))
self.verbose = verbose
self._cals = cals
self._raw_extras = list(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:
logger.info('Current compensation grade : %d'
% self._read_comp_grade)
self._comp = None
self._filenames = list(filenames)
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('orig_units must be of type dict, but got '
' {}'.format(type(orig_units)))
# original units need to be truncated to 15 chars, which is what
# the MNE IO procedure also does with the other channels
orig_units_trunc = [ch[:15] for ch in orig_units]
# 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 not \
(self.filenames[0].endswith('.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_trunc for ch in ch_names]
if not all(ch_correspond):
ch_without_orig_unit = ch_names[ch_correspond.index(False)]
raise ValueError('Channel {0} has no associated original '
'unit.'.format(ch_without_orig_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
self._projectors = list()
self._projector = None
self._dtype_ = dtype
self.set_annotations(None)
# If we have True or a string, actually do the preloading
self._update_times()
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 : bool, str, int, or None
If not None, override default verbose level (see
:func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
for more).
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_
def _read_segment(self, start=0, stop=None, sel=None, data_buffer=None,
projector=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 : bool, str, int, or None
If not None, override default verbose level (see
:func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
for more).
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
n_sel_channels = self.info['nchan'] if sel is None else len(sel)
assert n_sel_channels <= self.info['nchan']
# convert sel to a slice if possible for efficiency
if sel is not None and len(sel) > 1 and np.all(np.diff(sel) == 1):
sel = slice(sel[0], sel[-1] + 1)
idx = slice(None, None, None) if sel is None else sel
data_shape = (n_sel_channels, stop - start)
dtype = self._dtype
if isinstance(data_buffer, np.ndarray):
if data_buffer.shape != data_shape:
raise ValueError('data_buffer has incorrect shape: %s != %s'
% (data_buffer.shape, data_shape))
data = data_buffer
elif isinstance(data_buffer, string_types):
# use a memmap
data = np.memmap(data_buffer, mode='w+',
dtype=dtype, shape=data_shape)
else:
data = np.zeros(data_shape, dtype=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)
cals = self._cals.ravel()[np.newaxis, :]
if self._comp is not None:
if projector is not None:
mult = self._comp * cals
mult = np.dot(projector[idx], mult)
else:
mult = self._comp[idx] * cals
elif projector is not None:
mult = projector[idx] * cals
else:
mult = None
cals = cals.T[idx]
# 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)
self._read_segment_file(data[:, this_sl], 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``.
Parameters
----------
data : ndarray, shape (len(idx), 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 (len(idx), len(info['chs']) | None
The compensation + projection + cals matrix, if applicable.
"""
raise NotImplementedError
def _check_bad_segment(self, start, stop, picks,
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_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 < stop / sfreq)
overlaps = np.where(onset[overlaps] + annot.duration[overlaps] >
start / sfreq)
for descr in annot.description[overlaps]:
if descr.lower().startswith('bad'):
return descr
return self[picks, start:stop][0]
@verbose
def load_data(self, verbose=None):
"""Load raw data.
Parameters
----------
verbose : bool, str, int, or None
If not None, override default verbose level (see
:func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
for more).
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
@verbose
def _preload_data(self, preload, verbose=None):
"""Actually preload the data."""
data_buffer = preload if isinstance(preload, (string_types,
np.ndarray)) else None
logger.info('Reading %d ... %d = %9.3f ... %9.3f secs...' %
(0, len(self.times) - 1, 0., self.times[-1]))
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()
def _update_times(self):
"""Update times."""
self._times = np.arange(self.n_times) / float(self.info['sfreq'])
# make it immutable
self._times.flags.writeable = False
@property
def _first_time(self):
return self.first_samp / float(self.info['sfreq'])
@property
def first_samp(self):
"""The first data sample."""
return self._first_samps[0]
@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 : boolean
If True, use rounding (instead of truncation) when converting
times to indices. This can help avoid non-unique indices.
origin: time-like | float | int | None
Time reference for times. If None, ``times`` are assumed to be
relative to ``first_samp``.
.. versionadded:: 0.17.0
Returns
-------
index : ndarray
Indices relative to ``first_samp`` corresponding to the times
supplied.
"""
first_samp_in_abs_time = (_handle_meas_date(self.info['meas_date']) +
self._first_time)
if origin is None:
origin = first_samp_in_abs_time
absolute_time = np.atleast_1d(times) + _handle_meas_date(origin)
times = (absolute_time - first_samp_in_abs_time)
return super(BaseRaw, self).time_as_index(times, use_rounding)
@property
def _raw_lengths(self):
return [l - f + 1 for f, l 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):
"""The filenames used."""
return tuple(self._filenames)
@annotations.setter
def annotations(self, annotations, emit_warning=True):
warn('setting the annotations attribute by assignment is'
' deprecated since 0.17, and will be removed in 0.18.'
' Please use raw.set_annotations() instead.',
category=DeprecationWarning)
self.set_annotations(annotations, emit_warning=emit_warning)
def set_annotations(self, annotations, emit_warning=True, sync_orig=True):
"""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 : bool
Whether to emit warnings when limiting or omitting annotations.
sync_orig : bool
Whether to sync ``self.annotations.orig_time`` with
``self.info['meas_date']``, or not. This parameter is meant to be
True, and toggled to False only to achieve backward compatibility,
and will be removed in version 0.18.
Defaults to True.
.. versionadded:: 0.17
Returns
-------
self : instance of Raw
The raw object with annotations.
"""
if sync_orig is False:
warn(('Unsynchronized orig_time and meas_date is deprecated and'
' will be removed 0.18.'), DeprecationWarning)
if annotations is None:
self._annotations = Annotations([], [], [])
else:
_ensure_annotation_object(annotations)
if self.info['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.')
meas_date = _handle_meas_date(self.info['meas_date'])
delta = 1. / self.info['sfreq']
time_of_first_sample = meas_date + self.first_samp * delta
new_annotations = annotations.copy()
if annotations.orig_time is None:
# Assume annotations to be relative to the data
new_annotations.orig_time = time_of_first_sample
tmin = time_of_first_sample
tmax = tmin + self.times[-1] + delta
new_annotations.crop(tmin=tmin, tmax=tmax,
emit_warning=emit_warning)
if self.info['meas_date'] is None:
new_annotations.orig_time = None
elif sync_orig and annotations.orig_time != meas_date:
# XXX, TODO: this should be a function, method or something.
# maybe orig_time should have a setter
# new_annotations.orig_time = xxxxx # resets onset based on x
# new_annotations._update_orig(xxxx)
orig_time = new_annotations.orig_time
new_annotations.orig_time = meas_date
new_annotations.onset -= (meas_date - orig_time)
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)")
if isinstance(item[0], slice):
start = item[0].start if item[0].start is not None else 0
nchan = self.info['nchan']
if start < 0:
start += nchan
if start < 0:
raise ValueError('start must be >= -%s' % nchan)
stop = item[0].stop if item[0].stop is not None else nchan
if stop < 0:
stop += nchan
if stop < 0:
raise ValueError('stop must be >= -%s' % nchan)
stop = min(stop, nchan) # slices can legally exceed max
step = item[0].step if item[0].step is not None else 1
sel = list(range(start, stop, step))
else:
sel = 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
else:
raise ValueError('Must pass int or slice to __getitem__')
if start is None:
start = 0
if (step is not None) and (step is not 1):
raise ValueError('step needs to be 1 : %d given' % step)
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
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,
projector=self._projector,
verbose=self.verbose)
times = self.times[start:stop]
return data, times
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
def get_data(self, picks=None, start=0, stop=None,
reject_by_annotation=None, return_times=False):
"""Get data in the given range.
Parameters
----------
picks : array-like of int | None
Indices of channels to get data from. If None, data from all
channels is returned
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.
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
"""
if picks is None:
picks = np.arange(self.info['nchan'])
start = 0 if start is None else start
stop = min(self.n_times if stop is None else stop, self.n_times)
if len(self.annotations) == 0 or reject_by_annotation is None:
data, times = self[picks, start:stop]
return (data, times) if return_times else data
if reject_by_annotation.lower() not in ['omit', 'nan']:
raise ValueError("reject_by_annotation must be None, 'omit' or "
"'NaN'. Got %s." % reject_by_annotation)
onsets, ends = _annotations_starts_stops(self, ['BAD'])