def test_csd_morlet(): """Test computing cross-spectral density using Morlet wavelets.""" epochs = _generate_coherence_data() sfreq = epochs.info['sfreq'] # Compute CSDs by a variety of methods freqs = [10, 15, 22] n_cycles = [20, 30, 44] times = [(None, None), (1, 9)] as_arrays = [False, True] parameters = product(times, as_arrays) for (tmin, tmax), as_array in parameters: if as_array: csd = csd_array_morlet(epochs.get_data(), sfreq, freqs, t0=epochs.tmin, n_cycles=n_cycles, tmin=tmin, tmax=tmax, ch_names=epochs.ch_names) else: csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles, tmin=tmin, tmax=tmax) if tmin is None and tmax is None: assert csd.tmin == 0 and csd.tmax == 9.98 else: assert csd.tmin == tmin and csd.tmax == tmax _test_csd_matrix(csd) # CSD diagonals should contain PSD tfr = tfr_morlet(epochs, freqs, n_cycles, return_itc=False) power = np.mean(tfr.data, 2) csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles) assert_allclose(csd._data[[0, 3, 5]] * sfreq, power) # Test using plain convolution instead of FFT csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles, use_fft=False) assert_allclose(csd._data[[0, 3, 5]] * sfreq, power) # Test baselining warning with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs_nobase = epochs.copy() epochs_nobase.baseline = None epochs_nobase.info['highpass'] = 0 csd = csd_morlet(epochs_nobase, frequencies=[10], decim=20) assert len(w) == 1
def test_csd_morlet(): """Test computing cross-spectral density using Morlet wavelets.""" epochs = _generate_coherence_data() sfreq = epochs.info['sfreq'] # Compute CSDs by a variety of methods freqs = [10, 15, 22] n_cycles = [20, 30, 44] times = [(None, None), (1, 9)] as_arrays = [False, True] parameters = product(times, as_arrays) for (tmin, tmax), as_array in parameters: if as_array: csd = csd_array_morlet(epochs.get_data(), sfreq, freqs, t0=epochs.tmin, n_cycles=n_cycles, tmin=tmin, tmax=tmax, ch_names=epochs.ch_names) else: csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles, tmin=tmin, tmax=tmax) if tmin is None and tmax is None: assert csd.tmin == 0 and csd.tmax == 9.98 else: assert csd.tmin == tmin and csd.tmax == tmax _test_csd_matrix(csd) # CSD diagonals should contain PSD tfr = tfr_morlet(epochs, freqs, n_cycles, return_itc=False) power = np.mean(tfr.data, 2) csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles) assert_allclose(csd._data[[0, 3, 5]] * sfreq, power) # Test using plain convolution instead of FFT csd = csd_morlet(epochs, frequencies=freqs, n_cycles=n_cycles, use_fft=False) assert_allclose(csd._data[[0, 3, 5]] * sfreq, power) # Test baselining warning epochs_nobase = epochs.copy() epochs_nobase.baseline = None epochs_nobase.info['highpass'] = 0 with pytest.warns(RuntimeWarning, match='baseline'): csd = csd_morlet(epochs_nobase, frequencies=[10], decim=20)
def functional_connectivity(data: pd.DataFrame, metric: str = 'cov', **kwargs) -> np.ndarray: """Calculate functional connectivity of node timeseries in data. Parameters ---------- data Pandas dataframe containing the simulation results. metric Type of connectivtiy measurement that should be used. - `cov` for covariance (uses `np.cov`) - `corr` for pearsson correlation (uses `np.corrcoef`) - `csd` for cross-spectral density (uses `mne.time_frequency.csd_array_morlet`) - `coh` for coherence (uses `mne.connectivtiy.spectral_connectivity`) - `cohy` for coherency (uses `mne.connectivtiy.spectral_connectivity`) - `imcoh` for imaginary coherence (uses `mne.connectivtiy.spectral_connectivity`) - `plv` for phase locking value (uses `mne.connectivtiy.spectral_connectivity`) - `ppc` for pairwise phase consistency (uses `mne.connectivtiy.spectral_connectivity`) - `pli` for phase lag index (uses `mne.connectivtiy.spectral_connectivity`) - `pli2_unbiased` for unbiased estimate of squared phase lag index (uses `mne.connectivtiy.spectral_connectivity`) - `wpli`for weighted phase lag index (uses `mne.connectivtiy.spectral_connectivity`) - `wpli2_debiased` for debiased weighted phase lag index (uses `mne.connectivtiy.spectral_connectivity`) kwargs Additional keyword arguments passed to respective function used for fc calculation. Returns ------- np.ndarray Pairwise functional connectivity """ if 'time' in data.columns.values: idx = data.pop('time') data.index = idx # calculate functional connectivity ################################### if metric == 'cov': # covariance fc = np.cov(data.values.T, **kwargs) elif metric == 'corr': # pearsson correlation coefficient fc = np.corrcoef(data.values.T, **kwargs) elif metric == 'csd': from mne.time_frequency import csd_array_morlet fc = np.abs(csd_array_morlet(X=np.reshape(data.values, (1, data.shape[1], data.shape[0])), sfreq=1./(data.index[1] - data.index[0]), ch_names=data.columns.values, **kwargs).mean().get_data()) elif metric in 'cohcohyimcohplvppcplipli2_unbiasedwpliwpli2_debiased': # phase-based connectivtiy/synchronization measurement from mne.connectivity import spectral_connectivity fc, _, _, _, _ = spectral_connectivity(np.reshape(data.values.T, (1, data.shape[1], data.shape[0])), method=metric, sfreq=1./(data.index[1] - data.index[0]), **kwargs) fc = fc.squeeze() else: raise ValueError(f'FC metric is not supported by this function: {metric}. Check the documentation of the ' f'argument `metric` for valid options.') return fc