Skip to main content

Nimbus BCI: Bayesian classifiers for brain-computer interfaces

Project description

nimbus-bci

Bayesian BCI classifiers with sklearn compatibility, streaming inference, active-learning calibration loops, and rich diagnostics.

PyPI Python License

Documentation in this repo: Why Nimbus? (vs sklearn / pyRiemann) · Trust, calibration, and rejection · Active-learning calibration loops — cut calibration time with BALD ranking and label-free stopping. Hosted docs: docs.nimbusbci.com.

Features

  • Four sklearn-compatible classifiers: three static Bayesian decoders — LDA, QDA, Softmax (Polya–Gamma) — plus NimbusSTS for latent-state / non-stationary settings (EKF-style updates, experimental)
  • sklearn-compatible API: Works with pipelines, cross-validation, and GridSearchCV
  • Streaming inference: Real-time chunk-by-chunk processing
  • Active learning: suggest_next_trial (BALD on LDA/QDA/Softmax), should_query streaming gate, and label-free calibration_sufficient stopping — cut cued calibration time without manual heuristics
  • Rich diagnostics: Entropy, Mahalanobis distance, calibration metrics (ECE/MCE)
  • Online learning: Update models with new data without retraining
  • BCI-specific utilities: ITR calculation, temporal aggregation, quality assessment
  • MNE-Python integration: Convert between MNE Epochs and Nimbus data formats

Installation

pip install nimbus-bci

To use the optional JAX-based softmax model:

pip install nimbus-bci[softmax]

From source:

git clone https://github.com/nimbusbci/nimbuspysdk.git
cd nimbuspysdk
pip install -e ".[all]"

Quick Start

sklearn-Compatible API (Recommended)

from nimbus_bci import NimbusLDA, NimbusQDA, NimbusSoftmax, NimbusSTS
import numpy as np

# Create and fit classifier
clf = NimbusLDA()
clf.fit(X_train, y_train)

# Predict
predictions = clf.predict(X_test)
probabilities = clf.predict_proba(X_test)

# Online learning
clf.partial_fit(X_new, y_new)

Works with sklearn Pipelines

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score, GridSearchCV

# Simple pipeline
pipe = make_pipeline(StandardScaler(), NimbusLDA())
pipe.fit(X_train, y_train)

# Cross-validation
scores = cross_val_score(NimbusLDA(), X, y, cv=5)
print(f"Accuracy: {scores.mean():.2%} (+/- {scores.std():.2%})")

# Hyperparameter tuning
param_grid = {'mu_scale': [1.0, 3.0, 5.0], 'class_prior_alpha': [0.5, 1.0]}
grid = GridSearchCV(NimbusLDA(), param_grid, cv=5)
grid.fit(X, y)
print(f"Best params: {grid.best_params_}")

Streaming Inference (Real-Time BCI)

from nimbus_bci import NimbusLDA, StreamingSession
from nimbus_bci.data import BCIMetadata

# Setup
metadata = BCIMetadata(
    sampling_rate=250.0,
    paradigm="motor_imagery",
    feature_type="csp",
    n_features=16,
    n_classes=4,
    chunk_size=125,  # 500ms chunks
    temporal_aggregation="logvar",
)

# Train model
clf = NimbusLDA()
clf.fit(X_train, y_train)

# Create streaming session
session = StreamingSession(clf.model_, metadata)

# Process chunks in real-time
for chunk in eeg_stream:
    result = session.process_chunk(chunk)
    print(f"Chunk prediction: {result.prediction} ({result.confidence:.2%})")

# Finalize trial with aggregation
final = session.finalize_trial(method="weighted_vote")
print(f"Final: class {final.prediction} (entropy: {final.entropy:.2f} bits)")

For NimbusSTS specifically (stateful latent dynamics), use StreamingSessionSTS so the latent state can be propagated and updated with delayed feedback:

from nimbus_bci import NimbusSTS
from nimbus_bci.inference import StreamingSessionSTS
from nimbus_bci.data import BCIMetadata

metadata = BCIMetadata(
    sampling_rate=250.0,
    paradigm="motor_imagery",
    feature_type="csp",
    n_features=16,
    n_classes=2,
    chunk_size=125,
    temporal_aggregation="mean",
)

clf = NimbusSTS().fit(X_train, y_train)
session = StreamingSessionSTS(clf, metadata)

result = session.process_chunk(chunk)  # propagates state by default
session.provide_feedback(label=0)      # when label arrives later

Active Learning (Calibration Loop)

Cut cued-calibration time by labeling only the trials the model is genuinely uncertain about, and stop automatically when the posterior settles:

from nimbus_bci import NimbusLDA
from nimbus_bci.active_learning import (
    suggest_next_trial,
    calibration_sufficient,
)

clf = NimbusLDA().fit(X_seed, y_seed)   # small initial cued batch
prev = clf.get_model()

for _ in range(max_rounds):
    # Rank the unlabeled pool by BALD informativeness, label the top 4.
    ranked = suggest_next_trial(
        clf, X_pool, strategy="bald", n=4, num_posterior_samples=64,
    )
    X_new, y_new = collect_labels_for(ranked.indices)   # cue + record
    clf.partial_fit(X_new, y_new)

    # Label-free stopping: when predict_proba over the pool stops moving,
    # more cues will not change predictions much.
    status = calibration_sufficient(
        clf, X_pool,
        criterion="posterior_stability",
        previous=prev, threshold=0.02,
    )
    if status.is_sufficient:
        break
    prev = clf.get_model()

Strategies (entropy, margin, least_confidence, bald) and stopping criteria (posterior_stability, expected_info_gain) are all model-agnostic. STS gets posterior_stability for free; BALD-based features on STS are deferred to v1.1. Full recipe in docs/active_learning.md.

Batch Inference with Diagnostics

from nimbus_bci import predict_batch
from nimbus_bci.data import BCIData, BCIMetadata

# Create BCI data container
metadata = BCIMetadata(
    sampling_rate=250.0,
    paradigm="motor_imagery",
    feature_type="csp",
    n_features=16,
    n_classes=4,
)
data = BCIData(features, metadata, labels)

# Run batch inference with full diagnostics
result = predict_batch(model, data)

print(f"Mean entropy: {result.mean_entropy:.2f} bits")
print(f"Balance: {result.balance:.2%}")
if result.calibration is not None:
    print(f"ECE: {result.calibration.ece:.3f}")
print(f"Latency: {result.latency_ms:.1f}ms")

MNE-Python Integration

import mne
from nimbus_bci import NimbusLDA
from nimbus_bci.compat import from_mne_epochs, extract_csp_features

# Load and preprocess with MNE
raw = mne.io.read_raw_gdf("motor_imagery.gdf")
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, tmin=0, tmax=4, baseline=None, preload=True)
epochs.filter(8, 30)  # Mu + Beta bands

# Extract CSP features
csp_features, csp = extract_csp_features(epochs, n_components=8)

# Train Nimbus classifier
clf = NimbusLDA()
clf.fit(csp_features, epochs.events[:, 2])

Available Classifiers

Classifier Description Best For
NimbusLDA Bayesian LDA with shared covariance Fast, when classes have similar shapes
NimbusQDA Bayesian QDA with class-specific covariances Complex class distributions
NimbusSoftmax Bayesian logistic regression (Polya-Gamma VI) Non-Gaussian decision boundaries
NimbusSTS Structural time series classifier (latent state + EKF-style inference) Non-stationary settings, drifting class boundaries (experimental)

Choosing the Right Classifier

Quick Decision Guide

Is your data stationary (distributions don't change over time)?

  • Yes → Use static models (LDA/QDA/Softmax)
  • No → Use NimbusSTS for temporal adaptation

For stationary data:

  • Classes have similar covariance?NimbusLDA (fastest)
  • Classes have different shapes?NimbusQDA
  • Non-Gaussian boundaries?NimbusSoftmax

For non-stationary data:

  • Gradual drift (fatigue, electrode shift)?NimbusSTS
  • Multi-day sessions with state transfer?NimbusSTS
  • Delayed feedback paradigms?NimbusSTS

Detailed Comparison

Scenario Recommended Model Why?
Stable offline datasets NimbusLDA Fastest, closed-form solution
P300 spelling (stable) NimbusLDA or NimbusQDA Event-related, stationary
SSVEP NimbusLDA Highly stationary frequency response
Motor Imagery (short sessions) NimbusLDA or NimbusQDA Stationary within session
Motor Imagery (long sessions, fatigue) NimbusSTS Tracks drift due to fatigue
Multi-day experiments NimbusSTS State transfer across sessions
Electrode repositioning NimbusSTS Adapts to impedance changes
Closed-loop with delayed feedback NimbusSTS Explicit state propagation
Asynchronous BCI (idle vs active) NimbusSTS Models engagement state
Neurofeedback training NimbusSTS Tracks learning-induced changes
Long calibration sessions, want to cut label cost Any head + suggest_next_trial(strategy="bald") Pool-based BALD on the conjugate posterior; LDA/QDA/Softmax in v1
Don't know when to stop calibrating Any head + calibration_sufficient Label-free posterior_stability works for STS too

NimbusSTS Example (Temporal Adaptation)

from nimbus_bci import NimbusSTS

# Train on calibration data
clf = NimbusSTS(transition_cov=0.05, num_steps=50)
clf.fit(X_calibration, y_calibration)

# Online session with delayed feedback
for x_trial, y_feedback in online_trials:
    # 1. Propagate state forward (no label needed)
    clf.propagate_state()
    
    # 2. Make prediction
    prediction = clf.predict(x_trial)
    
    # ... user performs action, feedback arrives later ...
    
    # 3. Update with true label
    clf.partial_fit(x_trial, y_feedback)

# Multi-day state transfer
z_day1, P_day1 = clf.get_latent_state()

# Day 2: Initialize with Day 1 state (increased uncertainty)
clf_day2 = NimbusSTS()
clf_day2.fit(X_day2_calib, y_day2_calib)
clf_day2.set_latent_state(z_day1 * 0.5, P_day1 * 2.0)

Label Conventions (Important)

Nimbus supports common EEG/BCI labeling patterns:

  • BCIData labels: can be any non-negative integer codes (e.g., MNE event IDs like 769/770), as long as the number of unique labels does not exceed BCIMetadata.n_classes.
  • sklearn estimators (NimbusLDA, NimbusQDA, NimbusSoftmax, NimbusSTS):
    • fit() learns classes_ from your provided labels.
    • predict() returns labels in the original label space (elements of classes_).
  • Model-snapshot inference (NimbusModel + predict_batch / StreamingSession):
    • predictions are returned in the model’s label_base convention (label_base is stored in model.params).
    • use nimbus_bci.data.labels_to_zero_indexed(...) for metrics/aggregation that require 0-indexed labels.

NimbusSTS Sequence Semantics (Important)

NimbusSTS has a latent state. For correctness and sklearn compatibility:

  • NimbusSTS.predict_proba(X) treats rows as conditionally independent by default.
  • For time-ordered evaluation, propagate explicitly:
    • call clf.propagate_state() between trials/chunks, or
    • use the functional API nimbus_sts_predict_proba(model, X, evolve_state=True) when X rows are ordered in time.

Metrics & Diagnostics

from nimbus_bci import (
    compute_entropy,            # Prediction uncertainty
    compute_calibration_metrics,  # ECE, MCE
    calculate_itr,              # Information Transfer Rate
    assess_trial_quality,       # Quality checks
)

# Entropy (uncertainty)
entropy = compute_entropy(posterior)  # bits

# Calibration
calib = compute_calibration_metrics(predictions, confidences, labels)
print(f"ECE: {calib.ece:.3f}, MCE: {calib.mce:.3f}")

# ITR
itr = calculate_itr(accuracy=0.85, n_classes=4, trial_duration=4.0)
print(f"ITR: {itr:.1f} bits/min")

Normalization

Critical for cross-session BCI performance:

from nimbus_bci import estimate_normalization_params, apply_normalization

# Estimate from training data
params = estimate_normalization_params(X_train, method="zscore")

# Apply to all data
X_train_norm = apply_normalization(X_train, params)
X_test_norm = apply_normalization(X_test, params)  # Same params!

Project Structure

nimbus_bci/
├── models/              # Classifiers
│   ├── nimbus_lda/     # LDA (shared covariance)
│   ├── nimbus_qda/     # QDA (class-specific covariances)
│   └── nimbus_softmax/ # Softmax (Polya-Gamma)
├── data/               # Data contracts (BCIData, BCIMetadata)
├── inference/          # Batch and streaming inference
├── metrics/            # Diagnostics, calibration, ITR
├── utils/              # Normalization, aggregation
└── compat/             # sklearn/MNE compatibility

Functional API (Backward Compatible)

The original functional API is still available:

from nimbus_bci import (
    nimbus_lda_fit, nimbus_lda_predict, nimbus_lda_update,
    nimbus_qda_fit, nimbus_qda_predict,
    nimbus_softmax_fit, nimbus_softmax_predict,
    nimbus_save, nimbus_load,
)

# Fit model
model = nimbus_lda_fit(X, y, n_classes=4, label_base=0, ...)

# Predict
probs = nimbus_lda_predict_proba(model, X_test)

# Update (online learning)
model = nimbus_lda_update(model, X_new, y_new)

# Save/load
nimbus_save(model, "model.npz")
model = nimbus_load("model.npz")

Testing

pip install -e ".[dev]"
pytest -v

Requirements

Core (installed with pip install nimbus-bci):

  • Python ≥ 3.11
  • NumPy ≥ 1.26
  • scikit-learn ≥ 1.4

Optional extras:

  • JAX ≥ 0.4.25 — required for NimbusSoftmax and the softmax functional API (pip install nimbus-bci[softmax])
  • MNE ≥ 1.6 — EEG integration (pip install nimbus-bci[mne])
  • matplotlib ≥ 3.8 — visualization (pip install nimbus-bci[viz])
  • SciPy ≥ 1.12 — included in pip install nimbus-bci[all] alongside the extras above

License

This software is proprietary and requires a valid license for use.

License Tiers

Tier Use Case
Evaluation 30-day free trial for R&D
Academic University research (free)
Startup Companies < $1M revenue
Commercial Full production rights
Enterprise Unlimited deployments + SLA
OEM/Embedded Medical devices, FDA support

Request Access

To obtain a license:

  1. Email hello@nimbusbci.com with your use case
  2. Receive API key and license agreement
  3. Install and start building

Website: https://nimbusbci.com


© 2024-2025 Nimbus BCI Inc. — The AI Engine for Brain-Computer Interfaces

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

nimbus_bci-0.4.0.tar.gz (121.2 kB view details)

Uploaded Source

Built Distributions

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

nimbus_bci-0.4.0-cp312-cp312-win_amd64.whl (472.4 kB view details)

Uploaded CPython 3.12Windows x86-64

nimbus_bci-0.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl (3.1 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.17+ x86-64manylinux: glibc 2.28+ x86-64

nimbus_bci-0.4.0-cp312-cp312-macosx_11_0_arm64.whl (525.7 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

nimbus_bci-0.4.0-cp312-cp312-macosx_10_9_x86_64.whl (539.7 kB view details)

Uploaded CPython 3.12macOS 10.9+ x86-64

nimbus_bci-0.4.0-cp311-cp311-win_amd64.whl (497.6 kB view details)

Uploaded CPython 3.11Windows x86-64

nimbus_bci-0.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl (2.9 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.17+ x86-64manylinux: glibc 2.28+ x86-64

nimbus_bci-0.4.0-cp311-cp311-macosx_11_0_arm64.whl (535.4 kB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

nimbus_bci-0.4.0-cp311-cp311-macosx_10_9_x86_64.whl (571.8 kB view details)

Uploaded CPython 3.11macOS 10.9+ x86-64

File details

Details for the file nimbus_bci-0.4.0.tar.gz.

File metadata

  • Download URL: nimbus_bci-0.4.0.tar.gz
  • Upload date:
  • Size: 121.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for nimbus_bci-0.4.0.tar.gz
Algorithm Hash digest
SHA256 516cda88eec1fc781c26122b9de54f09a7992d80c5e92671da8371b2200a7be2
MD5 85d35c56cfea8e2e74d82b50287ba7d4
BLAKE2b-256 2b8d68ea24fa000276effc92b16e1c4fd698adb95a94db474226ac73a27d0f64

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp312-cp312-win_amd64.whl.

File metadata

  • Download URL: nimbus_bci-0.4.0-cp312-cp312-win_amd64.whl
  • Upload date:
  • Size: 472.4 kB
  • Tags: CPython 3.12, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for nimbus_bci-0.4.0-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 4b9adc3e2fdfc9d03b0105f5683a8947eb7b79a1c57cce8c1596797fe38ecb08
MD5 817bae6921602e57c0d1d71de5b94e92
BLAKE2b-256 0ad4b6f862ac150a29537333d344e9ed8c8abeb7fb6de08cb8daf3a818967e45

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for nimbus_bci-0.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 fcf70cf0d225358332d29ac724ac927532718a1ba1e89ad251a3b1ebde7a8466
MD5 abf724d1d3d9950dcb73bb9d91400db0
BLAKE2b-256 e45ee2cbfb0a84a2cd73acc766bfe8d182c42b0b63b8795c947317efff90d64f

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for nimbus_bci-0.4.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 cd2557983ba54626ff68df725543983740c53c5809a7a42174c85b3787d71955
MD5 c973ed51c69ad7e5da9f1b362b666745
BLAKE2b-256 a35f43490e296668639d8ea900e5ca63aae9d1a1828da952a4a3f4d731fcf01b

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp312-cp312-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for nimbus_bci-0.4.0-cp312-cp312-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 96e756386e76d4345c08122022966d7f94ca60acf531b71521f747ecd1071af0
MD5 d1f21a4a1802982167086d23bd650787
BLAKE2b-256 7bfe927b8f7fb1d2c2f7496fdd6a46651daf09e193e037a630a3a6fbbde3811d

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp311-cp311-win_amd64.whl.

File metadata

  • Download URL: nimbus_bci-0.4.0-cp311-cp311-win_amd64.whl
  • Upload date:
  • Size: 497.6 kB
  • Tags: CPython 3.11, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for nimbus_bci-0.4.0-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 e55411d8ee67c282be0a176a0f01aa28bdac1ceae264bf9e6de0f13b2d5df30e
MD5 01eb93921ea233a18fc3faeaaea46e2b
BLAKE2b-256 d3748a9a59c7d4c6423fbd88a9f43d7f24330d25cc00c87cd952503c6103a4c2

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for nimbus_bci-0.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 61fa2297e2edba6c9a734b9e4aed1ec48b7220a27e17c9f36ea28191cf3769d6
MD5 00608767c5ec5620737ba9b60e0d7ffc
BLAKE2b-256 f437d61d9aa32b1b40f214552515cf3beae83e628c74dca581bfed84cb59cc8f

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for nimbus_bci-0.4.0-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 c6599ad111cece23d89b697118f68fda239e1a5177f56f870b8de44af6b9e6f8
MD5 e2ab9b9c525beaf6e11bdf3558743fa8
BLAKE2b-256 d315a1eec11e0229660cff12bdedf868c04053ab1df7aa94036f31e5eadc8fe2

See more details on using hashes here.

File details

Details for the file nimbus_bci-0.4.0-cp311-cp311-macosx_10_9_x86_64.whl.

File metadata

File hashes

Hashes for nimbus_bci-0.4.0-cp311-cp311-macosx_10_9_x86_64.whl
Algorithm Hash digest
SHA256 2bb2a6df4c34e17f27eec455d6813239443d4fe45e16772d6357061962f62084
MD5 67b2ebf7426aa6b044c7a26904fc0d69
BLAKE2b-256 20e19042915d0f4ad4e9d288d6d543696f30ef988d659f1929995d734d9e2087

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