Ejemplo n.º 1
0
def simu_bimodal_meg(snr=6, white=True, seed=None, freqs=[3, 50], n_cycles=[1, 1.5],
                     phases=[0, 0], offsets=[0, 80]):
    tmin = -0.1
    sfreq = 1000.  # Hz
    tstep = 1. / sfreq
    n_samples = 600
    times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

    # Generate times series from 2 Morlet wavelets
    stc_data = np.zeros((len(labels), len(times)))
    Ws = morlet(sfreq, freqs, n_cycles=n_cycles)
    stc_data[0][:len(Ws[0])] = np.real(Ws[0] * np.exp(1j * phases[0]))
    stc_data[1][:len(Ws[1])] = np.real(Ws[1] * np.exp(1j * phases[1]))
    stc_data *= 100 * 1e-9  # use nAm as unit

    # time translation
    stc_data[0] = np.roll(stc_data[0], offsets[0])
    stc_data[1] = np.roll(stc_data[1], offsets[1])
    stc = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep,
                              random_state=0)

    ###############################################################################
    # Generate noisy evoked data
    picks = mne.pick_types(raw.info, meg=True, exclude='bads')
    if white:
        iir_filter = None  # for white noise
    else:
        iir_filter = iir_filter_raw(raw, order=5, picks=picks, tmin=60, tmax=180)
    evoked = generate_evoked(fwd, stc, evoked_template, cov, snr,
                             tmin=0.0, tmax=0.2, iir_filter=iir_filter, random_state=seed)
    return evoked
def envelope_coherence(se_data, seed_l, seed_r, fmin, fmax):

        '''
        se_data == used adaptive linear spatial filtering (beamforming)
        to estimate the spectral amplitude and phase of neuronal signals at the source
        level   
        Example:
        seed_l = Index of Left somatosensory cortex source estimate data
        seed_r = Index of Right somatosensory cortex source estimate data
        '''
        se_data = se_data.data[[seed_l,seed_r]].copy()

        # logarithm of the squared amplitude envelopes (power envelopes)
        data_squared = np.abs(se_data) * np.abs(se_data)
        data_mag = np.log(data_squared)
    
        log_range = np.arange(-1.5,1.1,0.1)
        covar_freqs = [math.pow(10,val) for val in log_range]
        '''
        We chose a spectral bandwidth of (σf = f * 3.15) and spaced the center frequencies log-
        arithmically according to the exponentiation of the base 10 with exponents ranging from −1.5 in steps of 0.1
        We derived spectral estimates in successive half-overlapping temporal windows that cov-
        ered ±3 σ t . From these complex numbers, we derived the coherency between power envelopes and 
        took the real part of coherency as the frequency-specific measure of correlation
        '''
        covar_freq_list = []
        sfreq = 1000
        for freq in covar_freqs:
            sigma = 3.15 * freq
            wvlt = morlet(sfreq, [freq], sigma=sigma, n_cycles=7)
            spectral_estimate = cwt(data_mag, wvlt)
            spectral_estimate = spectral_estimate[:,0,:]

            spectral_estimate_squared = np.abs(spectral_estimate) * np.abs(spectral_estimate)
            power_envelope = np.log(spectral_estimate_squared)
            power_envelope = power_envelope[np.newaxis,:,:]

            coherency, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                power_envelope, fmin=freq, fmax=freq+0.5, method='cohy',faverage=True, sfreq=sfreq, n_jobs=4)
            
            coherence_corr = np.real(coherency)
            coherence_corr = coherence_corr[1,:,:][0]
            covar_freq_list.append(coherence_corr)

        coherence_correlation = np.vstack(covar_freq_list)
        '''
        coherence_correlation.shape = (26,21)
        
        26 is the co-variation frequency (x-axis) [0.032 - 10]
        log_range = np.arange(-1.5,1.1,0.1)
        covar_freqs = [math.pow(10,val) for val in log_range]
        
        21 is the carrier freqeuncy (y-axis) [4 - 128]
        log_range = np.arange(2,7.25,0.25)
        carrier_freqs = [math.pow(2,val) for val in log_range]
        '''
        return coherence_correlation
Ejemplo n.º 3
0
def test_simulate_evoked():
    """ Test simulation of evoked data """

    raw = mne.fiff.Raw(raw_fname)
    fwd = read_forward_solution(fwd_fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
    cov = mne.read_cov(cov_fname)
    label_names = ['Aud-lh', 'Aud-rh']
    labels = [
        read_label(
            op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label))
        for label in label_names
    ]

    evoked_template = mne.fiff.read_evoked(ave_fname, setno=0, baseline=None)
    evoked_template = pick_types_evoked(evoked_template,
                                        meg=True,
                                        eeg=True,
                                        exclude=raw.info['bads'])

    snr = 6  # dB
    tmin = -0.1
    sfreq = 1000.  # Hz
    tstep = 1. / sfreq
    n_samples = 600
    times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

    # Generate times series from 2 Morlet wavelets
    stc_data = np.zeros((len(labels), len(times)))
    Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5])
    stc_data[0][:len(Ws[0])] = np.real(Ws[0])
    stc_data[1][:len(Ws[1])] = np.real(Ws[1])
    stc_data *= 100 * 1e-9  # use nAm as unit

    # time translation
    stc_data[1] = np.roll(stc_data[1], 80)
    stc = generate_sparse_stc(fwd['src'],
                              labels,
                              stc_data,
                              tmin,
                              tstep,
                              random_state=0)

    # Generate noisy evoked data
    iir_filter = [1, -0.9]
    evoked = generate_evoked(fwd,
                             stc,
                             evoked_template,
                             cov,
                             snr,
                             tmin=0.0,
                             tmax=0.2,
                             iir_filter=iir_filter)
    assert_array_almost_equal(evoked.times, stc.times)
    assert_true(len(evoked.data) == len(fwd['sol']['data']))
Ejemplo n.º 4
0
def test_simulate_evoked():
    """ Test simulation of evoked data """

    raw = Raw(raw_fname)
    fwd = read_forward_solution(fwd_fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
    cov = read_cov(cov_fname)
    label_names = ['Aud-lh', 'Aud-rh']
    labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
                         '%s.label' % label)) for label in label_names]

    evoked_template = read_evokeds(ave_fname, condition=0, baseline=None)
    evoked_template = pick_types_evoked(evoked_template, meg=True, eeg=True,
                                        exclude=raw.info['bads'])

    snr = 6  # dB
    tmin = -0.1
    sfreq = 1000.  # Hz
    tstep = 1. / sfreq
    n_samples = 600
    times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

    # Generate times series from 2 Morlet wavelets
    stc_data = np.zeros((len(labels), len(times)))
    Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5])
    stc_data[0][:len(Ws[0])] = np.real(Ws[0])
    stc_data[1][:len(Ws[1])] = np.real(Ws[1])
    stc_data *= 100 * 1e-9  # use nAm as unit

    # time translation
    stc_data[1] = np.roll(stc_data[1], 80)
    stc = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep,
                              random_state=0)

    # Generate noisy evoked data
    iir_filter = [1, -0.9]
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')  # positive semidefinite warning
        evoked = generate_evoked(fwd, stc, evoked_template, cov, snr,
                                 tmin=0.0, tmax=0.2, iir_filter=iir_filter)
    assert_array_almost_equal(evoked.times, stc.times)
    assert_true(len(evoked.data) == len(fwd['sol']['data']))

    # make a vertex that doesn't exist in fwd, should throw error
    stc_bad = stc.copy()
    mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']])
    stc_bad.vertices[0][0] = mv + 1
    assert_raises(RuntimeError, generate_evoked, fwd, stc_bad,
                  evoked_template, cov, snr, tmin=0.0, tmax=0.2)
Ejemplo n.º 5
0
def test_simulate_evoked():
    """ Test simulation of evoked data """

    raw = mne.fiff.Raw(raw_fname)
    fwd = read_forward_solution(fwd_fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
    cov = mne.read_cov(cov_fname)
    label_names = ['Aud-lh', 'Aud-rh']
    labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
                        '%s.label' % label)) for label in label_names]

    evoked_template = mne.fiff.read_evoked(ave_fname, setno=0, baseline=None)
    evoked_template = pick_types_evoked(evoked_template, meg=True, eeg=True,
                                        exclude=raw.info['bads'])

    snr = 6  # dB
    tmin = -0.1
    sfreq = 1000.  # Hz
    tstep = 1. / sfreq
    n_samples = 600
    times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

    # Generate times series from 2 Morlet wavelets
    stc_data = np.zeros((len(labels), len(times)))
    Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5])
    stc_data[0][:len(Ws[0])] = np.real(Ws[0])
    stc_data[1][:len(Ws[1])] = np.real(Ws[1])
    stc_data *= 100 * 1e-9  # use nAm as unit

    # time translation
    stc_data[1] = np.roll(stc_data[1], 80)
    stc = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep,
                              random_state=0)

    # Generate noisy evoked data
    iir_filter = [1, -0.9]
    evoked = generate_evoked(fwd, stc, evoked_template, cov, snr,
                             tmin=0.0, tmax=0.2, iir_filter=iir_filter)
    assert_array_almost_equal(evoked.times, stc.times)
    assert_true(len(evoked.data) == len(fwd['sol']['data']))
    read_label(data_path + '/MEG/sample/labels/%s.label' % ln)
    for ln in label_names
]

###############################################################################
# Generate source time courses and the correspond evoked data
snr = 6  # dB
tmin = -0.1
sfreq = 1000.  # Hz
tstep = 1. / sfreq
n_samples = 600
times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

# Generate times series from 2 Morlet wavelets
stc_data = np.zeros((len(labels), len(times)))
Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5])
stc_data[0][:len(Ws[0])] = np.real(Ws[0])
stc_data[1][:len(Ws[1])] = np.real(Ws[1])
stc_data *= 100 * 1e-9  # use nAm as unit

# time translation
stc_data[1] = np.roll(stc_data[1], 80)
stc = generate_sparse_stc(fwd['src'],
                          labels,
                          stc_data,
                          tmin,
                          tstep,
                          random_state=0)

###############################################################################
# Generate noisy evoked data
Ejemplo n.º 7
0
label_names = ['Aud-lh', 'Aud-rh']
labels = [mne.read_label(data_path + '/MEG/sample/labels/%s.label' % ln)
          for ln in label_names]

###############################################################################
# Generate source time courses and the correspond evoked data
snr = 6  # dB
tmin = -0.1
sfreq = 1000.  # Hz
tstep = 1. / sfreq
n_samples = 600
times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

# Generate times series from 2 Morlet wavelets
stc_data = np.zeros((len(labels), len(times)))
Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5])
stc_data[0][:len(Ws[0])] = np.real(Ws[0])
stc_data[1][:len(Ws[1])] = np.real(Ws[1])
stc_data *= 100 * 1e-9  # use nAm as unit

# time translation
stc_data[1] = np.roll(stc_data[1], 80)
stc = generate_sparse_stc(fwd['src'], labels, stc_data, tmin, tstep,
                          random_state=0)

###############################################################################
# Generate noisy evoked data
picks = mne.fiff.pick_types(raw.info, meg=True, exclude='bads')
iir_filter = iir_filter_raw(raw, order=5, picks=picks, tmin=60, tmax=180)
evoked = generate_evoked(fwd, stc, evoked_template, cov, snr,
                         tmin=0.0, tmax=0.2, iir_filter=iir_filter)
Ejemplo n.º 8
0
def test_simulate_evoked():
    """ Test simulation of evoked data """

    raw = Raw(raw_fname)
    fwd = read_forward_solution(fwd_fname, force_fixed=True)
    fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
    cov = read_cov(cov_fname)
    label_names = ['Aud-lh', 'Aud-rh']
    labels = [
        read_label(
            op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label))
        for label in label_names
    ]

    evoked_template = read_evokeds(ave_fname, condition=0, baseline=None)
    evoked_template.pick_types(meg=True, eeg=True, exclude=raw.info['bads'])

    snr = 6  # dB
    tmin = -0.1
    sfreq = 1000.  # Hz
    tstep = 1. / sfreq
    n_samples = 600
    times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

    # Generate times series from 2 Morlet wavelets
    stc_data = np.zeros((len(labels), len(times)))
    Ws = morlet(sfreq, [3, 10], n_cycles=[1, 1.5])
    stc_data[0][:len(Ws[0])] = np.real(Ws[0])
    stc_data[1][:len(Ws[1])] = np.real(Ws[1])
    stc_data *= 100 * 1e-9  # use nAm as unit

    # time translation
    stc_data[1] = np.roll(stc_data[1], 80)
    stc = generate_sparse_stc(fwd['src'],
                              labels,
                              stc_data,
                              tmin,
                              tstep,
                              random_state=0)

    # Generate noisy evoked data
    iir_filter = [1, -0.9]
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')  # positive semidefinite warning
        evoked = generate_evoked(fwd,
                                 stc,
                                 evoked_template,
                                 cov,
                                 snr,
                                 tmin=0.0,
                                 tmax=0.2,
                                 iir_filter=iir_filter)
    assert_array_almost_equal(evoked.times, stc.times)
    assert_true(len(evoked.data) == len(fwd['sol']['data']))

    # make a vertex that doesn't exist in fwd, should throw error
    stc_bad = stc.copy()
    mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']])
    stc_bad.vertices[0][0] = mv + 1
    assert_raises(RuntimeError,
                  generate_evoked,
                  fwd,
                  stc_bad,
                  evoked_template,
                  cov,
                  snr,
                  tmin=0.0,
                  tmax=0.2)
Ejemplo n.º 9
0
from mne.time_frequency import morlet
from mne.preprocessing.ctps_ import (ctps, _prob_kuiper,
                                     _compute_normalized_phase)

###############################################################################
# Generate testing signal

tmin = -0.3
sfreq = 1000.  # Hz
tstep = 1. / sfreq
n_samples = 600
times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

# Generate times series from Morlet wavelet
single_trial = np.zeros((1, len(times)))
Ws = morlet(sfreq, [3], n_cycles=[1])

single_trial[0][:len(Ws[0])] = np.real(Ws[0])
roll_to = 300 - 265  # shift data to center of time window
single_trial = np.roll(single_trial, roll_to)
rng = np.random.RandomState(42)


def get_data(n_trials, j_extent):
    """Generate ground truth and testing data."""
    ground_truth = np.tile(single_trial, n_trials)
    my_shape = n_trials, 1, 600
    random_data = rng.random_sample(my_shape)
    with warnings.catch_warnings(record=True):  # weight tables
        rand_ints = rng.random_integers(-j_extent, j_extent, n_trials)
    jittered_data = np.array([np.roll(single_trial, i) for i in rand_ints])
Ejemplo n.º 10
0
from numpy.testing import assert_array_equal
from mne.preprocessing.ctps_ import (ctps, _prob_kuiper,
                                     _compute_normalized_phase)

###############################################################################
# Generate testing signal

tmin = -0.3
sfreq = 1000.  # Hz
tstep = 1. / sfreq
n_samples = 600
times = np.linspace(tmin, tmin + n_samples * tstep, n_samples)

# Generate times series from Morlet wavelet
single_trial = np.zeros((1, len(times)))
Ws = morlet(sfreq, [3], n_cycles=[1])

single_trial[0][:len(Ws[0])] = np.real(Ws[0])
roll_to = 300 - 265  # shift data to center of time window
single_trial = np.roll(single_trial, roll_to)
rng = np.random.RandomState(42)


def get_data(n_trials, j_extent):
    """Generate ground truth and testing data"""
    ground_truth = np.tile(single_trial,  n_trials)
    my_shape = n_trials, 1, 600
    random_data = rng.random_sample(my_shape)
    rand_ints = rng.random_integers(-j_extent, j_extent, n_trials)
    jittered_data = np.array([np.roll(single_trial, i) for i in rand_ints])
    data = np.concatenate([ground_truth.reshape(my_shape),