Skip to main content

High-performance signal processing for BCI research

Project description

zpybci -- Zerostone Python for BCI

High-performance, real-time signal processing for brain-computer interface research. Powered by Rust with zero-copy NumPy integration.

Installation

pip install zpybci

Wheels are available for Linux (x86_64, aarch64), macOS (Intel + Apple Silicon), and Windows (x86_64). Python 3.8+.

Quick Start

import numpy as np
import zpybci as zbci

# Bandpass filter for alpha band (8-12 Hz)
bpf = zbci.IirFilter.butterworth_bandpass(sample_rate=256.0, low_cutoff=8.0, high_cutoff=12.0)
signal = np.random.randn(1000).astype(np.float32)
filtered = bpf.process(signal)

# ICA for artifact removal
ica = zbci.Ica(channels=16, contrast="logcosh")
ica.fit(eeg_data, max_iter=200)
cleaned = ica.remove_components(eeg_data, exclude=[0, 2])  # remove blink/muscle artifacts

# Load an EDF file -- no MNE dependency needed
rec = zbci.read_edf("recording.edf")
ch1 = rec.get_channel("Fp1")
all_data = rec.get_all_channels()  # (n_channels, n_samples) numpy array

Validated Results

Tested on the BCI Competition IV 2a motor imagery benchmark (9 subjects, 4-class, session-to-session transfer):

Pipeline Mean Accuracy Published Baseline
CSP+LDA 40.5% ~40-50%
TS+LDA 64.4% ~60-68%
MDM 59.0% ~55-62%
xDAWN+MDM 57.4% ~55-60%

TS+LDA exceeds the original competition winner (FBCSP, ~63%). All pipelines built entirely with zpybci primitives.

Features

Filters

  • IIR -- Butterworth lowpass, highpass, bandpass (order 2/4/6/8, proper pole placement matching scipy)
  • FIR -- arbitrary-length finite impulse response
  • AC coupling -- DC removal for streaming data
  • Median -- nonlinear smoothing
  • Adaptive -- LMS and NLMS for noise cancellation
  • Notch -- narrowband rejection (e.g., 50/60 Hz line noise)

Spatial Filters

  • CAR -- common average reference
  • Surface Laplacian -- current source density approximation
  • Channel Router -- flexible channel remapping
  • xDAWN -- supervised spatial filters maximizing ERP signal-to-noise ratio

Spectral Analysis

  • FFT -- fast Fourier transform (magnitude/phase)
  • STFT -- short-time Fourier transform
  • Multi-band power -- concurrent power in multiple frequency bands
  • Welch PSD -- power spectral density estimation
  • CWT -- continuous wavelet transform (Morlet)

Independent Component Analysis

  • FastICA -- symmetric parallel extraction with LogCosh, Exp, and Cube contrast functions
  • Artifact removal -- remove blink/muscle/cardiac components and reconstruct clean signal
  • Channel counts -- 4, 8, 16, 32, or 64 channels

Kalman Filter

  • State estimation -- predict/update cycle for real-time decoder smoothing
  • Joseph form -- numerically stable covariance update (preserves positive definiteness)
  • Flexible dimensions -- 8 state/observation combinations from (2,1) to (8,8)

Linear Discriminant Analysis

  • Fisher's LDA -- binary classification with shrinkage regularization
  • Calibrated probabilities -- predict_proba() via sigmoid scaling
  • Feature dimensions -- 2, 4, 6, 8, 12, 16, 32, or 64

Spike Sorting

  • Full pipeline -- sort_multichannel() for end-to-end multi-channel spike sorting (noise estimation, spatial whitening, detection, deduplication, peak alignment, PCA, online k-means, cluster merge/split, template subtraction, NCC residual detection, SNR auto-curation)
  • Streaming API -- StreamingSorter for segment-based processing with persistent template library, exponential moving average template updates, and online rigid drift estimation
  • Batch parallel -- sort_batch_parallel() for rayon-based parallel sorting of long recordings
  • Detection modes -- amplitude threshold, NEO (Nonlinear Energy Operator), SNEO (Smoothed NEO)
  • Probe geometry -- ProbeLayout with linear, polytrode, tetrode, Neuropixels 1.0/2.0, Utah array presets
  • Template subtraction -- multi-pass template subtraction with per-spike amplitude scaling and NCC residual detection
  • Cluster refinement -- d-prime merge, spatial merge, CCG-based merge, ISI-violation split, amplitude bimodality split, GMM full-covariance EM
  • Quality metrics -- per-cluster SNR, ISI violation rate, contamination rate, d-prime, silhouette score
  • SVD template initialization -- power-iteration SVD for principled initial centroids (no random k-means init dependency)
  • Drift correction -- rigid drift estimation per streaming segment via spatial cross-correlation of template positions
  • Wavelet denoising -- Haar SWT with Donoho-Johnstone universal threshold for preprocessing
  • Supported channels -- 4, 8, 16, 32, 64, 96, 128 (const-generic, no_std core)
  • Convenience pipeline -- spike_sort() for simple single-channel sorting with online k-means

EDF/EDF+ File Reader

  • read_edf() -- load EDF/EDF+ files without MNE or pyedflib
  • Channel access -- by index or label name
  • Physical units -- automatic digital-to-physical conversion
  • Mixed sample rates -- zero-padded multi-channel extraction

XDF File Reader (Lab Streaming Layer)

  • read_xdf() -- load XDF files from LSL recordings
  • Multi-stream -- numeric and string streams with per-stream metadata
  • Clock offsets -- collection time and offset value pairs
  • Sample formats -- float32, float64, int8, int16, int32, int64, string

Detection

  • Threshold -- fixed-threshold event detection
  • Adaptive threshold -- self-adjusting threshold based on signal statistics
  • Zero-crossing -- rate estimation

Artifact Handling

  • Amplitude-based -- flag samples exceeding a threshold
  • Z-score -- flag statistically outlying segments

Analysis

  • Envelope follower -- instantaneous amplitude via rectification + smoothing
  • Windowed RMS -- streaming root-mean-square
  • Hilbert transform -- analytic signal, instantaneous phase/frequency

Phase-Amplitude Coupling

  • Modulation index -- Tort et al. (2010), KL-divergence from uniform phase distribution
  • Mean vector length -- Canolty et al. (2006), normalized complex coupling strength
  • Comodulogram -- PAC across frequency pairs (bandpass + Hilbert + MI/MVL)
  • Phase-amplitude distribution -- binned amplitude histogram for visualization

Entropy Measures

  • Sample entropy -- template-matching complexity measure (SampEn)
  • Approximate entropy -- regularity statistic with self-matches (ApEn)
  • Spectral entropy -- Shannon entropy of normalized PSD
  • Multiscale entropy -- coarse-grained sample entropy across time scales

Event-Related Spectral Perturbation (ERSP)

  • compute_ersp() -- STFT-based time-frequency decomposition with epoch averaging
  • baseline_normalize() -- dB, z-score, percentage, and log-ratio normalization modes
  • Single-trial mode -- per-epoch time-frequency maps without averaging

Statistics

  • Online mean/variance -- Welford's algorithm, no buffer required
  • Online covariance -- streaming covariance matrix
  • Connectivity -- coherence, phase locking value (PLV), and Granger causality
  • Conditional Granger -- Granger causality conditioned on confound variables

BCI Paradigms

  • Motor imagery -- CSP with online adaptation, sklearn-compatible transformer
  • SSVEP -- CCA-based frequency detection, reference signal generation
  • P300/ERP -- epoch averaging, xDAWN spatial filters

Riemannian Geometry

  • Tangent space -- SPD manifold projection for classification
  • MDM classifier -- minimum distance to mean on SPD manifold
  • Frechet mean -- geometric mean of SPD matrices
  • Riemannian distance -- affine-invariant distance metric
  • Recentering -- domain adaptation via Riemannian transport

Sklearn Integration

  • CSPTransformer -- common spatial patterns as sklearn transformer
  • TangentSpaceTransformer -- Riemannian tangent space projection
  • BandPowerTransformer -- multi-band power feature extraction
  • CovarianceEstimator -- covariance matrix estimation
  • LdaClassifier -- Fisher's LDA with predict_proba and score
  • IcaTransformer -- ICA with component exclusion for artifact removal
  • MdmWrapper -- minimum distance to mean classifier
  • XDawnWrapper -- xDAWN spatial filter transformer
  • Works with make_pipeline(), cross_val_score(), GridSearchCV()

Advanced

  • OASIS deconvolution -- calcium transient inference from fluorescence traces

Utilities

  • Pipeline -- declarative stage chaining with a single process() call
  • Resampling -- integer decimation and interpolation
  • Streaming percentile -- approximate quantiles on unbounded streams
  • Clock sync -- offset estimation, linear drift correction, sample clock alignment
  • Cross-correlation -- full, valid, and circular modes
  • Window functions -- Hann, Hamming, Blackman, flat-top, Kaiser

Version

0.8.0

License

GPL-3.0

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

zpybci-0.8.0.tar.gz (744.7 kB view details)

Uploaded Source

Built Distributions

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

zpybci-0.8.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (2.0 MB view details)

Uploaded PyPymanylinux: glibc 2.17+ ARM64

zpybci-0.8.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (2.0 MB view details)

Uploaded PyPymanylinux: glibc 2.17+ ARM64

zpybci-0.8.0-cp38-abi3-win_amd64.whl (1.9 MB view details)

Uploaded CPython 3.8+Windows x86-64

zpybci-0.8.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.1 MB view details)

Uploaded CPython 3.8+manylinux: glibc 2.17+ x86-64

zpybci-0.8.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (2.0 MB view details)

Uploaded CPython 3.8+manylinux: glibc 2.17+ ARM64

zpybci-0.8.0-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl (3.9 MB view details)

Uploaded CPython 3.8+macOS 10.12+ universal2 (ARM64, x86-64)macOS 10.12+ x86-64macOS 11.0+ ARM64

File details

Details for the file zpybci-0.8.0.tar.gz.

File metadata

  • Download URL: zpybci-0.8.0.tar.gz
  • Upload date:
  • Size: 744.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for zpybci-0.8.0.tar.gz
Algorithm Hash digest
SHA256 07e12a5584deafa19ac0542985415e8d728defb411b828765bce7aa8d66e2908
MD5 b671a94c8930ce6a2b65c1cadfe74068
BLAKE2b-256 e1a811e04fc2f1b9e05fa63eb7545318b4c94903abb8915ffc37719f24c858c9

See more details on using hashes here.

Provenance

The following attestation bundles were made for zpybci-0.8.0.tar.gz:

Publisher: release.yml on fredrikWHaug/zerostone

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file zpybci-0.8.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for zpybci-0.8.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 64edb9e12c1d6aa2e62900d0a07cdeadca9dafab35d90a3f3ab04a75fb5cb786
MD5 d9549d06a3ce094eef4d0ba7621e7516
BLAKE2b-256 fad74eda12328ddbf418d3f7323c5403b29e1b833c9b746468183e198b9ac3b7

See more details on using hashes here.

Provenance

The following attestation bundles were made for zpybci-0.8.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: release.yml on fredrikWHaug/zerostone

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file zpybci-0.8.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for zpybci-0.8.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 0755459ee0e1cffe503865f7100ec8d73fe9c8577a8b5919c7250ea4b442314e
MD5 8706c548014664645ad53cd5c6d8238c
BLAKE2b-256 449473808a8c1a99a6b684d816d8dec9726ac74afc4f23de9d9a16be392574dc

See more details on using hashes here.

Provenance

The following attestation bundles were made for zpybci-0.8.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: release.yml on fredrikWHaug/zerostone

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file zpybci-0.8.0-cp38-abi3-win_amd64.whl.

File metadata

  • Download URL: zpybci-0.8.0-cp38-abi3-win_amd64.whl
  • Upload date:
  • Size: 1.9 MB
  • Tags: CPython 3.8+, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for zpybci-0.8.0-cp38-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 ce19f3551ae4e37538500e77e2ca202f1a55656ebd24ac8d9469655b4c2d1cdd
MD5 3921cfa1e55f070e971e03d3f8d3ba9d
BLAKE2b-256 28f13cf0d664a3741318d95183a9db6843e0cfe7a9c72e6123fb2e9d906e6cdc

See more details on using hashes here.

Provenance

The following attestation bundles were made for zpybci-0.8.0-cp38-abi3-win_amd64.whl:

Publisher: release.yml on fredrikWHaug/zerostone

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file zpybci-0.8.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for zpybci-0.8.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 c9ea9101fae4ff2ddfecd0b2ff9a409b887a8a7d189a3023753069f5f5b99db0
MD5 3e2b7fed1512d93be7e3a52fc8248a28
BLAKE2b-256 5e05aeae7ce2a432533040016047e96bcc38423a4e98b1bfcf706f7a384857b0

See more details on using hashes here.

Provenance

The following attestation bundles were made for zpybci-0.8.0-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on fredrikWHaug/zerostone

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file zpybci-0.8.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for zpybci-0.8.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 f88c37e1f220aac41436994ebfd001558c306a8a13105c967b3609548fb51672
MD5 c1910766fdc70160e1bd9f05bcf8472c
BLAKE2b-256 488bc0d6fbd22a9e92b28ed7ac42f536867cf17b5a732d480ce163f3d7c8b780

See more details on using hashes here.

Provenance

The following attestation bundles were made for zpybci-0.8.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: release.yml on fredrikWHaug/zerostone

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file zpybci-0.8.0-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl.

File metadata

File hashes

Hashes for zpybci-0.8.0-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl
Algorithm Hash digest
SHA256 cb73d6c735035c816f29a412bd1a06d019a738a80cbe448d9555da3ce4db1a70
MD5 fe71b0501ac347f54661010eebb9f6af
BLAKE2b-256 35b1b33f7504bd6c672e8c334b18925f79ee02dcba5ec427db9222fe79ed5d6c

See more details on using hashes here.

Provenance

The following attestation bundles were made for zpybci-0.8.0-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl:

Publisher: release.yml on fredrikWHaug/zerostone

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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