Esempio 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]])
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()

    # Plot the temporal pattern of the atom
Esempio n. 3
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()
Esempio n. 4
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()
Esempio n. 5
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()
Esempio n. 6
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()
Esempio n. 7
0
 # 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
 estimator.plot(contour_method='comod_max', contour_level=p_value,
                axs=[axs[1]])
 
 
 
 # save and show resuting comodulogram
 figure = filename.replace('.csv', '.jpeg')
 out_fig = os.path.join(out_dir, figure)
 plt.tight_layout()
 plt.savefig(out_fig)
 plt.show()
Esempio n. 8
0
                                     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):
    nmi = np.zeros(active.shape)
    for i, row in enumerate(active):
        for j, value in enumerate(row):
            nmi[i][j] = (active[i][j] - passive[i][j]) / passive[i][j]
# is Gaussian.
#
#
# The other method presented here considers the ditribution of comodulogram
# maxima. For each surrogate comodulogram, we compute the maximum PAC value.
# From the obtained empirical distribution of maxima, we compute the
# 95-percentile, which corresponds to a p-value of 0.05.
#
# This method does not assume the distribution to be Gaussian, nor suffers from
# multiple-testing issues. This is the default method in the `plot` method.

fig, axs = plt.subplots(1, 2, figsize=(10, 4))

z_score = 4.
estimator.plot(contour_method='z_score',
               contour_level=z_score,
               titles=['With a z-score on each couple of frequency'],
               axs=[axs[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'],
               axs=[axs[1]])

plt.show()

###############################################################################
# References
#
# [Canolty et al, 2006]
# Canolty, R. T., Edwards, E., Dalal, S. S., Soltani, M., Nagarajan,
Esempio n. 10
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
Esempio n. 11
0
# Plot the modulation extracted by the optimal model
dar.plot(ax=axs[1])
axs[1].set_title(dar.get_title(name=True))

###############################################################################
# To compute a comodulogram, we need to perform the same steps for each
# low frequency: extract the low frequency, fit a DAR model, potentially with
# a model selection with the BIC, and quantify the PAC accross the spectrum.
#
# Everything is handled by the function ``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 give a different set of parameter, and 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)
estimator.fit(signal)
estimator.plot(axs=[axs[2]])
axs[2].set_title('Comodulogram')

plt.show()
Esempio n. 12
0
####################################################################################################

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.
#

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

time = np.arange(0, n_seconds, 1/fs)