### Install Tensorpac using pip Source: https://etiennecmb.github.io/tensorpac/_sources/install.rst.txt Use this command to install the Tensorpac library from PyPI. This is the standard installation method. ```shell pip install tensorpac ``` -------------------------------- ### Install Tensorpac from GitHub Source: https://etiennecmb.github.io/tensorpac/_sources/install.rst.txt Clone the repository and install the latest development version. This is useful for accessing the most recent features and fixes. ```shell git clone https://github.com/EtienneCmb/tensorpac.git cd tensorpac/ python setup.py develop ``` -------------------------------- ### Numba-free JIT Wrapper for PAC Calculation Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/methods/meth_pac_nb.html This code block demonstrates a Numba-free JIT wrapper for PAC calculation, intended for use when Numba is not installed. It iterates through phase and amplitude bins to compute PAC. ```python n_amp, _, _ = amp.shape pac = np.zeros((n_amp, n_pha, n_epochs), dtype=np.float64) for a in range(n_amp): for p in range(n_pha): for tr in range(n_epochs): # select phase and amplitude _pha = np.ascontiguousarray(pha[p, tr, :]) _amp = np.ascontiguousarray(amp[a, tr, :]) # get the probability of each amp bin p_j = _kl_hr_nb(_pha, _amp, n_bins=n_bins, mean_bins=True) p_j /= p_j.sum() # find (maximum, minimum) of the binned distribution h_max, h_min = np.max(p_j), np.min(p_j) # compute the PAC pac[a, p, tr] = (h_max - h_min) / h_max return pac ``` -------------------------------- ### Numba JIT Wrapper Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/methods/meth_pac_nb.html Provides a JIT decorator that uses Numba when available, and falls back to a no-op decorator if Numba is not installed. This ensures compatibility across environments. ```python try: import numba def jit(signature=None, nopython=True, nogil=True, fastmath=True, # noqa cache=True, **kwargs): return numba.jit(signature_or_function=signature, cache=cache, nogil=nogil, fastmath=fastmath, nopython=nopython, **kwargs) except: def jit(*args, **kwargs): # noqa def _jit(func): return func return _jit ``` -------------------------------- ### Import Libraries for PAC Analysis Source: https://etiennecmb.github.io/tensorpac/_downloads/0c5a9e73184b78d93e94a00dc46f0620/plot_compare_normalizations.ipynb Imports necessary libraries for data manipulation, PAC calculation, signal generation, and plotting. Ensure these are installed before running. ```python from textwrap import wrap from tensorpac import Pac from tensorpac.signals import pac_signals_wavelet import matplotlib.pyplot as plt ``` -------------------------------- ### Plotting Binned Amplitude with Tensorpac Source: https://etiennecmb.github.io/tensorpac/_downloads/a036b2302ac69b7defa4f619cec0c49d/plot_binned_amplitude.ipynb This snippet illustrates how to use the BinAmplitude class to analyze phase-amplitude coupling. It generates artificial signals, bins the amplitude based on specified phase and amplitude frequencies, and plots the results. Ensure tensorpac and matplotlib are installed. ```python from tensorpac.signals import pac_signals_tort from tensorpac.utils import BinAmplitude import matplotlib.pyplot as plt # Dataset of signals artificially coupled between 10hz and 100hz : n_epochs = 20 n_times = 4000 sf = 512. # sampling frequency # Create artificially coupled signals using Tort method : data, time = pac_signals_tort(f_pha=10, f_amp=100, noise=2, n_epochs=n_epochs, dpha=10, damp=10, sf=sf, n_times=n_times) plt.figure(figsize=(14, 5)) plt.subplot(121) b_obj = BinAmplitude(data, sf, f_pha=[9, 11], f_amp=[90, 110], n_jobs=1, n_bins=18) ax = b_obj.plot(color='red', alpha=.5, unit='deg') plt.ylim(0, 180) plt.title("Binned amplitude (phase=[9, 11])") plt.subplot(122) b_obj = BinAmplitude(data, sf, f_pha=[2, 4], f_amp=[90, 110], n_jobs=1, n_bins=18) ax = b_obj.plot(color='blue', alpha=.5, unit='deg') plt.ylim(0, 180) plt.title("Binned amplitude (phase=[2, 4])") b_obj.show() ``` -------------------------------- ### BinAmplitude Initialization Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.BinAmplitude.html Initializes the BinAmplitude object with data, sampling frequency, and various parameters for phase and amplitude extraction. ```APIDOC ## BinAmplitude _class_`tensorpac.utils.``BinAmplitude`(_x, sf, f_pha=[2, 4], f_amp=[60, 80], n_bins=18, dcomplex='hilbert', cycle=(3, 6), width=7, edges=None, n_jobs=-1_)[source]¶ Bin the amplitude according to the phase. Parameters **x** array_like Array of data of shape (n_epochs, n_times) **sf** float The sampling frequency **f_pha** tuple, list | [2, 4] List of two floats describing the frequency bounds for extracting the phase **f_amp** tuple, list | [60, 80] List of two floats describing the frequency bounds for extracting the amplitude **n_bins** int | 18 Number of bins to use to binarize the phase and the amplitude **dcomplex**{‘wavelet’, ‘hilbert’} Method for the complex definition. Use either ‘hilbert’ or ‘wavelet’. **cycle** tuple | (3, 6) Control the number of cycles for filtering (only if dcomplex is ‘hilbert’). Should be a tuple of integers where the first one refers to the number of cycles for the phase and the second for the amplitude [2]. **width** int | 7 Width of the Morlet’s wavelet. **edges** int | None Number of samples to discard to avoid edge effects due to filtering ``` -------------------------------- ### width Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the width value. ```APIDOC ## width ### Description Get the width value. ### Property width ### Parameters None ### Response #### Success Response (200) - **width** (any) - The width value. ### Request Example None ### Response Example None ``` -------------------------------- ### Import necessary libraries Source: https://etiennecmb.github.io/tensorpac/_sources/auto_examples/pac/plot_compare_normalizations.rst.txt Imports libraries for text wrapping, Tensorpac PAC, signal generation, and plotting. ```default from textwrap import wrap from tensorpac import Pac from tensorpac.signals import pac_signals_wavelet import matplotlib.pyplot as plt ``` -------------------------------- ### itc Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the ITC value. ```APIDOC ## itc ### Description Get the ITC value. ### Property itc ### Parameters None ### Response #### Success Response (200) - **itc** (any) - The ITC value. ### Request Example None ### Response Example None ``` -------------------------------- ### PAC Initialization and Methods Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/pac.html This section details the initialization of the PAC object and the various methods available for PAC computation. It outlines the structure of the PAC ID, frequency definitions, complex signal methods, and cycle parameters. ```APIDOC ## PAC Initialization Parameters ### Description Initializes the Phase Amplitude Coupling (PAC) object with specified parameters for frequency, complex signal definition, and cycle control. ### Parameters * **idpac** (tuple | (1, 2, 3)) - Identifier for the PAC method. The ID is composed of three digits: * First digit: PAC method (e.g., 1: PLV, 2: PLI, 3: MI, 4: ndPAC, 5: PLV, 6: GCPAC). * Second digit: Surrogate method for computing surrogates (e.g., 0: No surrogates, 1: Swap phase/amplitude, 2: Swap amplitude blocks, 3: Time lag). * Third digit: Normalization method for correction (e.g., 0: No normalization, 1: Subtract mean, 2: Divide by mean, 3: Subtract then divide by mean, 4: Z-score). * **f_pha** (list/tuple/array | [2, 4]) - Frequency vector for the phase. Can be a basic list, list of bands, dynamic definition (start, stop, width, step), range definition, or string ('lres', 'mres', 'hres'). * **f_amp** (list/tuple/array | [60, 200]) - Frequency vector for the amplitude. Same format options as `f_pha`. * **dcomplex** (str | 'hilbert') - Method for complex signal definition. Options are 'wavelet' or 'hilbert'. * **cycle** (tuple | (3, 6)) - Controls the number of cycles for filtering when `dcomplex` is 'hilbert'. A tuple of integers for phase and amplitude cycles. * **width** (int | 7) - Width of the Morlet's wavelet (used when `dcomplex` is 'wavelet'). * **n_bins** (int | 18) - Number of bins for KLD and HR PAC methods. * **verbose** (int | None) - Controls the verbosity level of the logging output. ``` -------------------------------- ### f_pha Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the vector of phases. ```APIDOC ## f_pha ### Description Get the vector of phases. ### Property f_pha ### Parameters None ### Response #### Success Response (200) - **f_pha** (Vector of phases of shape (n_pha, 2)) - The vector of phases. ### Request Example None ### Response Example None ``` -------------------------------- ### f_amp Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the vector of amplitudes. ```APIDOC ## f_amp ### Description Get the vector of amplitudes. ### Property f_amp ### Parameters None ### Response #### Success Response (200) - **f_amp** (Vector of amplitudes of shape (n_amp, 2)) - The vector of amplitudes. ### Request Example None ### Response Example None ``` -------------------------------- ### dcomplex Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the dcomplex value. ```APIDOC ## dcomplex ### Description Get the dcomplex value. ### Property dcomplex ### Parameters None ### Response #### Success Response (200) - **dcomplex** (any) - The dcomplex value. ### Request Example None ### Response Response Example None ``` -------------------------------- ### Import necessary libraries Source: https://etiennecmb.github.io/tensorpac/_downloads/1fc0f5fc68595215bbe368c117a0c34e/plot_compare_mcp.ipynb Imports numpy, Pac and pac_signals_wavelet from tensorpac, and matplotlib.pyplot for plotting. ```python import numpy as np from tensorpac import Pac from tensorpac.signals import pac_signals_wavelet import matplotlib.pyplot as plt ``` -------------------------------- ### cycle Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the cycle value. ```APIDOC ## cycle ### Description Get the cycle value. ### Property cycle ### Parameters None ### Response #### Success Response (200) - **cycle** (any) - The cycle value. ### Request Example None ### Response Example None ``` -------------------------------- ### Import necessary libraries Source: https://etiennecmb.github.io/tensorpac/auto_examples/erpac/plot_erpac_stats.html Imports numpy for numerical operations, EventRelatedPac from tensorpac for PAC analysis, pac_signals_wavelet for signal generation, and matplotlib.pyplot for plotting. ```python import numpy as np from tensorpac import EventRelatedPac from tensorpac.signals import pac_signals_wavelet import matplotlib.pyplot as plt ``` -------------------------------- ### Generate Signal and Find Optimal Bandwidth Source: https://etiennecmb.github.io/tensorpac/auto_examples/misc/plot_fmin_fmax_optmization.html Generates a simulated signal with known phase and amplitude frequencies, then uses TensorPac to find the optimal bandwidth for amplitude coupling. Requires `tensorpac` and `matplotlib`. ```python from tensorpac import Pac from tensorpac.signals import pac_signals_tort from tensorpac.utils import pac_trivec sf = 256. data, time = pac_signals_tort(f_pha=[5, 7], f_amp=[60, 80], noise=2, n_epochs=5, n_times=3000, sf=sf, dpha=10) trif, tridx = pac_trivec(f_start=30, f_end=140, f_width=3) p = Pac(idpac=(1, 0, 0), f_pha=[5, 7], f_amp=trif) pac = p.filterfit(sf, data) p.triplot(pac.mean(-1), trif, tridx, cmap='Spectral_r', rmaxis=True, title=r'Optimal $[Fmin; Fmax]hz$ band for amplitude') # In this example, we generated a coupling with a phase between [5, 7]hz and an # amplitude between [60, 80]hz. To interpret the figure, the best starting # frequency is around 50hz and the best ending frequency is around 90hz. In # conclusion, the optimal amplitude bandwidth for this [5, 7]hz phase is # [50, 90]hz. # plt.savefig('triplot.png', dpi=600, bbox_inches='tight') p.show() ``` -------------------------------- ### yvec Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the vector of amplitudes used for plotting. ```APIDOC ## yvec ### Description Get the vector of amplitudes used for plotting. ### Property yvec ### Parameters None ### Response #### Success Response (200) - **yvec** (Vector of amplitudes of shape (n_amp,)) - The vector of amplitudes used for plotting. ### Request Example None ### Response Example None ``` -------------------------------- ### Simulate data for two experimental conditions Source: https://etiennecmb.github.io/tensorpac/_downloads/c7ece4cc20f5cf3cc03e97aea8df17f1/plot_compare_cond_cluster.ipynb Generates two datasets: one with simulated 10Hz phase <-> 120Hz amplitude coupling and another with random data (no coupling). ```python # create the first dataset with a 10hz <-> 100hz coupling n_epochs = 30 # number of datasets sf = 512. # sampling frequency n_times = 4000 # Number of time points x_1, time = pac_signals_wavelet(sf=sf, f_pha=10, f_amp=120, noise=2., n_epochs=n_epochs, n_times=n_times) # create a second random dataset without any coupling x_2 = np.random.rand(n_epochs, n_times) ``` -------------------------------- ### xvec Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.ITC.html Get the vector of phases used for plotting. ```APIDOC ## xvec ### Description Get the vector of phases used for plotting. ### Property xvec ### Parameters None ### Response #### Success Response (200) - **xvec** (Vector of phases of shape (n_pha,)) - The vector of phases used for plotting. ### Request Example None ### Response Example None ``` -------------------------------- ### Import necessary libraries Source: https://etiennecmb.github.io/tensorpac/_downloads/b2a4ab40aebab2fd20ec57f0efb904cd/plot_stats_stationary.ipynb Imports numpy for numerical operations, test_stationarity from tensorpac.stats for the stationarity test, and matplotlib.pyplot for plotting. ```python import numpy as np from tensorpac.stats import test_stationarity import matplotlib.pyplot as plt ``` -------------------------------- ### PSD.psd Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.PSD.html Get the psd value. This property returns the computed Power Spectrum Density values. ```APIDOC ## PSD.psd ### Description Get the psd value. This property returns the computed Power Spectrum Density values. ### Method ``` psd ``` ### Parameters None ### Response #### Success Response * **psd** - The psd value. ``` -------------------------------- ### Initialize PreferredPhase Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.PreferredPhase.html Initialize the PreferredPhase object with specified frequency vectors for phase and amplitude, complex definition method, cycle parameters, and wavelet width. ```python from tensorpac import PreferredPhase # Example with default parameters pp = PreferredPhase() # Example with custom parameters pp = PreferredPhase(f_pha=[1, 3], f_amp=[50, 150], dcomplex='wavelet', cycle=(2, 4), width=5) ``` -------------------------------- ### Update Tensorpac from GitHub Source: https://etiennecmb.github.io/tensorpac/_sources/install.rst.txt If you have installed Tensorpac from the GitHub repository, use this command to pull the latest changes. ```shell git pull ``` -------------------------------- ### Binning Amplitude by Phase Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/utils.html Initializes the BinAmplitude class to bin amplitude data according to phase. Requires data, sampling frequency, and frequency bands for phase and amplitude extraction. ```python x = np.atleast_2d(x) assert x.ndim <= 2, ("`x` input should be an array of shape " "(n_epochs, n_times)") assert isinstance(sf, (int, float)), ("`sf` input should be a integer " "or a float") assert all([isinstance(k, (int, float)) for k in f_pha]), ( "`f_pha` input should be a list of two integers / floats") assert all([isinstance(k, (int, float)) for k in f_amp]), ( "`f_amp` input should be a list of two integers / floats") assert isinstance(n_bins, int), "`n_bins` should be an integer" logger.info(f"Binning {f_amp}Hz amplitude according to {f_pha}Hz " "phase") # extract phase and amplitude kw = dict(keepfilt=False, edges=edges, n_jobs=n_jobs) pha = self.filter(sf, x, 'phase', **kw) amp = self.filter(sf, x, 'amplitude', **kw) # binarize amplitude according to phase self._amplitude = _kl_hr(pha, amp, n_bins, mean_bins=False).squeeze() self.n_bins = n_bins ``` -------------------------------- ### PSD.freqs Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.utils.PSD.html Get the frequency vector. This property returns the computed frequency vector used for the PSD calculation. ```APIDOC ## PSD.freqs ### Description Get the frequency vector. This property returns the computed frequency vector used for the PSD calculation. ### Method ``` freqs ``` ### Parameters None ### Response #### Success Response * **freqs** - The frequency vector. ``` -------------------------------- ### Pac Class Initialization Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/pac.html Initializes the Pac class for computing Phase-Amplitude Coupling (PAC). Allows selection of PAC methods via 'idpac'. ```python class Pac(_PacObj, _PacPlt): """Compute Phase-Amplitude Coupling (PAC). Computing PAC is assessed in three steps : compute the real PAC, compute surrogates and finally, because PAC is very sensible to the noise, correct the real PAC by the surrogates. This implementation is modular i.e. it lets you choose among a large range of possible combinations. Parameters ---------- idpac : tuple/list | (1, 1, 3) Choose the combination of methods to use in order to extract PAC. This tuple must be composed of three integers where each one them refer * First digit : refer to the pac method - 1 : Mean Vector Length (MVL) :cite:`canolty2006high` (see :func:`tensorpac.methods.mean_vector_length`) - 2 : Modulation Index (MI) :cite:`tort2010measuring` (see :func:`tensorpac.methods.modulation_index`) - 3 : Heights Ratio (HR) :cite:`lakatos2005oscillatory` ``` -------------------------------- ### Update Tensorpac to the latest version via pip Source: https://etiennecmb.github.io/tensorpac/_sources/install.rst.txt Run this command to update your installed Tensorpac package to the most recent version available on PyPI. ```shell pip install -U tensorpac ``` -------------------------------- ### Initialize PAC Object Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/pac.html Initializes a PAC object with specified frequency bands for phase and amplitude, complex decomposition method, cycle, and width. ```python pac_obj = _PacObj(f_pha=[2, 4], f_amp=[60, 200], dcomplex='hilbert', cycle=(3, 6), width=7) ``` -------------------------------- ### Initialize Pac object Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.Pac.html Instantiate the Pac class with custom parameters for PAC computation. This allows for flexible configuration of methods, frequency bands, and other settings. ```python from tensorpac import Pac # Default parameters pac = Pac() # Custom parameters pac = Pac(idpac=(1, 2, 3), f_pha=[2, 4], f_amp=[60, 200], dcomplex='hilbert', cycle=(3, 6), width=7, n_bins=18) ``` -------------------------------- ### Import necessary libraries Source: https://etiennecmb.github.io/tensorpac/_downloads/c7ece4cc20f5cf3cc03e97aea8df17f1/plot_compare_cond_cluster.ipynb Imports NumPy for numerical operations, TensorPac for PAC computation, MNE-Python for statistical testing, and Matplotlib for plotting. ```python import numpy as np from tensorpac import Pac from tensorpac.signals import pac_signals_wavelet from mne.stats import permutation_cluster_test import matplotlib.pyplot as plt ``` -------------------------------- ### Initialize PAC Object Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/pac.html Initializes a Phase Amplitude Coupling object with specified parameters for frequency bands, complex definition method, cycle counts, wavelet width, and number of bins. ```python from tensorpac import Pac # Example initialization pac = Pac(idpac=(1, 2, 3), f_pha=[2, 4], f_amp=[60, 200], dcomplex='hilbert', cycle=(3, 6), width=7, n_bins=18) ``` -------------------------------- ### Initialize PreferredPhase and Extract Phase/Amplitude Source: https://etiennecmb.github.io/tensorpac/_downloads/7686e975be654ea79143c3727dbf9ef2/plot_preferred_phase.ipynb Initializes the PreferredPhase object with specified phase and amplitude frequency ranges. Extracts phase and amplitude from the generated data using the filter method. ```python p = PreferredPhase(f_pha=[5, 7], f_amp=(60, 200, 10, 1)) # Extract the phase and the amplitude : pha = p.filter(sf, data, ftype='phase', n_jobs=1) amp = p.filter(sf, data, ftype='amplitude', n_jobs=1) ``` -------------------------------- ### Generate and Analyze PAC Data with Different Filters Source: https://etiennecmb.github.io/tensorpac/_downloads/42907ca139259e2a03611c2ef7305c3b/plot_compare_filtering.ipynb This snippet generates artificial time-series data with known phase-amplitude coupling and then applies PAC analysis using both fir1 filters and wavelets with varying parameters. It visualizes the results using comodulograms. Ensure matplotlib and tensorpac are installed. ```python from __future__ import print_function import matplotlib.pyplot as plt from tensorpac import Pac from tensorpac.signals import pac_signals_wavelet plt.style.use('seaborn-paper') # First, we generate a dataset of signals artificially coupled between 10hz # and 100hz. By default, this dataset is organized as (ntrials, n_times) where # n_times is the number of time points. n_epochs = 5 # number of datasets n_times = 4000 # number of time points data, time = pac_signals_wavelet(f_pha=10, f_amp=100, noise=1., n_epochs=n_epochs, n_times=n_times) # First, let's use the MVL, without any further correction by surrogates : p = Pac(idpac=(1, 0, 0), f_pha=(5, 14, 2, .3), f_amp=(80, 120, 2, 1), verbose=False) plt.figure(figsize=(18, 9)) # Define several cycle options for the fir1 (eegfilt like) filter : print('Filtering with fir1 filter') for i, k in enumerate([(1, 3), (2, 4), (3, 6)]): p.cycle = k xpac = p.filterfit(1024, data, n_jobs=1) plt.subplot(2, 3, i + 1) p.comodulogram(xpac.mean(-1), title='Fir1 - cycle ' + str(k)) # Define several wavelet width : p.dcomplex = 'wavelet' print('Filtering with wavelets') for i, k in enumerate([7, 9, 12]): p.width = k xpac = p.filterfit(1024, data) plt.subplot(2, 3, i + 4) p.comodulogram(xpac.mean(-1), title='Wavelet - width ' + str(k)) plt.show() ``` -------------------------------- ### Import necessary libraries Source: https://etiennecmb.github.io/tensorpac/_downloads/7503c0282dc3e3281c7b0a32e2d5e218/plot_align_tf_pha_peak.ipynb Imports NumPy for numerical operations, `pac_signals_wavelet` for signal generation, `PeakLockedTF` for TF realignment, and Matplotlib for plotting. ```python import numpy as np from tensorpac.signals import pac_signals_wavelet from tensorpac.utils import PeakLockedTF import matplotlib.pyplot as plt ``` -------------------------------- ### Generate Signals and Find Optimal Bandwidth Source: https://etiennecmb.github.io/tensorpac/_sources/auto_examples/misc/plot_fmin_fmax_optmization.rst.txt Generates simulated PAC signals with specified phase and amplitude frequencies, then determines the optimal bandwidth for amplitude coupling using a triplot visualization. Requires `tensorpac` and its utility functions. ```python from tensorpac import Pac from tensorpac.signals import pac_signals_tort from tensorpac.utils import pac_trivec sf = 256. data, time = pac_signals_tort(f_pha=[5, 7], f_amp=[60, 80], noise=2, n_epochs=5, n_times=3000, sf=sf, dpha=10) trif, tridx = pac_trivec(f_start=30, f_end=140, f_width=3) p = Pac(idpac=(1, 0, 0), f_pha=[5, 7], f_amp=trif) pac = p.filterfit(sf, data) p.triplot(pac.mean(-1), trif, tridx, cmap='Spectral_r', rmaxis=True, title=r'Optimal $[Fmin; Fmax]hz$ band for amplitude') # In this example, we generated a coupling with a phase between [5, 7]hz and an # amplitude between [60, 80]hz. To interpret the figure, the best starting # frequency is around 50hz and the best ending frequency is around 90hz. In # conclusion, the optimal amplitude bandwidth for this [5, 7]hz phase is # [50, 90]hz. # plt.savefig('triplot.png', dpi=600, bbox_inches='tight') p.show() ``` -------------------------------- ### PreferredPhase Class Initialization Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.PreferredPhase.html Initializes the PreferredPhase object with specified frequency bands for phase and amplitude, complex definition method, cycle parameters, and wavelet width. ```APIDOC ## PreferredPhase ### Description Initializes the PreferredPhase object with specified frequency bands for phase and amplitude, complex definition method, cycle parameters, and wavelet width. ### Parameters * **f_pha, f_amp** (list/tuple/array) - Frequency vector for the phase and amplitude. Can be a basic list, list of frequency bands, dynamic definition (start, stop, width, step), or range definition. * **dcomplex** (str) - Method for the complex definition. Use either ‘hilbert’ or ‘wavelet’. * **cycle** (tuple) - Control the number of cycles for filtering (only if dcomplex is ‘hilbert’). Should be a tuple of integers where the first one refers to the number of cycles for the phase and the second for the amplitude. * **width** (int) - Width of the Morlet’s wavelet. * **verbose** (any) - Verbosity level. ``` -------------------------------- ### Initialize PAC for Time-Period Comparison Source: https://etiennecmb.github.io/tensorpac/auto_examples/tuto/plot_real_data.html Initializes a Pac object to compute Phase-Amplitude Coupling (PAC) for comparing different time periods (rest, planning, execution). It defines specific phase and amplitude frequency bands and the PAC method. ```python p_obj = Pac(idpac=(6, 0, 0), f_pha=(6, 14, 4, .2), f_amp=(60, 120, 20, 2)) ``` -------------------------------- ### Compute, Plot, and Compare PAC Methods Source: https://etiennecmb.github.io/tensorpac/_sources/auto_examples/pac/plot_pac_methods.rst.txt Iterates through different PAC methods (identified by k), computes PAC for each, and visualizes the results using comodulograms. This allows for a direct comparison of the implemented PAC algorithms. ```python plt.figure(figsize=(14, 8)) for i, k in enumerate([1, 2, 3, 4, 5, 6]): # switch method of PAC p.idpac = (k, 0, 0) # compute only the pac without filtering xpac = p.fit(phases, amplitudes) # plot plt.subplot(2, 3, k) title = p.method.replace(' (', f' ({k}\n(') p.comodulogram(xpac.mean(-1), title=title, cmap='viridis') if k <= 3: plt.xlabel('') plt.tight_layout() plt.show() ``` -------------------------------- ### Pac Class Constructor Source: https://etiennecmb.github.io/tensorpac/_sources/generated/tensorpac.Pac.rst.txt Initializes the Pac class. This is the entry point for creating a Pac object, typically used to process and analyze phase-amplitude coupling in data. ```APIDOC ## Pac.__init__ ### Description Initializes the Pac class. ### Method __init__ ### Parameters This method does not explicitly list parameters in the source. Refer to the class attributes for initialization details. ### Attributes - **cycle** (any) - Stores cycle information. - **dcomplex** (any) - Stores the complex data. - **f_amp** (any) - Stores amplitude frequency information. - **f_pha** (any) - Stores phase frequency information. - **idpac** (any) - Stores the IDPAC value. - **pac** (any) - Stores the PAC value. - **pvalues** (any) - Stores p-values. - **surrogates** (any) - Stores surrogate data. - **width** (any) - Stores width information. - **xvec** (any) - Stores the x-axis vector. - **yvec** (any) - Stores the y-axis vector. ``` -------------------------------- ### Download and Load sEEG Data Source: https://etiennecmb.github.io/tensorpac/_downloads/c18546257dd2ef5d53834fe287a6598e/plot_real_data.ipynb Downloads the 'seeg_data_pac.npz' file if it doesn't exist in the current directory and then loads the data, sampling frequency, and time vector using numpy. This data is from a single sEEG contact during a motor task. ```python filename = os.path.join(os.getcwd(), 'seeg_data_pac.npz') if not os.path.isfile(filename): print('Downloading the data') url = "https://www.dropbox.com/s/dn51xh7nyyttf33/seeg_data_pac.npz?dl=1" urllib.request.urlretrieve(url, filename=filename) arch = np.load(filename) data = arch['data'] # data of a single sEEG contact sf = float(arch['sf']) # sampling frequency times = arch['times'] # time vector print(f"DATA: (n_trials, n_times)={data.shape}; SAMPLING FREQUENCY={sf}Hz; " f"TIME VECTOR: n_times={len(times)}") ``` -------------------------------- ### Extract Phases and Amplitudes Source: https://etiennecmb.github.io/tensorpac/_downloads/0c5a9e73184b78d93e94a00dc46f0620/plot_compare_normalizations.ipynb Initializes the PAC object and extracts phase and amplitude information from the simulated data. This is done once to avoid redundant filtering for comparison. ```python # define the pac object p = Pac(f_pha='mres', f_amp='mres') # Now, we want to compare PAC methods, hence it's useless to systematically # filter the data. So we extract the phase and the amplitude only once phases = p.filter(sf, data, ftype='phase', n_jobs=1) amplitudes = p.filter(sf, data, ftype='amplitude', n_jobs=1) ``` -------------------------------- ### Pac Class Initialization Source: https://etiennecmb.github.io/tensorpac/generated/tensorpac.Pac.html Initialize the Pac object to compute Phase-Amplitude Coupling (PAC). You can specify the methods for PAC calculation, surrogate generation, and normalization, as well as frequency bands, complex definition method, and other parameters. ```APIDOC ## Pac Class ### Description Initialize the Pac object to compute Phase-Amplitude Coupling (PAC). You can specify the methods for PAC calculation, surrogate data generation, and normalization, as well as frequency bands, complex definition method, and other parameters. ### Parameters - **idpac** (tuple/list, optional) - Default: (1, 2, 3) Choose the combination of methods to use in order to extract PAC. This tuple must be composed of three integers where each one them refer to the pac method, the surrogate method, and the normalization method respectively. * First digit (PAC method): 1: MVL, 2: MI, 3: HR, 4: ndPAC, 5: PLV, 6: GCPAC. * Second digit (Surrogate method): 0: No surrogates, 1: Swap phase/amplitude, 2: Swap blocks, 3: Time lag. * Third digit (Normalization method): 0: No normalization, 1: Subtract mean, 2: Divide by mean, 3: Subtract then divide, 4: Z-score. - **f_pha, f_amp** (list/tuple/array, optional) - Default: [2, 4] and [60, 200] Frequency vector for the phase and amplitude. Can be a basic list, list of bands, dynamic definition (start, stop, width, step), range definition, or strings like 'lres', 'mres', 'hres'. - **dcomplex** (str, optional) - Default: 'hilbert' Method for the complex definition. Use either ‘hilbert’ or ‘wavelet’. - **cycle** (tuple, optional) - Default: (3, 6) Control the number of cycles for filtering (only if dcomplex is ‘hilbert’). - **width** (int, optional) - Default: 7 Width of the Morlet’s wavelet (used when dcomplex is ‘wavelet’). - **n_bins** (int, optional) - Default: 18 Number of bins for the KLD and HR PAC method. - **verbose** (any, optional) - Default: None Verbosity level. ``` -------------------------------- ### Import Libraries Source: https://etiennecmb.github.io/tensorpac/_downloads/375ab6a680067f5613d641d47af5c5ac/plot_pvalues.ipynb Imports necessary libraries for PAC computation and signal generation, including matplotlib for plotting. ```python from tensorpac import Pac from tensorpac.signals import pac_signals_wavelet import matplotlib.pyplot as plt ``` -------------------------------- ### Import necessary libraries Source: https://etiennecmb.github.io/tensorpac/_downloads/8ed14b785dcbdbbf00bd6fae03a00170/plot_itc.ipynb Imports numpy for numerical operations, ITC and PSD from tensorpac.utils for analysis, and matplotlib.pyplot for plotting. ```python import numpy as np from tensorpac.utils import ITC, PSD import matplotlib.pyplot as plt ``` -------------------------------- ### Define Frequency Vectors using Various Methods Source: https://etiennecmb.github.io/tensorpac/_downloads/384035eaa9c21e9e77532e560844f573/plot_frequency_vectors.ipynb Illustrates four methods to define frequency vectors for phase and amplitude using `pac_vec`: manual single band, multiple bands, start-stop-width-step, and range definition. Requires `matplotlib.pyplot` and `numpy`. ```python # 1 - Manual defintion : fpha = [2, 4] famp = [60, 160] pvec1, avec1 = pac_vec(fpha, famp) plot(1, pvec1, avec1, '1 - One frequency band') ``` ```python # 2 - List/tuple/array : fpha = [[2, 4], [5, 7], [8, 13]] famp = ([60, 160], [60, 200]) pvec2, avec2 = pac_vec(fpha, famp) plot(2, pvec2, avec2, 'Manually define several frequency bands') ``` ```python # 3 - (start, end, width, step) : fpha = (1, 30, 2, 1) famp = (60, 200, 10, 5) pvec3, avec3 = pac_vec(fpha, famp) plot(3, pvec3, avec3, 'Use the (start, stop, width, step definition') ``` ```python # 4 - Range : fpha = np.arange(1, 20) famp = np.arange(60, 200, 10) pvec4, avec4 = pac_vec(fpha, famp) plot(4, pvec4, avec4, 'Using a range definition') plt.show() ``` -------------------------------- ### Numba PAC Implementation Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/methods/meth_pac_nb.html Provides Numba-accelerated functions for Phase Amplitude Coupling (PAC). Requires NumPy and SciPy.special.erfinv. ```python import numpy as np from scipy.special import erfinv ``` -------------------------------- ### Define and Plot Frequency Vectors Source: https://etiennecmb.github.io/tensorpac/auto_examples/misc/plot_frequency_vectors.html Demonstrates defining frequency vectors using four different methods: manual, list/tuple, start/stop/width/step, and range. Requires the plotting function and `pac_vec`. ```python plt.figure(figsize=(25, 5)) # 1 - Manual defintion : fpha = [2, 4] famp = [60, 160] pvec1, avec1 = pac_vec(fpha, famp) plot(1, pvec1, avec1, '1 - One frequency band') # 2 - List/tuple/array : fpha = [[2, 4], [5, 7], [8, 13]] famp = ([60, 160], [60, 200]) pvec2, avec2 = pac_vec(fpha, famp) plot(2, pvec2, avec2, 'Manually define several frequency bands') # 3 - (start, end, width, step) : fpha = (1, 30, 2, 1) famp = (60, 200, 10, 5) pvec3, avec3 = pac_vec(fpha, famp) plot(3, pvec3, avec3, 'Use the (start, stop, width, step definition') # 4 - Range : fpha = np.arange(1, 20) famp = np.arange(60, 200, 10) pvec4, avec4 = pac_vec(fpha, famp) plot(4, pvec4, avec4, 'Using a range definition') plt.show() ``` -------------------------------- ### Simulate artificial coupling Source: https://etiennecmb.github.io/tensorpac/auto_examples/pac/plot_pac_methods.html Generates trials with a coupling between a 10Hz phase and a 100Hz amplitude. The dataset is organized as (n_epochs, n_times). ```python f_pha = 10 # frequency phase for the coupling f_amp = 100 # frequency amplitude for the coupling n_epochs = 20 # number of trials n_times = 4000 # number of time points sf = 512. # sampling frequency data, time = pac_signals_wavelet(sf=sf, f_pha=f_pha, f_amp=f_amp, noise=.8, n_epochs=n_epochs, n_times=n_times) ``` -------------------------------- ### Generate random data for analysis Source: https://etiennecmb.github.io/tensorpac/_downloads/8ed14b785dcbdbbf00bd6fae03a00170/plot_itc.ipynb Creates a dataset of random sines with varying frequencies across epochs and adds some noise. This data is used to demonstrate phase synchronization around time 0. ```python # Let's start by creating a random dataset n_epochs = 100 # number of trials n_pts = 1000 # number of time points sf = 512. # sampling frequency f_min = 10 # minimum sine frequency f_max = 15 # maximum sine frequency # create sines time = np.linspace(-n_pts / 2, n_pts / 2, n_pts) / sf freqs = np.linspace(f_min, f_max, n_epochs) data = np.sin(2 * np.pi * freqs.reshape(-1, 1) * time.reshape(1, -1)) data += .1 * np.random.rand(n_epochs, n_pts) # plot some trials and see how sines are synchronized around 0 trials = np.linspace(0, n_epochs - 1, 10).astype(int) plt.figure(0) plt.plot(time, data[trials, :].T, alpha=.5) plt.xlabel('Time (seconds)'), plt.ylabel('Amplitude (V)') ``` -------------------------------- ### Simulate Artificial Coupling Source: https://etiennecmb.github.io/tensorpac/_downloads/375ab6a680067f5613d641d47af5c5ac/plot_pvalues.ipynb Generates a single trial dataset with artificial coupling between specified phase and amplitude frequencies using wavelet signals. The dataset is organized as (n_epochs, n_times). ```python f_pha = 6 # frequency phase for the coupling f_amp = 90 # frequency amplitude for the coupling n_epochs = 1 # number of trials n_times = 4000 # number of time points sf = 512. # sampling frequency data, time = pac_signals_wavelet(f_pha=f_pha, f_amp=f_amp, noise=.8, n_epochs=n_epochs, n_times=n_times, sf=sf) ``` -------------------------------- ### Extract Phases, Amplitudes, and Compute Preferred Phase Source: https://etiennecmb.github.io/tensorpac/_sources/auto_examples/misc/plot_preferred_phase.rst.txt Initializes the PreferredPhase object with specified frequency ranges for phase and amplitude. Filters the generated data to extract phase and amplitude components, then computes the preferred phase and amplitude bins. ```python p = PreferredPhase(f_pha=[5, 7], f_amp=(60, 200, 10, 1)) # Extract the phase and the amplitude : pha = p.filter(sf, data, ftype='phase', n_jobs=1) amp = p.filter(sf, data, ftype='amplitude', n_jobs=1) # Now, compute the PP : ampbin, pp, vecbin = p.fit(pha, amp, n_bins=72) ``` -------------------------------- ### Extracting and Preparing Preferred Phase Data Source: https://etiennecmb.github.io/tensorpac/auto_examples/tuto/plot_real_data.html This snippet initializes the PreferredPhase object, filters the data to extract alpha phase, and segments it into different time windows (rest, planning, execution). It then fits the data to compute binned amplitudes and vectors. ```python # define the preferred phase object pp_obj = PreferredPhase(f_pha=[8, 12]) # only extract the alpha phase pp_pha = pp_obj.filter(sf, data, ftype='phase') pp_pha_rest = pp_pha[..., time_rest] pp_pha_prep = pp_pha[..., time_prep] pp_pha_exec = pp_pha[..., time_exec] # compute the preferred phase (reuse the amplitude computed above) ampbin_rest, _, vecbin = pp_obj.fit(pp_pha_rest, amp_rest, n_bins=72) ampbin_prep, _, vecbin = pp_obj.fit(pp_pha_prep, amp_prep, n_bins=72) ampbin_exec, _, vecbin = pp_obj.fit(pp_pha_exec, amp_exec, n_bins=72) # mean binned amplitude across trials ampbin_rest = np.squeeze(ampbin_rest).mean(-1).T ampbin_prep = np.squeeze(ampbin_prep).mean(-1).T ampbin_exec = np.squeeze(ampbin_exec).mean(-1).T ``` -------------------------------- ### Generate PAC Signals using Tort et al. Method Source: https://etiennecmb.github.io/tensorpac/_modules/tensorpac/signals.html Generates artificial signals with phase-amplitude coupling based on the definition by Tort et al. (2010). Allows for controlled coupling strength, noise, and frequency uncertainties. ```python import numpy as np def pac_signals_tort(f_pha=10., f_amp=100., sf=1024, n_times=4000, n_epochs=10, chi=0., noise=1., dpha=0., damp=0., rnd_state=0): """Generate artificially phase-amplitude coupled signals. This function uses the definition of Tort et al. 2010 :cite:`tort2010measuring`. Parameters ---------- f_pha : float | 10. Frequency for phase. Use either a float number for a centered frequency of a band (like [5, 7]) for a bandwidth. f_amp : float | 100. Frequency for amplitude. Use either a float number for a centered frequency of a band (like [60, 80]) for a bandwidth. sf : int | 1024 Sampling frequency n_epochs : int | 10 Number of datasets n_times : int | 4000 Number of points for each signal. chi : float | 0. Amount of coupling. If chi=0, signals of phase and amplitude are strongly coupled (0.<=chi<=1.). noise : float | 1. Amount of noise (0<=noise<=3). dpha : float | 0. Random incertitude on phase frequences (0<=dpha<=100). If f_pha is 2, and dpha is 50, the frequency for the phase signal will be between : [2-0.5*2, 2+0.5*2]=[1,3] damp : float | 0. Random incertitude on amplitude frequencies (0<=damp<=100). If f_amp is 60, and damp is 10, the frequency for the amplitude signal will be between : [60-0.1*60, 60+0.1*60]=[54,66] rnd_state: int | 0 Fix random of the machine (for reproducibility) Returns ------- data : array_like Array of signals of shape (n_epochs, n_channels, n_times). time : array_like Time vector of shape (n_times,). """ n_times, sf = int(n_times), float(sf) # Check the inputs variables : chi = 0 if not 0 <= chi <= 1 else chi noise = 0 if not 0 <= noise <= 3 else noise dpha = 0 if not 0 <= dpha <= 100 else dpha damp = 0 if not 0 <= damp <= 100 else damp f_pha, f_amp = np.asarray(f_pha), np.asarray(f_amp) # time = np.mgrid[0:n_epochs, 0:n_times][1] / sf time = np.arange(n_times) / sf # Random state of the machine : rng = np.random.RandomState(rnd_state) # Band / Delta parameters : sh = (n_epochs, 1) if f_pha.ndim == 0: apha = [f_pha * (1. - dpha / 100.), f_pha * (1. + dpha / 100.)] del_pha = apha[0] + (apha[1] - apha[0]) * rng.rand(*sh) elif f_pha.ndim == 1: del_pha = rng.uniform(f_pha[0], f_pha[1], (n_epochs, 1)) if f_amp.ndim == 0: a_amp = [f_amp * (1. - damp / 100.), f_amp * (1. + damp / 100.)] ```