Skip to main content

A Python package for electrogastrography (EGG) signal processing and gastric-brain coupling analysis.

Project description

GastroPy Logo

GastroPy

A Python toolkit for electrogastrography (EGG) signal processing and gastric-brain coupling analysis.

Tests Docs License: MIT Python 3.10+


What is GastroPy?

GastroPy gives researchers a modular, tested Python pipeline for working with electrogastrography data — from raw signal to publication-ready metrics. It is designed to work with EGG recordings from any acquisition setup (standalone Biopac, ambulatory, MRI-concurrent, etc.) and provides specialised helpers for gastric-brain coupling analyses with fMRI, EEG, and MEG.

Key Features

Module What it does
gastropy.signal Welch PSD, FIR/IIR bandpass filtering, Hilbert phase extraction, cycle detection, resampling, phase-based artifact detection
gastropy.metrics Gastric frequency bands, band power, instability coefficient, cycle statistics, quality assessment
gastropy.egg High-level pipeline (egg_process), channel selection (find_peaks), peak frequency detection
gastropy.timefreq Per-band narrowband decomposition, cycle analysis across brady/normo/tachy bands
gastropy.coupling Phase-locking value (PLV), complex PLV, surrogate testing, circular statistics (Rayleigh test, resultant length)
gastropy.viz PSD plots, EGG overview panels, cycle histograms, artifact displays, fMRI volume phase, brain coupling maps
gastropy.data Bundled sample datasets (fMRI-EGG and standalone EGG), downloadable fMRI BOLD via fetch_fmri_bold
gastropy.neuro.fmri Scanner triggers, volume windowing, confound regression, voxelwise BOLD phase extraction, PLV map computation, NIfTI I/O

Planned: data I/O with BIDS support, EEG/MEG utilities, and statistical testing. See the Roadmap below.

Installation

From source (recommended during pre-release)

git clone https://github.com/embodied-computation-group/gastropy.git
cd gastropy
pip install -e ".[dev]"

Optional extras

pip install -e ".[neuro]"   # adds MNE, nilearn, nibabel
pip install -e ".[docs]"    # adds Sphinx, sphinx-book-theme, etc.
pip install -e ".[all]"     # everything

Quick Start

Load sample data

import gastropy as gp

# Bundled sample datasets — no external downloads needed
data = gp.load_egg()                        # standalone 7-channel EGG
fmri = gp.load_fmri_egg(session="0001")     # fMRI-concurrent 8-channel EGG
gp.list_datasets()                           # see all available datasets

One-liner pipeline

import numpy as np
import gastropy as gp

# Simulate a 5-minute EGG recording (3 cpm, 10 Hz sampling)
sfreq = 10.0
t = np.arange(0, 300, 1 / sfreq)
signal = np.sin(2 * np.pi * 0.05 * t) + 0.1 * np.random.randn(len(t))

# Full processing in one call
signals, info = gp.egg_process(signal, sfreq)

print(f"Peak frequency : {info['peak_freq_hz']:.3f} Hz")
print(f"Cycles detected: {info['cycle_stats']['n_cycles']}")
print(f"Instability IC : {info['instability_coefficient']:.4f}")
print(f"% Normogastric : {info['proportion_normogastric']:.0%}")

Artifact detection

# Detect phase artifacts (non-monotonic phase + duration outliers)
artifacts = gp.detect_phase_artifacts(signals["phase"].values, t)
print(f"Artifact cycles: {artifacts['n_artifacts']}")

Visualization

# PSD with normogastric band shading
fig, ax = gp.plot_psd(freqs, psd)

# 4-panel EGG overview (raw, filtered, phase, amplitude)
fig, axes = gp.plot_egg_overview(signals, sfreq)

# Cycle duration histogram
fig, ax = gp.plot_cycle_histogram(info["cycle_durations_s"])

# Phase with artifact overlay
fig, ax = gp.plot_artifacts(signals["phase"].values, t, artifacts)

Step-by-step control

# Spectral analysis (overlap parameter for smoothing control)
freqs, psd = gp.psd_welch(signal, sfreq, fmin=0.01, fmax=0.1, overlap=0.75)

# Bandpass filter to normogastric band (2-4 cpm)
filtered, filt_info = gp.apply_bandpass(signal, sfreq, low_hz=0.033, high_hz=0.067)

# Instantaneous phase & amplitude via Hilbert transform
phase, analytic = gp.instantaneous_phase(filtered)

# Cycle detection and metrics
durations = gp.cycle_durations(phase, t)
ic = gp.instability_coefficient(durations)

Multi-channel selection

# data: (n_channels, n_samples) numpy array
best_ch, peak_freq, freqs, psd = gp.select_best_channel(data, sfreq)

fMRI-concurrent EGG

from gastropy.neuro.fmri import (
    find_scanner_triggers, create_volume_windows,
    phase_per_volume, apply_volume_cuts,
)

onsets = find_scanner_triggers(raw.annotations, label="R128")
windows = create_volume_windows(onsets, tr=1.856, n_volumes=420)
phases = phase_per_volume(analytic, windows)
phases = apply_volume_cuts(phases, begin_cut=21, end_cut=21)

# Visualize per-volume phase with cut regions
fig, ax = gp.plot_volume_phase(phases, tr=1.856, cut_start=21, cut_end=21)

Gastric-brain coupling

import gastropy as gp
from gastropy.neuro.fmri import (
    load_bold, align_bold_to_egg, regress_confounds,
    bold_voxelwise_phases, compute_plv_map, to_nifti,
)

# Load preprocessed fMRI data (requires pip install gastropy[neuro])
bold = load_bold("bold_preproc.nii.gz", "brain_mask.nii.gz")
egg = gp.load_fmri_egg(session="0001")

# Align BOLD volumes to EGG triggers, regress confounds
bold_2d, confounds = align_bold_to_egg(bold["bold_2d"], len(egg["trigger_times"]), confounds_df)
residuals = regress_confounds(bold_2d, confounds)

# Extract BOLD phase at individual gastric frequency
bold_phases = bold_voxelwise_phases(residuals, peak_freq_hz=0.05, sfreq=1/1.856)

# Compute voxelwise PLV map
plv_map = compute_plv_map(egg_phase, bold_phases, vol_shape=bold["vol_shape"], mask_indices=bold["mask"])

# Visualize on brain
plv_img = to_nifti(plv_map, bold["affine"])
gp.plot_coupling_map(plv_img, threshold=0.03)
gp.plot_glass_brain(plv_img, threshold=0.03)

Tutorials & Examples

Step-by-step tutorials covering the full pipeline:

Browse the Examples Gallery for short, focused examples: PSD plots, signal overviews, cycle histograms, artifact detection, channel selection, multi-band analysis, PLV computation, surrogate testing, circular statistics, and brain map visualization.

Documentation

Full API reference and tutorials at embodied-computation-group.github.io/gastropy.

Roadmap

GastroPy is under active development. Current status:

  • gastropy.signal — core DSP, phase-based artifact detection
  • gastropy.metrics — band power, instability coefficient, quality control
  • gastropy.egg — high-level pipeline, channel selection
  • gastropy.timefreq — per-band decomposition and cycle analysis
  • gastropy.coupling — PLV, complex PLV, surrogate testing, circular statistics
  • gastropy.neuro.fmri — triggers, confound regression, BOLD phase extraction, PLV maps, NIfTI I/O
  • gastropy.data — bundled sample datasets + downloadable fMRI BOLD
  • gastropy.viz — publication-ready plotting (8 functions including brain maps)
  • gastropy.io — data I/O, BIDS support
  • gastropy.neuro.eeg / gastropy.neuro.meg — EEG/MEG utilities
  • gastropy.stats — statistical testing

Contributing

Contributions are welcome! To get started:

git clone https://github.com/embodied-computation-group/gastropy.git
cd gastropy
pip install -e ".[dev]"
pre-commit install

Run the test suite:

pytest

Check code style:

ruff check gastropy/
ruff format --check gastropy/

Citation

If you use GastroPy in your research, please cite:

@software{gastropy,
  title   = {GastroPy: A Python Package for Electrogastrography Signal Processing and Gastric-Brain Coupling Analysis},
  author  = {Allen, Micah},
  year    = {2026},
  url     = {https://github.com/embodied-computation-group/gastropy}
}

License

GastroPy is released under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gastropy-0.1.0.tar.gz (12.3 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gastropy-0.1.0-py3-none-any.whl (1.9 MB view details)

Uploaded Python 3

File details

Details for the file gastropy-0.1.0.tar.gz.

File metadata

  • Download URL: gastropy-0.1.0.tar.gz
  • Upload date:
  • Size: 12.3 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for gastropy-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2e8e4e8cb75bb90c003bc44db2ff8c6f2a7bdba8241595ad25b91e4c8411cf44
MD5 66e55d4a6997abc720565e7c4c70afa9
BLAKE2b-256 2ca912f25fbbd5c127e811fcefce1d62df71f075043db992beb634bc01877b9e

See more details on using hashes here.

File details

Details for the file gastropy-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: gastropy-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 1.9 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for gastropy-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 785c1a429bd2e5518521f633c85289c83e265e9747812a4f65efc145ea89ad54
MD5 8ad412b05f67906862ad85758e7510b5
BLAKE2b-256 d7b69855117d67ade9d725110e4b138cbed9378735a35658d2512d1918fd9ed8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page