コード例 #1
0
def test_apply_forward():
    """Test projection of source space data to sensor space."""
    start = 0
    stop = 5
    n_times = stop - start - 1
    sfreq = 10.0
    t_start = 0.123

    fwd = read_forward_solution(fname_meeg)
    fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                   use_cps=True)
    fwd = pick_types_forward(fwd, meg=True)
    assert isinstance(fwd, Forward)

    vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
    stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
    stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)

    gain_sum = np.sum(fwd['sol']['data'], axis=1)

    # Evoked
    evoked = read_evokeds(fname_evoked, condition=0)
    evoked.pick_types(meg=True)
    with pytest.warns(RuntimeWarning, match='only .* positive values'):
        evoked = apply_forward(fwd, stc, evoked.info, start=start, stop=stop)
    data = evoked.data
    times = evoked.times

    # do some tests
    assert_array_almost_equal(evoked.info['sfreq'], sfreq)
    assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
    assert_array_almost_equal(times[0], t_start)
    assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)

    # vector
    stc_vec = VectorSourceEstimate(
        fwd['source_nn'][:, :, np.newaxis] * stc.data[:, np.newaxis],
        stc.vertices, stc.tmin, stc.tstep)
    with pytest.warns(RuntimeWarning, match='very large'):
        evoked_2 = apply_forward(fwd, stc_vec, evoked.info)
    assert np.abs(evoked_2.data).mean() > 1e-5
    assert_allclose(evoked.data, evoked_2.data, atol=1e-10)

    # Raw
    with pytest.warns(RuntimeWarning, match='only .* positive values'):
        raw_proj = apply_forward_raw(fwd, stc, evoked.info, start=start,
                                     stop=stop)
    data, times = raw_proj[:, :]

    # do some tests
    assert_array_almost_equal(raw_proj.info['sfreq'], sfreq)
    assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
    atol = 1. / sfreq
    assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol)
    assert_allclose(raw_proj.last_samp / sfreq,
                    t_start + (n_times - 1) / sfreq, atol=atol)
コード例 #2
0
def test_load_fiff_mne():
    data_path = mne.datasets.sample.data_path()
    fwd_path = os.path.join(data_path, 'MEG', 'sample', 'sample-ico-4-fwd.fif')
    evoked_path = os.path.join(data_path, 'MEG', 'sample',
                               'sample_audvis-no-filter-ave.fif')
    cov_path = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
    mri_sdir = os.path.join(data_path, 'subjects')

    mne_evoked = mne.read_evokeds(evoked_path, 'Left Auditory')
    mne_fwd = mne.read_forward_solution(fwd_path)
    mne_fwd = mne.convert_forward_solution(mne_fwd, force_fixed=True, use_cps=True)
    cov = mne.read_cov(cov_path)

    picks = mne.pick_types(mne_evoked.info, 'mag')
    channels = [mne_evoked.ch_names[i] for i in picks]

    mne_evoked = mne_evoked.pick_channels(channels)
    mne_fwd = mne.pick_channels_forward(mne_fwd, channels)
    cov = mne.pick_channels_cov(cov, channels)

    mne_inv = mne.minimum_norm.make_inverse_operator(mne_evoked.info, mne_fwd,
                                                     cov, 0, None, True)

    mne_stc = mne.minimum_norm.apply_inverse(mne_evoked, mne_inv, 1., 'MNE')

    meg = load.fiff.evoked_ndvar(mne_evoked)
    inv = load.fiff.inverse_operator(mne_inv, 'ico-4', mri_sdir)
    stc = inv.dot(meg)
    assert_array_almost_equal(stc.get_data(('source', 'time')), mne_stc.data)

    fwd = load.fiff.forward_operator(mne_fwd, 'ico-4', mri_sdir)
    reconstruct = fwd.dot(stc)
    mne_reconstruct = mne.apply_forward(mne_fwd, mne_stc, mne_evoked.info)
    assert_array_almost_equal(reconstruct.get_data(('sensor', 'time')),
                              mne_reconstruct.data)
コード例 #3
0
 def apply_foward_model(self, x):
     out = []
     for z in x:
         info = mne.io.read_info(self.raw_fname)
         stc = mne.SourceEstimate(z.cpu().detach().numpy(),
                                  self.vertices,
                                  tmin=0.,
                                  tstep=self.time_step)
         # print("STC", stc)
         # print("Info", info)
         leadfield = mne.apply_forward(self.fwd_fixed, stc,
                                       info).data[0:self.num_nodes]
         # leadfield = torch.from_numpy(leadfield)
         # leadfield = leadfield.transpose(0,1)
         # print("YOUYOUYOUYOUY")
         # array = leadfield.to_data_frame().values
         # print("array", leadfield.shape)
         out += [leadfield]
     out = np.asarray(out)
     out = torch.from_numpy(out).transpose(1, 2)
     if x.is_cuda:
         out = out.type(torch.cuda.FloatTensor)
     else:
         out = out.type(torch.FloatTensor)
     # print("OUTOUTOUT", out.shape)
     # (n sensors, n samples)
     return out
コード例 #4
0
 def generate_eeg(self, source_index):
     stc = mne.SourceEstimate(self.preloaded_examples_source[source_index],
                              self.vertices,
                              tmin=0.,
                              tstep=1 / 250)
     leadfield = mne.apply_forward(self.fwd_fixed, stc,
                                   self.info).data / 1e-9
     return list(leadfield[:self.num_channels])
コード例 #5
0
def test_apply_forward():
    """Test projection of source space data to sensor space
    """
    start = 0
    stop = 5
    n_times = stop - start - 1
    sfreq = 10.0
    t_start = 0.123

    fwd = read_forward_solution(fname_meeg)
    fwd = convert_forward_solution(fwd,
                                   surf_ori=True,
                                   force_fixed=True,
                                   use_cps=True)
    fwd = pick_types_forward(fwd, meg=True)
    assert_true(isinstance(fwd, Forward))

    vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
    stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
    stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)

    gain_sum = np.sum(fwd['sol']['data'], axis=1)

    # Evoked
    with warnings.catch_warnings(record=True) as w:
        evoked = read_evokeds(fname_evoked, condition=0)
        evoked.pick_types(meg=True)
        evoked = apply_forward(fwd, stc, evoked.info, start=start, stop=stop)
        assert_equal(len(w), 2)
        data = evoked.data
        times = evoked.times

        # do some tests
        assert_array_almost_equal(evoked.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)

        # Raw
        raw_proj = apply_forward_raw(fwd,
                                     stc,
                                     evoked.info,
                                     start=start,
                                     stop=stop)
        data, times = raw_proj[:, :]

        # do some tests
        assert_array_almost_equal(raw_proj.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        atol = 1. / sfreq
        assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol)
        assert_allclose(raw_proj.last_samp / sfreq,
                        t_start + (n_times - 1) / sfreq,
                        atol=atol)
コード例 #6
0
ファイル: test_forward.py プロジェクト: nfoti/mne-python
def test_apply_forward():
    """Test projection of source space data to sensor space
    """
    start = 0
    stop = 5
    n_times = stop - start - 1
    sfreq = 10.0
    t_start = 0.123

    fwd = read_forward_solution(fname_meeg)
    fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                   use_cps=True)
    fwd = pick_types_forward(fwd, meg=True)
    assert_true(isinstance(fwd, Forward))

    vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
    stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
    stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)

    gain_sum = np.sum(fwd['sol']['data'], axis=1)

    # Evoked
    with warnings.catch_warnings(record=True) as w:
        evoked = read_evokeds(fname_evoked, condition=0)
        evoked.pick_types(meg=True)
        evoked = apply_forward(fwd, stc, evoked.info, start=start, stop=stop)
        assert_equal(len(w), 2)
        data = evoked.data
        times = evoked.times

        # do some tests
        assert_array_almost_equal(evoked.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)

        # Raw
        raw_proj = apply_forward_raw(fwd, stc, evoked.info, start=start,
                                     stop=stop)
        data, times = raw_proj[:, :]

        # do some tests
        assert_array_almost_equal(raw_proj.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        atol = 1. / sfreq
        assert_allclose(raw_proj.first_samp / sfreq, t_start, atol=atol)
        assert_allclose(raw_proj.last_samp / sfreq,
                        t_start + (n_times - 1) / sfreq, atol=atol)
コード例 #7
0
def make_surrogates_empty_room(raw, fwd, inverse_operator, step=10000):
    """Create spatially structured noise from empty room MEG

    .. note::
        Convert MEG empty room to spatially structured noise by applying
        the inverse solution and then the forward solution.

    .. note::
        To safe memory, projection proceeds in non-overlapping sliding windows.

    Parameters
    ----------
    raw : instance of mne.io.Raw
        The raw data (empty room).
    fwd : instance of mne.Forward
        The forward solution
    inverse_operator : mne.minimum_norm.InverseOperator
        The inverse solution.
    step : int
        The step size (in samples) when iterating over the raw object.

    Returns
    -------
    raw_surr : instance of mne.io.Raw
        The surrogate MEG data.
    """
    index = np.arange(len(raw.times)).astype(int)
    out = np.empty(raw.get_data().shape, dtype=raw.get_data().dtype)
    picks = mne.pick_types(raw.info, meg=True, eeg=True, ref_meg=False)
    other_picks = [ii for ii in range(len(raw.ch_names)) if ii not in picks]
    out[other_picks] = raw.get_data()[other_picks]
    last = len(index)
    for start in index[::step]:
        stop = start + min(step, last - start)
        stc = mne.minimum_norm.apply_inverse_raw(raw,
                                                 inverse_operator,
                                                 lambda2=1.0,
                                                 method='MNE',
                                                 start=start,
                                                 stop=stop,
                                                 pick_ori="normal")
        reprojected = mne.apply_forward(fwd=fwd, stc=stc, info=raw.info)
        out[picks, start:stop] = reprojected.data
    out = mne.io.RawArray(out, info=copy.deepcopy(raw.info))
    return out
コード例 #8
0
def generate_data(num_examples, data_dir, fwd_fixed, n_sensors=60, fs_gen=200, n_times=10, frequency=200, prefix="generated-"):
	leadfield = fwd_fixed['sol']['data']

	n_dipoles = leadfield.shape[1]
	vertices = [src_hemi['vertno'] for src_hemi in fwd_fixed['src']]

	time_step = 1.0/fs_gen # sample freq = 200 was 0.5
	n_times = 10 * fs_gen  # try 10 s of generation
	channel_names = [str(i) for i in range(60)]

	for i in range(num_examples):
		z = np.dot(np.random.randn(n_dipoles, n_sensors), np.random.randn(n_sensors, n_times)) * 1e-9
		filename = data_dir + "/"  + prefix + str(i) + "raw.fif"
		stc = mne.SourceEstimate(z, vertices, tmin=0., tstep=time_step)
		leadfield = mne.apply_forward(fwd_fixed, stc, info).data
		# save_data(leadfield, filename, channel_names, frequency)
		print("i: " + str(i) + " - " + str(int((i+1) * 100/num_examples)) + "%")
	print("finished")
コード例 #9
0
ファイル: test_forward.py プロジェクト: jaidevd/mne-python
def test_apply_forward():
    """Test projection of source space data to sensor space
    """
    start = 0
    stop = 5
    n_times = stop - start - 1
    sfreq = 10.0
    t_start = 0.123

    fwd = read_forward_solution(fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True)

    vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
    stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
    stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)

    gain_sum = np.sum(fwd['sol']['data'], axis=1)

    # Evoked
    with warnings.catch_warnings(record=True) as w:
        evoked = Evoked(fname_evoked, setno=0)
        evoked = apply_forward(fwd, stc, evoked, start=start, stop=stop)
        assert_equal(len(w), 2)
        data = evoked.data
        times = evoked.times

        # do some tests
        assert_array_almost_equal(evoked.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)

        # Raw
        raw = Raw(fname_raw)
        raw_proj = apply_forward_raw(fwd, stc, raw, start=start, stop=stop)
        data, times = raw_proj[:, :]

        # do some tests
        assert_array_almost_equal(raw_proj.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)
コード例 #10
0
ファイル: test_forward.py プロジェクト: Anevar/mne-python
def test_apply_forward():
    """Test projection of source space data to sensor space
    """
    start = 0
    stop = 5
    n_times = stop - start - 1
    sfreq = 10.0
    t_start = 0.123

    fwd = read_forward_solution(fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True)

    vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
    stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
    stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)

    gain_sum = np.sum(fwd['sol']['data'], axis=1)

    # Evoked
    with warnings.catch_warnings(record=True) as w:
        evoked = Evoked(fname_evoked, setno=0)
        evoked = apply_forward(fwd, stc, evoked, start=start, stop=stop)
        assert_equal(len(w), 2)
        data = evoked.data
        times = evoked.times

        # do some tests
        assert_array_almost_equal(evoked.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)

        # Raw
        raw = Raw(fname_raw)
        raw_proj = apply_forward_raw(fwd, stc, raw, start=start, stop=stop)
        data, times = raw_proj[:, :]

        # do some tests
        assert_array_almost_equal(raw_proj.info['sfreq'], sfreq)
        assert_array_almost_equal(np.sum(data, axis=1), n_times * gain_sum)
        assert_array_almost_equal(times[0], t_start)
        assert_array_almost_equal(times[-1], t_start + (n_times - 1) / sfreq)
コード例 #11
0
true_locs = list()
for v in vertices:
    true_locs.append(np.where(vertno == v[0])[0][0])

# Construct SourceEstimates that describe the signals at the cortical level.
stc_signal = mne.SourceEstimate(q,
                                vertices,
                                tmin=0,
                                tstep=1. / sfreq,
                                subject='sample')

###############################################################################
# Now we run the signal through the forward model to obtain simulated sensor
# data. We then corrupt the resulting simulated gradiometer recordings
# by empty room noise.
evoked = mne.apply_forward(fwd, stc_signal, info)
mne.simulation.add_noise(evoked, noise_cov, random_state=rand)

###############################################################################
# Visualize the data
evoked.plot()

###############################################################################
# Define the parameters and apply SESAME. We convert the data to the frequency
# domain by setting ``Fourier_transf=True``.

n_parts = 100
noise_std = None
dip_mom_std = None
freq_min = 9.5
freq_max = 10.5
コード例 #12
0
ファイル: plot_forward.py プロジェクト: nfoti/mne-python
# To extract the numpy array containing the forward operator corresponding to
# the source space `fwd['src']` with cortical orientation constraint
# we can use the following:

fwd_fixed = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                         use_cps=True)
leadfield = fwd_fixed['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)

###############################################################################
# This is equivalent to the following code that explicitly applies the
# forward operator to a source estimate composed of the identity operator:
n_dipoles = leadfield.shape[1]
vertices = [src_hemi['vertno'] for src_hemi in fwd_fixed['src']]
stc = mne.SourceEstimate(1e-9 * np.eye(n_dipoles), vertices, tmin=0., tstep=1)
leadfield = mne.apply_forward(fwd_fixed, stc, info).data / 1e-9

###############################################################################
# To save to disk a forward solution you can use
# :func:`mne.write_forward_solution` and to read it back from disk
# :func:`mne.read_forward_solution`. Don't forget that FIF files containing
# forward solution should end with *-fwd.fif*.
#
# To get a fixed-orientation forward solution, use
# :func:`mne.convert_forward_solution` to convert the free-orientation
# solution to (surface-oriented) fixed orientation.

###############################################################################
# Exercise
# --------
#
コード例 #13
0
ファイル: test.py プロジェクト: sanrou/fidelityWeighting

def data_fun(times):
    """Function to generate random source time courses"""
    rng = np.random.RandomState(42)
    return (50e-9 * np.sin(30. * times) *
            np.exp(-(times - 0.15 + 0.05 * rng.randn(1))**2 / 0.01))


simulated_stc = simulate_sparse_stc(
    fwd['src'], n_dipoles=2, times=times, random_state=42, data_fun=data_fun
)  # Gives an error later if n_dipoles = 1, as it puts a source only to the right hemisphere.

evoked = apply_forward(fwd=fwd_fixed,
                       stc=simulated_stc,
                       info=fwd_fixed['info'],
                       use_cps=True,
                       verbose=True)
"""Visualize dipole locations."""
surf = 'inflated'
brain = Brain(subject_id=subject,
              subjects_dir=subjects_dir,
              hemi='both',
              surf=surf)

brain.add_foci(coords=simulated_stc.lh_vertno,
               coords_as_verts=True,
               hemi='lh',
               map_surface=surf,
               color='red')
brain.add_foci(coords=simulated_stc.rh_vertno,
コード例 #14
0
z[stimulate_sites, :] = z[stimulate_sites, :] + source_scale * np.sin(
    2 * np.pi * 10.0 * t)

# determine vertex number of ??? something in the fwd_fixed solution
# vertices = [src_hemi['vertno'] for src_hemi in fwd_fixed['src']]
#len(vertices)
#vertices

# SourceEstimate(data, vertices=None, tmin=None, tstep=None,
#               subject=None, verbose=None
# data: array of shape (n_dipoles, n_times)
#       | 2-tuple (kernel, sens_data)
# vertices: list of two arrays with vertex numbers corresponding to the data

srcest = mne.SourceEstimate(z, vertices, tmin=0., tstep=time_step)
gen_eeg = mne.apply_forward(fwd_fixed, srcest, info)  # / np.sum(z, axis=1)

gen_eeg.data.shape

fig = gen_eeg.plot(exclude=(), time_unit='s')

picks = mne.pick_types(gen_eeg.info, meg=False, eeg=True, eog=False)
gen_eeg.plot(spatial_colors=True, gfp=True, picks=picks, time_unit='s')
gen_eeg.plot_topomap(time_unit='s')

signals = gen_eeg.data
electrode_labels = list(range(n_sensors))
ch0, ch1 = (0, 59)
DE = 1  # how many 10s epochs to display
epoch = 0
ptepoch = 10 * int(fs_gen)
コード例 #15
0
# Random source

# In[75]:


z = np.dot(np.random.randn(n_dipoles, n_sensors), np.random.randn(n_sensors, n_times)) * 1e-9


# In[76]:


# n_dipoles = leadfield.shape[1]
vertices = [src_hemi['vertno'] for src_hemi in fwd_fixed['src']]
# z = np.random.randn(n_dipoles, n_dipoles) * 1e-9
stc = mne.SourceEstimate(z, vertices, tmin=0., tstep=time_step)
leadfield_data = mne.apply_forward(fwd_fixed, stc, info).data # / np.sum(z, axis=1)


# In[13]:


leadfield_data.shape


# In[77]:


leadfield = mne.apply_forward(fwd_fixed, stc, info)


# In[97]:
コード例 #16
0
# we can use the following:

fwd_fixed = mne.convert_forward_solution(fwd,
                                         surf_ori=True,
                                         force_fixed=True,
                                         use_cps=True)
leadfield = fwd_fixed['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)

#%%##############################################################################
# This is equivalent to the following code that explicitly applies the
# forward operator to a source estimate composed of the identity operator:
n_dipoles = leadfield.shape[1]
vertices = [src_hemi['vertno'] for src_hemi in fwd_fixed['src']]
stc = mne.SourceEstimate(1e-9 * np.eye(n_dipoles), vertices, tmin=0., tstep=1)
leadfield = mne.apply_forward(fwd_fixed, stc, info).data / 1e-9

#%%##############################################################################
# To save to disk a forward solution you can use
# :func:`mne.write_forward_solution` and to read it back from disk
# :func:`mne.read_forward_solution`. Don't forget that FIF files containing
# forward solution should end with *-fwd.fif*.
#
# To get a fixed-orientation forward solution, use
# :func:`mne.convert_forward_solution` to convert the free-orientation
# solution to (surface-oriented) fixed orientation.

###############################################################################
# Exercise
# --------
#
コード例 #17
0
 def generate_source_then_eeg(self):
     source = np.random.randn(self.n_dipoles, self.length) * 1e-9
     stc = mne.SourceEstimate(source, self.vertices, tmin=0., tstep=1 / 250)
     leadfield = mne.apply_forward(self.fwd_fixed, stc,
                                   self.info).data / 1e-9
     return list(leadfield[:self.num_channels])