### start() Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/player.md Starts streaming data via LSL outlets, making them discoverable on the LSL network. This method creates StreamOutlet instances and starts a background streaming thread. ```APIDOC ## start() ### Description Starts streaming data via LSL outlets, making them discoverable on the LSL network. This method creates StreamOutlet instances and starts a background streaming thread. ### Method `start()` ### Returns - **PlayerLSL**: Self for method chaining ### Raises - **RuntimeError**: If already streaming ### Example ```python player = PlayerLSL("data.fif") player.start() # Streams now available on LSL network ``` ``` -------------------------------- ### Install MNE-LSL from GitHub Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/index.rst Install the mne-lsl package directly from GitHub. This method will build liblsl during installation. ```console $ pip install git+https://github.com/mne-tools/mne-lsl ``` -------------------------------- ### Start Streaming with PlayerLSL Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/player.md Initiate data streaming from the PlayerLSL instance. This makes the LSL outlets discoverable on the network. Ensure the player is instantiated before calling start. ```python player = PlayerLSL("data.fif") player.start() # Streams now available on LSL network ``` -------------------------------- ### Initialize and Start PlayerLSL with Annotations Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/player.md Initialize PlayerLSL to stream data from a .fif file along with annotations. The player must be started to begin streaming. ```python player = PlayerLSL("data_with_events.fif", annotations=True) player.start() ``` -------------------------------- ### Install Linux dependencies for liblsl and LabRecorder Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/install.rst Install necessary system dependencies on Linux for liblsl (libpugixml-dev) and LabRecorder (qt6-base-dev, freeglut3-dev). ```console $ sudo apt install -y libpugixml-dev qt6-base-dev freeglut3-dev ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Install the pre-commit framework hooks to enforce code style rules automatically before each commit. This ensures consistency across the project. ```console $ pre-commit install ``` -------------------------------- ### Debug Session Setup with File Logging Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/utils.md Enable detailed logging for debugging sessions by setting the log level to 'DEBUG' and adding a file handler to capture all logs. This setup is useful for troubleshooting operations. ```python from mne_lsl.utils import set_log_level, add_file_handler # Enable detailed logging set_log_level("DEBUG") add_file_handler("debug.log", verbose="DEBUG") # Now all operations produce detailed logs from mne_lsl.stream import StreamLSL stream = StreamLSL(bufsize=5.0) stream.connect() # All debug info logged to debug.log ``` -------------------------------- ### Install MNE-LSL using pip Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/index.rst Install the mne-lsl package from PyPI using pip. This is a common method for Python package installation. ```console $ pip install mne-lsl ``` -------------------------------- ### Get System Information Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Use this function to display detailed system and package information relevant to MNE-LSL. It's useful for debugging and verifying installations. ```python from mne_lsl.utils import sys_info sys_info(extra=True) ``` -------------------------------- ### Install MNE-LSL from GitHub skipping liblsl build Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/index.rst Install the mne-lsl package from GitHub while skipping the liblsl build. This requires specifying the liblsl path using environment variables. ```console $ MNE_LSL_SKIP_LIBLSL_BUILD=1 pip install git+https://github.com/mne-tools/mne-lsl ``` -------------------------------- ### Get Sample Dataset Path Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Retrieves the path to the sample dataset directory. This function is part of the sample module. ```python data_path() -> Path ``` -------------------------------- ### Start Mock Data Stream with PlayerLSL Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Initiates a mock LSL stream using PlayerLSL for testing purposes. Specify the data file, chunk size, and number of repetitions. ```python from mne_lsl.player import PlayerLSL from mne_lsl.stream import StreamLSL # Start mock stream player = PlayerLSL("test_data.fif", chunk_size=100, n_repeat=3) player.start() ``` -------------------------------- ### Install MNE-LSL in Editable Mode Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Install MNE-LSL in editable mode to test your changes without frequent reinstallation. This command also builds liblsl using CMake. ```console $ uv sync ``` -------------------------------- ### Build Documentation Skipping Plotting Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Build the HTML documentation while skipping the execution of examples and tutorials that generate plots. This speeds up the documentation build process. ```console $ make html-noplot ``` -------------------------------- ### Get Sample Dataset Path Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/datasets.md Returns the path to the sample dataset. Downloads the data if it's not already present. Subsequent calls use the cached path. The download location can be customized via the MNE_DATA environment variable. ```python from mne_lsl.datasets import sample data_dir = sample.data_path() print(f"Sample data location: {data_dir}") # List files in sample dataset import os files = os.listdir(data_dir) ``` -------------------------------- ### StreamInlet.pull_sample Example Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/lsl.md Pulls a single sample from the inlet with an optional timeout. Returns the sample data and its acquisition timestamp. ```python sample, timestamp = inlet.pull_sample(timeout=1.0) if timestamp is not None: print(f"Sample at time: {timestamp}") ``` -------------------------------- ### datasets.sample.data_path Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Get the directory path for the sample dataset. This function is used to locate and access sample data included with the MNE-LSL library. ```APIDOC ## Function data_path ### Description Get sample dataset directory. ### Signature ```python data_path() -> Path ``` ### Returns Path - The path to the sample dataset directory. ``` -------------------------------- ### NumPy Type Hinting for Data Processing Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/types.md Provides examples of using modern NumPy type hints for function signatures, improving code clarity and enabling static analysis for numerical arrays. ```python from numpy.typing import NDArray import numpy as np def filter_data(data: NDArray[np.float64]) -> NDArray[np.float64]: """Process float64 array.""" return data * 2 def select_channels( data: NDArray[np.float32], indices: NDArray[np.intp] ) -> NDArray[np.float32]: """Select channels by index.""" return data[:, indices] ``` -------------------------------- ### View Built Documentation Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Open a web browser with the locally built documentation. This command is run from the 'doc' directory. ```console $ make view ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Build the HTML documentation pages locally by navigating to the 'doc' directory and running the 'make html' command. The output will be in 'doc/_build/html'. ```console $ make html ``` -------------------------------- ### Install MNE-LSL using conda Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/index.rst Install the mne-lsl package from conda-forge using conda. This method is suitable for users who manage their environments with Conda. ```console $ conda install -c conda-forge mne-lsl ``` -------------------------------- ### Instantiate PlayerLSL from File or Raw Object Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/player.md Create a PlayerLSL instance either from a file path (fif, edf, etc.) or an MNE Raw object. Configure chunk size and repetition count for playback. The player replays the data, looping infinitely by default, and timestamps each chunk's last sample as the current time. ```python from mne_lsl.player import PlayerLSL # From file player = PlayerLSL("sample_data.fif", chunk_size=100, n_repeat=3) player.start() # From MNE Raw object from mne import io raw = io.read_raw_fif("sample_data.fif", preload=True) player = PlayerLSL(raw, chunk_size=100) player.start() ``` -------------------------------- ### Load Sample Data for Development Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/datasets.md Demonstrates how to load sample data for development purposes. It retrieves the sample data path and then reads a sample FIF file using mne.io.read_raw_fif. ```python from mne_lsl.datasets import sample from mne import io data_path = sample.data_path() raw = io.read_raw_fif(str(data_path / "sample_file.fif")) ``` -------------------------------- ### Instantiate and Connect EpochsStream Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/stream.md Demonstrates how to instantiate and connect an `EpochsStream` object. This involves creating a `StreamLSL` instance, connecting it, and then initializing `EpochsStream` with the stream and event parameters. ```python from mne_lsl.stream import StreamLSL, EpochsStream stream = StreamLSL(bufsize=10.0, stype="EEG") stream.connect() epochs = EpochsStream( stream, bufsize=100, event_channels="stim", event_id={1: "stim", 2: "response"}, tmin=-0.1, tmax=0.5 ) epochs.connect() # Get extracted epochs epoch_data = epochs.get_epochs() ``` -------------------------------- ### Configure Stream Connection Parameters Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/README.md Demonstrates how to configure stream connection parameters like acquisition delay, processing flags, and discovery timeout. These parameters are passed to the connect method. ```python stream.connect( acquisition_delay=0.001, # 1ms pull interval processing_flags=["clocksync"], # Post-processing timeout=2.0 # Stream discovery ) ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst If you have already cloned the repository without submodules, use this command to initialize and update them. This is necessary for building liblsl. ```console $ git submodule update --init --recursive ``` -------------------------------- ### Get Channel Information Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Retrieve channel information from a stream using `StreamInfo.get_channel_info()`. Located in lsl.stream_info. ```python StreamInfo.get_channel_info() ``` -------------------------------- ### StreamInfo.get_channel_info Example Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/lsl.md Retrieves the FIFF measurement Info object from the channel description of a StreamInfo object. ```python sinfo.get_channel_info() ``` -------------------------------- ### Download Sample and Testing Datasets Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Download sample and testing datasets using MNE-LSL's dataset functions. Loads a sample FIF file using MNE IO. ```python from mne_lsl.datasets import sample, testing from mne import io # Download and get path sample_path = sample.data_path() test_path = testing.data_path() # Load data raw = io.read_raw_fif(str(sample_path / "sample_file.fif")) ``` -------------------------------- ### Initialize PlayerLSL Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/configuration.md Instantiate PlayerLSL to play back data from a file or MNE Raw object. Configure chunk size, repeat count, and LSL stream properties. ```python player = PlayerLSL(fname="my_data.fif", chunk_size=100, n_repeat=1, name="MNE-LSL-Player", source_id="MNE-LSL", annotations=True) ``` -------------------------------- ### datasets.testing.data_path Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Get the directory path for the testing dataset. This function is used to locate and access testing data included with the MNE-LSL library. ```APIDOC ## Function data_path ### Description Get test dataset directory. ### Signature ```python data_path() -> Path ``` ### Returns Path - The path to the test dataset directory. ``` -------------------------------- ### Import MNE-LSL Submodules and Utilities Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Demonstrates how to import the main submodules and a top-level utility function from the MNE-LSL package. ```python from mne_lsl import ( datasets, lsl, player, stream, utils ) ``` ```python from mne_lsl import sys_info ``` -------------------------------- ### Import Sample and Testing Datasets Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Imports the sample and testing submodules from the datasets module. ```python from mne_lsl.datasets import sample, testing ``` -------------------------------- ### mne_lsl.lsl Functions Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Provides functions for interacting with the liblsl library, including getting version information, system time, and resolving streams. ```APIDOC ## mne_lsl.lsl Functions ### Description Provides functions for interacting with the liblsl library, including getting version information, system time, and resolving streams. ### Functions - **`library_version()`** - Returns: `int` - Get liblsl binary version. - **`protocol_version()`** - Returns: `int` - Get LSL protocol version. - **`local_clock()`** - Returns: `float` - Get system timestamp (seconds). - **`resolve_streams(timeout, name, stype, source_id, minimum)`** - Parameters: - `timeout` (any) - Timeout for stream resolution. - `name` (any) - Filter by stream name. - `stype` (any) - Filter by stream type. - `source_id` (any) - Filter by source ID. - `minimum` (any) - Minimum number of streams to find. - Returns: `list[StreamInfo]` - Discovered LSL streams on the network. ``` -------------------------------- ### Get LSL Library Version Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/lsl.md Retrieves the version of the binary LSL library. The major and minor versions can be calculated from the returned integer. ```python from mne_lsl.lsl import library_version version = library_version() major = version // 100 minor = version % 100 print(f"LSL version: {major}.{minor}") ``` -------------------------------- ### Configure Signal Filtering Parameters Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/README.md Shows how to apply bandpass and notch filters using the filter and notch_filter methods. Specify frequency ranges for bandpass and specific frequencies for notch filters. ```python stream.filter(l_freq=0.5, h_freq=40.0) # Bandpass stream.notch_filter(freqs=[50, 100]) # Notch ``` -------------------------------- ### Initialize and Connect StreamLSL Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/configuration.md Instantiate StreamLSL with buffer size and optional stream filters, then connect to an LSL stream with specified acquisition delay, processing flags, and timeout. ```python stream = StreamLSL(bufsize=10.0, stype="EEG") stream.connect( acquisition_delay=0.005, processing_flags=["clocksync", "dejitter"], timeout=5.0 ) ``` -------------------------------- ### Get Local System Clock Time Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/lsl.md Obtains a local system timestamp in seconds. This function provides a high-resolution time reference from the local machine. ```python from mne_lsl.lsl import local_clock current_time = local_clock() print(f"Current time: {current_time}") ``` -------------------------------- ### Create and Access MNE Info Object Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/types.md Demonstrates how to create an MNE Info object and access its channel names and sampling rate, typically obtained from an LSL stream. ```python from mne import create_info from mne_lsl.stream import StreamLSL stream = StreamLSL(bufsize=10.0) stream.connect() info = stream.info print(f"Channels: {info['ch_names']}") print(f"Sampling rate: {info['sfreq']}") ``` -------------------------------- ### Get LSL Protocol Version Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/lsl.md Retrieves the version of the LSL protocol. Protocol compatibility is determined by major version, while minor versions are generally compatible. ```python from mne_lsl.lsl import protocol_version protocol = protocol_version() print(f"Protocol version: {protocol // 100}.{protocol % 100}") ``` -------------------------------- ### Display MNE-LSL Commands Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/command_line.rst Run this command to see the available subcommands for the MNE-LSL CLI. ```console $ mne-lsl ``` -------------------------------- ### Example Usage of ScalarIntType Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/types.md Illustrates a generic function using ScalarIntType to pack integer arrays into bytes. The function accepts arrays of various integer types. ```python from typing import TypeVar import numpy as np ScalarIntType = TypeVar("ScalarIntType", np.int8, np.int16, np.int32, np.int64) def pack_indices( indices: np.ndarray[tuple[int, ...], np.dtype[ScalarIntType]], ) -> bytes: """Pack integer array to bytes.""" return indices.tobytes() # All valid pack_indices(np.array([1, 2, 3], dtype=np.int8)) pack_indices(np.array([1, 2, 3], dtype=np.int32)) pack_indices(np.array([1, 2, 3], dtype=np.int64)) ``` -------------------------------- ### Load Raw Data with PlayerLSL Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/types.md Shows how to load continuous data from a FIF file using MNE-Python's IO module and prepare it for playback with PlayerLSL. ```python from mne import io from mne_lsl.player import PlayerLSL raw = io.read_raw_fif("data.fif", preload=True) player = PlayerLSL(raw) player.start() ``` -------------------------------- ### Get Current LSL Local Clock Time Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Retrieve the current LSL local clock time in seconds since the epoch. This function provides a high-precision timestamp. ```python from mne_lsl.lsl import local_clock now = local_clock() # Returns float in seconds ``` -------------------------------- ### Open Legacy StreamViewer Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/command_line.rst Launch the legacy StreamViewer to visualize LSL streams. This command opens a graphical interface for channel selection and plotting. ```console $ mne-lsl viewer ``` -------------------------------- ### Example Usage of ScalarType Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/types.md Demonstrates a generic function using ScalarType to preserve the dtype of a 2D numpy array during a transpose operation. Works with any supported scalar type. ```python from typing import TypeVar import numpy as np ScalarType = TypeVar( "ScalarType", np.int8, np.int16, np.int32, np.int64, np.float32, np.float64 ) def transpose( data: np.ndarray[tuple[int, int], np.dtype[ScalarType]], ) -> np.ndarray[tuple[int, int], np.dtype[ScalarType]]: """Preserve dtype on transpose.""" return data.T # Works with any supported scalar type transpose(np.array([[1, 2], [3, 4]], dtype=np.float32)) transpose(np.array([[1, 2], [3, 4]], dtype=np.int16)) ``` -------------------------------- ### Example Usage of ScalarFloatType Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/types.md Demonstrates a generic function that uses ScalarFloatType to ensure the output dtype matches the input dtype for floating-point arrays. The function applies a gain factor. ```python from typing import TypeVar import numpy as np ScalarFloatType = TypeVar("ScalarFloatType", np.float32, np.float64) def apply_gain( data: np.ndarray[tuple[int, ...], np.dtype[ScalarFloatType]], gain: ScalarFloatType ) -> np.ndarray[tuple[int, ...], np.dtype[ScalarFloatType]]: """Return dtype matches input dtype.""" return data * gain # Returns float32 result32 = apply_gain(np.array([1.0], dtype=np.float32), np.float32(2.0)) # Returns float64 result64 = apply_gain(np.array([1.0], dtype=np.float64), np.float64(2.0)) ``` -------------------------------- ### Connect to a Live LSL Stream Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Establishes a connection to a live LSL stream, retrieves data, and then disconnects. Ensure the stream type matches your acquisition. ```python from mne_lsl.stream import StreamLSL # Create and connect stream = StreamLSL(bufsize=10.0, stype="EEG") stream.connect(acquisition_delay=0.01) # Retrieve data data, timestamps = stream.get_data(picks="eeg") # Cleanup stream.disconnect() ``` -------------------------------- ### Get Testing Dataset Path Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/datasets.md Returns the path to the testing dataset, which contains smaller datasets suitable for unit and integration testing. This function also handles downloading and caching similarly to sample.data_path(). ```python from mne_lsl.datasets import testing test_dir = testing.data_path() print(f"Test data location: {test_dir}") ``` -------------------------------- ### Stream MNE File with Player Options Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/command_line.rst Stream an MNE file using the 'player' command with optional arguments for chunk size, repetition, stream name, and annotation streaming. ```console $ mne-lsl player fname -c 16 --n-repeat 1 --name MyStream --annotations ``` -------------------------------- ### Mock Streaming for Testing with PlayerLSL Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/README.md Uses PlayerLSL to simulate an LSL stream from a file for testing purposes. Requires importing PlayerLSL and StreamLSL. ```python from mne_lsl.player import PlayerLSL from mne_lsl.stream import StreamLSL player = PlayerLSL("test_data.fif", chunk_size=100) player.start() stream = StreamLSL(bufsize=10.0, name="MNE-LSL-Player") stream.connect() ``` -------------------------------- ### Select Channels by Type, Name, or Index Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/configuration.md Demonstrates various methods for selecting channels using the pick() method. This includes selecting by channel type (e.g., 'eeg'), exact channel name (e.g., 'Cz'), or channel index. ```python from mne_lsl.stream import StreamLSL stream = StreamLSL(bufsize=10.0) stream.connect() # By type name stream.pick("eeg") # All EEG channels stream.pick(["eeg", "eog"]) # EEG and EOG # By exact channel name stream.pick("Cz") # Single channel stream.pick(["Cz", "Pz", "Oz"]) # Multiple channels # By index stream.pick(0) # First channel stream.pick([0, 1, 2]) # First three channels # Combine patterns stream.pick(["eeg", "Cz"]) # EEG type AND channel Cz ``` -------------------------------- ### sample.data_path Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/datasets.md Returns the path to the sample dataset, downloading it from GitHub if it's not already cached locally. This function is useful for accessing datasets for development and benchmarking. ```APIDOC ## Function: sample.data_path ### Description Returns the path to the sample dataset, downloading if needed. This function is intended for development and benchmarking purposes. ### Signature ```python def data_path() -> Path ``` ### Returns - `path` (Path): Path to sample dataset. Default location: `~/mne_data/MNE-LSL-data/sample` ### Notes - The first call to this function will download data from GitHub (mscheltienne/mne-lsl-datasets). - Subsequent calls will return the cached path if the data already exists. - The download location can be overridden by setting the `MNE_DATA` environment variable. ### Example ```python from mne_lsl.datasets import sample data_dir = sample.data_path() print(f"Sample data location: {data_dir}") # List files in sample dataset import os files = os.listdir(data_dir) ``` ``` -------------------------------- ### Real-Time Filtering and Callback Processing Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/stream.md Demonstrates applying filters (band-pass and notch) to an LSL stream in real-time and adding a custom callback function for preprocessing data. The callback function modifies the data and timestamps before they are retrieved. ```python stream = StreamLSL(bufsize=5.0, stype="EEG") stream.connect() # Apply filters stream.filter(0.5, 50.0, picks="eeg") stream.notch_filter(60.0, picks="eeg") # Add custom callback def preprocess(data, ts, info): data = (data - data.mean(axis=0)) / data.std(axis=0) return data, ts stream.add_callback(preprocess) # Get processed data data, ts = stream.get_data() ``` -------------------------------- ### Connect to an LSL Stream Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/stream.md Connect to an LSL stream and initiate data collection. Set acquisition_delay for automatic pulling or None for manual acquisition. ```python stream = StreamLSL(bufsize=2.0) stream.connect(acquisition_delay=0.001) # Pull every 1ms ``` -------------------------------- ### BaseStream.connect Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/stream.md Connect to the stream and initiate data collection in the buffer. This method can be used to set an acquisition delay for automatic data pulling or to disable it for manual acquisition. ```APIDOC ## BaseStream.connect ### Description Connect to the stream and initiate data collection in the buffer. ### Method Connect ### Endpoint connect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `acquisition_delay` (float | None): Delay in seconds between acquisitions. If None, automatic acquisition is disabled and manual `acquire()` calls required. Typical: 0.001 to 0.1 seconds. ### Returns - Self for method chaining ### Raises - RuntimeError if already connected - ValueError if acquisition_delay ≤ 0 ### Request Example ```python stream = StreamLSL(bufsize=2.0) stream.connect(acquisition_delay=0.001) # Pull every 1ms ``` ``` -------------------------------- ### Select Channels by Type, Name, or Index Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/README.md Demonstrates different ways to select channels from a stream using MNE-LSL. Use by type for broad selection, by name for specific channels, or by index for precise control. ```python stream.pick("eeg") # By type stream.pick(["Cz", "Pz"]) # By name stream.pick([0, 1, 2]) # By index ``` -------------------------------- ### PlayerLSL Constructor Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/player.md Initializes a PlayerLSL object to create a mock LSL stream from an MNE Raw data file or object. Allows configuration of chunk size, repetition, stream name, source ID, and annotation streaming. ```APIDOC ## PlayerLSL Constructor ### Description Initializes a PlayerLSL object to create a mock LSL stream from an MNE Raw data file or object. Allows configuration of chunk size, repetition, stream name, source ID, and annotation streaming. ### Parameters #### Path Parameters - **fname** (str | Path | BaseRaw) - Required - Path to MNE data file (fif, edf, etc.) or BaseRaw object. #### Query Parameters - **chunk_size** (int) - Optional - Number of samples to push per chunk. Larger values = fewer network packets. Default: 10 - **n_repeat** (int | float) - Optional - Number of times to repeat the file. np.inf = infinite looping. Default: numpy.inf - **name** (str | None) - Optional - Name of the mock LSL stream. Default: "MNE-LSL-Player" - **source_id** (str) - Optional - Unique identifier of the stream source. Default: "MNE-LSL" - **annotations** (bool | None) - Optional - If True, create separate annotations stream. If None, create only if annotations exist in file. Default: None ### Example ```python from mne_lsl.player import PlayerLSL # From file player = PlayerLSL("sample_data.fif", chunk_size=100, n_repeat=3) player.start() # From MNE Raw object from mne import io raw = io.read_raw_fif("sample_data.fif", preload=True) player = PlayerLSL(raw, chunk_size=100) player.start() ``` ``` -------------------------------- ### Configure MNE-LSL Logging and Data Paths Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Set MNE-LSL logging level and custom data directory using environment variables. Also shows how to enable stream error raising. ```bash # Logging level (CRITICAL, ERROR, WARNING, INFO, DEBUG) export MNE_LSL_LOG_LEVEL=DEBUG # Custom data directory export MNE_DATA=/path/to/mne_data # Error handling in acquisition export MNE_LSL_RAISE_STREAM_ERRORS=true ``` -------------------------------- ### PlayerLSL Class Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Create mock LSL streams by replaying recorded data files. This class allows for simulating LSL data streams from existing MNE Raw objects or file paths. ```APIDOC ## Class PlayerLSL ### Description Create mock LSL stream by replaying recorded data file. ### Constructor ```python PlayerLSL(fname: str | Path | BaseRaw, chunk_size: int = 10, n_repeat: int | float = np.inf, name: str | None = None, source_id: str = "MNE-LSL", annotations: bool | None = None) ``` ### Constructor Parameters - `fname` (str | Path | BaseRaw) - Data file path or MNE Raw object - `chunk_size` (int) - Samples per LSL chunk - `n_repeat` (int | float) - Repetitions (np.inf = infinite) - `name` (str | None) - Stream name - `source_id` (str) - Source identifier - `annotations` (bool | None) - Stream annotations? ### Key Methods - `start() -> PlayerLSL` - Begin streaming - `stop() -> PlayerLSL` - End streaming - `rename_channels(mapping: dict | Callable, allow_duplicates: bool = False) -> PlayerLSL` - Rename channels - `set_channel_types(mapping: dict, on_unit_change: str = "warn") -> PlayerLSL` - Set types - `set_channel_units(mapping: dict) -> PlayerLSL` - Set units ### Properties - `name` (str) - Stream name - `source_id` (str) - Source ID - `info` (mne.Info) - Measurement info - `sfreq` (float) - Sampling rate - `ch_names` (list[str]) - Channel names - `n_channels` (int) - Channel count - `chunk_size` (int) - Chunk size - `streaming` (bool) - Currently streaming? ``` -------------------------------- ### Logging for Production Environments Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/utils.md Configure logging for production by setting the log level to 'INFO' and adding a file handler to a timestamped log file. This ensures that important operational logs are captured without excessive detail. ```python from mne_lsl.utils import set_log_level, add_file_handler import logging from datetime import datetime # Setup production logging set_log_level("INFO") log_dir = "logs" log_file = f"{log_dir}/mne_lsl_{datetime.now().strftime('%Y%m%d')}.log" add_file_handler(log_file, mode="a", verbose="INFO") ``` -------------------------------- ### Clone MNE-LSL Repository with Submodules Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Clone your fork of the MNE-LSL repository locally, ensuring that submodules are also initialized. This is the first step for making changes. ```console $ git clone --recurse-submodules https://github.com/yourusername/mne-lsl.git ``` -------------------------------- ### push_sample Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/lsl.md Pushes a single sample through the outlet. This method can accept data as a numpy array or a list of strings and allows specifying a timestamp. ```APIDOC ## push_sample ### Description Pushes a single sample through the outlet. This method can accept data as a numpy array or a list of strings and allows specifying a timestamp. ### Method `push_sample(x: array | list[str], timestamp: float = 0.0, pushThrough: bool = True) -> None` ### Parameters - **x** (array | list[str]) - Required - Sample with one value per channel. - **timestamp** (float) - Optional - Default: 0.0 - Optional timestamp (default: current time). - **pushThrough** (bool) - Optional - Default: True - Push through any network packet boundaries. ### Request Example ```python import numpy as np sample = np.random.randn(n_channels) outlet.push_sample(sample) ``` ``` -------------------------------- ### Import Utils Submodules Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Imports configuration, logs, and measurement info submodules from the utils module. ```python from mne_lsl.utils import config, logs, meas_info ``` -------------------------------- ### Stream MNE File with Player Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/command_line.rst Use the 'player' command to stream data from an MNE-readable file. Specify the file name as the mandatory argument. ```console $ mne-lsl player fname ``` -------------------------------- ### sys_info Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/utils.md Prints system information for debugging and troubleshooting purposes. It can include optional and developer-specific dependency details. ```APIDOC ## sys_info ### Description Prints system information for debugging and troubleshooting. This function can output to a specified file-like object or to standard output, and can include extra dependency information or developer-specific details. ### Method ```python def sys_info( fid: IO | None = None, *, extra: bool = False, developer: bool = False, ) -> None ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | fid | IO \| None | No | None | File-like object to write to. None uses sys.stdout. | | extra | bool | No | False | Include optional dependency information. | | developer | bool | No | False | Include developer dependency info (editable install only). | ### Request Example ```python from mne_lsl.utils import sys_info # Print to stdout sys_info() # Print to file with open("system_info.txt", "w") as f: sys_info(fid=f, extra=True) # With optional dependencies sys_info(extra=True, developer=True) ``` ### Response #### Success Response (200) Displays: - Platform information (OS, version) - Python version and executable path - CPU information (processor, core count) - Memory information (RAM, SWAP) - Package version (mne_lsl, liblsl) - Core and optional dependency versions #### Response Example None (This function prints directly to stdout or a file-like object) ``` -------------------------------- ### Utilities (Direct Import) Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-exports.md Provides direct access to utility functions from the mne_lsl package. ```APIDOC ## Utilities (Direct Import) ### Description Provides direct access to utility functions from the mne_lsl package. ### Functions - **`sys_info()`** - Source module: `utils` - Returns: Information about the system environment. ``` -------------------------------- ### Run Pre-commit Hooks Manually Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Manually run all pre-commit hooks on all files in the repository. This is useful for checking style compliance or fixing issues before committing. ```console $ pre-commit run --all-files ``` -------------------------------- ### Set Custom Data Directory Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/datasets.md Shows how to specify a custom directory for downloading and storing MNE-LSL datasets by setting the MNE_DATA environment variable. ```python import os from mne_lsl.datasets import sample # Set custom download location os.environ["MNE_DATA"] = "/path/to/custom/data" data_path = sample.data_path() ``` -------------------------------- ### Initialize and Connect to EEG Stream Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/utils.md Initializes a StreamLSL object for EEG data and connects to the LSL stream. Ensure the LSL stream is available before connecting. ```python from mne_lsl.stream import StreamLSL stream = StreamLSL(bufsize=10.0, stype="EEG") stream.connect() ``` -------------------------------- ### Open StreamViewer with Specific Stream Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/command_line.rst Connect the StreamViewer to a specific LSL stream by providing its name using the -s or --stream flag. ```console $ mne-lsl viewer -s MyStream ``` -------------------------------- ### Print System Information Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/utils.md Use this function to print detailed system and dependency information for debugging. It can output to standard output or a specified file-like object, with options to include extra or developer-specific dependency details. ```python from mne_lsl.utils import sys_info # Print to stdout sys_info() # Print to file with open("system_info.txt", "w") as f: sys_info(fid=f, extra=True) # With optional dependencies sys_info(extra=True, developer=True) ``` -------------------------------- ### Multi-Stream Testing with EEG and Stimulus Channels Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/player.md Create and stream multi-channel data including EEG and stimulus channels from a RawArray object. PlayerLSL can stream this data, and a client can connect to process it. ```python # Create EEG + stimulus channels from mne import create_info, EpochsArray import numpy as np from mne.io import RawArray sfreq = 250 n_channels = 32 duration = 120 # seconds n_samples = int(sfreq * duration) # Create EEG data data = np.random.randn(n_channels, n_samples) * 100 # µV # Create info with channel types ch_types = ["eeg"] * 30 + ["stim"] * 2 info = create_info(n_channels, sfreq, ch_types) # Create raw raw = RawArray(data, info) # Add annotations raw.set_annotations(None) # Stream player = PlayerLSL(raw, chunk_size=50, n_repeat=np.inf) player.start() # Connect and process stream = StreamLSL(bufsize=10) stream.connect() data, ts = stream.get_data() ``` -------------------------------- ### Benchmark Real-time Processing Pipeline Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/player.md Benchmark a real-time processing pipeline by streaming data from a large file. Configure the player and stream with appropriate buffer sizes and processing delays. The loop continues until a time limit is reached or new samples are available. ```python # Benchmark real-time processing pipeline player = PlayerLSL("large_dataset.fif", chunk_size=256, n_repeat=1) player.start() # Test stream processing stream = StreamLSL(bufsize=10, name="MNE-LSL-Player") stream.connect(acquisition_delay=0.01) stream.filter(0.5, 40.0) import time start = time.time() # Simulate acquisition loop while stream.get_n_new_samples() > 0 or time.time() - start < 60: data, ts = stream.get_data() # Process data... player.stop() print(f"Processing time: {time.time() - start:.2f}s") ``` -------------------------------- ### StreamInlet.open_stream() Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/lsl.md Subscribes to the data stream. Note that samples pushed before the stream is opened will be missed. ```APIDOC ## open_stream() ### Description Subscribe to the data stream. Note that samples pushed before the stream is opened will be missed. ### Method POST ### Endpoint N/A (Method of StreamInlet object) ### Parameters #### Query Parameters - **timeout** (float | None) - Optional - Timeout in seconds. Default: disabled. ### Notes Opens stream non-blocking; samples pushed before stream opens are missed. ``` -------------------------------- ### mne_lsl pull_chunk with numpy.frombuffer Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/pylsl.rst Demonstrates how mne-lsl uses numpy.frombuffer for efficient data retrieval, creating a numpy array in constant time. This is significantly faster than the default list comprehension method. ```python samples = np.frombuffer( data_buffer, dtype=self._dtype)[:n_samples_data].reshape(-1, self._n_channels ) ``` -------------------------------- ### Utility Functions for MNE-LSL Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/index.md Perform system diagnostics and control logging levels using utility functions. Includes adding a file handler for debug logs. ```python from mne_lsl.utils import sys_info, set_log_level, add_file_handler # System diagnostics sys_info(extra=True) # Logging control set_log_level("DEBUG") add_file_handler("debug.log", verbose="DEBUG") ``` -------------------------------- ### Timeit comparison of pylsl and mne_lsl data pulling Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/resources/pylsl.rst A timeit script to compare the performance of pylsl's default list comprehension method against mne-lsl's numpy.frombuffer method for pulling data chunks. It measures and prints the execution time for each method. ```python import ctypes import timeit import numpy as np n_samples = 1024 n_channels = 650 max_values = n_samples * n_channels # create a data buffer, 'retrieved from liblsl' data_buffer = (ctypes.c_double * max_values)() for i in range(max_values): data_buffer[i] = float(i) def method_list_comprehension(): """List comprehension, default method for pylsl.""" samples = [ [data_buffer[s * n_channels + c] for c in range(n_channels)] for s in range(n_samples) ] return samples def method_frombuffer(): """Numpy frombuffer, default method for mne-lsl.""" samples = np.frombuffer(data_buffer, dtype=np.float64)[:max_values].reshape( n_samples, n_channels ) return samples repeat = 5 number = 100 for func in (method_list_comprehension, method_frombuffer): timer = timeit.Timer(func) results = timer.repeat(repeat, number=number) times = [t / number for t in results] best = min(times) worst = max(times) avg = sum(times) / len(times) # format with the correct unit if best < 1e-6: unit, factor = "ns", 1e9 elif best < 1e-3: unit, factor = "µs", 1e6 elif best < 1: unit, factor = "ms", 1e3 else: unit, factor = "s", 1 formatted_time = f"{best * factor:.2f} ± {(avg - best) * factor:.2f} {unit}" plural = "s" if number != 1 else "" print(f"{number} loop{plural}, best of {repeat}: {formatted_time} per loop") ``` -------------------------------- ### Add File Handler for Logging Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/utils.md Set up a file handler to write logs to a specified file. This function allows configuration of the file path, write mode ('a' for append, 'w' for write), text encoding, and the verbosity level for the handler itself. ```python from mne_lsl.utils import add_file_handler, set_log_level set_log_level("DEBUG") add_file_handler("mne_lsl_debug.log", verbose="DEBUG") # All DEBUG-level logs written to file from mne_lsl.stream import StreamLSL stream = StreamLSL(bufsize=10.0) stream.connect() # Logs written to mne_lsl_debug.log ``` -------------------------------- ### Run Unit Tests Source: https://github.com/mne-tools/mne-lsl/blob/main/doc/development/contributing.rst Execute all unit tests for the MNE-LSL project from the root of the repository using pytest. Ensure tests are short and focused. ```console $ pytest tests ``` -------------------------------- ### MNE-LSL File Structure Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/README.md This diagram illustrates the directory structure of the MNE-LSL project, showing the organization of documentation files and API reference modules. ```text output/ ├── README.md # This file ├── index.md # Main overview and navigation ├── types.md # Type definitions ├── configuration.md # Parameters and options ├── api-exports.md # Complete symbol reference └── api-reference/ ├── lsl.md # Low-level LSL bindings ├── stream.md # High-level stream classes ├── player.md # Mock stream player ├── datasets.md # Sample datasets └── utils.md # Logging utilities ``` -------------------------------- ### System Information Reporting for Diagnostics Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/utils.md Generate a comprehensive diagnostic report by capturing system information to a file. This includes timestamps and detailed system/dependency data, useful for troubleshooting. ```python from mne_lsl.utils import sys_info import datetime # Generate diagnostic report timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") report_file = f"system_report_{timestamp}.txt" with open(report_file, "w") as f: print(f"MNE-LSL System Diagnostic Report", file=f) print(f"Generated: {timestamp}", file=f) print("-" * 50, file=f) sys_info(fid=f, extra=True, developer=True) print(f"Report saved to {report_file}") ``` -------------------------------- ### EpochsStream Constructor Parameters Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/configuration.md Defines the parameters for creating an EpochsStream, including buffer size, event handling, timing, and rejection thresholds. Use this to specify how epochs are extracted and processed from a continuous stream. ```python class EpochsStream( stream: BaseStream, bufsize: int, event_id: int | dict | None = None, event_channels: str | list[str] = "stim", event_stream: BaseStream | None = None, tmin: float = -0.1, tmax: float = 0.5, baseline: tuple[float, float] | None = (None, 0), picks: str | list[str] | None = None, reject: dict | None = None, flat: dict | None = None, reject_tmin: float | None = None, reject_tmax: float | None = None, detrend: int | str | None = None, ) -> None ``` ```python epochs = EpochsStream( stream, bufsize=100, event_id=1, tmin=-0.1, tmax=0.5, reject={"eeg": 200, "mag": 5000}, # µV thresholds flat={"eeg": 1, "mag": 100}, # Minimum amplitude reject_tmin=-0.1, reject_tmax=0.8 # Wider window for QA ) ``` -------------------------------- ### Apply Notch Filter to Stream Source: https://github.com/mne-tools/mne-lsl/blob/main/_autodocs/api-reference/stream.md Apply a notch filter at specific frequencies to selected channels. This method is chainable. ```python stream.notch_filter([50, 100]) # 50Hz and 100Hz ```