-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
A navigable map of the processFNIRS2 package namespaces — what lives where, and a one-line purpose for each public function. Use this page to find capability by location; for step-by-step how-tos see the topic pages linked throughout, and Home for the overall map of the wiki.
pf2 single-subject: import, process, epoch, probe/spatial, QC, export
pf2_base advanced/internal: pipeline machinery, algorithm engines, first-party DSP
exploreFNIRS group analysis: Experiment/GLMExperiment, stats, connectivity, hyperscanning
functions/ flat algorithm implementations, dispatched by name from method chains
pf2 is the primary user-facing package (Layer 1: raw device file → processed
HbO/HbR struct). exploreFNIRS is the group-analysis layer (Layer 2: a cell
array of processed structs → statistics and figures). pf2_base underlies
both — it holds the pipeline classes, the three-stage processing engines, and
first-party signal/wavelet code, plus a documented allowlist of advanced APIs
for users who need lower-level control. See Getting Started
for the two-layer architecture in context, and Processing
Pipeline for how the stages fit together.
Namespaces are lowercase (pf2.import.importNIR, pf2.data.blockAverage,
exploreFNIRS.core.Experiment). Older capitalized forms
(processFNIRS.Import.ImportNIR) are from a prior major version and no
longer apply.
| Function | Purpose |
|---|---|
processFNIRS2(data, ...) |
Main processing entry point. Runs the three-stage pipeline (raw → OD → Hb → filtered Hb). Assigning an output (out = processFNIRS2(data)) suppresses the GUI; a bare call opens it. Accepts a single struct or a cell array (processes each element); elements with no .raw (already-processed or empty) pass through as no-ops when the GUI is suppressed. |
pf2.process(data, ...) |
Namespaced wrapper for the same entry point. |
pf2.GUI |
Launch the processFNIRS2 GUI directly. |
pf2.help |
Print a getting-started overview to the console. |
pf2.methods |
List both raw and oxy processing methods in one call. |
See Processing Pipeline and Getting Started.
| Function | Purpose |
|---|---|
importNIR |
Import fNIR Devices/Biopac .nir files. |
importNIRX |
Import NIRx system files. |
importHitachiMES |
Import Hitachi ETG-4000 .csv files. |
importOxy3 |
Import Artinis OxySoft .oxy3 files; markers from port/trigger channels; pass 'OptodeTemplate' for real optode geometry. |
importSNIRF |
Import standardized SNIRF files (auto-reads BIDS _events.tsv trial types). |
importDirectory |
Batch-import a directory tree with auto format detection; 'Dir1'..'Dir4'/'Filename' map path components to .info fields. |
importEmbeddings |
Re-import learned features/predictions from an HDF5 file (foundation-model export contract) into data.embeddings. |
fromTable |
Build fNIRS-shaped segment structs from a long-format (tidy) table — no device/probe, but usable with Experiment, temporal/bar plots, and the LME engine. |
sampleData |
Bundled example datasets: bare call loads fNIR1200 (with markers); sampleData.fNIR2000(), sampleData.experiment(), sampleData.group() for siblings. |
See Importing Data.
| Function | Purpose |
|---|---|
setT0 |
Shift the time axis so a given point becomes t = 0. |
resample |
Resample/average fNIRS data to a new bin size. |
split |
Extract a time segment with optional baseline correction. |
crop |
Extract a time segment with no baseline correction. |
concatenate |
Merge multiple devices/probes into one structure (more channels; resamples/aligns time). |
concatenateHorizontal |
Concatenate segments in time (temporal merge of runs from the same probe). |
applyChannelMask |
Set data in rejected channels (per fchMask) to NaN. |
getMarkers |
Extract marker onset timepoints by code (scalar, sequence, or OR set). |
getMarkerDict / setMarkerDict
|
Resolve / set the dataset's code→label dictionary (info.markerDict). |
labelMarkers |
Stamp a categorical .Label column on the marker table from the dictionary. |
dedupeMarkers |
Collapse near-duplicate markers firing within a tolerance. |
removeMarkers |
Remove marker rows by code, time window, or row index. |
defineBlocks |
Convert marker codes into block definitions (auto-labeled from the marker dictionary). |
slidingWindows |
Tile a continuous recording into fixed-length/overlapping window blocks (marker-free), same block format as defineBlocks. |
extractBlocks |
Cut time-locked segments from block definitions (PreTime/PostTime; 'RejectByAux' for motion-aware rejection). |
blockAverage / grandAverage
|
Trial/grand-average epoched segments onto a common time grid (grandAverage is an alias). |
blocksToEvents |
Convert block definitions to GLM event structs. |
betasToSegments |
Convert GLM betas back into segment-style data for group analysis. |
auxOnGrid |
Resample a named auxiliary signal onto the fNIRS time base (anti-aliased, NaN-gap aware). |
importInfo |
Import subject-level metadata from CSV/Excel into .info. |
importBlockInfo |
Import block-level metadata into block structs (CSV/Excel path, in-memory table, or numeric vector). |
infoToTable / infoFromTable
|
Extract .info fields to a MATLAB table, or write a table (or single field) back into .info. |
editChannelMaskGUI |
Interactive GUI for editing the channel mask. |
plot |
Router to the appropriate +pf2/+data/+plot function. |
See Importing Data, Processing Pipeline, and Block Averaging and Epoching.
| Function | Purpose |
|---|---|
oxy |
Plot hemoglobin concentration timeseries (single/all channels, baseline overlay). |
raw |
Plot raw light intensity timeseries. |
roi |
Plot region-of-interest data. |
auxData |
Plot auxiliary (physiological) temporal data. |
See Visualization.
Type-aware extractors that turn a raw auxiliary waveform (typed via
pf2_base.auxSignalType, canonicalized via pf2_base.normalizeAux) into a
derived feature series.
| Function | Purpose |
|---|---|
heartRateFrom |
Derive a heart-rate (bpm) series from a PPG or EKG waveform. |
hrvFeatures |
HRV metrics (SDNN, RMSSD, pNN50, LF, HF, LF/HF) from a waveform or beat series. |
hrvSeries |
Time-resolved HRV via a sliding window. |
edaDecompose |
Split GSR/EDA into tonic (SCL) and phasic (SCR) components. |
accelFeatures |
Motion features (norm, jerk) from a multi-axis accelerometer signal. |
eegBandPower |
Canonical EEG band-power feature series (delta through gamma). |
respFeatures |
Respiration rate (br/min) and RVT from a respiration waveform. |
addFeature |
Store a derived signal back as a typed Aux feature (survives SNIRF round-trip). |
See Auxiliary Signals.
| Function | Purpose |
|---|---|
nearestBrodmann |
Find the nearest Brodmann area(s) for each channel. |
montage |
Portable, self-describing montage export (MNI coords, S-D distances, wavelengths, short-sep flags, nearest BA); optional JSON/CSV/XLSX sidecar. |
saveCfg |
Write a probe's geometry to a toolbox-native device .cfg (reloadable via pf2.Device.load). |
canonicalize |
Project channel biomarker series onto a shared Brodmann-region axis for cross-montage/cross-device comparison. |
channelLabels |
Return S#_D# string labels for each channel. |
computeAdjacency |
Compute a channel adjacency matrix from MNI coordinates. |
transformToMNI |
Transform coordinates from subject space to MNI space. |
plot |
Router to the appropriate +pf2/+probe/+plot function. |
See Visualization.
| Function | Purpose |
|---|---|
topo |
Quick topographic map (2D heatmap or 3D cortex); 'View','movie' animates over time. |
arrangedValues |
Plot channel values in the device's configured 2D layout. |
imageValues |
2D heatmap of channel values. |
interpolateValues / interpolateValues3D
|
Interpolate channel values across the probe (2D / 3D cortical surface); 'Style' selects the showcase/publication render preset. |
imageROIvalues / interpolateROIvalues
|
ROI-level heatmap / interpolated visualization. |
showProbe3D |
3D probe geometry visualization. |
showHead3D |
Colin27 head model (translucent scalp + brain) with the probe overlaid. |
movie |
Animate a biomarker over time on the cortex/probe (MP4/AVI/GIF). |
connectome |
Draw a connectivity network anchored at real channel/ROI positions (2D/3D). |
tomographyMovie |
Animate a time-resolved DOT reconstruction on the cortex. |
Explore3D |
Interactive explorer for interpolateValues3D with live controls and a copy-paste command. |
| Function | Purpose |
|---|---|
pvalues |
Project per-channel p-values onto the cortex (significance-based transparency). |
fstats |
Project F-statistics. |
correlation |
Project correlation values. |
biomarker |
Project biomarker values (e.g. mean HbO); 'interpolateType','sensitivity' for a Gaussian optical-sensitivity kernel. |
counts |
Project per-channel N counts. |
regions |
Flat-fill Brodmann parcels from canonicalized region values. |
parcels |
Optode parcel map — per-channel Voronoi cells with outlines/numbers (channel-assignment cartoon, not image reconstruction). |
pmdf |
Project channel values through the physical sensitivity "banana" footprint. |
tomography |
Render a DOT image reconstruction (signed, sensitivity-masked) on the cortex. |
See Visualization and Diffuse Optical Tomography.
| Function | Purpose |
|---|---|
forward.sensitivity |
Channel-by-vertex PMDF sensitivity ("banana") matrix on the MNI cortical mesh. |
forward.coverage |
Per-vertex sensitivity support map for a montage. |
dot.reconstruct |
Vertex-space HbO/HbR reconstruction (depth-weighted, channel-whitened Tikhonov min-norm, auto-regularized). |
dot.montageInfo |
Report whether a montage is high-density/multi-distance and its reconstruction suitability. |
dot.resolution |
Point-spread-function diagnostics (localization error, spread, FWHM). |
See Diffuse Optical Tomography.
| Function | Purpose |
|---|---|
defineROI |
Define regions of interest for fNIRS analysis. |
| Function | Purpose |
|---|---|
ChannelCheck |
Interactive App Designer GUI for channel quality review (auto-suppresses headless/-batch/unit-test sessions). |
snapshot |
One-call headless QC summary — dashboard + PSD + SCI PNGs to a directory. |
sci |
Scalp Coupling Index (cross-correlates cardiac signal across wavelengths). |
powerSpectrum |
PSD with physiological peak detection (cardiac, respiratory, Mayer). |
plotQuality |
Visualize SCI bar charts or PSD line plots with band overlays. |
takizawa |
Four-rule Hb quality check (Takizawa 2008). |
| Function | Purpose |
|---|---|
assess |
Run configurable quality checks (saturation, SCI, cardiac, CoV, Takizawa) and return a report. |
apply |
Apply a QC report's recommendations to data.fchMask. |
report |
Print a QC report summary to the command window. |
plotReport |
Visualize a QC report as a spatial channel-map dashboard. |
See Quality Control.
| Function | Purpose |
|---|---|
export |
Auto-detect output format from extension/'Format'; batch-capable. |
asNIR |
Export to NIR file format (single struct or batch cell array). |
asSNIRF |
Export to SNIRF (single struct, multi-run, or batch). |
asBIDS |
Export a cell array as a true BIDS-NIRS dataset (sub-/ses-/nirs tree with sidecars, dataset_description.json, participants.tsv). |
asTensor |
Export as a self-describing HDF5 tensor (foundation-model contract v1.0): [time × channel × feature] plus montage descriptor and manifest. |
blockAvgToTable |
Export block-averaged epochs to a flat benchmark table. |
glmToTable |
Export GLM first-level results to a flat benchmark-schema table. |
See Export and Interoperability.
| Subpackage / Function | Purpose |
|---|---|
+raw |
Raw-stage method configuration: list, setMethod, configureMethods (GUI), describeMethod, importMethods/importMethod, create, delete, editFunction, removeFunction, addFunction, exportMethod. |
+oxy |
Same operation set for the oxy (filtered-Hb) stage. |
Editor |
App Designer editor for raw/oxy processing methods. |
describeCurrentMethods |
Display details of the currently active methods. |
resetDefaults |
Wipe stored methods and re-seed from the repo's factory functions. |
Method-authoring internals (function validation, the default-method seed
factories, add/edit-function GUI helpers) live under pf2_base.methods, not
in this primary namespace. See Processing Pipeline.
| Function | Purpose |
|---|---|
process |
Execute the full pipeline (Raw + OD + Oxy stages) — namespaced dispatcher underlying processFNIRS2. |
processRaw |
Execute the raw processing stage only. |
processOxy |
Execute the oxy processing stage only. |
See Processing Pipeline.
| Function | Purpose |
|---|---|
selectDevice |
Load a device configuration file. |
getDevice |
Query the current device settings (checks data.device first). |
setRejectLevel |
Set the channel rejection threshold. |
+baseline.setBaselineStartTime / setBaselineLength / useGlobalMean
|
Configure baseline window for DPF/normalization. |
+dpf.setDPFmode |
Set DPF mode (None/Fixed/Calc; case-insensitive). |
+dpf.setFixedDPF |
Set the fixed DPF value. |
See Processing Pipeline.
Immutable value object describing a probe: geometry, wavelengths, MNI
positions, saturation bounds. Auto-attached as data.device by all import
functions and by processFNIRS2.
| Member | Returns |
|---|---|
Device.load(nameOrData) |
Construct from a config name or a data struct (cached). |
Device.fromProbeInfo(probeInfo) |
Construct from an already-loaded probeInfo struct. |
Device.clearCache() |
Reset the persistent load cache. |
dev.wavelengths() |
[1×C_raw] wavelength per raw column. |
dev.mniPositions() |
[nCh×3] MNI coordinates. |
dev.sdDistances() |
[1×nCh] source-detector distances. |
dev.channelTable() / dev.optodeTable()
|
MATLAB tables of channel / optode metadata. |
dev.hasMNI() |
Logical: whether MNI coordinates are available. |
dev.isShortSep() |
[1×nCh] logical short-separation mask. |
dev.rawMax / dev.rawMin
|
Saturation ceiling / intensity floor. |
Public entry point for bypassing the PF2/setF globals: bundles DPF mode,
baseline, methods, device, and rejection level into one object, configurable
with processFNIRS2-style Name-Value pairs and usable directly as
ctx.process(data) or via processFNIRS2(data, 'Context', ctx). ctx.copy()
gives each parfor worker an independent context. See Processing
Pipeline.
Consumes a cell array of processed fNIRS structs (from processFNIRS2) for
multi-subject statistics and visualization. Full workflow in Group
Analysis.
| Function | Purpose |
|---|---|
Experiment |
Main group-analysis container class — select, groupby, aggregate, connectivity, hyperscanning, HB-ICA, intra/inter-ROI, plot, export. |
GLMExperiment |
GLM wrapper extending Experiment — continuous-recording processing, design matrix, first-level fitting, beta packaging, betaSeriesConnectivity(), ppi(). |
plotTemporal |
Headless time-series plots with ROI support. |
plotBar |
Headless bar charts with ROI support. |
plotTopo |
Headless topographic maps (single/per-group layout, snapshot or time window). |
plotHeatmap |
Channel × time heatmap (sortable, diverging colormap, ROI support). |
plotComposite |
Multi-panel publication figures. |
plotLME |
LME analysis with bar charts, ANOVA tables, and topographic F-maps. |
plotTopoLME |
All-in-one LME fit + cortical projection. |
plotScatter |
Scatter correlation with regression, topographic maps, and ROI support. |
ColorScheme |
Hierarchical color rules for multi-factor plots. |
| Function | Purpose |
|---|---|
fitLME |
Standalone channel-wise LME fitting (fNIRS, ROI, or Aux; no visualization). |
fitInfoLME |
Fit an LME for an info/behavioral variable. |
autoModelLME |
Automatic per-channel LME model selection via forward stepwise information criteria. |
runContrasts |
Post-hoc contrasts with FDR correction across channels. |
buildContrasts |
Generate standard contrast matrices from a fitted LME model. |
summarize |
Publication-ready summary tables (ANOVA, contrasts, coefficients, fit, APA). |
permTest |
Non-parametric permutation test for paired comparisons. |
clusterPermutation / findClusters
|
Cluster-based permutation testing across channels. |
effectSize |
Effect size with bootstrap confidence intervals. |
behavioralTable |
Descriptive stats, comparisons, or correlations for behavioral data. |
| Function | Purpose |
|---|---|
computeMatrix |
Channel-pair connectivity matrices (symmetric or directed). |
computeDynamicFC / detectStates
|
Sliding-window dynamic FC tensor, then K-means brain-state clustering. |
computeIntraROI / computeInterROI
|
Within-ROI and between-ROI coupling analysis. |
computeBetaSeries |
Beta-series correlation connectivity (LSA/LSS). |
computePPI |
Psychophysiological interaction analysis (gPPI). |
alignMatrices |
Align results across subjects with different channel sets. |
plotMatrix / plotChord / plotDirected / plotDynamicFC / plotIntraROI / plotInterROI / plotBlockComparison
|
Connectivity visualizations (heatmap, chord/connectogram, directed arcs, dynamic FC, ROI bar/radar). |
Brain-anchored connectome rendering at real channel/ROI positions is
pf2.probe.plot.connectome, above.
| Function | Purpose |
|---|---|
pearson / spearman
|
Linear / rank correlation. |
xcorr |
Cross-correlation. |
coherence / wcoherence
|
Magnitude-squared coherence / wavelet coherence. |
granger / transferEntropy
|
Directed coupling (AR F-test / histogram-based transfer entropy). |
mutualInfo |
Histogram-based mutual information with surrogate p-values. |
partialCorr / partialCoherence
|
Coupling controlling for confounds or shared physiology. |
hbica |
HB-ICA pairwise coupling adapter. |
plotWcoherence / plotWindowed
|
Time-frequency and windowed coupling visualizations. |
| Function | Purpose |
|---|---|
pairSubjects |
Pair subjects by matching criteria. |
computeDyad |
Compute coupling for dyads (any +coupling method). |
computeGroup |
Group-level statistics with SEM. |
permutationTest |
Permutation-based significance vs. pseudo-pairs. |
hbica |
HB-ICA decomposition for a dyad (TDSEP ICA, GOF classification, dual regression). |
physioConfoundQC |
Flag shared-physiology (LFO/VLFO) confound risk. |
plotDualBrain |
Dual-brain synchrony at real probe geometry with cross-brain edges. |
plotGroup / plotGroupTemporal / plotDyadMatrix / plotHBICA / plotInterBrainTopo
|
Group/dyad-level visualizations. |
See Group Analysis.
| Subpackage | Purpose |
|---|---|
+graph |
Graph-theory metrics on connectivity matrices — degree, clustering, path length, efficiency, betweenness, modularity, small-world, hub detection, network plots. |
+report |
Publication tables and report assembly — ANOVA/contrast/correlation/demographics tables, APA-style formatting, HTML pipeline, LaTeX export. |
+fx |
performFDR / performFDR_twostep (Benjamini-Hochberg / adaptive two-step FDR), autoContrast. |
+export |
mergeGbyTablesLong / mergeGbyTablesWide / connectivityToTable — flatten grouped results for R/SPSS/Excel. |
+dataset |
buildSegmentInfoTable, standardizeROIs — data organization helpers. |
+plot |
Legacy GUI-bound plotting (temporal, barchart, scatter); prefer the headless +core/plotTemporal etc. above for scripting. |
Top-level GUI glue: exploreFNIRS.m (main app), browseEx, loadEx,
saveEx, processMethods, plotExTimeline.
pf2_base serves two roles: a documented allowlist of low-level interfaces
for advanced users, and the implementation machinery underneath the primary
pf2 workflow. Package membership alone isn't a support promise — only the
cataloged functions are part of the advanced public surface.
| Area | Contains |
|---|---|
| Pipeline classes (top level) |
PipelineFunction, Pipeline, RawPipeline, OxyPipeline, ProcessingContext — the programmatic method-chain API behind pf2.methods. See Processing Pipeline. |
+fnirs |
The three-stage engines (processStageRaw2OD, bvoxy, processStageFilterHb), GLM primitives (buildDesignMatrix, fitGLM, diagnoseGLM), ROI/short-channel helpers. |
+signal |
First-party filters (lpf, hpf, bpf) and tdsep (blind source separation). |
+wavelet |
Self-contained discrete/continuous wavelet transforms (no Wavelet Toolbox dependency). |
+accel |
Accelerometer-informed motion detection/regression. |
+dot |
DOT internals — Green's functions, head models, mesh/sensitivity primitives underneath pf2.probe.forward/pf2.probe.dot. |
+bids |
BIDS sidecar helpers underneath pf2.export.asBIDS. |
+plot |
Shared plot styling/rendering infrastructure — PlotStyle, RenderStyle, brainColormap, matcap shading, figure save helpers. |
+methods |
Method-authoring internals: validateFunction, the +seeds default-method factories, add/edit-function GUI helpers. |
+external |
Vendored/first-party replacements for Signal Processing Toolbox and SNIRF/HDF5 I/O (no third-party runtime dependency). |
+tests |
The test suite (runAllTests, runQuickTests). |
| Top-level utilities |
normalizeMarkers/markersToArray/mergeMarkers, normalizeMarkerDict/mergeMarkerDict, normalizeAux, auxSignalType, pf2_initialize, loadDeviceCfg, hierarchicalAverage. |
Flat, standalone signal-processing step functions dispatched by name from raw
and oxy method chains (or added ad hoc to a RawPipeline/OxyPipeline). Not
a package namespace — called by string name from pf2.methods configuration.
| Category | Examples |
|---|---|
| Intensity → OD | pf2_Intensity2OD |
| Filtering |
pf2_lpf, pf2_hpf, pf2_bpf_butter, pf2_bpf_fir, pf2_bpf_iir, pf2_bandstop, detrend_nan, detrend_3rd_order
|
| Motion correction |
pf2_SMAR, pf2_SMAR2, pf2_fnirs_MARA, pf2_MotionCorrectTDDR, pf2_MotionCorrectSpline, pf2_MotionCorrectSplineSG, pf2_MotionCorrectWavelet
|
| Channel/global processing |
pf2_CAR, pf2_GSR, pf2_SSR, pf2_subtractAmbient, applyTimeChMask, pf2_ambient_ICA_clean, icaClean, waveClean
|
| Quality control |
pf2_thresholdValues, pf2_TakizawaRejection, pf2_SCIRejection
|
| ROI construction |
pf2_build_nanmean_ROI, pf2_build_pca_ROI
|
The gold-standard header example is functions/pf2_SMAR.m. See Processing
Pipeline for how these are chained into raw/oxy
methods.
Full field-by-field detail lives on Importing Data and Processing Pipeline; this is the compact map.
| Field | Meaning |
|---|---|
raw [T×C]
|
Raw light intensity. |
time [T×1], fs
|
Time vector (s) and sampling rate (Hz). |
fchMask [1×C]
|
Channel mask (1 = good, 0 = bad). |
markers (table) |
Time, Code, Duration, Amplitude + any extra columns; read by name, never by position. |
info |
Metadata struct; info.markerDict (code→label), info.eventTypes (BIDS). |
device |
pf2.Device object, auto-attached. |
Aux |
Optional typed auxiliary signals (.data, .time, .unit, .varNames, .type, .kind). |
| Field | Meaning |
|---|---|
HbO HbR HbTotal HbDiff CBSI [T×C]
|
Hemoglobin biomarkers. |
units |
Units of biomarker data (µM, or mM·mm if DPFmode='None'). |
DPF_factor |
DPF used in the Beer-Lambert conversion. |
device |
Immutable pf2.Device config. |
processingInfo |
Full processing record (see below), for reproducibility. |
| Field | Meaning |
|---|---|
timestamp |
When processed. |
dpfMode, dpfValue, subjectAge
|
DPF configuration used. |
baselineStart, baselineLength
|
Baseline window used for normalization. |
rawMethod, oxyMethod
|
Named method chains applied at each stage. |
deviceName, samplingRate
|
Device and sampling rate. |
rejectLevel |
Channel rejection threshold. |
- Home — wiki overview and navigation
- Getting Started — two-layer architecture and first run
- Processing Pipeline — the three processing stages in depth
-
Group Analysis — the
exploreFNIRSworkflow end to end - Visualization — every plotting entry point in context
processFNIRS2
Getting Started
Core Workflow
Group Analysis
Visualization & Export
Reference