Skip to main content

gPAC: GPU-Accelerated Phase-Amplitude Coupling

PyPI version pytest codecov License: MIT Python 3.8+

gPAC is a PyTorch-based package for efficient computation of Phase-Amplitude Coupling (PAC) using Modulation Index (MI) with GPU acceleration. It provides:

  • 341.8x speedup over TensorPAC (tested on real benchmarks)
  • Smart memory management with auto/chunked/sequential strategies
  • Full differentiability for deep learning integration
  • Production-ready with comprehensive tests and examples
  • High correlation with TensorPAC (0.81 ± 0.04 across diverse PAC configurations)

🎯 Example Applications

Static PAC Analysis
Static PAC Analysis
Comodulogram visualization
Trainable PAC Classification
Trainable PAC Classification
Deep learning integration
PAC Comparison
Static vs Trainable Comparison
Performance & accuracy analysis
Amplitude Distributions
Amplitude Distributions
Phase preference for clinical analysis

🔬 PAC Values Comparison with TensorPAC

Comparison Pair 1
Phase: 4Hz, Amp: 40Hz
Correlation: 0.826
Comparison Pair 4
Phase: 12Hz, Amp: 100Hz
Correlation: 0.730
Correlation Summary
Overall Correlation
0.811 ± 0.042 (n=16)

Click images to view full size. Ground truth PAC locations marked with crosses.

📊 Performance Benchmarks

Parameter Scaling
Parameter Scaling Comparison
gPAC (blue) vs TensorPAC (red)
Performance Analysis
Performance Analysis
Speed & memory efficiency

Click images to view detailed performance metrics

🚀 Quick Start

# Installation
pip install gpu-pac

Quick Start

import torch
from torch.utils.data import DataLoader
from gpac import PAC
from gpac.dataset import SyntheticDataGenerator

# Generate synthetic PAC dataset
generator = SyntheticDataGenerator(fs=512, duration_sec=2.0)
dataset = generator.dataset(n_samples=100, balanced=True)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)

# Method 1: Specify frequency range and number of bands
pac_model = PAC(
    seq_len=dataset[0][0].shape[-1],
    fs=512,
    pha_range_hz=(2, 20),    # Phase: 2-20 Hz
    pha_n_bands=10,          # 10 linearly spaced bands
    amp_range_hz=(30, 100),  # Amplitude: 30-100 Hz  
    amp_n_bands=10,          # 10 linearly spaced bands
)

# Method 2: Direct band specification (alternative)
# pac_model = PAC(
#     seq_len=dataset[0][0].shape[-1],
#     fs=512,
#     pha_bands_hz=[[4, 8], [8, 12], [12, 20]],      # Theta, Alpha, Beta
#     amp_bands_hz=[[30, 50], [50, 80], [80, 120]],  # Low, Mid, High Gamma
# )

# Move to GPU if available
device = 'cuda' if torch.cuda.is_available() else 'cpu'
pac_model = pac_model.to(device)

# Process a batch
for signals, labels, metadata in dataloader:
    signals = signals.to(device)
    
    # Calculate PAC
    results = pac_model(signals)
    pac_values = results['pac']  # Shape: (batch, channels, pha_bands, amp_bands)
    
    print(f"Batch PAC shape: {pac_values.shape}")
    print(f"Max PAC value: {pac_values.max().item():.3f}")
    
    # Access frequency band definitions
    print(f"Phase bands: {pac_model.pha_bands_hz}")  # Tensor of shape (n_pha, 2) with [low, high] Hz
    print(f"Amplitude bands: {pac_model.amp_bands_hz}")  # Tensor of shape (n_amp, 2) with [low, high] Hz
    
    # Advanced: Get amplitude distributions for phase preference analysis
    results_with_dist = pac_model(signals, compute_distributions=True)
    amp_distributions = results_with_dist['amplitude_distributions']
    print(f"Amplitude distributions shape: {amp_distributions.shape}")
    # Shape: (batch, channels, pha_bands, amp_bands, n_phase_bins=18)
    
    break  # Just show first batch

For more examples, see the examples directory.

📊 Amplitude Distributions for Clinical Analysis

The compute_distributions=True option provides detailed phase preference analysis, particularly useful for seizure detection and neurophysiological research:

# Compute PAC with amplitude distributions
results = pac_model(signals, compute_distributions=True)

# Access distributions
pac_values = results['pac']
amp_distributions = results['amplitude_distributions']
phase_bin_centers = results['phase_bin_centers']  # Phase bins in radians

# Analyze phase preference for strongest coupling
batch_idx, ch_idx = 0, 0
max_idx = pac_values[batch_idx, ch_idx].argmax()
pha_idx, amp_idx = np.unravel_index(max_idx, pac_values[batch_idx, ch_idx].shape)

# Get the amplitude distribution across phase bins
phase_dist = amp_distributions[batch_idx, ch_idx, pha_idx, amp_idx]

# Calculate phase preference metrics
preferred_phase = phase_bin_centers[phase_dist.argmax()]
distribution_entropy = -torch.sum(phase_dist * torch.log(phase_dist + 1e-10))

print(f"Preferred phase: {preferred_phase * 180/np.pi:.1f}°")
print(f"Distribution entropy: {distribution_entropy:.3f}")

Clinical Applications:

  • Seizure onset detection: Phase preference changes may precede visible PAC strength changes
  • Distribution shape analysis: Bimodal distributions indicate competing neural dynamics
  • Temporal tracking: Monitor distribution evolution for state transitions
  • Network synchronization: Compare distributions across frequency pairs

🔧 Core Features

Flexible Frequency Band Configuration

  • Range-based: Specify frequency range and number of bands for automatic spacing
  • Direct specification: Define custom frequency bands for precise control
  • Standard bands: Compatible with theta, alpha, beta, gamma conventions
  • High resolution: Support for 50+ bands for detailed analysis
  • Band access: Direct access to frequency band definitions via pac.pha_bands_hz and pac.amp_bands_hz properties

GPU Optimization

  • Multi-GPU support: Automatic data parallelism across GPUs
  • FP16 mode: Half-precision computation for 2x memory efficiency
  • Torch compilation: JIT compilation for additional speedup
  • Batch processing: Efficient handling of multiple signals

Scientific Features

  • Permutation testing: Statistical validation with n_perm surrogates
  • Z-score normalization: Automatic statistical significance testing
  • Modulation Index: Standard MI calculation with 18 phase bins
  • Full differentiability: Gradient support for deep learning applications
  • Amplitude distributions: Optional phase preference analysis for clinical applications

🤝 Contributing

Contributions are welcome! Please see our contributing guidelines.

📖 Citation

If you use gPAC in your research, please cite:

@software{watanabe2025gpac,
  author = {Watanabe, Yusuke},
  title = {gPAC: GPU-Accelerated Phase-Amplitude Coupling},
  year = {2025},
  url = {https://github.com/ywatanabe1989/gPAC}
}

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • TensorPAC team for the reference implementation
  • For fair comparison with TensorPAC, use identical frequency bands as demonstrated in ./benchmark/pac_values_comparison_with_tensorpac/generate_16_comparison_pairs.py

Metadata

Release files for gpu-pac 0.3.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gpu-pac 0.3.4
File Size Uploaded Provenance
gpu_pac-0.3.4.tar.gz 39.4 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for gpu-pac 0.3.4
File Interpreter ABI Platform
gpu_pac-0.3.4-py3-none-any.whl Python 3 none any Details

Total release size: 89.2 kB

Release files / gpu_pac-0.3.4.tar.gz

Download URL gpu_pac-0.3.4.tar.gz
Size 39.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f11216978bfb4e90ea9cfde410f5d875818af5c8883b98e6c23011ec7f6b5fa3
BLAKE2b-256 checksum
How to use checksums
27af0bce326f84d37d30e28d321a9f554059d9aaebe205aa8aa9c6ed41bd8534
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.4

Release files / gpu_pac-0.3.4-py3-none-any.whl

Download URL gpu_pac-0.3.4-py3-none-any.whl
Size 49.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a31beb70304ae59903b6cdfd10a1115f6ba709b53e13d26a1713940c1a3de6f0
BLAKE2b-256 checksum
How to use checksums
270582d1f7b4547f3c36cb55116663d092fe99540239f81f8420bb26ea9fe4c2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.4

Security for gpu-pac 0.3.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page