### Import dependencies Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_detrend.rst.txt Initial setup for the meegkit detrending examples. ```Python import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec from meegkit.detrend import detrend, regress # import config # plotting utils rng = np.random.default_rng(9) ``` -------------------------------- ### RESS Examples Source: https://nbara.github.io/python-meegkit/modules/meegkit.ress.html Examples demonstrating how to use the RESS class for source separation and projection. ```APIDOC ## RESS Examples ### Example 1: Projecting RESS components back to sensor space ```python # First create RESS estimator and fit_transform the data r = ress.RESS(sfreq, peak_freq, compute_unmixing=True) out = r.fit_transform(data) # Then matrix multiply each trial by the unmixing matrix: from RESS import matmul3d # Assuming matmul3d is available fromRESS = r.from_ress proj = matmul3d(out, fromRESS) ``` ### Example 2: Transforming new observations ```python # To transform a new observation into RESS component space (e.g. in the context of a cross-validation, with separate train/test sets) use the transform method: new_comp = r.transform(newdata) ``` ``` -------------------------------- ### Import dependencies and setup environment Source: https://nbara.github.io/python-meegkit/_downloads/12249a2c389fa906a19c26e2a6d00a77/example_phase_estimation.ipynb Initializes necessary libraries and adds test paths for signal generation utilities. ```python import os import sys import matplotlib.pyplot as plt import numpy as np from scipy.signal import hilbert from meegkit.phase import NonResOscillator, ResOscillator, locking_based_phase sys.path.append(os.path.join("..", "tests")) from test_filters import generate_multi_comp_data, phase_difference # noqa:E402 rng = np.random.default_rng(5) ``` -------------------------------- ### Import Libraries and Setup Source: https://nbara.github.io/python-meegkit/auto_examples/example_star_dss.html Imports necessary libraries for signal processing, optimization, and plotting. Sets up a random number generator for data simulation. ```python import matplotlib.pyplot as plt import numpy as np from scipy.optimize import leastsq from meegkit import dss, star from meegkit.utils import demean, normcol, tscov # import config # noqa rng = np.random.default_rng(9) ``` -------------------------------- ### Third example: Identical datasets Source: https://nbara.github.io/python-meegkit/auto_examples/example_mcca.html Uses three identical datasets to demonstrate perfect variance explanation. ```python x1 = rng.standard_normal((10000, 10)) x = np.hstack((x1, x1, x1)) C = np.dot(x.T, x) print(f"Aggregated data covariance shape: {C.shape}") ``` ```python A, score, AA = cca.mcca(C, 10) ``` ```python f, axes = plt.subplots(1, 3, figsize=(12, 4)) axes[0].imshow(A, aspect="auto") axes[0].set_title("mCCA transform matrix") axes[1].imshow(A.T.dot(C.dot(A)), aspect="auto") axes[1].set_title("Covariance of\ntransformed data") axes[2].imshow(x.T.dot(x.dot(A)), aspect="auto") axes[2].set_title("Cross-correlation between\nraw & transformed data") axes[2].set_xlabel("transformed") axes[2].set_ylabel("raw") plt.show() ``` -------------------------------- ### Import Libraries and Setup Source: https://nbara.github.io/python-meegkit/auto_examples/example_dss.html Imports necessary libraries for data manipulation, DSS, and plotting. Sets up a random number generator for data simulation. ```python import matplotlib.pyplot as plt import numpy as np from meegkit import dss from meegkit.utils import fold, rms, tscov, unfold rng = np.random.default_rng(5) ``` -------------------------------- ### Second example: Shared components Source: https://nbara.github.io/python-meegkit/auto_examples/example_mcca.html Creates datasets with shared parts and applies mCCA to extract common components. ```python x1 = rng.standard_normal((10000, 5)) x2 = rng.standard_normal((10000, 5)) x3 = rng.standard_normal((10000, 5)) x4 = rng.standard_normal((10000, 5)) x = np.hstack((x2, x1, x3, x1, x4, x1)) C = np.dot(x.T, x) print(f"Aggregated data covariance shape: {C.shape}") ``` ```python A, score, AA = cca.mcca(C, 10) ``` ```python f, axes = plt.subplots(1, 3, figsize=(12, 4)) axes[0].imshow(A, aspect="auto") axes[0].set_title("mCCA transform matrix") axes[1].imshow(A.T.dot(C.dot(A)), aspect="auto") axes[1].set_title("Covariance of\ntransformed data") axes[2].imshow(x.T.dot(x.dot(A)), aspect="auto") axes[2].set_title("Cross-correlation between\nraw & transformed data") axes[2].set_xlabel("transformed") axes[2].set_ylabel("raw") plt.show() ``` -------------------------------- ### First example: Uncorrelated data Source: https://nbara.github.io/python-meegkit/auto_examples/example_mcca.html Builds three uncorrelated datasets and applies mCCA to show no common structure. ```python x1 = rng.standard_normal((10000, 10)) x2 = rng.standard_normal((10000, 10)) x3 = rng.standard_normal((10000, 10)) x = np.hstack((x1, x2, x3)) C = np.dot(x.T, x) print(f"Aggregated data covariance shape: {C.shape}") ``` ```python [A, score, AA] = cca.mcca(C, 10) z = x.dot(A) ``` ```python f, axes = plt.subplots(1, 3, figsize=(12, 4)) axes[0].imshow(A, aspect="auto") axes[0].set_title("mCCA transform matrix") axes[1].imshow(A.T.dot(C.dot(A)), aspect="auto") axes[1].set_title("Covariance of\ntransformed data") axes[2].imshow(x.T.dot(x.dot(A)), aspect="auto") axes[2].set_title("Cross-correlation between\nraw & transformed data") axes[2].set_xlabel("transformed") axes[2].set_ylabel("raw") plt.plot(np.mean(z ** 2, axis=0)) plt.show() ``` -------------------------------- ### Derive Phase and Amplitude Source: https://nbara.github.io/python-meegkit/modules/meegkit.utils.html Example showing how to derive phase and amplitude from time series data using the analytic signal. ```python >> analytic_signal = hilbert(filtered_data) >> phase = np.phase(analytic_signal) >> amplitude = np.abs(analytic_signal) ``` -------------------------------- ### Import necessary libraries Source: https://nbara.github.io/python-meegkit/auto_examples/example_detrend.html Imports matplotlib for plotting, numpy for numerical operations, and specific functions from meegkit.detrend. Includes setup for random number generation. ```python import matplotlib.pyplot as plt import numpy as np from matplotlib.gridspec import GridSpec from meegkit.detrend import detrend, regress # import config # plotting utils rng = np.random.default_rng(9) ``` -------------------------------- ### Import necessary libraries Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_star_dss.rst.txt Imports required libraries for data manipulation, signal processing, and plotting. Ensure these libraries are installed. ```Python import matplotlib.pyplot as plt import numpy as np from scipy.optimize import leastsq from meegkit import dss, star from meegkit.utils import demean, normcol, tscov ``` -------------------------------- ### Execute All Notebooks with Papermill Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/run_all_notebooks.rst.txt Use this script to automate the execution of multiple Jupyter notebooks. Ensure papermill is installed and notebooks are located in the './examples' directory. ```Python from pathlib import Path import papermill as pm for nb in Path("./examples").glob("*.ipynb"): pm.execute_notebook( input_path=nb, output_path=nb # Path to save executed notebook ) ``` -------------------------------- ### Compute Modulation Index Source: https://nbara.github.io/python-meegkit/modules/meegkit.utils.html Example usage for calculating the modulation index between phase and amplitude signals. ```python >> phas = np.random.rand(100, 1) * 2 * np.pi - np.pi >> ampl = rng.standard_normal((100, 1) * 30 + 100 >> MI, KL = modulation_index(phas, ampl) ``` -------------------------------- ### TRCA Filterbank Frequencies Example Source: https://nbara.github.io/python-meegkit/modules/meegkit.trca.html Defines filterbank frequencies for TRCA. This example creates 3 bands starting at 6, 14, and 22 Hz respectively. Consult scipy.signal.cheb1ord for Wp and Ws specification. ```python [[ (6, 90), (4, 100)], [(14, 90), (10, 100)], [(22, 90), (16, 100)]] ``` -------------------------------- ### TRCA Classification Output Example Source: https://nbara.github.io/python-meegkit/auto_examples/example_trca.html Sample output generated by the TRCA-based classification script. ```text Results of the ensemble TRCA-based method: Block 0: accuracy = 97.5, ITR = 301.3 Block 1: accuracy = 100.0, ITR = 319.3 Block 2: accuracy = 95.0, ITR = 286.3 Block 3: accuracy = 95.0, ITR = 286.3 Block 4: accuracy = 95.0, ITR = 286.3 Block 5: accuracy = 100.0, ITR = 319.3 Mean accuracy = 97.1% (95% CI: 97.0-97.1%) Mean ITR = 299.8 (95% CI: 299.4-300.2) Elapsed time: 11.4 seconds ``` -------------------------------- ### Initialize ECHT environment Source: https://nbara.github.io/python-meegkit/_downloads/935b350564852dc76b851f10e135a3cc/example_echt.ipynb Imports necessary libraries and configures matplotlib settings for signal visualization. ```python import matplotlib.pyplot as plt import numpy as np from scipy.signal import hilbert from meegkit.phase import ECHT rng = np.random.default_rng(38872) plt.rcParams["axes.grid"] = True plt.rcParams["grid.linestyle"] = ":" ``` -------------------------------- ### Importing dependencies for ringing reduction Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_dering.rst.txt Initializes the environment by importing necessary libraries and setting up a random number generator. ```Python import matplotlib.pyplot as plt import numpy as np from scipy.signal import butter, lfilter from meegkit.detrend import reduce_ringing rng = np.random.default_rng(9) ``` -------------------------------- ### Initialize result plotting Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_phase_estimation.rst.txt Sets up the figure layout for visualizing the comparison between different phase estimation methods. ```Python f, ax = plt.subplots(4, 2, sharex=True, sharey=True, figsize=(12, 8)) ``` -------------------------------- ### Import dependencies for STAR Source: https://nbara.github.io/python-meegkit/_downloads/b59b69eb8e7819b9c3d3219863258e2b/example_star.ipynb Initializes the environment by importing necessary libraries and setting up a random number generator. ```python import matplotlib.pyplot as plt import numpy as np from meegkit import star from meegkit.utils import demean, normcol rng = np.random.default_rng(9) ``` -------------------------------- ### Initialize ResOscillator Source: https://nbara.github.io/python-meegkit/modules/meegkit.phase.html Instantiates a resonant oscillator for real-time phase and amplitude measurement with optional frequency adaptation. ```python class meegkit.phase.ResOscillator(fs=1000, nu=4.5, update_factor=5, freq_adaptation=True, assume_centered=False) ``` -------------------------------- ### Execute all notebooks in a directory Source: https://nbara.github.io/python-meegkit/_downloads/e8917d1ab6c97cffe45f4d88f59c2808/run_all_notebooks.ipynb Uses papermill to execute all .ipynb files found in the ./examples directory. The output is saved back to the original file path. ```python from pathlib import Path import papermill as pm for nb in Path("./examples").glob("*.ipynb"): pm.execute_notebook( input_path=nb, output_path=nb # Path to save executed notebook ) ``` -------------------------------- ### Initialize ASR Data Loading Source: https://nbara.github.io/python-meegkit/auto_examples/example_asr.html Imports necessary libraries and loads raw EEG data from a local file for processing. ```python import os import matplotlib.pyplot as plt import numpy as np from meegkit.asr import ASR from meegkit.utils.matrix import sliding_window # THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) raw = np.load(os.path.join("..", "tests", "data", "eeg_raw.npy")) sfreq = 250 ``` -------------------------------- ### Import necessary libraries for mCCA Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_mcca.rst.txt Imports matplotlib for plotting, numpy for numerical operations, and the cca module from meegkit. This setup is required before applying the mCCA function. ```Python import matplotlib.pyplot as plt import numpy as np from meegkit import cca rng = np.random.default_rng(5) ``` -------------------------------- ### Initialize NonResOscillator Source: https://nbara.github.io/python-meegkit/modules/meegkit.phase.html Instantiates a non-resonant oscillator for real-time phase and amplitude measurement. ```python class meegkit.phase.NonResOscillator(fs=250, nu=1.1, alpha_a=6.0, alpha_p=0.2, update_factor=5) ``` -------------------------------- ### Build uncorrelated data for mCCA Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_mcca.rst.txt Creates three independent datasets (x1, x2, x3) using random normal distribution. These are then horizontally stacked into a single matrix 'x'. The aggregated covariance matrix 'C' is computed. This setup is used to demonstrate mCCA on data with no expected shared structure. ```Python x1 = rng.standard_normal((10000, 10)) x2 = rng.standard_normal((10000, 10)) x3 = rng.standard_normal((10000, 10)) x = np.hstack((x1, x2, x3)) C = np.dot(x.T, x) print(f"Aggregated data covariance shape: {C.shape}") ``` -------------------------------- ### Project RESS components to sensor space Source: https://nbara.github.io/python-meegkit/modules/meegkit.ress.html Demonstrates how to compute RESS components and project them back into sensor space using the unmixing matrix. ```python >>> # First create RESS estimator and fit_transform the data >>> r = ress.RESS(sfreq, peak_freq, compute_unmixing=True) >>> out = r.fit_transform(data) >>> # Then matrix multiply each trial by the unmixing matrix: >>> fromRESS = r.from_ress >>> proj = matmul3d(out, fromRESS) ``` -------------------------------- ### Detrending with Weights to Handle Artifacts Source: https://nbara.github.io/python-meegkit/auto_examples/example_detrend.html Demonstrates detrending with and without weights. The first 100 samples are artificially set to a high value to simulate an artifact. Detrending without weights performs poorly, while downweighting the artifactual period significantly improves the fit. ```python x = np.linspace(0, 100, 1000)[:, None] x = x + 3 * rng.standard_normal(x.shape) # introduce some strong artifact on the first 100 samples x[:100, :] = 100 # Detrend y, _, _ = detrend(x, 3, None, threshold=np.inf) # Same process but this time downweight artifactual window w = np.ones(x.shape) w[:100, :] = 0 z, _, _ = detrend(x, 3, w) plt.figure(7) plt.plot(x, label="original") plt.plot(y, label="detrended - no weights") plt.plot(z, label="detrended - weights") plt.legend() plt.show() ``` -------------------------------- ### Import required libraries Source: https://nbara.github.io/python-meegkit/_downloads/127999bfe25ff667ca6d2d8ac8525a33/example_dss_line.ipynb Initial imports for data processing and visualization. ```python # Authors: Maciej Szul # Nicolas Barascud import os import matplotlib.pyplot as plt import numpy as np from scipy import signal from meegkit import dss from meegkit.utils import create_line_data, unfold ``` -------------------------------- ### Visualize signal and phase results Source: https://nbara.github.io/python-meegkit/_downloads/935b350564852dc76b851f10e135a3cc/example_echt.ipynb Plots the original signal, its Fourier spectrum, and compares the phase estimates from the Hilbert transform and the ECHT filter. ```python fig, ax = plt.subplots(3, 1, figsize=(8, 6)) ax[0].plot(time, X) ax[0].set_xlabel("Time (s)") ax[0].set_title("Test signal") ax[0].set_ylabel("Amplitude") ax[1].psd(X, Fs=sfreq, NFFT=2048*4, noverlap=sfreq) ax[1].set_ylabel("PSD (dB/Hz)") ax[1].set_title("Test signal's Fourier spectrum") ax[2].plot(time, phase_true, label="True phase", ls=":") ax[2].plot(time, phase_echt, label="ECHT phase", lw=.5, alpha=.8) ax[2].plot(time, phase_hilbert, label="Hilbert phase", lw=.5, alpha=.8) ax[2].set_title("Phase") ax[2].set_ylabel("Amplitude") ax[2].set_xlabel("Time (s)") ax[2].legend(loc="upper right", fontsize="small") plt.tight_layout() plt.show() ``` -------------------------------- ### meegkit.utils Overview Source: https://nbara.github.io/python-meegkit/_sources/modules/meegkit.utils.rst.txt The meegkit.utils module contains a collection of utility functions for various signal processing tasks relevant to MEEG data. ```APIDOC ## meegkit.utils ### Description This module serves as a central hub for various utility functions used across the MEEGKit library. It organizes related functionalities into submodules for better modularity and maintainability. ### Submodules - **auditory**: Utilities for auditory processing. - **buffer**: Functions for managing data buffers. - **coherence**: Tools for calculating signal coherence. - **covariances**: Utilities related to covariance matrices. - **denoise**: Functions for denoising MEEG data. - **matrix**: Matrix manipulation utilities. - **sig**: Signal processing functions. - **stats**: Statistical functions. - **trca**: Utilities for Temporal Regression Coefficient Analysis (TRCA). ``` -------------------------------- ### Load Data and Initialize ASR Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_asr.rst.txt Imports necessary libraries and loads EEG data. Initializes the ASR object with the 'euclid' method. This code is used to set up the environment for artifact subspace reconstruction. ```Python import os import matplotlib.pyplot as plt import numpy as np from meegkit.asr import ASR from meegkit.utils.matrix import sliding_window # THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) raw = np.load(os.path.join("..", "tests", "data", "eeg_raw.npy")) sfreq = 250 ``` -------------------------------- ### Import necessary libraries Source: https://nbara.github.io/python-meegkit/auto_examples/example_echt.html Imports libraries for plotting, numerical operations, Hilbert transform, and the ECHT filter. Sets up plot configurations for grids. ```python import matplotlib.pyplot as plt import numpy as np from scipy.signal import hilbert from meegkit.phase import ECHT rng = np.random.default_rng(38872) plt.rcParams["axes.grid"] = True plt.rcParams["grid.linestyle"] = ":" ``` -------------------------------- ### MEEGKit Attributes and Methods Source: https://nbara.github.io/python-meegkit/genindex.html Lists attributes and methods for specific classes and modules. ```APIDOC ## MEEGKit Attributes and Methods ### Attributes: - **n_bands**: Attribute of `meegkit.trca.TRCA`. - **n_channels**: Attribute of `meegkit.utils.buffer.Buffer`. - **size**: Attribute of `meegkit.utils.buffer.Buffer`. - **tail**: Property of `meegkit.utils.buffer.Buffer`. - **traindata**: Attribute of `meegkit.trca.TRCA`. ### Methods: - **predict()**: Method of `meegkit.lof.LOF` and `meegkit.trca.TRCA`. - **push()**: Method of `meegkit.utils.buffer.Buffer`. - **reset()**: Method of `meegkit.asr.ASR` and `meegkit.utils.buffer.Buffer`. - **step()**: Method of `meegkit.phase.Device`. - **transform()**: Method of `meegkit.asr.ASR`, `meegkit.phase.ECHT`, `meegkit.phase.NonResOscillator`, `meegkit.phase.ResOscillator`, and `meegkit.ress.RESS`. - **view()**: Method of `meegkit.utils.buffer.Buffer`. ``` -------------------------------- ### Create simulated data Source: https://nbara.github.io/python-meegkit/_downloads/22a83c59bf23910872ecdf61ccc22837/example_dss.ipynb Generates simulated multichannel data with a defined signal and noise component. The data is structured as time * channel * trials. ```python # Data are time * channel * trials. n_samples = 100 * 3 n_chans = 30 n_trials = 100 noise_dim = 20 # dimensionality of noise # Source signal source = np.hstack(( np.zeros((n_samples // 3,)), np.sin(2 * np.pi * np.arange(n_samples // 3) / (n_samples / 3)).T, np.zeros((n_samples // 3,))))[np.newaxis].T s = source * rng.standard_normal((1, n_chans)) # 300 * 30 s = s[:, :, np.newaxis] s = np.tile(s, (1, 1, 100)) # Noise noise = np.dot( unfold(rng.standard_normal((n_samples, noise_dim, n_trials))), rng.standard_normal((noise_dim, n_chans))) noise = fold(noise, n_samples) # Mix signal and noise SNR = 0.1 data = noise / rms(noise.flatten()) + SNR * s / rms(s.flatten()) ``` -------------------------------- ### Define filterbank specifications Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_trca.rst.txt Sets up the filterbank passband and stopband frequencies for analysis. ```Python filterbank = [[(6, 90), (4, 100)], # passband, stopband freqs [(Wp), (Ws)] [(14, 90), (10, 100)], [(22, 90), (16, 100)], [(30, 90), (24, 100)], [(38, 90), (32, 100)], [(46, 90), (40, 100)], [(54, 90), (48, 100)]] f, ax = plt.subplots(1, figsize=(7, 4)) ``` -------------------------------- ### Visualize signal and phase estimates Source: https://nbara.github.io/python-meegkit/auto_examples/example_echt.html Plots the original test signal, its Fourier spectrum, and compares the true phase, ECHT phase, and Hilbert phase. The ECHT filter is shown to provide a smoother phase estimate. ```python fig, ax = plt.subplots(3, 1, figsize=(8, 6)) ax[0].plot(time, X) ax[0].set_xlabel("Time (s)") ax[0].set_title("Test signal") ax[0].set_ylabel("Amplitude") ax[1].psd(X, Fs=sfreq, NFFT=2048*4, noverlap=sfreq) ax[1].set_ylabel("PSD (dB/Hz)") ax[1].set_title("Test signal's Fourier spectrum") ax[2].plot(time, phase_true, label="True phase", ls=":") ax[2].plot(time, phase_echt, label="ECHT phase", lw=.5, alpha=.8) ax[2].plot(time, phase_hilbert, label="Hilbert phase", lw=.5, alpha=.8) ax[2].set_title("Phase") ax[2].set_ylabel("Amplitude") ax[2].set_xlabel("Time (s)") ax[2].legend(loc="upper right", fontsize="small") plt.tight_layout() plt.show() ``` -------------------------------- ### Meegkit Phase Module Overview Source: https://nbara.github.io/python-meegkit/_sources/modules/meegkit.phase.rst.txt This snippet provides an overview of the classes and functions available within the meegkit.phase module. ```APIDOC ## Meegkit Phase Module This module provides functionalities for phase analysis and oscillator modeling. ### Classes - **NonResOscillator**: Represents a non-resonant oscillator. - **ResOscillator**: Represents a resonant oscillator. - **Device**: Represents a device, likely for signal processing. - **ECHT**: Represents the Empirical Characteristic Function Transform. ### Functions - **locking_based_phase**: Computes phase based on a locking mechanism. - **rk**: Likely a Runge-Kutta integration method. - **init_coefs**: Initializes coefficients for a process. - **one_step_oscillator**: Performs one step of oscillator calculation. - **one_step_integrator**: Performs one step of integration. ``` -------------------------------- ### Perform simple regression Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_detrend.rst.txt Fit a random walk process without using weights. ```Python x = np.cumsum(rng.standard_normal((1000, 1)), axis=0) r = np.arange(1000.)[:, None] r = np.hstack([r, r ** 2, r ** 3]) b, y = regress(x, r) plt.figure(1) plt.plot(x, label="data") plt.plot(y, label="fit") plt.title("No weights") plt.legend() plt.show() ``` -------------------------------- ### Detrend with Weights for Artifacts Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_detrend.rst.txt Demonstrates detrending with and without weights to handle local artifacts. Weights can improve detrending accuracy when specific data periods should be downweighted, such as strong glitches. ```Python x = np.linspace(0, 100, 1000)[:, None] x = x + 3 * rng.standard_normal(x.shape) # introduce some strong artifact on the first 100 samples x[:100, :] = 100 # Detrend y, _, _ = detrend(x, 3, None, threshold=np.inf) # Same process but this time downweight artifactual window w = np.ones(x.shape) w[:100, :] = 0 z, _, _ = detrend(x, 3, w) plt.figure(7) plt.plot(x, label="original") plt.plot(y, label="detrended - no weights") plt.plot(z, label="detrended - weights") plt.legend() plt.show() ``` -------------------------------- ### meegkit.dss.dss1 Source: https://nbara.github.io/python-meegkit/modules/meegkit.dss.html DSS to maximise repeatability across trials. ```APIDOC ## meegkit.dss.dss1 ### Description DSS to maximise repeatability across trials. Evoked-biased DSS denoising. ### Method Not specified (likely a Python function call) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **X** (array, shape=(n_samples, n_chans, n_trials)) - Data to denoise. - **weights** (array) - Weights. - **keep1** (int) - Number of PCs to retain in function:dss0 (default=all). - **keep2** (float) - Ignore PCs smaller than keep2 in function:dss0 (default=1e-12). ### Returns - **todss** (array, shape=(n_dss_components, n_chans)) - Denoising matrix to convert X to normalized DSS components. - **from** (array, shape=(n_dss_components, n_chans)) - Matrix to convert DSS components back to sensor space. - **pwr0** (array) - Power per component (raw). - **pwr1** (array) - Power per component (averaged). ``` -------------------------------- ### Smooth a signal Source: https://nbara.github.io/python-meegkit/modules/meegkit.utils.html Demonstrates basic usage of the smooth function and how to adjust the output length to match the input length. ```python >> t = linspace(-2, 2, 0.1) >> x = sin(t) + randn(len(t)) * 0.1 >> y = smooth(x, 2) ``` ```python >> y[(window_len / 2 - 1):-(window_len / 2)] # noqa ``` -------------------------------- ### ASR Class Initialization Source: https://nbara.github.io/python-meegkit/modules/meegkit.asr.html Initializes the ASR object with parameters for artifact detection and removal. ```APIDOC ## Class: meegkit.asr.ASR ### Description Artifact subspace reconstruction (ASR) is an automatic, online, component-based artifact removal method for removing transient or large-amplitude artifacts in multi-channel EEG recordings. ### Parameters - **sfreq** (float) - Sampling rate of the data, in Hz (default=250). - **cutoff** (float) - Standard deviation cutoff for rejection (default=5). - **blocksize** (int) - Block size for calculating robust data covariance and thresholds (default=10). - **win_len** (float) - Window length (s) used to check data for artifact content (default=1). - **win_overlap** (float) - Window overlap fraction (default=0.66). - **max_dropout_fraction** (float) - Maximum fraction of windows subject to signal dropouts (default=0.1). - **min_clean_fraction** (float) - Minimum fraction of windows that need to be clean (default=0.25). - **method** (str) - Method to use: 'riemann' or 'euclid' (default='euclid'). - **memory** (float) - Memory size in samples (default=None). - **estimator** (str) - Covariance estimator: 'scm', 'lwf', 'oas', or 'mcd' (default='scm'). ``` -------------------------------- ### Compute phase and amplitude estimates Source: https://nbara.github.io/python-meegkit/_downloads/12249a2c389fa906a19c26e2a6d00a77/example_phase_estimation.ipynb Calculates phase and amplitude using Hilbert transform, locking-based techniques, and oscillator models. ```python ht_ampl = np.abs(hilbert(s)) # Hilbert amplitude ht_phase = np.angle(hilbert(s)) # Hilbert phase lb_phase = locking_based_phase(s, dt, npt) lb_phi_dif = phase_difference(ht_phase, lb_phase) osc = NonResOscillator(fs, 1.1) nr_phase, nr_ampl = osc.transform(s) nr_phase = nr_phase[:, 0] nr_phi_dif = phase_difference(ht_phase, nr_phase) osc = ResOscillator(fs, 1.1) r_phase, r_ampl = osc.transform(s) r_phase = r_phase[:, 0] r_phi_dif = phase_difference(ht_phase, r_phase) ``` -------------------------------- ### Simulate multi-channel data with artifacts Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_star.rst.txt Generates a synthetic dataset consisting of sinusoidal targets, noise sources, and temporally local artifacts. ```Python # Create simulated data nchans = 10 n_samples = 1000 f = 2 target = np.sin(np.arange(n_samples) / n_samples * 2 * np.pi * f) target = target[:, np.newaxis] noise = rng.standard_normal((n_samples, nchans - 3)) # Create artifact signal SNR = np.sqrt(1) x0 = normcol(np.dot(noise, rng.standard_normal((noise.shape[1], nchans)))) + \ SNR * target * rng.standard_normal((1, nchans)) x0 = demean(x0) artifact = np.zeros(x0.shape) for k in np.arange(nchans): artifact[k * 100 + np.arange(20), k] = 1 x = x0 + 10 * artifact # This is to compare with matlab numerically # from scipy.io import loadmat # mat = loadmat('/Users/nicolas/Toolboxes/NoiseTools/TEST/X.mat') # x = mat['x'] # x0 = mat['x0'] ``` -------------------------------- ### LOF Class Initialization Source: https://nbara.github.io/python-meegkit/modules/meegkit.lof.html Initializes the Local Outlier Factor (LOF) model with specified parameters. ```APIDOC ## LOF Class ### Description Local Outlier Factor (LOF) is an automatic, density-based outlier detection algorithm. ### Parameters #### Initialization Parameters - **n_neighbors** (int) - Optional - Number of neighbours defining the local neighbourhood. Default is 20. - **metric** (str) - Optional - Metric to use for distance computation. Default is "euclidean". Supported values: 'euclidean', 'nan_euclidean', 'cosine', 'cityblock', 'manhattan'. - **threshold** (float) - Optional - Threshold to define outliers. Default is 1.5. ### Notes It is recommended to perform a CV (e.g., 10-fold) on training set to calibrate this parameter for the given M/EEG dataset. ``` -------------------------------- ### TRCA Class Initialization Source: https://nbara.github.io/python-meegkit/modules/meegkit.trca.html Initializes the TRCA class with sampling frequency, filterbank, and optional parameters for ensemble analysis, method, and estimator. ```python TRCA(sfreq, filterbank, ensemble=False, method='original', estimator='scm') ``` -------------------------------- ### Import Libraries and Set Random Seed Source: https://nbara.github.io/python-meegkit/_downloads/ea69e60d8097b4a52c572727119cb9b5/example_mcca_2.ipynb Imports necessary libraries and sets a random seed for reproducible results. ```python import matplotlib.pyplot as plt import numpy as np from meegkit import cca # Set the seed for the random number generator for reproducibility rng = np.random.default_rng(5) ``` -------------------------------- ### Create Simulated Data Source: https://nbara.github.io/python-meegkit/auto_examples/example_dss.html Generates synthetic multichannel time-series data with a known source signal and added noise. The data is structured as time * channel * trials. ```python # Data are time * channel * trials. n_samples = 100 * 3 n_chans = 30 n_trials = 100 noise_dim = 20 # dimensionality of noise # Source signal source = np.hstack(( np.zeros((n_samples // 3,)), np.sin(2 * np.pi * np.arange(n_samples // 3) / (n_samples / 3)).T, np.zeros((n_samples // 3,))))[np.newaxis].T s = source * rng.standard_normal((1, n_chans)) # 300 * 30 s = s[:, :, np.newaxis] s = np.tile(s, (1, 1, 100)) # Noise noise = np.dot( unfold(rng.standard_normal((n_samples, noise_dim, n_trials))), rng.standard_normal((noise_dim, n_chans))) noise = fold(noise, n_samples) # Mix signal and noise SNR = 0.1 data = noise / rms(noise.flatten()) + SNR * s / rms(s.flatten()) ``` -------------------------------- ### Visualize test signal spectrum Source: https://nbara.github.io/python-meegkit/_downloads/12249a2c389fa906a19c26e2a6d00a77/example_phase_estimation.ipynb Plots the time-domain signal and its power spectral density. ```python f, ax = plt.subplots(2, 1) ax[0].plot(time, s) ax[0].set_xlabel("Time (s)") ax[0].set_title("Test signal") ax[1].psd(s, Fs=fs, NFFT=2048*4, noverlap=fs) ax[1].set_title("Test signal's Fourier spectrum") plt.tight_layout() ``` -------------------------------- ### Apply STAR algorithm Source: https://nbara.github.io/python-meegkit/_downloads/b59b69eb8e7819b9c3d3219863258e2b/example_star.ipynb Executes the STAR denoising function on the simulated signal. ```python y, w, _ = star.star(x, 2) ``` -------------------------------- ### meegkit.dss Functions Source: https://nbara.github.io/python-meegkit/_sources/modules/meegkit.dss.rst.txt Overview of the available functions within the meegkit.dss module. ```APIDOC ## meegkit.dss Functions ### Description The following functions are available in the `meegkit.dss` module for performing Denoising Source Separation: - **dss0**: Basic DSS implementation. - **dss1**: Standard DSS implementation. - **dss_line**: DSS for line noise removal. - **dss_line_iter**: Iterative DSS for line noise removal. ``` -------------------------------- ### Visualize power spectral density Source: https://nbara.github.io/python-meegkit/_downloads/127999bfe25ff667ca6d2d8ac8525a33/example_dss_line.ipynb Compare the PSD of the data before and after applying the line noise filter. ```python f, ax = plt.subplots(1, 2, sharey=True) f, Pxx = signal.welch(data, sfreq, nperseg=500, axis=0, return_onesided=True) ax[0].semilogy(f, Pxx) f, Pxx = signal.welch(out, sfreq, nperseg=500, axis=0, return_onesided=True) ax[1].semilogy(f, Pxx) ax[0].set_xlabel("frequency [Hz]") ax[1].set_xlabel("frequency [Hz]") ax[0].set_ylabel("PSD [V**2/Hz]") ax[0].set_title("before") ax[1].set_title("after") plt.show() ``` -------------------------------- ### Import necessary libraries Source: https://nbara.github.io/python-meegkit/_downloads/55fbbf73209011b3e5a3fed72c42bd04/example_ress.ipynb Imports required libraries for data manipulation, signal processing, and plotting, including specific modules from the meegkit library. ```python import matplotlib.pyplot as plt import numpy as np import scipy.signal as ss from meegkit import ress from meegkit.utils import fold, matmul3d, snr_spectrum, unfold # import config rng = np.random.default_rng(9) ``` -------------------------------- ### MEEGKit Modules Source: https://nbara.github.io/python-meegkit/genindex.html Overview of the main modules available in the MEEGKit library. ```APIDOC ## MEEGKit Modules - **meegkit.asr**: Module for Artifact Subspace Reconstruction. - **meegkit.cca**: Module for Canonical Correlation Analysis. - **meegkit.detrend**: Module for detrending MEEG data. - **meegkit.dss**: Module for Dynamic Source Separation. - **meegkit.lof**: Module for Local Outlier Factor. - **meegkit.phase**: Module for phase analysis. - **meegkit.ress**: Module for Regression-based Source Separation. - **meegkit.sns**: Module for Signal-to-Noise ratio estimation. - **meegkit.star**: Module for STAR algorithm. - **meegkit.trca**: Module for Temporal Regression Component Analysis. - **meegkit.tspca**: Module for Temporal Sparse PCA. - **meegkit.utils**: Utility functions module. - **meegkit.utils.auditory**: Auditory signal processing utilities. - **meegkit.utils.buffer**: Buffer management utilities. - **meegkit.utils.coherence**: Coherence analysis utilities. - **meegkit.utils.covariances**: Covariance matrix utilities. - **meegkit.utils.denoise**: Denoising utilities. - **meegkit.utils.matrix**: Matrix manipulation utilities. - **meegkit.utils.sig**: Signal processing utilities. - **meegkit.utils.stats**: Statistical utilities. - **meegkit.utils.trca**: TRCA-related utilities. ``` -------------------------------- ### Helper Functions Source: https://nbara.github.io/python-meegkit/modules/meegkit.phase.html Utility functions for phase estimation calculations. ```APIDOC ## Helper Functions ### `init_coefs(om0, dt, alpha)` Compute coefficients for solving oscillator’s equations. #### Parameters * **om0** (float) – Oscillator frequency (estimation). * **dt** (float) – Sampling interval. * **alpha** (float) – Half of the damping. #### Returns * **C1** (float) – Coefficient C1. * **C2** (float) – Coefficient C2. * **C3** (float) – Coefficient C3. * **eetadel** (complex) – Exponential term for amplitude device. * **ealdel** (float) – Exponential term for amplitude device. * **eta** (float) – Square root of the difference of oscillator frequency squared and damping squared. ### `locking_based_phase(s, dt, npt)` Compute the locking-based phase. #### Parameters * **s** (ndarray) – The input signal. * **dt** (float) – Sampling interval. * **npt** (int) – Number of points to be measured and processed. ``` -------------------------------- ### MEEGKit Core Classes and Methods Source: https://nbara.github.io/python-meegkit/genindex.html This section details core classes and their associated methods within the MEEGKit library. ```APIDOC ## Class: meegkit.asr.ASR ### Description Represents an Automatic Speech Recognition (ASR) system. ### Methods - **fit(X, y)**: Fits the ASR model. - **clean_windows(data)**: Cleans windows of data. ## Class: meegkit.lof.LOF ### Description Local Outlier Factor (LOF) class. ## Class: meegkit.phase.Device ### Description Represents a device for phase analysis. ### Methods - **init_coefs()**: Initializes coefficients. ## Class: meegkit.phase.ECHT ### Description Represents the Empirical Characteristic Time (ECHT) analysis. ### Methods - **fit(X, y)**: Fits the ECHT model. - **fit_transform(X, y)**: Fits and transforms the data. ## Class: meegkit.phase.NonResOscillator ### Description Non-resonant oscillator class. ## Class: meegkit.phase.ResOscillator ### Description Resonant oscillator class. ## Class: meegkit.ress.RESS ### Description Represents the Recursive Ensemble Smoothing (RESS) method. ### Methods - **fit(X, y)**: Fits the RESS model. - **inverse_transform(X)**: Inverts the RESS transformation. - **fit_transform(X, y)**: Fits and transforms the data. ## Class: meegkit.trca.TRCA ### Description Represents the Temporal Regression (TRCA) analysis. ### Attributes - **classes**: Class labels. - **coef_**: Coefficients of the TRCA model. ### Methods - **fit(X, y)**: Fits the TRCA model. ## Class: meegkit.utils.auditory.AuditoryFilterbank ### Description Abstract base class for auditory filterbanks. ## Class: meegkit.utils.auditory.GammatoneFilterbank ### Description Implements a Gammatone filterbank. ### Methods - **filter(data)**: Applies the Gammatone filter. ## Class: meegkit.utils.buffer.Buffer ### Description Represents a buffer for data handling. ### Attributes - **_data**: Internal data storage. - **counter**: Counter for buffer operations. - **head**: Head of the buffer. ### Methods - **get_new_samples()**: Retrieves new samples from the buffer. ``` -------------------------------- ### Build identical data for mCCA Source: https://nbara.github.io/python-meegkit/_sources/auto_examples/example_mcca.rst.txt Creates three identical 10-channel datasets (x1) and stacks them horizontally to form 'x'. This scenario is designed to test mCCA's ability to find a limited number of meaningful components when data is highly redundant. ```Python x1 = rng.standard_normal((10000, 10)) x = np.hstack((x1, x1, x1)) ``` -------------------------------- ### Simulate MEEG data with artifacts Source: https://nbara.github.io/python-meegkit/_downloads/b59b69eb8e7819b9c3d3219863258e2b/example_star.ipynb Generates synthetic multi-channel data containing a sinusoidal target, noise sources, and localized temporal artifacts. ```python # Create simulated data nchans = 10 n_samples = 1000 f = 2 target = np.sin(np.arange(n_samples) / n_samples * 2 * np.pi * f) target = target[:, np.newaxis] noise = rng.standard_normal((n_samples, nchans - 3)) # Create artifact signal SNR = np.sqrt(1) x0 = normcol(np.dot(noise, rng.standard_normal((noise.shape[1], nchans)))) + \ SNR * target * rng.standard_normal((1, nchans)) x0 = demean(x0) artifact = np.zeros(x0.shape) for k in np.arange(nchans): artifact[k * 100 + np.arange(20), k] = 1 x = x0 + 10 * artifact # This is to compare with matlab numerically # from scipy.io import loadmat # mat = loadmat('/Users/nicolas/Toolboxes/NoiseTools/TEST/X.mat') # x = mat['x'] # x0 = mat['x0'] ``` -------------------------------- ### meegkit.utils.auditory Module Source: https://nbara.github.io/python-meegkit/modules/meegkit.utils.html Tools for working with auditory signals, including Gammatone filterbanks and frequency conversion utilities. ```APIDOC ## Auditory Filterbank Class ### Description Represents a Gammatone filterbank, adapted for simulating the cochlea. ### Class Definition `class meegkit.utils.auditory.GammatoneFilterbank(_sfreq_, _cf_, _b=1.019_, _order=1_, _q=9.26449_, _min_bw=24.7_) Bases: `object` ### Parameters * **sfreq** (float) - Sampling frequency of the signals to filter. * **cf** (array_like) - Center frequencies of the filterbank. * **b** (float) - Beta of the gammatone filters (default=1.019). * **order** (int) - Order (default=1). * **q** (float) - Q-value of the ERB (default=9.26449). * **min_bw** (float) - Minimum bandwidth of an ERB. ### Methods #### filter(_X_) ##### Description Filter input signal `X` along its last dimension using the Gammatone filterbank. ##### Parameters * **X** (ndarray, shape=(n_chans, n_times)) - Signal to filter. ##### Returns Filtered signals with shape `(M, N)`, where `M` is the number of channels, and `N` is the input signal’s number of samples. ##### Return Type ndarray ## Auditory Utility Functions ### Description Provides functions for converting between ERB (Equivalent Rectangular Bandwidth) and Hz, calculating ERB bandwidth, and generating frequency scales. ### Functions #### erb2hz(_erb_) ##### Description Convert ERB-rate values to the corresponding frequencies in Hz. #### erb_bandwidth(_fc_) ##### Description Calculate the bandwidth of an Equivalent Rectangular Bandwidth (ERB). ##### Parameters * **fc** (ndarray) - Center frequency, or center frequencies, of the filter. ##### Returns Equivalent rectangular bandwidth of the filter(s). ##### Return Type ndarray or float #### erbspace(_flow_, _fhigh_, _n_) ##### Description Generate `n` equidistantly spaced points on the ERB scale. #### hz2erb(_f_) ##### Description Convert frequencies to the corresponding ERB-rates. ##### Notes There is a round-off error in the Glasberg & Moore paper, as 1000 / (24.7 * 4.37) * log(10) = 21.332 and not 21.4 as is stated. ``` -------------------------------- ### Compare dss_line and dss_line_iter results Source: https://nbara.github.io/python-meegkit/_downloads/127999bfe25ff667ca6d2d8ac8525a33/example_dss_line.ipynb Visualize the PSD results comparing the standard dss_line and the iterative dss_line_iter methods. ```python f, ax = plt.subplots(1, 2, sharey=True) f, Pxx = signal.welch(unfold(out1), sfreq, nperseg=200, axis=0, return_onesided=True) ax[0].semilogy(f, Pxx, lw=.5) f, Pxx = signal.welch(unfold(out2), sfreq, nperseg=200, axis=0, return_onesided=True) ax[1].semilogy(f, Pxx, lw=.5) ax[0].set_xlabel("frequency [Hz]") ax[1].set_xlabel("frequency [Hz]") ax[0].set_ylabel("PSD [V**2/Hz]") ax[0].set_title("dss_line") ax[1].set_title("dss_line_iter") plt.tight_layout() plt.show() ```