API Reference

This page contains the API documentation for labnirs2snirf.

Labnirs2Snirf

Convert LabNIRS data files to SNIRF format.

This package provides tools to convert fNIRS data exported from LabNIRS software to the Shared Near Infrared Spectroscopy Format (SNIRF), enabling compatibility with analysis tools like MNE-Python and other NIRS analysis software.

Main modules:

  • labnirs: Reading and parsing LabNIRS data files

  • snirf: Writing data to SNIRF/HDF5 format

  • layout: Importing and applying probe position data

  • model: Data models following the SNIRF specification

  • labnirs2snirf: Entrypoint when run as a script

  • args: Command-line argument parsing

  • log: Logging configuration for command-line usage

Modules that are needed for running as a script are listed on the Script page.

LabNIRS Reader

Functions related to reading data from LabNIRS files.

exception labnirs2snirf.labnirs.LabNirsReadError[source]

Bases: Labnirs2SnirfError

Custom error class for LabNIRS reading errors.

labnirs2snirf.labnirs.read_labnirs(data_file: Path, keep_category: str = 'all', drop_subtype: Collection[str] | None = None) Nirs[source]

Read and process a LabNIRS data file and returns a NIRS data model.

Parameters:
  • data_file (Path) – Path to the LabNIRS data file. File is expected to be in the format exported by the LabNIRS software, with 35 lines of header and a version number/header type of 11.0.

  • keep_category ("hb"| "raw" | "all", default="all") – Data category to include in the output. “Raw” means raw voltage data, “hb” means haemoglobin data. If “all”, both categories are included.

  • drop_subtype (Collection[str] | None, default=None) – Set or list of data types and/or wavelengths to drop from the data. Hb data types are: “hbr”, “hbo” and “hbt”. Wavelengths should be convertible to integer. All included if None.

Returns:

A NIRS object containing most data required by the SNIRF specification.

Return type:

model.Nirs

Notes

This function reads experiment data and metadata from .txt files exported by the LabNIRS software. It expects a 35-line header with specific formatting (and version 11.0). Only the top line (containing header length), the presence of channel pairs on line 33, and the presence of data columns are enforced. Other validation failures only raise a warning, but errors may still occur.

LabNIRS can export files with both raw and Hb data, depending on the options selected. The keep_category parameter controls which of the two is retained in the output. The drop_subtype parameter can be used to further exclude specific wavelengths or Hb data types from the output.

By default, all data is included, which may not be desirable when the goal is to import the .snirf file to a NIRS analyser tool such as MNE, as these tools may not support files with both raw and Hb data present, may not need HbT, or may not be able to handle more than 2 wavelengths. For MNE, for example, it would be sensible to either include raw and drop one wavelength of the 3, or to include hb and drop HbT.

For reasons of compatibility with other software, a list of wavelengths is preserved even for Hb data. Dropped wavelengths are not included in the list. For Hb data, the wavelength indices are set to 0 for each data channel. NB that this is an invalid index.

Since the labNIRS files don’t store coordinates, probe positions are all set to (0, 0, 0). Positions can be read from file using the --layout option. Probe labels are based on actual numbers in the source file, however, the position matrices are contiguous and skip over any missing probe numbers. E.g. if there are sources 1 and 3, then the source position matrix will have 2 rows, with source 1 at index 0 and source 3 at index 1, and the labels will be S1 and S3 respectively.

labnirs2snirf.labnirs.read_probe_pairs(data_file: Path) str[source]

Read the header line containing probe pairs.

Parameters:

data_file (Path) – Path to the LabNIRS data file. File is expected to be in the format exported by the LabNIRS software, with 35 lines of header and a version number/header type of 11.0.

Returns:

String containing probe pairs without leading and trailing whitespace. For example: “(1,1)(2,1)…”.

Return type:

str

SNIRF Writer

Functions related to writing NIRS data to SNIRF files using HDF5.

exception labnirs2snirf.snirf.SnirfWriteError[source]

Bases: Labnirs2SnirfError

Custom error class for SNIRF writing errors.

labnirs2snirf.snirf.write_snirf(nirs: Nirs, output_file: Path) None[source]

Write the NIRS data to a SNIRF file.

Parameters:
  • nirs (model.Nirs) – NIRS data model containing metadata, data, stim and probe information.

  • output_file (Path) – Path to the output SNIRF file. A warning is shown if the file does not have a “.snirf” extension.

Notes

  • Stimulus onsets are available, but durations, pre, and post rest periods are not stored in the data exported by LABNIRS. As such, onsets are written correctly, durations are set to 0, and rest periods are not included. These timings are stored in a separate .csv file by LABNIRS, reading which may be implemented in the future.

  • While the SNIRF specification allows for both indexed and non-indexed nirs groups (e.g. /nirs, /nirs1, /nirs2, …), some tools (e.g. MNE) only accept a single non-indexed /nirs group. Therefore, we always write it as such.

  • These tools (may) have other restrictions as well, such as expecting only a single data group (/nirs/data1), but as far as I am aware, this is not an issue for LABNIRS data.

Probe Layout

Functions related to importing probe positions.

exception labnirs2snirf.layout.LayoutError[source]

Bases: Labnirs2SnirfError

Custom error class for layout-related issues.

labnirs2snirf.layout.read_layout(file: Path) Layout_3D[source]

Read optode coordinates from file.

Parameters:

file (Path) – Path pointing to location file.

Returns:

Dict mapping probe labels to 3D coordinates.

Return type:

dict[str, tuple[float, float, float]]

Notes

Location files are expected to follow the .sfp format, which is a tab-separated text file with columns: label, x, y, and z, where ‘x’, ‘y’, and ‘z’ are the 3D coordinates of the optode. Labels are case-sensitive. If duplicate labels are found, a warning is logged and the last occurrence is used.

labnirs2snirf.layout.update_layout(data: Nirs, locations: Layout_3D) None[source]

Update source and position 3D coordinates in nirs data.

Parameters:
  • data (model.Nirs) – Nirs data produced by labirs.read_nirs(). Probes have labels (Si, Di) corresponding to their original numbering in the exported labNIRS data.

  • locations (dict[str, tuple[float, float, float]]) – Mapping of probe labels to 3D coordinates. These can be read in from file by read_layout(). Coordinates are always stored as 3D tuples - when only 2D is available, Z is set to 0. Labels are case-sensitive.

Raises:

LayoutError – If no probe labels present in data.

Error Handling

Custom exception classes for the labnirs2snirf package.

exception labnirs2snirf.error.Labnirs2SnirfError[source]

Bases: Exception

Base class for exceptions in this module.

Data Models

NIRS data model definitions for Labnirs –> SNIRF conversion.

Based on the SNIRF specification v1.1. See https://github.com/fNIRS/snirf/blob/v1.1/snirf_specification.md for details.

class labnirs2snirf.model.Data(time: ndarray, dataTimeSeries: ndarray, measurementList: list[Measurement])[source]

Bases: object

Experimental time series data following SNIRF specification.

time

1D array of time points in seconds. Possible dtypes: float64 (recommended), float32.

Type:

np.ndarray

dataTimeSeries

2D array (time x channels) of measurement values. Possible dtypes: float64 (recommended), float32.

Type:

np.ndarray

measurementList

List of Measurement objects describing each data channel.

Type:

list[Measurement]

class labnirs2snirf.model.Measurement(sourceIndex: int, detectorIndex: int, dataType: int, dataTypeIndex: int, wavelengthIndex: int, dataTypeLabel: str | None = None)[source]

Bases: object

Measurement channel specification following SNIRF specification.

Each Measurement describes a single data channel with information about the source-detector pair, wavelength, and data type.

sourceIndex

Index of the source optode (1-based).

Type:

int

detectorIndex

Index of the detector optode (1-based).

Type:

int

dataType

Type of data: 1 for continuous wave, 99999 for processed (e.g., HbO, HbR).

Type:

int

dataTypeIndex

Index for grouping measurements of the same type (typically 0).

Type:

int

wavelengthIndex

Index into the wavelengths array, indicating the wavelength used.

Type:

int

dataTypeLabel

Optional label for processed data types (e.g., “HbO”, “HbR”, “HbT”).

Type:

str or None, default=None

class labnirs2snirf.model.Metadata(SubjectID: str, MeasurementDate: str, MeasurementTime: str, LengthUnit: str = 'm', TimeUnit: str = 's', FrequencyUnit: str = 'Hz', additional_fields: dict[str, str] = <factory>)[source]

Bases: object

Metadata container for NIRS measurements following SNIRF specification.

SubjectID

Subject identifier string.

Type:

str

MeasurementDate

Date of measurement in YYYY-MM-DD format.

Type:

str

MeasurementTime

Time of measurement in HH:MM:SS format.

Type:

str

LengthUnit

Unit of length measurements (meters).

Type:

str, default=”m”

TimeUnit

Unit of time measurements (seconds).

Type:

str, default=”s”

FrequencyUnit

Unit of frequency measurements (Hertz).

Type:

str, default=”Hz”

additional_fields

Additional optional metadata fields as key-value pairs.

Type:

dict[str, str], default=empty dict

class labnirs2snirf.model.Nirs(metadata: Metadata, data: list[Data], probe: Probe, stim: list[Stim] | None = None)[source]

Bases: object

Complete NIRS dataset following SNIRF specification.

This is the top-level container for a complete NIRS measurement, including metadata, experimental data, probe geometry, and stimuli.

metadata

Metadata about the subject and measurement.

Type:

Metadata

data

List of Data objects (in this package, it always contains one Data object).

Type:

list[Data]

probe

Probe geometry and configuration information.

Type:

Probe

stim

Optional list of stimulus/event information.

Type:

list[Stim] or None, default=None

class labnirs2snirf.model.Probe(wavelengths: ndarray, sourcePos3D: ndarray, detectorPos3D: ndarray, sourceLabels: list[str] | None = None, detectorLabels: list[str] | None = None)[source]

Bases: object

Probe geometry and configuration following SNIRF specification.

wavelengths

1D array of wavelengths in nanometers.

Type:

np.ndarray

sourcePos3D

2D array (n_sources x 3) of source 3D coordinates [x, y, z].

Type:

np.ndarray

detectorPos3D

2D array (n_detectors x 3) of detector 3D coordinates [x, y, z].

Type:

np.ndarray

sourceLabels

Optional list of source labels (e.g., [“S1”, “S2”, …]).

Type:

list[str] or None, default=None

detectorLabels

Optional list of detector labels (e.g., [“D1”, “D2”, …]).

Type:

list[str] or None, default=None

class labnirs2snirf.model.Stim(name: str, data: ndarray)[source]

Bases: object

Stimulus/event information following SNIRF specification.

name

Name or identifier for the stimulus condition.

Type:

str

data

1D array of stimulus onset times in seconds.

Type:

np.ndarray