Example #1
0
 def test_fit(self):
     """Test function fit."""
     data = np.random.rand(100, 1000)
     p = EventRelatedPac()
     pha = p.filter(256, data, 'phase')
     amp = p.filter(256, data, 'amplitude')
     p.fit(pha, amp, method='circular')
     p.fit(pha, amp, method='gc')
     p.fit(pha, amp, method='gc', n_perm=2)
     p.fit(pha, amp, method='gc', smooth=5)
     p.surrogates, p.pvalues
Example #2
0
 def test_fit(self):
     """Test function fit."""
     data = np.random.rand(100, 1000)
     p = EventRelatedPac()
     pha = p.filter(256, data, 'phase')
     amp = p.filter(256, data, 'amplitude')
     p.fit(pha, amp, method='circular')
     p.fit(pha, amp, method='gc')
Example #3
0
    def test_functional_erpac(self):
        """Test function test_functional_pac."""
        # erpac simultation
        n_epochs, n_times, sf, edges = 400, 1000, 512., 50
        x, times = pac_signals_wavelet(f_pha=10,
                                       f_amp=100,
                                       n_epochs=n_epochs,
                                       noise=.1,
                                       n_times=n_times,
                                       sf=sf)
        times = times[edges:-edges]
        # phase / amplitude extraction (single time)
        p = EventRelatedPac(f_pha=[8, 12],
                            f_amp=(30, 200, 5, 5),
                            dcomplex='wavelet',
                            width=12)
        kw = dict(n_jobs=1, edges=edges)
        phases = p.filter(sf, x, ftype='phase', **kw)
        amplitudes = p.filter(sf, x, ftype='amplitude', **kw)
        n_amp = len(p.yvec)
        # generate a normal distribution
        gt = np.zeros((n_amp, n_times - 2 * edges))
        b_amp = np.abs(p.yvec.reshape(-1, 1) - np.array([[80, 120]])).argmin(0)
        gt[b_amp[0]:b_amp[1] + 1, :] = True

        plt.figure(figsize=(16, 5))
        plt.subplot(131)
        p.pacplot(gt, times, p.yvec, title='Ground truth', cmap='magma')

        for n_meth, meth in enumerate(['circular', 'gc']):
            # compute erpac + p-values
            erpac = p.fit(phases,
                          amplitudes,
                          method=meth,
                          mcp='bonferroni',
                          n_perm=30).squeeze()
            pvalues = p.pvalues.squeeze()
            # find everywhere erpac is significant + compare to ground truth
            is_signi = pvalues < .05
            erpac[~is_signi] = np.nan
            # computes accuracy
            acc = 100 * (is_signi == gt).sum() / (n_amp * n_times)
            assert acc > 80.
            # plot the result
            title = f"Method={p.method}\nAccuracy={np.around(acc, 2)}%"
            plt.subplot(1, 3, n_meth + 2)
            p.pacplot(erpac, times, p.yvec, title=title)
        plt.tight_layout()
        plt.show()
Example #4
0
 def test_filterfit(self):
     """Test function filterfit."""
     p = EventRelatedPac()
     x_pha = np.random.rand(100, 1000)
     x_amp = np.random.rand(100, 1000)
     p.filterfit(256, x_pha, x_amp=x_amp, method='circular')
     p.filterfit(256, x_pha, x_amp=x_amp, method='gc')
Example #5
0
# Second signal : one second of random noise
x2 = np.random.rand(n_epochs, 1000)

# now, concatenate the two signals across the time axis
x = np.concatenate((x1, x2), axis=1)
time = np.arange(x.shape[1]) / sf

###############################################################################
# Define an ERPAC object and extract the phase and the amplitude
###############################################################################
# use :class:`tensorpac.EventRelatedPac.filter` method to extract phases and
# amplitudes

# define an ERPAC object
p = EventRelatedPac(f_pha=[9, 11], f_amp=(60, 140, 5, 1))

# method for correcting p-values for multiple comparisons
mcp = 'bonferroni'
# extract phases and amplitudes
erpac = p.filterfit(sf, x, method='circular', mcp=mcp).squeeze()
# get the p-values and squeeze unused dimensions
pvalues = p.pvalues.squeeze()
# set to nan everywhere it's not significant
erpac[pvalues > .05] = np.nan

vmin, vmax = np.nanmin(erpac), np.nanmax(erpac)

p.pacplot(erpac,
          time,
          p.yvec,
Example #6
0
# an alpha <-> gamma coupling. This peak is essentially comprised between
# [8, 12]Hz. This range of frequencies is then gonig to be used to see if there
# is indeed an alpha <-> gamma coupling (Aru et al. 2015
# :cite:`aru2015untangling`)

###############################################################################
# Compute and plot the Event-Related PAC
###############################################################################
# To go one step further we can use the Event-Related PAC (ERPAC) in order to
# isolate the gamma range that is coupled with the alpha phase such as when, in
# time, this coupling occurs. Here, we compute the ERPAC using the
# Gaussian-Copula mutual information (Ince et al. 2017
# :cite:`ince2017statistical`), between the alpha [8, 12]Hz and several gamma
# amplitudes, at each time point.

rp_obj = EventRelatedPac(f_pha=[8, 12], f_amp=(30, 160, 30, 2))
erpac = rp_obj.filterfit(sf, data, method='gc', smooth=100)

###############################################################################

plt.figure(figsize=(8, 6))
rp_obj.pacplot(erpac.squeeze(),
               times,
               rp_obj.yvec,
               xlabel='Time',
               ylabel='Amplitude frequency (Hz)',
               title='Event-Related PAC occurring for alpha phase',
               fz_labels=15,
               fz_title=18)
add_motor_condition(135, color='white')
plt.show()
Example #7
0
 def test_filter(self):
     """Test function filter."""
     data = np.random.rand(7, 1000)
     p = EventRelatedPac()
     p.filter(256, data, 'phase')
     p.filter(256, data, 'amplitude')
Example #8
0
# Second signal : one second of random noise
x2 = np.random.rand(n_epochs, 1000)

# now, concatenate the two signals across the time axis
x = np.concatenate((x1, x2), axis=1)
time = np.arange(x.shape[1]) / sf

###############################################################################
# Define an ERPAC object and extract the phase and the amplitude
###############################################################################
# use :class:`tensorpac.EventRelatedPac.filter` method to extract phases and
# amplitudes

# define an ERPAC object
p = EventRelatedPac(f_pha=[9, 11], f_amp=(60, 140, 5, 3))

# extract phases and amplitudes
pha = p.filter(sf, x, ftype='phase')
amp = p.filter(sf, x, ftype='amplitude')

###############################################################################
# Compute the ERPAC using the two implemented methods and plot it
###############################################################################

# implemented ERPAC methods
methods = ['circular', 'gc']

plt.figure(figsize=(16, 8))
for n_m, m in enumerate(methods):
    # compute the erpac
Example #9
0
plt.rc('font', family=cfg["font"])

###############################################################################
n_epochs = 300
n_times = 1000
sf = 1000.
###############################################################################

x1, tvec = pac_signals_wavelet(f_pha=10, f_amp=100, n_epochs=n_epochs, noise=2,
                               n_times=n_times, sf=sf)
x2 = np.random.rand(n_epochs, 1000)
x = np.concatenate((x1, x2), axis=1)
time = np.arange(x.shape[1]) / sf


p = EventRelatedPac(f_pha=[9, 11], f_amp='hres')
pha = p.filter(sf, x, ftype='phase', n_jobs=-1)
amp = p.filter(sf, x, ftype='amplitude', n_jobs=-1)

plt.figure(figsize=(14, 6))
for n_m, (method, nb) in enumerate(zip(['circular', 'gc'], ['A', 'B'])):
    # to be fair with the comparison between ERPAC and gcERPAC, the smoothing
    # parameter of the gcERPAC is turned off but results could look way better
    # if for example with add a `smooth=20`
    erpac = p.fit(pha, amp, method=method, n_jobs=-1).squeeze()
    plt.subplot(1, 2, n_m + 1)
    p.pacplot(erpac, time, p.yvec, xlabel='Time (second)', cmap=cfg["cmap"],
              ylabel='Frequency for amplitude (Hz)', title=p.method,
              vmin=0., rmaxis=True, fz_labels=20, fz_title=22, fz_cblabel=20)
    plt.axvline(1., linestyle='--', color='w', linewidth=2)
    if n_m == 1: plt.ylabel('')
Example #10
0
n_epochs = 300
n_times = 1000
sf = 1000.
###############################################################################

x1, tvec = pac_signals_wavelet(f_pha=10,
                               f_amp=100,
                               n_epochs=n_epochs,
                               noise=2,
                               n_times=n_times,
                               sf=sf)
x2 = np.random.rand(n_epochs, 1000)
x = np.concatenate((x1, x2), axis=1)
time = np.arange(x.shape[1]) / sf

p = EventRelatedPac(f_pha=[9, 11], f_amp=(60, 140, 5, 1))
pha = p.filter(sf, x, ftype='phase', n_jobs=1)
amp = p.filter(sf, x, ftype='amplitude', n_jobs=1)

plt.figure(figsize=(8, 6))
erpac = p.fit(pha, amp, method='circular', n_jobs=-1).squeeze()
p.pacplot(erpac,
          time,
          p.yvec,
          xlabel='Time (second)',
          cmap=cfg["cmap"],
          ylabel='Frequency for amplitude (Hz)',
          title='Event Related PAC',
          vmin=0.,
          rmaxis=True)
plt.axvline(1., linestyle='--', color='w', linewidth=2)
Example #11
0
from tensorpac import EventRelatedPac

import matplotlib.pyplot as plt
import seaborn as sns

plt.style.use('seaborn-poster')
sns.set_style("white")
plt.rc('font', family=cfg["font"])

# erpac simultation
n_epochs, n_times, sf, edges = 400, 1000, 512., 50
x, times = pac_signals_wavelet(f_pha=10, f_amp=100, n_epochs=n_epochs,
                               noise=.1, n_times=n_times, sf=sf)
times = times[edges:-edges]
# phase / amplitude extraction (single time)
p = EventRelatedPac(f_pha=[8, 12], f_amp=(30, 200, 5, 5),
                    dcomplex='wavelet', width=12)
kw = dict(n_jobs=1, edges=edges)
phases = p.filter(sf, x, ftype='phase', **kw)
amplitudes = p.filter(sf, x, ftype='amplitude', **kw)
n_amp = len(p.yvec)
# generate a normal distribution
gt = np.zeros((n_amp, n_times - 2 * edges))
b_amp = np.abs(p.yvec.reshape(-1, 1) - np.array([[80, 120]])).argmin(0)
gt[b_amp[0]:b_amp[1] + 1, :] = True

plt.figure(figsize=(16, 5))
plt.subplot(131)
p.pacplot(gt, times, p.yvec, title='Ground truth', cmap='magma')

for n_meth, meth in enumerate(['circular', 'gc']):
    # compute erpac + p-values