def test_csd_epochs_on_artificial_data(): """Test computing CSD on artificial data. """ epochs = _get_data(mode='sin') sfreq = epochs.info['sfreq'] # Computing signal power in the time domain signal_power = sum_squared(epochs._data) signal_power_per_sample = signal_power / len(epochs.times) # Computing signal power in the frequency domain data_csd_fourier = csd_epochs(epochs, mode='fourier') data_csd_mt = csd_epochs(epochs, mode='multitaper') fourier_power = np.abs(data_csd_fourier.data[0, 0]) * sfreq mt_power = np.abs(data_csd_mt.data[0, 0]) * sfreq assert_true(abs(fourier_power - signal_power) <= 0.5) assert_true(abs(mt_power - signal_power) <= 1) # Power per sample should not depend on time window length for tmax in [0.2, 0.8]: for add_n_fft in [0, 30]: t_mask = (epochs.times >= 0) & (epochs.times <= tmax) n_samples = sum(t_mask) n_fft = n_samples + add_n_fft data_csd_fourier = csd_epochs(epochs, mode='fourier', tmin=None, tmax=tmax, fmin=0, fmax=np.inf, n_fft=n_fft) first_samp = data_csd_fourier.data[0, 0] fourier_power_per_sample = np.abs(first_samp) * sfreq / n_fft assert_true( abs(signal_power_per_sample - fourier_power_per_sample) < 0.003) # Power per sample should not depend on number of tapers for n_tapers in [1, 2, 5]: for add_n_fft in [0, 30]: mt_bandwidth = sfreq / float(n_samples) * (n_tapers + 1) data_csd_mt = csd_epochs(epochs, mode='multitaper', tmin=None, tmax=tmax, fmin=0, fmax=np.inf, mt_bandwidth=mt_bandwidth, n_fft=n_fft) mt_power_per_sample = np.abs(data_csd_mt.data[0, 0]) *\ sfreq / data_csd_mt.n_fft # The estimate of power gets worse for small time windows when # more tapers are used if n_tapers == 5 and tmax == 0.2: delta = 0.05 else: delta = 0.004 assert_true( abs(signal_power_per_sample - mt_power_per_sample) < delta)
def test_csd_epochs_on_artificial_data(): """Test computing CSD on artificial data.""" epochs = _generate_simple_data() sfreq = epochs.info['sfreq'] # Computing signal power in the time domain signal_power = sum_squared(epochs._data) signal_power_per_sample = signal_power / len(epochs.times) # Computing signal power in the frequency domain with warnings.catch_warnings(record=True): # deprecation csd_fourier = csd_epochs(epochs, mode='fourier').get_data() csd_mt = csd_epochs(epochs, mode='multitaper').get_data() fourier_power = np.abs(csd_fourier[0, 0]) * sfreq mt_power = np.abs(csd_mt[0, 0]) * sfreq assert abs(fourier_power - signal_power) <= 0.5 assert abs(mt_power - signal_power) <= 1 # Power per sample should not depend on time window length for tmax in [0.2, 0.8]: t_mask = (epochs.times >= 0) & (epochs.times <= tmax) n_samples = sum(t_mask) for add_n_fft in [0, 30]: n_fft = n_samples + add_n_fft with warnings.catch_warnings(record=True): # deprecation csd_fourier = csd_epochs( epochs, mode='fourier', tmin=None, tmax=tmax, fmin=0, fmax=np.inf, n_fft=n_fft ).get_data() first_samp = csd_fourier[0, 0] fourier_power_per_sample = np.abs(first_samp) * sfreq / n_fft assert abs(signal_power_per_sample - fourier_power_per_sample) < 0.003 # Power per sample should not depend on number of tapers for n_tapers in [1, 2, 5]: mt_bandwidth = sfreq / float(n_samples) * (n_tapers + 1) with warnings.catch_warnings(record=True): # deprecation csd_mt = csd_epochs( epochs, mode='multitaper', tmin=None, tmax=tmax, fmin=0, fmax=np.inf, mt_bandwidth=mt_bandwidth, n_fft=n_fft ).get_data() mt_power_per_sample = np.abs(csd_mt[0, 0]) * sfreq / n_fft # The estimate of power gets worse for small time windows when more # tapers are used if n_tapers == 5 and tmax == 0.2: delta = 0.05 else: delta = 0.004 assert abs(signal_power_per_sample - mt_power_per_sample) < delta
def _get_data(tmin=-0.11, tmax=0.15, read_all_forward=True, compute_csds=True): """Read in data used in tests.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event)[:10] raw = mne.io.read_raw_fif(fname_raw, preload=False) raw.add_proj([], remove_existing=True) # we'll subselect so remove proj forward = mne.read_forward_solution(fname_fwd) if read_all_forward: forward_surf_ori = _read_forward_solution_meg( fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg( fname_fwd, force_fixed=True, use_cps=False) forward_vol = mne.read_forward_solution(fname_fwd_vol) forward_vol = mne.convert_forward_solution(forward_vol, surf_ori=True) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average().crop(0, None) # Computing the data and noise cross-spectral density matrices if compute_csds: data_csd = csd_epochs(epochs, mode='multitaper', tmin=0.045, tmax=None, fmin=8, fmax=12, mt_bandwidth=72.72) noise_csd = csd_epochs(epochs, mode='multitaper', tmin=None, tmax=0.0, fmin=8, fmax=12, mt_bandwidth=72.72) else: data_csd, noise_csd = None, None return raw, epochs, evoked, data_csd, noise_csd, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def test_csd_epochs_on_artificial_data(): """Test computing CSD on artificial data. """ epochs = _get_data(mode='sin') sfreq = epochs.info['sfreq'] # Computing signal power in the time domain signal_power = sum_squared(epochs._data) signal_power_per_sample = signal_power / len(epochs.times) # Computing signal power in the frequency domain data_csd_fourier = csd_epochs(epochs, mode='fourier') data_csd_mt = csd_epochs(epochs, mode='multitaper') fourier_power = np.abs(data_csd_fourier.data[0, 0]) * sfreq mt_power = np.abs(data_csd_mt.data[0, 0]) * sfreq assert_true(abs(fourier_power - signal_power) <= 0.5) assert_true(abs(mt_power - signal_power) <= 1) # Power per sample should not depend on time window length for tmax in [0.2, 0.8]: for add_n_fft in [0, 30]: t_mask = (epochs.times >= 0) & (epochs.times <= tmax) n_samples = sum(t_mask) n_fft = n_samples + add_n_fft data_csd_fourier = csd_epochs(epochs, mode='fourier', tmin=None, tmax=tmax, fmin=0, fmax=np.inf, n_fft=n_fft) first_samp = data_csd_fourier.data[0, 0] fourier_power_per_sample = np.abs(first_samp) * sfreq / n_fft assert_true(abs(signal_power_per_sample - fourier_power_per_sample) < 0.003) # Power per sample should not depend on number of tapers for n_tapers in [1, 2, 5]: for add_n_fft in [0, 30]: mt_bandwidth = sfreq / float(n_samples) * (n_tapers + 1) data_csd_mt = csd_epochs(epochs, mode='multitaper', tmin=None, tmax=tmax, fmin=0, fmax=np.inf, mt_bandwidth=mt_bandwidth, n_fft=n_fft) mt_power_per_sample = np.abs(data_csd_mt.data[0, 0]) *\ sfreq / data_csd_mt.n_fft # The estimate of power gets worse for small time windows when # more tapers are used if n_tapers == 5 and tmax == 0.2: delta = 0.05 else: delta = 0.004 assert_true(abs(signal_power_per_sample - mt_power_per_sample) < delta)
def test_tf_dics(): """Test TF beamforming based on DICS """ tmin, tmax, tstep = -0.2, 0.2, 0.1 raw, epochs, _, _, _, label, forward, _, _, _ =\ _get_data(tmin, tmax, read_all_forward=False, compute_csds=False) freq_bins = [(4, 20), (30, 55)] win_lengths = [0.2, 0.2] reg = 0.001 noise_csds = [] for freq_bin, win_length in zip(freq_bins, win_lengths): noise_csd = csd_epochs(epochs, mode='fourier', fmin=freq_bin[0], fmax=freq_bin[1], fsum=True, tmin=tmin, tmax=tmin + win_length) noise_csds.append(noise_csd) stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label) assert_true(len(stcs) == len(freq_bins)) assert_true(stcs[0].shape[1] == 4) # Manually calculating source power in several time windows to compare # results and test overlapping source_power = [] time_windows = [(-0.1, 0.1), (0.0, 0.2)] for time_window in time_windows: data_csd = csd_epochs(epochs, mode='fourier', fmin=freq_bins[0][0], fmax=freq_bins[0][1], fsum=True, tmin=time_window[0], tmax=time_window[1]) noise_csd = csd_epochs(epochs, mode='fourier', fmin=freq_bins[0][0], fmax=freq_bins[0][1], fsum=True, tmin=-0.2, tmax=0.0) data_csd.data /= data_csd.n_fft noise_csd.data /= noise_csd.n_fft stc_source_power = dics_source_power(epochs.info, forward, noise_csd, data_csd, reg=reg, label=label) source_power.append(stc_source_power.data) # Averaging all time windows that overlap the time period 0 to 100 ms source_power = np.mean(source_power, axis=0) # Selecting the first frequency bin in tf_dics results stc = stcs[0] # Comparing tf_dics results with dics_source_power results assert_array_almost_equal(stc.data[:, 2], source_power[:, 0]) # Test if using unsupported max-power orientation is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins, pick_ori='max-power') # Test if incorrect number of noise CSDs is detected assert_raises(ValueError, tf_dics, epochs, forward, [noise_csds[0]], tmin, tmax, tstep, win_lengths, freq_bins=freq_bins) # Test if freq_bins and win_lengths incompatibility is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins) # Test if time step exceeding window lengths is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins) # Test if incorrect number of mt_bandwidths is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins, mode='multitaper', mt_bandwidths=[20]) # Pass only one epoch to test if subtracting evoked responses yields zeros stcs = tf_dics(epochs[0], forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins, subtract_evoked=True, reg=reg, label=label) assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12)) evoked = epochs.average() # Read forward operator forward = mne.read_forward_solution(fname_fwd, surf_ori=True) # Computing the data and noise cross-spectral density matrices # The time-frequency window was chosen on the basis of spectrograms from # example time_frequency/plot_time_frequency.py data_csd = csd_epochs(epochs, mode='multitaper', tmin=0.04, tmax=0.15, fmin=6, fmax=10) noise_csd = csd_epochs(epochs, mode='multitaper', tmin=-0.11, tmax=0.0, fmin=6, fmax=10) evoked = epochs.average() # Compute DICS spatial filter and estimate source time courses on evoked data stc = dics(evoked, forward, noise_csd, data_csd, reg=0.05) plt.figure()
pick_ori=None) stc20 = apply_inverse(evoked20, inverse_operator20, lambda2, method=method, pick_ori=None) stc40.save(stc40_fname, ftype='stc') stc30.save(stc30_fname, ftype='stc') stc20.save(stc20_fname, ftype='stc') ##40 hz####################################################### data_csd40 = csd_epochs(epochs40, mode='multitaper', tmin=0.01, tmax=0.50, fmin=35, fmax=45) noise_csd40 = csd_epochs(epochs40, mode='multitaper', tmin=-0.49, tmax=0.00, fmin=35, fmax=45) stc40_2 = dics_source_power(epochs40.info, fwd40, noise_csd40, data_csd40) # Compute DICS spatial filter and estimate source power stc40_3 = dics(evoked40, fwd40, noise_csd40, data_csd40, reg=0.05) stc40_2.save(stc40_fname2, ftype='stc') stc40_3.save(stc40_fname3, ftype='stc') ################################################################
# Then set FFTs length for each frequency range. # Should be a power of 2 to be faster. n_ffts = [256, 128, 128, 128] # Subtract evoked response prior to computation? subtract_evoked = False # Calculating noise cross-spectral density from empty room noise for each # frequency bin and the corresponding time window length. To calculate noise # from the baseline period in the data, change epochs_noise to epochs noise_csds = [] for freq_bin, win_length, n_fft in zip(freq_bins, win_lengths, n_ffts): noise_csd = csd_epochs(epochs_noise, mode='fourier', fmin=freq_bin[0], fmax=freq_bin[1], fsum=True, tmin=-win_length, tmax=0, n_fft=n_fft) noise_csds.append(noise_csd) # Computing DICS solutions for time-frequency windows in a label in source # space for faster computation, use label=None for full solution stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins,
def test_tf_dics(): """Test TF beamforming based on DICS.""" tmin, tmax, tstep = -0.2, 0.2, 0.1 raw, epochs, _, _, _, label, forward, _, _, _ =\ _get_data(tmin, tmax, read_all_forward=False, compute_csds=False) freq_bins = [(4, 20), (30, 55)] win_lengths = [0.2, 0.2] reg = 0.05 noise_csds = [] for freq_bin, win_length in zip(freq_bins, win_lengths): noise_csd = csd_epochs(epochs, mode='fourier', fmin=freq_bin[0], fmax=freq_bin[1], fsum=True, tmin=tmin, tmax=tmin + win_length) noise_csds.append(noise_csd) stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label) assert_true(len(stcs) == len(freq_bins)) assert_true(stcs[0].shape[1] == 4) assert_true(2.2 < stcs[0].data.max() < 2.3) assert_true(0.94 < stcs[0].data.min() < 0.95) # Manually calculating source power in several time windows to compare # results and test overlapping source_power = [] time_windows = [(-0.1, 0.1), (0.0, 0.2)] for time_window in time_windows: data_csd = csd_epochs(epochs, mode='fourier', fmin=freq_bins[0][0], fmax=freq_bins[0][1], fsum=True, tmin=time_window[0], tmax=time_window[1]) noise_csd = csd_epochs(epochs, mode='fourier', fmin=freq_bins[0][0], fmax=freq_bins[0][1], fsum=True, tmin=-0.2, tmax=0.0) data_csd.data /= data_csd.n_fft noise_csd.data /= noise_csd.n_fft stc_source_power = dics_source_power(epochs.info, forward, noise_csd, data_csd, reg=reg, label=label) source_power.append(stc_source_power.data) # Averaging all time windows that overlap the time period 0 to 100 ms source_power = np.mean(source_power, axis=0) # Selecting the first frequency bin in tf_dics results stc = stcs[0] # Comparing tf_dics results with dics_source_power results assert_array_almost_equal(stc.data[:, 2], source_power[:, 0]) # Test if using unsupported max-power orientation is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins, pick_ori='max-power') # Test if incorrect number of noise CSDs is detected assert_raises(ValueError, tf_dics, epochs, forward, [noise_csds[0]], tmin, tmax, tstep, win_lengths, freq_bins=freq_bins) # Test if freq_bins and win_lengths incompatibility is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins) # Test if time step exceeding window lengths is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins) # Test if incorrect number of mt_bandwidths is detected assert_raises(ValueError, tf_dics, epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins, mode='multitaper', mt_bandwidths=[20]) # Pass only one epoch to test if subtracting evoked responses yields zeros stcs = tf_dics(epochs[0], forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins, subtract_evoked=True, reg=reg, label=label) assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
def test_csd_epochs(): """Test computing cross-spectral density from epochs. """ epochs = _get_data(mode='real') # Check that wrong parameters are recognized assert_raises(ValueError, csd_epochs, epochs, mode='notamode') assert_raises(ValueError, csd_epochs, epochs, fmin=20, fmax=10) assert_raises(ValueError, csd_epochs, epochs, fmin=20, fmax=20.1) assert_raises(ValueError, csd_epochs, epochs, tmin=0.15, tmax=0.1) assert_raises(ValueError, csd_epochs, epochs, tmin=0, tmax=10) assert_raises(ValueError, csd_epochs, epochs, tmin=10, tmax=11) data_csd_mt = csd_epochs(epochs, mode='multitaper', fmin=8, fmax=12, tmin=0.04, tmax=0.15) data_csd_fourier = csd_epochs(epochs, mode='fourier', fmin=8, fmax=12, tmin=0.04, tmax=0.15) # Check shape of the CSD matrix n_chan = len(data_csd_mt.ch_names) assert_equal(data_csd_mt.data.shape, (n_chan, n_chan)) assert_equal(data_csd_fourier.data.shape, (n_chan, n_chan)) # Check if the CSD matrix is hermitian assert_array_equal( np.tril(data_csd_mt.data).T.conj(), np.triu(data_csd_mt.data)) assert_array_equal( np.tril(data_csd_fourier.data).T.conj(), np.triu(data_csd_fourier.data)) # Computing induced power for comparison epochs.crop(tmin=0.04, tmax=0.15) tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False) power = np.mean(tfr.data, 2) # Maximum PSD should occur for specific channel max_ch_power = power.argmax() max_ch_mt = data_csd_mt.data.diagonal().argmax() max_ch_fourier = data_csd_fourier.data.diagonal().argmax() assert_equal(max_ch_mt, max_ch_power) assert_equal(max_ch_fourier, max_ch_power) # Maximum CSD should occur for specific channel ch_csd_mt = np.abs(data_csd_mt.data[max_ch_power]) ch_csd_mt[max_ch_power] = 0. max_ch_csd_mt = np.argmax(ch_csd_mt) ch_csd_fourier = np.abs(data_csd_fourier.data[max_ch_power]) ch_csd_fourier[max_ch_power] = 0. max_ch_csd_fourier = np.argmax(ch_csd_fourier) assert_equal(max_ch_csd_mt, max_ch_csd_fourier) # Check a list of CSD matrices is returned for multiple frequencies within # a given range when fsum=False csd_fsum = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=True) csds = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=False) freqs = [csd.frequencies[0] for csd in csds] csd_sum = np.zeros_like(csd_fsum.data) for csd in csds: csd_sum += csd.data assert_equal(len(csds), 2) assert_equal(len(csd_fsum.frequencies), 2) assert_array_equal(csd_fsum.frequencies, freqs) assert_array_equal(csd_fsum.data, csd_sum)
preload=True, reject=dict(grad=4000e-13, mag=4e-12)) evoked = epochs.average() # Read forward operator forward = mne.read_forward_solution(fname_fwd) # Computing the data and noise cross-spectral density matrices # The time-frequency window was chosen on the basis of spectrograms from # example time_frequency/plot_time_frequency.py # As fsum is False csd_epochs returns a list of CrossSpectralDensity # instances than can then be passed to dics_source_power data_csds = csd_epochs(epochs, mode='multitaper', tmin=0.04, tmax=0.15, fmin=15, fmax=30, fsum=False) noise_csds = csd_epochs(epochs, mode='multitaper', tmin=-0.11, tmax=-0.001, fmin=15, fmax=30, fsum=False) # Compute DICS spatial filter and estimate source power stc = dics_source_power(epochs.info, forward, noise_csds, data_csds) for i, csd in enumerate(data_csds):
event_id, tmin, tmax = 1, -0.2, 0.5 events = mne.read_events(event_fname) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12)) evoked = epochs.average() # Read forward operator forward = mne.read_forward_solution(fname_fwd) # Computing the data and noise cross-spectral density matrices # The time-frequency window was chosen on the basis of spectrograms from # example time_frequency/plot_time_frequency.py # As fsum is False csd_epochs returns a list of CrossSpectralDensity # instances than can then be passed to dics_source_power data_csds = csd_epochs(epochs, mode='multitaper', tmin=0.04, tmax=0.15, fmin=15, fmax=30, fsum=False) noise_csds = csd_epochs(epochs, mode='multitaper', tmin=-0.11, tmax=-0.001, fmin=15, fmax=30, fsum=False) # Compute DICS spatial filter and estimate source power stc = dics_source_power(epochs.info, forward, noise_csds, data_csds) for i, csd in enumerate(data_csds): message = 'DICS source power at %0.1f Hz' % csd.freqs[0] brain = stc.plot(surface='inflated', hemi='rh', subjects_dir=subjects_dir, time_label=message, figure=i) brain.set_data_time_index(i) brain.show_view('lateral') # Uncomment line below to save images # brain.save_image('DICS_source_power_freq_%d.png' % csd.freqs[0])
def test_csd_epochs(): """Test computing cross-spectral density from epochs. """ epochs = _get_data(mode='real') # Check that wrong parameters are recognized assert_raises(ValueError, csd_epochs, epochs, mode='notamode') assert_raises(ValueError, csd_epochs, epochs, fmin=20, fmax=10) assert_raises(ValueError, csd_epochs, epochs, fmin=20, fmax=20.1) assert_raises(ValueError, csd_epochs, epochs, tmin=0.15, tmax=0.1) assert_raises(ValueError, csd_epochs, epochs, tmin=0, tmax=10) assert_raises(ValueError, csd_epochs, epochs, tmin=10, tmax=11) data_csd_mt = csd_epochs(epochs, mode='multitaper', fmin=8, fmax=12, tmin=0.04, tmax=0.15) data_csd_fourier = csd_epochs(epochs, mode='fourier', fmin=8, fmax=12, tmin=0.04, tmax=0.15) # Check shape of the CSD matrix n_chan = len(data_csd_mt.ch_names) assert_equal(data_csd_mt.data.shape, (n_chan, n_chan)) assert_equal(data_csd_fourier.data.shape, (n_chan, n_chan)) # Check if the CSD matrix is hermitian assert_array_equal(np.tril(data_csd_mt.data).T.conj(), np.triu(data_csd_mt.data)) assert_array_equal(np.tril(data_csd_fourier.data).T.conj(), np.triu(data_csd_fourier.data)) # Computing induced power for comparison epochs.crop(tmin=0.04, tmax=0.15) tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False) power = np.mean(tfr.data, 2) # Maximum PSD should occur for specific channel max_ch_power = power.argmax() max_ch_mt = data_csd_mt.data.diagonal().argmax() max_ch_fourier = data_csd_fourier.data.diagonal().argmax() assert_equal(max_ch_mt, max_ch_power) assert_equal(max_ch_fourier, max_ch_power) # Maximum CSD should occur for specific channel ch_csd_mt = np.abs(data_csd_mt.data[max_ch_power]) ch_csd_mt[max_ch_power] = 0. max_ch_csd_mt = np.argmax(ch_csd_mt) ch_csd_fourier = np.abs(data_csd_fourier.data[max_ch_power]) ch_csd_fourier[max_ch_power] = 0. max_ch_csd_fourier = np.argmax(ch_csd_fourier) assert_equal(max_ch_csd_mt, max_ch_csd_fourier) # Check a list of CSD matrices is returned for multiple frequencies within # a given range when fsum=False csd_fsum = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=True) csds = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=False) freqs = [csd.frequencies[0] for csd in csds] csd_sum = np.zeros_like(csd_fsum.data) for csd in csds: csd_sum += csd.data assert_equal(len(csds), 2) assert_equal(len(csd_fsum.frequencies), 2) assert_array_equal(csd_fsum.frequencies, freqs) assert_array_equal(csd_fsum.data, csd_sum)
def test_csd_epochs(): """Test computing cross-spectral density from epochs.""" epochs = _get_real_data() # Check that wrong parameters are recognized raises(ValueError, csd_epochs, epochs, mode='notamode') raises(ValueError, csd_epochs, epochs, fmin=20, fmax=10) raises(ValueError, csd_epochs, epochs, fmin=20, fmax=20.1) raises(ValueError, csd_epochs, epochs, tmin=0.15, tmax=0.1) raises(ValueError, csd_epochs, epochs, tmin=0, tmax=10) raises(ValueError, csd_epochs, epochs, tmin=10, tmax=11) # Test deprecation warning with warnings.catch_warnings(record=True) as ws: warnings.simplefilter('always') csd_mt = csd_epochs(epochs, mode='multitaper', fmin=8, fmax=12, tmin=0.04, tmax=0.15) assert len([w for w in ws if issubclass(w.category, DeprecationWarning)]) == 1 csd_fourier = csd_epochs(epochs, mode='fourier', fmin=8, fmax=12, tmin=0.04, tmax=0.15) # Check shape of the CSD matrix n_chan = len(csd_mt.ch_names) csd_mt_data = csd_mt.get_data() csd_fourier_data = csd_fourier.get_data() assert csd_mt_data.shape == (n_chan, n_chan) assert csd_fourier_data.shape == (n_chan, n_chan) # Check if the CSD matrix is hermitian assert_array_equal(np.tril(csd_mt_data).T.conj(), np.triu(csd_mt_data)) assert_array_equal( np.tril(csd_fourier_data).T.conj(), np.triu(csd_fourier_data)) # Computing induced power for comparison epochs.crop(tmin=0.04, tmax=0.15) tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False) power = np.mean(tfr.data, 2) # Maximum PSD should occur for specific channel max_ch_power = power.argmax() max_ch_mt = csd_mt_data.diagonal().argmax() max_ch_fourier = csd_fourier_data.diagonal().argmax() assert max_ch_mt == max_ch_power assert max_ch_fourier == max_ch_power # Maximum CSD should occur for specific channel ch_csd_mt = np.abs(csd_mt_data[max_ch_power]) ch_csd_mt[max_ch_power] = 0. max_ch_csd_mt = np.argmax(ch_csd_mt) ch_csd_fourier = np.abs(csd_fourier_data[max_ch_power]) ch_csd_fourier[max_ch_power] = 0. max_ch_csd_fourier = np.argmax(ch_csd_fourier) assert max_ch_csd_mt == max_ch_csd_fourier # Check a list of CSD matrices is returned for multiple frequencies within # a given range when fsum=False csd_fsum = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=True) csds = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=False) assert len(csd_fsum.frequencies) == 1 assert len(csds.frequencies) == 2 assert_array_equal(csd_fsum.frequencies[0], csds.frequencies) csd_sum = csds._data.sum(axis=1, keepdims=True) assert_array_equal(csd_fsum._data, csd_sum)
freq_bins = [(4, 12), (12, 30), (30, 55), (65, 300)] # Hz win_lengths = [0.3, 0.2, 0.15, 0.1] # s # Then set FFTs length for each frequency range. # Should be a power of 2 to be faster. n_ffts = [256, 128, 128, 128] # Subtract evoked response prior to computation? subtract_evoked = False # Calculating noise cross-spectral density from empty room noise for each # frequency bin and the corresponding time window length. To calculate noise # from the baseline period in the data, change epochs_noise to epochs noise_csds = [] for freq_bin, win_length, n_fft in zip(freq_bins, win_lengths, n_ffts): noise_csd = csd_epochs(epochs_noise, mode='fourier', fmin=freq_bin[0], fmax=freq_bin[1], fsum=True, tmin=-win_length, tmax=0, n_fft=n_fft) noise_csds.append(noise_csd) # Computing DICS solutions for time-frequency windows in a label in source # space for faster computation, use label=None for full solution stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins, subtract_evoked=subtract_evoked, n_ffts=n_ffts, reg=0.001, label=label) # Plotting source spectrogram for source with maximum activity # Note that tmin and tmax are set to display a time range that is smaller than # the one for which beamforming estimates were calculated. This ensures that # all time bins shown are a result of smoothing across an identical number of # time windows. plot_source_spectrogram(stcs, freq_bins, tmin=tmin_plot, tmax=tmax_plot,
# Read epochs event_id, tmin, tmax = 1, -0.2, 0.5 events = mne.read_events(event_fname) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12)) evoked = epochs.average() # Read forward operator forward = mne.read_forward_solution(fname_fwd) # Computing the data and noise cross-spectral density matrices # The time-frequency window was chosen on the basis of spectrograms from # example time_frequency/plot_time_frequency.py data_csd = csd_epochs(epochs, mode='multitaper', tmin=0.04, tmax=0.15, fmin=6, fmax=10) noise_csd = csd_epochs(epochs, mode='multitaper', tmin=-0.11, tmax=0.0, fmin=6, fmax=10) evoked = epochs.average() # Compute DICS spatial filter and estimate source time courses on evoked data stc = dics(evoked, forward, noise_csd, data_csd, reg=0.05) plt.figure() ts_show = -30 # show the 40 largest responses plt.plot(1e3 * stc.times, stc.data[np.argsort(stc.data.max(axis=1))[ts_show:]].T) plt.xlabel('Time (ms)') plt.ylabel('DICS value') plt.title('DICS time course of the 30 largest sources.')
def test_csd_epochs(): """Test computing cross-spectral density from epochs.""" epochs = _get_real_data() # Check that wrong parameters are recognized with warnings.catch_warnings(record=True): # deprecation raises(ValueError, csd_epochs, epochs, mode='notamode') raises(ValueError, csd_epochs, epochs, fmin=20, fmax=10) raises(ValueError, csd_epochs, epochs, fmin=20, fmax=20.1) raises(ValueError, csd_epochs, epochs, tmin=0.15, tmax=0.1) raises(ValueError, csd_epochs, epochs, tmin=0, tmax=10) raises(ValueError, csd_epochs, epochs, tmin=10, tmax=11) # Test deprecation warning with warnings.catch_warnings(record=True) as ws: warnings.simplefilter('always') csd_mt = csd_epochs(epochs, mode='multitaper', fmin=8, fmax=12, tmin=0.04, tmax=0.15) assert len([w for w in ws if issubclass(w.category, DeprecationWarning)]) == 1 with warnings.catch_warnings(record=True): # deprecation csd_fourier = csd_epochs(epochs, mode='fourier', fmin=8, fmax=12, tmin=0.04, tmax=0.15) # Check shape of the CSD matrix n_chan = len(csd_mt.ch_names) csd_mt_data = csd_mt.get_data() csd_fourier_data = csd_fourier.get_data() assert csd_mt_data.shape == (n_chan, n_chan) assert csd_fourier_data.shape == (n_chan, n_chan) # Check if the CSD matrix is hermitian assert_array_equal(np.tril(csd_mt_data).T.conj(), np.triu(csd_mt_data)) assert_array_equal(np.tril(csd_fourier_data).T.conj(), np.triu(csd_fourier_data)) # Computing induced power for comparison epochs.crop(tmin=0.04, tmax=0.15) tfr = tfr_morlet(epochs, freqs=[10], n_cycles=0.6, return_itc=False) power = np.mean(tfr.data, 2) # Maximum PSD should occur for specific channel max_ch_power = power.argmax() max_ch_mt = csd_mt_data.diagonal().argmax() max_ch_fourier = csd_fourier_data.diagonal().argmax() assert max_ch_mt == max_ch_power assert max_ch_fourier == max_ch_power # Maximum CSD should occur for specific channel ch_csd_mt = np.abs(csd_mt_data[max_ch_power]) ch_csd_mt[max_ch_power] = 0. max_ch_csd_mt = np.argmax(ch_csd_mt) ch_csd_fourier = np.abs(csd_fourier_data[max_ch_power]) ch_csd_fourier[max_ch_power] = 0. max_ch_csd_fourier = np.argmax(ch_csd_fourier) assert max_ch_csd_mt == max_ch_csd_fourier # Check a list of CSD matrices is returned for multiple frequencies within # a given range when fsum=False with warnings.catch_warnings(record=True): # deprecation csd_fsum = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=True) csds = csd_epochs(epochs, mode='fourier', fmin=8, fmax=20, fsum=False) assert len(csd_fsum.frequencies) == 1 assert len(csds.frequencies) == 2 assert_array_equal(csd_fsum.frequencies[0], csds.frequencies) csd_sum = csds._data.sum(axis=1, keepdims=True) assert_array_equal(csd_fsum._data, csd_sum)