PyBCI

PyBCI: A Python Package for Brain-Computer Interface (BCI) Design - Published in JOSS (2023)

https://github.com/lmbooth/pybci

Science Score: 100.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
    Found 2 DOI reference(s) in README and JOSS metadata
  • Academic publication links
    Links to: joss.theoj.org
  • Committers with academic emails
    1 of 2 committers (50.0%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
    Published in Journal of Open Source Software

Keywords

bci brain-computer-interface hmi human-computer-interaction human-machine-interface labstreaminglayer lsl machine-learning python python-brain-computer-interface pytorch sklearn tensorflow

Scientific Fields

Mathematics Computer Science - 84% confidence
Last synced: 6 months ago · JSON representation ·

Repository

Create real-time BCI's with the LSL, PyTorch, SKLearn and TensorFlow packages.

Basic Info
Statistics
  • Stars: 25
  • Watchers: 2
  • Forks: 5
  • Open Issues: 0
  • Releases: 36
Topics
bci brain-computer-interface hmi human-computer-interaction human-machine-interface labstreaminglayer lsl machine-learning python python-brain-computer-interface pytorch sklearn tensorflow
Created almost 3 years ago · Last pushed 7 months ago
Metadata Files
Readme Contributing License Code of conduct Citation

README.md

Downloads PyPI - Downloads PyPI - version Documentation Status AppVeyor Build codecov status

pybci

A Python package to create real-time Brain Computer Interfaces (BCI's). Data synchronisation and pipelining handled by the Lab Streaming Layer, machine learning with Pytorch, scikit-learn or TensorFlow, leveraging packages like AntroPy, SciPy and NumPy for generic time and/or frequency based feature extraction or optionally have the users own custom feature extraction class used.

The goal of PyBCI is to enable quick iteration when creating pipelines for testing human machine and brain computer interfaces, namely testing applied data processing and feature extraction techniques on custom machine learning models. Training the BCI requires LSL enabled devices and an LSL marker stream for timing stimuli.

All the examples found on the github not in a dedicated folder have a pseudo LSL data generator enabled by default, createPseudoDevice=True so the examples can run without the need of LSL capable hardware. Any generic LSLViewer can be used to view the generated data, example viewers found on this link.

If samples have been collected previously and model made the user can set the clf, model, or torchModel to their sklearn, tensorflow or pytorch classifier and immediately set bci.TestMode().

Official paper here!

ReadTheDocs available here!

Examples found here!

Examples of supported LSL hardware here!

TODO:

  • Add optional LSL outlet configuration for class estimator (either send every classification or send on classification change - help with reducing spam on classification if estimator time is very short)
  • Add example showing previously saved models.
  • Add example showing how feature data can be saved and used to build models so model creation can be done offline whilst data collection and classification can be done online.
  • Update and verify via appveyor for 3.13 when appveyor provides full support (finally fixed 3.12 so 3.13 will hopefully be easier, famous last words).

Installation

For stable releases use: pip install pybci-package

For development versions use: pip install git+https://github.com/LMBooth/pybci.git or git clone https://github.com/LMBooth/pybci.git cd pybci pip install -e .

Optional: Virtual Environment

Or optionally, install and run in a virtual environment:

Windows: ``` python -m venv myenv .\myenv\Scripts\Activate pip install pybci-package # For stable releases

OR

pip install git+https://github.com/LMBooth/pybci.git # For development version Linux/MaxOS: python3 -m venv myenv source myenv/bin/activate pip install pybci-package # For stable releases

OR

pip install git+https://github.com/LMBooth/pybci.git # For development version ```

Prerequisite for Non-Windows Users

If you are not using windows then there is a prerequisite stipulated on the pylsl repository to obtain a liblsl shared library. See the liblsl repo documentation for more information. Once the liblsl library has been downloaded pip install pybci-package should work.

(currently using pybci-package due to pybci having name too similar with another package on pypi, issue here.)

There has been issues raised with Linux successfully running all pytests and examples, there is a dockerfile included in the root repository outlining what should be a successful build of ubuntu 22:04.

Dockerfile

There is an Ubuntu 22.04 setup found in the Dockerfile in the root of the directory which can be used in conjunction with docker.

Once docker is installed call the following in the root directory: sudo docker build -t pybci . sudo docker run -it -p 4000:8080 pybci Then either run the pybci CLI command or run pytest Tests to verify functionality.

Download the Dockerfile and run

Running Pytest Locally

After installing pybci and downloading and extracting the pybci git repository, navigate to the extracted location and run pip install requirements-devel.txt to install pytest, then call pytest -vv -s Tests\ to run all the automated tests and ensure all 10 tests pass (should take approximately 15 mins to complete), this will ensure pybci functionality is as desired.

Python Package Dependencies Version Minimums

Tested on Python 3.9, 3.10, 3.11 & 3.12 (appveyor.yml)

The following package versions define the minimum supported by PyBCI, also defined in setup.py:

"pylsl>=1.16.1",
"scipy>=1.11.1",
"numpy>=1.24.3",
"antropy>=0.1.6",
"tensorflow>=2.13.0",
"scikit-learn>=1.3.0",
"torch>=2.0.1"

Earlier packages may work but are not guaranteed to be supported.

Basic implementation

python import time from pybci import PyBCI if __name__ == '__main__': bci = PyBCI(createPseudoDevice=True) # set default epoch timing, looks for first available lsl marker stream and all data streams while not bci.connected: # check to see if lsl marker and datastream are available bci.Connect() time.sleep(1) bci.TrainMode() # now both marker and datastreams available start training on received epochs accuracy = 0 try: while(True): currentMarkers = bci.ReceivedMarkerCount() # check to see how many received epochs, if markers sent to close together will be ignored till done processing time.sleep(0.5) # wait for marker updates print("Markers received: " + str(currentMarkers) +" Accuracy: " + str(round(accuracy,2)), end=" \r") if len(currentMarkers) > 1: # check there is more then one marker type received if min([currentMarkers[key][1] for key in currentMarkers]) > bci.minimumEpochsRequired: classInfo = bci.CurrentClassifierInfo() # hangs if called too early accuracy = classInfo["accuracy"] if min([currentMarkers[key][1] for key in currentMarkers]) > bci.minimumEpochsRequired+10: bci.TestMode() break while True: markerGuess = bci.CurrentClassifierMarkerGuess() # when in test mode only y_pred returned guess = [key for key, value in currentMarkers.items() if value[0] == markerGuess] print("Current marker estimation: " + str(guess), end=" \r") time.sleep(0.2) except KeyboardInterrupt: # allow user to break while loop print("\nLoop interrupted by user.")

Background Information

PyBCI is a python brain computer interface software designed to receive a varying number, be it singular or multiple, Lab Streaming Layer enabled data streams. An understanding of time-series data analysis, the lab streaming layer protocol, and machine learning techniques are a must to integrate innovative ideas with this interface.

An LSL marker stream is required to train the model, where a received marker epochs the data received on the accepted datastreams based on a configurable time window around set markers - where custom marker strings can optionally have their epoch time-window split and overlapped to count as more then one marker, example: in training mode a baseline marker may have one marker sent for a 60 second window, whereas target actions may only be ~0.5s long, when testing the model and data is constantly analysed it would be desirable to standardise the window length, we do this by splitting the 60s window after the received baseline marker in to ~0.5s windows. PyBCI allows optional overlapping of time windows to try to account for potential missed signal patterns/aliasing - as a rule of thumb it would be advised when testing a model to have a time window overlap >= 50% (Shannon-Nyquist criterion). See here for more information on epoch timing.

Once the data has been epoched it is sent for feature extraction, there is a general feature extraction class which can be configured for general time and/or frequency analysis based features, ideal for data stream types like "EEG" and "EMG". Since data analysis, preprocessing and feature extraction trechniques can vary greatly between device data inputs, a custom feature extraction class can be created for each data stream maker type. See here for more information on feature extraction.

Finally a passable pytorch, sklearn or tensorflow classifier can be given to the bci class, once a defined number of epochs have been obtained for each received epoch/marker type the classifier can begin to fit the model. It's advised to use bci.ReceivedMarkerCount() to get the number of received training epochs received, once the min num epochs received of each type is >= pybci.minimumEpochsRequired (default 10 of each epoch) the model will begin to fit. Once fit the classifier info can be queried with CurrentClassifierInfo, this returns the model used and accuracy. If enough epochs are received or high enough accuracy is obtained TestMode() can be called. Once in test mode you can query what pybci estimates the current bci epoch is(typically baseline is used for no state). Review the examples for sklearn and model implementations.

All issues, recommendations, pull-requests and suggestions are welcome and encouraged!

Owner

  • Name: LMBooth
  • Login: LMBooth
  • Kind: user
  • Location: Hull, United Kingdom
  • Company: University of Hull

JOSS Publication

PyBCI: A Python Package for Brain-Computer Interface (BCI) Design
Published
December 02, 2023
Volume 8, Issue 92, Page 5706
Authors
Liam Booth ORCID
Faculty of Science and Engineering, University of Hull, United Kingdom.
Aziz Asghar ORCID
Centre for Anatomical and Human Sciences, Hull York Medical School, University of Hull, United Kingdom.
Anthony Bateson ORCID
Faculty of Science and Engineering, University of Hull, United Kingdom.
Editor
Elizabeth DuPre ORCID
Tags
brain-computer-interface python bci lsl labstreaminglayer machinelearning

Citation (CITATION.cff)

cff-version: "1.2.0"
authors:
- family-names: Booth
  given-names: Liam
  orcid: "https://orcid.org/0000-0002-8749-9726"
- family-names: Asghar
  given-names: Aziz
  orcid: "https://orcid.org/0000-0002-3735-4449"
- family-names: Bateson
  given-names: Anthony
  orcid: "https://orcid.org/0000-0002-4780-4458"
doi: 10.5281/zenodo.10245437
message: If you use this software, please cite our article in the
  Journal of Open Source Software.
preferred-citation:
  authors:
  - family-names: Booth
    given-names: Liam
    orcid: "https://orcid.org/0000-0002-8749-9726"
  - family-names: Asghar
    given-names: Aziz
    orcid: "https://orcid.org/0000-0002-3735-4449"
  - family-names: Bateson
    given-names: Anthony
    orcid: "https://orcid.org/0000-0002-4780-4458"
  date-published: 2023-12-02
  doi: 10.21105/joss.05706
  issn: 2475-9066
  issue: 92
  journal: Journal of Open Source Software
  publisher:
    name: Open Journals
  start: 5706
  title: "PyBCI: A Python Package for Brain-Computer Interface (BCI)
    Design"
  type: article
  url: "https://joss.theoj.org/papers/10.21105/joss.05706"
  volume: 8
title: "PyBCI: A Python Package for Brain-Computer Interface (BCI)
  Design"

GitHub Events

Total
  • Release event: 3
  • Watch event: 4
  • Delete event: 2
  • Push event: 35
  • Fork event: 1
  • Create event: 3
Last Year
  • Release event: 3
  • Watch event: 4
  • Delete event: 2
  • Push event: 35
  • Fork event: 1
  • Create event: 3

Committers

Last synced: 7 months ago

All Time
  • Total Commits: 1,346
  • Total Committers: 2
  • Avg Commits per committer: 673.0
  • Development Distribution Score (DDS): 0.004
Past Year
  • Commits: 43
  • Committers: 1
  • Avg Commits per committer: 43.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
LMBooth 3****h 1,341
Stephan Heunis s****s@f****e 5
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 24
  • Total pull requests: 2
  • Average time to close issues: 15 days
  • Average time to close pull requests: 13 minutes
  • Total issue authors: 2
  • Total pull request authors: 1
  • Average comments per issue: 3.25
  • Average comments per pull request: 0.0
  • Merged pull requests: 2
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 0
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 0
  • Pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • jsheunis (19)
  • anilbey (5)
Pull Request Authors
  • jsheunis (2)
Top Labels
Issue Labels
mac (1)
Pull Request Labels

Packages

  • Total packages: 2
  • Total downloads:
    • pypi 118 last-month
  • Total dependent packages: 0
    (may contain duplicates)
  • Total dependent repositories: 0
    (may contain duplicates)
  • Total versions: 42
  • Total maintainers: 1
pypi.org: pybci-package

A Python interface to create a BCI with the Lab Streaming Layer, Pytorch, SciKit-Learn and Tensorflow packages

  • Versions: 21
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 34 Last month
Rankings
Dependent packages count: 7.4%
Downloads: 14.4%
Stargazers count: 18.5%
Average: 27.8%
Forks count: 30.0%
Dependent repos count: 68.9%
Maintainers (1)
Last synced: 6 months ago
pypi.org: install-pybci

A Python interface to create a BCI with the Lab Streaming Layer, Pytorch, SciKit-Learn and Tensorflow packages

  • Versions: 21
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 84 Last month
Rankings
Dependent packages count: 7.3%
Average: 29.5%
Forks count: 30.5%
Stargazers count: 39.4%
Dependent repos count: 40.9%
Maintainers (1)
Last synced: about 1 year ago

Dependencies

.github/workflows/python-publish.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v3 composite
docs/requirements.txt pypi
  • antropy *
  • numpy *
  • pylsl *
  • scikit-learn *
  • scipy *
  • tensorflow *
setup.py pypi
  • antropy *
  • numpy *
  • pylsl *
  • scikit-learn *
  • scipy *
  • tensorflow *
  • torch *
.github/workflows/ci.yml actions
  • actions/checkout v2 composite
  • actions/setup-python v2 composite
  • codecov/codecov-action v2 composite
Dockerfile docker
  • ubuntu 22.04 build
pyproject.toml pypi
requirements-devel.txt pypi
  • pytest >=7.4.3 development