Exemplo n.º 1
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]])
Exemplo n.º 2
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')
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)
    axes = axes.ravel()
Exemplo n.º 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()
Exemplo n.º 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()
# To make the most of parallel computing, we split the data into trials.
data = data.reshape(50, -1)
data /= data.std()

###############################################################################
# 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)
comod.plot()
plt.show()

###############################################################################
# We fit a CSC model on the data.

from alphacsc import learn_d_z

params = dict(
    n_atoms=3,
    n_times_atom=int(sfreq * 1.0),  # 1000. ms
    reg=5.,
    n_iter=10,
    solver_z='l-bfgs',
    solver_z_kwargs=dict(factr=1e9),
Exemplo n.º 8
0
                                     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',
                contour_level=p_value,
                titles=['With a p-value on the distribution of maxima'])
            mx.append(estimator.get_maximum_pac())
            estimator.save("Subject" + str(i) + x.split("_")[-2],
                           overwrite=True)
            plt.title("Subject" + str(i) + x.split("_")[-2])
            plt.savefig("pics\\" + str(x) + '.png')
            plt.show()


#%%
def nmi(active, passive):
Exemplo n.º 9
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
Exemplo n.º 10
0
# 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.
#

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