def test_conn_covgc(self): """Test function conn_covgc.""" n_epochs = 5 n_times = 100 n_roi = 3 x = np.random.rand(n_epochs, n_roi, n_times) dt = 10 lag = 2 t0 = [50, 80] _ = conn_covgc(x, dt, lag, t0, n_jobs=1, method='gc') gc = conn_covgc(x, dt, lag, t0, n_jobs=1, method='gauss') assert gc.shape == (n_epochs, 3, len(t0), 3) assert isinstance(gc, xr.DataArray) gc = conn_covgc(x, dt, lag, t0, n_jobs=1, method='gc', conditional=True)
def compute_covgc(self, ar, dt=50, lag=5, step=1, method='gc', conditional=False): """Compute the Covariance-based Granger Causality. In addition of computing the Granger Causality, the mutual-information between the Granger causalitity and the stimulus is also computed. Parameters ---------- dt : int Duration of the time window for covariance correlation in samples lag : int Number of samples for the lag within each trial step : int | 1 Number of samples stepping between each sliding window onset method : {'gauss', 'gc'} Method for the estimation of the covgc. Use either 'gauss' which assumes that the time-points are normally distributed or 'gc' in order to use the gaussian-copula. Returns ------- gc : array_like Granger Causality arranged as (n_epochs, n_pairs, n_windows, 3) where the last dimension means : * 0 : pairs[:, 0] -> pairs[:, 1] (x->y) * 1 : pairs[:, 1] -> pairs[:, 0] (y->x) * 2 : instantaneous (x.y) """ # compute the granger causality t0 = np.arange(lag, ar.shape[-1] - dt, step) gc = conn_covgc(ar, dt, lag, t0, times='times', method=method, roi='roi', step=1, conditional=conditional) gc['trials'] = ar['trials'] self._gc = gc # compute the MI between stimulus / raw mi = mi_model_nd_gd(gc.data, gc['trials'].data, traxis=0) self._mi = xr.DataArray(mi, dims=('roi', 'times', 'direction'), coords=(gc['roi'], gc['times'], gc['direction'])) self._mi.attrs['description'] = ( "Mutual information between the stimulus and the output of the " "covgc") return gc
def test_conn_reshape_directed(self): """Test function conn_reshape_directed.""" n_epochs, n_times, n_roi = 5, 100, 3 x = np.random.rand(n_epochs, n_roi, n_times) dt, lag, t0 = 10, 2, [50, 80] order = ['roi_2', 'roi_1'] # compute covgc gc = conn_covgc(x, dt, lag, t0, n_jobs=1, method='gauss') gc = gc.mean('trials') # reshape it without the time dimension gc_mean = conn_reshape_directed(gc.copy().mean('times')) assert gc_mean.shape == (n_roi, n_roi, 1) # reshape it with the time dimension gc_times = conn_reshape_directed(gc.copy()) assert gc_times.shape == (n_roi, n_roi, len(gc['times'])) # try the reorder gc_order = conn_reshape_directed(gc.copy(), order=order) assert gc_order.shape == (2, 2, len(gc['times'])) assert np.array_equal(gc_order['sources'], gc_order['targets']) assert np.array_equal(gc_order['sources'], order)
# directed flow from 0 to 1 (0->1) x[:, [0], slice(600, 800)] += x[:, [1], slice(600, 800)] x[:, [0], slice(599, 799)] += x[:, [0], slice(600, 800)] ############################################################################### # Compute the covgc # ----------------- # # The covgc is going to be computed per trials, bewteen pairs of ROI and inside # each of the temporal window t0 = np.arange(100, 900, 10) lag = 10 dt = 100 gc = conn_covgc(x, dt, lag, t0, times=times, roi=roi, n_jobs=1) roi_p = gc['roi'].data ############################################################################### # Below we plot the mean time series of both directed and undirected covgc # take the mean across trials gc = gc.mean('trials') plt.figure(figsize=(10, 8)) plt.subplot(311) for r in roi_p: plt.plot(gc.times.data, gc.sel(roi=r, direction='x->y').T, label=r.replace('-', ' -> ')) plt.legend() plt.subplot(312)
# ----------------------------- # # We first compute the Granger Causality and then the conditional Granger # causality (i.e conditioning by the past coming from other sources) dt, lag, step = 50, 5, 2 t0 = np.arange(lag, ar.shape[-1] - dt, step) kw_gc = dict(dt=dt, lag=lag, step=1, t0=t0, roi='roi', times='times', n_jobs=-1) # granger causality gc = conn_covgc(ar, conditional=False, **kw_gc) # conditional granger causality gc_cond = conn_covgc(ar, conditional=True, **kw_gc) ############################################################################### # Plot the Granger causality plt.figure(figsize=(12, 10)) ss.plot_covgc(gc) plt.tight_layout() plt.show() ############################################################################### # Plot the conditional Granger causality
# ------------------------------------------------- # # The final point of this tutorial is to try to compute the directed # connectivity and perform the stats on it to see whether the information is # sent from one region to another (which should be X->Y) # covgc settings dt = 50 lag = 5 step = 3 t0 = np.arange(lag, len(times) - dt, step) # compute the covgc for each subject gc = [] for n_s in range(n_subjects): _gc = conn_covgc(x[n_s], roi='roi', times='times', dt=dt, lag=lag, t0=t0, n_jobs=1) gc += [_gc] gc_times, gc_roi = _gc['times'].data, _gc['roi'].data # plot the mean covgc across subjects gc_suj = xr.concat(gc, 'trials').groupby('trials').mean('trials') fig, gs = plt.subplots(3, 3, sharex='all', sharey='all', figsize=(12, 12)) for n_d, direction in enumerate(['x->y', 'y->x', 'x.y']): for n_r, r in enumerate(gc_roi): gc_dir_r = gc_suj.sel(direction=direction, roi=r) plt.sca(gs[n_d, n_r]) plt.plot(gc_times, gc_dir_r.sel(trials=1), color='red') plt.plot(gc_times, gc_dir_r.sel(trials=2), color='green')
############################################################################### # plot the power spectrum density (PSD) plt.figure(figsize=(7, 8)) ss.plot(cmap='Reds', psd=True) plt.tight_layout() plt.show() ############################################################################### # Compute the Granger-Causality # ----------------------------- # # We then compute and plot the Granger Causality. From the plot you can see # that there's indeed an information transfer from X->Y and X->Z and, in # addition, an instantaneous connectivity between Y.Z dt = 50 lag = 5 step = 2 t0 = np.arange(lag, ar.shape[-1] - dt, step) gc = conn_covgc(ar, roi='roi', times='times', dt=dt, lag=lag, t0=t0, n_jobs=-1) # sphinx_gallery_thumbnail_number = 4 plt.figure(figsize=(12, 10)) ss.plot_covgc(gc) plt.tight_layout() plt.show()