Source code for brainaccess.utils.acquisition

import typing
import time
import threading
import warnings
import numpy as np
import mne  # type: ignore

import brainaccess.core as bacore
import brainaccess.core.eeg_channel as eeg_channel
from brainaccess.core.gain_mode import GainMode, multiplier_to_gain_mode
from brainaccess.core.eeg_manager import EEGManager
from brainaccess.core.impedance_measurement_mode import ImpedanceMeasurementMode
from brainaccess.core.device_features import DeviceFeatures
from brainaccess.utils.exceptions import BrainAccessException


_MICROVOLTS_TO_VOLTS = 1e-6
# MNE 1.13 renamed the 10-05 montage to "colin27_1005" (same positions) and
# drops "standard_1005" in 1.14; older MNE only knows the old name.
_MONTAGE_1005 = (
    "colin27_1005"
    if "colin27_1005" in mne.channels.get_builtin_montages()
    else "standard_1005"
)


def _select_window(full, tim, samples, sfreq):
    """Return the trailing window of ``full`` selected by ``tim`` seconds or
    ``samples`` samples; the whole array when neither is given."""
    if tim is not None and samples is not None:
        raise BrainAccessException("Pass either tim or samples, not both")
    if tim is not None:
        if tim <= 0:
            raise BrainAccessException("tim must be positive")
        samples = max(1, int(tim * sfreq))
    if samples is None:
        return full
    if samples <= 0:
        raise BrainAccessException("samples must be positive")
    return full[:, -samples:]


def _scale_measurements_to_volts(data, ch_types):
    """Return a copy of ``data`` with microvolt measurement rows scaled to volts.

    The device streams electrode samples in microvolts; MNE expects volts. Only
    ``eeg`` rows are scaled by 1e-6; every other row (IMU, digital, sample
    counter) is copied through unchanged. The input is never mutated, so
    converting repeatedly from the same raw storage is idempotent and never
    double-scales.

    Parameters
    ----------
    data : numpy.ndarray
        Channel-major array whose rows align with ``ch_types``.
    ch_types : sequence of str
        MNE channel type for each row, in row order.
    """
    scaled = np.array(data, dtype=float)
    mask = np.array([t == "eeg" for t in ch_types], dtype=bool)
    if mask.any():
        scaled[mask] *= _MICROVOLTS_TO_VOLTS
    return scaled


def _tag_stream(annotations, stream):
    """The core's annotation dict with every mark tagged by its stream index."""
    texts = list(annotations.get("annotations", []))
    stamps = list(annotations.get("timestamps", []))
    return {"annotations": texts, "timestamps": stamps, "streams": [stream] * len(texts)}


def _join_annotations(*parts):
    """Concatenate stream-tagged annotation dicts."""
    joined: dict = {"annotations": [], "timestamps": [], "streams": []}
    for part in parts:
        for key, values in joined.items():
            values.extend(part[key])
    return joined


def _annotation_onsets(timestamps, streams, syst_row, leading_pad, sfreq, stream_starts, first):
    """``(index, onset)`` for every mark inside the window, onsets in seconds.

    ``syst_row`` is the sample-counter channel of the returned window. Its first
    ``leading_pad`` columns are known zero padding, so column ``leading_pad``
    holds the first real sample. Counter value 0 is a legitimate sample, so
    padding is located by the explicit ``leading_pad`` count, never by treating
    a zero counter as padding.

    The device restarts its counter with every stream, so a mark is searched
    for only among the samples of its own stream: the real columns are buffer
    samples ``first`` onward, ``stream_starts`` holds the buffer sample each
    stream began at, and ``streams`` names each mark's stream (None: the whole
    window is one stream). A mark sits at the first sample of its stream whose
    counter reaches its timestamp. Marks whose stream or timestamp lies outside
    the window are left out.
    """
    counters = np.asarray(syst_row[leading_pad:])
    real = len(counters)
    placed = []
    for index, (stamp, stream) in enumerate(zip(timestamps, streams)):
        if stream is None or not stream_starts:
            low, high = 0, real
        elif stream < len(stream_starts):
            low = max(stream_starts[stream] - first, 0)
            end = stream_starts[stream + 1] if stream + 1 < len(stream_starts) else first + real
            high = min(end - first, real)
        else:
            continue
        if low >= high:
            continue
        segment = counters[low:high]
        if not segment[0] <= stamp <= segment[-1]:
            continue
        column = low + int(np.searchsorted(segment, stamp, side="left"))
        placed.append((index, (leading_pad + column) / sfreq))
    return placed


def _attach_annotations(mne_raw, annotations, syst_row, leading_pad, sfreq, stream_starts=(), first=0):
    """Attach device annotations to ``mne_raw`` with window-relative onsets.

    Onsets are derived from the selected window's sample-counter channel and the
    leading zero-padding count, so cropping and initial padding shift them
    consistently; see ``_annotation_onsets`` for how streams are kept apart.
    """
    descriptions = list(annotations.get("annotations", []))
    timestamps = list(annotations.get("timestamps", []))
    streams = list(annotations.get("streams", [None] * len(timestamps)))
    if syst_row is not None and len(descriptions) == len(timestamps) == len(streams):
        placed = _annotation_onsets(
            timestamps, streams, syst_row, leading_pad, sfreq, stream_starts, first
        )
    else:
        placed = []
    onsets = [onset for _, onset in placed]
    annot = mne.Annotations(onsets, np.zeros(len(onsets)), [descriptions[i] for i, _ in placed])
    mne_raw.set_annotations(annot, verbose=False)


[docs] class EEG: """High-level EEG acquisition. Connects to a headset through an :class:`~brainaccess.core.eeg_manager.EEGManager`, collects the stream into a buffer and returns it as an MNE ``Raw`` object. Typical use: create the object, call :meth:`setup`, :meth:`start_acquisition`, then :meth:`stop_acquisition` and :meth:`get_mne`. Save with ``raw = eeg.get_mne(); raw.save(...)``. Call the methods from one thread at a time. Creating an ``EEG`` initializes the BrainAccess Core library (see :func:`brainaccess.core.init`), not a headset; call :meth:`setup` to connect to one. Creating several ``EEG`` objects is safe. Parameters ---------- mode : str, default "accumulate" ``"accumulate"`` keeps all data from the start of the acquisition; ``"roll"`` keeps only the most recent ``window_seconds`` (see :meth:`setup`). Raises ------ BrainAccessException If ``mode`` is not ``"accumulate"`` or ``"roll"``, or the library could not be initialized. """ _MODES = ("accumulate", "roll") _DEFAULT_CAP = {0: "F3", 1: "F4", 2: "C3", 3: "C4", 4: "P3", 5: "P4", 6: "O1", 7: "O2"} def __init__( self, mode: str = "accumulate", ) -> None: """Create the acquisition object; see the class description.""" if mode not in self._MODES: raise BrainAccessException(f"mode must be one of {self._MODES}, got {mode!r}") self._wait_max: int = 2 self._time_step: float = 0.5 self._eeg_channels: dict = {} self._electrode_count: int = 0 self._bias_channels: typing.Optional[list] = None self._mode: str = mode self._gain: GainMode = GainMode.X8 self._mgr: typing.Optional[EEGManager] = None self._eeg_data: typing.Optional["typing.Union[_EEGData, _EEGDataRoll]"] = None # (buffer, stream index) of the stream whose annotations the core holds self._live_stream: typing.Optional[tuple] = None bacore.init() def _require_setup(self) -> None: if self._eeg_data is None: raise BrainAccessException("Call setup() before using the acquisition")
[docs] def setup( self, mgr: EEGManager, device_name: str, cap: typing.Optional[dict] = None, zeros_at_start: int = 0, bias: typing.Optional[list] = None, gain: int = 8, sfreq: int = 250, window_seconds: float = 10.0, digital_input: bool = False, ) -> None: """Connect to a headset and choose the channels to record. Connecting is retried for about two seconds before giving up. If anything fails after the connection is made, the manager is disconnected again so that ``setup`` can be called once more. Parameters ---------- mgr : EEGManager A new, unconnected manager. device_name : str Exact advertised name of the headset, for example ``"BA HALO 001"``. cap : dict, optional Maps 0-based electrode indices to channel names. Electrodes not listed are not recorded. By default an eight-electrode 10-20 layout is used (F3, F4, C3, C4, P3, P4, O1, O2); a headset with fewer electrodes (HALO) gets one channel per electrode named ``Ch1`` to ``ChN`` without montage positions. An empty dict records no electrodes, only the motion sensors and the sample number. zeros_at_start : int, default 0 Number of zero samples placed in front of the data in ``"accumulate"`` mode. bias : list of int, optional 0-based indices of the electrodes used for the bias (reference drive) feedback. Recommended for impedance measurement. gain : int, default 8 Amplifier gain of the electrodes: 4, 6, 8 or 12. Any other value triggers a warning and gain 8 is used. sfreq : int, default 250 Sample rate in Hz. Every headset supports 250 and 500; HALO V3 also 1000; EXG8 also 1000 and 2000. window_seconds : float, default 10.0 Length of the rolling window in seconds. Only used in ``"roll"`` mode (ignored in ``"accumulate"`` mode). digital_input : bool, default False 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. If ``True``, a channel named ``"Digital"`` (type ``stim``) is recorded. Raises ------ BrainAccessException If ``mgr`` is already connected, no headset is found, the connection fails, the headset is not supported or ``sfreq`` is not supported by the headset. """ if mgr.is_connected(): raise BrainAccessException("Already connected; disconnect first") self._mgr = mgr self._sfreq = sfreq devices = bacore.scan() if len(devices) == 0: raise BrainAccessException("No devices found; check that the headset is on and in range") self._zeros_at_start = zeros_at_start if bias: self._bias_channels = bias else: self._bias_channels = [] if gain in [4, 6, 8, 12]: self._gain = multiplier_to_gain_mode(gain) else: warnings.warn("Provided gain not supported. Using default 8", stacklevel=2) start_time = time.time() last_error: typing.Optional[Exception] = None while time.time() < (start_time + self._wait_max): try: mgr.connect(device_name) except BrainAccessException as e: last_error = e # transient BLE failure: retry until wait_max time.sleep(self._time_step) continue break else: raise BrainAccessException(f"Could not connect to device: {last_error}") try: features = DeviceFeatures(self._mgr.get_device_info()) self._electrode_count = features.electrode_count() if cap is None: cap = self._default_cap(self._electrode_count) self._eeg_channels = {} self._channels_type: dict = {} self._channels_indexes = {} for electrode, name in cap.items(): self._eeg_channels[eeg_channel.ELECTRODE_MEASUREMENT + electrode] = name self._channels_type[eeg_channel.ELECTRODE_MEASUREMENT + electrode] = "EEG" self._channels_indexes[eeg_channel.ELECTRODE_MEASUREMENT + electrode] = 0 # Accelerometer streams in m/s^2 (not voltage); it is exposed as a # `misc` channel and never amplitude-scaled. if features.has_accel(): for axis, name in enumerate(("Accel_x", "Accel_y", "Accel_z")): self._eeg_channels[eeg_channel.ACCELEROMETER + axis] = name self._channels_type[eeg_channel.ACCELEROMETER + axis] = "ACC" self._channels_indexes[eeg_channel.ACCELEROMETER + axis] = 0 # Gyroscope streams in degrees/s (not voltage); exposed as `misc` # only when the device reports gyroscope support. if features.has_gyro(): for axis, name in enumerate(("Gyro_x", "Gyro_y", "Gyro_z")): self._eeg_channels[eeg_channel.GYROSCOPE + axis] = name self._channels_type[eeg_channel.GYROSCOPE + axis] = "GYR" self._channels_indexes[eeg_channel.GYROSCOPE + axis] = 0 if digital_input: self._eeg_channels[eeg_channel.DIGITAL_INPUT] = "Digital" self._channels_type[eeg_channel.DIGITAL_INPUT] = "DIG" self._channels_indexes[eeg_channel.DIGITAL_INPUT] = 0 self._eeg_channels[eeg_channel.SAMPLE_NUMBER] = "Sample" self._channels_type[eeg_channel.SAMPLE_NUMBER] = "Sample" self._channels_indexes[eeg_channel.SAMPLE_NUMBER] = 0 # Rejects a rate the device does not support before any buffer exists. # The core resets the rate to 250 Hz at every stop, so every stream # start applies it again (_start_acquisition). self._mgr.set_sample_rate(self._sfreq) eeg_info = self._create_info() self._info = eeg_info self._window_seconds = window_seconds self._lock = threading.Lock() self._data: typing.Union[_EEGData, _EEGDataRoll] = self._create_data(eeg_info) self._eeg_data = self._data self._live_stream = None except BaseException: # Leave the manager unconnected so that setup() can be retried. try: mgr.disconnect() except BrainAccessException: pass raise
def _create_data(self, info): # `self._data`/`self._info` always refer to the active buffer: the normal # EEG buffer kept in `_eeg_data`, or a fresh one per impedance run. if self._mode == "accumulate": return _EEGData(info, lock=self._lock, zeros_at_start=self._zeros_at_start) return _EEGDataRoll(info, lock=self._lock, window_seconds=self._window_seconds) @classmethod def _default_cap(cls, electrode_count: int) -> dict: if electrode_count >= len(cls._DEFAULT_CAP): return dict(cls._DEFAULT_CAP) return {electrode: f"Ch{electrode + 1}" for electrode in range(electrode_count)} def _set_channels(self): """Enable exactly the cap's electrodes and the auxiliary channels. The core enables every electrode after connect and after each stop, so electrodes outside the cap are disabled explicitly; the buffers have one row per entry of ``eeg_channels`` and nothing else. """ for electrode in range(self._electrode_count): chan = eeg_channel.ELECTRODE_MEASUREMENT + electrode if chan not in self._eeg_channels: self._mgr.set_channel_enabled(chan, False) for chan in self._eeg_channels.keys(): self._mgr.set_channel_enabled(chan, True)
[docs] def get_battery(self) -> int: """Return the battery level. Returns ------- int Battery level in percent. Raises ------ BrainAccessException If :meth:`setup` has not been called or the level could not be read. """ self._require_setup() res = self._mgr.get_battery_info() return res.level
[docs] def close(self): """Close the BrainAccess Core library. This is a process-wide shutdown, not a per-device close. Destroy every :class:`~brainaccess.core.eeg_manager.EEGManager` first (leave its ``with`` block). It is safe to call repeatedly; creating a new ``EEG`` initializes the library again. Raises ------ BrainAccessException If an :class:`~brainaccess.core.eeg_manager.EEGManager` still exists. """ bacore.close()
def _start_acquisition(self): """Starts streaming and collecting data. The core forgets channels, bias, gains and rate at every stop, so all of them are applied again before each start. """ self._finish_stream() self._set_channels() self._mgr.set_sample_rate(self._sfreq) for chan in self._bias_channels: self._mgr.set_channel_bias_feedback(eeg_channel.ELECTRODE_MEASUREMENT + chan) for value in self._eeg_channels.keys(): if self._channels_type[value] == "EEG": self._mgr.set_channel_gain(value, self._gain) if self._mode == "accumulate": self._mgr.set_callback_chunk(self._acq) else: self._mgr.set_callback_chunk(self._acq_roll) self._mgr.load_config() self._live_stream = (self._data, self._data.begin_stream()) self._mgr.start_stream() for key in self._channels_indexes.keys(): self._channels_indexes[key] = self._mgr.get_channel_index(key) def _finish_stream(self): """Move the core's annotations to the buffer of the stream they belong to. The core keeps annotations until disconnect and stamps them with the sample counter of their stream, which restarts with every stream, so ``EEG`` holds them per stream and clears the core's list. """ if self._live_stream is not None: buffer, stream = self._live_stream buffer.kept_annotations = _join_annotations( buffer.kept_annotations, _tag_stream(self._mgr.get_annotations(), stream) ) self._live_stream = None self._mgr.clear_annotations()
[docs] def start_acquisition(self): """Start streaming EEG into the EEG buffer. Starting again after :meth:`stop_acquisition` appends to the same buffer. Raises ------ BrainAccessException If :meth:`setup` has not been called, a stream is already running or the stream could not be started. """ self._require_setup() if self._mgr.is_streaming(): raise BrainAccessException("Stream already running") self._mgr.set_impedance_mode(ImpedanceMeasurementMode.OFF) self._data = self._eeg_data self._info = self._data.eeg_info self._start_acquisition()
def _stop_acquisition(self): """Stops the data acquisition stream.""" self._mgr.stop_stream()
[docs] def stop_acquisition(self): """Stop the running stream. The data stays in the buffer. Call :meth:`get_mne` afterwards to include the last chunk. Raises ------ BrainAccessException If :meth:`setup` has not been called or the stream could not be stopped. """ self._require_setup() self._stop_acquisition() self._finish_stream()
[docs] def get_annotations(self) -> dict: """Return the annotations of the active buffer. Returns ------- dict Dictionary with the keys ``"annotations"`` (texts), ``"timestamps"`` (sample numbers, counted from the start of the stream in which each annotation was made) and ``"streams"`` (the index of that stream within the buffer; each restart with :meth:`start_acquisition` begins a new stream). Notes ----- ``EEG`` takes over the annotations from its manager and empties the manager's list, so do not call :meth:`~brainaccess.core.eeg_manager.EEGManager.get_annotations` on the same manager. Raises ------ BrainAccessException If :meth:`setup` has not been called. """ self._require_setup() stream = None live = self._mgr.get_annotations() if self._live_stream is not None: buffer, stream = self._live_stream if buffer is not self._data: live = {} self._data.annotations = _join_annotations( self._data.kept_annotations, _tag_stream(live, stream) ) return self._data.annotations
[docs] def annotate(self, msg: str) -> None: """Add an annotation to the running stream. Parameters ---------- msg : str Annotation text. Raises ------ BrainAccessException If :meth:`setup` has not been called, no stream is running or the annotation could not be sent. """ self._require_setup() self._mgr.annotate(msg)
[docs] def get_mne( self, tim: typing.Optional[float] = None, samples: typing.Optional[int] = None, annotations: bool = True, ) -> mne.io.BaseRaw: """Return the acquired data as an MNE ``Raw`` object. Pass at most one of ``tim`` and ``samples``; with neither, all buffered data is returned. In ``"roll"`` mode that is the whole window, padded with zeros at the start until the window has filled. The data can be read while a stream is running. After :meth:`stop_acquisition`, call it again to include the last chunk. Channel types and units: - Electrodes: ``eeg`` channels in V (during impedance measurement: ``misc`` channels in kOhm; select them by the names given in ``cap``). - Accelerometer axes in m/s² and gyroscope axes in deg/s: ``misc``. - ``"Digital"`` (if requested): ``stim``. - ``"Sample"``, the sample number: ``syst``. Impedance data is kept in its own buffer; :meth:`start_acquisition` returns to the EEG buffer. An impedance buffer holds one row per impedance estimate rather than one per sample, so ``tim`` and the time axis of the result do not measure seconds there; select estimates with ``samples`` (``samples=1`` is the latest). Parameters ---------- tim : float, optional Return only the last ``tim`` seconds of data. samples : int, optional Return only the last ``samples`` samples (impedance data: estimates). annotations : bool, default True Attach the annotations made with :meth:`annotate`. Returns ------- mne.io.BaseRaw The data as an MNE ``Raw`` object. Raises ------ BrainAccessException If :meth:`setup` has not been called, both ``tim`` and ``samples`` are given, one of them is not positive, or no data has been acquired yet. """ self._require_setup() if annotations: self.get_annotations() self._data.convert_to_mne( tim=tim, samples=samples, annotations=annotations, channels_indexes=list(self._channels_indexes.values()), ) return self._data.mne_raw
def _acq(self, chunk, chunk_size): """function to acquire data with callback Parameters ---------- chunk data chunk from device chunk_size: int size of the chunk """ self._data.append(np.array(chunk)) def _acq_roll(self, chunk, chunk_size): """function to acquire fixed size data with callback Parameters ---------- chunk data chunk from device chunk_size: int size of the chunk """ self._data.append(np.array(chunk), chunk_size) def _create_info(self, impedance=False): """Create the MNE Info in channel order. Channel types come from ``self._channels_type`` in ``eeg_channels`` insertion order, so IMU axes land in the correct slot regardless of their channel-id ranges. The sampling frequency is the rate the core reports for the next stream (``get_sample_frequency()``), so callers set the rate and impedance mode first; every stream start applies the same settings again (the core falls back to 250 Hz for the next stream after each stop), so metadata matches the stream. Accelerometer (m/s^2) and gyroscope (deg/s) axes are ``misc`` channels and are not voltage-scaled. """ sampling_freq = self._mgr.get_sample_frequency() ch_names = list(self._eeg_channels.values()) _mne_type = { "EEG": "misc" if impedance else "eeg", "ACC": "misc", "GYR": "misc", "DIG": "stim", "Sample": "syst", } ch_types = [ _mne_type.get(self._channels_type[key], "misc") for key in self._eeg_channels.keys() ] eeg_info = mne.create_info(ch_names, ch_types=ch_types, sfreq=sampling_freq) if impedance: eeg_info["description"] = "Electrode impedance estimates in kOhm (misc channels)." else: # Positions are attached for labels present in the 10-05 system; # other labels simply have no position. eeg_info.set_montage(_MONTAGE_1005, on_missing="ignore") return eeg_info
[docs] def start_impedance_measurement(self): """Start measuring electrode impedance. Impedance data goes into a fresh buffer, separate from the EEG buffer. The measurement uses a 31.2 Hz test wave, which a headset cannot measure at sample rates above 1000 Hz; with ``sfreq`` of 2000 Hz the headset streams at 250 Hz, and the impedance data carries that rate. The EEG buffer keeps ``sfreq``. Passing ``bias`` to :meth:`setup` is recommended for this measurement. :meth:`get_mne` raises until the first impedance values have arrived. See :meth:`get_mne` for how impedance data is represented. Raises ------ BrainAccessException If :meth:`setup` has not been called, a stream is already running or the stream could not be started. """ self._require_setup() self._mgr.set_impedance_mode(ImpedanceMeasurementMode.HZ_31_2) self._mgr.set_sample_rate(self._sfreq) self._info = self._create_info(impedance=True) self._data = self._create_data(self._info) self._start_acquisition()
[docs] def stop_impedance_measurement(self): """Stop the impedance measurement. The impedance data stays available through :meth:`get_mne`. Call :meth:`start_acquisition` to record EEG again. Raises ------ BrainAccessException If :meth:`setup` has not been called or the stream could not be stopped. """ self.stop_acquisition() self._mgr.set_impedance_mode(ImpedanceMeasurementMode.OFF)
class _EEGDataRoll: """Data structure to store rolling EEG data buffer""" def __init__(self, info, lock, window_seconds: float = 10.0): """Initializes the _EEGDataRoll object. Parameters ---------- info : mne.Info The MNE info object. lock : threading.Lock The threading lock shared with every buffer writer and snapshot. window_seconds : float, optional Rolling window duration in seconds (default 10). The buffer keeps the most recent ``window_seconds * sampling rate`` samples. Raises ------ BrainAccessException If no lock is passed. """ if not lock: raise BrainAccessException("No lock passed") self.eeg_info: mne.Info = info self.mne_raw: mne.io.BaseRaw self.chans = len(info.ch_names) self.window_seconds = window_seconds self.capacity = max(1, int(round(window_seconds * info["sfreq"]))) # Ring storage: `_head` is the next write column. `snapshot()` returns # the samples in chronological order with unfilled padding on the left. self.data = np.zeros((self.chans, self.capacity)) self._head = 0 self.filled = 0 self.annotations: dict = {} # Annotations of finished streams, and the buffer sample each stream began at self.kept_annotations: dict = _tag_stream({}, None) self.stream_starts: list = [] self.total = 0 # samples appended since creation self.lock = lock def begin_stream(self) -> int: """Record that a new stream starts at the next sample; return its index.""" with self.lock: self.stream_starts.append(self.total) return len(self.stream_starts) - 1 def append(self, chunk, chunk_size: int) -> None: """Write a chunk into the rolling buffer under the shared lock. Writes are O(chunk_size): samples go to the ring position ``_head``, wrapping at capacity; oversized chunks keep only their most recent ``capacity`` samples. Every write takes the same lock ``snapshot`` uses, so a reader never observes a half-written buffer. """ if chunk_size <= 0: return chunk = np.asarray(chunk, dtype=float)[:, :chunk_size] with self.lock: self.total += chunk_size capacity = self.data.shape[1] if chunk_size >= capacity: self.data[:] = chunk[:, -capacity:] self._head = 0 self.filled = capacity return end = self._head + chunk_size if end <= capacity: self.data[:, self._head:end] = chunk else: first = capacity - self._head self.data[:, self._head:] = chunk[:, :first] self.data[:, : end - capacity] = chunk[:, first:] self._head = end % capacity self.filled = min(self.filled + chunk_size, capacity) def snapshot(self): """Return ``(data, filled)``: a chronological copy of the window with ``capacity - filled`` zero columns of padding on the left.""" data, filled, _ = self._snapshot() return data, filled def _snapshot(self): """``snapshot()`` plus the number of samples appended so far.""" with self.lock: head = self._head data = np.concatenate((self.data[:, head:], self.data[:, :head]), axis=1) return data, self.filled, max(self.total, self.filled) def save(self, fname: str): """Saves the raw data to a file. Parameters ------------ fname: str filename to save data to """ with self.lock: self.mne_raw.save(fname=fname, verbose=False, overwrite=True, fmt="double") def load(self, fname: str): """Loads raw data from a file. Parameters ---------- fname : str The name of the file to load. """ self.mne_raw = mne.io.read_raw(fname, verbose=False) def convert_to_mne( self, tim: typing.Optional[float] = None, samples: typing.Optional[int] = None, annotations: bool = True, channels_indexes: typing.Optional[list] = None, ): """Convert arrays to MNE. If tim None returns all data from acquisition start. Otherwise last tim seconds Parameters ------------ tim: float, default value = None time in seconds or samples to cut samples: int, default value = None samples or time to cut annotations: bool, default value = True should annotations be included channels_indexes: list, optional A list of channel indexes to include. """ sfreq = self.eeg_info["sfreq"] ch_types = self.eeg_info.get_channel_types() full, filled, total = self._snapshot() n_full = full.shape[1] if filled == 0: raise BrainAccessException("No data acquired") data = _select_window(full, tim, samples, sfreq) dropped = n_full - data.shape[1] # select right order channels if channels_indexes: data = data[channels_indexes] syst_row = ( np.asarray(data[ch_types.index("syst")]) if "syst" in ch_types else None ) data = _scale_measurements_to_volts(data, ch_types) self.mne_raw = mne.io.RawArray(data, self.eeg_info, verbose=False) if annotations: # The buffer starts full of zeros and fills from the right, so # (capacity - filled) leading columns are padding; cropping removes # `dropped` of them from the front. leading_pad = max(0, (n_full - filled) - dropped) first = total - (data.shape[1] - leading_pad) _attach_annotations( self.mne_raw, self.annotations, syst_row, leading_pad, sfreq, list(self.stream_starts), first, ) class _EEGData: """Object to store EEG data in accumulation mode""" def __init__(self, info, lock, zeros_at_start: int = 2): """Initializes the EEGData object. Parameters ---------- info : mne.Info The MNE info object. lock : threading.Lock The threading lock. zeros_at_start : int, optional The number of zeros to add at the beginning of the data, by default 2. """ self.eeg_info: mne.Info = info self.mne_raw: mne.io.BaseRaw self.lock = lock chans = len(info.ch_names) self.zeros_at_start = zeros_at_start self.data: list = [np.zeros((chans, self.zeros_at_start))] self.annotations: dict = {} # Annotations of finished streams, and the buffer sample each stream began at self.kept_annotations: dict = _tag_stream({}, None) self.stream_starts: list = [] def begin_stream(self) -> int: """Record that a new stream starts at the next sample; return its index.""" with self.lock: self.stream_starts.append(sum(block.shape[1] for block in self.data) - self.zeros_at_start) return len(self.stream_starts) - 1 def append(self, chunk) -> None: """Append a data block under the shared lock so snapshots stay consistent.""" with self.lock: self.data.append(chunk) def save(self, fname: str): """Saves the raw data to a file. Parameters ------------ fname: str filename to save data to """ with self.lock: self.mne_raw.save(fname=fname, verbose=False, overwrite=True, fmt="double") def load(self, fname: str): """Loads raw data from a file. Parameters ---------- fname : str The name of the file to load. """ self.mne_raw = mne.io.read_raw(fname, verbose=False) def convert_to_mne( self, tim: typing.Optional[float] = None, samples: typing.Optional[int] = None, annotations: bool = True, channels_indexes: typing.Optional[list] = None, ): """Convert arrays to MNE. If tim None returns all data from acquisition start. Otherwise last tim seconds Parameters ------------ tim: float, default value = None time in seconds till the end to include in the output samples: int, default value = None time in samples till the end to include in the output annotations: bool, default value = True should annotations be included channels_indexes: list, optional A list of channel indexes to include. """ sfreq = self.eeg_info["sfreq"] ch_types = self.eeg_info.get_channel_types() full = self._concat_data() n_full = full.shape[1] if n_full <= self.zeros_at_start: raise BrainAccessException("No data acquired") data = _select_window(full, tim, samples, sfreq) dropped = n_full - data.shape[1] # select right order channels if channels_indexes: data = data[channels_indexes] syst_row = ( np.asarray(data[ch_types.index("syst")]) if "syst" in ch_types else None ) data = _scale_measurements_to_volts(data, ch_types) self.mne_raw = mne.io.RawArray(data, self.eeg_info, verbose=False) if annotations: # The first `zeros_at_start` columns are prepended padding; cropping # removes `dropped` of them from the front. leading_pad = max(0, self.zeros_at_start - dropped) first = (n_full - self.zeros_at_start) - (data.shape[1] - leading_pad) _attach_annotations( self.mne_raw, self.annotations, syst_row, leading_pad, sfreq, list(self.stream_starts), first, ) def _concat_data(self): """Concatenates the data blocks.""" with self.lock: data = np.block(self.data) return data