Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
on decimated data. This is legitimate because the linear model does
not have any representation of time, only the distributions
matter.
Parameters
----------
raw : instance of Raw
The BTi/4D raw data.
decim_fit : int
The decimation factor used for fitting the model.
Defaults to 100.
"""
from sklearn.linear_model import LinearRegression
meg_picks = mne.pick_types(raw.info, ref_meg=False, meg=True)
ref_picks = mne.pick_types(raw.info, ref_meg=True, meg=False)
if len(ref_picks) == 0:
raise ValueError('Could not find meg ref channels.')
estimator = LinearRegression(normalize=True) # ref MAG + GRAD
Y_pred = estimator.fit(
raw[ref_picks][0][:, ::decim_fit].T,
raw[meg_picks][0][:, ::decim_fit].T).predict(
raw[ref_picks][0].T)
raw._data[meg_picks] -= Y_pred.T
# Generate times series from 2 Morlet wavelets
stc_data = np.zeros((len(labels), len(times)))
Ws = morlet(sfreq, freqs, n_cycles=n_cycles)
stc_data[0][:len(Ws[0])] = np.real(Ws[0] * np.exp(1j * phases[0]))
stc_data[1][:len(Ws[1])] = np.real(Ws[1] * np.exp(1j * phases[1]))
stc_data *= 100 * 1e-9 # use nAm as unit
# time translation
stc_data[0] = np.roll(stc_data[0], offsets[0])
stc_data[1] = np.roll(stc_data[1], offsets[1])
stc = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep,
random_state=0)
###############################################################################
# Generate noisy evoked data
picks = mne.pick_types(raw.info, meg=True, exclude='bads')
if white:
iir_filter = None # for white noise
else:
iir_filter = iir_filter_raw(raw, order=5, picks=picks, tmin=60, tmax=180)
evoked = generate_evoked(fwd, stc, evoked_template, cov, snr,
tmin=0.0, tmax=0.2, iir_filter=iir_filter, random_state=seed)
return evoked
def load_data(sfreq=sfreq):
data_path = os.path.join(mne.datasets.somato.data_path(), 'MEG', 'somato')
raw = mne.io.read_raw_fif(
os.path.join(data_path, 'sef_raw_sss.fif'), preload=True)
raw.filter(2., 90., n_jobs=n_jobs)
raw.notch_filter(np.arange(50, 101, 50), n_jobs=n_jobs)
events = mne.find_events(raw, stim_channel='STI 014')
event_id, tmin, tmax = 1, -1., 3.
baseline = (None, 0)
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True,
stim=False)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
picks=picks, baseline=baseline, reject=dict(
grad=4000e-13, eog=350e-6), preload=True)
epochs.pick_types(meg='grad', eog=False)
epochs.resample(sfreq, npad='auto')
# define n_channels, n_trials, n_times
X = epochs.get_data()
n_trials, n_channels, n_times = X.shape
X *= tukey(n_times, alpha=0.1)[None, None, :]
X /= np.std(X)
return X
subject=subject, data_type=data_type, hcp_path=hcp_path,
run_index=run_index if run_index is None else run_index)
except (ValueError, IOError):
raise ValueError(
'could not find config to complete info.'
'reading only channel positions without '
'transforms.')
# full BTI MEG channels
bti_meg_channel_names = ['A%i' % ii for ii in range(1, 249, 1)]
# figure out which channels are missing
bti_meg_channel_missing_names = [
ch for ch in bti_meg_channel_names if ch not in inst.ch_names]
# get meg picks
picks_meg = mne.pick_types(inst.info, meg=True, ref_meg=False)
# some non-contiguous block in the middle so let's try to invert
picks_other = [ii for ii in range(len(inst.ch_names)) if ii not in
picks_meg]
other_chans = [inst.ch_names[po] for po in picks_other]
# compute new n channels
n_channels = (len(picks_meg) +
len(bti_meg_channel_missing_names) +
len(other_chans))
# restrict info to final channels
# ! info read from config file is not sorted like inst.info
# ! therefore picking order matters, but we don't know it.
# ! so far we will rely on the consistent layout for raw files
final_names = [ch for ch in _data_labels if ch in bti_meg_channel_names or
ch in other_chans]
###############################################################################
# We can then read in the events
event_fname = data_path + ('/MEG/sample/sample_audvis_filt-0-40_raw-'
'eve.fif')
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2}
tmin, tmax = -0.2, 0.5
events = mne.read_events(event_fname)
###############################################################################
# And pick MEG channels for repairing. Currently, :mod:`autoreject` can repair
# only one channel type at a time.
raw.info['bads'] = []
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=False,
include=[], exclude=[])
###############################################################################
# Now, we can create epochs. The ``reject`` params will be set to ``None``
# because we do not want epochs to be dropped when instantiating
# :class:`mne.Epochs`.
raw.info['projs'] = list() # remove proj, don't proj while interpolating
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
baseline=(None, 0), reject=None,
verbose=False, detrend=0, preload=True)
###############################################################################
# :class:`autoreject.AutoReject` internally does cross-validation to
# determine the optimal values :math:`\rho^{*}` and :math:`\kappa^{*}`
###############################################################################
TODO:
* sfreq from timestamps? (not nominal)
"""
Transformer.__init__(self, buffer_in=buffer_in)
channel_types = [source_type] * len(buffer_in.ch_names)
self.source_type = source_type
self.info = mne.create_info(buffer_in.ch_names, sfreq, channel_types)
self._sfreq = sfreq
if source_type == 'eeg':
self.montage = mne.channels.read_montage(montage,
ch_names=buffer_in.ch_names)
if not source_type == 'meg':
# MNE defaults to `meg=True` and everything else `False`...
self.picks = mne.pick_types(self.info, meg=False,
**{source_type: True})
else:
self.picks = mne.pick_types(self.info)
self.scaling = scaling
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_ids = {'AudL': 1, 'AudR': 2, 'VisL': 3, 'VisR': 4}
tmin = -0.2
tmax = 0.5
# Setup for reading the raw data
raw = io.Raw(raw_fname)
events = mne.read_events(event_fname)
# Set up pick list: EEG + STI 014 - bad channels (modify to your needs)
include = [] # or stim channels ['STI 014']
raw.info['bads'] += ['EEG 053'] # bads + 1 more
# pick EEG channels
picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=True,
include=include, exclude='bads')
# Read epochs
epochs = mne.Epochs(raw, events, event_ids, tmin, tmax, picks=picks,
baseline=(None, 0), reject=dict(eeg=80e-6, eog=150e-6))
# Let's equalize the trial counts in each condition
epochs.equalize_event_counts(['AudL', 'AudR', 'VisL', 'VisR'], copy=False)
# Now let's combine some conditions
combine_event_ids(epochs, ['AudL', 'AudR'], {'Auditory': 12}, copy=False)
combine_event_ids(epochs, ['VisL', 'VisR'], {'Visual': 34}, copy=False)
# average epochs and get Evoked datasets
evokeds = [epochs[cond].average() for cond in ['Auditory', 'Visual']]
# save evoked data to disk
mne.write_evokeds('sample_auditory_and_visual_eeg-ave.fif', evokeds)
data_path = sample.data_path()
###############################################################################
# Set parameters and read data
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.2, 0.5
event_id = dict(aud_l=1, vis_l=3)
# Setup for reading the raw data
raw = io.Raw(raw_fname, preload=True)
raw.filter(2, None, method='iir') # replace baselining with high-pass
events = mne.read_events(event_fname)
raw.info['bads'] = ['MEG 2443'] # set bad channels
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=False,
exclude='bads')
# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=False,
picks=picks, baseline=None, preload=True)
labels = epochs.events[:, -1]
evoked = epochs.average()
###############################################################################
# Decoding in sensor space using a MDM
n_components = 3 # pick some components
# Define a monte-carlo cross-validation generator (reduce variance):
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id = {'Aud_L': 1, 'Aud_R': 2, 'Vis_L': 3, 'Vis_R': 4}
tmin = -0.2
tmax = 0.5
# Setup for reading the raw data
raw = mne.io.Raw(raw_fname, preload=True)
raw.filter(1, 30)
events = mne.read_events(event_fname)
###############################################################################
# Read epochs for the channel of interest
picks = mne.pick_types(raw.info, meg='mag', eog=True)
reject = dict(mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=None, reject=reject, preload=True)
epochs.drop_channels(['EOG 061'])
epochs.equalize_event_counts(event_id, copy=False)
condition_names = 'Aud_L', 'Aud_R', 'Vis_L', 'Vis_R'
X = [epochs[k].get_data() for k in condition_names] # as 3D matrix
X = [np.transpose(x, (0, 2, 1)) for x in X] # transpose for clustering
###############################################################################
# load FieldTrip neighbor definition to setup sensor connectivity
connectivity, ch_names = read_ch_connectivity('neuromag306mag')
###############################################################################
# Set parameters and read data
###############################################################################
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0., 1
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)
# Setup for reading the raw data
raw = io.Raw(raw_fname, preload=True)
raw.filter(2, None, method='iir') # replace baselining with high-pass
events = mne.read_events(event_fname)
raw.info['bads'] = ['MEG 2443'] # set bad channels
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=False,
exclude='bads')
# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=False,
picks=picks, baseline=None, preload=True, verbose=False)
labels = epochs.events[::5, -1]
# get epochs
epochs_data = epochs.get_data()[::5]
n_perms = 100
###############################################################################
# Pairwise distance based permutation test
###############################################################################
t_init = time()