예제 #1
0
def comodulogram(po, pos, sig1, sig2, name, save=1, plot=1, vmax=0.01, mtrx=False):
    ax1 = py.subplot(gs[pos[2]:pos[3], pos[0]:pos[1]])
    set_axis(ax1, -0.05, 1.05, letter= po)
    estimator = Comodulogram(fs=Fs, low_fq_range= np.linspace(0.1, 4, 13), 
                             high_fq_range=np.linspace(30, 150, 25),
                             low_fq_width=0.5, method = 'tort',#method='duprelatour',
                             progress_bar=True, n_jobs=4)
    estimator.fit(sig1, sig2)
    low_fq=0.1
    high_fq=4
    low_mod=30
    high_mod=150
    if mtrx:
        im = py.imshow(mtrx, extent=[low_fq, high_fq, low_mod, high_mod], 
                       vmax=vmax, aspect='auto', origin='lower', cmap='Blues')    
    else:
        im = py.imshow(estimator.comod_.T, extent=[low_fq, high_fq, low_mod, high_mod], 
                       vmax=vmax, aspect='auto', origin='lower', cmap='Blues')

    py.ylim(30, 130)
    py.xlabel('Driving Frequency (Hz)', fontsize = 13)
    py.ylabel('Modulated high Frequency (Hz)', fontsize = 13)
    py.xticks(fontsize=14)
    py.yticks(fontsize=14) 
    
    cax2 = make_axes_locatable(ax1).append_axes("right", size="5%", pad=0)
    cbar = py.colorbar(im, cax = cax2)#, format=mpl.ticker.FuncFormatter(fmt))
    cbar.ax.set_title('MI', fontsize = 13)
    cbar.ax.tick_params(labelsize=9)
    return estimator.comod_.T
def compute_pt_tp(n_jobs, n_perm, title=''):
    """Compute Pactools and Tensorpac."""
    cpt, meth_comp, soft = [], [], []
    for meth in ['MVL', 'MI', 'PLV']:
        # ---------------------------------------------------------------------
        # get the method name
        meth_pt = METH['PACTOOLS'][meth]
        meth_tp = METH['TENSORPAC'][meth]

        if n_perm > 0:
            idpac = (meth_tp, 2, 4)
        else:
            idpac = (meth_tp, 0, 0)

        # ---------------------------------------------------------------------
        # PACTOOLS
        pt_start = tst()
        estimator = Comodulogram(fs=sf,
                                 low_fq_range=f_pha_pt,
                                 low_fq_width=f_pha_pt_width,
                                 high_fq_range=f_amp_pt,
                                 high_fq_width=f_amp_pt_width,
                                 method=meth_pt,
                                 progress_bar=False,
                                 n_jobs=n_jobs,
                                 n_surrogates=n_perm)
        estimator.fit(data)
        pt_end = tst()
        # ---------------------------------------------------------------------
        # TENSORPAC
        tp_start = tst()
        p_obj = Pac(idpac=idpac,
                    f_pha=f_pha_tp,
                    f_amp=f_amp_tp,
                    verbose='error')
        pac = p_obj.filterfit(sf, data, n_jobs=n_jobs, n_perm=n_perm).mean(-1)
        tp_end = tst()

        # ---------------------------------------------------------------------
        # shape shape checking
        assert estimator.comod_.shape == pac.T.shape
        # saving the results
        cpt += [pt_end - pt_start, tp_end - tp_start]
        meth_comp += [meth] * 2
        soft += ['Pactools', 'Tensorpac']

    # -------------------------------------------------------------------------
    df = pd.DataFrame({
        "Computing time": cpt,
        "PAC method": meth_comp,
        "Software": soft
    })
    sns.barplot(x="PAC method", y="Computing time", hue="Software", data=df)
    plt.title(title, fontsize=14, fontweight='bold')
예제 #3
0
def plot_compare_lfp_power_coh_vs_loc(dataset, brain_area_1 = [0], brain_area_2 = [0], axs = None, method = 'duprelatour'):

    if ~(method in all_pac_methods):
        method = 'duprelatour'
        
    bands ={
    'theta':{'low': 4,      'high':8},
    'beta' :{'low': 13,     'high':30},
    'gamma':{'low': 30,     'high':70}}


    [brain_area1, name1] = get_brain_area_by_name(dataset, brain_area_1)
    [brain_area2, name2] = get_brain_area_by_name(dataset, brain_area_2)
    
    n_columns = len(bands.keys())
    n_lines   = 2
    frq_res   = 50
    fig, axs = plt.subplots(
    n_lines, n_columns, figsize=(4 * n_columns, 3 * n_lines))
    axs = axs.ravel()
    
    fs = dataset['sampling_rate']
    
    for i, (area, name) in enumerate(zip([brain_area1,brain_area1], [name1,name2])):
        for index, band in enumerate(bands):
            low_fq_range = np.linspace(bands[band]['low'], bands[band]['high'], frq_res)
            low_fq_width = 1.0
            signal = np.mean(dataset['lfp']['amplifier_data'][area,:], axis = 0)
            estimator = Comodulogram(fs=fs, low_fq_range=low_fq_range,
                                     low_fq_width=low_fq_width, method=method,
                                     progress_bar=False)
            estimator.fit(signal)
            estimator.plot(titles= [band +'@'+name], axs=[axs[index + i * n_columns]])
data_dirty = data_dirty.reshape(50, -1)

# We scale the data, since parameter alpha is scale dependant.
scale = data_clean.std()
data_clean /= scale
data_dirty /= scale

###############################################################################
# This sample contains CFC between 3 Hz and 80 Hz. This phenomenon can be
# described with a comodulogram, computed for instance with the `pactools
# <http://pactools.github.io/>`_ Python library.

from pactools import Comodulogram

comod = Comodulogram(fs=sfreq,
                     low_fq_range=np.arange(0.2, 10.2, 0.2),
                     low_fq_width=2.,
                     method='duprelatour')
comod.fit(data_clean)
comod.plot()
plt.show()

###############################################################################
# Here we define the plotting function which display the learned atoms.


def plot_atoms(d_hat):
    n_atoms, n_times_atom = d_hat.shape
    n_columns = min(6, n_atoms)
    n_rows = int(np.ceil(n_atoms // n_columns))
    figsize = (4 * n_columns, 3 * n_rows)
    fig, axes = plt.subplots(n_rows, n_columns, figsize=figsize, sharey=True)
예제 #5
0
# on which time window around each event.

# select the time interval around the events
tmin, tmax = -5, 15
# select the channels (phase_channel, amplitude_channel)
ixs = (8, 10)

###############################################################################
# Then, we create the inputs with the function raw_to_mask, which creates the
# input arrays and the mask arrays. These arrays are then given to a
# comodulogram instance with the `fit` method, and the `plot` method draws the
# results.

# create the input array for Comodulogram.fit
low_sig, high_sig, mask = raw_to_mask(raw,
                                      ixs=ixs,
                                      events=events,
                                      tmin=tmin,
                                      tmax=tmax)
# create the instance of Comodulogram
estimator = Comodulogram(fs=raw.info['sfreq'],
                         low_fq_range=np.linspace(1, 10, 20),
                         low_fq_width=2.,
                         method='tort',
                         progress_bar=True)
# compute the comodulogram
estimator.fit(low_sig, high_sig, mask)
# plot the results
estimator.plot(tight_layout=False)
plt.show()
예제 #6
0
                      high_fq=high_fq,
                      low_fq=low_fq,
                      low_fq_width=low_fq_width,
                      noise_level=noise_level,
                      random_state=0)

low_fq_range = np.linspace(1, 10, 50)
methods = [
    'ozkurt', 'canolty', 'tort', 'penny', 'vanwijk', 'duprelatour', 'colgin',
    'sigl', 'bispectrum'
]

n_lines = 3
n_columns = int(np.ceil(len(methods) / float(n_lines)))
fig, axs = plt.subplots(n_lines,
                        n_columns,
                        figsize=(4 * n_columns, 3 * n_lines))
axs = axs.ravel()

for ax, method in zip(axs, methods):
    print('%s... ' % (method, ))
    estimator = Comodulogram(fs=fs,
                             low_fq_range=low_fq_range,
                             low_fq_width=low_fq_width,
                             method=method,
                             progress_bar=False)
    estimator.fit(signal)
    estimator.plot(titles=[REFERENCES[method]], axs=[ax])

plt.show()
예제 #7
0
axs[1].set_title(dar.get_title(name=True))

###############################################################################
# To compute a comodulogram, we perform the same steps for each low frequency:
# * Extract the low frequency
# * Fit a DAR model
# * Potentially with a model selection using the BIC
# * And quantify the PAC accross the spectrum.
#
# Everything is handled by the class :class:`~pactools.Comodulogram`, by giving
# a (non-fitted) DAR model in the parameter ``method``.
# Giving ``method='duprelatour'`` will default to
# ``DAR(ordar=10, ordriv=1, criterion=None)``, without BIC selection.

# Here we do not give the default set of parameter. Note that the BIC selection
# will be performed independantly for each model (i.e. at each low frequency).
dar = DAR(ordar=20, ordriv=2, criterion='bic')
low_fq_range = np.linspace(1, 10, 50)
estimator = Comodulogram(fs=fs,
                         low_fq_range=low_fq_range,
                         low_fq_width=low_fq_width,
                         method=dar,
                         progress_bar=False,
                         random_state=0)
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
estimator.fit(signal)
estimator.plot(axs=[ax])
ax.set_title('Comodulogram')

plt.show()
예제 #8
0
    signal = signal[180000:480000,]



    #  Significance testing with surrogate analysis

    # number of comodulograms computed in the surrogate analysis.
    # rule of thumb is 10 / p_value. Example: 10 / 0.05 = 200.
    n_surrogates = 200
    # how many cores to use
    n_jobs = 2
    # input the ordar and ordriv from DAR model
    method = 'duprelatour'
    
    estimator = Comodulogram(fs=fs, low_fq_range=low_fq_range,
                             low_fq_width=low_fq_width, method=method,
                             n_surrogates=n_surrogates, high_fq_range=high_fq_range,
                             progress_bar=True, n_jobs=n_jobs)
    estimator.fit(signal)
    
    # plot the significance level on top of the comodulogram
    fig, axs = plt.subplots(1, 2, figsize=(10, 4))
    
    # suffers from multiple testing and assumes normality
    # titles=['With a z-score on each couple of frequency']
    z_score = 4.
    estimator.plot(contour_method='z_score', contour_level=z_score,
                   axs=[axs[0]])
    
    # does not assume normality nor does it suffer from multiple testing
    # titles=['With a p-value on the distribution of maxima']
    p_value = 0.05
예제 #9
0
high_fq_range = np.linspace(low_fq_range[-1], 100., 60)
low_fq_width = 4.  # Hz

# A good rule of thumb is n_surrogates = 10 / p_value. Example: 10 / 0.05 = 200
# Here we use 10 to be fast
n_surrogates = 10
p_value = 0.05
n_jobs = 11

# prepare the plot axes
n_lines = 2
n_columns = int(np.ceil(len(methods) / float(n_lines)))
figsize = (4 * n_columns, 3 * n_lines)
fig, axs = plt.subplots(nrows=n_lines, ncols=n_columns, figsize=figsize)
axs = axs.ravel()

for ax, method in zip(axs, methods):
    # compute the comodulograms
    estimator = Comodulogram(fs=fs, low_fq_range=low_fq_range,
                             high_fq_range=high_fq_range,
                             low_fq_width=low_fq_width, method=method,
                             n_surrogates=n_surrogates, n_jobs=n_jobs)
    estimator.fit(signal)

    # plot the comodulogram with contour levels
    estimator.plot(contour_method='comod_max', contour_level=p_value, axs=[ax],
                   titles=[REFERENCES[method]])

fig.tight_layout()
plt.show()
예제 #10
0
high_fq_range = np.linspace(1, 40, 18)
n_surrogates = 200
methods = [
    'ozkurt', 'canolty', 'tort', 'penny', 'vanwijk', 'duprelatour', 'colgin',
    'sigl', 'bispectrum'
]
mx = []
n_surrogates = 100
for x in filenames:
    for i in range(1, 5):
        if "Subject" + str(i) in x:
            estimator = Comodulogram(fs=fs,
                                     low_fq_range=low_fq_range,
                                     low_fq_width=1,
                                     high_fq_range=high_fq_range,
                                     high_fq_width=1,
                                     method='duprelatour',
                                     progress_bar=True,
                                     n_jobs=-1,
                                     n_surrogates=n_surrogates)
            Data = signal.lfilter(
                b, a,
                np.loadtxt("SavedData\\" + x,
                           comments="%",
                           delimiter=",",
                           usecols=(0, 1, 2)).T, 1)
            Data = np.array_split(Data[1][100:], len(Data[1]) / (250 * 70))
            q = estimator.fit(Data[0])
            p_value = 0.05
            estimator.plot(
                contour_method='comod_max',
예제 #11
0
###############################################################################
# As a surrogate analysis recquires to compute many comodulograms, the
# computation can be slow. If you have multiple cores in your CPU, you can
# leverage them using the parameter `n_jobs` > 1.

n_jobs = 1

###############################################################################
# To compute the comodulogram, we need to instanciate a `Comodulogram` object,
# then call the method `fit`. Adding the surrogate analysis is as simple as
# adding the `n_surrogates` parameter.

estimator = Comodulogram(fs=fs,
                         low_fq_range=low_fq_range,
                         low_fq_width=low_fq_width,
                         method=method,
                         n_surrogates=n_surrogates,
                         progress_bar=True,
                         n_jobs=n_jobs)
estimator.fit(signal)

###############################################################################
# Then we plot the significance level on top of the comodulogram.
# Here we present two methods.
#
# The z-score method presented here considers independently each pair of
# frequency of the comodulogram. For each pair, we compute the mean `mu` and
# standard deviation `sigma` of the PAC values computed over the surrogates
# signals. We then transform the original PAC values `PAC` (non time-shifted)
# into z-scores `Z`: Z = (PAC - mu) / sigma
#
예제 #12
0
def pac_frequencies(ts,
                    sf,
                    method='duprelatour',
                    n_values=10,
                    drive_precision=0.05,
                    max_drive_freq=6,
                    min_drive_freq=3,
                    sig_precision=1,
                    max_sig_freq=50,
                    min_sig_freq=8,
                    low_fq_width=0.5,
                    high_fq_width=1,
                    plot=False):
    """Short summary.

    Parameters
    ----------
    ts : type
        Description of parameter `ts`.
    sf : type
        Description of parameter `sf`.
    method : type
        Description of parameter `method`.
    n_values : type
        Description of parameter `n_values`.
    drive_precision : type
        Description of parameter `drive_precision`.
    max_drive_freq : type
        Description of parameter `max_drive_freq`.
    min_drive_freq : type
        Description of parameter `min_drive_freq`.
    sig_precision : type
        Description of parameter `sig_precision`.
    max_sig_freq : type
        Description of parameter `max_sig_freq`.
    min_sig_freq : type
        Description of parameter `min_sig_freq`.
    low_fq_width : type
        Description of parameter `low_fq_width`.
    high_fq_width : type
        Description of parameter `high_fq_width`.
    plot : type
        Description of parameter `plot`.

    Returns
    -------
    type
        Description of returned object.

    """

    drive_steps = int(((max_drive_freq - min_drive_freq) / drive_precision) +
                      1)
    low_fq_range = np.linspace(min_drive_freq, max_drive_freq, drive_steps)
    sig_steps = int(((max_sig_freq - min_sig_freq) / sig_precision) + 1)
    high_fq_range = np.linspace(min_sig_freq, max_sig_freq, sig_steps)

    estimator = Comodulogram(fs=sf,
                             low_fq_range=low_fq_range,
                             low_fq_width=low_fq_width,
                             high_fq_width=high_fq_width,
                             high_fq_range=high_fq_range,
                             method=method,
                             progress_bar=False)
    estimator.fit(ts)
    indexes = top_n_indexes(estimator.comod_, n_values)[::-1]
    pac_freqs = []
    pac_coupling = []
    for i in indexes:
        pac_freqs.append([low_fq_range[i[0]], high_fq_range[i[1]]])
        pac_coupling.append([estimator.comod_[i[0]], estimator.comod_[i[1]]])
    if plot is True:
        estimator.plot()
    return pac_freqs, pac_coupling
예제 #13
0
#
# Now, we will use the tools from pactools to compute the comodulogram which
# is a visualization of phase amplitude coupling. The stronger the driver
# phase couples with a particular frequency, the brighter the color value.
# The pac signal has 24 - 80 Hz pac as designed, the spurious pac has 10 - 60 Hz
# spurious pac and the final signal has no pac, just background noise.

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

fig, axs = plt.subplots(nrows=3, figsize=(10, 12), sharex=True)
titles = ['Signal with PAC', 'Signal with Spurious PAC', 'Signal with no  PAC']
for sig, ax, title in zip((sig_pac, sig_spurious_pac, sig_no_pac), axs, titles):

    # Check PAC within only channel; high and low sig are the same
    #   Use the duprelatour driven autoregressive model to fit the data
    estimator = Comodulogram(fs=fs, low_fq_range=np.arange(1, 41), low_fq_width=2.,
                             method='duprelatour', progress_bar=False)

    # Compute the comodulogram
    estimator.fit(sig)

    # Plot the results
    estimator.plot(axs=[ax], tight_layout=False, titles=[title])

####################################################################################################
#
# Plot time series for each recording
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Now let's see how each signal looks in time. The third plot of spikes is
# added to pink noise to make the second plot which is the spurious pac.
# This is so that where the spikes occur can be noted in the spurious pac plot.