Esempio n. 1
0
    def transform(self, X):
        from mne.beamformer import apply_lcmv_epochs
        mne.set_log_level('WARNING')
        epochs = mne.EpochsArray(X, self.info, verbose=False)
        epochs.filter(self.filter_specs['lp'],
                      self.filter_specs['hp'],
                      fir_design='firwin',
                      n_jobs=self.n_jobs)
        stcs = apply_lcmv_epochs(epochs,
                                 self.filters,
                                 return_generator=True,
                                 max_ori_out='signed',
                                 verbose=False)
        stcs_mat = np.ones((X.shape[0], self.fwd['nsource'], X.shape[2]))
        for trial in range(X.shape[0]):
            stcs_mat[trial, :, :] = next(stcs).data

        # make an epoch
        # epochs_stcs = source2epoch(stcs_mat, self.fwd['nsource'],
        #                            self.info['sfreq'])
        # epochs_stcs.filter(self.filter_specs['lp'], self.filter_specs['hp'],
        #                    n_jobs=self.n_jobs)

        if self.power_win is None:
            self.power_win = self.t_win
        time_idx = epochs.time_as_index(self.power_win)

        # stcs_mat is [trials, grid points, time points]
        return np.sum(stcs_mat[:, :, time_idx[0]:time_idx[1]]**2, axis=2)
Esempio n. 2
0
def run_lcmv_epochs(epochs, fwd, data_cov, reg, noise_cov=None,
                    pick_ori='max-power', weight_norm='nai', verbose=False):
    """Run LCMV on epochs.

    Run weight-normalized LCMV beamformer on epoch data, will return matrix of
    trials or stc object.

    Parameters:
    -----------
    epochs : MNE epochs
        epochs to source reconstruct.
    fwd : MNE forward model
        forward model.
    data_cov : MNE covariance estimate
        data covariance matrix
    reg : float
        regularization parameter
    noise_cov : MNE covariance estimate
        noise covariance matrix, optional
    verbose : bool
        overrides default verbose level, defaults to False, i.e., no logger
        info.

    Returns
    -------
    stcs_mat : numpy array
        matrix with all source trials
    stc : MNE stc
        single trial stc object (last trial)
    filters : dict
        spatial filter used in computation
    """
    filters = make_lcmv(epochs.info, fwd, data_cov=data_cov,
                        noise_cov=noise_cov, pick_ori=pick_ori, reg=reg,
                        weight_norm=weight_norm, verbose=verbose)

    # apply that filter to epochs
    stcs = apply_lcmv_epochs(epochs, filters, return_generator=True,
                             max_ori_out='signed', verbose=verbose)

    # preallocate matrix
    stcs_mat = np.ones((epochs._data.shape[0], fwd['nsource'],
                        len(epochs.times)))

    if verbose is False:
        mne.set_log_level('WARNING')

    # resolve generator
    for trial in range(epochs._data.shape[0]):
        # last time: also save stc
        if trial == 0:
            stc = next(stcs)
            stcs_mat[trial, :, :] = stc.data
        else:
            stcs_mat[trial, :, :] = next(stcs).data

    return stcs_mat, stc, filters
Esempio n. 3
0
    def transform(self, X):
        from mne.beamformer import apply_lcmv_epochs
        mne.set_log_level('WARNING')
        epochs = mne.EpochsArray(X, self.info, tmin=self.tmin, verbose=False)
        stcs = apply_lcmv_epochs(epochs,
                                 self.filters,
                                 return_generator=True,
                                 max_ori_out='signed',
                                 verbose=False)
        stcs_mat = np.ones((X.shape[0], self.fwd['nsource'], X.shape[2]))
        for trial in range(X.shape[0]):
            stcs_mat[trial, :, :] = next(stcs).data

        # stcs_mat is [trials, grid points, time points]
        if self.erp is False:
            time_idx_a = epochs.time_as_index(self.power_win[0])
            time_idx_b = epochs.time_as_index(self.power_win[1])
            return np.mean((stcs_mat[:, :, time_idx_a[0]:time_idx_b[0]]**2),
                           axis=2)
        else:
            return np.squeeze(stcs_mat[:, :, self.time_idx])
Esempio n. 4
0
    def transform(self, X):
        from scipy import signal
        from mne.beamformer import apply_lcmv_epochs
        mne.set_log_level('WARNING')
        hilbert_X = np.abs(signal.hilbert(X))
        epochs = mne.EpochsArray(hilbert_X, self.info, verbose=False)
        stcs = apply_lcmv_epochs(epochs,
                                 self.filters,
                                 return_generator=True,
                                 max_ori_out='signed',
                                 verbose=False)
        stcs_mat = np.ones((X.shape[0], self.fwd['nsource'], X.shape[2]))
        for trial in range(X.shape[0]):
            stcs_mat[trial, :, :] = next(stcs).data

        # stcs_mat is [trials, grid points, time points]
        if self.power_win is None:
            self.power_win = self.t_win
        time_idx = epochs.time_as_index(self.power_win)

        return np.mean(stcs_mat[:, :, time_idx[0]:time_idx[1]]**2, axis=2)
Esempio n. 5
0
def test_make_lcmv(tmpdir, reg, proj):
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data(proj=proj)

    for fwd in [forward, forward_vol]:
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg,
                            noise_cov=noise_cov)
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.08 < tmax < 0.15, tmax
        assert 0.9 < np.max(max_stc) < 3.5, np.max(max_stc)

        if fwd is forward:
            # Test picking normal orientation (surface source space only).
            filters = make_lcmv(evoked.info, forward_surf_ori, data_cov,
                                reg=reg, noise_cov=noise_cov,
                                pick_ori='normal', weight_norm=None)
            stc_normal = apply_lcmv(evoked, filters, max_ori_out='signed')
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            lower = 0.04 if proj else 0.025
            assert lower < tmax < 0.14, tmax
            lower = 3e-7 if proj else 2e-7
            assert lower < np.max(max_stc) < 3e-6, np.max(max_stc)

            # No weight normalization was applied, so the amplitude of normal
            # orientation results should always be smaller than free
            # orientation results.
            assert (np.abs(stc_normal.data) <= stc.data).all()

        # Test picking source orientation maximizing output source power
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg,
                            noise_cov=noise_cov, pick_ori='max-power')
        stc_max_power = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        lower = 0.08 if proj else 0.04
        assert lower < tmax < 0.15, tmax
        assert 0.8 < np.max(max_stc) < 3., np.max(max_stc)

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label, fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_array_less(np.abs(mean_stc - mean_stc_max_pow), 1.0)

        # Test NAI weight normalization:
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=reg,
                            noise_cov=noise_cov, pick_ori='max-power',
                            weight_norm='nai')
        stc_nai = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # __repr__
    assert len(evoked.ch_names) == 22
    assert len(evoked.info['projs']) == (3 if proj else 0)
    assert len(evoked.info['bads']) == 2
    rank = 17 if proj else 20
    assert 'LCMV' in repr(filters)
    assert 'unknown subject' not in repr(filters)
    assert '4157 vert' in repr(filters)
    assert '20 ch' in repr(filters)
    assert 'rank %s' % rank in repr(filters)

    # I/O
    fname = op.join(str(tmpdir), 'filters.h5')
    with pytest.warns(RuntimeWarning, match='-lcmv.h5'):
        filters.save(fname)
    filters_read = read_beamformer(fname)
    assert isinstance(filters, Beamformer)
    assert isinstance(filters_read, Beamformer)
    # deal with object_diff strictness
    filters_read['rank'] = int(filters_read['rank'])
    filters['rank'] = int(filters['rank'])
    assert object_diff(filters, filters_read) == ''

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='max-power')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')

    # Test if volume forward operator is detected when picking normal
    # orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol,
                  data_cov=data_cov, reg=0.01, noise_cov=None,
                  pick_ori='max-power')

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[1:])
    filters = make_lcmv(evoked.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    pytest.raises(ValueError, apply_lcmv, evoked_ch, filters,
                  max_ori_out='signed')

    # Test if discrepancies in channel selection of data and fwd model are
    # handled correctly in apply_lcmv
    # make filter with data where first channel was removed
    filters = make_lcmv(evoked_ch.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    # applying that filter to the full data set should automatically exclude
    # this channel from the data
    # also test here that no warnings are thrown - implemented to check whether
    # src should not be None warning occurs
    with pytest.warns(None) as w:
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert len(w) == 0
    # the result should be equal to applying this filter to a dataset without
    # this channel:
    stc_ch = apply_lcmv(evoked_ch, filters, max_ori_out='signed')
    assert_array_almost_equal(stc.data, stc_ch.data)

    # Test if non-matching SSP projection is detected in application of filter
    if proj:
        raw_proj = deepcopy(raw)
        raw_proj.del_proj()
        with pytest.raises(ValueError, match='do not match the projections'):
            apply_lcmv_raw(raw_proj, filters, max_ori_out='signed')

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # check whether a filters object without src_type throws expected warning
    del filters['src_type']  # emulate 0.16 behaviour to cause warning
    with pytest.warns(RuntimeWarning, match='spatial filter does not contain '
                      'src_type'):
        apply_lcmv(evoked, filters, max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')
    stcs_ = apply_lcmv_epochs(epochs, filters, return_generator=True,
                              max_ori_out='signed')
    assert_array_equal(stcs[0].data, next(stcs_).data)

    epochs.drop_bad()
    assert (len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    filters = make_lcmv(evoked.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    stc_fixed = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov, label=label)
    stcs_label = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)

    # Test condition where the filters weights are zero. There should not be
    # any divide-by-zero errors
    zero_cov = data_cov.copy()
    zero_cov['data'][:] = 0
    filters = make_lcmv(epochs.info, forward_fixed, zero_cov, reg=0.01,
                        noise_cov=noise_cov)
    assert_array_equal(filters['weights'], 0)

    # Test condition where one channel type is picked
    # (avoid "grad data rank (13) did not match the noise rank (None)")
    data_cov_grad = pick_channels_cov(
        data_cov, [ch_name for ch_name in epochs.info['ch_names']
                   if ch_name.endswith(('2', '3'))])
    assert len(data_cov_grad['names']) > 4
    make_lcmv(epochs.info, forward_fixed, data_cov_grad, reg=0.01,
              noise_cov=noise_cov)
Esempio n. 6
0
data_cov = mne.compute_covariance(epochs)
filters = make_lcmv(epochs.info,
                    fwd,
                    data_cov,
                    0.05,
                    cov,
                    pick_ori='max-power',
                    weight_norm='nai')
del fwd

##############################################################################
# Compute label time series and do envelope correlation
# -----------------------------------------------------

epochs.apply_hilbert()  # faster to do in sensor space
stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)
corr = envelope_correlation(stcs, verbose=True)

##############################################################################
# Compute the degree and plot it
# ------------------------------

degree = mne.connectivity.degree(corr, 0.15)
stc = mne.VolSourceEstimate(degree, src[0]['vertno'], 0, 1, 'bst_resting')
brain = stc.plot(src,
                 clim=dict(kind='percent', lims=[75, 85, 95]),
                 colormap='gnuplot',
                 subjects_dir=subjects_dir,
                 mode='glass_brain')

##############################################################################
Esempio n. 7
0
def test_lcmv():
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        filters = make_lcmv(evoked.info,
                            fwd,
                            data_cov,
                            reg=0.01,
                            noise_cov=noise_cov)
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.09 < tmax < 0.12, tmax
        assert 0.9 < np.max(max_stc) < 3., np.max(max_stc)

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            filters = make_lcmv(evoked.info,
                                forward_surf_ori,
                                data_cov,
                                reg=0.01,
                                noise_cov=noise_cov,
                                pick_ori='normal')
            stc_normal = apply_lcmv(evoked, filters, max_ori_out='signed')
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert 0.04 < tmax < 0.12, tmax
            assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert (np.abs(stc_normal.data) <= stc.data).all()

        # Test picking source orientation maximizing output source power
        filters = make_lcmv(evoked.info,
                            fwd,
                            data_cov,
                            reg=0.01,
                            noise_cov=noise_cov,
                            pick_ori='max-power')
        stc_max_power = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.08 < tmax < 0.12, tmax
        assert 0.8 < np.max(max_stc) < 3., np.max(max_stc)

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label,
                                                     fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_array_less(np.abs(mean_stc - mean_stc_max_pow), 0.6)

        # Test NAI weight normalization:
        filters = make_lcmv(evoked.info,
                            fwd,
                            data_cov,
                            reg=0.01,
                            noise_cov=noise_cov,
                            pick_ori='max-power',
                            weight_norm='nai')
        stc_nai = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test sphere head model with unit-noise gain beamformer and orientation
    # selection and rank reduction of the leadfield
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None,
                                        pos=15.,
                                        mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None,
                                        mindist=5.0,
                                        exclude=2.0)

    fwd_sphere = mne.make_forward_solution(evoked.info,
                                           trans=None,
                                           src=src,
                                           bem=sphere,
                                           eeg=False,
                                           meg=True)

    # Test that we get an error if not reducing rank
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  fwd_sphere,
                  data_cov,
                  reg=0.1,
                  noise_cov=noise_cov,
                  weight_norm='unit-noise-gain',
                  pick_ori='max-power',
                  reduce_rank=False)

    # Now let's reduce it
    filters = make_lcmv(evoked.info,
                        fwd_sphere,
                        data_cov,
                        reg=0.1,
                        noise_cov=noise_cov,
                        weight_norm='unit-noise-gain',
                        pick_ori='max-power',
                        reduce_rank=True)
    stc_sphere = apply_lcmv(evoked, filters, max_ori_out='signed')
    stc_sphere = np.abs(stc_sphere)
    stc_sphere.crop(0.02, None)

    stc_pow = np.sum(stc_sphere.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_sphere.data[idx]
    tmax = stc_sphere.times[np.argmax(max_stc)]

    assert 0.08 < tmax < 0.15, tmax
    assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_fixed,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='normal')
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_fixed,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='max-power')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='normal')

    # Test if volume forward operator is detected when picking normal
    # orientation
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='normal')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov=data_cov,
                  reg=0.01,
                  noise_cov=None,
                  pick_ori='max-power')

    # Test if not-yet-implemented orientation selections raise error with
    # neural activity index
    pytest.raises(NotImplementedError,
                  make_lcmv,
                  evoked.info,
                  forward_surf_ori,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='normal',
                  weight_norm='nai')
    pytest.raises(NotImplementedError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori=None,
                  weight_norm='nai')

    # Test if no weight-normalization and max-power source orientation throws
    # an error
    pytest.raises(NotImplementedError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='max-power',
                  weight_norm=None)

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[1:])
    filters = make_lcmv(evoked.info,
                        forward_vol,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    pytest.raises(ValueError,
                  apply_lcmv,
                  evoked_ch,
                  filters,
                  max_ori_out='signed')

    # Test if discrepancies in channel selection of data and fwd model are
    # handled correctly in apply_lcmv
    # make filter with data where first channel was removed
    filters = make_lcmv(evoked_ch.info,
                        forward_vol,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    # applying that filter to the full data set should automatically exclude
    # this channel from the data
    stc = apply_lcmv(evoked, filters, max_ori_out='signed')
    # the result should be equal to applying this filter to a dataset without
    # this channel:
    stc_ch = apply_lcmv(evoked_ch, filters, max_ori_out='signed')
    assert_array_almost_equal(stc.data, stc_ch.data)

    # Test if non-matching SSP projection is detected in application of filter
    raw_proj = deepcopy(raw)
    raw_proj.del_proj()
    pytest.raises(ValueError,
                  apply_lcmv_raw,
                  raw_proj,
                  filters,
                  max_ori_out='signed')

    # Test if setting reduce_rank to True returns a NotImplementedError
    # when no orientation selection is done or pick_ori='normal'
    pytest.raises(NotImplementedError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov,
                  noise_cov=noise_cov,
                  pick_ori=None,
                  weight_norm='nai',
                  reduce_rank=True)
    pytest.raises(NotImplementedError,
                  make_lcmv,
                  evoked.info,
                  forward_surf_ori,
                  data_cov,
                  noise_cov=noise_cov,
                  pick_ori='normal',
                  weight_norm='nai',
                  reduce_rank=True)

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    filters = make_lcmv(epochs.info,
                        forward_fixed,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')
    stcs_ = apply_lcmv_epochs(epochs,
                              filters,
                              return_generator=True,
                              max_ori_out='signed')
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad()
    assert (len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    filters = make_lcmv(evoked.info,
                        forward_fixed,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    stc_fixed = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    filters = make_lcmv(epochs.info,
                        forward_fixed,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov,
                        label=label)
    stcs_label = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Esempio n. 8
0
def test_make_lcmv(tmpdir):
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        filters = make_lcmv(evoked.info,
                            fwd,
                            data_cov,
                            reg=0.01,
                            noise_cov=noise_cov)
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.09 < tmax < 0.12, tmax
        assert 0.9 < np.max(max_stc) < 3., np.max(max_stc)

        if fwd is forward:
            # Test picking normal orientation (surface source space only).
            filters = make_lcmv(evoked.info,
                                forward_surf_ori,
                                data_cov,
                                reg=0.01,
                                noise_cov=noise_cov,
                                pick_ori='normal',
                                weight_norm=None)
            stc_normal = apply_lcmv(evoked, filters, max_ori_out='signed')
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert 0.04 < tmax < 0.13, tmax
            assert 3e-7 < np.max(max_stc) < 5e-7, np.max(max_stc)

            # No weight normalization was applied, so the amplitude of normal
            # orientation results should always be smaller than free
            # orientation results.
            assert (np.abs(stc_normal.data) <= stc.data).all()

        # Test picking source orientation maximizing output source power
        filters = make_lcmv(evoked.info,
                            fwd,
                            data_cov,
                            reg=0.01,
                            noise_cov=noise_cov,
                            pick_ori='max-power')
        stc_max_power = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.08 < tmax < 0.12, tmax
        assert 0.8 < np.max(max_stc) < 3., np.max(max_stc)

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label,
                                                     fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_array_less(np.abs(mean_stc - mean_stc_max_pow), 0.6)

        # Test NAI weight normalization:
        filters = make_lcmv(evoked.info,
                            fwd,
                            data_cov,
                            reg=0.01,
                            noise_cov=noise_cov,
                            pick_ori='max-power',
                            weight_norm='nai')
        stc_nai = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test sphere head model with unit-noise gain beamformer and orientation
    # selection and rank reduction of the leadfield
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None,
                                        pos=15.,
                                        mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None,
                                        mindist=5.0,
                                        exclude=2.0)

    fwd_sphere = mne.make_forward_solution(evoked.info,
                                           trans=None,
                                           src=src,
                                           bem=sphere,
                                           eeg=False,
                                           meg=True)

    # Test that we get an error if not reducing rank
    with pytest.raises(ValueError):  # Singular matrix or complex spectrum
        make_lcmv(evoked.info,
                  fwd_sphere,
                  data_cov,
                  reg=0.1,
                  noise_cov=noise_cov,
                  weight_norm='unit-noise-gain',
                  pick_ori='max-power',
                  reduce_rank=False,
                  rank='full')

    # Now let's reduce it
    filters = make_lcmv(evoked.info,
                        fwd_sphere,
                        data_cov,
                        reg=0.1,
                        noise_cov=noise_cov,
                        weight_norm='unit-noise-gain',
                        pick_ori='max-power',
                        reduce_rank=True)
    stc_sphere = apply_lcmv(evoked, filters, max_ori_out='signed')
    stc_sphere = np.abs(stc_sphere)
    stc_sphere.crop(0.02, None)

    stc_pow = np.sum(stc_sphere.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_sphere.data[idx]
    tmax = stc_sphere.times[np.argmax(max_stc)]

    assert 0.08 < tmax < 0.15, tmax
    assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # __repr__
    assert 'LCMV' in repr(filters)
    assert 'unknown subject' not in repr(filters)
    assert '484' in repr(filters)
    assert '20' in repr(filters)
    assert 'rank 17' in repr(filters)

    # I/O
    fname = op.join(str(tmpdir), 'filters.h5')
    with pytest.warns(RuntimeWarning, match='-lcmv.h5'):
        filters.save(fname)
    filters_read = read_beamformer(fname)
    assert isinstance(filters, Beamformer)
    assert isinstance(filters_read, Beamformer)
    # deal with object_diff strictness
    filters_read['rank'] = int(filters_read['rank'])
    filters['rank'] = int(filters['rank'])
    assert object_diff(filters, filters_read) == ''

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_fixed,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='normal')
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_fixed,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='max-power')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='normal')

    # Test if volume forward operator is detected when picking normal
    # orientation
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov,
                  reg=0.01,
                  noise_cov=noise_cov,
                  pick_ori='normal')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    pytest.raises(ValueError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov=data_cov,
                  reg=0.01,
                  noise_cov=None,
                  pick_ori='max-power')

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[1:])
    filters = make_lcmv(evoked.info,
                        forward_vol,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    pytest.raises(ValueError,
                  apply_lcmv,
                  evoked_ch,
                  filters,
                  max_ori_out='signed')

    # Test if discrepancies in channel selection of data and fwd model are
    # handled correctly in apply_lcmv
    # make filter with data where first channel was removed
    filters = make_lcmv(evoked_ch.info,
                        forward_vol,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    # applying that filter to the full data set should automatically exclude
    # this channel from the data
    # also test here that no warnings are thrown - implemented to check whether
    # src should not be None warning occurs
    with pytest.warns(None) as w:
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert len(w) == 0
    # the result should be equal to applying this filter to a dataset without
    # this channel:
    stc_ch = apply_lcmv(evoked_ch, filters, max_ori_out='signed')
    assert_array_almost_equal(stc.data, stc_ch.data)

    # Test if non-matching SSP projection is detected in application of filter
    raw_proj = deepcopy(raw)
    raw_proj.del_proj()
    pytest.raises(ValueError,
                  apply_lcmv_raw,
                  raw_proj,
                  filters,
                  max_ori_out='signed')

    # Test if setting reduce_rank to True returns a NotImplementedError
    # when no orientation selection is done or pick_ori='normal'
    pytest.raises(NotImplementedError,
                  make_lcmv,
                  evoked.info,
                  forward_vol,
                  data_cov,
                  noise_cov=noise_cov,
                  pick_ori=None,
                  weight_norm='nai',
                  reduce_rank=True)
    pytest.raises(NotImplementedError,
                  make_lcmv,
                  evoked.info,
                  forward_surf_ori,
                  data_cov,
                  noise_cov=noise_cov,
                  pick_ori='normal',
                  weight_norm='nai',
                  reduce_rank=True)

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # check whether a filters object without src_type throws expected warning
    del filters['src_type']  # emulate 0.16 behaviour to cause warning
    with pytest.warns(RuntimeWarning,
                      match='spatial filter does not contain '
                      'src_type'):
        apply_lcmv(evoked, filters, max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    filters = make_lcmv(epochs.info,
                        forward_fixed,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')
    stcs_ = apply_lcmv_epochs(epochs,
                              filters,
                              return_generator=True,
                              max_ori_out='signed')
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad()
    assert (len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    filters = make_lcmv(evoked.info,
                        forward_fixed,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    stc_fixed = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    filters = make_lcmv(epochs.info,
                        forward_fixed,
                        data_cov,
                        reg=0.01,
                        noise_cov=noise_cov,
                        label=label)
    stcs_label = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)

    # Test condition where the filters weights are zero. There should not be
    # any divide-by-zero errors
    zero_cov = data_cov.copy()
    zero_cov['data'][:] = 0
    filters = make_lcmv(epochs.info,
                        forward_fixed,
                        zero_cov,
                        reg=0.01,
                        noise_cov=noise_cov)
    assert_array_equal(filters['weights'], 0)
Esempio n. 9
0
def test_lcmv():
    """Test LCMV with evoked data and single trials."""
    raw, epochs, evoked, data_cov, noise_cov, label, forward,\
        forward_surf_ori, forward_fixed, forward_vol = _get_data()

    for fwd in [forward, forward_vol]:
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=0.01,
                            noise_cov=noise_cov)
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc.crop(0.02, None)

        stc_pow = np.sum(np.abs(stc.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = stc.data[idx]
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.09 < tmax < 0.12, tmax
        assert 0.9 < np.max(max_stc) < 3., np.max(max_stc)

        if fwd is forward:
            # Test picking normal orientation (surface source space only)
            filters = make_lcmv(evoked.info, forward_surf_ori, data_cov,
                                reg=0.01, noise_cov=noise_cov,
                                pick_ori='normal')
            stc_normal = apply_lcmv(evoked, filters, max_ori_out='signed')
            stc_normal.crop(0.02, None)

            stc_pow = np.sum(np.abs(stc_normal.data), axis=1)
            idx = np.argmax(stc_pow)
            max_stc = stc_normal.data[idx]
            tmax = stc_normal.times[np.argmax(max_stc)]

            assert 0.04 < tmax < 0.12, tmax
            assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)

            # The amplitude of normal orientation results should always be
            # smaller than free orientation results
            assert (np.abs(stc_normal.data) <= stc.data).all()

        # Test picking source orientation maximizing output source power
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=0.01,
                            noise_cov=noise_cov, pick_ori='max-power')
        stc_max_power = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_max_power.crop(0.02, None)
        stc_pow = np.sum(np.abs(stc_max_power.data), axis=1)
        idx = np.argmax(stc_pow)
        max_stc = np.abs(stc_max_power.data[idx])
        tmax = stc.times[np.argmax(max_stc)]

        assert 0.08 < tmax < 0.12, tmax
        assert 0.8 < np.max(max_stc) < 3., np.max(max_stc)

        stc_max_power.data[:, :] = np.abs(stc_max_power.data)

        if fwd is forward:
            # Maximum output source power orientation results should be
            # similar to free orientation results in areas with channel
            # coverage
            label = mne.read_label(fname_label)
            mean_stc = stc.extract_label_time_course(label, fwd['src'],
                                                     mode='mean')
            mean_stc_max_pow = \
                stc_max_power.extract_label_time_course(label, fwd['src'],
                                                        mode='mean')
            assert_array_less(np.abs(mean_stc - mean_stc_max_pow), 0.6)

        # Test NAI weight normalization:
        filters = make_lcmv(evoked.info, fwd, data_cov, reg=0.01,
                            noise_cov=noise_cov, pick_ori='max-power',
                            weight_norm='nai')
        stc_nai = apply_lcmv(evoked, filters, max_ori_out='signed')
        stc_nai.crop(0.02, None)

        # Test whether unit-noise-gain solution is a scaled version of NAI
        pearsoncorr = np.corrcoef(np.concatenate(np.abs(stc_nai.data)),
                                  np.concatenate(stc_max_power.data))
        assert_almost_equal(pearsoncorr[0, 1], 1.)

    # Test sphere head model with unit-noise gain beamformer and orientation
    # selection and rank reduction of the leadfield
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)
    src = mne.setup_volume_source_space(subject=None, pos=15., mri=None,
                                        sphere=(0.0, 0.0, 0.0, 80.0),
                                        bem=None, mindist=5.0, exclude=2.0)

    fwd_sphere = mne.make_forward_solution(evoked.info, trans=None, src=src,
                                           bem=sphere, eeg=False, meg=True)

    # Test that we get an error if not reducing rank
    pytest.raises(ValueError, make_lcmv, evoked.info, fwd_sphere, data_cov,
                  reg=0.1, noise_cov=noise_cov, weight_norm='unit-noise-gain',
                  pick_ori='max-power', reduce_rank=False)

    # Now let's reduce it
    filters = make_lcmv(evoked.info, fwd_sphere, data_cov, reg=0.1,
                        noise_cov=noise_cov, weight_norm='unit-noise-gain',
                        pick_ori='max-power', reduce_rank=True)
    stc_sphere = apply_lcmv(evoked, filters, max_ori_out='signed')
    stc_sphere = np.abs(stc_sphere)
    stc_sphere.crop(0.02, None)

    stc_pow = np.sum(stc_sphere.data, axis=1)
    idx = np.argmax(stc_pow)
    max_stc = stc_sphere.data[idx]
    tmax = stc_sphere.times[np.argmax(max_stc)]

    assert 0.08 < tmax < 0.15, tmax
    assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # Test if fixed forward operator is detected when picking normal or
    # max-power orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='max-power')

    # Test if non-surface oriented forward operator is detected when picking
    # normal orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')

    # Test if volume forward operator is detected when picking normal
    # orientation
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov,
                  reg=0.01, noise_cov=noise_cov, pick_ori='normal')

    # Test if missing of noise covariance matrix is detected when more than
    # one channel type is present in the data
    pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol,
                  data_cov=data_cov, reg=0.01, noise_cov=None,
                  pick_ori='max-power')

    # Test if not-yet-implemented orientation selections raise error with
    # neural activity index
    pytest.raises(NotImplementedError, make_lcmv, evoked.info,
                  forward_surf_ori, data_cov, reg=0.01, noise_cov=noise_cov,
                  pick_ori='normal', weight_norm='nai')
    pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
                  data_cov, reg=0.01, noise_cov=noise_cov, pick_ori=None,
                  weight_norm='nai')

    # Test if no weight-normalization and max-power source orientation throws
    # an error
    pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
                  data_cov, reg=0.01, noise_cov=noise_cov,
                  pick_ori='max-power', weight_norm=None)

    # Test if wrong channel selection is detected in application of filter
    evoked_ch = deepcopy(evoked)
    evoked_ch.pick_channels(evoked_ch.ch_names[1:])
    filters = make_lcmv(evoked.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    pytest.raises(ValueError, apply_lcmv, evoked_ch, filters,
                  max_ori_out='signed')

    # Test if discrepancies in channel selection of data and fwd model are
    # handled correctly in apply_lcmv
    # make filter with data where first channel was removed
    filters = make_lcmv(evoked_ch.info, forward_vol, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    # applying that filter to the full data set should automatically exclude
    # this channel from the data
    # also test here that no warnings are thrown - implemented to check whether
    # src should not be None warning occurs
    with pytest.warns(None) as w:
        stc = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert len(w) == 0
    # the result should be equal to applying this filter to a dataset without
    # this channel:
    stc_ch = apply_lcmv(evoked_ch, filters, max_ori_out='signed')
    assert_array_almost_equal(stc.data, stc_ch.data)

    # Test if non-matching SSP projection is detected in application of filter
    raw_proj = deepcopy(raw)
    raw_proj.del_proj()
    pytest.raises(ValueError, apply_lcmv_raw, raw_proj, filters,
                  max_ori_out='signed')

    # Test if setting reduce_rank to True returns a NotImplementedError
    # when no orientation selection is done or pick_ori='normal'
    pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
                  data_cov, noise_cov=noise_cov, pick_ori=None,
                  weight_norm='nai', reduce_rank=True)
    pytest.raises(NotImplementedError, make_lcmv, evoked.info,
                  forward_surf_ori, data_cov, noise_cov=noise_cov,
                  pick_ori='normal', weight_norm='nai', reduce_rank=True)

    # Test if spatial filter contains src_type
    assert 'src_type' in filters

    # check whether a filters object without src_type throws expected warning
    del filters['src_type']  # emulate 0.16 behaviour to cause warning
    with pytest.warns(RuntimeWarning, match='spatial filter does not contain '
                      'src_type'):
        apply_lcmv(evoked, filters, max_ori_out='signed')

    # Now test single trial using fixed orientation forward solution
    # so we can compare it to the evoked solution
    filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')
    stcs_ = apply_lcmv_epochs(epochs, filters, return_generator=True,
                              max_ori_out='signed')
    assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)

    epochs.drop_bad()
    assert (len(epochs.events) == len(stcs))

    # average the single trial estimates
    stc_avg = np.zeros_like(stcs[0].data)
    for this_stc in stcs:
        stc_avg += this_stc.data
    stc_avg /= len(stcs)

    # compare it to the solution using evoked with fixed orientation
    filters = make_lcmv(evoked.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov)
    stc_fixed = apply_lcmv(evoked, filters, max_ori_out='signed')
    assert_array_almost_equal(stc_avg, stc_fixed.data)

    # use a label so we have few source vertices and delayed computation is
    # not used
    filters = make_lcmv(epochs.info, forward_fixed, data_cov, reg=0.01,
                        noise_cov=noise_cov, label=label)
    stcs_label = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')

    assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
Esempio n. 10
0
def run_correlation(subjects_dir, subject, volume_spacing, freq, ortho_bool):

    num_threads(8)
    ortho_flag = str(ortho_bool)
    frequency = str(freq)
    DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files')
    eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz'
    eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz'
    fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif'
    t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz')
    heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz'
    fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd.fif.gz'
    src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src.fif.gz'
    cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}.fif.gz'
    raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}.fif.gz'
    raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj.fif.gz'
    source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl'
    corr_file_acLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acLeft.npy'
    corr_file_scLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scLeft.npy'
    corr_file_vcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcLeft.npy'
    corr_file_mtLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtLeft.npy'
    corr_file_mtlLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlLeft.npy'
    corr_file_smcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcLeft.npy'
    corr_file_lpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcLeft.npy'
    corr_file_dpfcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcLeft.npy'
    corr_file_tmpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcLeft.npy'

    corr_file_acRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acRight.npy'
    corr_file_scRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scRight.npy'
    corr_file_vcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcRight.npy'
    corr_file_mtRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtRight.npy'
    corr_file_mtlRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlRight.npy'
    corr_file_smcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcRight.npy'
    corr_file_lpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcRight.npy'
    corr_file_dpfcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcRight.npy'
    corr_file_tmpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcRight.npy'

    corr_file_mpfc = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mpfc.npy'
    corr_file_sma = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_sma.npy'

    check_for_files = []
    check_for_files.append(corr_file_acLeft)
    check_for_files.append(corr_file_scLeft)
    check_for_files.append(corr_file_vcLeft)
    check_for_files.append(corr_file_mtLeft)
    check_for_files.append(corr_file_mtlLeft)
    check_for_files.append(corr_file_smcLeft)
    check_for_files.append(corr_file_lpcLeft)
    check_for_files.append(corr_file_dpfcLeft)
    check_for_files.append(corr_file_tmpcLeft)

    check_for_files.append(corr_file_acRight)
    check_for_files.append(corr_file_scRight)
    check_for_files.append(corr_file_vcRight)
    check_for_files.append(corr_file_mtRight)
    check_for_files.append(corr_file_mtlRight)
    check_for_files.append(corr_file_smcRight)
    check_for_files.append(corr_file_lpcRight)
    check_for_files.append(corr_file_dpfcRight)
    check_for_files.append(corr_file_tmpcRight)

    check_for_files.append(corr_file_mpfc)
    check_for_files.append(corr_file_sma)


    file_exist = [f for f in check_for_files if os.path.isfile(f)]
    file_not_exist = list(set(file_exist) ^ set(check_for_files))

    if not file_not_exist:
        print('SC, AC, VC correlation files exists...')

    else:
        trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration
        file_trans = pathlib.Path(trans)
        file_ss = pathlib.Path(src_fname)
        file_fm = pathlib.Path(fwd_fname)
        file_proj = pathlib.Path(raw_proj)
        file_cov = pathlib.Path(cov_fname)
        file_rawcov = pathlib.Path(raw_cov_fname)
        t1 = nib.load(t1_fname)

        if not file_trans.exists():
            print (f'{trans} File doesnt exist...')
            sys.exit(0)

        #info = mne.io.read_info(fname_meg)
        # plot_registration(info, trans, subject, subjects_dir)
        if not file_ss.exists():

            src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', 
                                volume_spacing=volume_spacing)
            seed_l_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Left'])
            seed_r_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Right'])
            seed_l_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Left'])
            seed_r_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Right'])
            seed_l_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Left'])
            seed_r_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Right'])
            seed_l_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Left'])
            seed_r_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Right'])
            seed_l_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Left'])
            seed_r_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Right'])
            seed_l_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Left'])
            seed_r_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Right'])
            seed_l_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Left'])
            seed_r_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Right'])
            seed_l_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Left'])
            seed_r_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Right'])
            seed_l_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Left'])
            seed_r_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Right'])

            seed_mpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MPFC_MidBrain'])
            seed_sma = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMA_MidBrain'])

            src_inuse = np.where(src[0]['inuse'] == 1)
            loc_l_sc = src_inuse[0][0]
            loc_r_sc = src_inuse[0][1]
            loc_l_ac = src_inuse[0][2]
            loc_r_ac = src_inuse[0][3]
            loc_l_vc = src_inuse[0][4]
            loc_r_vc = src_inuse[0][5]
            loc_l_mt = src_inuse[0][6]
            loc_r_mt = src_inuse[0][7]
            loc_l_mtl = src_inuse[0][8]
            loc_r_mtl = src_inuse[0][9]
            loc_l_smc = src_inuse[0][10]
            loc_r_smc = src_inuse[0][11]
            loc_l_lpc = src_inuse[0][12]
            loc_r_lpc = src_inuse[0][13]
            loc_l_dpfc = src_inuse[0][14]
            loc_r_dpfc = src_inuse[0][15]
            loc_l_tmpc = src_inuse[0][16]
            loc_r_tmpc = src_inuse[0][17]
            loc_mpfc = src_inuse[0][18]
            loc_sma = src_inuse[0][19]
            src[0]['rr'][loc_l_sc] = seed_l_sc
            src[0]['rr'][loc_r_sc] = seed_r_sc
            src[0]['rr'][loc_l_ac] = seed_l_ac
            src[0]['rr'][loc_r_ac] = seed_r_ac
            src[0]['rr'][loc_l_vc] = seed_l_vc
            src[0]['rr'][loc_r_vc] = seed_r_vc
            src[0]['rr'][loc_l_mt] = seed_l_mt
            src[0]['rr'][loc_r_mt] = seed_r_mt
            src[0]['rr'][loc_l_mtl] = seed_l_mtl
            src[0]['rr'][loc_r_mtl] = seed_r_mtl
            src[0]['rr'][loc_l_smc] = seed_l_smc
            src[0]['rr'][loc_r_smc] = seed_r_smc
            src[0]['rr'][loc_l_lpc] = seed_l_lpc
            src[0]['rr'][loc_r_lpc] = seed_r_lpc
            src[0]['rr'][loc_l_dpfc] = seed_l_dpfc
            src[0]['rr'][loc_r_dpfc] = seed_r_dpfc
            src[0]['rr'][loc_l_tmpc] = seed_l_tmpc
            src[0]['rr'][loc_r_tmpc] = seed_r_tmpc
            src[0]['rr'][loc_mpfc] = seed_mpfc
            src[0]['rr'][loc_sma] = seed_sma
            src.save(src_fname, overwrite=True)
        src = mne.read_source_spaces(src_fname)
        #view_SS_brain(subject, subjects_dir, src)

        if not file_fm.exists():
            forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname)
        fwd = mne.read_forward_solution(fwd_fname)

        # sensitivty_plot(subject, subjects_dir, fwd)
        raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True)

        srate = raw.info['sfreq']
        n_time_samps = raw.n_times
        time_secs = raw.times
        ch_names = raw.ch_names
        n_chan = len(ch_names)
        freq_res =  srate/n_time_samps
        print('\n')
        print('-------------------------- Data summary-------------------------------')
        print(f'Subject {subject}')
        print(f"Frequency resolution {freq_res} Hz")
        print(f"The first few channel names are {ch_names[:3]}")
        print(f"The last time sample at {time_secs[-1]} seconds.")
        print(f"Sampling Frequency (No of time points/sec) {srate} Hz")
        print(f"Miscellaneous acquisition info {raw.info['description']}")
        print(f"Bad channels marked during data acquisition {raw.info['bads']}")
        print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices
        print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.")
        print('------------------------------------------------------------------------')
        print('\n')
        # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True)
        if not file_proj.exists():
            projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063')
            projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061')
            projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062')
            if projs_ecg is not None:
                mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors
                raw.info['projs'] += projs_ecg
            if projs_eog1 is not None:
                mne.write_proj(eye_proj1, projs_eog1)
                raw.info['projs'] += projs_eog1
            if projs_eog2 is not None:
                mne.write_proj(eye_proj2, projs_eog2)
                raw.info['projs'] += projs_eog2
            raw.apply_proj()
            raw.save(raw_proj, proj=True, overwrite=True)
        print(raw_proj)
        raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True)


        print(f'High-pass filtering data at 0.5 Hz')
        raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir')

        if not file_cov.exists():
            cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest
            mne.write_cov(cov_fname, cov)
        cov = mne.read_cov(cov_fname) 

        # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False
        # raw_proj_applied.crop(tmax=10)
        
        do_epochs = False

        l_freq = freq-2.0
        h_freq = freq+2.0
        print(f'Band pass filter data [{l_freq}, {h_freq}]')
        raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq)

        if do_epochs:
            print('Segmenting raw data...')
            events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.)
            raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5.,
                                            baseline=None, preload=True)
            data_cov = mne.compute_covariance(raw_proj_filtered)         
        else:
            if not file_rawcov.exists():
                data_cov = mne.compute_raw_covariance(raw_proj_filtered)
                mne.write_cov(raw_cov_fname, data_cov)
            else:
                data_cov = mne.read_cov(file_rawcov)

        filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov,
                            pick_ori='max-power', weight_norm='nai')
        raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert()

        if do_epochs:
            stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False)
        else:
            stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True)
            stcs = [stcs]
        # Power Envelope Correlation
        print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize {ortho_flag}')

        all_corr = envelope_correlation(stcs, combine=None, orthogonalize=False,
                    log=False, absolute=True, verbose=None)

        np.save(corr_file_scLeft, all_corr[seed_left_sc])
        np.save(corr_file_acLeft, all_corr[seed_left_ac])
        np.save(corr_file_vcLeft, all_corr[seed_left_vc])
        np.save(corr_file_mtLeft, all_corr[seed_left_mt])
        np.save(corr_file_mtlLeft, all_corr[seed_left_mtl])
        np.save(corr_file_smcLeft, all_corr[seed_left_smc])
        np.save(corr_file_lpcLeft, all_corr[seed_left_lpc])
        np.save(corr_file_dpfcLeft, all_corr[seed_left_dpfc])
        np.save(corr_file_tmpcLeft, all_corr[seed_left_tmpc])

        np.save(corr_file_scRight, all_corr[seed_right_sc])
        np.save(corr_file_acRight, all_corr[seed_right_ac])
        np.save(corr_file_vcRight, all_corr[seed_right_vc])
        np.save(corr_file_mtRight, all_corr[seed_right_mt])
        np.save(corr_file_mtlRight, all_corr[seed_right_mtl])
        np.save(corr_file_smcRight, all_corr[seed_right_smc])
        np.save(corr_file_lpcRight, all_corr[seed_right_lpc])
        np.save(corr_file_dpfcRight, all_corr[seed_right_dpfc])
        np.save(corr_file_tmpcRight, all_corr[seed_right_tmpc])

        np.save(corr_file_mpfc, all_corr[seed_mpfc_index])
        np.save(corr_file_sma, all_corr[seed_sma_index])

        del stcs
Esempio n. 11
0
    epochs.pick_types(meg=True, ref_meg=False)
    # inv = make_inverse_operator(epochs.info, fwd, noise_cov,
    #                             loose=0.2, depth=0.8)
    method = 'beamformer'  # use of beamformer method
    # reconstruct source signal at the single trial
    data_cov = mne.compute_covariance(epochs, tmin=0.04)
    if not target_baseline:
        noise_cov = mne.compute_covariance(epochs, tmax=0)

    filters = make_lcmv(epochs.info,
                        fwd,
                        noise_cov=noise_cov,
                        data_cov=data_cov,
                        reg=0.05,
                        pick_ori='max-power')
    stcs = apply_lcmv_epochs(epochs, filters, max_ori_out='signed')

    n_times = len(epochs.times)
    n_vertices = len(stcs[0].data)
    n_epochs = len(epochs.events)
    X_data = np.zeros([n_epochs, n_vertices, n_times])
    for jj, stc in enumerate(stcs):
        X_data[jj] = stc.data
    X = mne.time_frequency.tfr_array_morlet(X_data,
                                            sfreq=epochs.info['sfreq'],
                                            freqs=freqs,
                                            output='power',
                                            n_cycles=n_cycles,
                                            n_jobs=24)
    n_epochs, n_channels, n_freqs, n_times = X.shape
    X = X.reshape(n_epochs, n_channels, -1)  # collapse freqs and time
# considerations here
pos = 15.  # 1.5 cm is very broad, done here for speed!
src = mne.setup_volume_source_space('bst_resting', pos, bem=bem,
                                    subjects_dir=subjects_dir, verbose=True)
fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
data_cov = mne.compute_covariance(epochs)
filters = make_lcmv(epochs.info, fwd, data_cov, 0.05, cov,
                    pick_ori='max-power', weight_norm='nai')
del fwd

##############################################################################
# Compute label time series and do envelope correlation
# -----------------------------------------------------

epochs.apply_hilbert()  # faster to do in sensor space
stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)
corr = envelope_correlation(stcs, verbose=True)

##############################################################################
# Compute the degree and plot it
# ------------------------------

degree = mne.connectivity.degree(corr, 0.15)
stc = mne.VolSourceEstimate(degree, src[0]['vertno'], 0, 1, 'bst_resting')
brain = stc.plot(
    src, clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot',
    subjects_dir=subjects_dir, mode='glass_brain')

##############################################################################
# References
# ----------
Esempio n. 13
0
GA_break = []
GA_diff = []

for meg, mri in sub_dict.items():

    epo = mne.read_epochs("{}{}-analysis-epo.fif".format(meg_dir,meg))
    fwd = mne.read_forward_solution("{}{}_vol-fwd.fif".format(meg_dir,meg))
    epo.filter(fmin, fmax, n_jobs='cuda')
    data_cov = mne.compute_covariance(epo, tmin=0, tmax=None, rank=None, n_jobs=8)
    noise_cov = mne.compute_covariance(epo, tmin=None, tmax=0, rank=None, n_jobs=8)
    filters = make_lcmv(epo.info, fwd, data_cov=data_cov,
                        noise_cov=noise_cov, pick_ori='max-power',
                        weight_norm='unit-noise-gain', reg=0.05, rank=None)
    filters.save('{}{}_alpha_vol-lcmv.h5'.format(meg_dir,meg),overwrite=True)
    epo.apply_hilbert(n_jobs=1, envelope=False)
    stcs_cont = apply_lcmv_epochs(epo['cont'], filters, max_ori_out='signed')
    stcs_break = apply_lcmv_epochs(epo['break'], filters, max_ori_out='signed')
    del epo, noise_cov, data_cov
    # envelope data (absolute) for both conditions
    for stc in stcs_cont:
        stc.data[:, :] = np.abs(stc.data)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            stc.data = np.array(stc.data, 'float64')
    for stc in stcs_break:
        stc.data[:, :] = np.abs(stc.data)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            stc.data = np.array(stc.data, 'float64')
    # average across epochs per condition 
    mean_cont = np.mean([stc.data for stc in stcs_cont], axis=0)
def run_correlation(subjects_dir, subject, volume_spacing, freq):

    num_threads(8)
    frequency = str(freq)
    DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files')
    eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz'
    eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz'
    fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif'
    t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz')
    heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz'
    fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd-label.fif.gz'
    src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src-label.fif.gz'
    cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}-label.fif.gz'
    raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}-label.fif.gz'
    raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj-label.fif.gz'
    source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl'
    freesurfer_label = f'{DATA_DIR}/{subject}_freesurferlabel_{volume_spacing}-label.pkl'
    corr_true_file_label = f'{DATA_DIR}/{subject}_corr_ortho_true_{volume_spacing}_{frequency}_label.npy'

    check_for_files = []
    check_for_files.append(corr_true_file_label)


    file_exist = [f for f in check_for_files if os.path.isfile(f)]
    file_not_exist = list(set(file_exist) ^ set(check_for_files))

    if not file_not_exist:
        print('correlation files exists...')

    else:
        trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration
        file_trans = pathlib.Path(trans)
        file_ss = pathlib.Path(src_fname)
        file_fm = pathlib.Path(fwd_fname)
        file_proj = pathlib.Path(raw_proj)
        file_cov = pathlib.Path(cov_fname)
        file_rawcov = pathlib.Path(raw_cov_fname)
        t1 = nib.load(t1_fname)

        if not file_trans.exists():
            print (f'{trans} File doesnt exist...')
            sys.exit(0)

        info = mne.io.read_info(fname_meg)
        # plot_registration(info, trans, subject, subjects_dir)

        print(file_ss)
        if not file_ss.exists():

            src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', 
                                volume_spacing=volume_spacing)

            src.save(src_fname, overwrite=True)
        src = mne.read_source_spaces(src_fname)
        #view_SS_brain(subject, subjects_dir, src)

        if not file_fm.exists():
            forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname)
        fwd = mne.read_forward_solution(fwd_fname)


       
        # sensitivty_plot(subject, subjects_dir, fwd)
        raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True)

        srate = raw.info['sfreq']
        n_time_samps = raw.n_times
        time_secs = raw.times
        ch_names = raw.ch_names
        n_chan = len(ch_names)
        freq_res =  srate/n_time_samps
        print('\n')
        print('-------------------------- Data summary-------------------------------')
        print(f'Subject {subject}')
        print(f"Frequency resolution {freq_res} Hz")
        print(f"The first few channel names are {ch_names[:3]}")
        print(f"The last time sample at {time_secs[-1]} seconds.")
        print(f"Sampling Frequency (No of time points/sec) {srate} Hz")
        print(f"Miscellaneous acquisition info {raw.info['description']}")
        print(f"Bad channels marked during data acquisition {raw.info['bads']}")
        print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices
        print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.")
        print('------------------------------------------------------------------------')
        print('\n')
        # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True)
        if not file_proj.exists():
            projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063')
            projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061')
            projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062')
            if projs_ecg is not None:
                mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors
                raw.info['projs'] += projs_ecg
            if projs_eog1 is not None:
                mne.write_proj(eye_proj1, projs_eog1)
                raw.info['projs'] += projs_eog1
            if projs_eog2 is not None:
                mne.write_proj(eye_proj2, projs_eog2)
                raw.info['projs'] += projs_eog2
            raw.apply_proj()
            raw.save(raw_proj, proj=True, overwrite=True)
        print(raw_proj)
        raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True)


        print(f'High-pass filtering data at 0.5 Hz')
        raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir')

        if not file_cov.exists():
            cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest
            mne.write_cov(cov_fname, cov)
        cov = mne.read_cov(cov_fname) 

        # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False
        # raw_proj_applied.crop(tmax=10)
        
        do_epochs = False

        l_freq = freq-2.0
        h_freq = freq+2.0
        print(f'Band pass filter data [{l_freq}, {h_freq}]')
        raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq)

        if do_epochs:
            print('Segmenting raw data...')
            events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.)
            raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5.,
                                            baseline=None, preload=True)
            data_cov = mne.compute_covariance(raw_proj_filtered)         
        else:
            if not file_rawcov.exists():
                data_cov = mne.compute_raw_covariance(raw_proj_filtered)
                mne.write_cov(raw_cov_fname, data_cov)
            else:
                data_cov = mne.read_cov(file_rawcov)

        filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov,
                            pick_ori='max-power', weight_norm='nai')
        raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert()

        if do_epochs:
            stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False)
        else:
            stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True)
        
        print('Extracting label time course...')
        atlas = f'{subjects_dir}/{subject}/mri/aparc.a2009s+aseg.mgz'
        label_ts = mne.extract_label_time_course(stcs, atlas, fwd['src'], return_generator=False)
        label_ts = [label_ts]

        # Power Envelope Correlation
        print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize True')

        all_corr = envelope_correlation(label_ts, combine=None, orthogonalize="pairwise",
                    log=True, absolute=True, verbose=None)

        print(f'Correlation saved to {corr_true_file_label}')
        np.save(corr_true_file_label, all_corr)

        del stcs
Esempio n. 15
0
def main(filename=None, subjid=None, trans=None, info=None, line_freq=None, 
         emptyroom_filename=None, subjects_dir=None):
    
    raw = hcp.read_raw(subjid, 'rest', hcp_path='/data/EnigmaMeg/HCP/HCP_MEG')
    raw.load_data()
    
    eraw = hcp.read_raw(subjid, 'noise_empty_room',hcp_path='/data/EnigmaMeg/HCP/HCP_MEG')
    eraw.load_data()
    
    hcp.preprocessing.apply_ref_correction(raw)
    hcp.preprocessing.apply_ref_correction(eraw)
    #Below may be useful for testing ICA components
    #ica_mat = hcp.read_ica(subjid, 'rest')
    #annotations_dict=hcp.read_annot(subjid, 'rest')
    #hcp.preprocessing.apply_ica_hcp(raw, ica_mat, annotations_dict['ica']['ecg_eog_ic'])
    
    ## Load and prefilter continuous data
    #raw=load_data(filename)
    #eraw=load_data(emptyroom_filename)
    
    if type(raw)==mne.io.ctf.ctf.RawCTF:
        raw.apply_gradient_compensation(3)
    
    ## Test SSS bad channel detection for non-Elekta data
    # !!!!!!!!!!!  Currently no finecal or crosstalk used  !!!!!!!!!!!!!!!
    # if filename[-3:]=='fif':
    #     raw_bads_dict = assess_bads(filename)
    #     eraw_bads_dict = assess_bads(emptyroom_filename, is_eroom=True)
        
    #     raw.info['bads']=raw_bads_dict['noisy'] + raw_bads_dict['flat']
    #     eraw.info['bads']=eraw_bads_dict['noisy'] + eraw_bads_dict['flat']
    
    resample_freq=300
    
    raw.resample(resample_freq)
    eraw.resample(resample_freq)
    
    raw.filter(0.5, 140)
    eraw.filter(0.5, 140)
    
    if line_freq==None:
        try:
            line_freq = raw.info['line_freq']  # this isn't present in all files
        except:
            raise(ValueError('Could not determine line_frequency'))
    notch_freqs = np.arange(line_freq, 
                            resample_freq/2, 
                            line_freq)
    raw.notch_filter(notch_freqs)
    
    
    ## Create Epochs and covariance 
    epochs = mne.make_fixed_length_epochs(raw, duration=4.0, preload=True)
    epochs.apply_baseline(baseline=(0,None))
    cov = mne.compute_covariance(epochs)
    
    er_epochs=mne.make_fixed_length_epochs(eraw, duration=4.0, preload=True)
    er_epochs.apply_baseline(baseline=(0,None))
    er_cov = mne.compute_covariance(er_epochs)
    
    os.environ['SUBJECTS_DIR']=subjects_dir
    src = mne.read_source_spaces(info.src_filename)
    bem = mne.read_bem_solution(info.bem_sol_filename)
    fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
    
    data_info = epochs.info
    
    from mne.beamformer import make_lcmv, apply_lcmv_epochs
    filters = make_lcmv(epochs.info, fwd, cov, reg=0.01,
                        noise_cov=er_cov, pick_ori='max-power',
                        weight_norm='unit-noise-gain', rank=None)
    
    labels_lh=mne.read_labels_from_annot(subjid, parc='aparc_sub',
                                        subjects_dir=subjects_dir, hemi='lh') 
    labels_rh=mne.read_labels_from_annot(subjid, parc='aparc_sub',
                                        subjects_dir=subjects_dir, hemi='rh') 
    labels=labels_lh + labels_rh 
    
    results_stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)#, max_ori_out='max_power')
    
    #Monkey patch of mne.source_estimate to perform 15 component SVD
    label_ts = mod_source_estimate.extract_label_time_course(results_stcs, 
                                                             labels, 
                                                             fwd['src'],
                                                             mode='pca15_multitaper')
    
    #Convert list of numpy arrays to ndarray (Epoch/Label/Sample)
    label_stack = np.stack(label_ts)

    #HACK HARDCODED FREQ BINS
    freq_bins = np.linspace(1,45,177)    ######################################3######### FIX

    #Initialize 
    label_power = np.zeros([len(labels), len(freq_bins)])  
    alpha_peak = np.zeros(len(labels))
    
    #Create PSD for each label
    for label_idx in range(len(labels)):
        print(str(label_idx))
        current_psd = label_stack[:,label_idx, :].mean(axis=0) 
        label_power[label_idx,:] = current_psd
        
        spectral_image_path = os.path.join(info.outfolder, 'Spectra_'+
                                            labels[label_idx].name + '.png')

        try:
            tmp_fmodel = calc_spec_peak(freq_bins, current_psd, 
                            out_image_path=spectral_image_path)
            
            #FIX FOR MULTIPLE ALPHA PEAKS
            potential_alpha_idx = np.where((8.0 <= tmp_fmodel.peak_params[:,0] ) & \
                                    (tmp_fmodel.peak_params[:,0] <= 12.0 ) )[0]
            if len(potential_alpha_idx) != 1:
                alpha_peak[label_idx] = np.nan         #############FIX ###########################3 FIX     
            else:
                alpha_peak[label_idx] = tmp_fmodel.peak_params[potential_alpha_idx[0]][0]
        except:
            alpha_peak[label_idx] = np.nan  #Fix <<<<<<<<<<<<<<    
        
    #Save the label spectrum to assemble the relative power
    freq_bin_names=[str(binval) for binval in freq_bins]
    label_spectra_dframe = pd.DataFrame(label_power, columns=[freq_bin_names])
    label_spectra_dframe.to_csv( os.path.join(info.outfolder, 'label_spectra.csv') , index=False)
    # with open(os.path.join(info.outfolder, 'label_spectra.npy'), 'wb') as f:
    #     np.save(f, label_power)
    
    relative_power = label_power / label_power.sum(axis=1, keepdims=True)

    #Define bands
    bands = [[1,3], [3,6], [8,12], [13,35], [35,55]]
    band_idxs = get_freq_idx(bands, freq_bins)

    #initialize output
    band_means = np.zeros([len(labels), len(bands)]) 
    #Loop over all bands, select the indexes assocaited with the band and average    
    for mean_band, band_idx in enumerate(band_idxs):
        band_means[:, mean_band] = relative_power[:, band_idx].mean(axis=1) 
    
    output_filename = os.path.join(info.outfolder, 'Band_rel_power.csv')
    

    bands_str = [str(i) for i in bands]
    label_names = [i.name for i in labels]
    
    output_dframe = pd.DataFrame(band_means, columns=bands_str, 
                                 index=label_names)
    output_dframe['AlphaPeak'] = alpha_peak
    output_dframe.to_csv(output_filename, sep='\t')    
Esempio n. 16
0
def test_beamformer():
   
    #Load filenames from test datasets
    from enigmeg.test_data.get_test_data import datasets
    test_dat = datasets().ctf

    meg_filename = test_dat['meg_rest'] 
    subjid = test_dat['subject']
    subjects_dir = test_dat['SUBJECTS_DIR'] 
    trans_fname = test_dat['trans']
    src_fname = test_dat['src']
    bem = test_dat['bem']
    
    outfolder = './tmp'  #<<< Change this ############################
    
    raw = mne.io.read_raw_ctf(meg_filename, preload=True)
    trans = mne.read_trans(trans_fname)
    # info.subjid, info.subjects_dir = subjid, subjects_dir
    
    raw.apply_gradient_compensation(3)
    raw.resample(300)
    raw.filter(1.0, None)
    raw.notch_filter([60,120])
    eraw.notch_filter([60,120])
    
    epochs = mne.make_fixed_length_epochs(raw, duration=4.0, preload=True)

    data_cov = mne.compute_covariance(epochs, method='empirical')  
    
    eroom_filename = test_dat['meg_eroom'] 
    eroom_raw = mne.io.read_raw_ctf(eroom_filename, preload=True)
    eroom_raw.resample(300)
    eroom_raw.notch_filter([60,120])
    eroom_raw.filter(1.0, None)
    
    eroom_epochs = mne.make_fixed_length_epochs(eroom_raw, duration=4.0)
    noise_cov = mne.compute_covariance(eroom_epochs)

    fwd = mne.make_forward_solution(epochs.info, trans, src_fname, 
                                    bem)
    
    from mne.beamformer import make_lcmv, apply_lcmv_epochs
    filters = make_lcmv(epochs.info, fwd, data_cov, reg=0.01,
                        noise_cov=noise_cov, pick_ori='max-power',
                        weight_norm='unit-noise-gain', rank=None)
    
    labels_lh=mne.read_labels_from_annot(subjid, parc='aparc',
                                        subjects_dir=subjects_dir, hemi='lh') 
    labels_rh=mne.read_labels_from_annot(subjid, parc='aparc',
                                        subjects_dir=subjects_dir, hemi='rh') 
    labels=labels_lh + labels_rh 
    
    # labels[1].center_of_mass()
    
    results_stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)#, max_ori_out='max_power')
    
    #Monkey patch of mne.source_estimate to perform 15 component SVD
    label_ts = mod_source_estimate.extract_label_time_course(results_stcs, labels, 
                                                         fwd['src'],
                                       mode='pca15_multitaper')
    
    #Convert list of numpy arrays to ndarray (Epoch/Label/Sample)
    label_stack = np.stack(label_ts)
    # label_stack = np.mean(label_stack, axis=0)

#    freq_bins, _ = label_psd(label_stack[:,0, :], raw.info['sfreq'])
    freq_bins = np.linspace(1,45,177)    ######################################3######### FIX

    #Initialize 
    label_power = np.zeros([len(labels), len(freq_bins)])  
    alpha_peak = np.zeros(len(labels))
    
    #Create PSD for each label
    for label_idx in range(len(labels)):
        print(str(label_idx))
        current_psd = label_stack[:,label_idx, :].mean(axis=0) 
        label_power[label_idx,:] = current_psd
        
        spectral_image_path = os.path.join(outfolder, 'Spectra_'+
                                            labels[label_idx].name + '.png')

        try:
            tmp_fmodel = calc_spec_peak(freq_bins, current_psd, 
                            out_image_path=spectral_image_path)
            
            #FIX FOR MULTIPLE ALPHA PEAKS
            potential_alpha_idx = np.where((8.0 <= tmp_fmodel.peak_params[:,0] ) & \
                                    (tmp_fmodel.peak_params[:,0] <= 12.0 ) )[0]
            if len(potential_alpha_idx) != 1:
                alpha_peak[label_idx] = np.nan         #############FIX ###########################3 FIX     
            else:
                alpha_peak[label_idx] = tmp_fmodel.peak_params[potential_alpha_idx[0]][0]
        except:
            alpha_peak[label_idx] = np.nan  #Fix <<<<<<<<<<<<<<