Usage#
This guide shows how to connect to a BrainAccess headset and acquire EEG data. The high-level
EEG helper is the recommended starting point; Using the core API covers the
low-level interface.
Quickstart: data acquisition with EEG#
The EEG class connects to a headset, collects the streamed data and converts it into an
MNE-Python mne.io.Raw object.
The typical workflow is:
Create the EEG object:
eeg = EEG().Open a manager and set up the headset: inside
with EEGManager() as mgr:, calleeg.setup(mgr, ...)to scan for the headset, connect, and configure channels.Start acquisition: call
start_acquisition()to begin streaming.Stop acquisition: call
stop_acquisition(). The last partial chunk of data arrives while the stream stops, so stop before reading the data.Retrieve the data: call
get_mne()to get the recording as an MNERawobject, and save or analyze it. Save it withraw.save(...).Close: after the
withblock, calleeg.close()to release the BrainAccess library.
Continuous data acquisition with MNE#
This example streams data and saves it as an MNE recording for further analysis.
"""Record EEG and save it as an MNE file.
Connects to a headset with the ``brainaccess.utils.acquisition.EEG`` helper,
records for about 15 seconds while sending one annotation per second, saves the
recording in MNE's FIF format and plots it after a 1-40 Hz band-pass filter.
Set the ``BA_DEVICE`` environment variable to the name printed on your headset
(for example ``BA_DEVICE="BA HALO 001"``), or edit ``device_name`` below.
"""
import os
import time
import matplotlib.pyplot as plt
from brainaccess.core.eeg_manager import EEGManager
from brainaccess.utils import acquisition
# Electrodes to record: keys are 0-based electrode indices on the headset,
# values are the names of the channels in the recording.
cap: dict = {
0: "Fp1",
1: "Fp2",
2: "O1",
3: "O2",
}
device_name = os.environ.get("BA_DEVICE", "BA HALO 001") # name printed on your headset
eeg = acquisition.EEG()
with EEGManager() as mgr:
eeg.setup(mgr, device_name=device_name, cap=cap, sfreq=250)
eeg.start_acquisition()
print("Acquisition started")
time.sleep(3) # let the signal settle before the first annotation
# Send one annotation per second for 10 seconds.
start_time = time.time()
annotation = 1
while time.time() - start_time < 10:
time.sleep(1)
print(f"Sending annotation {annotation} to the device")
eeg.annotate(str(annotation))
annotation += 1
time.sleep(2) # keep recording a little after the last annotation
# Stop first, so that the recording contains every received sample.
eeg.stop_acquisition()
raw = eeg.get_mne()
mgr.disconnect()
# Save the recording in MNE's FIF format.
raw.save(f"{time.strftime('%Y%m%d_%H%M')}-raw.fif", overwrite=True)
# Release the BrainAccess library.
eeg.close()
# Show the recording, band-pass filtered between 1 and 40 Hz.
raw.copy().filter(1, 40).plot(scalings="auto", verbose=False)
plt.show()
The EEG class#
EEG(mode="accumulate")Creates the acquisition object.
mode="accumulate"keeps all data;mode="roll"keeps only the most recent window.setup(mgr, device_name, cap=None, zeros_at_start=0, bias=None, gain=8, sfreq=250, window_seconds=10.0, digital_input=False)Scans for the headset, connects and configures the channels.
cap: mapping of electrode index (0-based) to channel name. Electrodes not listed are not streamed. Defaults to F3, F4, C3, C4, P3, P4, O1, O2 on headsets with at least eight electrodes, and to one channel per electrode named Ch1..ChN (without montage positions) on smaller ones such as HALO. The names need not be 10-05 labels. An emptycapstreams no electrodes but still delivers the sample number and, on headsets that have them, the accelerometer and gyroscope.zeros_at_start: number of zero samples placed in front of the data.bias: indices of the electrodes used for bias feedback. The headset forgets its bias selection whenever a stream stops, soEEGselects these electrodes again at every start.gain: electrode gain, one of 4, 6, 8 or 12. Any other value produces a warning and gain 8 is used.sfreq: sample rate in Hz; see Sample rates.window_seconds: length of the rolling window in"roll"mode.digital_input: also stream the digital input as an MNEstimchannel namedDigital. Debug feature: standard BrainAccess headsets do not provide a digital input; on them the channel is always 0. Requires headset firmware 3.8.1 or newer.
Accelerometer (m/s²) and gyroscope (deg/s) channels, on headsets that have them, are added as
miscchannels.start_acquisition()/stop_acquisition()Start and stop the EEG data stream. Starting again appends to the same recording. The data can be read while streaming; stop before the final
get_mne()so that it includes the last chunk.annotate(msg)Marks the moment of the call in the recording with the text
msg(plain text, not empty). It needs a running stream. With headset firmware 3.8.0 or newer, the annotation is placed using the headset’s own clock. With older firmware, in impedance mode, or in the first half second of a stream, the position is estimated from packet arrival times and can be slightly early.EEGManager.get_time_sync_infotells which case applies.get_annotations()Returns the annotations collected so far as a dictionary.
get_battery()Returns the headset’s battery level in percent.
get_mne(tim=None, samples=None, annotations=True)Returns the acquired data as an MNE
Rawobject, with electrode channels in volts.tim: if given, return the lasttimseconds of data.samples: if given, return the lastsamplessamples. Give at most one oftimandsamples.annotations: whether to attach the annotations.
start_impedance_measurement()/stop_impedance_measurement()Start and stop impedance measurement. While measuring,
get_mne()returns the electrode impedance in kOhm asmiscchannels; select them by the names incap. Impedance data is kept separately from EEG data and remains readable after stopping;start_acquisition()switches back to the EEG data. Each impedance row is one estimate per sweep over the cap’s electrodes (0.1 s per electrode at 250 Hz), so usesamplesrather thantimthere;get_mne(samples=1)gives the latest estimate.EEGmeasures with the 31.2 Hz test wave, so withsfreqabove 1000 Hz the impedance data is streamed at 250 Hz; see Sample rates.close()Releases the BrainAccess library. Call it after leaving the
with EEGManager()block.
See Impedance measurement for a complete example.
Impedance measurement#
"""Measure electrode impedance.
Prints the impedance of each electrode in kOhm once per second for 20 seconds,
using the ``brainaccess.utils.acquisition.EEG`` helper.
Set the ``BA_DEVICE`` environment variable to the name printed on your headset
(for example ``BA_DEVICE="BA HALO 001"``), or edit ``device_name`` below.
"""
import os
import time
from brainaccess.core.eeg_manager import EEGManager
from brainaccess.utils import acquisition
# Electrodes to measure: keys are 0-based electrode indices on the headset,
# values are the names of the channels.
cap: dict = {
0: "Fp1",
1: "Fp2",
2: "O1",
3: "O2",
}
device_name = os.environ.get("BA_DEVICE", "BA HALO 001") # name printed on your headset
eeg = acquisition.EEG()
with EEGManager() as mgr:
# A bias electrode is recommended for impedance measurement; pass its
# 0-based index, for example bias=[0].
eeg.setup(mgr, device_name=device_name, cap=cap)
eeg.start_impedance_measurement()
time.sleep(2) # wait for the first impedance values to arrive
# Print the latest impedance of every electrode once per second.
start_time = time.time()
while time.time() - start_time < 20:
time.sleep(1)
raw = eeg.get_mne(samples=1) # the newest impedance estimate
impedances_kohm = raw.get_data(picks=list(cap.values()))[:, -1]
print("Electrode impedance (kOhm):")
for name, kiloohms in zip(cap.values(), impedances_kohm):
print(f" {name}: {kiloohms:.0f}")
eeg.stop_impedance_measurement()
mgr.disconnect()
eeg.close()
Sample rates#
Supported sample rates (in Hz):
every model: 250 and 500;
HALO V3: also 1000;
EXG8: also 1000 and 2000.
A higher rate than the headset supports is rejected with a BrainAccessException
and the configured rate stays unchanged. In impedance measurement mode, the stream always runs at 250 Hz for the
7.8 Hz test wave, and for the 31.2 Hz test wave when the sample rate is above 1000 Hz. The MNE recording that
EEG returns carries the rate that was actually streamed.
Using the core API#
For fine-grained control over the headset, use brainaccess.core. The reference for every function is in the
API reference; this section explains how the pieces fit together.
Lifecycle#
A program that uses the core API follows this order:
brainaccess.core.init()starts the library.Create an
EEGManager, preferably withwith EEGManager() as mgr:so it is destroyed on leaving the block.connect()to the headset by name.Configure channels, gain, sample rate and so on.
Register a data callback with
set_callback_chunk().start_stream(), thenstop_stream()when done.After every manager is destroyed,
brainaccess.core.close().
The channel, gain, bias feedback, impedance mode and sample rate settings apply to one stream: the library resets them (all electrodes enabled, every other channel disabled, gain 8, no bias feedback, impedance mode off, 250 Hz) when a stream stops and when the headset disconnects, so apply them again before each start. The one exception is the output mode (see Test signal), which persists.
The data callback#
The function you pass to set_callback_chunk() is called as
callback(data, chunk_size). data is a list with one NumPy array per streamed channel, and chunk_size is the
number of samples in each array. Find a channel’s position in the list with
get_channel_index(), and the array types with
get_stream_channel_data_types(). The channel IDs are in
brainaccess.core.eeg_channel.
Electrode values are in µV, or in kOhm while an impedance measurement mode is active.
By default a chunk holds 25 samples; change it with
brainaccess.core.config_set_chunk_size()(1 to 100) before the stream starts.When the stream ends, the samples received since the last full chunk are delivered in one final, shorter chunk before
stop_stream()returns. Destroying a manager that is still streaming drops that chunk, so stop the stream first.The callback runs on a thread owned by the library, so protect any data it shares with your own threads, and keep it quick so that it does not delay the reception of data.
Do not call device operations such as
connect,disconnect,start_streamorstop_streamfrom inside a callback; they raise an error. Signal your main thread instead.
Sample numbers and lost samples#
Enable SAMPLE_NUMBER to receive the headset’s running sample counter, which
starts at 0 when a stream starts. Enable STREAMING to learn which rows are real:
it is 1 for a received sample and 0 for a row the library filled in because that sample was lost on the way
(for example in a radio dropout). Lost samples are filled in so that the data keeps its timing; the filled rows hold
zeros. Gaps longer than about 8 seconds are not filled.
Test signal#
set_output_mode() with
OutputMode.SQUARE_WAVE replaces the electrode data with
a square wave generated inside the headset, which is useful to check a recording pipeline. It takes effect at the next
stream start. Unlike every other stream setting, the output mode is not reset when a stream stops; set
OutputMode.NORMAL to return to real data.
Charging settings#
get_charging_settings() and
set_charging_settings() use
ChargingSettings to read and change the inactivity timeout (in minutes)
and the “stay on while charging” option.
Warning
“Stay on while charging” is for development only and not for normal use. Never record from a person while the headset is connected to a charger. It must be enabled before the charger is plugged in; otherwise the headset disconnects when charging starts. The default is off.
Bluetooth adapter selection#
On Linux, a computer with several Bluetooth adapters uses its default adapter. After
brainaccess.core.init(), call brainaccess.core.config_set_adapter_index() with n to use hci<n>
instead. Both brainaccess.core.scan() and connect() honor the
setting, and scanning first is not required before connecting. The setter only checks that n is a number from 0
to 255; a missing adapter, or an unreachable Bluetooth service, shows up as a
BrainAccessException when you scan or connect.
Windows and macOS always use the system’s default adapter and ignore this setting.
Logging#
The library writes a log to bacore.log in the current directory, starting a new file at the first line written.
Use brainaccess.core.set_config_path() to choose another file, and
brainaccess.core.config_enable_logging() to turn logging on or off. The log is the first place to look when a
connection or stream misbehaves. brainaccess.core.config_set_log_level() sets how much is logged.
Errors#
Failures raise BrainAccessException with a message that names the problem
(for example “Already connected; disconnect first” or “Bluetooth adapter not found”).
Minimal data acquisition#
A basic example of connecting, streaming, and plotting EEG data with the core API.
"""Record EEG with the low-level ``EEGManager`` API.
Scans for headsets, connects to one, streams EEG (and accelerometer data when
the headset has one) for 10 seconds into a rolling buffer, then plots the
band-pass filtered signals.
Set the ``BA_DEVICE`` environment variable to the name printed on your headset
(for example ``BA_DEVICE="BA HALO 001"``), or edit ``device_name`` below.
"""
import os
import numpy as np
import time
import threading
import matplotlib.pyplot as plt
from scipy.signal import butter, sosfiltfilt
from brainaccess import core
from brainaccess.core.eeg_manager import EEGManager
import brainaccess.core.eeg_channel as eeg_channel
from brainaccess.core.gain_mode import (
GainMode,
)
def butter_bandpass(
lowcut: float, highcut: float, fs: int, order: int = 2
) -> np.ndarray:
"""Design a bandpass Butterworth filter."""
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype="bandpass", output="sos")
return sos
def butter_bandpass_filter(
data: np.ndarray, lowcut: float, highcut: float, fs: int, order: int = 2
) -> np.ndarray:
"""Apply a bandpass Butterworth filter to the data."""
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfiltfilt(sos, data)
return y
def _acq_closure(ch_number: int = 1, buffer_length: int = 1000) -> tuple:
"""Acquisition callback closure."""
data = np.zeros((ch_number, buffer_length))
mutex = threading.Lock()
def _acq_callback(chunk: list, chunk_size: int) -> None:
nonlocal data
nonlocal mutex
with mutex:
data = np.roll(data, -chunk_size)
data[:, -chunk_size:] = chunk
def get_data() -> np.ndarray:
nonlocal data
with mutex:
return data.copy()
return _acq_callback, get_data
if __name__ == "__main__":
device_name = os.environ.get("BA_DEVICE", "BA HALO 001") # name printed on your headset
# init the core
core.init()
# scan for devices
devices = core.scan()
print("Found devices:", len(devices))
print(f"Devices: {[device.name for device in devices]}")
# connect to the device
with EEGManager() as mgr:
print("Connecting to device:", device_name)
mgr.connect(device_name) # raises BrainAccessException on failure
# battery info
print(f"battery level: {mgr.get_battery_info().level} %")
# Get electrode count
device_features = mgr.get_device_features()
eeg_channels_number = device_features.electrode_count()
print(f"Device has {eeg_channels_number} EEG channels")
# Enable every electrode and set its gain. Electrode indices are 0-based.
electrodes = list(range(eeg_channels_number))
for electrode in electrodes:
mgr.set_channel_enabled(eeg_channel.ELECTRODE_MEASUREMENT + electrode, True)
mgr.set_channel_gain(eeg_channel.ELECTRODE_MEASUREMENT + electrode, GainMode.X8)
# Use the last electrode as the bias electrode (it reduces common-mode noise).
bias_electrode = electrodes[-1]
mgr.set_channel_bias_feedback(eeg_channel.ELECTRODE_MEASUREMENT + bias_electrode)
# The accelerometer (x, y, z), if the headset has one.
has_accel = device_features.has_accel()
accel_channels = [eeg_channel.ACCELEROMETER + axis for axis in range(3)]
if has_accel:
print("Setting the accelerometer")
for channel in accel_channels:
mgr.set_channel_enabled(channel, True)
# Sample counter: lets you detect gaps in the data.
mgr.set_channel_enabled(eeg_channel.SAMPLE_NUMBER, True)
# STREAMING is 1 for a sample that was received from the headset and
# 0 for a sample that was filled in because it was lost (for example
# when the Bluetooth connection dropped).
mgr.set_channel_enabled(eeg_channel.STREAMING, True)
# Sample rate in Hz, and the buffer: the last 10 seconds of data.
sr = mgr.get_sample_frequency()
duration = 10 # seconds
buffer_samples = int(sr * duration)
# Each chunk delivered by the headset becomes columns of the buffer. The
# number of rows is the number of enabled channels.
ch_nr = eeg_channels_number + (3 if has_accel else 0) + 2
_acq_callback, get_data = _acq_closure(ch_number=ch_nr, buffer_length=buffer_samples)
mgr.set_callback_chunk(_acq_callback)
# load defined configuration
mgr.load_config()
# Row of each channel in the data chunks.
eeg_rows = [mgr.get_channel_index(eeg_channel.ELECTRODE_MEASUREMENT + e) for e in electrodes]
accel_rows = [mgr.get_channel_index(c) for c in accel_channels] if has_accel else []
sample_row = mgr.get_channel_index(eeg_channel.SAMPLE_NUMBER)
streaming_row = mgr.get_channel_index(eeg_channel.STREAMING)
# start the stream
mgr.start_stream()
print("Stream started")
# Collect a little longer than the buffer holds, so that it contains
# only received data and no leading zeros from before the stream.
time.sleep(2)
for i in range(duration):
time.sleep(1)
print(f"Collecting data {i + 1}/{duration}")
# copy the buffered samples (rows = channels, columns = samples)
dat = get_data()
# stop the stream
mgr.stop_stream()
print("Stream stopped")
# Leaving the with block calls destroy(), which also disconnects
# from the headset, so there is no need to call disconnect().
print("Disconnected from the device")
# close the core
core.close()
print("Core closed")
# plot the data
print("Plotting the data")
# EEG in microvolts: remove the offset, then band-pass filter 1-40 Hz
eeg_data = dat[eeg_rows, :]
eeg_data = eeg_data - np.mean(eeg_data, axis=1, keepdims=True)
eeg_data = butter_bandpass_filter(eeg_data, 1, 40, sr)
# Stack the channels vertically, one spread apart, so they do not overlap
spacing = 4 * np.std(eeg_data)
eeg_data = eeg_data + spacing * np.arange(len(electrodes))[:, np.newaxis]
seconds = np.arange(buffer_samples) / sr
fig, axs = plt.subplots(4, 1, figsize=(10, 10), sharex=True)
axs[0].plot(seconds, eeg_data.T)
axs[0].set_ylabel("EEG (µV, offset per channel)")
axs[0].set_xlim([1, duration]) # skip the filter's edge effects at the start
if has_accel:
axs[1].plot(seconds, dat[accel_rows, :].T)
axs[1].set_ylabel("Accelerometer (m/s²)")
else:
axs[1].axis("off") # no accelerometer on this headset
axs[2].plot(seconds, dat[sample_row, :])
axs[2].set_ylabel("Sample number")
axs[3].plot(seconds, dat[streaming_row, :])
axs[3].set_ylabel("Streaming (1 = received)")
axs[3].set_xlabel("Time (s)")
plt.show()
Running the examples#
Each example has a line like device_name = os.environ.get("BA_DEVICE", "BA HALO 001"). Either edit the name to
your headset’s name, or set the BA_DEVICE environment variable, then run the example with the installed package:
BA_DEVICE="BA MINI 053" python -m brainaccess.examples.example_minimal_eeg_acquisition
The other examples are brainaccess.examples.example_eeg_acquisition_to_mne and
brainaccess.examples.example_impedance_measurement. The MNE example writes its recording as a FIF file in the
current directory. To run without opening plot windows, also set MPLBACKEND=Agg and
MNE_BROWSER_BACKEND=matplotlib.
Module reference#
For detailed information on all classes and functions, see the API reference.