
NeuroAnalyzer.jl documentation
This documentation has been generated using Documenter.jl.
NeuroAnalyzer
NeuroAnalyzer.na_info — Function
na_info()Show NeuroAnalyzer and imported packages versions.
Arguments
Nothing
Returns
Nothing
NeuroAnalyzer.na_set_colors — Function
na_set_colors(value)Change colors preference.
Arguments
value::Bool: value
Returns
Nothing
NeuroAnalyzer.na_set_exclude_bads — Function
na_set_exclude_bads(value)Change exclude_bads preference.
Arguments
value::Bool: value
Returns
Nothing
NeuroAnalyzer.na_set_prefs — Function
na_set_prefs(; <keyword arguments>)Set and save NeuroAnalyzer preferences.
Arguments
progress_bar::Boolverbose::Boolexclude_bads::Boolcolors::Bool
Returns
Nothing
NeuroAnalyzer.na_set_progress_bar — Function
na_set_progress_bar(value)Change progress_bar preference.
Arguments
value::Bool: value
Returns
Nothing
NeuroAnalyzer.na_set_verbose — Function
na_set_verbose(value)Change verbose preference.
Arguments
value::Bool: value
Returns
Nothing
NeuroAnalyzer.na_version — Function
na_version()Convert NeuroAnalyzer version to string.
Arguments
Nothing
Returns
VER::String
NeuroAnalyzer.na_plugins_install — Function
na_plugins_install(plugin)Install NeuroAnalyzer plugin from remote Git repository or from local .TAR.GZ/.ZIP archive (requires unzip or tar command to be available).
Arguments
plugin::String: plugin Git repository URL or file name (with full path)
Returns
Nothing
NeuroAnalyzer.na_plugins_list — Function
na_plugins_list()List NeuroAnalyzer plugins.
Arguments
Nothing
Returns
Nothing
NeuroAnalyzer.na_plugins_reload — Function
na_plugins_reload()Reload NeuroAnalyzer plugins.
Arguments
Nothing
Returns
Nothing
NeuroAnalyzer.na_plugins_remove — Function
na_plugins_remove(plugin)Remove NeuroAnalyzer plugin.
Arguments
plugin::String: plugin name
Returns
Nothing
NeuroAnalyzer.na_plugins_update — Function
na_plugins_update(plugin)Update NeuroAnalyzer plugin(s).
Arguments
plugin::String: plugin to update; if empty, update all
Returns
Nothing
Utils
Base.size — Function
size(obj)Return the size of the object data array.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Tuple{Int64, Int64, Int64}: (channels, samples, epochs).
size(obj, d)Return the size of the object data array along dimension d.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectd::Int64: dimension index; must be in[1, ndims(obj.data)]
Returns
Int64: size along dimensiond
NeuroAnalyzer.add_note — Function
add_note(obj; <keyword arguments>)Return a copy of obj with the recording note set to note. The original object is not modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnote::String: note text to store
Returns
NeuroAnalyzer.NEURO: new NEURO object with the updated recording note
NeuroAnalyzer.add_note! — Function
add_note!(obj; <keyword arguments>)Set the recording note in obj in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnote::String: note text to store
Returns
Nothing
NeuroAnalyzer.aff_mni2tal — Function
aff_mni2tal(pts)Convert MNI coordinates to Talairach coordinates using an affine transform.
Applies the Brett affine transformation:
x′ = 0.88x − 0.8y′ = 0.97y − 3.32z′ = 0.05y + 0.88z − 0.44
Arguments
pts::Vector{<:Number}: MNI[X, Y, Z]coordinates
Returns
Vector{Float64}: Talairach[X, Y, Z]coordinates
References
Brett M. https://www.brainmap.org/training/BrettTransform.html
NeuroAnalyzer.aff_tal2mni — Function
aff_tal2mni(pts)Convert Talairach coordinates to MNI coordinates using the inverse affine transform.
Applies the inverse of the Brett affine transformation:
x = (x′ + 0.8) / 0.88y = (y′ + 3.32) / 0.97z = (z′ − 0.05y + 0.44) / 0.88
Arguments
pts::Vector{<:Number}: Talairach[X, Y, Z]coordinates
Returns
Vector{Float64}: MNI[X, Y, Z]coordinates
References
Brett M. https://www.brainmap.org/training/BrettTransform.html
NeuroAnalyzer.apply — Function
apply(obj; <keyword arguments>)Apply a custom function to selected channels and epochs of a NEURO object.
The function string f must reference the signal data using the placeholder variable obj, which is substituted at runtime with the actual channel data (a Vector{Float64} representing one channel × one epoch slice).
Example: f = "cumsum(obj)" or f = "obj .^ 2".
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)f::String: Julia expression to evaluate, usingobjas the signal placeholder
Returns
Array{Float64, 3}: result array, shape (channels, epoch length, epochs)
NeuroAnalyzer.areduce — Function
areduce(a, f; <keyword arguments>)Reduce an array by resampling along its second axis at regular intervals of n.
Useful for downsampling a frequency axis (and its associated data) when the number of frequency bins is very large. Only the nearest existing frequency bin to each target frequency is used (via vsearch); no interpolation is performed.
Arguments
a::AbstractArray: 2- or 3-dimensional data array whose second axis corresponds tof, shape(channels, frequencies)or(channels, frequencies, epochs)f::AbstractVector: frequency (or index) vector;length(f)must equalsize(a, 2)n::Float64=0.5: step size between retained values (in the same units asf); smaller values retain more points; larger values reduce more aggressively
Returns
Array{eltype(a), ndims(a)}: deduced data arrayVector{eltype(f)}: reduced frequency vector
NeuroAnalyzer.arr2mat — Function
arr2mat(x)Reshape a 3-D array of shape (1, samples, epochs) into a (epochs, samples) matrix.
Arguments
x::AbstractArray: 3-D input array; first dimension must equal 1
Returns
AbstractMatrix: matrix of shape (size(x, 3), size(x, 2))
NeuroAnalyzer.band_frq — Function
band_frq(obj, band)Return the frequency limits for a named EEG band.
When band = :list, the available band names are printed to stdout and the function returns (0.0, 0.0) as a sentinel (rather than nothing, which would violate the declared return type).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectband::Symbol: band name (see list below or pass:listto print all names)::list:total:delta: 0.1-4.0 Hz:theta: 4.0-8.0 Hz:alpha: 8.0-3.0 Hz:alpha_lower: 8.0-10.5 Hz:alpha_higher: 10.5-13.0 Hz:beta: 14.0-30.0 Hz:beta_lower: 14.0-25.0 Hz:beta_higher: 25.0-30.0 Hz:gamma: 30.0-150.0 Hz:gamma_1: 30.0-40.0 Hz:gamma_2: 40.0-50.0 Hz:gamma_lower: 30.0-80.0 Hz:gamma_higher: 80.0-150.0 Hz
Returns
Tuple{Float64, Float64}:(low_Hz, high_Hz)limits, clamped to the Nyquist frequency if necessary
band_frq(fs, band)Return the frequency limits for a named EEG band.
When band = :list, the available band names are printed to stdout and the function returns (0.0, 0.0) as a sentinel.
Arguments
fs::Int64: sampling rate in Hz; must be ≥ 1band::Symbol: band name (see list below or pass:listto print all names)::list:total:delta: 0.1-4.0 Hz:theta: 4.0-8.0 Hz:alpha: 8.0-3.0 Hz:alpha_lower: 8.0-10.5 Hz:alpha_higher: 10.5-13.0 Hz:beta: 14.0-30.0 Hz:beta_lower: 14.0-25.0 Hz:beta_higher: 25.0-30.0 Hz:gamma: 30.0-150.0 Hz:gamma_1: 30.0-40.0 Hz:gamma_2: 40.0-50.0 Hz:gamma_lower: 30.0-80.0 Hz:gamma_higher: 80.0-150.0 Hz
Returns
Tuple{Float64, Float64}:(low_Hz, high_Hz)limits, clamped to the Nyquist frequency if necessary
NeuroAnalyzer.cextrema — Function
cextrema(x)Return the elements of a complex vector with the largest and smallest magnitudes.
Arguments
x::Vector{ComplexF64}: input complex vector; must not be empty
Returns
Tuple containing:
ComplexF64: element with the largest absolute value (cmax)ComplexF64: element with the smallest absolute value (cmin)
NeuroAnalyzer.channel_cluster — Function
channels_cluster(obj; <keyword arguments>)Return channel names belonging to a predefined spatial cluster.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectcluster::Symbol: cluster name::f1: left frontal (Fp1, F1, F3, F5, F7, F9, AF3, AF7):f2: right frontal (Fp2, F2, F4, F6, F8, F10, AF4, AF8):t1: left temporal (C3, C5, T7, T9, FC3, FC5, FT7, FT9):t2: right temporal (C4, C6, T8, T10, FC4, FC6, FT8, FT10):c1: anterior central (Cz, C1, C2, FC1, FC2, FCz):c2: posterior central (Pz, P1, P2, CP1, CP2, CPz):p1: left parietal (P3, P5, P7, P9, CP3, CP5, TP7, TP9):p2: right parietal (P4, P6, P8, P10, CP4, CP6, TP8, TP10):o: occipital (O1, O2, POz, PO3, PO4, PO7, PO8, PO9, PO10)
Returns
Vector{String}: channel names present in the object that belong to the cluster
NeuroAnalyzer.channel_info — Function
channel_info(obj; <keyword arguments>)Return or print information for a single channel.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelpr::Bool=true: iftrue, print to stdout and returnnothing; iffalse, return the info string
Returns
Nothingwhenpr=true, orStringwhenpr=false.
NeuroAnalyzer.channel_order — Function
channel_order(obj)Return the channel order indices stored in the object header.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Vector{Int64}: channel order indices
NeuroAnalyzer.channel_pick — Function
channel_pick(obj; <keyword arguments>)Return set of channel indices corresponding to a set of electrodes ("pick", e.g. left or frontal electrodes).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"pick::Vector{Symbol}: pick of electrodes; picks may be combined, e.g.[:left, :frontal]:central/:c:left/:l:right/:r:frontal/:f:temporal/:t:parietal/:p:occipital/:o
Returns
Vector{String}: channel names matching the pick
NeuroAnalyzer.chtypes — Function
chtypes(obj)Return channel type strings.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Vector{String}: channel type strings (one per channel)
NeuroAnalyzer.cmax — Function
cmax(x)Return the element of a complex vector with the largest magnitude.
Selects the element that maximises |x|² (equivalent to maximising |x|).
Arguments
x::Vector{ComplexF64}: input complex vector; must not be empty
Returns
ComplexF64: element ofxwith the largest absolute value
NeuroAnalyzer.cmin — Function
cmin(x)Return the element of a complex vector with the smallest magnitude.
Selects the element that minimises |x|² (equivalent to minimising |x|).
Arguments
x::Vector{<:Complex}: input complex vector; must not be empty
Returns
ComplexF64: element ofxwith the smallest absolute value
NeuroAnalyzer.cums — Function
cums(signal)Compute the cumulative sum of a 3-dimensional array along the sample (second) axis.
Arguments
s::Array{<:Real, 3}: input array of shape (channels, samples, epochs)
Returns
Array{Float64, 3}: cumulative sum array of the same shape assignal
NeuroAnalyzer.cwtfrq — Function
cwtfrq(s; <keyword arguments>)Return the mean frequencies of a collection of analytic or real wavelets for a signal of a given length.
The first frequency bin is set to 0.0 Hz because getMeanFreq returns a non-physical low-frequency artifact for the lowest scale.
Arguments
s::AbstractVector: signal vector; used only for its lengthfs::Int64: sampling rate in Hz; must be ≥ 1wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): wavelet to use; see the ContinuousWavelets.jl documentation for the full list of available wavelets
Returns
Vector{Float64}: center frequencies in Hz (rounded to 2 decimal places), length determined by the number of wavelet scales
cwtfrq(s; <keyword arguments>)Return the mean frequencies of a collection of analytic or real wavelets for a 3-D signal array.
Delegates to the vector method using the first channel and first epoch s[1, :, 1] to determine the wavelet frequency grid (all channels and epochs share the same grid for a fixed signal length).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): wavelet to use; see the ContinuousWavelets.jl documentation for the full list of available wavelets
Returns
Vector{Float64}: center frequencies in Hz (rounded to 2 decimal places)
cwtfrq(obj; <keyword arguments>)Return the mean frequencies of a collection of analytic or real wavelets for a NEURO object.
Uses the first channel and first epoch to determine the wavelet frequency grid.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectwt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): wavelet to use; see the ContinuousWavelets.jl documentation for the full list of available wavelets
Returns
Vector{Float64}: center frequencies in Hz (rounded to 2 decimal places)
NeuroAnalyzer.datatype — Function
datatype(obj)Return the data type string of the object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
String: data type (e.g."eeg","meg","nirs").
NeuroAnalyzer.delete_note — Function
delete_note(obj)Return a copy of obj with the recording note cleared. The original object is not modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
NeuroAnalyzer.NEURO: new NEURO object with an empty recording note
NeuroAnalyzer.delete_note! — Function
delete_note!(obj)Clear the recording note in obj in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Nothing
NeuroAnalyzer.describe — Function
describe(obj; <keyword arguments>)Print or return descriptive statistics for each channel.
Statistics reported: range, mean, SD, minimum, Q1 (25th percentile), median, Q3 (75th percentile), maximum.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdf::Bool=false: iftrue, return statistics as aDataFrame; otherwise print a formatted table and returnnothing
Returns
Nothingwhendf=false, or aDataFramewhendf=true
NeuroAnalyzer.detector_labels — Function
detector_labels(obj)Return detector labels (NIRS objects only).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"nirs"
Returns
Vector{String}: detector label strings
NeuroAnalyzer.e2t — Function
e2t(obj; <keyword arguments>)Return the time segment in seconds spanning a contiguous range of epoch indices. The returned segment runs from the start of ep[1] to the end of ep[end].
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep::Union{Int64, Vector{Int64}: epoch index or vector of epoch indices
Returns
Tuple{Float64, Float64}:(start_time, end_time)in seconds
NeuroAnalyzer.epoch_duration — Function
epoch_duration(obj)Return the epoch duration in seconds.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Float64: duration of one epoch in seconds
NeuroAnalyzer.epoch_len — Function
epoch_len(obj)Return the epoch length in samples.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Int64: number of samples per epoch (second data dimension)
NeuroAnalyzer.f2t — Function
f2t(f)Convert a frequency in Hz to a cycle length in milliseconds.
Computes 1000 / f, rounded to 2 decimal places.
Arguments
f::Real: frequency in Hz; must be > 0
Returns
Float64: cycle length in ms
NeuroAnalyzer.fft0 — Function
fft0(x, n)Perform a zero-padded full (two-sided) FFT.
Appends n zeros to x before computing the FFT. When n = 0 the input is transformed directly, avoiding an unnecessary copy.
Arguments
x::AbstractVector: signal vector of lengthLn::Int64: number of zeros to append; must be ≥ 0.
Returns
Vector{ComplexF64}: two-sided Fourier coefficients of lengthL + n.
NeuroAnalyzer.fft2 — Function
fft2(x)Perform a full (two-sided) FFT after zero-padding the input to the next power of 2.
Zero-padding to a power-of-2 length maximizes FFT efficiency (radix-2 algorithm). If length(x) is already a power of 2, no padding is added.
Arguments
x::AbstractVector: signal vector of lengthL
Returns
Vector{ComplexF64}: two-sided Fourier coefficients of lengthnextpow2(L)
NeuroAnalyzer.findpeaks — Function
findpeaks(signal; <keyword arguments>)Find the indices of local peaks in a 1-D signal.
Peaks are detected using findpeaks1d and a minimum separation of d samples is enforced between consecutive peaks (non-maximum suppression).
Arguments
signal::AbstractVector: signal vectord::Int64=32: minimum distance between consecutive peaks in samples; must be ≥ 1
Returns
Vector{Int64}: indices of detected peaks insignal, sorted in ascending order
NeuroAnalyzer.fir_order_bw — Function
fir_order_bw(; <keyword arguments>)Calculate the order of a FIR filter using the Harris formula.
The formula is: n = round((a × fs) / (22 × bw)), where 22 is the Harris empirical constant relating attenuation, bandwidth, and sample rate.
Arguments
bw::Real: transition band width in Hz; must be > 0.a::Real=60: attenuation in dB; must be > 0fs::Int64: sampling rate in Hz; must be > 0
Returns
Int64: estimated FIR filter order
fir_order_bw(obj; <keyword arguments>)Calculate the order of a FIR filter using the Harris formula.
Convenience wrapper that reads the sampling rate from obj.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectbw::Real: transition band width in Hz; must be > 0a::Real=60: attenuation in dB; must be > 0
Returns
Int64: estimated FIR filter order
NeuroAnalyzer.fir_order_f — Function
fir_order_f(; <keyword arguments>)Calculate a recommended FIR filter order range from the lower frequency bound.
The rule of thumb is that the filter should span 4–5 full cycles of the lowest frequency of interest. The range is returned as (4 × n_samples, 5 × n_samples), where n_samples is the number of samples in one cycle of f.
Arguments
fs::Int64: sampling rate in Hz; must be > 0f::Real: lower frequency bound of the analyzed range in Hz; must be > 0
Returns
Tuple{Int64, Int64}: recommended filter order range (lowerorder, upperorder)
fir_order_f(obj; <keyword arguments>)Calculate a recommended FIR filter order range from the lower frequency bound.
Convenience wrapper that reads the sampling rate from obj.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectf::Real: lower frequency bound of the analyzed range in Hz; must be > 0
Returns
Tuple{Int64, Int64}:(lower_order, upper_order)recommended filter order range
NeuroAnalyzer.f_nearest — Function
f_nearest(m, pos)Find the matrix position closest to a query position tuple.
Computes the Euclidean distance from every element of m to p and returns the row and column indices of the nearest element.
Arguments
m::Matrix{Tuple{Float64, Float64}}: matrix of 2-D position tuplesp::Tuple{Float64, Float64}: query position
Returns
Tuple{Int64, Int64}:(row, column)of the nearest position inm
NeuroAnalyzer.freqs — Function
freqs(t; nf)Return the frequency vector and Nyquist frequency for a time vector.
The sampling rate is inferred as 1 / (t[2] - t[1]).
Arguments
t::AbstractVector, AbstractRange}: time vector; must contain at least 2 elementsnf::Bool=false: iftrue, return both negative and positive frequencies (viafftfreq+fftshift); iffalse, return positive frequencies only (viarfftfreq)
Returns
Vector{Float64}: frequency vector in Hz, rounded to 3 decimal placesFloat64: Nyquist frequency in Hz
freqs(s, fs; <keyword arguments>)Return the frequency vector and Nyquist frequency for a signal vector.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1nf::Bool=false: iftrue, return both negative and positive frequencies (viafftfreq+fftshift); iffalse, return positive frequencies only (viarfftfreq)
Returns
Vector{Float64}: frequency vector in Hz, rounded to 3 decimal placesFloat64: Nyquist frequency in Hz
freqs(n, fs; <keyword arguments>)Return the frequency vector and Nyquist frequency for a signal of n samples.
Arguments
n::Int64: number of samples; must be ≥ 1fs::Int64: sampling rate in Hz; must be ≥ 1nf::Bool=false: iftrue, return both negative and positive frequencies (viafftfreq+fftshift); iffalse, return positive frequencies only (viarfftfreq)
Returns
Vector{Float64}: frequency vector in Hz, rounded to 3 decimal placesFloat64: Nyquist frequency in Hz
freqs(obj; <keyword arguments>)Return the frequency vector and Nyquist frequency for a NEURO object.
Uses the first channel and first epoch of obj to infer signal length, and reads the sampling rate via sr(obj).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnf::Bool=false: iftrue, return both negative and positive frequencies; iffalse, return positive frequencies only
Returns
Vector{Float64}: frequency vector in Hz, rounded to 3 decimal placesFloat64: Nyquist frequency in Hz
NeuroAnalyzer.fwhm — Function
fwhm(s)Calculate the indices of the full-width at half-maximum (FWHM) points of a Gaussian-like signal.
Arguments
s::AbstractVector: signal vector; must contain at least 2 elements
Returns
Int64: index of the pre-peak half-maximum pointInt64: index of the signal peakInt64: index of the post-peak half-maximum point
Notes
- The input
sis normalized internally; the original vector is not modified. - For noisy or non-unimodal signals,
vsearchmay return the index of the closest sample to 0.5 rather than a true half-maximum crossing.
NeuroAnalyzer.generate_cosine — Function
generate_cosine(f, t, a, p)Generate a cosine wave.
Computes a × cos(2πft + φ) where φ = deg2rad(p).
Arguments
f::Real: frequency in Hzt::AbstractVector: time vector in secondsa::Real: amplitude; the signal ranges over[-a, +a]p::Real: phase shift in degrees
Returns
Vector{Float64}: cosine wave sampled at the points int
NeuroAnalyzer.generate_csine — Function
generate_csine(f, t, a)Generate a complex sine wave (complex exponential).
Computes a × exp(i × 2πft).
Arguments
f::Real: frequency in Hzt::AbstractVector: time vector in secondsa::Real: amplitude; the signal ranges over[-a, +a]
Returns
Vector{ComplexF64}: complex exponential sampled at the points int
NeuroAnalyzer.generate_gaussian — Function
generate_gaussian(fs, f, t; <keyword arguments>)Generate a Gaussian envelope.
The standard deviation of the Gaussian is σ = ncyc / (2πf). The time axis spans −t : 1/fs : t.
Arguments
fs::Int64: sampling rate in Hz; must be ≥ 1f::Real: frequency in Hz; determines the Gaussian width viaσ = ncyc / (2πf)t::Real=1: half-length of the time axis in seconds; must be > 0ncyc::Int64: : number of cycles; controls the width (SD) of the Gaussian; must be ≥ 1a::Real=1.0: peak amplitude
Returns
Vector{Float64}: Gaussian envelope of lengthlength(-t:1/fs:t)
NeuroAnalyzer.generate_morlet — Function
generate_morlet(fs, f, t; <keyword arguments>)Generate a Morlet wavelet.
The wavelet is the product of a complex (or real) sine wave at frequency f and a Gaussian envelope whose width is determined by ncyc. The time axis spans −t : 1/fs : t.
Arguments
fs::Int64: sampling rate in Hz; must be ≥ 1f::Real: centre frequency in Hzt::Real=1: half-length of the wavelet in seconds; must be > 0ncyc::Int64=5: number of cycles; controls the Gaussian width; must be ≥ 1complex::Bool=false: iftrue, return a complex Morlet; otherwise return the real part only
Returns
Union{Vector{Float64}, Vector{ComplexF64}}: Morlet wavelet of lengthlength(-t:1/fs:t)
NeuroAnalyzer.generate_morlet_fwhm — Function
generate_morlet_fwhm(fs, f, t; <keyword arguments>)Generate a complex Morlet wavelet parameterized by full-width at half-maximum (FWHM).
Uses the FWHM-based Gaussian envelope exp(−4 ln 2 × t² / h²) instead of a cycle-count parameter, providing more intuitive control over time–frequency resolution.
Arguments
fs::Int64: sampling rate in Hz; must be ≥ 1f::Real: centre frequency in Hzt::Real=1: half-length of the wavelet in seconds; must be > 0h::Float64=0.25: full-width at half-maximum of the Gaussian envelope in seconds; must be > 0
Returns
Vector{ComplexF64}: complex Morlet wavelet of lengthlength(-t:1/fs:t)
References
Cohen MX. A better way to define and describe Morlet wavelets for time-frequency analysis. NeuroImage. 2019 Oct;199:81–6.
NeuroAnalyzer.generate_noise — Function
generate_noise(n, a; <keyword arguments>)Generate a noise signal.
The raw noise is normalized to [−1, 1] and then scaled by a.
Arguments
n::Int64: number of samples; must be ≥ 1a::Real=1.0: amplitude; the output ranges over[-a, +a]type::Symbol=:whiten: noise type::whiten: white noise (normally distributed):whiteu: white noise (uniformly distributed):pink: pink (1/f²) noise.
Returns
Vector{Float64}: noise signal of lengthn
NeuroAnalyzer.generate_signal — Function
generate_signal(n, a)Generate a random walk signal based on cumulative normally distributed noise.
The cumulative sum introduces temporal autocorrelation, producing a Brownian-motion–like signal. The result is normalized to [−1, 1] and scaled by a.
Arguments
n::Int64: number of samples; must be ≥ 1a::Real=1.0: amplitude; the output ranges over[-a, +a]
Returns
Vector{Float64}: random walk signal of lengthn
NeuroAnalyzer.generate_sinc — Function
generate_sinc(t; <keyword arguments>)Generate a sinc function.
Produces either the normalized (sin(2πf(t−peak)) / (π(t−peak))) or unnormalized (sin(2f(t−peak)) / (t−peak)) sinc. The singularity at t = peak is resolved by linear interpolation from the two neighboring samples.
Arguments
t::AbstractVector=-2:0.01:2: time vector- `f::Real=1.0: frequency in Hz
peak::Real=0: time of the sinc peak (location of the singularity)norm::Bool=true: iftrue, generate the normalized sinc; otherwise generate the unnormalized sinc
Returns
Vector{Float64}: sinc function sampled at the points int
NeuroAnalyzer.generate_sine — Function
generate_sine(f, t, a, p)Generate a sine wave.
Computes a × sin(2πft + φ) where φ = deg2rad(p).
Arguments
f::Real: frequency in Hzt::AbstractVector: time vector in secondsa::Real: amplitude; the signal ranges over[-a, +a]p::Real: phase shift in degrees
Returns
Vector{Float64}: sine wave sampled at the points int
NeuroAnalyzer.generate_square — Function
generate_square(t, a, p; <keyword arguments>)Generate a square wave.
Arguments
t::AbstractVector: time vectora::Real: amplitude scaling factorp::Real: phase (horizontal shift of the wave) = duty cyclew::Real: width = duty-cycle threshold; samples wheremod(p + t, 2) > ware highoffset::Real=0: vertical amplitude offset
Returns
Vector{Float64}: square wave sampled at the points int
NeuroAnalyzer.generate_triangle — Function
generate_triangle(t, a)Generate a triangle wave.
Computes a × |mod(t, 2) − 1|, which produces a symmetric triangle wave with period 2 and amplitude a.
Arguments
t::AbstractVector: time vectora::Real: amplitude scaling factor
Returns
Vector{Float64}: triangle wave sampled at the points int
NeuroAnalyzer.generate_window — Function
generate_window(type, n; <keyword arguments>)Return an n-point symmetric window of the given type.
Arguments
type::Symbol: window type::hann: Hann:bh: Blackman-Harris:bohman: Bohman:flat: Flat-top:bn: Blackman-Nuttall:nutall: Nuttall:triangle: symmetric triangle (left half ↑, right half ↓):exp: symmetric exponential (left half ↑, right half ↓)
n::Int64: window length in samples; must be ≥ 1even::Bool=false: iftrue, andnis odd, incrementnby 1 to enforce even length
Returns
Vector{Float64}: generated window of lengthn(orn + 1ifeven=trueandnwas odd)
NeuroAnalyzer.get_channel — Function
get_channel(obj; <keyword arguments>)Return list of channel names of specified type or their numbers if names are specified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}="": channel name or list of channel namestype::Union{String, Vector{String}}="all": channels typeswl::Real: return NIRS channels for wavelength (in nm)exclude::Union{String, Vector{String}, Regex}="": channel name or list of channel names to exclude from the list
Returns
ch::Union{Vector{String}, Vector{Int64}}
NeuroAnalyzer.gradient — Function
gradient(x; <keyword arguments>)Calculate the gradient of a 1-dimensional scalar field.
Each element of the returned vector field grad_vf is a 1-element Vector{Float64} giving the gradient direction at that position. grad_mag contains the corresponding gradient magnitudes.
Arguments
x::AbstractVector: 1-D scalar fieldrev::Bool=false: iffalse(default), the gradient direction points toward the maximum value; iftrue, it points toward the minimum value
Returns
Named tuple:
grad_vf::Vector{Vector{Float64}}: vector field of gradients (one gradient vector per element)grad_mag::Vector{Float64}: scalar field of gradient magnitudes
gradient(x; <keyword arguments>)Calculate the gradient of a 2-dimensional scalar field.
Each element of the returned matrix field grad_vf is a 2-element Vector{Float64} giving the gradient direction (row, column) at that position. grad_mag contains the corresponding gradient magnitudes.
Arguments
x::AbstractMatrix: 2-D scalar fieldrev::Bool=false: iffalse(default), the gradient direction points toward the maximum value; iftrue, it points toward the minimum value
Returns
Named tuple:
grad_vf::Matrix{Vector{Float64}}: vector field of gradients (one gradient vector per element)grad_mag::Matrix{Float64}: scalar field of gradient magnitudes
gradient(x; <keyword arguments>)Calculate the gradient of a 3-or-higher-dimensional scalar field.
Dispatches when x is neither a vector nor a matrix (i.e. ndims(x) ≥ 3). Each element of the returned array field grad_vf is an ndims(x)-element Vector{Float64} giving the gradient direction at that position. grad_mag contains the corresponding gradient magnitudes.
Arguments
x::AbstractArray: scalar field withndims(x) ≥ 3rev::Bool=false: iffalse(default), the gradient direction points toward the maximum value; iftrue, it points toward the minimum value
Returns
Named tuple:
grad_vf::Array{Vector{Float64}, 3}: vector field of gradientsgrad_mag::Array{Float64, 3}: scalar field of gradient magnitudes
NeuroAnalyzer.header — Function
header(obj; <keyword arguments>)Print object header metadata to stdout.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Nothing
NeuroAnalyzer.history — Function
history(obj)Return the processing history log.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Vector{String}: list of processing steps applied to the object
NeuroAnalyzer.hz2rads — Function
hz2rads(f)Convert a frequency from Hz to rad/s.
Computes 2π × f.
Arguments
f::Real: frequency in Hz
Returns
Float64: frequency in rad/s
NeuroAnalyzer.ifft0 — Function
ifft0(x, n)Perform an IFFT on a zero-padded spectrum and trim the result to the original signal length.
If a signal of length L was zero-padded by n samples before the forward FFT, the padded spectrum has length L + n. This function recovers the original L-sample signal by discarding the trailing n samples after the IFFT.
Arguments
x::AbstractVector: zero-padded spectrum (lengthL + n)n::Int64: number of zeros that were appended during the forward FFT; must be ≥ 0
Returns
Vector{ComplexF64}: reconstructed signal of lengthlength(x) - n
NeuroAnalyzer.iir_order — Function
iir_order(; <keyword arguments>)Calculate the minimum order of an IIR filter meeting the given specifications.
Pass-band and stop-band edges are derived from cutoff and bw:
- For
:lp/:hp: pass edge =cutoff ± bw/2, stop edge =cutoff ∓ bw/2. - For
:bp/:bs: inner edges shifted inward bybw/2, outer edges shifted outward bybw/2.
The order is estimated via the appropriate DSP.jl design function (buttord, cheb1ord, cheb2ord, or ellipord).
Arguments
fprototype::Symbol: filter prototype::butterworth:chebyshev1:chebyshev2:elliptic
ftype::Symbol: filter type::lp: low-pass:hp: high-pass:bp: band-pass:bs: band-stop
cutoff::Union{Real, Tuple{Real, Real}}: cutoff frequency in Hz; scalar for:lp/:hp; two-element tuple for:bp/:bsbw::Real: transition band width in Hz; must be > 0rp::Union{Nothing, Real}=nothing: pass-band ripple in dB; defaults to 0.5 dBrs::Union{Nothing, Real}=nothing: stop-band ripple in dB; defaults to 20 dBfs::Int64: sampling rate in Hz; must be > 0
Returns
order::Int64: minimum filter order satisfying the specifications
iir_order(obj; <keyword arguments>)Calculate the minimum order of an IIR filter meeting the given specifications.
Convenience wrapper that reads the sampling rate from obj.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfprototype::Symbol: filter prototype::butterworth:chebyshev1:chebyshev2:elliptic
ftype::Symbol: filter type::lp: low-pass:hp: high-pass:bp: band-pass:bs: band-stop
cutoff::Union{Real, Tuple{Real, Real}}: cutoff frequency in Hz; scalar for:lp/:hp; two-element tuple for:bp/:bsbw::Real: transition band width in Hz; must be > 0rp::Union{Nothing, Real}=nothing: pass-band ripple in dB; defaults to 0.5 dBrs::Union{Nothing, Real}=nothing: stop-band ripple in dB; defaults to 20 dB
Returns
Int64: minimum filter order satisfying the specifications
NeuroAnalyzer.info — Function
info(obj; <keyword arguments>)Print object metadata and channel table. Optionally return data as a DataFrame.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdf::Bool=false: iftrue, return the signal data reshaped into aDataFramewith columns:timeand one column per channel label
Returns
Nothingifdf=false, or aDataFrameifdf=true.
NeuroAnalyzer.l1 — Function
l1(a1, a2)Compare two arrays using the L1 (Manhattan) distance.
Computes ∑|a1ᵢ - a2ᵢ| element-wise.
Suitable for comparing spectrograms, feature maps, or any same-shaped numeric arrays.
Arguments
a1::AbstractArray: first arraya2::AbstractArray: second array; must be the same size asa1.
Returns
Float64: L1 distance betweena1anda2
NeuroAnalyzer.l2 — Function
l2(a1, a2)Compare two arrays using the L2 (Euclidean) distance.
Computes √∑(a1ᵢ - a2ᵢ)² element-wise via Distances.euclidean.
Suitable for comparing spectrograms, feature maps, or any same-shaped numeric arrays.
Arguments
a1::AbstractArray: first arraya2::AbstractArray: second array; must be the same size asa1
Returns
Float64: L2 distance betweena1anda2.
NeuroAnalyzer.labels — Function
labels(obj)Return channel labels.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Vector{String}: channel label strings
NeuroAnalyzer.linspace — Function
linspace(start, stop, length)Return a vector of n evenly spaced numbers from start to stop (inclusive).
Thin wrapper around Base.range that always materialises the result as a Vector{Float64}.
Arguments
start::Real: start of the sequencestop::Real: end of the sequence (inclusive)n::Int64: number of points; must be ≥ 2
Returns
Vector{Float64}: linearly spaced sequence of lengthn
NeuroAnalyzer.logspace — Function
logspace(start, stop, n)Return a vector of n logarithmically spaced numbers from start to stop (inclusive).
Requires start > 0 and stop > 0 (logarithmic spacing is undefined for non-positive values).
Arguments
start::Real: start of the sequence; must be > 0stop::Real: end of the sequence (inclusive); must be > 0n::Int64: number of points; must be ≥ 2
Returns
Vector{Float64}: logarithmically spaced sequence of lengthn
NeuroAnalyzer.markers_s2t — Function
markers_s2t(m; <keyword arguments>)Return a copy of a markers DataFrame with :start and :length columns converted from sample numbers to seconds.
Arguments
m::DataFrame: markers DataFrame containing integer:startand:lengthcolumnsfs::Int64: sampling rate in Hz; must be ≥ 1
Returns
DataFrame: new DataFrame with:startand:lengthexpressed in seconds
markers_s2t(obj; <keyword arguments>)Return a copy of the object's markers DataFrame with :start and :length converted from sample numbers to seconds.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
DataFrame: new DataFrame with:startand:lengthexpressed in seconds
NeuroAnalyzer.markers_s2t! — Function
markers_s2t!(m; <keyword arguments>)Convert :start and :length columns of a markers DataFrame from sample numbers to seconds, in-place.
Arguments
m::DataFrame: markers DataFrame; modified in-placefs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Nothing
markers_s2t!(obj; <keyword arguments>)Convert :start and :length columns of the object's markers DataFrame from sample numbers to seconds, in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Nothing
NeuroAnalyzer.maxat — Function
maxat(x, y)Find the maximum value of x and return the corresponding value from y at that index.
Argument
x::AbstractVector: vector to find the maximum of; must not be emptyy::AbstractVector: vector to read the value from; must be the same length asx
Returns
Real:y[idx]whereidx = argmin(x)Int64: index of the maximum value inx
NeuroAnalyzer.meshgrid — Function
meshgrid(x)Build a 2-D mesh grid from two coordinate vectors.
Returns a pair (mx, my) where mx[i] repeats the full x vector for row i, and my[i] repeats y[i] across all columns. This matches the convention of MATLAB's meshgrid / NumPy's meshgrid(..., indexing="xy").
Arguments
x::Vector{Float64}: x-coordinate vector of lengthny::Vector{Float64}: y-coordinate vector of lengthm
Returns
Tuple{Vector{Vector{Float64}}, Vector{Vector{Float64}}}:mx:mrepetitions ofx(one per row)my:mvectors each filled with the correspondingy[i]value
NeuroAnalyzer.minat — Function
minat(x, y)Find the minimum value of x and return the corresponding value from y at that index.
Argument
x::AbstractVector: vector to find the minimum of; must not be emptyy::AbstractVector: vector to read the value from; must be the same length asx
Returns
Real:y[idx]whereidx = argmin(x)Int64: index of the minimum value inx
NeuroAnalyzer.mni2tal — Function
mni2tal(pts)Convert MNI coordinates to Talairach coordinates using the non-linear Brett transform.
The transform is piecewise-linear in z:
- z ≥ 0 (above the AC–PC plane):
x′ = 0.99x,y′ = 0.9688y + 0.046z,z′ = −0.0485y + 0.9189z - z < 0 (below the AC–PC plane):
x′ = 0.99x,y′ = 0.9688y + 0.042z,z′ = −0.0485y + 0.839z
Arguments
pts::Vector{<:Number}: MNI[X, Y, Z]coordinates
Returns
Vector{Float64}: Talairach[X, Y, Z]coordinates
References
Brett M. https://www.brainmap.org/training/BrettTransform.html
NeuroAnalyzer.m_norm — Function
m_norm(m)Normalize an array by the number of columns minus one (size(m, 2) - 1).
Arguments
m::AbstractArray: input array; must have at least 2 columns
Returns
AbstractArray: array divided element-wise bysize(m, 2) - 1
NeuroAnalyzer.m_pad0 — Function
m_pad0(m)Pad a matrix with zeros to make it square.
Adds zero columns if the matrix has more rows than columns, or zero rows if it has more columns than rows. Returns the matrix unchanged if it is already square.
Arguments
m::AbstractMatrix: input matrix
Returns
AbstractMatrix: square matrix of sizemax(r, c) × max(r, c)with the same element type asm.
m_pad0(m, r, c)Pad a matrix with zeros to reach the target size r × c.
Rows are appended to the bottom and columns to the right as needed. At least one of r, c must be strictly larger than the corresponding dimension of m.
Arguments
m::AbstractMatrix: input matrixr::Int64: target number of rows; must be ≥size(m, 1)c::Int64: target number of columns; must be ≥size(m, 2)
Returns
AbstractMatrix: matrix of sizer × cpadded with zeros of the same element type asm
NeuroAnalyzer.m_sort — Function
m_sort(m, m_idx; <keyword arguments>)Sort a matrix using a pre-computed permutation index vector.
Arguments
m::AbstractMatrix: input matrixm_idx::Vector{Int64}: permutation index vector (e.g. fromsortperm); this vector is not modified by the functionrev::Bool=false: iftrue, reverse the permutation before applying itdims::Int64=1: apply permutation along columns (dims=1) or rows (dims=2)
Returns
AbstractMatrix: sorted matrix with the same size and element type asm
NeuroAnalyzer.m_sortperm — Function
m_sortperm(m; <keyword arguments>)Return the sorting permutation indices of a matrix column-wise or row-wise.
Arguments
m::AbstractMatrix: input matrixrev::Bool: iftrue, sort in descending orderdims::Int64=1: sort along columns (dims=1) or rows (dims=2)
Returns
Matrix{Int64}: index matrix of the same size asm; each column (or row) contains the permutation that would sort that column (or row)
NeuroAnalyzer.nchannels — Function
nchannels(obj; <keyword arguments>)Return the number of channels of a given type.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objecttype::String="all": channel type string (must be one of the values in the globalchannel_typesconstant); use"all"to count every channel.
Returns
Int64: number of channels of the requested type
NeuroAnalyzer.nepochs — Function
nepochs(obj)Return the number of epochs.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Int64: number of epochs (third data dimension)
NeuroAnalyzer.nextpow2 — Function
nextpow2(x)Return the smallest power of 2 that is ≥ x.
Thin wrapper around Base.nextpow(2, x) with an explicit positivity guard.
Arguments
x::Int64: input value; must be > 0
Examples
nextpow2(5) # → 8
nextpow2(8) # → 8
nextpow2(9) # → 16NeuroAnalyzer.ntapers — Function
ntapers(obj; <keyword arguments>)Return the recommended number of Slepian tapers for multi-taper spectral analysis.
The formula is nt = floor(df × T) - 1, where T = epoch_len / fs is the epoch duration in seconds. The result is clamped to a minimum of 1.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdf::Real: desired frequency resolution (bandwidth) in Hz; must be > 0; this is the minimum separation between frequency peaks to be resolved
Returns
Int64: recommended number of Slepian tapers (≥ 1)
NeuroAnalyzer.optode_labels — Function
optode_labels(obj)Return optode labels (NIRS objects only).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"nirs"
Returns
Vector{String}: optode label strings
NeuroAnalyzer.pad0 — Function
pad0(x, n)Append n zeros along the second axis (or at the end for 1-D input). Works with 1-, 2-, and 3-dimensional arrays. The zero values match the element type of x.
Arguments
x::Union{AbstractVector, AbstractArray}: input array; must be 1-, 2-, or 3-dimensionaln::Int64: number of zeros to append; must be ≥ 0
Returns
Union{AbstractVector, AbstractArray}: padded array with the same number of dimensions asx
NeuroAnalyzer.pad2 — Function
pad2(x)Pad an array with zeros along its second axis to the next power-of-2 length. Works with 1-, 2-, and 3-dimensional arrays. If the relevant dimension is already a power of 2, the array is returned unchanged.
Arguments
x::Union{AbstractVector, AbstractArray}: input array; must be 1-, 2-, or 3-dimensional
Returns
Union{AbstractVector, AbstractArray}: padded array whose second dimension (or length, for 1-D) is a power of 2
NeuroAnalyzer.padm — Function
padm(x, n)Pad an array with mean values along its second axis (or at the end for 1-D input). Works with 1-, 2-, and 3-dimensional arrays.
Arguments
x::Union{AbstractVector, AbstractArray}: input array; must be 1-, 2-, or 3-dimensionaln::Int64: number of mean-value samples to append; must be ≥ 0mode::Symbol=:row: how the mean is computed for 2-D and 3-D arrays::all: single mean of all elements:row: separate mean per row (broadcasts across the padded columns)
Returns
Union{AbstractVector, AbstractArray}: padded array with the same number of dimensions asx
NeuroAnalyzer.paired_labels — Function
paired_labels(l; <keyword arguments>)Generate all ordered pairwise label combinations from a single label vector.
Arguments
l::Vector{String}: input label vector; must not be emptyunq::Bool=true: iftrue, exclude self-pairs ("label1-label1")
Returns
Vector{String}: ordered paired labels
paired_labels(l1, l2)Generate element-wise paired labels from two label vectors of equal length.
Arguments
l1::Vector{String}: first label vector; must not be emptyl2::Vector{String}: second label vector; must have the same length asl1
Returns
Vector{String}: element-wise paired labels of lengthlength(l1)
NeuroAnalyzer.perm_cmp — Function
perm_cmp(a1, a2; <keyword arguments>)Compare two 3-dimensional arrays using a permutation-based statistic.
Randomly shuffles the combined pool of epochs perm_n times, splits each shuffle into two equal halves, and builds a null distribution of difference maps. The real difference map is then Z-scored against this null distribution and thresholded at the Z-value corresponding to p.
Arguments
a1::Array{<:Real, 3}: first array (e.g. spectrogram), shape(freq, time, epochs)a2::Array{<:Real, 3}: second array; must matcha1in size.p::Float64=0.05: two-tailed p-value threshold (must be in(0, 1))perm_n::Int64=1000: number of permutations (must be > 0)
Returns
Named tuple:
zmap::Matrix{Float64}: Z-scored difference map(a2 mean − a1 mean)normalized by the permutation null distributionbm::BitMatrix: Boolean mask wheretrueindicates a statistically significant position (|z| ≥ zval)
NeuroAnalyzer.phases — Function
phases(s)Compute the instantaneous phase of a signal via the Hilbert transform. The analytic signal is obtained as z = DSP.hilbert(s), then the wrapped instantaneous phase is extracted as φ(t) = angle(z(t)) = atan(imag(z), real(z)).
For the unwrapped phase (suitable for differentiating to obtain instantaneous frequency) apply DSP.unwrap to the output.
Arguments
s::AbstractVector: signal vector; must contain at least 1 element
Returns
Vector{Float64}: instantaneous phase in radians ∈ (−π, π]
NeuroAnalyzer.play — Function
play(obj; <keyword arguments>)Play a channel signal segment as audio.
The signal is normalized to [−1, 1] and scaled to [−1000, +1000] before playback. For best results the channel should contain an audio-range signal (e.g. speech, auditory ERP); arbitrary EEG/MEG data will be audible but may not be meaningful.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelseg::Tuple{Real, Real}: time segment to play in seconds, as(start, stop); both values must lie within the epoch time rangeep::Int64: epoch index
Returns
Nothing
NeuroAnalyzer.rads2hz — Function
rads2hz(f)Convert a frequency from rad/s to Hz.
Computes f / 2π.
Arguments
f::Real: frequency in rad/s
Returns
Float64: frequency in Hz
NeuroAnalyzer.rfft0 — Function
rfft0(x, n)Perform a zero-padded one-sided (real) FFT.
Appends n zeros to x before computing rfft, returning only the positive-frequency coefficients. When n = 0 the input is transformed directly, avoiding an unnecessary copy.
Arguments
x::AbstractVector: signal vector of lengthLn::Int64: number of zeros to append; must be ≥ 0.
Returns
Vector{ComplexF64}: one-sided Fourier coefficients of length(L + n) ÷ 2 + 1
NeuroAnalyzer.rfft2 — Function
rfft2(x)Perform a one-sided (real) FFT after zero-padding the input to the next power of 2.
Zero-padding to a power-of-2 length maximizes FFT efficiency (radix-2 algorithm). If length(x) is already a power of 2, no padding is added.
Arguments
x::AbstractVector: signal vector of lengthL
Returns
Vector{ComplexF64}: one-sided Fourier coefficients of lengthnextpow2(L) ÷ 2 + 1
NeuroAnalyzer.s2t — Function
s2t(s, fs)Convert a sample number to time in seconds.
Sample numbering starts at 1: sample 1 maps to t = 0.0. Passing s = 0 is invalid; a warning is emitted and s is silently clamped to 1.
Arguments
s::Real: sample number; must be ≥ 1 (or 0, which is clamped with a warning)fs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Float64: time in seconds (rounded to 4 decimal places)
s2t(obj; <keyword arguments>)Convert a sample number to time in seconds using the object's sampling rate.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objects::Int64: sample number; must be ≥ 1
Returns
Float64: time in seconds
NeuroAnalyzer.signal_duration — Function
signal_duration(obj)Return the total signal duration in seconds.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Float64: duration in seconds
NeuroAnalyzer.signal_len — Function
signal_len(obj)Return the total signal length in samples (across all epochs).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Int64: total number of samples; for a 3-D array this equalsepoch_len × nepochs
NeuroAnalyzer.source_labels — Function
source_labels(obj)Return source labels (NIRS objects only).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"nirs"
Returns
Vector{String}: source label strings
NeuroAnalyzer.sr — Function
sr(obj)Return the sampling rate of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Int64: sampling rate in Hz
NeuroAnalyzer.t2f — Function
t2f(t)Convert a cycle length in milliseconds to a frequency in Hz.
Computes 1000 / t, rounded to 2 decimal places.
Arguments
t::Real: cycle length in ms; must be > 0
Returns
Float64: frequency in Hz
NeuroAnalyzer.t2s — Function
t2s(t, fs)Convert a time in seconds to the nearest sample number.
Sample numbering starts at 1: t = 0 maps to sample 1, and any positive time is rounded up via ceil.
Arguments
t::Real: time in seconds; must be ≥ 0fs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Int64: sample number (≥ 1)
t2s(obj; <keyword arguments>)Convert a time in seconds to a sample number using the object's sampling rate.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectt::Real: time in seconds; must be ≥ 0
Returns
Int64: sample number (≥ 1)
NeuroAnalyzer.tal2mni — Function
tal2mni(pts)Convert Talairach coordinates to MNI coordinates using the inverse non-linear Brett transform.
This is the analytical inverse of mni2tal. The transform is piecewise-linear in z, with the branching threshold applied to the Talairach z coordinate:
z ≥ 0 - inverse of the upper matrix [[0.9688, 0.046], [−0.0485, 0.9189]] (det ≈ 0.8925):
x = x′ / 0.99y = (0.9189 y′ − 0.046 z′) / detz = (0.0485 y′ + 0.9688 z′) / det
z < 0 - inverse of the lower matrix [[0.9688, 0.042], [−0.0485, 0.839]] (det ≈ 0.8151):
x = x′ / 0.99y = (0.839 y′ − 0.042 z′) / detz = (0.0485 y′ + 0.9688 z′) / det
Arguments
pts::Vector{<:Number}: Talairach[X, Y, Z]coordinates
Returns
m::Vector{Float64}: MNI[X, Y, Z]coordinates
References
Brett M. https://www.brainmap.org/training/BrettTransform.html
NeuroAnalyzer.tavg — Function
tavg(s)Average a 3-dimensional signal array across the trial (third) dimension.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
AbstractArray: mean across epochs, shape(channels, samples, 1)
NeuroAnalyzer.to_df — Function
to_df(obj)Export object signal data as a DataFrame.
Each row corresponds to one time point across all epochs (epochs are concatenated). Columns are :time followed by one column per channel, named after the channel labels.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
DataFrame: table withsignal_len(obj)rows andnchannels(obj) + 1columns ([:time, ch1, ch2, …])
Notes
- For multi-epoch objects the time column contains
obj.time_pts, which spans the full concatenated signal, not individual epoch times. - Channel columns are named via
labels(obj); ensure the object has channel labels assigned before calling this function.
NeuroAnalyzer.trtm — Function
trtm(obj; <keyword arguments>)Return a single channel's signal in trials × time format.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj)): epoch numbers; default use all epochs
Returns
Matrix{Float64}: matrix of shape(n_epochs, epoch_len)
NeuroAnalyzer.vec2mat — Function
vec2mat(x; <keyword arguments>)Reshape a vector into a matrix using a sliding window with optional overlap.
The vector is divided into ⌊length(x) / wlen⌋ non-overlapping segments of length wlen. The woverlap parameter shifts the start of each subsequent window backward by that many samples.
Arguments
x::AbstractVector: input vectorwlen::Int64: window length in samples; must be ≥ 1woverlap::Int64: number of overlapping samples between consecutive windows; must satisfy0 ≤ woverlap < wlen
Returns
AbstractMatrix: matrix of shape (n_segments, wlen)
NeuroAnalyzer.view_header — Function
header(obj)Print all keys and values stored in the object header.
Iterates over the :subject, :recording, and :experiment sub-dictionaries of obj.header and prints each key–value pair in the format header.<section>[:<key>]: <value>.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Nothing
NeuroAnalyzer.view_note — Function
view_note(obj)Return the recording note stored in the object header.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
String: recording note (empty string if no note has been set)
NeuroAnalyzer.vreduce — Function
vreduce(x, f; <keyword arguments>)Reduce two same-length vectors by resampling f at regular intervals of n and returning the corresponding values from x.
Useful for downsampling a frequency axis (and its associated data) when the number of frequency bins is large. The nearest existing entry in f is used for each target frequency (via vsearch); no interpolation is performed.
Arguments
x::AbstractVector: data vector (e.g. spectral power); must not be emptyf::AbstractVector: index vector (e.g. frequencies); must have the same length asxn::Float64=0.5: step size for the reduced grid (in the same units asf)
Returns
AbstractVector: reduced data valuesAbstractVector: reduced frequency grid
NeuroAnalyzer.vsearch — Function
vsearch(y, x)Return the index of the first occurrence of string y in vector x, or nothing if y is not present.
Arguments
y::String: value to search forx::Vector{String}: vector to search within
Returns
Union{Int64, Nothing}: index of the first match, ornothingif not found
vsearch(y, x; <keyword arguments>)Return the index of the element in x nearest to scalar y.
Arguments
y::Real: value of interestx::AbstractVector: vector to search within; must not be emptyacc::Bool=false: iftrue, also return the absolute difference betweenyandx[idx]
Returns
Int64: index of the nearest elementTuple{Int64, Real}:(index, |y − x[index]|)whenacc=true
vsearch(y, x; <keyword arguments>)Return the indices of the elements in x nearest to each element of y.
Arguments
y::AbstractVector: vector of interestx::AbstractVector: vector to search within; must not be empty and must be at least as long asy.acc::Bool=false: iftrue, also return the absolute differences between eachy[i]and its nearest match inx
Returns
Vector{Int64}: indices of nearest elements (one per entry ofy)Tuple{Vector{Int64}, Vector{Real}}:(indices, differences)whenacc=true
NeuroAnalyzer.vsplit — Function
vsplit(x, n)Split a vector into contiguous pieces of equal length n.
Argument
x::AbstractVector: input vector; must not be empty and its length must be divisible bynn::Int64: length of each piece; must be ≥ 1
Returns
Vector{AbstractVector}: vector oflength(x) ÷ nsub-vectors, each of lengthn
Stats
NeuroAnalyzer.arf — Function
arf(df, var)Calculate absolute and relative frequencies for a categorical variable.
Arguments
df::DataFrame: input DataFramevar::Union{Symbol, String}: column name; must be present indfand contain at least 2 distinct values
Returns
Matrix{Float64}: a(3 × (k + 1))matrix wherek = length(unique(x)):- row 1: absolute frequencies per category, total in last column
- row 2: relative frequencies as proportions (rounded to 3 d.p.), total = 1.0
- row 3: relative frequencies as percentages (rounded to 2 d.p.), total = 100.0
NeuroAnalyzer.ba — Function
ba(x, y; <keyword arguments>)Calculate a Bland-Altman comparison between two sets of clinical measurements.
Computes the mean difference and the upper and lower limits of agreement (LoA), defined as mean(d) ± z × std(d), where d = x − y and z is the two-tailed Z-score corresponding to la.
Arguments
x::AbstractVector: first measurement vectory::AbstractVector: second measurement vector; must be the same length asxla::Float64=0.95: confidence level for the limits of agreement; must be in(0, 1); default gives the standard 95 % LoA (mean ± 1.96 SD)
Returns
Named tuple:
md::Float64: mean of the differencesx − yll::Float64: lower limit of agreement (md − z × SD)ul::Float64: upper limit of agreement (md + z × SD)
Notes
To produce a Bland-Altman plot:
means = (x .+ y) ./ 2
diffs = x .- y
scatter(means, diffs)
hline!([md, ul, ll])NeuroAnalyzer.binom_prob — Function
binom_prob(p, r, n)Calculate the probability of exactly r successes in n independent trials.
Uses the binomial probability mass function: P(X = r) = C(n, r) × pʳ × (1 − p)^(n − r)
Arguments
p::Float64: success probability per trial; must be in[0, 1]r::Int64: number of successes; must satisfy0 ≤ r ≤ nn::Int64: number of successes; must satisfy0 ≤ r ≤ n
Returns
Float64: probability of exactlyrsuccesses
NeuroAnalyzer.binom_test — Function
binom_test(p, n; verbose)Test whether a proportion differs significantly from 0.5 (two-sided binomial test).
Arguments
prop::Float64: proportion of level-1 observations; must be in[0, 1]n::Int64: total number of observations; must be ≥ 1verbose::Bool=true: iftrue, print counts, proportions, 95 % CIs, and p-value
Returns
Named tuple:
x0::Int64: level-0 countx1::Int64: level-1 countp0::Float64: level-0 proportionp1::Float64: level-1 proportionci0::Tuple{Float64, Float64}: level-0 proportion 95 % CIci1::Tuple{Float64, Float64}: level-1 proportion 95 % CIp::Float64: Two-sided binomial test p-value (clamped toeps()if below machine epsilon)
binom_test(x; verbose)Test whether the proportion of true values in a boolean vector differs from 0.5.
Delegates to binom_test(::Float64, ::Int64) after computing the proportion of true observations.
Arguments
x::Vector{Bool}: binary observation vector; must not be emptyverbose::Bool=true: iftrue, print counts, proportions, 95 % CIs, and p-value
Returns
Named tuple:
x0::Int64: level-0 countx1::Int64: level-1 countp0::Float64: level-0 proportionp1::Float64: level-1 proportionci0::Tuple{Float64, Float64}: level-0 proportion 95 % CIci1::Tuple{Float64, Float64}: level-1 proportion 95 % CIp::Float64: Two-sided binomial test p-value (clamped toeps()if below machine epsilon)
binom_test(x, n; verbose)Test whether the proportion x / n differs from 0.5 (two-sided binomial test).
Delegates to binom_test(::Float64, ::Int64).
Arguments
x::Int64: number of level 1 observations; must satisfy0 ≤ x ≤ nn::Int64: number of observations; must be ≥ 1verbose::Bool=true: iftrue, print counts, proportions, 95 % CIs, and p-value
Returns
Named tuple:
x0::Int64: level-0 countx1::Int64: level-1 countp0::Float64: level-0 proportionp1::Float64: level-1 proportionci0::Tuple{Float64, Float64}: level-0 proportion 95 % CIci1::Tuple{Float64, Float64}: level-1 proportion 95 % CIp::Float64: Two-sided binomial test p-value (clamped toeps()if below machine epsilon)
NeuroAnalyzer.biplot — Function
biplot(df, vars; <keyword arguments>)Plot a PCA biplot (PC1 vs PC2 scores with loading vectors).
Requires at least 2 PCs; returns nothing with a warning otherwise.
Arguments
df::DataFrame: input datavars::Union{Vector{String}, Vector{Symbol}}: variable names for PCAn::Int64=length(vars): number of PCs to compute (≥ 2 needed for the plot)zstd::Bool=true: iftrue, Z-score standardise before PCA
Returns
GLMakie.Figure: biplot figure, ornothingif fewer than 2 PCs result
NeuroAnalyzer.bootstrap_ci — Function
bootstrap_ci(s; <keyword arguments>)Calculate a bootstrap confidence interval for a signal matrix.
Algorithm:
- Stage 1 (
n1iterations): randomly drawn2epochs (with replacement), average them → producesn1bootstrap mean traces. - Stage 2: for each time point, sort the
n1bootstrap means and take thecl/2and1 − cl/2quantiles as the lower and upper CI bounds.
Arguments
s::AbstractMatrix: signal matrix, shape (samples, epochs)n1::Int64=3000: number of bootstrap resamples (outer loop); must be ≥ 1n2::Int64=1000: number of epochs drawn per resample (inner loop); must be ≥ 1cl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Named tuple:
gm::Vector{Float64}: bootstrap grand mean (averaged across alln1resamples)ll::Vector{Float64}: lower CI bound at each time pointul::Vector{Float64}: upper CI bound at each time point
NeuroAnalyzer.bootstrap_stat — Function
bootstrap_stat(s; <keyword arguments>)Calculate a scalar statistic of a signal matrix using bootstrapping.
At each of the n1 iterations, n2 epochs are drawn at random (with replacement), averaged into a single trace, and the expression f is evaluated on that trace. The result is a distribution of the statistic across bootstrap resamples.
The formula string f must reference the current signal trace using the placeholder variable obj. For example: f = "abs(maximum(obj))".
Arguments
s::AbstractMatrix: signal matrix, shape (samples, epochs)n1::Int64=3000: number of bootstrap resamples; must be ≥ 1n2::Int64=1000: number of epochs drawn per resample; must be ≥ 1f::String: Julia expression to evaluate on each bootstrap mean trace; useobjas the placeholder for the current trace vector
Returns
AbstractVector: bootstrap distribution of the statistic; lengthn1
NeuroAnalyzer.center — Function
center(x)Center a vector by subtracting its mean.
Arguments
x::AbstractVector: input vector; must contain at least 1 element
Returns
Vector{Float64}: mean-centered vectorx .- mean(x)
NeuroAnalyzer.chi2p — Function
chi2p(chi; <keyword arguments>)Convert a χ² statistic to a right-tailed p-value P(χ² > chi).
Arguments
chi::Real: χ² statistic; must be ≥ 0df::Real: degrees of freedom; must be > 0
Returns
Float64: right-tailed p-value
Notes
To obtain the left-tailed probability P(χ² < chi) use 1 - chi2p(chi; df=df).
NeuroAnalyzer.cim — Function
cim(x; <keyword arguments>)Calculate the confidence interval for the mean.
Arguments
x::AbstractVector: data vector; must contain at least 2 elementscl::Float64=0.95: confidence level; must be in(0, 1)d::Symbol=:t: istribution used for the critical value;:t(Student's t, recommended for small samples) or:z(standard normal)twotailed::Bool=true: iftrue, compute a two-sided interval
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)
NeuroAnalyzer.cimd — Function
cimd(x; <keyword arguments>)Calculate the confidence interval for the median of a 1-D vector.
Uses the order-statistic method: the CI bounds are x[j] and x[k] where j and k are quantile-derived indices from the sorted data.
Arguments
x::AbstractVector: data vector; must contain enough elements so that the derived indicesjandkfall within[1, n]cl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)
cimd(x; <keyword arguments>)Calculate the confidence interval for the median of a multi-dimensional array.
Column medians are computed, sorted, and the order-statistic CI method is applied across columns.
Arguments
x::AbstractArray: data array; medians are taken alongdims=1(across rows per column); must have at least 2 columnscl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)
NeuroAnalyzer.cip — Function
cip(p, n; <keyword arguments>)Calculate the confidence interval for a proportion using the normal approximation (Wald interval).
Arguments
p::Float64: sample proportion; must be in[0, 1]n::Int64: sample size; must be ≥ 1cl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)
NeuroAnalyzer.cir — Function
cir(x, y; <keyword arguments>)Calculate the confidence interval for a Pearson correlation coefficient computed from two vectors, using Fisher's Z transformation.
Arguments
x::AbstractVector: first data vector; must have the same length asyand length > 3y::AbstractVector: second data vectorcl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)
cir(; <keyword arguments>)Calculate the confidence interval for a Pearson correlation coefficient using Fisher's Z transformation.
Transforms r to z = arctanh(r), applies the normal CI, then back-transforms with tanh.
Arguments
r::Float64: Pearson correlation coefficient; must be in(−1, 1)n::Int64: number of observations; must be > 3cl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)in correlation units
NeuroAnalyzer.cis — Function
cis(x; <keyword arguments>)Calculate the confidence interval for the standard deviation using the chi-squared distribution.
Arguments
x::AbstractVector: data vector; must contain at least 2 elementscl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)
NeuroAnalyzer.civ — Function
civ(x; <keyword arguments>)Calculate the confidence interval for the variance using the chi-squared distribution.
Arguments
x::AbstractVector: data vector; must contain at least 2 elementscl::Float64=0.95: confidence level; must be in(0, 1)
Returns
Tuple{Float64, Float64}:(lower_bound, upper_bound)
NeuroAnalyzer.cl2z — Function
cl2z(ci; <keyword arguments>)Convert a confidence level to the corresponding Z-score.
Arguments
cl::Float64: confidence level; must be in(0, 1)twotailed::Bool=true: iftrue, returns the Z-score for a two-tailed interval, i.e.zsuch thatP(−z ≤ X ≤ z) = cl; iffalse, returns the Z-score for a one-tailed interval, i.e.zsuch thatP(X ≤ z) = cl
Returns
Float64: critical Z-score
Notes
- Two-tailed (
twotailed=true): the CI is(−z, +z) - One-tailed (
twotailed=false): the CI is(−∞, z)(upper bound) or equivalently(−z, +∞)(lower bound) depending on direction
NeuroAnalyzer.cmp_stat — Function
cmp_stat(stat_dist, v)Calculate the proportion of elements in a statistic distribution that are greater or lesser than a given value.
Arguments
stat_dist::AbstractVector: distribution of statistic values; must not be emptyv::Real: reference statistic valuetype::Symbol=:g: Comparison direction::g: proportion of elements >v:l: proportion of elements <v
Returns
Float64: proportion of elements satisfying the condition
NeuroAnalyzer.cmp_test — Function
cmp_test(seg1, seg2; <keyword arguments>)Compare two vectors using an automatically selected or explicitly requested statistical test.
Test selection (when type = :auto):
- Jarque–Bera test is applied to the pooled data to assess normality.
- If normal: variances are compared with an F-test; an equal- or unequal-variance t-test (or a paired one-sample t-test) is used.
- If non-normal: Wilcoxon signed-rank test (paired) or Mann–Whitney U test (unpaired) is used.
Arguments
s1::AbstractVector: first signal vectors2::AbstractVector: second signal vector; must have the same length ass1whenpaired = truepaired::Bool" iftrue, treat the vectors as paired observations"alpha::Float64=0.05: significance level; must be in(0, 1)type::Symbol=:auto: test selection strategy::auto: choose automatically based on normality and variance tests:perm: permutation-based test:p: force parametric test:np: force non-parametric test
exact::Bool=false: iftrue, use the exact Wilcoxon signed-rank test (only applies whentype ∈ {:auto, :np}andpaired = true)nperm::Int64=1000: number of permutations fortype = :perm; must be ≥ 1verbose::Bool=true: iftrue, print test selection and result details
Returns
Permutation test (type = :perm), named tuple:
t::NamedTuple{perm_diff, obs_diff}: permutation null distribution and observed differencep1::Float64: one-tailed p-valuep2::Float64: two-tailed p-value (2 × p1, clamped to 1.0)
All other tests, named tuple:
t: the HypothesisTests.jl test objectts::Tuple{Float64, String}: test statistic value and its nametc: confidence interval of the test statistic (tuple or scalar NaN for non-parametric)df::Float64: degrees of freedomp::Float64: two-tailed p-value (clamped toeps()if below machine epsilon)
NeuroAnalyzer.cor_test — Function
cor_test(seg1, seg2)Calculate the Pearson correlation between two vectors and return associated test statistics.
Arguments
s1::AbstractVector: first signal vector; must have the same length ass2andlength > 3(required for the Fisher Z confidence interval)s2::AbstractVector: second signal vector
Returns
Named tuple:
t::CorrelationTest{Float64}: full HypothesisTests.jl result objectr::Float64: Pearson correlation coefficientrc::Tuple{Float64, Float64}: 95 % confidence interval forrts::Tuple{Float64, String}: t-statistic and label"t"df::Int64: degrees of freedom (n1 + n2 − 2)p::Float64: two-tailed p-value (clamped toeps()if below machine epsilon)
NeuroAnalyzer.count_thresh — Function
count_thresh(x; <keyword arguments>)Threshold a matrix and count the number of elements satisfying the condition.
Arguments
x::AbstractMatrix: input matrixt::Real: threshold valuet_type::Symbol=:g: thresholding rule::eq:x == t:geq:x ≥ t:leq:x ≤ t:g:x > t:l:x < t
Returns
Named tuple:
x_t::Matrix{Bool}: boolean mask;truewhere the condition holdsn::Int64: number of elements satisfying the condition
NeuroAnalyzer.crit_chi — Function
crit_chi(df, alpha)Calculate the critical χ² value for a given degrees of freedom and significance level.
Arguments
df::Real: degrees of freedom; must be > 0; typicallydf = n − 1alpha::Float64=0.05: significance level (upper or lower tail probability); must be in(0, 1)
Returns
Float64: critical χ² value such thatP(X ≤ chi) = alphaunderχ²(df)
Notes
To obtain the upper-tail critical value (i.e. P(X > chi) = alpha) pass 1 − alpha as the alpha argument.
NeuroAnalyzer.crit_t — Function
crit_t(df, alpha; <keyword arguments>)Calculate the critical t-value for a given degrees of freedom and significance level.
Arguments
df::Real: degrees of freedom; must be > 0; typicallydf = n − 1alpha::Float64=0.05: significance level (upper or lower tail probability); must be in(0, 1)twotailed::Bool=true: iftrue, compute the two-tailed critical value; iffalse, compute the one-tailed critical value
Returns
Float64: critical t-value (always positive)
Notes
Critical regions:
- One-tailed left:
(−∞, −t] - One-tailed right:
[t, +∞) - Two-tailed:
(−∞, −t] ∪ [t, +∞)
NeuroAnalyzer.crit_z — Function
crit_z(alpha; <keyword arguments>)Calculate the critical Z-score for a given significance level.
Arguments
alpha::Float64=0.05: significance level (upper or lower tail probability); must be in(0, 1)twotailed::Bool=true: iftrue, compute the two-tailed critical value; iffalse, compute the one-tailed critical value
Returns
Float64: critical Z-score (always positive; the rejection region is symmetric around zero)
Notes
Critical regions:
- One-tailed left:
(−∞, −z] - One-tailed right:
[z, +∞) - Two-tailed:
(−∞, −z] ∪ [z, +∞)
NeuroAnalyzer.cvm — Function
cvm(x)Calculate the coefficient of variation (CV) for the mean.
Computed as σ / μ, where σ = std(x) and μ = mean(x). Expresses the standard deviation as a fraction of the mean; meaningful only when mean(x) ≠ 0.
Arguments
x::AbstractVector: input vector; must contain at least 2 elements and have a non-zero mean
Returns
Float64: coefficient of variation (dimensionless ratio)
NeuroAnalyzer.cvmd — Function
cvmd(x)Calculate the coefficient of variation (CV) for the median.
Uses the robust formula (Q3 − Q1) / 2 / median(x), where Q1 and Q3 are the 25th and 75th percentiles (the semi-interquartile range normalised by the median). Meaningful only when median(x) ≠ 0.
Arguments
x::AbstractVector: input vector; must contain at least 2 elements and have a non-zero median
Returns
Float64: robust coefficient of variation (dimensionless ratio)
NeuroAnalyzer.dap — Function
dap(x)Calculate the D'Agostino–Pearson omnibus test for normality.
Combines standardized skewness (zs) and standardized kurtosis (zk) into a single chi-squared test statistic d = zs² + zk², which follows a χ²(2) distribution under the null hypothesis of normality.
Arguments
x::AbstractVector: input vector; must contain at least 8 elements (sesandsekrequire sufficient sample size); a warning is issued forlength(x) < 20as the approximation is unreliable for small samples
Returns
Named tuple:
zs::Float64: standardized skewness statistic (skewness(x) / ses(x))zk::Float64: standardized kurtosis statistic (kurtosis(x) / sek(x))d::Float64: omnibus test statisticzs² + zk²; followsχ²(2)under H₀p::Float64: p-value from theχ²(2)survival function
Notes
- The test requires
n ≥ 20for reliable results; a diagnostic message is printed for smaller samples. - H₀: the data are normally distributed.
- H₁: the data are not normally distributed.
References
D'Agostino RB, Belanger A, D'Agostino RB Jr. A suggestion for using powerful and informative tests of normality. The American Statistician. 1990;44(4):316–21.
NeuroAnalyzer.df — Function
df(x)Calculate the degrees of freedom for a vector (length(x) − 1).
Arguments
x::AbstractVector: input vector; must contain at least 1 element
Returns
Int64: degrees of freedomlength(x) − 1
NeuroAnalyzer.distance — Function
distance(p1, p2)Calculate the Euclidean distance between two points.
Arguments
p1::Tuple{Real, Real}: first point(x₁, y₁)p2::Tuple{Real, Real}: second point(x₂, y₂)
Returns
Float64: Euclidean distance√((x₂−x₁)² + (y₂−y₁)²)
NeuroAnalyzer.dprime — Function
dprime(p1::Real, p2::Real)Calculate the sensitivity index d′ and response bias for two proportions.
p1 is typically the hit rate and p2 the false-alarm rate. Both are converted to Z-scores using the inverse normal CDF, then combined as:
d′ = Z(p1) − Z(p2)bias = −(Z(p1) + Z(p2)) / 2
Boundary values p ∈ {0, 1} produce ±Inf; callers should apply a correction (e.g. the Hautus log-linear rule) before passing boundary proportions.
Arguments
Named tuple:
dp::Float64: sensitivity index d′rb::Float64: response bias (negative = liberal, positive = conservative)
References
Green DM, Swets JA. Signal Detection Theory and Psychophysics. Wiley; 1966.
NeuroAnalyzer.dranks — Function
dranks(x, nbins)Scale tied ranks into discrete bins 1 … nbins.
Tied ranks are computed with StatsBase.tiedrank, normalised to (0, 1], then mapped to integers in [1, nbins] via ceil.
Arguments
x::AbstractArray: input array of continuous values; must not be emptynbins::Int64: number of bins; defaults to Sturges' formulaceil(Int64, 1 + log2(length(x))); must be ≥ 1
Returns
Array{Int64}: rank-bin indices ∈[1, nbins], same shape asx
NeuroAnalyzer.efs — Function
efs(x1, x2)Calculate effect size measures for two independent samples.
Arguments
x1::AbstractVector: first sample; must contain ≥ 2 elements with non-zero SDx2::AbstractVector: second sample; must contain ≥ 2 elements with non-zero SD
Returns
Named tuple:
d::Float64: Cohen's d (pooled SD denominator, unbiased for equal n)g::Float64: Hedges' g (maximum-likelihood pooled SD; less biased for small n)delta::Float64: Glass' Δ (uses SD ofx2as the denominator; preferred when groups have different variances)
NeuroAnalyzer.efs_p1g — Function
efs_p1g(p)Calculate Cohen's h arcsine transformation for a single proportion.
Computes the arcsine-transformed proportion φ = 2 × arcsin(√p), which stabilizes the variance of a binomial proportion.
Arguments
p::Float64: proportion; must be in[0, 1]
Returns
Float64: transformed valueφ = 2 × arcsin(√p)
NeuroAnalyzer.efs_p2g — Function
efs_p2g(p1, p2; nd)Calculate Cohen's h effect size for two independent proportions.
Computed as h = 2arcsin(√p1) − 2arcsin(√p2). The two proportions are independent and do not need to sum to 1.
Arguments
p1::Float64: first proportion; must be in[0, 1]p2::Float64: second proportion; must be in[0, 1]nd::Bool=false: iftrue, return|h|(non-directional effect size)
Returns
Float64: Cohen's h (signed, or absolute ifnd=true)
NeuroAnalyzer.f1 — Function
f1(; <keyword arguments>)Assess classification model performance using the F1-score.
The F1-score is the harmonic mean of precision and recall: F1 = 2 × (precision × recall) / (precision + recall)
Arguments
tp::Int64: number of true positives; must be ≥ 0tn::Int64: number of true negatives; must be ≥ 0fp::Int64: number of false positives; must be ≥ 0fn::Int64: number of false negatives; must be ≥ 0
Returns
Named tuple:
f1_score::Float64: F1-score ∈ [0, 1]prec::Float64: precisiontp / (tp + fp)rec::Float64: recalltp / (tp + fn)
References
https://www.statology.org/what-is-a-good-f1-score/
NeuroAnalyzer.f2p — Function
f2p(t; <keyword arguments>)Convert an F-statistic to a right-tailed p-value P(F > f).
Arguments
f::Real: F-statistic; must be ≥ 0df1::Real: numerator degrees of freedom; must be > 0df2::Real: denominator degrees of freedom; must be > 0
Returns
Float64: right-tailed p-value
Notes
To obtain the left-tailed probability P(F < f) use 1 - f2p(f; df1=df1, df2=df2).
NeuroAnalyzer.fano — Function
fano(x)Calculate the Fano factor.
Computed as σ² / μ, where σ² = var(x) and μ = mean(x). The Fano factor is a measure of the dispersion of a probability distribution relative to its mean; a value of 1 corresponds to a Poisson process.
Arguments
x::AbstractVector: input vector; must contain at least 2 elements and have a non-zero mean
Returns
Float64: Fano factor (units ofx)
NeuroAnalyzer.friedman — Function
friedman(m)Estimate Friedman's non-parametric two-way analysis of variance and the associated Kendall's coefficient of concordance W.
Rankings are computed within each group (column) across observations (rows). The Q statistic approximately follows a χ²(k − 1) distribution under H₀.
Arguments
m::AbstractArray: data matrix of shape(observations × groups); must have ≥ 2 groups (columns) and ≥ 2 observations (rows)
Returns
Named tuple:
q::Float64: Friedman's Q statisticw::Float64: Kendall's coefficient of concordance W ∈ [0, 1]p::Float64: p-value from the χ²(k − 1) distribution
Notes
- H₀ (Friedman): all treatment groups have the same distribution
- H₀ (Kendall): there is no agreement between rankings (W = 0)
- W = 0 indicates no agreement; W = 1 indicates perfect agreement
References
Friedman M. The use of ranks to avoid the assumption of normality implicit in the analysis of variance. Journal of the American Statistical Association. 1937;32(200):675–701.
NeuroAnalyzer.grubbs — Function
grubbs(x; <keyword arguments>)Perform the Grubbs test for a single outlier.
Tests whether the most extreme value in x (maximum, minimum, or both) is a statistically significant outlier at confidence level alpha.
The test statistic is:
- Two-tailed:
G = max|xᵢ − x̄| / s - Upper one-tailed:
G = (max(x) − x̄) / s - Lower one-tailed:
G = (x̄ − min(x)) / s
The critical value is derived from the t-distribution with df = n − 2.
Arguments
x::AbstractVector: input vector; must contain at least 7 elementsalpha::Float64=0.95: confidence level (not significance level); must be in(0, 1); default 0.95 corresponds to a 5 % significance levelt::Int64=0: test type:0: two-tailed (tests both extremes)1: upper one-tailed (tests maximum)-1: lower one-tailed (tests minimum)
Returns
Bool:trueif an outlier is detected;falseotherwise
References
Grubbs FE. Procedures for detecting outlying observations in samples. Technometrics. 1969;11(1):1–21.
NeuroAnalyzer.hildebrand_rule — Function
hildebrand_rule(x; verbose)Calculate the Hildebrand rule statistic for a vector.
Computed as H = (mean(x) − median(x)) / std(x). Values of |H| < 0.2 indicate approximate symmetry of the distribution.
Arguments
x::AbstractVector: input vector; must contain at least 2 elements and have non-zero standard deviationverbose::Bool=true: iftrue, print a message when the symmetry criterion is met
Returns
Float64: Hildebrand statistic H
Notes
The criterion |H| < 0.2 is checked (not just H < 0.2) because a negative mean–median difference also indicates asymmetry if its magnitude is ≥ 0.2.
NeuroAnalyzer.infcrit — Function
infcrit(m)Calculate R², adjusted R², AIC (with small-sample correction), and BIC for a fitted linear regression model.
The small-sample corrected AIC (AICc) is applied when n / k < 40: AICc = AIC + 2k(k+1) / (n − k − 1), where k is the number of predictors (excluding the intercept).
Arguments
m::StatsModels.TableRegressionModel: fitted linear regression model
Returns
Named tuple:
R2::Float64: coefficient of determination R²R2adj::Float64: adjusted R²; penalizes for the number of predictorsaic::Float64: AIC (AICc-corrected whenn / k < 40)bic::Float64: BIC
Notes
k= number of predictors (coefficients excluding the intercept).- AIC =
2k − 2L; BIC =k × ln(n) − 2L, where L = log-likelihood. - AICc correction is applied when the sample-to-parameter ratio
n/k < 40.
NeuroAnalyzer.jaccsim — Function
jaccsim(x, y)Calculate the Jaccard similarity between two vectors.
Computed as |x ∩ y| / |x ∪ y| where |x ∪ y| = |x| + |y| − |x ∩ y|.
Values range from 0 (no common elements) to 1 (identical element sets).
Arguments
x::AbstractVector: first vector; must not be emptyy::AbstractVector: second vector; must not be empty
Returns
Float64: Jaccard similarity ∈[0, 1]
Notes
Jaccard distance = 1 − jaccsim(x, y).
NeuroAnalyzer.k_categories — Function
k_categories(n)Calculate the recommended number of histogram categories for a sample of size n.
Returns two common rules:
- Square-root choice:
k1 = √n - Sturges' extended rule:
k2 = 1 + 3.222 × log₁₀(n)
Arguments
n::Int64: sample size; must be ≥ 1
Returns
Named tuple:
k1::Float64: square-root estimatek2::Float64: sturges' extended estimate
NeuroAnalyzer.linreg — Function
linreg(x, y)Fit a simple linear regression model y ~ x.
Arguments
x::AbstractVector: predictor vector; must have the same length asyand contain at least 3 elementsy::AbstractVector: response vector
Returns
Named tuple:
lr::StatsModels.TableRegressionModel: fitted model objectc::Vector{Float64}: coefficients[intercept, slope]se::Vector{Float64}: standard errors of the coefficientsR2::Float64: coefficient of determination R²R2adj::Float64: adjusted R²aic::Float64: Akaike Information Criterion (AICc-corrected whenn/k < 40)bic::Float64: Bayesian Information Criterionlf::Vector{Float64}: fitted values (useplot(x, lf)to visualise)
Notes
To predict at new x-values:
new_x = DataFrame(x = [3.5, 7])
predict(lr, new_x)NeuroAnalyzer.logit — Function
logit(p)Convert a proportion to its logit (log-odds).
Computed as log(p / (1 − p)). Returns −Inf for p = 0 and +Inf for p = 1.
Arguments
p::Float64: proportion; must be in[0, 1]
Returns
Float64: log-oddslog(p / (1 − p))
NeuroAnalyzer.make_table — Function
make_table(; <keyword arguments>)Display data as a formatted table using PrettyTables.jl.
The header row is prepended to the data and printed as a single table body with a horizontal separator after the first row.
Arguments
header::Matrix{String}: single-row header matrix, e.g.["Group" "A" "B"]; must have the same number of columns asdatadata::Matrix{Any}: data matrix, e.g.["var1" 1.0 2.0; "var2" 3.0 4.0]; integer values are converted to strings before display
Returns
Nothing
Notes
- The
formatters = ft_printf("%1.3f", 2:3)format is hardcoded to columns 2 and 3; callers with a different column count should adjust the source accordingly. - Integer elements in
dataare converted toStringin-place to ensure uniform display.
NeuroAnalyzer.mcc — Function
mcc(; <keyword arguments>)Assess classification model performance using the Matthews Correlation Coefficient (MCC).
MCC is a balanced metric that accounts for all four confusion-matrix cells, making it reliable even for imbalanced classes.
Computed as: MCC = (tp × tn − fp × fn) / √((tp+fp)(tp+fn)(tn+fp)(tn+fn))
MCC's value ranges from -1 to 1, depending on:
- A score of -1 denotes a complete discrepancy between expected and actual classes.
- 0 is equivalent to making an entirely arbitrary guess.
- Total agreement between expected and actual classes is indicated by a score of 1.
Arguments
tp::Int64: number of true positives; must be ≥ 0tn::Int64: number of true negatives; must be ≥ 0fp::Int64: number of false positives; must be ≥ 0fn::Int64: number of false negatives; must be ≥ 0
Returns
Float64: MCC ∈ [−1, 1]; returns0.0when the denominator is zero (degenerate classifier - all predictions in one class)
References
https://finnstats.com/index.php/2022/09/06/assess-performance-of-the-classification-model/
NeuroAnalyzer.mde — Function
mde(; <keyword arguments>)Calculate the minimum detectable effect (MDE) for a given sample size.
Computed as MDE = (z_α + z_β)² × s² / n.
Arguments
n::Int64: number of subjects per group; must be ≥ 1s::Real: standard deviation; must be > 0alpha::Float64=0.05: type I error probability; must be in(0, 1)beta::Float64=0.20: type II error probability; must be in(0, 1)verbose::Bool=true: iftrue, print the critical Z-scores
Returns
Float64: minimum detectable effect size
NeuroAnalyzer.meanc — Function
meanc(g, x)Calculate the weighted mean of categorical data.
Computed as Σ(g × x) / Σx.
Arguments
g::Vector{Int64}: group labels (e.g.[0, 1, 2, 3])x::Vector{Int64}: subject counts per group (e.g.[2, 8, 27, 45]); must be the same length asg, non-empty, and sum to ≥ 1
Returns
Float64: weighted categorical mean
NeuroAnalyzer.meancirc — Function
meancirc(x; <keyword arguments>)Calculate the circular (angular) mean.
Uses the two-argument arctangent of the mean sine and cosine components.
Arguments
x::AbstractVector: angles; must be non-emptyrad::Bool=false: iftrue,xis in radians; iffalse,xis in degrees
Returns
Float64: circular mean in the same unit as the input (radians or degrees)
NeuroAnalyzer.meang — Function
meang(x)Calculate the geometric mean.
Computed as exp(mean(log.(x))), which is numerically stable for large vectors (avoids overflow from prod(x)). All elements must be strictly positive.
Arguments
x::AbstractVector: input vector; must be non-empty and contain only positive values
Returns
Float64: geometric mean
NeuroAnalyzer.meanh — Function
meanh(x)Calculate the harmonic mean.
Computed as n / Σ(1/xᵢ). All elements must be non-zero.
Arguments
x::AbstractVector: input vector; must be non-empty and contain no zero values
Returns
Float64: harmonic mean
NeuroAnalyzer.meanp — Function
meanp(p, n)Calculate the expected count (mean) of a proportion.
Computed as n × p.
Arguments
p::Float64: proportion; must be in[0, 1]n::Int64: number of observations; must be ≥ 1
Returns
Float64: expected countn × p
NeuroAnalyzer.meant — Function
meant(x; <keyword arguments>)Calculate the trimmed mean.
Sorts x and removes the bottom and top n × 100 % of values before computing the mean.
Arguments
x::AbstractVector: input vector; must contain enough elements so that trimming leaves at least one valuen::Float64=0.1: fraction of values to trim from each tail; must be in(0, 0.5)to ensure a non-empty trimmed set
Returns
Float64: trimmed mean
NeuroAnalyzer.meanw — Function
meanw(x, w)Calculate the weighted mean.
Computed as Σ(xᵢ × wᵢ) / Σwᵢ.
Arguments
x::AbstractVector: values vector; must be non-emptyw::AbstractVector: weights vector; must have the same length asxand sum to a non-zero value
Returns
Float64: weighted mean
NeuroAnalyzer.moe — Function
moe(n)Calculate the margin of error for a given sample size.
Computed as 1 / √n (the standard error of a proportion at p = 0.5).
Arguments
n::Int64: sample size; must be ≥ 1
Returns
Float64: margin of error
moe(x)Calculate the margin of error for a data array based on its sample size.
Computed as 1 / √length(x).
Arguments
x::AbstractArray: input array; must not be empty
Returns
Float64: margin of error
NeuroAnalyzer.mrng — Function
mrng(x)Calculate the midrange of an array: (maximum(x) − minimum(x)) / 2.
Arguments
Float64: midrange ofx.
NeuroAnalyzer.mscr — Function
mscr(; <keyword arguments>)Assess classification model performance using the misclassification rate and accuracy.
- Misclassification rate:
(fp + fn) / (tp + tn + fp + fn) - Accuracy:
1 − misclassification rate
Arguments
tp::Int64: number of true positives; must be ≥ 0tn::Int64: number of true negatives; must be ≥ 0fp::Int64: number of false positives; must be ≥ 0fn::Int64: number of false negatives; must be ≥ 0
Returns
Named tuple:
mr::Float64: misclassification rate ∈ [0, 1]acc::Float64: accuracy ∈ [0, 1]
References
https://www.statology.org/misclassification-rate/
NeuroAnalyzer.norminv — Function
norminv(x::Real)Return the quantile of the standard normal distribution at probability x.
Equivalent to Φ⁻¹(x) where Φ is the standard normal CDF.
Arguments
x::Real: probability; must be in(0, 1)
Returns
Float64: normal quantile atx
NeuroAnalyzer.npca — Function
npca(m; <keyword arguments>)Calculate the recommended number of principal components (PCs).
Arguments
m::Matrix{Float64}: data matrix(observations × variables); must have ≥ 2 rows and ≥ 1 columnzstd::Bool=true: iftrue, Z-score standardise each variable before PCA.type::Symbol: selection criterion::var: keep enough PCs to explain at leastvaluefraction of total variance:eig: keep PCs whose eigenvalue exceedsvalue
value::Real: threshold; must be in(0, 1)for:var, or> 0for:eig
Returns
Int64: recommended number of PCs (≥ 1)
NeuroAnalyzer.o2p — Function
o2p(o::Float64)Convert odds to a probability.
Computed as p = o / (1 + o).
Arguments
o::Real: odds; must be ≥ 0
Returns
Float64: probability ∈[0, 1)
NeuroAnalyzer.op — Function
op(x, y)Calculate the outer product of two vectors.
Computed as x × yᵀ, producing a matrix of shape (length(x) × length(y)).
Arguments
x::AbstractVector: left vector; must not be emptyy::AbstractVector: right vector; must not be empty
Returns
Matrix: outer product matrix of shape(length(x), length(y))
NeuroAnalyzer.outlier_detect — Function
outlier_detect(x; <keyword arguments>)Detect outliers in a vector using a selected method.
Arguments
x::AbstractVector: input vector; must contain at least 7 elements when usingmethod = :gmethod::Symbol=:iqr: detection method::iqr: interquartile range (flags values outsideQ1 − 1.5×IQRandQ3 + 1.5×IQR):z: Z-score (flags values with|z| > 3):g: iterative Grubbs test applied to both tails
Returns
Vector{Bool}: boolean mask;trueat each index identified as an outlier
Notes
- The
:gmethod iteratively removes the most extreme value whilelength(x_tmp) > 6(Grubbs requires at least 7 observations), checking both the maximum and minimum tails separately. - Outlier indices are tracked relative to the original vector, so deletion from the working copy does not affect index mapping.
NeuroAnalyzer.p2o — Function
p2o(p::Float64)Convert a probability to odds.
Computed as o = p / (1 − p).
Arguments
p::Real: probability; must be in[0, 1)(odds undefined atp = 1)
Returns
Float64: odds
NeuroAnalyzer.p2z — Function
p2z(p; <keyword arguments>)Convert a p-value to the corresponding Z-score.
Arguments
p::Float64=0.05: p-value; must be in(0, 1)twotailed::Bool=false: iftrue, compute the two-tailed Z-score; iffalse(default), compute the one-tailed Z-score
Returns
Float64: Z-score such thatP(Z > z) = p(one-tailed) orP(|Z| > z) = p(two-tailed)
NeuroAnalyzer.pcacomp — Function
pcacomp(m; <keyword arguments>)Calculate the first n principal components (PCs) of a data matrix.
Arguments
m::Matrix{Float64}: data matrix of shape(observations × variables); must have ≥ 2 rows and ≥ 1 columnn::Int64=size(m, 2): number of PCs to compute; must satisfy1 ≤ n ≤ size(m, 2)zstd::Bool=true: iftrue, Z-score standardize each variable before PCA
Returns
Named tuple:
pc::DataFrame: PC scores; columns namedPC1 … PCnpcv::Vector{Float64}: percentage of total variance explained by each PCpcm::Vector{Float64}: column means of the (possibly standardised) datapcp::Matrix{Float64}: PC projection (loading) matrixpc_model::MultivariateStats.PCA{Float64}: fitted PCA model object
pcacomp(df, vars; <keyword arguments>)Calculate the first n principal components from selected columns of a DataFrame.
Arguments
df::DataFrame: input datavars::Union{Vector{String}, Vector{Symbol}}: column names to use; must all exist indfand there must be at least 2n::Int64=length(vars): number of PCs; must satisfy1 ≤ n ≤ length(vars)zstd::Bool=true: iftrue, Z-score standardize each variable before PCA
Returns
Named tuple:
pc::DataFrame: PC scores; columns namedPC1 … PCnpcv::Vector{Float64}: percentage of total variance explained by each PCpcm::Vector{Float64}: column means of the (possibly standardised) datapcp::Matrix{Float64}: PC projection (loading) matrixpc_model::MultivariateStats.PCA{Float64}: fitted PCA model object
NeuroAnalyzer.permute — Function
permute(s, n)Generate n cyclic permutations of a signal vector.
Each permutation randomly selects a split point and rotates the vector (moves the tail before the head).
Arguments
s::AbstractVector: input signal vector; must contain at least 2 elementsn::Int64: number of permutations; must be ≥ 1
Returns
Matrix{Float64}: matrix, shape (n, length(s))
permute(s, n)Generate n cyclic permutations of each row of a 2- or 3-D array.
Each permutation randomly selects a split point along the second axis and rotates that row cyclically.
Arguments
s::AbstractArray: input array; must be 2- or 3-dimensional, with at least 2 elements along the second axisn::Int64: number of permutations; must be ≥ 1
Returns
Array{Float64, 3}: shape (n × size(s,1) × size(s,2)) for 2-D inputArray{Float64, 4}: shape (n × size(s,1) × size(s,2) × size(s,3)) for 3-D input
NeuroAnalyzer.power_c1g — Function
power_c1g(; <keyword arguments>)Calculate study power for a one-group continuous outcome comparison (group vs population), using the t-distribution.
Arguments
m::Real: population means::Real: population standard deviation; must be > 0xbar::Real: study group meann::Int64: group sample size; must be ≥ 2alpha::Float64=0.05: type I error probability; must be in(0, 1)
Returns
Float64: estimated study power
NeuroAnalyzer.power_c2g — Function
power_c2g(; <keyword arguments>)Calculate study power for a two-group continuous outcome comparison.
Arguments
m1::Real: group 1 means1::Real: group 1 standard deviation; must be > 0n1::Int64: group 1 sample size; must be ≥ 1m2::Real: group 2 means2::Real: group 2 standard deviation; must be > 0n2::Int64: group 2 sample size; must be ≥ 1alpha::Float64=0.05: type I error probability; must be in(0, 1)
Returns
Float64: estimated study power
NeuroAnalyzer.power_p1g — Function
power_p1g(; <keyword arguments>)Calculate study power for a one-proportion comparison (group vs population).
Arguments
p1::Float64: study group proportion; must be in(0, 1)p2::Float64: population proportion; must be in(0, 1)n1::Int64: study group sample size; must be ≥ 1alpha::Float64=0.05: type I error probability; must be in(0, 1)
Returns
Float64: estimated study power
NeuroAnalyzer.power_p2g — Function
power_p2g(; <keyword arguments>)Calculate study power for a two-proportion comparison.
Arguments
p1::Float64: group 1 proportion; must be in(0, 1)p2::Float64: group 2 proportion; must be in(0, 1)n1::Int64: group 1 sample size; must be ≥ 1n2::Int64: group 2 sample size; must be ≥ 1alpha::Float64=0.05: type I error probability; must be in(0, 1)
Returns
Float64: estimated study power
NeuroAnalyzer.prank — Function
prank(x)Calculate percentile ranks for each element of x.
The percentile rank of element xᵢ is the proportion of values in x that are strictly less than xᵢ, expressed as a value in [0, 1): PR(xᵢ) = count(x .< xᵢ) / length(x)
Ties receive the same rank. Results are returned in the original element order.
Arguments
x::AbstractVector: input vector; must not be empty
Returns
Vector{Float64}: percentile ranks ∈[0, 1), in the same order asx
NeuroAnalyzer.pred_int — Function
pred_int(n)Return the 95 % prediction interval multiplier adjusted for sample size n.
Values for n ≤ 19 are taken from a lookup table. Values for n ≥ 20 are approximated from published stepped ranges; a warning is issued because accuracy decreases for larger samples. For very large samples (n > 200) the value converges to the normal-distribution limit of 1.96.
Returns NaN for n = 1 (prediction interval is undefined for a single observation).
Arguments
n::Int64: sample size; must be ≥ 1
Returns
Float64: prediction interval multiplier
Notes
For n > 20 the result is approximate and a diagnostic warning is issued.
NeuroAnalyzer.r1r2_zscore — Function
r1r2_zscore(; <keyword arguments>)Calculate the Z-score for the difference between two independent Pearson correlation coefficients using Fisher's Z transformation.
The test statistic is: z = (atanh(r1) − atanh(r2)) / √(1/(n1 − 3) + 1/(n2 − 3))
Arguments
r1::Float64: correlation coefficient for group 1; must be in(−1, 1)r2::Float64: correlation coefficient for group 2; must be in(−1, 1)n1::Int64: number of observations in group 1; must be > 3n2::Int64: number of observations in group 2; must be > 3
Returns
Float64: Z-score for the differencer1 − r2
Notes
Both samples must have n > 3 for the Fisher Z standard error 1/√(n − 3) to be defined. The original guards (n > 0) were insufficient.
NeuroAnalyzer.res_norm — Function
res_norm(x, g)Test whether residuals follow a normal distribution, per group and overall.
For each group (and for the whole sample), residuals are computed as x .- mean(x_group). Normality is then assessed with:
- Anderson–Darling one-sample test against
Normal(0, 1). - Kolmogorov–Smirnov one-sample exact test against
Normal(0, 1).
Arguments
x::AbstractVector: data values; must not be emptyg::Vector{Int64}=repeat([1], length(x)): group membership for each element ofx; must have the same length asx
Returns
Named tuple:
adt_p::Vector{Float64}: Anderson–Darling p-values; one per group (in sorted group order) plus one for the whole sample at the last indexks_p::Vector{Float64}: Kolmogorov–Smirnov p-values; same layout asadt_p
If there is only one group, both vectors have length 1 (whole-sample result only).
Notes
- Results are non-random: both tests compare residuals against the theoretical
Normal(0, 1)distribution rather than a random reference sample. - For large groups
ExactOneSampleKSTestmay be slow; consider wrapping inApproximateOneSampleKSTestforn > 1000.
NeuroAnalyzer.rfz — Function
rfz(r)Compute Fisher's Z transformation of a Pearson correlation coefficient.
Applies z = atanh(r). Because atanh(±1) is infinite, the boundary values r = ±1 are clamped to ±atanh(1 − ε) where ε = eps(), giving z ≈ ±18.368 in practice.
Arguments
r::Float64: Pearson correlation coefficient; must be in[−1, 1]
Returns
Float64: Fisher z-transformed value
Notes
- Boundary clamping:
rfz(1.0) ≈ 18.368,rfz(-1.0) ≈ -18.368. - For values strictly inside
(−1, 1)the result equalsatanh(r)exactly.
NeuroAnalyzer.rmna — Function
rmna(x)Return a copy of x with all NaN and Missing values removed.
Arguments
x::AbstractVector: input vector; may containFloat64,Missing, orNaN
Returns
Vector{Float64}: filtered vector converted toFloat64
NeuroAnalyzer.rng — Function
rng(x)Calculate the range of an array (maximum − minimum).
Arguments
x::AbstractArray: input array; must not be empty
Returns
Float64: range ofx
NeuroAnalyzer.screeplot — Function
screeplot(df, vars; <keyword arguments>)Plot a PCA scree plot showing variance explained and eigenvalues per PC.
Arguments
df::DataFrame: input datavars::Union{Vector{String}, Vector{Symbol}}: variable names for PCAn::Int64=length(vars): number of PCs to computezstd::Bool=true: iftrue, Z-score standardize before PCA
Returns
GLMakie.Figure: two-panel figure (% variance explained + eigenvalues)
NeuroAnalyzer.sdi — Function
sdi(x, y)Calculate the Sørensen–Dice similarity index between two vectors.
Computed as 2|x ∩ y| / (|x| + |y|). Values range from 0 to 1.
Arguments
x::AbstractVector: first vector; must not be emptyy::AbstractVector: second vector; must not be empty
Returns
Float64: Sørensen–Dice index ∈[0, 1], rounded to 2 decimal places
Notes
Interpretation guide:
0.80–1.00: very high similarity0.60–0.79: high similarity0.40–0.59: moderate similarity0.20–0.39: low similarity0.00–0.19: very low similarity
NeuroAnalyzer.sek — Function
sek(x)Calculate the standard error of kurtosis.
Computed as 2 × (n−1) × √(6n / ((n−2)(n−3)(n+3)(n+5))).
Requires n ≥ 4 so that the (n−3) term in the denominator is non-zero.
Arguments
x::AbstractVector: input vector; must contain at least 4 elements.
Returns
Float64: standard error of kurtosis
sek(n)Calculate the standard error of kurtosis for a sample of size n.
Computed as 2 × (n−1) × √(6n / ((n−2)(n−3)(n+3)(n+5))).
Arguments
n::Int64: sample size; must be ≥ 4
Returns
Float64: standard error of kurtosis
NeuroAnalyzer.sem — Function
sem(x)Calculate the standard error of the mean.
Computed as std(x) / √n.
Arguments
x::AbstractVector: input vector; must contain at least 2 elements
Returns
Float64: standard error of the mean
NeuroAnalyzer.semd — Function
semd(x)Calculate the standard error of the median.
Approximated as 1.253 × std(x) / √n (valid for large normal samples).
Arguments
x::AbstractVector: input vector; must contain at least 2 elements
Returns
Float64: standard error of the median
NeuroAnalyzer.sem_diff — Function
sem_diff(x, y)Calculate the standard error of the difference between two means.
For equal-length vectors: √(SEM(x)² + SEM(y)²).
For unequal-length vectors: pooled SD × √(1/n1 + 1/n2).
Arguments
x::AbstractVector: first sample; must contain at least 2 elementsy::AbstractVector: second sample; must contain at least 2 elements
Returns
Float64: standard error of the mean difference
NeuroAnalyzer.sen — Function
sen(n)Calculate the standard error of a count (√n).
Arguments
n::Int64: number of observations; must be ≥ 1
Returns
Float64: √n.
NeuroAnalyzer.sen_diff — Function
sen_diff(n1, n2)Calculate the standard error of the difference between two counts.
Computed as √(n1 + n2).
Arguments
n1::Int64: group 1 count; must be ≥ 1n2::Int64: group 2 count; must be ≥ 1
Returns
Float64:√(n1 + n2)
NeuroAnalyzer.sep — Function
sep(p, n)Calculate the standard error of a proportion.
Computed as √(p(1 − p) / n).
Arguments
p::Float64: proportion; must be in[0, 1]n::Int64: number of observations; must be ≥ 1
Returns
Float64: standard error of the proportion
NeuroAnalyzer.sep_diff — Function
sep_diff(p1, p2, n1, n2)Calculate the standard error of the difference between two proportions.
Computed as √(p1(1−p1)/n1 + p2(1−p2)/n2).
Arguments
p1::Float64: proportion of group 1; must be in[0, 1]p2::Float64: proportion of group 2; must be in[0, 1]n1::Int64: group 1 sample size; must be ≥ 1n2::Int64: group 2 sample size; must be ≥ 1
Returns
Float64: standard error of the difference in proportions
NeuroAnalyzer.ses — Function
ses(x)Calculate the standard error of skewness.
Computed as √(6n(n−1) / ((n−2)(n+1)(n+3))).
Requires n ≥ 3 so that the denominator is non-zero.
Arguments
x::AbstractVector: input vector; must contain at least 3 elements
Returns
Float64: standard error of skewness
ses(n)Calculate the standard error of skewness for a sample of size n.
Arguments
n::Int64: sample size; must be ≥ 3
Returns
Float64: standard error of skewness
NeuroAnalyzer.size_c1diff — Function
size_c1diff(; <keyword arguments>)Calculate required sample size for detecting a difference in variance (study SD vs population SD) using a lookup table.
Arguments
s1::Real: study SD to detect; ratios1/s2must be in[0.1, 1.5]s2::Real: population SD; must be > 0twotailed::Bool=true: iftrue, return twice the one-sided table valuepower::Float64=0.8: desired power; must be in[0.8, 0.99]
Returns
Int64: required sample size (doubled iftwotailed=true)
Notes
Values outside the table range are clamped to the nearest boundary and a warning is issued.
NeuroAnalyzer.size_c1g — Function
size_c1g(; <keyword arguments>)Calculate the required sample size for a one-group continuous outcome study (group vs population).
Arguments
m::Real: population means::Real: population standard deviation; must be > 0xbar::Real: expected study group mean; must differ frommalpha::Float64=0.05: type I error probability; must be in(0, 1)power::Float64=0.8: desired power; must be in(0, 1)iter::Bool=false: iftrue, use an iterative power search (n from 2 to 10,000)
Returns
Int64: required sample size
NeuroAnalyzer.size_c2g — Function
size_c2g(; <keyword arguments>)Calculate the required sample size for a two-group continuous outcome study.
Assumes equal group standard deviations (both equal to s1).
Arguments
m1::Real: group 1 means1::Real: group 1 standard deviation (assumed equal for both groups); must be > 0m2::Real: group 2 mean (expected)r::Int64=1: enrollment ratio (group 2 / group 1); must be ≥ 1alpha::Float64=0.05: type I error probability; must be in(0, 1)power::Float64=0.8: desired power; must be in(0, 1)
Returns
Named tuple:
n1::Int64: group 1 sample sizen2::Int64: group 2 sample size
NeuroAnalyzer.size_m — Function
size_m(; <keyword arguments>)Calculate the required sample size for estimating a population mean within a margin of error E.
Arguments
sigma::Real: population standard deviation; must be > 0alpha::Float64=0.05: type I error probability; must be in(0, 1)E::Real: desired margin of error; must be > 0
Returns
Int64: required sample size
NeuroAnalyzer.size_p — Function
size_p(; <keyword arguments>)Calculate the required sample size for estimating a proportion within a margin of error E.
Arguments
p::Union{Float64, Nothing}=nothing: expected proportion; ifnothing, uses the conservative estimatep = 0.5alpha::Float64=0.05: type I error probability; must be in(0, 1)E::Float64: desired margin of error; must be in(0, 1)
Returns
Int64: required sample size
NeuroAnalyzer.size_p1diff — Function
size_p1diff(; <keyword arguments>)Calculate required sample size for detecting a difference in proportions (study vs population) using a lookup table.
Arguments
p1::Float64: study group proportion; must be in(0, 1)p2::Float64: population proportion; must be in(0, 1)power::Float64=0.8: desired power; must be in[0.8, 0.99]
Returns
Int64: total required sample size (both groups combined)
Notes
Values outside the table range are clamped and a warning is issued.
NeuroAnalyzer.size_p1g — Function
size_p1g(; <keyword arguments>)Calculate the required sample size for a one-group proportion study (group vs population).
Arguments
p1::Float64: population proportion; must be in(0, 1)p2::Float64: study group proportion; must be in(0, 1)and ≠p1alpha::Float64=0.05: type I error probability; must be in(0, 1)power::Float64=0.8: desired power; must be in(0, 1)
Returns
Int64: required sample size
NeuroAnalyzer.size_p2g — Function
size_p2g(; <keyword arguments>)Calculate the required sample size for a two-group proportion study.
Arguments
p1::Float64: group 1 proportion; must be in(0, 1)p2::Float64: group 2 proportion; must be in(0, 1)and ≠p1r::Int64=1: enrollment ratio (group 2 / group 1); must be ≥ 1alpha::Float64=0.05: type I error probability; must be in(0, 1)power::Float64=0.8: desired power; must be in(0, 1)
Returns
Named tuple:
n1::Int64: group 1 sample sizen2::Int64: group 2 sample size
NeuroAnalyzer.slope — Function
slope(p1, p2)Calculate the slope of the line passing through two points.
Arguments
p1::Tuple{Real, Real}: first point(x₁, y₁)p2::Tuple{Real, Real}: second point(x₂, y₂);x₂ ≠ x₁
Returns
Float64: slope(y₂ − y₁) / (x₂ − x₁)
NeuroAnalyzer.stdc — Function
stdc(g, x)Calculate the standard deviation of categorical data.
Arguments
g::Vector{Int64}: group labels (e.g.[0, 1, 2, 3])x::Vector{Int64}: number of subjects per group; same length asg
Returns
Float64: standard deviation of the categorical variable
NeuroAnalyzer.stdp — Function
stdp(p, n)Calculate the standard deviation of a proportion.
Computed as √(p × (1 − p) / n).
Arguments
p::Float64: proportion; must be in[0, 1]n::Int64: number of observations; must be ≥ 1
Returns
Float64: standard deviation of the proportion
stdp(x1, x2; <keyword arguments>)Calculate the pooled standard deviation from two sample vectors.
Arguments
x1::AbstractVector: first sample; must contain ≥ 2 elementsx2::AbstractVector: second sample; must contain ≥ 2 elementstype::Symbol=:cohen: pooling method::cohen:√(((n1−1)s1² + (n2−1)s2²) / (n1+n2−2)); requiresn1+n2 > 2:hedges:√(((n1−1)s1² + (n2−1)s2²) / (n1+n2))(MLE; slightly biased downward)
Returns
Float64: pooled standard deviation
stdp(s1, s2, n1, n2; <keyword arguments>)Calculate the pooled standard deviation from summary statistics when group sizes differ.
Arguments
s1::Real: standard deviation of group 1; must be ≥ 0s2::Real: standard deviation of group 2; must be ≥ 0n1::Int64: sample size of group 1; must be ≥ 2n2::Int64: sample size of group 2; must be ≥ 2type::Symbol=:cohen: pooling method::cohen:√(((n1−1)s1² + (n2−1)s2²) / (n1+n2−2)); requiresn1+n2 > 2:hedges:√(((n1−1)s1² + (n2−1)s2²) / (n1+n2))(MLE; slightly biased downward)
Returns
Float64: pooled standard deviation
stdp(s1, s2)Calculate the pooled standard deviation when both groups have equal size.
Computed as √((s1² + s2²) / 2).
Arguments
s1::Real: standard deviation of group 1; must be ≥ 0s2::Real: standard deviation of group 2; must be ≥ 0
Returns
Float64: pooled standard deviation
NeuroAnalyzer.summary — Function
summary(x; g)Return summary statistics for a single vector, printing a formatted table.
Arguments
x::AbstractVector: input data; may containMissingorNaNvalues (removed before computation)g::String="": optional group label shown in the table header
Returns
Named tuple:
n::Int64: total number of observations (including missing)ms::Int64: number of missing / NaN observationsm::Float64: meanv::Float64: variances::Float64: standard deviationmin::Float64: minimumq1::Float64: first quartile (25th percentile)me::Float64: medianq3::Float64: third quartile (75th percentile)max::Float64: maximummo::Float64: mode
summary(x; g, d)Return summary statistics for each column of a matrix, printing a formatted table.
Arguments
x::AbstractMatrix: data matrix; each column is treated as one group. may containMissingorNaNvaluesg::Vector{String}: group labels; length must equalsize(x, 2)d::Int64=3: number of decimal places for rounding
Returns
DataFrame: one row per group with columns:group,:n,:missing,:mean,:var,:std,:min,:Q1,:median,:Q3,:max,:mode
summary(x; g, d)Return summary statistics for each vector in a varargs list, printing a formatted table.
Arguments
x::AbstractArray...: one or more data vectors (passed as positional arguments)g::Vector{String}: group labels; length must equal the number of vectorsd::Int64=3: number of decimal places for rounding
Returns
DataFrame: one row per group with columns:group,:n,:missing,:mean,:var,:std,:min,:Q1,:median,:Q3,:max,:mode
NeuroAnalyzer.sumsq — Function
sumsq(x)Calculate the sum of squared deviations from the mean.
Computed as Σ(xᵢ − x̄)².
Arguments
x::AbstractVector: input vector; must contain at least 2 elements
Returns
Float64: sum of squared deviations
NeuroAnalyzer.t2p — Function
t2p(t; <keyword arguments>)Convert a t-score to a p-value using the Student's t-distribution.
Arguments
t::Real: t-statisticdf::Real: degrees of freedom; must be > 0twotailed::Bool=false: iftrue, computeP(|T| > |t|); iffalse, computeP(T > t)fort ≥ 0orP(T < t)fort < 0
Returns
Float64: p-value ∈(0, 1)
Notes
Derived probabilities:
P(T < t)(left-tailed):1 - t2p(t; df=df, twotailed=false)P(|T| < t):1 - t2p(t; df=df, twotailed=true)P(0 < T < t):(1 - t2p(t; df=df, twotailed=true)) / 2
NeuroAnalyzer.varc — Function
varc(g, x)Calculate the variance of categorical data using group labels and counts.
Arguments
g::Vector{Int64}: group labels (e.g.[0, 1, 2, 3])x::Vector{Int64}: number of subjects per group (e.g.[2, 8, 27, 45]); must be the same length asg, non-empty, and sum to > 1
Returns
Float64: variance of the categorical variable
Notes
Formula: (Σ(g² × x) − (Σ(g × x))² / Σx) / (Σx − 1)
NeuroAnalyzer.varp — Function
varp(p, n)Calculate the variance of a proportion.
Computed as p × (1 − p) / n (the variance of a binomial proportion estimator).
Arguments
p::Float64: proportion; must be in[0, 1]n::Int64: number of observations; must be ≥ 1
Returns
Float64: variance of the proportion
NeuroAnalyzer.z2p — Function
z2p(z; <keyword arguments>)Convert a Z-score to a p-value.
Arguments
z::Real: Z-scoretwotailed::Bool=false: iftrue, compute the two-tailed probabilityP(|Z| > |z|); iffalse, compute the one-tailed probabilityP(Z > z)forz ≥ 0orP(Z < z)forz < 0.
Returns
Float64: p-value ∈(0, 1)
Notes
Derived probabilities:
P(Z < z)(left-tailed):1 - z2p(z; twotailed=false)P(|Z| < z):1 - z2p(z; twotailed=true)P(0 < Z < z):(1 - z2p(z; twotailed=true)) / 2
NeuroAnalyzer.zscore — Function
zscore(x)Calculate Z-scores for each element of a vector.
Computed as (xᵢ − mean(x)) / std(x).
Arguments
x::AbstractVector: input vector; must contain at least 2 elements and have non-zero standard deviation
Returns
Vector{Float64}: Z-scores with mean ≈ 0 and SD ≈ 1
zscore(x, m, sd)Calculate the Z-score of a single value given a known mean and standard deviation.
Computed as (x − m) / sd.
Arguments
x::Real: observed valuem::Real: population or sample meansd::Real: population or sample standard deviation; must not be zero
Returns
Float64: Z-score
IO
NeuroAnalyzer.export_csv — Function
export_csv(obj; <keyword arguments>)Export a NeuroAnalyzer.NEURO object to CSV (and optional sidecar files).
The primary signal data is always written to file_name. When the corresponding flag is true, companion files are created next to it using the same base name:
| Option | Output file |
|---|---|
header=true | <base>_header.txt |
epoch_time=true | <base>_epoch_time.csv |
markers=true | <base>_markers.csv |
locs=true | <base>_locs.csv |
history=true | <base>_history.txt |
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfile_name::String: path of the primary output CSV filenames::Bool=true: write channel names as the CSV header rowheader::Bool=false: export recording/subject/experiment metadata to a sidecar text fileepoch_time::Bool=false: export per-epoch time points to a sidecar CSVmarkers::Bool=false: export event markers to a sidecar CSV (skipped when the markers table is empty)locs::Bool=false: export channel locations to a sidecar CSV (skipped when the locations table is empty)history::Bool=false: export processing history to a sidecar text file (skipped when history is empty)overwrite::Bool=false: allow overwriting existing files; throwsArgumentErrorotherwise
Returns
Nothing
NeuroAnalyzer.export_locs — Function
export_locs(obj; <keyword arguments>)Export channel location data from a NeuroAnalyzer.NEURO object to a file.
The output format is determined automatically from file_name's extension:
| Extension | Format |
|---|---|
.csv | Full locations table (all columns) |
.ced | EEGLAB CED - tab-separated with header |
.locs | EEGLAB .locs - tab-separated, no header |
.tsv | BIDS-style TSV - tab-separated with header |
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfile_name::String: output file path; extension determines the formatoverwrite::Bool=false: allow overwriting an existing file; throwsArgumentErrorotherwise
Returns
Nothing
export_locs(locs; <keyword arguments>)Export a channel-locations DataFrame to a file.
The output format is determined automatically from file_name's extension:
| Extension | Format |
|---|---|
.ced | EEGLAB CED - tab-separated with header |
.locs | EEGLAB .locs - tab-separated, no header |
.tsv | BIDS-style TSV - tab-separated with header |
Arguments
locs::DataFrame: channel locations table (must contain the standard NeuroAnalyzer location columns)file_name::String: output file path; extension determines the formatoverwrite::Bool=false: allow overwriting an existing file; throwsArgumentErrorotherwise
Returns
Nothing
NeuroAnalyzer.export_markers — Function
export_markers(obj; <keyword arguments>)Export the event markers table of a NeuroAnalyzer.NEURO object to a CSV file.
If the markers table is empty, a warning is issued and no file is written.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfile_name::String: path of the output CSV fileoverwrite::Bool=false: allow overwriting an existing file; throwsArgumentErrorotherwise
Returns
Nothing
NeuroAnalyzer.import_alice4 — Function
import_alice4(file_name; <keyword arguments>)Load an EDF file exported from the Alice 4 Polysomnography System and return a NeuroAnalyzer.NEURO object.
Alice 4 EDF files are non-conforming in two ways that prevent import_edf from handling them:
- The
data_recordsheader field is always-1(unknown); the true record count is inferred from file size. - Channels may have different sampling rates; they are upsampled to the highest rate using Fourier resampling.
Arguments
file_name::String: name of the file to loaddetect_type::Bool=true: infer channel type from channel label
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_bdf — Function
import_bdf(file_name; <keyword arguments>)Load a BDF or BDF+ file and return a NeuroAnalyzer.NEURO object.
BDF is BioSemi's 24-bit extension of the EDF format. Each sample is stored as a 24-bit little-endian two's-complement integer. BDF files always carry a Status channel as their last channel; BDF+ files may additionally contain annotation channels which are parsed into event markers and removed from the signal data.
Arguments
file_name::String: name of the file to loaddetect_type::Bool=true: infer channel type from channel label
Returns
NeuroAnalyzer.NEURO
Notes
sampling_rate = samples_per_datarecord ÷ data_record_durationgain = (physical_max − physical_min) / (digital_max − digital_min)value = (raw − digital_min) × gain + physical_min
References
- https://www.biosemi.com/faq/file_format.htm
NeuroAnalyzer.import_bv — Function
import_bv(file_name; <keyword arguments>)Load a BrainVision BV/BVCDF recording and return a NeuroAnalyzer.NEURO object.
At minimum two files are required: a .vhdr (or .ahdr) header file and the corresponding .eeg signal file. Event markers are loaded automatically from the .vmrk file when present, or from a BIDS-style _events.tsv sidecar.
Channel locations are read from the [Coordinates] section of the header when available. A BIDS JSON sidecar (.json) is parsed for experiment metadata.
Arguments
file_name::String: path to the.vhdror.ahdrheader filedetect_type::Bool=true: infer channel type from channel label
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_cnt — Function
import_cnt(file_name; <keyword arguments>)Load a Neuroscan continuous signal (CNT) file and return a NeuroAnalyzer.NEURO object.
CNT files store a fixed 900-byte global header, a per-channel header block (75 bytes × number of channels), multiplexed signal data, and an event table. Three event-table variants are supported (TEEG types 1, 2, and 3).
Arguments
file_name::String: name of the file to loaddetect_type::Bool=true: infer channel type from channel labeldata_format::Symbol=:i32: sample width;:i16for 16-bit or:i32for 32-bit; Neuroscan does not encode this in the file header - you must supply it based on your recording setup
Returns
NeuroAnalyzer.NEURO
Notes
Based on loadcnt.m by Sean Fitzgibbon and Arnaud Delorme (https://cnl.salk.edu/~arno/cntload/index.html).
NeuroAnalyzer.import_csv — Function
import_csv(file_name; <keyword arguments>)Load a CSV (or gzip-compressed CSV) file and return a NeuroAnalyzer.NEURO object.
The file layout (time × channels or channels × time) is detected automatically from the type of the first column:
- Time × channels: first column is numeric (time axis); remaining columns are channels labelled by their header row.
- Channels × time: first column is a string (channel names); remaining column headers are parsed as time points.
Sampling rate is inferred from the step between the first two time points.
Gzip-compressed files (.csv.gz) are decompressed automatically by CSV.jl.
Arguments
file_name::String: path to the.csvor.csv.gzfiledetect_type::Bool=true: infer channel type from channel label
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_dat — Function
import_dat(file_name)Load a Neuroscan DAT behavioural data file and return it as a DataFrame.
The DAT format has a 20-line text header followed by space-separated data rows with five columns: event index, trial number, response, type, and correctness flag. Event indices are stored as 1-based in the file and are converted to 0-based on import to match Neuroscan's convention.
Arguments
file_name::String: path to the.datfile
Returns
DataFrame: table with columns:event,:trial,:response,:type,:correct
NeuroAnalyzer.import_digitrack — Function
import_digitrack(file_name; <keyword arguments>)Load a Digitrack ASCII EEG file and return a NeuroAnalyzer.NEURO object.
The Digitrack ASCII format has a 3-line text header followed by one line per channel (label and prefiltering, tab-separated), a blank separator line, and then tab-separated signal samples (one column per channel per row).
Arguments
file_name::String: path to the Digitrack ASCII filedetect_type::Bool=true: infer channel type from channel label
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_duomag — Function
import_duomag(file_name)Load a DuoMAG TMS MEP recording file (.ascii or .m) and return a NeuroAnalyzer.NEURO object.
Both file formats carry metadata (subject, recording info, stimulation parameters), per-channel MEP signals, and positive/negative peak markers. Signal data are baseline-corrected, stimulation artifacts suppressed, and amplitudes scaled to μV on import.
Arguments
file_name::String: path to the.asciior.mfile
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_edf — Function
import_edf(file_name; <keyword arguments>)Load an EDF or EDF+ file and return a NeuroAnalyzer.NEURO object.
Annotation-only channels (EDF+ TAL) are automatically detected, parsed into event markers, and then removed from the signal data. When channels have mixed sampling rates they are upsampled to the highest rate using Fourier resampling.
Arguments
file_name::String: path to the EDF/EDF+ file to loaddetect_type::Bool=true: infer channel type from channel label
Returns
NeuroAnalyzer.NEURO
Notes
sampling_rate = samples_per_datarecord ÷ data_record_durationgain = (physical_max - physical_min) / (digital_max - digital_min)value = (raw_value - digital_min) × gain + physical_min
References
- Kemp B et al. A simple format for exchange of digitized polygraphic recordings. EEG Clin Neurophysiol. 1992;82(5):391-3.
- Kemp B, Olivan J. European data format 'plus' (EDF+). Clin Neurophysiol. 2003;114:1755-61.
- https://www.edfplus.info/specs/
NeuroAnalyzer.import_edf_annotations — Function
import_edf_annotations(file_name; <keyword arguments>)Load annotations from an EDF+ annotation-only file and return a DataFrame of event markers.
This function is intended for EDF+ files whose data_records_duration header field is 0, meaning the file contains only TAL (Time-stamped Annotations Lists) and no signal data. For regular EDF/EDF+ files with signal data, use import_edf() instead - it parses annotations automatically.
Arguments
file_name::String: path to the EDF+ annotation file
Returns
DataFramewith columns:id,:start,:length,:value,:channel
NeuroAnalyzer.import_fiff — Function
import_fiff(file_name)Load an Elekta-Neuromag FIFF file (MEG or EEG) and return a NeuroAnalyzer.NEURO object.
Arguments
file_name::String: path to the.fifor.fifffile
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_ft — Function
import_ft(file_name; <keyword arguments>)Load a FieldTrip MATLAB (.mat) file and return a NeuroAnalyzer.NEURO object or a markers DataFrame.
FieldTrip stores EEG, MEG, fNIRS data and event tables in separate .mat files. The type argument selects which data type to import. Markers are always stored separately in FieldTrip and must be imported with type = :events, then added with add_markers().
Arguments
file_name::String: path to the.matfiletype::Symbol: data type to import; one of:eeg,:meg,:nirs,:eventsdetect_type::Bool=false: infer channel type from channel label
Returns
NeuroAnalyzer.NEUROfor EEG, MEG, and fNIRS dataDataFramefor event tables
NeuroAnalyzer.import_gdf — Function
import_gdf(file_name; <keyword arguments>)Load a GDF (General Dataformat for Biosignals) file and return a NeuroAnalyzer.NEURO object.
Both GDF 1.x and GDF 2.x variants are supported. Channels may have mixed data types; all are converted to Float64 on import. The event table (ETP block) is parsed into a markers DataFrame when present.
Arguments
file_name::String: path to the.gdffiledetect_type::Bool=true: infer channel type from channel label
Returns
NeuroAnalyzer.NEURO
Notes
sampling_rate = samples_per_datarecord ÷ data_record_durationgain = (physical_max − physical_min) / (digital_max − digital_min)value = (raw − digital_min) × gain + physical_min
References
- Schlögl A et al. GDF v1.25. 1998.
- Schlögl A. GDF v2.12. 2009.
- Schlögl A. GDF v2.51. 2013.
NeuroAnalyzer.import_locs — Function
import_locs(file_name)Load channel locations from a file. The format is detected from the extension.
Supported formats: CED, ELC, LOCS, TSV, SFP, CSD, GEO, MAT, TXT, DAT, ASC, CSV.
Arguments
file_name::String: path to the locations file
Returns
DataFrame
NeuroAnalyzer.import_locs_asc — Function
import_locs_asc(file_name)Load channel locations from an ASC file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_ced — Function
import_locs_ced(file_name)Load channel locations from a CED (EEGLAB) file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_csd — Function
import_locs_csd(file_name)Load channel locations from a CSD file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_csv — Function
import_locs_csv(file_name)Load channel locations from a NeuroAnalyzer standard CSV file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_dat — Function
import_locs_dat(file_name)Load channel locations from a DAT file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_elc — Function
import_locs_elc(file_name)Load channel locations from an ELC file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_geo — Function
import_locs_geo(file_name)Load channel locations from a GEO file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_locs — Function
import_locs_locs(file_name)Load channel locations from an EEGLAB LOCS file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_mat — Function
import_locs_mat(file_name)Load channel locations from a MATLAB MAT file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_sfp — Function
import_locs_sfp(file_name)Load channel locations from an SFP file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_tsv — Function
import_locs_tsv(file_name)Load channel locations from a TSV (BIDS-style) file.
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_locs_txt — Function
import_locs_txt(file_name)Load channel locations from a TXT file (spherical theta/phi format).
Arguments
file_name::String
Returns
DataFrame
NeuroAnalyzer.import_montage — Function
import_montage(file_name)Load a montage definition from a plain-text file.
The file format is:
- Line 1: montage name (e.g.
longitudinal-BIP) - Subsequent lines: one channel or channel pair per line (e.g.
Fp1,Fz-Cz)
Blank lines and lines beginning with # are ignored, so comments and trailing newlines do not corrupt the channel list.
Example montage files are located in the montages/ folder.
Each channel/channel pair must be in a separate line
Arguments
file_name::String: path to the montage text file
Returns
Named tuple:
ref_list::Vector{String}: list of channel / channel-pair stringsref_name::String: name of the montage
NeuroAnalyzer.import_ncs — Function
import_ncs(file_name)Load a Neuralynx Continuously Sampled Channels (CSC/NCS) file and return a NeuroAnalyzer.NEURO object.
NCS files have a fixed 16 KiB text header followed by data blocks of 1044 bytes each. Each block contains a timestamp, channel number, sampling frequency, valid sample count, and 512 Int16 samples. Blocks with fewer than 512 valid samples are handled correctly.
Arguments
file_name::String: path to the.ncsfile
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_nirs — Function
import_nirs(file_name)Load a Homer3-compatible NIRS file and return a NeuroAnalyzer.NEURO object.
The NIRS format is a MATLAB .mat file containing raw intensity data (d), a time vector (t), a probe structure (SD), stimulus onset matrix (s), and optional auxiliary channels (aux).
Arguments
file_name::String: path to the.nirsfile
Returns
NeuroAnalyzer.NEURO
References
- https://github.com/BUNPC/Homer3/wiki/HOMER3-file-formats
NeuroAnalyzer.import_nirx — Function
import_nirx(file_name)Load NIRX file and return NeuroAnalyzer.NEURO object.
Arguments
file_name::String: name of the file to load, should point to .hdr file.
Returns
NeuroAnalyzer.NEURO
References
- https://nirx.net/file-formats
NeuroAnalyzer.import_npy — Function
import_npy(file_name; <keyword arguments>)Load NPY file (exported from MNE) and return NeuroAnalyzer.NEURO object. Data type and channel types are set as is EEG.
Arguments
file_name::String: name of the file to loadsampling_rate::Int64: NPY file contains only signal data, therefore its sampling rate must be provided upon importing
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.import_nwb — Function
import_nwb(file_name; <keyword arguments>)Load EEG data from Neurodata Without Borders (NWB) file and return NeuroAnalyzer.NEURO object.
Arguments
file_name::String: name of the file to loaddetect_type::Bool=true: detect channel type based on its label
Returns
NeuroAnalyzer.NEURO
References
- https://www.biorxiv.org/content/10.1101/523035v1
NeuroAnalyzer.import_recording — Function
import_recording(file_name; <keyword arguments>)Load a recording file and return a NeuroAnalyzer.NEURO object.
This is a meta-function: it detects the file format from the extension and delegates to the appropriate import_*() function. The signal data type (EEG, MEG, fNIRS, …) is auto-detected where possible and stored in obj.header.recording[:data_type].
Supported formats and their extensions:
| Format | Extension(s) |
|---|---|
| EDF / EDF+ | .edf |
| BDF / BDF+ | .bdf |
| GDF | .gdf |
| BrainVision | .vhdr, .ahdr |
| CSV (plain or gzip-compressed) | .csv, .csv.gz |
| EEGLAB dataset | .set |
| MNE NumPy array | .npy |
| Extensible Data Format | .xdf |
| Neurodata Without Borders | .nwb |
| Neuralynx CSC | .ncs |
| Neuromag FIFF | .fif, .fiff |
| FieldTrip MATLAB | .mat |
| SNIRF | .snirf |
| NIRS | .nirs |
| DuoMAG TMS MEP | .ascii, .m |
Arguments
file_name::String: name of the file to loaddetect_type::Bool=true: infer channel type from channel labeltype::Union{Nothing, Symbol}=nothing: data type for FieldTrip (.mat) files, where auto-detection is not possible; one of:eeg,:meg,:nirs,:eventssampling_rate::Union{Nothing, Int64}=nothing: sampling rate for.npyfiles, which store only raw signal data with no embedded metadatan::Int64=0: subject index to extract from multi-subject SNIRF files
Returns
NeuroAnalyzer.NEURO: for EEG, MEG, and fNIRS dataDataFrame: whentype = :events(FieldTrip.matfiles)
NeuroAnalyzer.import_set — Function
import_set(file_name; <keyword arguments>)Load SET file (exported from EEGLAB) and return NeuroAnalyzer.NEURO object.
Arguments
file_name::String: name of the file to loaddetect_type::Bool=true: detect channel type based on its label
Returns
NeuroAnalyzer.NEURO
References
- https://eeglab.org/tutorials/ConceptsGuide/Data_Structures.html
NeuroAnalyzer.import_snirf — Function
import_snirf(file_name; <keyword arguments>)Load Shared Near Infrared Spectroscopy Format (SNIRF) file and return NeuroAnalyzer.NEURO object.
Arguments
file_name::String: name of the file to loadn::Int64=0: subject number to extract in case of multi-subject file
Returns
NeuroAnalyzer.NEURO
References
- https://github.com/fNIRS/snirf/blob/v1.1/snirf_specification.md
NeuroAnalyzer.import_thymatron — Function
import_thymatron(file_name)Import scanned images of EEG printed by Thymatron ECT equipment and return NeuroAnalyzer.NEURO object.
Usually there are three images: baseline, during seizure activity and after seizure activity. If more then one image is provided, images are added as consecutive channels in the same object.
Image properties:
- 100 DPI
- 490 x 100 px
- height 2.5 cm
- width 12.5 cm
Arguments
file_name::Union{String, Vector{String}}: name(s) of the file(s) to loaddpi::Int64=100: DPI of the scanned images
Returns
NeuroAnalyzer.NEURO
References
- Wysokiński A. EEG_ADC: Digitizer and Analyzer of Electroconvulsive Therapy Paper Electroencephalogram Recordings. JECT 2022; 4: 255-256
NeuroAnalyzer.import_xdf — Function
import_xdf(file_name)Load Extensible Data Format (XDF) and return NeuroAnalyzer.NEURO object.
Arguments
file_name::String: name of the file to load
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.load — Function
load(file_name)Load NeuroAnalyzer.NEURO object from file_name file (HDF5-based).
Arguments
file_name::String: name of the file to load
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.load_fiff — Function
load_fiff(file_name)Load an Elekta-Neuromag FIFF (Functional Image File Format) file and return the parsed FIFF structure.
Arguments
file_name::String: path to the.fifor.fifffile
Returns
Dict{Symbol, Dict{Any, Any}}: FIFF structureVector{Any}: FIFF objectMatrix{Int64}: FIFF blocks
References
- Elekta Neuromag: Functional Image File Format Description. FIFF v1.3, 2011.
NeuroAnalyzer.load_locs — Function
load_locs(obj; <keyword arguments>)Load channel locations from file_name and return NeuroAnalyzer.NEURO object with locs data frame.
Accepted formats:
- CED
- LOCS
- ELC
- TSV
- SFP
- CSD
- GEO
- MAT
- TXT
- DAT
- ASC
- CSV
Channel locations:
loc_theta: polar angleloc_radius: polar radiusloc_x: spherical Cartesian xloc_y: spherical Cartesian yloc_z: spherical Cartesian zloc_radius_sph: spherical radiusloc_theta_sph: spherical horizontal angleloc_phi_sph: spherical azimuth angle
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfile_name::String: name of the file to load
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.load_locs! — Function
load_locs!(obj; <keyword arguments>)Load channel locations from file_name and return NeuroAnalyzer.NEURO object with locs data frame.
Accepted formats:
- CED
- LOCS
- ELC
- TSV
- SFP
- CSD
- GEO
- MAT
- TXT
- DAT
- ASC
Channel locations:
loc_theta: polar angleloc_radius: polar radiusloc_x: spherical Cartesian xloc_y: spherical Cartesian yloc_z: spherical Cartesian zloc_radius_sph: spherical radiusloc_theta_sph: spherical horizontal angleloc_phi_sph: spherical azimuth angle
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfile_name::String: name of the file to load
Return
Nothing
NeuroAnalyzer.save — Function
save(obj; <keyword arguments>)Save NeuroAnalyzer.NEURO object to file_name file (HDF5-based).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfile_name::String: name of the file to save tooverwrite::Bool=false
Return
Nothing
Edit
NeuroAnalyzer.add_channel — Function
add_channel(obj; <keyword arguments>)Return a copy of obj with new channel(s) appended.
If obj.data is empty the object is initialized with the provided data; otherwise the new channels are concatenated along the first (channel) dimension.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdata::Array{<:Number, 3}: channel data, shape (chn, epochlen, epoch_n)label::Union{String, Vector{String}}: channel label(s)type::Union{String, Vector{String}}: channel type(s)unit::Union{String, Vector{String}}: channel unit(s)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.add_channel! — Function
add_channel!(obj; <keyword arguments>)Add new channel(s) in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdata::Array{<:Number, 3}: channel data, shape (chn, epochlen, epoch_n)label::Union{String, Vector{String}}: channel label(s)type::Union{String, Vector{String}}: channel type(s)unit::Union{String, Vector{String}}: channel unit(s)
Returns
Nothing
NeuroAnalyzer.add_label — Function
add_label(obj; <keyword arguments>)Return a copy of obj with channel labels replaced.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectclabels::Vector{String}: new labels; must have length equal tonchannels(obj)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.add_label! — Function
add_label!(obj; <keyword arguments>)Replace channel labels in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectclabels::Vector{String}: new labels; must have length equal tonchannels(obj)
Returns
Nothing
NeuroAnalyzer.add_marker — Function
add_marker(obj; <keyword arguments>)Append a new marker.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectid::String: marker IDstart::Real: marker start time in seconds (must be ≥ 0 and within signal)len::Real=1.0: marker duration in seconds (must be > 0)value::String: marker valuech::Int64=0: channel number;0means the marker applies to all channels
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.add_marker! — Function
add_marker!(obj; <keyword arguments>)Add a marker in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectid::String: marker IDstart::Real: marker start time in seconds (must be ≥ 0 and within signal)len::Real=1.0: marker duration in seconds (must be > 0)value::String: marker valuech::Int64=0: channel number;0means the marker applies to all channels
Returns
Nothing
NeuroAnalyzer.add_markers — Function
add_markers(obj; <keyword arguments>)Return a copy of obj with its marker table replaced by markers.
The provided DataFrame must have exactly the columns: id, start, length, value, channel.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectmarkers::DataFrame: replacement marker table
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.add_markers! — Function
add_markers!(obj; <keyword arguments>)Replace obj's marker table in-place.
The provided DataFrame must have exactly the columns: id, start, length, value, channel.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectmarkers::DataFrame: replacement marker table
Returns
Nothing
NeuroAnalyzer.channel2marker — Function
channel2marker(obj; <keyword arguments>)Return a copy of obj with events detected in an event channel added as markers.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelv::Real=1.0: signal value interpreted as an eventid::String: prefix for generated marker IDs (default: channel name +"_")value::String="": marker value string (default: channel label)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.channel2marker! — Function
channel2marker!(obj; <keyword arguments>)Convert an event channel to markers in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelv::Real=1.0: signal value interpreted as an eventid::String: prefix for generated marker IDs (default: channel name +"_")value::String="": marker value string (default: channel label)
Returns
Nothing
NeuroAnalyzer.channel_reject — Function
channel_reject(obj; <keyword arguments>)Detect bad channels using one or more artifact-detection methods.
A channel is marked bad if any of the selected methods flags it in at least one epoch. The returned mask has one entry per selected channel.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)method::Union{Symbol, Vector{Symbol}}=[:flat, :rmse, :rmsd, :euclid, :var, :p2p, :tkeo, :kurt, :z, :ransac, :amp]: one or more detection methods (see below); default: all available methods.w::Int64=sr(obj): sliding-window width in samples (default = 1 s)flat_tol::Float64=0.1: flatness tolerance; a segment is flat if|diff(window_mean)| < flat_tol.flat_fr::Float64=0.3: maximum acceptable fraction of flat windows before marking a channel as badp::Float64=0.99: probability threshold for:p2p,:tkeo, and:zmethods; interpreted as a percentile (converted internally to a z-score)tc::Float64=0.2: reserved threshold parameter (not currently used by all methods)tkeo_method::Symbol=:pow: TKEO variant; seetkeo()for optionsz::Real=3: z-score threshold for:kurtand:zmethods; must be > 0ransac_r::Float64=0.8: minimum acceptable Pearson r between a channel and its nearest neighbor (:ransacmethod)ransac_tr::Float64=0.4: maximum acceptable fraction of windows belowransac_rbefore marking a channel badransac_t::Float64=100.0: RANSAC inlier distance threshold (in signal units)amp_t::Real=400.0: amplitude rejection threshold; channels withmax > +amp_tormin < −amp_tare flagged
Detection methods
:flat: channels with a large proportion of flat windows:rmse: channels whose RMSE vs the median reference is outside the 95 % CI:rmsd: same as:rmseusing RMSD:euclid: same using Euclidean distance:var: channels with IQR-outlier variance:p2p: channels with excessive peak-to-peak variation:tkeo: channels where z-scored TKEO diverges from z-scored signal:kurt: channels with z-scored kurtosis exceedingz:z: channels with a large proportion of samples above the z-score threshold:ransac: channels poorly correlated with their nearest spatial neighbor:amp: channels exceeding ±amp_t
Returns
Vector{Bool}: bad-channel mask (length = number of selected channels);true= bad
NeuroAnalyzer.channel_reject! — Function
channel_reject!(obj; <keyword arguments>)Detect bad channels and update the :bad_channel field in the object header in-place.
A channel is marked bad if any of the selected methods flags it in at least one epoch. The returned mask has one entry per selected channel.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)method::Union{Symbol, Vector{Symbol}}=[:flat, :rmse, :rmsd, :euclid, :var, :p2p, :tkeo, :kurt, :z, :ransac, :amp]: one or more detection methods (see below); default: all available methods.w::Int64=sr(obj): sliding-window width in samples (default = 1 s)flat_tol::Float64=0.1: flatness tolerance; a segment is flat if|diff(window_mean)| < flat_tol.flat_fr::Float64=0.3: maximum acceptable fraction of flat windows before marking a channel as badp::Float64=0.99: probability threshold for:p2p,:tkeo, and:zmethods; interpreted as a percentile (converted internally to a z-score)tc::Float64=0.2: reserved threshold parameter (not currently used by all methods)tkeo_method::Symbol=:pow: TKEO variant; seetkeo()for optionsz::Real=3: z-score threshold for:kurtand:zmethods; must be > 0ransac_r::Float64=0.8: minimum acceptable Pearson r between a channel and its nearest neighbor (:ransacmethod)ransac_tr::Float64=0.4: maximum acceptable fraction of windows belowransac_rbefore marking a channel badransac_t::Float64=100.0: RANSAC inlier distance threshold (in signal units)amp_t::Real=400.0: amplitude rejection threshold; channels withmax > +amp_tormin < −amp_tare flagged
Detection methods
:flat: channels with a large proportion of flat windows:rmse: channels whose RMSE vs the median reference is outside the 95 % CI:rmsd: same as:rmseusing RMSD:euclid: same using Euclidean distance:var: channels with IQR-outlier variance:p2p: channels with excessive peak-to-peak variation:tkeo: channels where z-scored TKEO diverges from z-scored signal:kurt: channels with z-scored kurtosis exceedingz:z: channels with a large proportion of samples above the z-score threshold:ransac: channels poorly correlated with their nearest spatial neighbor:amp: channels exceeding ±amp_t
Returns
Nothing
NeuroAnalyzer.channel_type — Function
channel_type(obj; <keyword arguments>)Return the type string of a single channel.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channel
Returns
String: channel type (e.g."eeg","eog")
NeuroAnalyzer.chop — Function
chop(obj; <keyword arguments>)Reduce signal by removing reflected signal before the signal and after the signal, i.e. a signal 432112344321 becomes 1234.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64=sr(obj): number of samples to remove, default is 1 second
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.chop! — Function
chop!(obj; <keyword arguments>)Reduce signal by removing reflected signal before the signal and after the signal, i.e. a signal 432112344321 becomes 1234.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64=sr(obj): number of samples to remove, default is 1 second
Returns
Nothing
NeuroAnalyzer.create_data — Function
create_data(obj; <keyword arguments>)Return a copy of obj with data, channel metadata and time vectors populated.
Auto-generates channel labels of the form "ch-1", "ch-2", … and sets channel type and units uniformly for all new channels.
obj must be empty (no data, no time points).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdata::Array{Float64, 3}: signal data, shape (chn, epochlen, n_epochs)fs::Int64: sampling rate in Hz; must be > 0type::String: channel type applied to all channels (must be a recognized type)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.create_data! — Function
create_data!(obj; <keyword arguments>)Populate obj with data, channel metadata and time vectors in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdata::Array{Float64, 3}: signal data, shape (chn, epochlen, n_epochs)fs::Int64: sampling rate in Hz; must be > 0type::String: channel type applied to all channels (must be a recognized type)
Returns
Nothing
NeuroAnalyzer.create_object — Function
create_object(; <keyword arguments>)Create an empty NeuroAnalyzer.NEURO object of the specified data type.
All data, time, and header fields are initialized to empty/zero values. Use create_data! to populate with signal data and create_time! to set the sampling rate and build time vectors.
Arguments
data_type::String: data type of the new object (must be a recognized type)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.create_time — Function
create_time(obj; <keyword arguments>)Return a copy of obj with time vectors built from a specified sampling rate.
obj must already contain data and must not already have time points assigned.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfs::Int64: sampling rate in Hz; must be > 0
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.create_time! — Function
create_time!(obj; <keyword arguments>)Build time vectors from a specified sampling rate in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfs::Int64: sampling rate in Hz; must be > 0
Returns
Nothing
NeuroAnalyzer.crop — Function
crop(obj; <keyword arguments>)Crop signal by removing parts of the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectseg::Tuple{Real, Real}: segment to be cropped (from, to) in seconds
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.crop! — Function
crop!(obj; <keyword arguments>)Crop signal by removing parts of the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectseg::Tuple{Real, Real}: segment to be cropped (from, to) in seconds
Returns
Nothing
NeuroAnalyzer.delete_channel — Function
delete_channel(obj; <keyword arguments>)Return a copy of obj with the specified channel(s) removed.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s) to removedel_opt::Bool=false: settrueonly when called fromdelete_optode(); bypasses the NIRS guard that prevents direct signal-channel deletion
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.delete_channel! — Function
delete_channel!(obj; <keyword arguments>)Delete channel(s) in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel nanme(s) to removedel_opt::Bool=false: settrueonly when called fromdelete_optode(); bypasses the NIRS guard that prevents direct signal-channel deletion
Returns
Nothing
NeuroAnalyzer.delete_epoch — Function
delete_epoch(obj; <keyword arguments>)Return a copy of obj with the specified epoch(s) removed.
Markers within deleted epochs are dropped; markers after deleted epochs are shifted to remain aligned with the new time axis.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: epoch numbers to remove
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.delete_epoch! — Function
delete_epoch!(obj; <keyword arguments>)Delete epoch(s) in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: epoch numbers to remove
Returns
Nothing
NeuroAnalyzer.delete_marker — Function
delete_marker(obj; <keyword arguments>)Delete a marker.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64: marker number
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.delete_marker! — Function
delete_marker!(obj; <keyword arguments>)Delete a marker in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64: marker number
Returns
Nothing
NeuroAnalyzer.delete_optode — Function
delete_optode(obj; <keyword arguments>)Return a copy of obj with the specified NIRS optode(s) and all their associated channels removed.
Source or detector labels, optode-pair mappings, and channel location entries are all updated consistently. Associated NIRS signal channels are removed via delete_channel!.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectopt::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: optode number(s) to remove
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.delete_optode! — Function
delete_optode!(obj; <keyword arguments>)Delete optode(s) in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectopt::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: optode number(s) to be removed
Returns
Nothing
NeuroAnalyzer.detect_amp — Function
Return true for each channel whose peak amplitude exceeds ±amp_t.
NeuroAnalyzer.detect_euclid — Function
Return true for each channel whose Euclidean distance to the cross-channel median lies outside the 95 % CI of the per-channel distance distribution.
NeuroAnalyzer.detect_p2p — Function
Return true for each channel with excessive peak-to-peak variation.
Sliding-window means are computed, their differences are rounded to the nearest 100, and a channel is flagged if any rounded difference falls outside [mean − p_z×std, mean + p_z×std] where p_z = Φ⁻¹(p).
NeuroAnalyzer.detect_ransac — Function
Return true for each channel whose correlation with its nearest spatial neighbour (outliers removed via RANSAC) falls below ransac_r in more than ransac_tr proportion of sliding windows.
NeuroAnalyzer.detect_rmsd — Function
Return true for each channel whose RMSD vs the cross-channel median lies outside the 95 % CI of the per-channel RMSD distribution.
NeuroAnalyzer.detect_rmse — Function
Return true for each channel whose RMSE vs the cross-channel median lies outside the 95 % confidence interval of the per-channel RMSE distribution.
NeuroAnalyzer.detect_tkeo — Function
Return true for each channel with at least two 10-sample windows where the absolute z-scored signal exceeds the absolute z-scored TKEO by more than the z-score corresponding to p.
NeuroAnalyzer.edit_channel — Function
edit_channel(obj; <keyword arguments>)Return a copy of obj with one field of one channel's header entry changed.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelfield::Symbol: field to edit (:channel_typeor:label)value::String: new value
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.edit_channel! — Function
edit_channel!(obj; <keyword arguments>)Edit one field of one channel's header entry in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelfield::Symbol: field to edit (:channel_typeor:label)value::String: new value
Returns
Nothing
NeuroAnalyzer.edit_marker — Function
edit_marker(obj; <keyword arguments>)Edit a marker.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64: marker number to editid::String: marker IDstart::Real: marker start time in seconds (must be ≥ 0 and within signal)len::Real=1.0: marker duration in seconds (must be > 0)value::String: marker valuech::Int64=0: channel number;0means the marker applies to all channels
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.edit_marker! — Function
edit_marker!(obj; <keyword arguments>)Edit a marker in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64: marker number to editid::String: marker IDstart::Real: marker start time in seconds (must be ≥ 0 and within signal)len::Real=1.0: marker duration in seconds (must be > 0)value::String: marker valuech::Int64=0: channel number;0means the marker applies to all channels
Returns
Nothing
NeuroAnalyzer.epoch — Function
epoch(obj; <keyword arguments>)Return a copy of obj split into epochs.
Epochs are created either by splitting at marker positions (when marker is specified) or by dividing the signal into fixed-length windows (ep_len).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be continuous (1 epoch)marker::String="": marker value to split at; if empty, split byep_lenoffset::Real=0: time offset in seconds for marker-based epoching (each epoch begins atmarker_time - offset)ep_len::Union{Real, Nothing}=nothing: epoch length in seconds
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.epoch! — Function
epoch!(obj; <keyword arguments>)Split obj into epochs in-place.
Epochs are created either by splitting at marker positions (when marker is specified) or by dividing the signal into fixed-length windows (ep_len).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be continuous (1 epoch)marker::String="": marker value to split at; if empty, split byep_lenoffset::Real=0: time offset in seconds for marker-based epoching (each epoch begins atmarker_time - offset)ep_len::Union{Real, Nothing}=nothing: epoch length in seconds
Returns
Nothing
NeuroAnalyzer.epoch_reject — Function
epoch_reject(obj; <keyword arguments>)Detect bad epochs using one or more artifact-detection methods.
An epoch is marked bad if it contains at least nbad bad channels according to any of the selected methods.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)method::Union{Symbol, Vector{Symbol}}=[:flat, :rmse, :rmsd, :euclid, :var, :p2p, :tkeo, :kurt, :z, :ransac, :amp]: one or more detection methods (see below); default: all available methods.w::Int64=sr(obj): sliding-window width in samples (default = 1 s)flat_tol::Float64=0.1: flatness tolerance; a segment is flat if|diff(window_mean)| < flat_tol.flat_fr::Float64=0.3: maximum acceptable fraction of flat windows before marking a channel as badp::Float64=0.99: probability threshold for:p2p,:tkeo, and:zmethods; interpreted as a percentile (converted internally to a z-score)tc::Float64=0.2: reserved threshold parameter (not currently used by all methods)tkeo_method::Symbol=:pow: TKEO variant; seetkeo()for optionsz::Real=3: z-score threshold for:kurtand:zmethods; must be > 0ransac_r::Float64=0.8: minimum acceptable Pearson r between a channel and its nearest neighbor (:ransacmethod)ransac_tr::Float64=0.4: maximum acceptable fraction of windows belowransac_rbefore marking a channel badransac_t::Float64=100.0: RANSAC inlier distance threshold (in signal units)amp_t::Real=400.0: amplitude rejection threshold; channels withmax > +amp_tormin < −amp_tare flaggednbad::Int64=1: minimum number of bad channels to declare an epoch bad; must be in[1, nchannels(obj)]
Detection methods
:flat: channels with a large proportion of flat windows:rmse: channels whose RMSE vs the median reference is outside the 95 % CI:rmsd: same as:rmseusing RMSD:euclid: same using Euclidean distance:var: channels with IQR-outlier variance:p2p: channels with excessive peak-to-peak variation:tkeo: channels where z-scored TKEO diverges from z-scored signal:kurt: channels with z-scored kurtosis exceedingz:z: channels with a large proportion of samples above the z-score threshold:ransac: channels poorly correlated with their nearest spatial neighbor:amp: channels exceeding ±amp_t
Returns
Vector{Int64}: sorted, unique indices of bad epochs
NeuroAnalyzer.epoch_ts — Function
epoch_ts(obj; <keyword arguments>)Return a copy of obj with the epoch time axis shifted by ts seconds.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectts::Real: time shift in seconds (positive → later start, negative → earlier start)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.epoch_ts! — Function
epoch_ts!(obj; <keyword arguments>)Shift the epoch time axis by ts seconds in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectts::Real: time shift in seconds (positive → later start, negative → earlier start)
Returns
Nothing
NeuroAnalyzer.extract_channel — Function
extract_channel(obj; <keyword arguments>)Extract data from a single channel as a 3-D array.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channel
Returns
Array{Float64, 3}: shape (1, epoch_len, nepochs)
NeuroAnalyzer.extract_data — Function
extract_data(obj; <keyword arguments>)Extract signal data for specified channels and epochs.
Optionally return the corresponding time vectors alongside the data.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)ep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=1:nepochs(obj): index of epochs, default is all epochstime::Bool=false: iftrue, also returnobj.time_ptsetime::Bool=false: iftrue, also returnobj.epoch_time
Returns
Array{Float64, 3}: data, shape (nch, epochlen, n_ep)- Additionally
Vector{Float64}time points iftime=true - Additionally
Vector{Float64}epoch time ifetime=true
NeuroAnalyzer.extract_epoch — Function
extract_epoch(obj; <keyword arguments>)Return a new NEURO object containing only the specified epoch.
The returned object has a single epoch; time vectors are rebuilt consistently from the original epoch time axis
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep::Int64: epoch index
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.extract_epoch! — Function
extract_epoch!(obj; <keyword arguments>)Extract epoch.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep::Int64: epoch index
Returns
Nothing
NeuroAnalyzer.join — Function
join(obj1, obj2)Join two NeuroAnalyzer objects. Each obj2 epoch are horizontally concatenated (along time) with respective obj1 epoch. Both objects must have the same data type, number of channels, epochs and sampling rate, but may differ in epoch lengths.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO object
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.join! — Function
join!(obj1, obj2)Join two NeuroAnalyzer objects into the first object. Each obj2 epoch are horizontally concatenated (along time) with respective obj1 epoch. Both objects must have the same data type, number of channels, epochs and sampling rate, but may differ in epoch lengths.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO object
Returns
Nothing
NeuroAnalyzer.keep_channel — Function
keep_channel(obj; <keyword arguments>)Return a copy of obj retaining only the specified channel(s).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s) to keep
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.keep_channel! — Function
keep_channel!(obj; <keyword arguments>)Keep only the specified channel(s) in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s) to keep
Returns
Nothing
NeuroAnalyzer.keep_epoch — Function
keep_epoch(obj; <keyword arguments>)Return a copy of obj retaining only the specified epoch(s).
Implemented by computing the complement set and delegating to delete_epoch.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: epoch numbers to keep
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.keep_epoch! — Function
keep_epoch!(obj; <keyword arguments>)Keep only the specified epoch(s) in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: epoch numbers to keep
Returns
Nothing
NeuroAnalyzer.reflect — Function
reflect(obj; <keyword arguments>)Expand signal by adding reflected signal before the signal and after the signal, i.e. a signal 1234 becomes 432112344321. This may reduce edge artifacts, but will also affect amplitude of the filtered signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64=sr(obj): number of samples to add, default is 1 second
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.reflect! — Function
reflect!(obj; <keyword arguments>)Expand signal by adding reflected signal before the signal and after the signal, i.e. a signal 1234 becomes 432112344321. This may reduce edge artifacts, but will also affect amplitude of the filtered signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectn::Int64=sr(obj): number of samples to add, default is 1 second
Returns
Nothing
NeuroAnalyzer.rename_channel — Function
rename_channel(obj; <keyword arguments>)Return a copy of obj with one channel renamed. Also updates the matching entry in obj.locs if one exists.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelname::String: new name (must not already exist)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.rename_channel! — Function
rename_channel!(obj; <keyword arguments>)Rename one channel in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelname::String: new name (must not already exist)
Returns
Nothing
NeuroAnalyzer.replace_channel — Function
replace_channel(obj; <keyword arguments>)Return a copy of obj with one channel's data replaced.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channels::AbstractArray: replacement data, shape (1, epoch_len, nepochs)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.replace_channel! — Function
replace_channel!(obj; <keyword arguments>)Replace one channel's data in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channels::Array{Float64, 3}: replacement data, shape (1, epoch_len, nepochs)
Returns
Nothing
NeuroAnalyzer.set_channel_type — Function
set_channel_type(obj; <keyword arguments>)Return a copy of obj with the type of one channel changed.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channeltype::String: new channel type (must be a recognized type)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.set_channel_type! — Function
set_channel_type!(obj; <keyword arguments>)Set the type of one channel in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channeltype::String: new channel type (must be a recognized type)
Returns
Nothing
NeuroAnalyzer.subepoch — Function
subepoch(obj; <keyword arguments>)Return a copy of obj trimmed to a sub-range within each epoch.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep_start::Real: sub-epoch start in seconds (relative to epoch start)ep_end::Real: sub-epoch end in seconds (relative to epoch start)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.subepoch! — Function
subepoch!(obj; <keyword arguments>)Trim each epoch to a sub-range in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectep_start::Real: sub-epoch start in seconds (relative to epoch start)ep_end::Real: sub-epoch end in seconds (relative to epoch start)
Returns
Nothing
NeuroAnalyzer.trim — Function
trim(s; <keyword arguments>)Remove segment from the signal.
Arguments
v::AbstractVectorseg::Tuple{Int64, Int64}: segment (from, to) in sampleskeep::Bool=false: if true, keep the segment
Returns
Vector{Float64}
trim(m; <keyword arguments>)Remove segment from the signal.
Arguments
m::AbstractMatrixseg::Tuple{Int64, Int64}: segment (from, to) in sampleskeep::Bool=false: if true, keep the segment
Returns
Matrix{Float64}
trim(a; <keyword arguments>)Remove segment from a 3-D signal array.
Arguments
a::AbstractArray: signal array, shape (channels, samples, epochs)seg::Tuple{Int64, Int64}: segment (from, to) in sampleskeep::Bool=false: if true, keep the segment
Returns
Array{Float64, 3}
trim(obj; <keyword arguments>)Trim signal by removing parts of the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectseg::Tuple{Real, Real}: segment to be removed (from, to) in secondskeep::Bool=false: if true, keep the segmentremove_epochs::Bool=false: if true, remove epochs containing signal to trim or remove signal and re-epoch trimmed signal
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.trim! — Function
trim!(obj; <keyword arguments>)Trim signal by removing parts of the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectseg::Tuple{Real, Real}: segment to be removed (from, to) in secondskeep::Bool=false: if true, keep the segment
Returns
Nothing
NeuroAnalyzer.vch — Function
vch(obj; <keyword arguments>)Calculate a virtual channel using formula f.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectf::String: channel calculation formula, e.g."cz / mean(Fp1 + Fp2)"; all standard Julia math operators are available, channel labels must be the same as of the OBJ object
Returns
Array{Float64, 3}: shape (1, time, epochs)
NeuroAnalyzer.view_marker — Function
view_marker(obj)Print a formatted table of all markers.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Nothing
Process
NeuroAnalyzer.add_signal — Function
add_signal(s1, s2)Add two equal-length signal vectors element-wise.
Arguments
s1::AbstractVector: target signals2::AbstractVector: signal to add tos1; must have the same length ass1
Returns
AbstractVector: element-wise sums1 .+ s2
add_signal(obj; <keyword arguments>)Add a signal vector to selected channels of a NEURO object.
The same signal s is added to every selected channel in every epoch. s must have the same length as one epoch of the signal (epoch_len(obj)). Channels are processed in parallel using Threads.@threads.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)s::AbstractVector: signal to add; length must equalepoch_len(obj)
Returns
NeuroAnalyzer.NEURO: new object withsadded to the selected channels
NeuroAnalyzer.add_signal! — Function
add_signal!(obj; <keyword arguments>)Add a signal vector to selected channels of a NEURO object in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)s::AbstractVector: signal to add; length must equalepoch_len(obj)
Returns
Nothing
NeuroAnalyzer.apply_ssp_projectors — Function
apply_ssp_projectors(obj; <keyword arguments>)Apply SSP projectors generated from embedded projections to a MEG object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectpidx::Union{Int64, Vector{Int64}}=0: projection index/indices to use;0(default) selects all available projections
Returns
NeuroAnalyzer.NEURO: output NEURO object with SSP projections applied
NeuroAnalyzer.apply_ssp_projectors! — Function
apply_ssp_projectors!(obj; <keyword arguments>)Apply SSP projectors from embedded projections.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectpidx::Union{Int64, Vector{Int64}}=0: projection index/indices to use;0(default) selects all available projections
Returns
Nothing
NeuroAnalyzer.artrem_cwd — Function
artrem_cwd(s, t; <keyword arguments>)Remove an artifact from a signal using continuous wavelet decomposition (CWD).
The signal is transformed into the time-frequency domain via CWD, the coefficients within the specified time (tseg) and frequency (fseg) windows are zeroed, and the signal is reconstructed via the inverse CWD (iCWD).
Arguments
s::AbstractVector: signal vectort::AbstractVector: time-point vector corresponding tos; must not be emptyfs::Int64: sampling rate in Hz; must be ≥ 1wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): wavelet to use; see ContinuousWavelets.jl for available waveletstseg::Tuple{Real, Real}: time window of the artifact(t_start, t_end)in seconds; must be a strictly ascending pair within[t[1], t[end]]fseg::Tuple{Real, Real}: frequency window of the artifact(f_low, f_high)in Hz; must be a strictly ascending pair within the wavelet frequency rangetype::Symbol=:nd: inverse CWD reconstruction method::pd: PenroseDelta:nd: NaiveDelta (default):df: DualFrames
Returns
Vector{Float64}: artifact-corrected signal of the same length ass
artrem_cwd(obj; <keyword arguments>)Remove an artifact from one channel and one epoch of a NEURO object using continuous wavelet decomposition (CWD).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelep::Int64: epoch index; must be a valid epoch numberwt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): wavelet to use; see ContinuousWavelets.jl for available waveletstseg::Tuple{Real, Real}: time window of the artifact(t_start, t_end)in seconds; must be a strictly ascending pair within[t[1], t[end]]fseg::Tuple{Real, Real}: frequency window of the artifact(f_low, f_high)in Hz; must be a strictly ascending pair within the wavelet frequency rangetype::Symbol=:nd: inverse CWD reconstruction method::pd: PenroseDelta:nd: NaiveDelta (default):df: DualFrames
Returns
NeuroAnalyzer.NEURO: new object with the artifact removed from the specified channel and epoch
NeuroAnalyzer.artrem_cwd! — Function
artrem_cwd!(obj; <keyword arguments>)Remove an artifact from one channel and one epoch of a NEURO object in-place using continuous wavelet decomposition (CWD).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::String: channel name; must resolve to exactly one channelep::Int64: epoch index; must be a valid epoch numberwt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): wavelet to use; see ContinuousWavelets.jl for available waveletstseg::Tuple{Real, Real}: time window of the artifact(t_start, t_end)in seconds; must be a strictly ascending pair within[t[1], t[end]]fseg::Tuple{Real, Real}: frequency window of the artifact(f_low, f_high)in Hz; must be a strictly ascending pair within the wavelet frequency rangetype::Symbol=:nd: inverse CWD reconstruction method::pd: PenroseDelta:nd: NaiveDelta (default):df: DualFrames
Returns
Nothing
NeuroAnalyzer.average_epochs — Function
average_epochs(obj; <keyword arguments>)Average EEG/MEG epochs and prepend the average as epoch 1. Non-signal channels are removed. obj.header.recording[:data_type]is updated to"erp"(EEG) or"erf"` (MEG).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectbl::Tuple{Real, Real}=(0, 0): baseline window in seconds; when not(0, 0)the mean of this window is subtracted from the signalblfirst::Bool=false: whentrue, subtract the baseline from each epoch before averaging; whenfalse, subtract the baseline from the averaged epoch only
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.average_epochs! — Function
average_epochs!(obj; <keyword arguments>)Average EEG/MEG epochs in-place and prepend the average as epoch 1. Non-signal channels are removed. obj.header.recording[:data_type]is updated to"erp"(EEG) or"erf"` (MEG).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectbl::Tuple{Real, Real}=(0, 0): baseline window in seconds; when not(0, 0)the mean of this window is subtracted from the signalblfirst::Bool=false: whentrue, subtract the baseline from each epoch before averaging; whenfalse, subtract the baseline from the averaged epoch only
Returns
Nothing
NeuroAnalyzer.bpsplit — Function
bpsplit(obj; <keyword arguments>)Split a signal into standard EEG frequency bands using FIR band-pass filters.
One filter is designed per band and applied to every selected channel and epoch.
The following bands are extracted: :delta, :theta, :alpha, :alpha_lower, :alpha_higher, :beta, :beta_lower, :beta_higher, :gamma, :gamma_1, :gamma_2, :gamma_lower, :gamma_higher.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)order::Int64=91: number of taps for the FIR band-pass filter; must be odd for band-pass filtersbw::Real=0.5: transition band width in Hzw::Union{Nothing, AbstractVector, <:Real}=nothing: window for the FIR filter;nothingapplies the default Hamming window of lengthorder
Returns
Named tuple:
s::Array{Float64, 4}: band-split signal of shape(n_bands, n_channels, epoch_len, n_epochs)bn::Vector{Symbol}: band name symbols (in the order used ins)bf::Vector{Tuple{Real, Real}}: frequency limits(f_low, f_high)in Hz for each band, in the same order asbn
NeuroAnalyzer.cbp — Function
cbp(s; <keyword arguments>)Perform convolution band-pass filtering at a single frequency.
Generates a sine-wave kernel at frq Hz over a ±1 s window and convolves it with the signal. This acts as a narrow band-pass filter centred at frq.
Arguments
s::AbstractVector: signal vectorpad::Int64=0: number of zeros to append before filtering; must be ≥ 0frq::Real: filter centre frequency in Hz; must be in(0, fs/2]fs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Vector{Float64}: band-pass filtered signal of the same length ass(padding is removed after convolution)
cbp(obj; <keyword arguments>)Perform convolution band-pass filtering on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to append before filtering; must be ≥ 0frq::Real: filter centre frequency in Hz; must be in(0, fs/2]
Returns
NeuroAnalyzer.NEURO: new object with filtered channels
NeuroAnalyzer.cbp! — Function
cbp!(obj; <keyword arguments>)Perform convolution band-pass filtering in-place on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to append before filtering; must be ≥ 0frq::Real: filter centre frequency in Hz; must be in(0, fs/2]
Returns
Nothing
NeuroAnalyzer.csd — Function
csd(obj; <keyword arguments>)Transform EEG data using the Current Source Density (CSD) transformation based on a spherical spline surface Laplacian.
The algorithm (Perrin et al. 1989):
- Compute the G (potential) and H (Laplacian) spline matrices from electrode locations.
- Add a Tikhonov regularisation term
λIto G. - Solve for the constrained spline coefficients C.
- Compute the surface Laplacian as
H × C.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"with channel locations definedm::Int64=4: spline flexibility constant; must be in[2, 10]; higher values increase rigidityn::Int64=8: Legendre polynomial order; must be ≥ 1lambda::Float64=10^-5: Tikhonov smoothing factor; must be > 0
Returns
NeuroAnalyzer.NEURO: new object with CSD-transformed data, channel types set to"csd", and units set to"µV/m²"
References
- Perrin F, Pernier J, Bertrand O, Echallier JF. Spherical splines for scalp potential and current density mapping. Electroencephalography and Clinical Neurophysiology. 1989;72(2):184–187.
- Kayser J, Tenke CE. Principal components analysis of Laplacian waveforms as a generic method for identifying ERP generator patterns: I. Evaluation with auditory oddball tasks. Clinical Neurophysiology. 2006;117(2):348–368.
NeuroAnalyzer.csd! — Function
csd!(obj; <keyword arguments>)Transform EEG data using the CSD transformation in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"with channel locations defined; modified in-placem::Int64=4: spline flexibility constant; must be in[2, 10]; higher values increase rigidityn::Int64=8: Legendre polynomial order; must be ≥ 1lambda::Float64=10^-5: Tikhonov smoothing factor; must be > 0
Returns
Nothing
References
- Perrin F, Pernier J, Bertrand O, Echallier JF. Spherical splines for scalp potential and current density mapping. Electroencephalography and Clinical Neurophysiology. 1989;72(2):184–187.
- Kayser J, Tenke CE. Principal components analysis of Laplacian waveforms as a generic method for identifying ERP generator patterns: I. Evaluation with auditory oddball tasks. Clinical Neurophysiology. 2006;117(2):348–368.
NeuroAnalyzer.cwd — Function
cwd(s; <keyword arguments>)Perform continuous wavelet decomposition (CWD) on a signal vector.
Returns the real part of the CWT coefficient matrix. Each row corresponds to one wavelet scale (frequency band); each column corresponds to one time point.
Arguments
s::AbstractVector: signal vectorwt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available wavelets
Returns
Matrix{Float64}: CWT coefficient matrix of shape(n_scales, length(s))
cwd(s; <keyword arguments>)Perform continuous wavelet decomposition on a 3-D signal array.
Applies cwd(::AbstractVector) to every channel × epoch slice in parallel and returns a 4-D coefficient array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)wt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available wavelets
Returns
Array{Float64, 4}: CWT coefficients of shape(channels, n_scales, samples, epochs)
cwd(obj; <keyword arguments>)Perform continuous wavelet decomposition on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)wt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available wavelets
Returns
Array{Float64, 4}: CWT coefficients of shape(channels, n_scales, samples, epochs)
NeuroAnalyzer.denoise_cwd — Function
denoise_cwd(s; <keyword arguments>)Perform denoising by zeroing a frequency band in the continuous wavelet domain.
Computes the CWD, zeros all coefficients in the band [nf − w, nf + w] Hz, then reconstructs the signal via the inverse CWD.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2), see ContinuousWavelets.jl documentation for the list of available waveletsnf::Real: noise frequency to suppress in Hz; must be in[1, fs/2]w::Int64=5: half-width of the suppression band in Hz; the zeroed region is[nf − w, nf + w]type::Symbol=:pd: reconstruction method::pd: PenroseDelta (default; generally most accurate):nd: NaiveDelta:df: DualFrames
Returns
Vector{Float64}: denoised signal of the same length ass
denoise_cwd(s; <keyword arguments>)Perform denoising by zeroing a frequency band in the continuous wavelet domain for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2), see ContinuousWavelets.jl documentation for the list of available waveletsnf::Real: noise frequency to suppress in Hz; must be in[1, fs/2]w::Int64=5: half-width of the suppression band in Hz; the zeroed region is[nf − w, nf + w]type::Symbol=:pd: reconstruction method::pd: PenroseDelta (default; generally most accurate):nd: NaiveDelta:df: DualFrames
Returns
Array{Float64, 3}: denoised signal array
denoise_cwd(obj; <keyword arguments>)Perform denoising by zeroing a frequency band in the continuous wavelet domain on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2), see ContinuousWavelets.jl documentation for the list of available waveletsnf::Real: noise frequency to suppress in Hz; must be in[1, fs/2]w::Int64=5: half-width of the suppression band in Hz; the zeroed region is[nf − w, nf + w]type::Symbol=:pd: reconstruction method::pd: PenroseDelta (default; generally most accurate):nd: NaiveDelta:df: DualFrames
Returns
NeuroAnalyzer.NEURO: new object with denoised channels
NeuroAnalyzer.denoise_cwd! — Function
denoise_cwd!(obj; <keyword arguments>)Perform denoising by zeroing a frequency band in the continuous wavelet domain in-place on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2), see ContinuousWavelets.jl documentation for the list of available waveletsnf::Real: noise frequency to suppress in Hz; must be in[1, fs/2]w::Int64=5: half-width of the suppression band in Hz; the zeroed region is[nf − w, nf + w]type::Symbol=:pd: reconstruction method::pd: PenroseDelta (default; generally most accurate):nd: NaiveDelta:df: DualFrames
Returns
Nothing
NeuroAnalyzer.denoise_dwd — Function
denoise_dwd(s; <keyword arguments>)Perform threshold denoising using discrete wavelet decomposition (DWD).
Arguments
s::AbstractVector: signal vectorwt<:DiscreteWavelet=wavelet(WT.haar): discrete wavelet, see Wavelets.jl documentation for the list of available waveletsl::Int64=0: decomposition level;0uses the maximum available level (maxtransformlevels(s)); must be ≤maxtransformlevels(s)dnt<:DNF=RelErrorShrink(SoftTH()): denoise type, see WaveletsExt.jl documentation for detailed description of available denoising functionssmooth::Symbol=:regular: smoothing method::regular: threshold all coefficients:undersmooth: do not threshold the lowest-frequency subspace
Returns
Vector{Float64}: denoised signal
denoise_dwd(s; <keyword arguments>)Perform threshold denoising using discrete wavelet decomposition (DWD) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)wt<:DiscreteWavelet: discrete wavelet, e.g.wt = wavelet(WT.haar); see Wavelets.jl documentation for the list of available waveletsl::Int64=0: decomposition level;0uses the maximum available level (maxtransformlevels(s)); must be ≤maxtransformlevels(s)dnt<:DNF=RelErrorShrink(SoftTH()): denoise type, see WaveletsExt.jl documentation for detailed description of available denoising functionssmooth::Symbol=:regular: smoothing method::regular: threshold all coefficients:undersmooth: do not threshold the lowest-frequency subspace
Returns
Array{Float64, 3}: denoised signal array
denoise_dwd(obj; <keyword arguments>)Perform denoising using discrete wavelet decomposition (DWD) on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)wt<:DiscreteWavelet: discrete wavelet, e.g.wt = wavelet(WT.haar); see Wavelets.jl documentation for the list of available waveletsl::Int64=0: decomposition level;0uses the maximum available level (maxtransformlevels(s)); must be ≤maxtransformlevels(s)dnt<:DNF=RelErrorShrink(SoftTH()): denoise type, see WaveletsExt.jl documentation for detailed description of available denoising functionssmooth::Symbol=:regular: smoothing method::regular: threshold all coefficients:undersmooth: do not threshold the lowest-frequency subspace
Returns
NeuroAnalyzer.NEURO: new object with denoised channels
NeuroAnalyzer.denoise_dwd! — Function
denoise_dwd!(obj; <keyword arguments>)Perform denoising using discrete wavelet decomposition (DWD) in-place on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)wt<:DiscreteWavelet: discrete wavelet, e.g.wt = wavelet(WT.haar); see Wavelets.jl documentation for the list of available waveletsl::Int64=0: number of levels, default maximum number of levels available or total transformationdnt<:DNF=RelErrorShrink(SoftTH()): denoise type, see WaveletsExt.jl documentation for detailed description of available denoising functionssmooth::Symbol=:regular: the smoothing method::regular: smoothing thresholds all given coefficients:undersmooth: smoothing does not threshold the lowest frequency subspace node of the wavelet transform
Returns
Nothing
NeuroAnalyzer.denoise_fft — Function
denoise_fft(s; <keyword arguments>)Perform FFT-based denoising on a signal vector.
Computes the FFT, zeros all frequency components whose power exceeds the threshold t, then reconstructs the signal via the inverse FFT. This keeps low-power (signal) components and suppresses high-power artifact components.
Arguments
s::AbstractVector: signal vectorpad::Int64=0: number of zeros to append before FFT; must be ≥ 0t::Real=0: power spectral density threshold; components with power >tare zeroed; ift = 0, the mean power across all frequency bins is used
Returns
Named tuple:
s::Vector{Float64}: denoised signal of the same length as the inputf_idx::BitVector: boolean mask;trueat each frequency index that was zeroed
denoise_fft(s; <keyword arguments>)Perform FFT-based denoising on every channel × epoch slice of a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)pad::Int64=0: number of zeros to append before FFT; must be ≥ 0t::Real=0: power spectral density threshold; components with power >tare zeroed; ift = 0, the mean power across all frequency bins is used
Returns
Array{Float64, 3}: denoised 3D signal array
denoise_fft(obj; <keyword arguments>)Perform FFT-based denoising on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to append before FFT; must be ≥ 0t::Real=0: power spectral density threshold; components with power >tare zeroed; ift = 0, the mean power across all frequency bins is used
Returns
NeuroAnalyzer.NEURO: new object with denoised channels
NeuroAnalyzer.denoise_fft! — Function
denoise_fft!(obj; <keyword arguments>)Perform FFT-based denoising in-place on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to append before FFT; must be ≥ 0t::Real=0: power spectral density threshold; components with power >tare zeroed; ift = 0, the mean power across all frequency bins is used
Returns
Nothing
NeuroAnalyzer.denoise_wien — Function
denoise_wien(s)Perform Wiener deconvolution denoising on a 3-D signal array.
For each epoch, the cross-channel mean signal is used as the reference, and a noise estimate is generated as white noise scaled to the mean signal power. The Wiener filter is then applied independently to each channel.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs).
Returns
Array{Float64, 3}: denoised array of the same shape ass
Notes
- The noise estimate is random (
rand); results are not reproducible unless a random seed is set by the caller
denoise_wien(obj; <keyword arguments>)Perform Wiener deconvolution denoising on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
NeuroAnalyzer.NEURO: new object with denoised channels
NeuroAnalyzer.denoise_wien! — Function
denoise_wien!(obj; <keyword arguments>)Perform Wiener deconvolution denoising in-place on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Nothing
NeuroAnalyzer.derivative — Function
derivative(s)Return the derivative of a discrete signal using the symmetric difference quotient.
For interior samples: ds[i] = (s[i+1] − s[i−1]) / 2.
For the boundary samples the one-sided half-difference is used so that the output has the same length as the input.
Arguments
s::AbstractVector: signal vector; must contain at least 3 elements
Returns
Vector{Float64}: derivative signal of the same length ass
derivative(s)Return the derivative of a discrete signal using the symmetric difference quotient.
For interior samples: ds[i] = (s[i+1] − s[i−1]) / 2.
For the boundary samples the one-sided half-difference is used so that the output has the same length as the input.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Array{Float64, 3}: derivative array of the same shape ass
derivative(obj; <keyword arguments>)Return the derivative of a discrete signal using the symmetric difference quotient of selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
NeuroAnalyzer.NEURO: new object with differentiated channels
NeuroAnalyzer.derivative! — Function
derivative!(obj; <keyword arguments>)Return the derivative of a discrete signal using the symmetric difference quotient in-place of selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Nothing
NeuroAnalyzer.detect_powerline — Function
detect_powerline(s; <keyword arguments>)Detect the dominant power line noise frequency in a signal.
Fits a sine + cosine model at each integer frequency from 1 to fs÷2 Hz and returns the frequency with maximum fitted power.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 2
Returns
Float64: dominant noise frequency in Hz
detect_powerline(obj)Detect the dominant power line noise frequency for each channel and epoch.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Array{Float64, 2}: noise frequency in Hz; shape(channels, epochs)
NeuroAnalyzer.detect_powerline! — Function
detect_powerline!(obj)Detect power line noise and store the median detected frequency in the object header in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object;header.recording[:line_frequency]is updated in-place
Returns
Nothing
NeuroAnalyzer.detrend — Function
detrend(s; <keyword arguments>)Remove a trend.
Arguments
s::AbstractVector: signal vector; must contain at least 2 elementstype::Symbol=:linear: detrending method::linear: subtract a 1st-order polynomial (linear trend); equivalent to:polywithorder=1:ls: subtract a linear least-squares fit using an efficient closed-form solution:poly: subtract a polynomial of degreeorderfitted withPolynomials.fit:loess: subtract a Loess smooth fitted with smoothing factorf:mean: subtract the signal mean:constant: subtractoffset
offset::Real=0: constant subtracted whentype = :constantorder::Int64=1: polynomial degree fortype = :poly; must be ≥ 1 and <length(s)f::Float64=1.0: loess smoothing span ∈(0, 1]fortype = :loess
Returns
Vector{Float64}: detrended signal of the same length ass
detrend(s; <keyword arguments>)Remove a trend in a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)type::Symbol=:linear: detrending method::linear: subtract a 1st-order polynomial (linear trend); equivalent to:polywithorder=1:ls: subtract a linear least-squares fit using an efficient closed-form solution:poly: subtract a polynomial of degreeorderfitted withPolynomials.fit:loess: subtract a Loess smooth fitted with smoothing factorf:mean: subtract the signal mean:constant: subtractoffset
offset::Real=0: constant subtracted whentype = :constantorder::Int64=1: polynomial degree fortype = :poly; must be ≥ 1 and <length(s)f::Float64=1.0: loess smoothing span ∈(0, 1]fortype = :loess
Returns
Array{Float64, 3}: detrended array of the same shape ass
detrend(obj; <keyword arguments>)Remove a trend from selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)type::Symbol=:linear: detrending method::linear: subtract a 1st-order polynomial (linear trend); equivalent to:polywithorder=1:ls: subtract a linear least-squares fit using an efficient closed-form solution:poly: subtract a polynomial of degreeorderfitted withPolynomials.fit:loess: subtract a Loess smooth fitted with smoothing factorf:mean: subtract the signal mean:constant: subtractoffset
offset::Real=0: constant subtracted whentype = :constantorder::Int64=1: polynomial degree fortype = :poly; must be ≥ 1 and <length(s)f::Float64=1.0: loess smoothing span ∈(0, 1]fortype = :loess
Returns
NeuroAnalyzer.NEURO: new object with detrended channels
NeuroAnalyzer.detrend! — Function
detrend!(obj; <keyword arguments>)Remove a trend in-place from selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)type::Symbol=:linear: detrending method::linear: subtract a 1st-order polynomial (linear trend); equivalent to:polywithorder=1:ls: subtract a linear least-squares fit using an efficient closed-form solution:poly: subtract a polynomial of degreeorderfitted withPolynomials.fit:loess: subtract a Loess smooth fitted with smoothing factorf:mean: subtract the signal mean:constant: subtractoffset
offset::Real=0: constant subtracted whentype = :constantorder::Int64=1: polynomial degree fortype = :poly; must be ≥ 1 and <length(s)f::Float64=1.0: loess smoothing span ∈(0, 1]fortype = :loess
Returns
Nothing
NeuroAnalyzer.downsample — Function
downsample(obj; <keyword arguments>)Downsample.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnew_sr::Int64: new sampling rate
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.downsample! — Function
downsample!(obj; <keyword arguments>)Downsample.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnew_sr::Int64: new sampling rate
Returns
Nothing
NeuroAnalyzer.dwd — Function
dwd(s; <keyword arguments>)Perform discrete wavelet decomposition (DWD).
Returns the decomposition coefficient matrix. Each row corresponds to one subspace node; each column corresponds to one time sample.
Arguments
s::AbstractVector: signal vectorwt<:DiscreteWavelet=wavelet(WT.haar): discrete wavelet; see Wavelets.jl documentation for the list of available waveletstype::Symbol: decomposition type::sdwt: stationary discrete wavelet transform:acdwt: discrete autocorrelation wavelet transform
l::Int64=maxtransformlevels(s): number of decomposition levels; must be ≥ 1 and ≤maxtransformlevels(s)
Returns
Matrix{Float64}: DWD coefficient matrix of shape((1 + Σ 2^k for k=1..l), length(s))
dwd(s; <keyword arguments>)Perform discrete wavelet decomposition (DWD).
Returns the decomposition coefficient matrix for a 3-D signal array.
Each row corresponds to one subspace node; each column corresponds to one time sample.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)wt<:DiscreteWavelet=wavelet(WT.haar): discrete wavelet; see Wavelets.jl documentation for the list of available waveletstype::Symbol: transformation type::sdwt: stationary discrete wavelet transform:acdwt: discrete autocorrelation wavelet transform
l::Int64=maxtransformlevels(s): number of decomposition levels; must be ≥ 1 and ≤maxtransformlevels(s)
Returns
Array{Float64, 4}: DWD coefficients of shape(channels, n_nodes, samples, epochs)
dwd(obj; <keyword arguments>)Perform discrete wavelet decomposition on selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)wt<:DiscreteWavelet=wavelet(WT.haar): discrete wavelet; see Wavelets.jl documentation for the list of available waveletstype::Symbol: transformation type::sdwt: stationary discrete wavelet transform:acdwt: discrete autocorrelation wavelet transform
l::Int64=maxtransformlevels(s): number of decomposition levels; must be ≥ 1 and ≤maxtransformlevels(s)
Returns
Array{Float64, 4}: DWD coefficients of shape(channels, n_nodes, samples, epochs)
NeuroAnalyzer.edit_montage — Function
edit_montage(file_name; <keyword arguments>)Open a montage file in the operating-system default text editor.
- Windows: opens with
notepad.exe. - Linux: opens with the editor specified in the
$EDITORenvironment variable. - macOS: opens with TextEdit via
open -e.
Arguments
file_name::String: path to the montage file to edit; must exist
Returns
Nothing
NeuroAnalyzer.fconv — Function
fconv(s; <keyword arguments>)Perform convolution in the frequency domain.
Both s and kernel are zero-padded to length length(s) + length(kernel) - 1 before the FFT so the result is equivalent to linear (non-circular) convolution.
Arguments
s::AbstractVector: signal vectorkernel::AbstractVector: convolution kernel (must be non-empty)norm::Bool=true: normalize the kernel FFT by its maximum magnitude to keep post-convolution amplitudes on the same scale as the input
Returns
Vector{ComplexF64}: convolved signal (same length ass)
fconv(s; <keyword arguments>)Perform convolution in the frequency domain for a 3-D signal array.
Both s and kernel are zero-padded to length length(s) + length(kernel) - 1 before the FFT so the result is equivalent to linear (non-circular) convolution.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)kernel::AbstractVector: convolution kernel (must be non-empty)norm::Bool=true: normalize the kernel FFT by its maximum magnitude to keep post-convolution amplitudes on the same scale as the input
Returns
Array{ComplexF64, 3}: convolved signal, same shape ass
fconv(obj; <keyword arguments>)Perform convolution in the frequency domain on selected channels of a NeuroAnalyzer.NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)kernel::AbstractVector: convolution kernel (must be non-empty)norm::Bool=true: normalize the kernel FFT by its maximum magnitude to keep post-convolution amplitudes on the same scale as the input
Returns
Array{ComplexF64, 3}: convolved signal for the selected channels
NeuroAnalyzer.filter — Function
filter(obj; <keyword arguments>)Design and apply a digital filter to selected channels of a NEURO object in a single call.
Combines filter_create and filter_apply. When preview=true, the filter frequency response is plotted without modifying the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)fprototype::Symbol: filter prototype::fir: FIR filter (window method):firls: weighted least-squares FIR filter:remez: Remez (Parks-McClellan) FIR filter:butterworth: Butterworth IIR filter:chebyshev1: Chebyshev type-I IIR filter:chebyshev2: Chebyshev type-II IIR filter:elliptic: elliptic IIR filter:iirnotch: second-order IIR notch filter
ftype::Union{Nothing, Symbol}=nothing: filter type::lp: low pass:hp: high pass:bp: band pass:bs: band stop
cutoff::Union{Real, Tuple{Real, Real}}: filter cutoff in Hz- for
:lp/:hp: single frequency - for
:bp/:bs: frequency range (f1, f2)-fs::Int64: sampling rate in Hz; must be ≥ 1
- for
order::Union{Nothing, Int64}=nothing: filter order (number of taps for FIR, filter order for IIR)rp::Union{Nothing, Real}=nothing: pass-band ripple in dB (default 0.5 dB)rs::Union{Nothing, Real}=nothing: stop-band attenuation in dB (default 20 dB)bw::Union{Nothing, Real}=nothing: transition band width in Hz (required for:firls,:remez,:iirnotch)w::Union{Nothing, AbstractVector}=nothing: window for:fir(default: Hamming) or weight vector for:firlsdir:Symbol=:twopass: filtering direction::twopass: forward pass followed by reverse pass (zero phase distortion; effective filter order is doubled):onepass: single forward pass (introduces phase delay):reverse: single reverse pass
preview::Bool=false: iftrue, plot the filter frequency response and return the figure without filtering the signal
Returns
NeuroAnalyzer.NEURO: filtered object (whenpreview=false)GLMakie.Figure: filter frequency-response plot (whenpreview=true)
NeuroAnalyzer.filter! — Function
filter!(obj; <keyword arguments>)Design and apply a digital filter in-place to selected channels of a NEURO object.
When preview=true, the filter frequency response is plotted and returned without modifying the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)fprototype::Symbol: filter prototype::fir: FIR filter (window method):firls: weighted least-squares FIR filter:remez: Remez (Parks-McClellan) FIR filter:butterworth: Butterworth IIR filter:chebyshev1: Chebyshev type-I IIR filter:chebyshev2: Chebyshev type-II IIR filter:elliptic: elliptic IIR filter:iirnotch: second-order IIR notch filter
ftype::Union{Nothing, Symbol}=nothing: filter type::lp: low pass:hp: high pass:bp: band pass:bs: band stop
cutoff::Union{Real, Tuple{Real, Real}}: filter cutoff in Hz- for
:lp/:hp: single frequency - for
:bp/:bs: frequency range (f1, f2)
- for
fs::Int64: sampling rate in Hz; must be ≥ 1order::Union{Nothing, Int64}=nothing: filter order (number of taps for FIR, filter order for IIR)rp::Union{Nothing, Real}=nothing: pass-band ripple in dB (default 0.5 dB)rs::Union{Nothing, Real}=nothing: stop-band attenuation in dB (default 20 dB)bw::Union{Nothing, Real}=nothing: transition band width in Hz (required for:firls,:remez,:iirnotch)w::Union{Nothing, AbstractVector}=nothing: window for:fir(default: Hamming) or weight vector for:firlsdir:Symbol=:twopass: filtering direction::twopass: forward pass followed by reverse pass (zero phase distortion; effective filter order is doubled):onepass: single forward pass (introduces phase delay):reverse: single reverse pass
preview::Bool=false: iftrue, plot the filter frequency response and return the figure without filtering the signal
Returns
Nothingwhenpreview=falseGLMakie.Figure: filter frequency-response plot (whenpreview=true)
NeuroAnalyzer.filter_apply — Function
filter_apply(s; <keyword arguments>)Apply a pre-designed IIR or FIR filter to a signal vector.
Arguments
s::AbstractVector: signal vectorflt::Union{Vector{Float64}, ZeroPoleGain{:z, ComplexF64, ComplexF64, Float64}, Biquad{:z, Float64}}: filter object returned byfilter_createdir:Symbol=:twopass: filtering direction::twopass: forward pass followed by reverse pass (zero phase distortion; effective filter order is doubled):onepass: single forward pass (introduces phase delay):reverse: single reverse pass
Returns
Vector{Float64}: filtered signal of the same length ass
filter_apply(obj; <keyword arguments>)Apply a pre-designed filter to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flt::Union{Vector{Float64}, ZeroPoleGain{:z, ComplexF64, ComplexF64, Float64}, Biquad{:z, Float64}}: filter object returned byfilter_createdir:Symbol=:twopass: filtering direction::twopass: forward pass followed by reverse pass (zero phase distortion; effective filter order is doubled):onepass: single forward pass (introduces phase delay):reverse: single reverse pass
Returns
NeuroAnalyzer.NEURO: output NEURO object with filtered data
Notes
- For best results apply to a continuous (single-epoch) signal. A warning is issued when
nepochs(obj) > 1. - Taper the signal before filtering to reduce edge artifacts.
NeuroAnalyzer.filter_apply! — Function
filter_apply!(obj; <keyword arguments>)Apply a pre-designed filter in-place to selected channels of a NEURO object.
Delegates to filter_apply and copies the result back.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)flt::Union{Vector{Float64}, ZeroPoleGain{:z, ComplexF64, ComplexF64, Float64}, Biquad{:z, Float64}}: filter object returned byfilter_createdir:Symbol=:twopass: filtering direction::twopass: forward pass followed by reverse pass (zero phase distortion; effective filter order is doubled):onepass: single forward pass (introduces phase delay):reverse: single reverse pass
Returns
Nothing
NeuroAnalyzer.filter_create — Function
filter_create(; <keyword arguments>)Create a FIR or IIR filter object.
Arguments
fprototype::Symbol: filter prototype::fir: FIR filter (window method):firls: weighted least-squares FIR filter:remez: Remez (Parks-McClellan) FIR filter:butterworth: Butterworth IIR filter:chebyshev1: Chebyshev type-I IIR filter:chebyshev2: Chebyshev type-II IIR filter:elliptic: elliptic IIR filter:iirnotch: second-order IIR notch filter
ftype::Union{Nothing, Symbol}=nothing: filter type::lp: low pass:hp: high pass:bp: band pass:bs: band stop
cutoff::Union{Real, Tuple{Real, Real}}: filter cutoff in Hz- for
:lp/:hp: single frequency - for
:bp/:bs: frequency range (f1, f2)
- for
fs::Int64: sampling rate in Hz; must be ≥ 1order::Union{Nothing, Int64}=nothing: filter order (number of taps for FIR, filter order for IIR)rp::Union{Nothing, Real}=nothing: pass-band ripple in dB (default 0.5 dB)rs::Union{Nothing, Real}=nothing: stop-band attenuation in dB (default 20 dB)bw::Union{Nothing, Real}=nothing: transition band width in Hz (required for:firls,:remez,:iirnotch)w::Union{Nothing, AbstractVector}=nothing: window for:fir(default: Hamming) or weight vector for:firls
Returns
Vector{Float64}: FIR filter coefficients (for:fir,:firls,:remez)ZeroPoleGain{:z, ComplexF64, ComplexF64, Float64}: IIR filter in zero-pole-gain form (for:butterworth,:chebyshev1,:chebyshev2,:elliptic)Biquad{:z, Float64}: second-order biquad filter (for:iirnotch)
NeuroAnalyzer.filter_g — Function
filter_g(s; <keyword arguments>)Filter a signal by multiplying its FFT spectrum with a Gaussian kernel centered at frequency f.
The Gaussian is normalized to unit gain at its peak. Taking the absolute value of the inverse FFT after multiplication yields the filtered signal envelope.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1pad::Int64=0: number of zeros to append before the FFT; must be ≥ 0f::Real: center frequency of the Gaussian kernel in Hz; must be ≥ 0 and <fs/2gw::Real=5: Gaussian width in Hz (used by:gh) (full width parameter); must be > 0
Returns
Vector{Float64}: filtered signal of lengthlength(s)
filter_g(s; <keyword arguments>)Filter a 3-dimensional signal array using a Gaussian kernel in the frequency domain for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1pad::Int64=0: number of zeros to append; must be ≥ 0f::Real: center frequency of the Gaussian kernel in Hz; must be ≥ 0 and <fs/2gw::Real=5: Gaussian width in Hz (used by:gh) (full width parameter); must be > 0
Returns
Array{Float64, 3}: filtered array of the same shape ass
filter_g(obj; <keyword arguments>)Filter selected channels of a NEURO object using a Gaussian kernel in the frequency domain.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to append; must be ≥ 0f::Real: center frequency of the Gaussian kernel in Hz; must be ≥ 0 and <fs/2gw::Real=5: Gaussian width in Hz (full width parameter); must be > 0
Returns
NeuroAnalyzer.NEURO: new object with filtered channels
NeuroAnalyzer.filter_g! — Function
filter_g!(obj; <keyword arguments>)Filter selected channels of a NEURO object in-place using a Gaussian kernel in the frequency domain.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to append; must be ≥ 0f::Real: center frequency of the Gaussian kernel in Hz; must be ≥ 0 and <fs/2gw::Real=5: Gaussian width in Hz (used by:gh) (full width parameter); must be > 0
Returns
Nothing
NeuroAnalyzer.filter_mavg — Function
filter_mavg(s; <keyword arguments>)Filter a signal using a weighted moving average with an optional threshold.
Samples within the threshold band [mean(s) − t×std(s), mean(s) + t×std(s)] are left unchanged; only outliers outside that band are replaced by the local weighted mean. When t = 0 (default) every sample is filtered.
Arguments
s::AbstractVector: signal vectork::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0);t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
Vector{Float64}: filtered signal of the same length ass
References
- https://dsp.stackexchange.com/questions/9966/what-is-the-cutoff-frequency-of-a-moving-average-filter
filter_mavg(s; <keyword arguments>)Apply a weighted moving average filter to every channel × epoch slice of a 3-D signal array.
Arguments
s::AbstractArray: 3-D signal array, shape (channels, samples, epochs)k::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0).t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
Array{Float64, 3}: filtered array of the same shape ass
filter_mavg(obj; <keyword arguments>)Apply a weighted moving average filter to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)k::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0).t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
NeuroAnalyzer.NEURO: new object with filtered channels
NeuroAnalyzer.filter_mavg! — Function
filter_mavg!(obj; <keyword arguments>)Apply a weighted moving average filter in-place to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)k::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0).t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
Nothing
NeuroAnalyzer.filter_mmed — Function
filter_mmed(s; <keyword arguments>)Filter a signal using a weighted moving median with an optional threshold.
Samples within the threshold band [mean(s) − t×std(s), mean(s) + t×std(s)] are left unchanged; only outliers outside that band are replaced by the local weighted median. When t = 0 (default) every sample is filtered.
Arguments
s::AbstractVector: signal vectork::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0).t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
Vector{Float64}: filtered signal of the same length ass
References
- https://dsp.stackexchange.com/questions/9966/what-is-the-cutoff-frequency-of-a-moving-average-filter
filter_mmed(s; <keyword arguments>)Apply a weighted moving median filter to every channel × epoch slice of a 3-D signal array.
Arguments
s::AbstractArray: 3-D signal array, shape (channels, samples, epochs)k::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0).t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
Array{Float64, 3}: filtered array of the same shape ass
filter_mmed(obj; <keyword arguments>)Apply a weighted moving median filter to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)k::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0).t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
NeuroAnalyzer.NEURO: new object with filtered channels
NeuroAnalyzer.filter_mmed! — Function
filter_mmed!(obj; <keyword arguments>)Apply a weighted moving median filter in-place to selected channels of a NEURO object
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)k::Int64=8: half-window length; full window is2k + 1samples; for a desired normalized cutoffF = f/fs, choosek = round(Int, sqrt(0.196202 + F^2) / F); must satisfy1 ≤ k < length(s)t::Real=0: threshold multiplier (≥ 0).t = 0filters all samplesww::Union{Nothing, AbstractVector}=ones(2k+1): weighting window of length2k + 1
Returns
Nothing
NeuroAnalyzer.filter_poly — Function
filter_poly(s; <keyword arguments>)Filter a signal using a piecewise polynomial (Savitzky-Golay-style) filter.
The signal is split into non-overlapping windows. A polynomial of degree order is fitted to each window and used to replace the raw samples. Window boundaries are then smoothed with a Loess regression to suppress discontinuities between adjacent windows.
Arguments
s::AbstractVector: signal vectororder::Int64=8: polynomial degree; must be ≥ 2 and <windowwindow::Int64=10: window length in samples; must satisfy1 ≤ window ≤ length(s)
Returns
Vector{Float64}: filtered signal of the same length ass
filter_poly(s; <keyword arguments>)Apply a piecewise polynomial filter to every channel × epoch slice of a 3-D signal array.
Arguments
s::AbstractArray: 3-D signal array, shape (channels, samples, epochs)order::Int64=8: polynomial degree; must be ≥ 2 and <windowwindow::Int64=10: window length in samples; must satisfy1 ≤ window ≤ size(s, 2)
Returns
Returns
Array{Float64, 3}: filtered array of the same shape ass
filter_poly(obj; <keyword arguments>)Apply a piecewise polynomial filter to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)order::Int64=8: polynomial degree; must be ≥ 2 and <windowwindow::Int64=10: window length in samples; must satisfy1 ≤ window ≤ epoch_len(obj)
Returns
NeuroAnalyzer.NEURO: new object with filtered channels
NeuroAnalyzer.filter_poly! — Function
filter_poly!(obj; <keyword arguments>)Apply a piecewise polynomial filter in-place to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)order::Int64=8: polynomial degree; must be ≥ 2 and <windowwindow::Int64=10: window length in samples; must satisfy1 ≤ window ≤ epoch_len(obj)
Returns
Nothing
NeuroAnalyzer.filter_sg — Function
filter_sg(s; <keyword arguments>)Filter a signal using a Savitzky-Golay smoothing filter.
Fits a polynomial of degree order to successive overlapping windows of window samples using least squares, then uses the fitted polynomial to replace each sample. Preserves peak heights and widths better than a simple moving average.
Arguments
s::AbstractVector: signal vector; must have at leastwindowelementsorder::Int64=6: polynomial degree; must satisfy2 ≤ order < windowwindow::Int64=11: filter window length (number of coefficients); must be odd and satisfy1 ≤ window ≤ length(s)
Returns
Vector{Float64}: filtered signal of the same length ass
filter_sg(s; <keyword arguments>)Apply a Savitzky-Golay filter to every channel × epoch slice of a 3-D signal array.
Arguments
s::AbstractArray: 3-D signal array, shape (channels, samples, epochs)order::Int64=6: polynomial degree; must satisfy2 ≤ order < windowwindow::Int64=11: filter window length (number of coefficients); must be odd and satisfy1 ≤ window ≤ size(s, 2)
Returns
Array{Float64, 3}: filtered array of the same shape ass
filter_sg(obj; <keyword arguments>)Apply a Savitzky-Golay filter to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)order::Int64=6: polynomial degree; must satisfy2 ≤ order < windowwindow::Int64=11: filter window length (number of coefficients); must be odd and satisfy1 ≤ window ≤ epoch_len(obj)
Returns
NeuroAnalyzer.NEURO: new object with filtered channels
NeuroAnalyzer.filter_sg! — Function
filter_sg!(obj; <keyword arguments>)Apply a Savitzky-Golay filter in-place to selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)order::Int64=6: order of the polynomial used to fit the samples; must be less thanwindowwindow::Int64=11: length of the filter window (i.e., the number of coefficients); must be an odd number
Returns
Nothing
NeuroAnalyzer.generate_ssp_projectors — Function
generate_ssp_projectors(obj; <keyword arguments>)Generate SSP (Signal-Space Projection) projectors from the SSP data embedded in a MEG recording.
The projectors are constructed by extracting the selected projection vectors, re-orthogonalising them via SVD, discarding linearly dependent vectors (relative singular-value threshold 0.01, following MNE-Python), and forming I - U Uᵀ to project the data onto the space orthogonal to the noise subspace.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectpidx::Union{Int64, Vector{Int64}}=0: projection index/indices to use;0(default) selects all available projections
Returns
Named tuple:
ssp_projectors::Matrix{Float64}: projection operatorI − U UᵀU::Matrix{Float64}}: SVD U matrix (orthonormal basis of the noise subspace)
NeuroAnalyzer.gh — Function
gh(locs; <keyword arguments>)Compute the G (potential spline) and H (CSD spline) matrices for a set of electrode locations on the unit sphere.
Arguments
locs::DataFrame: electrode locations; must contain columns:loc_x,:loc_y,:loc_z(Cartesian coordinates, normalised to the unit sphere)m::Int64=4: spline flexibility constant; must be in[2, 10]; higher values increase rigidityn::Int64=8: Legendre polynomial order; must be ≥ 1
Returns
Named tuple:
G::Matrix{Float64}: potential spline matrix(ch_n, ch_n)H::Matrix{Float64}: CSD spline matrix(ch_n, ch_n)
References
Perrin F, Pernier J, Bertrand O, Echallier JF. Spherical splines for scalp potential and current density mapping. Electroencephalography and Clinical Neurophysiology. 1989;72(2):184–187.
NeuroAnalyzer.ica_decompose — Function
ica_decompose(s; <keyword arguments>)Decompose a signal into Independent Components (ICs) using the FastICA algorithm.
Arguments
s::AbstractMatrix: input signal, shape(channels, samples)n::Int: number of independent components to extractiter::Int=100: max iterations per tolerance levelf::Symbol=:tanh: nonlinear function for neg-entropy approximation (:tanhor:gaus)
Returns
Named tuple:
ic::Matrix{Float64}: independent components, shape (n, samples)ic_mw::Matrix{Float64}: weighting (unmixing) matrix, shape (channels, n)
ica_decompose(obj; <keyword arguments>)Decompose selected channels of a NEURO object into Independent Components (ICs) using the FastICA algorithm. Sorts components by variance explained.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)n::Int: number of independent components to extractiter::Int=100: max iterations per tolerance levelf::Symbol=:tanh: nonlinear function for neg-entropy approximation (:tanhor:gaus)
Returns
Named tuple:
ic::Matrix{Float64}: independent components, shape (n, samples)ic_mw::Matrix{Float64}: weighting (unmixing) matrix, shape (channels, n)ic_var::Vector{Float64}: variance explained by each component
NeuroAnalyzer.ica_remove — Function
ica_remove(; <keyword arguments>)Reconstruct a signal by removing independent component(s).
Arguments
ic::Matrix{Float64}: independent components, shape (n, samples)ic_mw::Matrix{Float64}: weighting (unmixing) matrix, shape (channels, n)ic_idx::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: indices of components to removekeep::Bool=false: iftrue, keep specified components and remove all other components
Returns
Matrix{Float64}: reconstructed signal, shape (channels, samples)
ica_remove(obj, ic, ic_mw; <keyword arguments>)Reconstruct selected channels of a NEURO object by removing independent component(s).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)ic::Matrix{Float64}: independent components, shape (n, samples)ic_mw::Matrix{Float64}: weighting (unmixing) matrix, shape (channels, n)ic_idx::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: indices of components to removekeep::Bool=false: iftrue, keep specified components and remove all other components
Returns
NeuroAnalyzer.NEURO: reconstructed NEURO object
NeuroAnalyzer.ica_remove! — Function
ica_remove!(obj, ic, ic_mw; <keyword arguments>)Reconstruct selected channels of a NEURO object by removing independent component(s) in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s), default is all channelsic_idx::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: indices of components to keep or removeic::Matrix{Float64}: independent components, shape (n, samples)ic_mw::Matrix{Float64}: weighting (unmixing) matrix, shape (channels, n)keep::Bool=false: iftrue, keep specified components; otherwise, remove them
Returns
Nothing
NeuroAnalyzer.icwd — Function
icwd(ct; <keyword arguments>)Perform inverse continuous wavelet transformation (iCWT).
Reconstructs the original signal from a CWT coefficient matrix produced by cwd.
Arguments
ct::Matrix{Float64}: CWT coefficient matrix of shape(n_scales, samples)(as returned bycwd)wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): continuous wavelet; must match the one used in the forward transformtype::Symbol=:pd: reconstruction method::pd: PenroseDelta (default; generally most accurate):nd: NaiveDelta:df: DualFrames
Returns
Vector{Float64}: reconstructed signal
NeuroAnalyzer.idwd — Function
idwd(dc; <keyword arguments>)Perform inverse discrete wavelet decomposition (iDWD).
Reconstructs a signal from a subset (or all) of the DWD coefficient rows.
Arguments
dc::Matrix{Float64}: DWD coefficient matrix of shape(n_nodes, samples)as returned bydwdwt<:DiscreteWavelet=wavelet(WT.haar): discrete wavelet; see Wavelets.jl documentation for the list of available waveletstype::Symbol: transformation type::sdwt: average-based stationary discrete wavelet transform:acdwt: discrete autocorrelation wavelet transform
c::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=axes(dc, 1): row indices of coefficients to use for reconstruction; default uses all rows; indices must be in[1, size(dc, 1)]
Returns
Vector{Float64}: reconstructed signal
NeuroAnalyzer.intensity2od — Function
intensity2od(s)Convert NIRS raw intensity signal to optical density (OD).
The optical density is defined as:
OD = −log(I / Ī)where Ī is the mean absolute intensity across the sample (time) dimension. The mean is computed per channel and per epoch so that the reference level adapts to each recording segment independently.
Arguments
s::AbstractArray: intensity array with axes, shape (channels, samples, epochs)
Returns
od::AbstractArray: optical density array, same shape ass
intensity2od(obj; <keyword arguments>)Convert NIRS intensity (RAW) channels to optical density (OD) and append the OD channels to the object. Both the original intensity channels and the new OD channels are retained.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}=get_channel(obj, type="nirs_int")): list of channels, default is all NIRS intensity channels
Returns
NeuroAnalyzer.NEURO: output NEURO object with OD channels appended after the selected intensity channels
NeuroAnalyzer.intensity2od! — Function
intensity2od!(obj; <keyword arguments>)Convert NIRS intensity channels to optical density in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}=get_channel(obj, type="nirs_int")): list of channels, default is NIRS intensity channels
Returns
Nothing
NeuroAnalyzer.invert_polarity — Function
invert_polarity(obj; <keyword arguments>)Invert polarity.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.invert_polarity! — Function
invert_polarity!(obj; <keyword arguments>)Invert polarity.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel(s) to invert
Returns
Nothing
NeuroAnalyzer.lrinterpolate_channel — Function
lrinterpolate_channel(obj; <keyword arguments>)Interpolate channel using linear regression.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel to interpolateep::Int64: epoch index to interpolateep_ref::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=setdiff(_c(nepochs(obj)), ep): reference epochs used for training; default is all epochs exceptep
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.lrinterpolate_channel! — Function
lrinterpolate_channel!(obj; <keyword arguments>)Interpolate channel using linear regression.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel to interpolateep::Int64: epoch index(s) within to interpolateep_ref::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=setdiff(_c(nepochs(obj)), ep): reference epochs used for training; default is all epochs exceptep
Returns
Nothing
NeuroAnalyzer.mlinterpolate_channel — Function
mlinterpolate_channel(obj; <keyword arguments>)Interpolate a single channel in a specified epoch using a machine-learning regression model trained on the remaining epochs.
The model is trained with all other signal channels as features and the target channel as the response. After training, the fitted model predicts the target channel's values for the epoch to interpolate.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: name of the channel to interpolateep::Int64: index of the epoch to interpolateep_ref::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=setdiff(_c(nepochs(obj)), ep): reference epochs used for training; default is all epochs exceptepmodel::T where T <: MLJ.Model: any MLJ regressor (e.g.RandomForestRegressor)
Returns
NeuroAnalyzer.NEURO: output NEURO object with the specified channel/epoch replaced by the model's prediction
NeuroAnalyzer.mlinterpolate_channel! — Function
mlinterpolate_channel!(obj; <keyword arguments>)Interpolate a channel using an MLJ regression model, modifying obj in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: name of the channel to interpolateep::Int64: index of the epoch to interpolateep_ref::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=setdiff(_c(nepochs(obj)), ep): reference epochs for training; default is all epochs exceptepmodel::T where T <: MLJ.Model: any MLJ regressor (e.g.RandomForestRegressor)
Returns
Nothing
NeuroAnalyzer.normalize — Function
normalize(s, n; <keyword arguments>)Normalize.
Arguments
s::AbstractVector: signal vectorn::Real=1: scaling parameter used by:minmax,:nmethod::Symbol: normalization method::zscore: by z-score:minmax: in [-n, +n]:log: using log-transformation:log10: using log10-transformation:neglog: using -log-transformation:neglog10: using -log10-transformation:neg: in [-∞, 0]:pos: in [0, +∞]:perc: in percentages:gauss: to Gaussian:invroot: to inverse root: 1/sqrt(x):n: in [0, n], default is [0, 1]:softmax: using softmax function: exp(x_i) / sum(exp(x)):sigmoid: using sigmoid function: 1 / 1 + exp(-x_i):mad: by MAD:rank: using tiedranks:none
Returns
normalized::AbstractVector
normalize(s, n; <keyword arguments>)Normalize a signal array using the specified method.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)n::Real=1: scaling parameter used by:minmax,:nbych::Bool=false: iftrue, normalize each channel separatelymethod::Symbol: normalization method::zscore: by z-score:minmax: in [-n, +n]:log: using log-transformation:log10: using log10-transformation:neglog: using -log-transformation:neglog10: using -log10-transformation:neg: in [-∞, 0]:pos: in [0, +∞]:perc: in percentages:gauss: to Gaussian:invroot: to inverse root: 1/sqrt(x):n: in [0, n], default is [0, 1]; <keyword arguments>) .+ n1`:softmax: using softmax function: exp(x_i) / sum(exp(x)):sigmoid: using sigmoid function: 1 / 1 + exp(-x_i):none
Returns
AbstractArray: normalized signal, same shape ass
normalize(obj; <keyword arguments>)Normalize selected channels of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)method::Symbol: normalization method::zscore: by z-score:minmax: in [-n, +n]:log: using log-transformation:log10: using log10-transformation:neglog: using -log-transformation:neglog10: using -log10-transformation:neg: in [-∞, 0]:pos: in [0, +∞]:perc: in percentages:gauss: to Gaussian:invroot: to inverse root: 1/sqrt(x):n: in [0, n], default is [0, 1]:softmax: using softmax function: exp(x_i) / sum(exp(x)):sigmoid: using sigmoid function: 1 / 1 + exp(-x_i):mad: by MAD:rank: using tiedranks:none
bych::Bool=false: iftrue, normalize each channel separatelyn::Real=1: scaling parameter used by:minmax,:n
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.normalize! — Function
normalize!(obj; <keyword arguments>)Normalize selected channels in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)method::Symbol: normalization method::zscore: by z-score:minmax: in [-n, +n]:log: using log-transformation:log10: using log10-transformation:neglog: using -log-transformation:neglog10: using -log10-transformation:neg: in [-∞, 0]:pos: in [0, +∞]:perc: in percentages:gauss: to Gaussian:invroot: to inverse root: 1/sqrt(x):n: in [0, n], default is [0, 1]:softmax: using softmax function: exp(x_i) / sum(exp(x)):sigmoid: using sigmoid function: 1 / 1 + exp(-x_i):mad: by MAD:rank: using tiedranks:none
bych::Bool=false: iftrue, normalize each channel separatelyn::Real=1: scaling parameter used by:minmax,:n
Returns
Nothing
NeuroAnalyzer.normalize_fisher — Function
normalize_fisher(s)Fisher z-transform normalization. First normalizes to [−1, +1] via normalize_minmax, then applies atanh(x) = 0.5 × ln((1+x)/(1−x)). Endpoint values ±1 are nudged inward by eps() to avoid infinite output.
This is mathematically equivalent to atanh, and converts a uniform distribution into a normal distribution.
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_fisher(s; <keyword arguments>)Fisher z-transform normalization. First normalizes to [−1, +1] via normalize_minmax, then applies atanh(x) = 0.5 × ln((1+x)/(1−x)). Endpoint values ±1 are nudged inward by eps() to avoid infinite output.
This is mathematically equivalent to atanh, and converts a uniform distribution into a normal distribution.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: ignored
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_gauss — Function
normalize_gauss(s)Normalize to Gaussian via rank-based inverse normal transform (Fisher–Yates): atanh(2 * tiedrank(x) / (n+1) − 1).
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_gauss(s; <keyword arguments>)Normalize to Gaussian via rank-based inverse normal transform (Fisher–Yates): atanh(2 * tiedrank(x) / (n+1) − 1).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_invroot — Function
normalize_invroot(s)Inverse-root normalize: 1 / √x. Exact zeros are replaced with eps() to avoid division by zero. A copy of s is made to avoid mutating the input.
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_invroot(s; <keyword arguments>)Inverse-root normalize: 1 / √x. Exact zeros are replaced with eps() to avoid division by zero. A copy of s is made to avoid mutating the input.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_log — Function
normalize_log(s)Log-normalize: log(1 + x + |min(x)|), ensuring the argument is always ≥ 1.
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_log(s; <keyword arguments>)Normalize using log-transformation.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_log10 — Function
normalize_log10(s)Log₁₀-normalize: log10(x + 1 + |min(x)|).
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_log10(s; <keyword arguments>)Log₁₀-normalize: log10(x + 1 + |min(x)|).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_mad — Function
normalize_mad(s)Normalize by MAD: (x − x̃) / (1.4826 × MAD). If MAD = 0, subtracts the median only.
The 1.4826 factor is the standard consistency constant for a normal distribution (scales MAD to estimate σ).
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_mad(s; <keyword arguments>)Normalize by MAD: (x − x̃) / (1.4826 × MAD). If MAD = 0, subtracts the median only.
The 1.4826 factor is the standard consistency constant for a normal distribution (scales MAD to estimate σ).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_minmax — Function
normalize_minmax(s, n)Normalize in [-n, +n]. Constant signals are mapped to +n.
Arguments
s::AbstractVector: signal vectorn::Real=1: scaling parameter
Returns
AbstractVector: normalized signal, same shape ass
normalize_minmax(s, n; <keyword arguments>)Normalize to [−n, +n] across the array, or per channel when bych=true. Constant signals are mapped to +n.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)n::Real=1: scaling parameterbych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_n — Function
normalize_n(s, n)Normalize to [0, n] (default [0, 1]). Constant signals map to n.
Arguments
s::AbstractVector: signal vectorn::Real=1: scaling parameter
Returns
AbstractVector: normalized signal, same shape ass
normalize_n(s, n; <keyword arguments>)Normalize to [0, n], or per channel when bych=true.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)n::Real=1bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_neg — Function
normalize_neg(s)Shift signal to (−∞, 0] by subtracting the maximum.
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_neg(s)Shift signal to (−∞, 0] by subtracting the maximum.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_neglog — Function
normalize_neglog(s; <keyword arguments>)Negative log-normalize: −log(x). bych is ignored (element-wise operation).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: ignored
Returns
Vector{Float64}
NeuroAnalyzer.normalize_neglog10 — Function
normalize_neglog10(s; <keyword arguments>)Negative log-normalize: −log(x). bych is ignored (element-wise operation).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: ignored
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_perc — Function
normalize_perc(s)Normalize to percentages: (x − min) / (max − min). Constant signals produce all-zeros.
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_perc(s; <keyword arguments>)Normalize to percentages: (x − min) / (max − min). Constant signals produce all-zeros.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_pos — Function
normalize_pos(s)Shift signal to [0, +∞) by adding |min(x)|.
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_pos(s; <keyword arguments>)Shift signal to [0, +∞) by adding |min(x)|.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_rank — Function
normalize_rank(s)Normalize using tied ranks (result is in [1, n]).
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_rank(s; <keyword arguments>)Normalize using tied ranks (result is in [1, n]).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_sigmoid — Function
normalize_sigmoid(s; <keyword arguments>)Sigmoid normalization: 1 / (1 + e^{−xᵢ}). bych is ignored.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: ignored
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_softmax — Function
normalize_softmax(s; <keyword arguments>)Softmax normalization: exp(xᵢ) / Σexp(x). bych is ignored.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: ignored
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normalize_zscore — Function
normalize_zscore(s)Normalize by z-score: (x − x̄) / σ. If σ = 0, subtracts the mean only.
Arguments
s::AbstractVector: signal vector
Returns
AbstractVector: normalized signal, same shape ass
normalize_zscore(s; <keyword arguments>)Normalize by z-score across the whole array, or per channel when bych=true.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)bych::Bool=false: if true, normalize each channel separately
Returns
AbstractArray: normalized signal, same shape ass
NeuroAnalyzer.normpower — Function
normpower(s)Return a signal with normalized power (amplitudes divided by the root-mean-squared value of the entire signal).
Arguments
s::AbstractVector: signal vector
Returns
Vector{Float64}
normpower(s)Return a signal with normalized power (amplitudes divided by the root-mean-squared value of the entire signal) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Array{Float64, 3}
normpower(obj; <keyword arguments>)Return a signal with normalized power (amplitudes divided by the root-mean-squared value of the entire signal).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.normpower! — Function
normpower!(obj; <keyword arguments>)Return a signal with normalized power (amplitudes divided by the root-mean-squared value of the entire signal).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Nothing
NeuroAnalyzer.npl — Function
npl(obj)Calculate non-phase-locked signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be ERP/ERF object
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.npl! — Function
npl!(obj)Calculate non-phase-locked signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be ERP object
Returns
Nothing
NeuroAnalyzer.od2conc — Function
od2conc(obj; <keyword arguments>)Convert NIRS optical density (OD) to concentration (HbO, HbR, HbT).
ppf parameter is the partial path length factors for each wavelength. This is a vector of factors per wavelength. Typical value is ~6 for each wavelength if the absorption change is uniform over the volume of tissue measured. To approximate the partial volume effect of a small localized absorption change within an adult human head, this value could be as small as 0.1. Convention is becoming to set ppf=1 and to not divide by the source-detector separation such that the resultant "concentration" is in units of Molar mm (or Molar cm if those are the spatial units). This is becoming wide spread in the literature but there is no fixed citation. Use a value of 1 to choose this option.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}=get_channel(obj, type="nirs_od")): list of channels, default is NIRS intensity channelsppf::Vector{Real}=ones(length(obj.header.recording[:wavelengths])): partial path length factors for each wavelength
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.od2conc! — Function
od2conc!(obj; <keyword arguments>)Convert NIRS optical density (OD) to concentration (HbO, HbR, HbT).
ppf parameter is the partial path length factors for each wavelength. This is a vector of factors per wavelength. Typical value is ~6 for each wavelength if the absorption change is uniform over the volume of tissue measured. To approximate the partial volume effect of a small localized absorption change within an adult human head, this value could be as small as 0.1. Convention is becoming to set ppf=1 and to not divide by the source-detector separation such that the resultant "concentration" is in units of Molar mm (or Molar cm if those are the spatial units). This is becoming wide spread in the literature but there is no fixed citation. Use a value of 1 to choose this option.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}=get_channel(obj, type="nirs_od")): list of channels, default is NIRS intensity channelsppf::Vector{Real}=ones(length(obj.header.recording[:wavelengths])): partial path length factors for each wavelength
Returns
Nothing
NeuroAnalyzer.pca_decompose — Function
pca_decompose(s, n)Calculate n first Primary Components (PCs) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)n::Int64: number of PCs
Returns
Named tuple:
pc::Array{Float64, 3}: PC(1)..PC(n) × epochpcv::Matrix{Float64}: PC(1)..PC(n) variances (fraction of total variance explained)pcm::Vector{Float64}: PC meanspc_model::MultivariateStats.PCA{Float64}: PC model
pca_decompose(obj; <keyword arguments>)Calculate n first Primary Components (PCs).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)n::Int64: number of PCs to calculate
Returns
Named tuple:
pc::Array{Float64, 3}: PC(1)..PC(n) × epochpcv::Matrix{Float64}: PC variances (fraction of total variance explained)pcm::Vector{Float64}: PC meanspc_model::MultivariateStats.PCA{Float64}: PC model
NeuroAnalyzer.pca_reconstruct — Function
pca_reconstruct(s, pc, pca)Reconstructs signal using PCA components for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)pc::AbstractArray: IC(1)..IC(n) × epochpc_model::MultivariateStats.PCA{Float64}: PC model
Returns
Array{Float64, 3}
pca_reconstruct(obj, pc, pc_model; <keyword arguments>)Reconstruct signal using PCA components (pc and pca).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pc::Array{Float64, 3}: PC(1)..PC(n) × epochpc_model::MultivariateStats.PCA{Float64}: PC model
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.pca_reconstruct! — Function
pca_reconstruct!(obj, pc, pc_model; <keyword arguments>)Reconstruct signals using PCA components (pc and pc_model).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pc::Array{Float64, 3}: PC(1)..PC(n) × epochpc_model::MultivariateStats.PCA{Float64}: PC model
Returns
Nothing
NeuroAnalyzer.plinterpolate — Function
plinterpolate(s; <keyword arguments>)Interpolate channel using planar interpolation.
Arguments
s::Matrix{Float64}: values to plot (one value per channel)locs::DataFrame: columns: channel, labels, locradius, loctheta, locx, locy, locz, locradiussph, locthetasph, locphi_sphch::Int64: channel to interpolateimethod::Symbol=:sh: interpolation method::sh: Shepard:mq: Multiquadratic:imq: Inverse Multiquadratic:tp: ThinPlate:nn: Nearest Neighbour:ga: Gaussian
nmethod::Symbol=:minmax: method for normalization, seenormalize()cart::Bool=false: if true, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planesifactor::Int64=100: interpolation quality
Returns
Named tuple:
int_s::Matrix{Float64}: interpolated signalint_x::Vector{Float64}: X-axis coordinatesint_y::Vector{Float64}: Y-axis coordinates
NeuroAnalyzer.plinterpolate_channel — Function
plinterpolate_channel(obj; <keyword arguments>)Interpolate channel using planar interpolation.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel to interpolateep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: epoch number(s) within to interpolateimethod::Symbol=:sh: interpolation method::sh: Shepard:mq: Multiquadratic:imq: Inverse Multiquadratic:tp: ThinPlate:nn: Nearest Neighbour:ga: Gaussian
ifactor::Int64=100: interpolation quality
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.plinterpolate_channel! — Function
plinterpolate_channel!(obj; <keyword arguments>)Interpolate channel using planar interpolation.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel to interpolateep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}: epoch number(s) within to interpolateimethod::Symbol=:sh: interpolation method Shepard (:sh), Multiquadratic (:mq), InverseMultiquadratic (:imq), ThinPlate (:tp), NearestNeighbour (:nn), Gaussian (:ga)ifactor::Int64=100: interpolation quality
Returns
Nothing
NeuroAnalyzer.reference_a — Function
reference_a(obj; <keyword arguments>)Re-reference EEG channels to auricular electrodes (A1, A2). Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must contain A1 and A2 channels; must be of type"eeg"type::Symbol=:l: reference type::l: linked - average of A1 and A2:i: ipsilateral - A1 for left channels, A2 for right channels:c: contralateral - A2 for left channels, A1 for right channels
med::Bool=false: use median instead of mean
Returns
NeuroAnalyzer.NEURO: new re-referenced object
NeuroAnalyzer.reference_a! — Function
reference_a!(obj; <keyword arguments>)Re-reference EEG channels to auricular electrodes in-place. Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must contain A1 and A2 channels; must be of type"eeg"; modified in-placetype::Symbol=:l: reference type::l: linked - average of A1 and A2:i: ipsilateral - A1 for left channels, A2 for right channels:c: contralateral - A2 for left channels, A1 for right channels
med::Bool=false: use median instead of mean
Returns
Nothing
NeuroAnalyzer.reference_avg — Function
reference_avg(obj; <keyword arguments>)Re-reference EEG channels to the common average reference (CAR). Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"exclude_fpo::Bool=false: exclude Fp1, Fp2 (due to eye blinks), O1, O2 (due to head movements) from the CAR calculationexclude_current::Bool=false: exclude the current channel from its own CAR calculationaverage::Bool=true: subtract the mean (or median) reference; iffalse, subtract the summed::Bool=false: use median instead of meanweighted::Bool=false: weight reference channels by inverse distance (requires channel locations)
Returns
NeuroAnalyzer.NEURO: new object with re-referenced EEG channels
NeuroAnalyzer.reference_avg! — Function
reference_avg!(obj; <keyword arguments>)Re-reference EEG channels to the common average reference in-place. Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"; modified in-placeexclude_fpo::Bool=false: exclude Fp1, Fp2 (due to eye blinks), O1, O2 (due to head movements) from the CAR calculationexclude_current::Bool=false: exclude the current channel from its own CAR calculationaverage::Bool=true: subtract the mean (or median) reference; iffalse, subtract the summed::Bool=false: use median instead of meanweighted::Bool=false: weight reference channels by inverse distance (requires channel locations)
Returns
Nothing
NeuroAnalyzer.reference_ce — Function
reference_ce(obj; <keyword arguments>)Re-reference EEG channels to a common electrode or the average of multiple electrodes. Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"ch::Union{String, Vector{String}, Regex}: reference channel name(s); if multiple channels are given their mean (or median) is used as the referencemed::Bool=false: iftrue, use median instead of mean for multi-channel reference
Returns
NeuroAnalyzer.NEURO: new object with re-referenced EEG channels
NeuroAnalyzer.reference_ce! — Function
reference_ce!(obj; <keyword arguments>)Re-reference EEG channels to a common electrode in-place. Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"; modified in-placech::Union{String, Vector{String}, Regex}: reference channel name(s); if multiple channels are given their mean (or median) is used as the referencemed::Bool=false: iftrue, use median instead of mean for multi-channel reference
Returns
Nothing
NeuroAnalyzer.reference_custom — Function
reference_custom(obj; <keyword arguments>)Re-reference EEG channels using a custom bipolar or referential montage.
Each entry in ref_list is either a single channel name (copied as-is) or a "Ch1-Ch2" pair (output = Ch2 − Ch1). All referenced EEG channels are replaced by the new montage channels; non-EEG channels are preserved.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectref_list::Vector{String}=["Fz-Cz", "Cz-Pz", "Fp1-F7", "Fp1-F3", "F7-T3", "T3-T5", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "Fp2-F4", "F8-T4", "T4-T6", "T6-O2", "F4-C4", "C4-P4", "P4-O2"]: montage definition; default is a standard longitudinal bipolar montageref_name::String="longitudinal-BIP": montage name stored in the header
Returns
NeuroAnalyzer.NEURO: new object with montage-referenced channels
Notes
"Ch1-Ch2"→ output = amplitude(Ch2) − amplitude(Ch1).- The channel location table is not updated (marked as TODO).
Examples of montages:
- bipolar transverse: ["Fp2-Fp1", "F8-Fp2", "F8-F4", "F4-Fz", "Fz-F3", "F3-F7", "Fp1-F7", "T4-C4", "C4-Cz", "Cz-C3", "C3-T3", "T6-P4", "P4-Pz", "Pz-P3", "P3-T5", "O2-O1"], "transverse-BIP"
- bipolar longitudinal: ["Fz-Cz", "Cz-Pz", "Pz-Oz", "Fp1-F7", "Fp1-F3", "F7-T7", "F7-T3", "T7-P7", "T7-T5", "T3-P7", "T3-T5", "P7-O1", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "F8-T8", "F8-T4", "T8-P8", "T8-T6", "T4-P8", "T4-T6", "T6-O2", "P8-O2", "Fp2-F4", "F4-C4", "C4-P4", "P4-O2"], "longitudinal-BIP"
- bipolar longitudinal: ["Fz", "Cz", "Pz", "Fp1-F7", "Fp1-F3", "F7-T3", "T3-T5", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "Fp2-F4", "F8-T4", "T4-T6", "T6-O2", "F4-C4", "C4-P4", "P4-O2"], "longitudinal-BIP"
- bipolar longitudinal: ["FPz-Fz", "Fz-Cz", "Cz-Pz", "Pz-Oz", "Fp1-F7", "Fp1-F3", "F7-T7", "F7-T3", "T7-P7", "T7-T5", "T3-P7", "T3-T5", "P7-O1", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "F8-T8", "F8-T4", "T8-P8", "T8-T6", "T4-P8", "T4-T6", "T6-O2", "P8-O2", "Fp2-F4", "F4-C4", "C4-P4", "P4-O2"], "longitudinal-BIP"
NeuroAnalyzer.reference_custom! — Function
reference_custom!(obj; <keyword arguments>)Re-reference EEG channels using a custom montage in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be of type"eeg"; modified in-placeref_list::Vector{String}=["Fz-Cz", "Cz-Pz", "Fp1-F7", "Fp1-F3", "F7-T3", "T3-T5", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "Fp2-F4", "F8-T4", "T4-T6", "T6-O2", "F4-C4", "C4-P4", "P4-O2"]: montage definition; default is a standard longitudinal bipolar montageref_name::String="longitudinal-BIP": montage name stored in the header
Returns
Nothing
Notes
"Ch1-Ch2"→ output = amplitude(Ch2) − amplitude(Ch1).- The channel location table is not updated (marked as TODO).
Examples of montages:
- bipolar transverse: ["Fp2-Fp1", "F8-Fp2", "F8-F4", "F4-Fz", "Fz-F3", "F3-F7", "Fp1-F7", "T4-C4", "C4-Cz", "Cz-C3", "C3-T3", "T6-P4", "P4-Pz", "Pz-P3", "P3-T5", "O2-O1"], "transverse-BIP"
- bipolar longitudinal: ["Fz-Cz", "Cz-Pz", "Pz-Oz", "Fp1-F7", "Fp1-F3", "F7-T7", "F7-T3", "T7-P7", "T7-T5", "T3-P7", "T3-T5", "P7-O1", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "F8-T8", "F8-T4", "T8-P8", "T8-T6", "T4-P8", "T4-T6", "T6-O2", "P8-O2", "Fp2-F4", "F4-C4", "C4-P4", "P4-O2"], "longitudinal-BIP"
- bipolar longitudinal: ["Fz", "Cz", "Pz", "Fp1-F7", "Fp1-F3", "F7-T3", "T3-T5", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "Fp2-F4", "F8-T4", "T4-T6", "T6-O2", "F4-C4", "C4-P4", "P4-O2"], "longitudinal-BIP"
- bipolar longitudinal: ["FPz-Fz", "Fz-Cz", "Cz-Pz", "Pz-Oz", "Fp1-F7", "Fp1-F3", "F7-T7", "F7-T3", "T7-P7", "T7-T5", "T3-P7", "T3-T5", "P7-O1", "T5-O1", "F3-C3", "C3-P3", "P3-O1", "Fp2-F8", "F8-T8", "F8-T4", "T8-P8", "T8-T6", "T4-P8", "T4-T6", "T6-O2", "P8-O2", "Fp2-F4", "F4-C4", "C4-P4", "P4-O2"], "longitudinal-BIP"
NeuroAnalyzer.reference_m — Function
reference_m(obj; <keyword arguments>)Re-reference EEG channels to mastoid electrodes (M1, M2). Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must contain M1 and M2 channels; must be of type"eeg"; modified in-placetype::Symbol=:l: reference type::l: linked - average of M1 and M2:i: ipsilateral - M1 for left channels, M2 for right channels:c: contralateral - M2 for left channels, M1 for right channels
med::Bool=false: use median instead of mean
Returns
NeuroAnalyzer.NEURO: new re-referenced object
NeuroAnalyzer.reference_m! — Function
reference_m!(obj; <keyword arguments>)Re-reference EEG channels to mastoid electrodes in-place. Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must contain M1 and M2 channels; must be of type"eeg"; modified in-placetype::Symbol=:l: reference type::l: linked - average of M1 and M2:i: ipsilateral - M1 for left channels, M2 for right channels:c: contralateral - M2 for left channels, M1 for right channels
med::Bool=false: use median instead of mean
Returns
Nothing
NeuroAnalyzer.reference_plap — Function
reference_plap(obj; <keyword arguments>)Re-reference EEG channels using the planar (2-D Euclidean) Laplacian. Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must have channel locations; must be of type"eeg"nn::Int64=4: number of nearest-neighbour electrodes; must satisfy1 ≤ nn < nch-1weighted::Bool=false: weight neighbours by inverse distancemed::Bool=false: use median instead of mean.
Returns
NeuroAnalyzer.NEURO: new re-referenced object
NeuroAnalyzer.reference_plap! — Function
reference_plap!(obj; <keyword arguments>)Re-reference EEG channels using the planar Laplacian in-place. Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must have channel locations; must be of type"eeg"; modified in-placenn::Int64=4: number of nearest-neighbour electrodes; must satisfy1 ≤ nn < nch-1weighted::Bool=false: weight neighbours by inverse distancemed::Bool=false: use median instead of mean.
Returns
Nothing
NeuroAnalyzer.reference_slap — Function
reference_slap(obj; <keyword arguments>)Re-reference EEG channels using the spherical Laplacian (great-circle distance). Only EEG-type channels are modified.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must have channel locations; must be of type"eeg"nn::Int64=4: number of nearest-neighbour electrodes; must satisfy1 ≤ nn < nch-1weighted::Bool=false: weight neighbours by inverse distancemed::Bool=false: use median instead of mean.
Returns
NeuroAnalyzer.NEURO: new re-referenced object
NeuroAnalyzer.reference_slap! — Function
reference_slap!(obj; <keyword arguments>)Re-reference EEG channels using the spherical Laplacian in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must have channel locations; must be of type"eeg"; modified in-placenn::Int64=4: number of nearest-neighbour electrodes; must satisfy1 ≤ nn < nch-1weighted::Bool=false: weight neighbours by inverse distancemed::Bool=false: use median instead of mean.
Returns
Nothing
NeuroAnalyzer.remove_dc — Function
remove_dc(s, n)Remove mean value (DC offset).
Arguments
s::AbstractVector: signal vectorn::Union{Int64, Tuple{Int64, Int64}}=0: ifnis greater than 0, mean value is calculated for the firstnsamples or ifnis a tuple greater than (0, 0), mean value is calculated forn[1]ton[2]samples
Returns
Vector{Float64}
remove_dc(s, n)Remove mean value (DC offset).
Arguments
s::AbstractMatrix: signal matrix, shape (channels, samples)n::Union{Int64, Tuple{Int64, Int64}}=0: ifnis greater than 0, mean value is calculated for the firstnsamples or ifnis a tuple greater than (0, 0), mean value is calculated forn[1]ton[2]samples
Returns
Matrix{Float64}
remove_dc(s, n)Remove mean value (DC offset) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)n::Union{Int64, Tuple{Int64, Int64}}=0: ifnis greater than 0, mean value is calculated for the firstnsamples or ifnis a tuple greater than (0, 0), mean value is calculated forn[1]ton[2]samples
Returns
Array{Float64, 3}
remove_dc(obj; <keyword arguments>)Remove mean value (DC offset).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)n::Union{Int64, Tuple{Int64, Int64}}=0: ifnis greater than 0, mean value is calculated for the firstnsamples or ifnis a tuple greater than (0, 0), mean value is calculated forn[1]ton[2]samples
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.remove_dc! — Function
remove_dc!(obj; <keyword arguments>)Remove mean value (DC offset).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)n::Union{Int64, Tuple{Int64, Int64}}=0: ifnis greater than 0, mean value is calculated for the firstnsamples or ifnis a tuple greater than (0, 0), mean value is calculated forn[1]ton[2]samples
Returns
Nothing
NeuroAnalyzer.remove_pops — Function
remove_pops(s; <keyword arguments>)Detect and repair electrode pops (rapid amplitude change). Signal is recovered within the segments starting and ending at zero-crossing. Only one pop is detected, signal length should be ≥2 seconds.
Arguments
s::AbstractVector: signal vectorr::Int64=20: detection segment length; pops are checked withinpop_loc - r:pop_loc + rsamplesrepair::Bool=true: recover the segment iftrue
Returns
Named tuple:
s::Vector{Float64}pop_loc::Int64: sample number in the signall_seg::Int64: length of segment before the pop that starts when signal crosses 0r_seg::Int64: length of segment after the pop that ends when signal crosses 0
remove_pops(obj; <keyword arguments>)Detect and repair electrode pops (rapid amplitude change). Signal is recovered within the segments starting and ending at zero-crossing. Only one pop is detected per segment, signal length should be ≈2 seconds.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)repair::Bool=true: recover the segment iftruewindow::Real=10.0: window length (in seconds) in which the signal is scanned and repaired (windows are non-overlapping)r::Int64=sr(obj)÷2: detection segment length; pops are checked within(pop_loc - r):(pop_loc + r)samples
Returns
NeuroAnalyzer.NEURO: output NEURO object: returned ifrepair=truepop_loc::Vector{Vector{Int64}}: location of pops: channel, epoch and sample number in the signall_seg::Vector{Int64}: length of segment before the pop that starts when signal crosses 0r_seg::Vector{Int64}: length of segment after the pop that ends when signal crosses 0
NeuroAnalyzer.remove_pops! — Function
remove_pops!(obj; <keyword arguments>)Detect and repair electrode pops (rapid amplitude change). Signal is recovered within the segments starting and ending at zero-crossing. Only one pop is detected, signal length should be ≈2 seconds.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)repair::Bool=true: recover the segment iftruewindow::Real=20.0: window length (in seconds) in which the signal is scanned and repaired (windows are non-overlapping)r::Int64=sr(obj)÷2: detection segment length; pops are checked withinpop_loc - r:pop_loc + rsamples
Returns
pop_loc::Vector{Vector{Int64}}: location of pops: channel, epoch and sample number in the signall_seg::Vector{Int64}: length of segment before the pop that starts when signal crosses 0r_seg::Vector{Int64}: length of segment after the pop that ends when signal crosses 0
NeuroAnalyzer.remove_powerline — Function
remove_powerline(obj; <keyword arguments>)Remove power line noise and its harmonics from a continuous NEURO object.
For each selected channel, an IIR notch filter is optimised by scanning a range of bandwidth values and choosing the one that minimises spectral variance around the noise frequency. The same process is repeated for any harmonic peaks detected above the fundamental.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; must be continuous (1 epoch)ch::Union{String, Vector{String}, Regex}: channel name(s)pl_frq::Real=obj.header.recording[:line_frequency]: power line frequency in Hz; default is read from the object headermethod::Symbol=:iir: filtering method (currently only:iiris supported)pr::Real=2.0: minimum peak prominence in dB for harmonic detectiond::Real=5.0: minimum distance between detected peaks in Hzq::Real=0.1: bandwidth optimization step size in Hz; must be in[0.01, 5)
Returns
NeuroAnalyzer.NEURO: new object with power line noise removedDataFrame: detected peaks with their optimized notch bandwidths
NeuroAnalyzer.remove_powerline! — Function
remove_powerline!(obj; <keyword arguments>)Remove power line noise in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object; modified in-placech::Union{String, Vector{String}, Regex}: channel name(s)pl_frq::Real=obj.header.recording[:line_frequency]: power line frequency in Hz; default is read from the object headermethod::Symbol=:iir: filtering method (currently only:iiris supported)pr::Real=2.0: minimum peak prominence in dB for harmonic detectiond::Real=5.0: minimum distance between detected peaks in Hzq::Real=0.1: bandwidth optimization step size in Hz; must be in[0.01, 5)
Returns
DataFrame: detected peaks with their optimized notch bandwidths
NeuroAnalyzer.resample — Function
resample(s; <keyword arguments>)Resample to new_sr sampling frequency.
Arguments
s::AbstractVector: signal vectorold_sr::Int64: old sampling ratenew_sr::Int64: new sampling rate
Returns
Vector{Float64}
resample(s; <keyword arguments>)Resamples all channels and time vector t to new_sr sampling frequency for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)old_sr::Int64: old sampling ratenew_sr::Int64: new sampling rate
Returns
Array{Float64, 3}
resample(obj; <keyword arguments>)Resample (up- or down-sample).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectold_sr::Int64: old sampling rate -new_sr::Int64: new sampling rate
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.resample! — Function
resample!(obj; <keyword arguments>)Resample (up- or down-sample).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnew_sr::Int64: new sampling rate
Returns
Nothing
NeuroAnalyzer.scale — Function
scale(obj; <keyword arguments>)Multiply channel(s) by factor.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)factor::Real: signal is multiplied byfactor
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.scale! — Function
scale!(obj; <keyword arguments>)Multiply channel(s) by factor.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)factor::Real: signal is multiplied byfactor
Returns
Nothing
NeuroAnalyzer.sort_epochs — Function
sort_epochs(obj; <keyword arguments>)Sort epochs 2:end of an ERP/ERF object according to a permutation vector. Epoch 1 (the average) is always kept in place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object (must be ERP or ERF)s::Vector{Int64}: permutation vector of lengthnepochs(obj) - 1; values must be in2:nepochs(obj)to avoid overwriting the average epoch
Returns
NeuroAnalyzer.NEURO
NeuroAnalyzer.sort_epochs! — Function
sort_epochs(obj; <keyword arguments>)Sort epochs 2:end in-place of an ERP/ERF object according to a permutation vector. Epoch 1 (the average) is always kept in place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object (must be ERP or ERF)s::Vector{Int64}: permutation vector of lengthnepochs(obj) - 1; values must be in2:nepochs(obj)to avoid overwriting the average epoch
Returns
Nothing
NeuroAnalyzer.standardize — Function
standardize(s)Standardize channels of a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Array{Float64, 3}Vector{ZScoreTransform{Float64, Vector{Float64}}}
standardize(obj; <keyword arguments>)Standardize channels.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
NeuroAnalyzer.NEURO: output NEURO objectVector{ZScoreTransform{Float64, Vector{Float64}}}
NeuroAnalyzer.standardize! — Function
standardize!(obj; <keyword arguments>)Standardize channels.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Vector{ZScoreTransform{Float64, Vector{Float64}}}
NeuroAnalyzer.taper — Function
taper(s; <keyword arguments>)Taper the signal.
Arguments
s::AbstractVector: signal vectort::Vector{<:Real}
Returns
Vector{Float64}
taper(s; <keyword arguments>)Taper a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)t::Vector{<:Real}
Returns
Array{Float64, 3}
taper(obj; <keyword arguments>)Taper the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)t::Vector{<:Real}
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.taper! — Function
taper!(obj; <keyword arguments>)Taper the signal.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)t::Vector{<:Real}
Returns
Nothing
NeuroAnalyzer.tconv — Function
tconv(s; <keyword arguments>)Performs convolution in the time domain.
Arguments
s::AbstractVector: signal vectorkernel::AbstractVector
Returns
Union{Vector{Float64}, Vector{ComplexF64}}: convoluted signal
tconv(s; <keyword arguments>)Perform convolution in the time domain for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)kernel::AbstractVector: convolution kernel
Returns
Union{Array{Float64, 3}, Array{ComplexF64, 3}}: convoluted signal
tconv(obj; <keyword arguments>)Perform convolution in the time domain.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)kernel::AbstractVector: convolution kernel
Returns
Union{NeuroAnalyzer.NEURO, Array{ComplexF64, 3}}: convoluted signal
NeuroAnalyzer.tconv! — Function
tconv!(obj; <keyword arguments>)Perform convolution in the time domain.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)kernel::AbstractVector: convolution kernel
NeuroAnalyzer.upsample — Function
upsample(obj; <keyword arguments>)Upsample.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnew_sr::Int64: new sampling rate
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.upsample! — Function
upsample!(obj; <keyword arguments>)Upsample.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectnew_sr::Int64: new sampling rate
Returns
Nothing
NeuroAnalyzer.wbp — Function
wbp(s; <keyword arguments>)Perform wavelet band-pass filtering.
Arguments
s::AbstractVector: signal vectorpad::Int64=0: number of zeros to appendfrq::Real: filter frequencyfs::Int64: sampling rate in Hz; must be ≥ 1ncyc::Int64=6: Morlet wavelet cycles
Returns
Vector{Float64}
wbp(s; <keyword arguments>)Perform wavelet band-pass filtering for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)pad::Int64=0: pad thesignalwithpadzerosfrq::Real: filter frequencyfs::Int64: sampling rate in Hz; must be ≥ 1ncyc::Int64=6: Morlet wavelet cycles
Returns
Array{Float64, 3}
wbp(obj; <keyword arguments>)Perform wavelet band-pass filtering.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: pad thesignalwithpadzerosfrq::Real: filter frequencyncyc::Int64=6: Morlet wavelet cycles
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.wbp! — Function
wbp!(obj; <keyword arguments>)Perform wavelet band-pass filtering.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: pad thesignalwithpadzerosfrq::Real: filter frequencyncyc::Int64=6: Morlet wavelet cycles
Returns
Nothing
Locs
NeuroAnalyzer.add_locs — Function
add_locs(obj; <keyword arguments>)Add electrode positions from locs.
Electrode locations:
labelschannel labelloc_thetapolar angleloc_radiuspolar radiusloc_xCartesian xloc_yCartesian yloc_zCartesian zloc_radius_sphspherical radiusloc_theta_sphspherical horizontal angleloc_phi_sphspherical azimuth angle
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectlocs::DataFrame: channel location data
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.add_locs! — Function
add_locs!(obj; <keyword arguments>)Load electrode positions from locs and return NeuroAnalyzer.NEURO object attached with channel locations data.
Electrode locations:
labels: channel labelloc_theta: polar angleloc_radius: polar radiusloc_x: Cartesian Xloc_y: Cartesian Yloc_z: Cartesian Zloc_radius_sph: spherical radiusloc_theta_sph: spherical horizontal angleloc_phi_sph: spherical azimuth angle
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectlocs::DataFrame: channel location data
Returns
Nothing
NeuroAnalyzer.cart2pol — Function
cart2pol(x, y)Convert Cartesian coordinates to polar.
Arguments
x::Real: x coordinatey::Real: y coordinate
Returns
Float64: planar radius, the distance from the origin to the pointFloat64: planar horizontal angle, the angle in the xy plane with respect to the x axis, in degrees
NeuroAnalyzer.cart2sph — Function
cart2sph(x, y, z)Convert spherical coordinates to Cartesian.
Arguments
x::Real: x coordinatey::Real: y coordinatez::Real: z coordinate
Returns
Float64: spherical radius, the distance from the origin to the pointFloat64: spherical horizontal angle, the angle in the xy plane with respect to the x axis, in degreesFloat64: spherical azimuth angle, the angle with respect to the z axis (elevation), in degrees
NeuroAnalyzer.edit_locs — Function
edit_locs(obj; <keyword arguments>)Edit electrode.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelx::Union{Real, Nothing}=nothing: Cartesian X spherical coordinatey::Union{Real, Nothing}=nothing: Cartesian Y spherical coordinatez::Union{Real, Nothing}=nothing: Cartesian Z spherical coordinatetheta::Union{Real, Nothing}=nothing: polar angleradius::Union{Real, Nothing}=nothing: polar radiustheta_sph::Union{Real, Nothing}=nothing: spherical horizontal angle, the angle in the xy plane with respect to the x-axis, in degreesradius_sph::Union{Real, Nothing}=nothing: spherical radius, the distance from the origin to the pointphi_sph::Union{Real, Nothing}=nothing: spherical azimuth angle, the angle with respect to the z-axis (elevation), in degreesname::String="": channel nametype::String="": channel type
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.edit_locs! — Function
edit_locs!(obj; <keyword arguments>)Edit electrode.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch1::String: channel name; must resolve to exactly one channelx::Union{Real, Nothing}=nothing: Cartesian X spherical coordinatey::Union{Real, Nothing}=nothing: Cartesian Y spherical coordinatez::Union{Real, Nothing}=nothing: Cartesian Z spherical coordinatetheta::Union{Real, Nothing}=nothing: polar angleradius::Union{Real, Nothing}=nothing: polar radiustheta_sph::Union{Real, Nothing}=nothing: spherical horizontal angle, the angle in the xy plane with respect to the x-axis, in degreesradius_sph::Union{Real, Nothing}=nothing: spherical radius, the distance from the origin to the pointphi_sph::Union{Real, Nothing}=nothing: spherical azimuth angle, the angle with respect to the z-axis (elevation), in degreesname::String="": channel nametype::String="": channel type
Returns
Nothing
NeuroAnalyzer.locs_cart2pol — Function
locs_cart2pol(locs)Convert Cartesian coordinates to polar.
Arguments
locs::DataFrame: channel location data
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_cart2pol! — Function
locs_cart2pol!(locs)Convert Cartesian coordinates to polar.
Arguments
locs::DataFrame: channel location data
Returns
Nothing
NeuroAnalyzer.locs_cart2sph — Function
locs_cart2sph(locs)Convert Cartesian coordinates to spherical.
Arguments
locs::DataFrame: channel location data
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_cart2sph! — Function
locs_cart2sph!(locs)Convert Cartesian coordinates to spherical.
Arguments
locs::DataFrame: channel location data
Returns
Nothing
NeuroAnalyzer.locs_center — Function
locs_center(locs; <keyword arguments>)Center channel locations at (0, 0)
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_center! — Function
locs_center!(locs; <keyword arguments>)Center channel locations at (0, 0).
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_details — Function
locs_details(obj; <keyword arguments>)Return channel location details.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelout::Bool=true: if true, print details
Returns
Named tuple:
label::String: location labeltheta_pl::Float64: polar angleradius_pl::Float64: polar radiusx::Float64: Cartesian x spherical coordinatey::Float64: Cartesian y spherical coordinatez::Float64: Cartesian z spherical coordinatetheta_sph::Float64: spherical horizontal angle, the angle in the xy plane with respect to the x-axis, in degreesradius_sph::Float64: spherical radius, the distance from the origin to the pointphi_sph::Float64: spherical azimuth angle, the angle with respect to the z-axis (elevation), in degrees
NeuroAnalyzer.locs_flipx — Function
locs_flipx(locs; <keyword arguments>)Flip channel locations along x axis.
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_flipx! — Function
locs_flipx!(locs; <keyword arguments>)Flip channel locations along x axis.
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_flipy — Function
locs_flipy(locs; <keyword arguments>)Flip channel locations along y axis.
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_flipy! — Function
locs_flipy!(locs; <keyword arguments>)Flip channel locations along y axis.
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_flipz — Function
locs_flipz(locs; <keyword arguments>)Flip channel locations along z axis.
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_flipz! — Function
locs_flipz!(locs; <keyword arguments>)Flip channel locations along z axis.
Arguments
locs::DataFrame: channel location datapolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_generate — Function
locs_generate(locs)Generate Cartesian and spherical electrode coordinates according to the 10/10 international system.
Labels are matched case-insensitively. Bipolar labels (e.g. Fp1-Fz) are stripped to their first component before matching. Unrecognized labels are reported in a warning but left with their original (zero) coordinates.
Arguments
locs::DataFrame: channel location data
Returns
DataFrame: modified channel location data
locs_generate(obj)Generate spherical coordinates according to the 10/10 system for all channels in a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.locs_generate! — Function
locs_generate!(locs)Generate spherical coordinates according to the 10/10 system, modifying locs in-place.
Arguments
locs::DataFrame: channel location data
Returns
Nothing
locs_generate!(obj)Generate spherical coordinates according to the 10/10 system, modifying locs in-place.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Nothing
NeuroAnalyzer.locs_normalize — Function
locs_normalize(locs; <keyword arguments>)Normalize channel locations to fit the unit sphere.
Arguments
locs::DataFramepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame
NeuroAnalyzer.locs_normalize! — Function
locs_normalize!(locs; <keyword arguments>)Normalize channel locations to fit the unit sphere.
Arguments
locs::DataFramepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_origin — Function
locs_origin(locs; <keyword arguments>)Move locs origin ([0, 0, 0]) along the axes.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectx::Real=0: move origin along X axisy::Real=0: move origin along Y axisz::Real=0: move origin along Z axis
Returns
DataFrame
NeuroAnalyzer.locs_origin! — Function
locs_origin!(locs; <keyword arguments>)Move locs origin ([0, 0, 0]) along the axes.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectx::Real=0: move origin along X axisy::Real=0: move origin along Y axisz::Real=0: move origin along Z axis
Returns
Nothing
locs_origin!(locs; <keyword arguments>)Move locs origin ([0, 0, 0]) along the axes.
Arguments
locs::DataFramex::Real=0: move origin along X axisy::Real=0: move origin along Y axisz::Real=0: move origin along Z axis
Returns
Nothing
NeuroAnalyzer.locs_pol2cart — Function
locs_pol2cart(locs)Convert polar coordinates to Cartesian.
Arguments
locs::DataFrame: channel location data
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_pol2cart! — Function
locs_pol2cart!(locs)Convert polar coordinates to Cartesian.
Arguments
locs::DataFrame: channel location data
Returns
Nothing
NeuroAnalyzer.locs_pol2sph — Function
locs_pol2sph(locs)Convert polar coordinates to spherical.
Arguments
locs::DataFrame: channel location data
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_pol2sph! — Function
locs_pol2sph!(locs)Convert polar coordinates to spherical.
Arguments
locs::DataFrame: channel location data
Returns
Nothing
NeuroAnalyzer.locs_rotx — Function
locs_rotx(locs; <keyword arguments>)Rotate channel locations around the X axis (in the YZ-plane).
Arguments
locs::DataFramea::Real: angle of rotation (in degrees); positive angle rotates anti-clockwisepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame
NeuroAnalyzer.locs_rotx! — Function
locs_rotx!(locs; <keyword arguments>)Rotate channel locations around the X axis (in the YZ-plane).
Arguments
locs::DataFramea::Real: angle of rotation (in degrees); positive angle rotates anti-clockwisepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_roty — Function
locs_roty(locs; <keyword arguments>)Rotate channel locations around the Y axis (in the XZ-plane).
Arguments
locs::DataFramea::Real: angle of rotation (in degrees); positive angle rotates clockwisepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame
NeuroAnalyzer.locs_roty! — Function
locs_roty!(locs; <keyword arguments>)Rotate channel locations around the Y axis (in the XZ-plane).
Arguments
locs::DataFramea::Real: angle of rotation (in degrees); positive angle rotates clockwisepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_rotz — Function
locs_rotz(locs; <keyword arguments>)Rotate channel locations around the Z axis.
Arguments
locs::DataFramea::Real: angle of rotation (in degrees); positive angle rotates anti-clockwisepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame
NeuroAnalyzer.locs_rotz! — Function
locs_rotz!(locs; <keyword arguments>)Rotate channel locations in the xy-plane.
Arguments
locs::DataFramea::Real: angle of rotation (in degrees); positive angle rotates anti-clockwisepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_scale — Function
locs_scale(locs; <keyword arguments>)Scale channel locations.
Arguments
locs::DataFramer::Real: scaling factorpolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
DataFrame
NeuroAnalyzer.locs_scale! — Function
locs_scale!(locs, r, polar, cart, spherical)Scale channel locations.
Arguments
locs::DataFramer::Real: scaling factorpolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.locs_sph2cart — Function
locs_sph2cart(locs)Convert spherical coordinates to Cartesian.
Arguments
locs::DataFrame: channel location data
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_sph2cart! — Function
locs_sph2cart!(locs)Convert spherical coordinates to Cartesian.
Arguments
locs::DataFrame: channel location data
Returns
Nothing
NeuroAnalyzer.locs_sph2pol — Function
locs_sph2pol(locs)Convert spherical coordinates to polar.
Arguments
locs::DataFrame: channel location data
Returns
DataFrame: modified channel location data
NeuroAnalyzer.locs_sph2pol! — Function
locs_sph2pol!(locs)Convert Cartesian coordinates to polar.
Arguments
locs::DataFrame: channel location data
Returns
Nothing
NeuroAnalyzer.locs_swapxy — Function
locs_swapxy(locs; <keyword arguments>)Swap channel locations x and y axes.
Arguments
locs::DataFramepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.locs_swapxy! — Function
locs_swapxy!(locs; <keyword arguments>)Swap channel locations x and y axes.
Arguments
locs::DataFramepolar::Bool=true: modify polar coordinatescart::Bool=true: modify Cartesian coordinatesspherical::Bool=true: modify spherical coordinates
Returns
Nothing
NeuroAnalyzer.pol2cart — Function
pol2cart(radius, theta)Convert polar coordinates to Cartesian.
Arguments
radius::Real: polar radius, the distance from the origin to the point, in degreestheta::Real: polar angle
Returns
Float64: x coordinateFloat64: y coordinate
NeuroAnalyzer.pol2sph — Function
pol2sph(radius, theta)Convert polar coordinates to spherical.
Arguments
radius::Real: polar radius, the distance from the origin to the point, in degreestheta::Real: polar angle
Returns
Float64: spherical radius, the distance from the origin to the pointFloat64: spherical horizontal angle, the angle in the xy plane with respect to the x axis, in degreesFloat64: spherical azimuth angle, the angle with respect to the z axis (elevation), in degrees
NeuroAnalyzer.sph2cart — Function
sph2cart(radius, theta, phi)Convert spherical coordinates to Cartesian.
Arguments
radius::Real: spherical radius, the distance from the origin to the pointtheta::Real: spherical horizontal angle, the angle in the xy plane with respect to the x axis, in degreesphi::Real: spherical azimuth angle, the angle with respect to the z axis (elevation), in degrees
Returns
Float64: x coordinateFloat64: y coordinateFloat64: z coordinate
NeuroAnalyzer.sph2pol — Function
sph2pol(radius, theta, phi)Convert spherical coordinates to polar.
Arguments
radius::Real: spherical radius, the distance from the origin to the pointtheta::Real: spherical horizontal angle, the angle in the xy plane with respect to the x axis, in degreesphi::Real: spherical azimuth angle, the angle with respect to the z axis (elevation), in degrees
Returns
Real: polar radius, the distance from the origin to the pointReal: polar horizontal angle, the angle in the xy plane with respect to the x axis, in degrees
Analyze
Statistics.std — Function
std(obj)Calculate standard deviation of a NEURO object (along epochs).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
s::Matrix{Float64}
NeuroAnalyzer.acor — Function
acor(s; <keyword arguments>)Calculate auto-correlation for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorl::Int64=round(Int64, min(length(s) - 1, 10 * log10(length(s)))): range of lags is-l:ldemean::Bool=true: subtract the mean before computing auto-correlationbiased::Bool=true: calculate biased or unbiased autocovariancemethod::Symbol=:sum: method of calculating auto-correlation::sum:acf = sum(s[1:(end - l)] .* s[(1 + l):end]) ./ var(s):cor:acf = cov(s[1:(end - l)], s[(1 + l):end]) ./ var(s):stat: use StatsBaseautocor(),biasedvalue is ignored
Returns
Vector{Float64}: auto-correlation of length2l + 1
acor(s; <keyword arguments>)Calculate auto-correlation for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)l::Int64=round(Int64, min(size(s, 2) - 1, 10 * log10(size(s, 2)))): range of lags is-l:ldemean::Bool=true: subtract the mean before computing auto-correlationbiased::Bool=true: calculate biased or unbiased autocovariancemethod::Symbol=:sum: method of calculating auto-correlation::sum:acf = sum(s[1:(end - l)] .* s[(1 + l):end]) ./ var(s):cor:acf = cov(s[1:(end - l)], s[(1 + l):end]) ./ var(s):stat: use StatsBaseautocor(),biasedvalue is ignored
Returns
Array{Float64, 3}: auto-correlations, shape (channels, 2l+1, epochs)
acor(obj; <keyword arguments>)Calculate auto-correlation for a NEURO object.
For ERP return trial-averaged auto-correlation.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)l::Int64=round(Int64, min(size(obj.data, 2) - 1, 10 * log10(size(obj.data, 2)))): range of lags is-l:ldemean::Bool=true: subtract the mean before computing auto-correlationbiased::Bool=true: calculate biased or unbiased autocovariancemethod::Symbol=:sum: method of calculating auto-correlation::sum:acf = sum(s[1:(end - l)] .* s[(1 + l):end]) ./ var(s):cor:acf = cov(s[1:(end - l)], s[(1 + l):end]) ./ var(s):stat: use StatsBaseautocor(),biasedvalue is ignored
Returns
Named tuple:
autocor_m::Array{Float64, 3}: auto-correlations, shape (channels, 2l+1, epochs)l::Vector{Float64}: lags in seconds
NeuroAnalyzer.acov — Function
acov(s; <keyword arguments>)Calculate auto-covariance for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorl::Int64=round(Int64, min(length(s) - 1, 10 * log10(length(s)))): range of lags is-l:ldemean::Bool=true: subtract the mean before computing auto-covariancebiased::Bool=true: calculate biased or unbiased auto-covariancemethod::Symbol=:sum: method of calculating auto-covariance::sum:acf = sum(s[1:(end - l)] .* s[(1 + l):end]):cov:acf = cov(s[1:(end - l)], s[(1 + l):end]):stat: use StatsBaseautocov(),biasedvalue is ignored
Returns
Vector{Float64}: auto-covariance of length2l + 1
acov(s; <keyword arguments>)Calculate auto-covariance for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)l::Int64=round(Int64, min(size(s, 2) - 1, 10 * log10(size(s, 2)))): range of lags is-l:ldemean::Bool=true: subtract the mean before computing auto-covariancebiased::Bool=true: calculate biased or unbiased auto-covariancemethod::Symbol=:sum: method of calculating auto-covariance::sum:acf = sum(s[1:(end - l)] .* s[1+l:end]):cov:acf = cov(s[1:(end - l)], s[1+l:end]):stat: use StatsBaseautocor(),biasedvalue is ignored
Returns
Array{Float64, 3}: auto-covariances, shape (channels, 2l+1, epochs)
acov(obj; <keyword arguments>)Calculate auto-covariance for a NEURO object.
For ERP return trial-averaged auto-covariance.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)l::Int64=round(Int64, min(size(obj.data, 2) - 1, 10 * log10(size(obj.data, 2)))): range of lags is-l:ldemean::Bool=true: subtract the mean before computing auto-covariancebiased::Bool=true: calculate biased or unbiased auto-covariancemethod::Symbol=:sum: method of calculating auto-covariance::sum:acf = sum(s[1:(end - l)] .* s[(1 + l):end]):cov:acf = cov(s[1:(end - l)], s[(1 + l):end]):stat: use StatsBaseautocor(),biasedvalue is ignored
Returns
Named tuple:
autocov::Array{Float64, 3}: auto-covariances of, shape (channels, 2l+1, epochs)lags::Vector{Float64}: lags in seconds
NeuroAnalyzer.aecor — Function
aecor(s1, s2)Calculate Amplitude Envelope Correlation (AEC) for 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Float64: AEC value
References
- Bruns, A., Eckhorn, R., Jokeit, H., & Ebner, A. (2000). Amplitude envelope correlation detects coupling among incoherent brain signals. Neuroreport, 11(7), 1509-1514.
aecor(obj1, obj2; <keyword arguments>)Calculate Amplitude Envelope Correlation (AEC) for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO object- `ch1::Union{String, Vector{String}, Regex}: channel name(s)
- `ch2::Union{String, Vector{String}, Regex}: channel name(s)
ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Matrix{Float64}: AEC value, shape (channels, epochs)
aecor(obj; <keyword arguments>)Calculate Amplitude Envelope Correlation (AEC) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: AEC value, shape(channels, channels, epochs)
NeuroAnalyzer.amp — Function
amp(s)Computes amplitude descriptors for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Named tuple:
peak_amp::Float64: peak amplitude (max(|s|))rms_amp::Float64: RMS amplitude (√mean(s²))p2p_amp::Float64: peak-to-peak amplitude (max(s) - min(s))semi_p2p_amp::Float64: half of the peak-to-peak amplitude (p2p/2)ms_amp::Float64: mean square amplitude (mean(s²))te_signal::Float64: total signal energy (Σ s²)
amp(s)Computes amplitude descriptors for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Named tuple:
peak_amp::Matrix{Float64}: peak amplitude (max(|s|)), shape (channels, epochs)rms_amp::Matrix{Float64}: RMS amplitude (peak_amp / √2; exact only for a pure sinusoid), shape (channels, epochs)p2p_amp::Matrix{Float64}: peak-to-peak amplitude (max(s) - min(s)), shape (channels, epochs)semi_p2p_amp::Matrix{Float64}: half of the peak-to-peak amplitude, shape (channels, epochs)ms_amp::Matrix{Float64}: mean square amplitude (mean(s²)), shape (channels, epochs)te_signal::Matrix{Float64}: total signal energy (Σ s²), shape (channels, epochs)
amp(obj; <keyword arguments>)Computes amplitude descriptors for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Named tuple:
peak_amp::Matrix{Float64}: peak amplitude (max(|s|)), shape (channels, epochs)rms_amp::Matrix{Float64}: RMS amplitude (peak_amp / √2; exact only for a pure sinusoid), shape (channels, epochs)p2p_amp::Matrix{Float64}: peak-to-peak amplitude (max(s) - min(s)), shape (channels, epochs)semi_p2p_amp::Matrix{Float64}: half of the peak-to-peak amplitude, shape (channels, epochs)ms_amp::Matrix{Float64}: mean square amplitude (mean(s²)), shape (channels, epochs)te_signal::Matrix{Float64}: total signal energy (Σ s²), shape (channels, epochs)
NeuroAnalyzer.amp_at — Function
amp_at(obj; <keyword arguments>)Calculate amplitude at a given time point.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectt::Real: time in seconds
Returns
Matrix{Float64}: amplitude for each channel per epoch, shape (channels, epochs) or(channels, 1)for continuous objects
NeuroAnalyzer.ampdiff — Function
ampdiff(s)Calculate amplitude difference to reference mean: amplitude difference between each channel and mean amplitude of reference channels.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Array{Float64, 3}: amplitude difference, shape (channels, samples, epochs)
ampdiff(obj; <keyword arguments>)Calculate amplitude difference to reference mean: amplitude difference between each channel and mean amplitude of reference channels.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: reference channel name(s)
Returns
Array{Float64, 3}: amplitude difference, shape (channels, samples, epochs)
NeuroAnalyzer.asy_idx — Function
asy_idx(obj; <keyword arguments>)Computes the log-ratio and normalized difference of mean band power between two sets of channels (typically left vs right hemisphere):
asi = log(mean_power(ch1)) - log(mean_power(ch2)): positive when ch1 has more power than ch2nasi = (mean_power(ch1) - mean_power(ch2)) / (mean_power(ch1) + mean_power(ch2)): bounded on (-1, 1), analogous to a contrast ratio
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1, e.g. left frontal channelsch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2, e.g. right frontal channelsflim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
asi::Float64: log band asymmetrynasi::Float64: normalized band asymmetry
NeuroAnalyzer.avgamp_at — Function
avgamp_at(obj; <keyword arguments>)Calculate mean amplitude over a time segment.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectt::Tuple{Real, Real}: time segment in seconds
Returns
Matrix{Float64}: mean amplitude for each channel per epoch, shape (channels, epochs) or(channels, 1)for continuous objects
NeuroAnalyzer.axc2frq — Function
axc2frq(c, l)Finds peaks in an auto-/cross-correlation or covariance vector, converts their lag positions to inter-peak intervals, and returns the corresponding frequencies (1 / interval).
Arguments
c::AbstractVector: auto-/cross- correlation/covariance valuesl::AbstractVector: lags corresponding to each value inc
Returns
Vector{Float64}: frequencies (Hz) dominating in the auto-/cross-correlation/covariance, sorted in ascending order
NeuroAnalyzer.band_mpower — Function
band_mpower(s; <keyword arguments>)Calculate mean and peak band power for a 1-D signal vector.
For a given frequency band, computes four descriptors:
mbp– mean power across the band- `maxfrq – frequency of the peak (maximum) power bin within the band
maxbp– power at that peak frequency binmaxba– amplitude at that peak frequency bin (√maxbp)
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
mbp::Float64: mean band powermaxfrq::Float64: frequency of maximum band powermaxbp::Float64: power at maximum band frequencymaxba::Float64: amplitude at maximum band frequency
band_mpower(s; <keyword arguments>)Calculate mean and peak band power for a 3-D signal array.
For a given frequency band, computes four descriptors:
mbp– mean power across the band- `maxfrq – frequency of the peak (maximum) power bin within the band
maxbp– power at that peak frequency binmaxba– amplitude at that peak frequency bin (√maxbp)
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
mbp::Matrix{Float64}: mean band power, shape (channels, epochs)maxfrq::Matrix{Float64}: frequency of maximum band power, shape (channels, epochs)maxbp::Matrix{Float64}: power at maximum band frequency, shape (channels, epochs)maxba::Matrix{Float64}: amplitude at maximum band frequency, shape (channels, epochs)
band_mpower(obj; <keyword arguments>)Calculate mean and peak band power for a NEURO object.
For a given frequency band, computes four descriptors:
mbp– mean power across the band- `maxfrq – frequency of the peak (maximum) power bin within the band
maxbp– power at that peak frequency binmaxba– amplitude at that peak frequency bin (√maxbp)
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
mbp::Matrix{Float64}: mean band power, shape (channels, epochs)maxfrq::Matrix{Float64}: frequency of maximum band power, shape (channels, epochs)maxbp::Matrix{Float64}: power at maximum band frequency, shape (channels, epochs)maxba::Matrix{Float64}: amplitude at maximum band frequency, shape (channels, epochs)
NeuroAnalyzer.band_power — Function
band_power(s; <keyword arguments>)Calculate the absolute power in a frequency band by:
- Estimating the PSD with the chosen method (Welch, FFT, MT, STFT, MW, GH)
- Locating the bin indices that bracket the requested band
- Integrating the PSD over that band using Simpson's rule
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Float64: band power
band_power(s; <keyword arguments>)Calculate absolute band power between two frequencies for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: band power, shape (channels, epochs)
band_power(obj; <keyword arguments>)Calculate absolute band power between two frequencies for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: band power, shape (channels, epochs)
NeuroAnalyzer.channel_stats — Function
channel_stats(obj)Calculate channels statistics per epoch for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Named tuple:
c_mean::Matrix{Float64}: meanc_median::Matrix{Float64}: medianc_std::Matrix{Float64}: standard deviationc_var::Matrix{Float64}: variancec_kurt::Matrix{Float64}: kurtosisc_skew::Matrix{Float64}: skewnessc_mean_diff::Matrix{Float64}: mean diff valuec_median_diff::Matrix{Float64}: median diff valuec_max_dif::Matrix{Float64}: max differencec_dev_mean::Matrix{Float64}: deviation from channel mean
NeuroAnalyzer.coherence — Function
coherence(s1, s2; <keyword arguments>)Calculate coherence, imaginary part of coherence and magnitude-squared coherence (MSC) for two 1-D signal vectors.
For two signals s1, s2 and their cross-power spectra:
- coh = S12 / √(S11 · S22) (complex coherence)
- imcoh = Im(coh) (imaginary part - insensitive to zero-lag volume conduction)
- msc = |coh|² (magnitude-squared coherence ∈ [0,1])
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectormethod::Symbol=:mt: method used to calculate CPSD::mt: multi-tapered cross-power spectra:fft: fast Fourier transformation:stft: short-time Fourier transformation
fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(0, fs / 2): frequency limitsdemean::Bool=false: if true, the channel-wise mean will be subtracted from the input signals before the cross spectral powers are computednt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)wstep::Int64=round(Int64, wlen * 0.90): step between window startsw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
coh::Vector{ComplexF64}: coherenceimcoh::Vector{Float64}: imaginary part of coherencemsc::Vector{Float64}: magnitude-squared coherencef::Vector{Float64}: frequencies
coherence(s1, s2; <keyword arguments>)Calculate coherence, imaginary part of coherence and magnitude-squared coherence (MSC) for two 3-D signal arrays.
For two signals s1, s2 and their cross-power spectra:
- coh = S12 / √(S11 · S22) (complex coherence)
- imcoh = Im(coh) (imaginary part - insensitive to zero-lag volume conduction)
- msc = |coh|² (magnitude-squared coherence ∈ [0,1])
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)method::Symbol=:mt: method used to calculate CPSD::mt: multi-tapered cross-power spectra:fft: fast Fourier transformation:stft: short-time Fourier transformation
fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(0, fs / 2): frequency limitsdemean::Bool=false: if true, the channel-wise mean will be subtracted from the input signals before the cross spectral powers are computednt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)wstep::Int64=round(Int64, wlen * 0.90): step between window startsw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
coh::Array{ComplexF64, 3}: coherence, shape(channels, frequencies, epochs)imcoh::Array{Float64, 3}: imaginary part of coherence, shape(channels, frequencies, epochs)msc::Array{Float64, 3}: magnitude-squared coherence, shape(channels, frequencies, epochs)f::Vector{Float64}: frequencies in Hz
coherence(obj1, obj2; <keyword arguments>)Calculate coherence, imaginary part of coherence and magnitude-squared coherence (MSC) for two NEURO objects.
For two signals s1, s2 and their cross-power spectra:
- coh = S12 / √(S11 · S22) (complex coherence)
- imcoh = Im(coh) (imaginary part - insensitive to zero-lag volume conduction)
- msc = |coh|² (magnitude-squared coherence ∈ [0,1])
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1))epoch number(s)ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2))epoch number(s)method::Symbol=:mt: method used to calculate CPSD::mt: multi-tapered cross-power spectra:fft: fast Fourier transformation:stft: short-time Fourier transformation
fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(0, fs / 2): frequency limitsdemean::Bool=false: if true, the channel-wise mean will be subtracted from the input signals before the cross spectral powers are computednt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)wstep::Int64=round(Int64, wlen * 0.90): step between window startsw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
coh::Array{ComplexF64, 3}: coherence, shape(channels, frequencies, epochs)imcoh::Array{Float64, 3}: imaginary part of coherence, shape(channels, frequencies, epochs)msc::Array{Float64, 3}: magnitude-squared coherence, shape(channels, frequencies, epochs)f::Vector{Float64}: frequencies
NeuroAnalyzer.corm — Function
corm(s1, s2; <keyword arguments>)Computes the channel × channel Pearson correlation matrix for two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectornorm::Bool = false: normalize correlation matrix
Returns
Matrix{Float64}: 2×2 correlation matrix
corm(s; <keyword arguments>)Calculate corelation matrix of channels × time points matrix.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)norm::Bool=false: normalize correlation matrix
Returns
Matrix{Float64}: correlation matrix, shape (channels × channels)
corm(s; <keyword arguments>)Calculate correlation matrix for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)norm::Bool=false: normalize correlation matrix
Returns
Array{Float64, 3}: correlation matrix for each epoch, shape (channels, channels, epochs)
corm(obj; <keyword arguments>)Calculate correlation matrix for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object- `ch::Union{String, Vector{String}, Regex}: channel name(s)
norm::Bool=true: normalize matrix
Returns
Array{Float64, 3}: correlation matrix for each epoch, shape (channels, channels, epochs)
NeuroAnalyzer.corr — Function
corr(obj1, obj2; <keyword arguments>)Compute the Pearson correlation between paired channels across two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO object- `ch1::Union{String, Vector{String}, Regex}: channel name(s)
- `ch2::Union{String, Vector{String}, Regex}: channel name(s)
ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Matrix{Float64}: correlation coefficients, shape (channels, epochs)
corr(obj; <keyword arguments>)Compute the Pearson correlation between all channel pairs within a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: correlation coefficient, shape(channels, channels, epochs)
NeuroAnalyzer.cosim — Function
cosim(s1, s2)Measures the cosine of the angle between two 1-D signal vectors.
CS = (s1 · s2) / (‖s1‖ · ‖s2‖) ∈ [-1, 1]
- CS = 1 → identical direction (perfectly similar)
- CS = 0 → orthogonal (no similarity)
- CS = -1 → opposite direction
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Float64: cosine similarity value ∈ [-1, 1]
cosim(obj1, obj2; <keyword arguments>)Measures the cosine of the angle between paired channels across two NEURO objects.
CS = (s1 · s2) / (‖s1‖ · ‖s2‖) ∈ [-1, 1]
- CS = 1 → identical direction (perfectly similar)
- CS = 0 → orthogonal (no similarity)
- CS = -1 → opposite direction
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO object- `ch1::Union{String, Vector{String}, Regex}: channel name(s)
- `ch2::Union{String, Vector{String}, Regex}: channel name(s)
ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Matrix{Float64}: cosine similarity values, shape (channels, epochs)
cosim(obj; <keyword arguments>)Measures the cosine of the angle between channels of a NEURO object.
CS = (s1 · s2) / (‖s1‖ · ‖s2‖) ∈ [-1, 1]
- CS = 1 → identical direction (perfectly similar)
- CS = 0 → orthogonal (no similarity)
- CS = -1 → opposite direction
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: cosine similarity values, shape (channels, channels, epochs)
NeuroAnalyzer.covm — Function
covm(s; <keyword arguments>)A single channel has no cross-channel covariance for a 1-D signal vector.
The 1×1 result is simply the signal's own variance.
Arguments
s::AbstractVector: signal vectornorm::Bool=false: iftrue, normalize covariance matrix matrix
Returns
Matrix{Float64}: 1×1 covariance matrix ([var(s)])
covm(s1, s2; <keyword arguments>)Calculate covariance matrix of two signals.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectornorm::Bool=false: iftrue, normalize covariance matrix
Returns
Matrix{Float64}: 2×2 covariance matrix
covm(s; <keyword arguments>)Calculate covariance matrix of a matrix.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)norm::Bool=false: iftrue, normalize covariance matrix
Returns
Matrix{Float64}: covariance matrix, shape(channels, channels)
covm(s; <keyword arguments>)Calculate covariance matrix for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)norm::Bool=false: iftrue, normalize covariance matrix
Returns
Array{Float64, 3}: covariance matrix, shape(channels, channels, epochs)
covm(obj; <keyword arguments>)Calculate covariance matrix between all channel pairs within a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object- `ch::Union{String, Vector{String}, Regex}: channel name(s)
norm::Bool=false: iftrue, normalize covariance matrix
Returns
Array{Float64, 3}: covariance matrix, shape(channels, channels, epochs)
NeuroAnalyzer.cph — Function
cph(s1, s2; <keyword arguments>)Computes the instantaneous phase of the cross-power spectrum between two 1-D signal vectors using multi-taper estimation.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Named tuple:
ph::Vector{Float64}: cross-power spectrum phase in radiansf::Vector{Float64}: cross-power spectrum frequencies
cph(s; <keyword arguments>)Computes the instantaneous phase of the cross-power spectrum between all channel pairs of a 3-D signal array using multi-taper estimation.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Named tuple:
ph::Array{Float64, 4}: cross-power spectrum phase (in radians), shape (channels, channels, frequencies, epochs)f::Vector{Float64}: cross-power spectrum frequencies
cph(s1, s2; <keyword arguments>)Calculate cross-phases between paired channels of two 3-D signal arrays.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Named tuple:
ph::Array{Float64, 3}: cross-power spectrum phase in radians, shape(channels, frequencies, epochs)f::Vector{Float64}: cross-power spectrum frequencies
cph(obj; <keyword arguments>)Calculate cross-phases between all channel pairs of a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Named tuple:
ph::Array{Float64, 4}: cross-power spectrum phase in radians, shape(channels, channels, frequencies, epochs)f::Vector{Float64}: cross-power spectrum frequencies
cph(obj1, obj2; <keyword arguments>)Calculate cross-phases between paired channels of two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO object- `ch1::Union{String, Vector{String}, Regex}: channel name(s)
- `ch2::Union{String, Vector{String}, Regex}: channel name(s)
ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
ph::Array{Float64, 3}: cross-power spectrum phase in radians, shape(channels, frequencies, epochs)f::Vector{Float64}: cross-power spectrum frequencies
NeuroAnalyzer.cpsd — Function
cpsd(s1, s2; <keyword arguments>)Calculate the complex cross power spectral density (CPSD) between two 1-D signal vectors via one of three estimators:
:mt– multi-taper (DSP.mtcrosspower_spectra):fft– single-window FFT:stft– segmented FFT averaged over overlapping windows
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectormethod::Symbol=:mt: method used to calculate CPSD::mt: multi-tapered cross-power spectra:fft: fast Fourier transformation:stft: short-time Fourier transformation
fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(0, fs / 2): frequency limitsdemean::Bool=false: if true, the channel-wise mean will be subtracted from the input signals before the cross spectral powers are computednt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)wstep::Int64=round(Int64, wlen * 0.90): step between window startsw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
pxy::Vector{ComplexF64}: cross-power spectrumf::Vector{Float64}: frequencies
cpsd(s1, s2; <keyword arguments>)Calculate the complex cross power spectral density (CPSD) between two 3-D signal arrays via one of three estimators:
:mt– multi-taper (DSP.mtcrosspower_spectra):fft– single-window FFT:stft– segmented FFT averaged over overlapping windows
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)method::Symbol=:mt: method used to calculate CPSD::mt: multi-tapered cross-power spectra:fft: fast Fourier transformation:stft: short-time Fourier transformation
fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(0, fs / 2): frequency limitsdemean::Bool=false: if true, the channel-wise mean will be subtracted from the input signals before the cross spectral powers are computednt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)wstep::Int64=round(Int64, wlen * 0.90): step between window startsw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
pxy::Array{ComplexF64, 3}: cross-power spectrum, shape(channels, frequencies, epochs)f::Vector{Float64}: frequencies
cpsd(obj1, obj2; <keyword arguments>)Calculate the complex cross power spectral density (CPSD) between paired channels of two NEURO objects via one of three estimators:
:mt– multi-taper (DSP.mtcrosspower_spectra):fft– single-window FFT:stft– segmented FFT averaged over overlapping windows
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2method::Symbol=:mt: method used to calculate CPSD::mt: multi-tapered cross-power spectra:fft: fast Fourier transformation:stft: short-time Fourier transformation
flim::Tuple{Real, Real}=(0, sr(obj1) / 2): frequency limitsdemean::Bool=false: if true, the channel-wise mean will be subtracted from the input signals before the cross spectral powers are computednt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj1): window length in samples, default is 1 secondwstep::Int64=round(Int64, wlen * 0.90): step between window startsw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
pxy::Array{ComplexF64, 3}: cross-power spectrum, shape(channels, frequencies, epochs)f::Vector{Float64}: frequencies
NeuroAnalyzer.cwtspectrogram — Function
cwtspectrogram(s; <keyword arguments>)Calculate scaleogram using Continuous Wavelet Transformation (CWT).
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available wavelets
Returns
Named tuple:
m::Matrix{Float64}: magnitudesf::Vector{Float64}: frequenciest::Vector{Float64}: time points
cwtspectrogram(s; <keyword arguments>)Calculate scaleogram using Continuous Wavelet Transformation (CWT) for each channel of a matrix.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)fs::Int64: sampling rate in Hz; must be ≥ 1wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available wavelets
Returns
Named tuple:
m::Array{Float64, 3}: magnitudes, shape (samples, frequencies, channels)f::Vector{Float64}: frequenciest::Vector{Float64}: time points
NeuroAnalyzer.dirinrg — Function
dirinrg(s)Calculate Dirichlet energy for a 1-D signal vector.
It measures the "roughness" of a discrete signal by summing the squared differences between consecutive samples: E(s) = Σ (s[i+1] - s[i])² = ‖diff(s)‖²
A smooth, slowly-varying signal has low Dirichlet energy; a noisy or rapidly oscillating signal has high energy.
Arguments
s::AbstractVector: signal vector
Returns
Float64: Dirichlet energy
dirinrg(s)Calculate Dirichlet energy. It measures the "roughness" of a discrete signal by summing the squared differences between consecutive samples: E(s) = Σ (s[i+1] - s[i])² = ‖diff(s)‖²
A smooth, slowly-varying signal has low Dirichlet energy; a noisy or rapidly oscillating signal has high energy.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Matrix{Float64}: Dirichlet energy, shape (channels, epochs)
dirinrg(obj; <keyword arguments>)Calculate Dirichlet energy for a NEURO object.
It measures the "roughness" of a discrete signal by summing the squared differences between consecutive samples: E(s) = Σ (s[i+1] - s[i])² = ‖diff(s)‖²
A smooth, slowly-varying signal has low Dirichlet energy; a noisy or rapidly oscillating signal has high energy.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Matrix{Float64}: Dirichlet energy, shape (channels, epochs)
NeuroAnalyzer.diss — Function
diss(s1, s2)Calculate Global Dissimilarity and Spatial Correlation. Measure how different two GFP-normalised scalp topographies are at each time point:
- gd[t] = √( Σch (g1[ch,t] - g2[ch,t])² / nch ) ∈ [0, 2]
- sc[t] = 1 - gd[t]² / 2 = 0.5 · (2 - gd[t]²) ∈ [-1, 1]
DISS = 0 (gd = 0) means identical topographies; DISS = 2 means opposite.
Spatial correlation is the linear rescaling of DISS onto [-1, 1].
Arguments
s1::AbstractMatrix: signal matrix (channels, samples)s2::AbstractMatrix: signal matrix (channels, samples)
Returns
Named tuple:
gd::Vector{Float64}: global dissimilarity ∈ [0, 2], one value per time pointsc::Vector{Float64}: spatial correlation ∈ [-1, 1], one value per time point
diss(obj1, obj2; <keyword arguments>)Calculate DISS (global dissimilarity) and spatial correlation for two NEURO objects.
Operates on ERP/ERF objects only and uses epoch 1 (the trial-averaged waveform).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object: must be an ERP or ERF objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2
Returns
Named tuple:
gd::Vector{Float64}: global dissimilarity ∈ [0, 2], one value per time pointsc::Vector{Float64}: spatial correlation ∈ [-1, 1], one value per time point
NeuroAnalyzer.dpli — Function
dpli(s1, s2)Calculate Directed Phase Lag Index (dPLI) for two 1-D signal vectors.
dPLI quantifies the fraction of time that s1 leads s2 in phase: dPLI = ( {t : 0 < phd[t] < π} + 0.5 · {t : phd[t] = 0} ) / N
where phd = s1phase − s2phase ∈ (−π, π].
- dPLI > 0.5 → s1 consistently leads s2
- dPLI < 0.5 → s2 consistently leads s1
- dPLI ≈ 0.5 → no consistent phase relationship
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Named tuple:
pv::Float64: dPLI value ∈ [0, 1]sd::Vector{Float64}: signal difference (s2 - s1)phd::Vector{Float64}: instantaneous phase difference (s1phase - s2phase) ∈ (−π, π]s1ph::Vector{Float64}: instantaneous phase of s1s2ph::Vector{Float64}: instantaneous phase of s2
References
- Stam, C. J., & van Straaten, E. C. W. (2012). Go with the flow: Use of a directed phase lag index (dPLI) to characterize patterns of phase relations in a large-scale model of brain dynamics. NeuroImage, 62(3), 1415–1428.
dpli(obj1, obj2; <keyword arguments>)Calculate Directed Phase Lag Index (dPLI) for two NEURO objects.
dPLI quantifies the fraction of time that s1 leads s2 in phase: dPLI = ( {t : 0 < phd[t] < π} + 0.5 · {t : phd[t] = 0} ) / N
where phd = s1phase − s2phase ∈ (−π, π].
- dPLI > 0.5 → s1 consistently leads s2
- dPLI < 0.5 → s2 consistently leads s1
- dPLI ≈ 0.5 → no consistent phase relationship
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
pv::Matrix{Float64}: dPLI values, shape (channels, epochs)sd::Array{Float64, 3}: signal difference, shape (channels, samples, epochs)phd::Array{Float64, 3}: phase difference, shape (channels, samples, epochs)s1ph::Array{Float64, 3}: signal 1 instantaneous phase, shape (channels, samples, epochs)s2ph::Array{Float64, 3}: signal 2 instantaneous phase, shape (channels, samples, epochs)
References
- Stam, C. J., & van Straaten, E. C. W. (2012). Go with the flow: Use of a directed phase lag index (dPLI) to characterize patterns of phase relations in a large-scale model of brain dynamics. NeuroImage, 62(3), 1415–1428.
dpli(obj; <keyword arguments>)Calculate Directed Phase Lag Index (dPLI) for a NEURO object.
dPLI quantifies the fraction of time that s1 leads s2 in phase: dPLI = ( {t : 0 < phd[t] < π} + 0.5 · {t : phd[t] = 0} ) / N
where phd = s1phase − s2phase ∈ (−π, π].
- dPLI > 0.5 → s1 consistently leads s2
- dPLI < 0.5 → s2 consistently leads s1
- dPLI ≈ 0.5 → no consistent phase relationship
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: dPLI values, shape (channels, channels, epochs)
References
- Stam, C. J., & van Straaten, E. C. W. (2012). Go with the flow: Use of a directed phase lag index (dPLI) to characterize patterns of phase relations in a large-scale model of brain dynamics. NeuroImage, 62(3), 1415–1428.
NeuroAnalyzer.emd — Function
emd(s, x; <keyword arguments>)Perform Empirical Mode Decomposition (EMD) for a 1-D signal vector.
Decomposes a signal into Intrinsic Mode Functions (IMFs) by iteratively "sieving" out oscillatory components from fastest to slowest.
Each sieving iteration:
- Replace any exact zeros with eps() to avoid spline interpolation issues.
- Compute upper/lower cubic-spline envelopes of the local extrema.
- Subtract the mean envelope to get a candidate IMF.
- Check the IMF stopping criterion (number of extrema ≈ number of roots).
- If criterion met: accept the IMF, subtract it, reset the sieve counter.
- If stopping condition SD < epsilon: append the residue and exit.
Returns a matrix whose rows are IMFs (1..end-1) and the final residue (end).
Arguments
s::AbstractVector: signal vectorx::AbstractVector: x-axis points (e.g. time points)epsilon::Real=0.3: decomposition stops when the normalised sum of squared differences (SD criterion) drops belowepsilon
Returns
Matrix{Float64}: intrinsic mode functions (IMF) by rows, with the residue as the last row; returns an empty0×0matrix if no IMFs found
emd(obj; <keyword arguments>)Perform Empirical Mode Decomposition (EMD) for a NEURO object.
Decomposes a signal into Intrinsic Mode Functions (IMFs) by iteratively "sieving" out oscillatory components from fastest to slowest.
Each sieving iteration:
- Replace any exact zeros with eps() to avoid spline interpolation issues.
- Compute upper/lower cubic-spline envelopes of the local extrema.
- Subtract the mean envelope to get a candidate IMF.
- Check the IMF stopping criterion (number of extrema ≈ number of roots).
- If criterion met: accept the IMF, subtract it, reset the sieve counter.
- If stopping condition SD < epsilon: append the residue and exit.
Returns a matrix whose rows are IMFs (1..end-1) and the final residue (end).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelep::Int64: epoch indexepsilon::Real=0.3: decomposition stops when the normalised sum of squared differences (SD criterion) drops belowepsilon
Returns
Matrix{Float64}: intrinsic mode functions (IMF) by rows, with the residue as the last row
NeuroAnalyzer.entropy — Function
entropy(s)Calculate signal entropy descriptors for a 1-D signal vector:
- histogram-based entropy in bits (Freedman-Diaconis binning)
- Shannon entropy (Wavelets.coefentropy)
- log energy entropy (Wavelets.coefentropy)
- sample entropy (ComplexityMeasures)
- normaliDsed sample entropy (ComplexityMeasures)
- differential entropy
Arguments
s::AbstractVector: signal vector
Returns
Named tuple:
ent::Float64: entropy in bitsshent::Float64: Shanon entropyleent::Float64: log energy entropysent::Float64: sample entropynsent::Float64: normalized sample entropydsent::Float64: differential entropy
Note
Histogram entropy uses Freedman-Diaconis binning: p = n / sum(n), ent = −Σ p·log₂(p). Shannon and log energy entropy use Wavelets.coefentropy(). Sample entropy approaches zero for completely regular signals and increases with irregularity.
entropy(s)Calculate signal entropy descriptors for a 3-D signal array:
- histogram-based entropy in bits (Freedman-Diaconis binning)
- Shannon entropy (Wavelets.coefentropy)
- log energy entropy (Wavelets.coefentropy)
- sample entropy (ComplexityMeasures)
- normalised sample entropy (ComplexityMeasures)
- differential entropy
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Named tuple:
ent::Matrix{Float64}: entropy in bits, shape (channels, epochs)shent::Matrix{Float64}: Shanon entropy, shape (channels, epochs)leent::Matrix{Float64}: log energy entropy, shape (channels, epochs)sent::Matrix{Float64}: sample entropy, shape (channels, epochs)nsent::Matrix{Float64}: normalized sample entropy, shape (channels, epochs)dent::Matrix{Float64}: differential entropy, shape (channels, epochs)
entropy(obj; <keyword arguments>)Calculate signal entropy descriptors:
- histogram-based entropy in bits (Freedman-Diaconis binning)
- Shannon entropy (Wavelets.coefentropy)
- log energy entropy (Wavelets.coefentropy)
- sample entropy (ComplexityMeasures)
- normalized sample entropy (ComplexityMeasures)
- differential entropy
Returns
Named tuple:
ent::Matrix{Float64}: entropy in bits, shape (channels, epochs)shent::Matrix{Float64}: Shanon entropy, shape (channels, epochs)leent::Matrix{Float64}: log energy entropy, shape (channels, epochs)sent::Matrix{Float64}: sample entropy, shape (channels, epochs)nsent::Matrix{Float64}: normalized sample entropy, shape (channels, epochs)dent::Matrix{Float64}: differential entropy, shape (channels, epochs)
NeuroAnalyzer.env_cor — Function
env_cor(env1, env2)Calculate envelope correlation.
Arguments
env1::Array{Float64, 3}env2::Array{Float64, 3}
Returns
Named tuple:
ec::Vector{Float64}: envelope correlation coefficientp::Vector{Float64}: p-value
NeuroAnalyzer.env_lo — Function
env_lo(s, x; <keyword arguments>)Calculate lower cubic-spline envelope from local minima for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorx::AbstractVector: x-axis points (e.g. time points)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Vector{Float64}: lower envelope (zeros if fewer than 2 troughs found)
NeuroAnalyzer.env_up — Function
env_up(s, x; <keyword arguments>)Calculate upper cubic-spline envelope from local maxima for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorx::AbstractVector: x-axis points (e.g. time points)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Vector{Float64}: upper envelope (zeros if fewer than 2 peaks found)
NeuroAnalyzer.epoch_stats — Function
epoch_stats(obj)Calculate epochs statistics for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Named tuple:
e_mean::Vector{Float64}: meane_median::Vector{Float64}: mediane_std::Vector{Float64}: standard deviatione_var::Vector{Float64}: variancee_kurt::Vector{Float64}: kurtosise_skew::Vector{Float64}: skewnesse_mean_diff::Vector{Float64}: mean diff valuee_median_diff::Vector{Float64}: median diff valuee_max_dif::Vector{Float64}: max differencee_dev_mean::Vector{Float64}: deviation from channel mean
NeuroAnalyzer.erop — Function
erop(obj; <keyword arguments>)Calculate ERO (Event-Related Oscillations) power spectrum.
Wraps psd() to compute an ERO power summary for a single channel:
ERP/ERF objects (two-column output):
- column 1 – power spectrum of the trial-averaged ERP/ERF (epoch 1)
- column 2 – mean power spectrum across all epochs (including epoch 1)
All other objects (one-column output):
- column 1 – mean power spectrum across all epochs
The two-column layout allows direct comparison between the "evoked" power (column 1, captures phase-locked activity) and the total power (column 2, captures both phase-locked and non-phase-locked activity).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelmethod::Symbol=:welch: power spectrum method::welch: Welch's periodogram:stft: short-time Fourier transform:mt: multi-tapered periodogram:fft: Fast Fourier transform:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowdb::Bool=true: normalize powers to dBncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Matrix{Float64}: powers, shape(frequencies, 1)or(frequencies, 2)f::Vector{Float64}: frequencies
NeuroAnalyzer.eros — Function
eros(obj; <keyword arguments>)Calculate ERO (Event-Related Oscillations) spectrogram.
Wraps NeuroAnalyzer.spectrogram() to compute an ERO time-frequency summary for a single channel:
ERP/ERF objects (two-slice output, along dim 3):
- s[:, :, 1] – spectrogram of the trial-averaged ERP/ERF (epoch 1)
- s[:, :, 2] – mean spectrogram across all epochs
All other objects (one-slice output):
- s[:, :, 1] – mean spectrogram across all epochs
The two-slice layout mirrors erop() and allows comparison between phase-locked (evoked) and total (evoked + induced) time-frequency power.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channelmethod::Symbol=:stft: spectrogram estimation method::stft: short-time Fourier transform:mt: multi-tapered periodogram:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform:cwt: continuous wavelet transformationnt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length, default is 1 secondwoverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowpad::Int64=0: number of zeros to appenddb::Bool=true: normalize powers to dBgw::Real=5: Gaussian width in Hz (used by:gh)ncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)wt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available wavelets
Returns
Named tuple:
s::Array{Float64, 3}: spectrogram(s)f::Vector{Float64}: frequenciest::Vector{Float64}: time
NeuroAnalyzer.erp_auc — Function
erp_auc(obj; <keyword arguments>)Compute area under curve of an ERP/ERF/MEP (epoch 1).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)seg::Tuple{Real, Real}=(obj.epoch_time[1], obj.epoch_time[end]): time segment in secondstype::Symbol=:all: which part of the signal to integrate::all- full waveform:pos- positive values only:neg- negative values only
Returns
Vector{Float64}
NeuroAnalyzer.erp_gfp — Function
erp_gfp(s)Calculate GFP (Global Field Power).
GFP is the population standard deviation across all selected channels at each time point. It is zero when all channels agree and maximal when they diverge. GFP peaks may reflect "interesting" brain activity warranting further investigation.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)
Returns
Vector{Float64}: GFP at each time point (length = number of samples)
Notes
GFP is the population standard deviation across all channels at each time point. It is zero when all channels have identical values and maximal when channel activity is maximally divergent.
GFP(t) = std_channels( s[:, t] )
This is used internally by diss() to make amplitudes comparable.
erp_gfp(obj)Calculate GFP (Global Field Power).
GFP is the population standard deviation across all selected channels at each time point for a NEURO object.
It is zero when all channels agree and maximal when they diverge. GFP peaks may reflect "interesting" brain activity warranting further investigation.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)norm::Bool=false: if true, return the GFP-normalised signal instead of GFP values
Returns
Union{Vector{Float64}, Matrix{Float64}}: GFP values over time (norm=false) or the GFP-normalized signal matrix (norm=true)
Notes
GFP is the population standard deviation across all channels at each time point. It is zero when all channels have identical values and maximal when channel activity is maximally divergent.
GFP(t) = std_channels( s[:, t] )
NeuroAnalyzer.erp_gfp_norm — Function
erp_gfp_norm(s)Normalize a signal matrix by its GFP (Global Field Power).
Each column (time point) is divided by the GFP value at that time, so that the resulting matrix has unit standard deviation across channels at every sample. Returns the original matrix unchanged at any time point where GFP = 0.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)
Returns
Matrix{Float64}: GFP-normalised signal (channels × samples)
NeuroAnalyzer.erp_peaks — Function
erp_peaks(obj)Detect the positive and negative peak of each channel's ERP/ERF/MEP.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Matrix{Int64}: shape(channels, 2)- column 1 is the positive peak sample index, column 2 is the negative peak sample index
NeuroAnalyzer.escor — Function
escor(s1, s2)Calculate Envelope-to-Signal Correlation (ESC).
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Float64: ESC value
References
Bruns, A., & Eckhorn, R. (2004). Task-related coupling from high-to low-frequency signals among visual cortical areas in human subdural recordings. International Journal of Psychophysiology, 51(2), 97-116.
escor(obj1, obj2; <keyword arguments>)Calculate Envelope-to-Signal Correlation (ESC) for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Matrix{Float64}: ESC value, shape (channels, epochs)
escor(obj; <keyword arguments>)Calculate Envelope-to-Signal Correlation (ESC) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: ESC value, shape(channels, channels, epochs)
NeuroAnalyzer.frqinst — Function
frqinst(s)Estimate the instantaneous frequency of a signal via the Hilbert transform for a 1-D signal vector:
- Compute the analytic signal with htransform().
- Extract the instantaneous phase (index 3 of htransform output).
- Unwrap the phase to remove 2π discontinuities.
- Differentiate to obtain dφ/dt in radians per sample.
- Divide by 2π to convert to cycles per sample.
Arguments
s::AbstractVector: signal vector
Returns
Vector{Float64}: instantaneous frequencies in cycles per sample (multiply by the sampling rate to obtain Hz)
Notes
Uses the Hilbert transform; best results for narrowband signals. Broadband signals produce meaningless instantaneous frequencies.
frqinst(s)Estimate the instantaneous frequency of a signal via the Hilbert transform:
- Compute the analytic signal with htransform().
- Extract the instantaneous phase (index 3 of htransform output).
- Unwrap the phase to remove 2π discontinuities.
- Differentiate to obtain dφ/dt in radians per sample.
- Divide by 2π to convert to cycles per sample.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Array{Float64, 3}: instantaneous frequencies in cycles per sample (multiply by the sampling rate to obtain Hz), shape (channels, samples, epochs)
Notes
Uses the Hilbert transform; best results for narrowband signals. Broadband signals produce meaningless instantaneous frequencies.
frqinst(obj; <keyword arguments>)Estimate the instantaneous frequency of a signal via the Hilbert transform:
- Compute the analytic signal with htransform().
- Extract the instantaneous phase (index 3 of htransform output).
- Unwrap the phase to remove 2π discontinuities.
- Differentiate to obtain dφ/dt in radians per sample.
- Divide by 2π to convert to cycles per sample.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: instantaneous frequencies in Hz, shape (channels, samples, epochs)
Notes
Uses the Hilbert transform; best results for narrowband signals. Broadband signals produce meaningless instantaneous frequencies.
NeuroAnalyzer.ftransform — Function
ftransform(s; <keyword arguments>)Calculate Fourier transform (FFT / rFFT) for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorpad::Int64=0: number of zeros to appenddb::Bool=false: normalize powers to dBnf::Bool=false: : if true, return coefficients for negative and positive frequencies; otherwise return coefficients for positive frequencies only
Returns
Named tuple:
c::Vector{ComplexF64}: Fourier coefficientsa::Vector{Float64}: amplitudesp::Vector{Float64}: powersph::Vector{Float64}: phases in radians
Notes
To obtain the matching frequency vector use f = freqs(s, fs).f.
ftransform(s; <keyword arguments>)Calculate Fourier transform (FFT / rFFT) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)pad::Int64=0: number of zeros to appenddb::Bool=false: normalize powers to dBnf::Bool=false: if true, return Fourier coefficients for negative and positive frequencies, otherwise return Fourier coefficients for positive frequencies only
Returns
Named tuple:
c::Array{ComplexF64, 3}: Fourier coefficients, shape (channels, samples, epochs)a::Array{Float64, 3}: amplitudes, shape (channels, samples, epochs)p::Array{Float64, 3}: powers, shape (channels, samples, epochs)ph::Array{Float64, 3}: phases in radians, shape (channels, samples, epochs)
NeuroAnalyzer.ftt_analyze — Function
ftt_analyze(t)Analyze taps in a TPT (Tapping Performance Task) recording. Summarizes inter-tap interval statistics from a TPT (Tapping Performance Task) recording.
Arguments
Named tuple:
taps::Vector{Int64}: number of taps per trialtap_t::Vector{Vector{Float64}}: tap time points per trial [ms]tap_d::Vector{Vector{Float64}}: tap durations per trial [ms]taps_int::Vector{Int64}: number of taps per trial during intervalstap_t_int::Vector{Vector{Float64}}: tap time points during intervals [ms]tap_d_int::Vector{Vector{Float64}}: tap durations during intervals [ms]
Returns
Named tuple:
n::Int64: total number of taps across all trialst_mean::Float64: mean inter-tap interval [ms]t_median::Float64: median inter-tap interval [ms]t_rmssd::Float64: root mean square of successive differences between adjacent inter-tap intervals [ms]:√(mean( diff(ITI)²))t_sdsd::Float64: standard deviation of successive differences [ms]:std(diff(ITI))
NeuroAnalyzer.ged — Function
ged(s1, s2)Perform Generalized Eigendecomposition.
Solves the generalised eigenvalue problem S1·W = S2·W·Λ, where S1 and S2 are the covariance matrices of the "target" and "reference" signals.
The first (largest) eigenvector defines the spatial filter that maximally distinguishes S1 from S2. The RESS (Rhythmic Entrainment Source Separation) spatial filter is the pseudoinverse of that eigenvector.
Arguments
s1::AbstractMatrix: target signal (channels × samples)s2::AbstractMatrix: reference signal (channels × samples)
Returns
Named tuple:
sged::Matrix{Float64}: reference signal weighted by the first eigenvector, shape(channels, samples)ress::Vector{Float64}: RESS spatial filter (pseudoinverse of leading eigenvector)ress_norm::Vector{Float64}: RESS normalized to −1..1
ged(obj1, obj2; <keyword arguments>)Perform Generalized Eigendecomposition.
Solves the generalised eigenvalue problem S1·W = S2·W·Λ, where S1 and S2 are the covariance matrices of the "target" and "reference" signals.
The first (largest) eigenvector defines the spatial filter that maximally distinguishes S1 from S2. The RESS (Rhythmic Entrainment Source Separation) spatial filter is the pseudoinverse of that eigenvector.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO object: object to be analyzed (target)obj2::NeuroAnalyzer.NEURO: input NEURO object: original object (reference)ch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
sged::Array{Float64, 3}: GED output, shape (channels, samples, epochs)ress::Matrix{Float64}: RESS spatial filter, shape (channels, epochs)ress_norm::Matrix{Float64}: RESS normalized to −1..1, shape (channels, epochs)
NeuroAnalyzer.ghexp — Function
ghexp(s; tau_range, q_range)Calculate the Generalised Hurst Exponent(s) of a 1-D signal vector by analysing how the q-th moment of the absolute increments |s(t+τ) − s(t)|^q scales with lag τ.
Two modes:
- qrange = nothing → standard Hurst exponent via hurstexponent(); output shape: (1, 2) → (exponent, goodness-of-fit)
- qrange provided → generalised exponents via generalisedhurstrange(); output shape: (length(qrange), 2)
Arguments
s::AbstractVector: signal vectortau_range::UnitRange{Int64}: lag range over which the q-th moment of absolute increments is estimatedq_range::Union{Nothing, StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}}=nothing: moments at which GHEs are estimated; ifnothing, the standard Hurst exponent is returned
Returns
Matrix{Float64}: shape(1, 2)whenq_range=nothing, otherwise(length(q_range), 2)- columns are (exponent, goodness-of-fit)
ghexp(s)Calculate the Generalised Hurst Exponents (GHEs) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)tau_range::UnitRange{Int64}: lag range over which the q-th moment of absolute increments is estimatedq_range::Union{Nothing, StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}}=nothing: moments at which GHEs are estimated; ifnothing, the standard Hurst exponent is returned
Returns
Array{Float64, 4}: shape (channels, q, 2, epochs) whereqis 1 whenq_range=nothing, otherwiselength(q_range)
ghexp(obj; <keyword arguments>)Calculate the Generalised Hurst Exponents (GHEs) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)tau_range::UnitRange{Int64}: lag range over which the q-th moment of absolute increments is estimatedq_range::Union{Nothing, StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}}=nothing: moments at which GHEs are estimated; ifnothing, the standard Hurst exponent is returned
Returns
Array{Float64, 4}: shape(channels, q, 2, epochs)
NeuroAnalyzer.ghpsd — Function
ghpsd(s; <keyword arguments>)Calculate power spectrum using Gaussian filter and Hilbert transform for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=true: normalize powers to dBgw::Real=5: Gaussian width in Hz (used by:gh)w::Bool=true: iftrue, apply Hanning windowdemean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Vector{Float64}: powersf::Vector{Float64}: frequencies
NeuroAnalyzer.ghtspectrogram — Function
ghtspectrogram(s; <keyword arguments>)Calculate spectrogram using Gaussian filter and Hilbert transform.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=true: normalize powers to dBgw::Real=10: Gaussian width in Hzw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
p::Matrix{Float64}: powersph::Matrix{Float64}: phasesf::Vector{Float64}: frequenciest::Vector{Float64}: time points
ghtspectrogram(s; <keyword arguments>)Calculate spectrogram using Gaussian and Hilbert transform for each channel of a matrix.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)fs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=true: normalize powers to dBgw::Real=10: Gaussian width in Hzw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
p::Array{Float64, 3}: powers, shape(freq, time, channels)ph::Array{Float64, 3}: phases, shape(freq, time, channels)f::Vector{Float64}: frequenciest::Vector{Float64}: time points
NeuroAnalyzer.hanalytic — Function
hanalytic(s)Calculate complex analytic signal (s + i·H(s)) using Hilbert transformation for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Vector{ComplexF64}: complex analytic signal
hanalytic(s; <keyword arguments>)Calculate complex analytic signal (s + i·H(s)) using Hilbert transformation for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)pad::Int64=0: number of zeros to append
Returns
Vector{ComplexF64}: complex analytic signal, shape (channels, samples, epochs)
hanalytic(obj; <keyword arguments>)Calculate complex analytic signal (s + i·H(s)) using Hilbert transformation for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to append
Returns
Vector{ComplexF64}: complex analytic signal, shape (channels, samples, epochs)
NeuroAnalyzer.henv — Function
henv(obj; <keyword arguments>)Calculate Hilbert spectrum amplitude envelope for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Named tuple:
e::Array{Float64, 3}: Hilbert spectrum amplitude envelope, shape (channels, samples, epochs)t::Vector{Float64}: time points
NeuroAnalyzer.henv_lo — Function
henv_lo(s)Calculate lower amplitude envelope using the Hilbert transform for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Vector{Float64}: negative instantaneous amplitude (lower envelope)
Notes
The Hilbert transform works best for narrowband signals (energy concentrated around a single frequency).
NeuroAnalyzer.henv_mean — Function
henv_mean(obj; <keyword arguments>)Calculate Hilbert spectrum amplitude envelope (mean and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: mean over channels (dims=1), epochs (dims=2), or both (dims=3)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Named tuple:
em::Matrix{Float64}: mean Hilbert spectrum amplitude envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3el::Matrix{Float64}: 95% CI lower boundeu::Matrix{Float64}: 95% CI upper boundt::Vector{Float64}: time points
NeuroAnalyzer.henv_median — Function
henv_median(obj; <keyword arguments>)Calculate Hilbert spectrum amplitude envelope (median and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: median over channels (dims=1), epochs (dims=2), or both (dims=3)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Named tuple:
em::Matrix{Float64}: median Hilbert spectrum amplitude envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3el::Matrix{Float64}: 95% CI lower boundeu::Matrix{Float64}: 95% CI upper boundt::Vector{Float64}: time points
NeuroAnalyzer.henv_up — Function
henv_up(s)Calculate upper amplitude envelope using the Hilbert transform for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Vector{Float64}: instantaneous amplitude (upper envelope)
Notes
The Hilbert transform works best for narrowband signals (energy concentrated around a single frequency).
NeuroAnalyzer.hfd — Function
hfd(s)Calculate the Higuchi fractal dimension for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Float64: the Higuchi fractal dimension
Notes
Wraps FractalDimensions.higuchi_dim() to compute the Higuchi fractal dimension (Higuchi, 1988) for neural signals.
The Higuchi FD estimates the fractal dimension directly from the time series by measuring how the length of the signal scales with the lag parameter k. Values range from 1 (smooth/linear) to 2 (maximally irregular/random).
hfd(s)Calculate the Higuchi fractal dimension for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Matrix{Float64}: the Higuchi fractal dimension, shape (channels, epochs)
Notes
Wraps FractalDimensions.higuchi_dim() to compute the Higuchi fractal dimension (Higuchi, 1988) for neural signals.
The Higuchi FD estimates the fractal dimension directly from the time series by measuring how the length of the signal scales with the lag parameter k. Values range from 1 (smooth/linear) to 2 (maximally irregular/random).
hfd(obj; <keyword arguments>)Calculate the Higuchi fractal dimension for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Matrix{Float64}
Notes
Wraps FractalDimensions.higuchi_dim() to compute the Higuchi fractal dimension (Higuchi, 1988) for neural signals.
The Higuchi FD estimates the fractal dimension directly from the time series by measuring how the length of the signal scales with the lag parameter k. Values range from 1 (smooth/linear) to 2 (maximally irregular/random).
NeuroAnalyzer.hhtspectrogram — Function
hhtspectrogram(s, t; <keyword arguments>)Calculate spectrogram using Hilbert-Huang transform.
- Empirical Mode Decomposition (EMD) – Decomposes the signal into Intrinsic Mode Functions (IMFs).
- Hilbert Spectral Analysis (HSA) – Applies the Hilbert transform to each IMF to extract instantaneous frequency and powers, producing a spectrogram-like representation.
Arguments
s::AbstractVector: signal vectortps::AbstractVector: time points (required for EMD)fs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=true: normalize powers to dB
Returns
Named tuple:
p::Matrix{Float64}: powers (frequencies × time points)f::Vector{Float64}: frequenciest::Vector{Float64}: time points
hhtspectrogram(s; <keyword arguments>)Calculate spectrogram using Hilbert-Huang transform.
- Empirical Mode Decomposition (EMD) – Decomposes the signal into Intrinsic Mode Functions (IMFs).
- Hilbert Spectral Analysis (HSA) – Applies the Hilbert transform to each IMF to extract instantaneous frequency and powers, producing a spectrogram-like representation.
Arguments
s::AbstractMatrix: signal matrixtps::AbstractVector: time points (required for EMD)fs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=true: normalize powers to dB
Returns
Named tuple:
p::Matrix{Float64}: powers (frequencies × time points)f::Vector{Float64}: frequenciest::Vector{Float64}: time points
NeuroAnalyzer.hjorth — Function
hjorth(s)Calculate Hjorths parameters for a 1-D signal vector.
Three features derived from a signal and its successive derivatives:
- Activity - total power of the signal (
var(s)) - Mobility - estimate of the mean frequency (
sqrt(var(s') / var(s))) - Complexity - similarity of the signal shape to a pure sine wave (
Mobility(s') / Mobility(s))
where s' = derivative(s).
Arguments
s::AbstractVector: signal vector
Returns
Named tuple:
h_act::Float64: activityh_mob::Float64: mobilityh_comp::Float64: complexity
hjorth(s)Calculate Hjorths parameters for a 3-D signal array.
Three features derived from a signal and its successive derivatives:
- Activity - total power of the signal (
var(s)) - Mobility - estimate of the mean frequency (
sqrt(var(s') / var(s))) - Complexity - similarity of the signal shape to a pure sine wave (
Mobility(s') / Mobility(s))
where s' = derivative(s).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Named tuple:
h_act::Matrix{Float64}: activity, shape (channels, epochs)h_mob::Matrix{Float64}: mobility, shape (channels, epochs)h_comp::Matrix{Float64}: complexity, shape (channels, epochs)
hjorth(obj; <keyword arguments>)Calculate Hjorths parameters for a NEURO object.
Three features derived from a signal and its successive derivatives:
- Activity - total power of the signal (
var(s)) - Mobility - estimate of the mean frequency (
sqrt(var(s') / var(s))) - Complexity - similarity of the signal shape to a pure sine wave (
Mobility(s') / Mobility(s))
where s' = derivative(s).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Named tuple:
h_act::Matrix{Float64}: activity, shape (channels, epochs)h_mob::Matrix{Float64}: mobility, shape (channels, epochs)h_comp::Matrix{Float64}: complexity, shape (channels, epochs)
NeuroAnalyzer.hmspectrum — Function
hmspectrum(obj; <keyword arguments>)Calculate Hilbert marginal spectrum for a NEURO object.
The Hilbert marginal spectrum is computed from the Hilbert-Huang Transform (HHT) spectrogram by integrating (summing) the instantaneous power over time for each frequency, independently per epoch. The result is a frequency × epochs power matrix analogous to a classical power spectrum.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel name; must resolve to exactly one channel
Returns
Named tuple:
p::Matrix{Float64}: Hilbert marginal spectra, shape (frequency, epochs)f::Vector{Float64}: frequencies
References
Huang et al. (1998), "The empirical mode decomposition and the Hilbert spectrum for nonlinear and non-stationary time series analysis."
NeuroAnalyzer.hrv_analyze — Function
hrv_analyze(nn_seg)Analyze time-domain heart rate variability (HRV) statistics from NN intervals. NN interval = interval between successive R-peaks (equivalent to RR interval when ectopic beats have been removed, hence "Normal-to-Normal").
Arguments
nn_seg::Vector{Float64}: list of NN segments [ms]
Returns
Named tuple:
menn::Float64: mean NN interval [ms]mdnn::Float64: median NN interval [ms]vnn::Float64: variance of NN intervals [ms²]sdnn::Float64: standard deviation of NN intervals [ms]rmssd::Float64: root mean square of successive differences between adjacent NN intervals [ms] - √(mean(diff(NN)²))sdsd::Float64: standard deviation of successive differences between adjacent NN intervals [ms] - std(diff(NN))nn50::Int64: number of pairs of successive NNs differing by > 50 mspnn50::Float64: proportion of NN50 to total number of NN intervalsnn20::Int64: number of pairs of successive NNs differing by > 20 mspnn20::Float64: proportion of NN20 to total number of NN intervals
NeuroAnalyzer.hrv_detect — Function
hrv_detect(obj)Detect heart rate variability (HRV) R-peaks from the ECG channel.
The ECG channel is located automatically from the channel_type field of obj.header.recording.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Named tuple:
nn_seg::Vector{Float64}: NN (normal-to-normal) interval durations [ms]r_idx::Vector{Int64}: sample indices of detected R-peaks
NeuroAnalyzer.htransform — Function
htransform(s; <keyword arguments>)Calculate Hilbert transform (analytic signal) for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectordb::Bool=false: normalize powers to dB
Returns
Named tuple:
c::Vector{ComplexF64}: analytic (Hilbert) coefficientsa::Vector{Float64}: instantaneous amplitudesp::Vector{Float64}: instantaneous powersph::Vector{Float64}: instantaneous phases in radians
htransform(s; <keyword arguments>)Calculate Hilbert transform (analytic signal) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)db::Bool=false: normalize powers to dB
Returns
Named tuple:
c::Array{ComplexF64, 3}: Hilbert coefficientsa::Array{Float64, 3}: amplitudesp::Array{Float64, 3}: powersph::Array{Float64, 3}: phases (in radians)
NeuroAnalyzer.iplv — Function
iplv(s1, s2)Calculate Imaginary Phase Locking Value (IPLV) for two 1-D signal vectors.
The IPLV is the absolute imaginary part of the mean complex phase difference:
IPLV = |Im( mean( exp(i·Δφ) ) )|
Unlike the standard PLV, the imaginary component is insensitive to spurious zero-lag synchrony introduced by volume conduction, making it more specific to true neural coupling.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Named tuple:
ipl::Float64: PLV valuesd::Vector{Float64}: signal difference (s1 - s2)phd::Vector{Float64}: phase difference (s1 - s2)s1ph::Vector{Float64}: instantaneous phase of s1s2ph::Vector{Float64}: instantaneous phase of s2
References
Aydore S, Pantazis D, Leahy RM. A note on the phase locking value and its properties. NeuroImage. 2013 July;74:231–44.
iplv(obj1, obj2; <keyword arguments>)Calculate Imaginary Phase Locking Value (IPLV) between channel-matched pairs of two NEURO objects.
The IPLV is the absolute imaginary part of the mean complex phase difference:
IPLV = |Im( mean( exp(i·Δφ) ) )|
Unlike the standard PLV, the imaginary component is insensitive to spurious zero-lag synchrony introduced by volume conduction, making it more specific to true neural coupling.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
ipl::Matrix{Float64}: IPLV value, shape (channels, epochs)sd::Array{Float64, 3}: signal difference (s1 - s2), shape (channels, samples, epochs)phd::Array{Float64, 3}: phase difference (s1 - s2), shape (channels, samples, epochs)s1ph::Array{Float64, 3}: signal 1 phases, shape (channels, samples, epochs)s2ph::Array{Float64, 3}: signal 2 phases, shape (channels, samples, epochs)
References
Aydore S, Pantazis D, Leahy RM. A note on the phase locking value and its properties. NeuroImage. 2013 July;74:231–44.
iplv(obj; <keyword arguments>)Calculate Imaginary Phase Locking Value (IPLV) for all channel pairs of a NEURO object.
The IPLV is the absolute imaginary part of the mean complex phase difference:
IPLV = |Im( mean( exp(i·Δφ) ) )|
Unlike the standard PLV, the imaginary component is insensitive to spurious zero-lag synchrony introduced by volume conduction, making it more specific to true neural coupling.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
ipl::Array{Float64, 3}: IPLV matrix, shape(channels, channels, epochs); symmetric with zeros on the diagonal
References
Aydore S, Pantazis D, Leahy RM. A note on the phase locking value and its properties. NeuroImage. 2013 July;74:231–44.
NeuroAnalyzer.ispc — Function
ispc(s1, s2)Calculate ISPC (Inter-Site-Phase Clustering) for two 1-D signal vectors.
ISPC measures the consistency of the phase difference between two signals across trials (or, here, across time within a single trial):
ISPC value = |mean( exp(i·Δφ) )| (0 = no clustering, 1 = perfect lock)
ISPC angle = angle( mean( exp(i·Δφ) ) ) (preferred phase difference)
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Named tuple:
ispcv::Float64: ISPC value (phase-locking magnitude)ispca::Float64: ISPC angle (preferred phase difference)sd::Vector{Float64}: signal difference (s1 - s2)phd::Vector{Float64}: phase difference (s1 - s2)s1ph::Vector{Float64}: instantaneous phase of s1s2ph::Vector{Float64}: instantaneous phase of s2
ispc(obj; <keyword arguments>)Calculate ISPC (Inter-Site Phase Clustering) for all channel pairs of a NEURO object.
ISPC measures the consistency of the phase difference between two signals across trials (or, here, across time within a single trial):
ISPC value = |mean( exp(i·Δφ) )| (0 = no clustering, 1 = perfect lock)
ISPC angle = angle( mean( exp(i·Δφ) ) ) (preferred phase difference)
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Named tuple:
ispcv::Array{Float64, 3}: ISPC value matrices, shape(channels, channels, epochs)ispca::Array{Float64, 3}: ISPC angle matrices, shape(channels, channels, epochs)
ispc(obj1, obj2; <keyword arguments>)Calculate ISPC (Inter-Site Phase Clustering) between channel-matched pairs of two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
ispcv::Matrix{Float64}: ISPC value, shape (channels, epochs)ispca::Matrix{Float64}: ISPC angle, shape (channels, epochs)sd::Array{Float64, 3}: signal difference (s1 - s2), shape (channels, samples, epochs)phd::Array{Float64, 3}: phase difference (s1 - s2), shape (channels, samples, epochs)s1ph::Array{Float64, 3}: signal 1 phases, shape (channels, samples, epochs)s2ph::Array{Float64, 3}: signal 2 phases, shape (channels, samples, epochs)
NeuroAnalyzer.itpc — Function
itpc(s; <keyword arguments>)Calculate ITPC (Inter-Trial Phase Clustering) at sample t over epochs for a 3-D signal array.
ITPC measures the consistency of the instantaneous phase across epochs at a given time point (or across all time points for the spectrogram variant):
ITPC value = |mean( w .* exp(i·φ) )| (0 = random, 1 = perfect lock) ITPC z = N · ITPC² (Rayleigh statistic) ITPC angle = angle( mean( w .* exp(i·φ) ) ) (preferred phase)
The weighted variant (wITPC) allows per-epoch importance weights.
Arguments
s::AbstractArray: single-channel array (1, samples, epochs)t::Int64: time point (sample number) at which ITPC is calculatedw::Union{AbstractVector, Nothing}: optional vector of epochs/trials weights for wITPC calculation
Returns
Named tuple:
itpcv::Float64: ITPC (or wITPC) valueitpcz::Float64: Rayleigh's ITPC z statisticitpca::Float64: ITPC angle (preferred phase)itpcph::Vector{Float64}: instantaneous phases at timetacross epochs
References
Cohen, M. X. (2014). Analyzing Neural Time Series Data: Theory and Practice.Cambridge: MIT Press
itpc(obj; <keyword arguments>)Calculate ITPC (Inter-Trial Phase Clustering) at time t over epochs for a NEURO object.
ITPC measures the consistency of the instantaneous phase across epochs at a given time point (or across all time points for the spectrogram variant):
ITPC value = |mean( w .* exp(i·φ) )| (0 = random, 1 = perfect lock) ITPC z = N · ITPC² (Rayleigh statistic) ITPC angle = angle( mean( w .* exp(i·φ) ) ) (preferred phase)
The weighted variant (wITPC) allows per-epoch importance weights.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)t::Real: time point in seconds at which ITPC is calculatedw::Union{Vector{<:Real}, Nothing}=nothing: optional per-epoch weights
Returns
Named tuple:
itpcv::Vector{Float64}: ITPC or wITPC value per channelitpcz::Vector{Float64}: Rayleigh's ITPC z statistic per channelitpca::Vector{Float64}: ITPC angle per channelitpcph::Matrix{Float64}: instantaneous phases att, shape (channels, epochs)
NeuroAnalyzer.itpc_spec — Function
itpc_spec(s; <keyword arguments>)Calculate the ITPC spectrogram (ITPC at every time point) for a 3-D signal array.
ITPC measures the consistency of the instantaneous phase across epochs at a given time point (or across all time points for the spectrogram variant):
ITPC value = |mean( w .* exp(i·φ) )| (0 = random, 1 = perfect lock) ITPC z = N · ITPC² (Rayleigh statistic) ITPC angle = angle( mean( w .* exp(i·φ) ) ) (preferred phase)
The weighted variant (wITPC) allows per-epoch importance weights.
Arguments
s::AbstractArray: single-channel array (1, samples, epochs)w::Union{AbstractVector, Nothing}: optional per-epoch weights
Returns
Named tuple:
itpcv::Vector{Float64}: ITPC or wITPC value per channelitpcz::Vector{Float64}: Rayleigh's ITPC z statistic per channelitpca::Vector{Float64}: ITPC angle per channelitpcph::Matrix{Float64}: instantaneous phases att, shape (channels, epochs)
itpc_spec(obj; <keyword arguments>)Calculate the ITPC spectrogram (ITPC at each frequency and time point) for a NEURO object.
ITPC measures the consistency of the instantaneous phase across epochs at a given time point (or across all time points for the spectrogram variant):
ITPC value = |mean( w .* exp(i·φ) )| (0 = random, 1 = perfect lock) ITPC z = N · ITPC² (Rayleigh statistic) ITPC angle = angle( mean( w .* exp(i·φ) ) ) (preferred phase)
The weighted variant (wITPC) allows per-epoch importance weights.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::String: channel to analyzeflim::Tuple{Real, Real}=(0, sr(obj) / 2): frequency bounds for the spectrogramnfrq::Int64=_tlength(flim): number of frequenciesfrq::Symbol=:lin: frequency scaling -:linor:logw::Union{Vector{<:Real}, Nothing}=nothing: optional vector of epochs/trials weights for wITPC calculation
Returns
Named tuple:
itpcs::Matrix{Float64}: ITPC spectrogram, shape(frequencies, samples)itpczs::Matrix{Float64}: ITPCZ spectrogram, shape(frequencies, samples)f::Vector{Float64}: frequency vector
NeuroAnalyzer.lat_idx — Function
lat_idx(obj; <keyword arguments>)Calculate Lateralization Index for a NEURO object.
LI is the log-ratio of right vs left hemisphere power at a given frequency (or frequency range):
LI = log( Pright / Pleft )
LI > 0 → right-dominant LI < 0 → left-dominant LI = 0 → symmetric
Hemisphere channels are detected automatically via channel_pick().
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectfrq::Union{Real, Tuple{<:Real, <:Real}}: frequency at which the index is calculated; if range is provided, than averaged index across the range is calculatedmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Float64: lateralization index (positive = right-dominant)
NeuroAnalyzer.maxamp_at — Function
maxamp_at(obj; <keyword arguments>)Calculate maximum amplitude over a time segment.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectt::Tuple{Real, Real}: time segment in seconds
Returns
Matrix{Float64}: maximum amplitude for each channel per epoch, shape (channels, epochs) or(channels, 1)for continuous objects
NeuroAnalyzer.mdiff — Function
mdiff(s1, s2; <keyword arguments>)Calculate the mean difference and its bootstrap p-value for two signal matrices. Estimate whether the mean difference between two signal matrices is statistically significant using a permutation/bootstrap approach:
- Compute the observed statistic (max absolute difference or integrated squared difference) between the mean waveforms of s1 and s2.
- Pool s1 and s2 rows; repeatedly resample with replacement and compute the same statistic on random pairs of sub-groups.
- p = proportion of bootstrap statistics exceeding the observed statistic.
Arguments
s1::AbstractMatrix: signal matrix (channels, samples)s2::AbstractMatrix: signal matrix (channels, samples)n::Int64=3: number of bootstrap iterations per channelmethod::Symbol=:absdiff: test statistic::absdiff: maximum absolute difference between mean waveforms:diff2int: integrated area of the squared difference
Returns
Named tuple:
st::Vector{Float64}: bootstrap distribution of the test statisticsts::Float64: observed test statisticp::Float64: proportion of bootstrap statistics exceedingsts
mdiff(s1, s2; <keyword arguments>)Calculate the mean difference and its bootstrap p-value for each epoch of two 3-D signal arrays.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)n::Int64=3: number of bootstrap iterations per channelmethod::Symbol=:absdiff: test statistic::absdiff: maximum absolute difference:diff2int: integrated area of the squared difference
Returns
Named tuple:
st::Matrix{Float64}: bootstrap distributions, shape(epochs, channels*n)sts::Vector{Float64}: observed statistics per epochp::Vector{Float64}: p-values per epoch
mdiff(obj1, obj2; <keyword arguments>)Calculate the mean difference and its bootstrap p-value for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2:NeuroAnalyzer.NEUROch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2n::Int64: number of bootstrapsmethod::Symbol=:absdiff: test statistic::absdiff: maximum absolute difference:diff2int: integrated area of the squared difference
Returns
Named tuple:
st::Matrix{Float64}: bootstrap distributions, shape(epochs, channels*n)sts::Vector{Float64}: observed statistics per epochp::Vector{Float64}: p-values per epoch
NeuroAnalyzer.mep_peaks — Function
mep_peaks(obj)Detect a pair of positive and negative peaks of MEP.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Matrix{Int64}: peaks, shape (channels, positive peak position, negative peak position)
NeuroAnalyzer.minamp_at — Function
minamp_at(obj; <keyword arguments>)Calculate minimum amplitude over a time segment.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectt::Tuple{Real, Real}: time segment in seconds
Returns
Matrix{Float64}: minimum amplitude for each channel per epoch, shape (channels, epochs) or(channels, 1)for continuous objects
NeuroAnalyzer.msci95 — Function
msci95(s; <keyword arguments>)Calculate mean, standard error and 95% CI for a 1-D signal vector.
Two methods:
:normal – analytical CI using the normal approximation: CI = mean ± 1.96 * (std / √N) :boot – empirical CI from n*length(s) bootstrap resamples: CI = [2.5th percentile, 97.5th percentile] of bootstrap means
Arguments
s::AbstractVector: signal vectorn::Int64=3: bootstrap resampling factor (total resamples =n * length(s))method::Symbol=:normal::normal(analytical) or:boot(bootstrap)
Returns
Named tuple:
sm::Float64: meanse::Float64: standard errorll::Float64: lower 95% CIul::Float64: upper 95% CI
msci95(s; <keyword arguments>)Calculate mean, standard error and 95% CI across rows.
Two methods:
:normal – analytical CI using the normal approximation: CI = mean ± 1.96 * (std / √N) :boot – empirical CI from n*length(s) bootstrap resamples: CI = [2.5th percentile, 97.5th percentile] of bootstrap means
Arguments
s::AbstractMatrix: signal matrix (channels/trials, samples)n::Int64=3: bootstrap resampling factormethod::Symbol=:normal::normal(analytical) or:boot(bootstrap)
Returns
Named tuple:
sm::Vector{Float64}: column-wise meanse::Vector{Float64}: column-wise standard errorll::Vector{Float64}: lower 95% CI per sampleul::Vector{Float64}: upper 95% CI per sample
msci95(s; <keyword arguments>)Calculate mean, standard error and 95% CI for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)n::Int64=3: bootstrap resampling factormethod::Symbol=:normal::normal(analytical) or:boot(bootstrap)
Returns
Named tuple:
sm::Matrix{Float64}: mean, shape (epochs, samples)se::Matrix{Float64}: standard error, shape (epochs, samples)ll::Matrix{Float64}: lower 95% CI, shape (epochs, samples)ul::Matrix{Float64}: upper 95% CI, shape (epochs, samples)
msci95(s1, s2)Calculate mean difference, standard error and 95% CI between two vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Named tuple:
sm::Float64: meanse::Float64: pooled standard errorll::Float64: lower 95% CIul::Float64: upper 95% CI
msci95(s1, s2)Calculate mean difference, standard error and 95% CI per channel and epoch for a 3-D signal array.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Named tuple:
sm::Matrix{Float64}: mean difference, shape (channels, epochs)se::Matrix{Float64}: pooled SE, shape (channels, epochs)ll::Matrix{Float64}: lower 95% CI, shape (channels, epochs)ul::Matrix{Float64}: upper 95% CI, shape (channels, epochs)
msci95(obj; <keyword arguments>)Calculate mean, standard error and 95% CI for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)n::Int64=3: bootstrap resampling factormethod::Symbol=:normal::normal(analytical) or:boot(bootstrap)
Returns
Named tuple:
sm::Matrix{Float64}: meanse::Matrix{Float64}: standard errorll::Matrix{Float64}: lower 95% CIul::Matrix{Float64}: upper 95% CI
msci95(obj1, obj2; <keyword arguments>)Calculate mean difference, standard ERROR and 95% CI between two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2:NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
sm::Matrix{Float64}: mean difference, shape (channels, epochs)se::Matrix{Float64}: pooled SE, shape (channels, epochs)ll::Matrix{Float64}: lower 95% CI bound, shape (channels, epochs)ul::Matrix{Float64}: upper 95% CI bound, shape (channels, epochs)
NeuroAnalyzer.mutual_information — Function
mutual_information(s1, s2)Calculate mutual information between two 1-D signal vectors.
Wraps InformationMeasures.get_mutual_information() for mutual information estimation using the maximum likelihood estimator.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Float64: mutual information
mutual_information(s1, s2)Calculate mutual information between matched channel pairs of two 3-D signal arrays.
Wraps InformationMeasures.get_mutual_information() for mutual information estimation using the maximum likelihood estimator.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Matrix{Float64}: mutual information matrix, shape (channels, epochs)
mutual_information(s)Calculate mutual information between all channel pairs of a 3-D signal array.
Wraps InformationMeasures.get_mutual_information() for mutual information estimation using the maximum likelihood estimator.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Array{Float64, 3}: symmetric mutual information matrix, shape(channels, channels, epochs)
mutual_information(obj; <keyword arguments>)Calculate mutual information between all channel pairs of a NEURO object.
Wraps InformationMeasures.get_mutual_information() for mutual information estimation using the maximum likelihood estimator.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: symmetric mutual information matrix, shape(channels, channels, epochs)
mutual_information(obj1, obj2; <keyword arguments>)Calculate mutual information between matched channel pairs of two NEURO objects.
Wraps InformationMeasures.get_mutual_information() for mutual information estimation using the maximum likelihood estimator.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Matrix{Float64}: mutual information matrix, shape (channels, epochs)
NeuroAnalyzer.mwpsd — Function
mwpsd(s; <keyword arguments>)Calculate power spectrum using Morlet wavelet convolution for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorpad::Int64=0: number of zeros to appenddb::Bool=true: normalize powers to dBfs::Int64: sampling rate in Hz; must be ≥ 1ncyc::Union{Int64, Tuple{Int64, Int64}}=32: number of Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)w::Bool=true: iftrue, apply Hanning windowdemean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Vector{Float64}: powersf::Vector{Float64}: frequencies
NeuroAnalyzer.mwspectrogram — Function
mwspectrogram(s; <keyword arguments>)Calculate spectrogram using Morlet wavelet convolution.
Arguments
s::AbstractVector: signal vectorpad::Int64=0: number of zeros to appenddb::Bool=true: normalize powers to dBfs::Int64: sampling rate in Hz; must be ≥ 1ncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)w::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
cs::Matrix{ComplexF64}: convolved analytic signalp::Matrix{Float64}: powersph::Matrix{Float64}: phasesf::Vector{Float64}: frequenciest::Vector{Float64}: time points
mwspectrogram(s; <keyword arguments>)Calculate Morlet wavelet spectrogram for each channel of a matrix.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)pad::Int64=0: number of zeros to appenddb::Bool=true: normalize powers to dBfs::Int64: sampling rate in Hz; must be ≥ 1ncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)w::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
cs::Array{ComplexF64, 3}: convolved analytic signalsp::Array{Float64, 3}: powersph::Array{Float64, 3}: phasesf::Vector{Float64}: frequenciest::Vector{Float64}: time points
NeuroAnalyzer.negentropy — Function
negentropy(s; <keyword arguments>)Calculate negentropy for a 1-D signal vector.
Negentropy measures how far a signal's distribution departs from Gaussian: ne = 0.5·ln(2πe·var(s)) − H(s), where H(s) is the histogram entropy. ne ≈ 0 for Gaussian; ne > 0 for distributions that are more structured (peaky, multi-modal, etc.).
Arguments
s::AbstractVector: signal vectordemean::Bool=true: iftrue, subtract DC before calculating negentropynorm::Bool=true: iftrue, normalize the signal by its total energytype::Symbol=:diff: entropy type used for calculations (:diffdifferential,:shannonShannon,:samplesample)
Returns
Float64: negentropy (≥ 0; equals 0 for a Gaussian signal)
negentropy(s; <keyword arguments>)Calculate negentropy for a 3-D signal array.
Negentropy measures how far a signal's distribution departs from Gaussian: ne = 0.5·ln(2πe·var(s)) − H(s), where H(s) is the histogram entropy. ne ≈ 0 for Gaussian; ne > 0 for distributions that are more structured (peaky, multi-modal, etc.).
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)demean::Bool=true: iftrue, subtract DC before calculating negentropynorm::Bool=true: iftrue, normalize the signal by its total energytype::Symbol=:diff: entropy type used for calculations (:diffdifferential,:shannonShannon,:samplesample)
Returns
Matrix{Float64}: negentropy (≥ 0; equals 0 for a Gaussian signal), shape (channel, epochs)
negentropy(obj; <keyword arguments>)Calculate negentropy for a NEURO object.
Negentropy measures how far a signal's distribution departs from Gaussian: ne = 0.5·ln(2πe·var(s)) − H(s), where H(s) is the histogram entropy. ne ≈ 0 for Gaussian; ne > 0 for distributions that are more structured (peaky, multi-modal, etc.).
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)demean::Bool=true: iftrue, subtract DC before calculating negentropynorm::Bool=true: iftrue, normalize the signal by its total energytype::Symbol=:diff: entropy type used for calculations (:diffdifferential,:shannonShannon,:samplesample)
Returns
Matrix{Float64}: negentropy (≥ 0; equals 0 for a Gaussian signal), shape (channel, epochs)
NeuroAnalyzer.pacor — Function
pacor(s; <keyword arguments>)Computes the partial auto-correlation function (PACF) of a 1-D signal vector over symmetric lags −l … l using one of two methods:
:yw(Yule-Walker) - fast, no matrix inversion, may need larger l:reg(regression) - via successive OLS models, more robust for small l
Arguments
s::AbstractVector: signal vectorl::Int64=round(Int64, min(size(s[1, :, 1], 1) - 1, 10 * log10(size(s[1, :, 1], 1)))): symmetric lag range is−l:ldemean::Bool=true: subtract the mean before computing PACFmethod::Symbol=:yw:yw: Yule-Walker equations:reg: successive regression models
Returns
Array{Float64, 3}: shape(1, 2l+1, 1)
Notes
If you get ERROR: PosDefException: matrix is not positive definite; Cholesky factorization failed., try lowering l value or change method to :yw.
pacor(s; <keyword arguments>)Calculate partial auto-correlation function (PACF) for each epoch of a matrix over symmetric lags −l … l using one of two methods:
:yw(Yule-Walker) - fast, no matrix inversion, may need larger l:reg(regression) - via successive OLS models, more robust for small l
Arguments
s::AbstractMatrix: signal matrix (samples × epochs)l::Int64=round(Int64, min(size(s[1, :, 1], 1) - 1, 10 * log10(size(s[1, :, 1], 1)))): symmetric lag range is−l:ldemean::Bool=true: subtract the mean before computing PACFmethod::Symbol=:yw: method of calculating auto-correlation::yw: Yule-Walker equations:reg: successive regression models
Returns
Array{Float64, 3}
pacor(s; <keyword arguments>)Calculate partial auto-correlation function (PACF) for a 3-D signal array over lags −l … l using one of two methods:
:yw(Yule-Walker) - fast, no matrix inversion, may need larger l:reg(regression) - via successive OLS models, more robust for small l
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)l::Int64=round(Int64, min(size(s[1, :, 1], 1) - 1, 10 * log10(size(s[1, :, 1], 1)))): symmetric lag range is−l:ldemean::Bool=true: subtract the mean before computing PACFmethod::Symbol=:yw: method of calculating auto-correlation::yw: Yule-Walker equations:reg: successive regression models
Returns
Array{Float64, 3}: shape(channels, 2l+1, epochs)
pacor(obj; <keyword arguments>)Calculate partial auto-correlation function (PACF) for a NEURO object over lags −l … l using one of two methods:
:yw(Yule-Walker) - fast, no matrix inversion, may need larger l:reg(regression) - via successive OLS models, more robust for small l
For ERP objects, epoch 1 is the trial-averaged waveform and is prepended to the per-trial result.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)l::Real=1: lag limit in seconds; lags vector is−l:1/sr(obj):ldemean::Bool=true: subtract the mean before computing PACFmethod::Symbol=:yw: method of calculating auto-correlation::yw: Yule-Walker equations:reg: successive regression models
Returns
Named tuple:
pac::Array{Float64, 3}: partial auto-correlationslags::Vector{Float64}: lag values in seconds
NeuroAnalyzer.peak_amp — Function
peak_amp(s; <keyword arguments>)Calculate amplitude at the peak frequency within a frequency band.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Float64: amplitude at peak frequency
peak_amp(s; <keyword arguments>)Calculate amplitude at peak frequency within a frequency band for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: amplitude at peak frequency, shape (channels, epochs)
peak_amp(obj; <keyword arguments>)Calculate amplitude at peak frequency within a frequency band for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: amplitude at peak frequency, shape (channels, epochs)
NeuroAnalyzer.peak_frq — Function
peak_frq(s; <keyword arguments>)Calculate peak frequency within a frequency band for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency bounds in Hzmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Float64: peak frequency
peak_frq(s; <keyword arguments>)Calculate peak frequency within a frequency band for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: peak frequency, shape (channels, epochs)
peak_frq(obj; <keyword arguments>)Calculate peak frequency within a frequency band for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: peak frequency, shape (channels, epochs)
NeuroAnalyzer.peak_pow — Function
peak_pow(s; <keyword arguments>)Calculate power at the peak frequency within a frequency band.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Float64: power at peak frequency
peak_pow(s; <keyword arguments>)Calculate power at peak frequency within a frequency band for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
pp::Matrix{Float64}: peak power, shape (channels, epochs)
peak_pow(obj; <keyword arguments>)Calculate power at peak frequency within a frequency band for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}: lower and upper frequency boundsmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: peak power, shape (channels, epochs)
NeuroAnalyzer.penv — Function
penv(obj; <keyword arguments>)Calculate power spectrum (in dB) envelope for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)d::Int64=8: minimum distance between peaks in samples; smaller values give a tighter fitmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window length in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
e::Array{Float64, 3}: power spectrum envelope, shape (channels, frequencies, epochs)f::Vector{Float64}: frequencies
NeuroAnalyzer.penv_mean — Function
penv_mean(obj; <keyword arguments>)Calculate power spectrum (in dB) envelope (mean and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: mean over channels (dims=1), epochs (dims=2), or both (dims=3)d::Int64=8: minimum distance between peaks in samples; smaller values give a tighter fitmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window length in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
em::Matrix{Float64}: mean power envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3el::Matrix{Float64}: 95% CI lower boundeu::Matrix{Float64}: 95% CI upper boundf::Vector{Float64}: frequencies
NeuroAnalyzer.penv_median — Function
penv_median(obj; <keyword arguments>)Calculate power spectrum (in dB) envelope (median and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: median over channels (dims = 1) or epochs (dims = 2)d::Int64=8: minimum distance between peaks in samples; smaller values give a tighter fitmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window length in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
em::Matrix{Float64}: median power envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3el::Matrix{Float64}: 95% CI lower boundeu::Matrix{Float64}: 95% CI upper boundf::Vector{Float64}: frequencies
NeuroAnalyzer.phdiff — Function
phdiff(s1, s2; <keyword arguments>)Calculate phase difference between two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectorpad::Int64=0: number of zeros to appendh::Bool=false: use Hilbert transform, otherwise use Fourier transform
Returns
Named tuple:
Vector{Float64}: phase differences in radians
phdiff(s; <keyword arguments>)Calculate phase difference between channels and mean phase of reference ch for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)ch::Union{Int64, Vector{Int64}}=_c(size(s, 1)): index of reference channels, default is all channels except the analyzed oneavg::Symbol=:phase: method of averaging::phase: phase is calculated for each reference channel separately and then averaged:signal: signals are averaged prior to phase calculation
pad::Int64=0: number of zeros to appendh::Bool=false: use Hilbert transform, otherwise use Fourier transform
Returns
Array{Float64, 3}
phdiff(obj; <keyword arguments>)Calculate phase difference between channels and mean phase of reference ch.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: index of reference channelsavg::Symbol=:phase: method of averaging::phase: phase is calculated for each reference channel separately and then averaged:signal: signals are averaged prior to phase calculation
pad::Int64=0: number of zeros to appendh::Bool=false: use Hilbert transform, otherwise use Fourier transform
Returns
Array{Float64, 3}
NeuroAnalyzer.phsd — Function
phsd(s; <keyword arguments>)Calculate phase spectral density for a 1-D signal vector.
Arguments
s::Vector{Float64}fs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Named tuple:
ph::Vector{Float64}: phases (in radians)f::Vector{Float64}: frequencies
phsd(s; <keyword arguments>)Calculate phase spectral density.
Arguments
s::AbstractMatrixfs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Named tuple:
ph::Matrix{Float64}: phases (in radians)f::Vector{Float64}: frequencies
phsd(s; <keyword arguments>)Calculate phase spectral density for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1
Returns
Named tuple:
ph::Array{Float64, 3}: phases (in radians)f::Vector{Float64}: frequencies
phsd(obj; <keyword arguments>)Calculate phase spectral density for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Named tuple:
ph::Array{Float64, 3}: phases (in radians)f::Vector{Float64}: frequencies
NeuroAnalyzer.pli — Function
pli(s1, s2)Calculate Phase Locking Index (PLI) for two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Named tuple:
pv::Float64: PLI valuesd::Vector{Float64}: signal difference (s1 - s2)phd::Vector{Float64}: phase difference (s1 - s2)s1ph::Vector{Float64}: signal 1 phases2ph::Vector{Float64}: signal 2 phase
References
- Stam CJ, Nolte G, Daffertshofer A. Phase lag index: assessment of functional connectivity from multi channel EEG and MEG with diminished bias from common sources. Hum Brain Mapp. 2007 Nov;28(11):1178-93.
- Aydore S, Pantazis D, Leahy RM. A note on the phase locking value and its properties. NeuroImage. 2013 July;74:231–44.
pli(obj1, obj2; <keyword arguments>)Calculate Phase Locking Index (PLI) for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
pv::Matrix{Float64}: PLI valuesd::Array{Float64, 3}: signal difference (s1 - s2)phd::Array{Float64, 3}: phase difference (s1 - s2)s1ph::Array{Float64, 3}: signal 1 phases2ph::Array{Float64, 3}: signal 2 phase
pli(obj; <keyword arguments>)Calculate Phase Locking Index (PLI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: PLI value
NeuroAnalyzer.plv — Function
plv(s1, s2)Calculate Phase Locking Value (PLV) for two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Named tuple:
pv::Float64: PLV valuesd::Vector{Float64}: signal difference (s1 - s2)phd::Vector{Float64}: phase difference (s1 - s2)s1ph::Vector{Float64}: signal 1 phases2ph::Vector{Float64}: signal 2 phase
References
- Aydore S, Pantazis D, Leahy RM. A note on the phase locking value and its properties. NeuroImage. 2013 July;74:231–44.
plv(obj1, obj2; <keyword arguments>)Calculate Phase Locking Value (PLV) for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
pv::Matrix{Float64}: PLV valuesd::Array{Float64, 3}: signal difference (s1 - s2)phd::Array{Float64, 3}: phase difference (s1 - s2)s1ph::Array{Float64, 3}: signal 1 phases2ph::Array{Float64, 3}: signal 2 phase
plv(obj; <keyword arguments>)Calculate Phase Locking Value (PLV) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: PLV value
NeuroAnalyzer.psa — Function
psa(s1, s2)Calculate Phase Synchronization Analysis for two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Float64: PSA value
psa(obj1, obj2; <keyword arguments>)Calculate Phase Synchronization Analysis for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Matrix{Float64}: PSA value
psa(obj; <keyword arguments>)Calculate Phase Synchronization Analysis for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Array{Float64, 3}: PSA value
NeuroAnalyzer.psd — Function
psd(s; <keyword arguments>)Calculate Power Spectral Density for a 1-D signal vector.
Default method is Welch's periodogram.
Arguments
s::Vector{Float64}: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=false: normalize powers to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: number of Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Vector{Float64}: powersf::Vector{Float64}: frequencies
Notes
Setting demean=true reduces (but doesn't fully eliminate) DC contamination; the 0 Hz bin is still present in the output.
psd(s; <keyword arguments>)Calculate Power Spectral Density for each channel of a matrix. Default method is Welch's periodogram.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)fs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=false: normalize powers to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: number of Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Matrix{Float64}: powers, shape (channels, frequencies)f::Vector{Float64}: frequencies
psd(s; <keyword arguments>)Calculate Power Spectral Density for a 3-D signal array.
Default method is Welch's periodogram.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=false: normalize powers to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: number of Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Array{Float64, 3}: powers, shape (channels, frequencies, epochs)f::Vector{Float64}: frequencies
psd(obj; <keyword arguments>)Calculate Power Spectral Density for a NEURO object.
Default method is Welch's periodogram.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)db::Bool=false: normalize powers to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: number of Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)flim::Tuple{Real, Real}=(0, sr(obj) / 2): frequency bounds for output trimmingdemean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Array{Float64, 3}: powers, shape (channels, frequencies, epochs)f::Vector{Float64}: frequencies (trimmed toflim)
NeuroAnalyzer.psd_rel — Function
psd_rel(s; <keyword arguments>)Calculate relative power spectral density (PSD) for a 1-D signal vector.
Power at each frequency bin is expressed as a fraction of either the total broadband power (when flim is nothing) or the power within the specified frequency band.
Default method is Welch's periodogram.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=false: iftrue, convert power to dBflim::Union{Tuple{Real, Real}, Nothing}=nothing: frequency band(f_low, f_high)used as the reference power;nothinguses total broadband powermethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Vector{Float64}: relative powers (one per frequency bin)f::Vector{Float64}: corresponding frequencies in Hz
psd_rel(s; <keyword arguments>)Calculate relative power spectral density for a 2-D signal matrix.
Default method is Welch's periodogram.
Arguments
s::AbstractMatrix: signal matrix, shape (channels, samples)fs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=false: iftrue, convert power to dBflim::Union{Tuple{Real, Real}, Nothing}=nothing: frequency range to calculate relative power to; if nothing, than calculate relative to total powermethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Matrix{Float64}: relative powers, shape (channels, frequency_bins)f::Vector{Float64}: corresponding frequencies in Hz
psd_rel(s; <keyword arguments>)Calculate relative power spectral density for a 3-D signal array.
Default method is Welch's periodogram.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1db::Bool=false: iftrue, convert power to dBflim::Union{Tuple{Real, Real}, Nothing}=nothing: frequency range to calculate relative power to; if nothing, than calculate relative to total powermethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Array{Float64, 3}: relative powers, shape (channels, frequency_bins, epochs)f::Vector{Float64}: corresponding frequencies in Hz
psd_rel(obj; <keyword arguments>)Calculate relative power spectral density for a NEURO object.
Default method is Welch's periodogram.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)db::Bool=false: iftrue, convert power to dBflim::Union{Tuple{Real, Real}, Nothing}=nothing: frequency range to calculate relative power to; if nothing, than calculate relative to total powermethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
p::Array{Float64, 3}: relative powers, shape (channels, frequency_bins, epochs)f::Vector{Float64}: corresponding frequencies in Hz
NeuroAnalyzer.psd_slope — Function
psd_slope(s; <keyword arguments>)Calculate PSD linear fit and slope for a 1-D signal vector.
Default method is Welch's periodogram.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(0, fs / 2): calculate slope of the total power (default) or frequency rangeflim[1]toflim[2]db::Bool=false: iftrue, convert power to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
lf::Vector{Float64}: linear fitls::Float64: slopes of linear fitf::Vector{Float64}: range of frequencies for the linear fit
psd_slope(s; <keyword arguments>)Calculate PSD linear fit and slope for a 3-D signal array.
Default method is Welch's periodogram.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(0, fs / 2): calculate slope of the total power (default) or frequency rangeflim[1]toflim[2]db::Bool=false: iftrue, convert power to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
lf::Array{Float64, 3}: linear fitls::Matrix{Float64}: slope of linear fitf::Vector{Float64}: range of frequencies for the linear fit
psd_slope(obj; <keyword arguments>)Calculate PSD linear fit and slope for a NEURO object.
Default method is Welch's periodogram.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}=(0, sr(obj) / 2): calculate slope of the total power (default) or frequency range flim[1] to flim[2]db::Bool=false: iftrue, convert power to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Named tuple:
lf::Array{Float64, 3}: linear fitls::Matrix{Float64}: slope of linear fitf::Vector{Float64}: range of frequencies for the linear fit
NeuroAnalyzer.psi — Function
psi(s1, s2; <keyword arguments>)Calculate Phase Slope Index (PSI) for two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1flim::Tuple{Real, Real}=(1, fs / 2 - 1)): frequency limits
Returns
Tuple{Float64, Float64}: PSI value (signal1 -> signal2, signal2 -> signal1)
References
- Nolte, G., Ziehe, A., Nikulin, V. V., Schlögl, A., Krämer, N., Brismar, T., & Müller, K.-R. (2008). Robustly Estimating the Flow Direction of Information in Complex Physical Systems. Physical Review Letters. 2008; 100(23).
psi(obj1, obj2; <keyword arguments>)Calculate Phase Slope Index (PSI) for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2flim::Tuple{Real, Real}=(1, sr(obj1) / 2 - 1)): frequency limits
Returns
Matrix{Float64}: PSI value
psi(obj; <keyword arguments>)Calculate Phase Slope Index (PSI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}=(1, sr(obj) / 2 - 1)): frequency limits
Returns
Array{Tuple{Float64, Float64}, 3}: PSI value
NeuroAnalyzer.rms — Function
rms(s)alculate Root Mean Square (RMS) of a 1-D signal vector.
RMS = √( mean(s²) ) = norm(s) / √length(s)
Arguments
s::AbstractVector: signal vector
Returns
Float64: RMS value
rms(s)Calculate Root Mean Square (RMS) for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Matrix{Float64}: RMS values, shape (channels, epochs)
rms(obj; <keyword arguments>)Calculate Root Mean Square (RMS) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object- `ch::Union{String, Vector{String}, Regex}: list of channels
ep::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj)): default use all epochs
Returns
Matrix{Float64}: RMS
NeuroAnalyzer.rmse — Function
rmse(s1, s2)Calculate Root Mean Square Error (RMSE).
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Float64: RMSE
rmse(s1, s2)Calculate Root Mean Square Error (RMSE) for two 3-D signal arrays.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Matrix{Float64}: RMSE
rmse(obj1, obj2; <keyword arguments>)Calculate Root Mean Square Error (RMSE) for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Matrix{Float64}: RMSE
NeuroAnalyzer.sef — Function
sef(s; <keyword arguments>)Calculate spectral edge frequency (SEF) for a 1-D signal vector.
SEF is the frequency below which x percent of the total power of a given signal are located; typically, x is in the range 75 to 95.
Arguments
s::AbstractVector: signal vectorx::Float64=0.95: thresholdfs::Int64: sampling rate in Hz; must be ≥ 1f::Tuple{Real, Real}=(0, fs / 2): lower and upper frequency bounds, default is total powermethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Float64: spectral edge frequency
sef(s; <keyword arguments>)Calculate spectral edge frequency (SEF) for a 3-D signal array.
SEF is the frequency below which x percent of the total power of a given signal are located; typically, x is in the range 75 to 95.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)x::Float64=0.95: thresholdfs::Int64: sampling rate in Hz; must be ≥ 1f::Tuple{Real, Real}=(0, fs / 2): lower and upper frequency bounds, default is total powermethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: spectral edge frequency
sef(obj; <keyword arguments>)Calculate spectral edge frequency (SEF) for a NEURO object.
SEF is the frequency below which x percent of the total power of a given signal are located; typically, x is in the range 75 to 95.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)x::Float64=0.95: thresholdf::Tuple{Real, Real}=(0, sr(obj) / 2): lower and upper frequency bounds, default is total powermethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-tapered periodogram:stft: short-time Fourier transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: spectral edge frequency
NeuroAnalyzer.seg_extract — Function
seg_extract(m, rc; <keyword arguments>)Extract segment from a matrix.
Arguments
m::AbstractMatrixrc::NTuple{4, Int64}: upper-left corner row and column, bottom-right corner row and columnc::Bool=false: if true, use circular segment; for circular segment the segment is always returned as vectorv::Bool=false: if true, return as vector (matrix m by rows over columns)
Returns
Union{AbstractMatrix, AbstractVector}
seg_extract(m; <keyword arguments>)Extract segment from a matrix using thresholding.
Arguments
m::AbstractMatrixthreshold::Union{Real, Tuple{Real, Real}}=0: thresholdthreshold_type::Symbol=:neq: rule for thresholding::eq: return equal to threshold:neq: return not equal to threshold:geq: return ≥ to threshold:leq: return ≤ to threshold:g: return > to threshold:l: return < to threshold:in: draw region is values are in the threshold values, including threshold boundaries:bin: draw region is values are between the threshold values, excluding threshold boundaries
Returns
Named tuple:
idx::Vector{CartesianIndex{2}}: Cartesian coordinates of matrix elementsbm::Matrix{Bool}: map of the segment
NeuroAnalyzer.seg_mean — Function
seg_mean(seg)Calculate mean of a segment (e.g. spectrogram).
Arguments
seg::AbstractArray
Returns
Vector{Float64}: averaged segment
seg2_mean(seg1, seg2)Calculate mean of two segments (e.g. spectrograms).
Arguments
seg1::AbstractArrayseg2::AbstractArray
Returns
Named tuple:
seg1::Vector{Float64}: averaged segment 1seg2::Vector{Float64}: averaged segment 2
NeuroAnalyzer.seg_select — Function
seg_select(m; <keyword arguments>)Interactive selection of a matrix area.
Arguments
m::AbstractMatrixshape::Symbol=:r: selection shape::r: rectangular:p: point:c: circular
extract::Bool=false: if true, return values of the matrixv::Bool=false: if true, return as vector (matrix m by rows over columns), always true ifshape=:c
Returns
Union{Nothing, <:Real, Tuple{Int64, Int64}, Tuple{Int64, Int64, Int64, Int64}, Union{AbstractMatrix, AbstractVector, Tuple{AbstractVector, AbstractVector}}}: extracted segment or its coordinates
NeuroAnalyzer.senv — Function
senv(obj; <keyword arguments>)Calculate spectral envelope (dominant frequency over time) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)d::Int64=2: minimum distance between peaks in samples; smaller values give a tighter fitthreshold::Union{Real, Nothing}=nothing: spectrogram threshold; powers abovethresholdare zeroed before finding the dominant frequencymethod::Symbol=:stftspectrogram method::stft: short-time Fourier transform:mt: multi-tapered periodogram:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform:cwt: continuous wavelet transformation
pad::Int64=0: number of zeros to appenddb::Bool=true: normalize powers to dBnt::Int64=7: number of Slepian tapers (used by:mt)gw::Real=5: Gaussian width in Hz (used by:gh)ncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)wt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available waveletswlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window length in samplesw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
e::Array{Float64, 3}: spectral envelope, shape (channels, samples, epochs)t::Vector{Float64}: spectrogram time
NeuroAnalyzer.senv_mean — Function
senv_mean(obj; <keyword arguments>)Calculate spectral envelope (mean and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: mean over channels (dims=1), epochs (dims=2), or both (dims=3)d::Int64=2: minimum distance between peaks in samples; smaller values give a tighter fitthreshold::Union{Real, Nothing}=nothing: spectrogram threshold; powers abovethresholdare zeroed before finding the dominant frequencymethod::Symbol=:stftspectrogram method::stft: short-time Fourier transform:mt: multi-tapered periodogram:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform:cwt: continuous wavelet transformation
pad::Int64=0: number of zeros to appenddb::Bool=true: normalize powers to dBnt::Int64=7: number of Slepian tapers (used by:mt)gw::Real=5: Gaussian width in Hz (used by:gh)ncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)wt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available waveletswlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window length in samplesw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
em::Matrix{Float64}: mean spectral envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3eu::Matrix{Float64}: 95% CI upper boundel::Matrix{Float64}: 95% CI lower boundt::Vector{Float64}: time points
NeuroAnalyzer.senv_median — Function
senv_median(obj; <keyword arguments>)Calculate spectral envelope (median and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: median over channels (dims=1), epochs (dims=2), or both (dims=3)d::Int64=2: minimum distance between peaks in samples; smaller values give a tighter fitthreshold::Union{Real, Nothing}=nothing: spectrogram threshold; powers abovethresholdare zeroed before finding the dominant frequencymethod::Symbol=:stftspectrogram method::stft: short-time Fourier transform:mt: multi-tapered periodogram:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform:cwt: continuous wavelet transformation
pad::Int64=0: number of zeros to appenddb::Bool=true: normalize powers to dBnt::Int64=7: number of Slepian tapers (used by:mt)gw::Real=5: Gaussian width in Hz (used by:gh)ncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)wt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available waveletswlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window length in samplesw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
em::Matrix{Float64}: median spectral envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3el::Matrix{Float64}: 95% CI lower boundeu::Matrix{Float64}: 95% CI upper boundt::Vector{Float64}: time points
NeuroAnalyzer.snr — Function
snr(s1, s2)Calculate SNR between two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector
Returns
Float64: SNR
snr(s)Calculate mean-based SNR for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Float64: SNR
References
D. J. Schroeder (1999). Astronomical optics (2nd ed.). Academic Press. ISBN 978-0-12-629810-9, p.278
snr(s; <keyword arguments>)Calculate SNR for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)t::Vector{Float64}: epoch timetype::Symbol=:rms: SNR type::mean: mean-based:rms: RMS-based
Returns
Named tuple:
sn::Matrix{Float64}: SNR for each channel over frequencies 1:Nyquistf::Vector{Float64}: frequencies
snr(obj; <keyword arguments>)Calculate SNR for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)type::Symbol=:rms: SNR type::mean: mean-based:rms: RMS-based
Returns
Named tuple:
sn::Matrix{Float64}: SNR for each channel over frequencies 1:Nyquistf::Vector{Float64}: frequencies
NeuroAnalyzer.snr2 — Function
snr2(s)Calculate RMS-based SNR for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Float64: SNR value
NeuroAnalyzer.spec_flim — Function
spec_flim(p, f; <keyword arguments>)Trim power spectrum or spectrogram array to a range of frequencies.
Arguments
p::AbstractArray: powersf::AbstractVector: frequenciesspec_flim::Tuple{Real, Real}: frequency limits
Returns
Named tuple:
p::Union{Array{Float64, 3}, Array{Float64, 4}}: powersf::Vector{Float64}: frequencies
NeuroAnalyzer.spec_seg — Function
spec_seg(sp, st, sf; <keyword arguments>)Return spectrogram segment.
Arguments
sp::Matrix{Float64}: spectrogram powerssf::Vector{Float64}: spectrogram frequenciesst::Vector{Float64}: spectrogram timet::Tuple{Real, Real}: time boundsf::Tuple{Real, Real}: frequency limits
Returns
Named tuple:
segp::Matrix{Float64}: powerssegs::Vector{Tuple{Float64, Float64}}: segment coordinatestidx::Tuple{Real, Real}: time indicesfidx::Tuple{Real, Real}: frequency indices
spec_seg(sp, sf, st; <keyword arguments>)Return spectrogram segment.
Arguments
sp::AbstractArray: spectrogram powerssf::AbstractVector: spectrogram frequenciesst::AbstractVector: spectrogram timech::Int64: channelt::Tuple{Real, Real}: time boundsf::Tuple{Real, Real}: frequency limits
Returns
Named tuple:
segp::Array{Float64, 3}: segment of powerssegs::Vector{Tuple{Float64, Float64}}: segment coordinatestidx::Tuple{Real, Real}: time indicesfidx::Tuple{Real, Real}: frequency indices
NeuroAnalyzer.spec_tlim — Function
spec_tlim(p, f; <keyword arguments>)Trim spectrogram array to a range of time points.
Arguments
p::AbstractArray: powerst::AbstractVector: time pointsseg::Tuple{Real, Real}: time segment
Returns
Named tuple:
p::Array{Float64, 4}: powerst::Vector{Float64}: time points
NeuroAnalyzer.spectrogram — Function
spectrogram(s; <keyword arguments>)Calculate spectrogram using STFT or multi-tapered method for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling frequencydb::Bool=true: normalize powers to dBmethod::Symbol=:stft: PSD method::stft: short-time Fourier transform:mt: multi-tapered periodogramnt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in sampleswoverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
p::Matrix{Float64}: powersf::Vector{Float64}: frequenciest::Vector{Float64}: time points
spectrogram(s; <keyword arguments>)Calculate spectrogram for each channel of a matrix.
Arguments
s::AbstractMatrix: signal matrix (channels, samples)fs::Int64: sampling frequencydb::Bool=true: normalize powers to dBmethod::Symbol=:stft: PSD method::stft: short-time Fourier transform:mt: multi-tapered periodogram
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length, default is 1 secondwoverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
p::Array{Float64, 3}: powers, shape(freq, time, channels)f::Vector{Float64}: frequenciest::Vector{Float64}: time points
spectrogram(obj; <keyword arguments>)Calculate spectrogram for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: number of zeros to appendmethod::Symbol=:stft: spectrogram estimation method::stft: short-time Fourier transform:mt: multi-tapered periodogram:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform:cwt: continuous wavelet transformation:hht: Hilbert-Huang transform
db::Bool=true: normalize powers to dBnt::Int64=7: number of Slepian tapers (used by:mt)gw::Real=10: Gaussian width in Hzncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)wt::T where {T <: CWT}=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available waveletswlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning window
Returns
Named tuple:
p::Array{Float64, 4}: powers (magnitudes for:cwt), shape(freq, time, channels, epochs)f::Vector{Float64}: frequenciest::Vector{Float64}: time points
NeuroAnalyzer.stationarity — Function
stationarity(obj; <keyword arguments>)Calculate stationarity for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object- `ch::Union{String, Vector{String}, Regex}: list of channels
window::Int64=10: time window in samplesmethod::Symbol=:euclid: stationarity method::mean: mean acrosswindow-long windows:var: variance acrosswindow-long windows:cov: covariance stationarity based on Euclidean distance between covariance matrix of adjacent time windows:hilbert: phase stationarity using Hilbert transformation:adf: Augmented Dickey–Fuller test; returns ADF-test value and p-value (H0: signal is non-stationary; p-value < alpha means that signal is stationary)
Returns
Union{Matrix{Float64}, Array{Float64, 3}}
NeuroAnalyzer.stationarity_hilbert — Function
stationarity_hilbert(s)Calculate phase stationarity using Hilbert transformation for a 1-D signal vector.
Arguments
s::AbstractVector: signal vector
Returns
Vector{Float64}
NeuroAnalyzer.stationarity_mean — Function
stationarity_mean(s; <keyword arguments>)Calculate mean stationarity for a 1-D signal vector.
Signal is split into window-long windows and averaged across windows.
Arguments
s::AbstractVector: signal vectorwindow::Int64: time window in samples
Returns
Vector{Float64}
NeuroAnalyzer.stationarity_var — Function
stationarity_var(s; <keyword arguments>)Calculate variance stationarity for a 1-D signal vector.
Signal is split into window-long windows and variance is calculated across windows.
Arguments
s::AbstractVector: signal vectorwindow::Int64: time window in samples
Returns
Vector{Float64}
NeuroAnalyzer.sumsim — Function
sumsim(s1, s2; theta)Calculate summed similarity using an exponential decay model between two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectortheta::Real: decay parameter
Returns
Float64: summed similarity
Notes
Values of ss are in the range [0, 1]; higher value indicates larger similarity.
sumsim(s1, s2; theta)Calculate summed similarity using an exponential decay model between two 3-D signal arrays.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)theta::Real: decay parameter
Returns
Matrix{Float64}: summed similarity
Notes
Values of ss are in the range [0, 1]; higher value indicates larger similarity.
sumsim(obj; <keyword arguments>)Calculate summed similarity using an exponential decay model between two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2theta::Real: decay parameter
Returns
Matrix{Float64}: summed similarity
Notes
Values of ss are in the range [0, 1]; higher value indicates larger similarity.
NeuroAnalyzer.sym_idx — Function
sym_idx(s)Calculate signal symmetry index (ratio of positive to negative amplitudes) for a 1-D signal vector.
Perfectly symmetrical signal has symmetry of 1.0. Symmetry above 1.0 indicates there are more positive amplitudes.
Arguments
s::AbstractVector: signal vector
Returns
Float64: symmetry index
sym_idx(s)Calculate signal symmetry index (ratio of positive to negative amplitudes) for a 3-D signal array.
Perfectly symmetrical signal has symmetry of 1.0. Symmetry above 1.0 indicates there are more positive amplitudes.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)
Returns
Matrix{Float64}: symmetry index
sym_idx(obj; <keyword arguments>)Calculate signal symmetry index (ratio of positive to negative amplitudes). Perfectly symmetrical signal has symmetry of 1.0. Symmetry above 1.0 indicates there are more positive amplitudes.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Matrix{Float64}: symmetry index
NeuroAnalyzer.tenv — Function
tenv(obj; <keyword arguments>)Calculate temporal envelope for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Named tuple:
e::Array{Float64, 3}: temporal envelope, shape (channels, samples, epochs)t::Vector{Float64}: time points
NeuroAnalyzer.tenv_mean — Function
tenv_mean(obj; <keyword arguments>)Calculate temporal envelope (mean and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: mean over channels (dims=1), epochs (dims=2), or both (dims=3)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Named tuple:
em::Matrix{Float64}: mean temporal envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3el::Matrix{Float64}: 95% CI lower boundeu::Matrix{Float64}: 95% CI upper boundt::Vector{Float64}: time points
NeuroAnalyzer.tenv_median — Function
tenv_median(obj; <keyword arguments>)Calculate temporal envelope (median and 95% CI) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)dims::Int64: median over channels (dims=1), epochs (dims=2), or both (dims=3)d::Int64=32: minimum distance between peaks in samples; smaller values give a tighter fit
Returns
Named tuple:
em::Matrix{Float64}: median temporal envelope, shape (samples, channels) whendims=1, (samples, epochs) whendims=2or (samples, 1) whendims=3el::Matrix{Float64}: 95% CI lower boundeu::Matrix{Float64}: 95% CI upper boundt::Vector{Float64}: time points
NeuroAnalyzer.tkeo — Function
tkeo(s, t; <keyword arguments>)Calculate Teager-Kaiser energy-tracking operator for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectort::AbstractVector=collect(1:length(s)): time pointsmethod::Symbol=:pow::pow: TKEO = x(t)^2 - x(t-1) × x(t+1):der: TKEO = f'(t) - f(t) × f''(t):amp: TKEO = envelope(amplitude)^2
Returns
Vector{Float64}
tkeo(s, t; <keyword arguments>)Calculate Teager-Kaiser energy-tracking operator for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)t::AbstractArray=collect(1:length(s)): time pointsmethod::Symbol=:pow::pow: TKEO = x(t)^2 - x(t-1) × x(t+1):der: TKEO = f'(t) - f(t) × f''(t):amp: TKEO = envelope(amplitude)^2
Returns
Array{Float64, 3}
tkeo(obj; <keyword arguments>)Calculate Teager-Kaiser energy-tracking operator for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object- `ch::Union{String, Vector{String}, Regex}: list of channels
method::Symbol=:pow::pow: TKEO = x(t)^2 - x(t-1) × x(t+1):der: TKEO = f'(t) - f(t) × f''(t):amp: TKEO = envelope(amplitude)^2
Returns
Array{Float64, 3}
NeuroAnalyzer.topo_var — Function
topo_var(obj; <keyword arguments>)Calculate the variance across channels at each time point of an ERP/ERF object (epoch 1 = the trial-averaged waveform), returning a time series of spatial variability.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object: must be an ERP or ERF objectch::Union{String, Vector{String}, Regex}: channel name(s)
Returns
Vector{Float64}: topographical variance
NeuroAnalyzer.total_power — Function
total_power(s; <keyword arguments>)Calculate total power for a 1-D signal vector.
Arguments
s::AbstractVector: signal vectorfs::Int64: sampling rate in Hz; must be ≥ 1method::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Float64: total power
total_power(s; <keyword arguments>)Calculate total power for a 3-D signal array.
`# Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)fs::Int64: sampling rate in Hz; must be ≥ 1method::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles, for tuple a variable number of cycles is used per frequency:ncyc=linspace(ncyc[1], ncyc[2], nfrq), wherenfrqis the length of0:(fs / 2)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: total power
total_power(obj; ch, method, nt, wlen, woverlap, w, ncyc, gw, wt)Calculate total power for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)method::Symbol=:welch: PSD estimation method::welch: Welch's periodogram (default):fft: plain FFT periodogram:mt: multi-tapered periodogram:stft: short-time Fourier transform averaged over segments:mw: Morlet wavelet convolution:gh: Gaussian filter + Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)demean::Bool=true: subtract DC component before estimating PSD
Returns
Matrix{Float64}: total power
NeuroAnalyzer.tpt_analyze — Function
tpt_analyze(nn_seg)Analyze pinches in TPT recording.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Named tuple:
n::Int64: number of pinchest_mean::Float64: mean interval between pinches [ms]t_median::Float64: median interval between pinches [ms]t_rmssd::Float64: ("root mean square of successive differences"), the square root of the mean of the squares of the successive differences between adjacent pinches [ms]t_sdsd::Float64: ("standard deviation of successive differences"), the standard deviation of the successive differences between adjacent pinches [ms]
Note
Return nothing if no pinches are detected.
NeuroAnalyzer.tpt_detect — Function
tpt_detect(obj)Detect pinches in TPT recording.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Vector{Int64}: index of pinches locations
NeuroAnalyzer.transform — Function
transform(s; <keyword arguments>)Calculate Fourier or Hilbert transformation for a 3-D signal array.
Arguments
s::AbstractArray: signal array, shape (channels, samples, epochs)pad::Int64=0: (FFT only) number of zeros to appendh::Bool=false: if true, use Hilbert transform instead of FFTdb::Bool=false: normalize powers to dBnf::Bool=false: (FFT only) if true, return negative and positive frequency coefficients; otherwise positive frequencies only
Returns
Named tuple:
c::Array{ComplexF64, 3}: Fourier or Hilbert coefficientsa::Array{Float64, 3}: amplitudesp::Array{Float64, 3}: powers- `ph::Array{Float64, 3}: phases in radians
transform(obj; <keyword arguments>)Calculate Fourier/Hilbert transform for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)pad::Int64=0: (FFT only) number of zeros to appendh::Bool=false: if true, use Hilbert transform instead of FFTdb::Bool=false: normalize powers to dBnf::Bool=false: (FFT only) if true, return negative and positive frequency coefficients; otherwise positive frequencies only
Returns
Named tuple:
c::Array{ComplexF64, 3}: Fourier or Hilbert coefficientsa::Array{Float64, 3}: amplitudesp::Array{Float64, 3}: powers- `ph::Array{Float64, 3}: phases in radians
NeuroAnalyzer.vartest — Function
vartest(obj; <keyword arguments>)Calculate variance F-test for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object- `ch::Union{String, Vector{String}, Regex}: list of channels
Returns
Named tuple:
f::Array{Float64, 3}p::Array{Float64, 3}
vartest(obj1, obj2; <keyword arguments>)Calculate variance F-test for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2
Returns
Named tuple:
f::Array{Float64, 3}p::Array{Float64, 3}
NeuroAnalyzer.wpli — Function
wpli(s1, s2; <keyword arguments>)Calculate weighted PLI (Phase Locking Index) for two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vectordebiased::Bool=false: iftrue, calculate debiased wPLI
Returns
Named tuple:
pv::Float64: wPLI valuesd::Vector{Float64}: signal difference (s1 - s2)phd::Vector{Float64}: phase difference (s1 - s2)s1ph::Vector{Float64}: signal 1 phases2ph::Vector{Float64}: signal 2 phase
wpli(obj1, obj2; <keyword arguments>)Calculate weighted PLI (Phase Locking Index) for two NEURO objects.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2debiased::Bool=false: iftrue, calculate debiased wPLI
Returns
Named tuple:
pv::Matrix{Float64}: PLI valuesd::Array{Float64, 3}: signal difference (s1 - s2)phd::Array{Float64, 3}: phase difference (s1 - s2)s1ph::Array{Float64, 3}: signal 1 phases2ph::Array{Float64, 3}: signal 2 phase
wpli(obj; <keyword arguments>)Calculate weighted PLI (Phase Locking Index) for a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)debiased::Bool=false: iftrue, calculate debiased wPLI
Returns
Array{Float64, 3}: wPLI value
NeuroAnalyzer.xcor — Function
xcor(s1, s2; <keyword arguments>)Calculate cross-correlation between two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector (must be the same length ass1)l::Int64=round(Int64, min(length(s1) - 1, 10 * log10(length(s1)))): maximum lag in samples; lags range is−l : ldemean::Bool=true: subtract the mean before computing cross-correlationbiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scor()(biasedis ignored):stat: useStatsBase.crosscor()(biasedis ignored)
Returns
Array{Float64, 3}: cross-correlation at lags−l:l
xcor(s1, s2; <keyword arguments>)Calculate cross-correlation for a pair of 2-D arrays.
Arguments
s1::AbstractMatrix: signal matrix (channels, epochs)s2::AbstractMatrix: signal matrix, same size ass1l::Int64=round(Int64, min(size(s1[1, :, 1], 1) - 1, 10 * log10(size(s1[1, :, 1], 1)))): maximum lag in samples; lags range is−l : ldemean::Bool=true: subtract the mean before computing cross-correlationbiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scor()(biasedis ignored):stat: useStatsBase.crosscor()(biasedis ignored)
Returns
Array{Float64, 3}
xcor(s1, s2; <keyword arguments>)Calculate cross-correlation for two 3-D signal arrays.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)l::Int64=round(Int64, min(size(s1[1, :, 1], 1) - 1, 10 * log10(size(s1[1, :, 1], 1)))): maximum lag in samples; lags range is−l : ldemean::Bool=true: subtract the mean before computing cross-correlationbiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scor()(biasedis ignored):stat: useStatsBase.crosscor()(biasedis ignored)
Returns
Array{Float64, 3}
xcor(obj1, obj2; <keyword arguments>)Calculate cross-correlation between selected channels of two NEURO objects.
For ERP/ERF objects the trial-averaged cross-correlation is prepended as epoch 1.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2l::Real=1: maximum lag in samples; lags range is−l : ldemean::Bool=true: subtract the mean before computing cross-correlationbiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scor()(biasedis ignored):stat: useStatsBase.crosscor()(biasedis ignored)
Returns
Named tuple:
xc::Array{Float64, 3}: cross-correlationlags::Vector{Float64}: lag values in seconds
NeuroAnalyzer.xcov — Function
xcov(s1, s2; <keyword arguments>)Calculate cross-covariance between two 1-D signal vectors.
Arguments
s1::AbstractVector: signal vectors2::AbstractVector: signal vector (must be the same length ass1)l::Int64=round(Int64, min(length(s1) - 1, 10 * log10(length(s1)))): maximum lag in samples; lags range is−l : ldemean::Bool=true: subtract the mean before computing cross-covariancebiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scov():stat: useStatsBase.crosscov()(biasedis ignored)
Returns
Array{Float64, 3}: cross-covariance at lags−l:l
xcov(s1, s2; <keyword arguments>)Calculate cross-covariance for a pair of 2-D arrays.
Arguments
s1::AbstractMatrix: signal matrix (channels, epochs)s2::AbstractMatrix: signal matrix, same size ass1l::Int64=round(Int64, min(size(s1, 2), 10 * log10(size(s1, 2)))): lags range is-l:ldemean::Bool=true: subtract the mean before computing cross-covariancebiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scov():stat: useStatsBase.crosscov()(biasedis ignored)
Returns
Array{Float64, 3}: cross-covariance, shape (1, 2l+1, ep_n)
xcov(s1, s2; <keyword arguments>)Calculate cross-covariance for a pair of 3-D arrays.
Arguments
s1::AbstractArray: signal array, shape (channels, samples, epochs)s2::AbstractArray: signal array, shape (channels, samples, epochs)l::Int64=round(Int64, min(size(s1, 2), 10 * log10(size(s1, 2)))): lags range is-l:ldemean::Bool=true: subtract the mean before computing cross-covariancebiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scov():stat: useStatsBase.crosscov()(biasedis ignored)
Returns
Array{Float64, 3}: cross-covariance, shape (chn, 2l+1, epn)
xcov(obj1, obj2; <keyword arguments>)Calculate cross-covariance between selected channels of two NEURO objects.
For ERP/ERF objects the trial-averaged cross-covariance is prepended as epoch 1.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO objectobj2::NeuroAnalyzer.NEURO: input NEURO objectch1::Union{String, Vector{String}, Regex}: channel name(s) inobj1ch2::Union{String, Vector{String}, Regex}: channel name(s) inobj2ep1::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj1)): epoch number(s) inobj1ep2::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=_c(nepochs(obj2)): epoch number(s) inobj2l::Real=1: lags range is-l:ldemean::Bool=true: subtract the mean before computing cross-covariancebiased::Bool=true: use biased (÷ n) or unbiased (÷ n−lag) estimatormethod::Symbol=:sum: computation method::sum: manual lag-shifted dot product:cov: use Julia'scov():stat: useStatsBase.crosscov()(biasedis ignored)
Returns
Named tuple:
xc::Array{Float64, 3}: cross-covariancelags::Vector{Float64}: lag values in seconds
NeuroAnalyzer.zipratio — Function
zipratio(obj)Calculate the zip ratio for a NEURO object data as a measure of signal complexity.
The zip ratio is defined as the size of the maximally compressed file (zip -9) divided by the size of the raw (uncompressed) CSV export. Lower values indicate lower complexity (higher compressibility).
zipratio() requires the zip command (Linux/macOS) or zip.exe (Windows) to be available on PATH.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object
Returns
Float64: ratio of compressed to uncompressed data size, in the range (0, 1]
Model
NeuroAnalyzer.efield2d — Function
efield2d(; <keyword arguments>)Create model of 2-dimensional electric field.
Arguments
q::Vector{Int64}: charges valuesqx::Vector{Int64}: charges X positions (1 to 100)qy::Vector{Int64}: charges Y positions (1 to 100)
Returns
Named tuple:
qq::Vector{Vector{Float64}}: charges positionsnorm_e::Matrix{Float64}: normalized electric fieldex::Matrix{Float64}: electric field X axis vectorey::Matrix{Float64}: electric field Y axis vector
NeuroAnalyzer.tes_model — Function
tes_model(; <keyword arguments>)Create model of TES stimulation.
Arguments
anode::String: anode locationcathode::String: cathode locationanode_curr::Real=2.0: anode current [mA]cathode_curr::Real=-2.0: cathode current [mA]
Returns
GLMakie.Figure
Notes
This is a very initial version, simplified model - just superficial spread of the electric field
To do
Model spread of electric field at the cortical surface - reduce charge for skull resistance
Plot
NeuroAnalyzer.add_pl — Function
add_pl(fig, pl; <keyword arguments>)Overlay a locations plot pl onto the top-right corner of fig, making the white background of pl transparent so only the electrode markers are visible.
Arguments
p1::GLMakie.Figure: primary plotp2::GLMakie.Figure: locations plot to overlay
Returns
GLMakie.Figure: the plotted figure:figwith the locations overlay applied in-place
NeuroAnalyzer.add_to_canvas — Function
add_to_canvas(c1, c2; <keyword arguments>)Composite c2 onto c1 at position (x, y), optionally adding a title label below c2 and/or saving the result to a PNG file.
Arguments
c1::Cairo.CairoSurfaceBase{UInt32}: destination canvasc2::Cairo.CairoSurfaceBase{UInt32}: source canvas to place onc1x::Int64: left edge ofc2inc1coordinatesy::Int64: top edge ofc2inc1coordinatestitle::String="": label placed centred belowc2file_name::String="": if non-empty, save as PNG at this path
Returns
c::Cairo.CairoSurfaceBase{UInt32}
NeuroAnalyzer.add_topmargin_canvas — Function
add_topmargin_canvas(c1, c2)Create a new canvas with c2 placed at the top and c1 below it, effectively adding a top margin of c2.height pixels above c1.
Arguments
c1::Cairo.CairoSurfaceBase{UInt32}: main canvasc2::Cairo.CairoSurfaceBase{UInt32}: canvas to place abovec1
Returns
Cairo.CairoSurfaceBase{UInt32}: combined canvas of heightc1.height + c2.height
NeuroAnalyzer.plot — Function
plot(obj; <keyword arguments>)Plot signal from a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}="all": channel name or list of channel namesep::Int64=1: first epoch to displayseg::Tuple{Real, Real}=(0, 10): segment (from, to) in seconds to display, default is 10 seconds or less if single epoch is shortertm::Union{Nothing, Int64, Vector{Int64}}=nothing: time markers (in milliseconds) for vertical lines, useful for adding topoplots at these time points (for ERP/ERF)rt::Union{Nothing, Real, AbstractVector}=nothing: response time(s) for each epoch; if provided, the response time line will be plotted over the:stackplot (for ERP/ERF)xlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlemarkers::Bool=true: draw markers if availablescale::Bool=true: draw scalesgroup_ch::Bool=true: group channels by typetype::Symbol=:normal: plot type::normal: standard multi-channel plot:butterfly: butterfly plot showing all channels overlaid:stack: for ERP/ERF/MEP:topo: for ERP/ERF
avg::Bool=false: plot averaged channel in butterfly plotci95::Bool=false: plot averaged channels and 95% CI in butterfly plotn_channels::Int64=20: number of visible channelsn_epochs::Int64=5: number of visible epochscb::Bool=true: iftrue, show color bar (for ERP/ERF/MEP)cb_title::String="default": color bar title (for ERP/ERF/MEP)peaks::Bool=true: iftrue, draw peak markers (for ERP/ERF/MEP)leg::Bool=true: iftrue, add legend with channel labels (for ERP/ERF/MEP)yrev::Bool=false: iftrue, reverse the y-axis (for ERP/ERF/MEP)smooth::Bool=false: iftrue, smooth the image using Gaussian blur (for ERP/ERF/MEP)ks::Int64=3: kernel size of the Gaussian blur (larger kernel means more smoothing) (for ERP/ERF/MEP)zl::Bool: iftrue, draw a dashed line at t = 0 (for ERP/ERF/MEP)mono::Bool=false: iftrue, use a monochrome paletteres::Int64=1: resampling factor (draw everyres-nth sample)snap::Bool=true: snap to grid when placing markersgui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure: the plotted figure
plot(obj1, obj2; <keyword arguments>)Plot two signals from NEURO objects for comparison.
Arguments
obj1::NeuroAnalyzer.NEURO: first NEURO objectobj2::NeuroAnalyzer.NEURO: second NEURO objectch::Union{String, Vector{String}, Regex}="all": channel name or list of channel namesseg::Tuple{Real, Real}=(0, 10): segment (from, to) in seconds to display, default is 10 seconds or less if single epoch is shorterxlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlescale::Bool=true: draw scalesgroup_ch::Bool=true: group channels by typen_channels::Int64=20: number of visible channelsn_epochs::Int64=5: number of visible epochsres::Int64=1: resampling factor (draw everyres-nth sample)gui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure
plot(t, s; <keyword arguments>)Plot a continuous signal with time and amplitude axes.
Arguments
t::AbstractVector: time points (must match length ofs)s::AbstractVector: signal dataxlabel::String="Time [s]": x-axis labelylabel::String="Amplitude": y-axis labeltitle::String="": plot title
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot2canvas — Function
plot2canvas(p)Render a Plots.Plot (GR backend) to an RGB Cairo surface.
Arguments
p::Plots.Plot{Plots.GRBackend}
Returns
Cairo.CairoSurfaceBase{UInt32}
plot2canvas(fig)Render a GLMakie.Figure to an RGB Cairo surface via a temporary PNG file.
Arguments
fig::GLMakie.Figure
Returns
Cairo.CairoSurfaceBase{UInt32}
NeuroAnalyzer.plot_bar — Function
plot_bar(s; <keyword arguments>)Create a bar plot from signal data with customizable labels and styling.
Arguments
s::AbstractVector: signal vectorglabels::Vector{String}: group labels for x-axis ticksxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_box — Function
plot_box(s; <keyword arguments>)Create a box plot from matrix data with customizable labels and styling.
Arguments
s::AbstractMatrix: matrix where each row represents a group for which to plot a box plotglabels::Vector{String}: group labels for x-axis ticksxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_ci — Function
plot_ci(s, s_ci_l, s_ci_h, t; <keyword arguments>)Plot a signal with its confidence interval (shaded region) over time.
Arguments
s::AbstractVector: signal vector containing the mean valuess_l::AbstractVector: lower bound of the confidence intervals_u::AbstractVector: upper bound of the confidence intervalt::AbstractVector: time points corresponding to the signal valuesxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_coherence — Function
plot_coherence(coh, f; <keyword arguments>)Plot single-channel coherence as a function of frequency.
Arguments
coh::Vector{Float64}: coherence values (must match length off)f::Vector{Float64}: frequency values (Hz)flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotxlabel::String="Frequency [Hz]": x-axis labelylabel::String="Coherence": y-axis labeltitle::String="": plot titlefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
plot_coherence(coh, f; <keyword arguments>)Plot multi-channel coherence as a function of frequency.
Arguments
coh::Matrix{Float64}: coherence matrix, shape (channels, frequencies)f::Vector{Float64}: frequency values (Hz)clabels::Vector{String}=string.(1:size(coh, 1)): channel pair labelsflim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotxlabel::String="Frequency [Hz]": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)avg::Bool=false: iftrue, plot averaged coherenceci95::Bool=false: iftrue, plot mean and ±95% CI of averaged coherenceleg::Bool=true: iftrue, add legend with channel labelsmono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_compose — Function
plot_compose(vfig; <keyword arguments>)Compose a grid of GLMakie.Figure plots into a single figure using the specified row × column layout.
Empty plots are added automatically when length(vfig) < layout[1]*layout[2] so the grid is always fully populated.
Arguments
vfig::Vector{GLMakie.Figure}: plots to composelayout::Tuple{Int64, Int64}: grid dimensions as(rows, columns)
Returns
GLMakie.Figure: the plotted figure: composite figure
NeuroAnalyzer.plot_connectivity_circle — Function
plot_connectivity_circle(m; <keyword arguments>)Plot a circular connectivity diagram for a matrix of connectivities.
Arguments
m::AbstractMatrix: connectivity matrix (must be square, channel vs. channel)clabels=Vector{String}: channels labels (must match matrix dimensions)title::String="": plot titlethreshold::Union{Nothing, Real, Tuple{Real, Real}}=nothing: threshold for marking regions- if
Real, use a single threshold value - if
Tuple{Real, Real}, use a range for:inor:binthresholding
- if
threshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_cont — Function
plot_cont(obj; <keyword arguments>)Plot continuous signal with interactive editing.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}="all": channel name(s)seg::Tuple{Real, Real}=(0, 10): time segment to display in seconds (from, to), default is 10 seconds or less if single epoch is shorterxlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlemono::Bool=false: iftrue, use a monochrome palettemarkers::Bool: iftrue, draw markers if availablescale::Bool=true: iftrue, draw scale referencegroup_ch::Bool=true: iftrue, group channels by type (e.g. EEG, EOG, ECG)type::Symbol=:normal: plot type::normal: standard multi-channel plot:butterfly: butterfly plot showing all channels overlaid
avg::Bool=false: iftrue, plot averaged channel in butterfly plotci95::Bool=false: iftrue, plot mean and ±95% confidence interval of averaged channels in butterfly plotn_channels::Int64=20: maximum number of visible channelsres::Int64=1: resampling factor (draw everyres-nth sample)snap::Bool=true: iftrue, snap to grid when placing markersgui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure
plot_cont(obj1, obj2; <keyword arguments>)Plot two continuous signals overlayed for comparison.
Arguments
obj1::NeuroAnalyzer.NEURO: input NEURO object, will be drawn in blueobj2::NeuroAnalyzer.NEURO: input NEURO object, will be drawn in blackch::Union{String, Vector{String}, Regex}="all": channel name(s)seg::Tuple{Real, Real}=(0, 10): time segment to display in seconds (from, to), default is 10 seconds or less if single epoch is shorterxlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlescale::Bool=true: iftrue, draw scale referencegroup_ch::Bool=true: iftrue, group channels by type (e.g. EEG, EOG, ECG)n_channels::Int64=20: maximum number of visible channelsres::Int64=1: resampling factor (draw everyres-nth sample)gui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_dipole2d — Function
plot_dipole2d(d; <keyword arguments>)Plot a 3D dipole in 2D views (top, side, front).
Arguments
d::NeuroAnalyzer.DIPOLE: dipole object withpos(position) andmag(magnitude) fieldspos::Tuple{Float64, Float64, Float64}: dipole position (x, y, z) in brain volume (range: -1.0 to +1.0)mag::Tuple{Float64, Float64, Float64}: dipole magnitude vector (mx, my, mz)
Returns
GLMakie.Figure: the plotted figure
Notes
- Brain volume is within -1.0 to +1.0 for all axes (x, y, z).
- The dipole position is marked with a red dot, and its magnitude is shown as a red line.
NeuroAnalyzer.plot_dipole3d — Function
plot_dipole3d(d; <keyword arguments>)Plot a 3D dipole inside a schematic brain model.
Arguments
d::NeuroAnalyzer.DIPOLE: dipole object withpos(position) andmag(magnitude) fieldspos::Tuple{Float64, Float64, Float64}: dipole position (x, y, z) in brain volume (range: -1.0 to +1.0)mag::Tuple{Float64, Float64, Float64}: dipole magnitude vector (mx, my, mz)
project::Bool=true: iftrue, plot lines projecting the dipole onto the x, y, and z axes
Returns
GLMakie.Figure: the plotted figure
Notes
- Brain volume is within -1.0 to +1.0 for all axes (x, y, z).
- The dipole position is marked with a red dot.
- If
project=true, dashed lines show the dipole's projection onto the coordinate planes.
NeuroAnalyzer.plot_dots — Function
plot_dots(s; <keyword arguments>)Create a dots plot from matrix data with customizable labels and styling.
Arguments
s::AbstractArray: matrix where each row represents a group for which to create a violin plotglabels::Vector{String}: group labels for x-axis ticksxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_dwc — Function
plot_dwc(dc; <keyword arguments>)Plot discrete wavelet decomposition (DWC) coefficients showing signal decomposition across different scales.
Arguments
dc::Matrix{Float64}: matrix where each row represents wavelet coefficients at a specific decomposition leveln::Int64=size(dc, 1) - 1: number of decomposition levels to plott::AbstractVector: time points corresponding to the signal values
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_efield2d — Function
plot_efield2d(; <keyword arguments>)Plot a 2D electric field generated by point charges.
Arguments
q::Vector{Int64}: charges values (positive or negative integers)qx::Vector{Float64}: x-axis positions of chargesqy::Vector{Float64}: y-axis positions of chargesd::Int64: density of field vectors; currently unused in the function, but kept for future compatibility
Returns
GLMakie.Figure: the plotted figure with electric field streamlines and charge markers
Notes
- The electric field is computed using Coulomb's law for point charges.
- Positive charges are plotted in red, negative charges in blue, with size proportional to charge magnitude.
- The field is visualized using streamlines, with color indicating field strength.
NeuroAnalyzer.plot_empty — Function
plot_empty()Return an empty GLMakie.Figure, useful for padding a grid of plots.
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_ep — Function
plot_ep(t, s; <keyword arguments>)Plot epoched signal with interactive editing.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}="all": channel name or list of channel namesep::Int64=1: first epoch to plotxlabel::String="default": x-axis label, default is Time [s]ylabel::String="default": y-axis label, default is no labeltitle::String="default": plot titlemono::Bool=false: iftrue, use a monochrome palettemarkers::Bool: draw markers if availablescale::Bool=true: draw scalegroup_ch::Bool=true: group channels by typetype::Symbol=:normal: plot type::normal: standard multi-channel plot:butterfly: butterfly plot showing all channels overlaid
avg::Bool=false: plot averaged channel in butterfly plotci95::Bool=false: plot averaged channels and 95% CI in butterfly plotn_channels::Int64=20: number of visible channelsn_epochs::Int64=5: number of visible epochsres::Int64=1: resampling factor (draw everyres-nth sample)gui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_erop — Function
plot_erop(fig, f; <keyword arguments>)Plot the power spectrum of Event-Related Oscillations (ERO) with customizable visualization.
Arguments
sp::AbstractArray: ERO power values, shape (frequency, powers)sf::AbstractVector: vector of frequency values in Hzdb::Bool=true: whether to display power values in decibelsxlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotcb::Bool=true: iftrue, show colorbarunits::String="μV": power unitsmono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_eros — Function
plot_eros(s, f, t; <keyword arguments>)Plot an Event-Related Oscillations (ERO) spectrogram with customizable visualization options.
Arguments
sp::AbstractArray: ERO spectrogram power values, shape (frequency, time, powers)sf::AbstractVector: vector of frequency values in Hzst::AbstractVector: vector of time values in secondsdb::Bool=true: whether to display power values in decibelsfrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plottm::Union{Nothing, Int64, Vector{Int64}} = nothing: time markers (in milliseconds) to be plot as vertical lines, useful for adding topoplots at these time pointsxlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlecb::Bool=true: iftrue, show colorbarmono::Bool=false: iftrue, use a monochrome paletteunits::String="μV": power unitssmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothing
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_erp — Function
plot_erp(t, s; <keyword arguments>)Plot Event-Related Potential/Field (single channel).
Arguments
t::Union{AbstractVector, AbstractRange}: time values (in seconds)s::AbstractVector: signal vector (ERP/ERF data)rt::Union{Nothing, Real}=nothing: response time (in milliseconds)xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titleyrev::Bool=false: iftrue, reverse the y-axiszl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
plot_erp(t, s; <keyword arguments>)Plot multi-channel Event-Related Potential/Field with optional averaging and confidence intervals.
Arguments
t::Union{AbstractVector, AbstractRange}: time values (in seconds).s::AbstractMatrix: signal data, shape (channels, samples)rt::Union{Nothing, Real}=nothing: response time (in milliseconds)clabels::Vector{String}=string.(1:size(s, 1)): channel labels (default: auto-generated)xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titleyrev::Bool=false: iftrue, reverse the y-axisavg::Bool=true: iftrue, plot averaged ERPci95::Bool=false: iftrue, plot mean and ±95% CIleg::Bool=true: iftrue, add legend with channel labelszl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
plot_erp(obj; <keyword arguments>)Plot Event-Related Potential/Field (ERP/ERF) from a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object containing ERP/ERF datach::Union{String, Vector{String}, Regex}: channel name(s)tm::Union{Nothing, Int64, Vector{Int64}}=nothing: time markers (in milliseconds) to plot as vertical lines, useful for adding topoplots at these time pointsxlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlecb::Bool=true: iftrue, show color barcb_title::String="default": color bar titlepeaks::Bool=true: iftrue, draw peak markersleg::Bool=true: iftrue, add legend with channel labelstype::Symbol=:normal: plot type::normal: standard ERP plot:gfp: plot Global Field Power:stack: stacked epochs/channels:topo: topographical plot
yrev::Bool=false: iftrue, reverse the y-axisavg::Bool=true: iftrue, plot averaged ERPci95::Bool=false: iftrue, plot mean and ±95% CIsmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingrt::Union{Nothing, Real, AbstractVector}=nothing: response time for each epoch; if provided, the response time line will be plotted over the:stackplotsort_epochs::Bool=false:: sort epochs by rt vectorzl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palettegui::Bool=false: ignored
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_erp_stack — Function
plot_erp_stack(t, s; <keyword arguments>)Plot stacked Event-Related Potentials/Fields.
Arguments
t::AbstractVector: time points (in seconds)s::AbstractMatrix: ERP/ERF data, shape (epochs, samples)rt::Union{Nothing, AbstractVector}=nothing: response time for each epoch; if provided, the response time line will be plotted over the:stackplotclabels::Vector{String}=string.(1:size(s, 1)): channel labels (default: auto-generated)xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlecb::Bool=true: iftrue, show color barcb_title::String="": color bar titlesmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingzl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_erp_topo — Function
plot_erp_topo(locs, t, s; <keyword arguments>)Plot topographical maps of Event-Related Potentials/Fields.
Arguments
locs::DataFrame: channel locations with columns:channel,labels,loc_radius,loc_theta,loc_x,loc_y, `loc_z,loc_radius_sph,loc_theta_sph,loc_phi_spht::Vector{Float64}: time points (in seconds)s::Matrix{Float64}: ERP/ERF data, shape (channels, samples)rt::Union{Nothing, Real}=nothing: response time (in milliseconds)clabels::Vector{String}=string.(1:size(s, 1)): channel labels (default: auto-generated)xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titleyrev::Bool=false: iftrue, reverse the y-axiscart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planeshead::Bool=true: iftrue, draw head outlinezl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_fi — Function
plot_fi(fi, st; <keyword arguments>)Plot instantaneous frequency over time from time-frequency analysis (e.g., Hilbert-Huang Transform).
Arguments
fi::Vector{Float64}: vector of instantaneous frequency values in Hzst::Vector{Float64}: vector of time points in seconds corresponding to frequency valuesxlabel::String="default": x-axis label, default is Time [s]ylabel::String="default": y-axis label, default is Power [μV^2/Hz]title::String="default": plot title
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_filter — Function
plot_filter(; <keyword arguments>)Plot filter response with interactive controls for various filter types.
Arguments
fs::Int64: sampling rate in Hz; must be ≥ 1fprototype::Symbol: filter prototype::fir: FIR filter:firls: weighted least-squares FIR filter:remez: Remez FIR filter:butterworth: IIR filter:chebyshev1IIR filter:chebyshev2IIR filter:ellipticIIR filter:iirnotch: second-order IIR notch filter
ftype::Union{Nothing, Symbol}=nothing: filter type::lp: low pass:hp: high pass:bp: band pass:bs: band stop
cutoff::Union{Real, Tuple{Real, Real}}: filter cutoff in Hz- for
:lp/:hp: single frequency - for
:bp/:bs: frequency range (f1, f2)
- for
order::Union{Nothing, Int64}=nothing: filter order (number of taps for FIR, filter order for IIR)rp::Union{Nothing, Real}=nothing: maximum ripple amplitude in dB in the pass band; default: 0.5 dBrs::Union{Nothing, Real}=nothing: minimum ripple attenuation in dB in the stop band; default: 20 dBbw::Union{Nothing, Real}=nothing: transition band width in Hz for:firls,:remezand:iirnotchfiltersw::Union{Nothing, AbstractVector}=nothing: window for:firfilter (default is Hamming window) or weights for:firlsfilterflim::Tuple{Real, Real} = (0, fs / 2): frequency limitsmono::Bool=false: iftrue, use a monochrome palettegui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure, ifgui = falseUnion{Vector{Float64}, ZeroPoleGain{:z, ComplexF64, ComplexF64, Float64}, Biquad{:z, Float64}}: returns the filter object, ifgui=true
Notes
- For IIR filters (
:butterworth,:chebyshev1, etc.), default ripple values are:- Passband ripple (
rp): 0.5 dB - Stopband attenuation (
rs): 20 dB
- Passband ripple (
- For
:ellipticfilters, defaults are 0.5 dB and 40 dB respectively. - For FIR filters, window length must be odd.
- Bandwidth (
bw) is required for:firls,:remez, and:iirnotchfilters.
plot_filter(obj, <keyword arguments>)Plot the frequency response of a digital filter with customizable visualization options.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object (used only for sampling rate information)n::Int64: signal length in samples for frequency response calculationfprototype::Symbol: filter prototype::fir: FIR filter:firls: weighted least-squares FIR filter:remez: Remez FIR filter:butterworth: IIR filter:chebyshev1IIR filter:chebyshev2IIR filter:ellipticIIR filter:iirnotch: second-order IIR notch filter
ftype::Union{Nothing, Symbol}=nothing: filter type::lp: low pass:hp: high pass:bp: band pass:bs: band stop
cutoff::Union{Real, Tuple{Real, Real}}: filter cutoff in Hz- for
:lp/:hp: single frequency - for
:bp/:bs: frequency range (f1, f2)
- for
order::Union{Nothing, Int64}=nothing: filter order (number of taps for FIR, filter order for IIR)rp::Union{Nothing, Real}=nothing: maximum ripple amplitude in dB in the pass band; default: 0.0025 dB for:elliptic, 2 dB for othersrs::Union{Nothing, Real}=nothing: minimum ripple attenuation in dB in the stop band; default: 40 dB for:elliptic, 20 dB for othersbw::Union{Nothing, Real}=nothing: transition band width in Hz for:firls,:remezand:iirnotchfiltersw::Union{Nothing, AbstractVector}=nothing: window for:firfilter (default is Hamming window) or weights for:firlsfilter- `flim::Tuple{Real, Real}=(0, sr(obj) / 2): frequency limit
mono::Bool=false: iftrue, use a monochrome palettegui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure, ifgui=trueUnion{Vector{Float64}, ZeroPoleGain{:z, ComplexF64, ComplexF64, Float64}, Biquad{:z, Float64}}: the filter object, ifgui=false
NeuroAnalyzer.plot_gfp — Function
plot_gfp(t, s; <keyword arguments>)Plot Global Field Power (GFP).
Arguments
t::Union{AbstractVector, AbstractRange}: time points (in seconds)g::AbstractVector: GFP valuesrt::Union{Nothing, Real}=nothing: response time (in milliseconds)xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlezl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_gridlocs — Function
plot_gridlocs()Plot a simplified grid layout of standard 10-20 EEG channels for reference.
Arguments
mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_heatmap — Function
plot_heatmap(m; <keyword arguments>)Plot a heatmap with customizable labels, styling, and optional threshold highlighting.
Arguments
m::AbstractMatrix: matrix containing values to plot as heatmapx::AbstractVector: x-axis coordinates for each column of the matrixy::AbstractVector: y-axis coordinates for each row of the matrixxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palettecb::Bool=true: iftrue, show colorbarcb_title::String="": colorbar titlethreshold::Union{Nothing, Real, Tuple{Real, Real}}=nothing: threshold for marking regions- if
Real, use a single threshold value - if
Tuple{Real, Real}, use a range for:inor:binthresholding
- if
threshold_type::Symbol=:neq: rule for threshold-based highlighting::eq: draw region where values are not equal to threshold:neq: draw region where values are equal to threshold:geq: draw region where values are ≥ threshold:leq: draw region where values are ≤ threshold:g: draw region where values are > threshold:l: draw region where values are < threshold
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_histogram — Function
plot_histogram(s; <keyword arguments>)Plot histogram of signal data with optional statistical overlays and comparison.
Arguments
s::AbstractVector: signal vectorx::Union{Nothing, Real}=nothing: optional value to plot as vertical reference linetype::Symbol: type of histogram to plot::hist: Standard histogram (default):kd: Kernel density estimate
bins::Int64=15: number of histogram binsxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titledraw_mean::Bool=true: iftrue, draw mean value linedraw_median::Bool=true: iftrue, draw median value linemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_icatopo — Function
plot_icatopo(obj; <keyword arguments>)Create a topographical plot of Independent Component Analysis (ICA) components from EEG/MEG data.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO object containing channel locations and dataic::Matrix{Float64}: ICA component matrix IC(1)..IC(n) containing spatial patternsic_mw::Matrix{Float64}: weighting matrix for ICA componentsch::Union{String, Vector{String}, Regex}: channel name(s)ic_idx::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=axes(ic, 1): component indices to plot, default is all componentstpos::Union{Nothing, Real, AbstractVector}=nothing: time point(s) in seconds to plot, ignored ifdatais providedimethod::Symbol=:sh: interpolation method::sh: Shepard:mq: Multiquadratic:imq: Inverse Multiquadratic:tp: ThinPlate:nn: Nearest Neighbour:ga: Gaussian
nmethod::Symbol=:minmax: method for normalization, seenormalize()contours::Int64=0: number of contour levels to plotelectrodes::Bools=true: iftrue, plot electrode locations over topographyps::Symbol: plot size::l: large (800×800 px):m: medium (300×300 px):s: small (100×100 px)
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_imf — Function
plot_imf(imf; <keyword arguments>)Plot intrinsic mode functions (IMF), the residual, and the reconstructed signal from Empirical Mode Decomposition (EMD).
Arguments
imf::Matrix{Float64}: matrix where each row represents an IMF component from EMDn::Int64=size(imf, 1) - 1: number of IMF components to plott::AbstractVector: time points corresponding to the signal values
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_line — Function
plot_line(s; <keyword arguments>)Create a line plot from signal data with customizable labels and styling.
Arguments
s::AbstractVector: signal vector containing y-values to plotglabels::Vector{String}: group labels for x-axis ticksxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot title
Returns
GLMakie.Figure: the plotted figure
plot_line(s; <keyword arguments>)Create a multi-line plot from multiple signal vectors (matrix rows) with customizable labels and styling.
Arguments
s::AbstractMatrix: matrix where each row represents a signal to plotrlabels::Vector{String}: signal row labels for legendglabels::Vector{String}: group labels for x-axis ticksxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_locs — Function
plot_locs(locs; <keyword arguments>)Preview channel locations with customizable visualization and connection mapping.
Arguments
locs::DataFrame: channel location datach::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=1:DataFrames.nrow(locs): list of locations to plot, default is all locationssch::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=0: significant channels to highlightch_labels::Bool=true: iftrue, draw locations labelshead::Bool=true: iftrue, draw head outlinehead_labels::Bool=false: draw head labelsmono::Bool=false: iftrue, use a monochrome palettegrid::Bool=true: iftrue, draw grid for locating positionsps::Symbol: plot size::l: large (800×800 px):m: medium (300×300 px):s: small (100×100 px)
cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planesplane::Symbol=:xy: which plane to plot::xy: horizontal (top):xz: coronary (front):yz: sagittal (side)
connections::Union{Nothing, Matrix{<:Real}}=nothing: matrix of connections weights, shape (channels, channels)threshold::Real=0: threshold for plotting connectionsthreshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
weights::Union{Bool, Vector{<:Real}}=true: iftrue, auto-scale line widths and transparency based on connection strength; if Vector, use provided weights to place at channel locationch_info::Vector{String}=string.(1:DataFrames.nrow(locs)): channel information details
Returns
GLMakie.Figure: the plotted figure
plot_locs(obj; <keyword arguments>)Preview channel locations from a NEURO object with customizable 2D/3D visualization and optional connection mapping.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)sch::Union{String, Vector{String}, Regex}: significant channels to highlightch_labels::Bool=true: plot channel labelssrc_labels::Bool=false: iftrue, plot source labels (for NIRS data)det_labels::Bool=false: iftrue, plot detector labels (for NIRS data)opt_labels::Bool=false: iftrue, plot optode type (S for source, D for detector) and numberhead::Bool=true: iftrue, draw head outlinehead_labels::Bool=false: iftrue, draw head labelsmono::Bool=false: iftrue, use a monochrome palettegrid::Bool=true: iftrue, draw grid for locating positionsps::Symbol: plot size::l: large (800×800 px):m: medium (300×300 px):s: small (100×100 px)
cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planesplane::Symbol=:xy: which plane to plot::xy: horizontal (top):xz: coronary (front):yz: sagittal (side)
connections::Union{Nothing, Matrix{<:Real}}=nothing: matrix of connections weights, shape (channels, channels)threshold::Real=0: threshold for plotting connectionsthreshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
weights::Union{Bool, Vector{<:Real}}=true: iftrue, auto-scale line widths and transparency based on connection strength; if Vector, use provided weights to place at channel locationgui::Bool=true: iftrue, keep window open and interactive
Returns
Union{GLMakie.Figure, Nothing}
NeuroAnalyzer.plot_locs3d — Function
plot_locs3d_mesh(locs; <keyword arguments>)3D interactive preview of channel locations with optional brain/head mesh visualization.
Arguments
locs::DataFrame: channel location datach::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=1:DataFrames.nrow(locs): channel indices to plot, default is all channelssch::Union{Int64, Vector{Int64}, AbstractUnitRange{Int64}}=0: significant channel indices to highlightch_labels::Bool=true: iftrue, plot channel labelshead_labels::Bool=true: iftrue, plot head labelsmono::Bool=false: iftrue, use a monochrome palettecart::Bool=false: iftrue, use Cartesian coordinates, otherwise use spherical coordinatescam::Tuple{Real, Real}=(20, 45): camera position as (XY plane angle, XZ plane angle) in degreesmesh_type::Symbol=:disabled: type of mesh to plot::disabled: no mesh:brain: brain mesh:head: head mesh
mesh_alpha::Float64=0.95: mesh opacity (0.0-1.0, higher = more opaque)gui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure
plot_locs3d(obj; <keyword arguments>)3D interactive preview of channel locations from a NEURO object.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)sch::Union{String, Vector{String}, Regex}: significant channels to highlightch_labels::Bool=true: iftrue, plot channel labelshead_labels::Bool=true: iftrue, plot head labelscart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planescam::Tuple{Real, Real}=(20, 45): camera position as (XY plane angle, XZ plane angle) in degreesmesh_type::Symbol=:disabled: type of mesh to plot::disabled: no mesh:brain: brain mesh:head: head mesh
mesh_alpha::Float64=0.95: mesh opacity (0.0-1.0, higher = more opaque)gui::Bool=true: iftrue, keep window open and interactive
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_locs_nirs — Function
plot_locs_nirs(locs; <keyword arguments>)Preview NIRS (Near-Infrared Spectroscopy) optodes and channel locations with customizable visualization.
Arguments
locs::DataFrame: channel location dataopt_pairs::Matrix{Int64}: matrix of source-detector pairs (n_pairs × 2)src_n::Int64: number of sources in the NIRS capdet_n::Int64: number of detectors in the NIRS capsrc_labels::Bool=false: plot source labelsdet_labels::Bool=false: plot detector labelsopt_labels::Bool=false: plot optode type (S for source, D for detector) and numberhead::Bool=true: iftrue, draw head outlinehead_labels::Bool=false: iftrue, draw head labelsmono::Bool=false: iftrue, use a monochrome palettegrid::Bool=false: iftrue, draw grid (useful for locating positions)ps::Symbol: plot size::l: large (800×800 px):m: medium (300×300 px):s: small (100×100 px)
cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planesplane::Symbol=:xy: which anatomical plane to plot::xy: horizontal (top-down) view:xz: coronary (front) view:yz: sagittal (side) view
ch_info::Vector{String}=string.(1:DataFrames.nrow(locs)): channel information details
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_matrix — Function
plot_matrix(m; <keyword arguments>)Plot matrix.
Arguments
m::Matrix{<:Real}: matrix to plotxlabels::Vector{String}: labels for x-axis ticksylabels::Vector{String}: labels for y-axis ticksxlabel::String="": x-axis labelsylabel::String="": y-axis labelstitle::String="": plot titlecb::Bool=true: iftrue, show colorbarcb_title::String="": colorbar titlexrot::Int64=90: x-axis label rotation in degreesmono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_mep — Function
plot_mep(t, s, bad; <keyword arguments>)Plot a single-channel Motor Evoked Potential (MEP) waveform with customizable visualization.
Arguments
t::Union{AbstractVector, AbstractRange}: vector of time points in secondss::AbstractVector: signal amplitude valuesxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlezl::Bool: iftrue, draw vertical line at t = 0yrev::Bool=false: iftrue, reverse the y-axismono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
plot_mep(t, s; <keyword arguments>)Plot multi-channel Motor Evoked Potentials (MEPs) with customizable visualization and averaging options.
Arguments
t::Union{AbstractVector, AbstractRange}: vector of time points in secondss::AbstractMatrix: signal amplitude values, shape (channel, samples)clabels::Vector{String}=string.(1:size(s, 1)): channel labels (default: auto-generated)xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titleyrev::Bool=false: iftrue, reverse the y-axisavg::Bool=true: iftrue, plot averaged MEP across channelsci95::Bool=false: iftrue, plot mean and ±95% confidence interval of averaged MEPsleg::Bool=true: iftrue, show legend with channel labelszl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
plot_mep(obj; <keyword arguments>)Plot Motor Evoked Potentials (MEPs) from a NEURO object with customizable visualization options.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectch::Union{String, Vector{String}, Regex}: channel name(s)xlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlecb::Bool=true: iftrue, show color barcb_title::String="default": color bar titlepeaks::Symbol=:detect: method for drawing peaks::detect: detect and draw peaks automatically:embed: embed peaks in the plot:off: do not draw peaks
leg::Bool=true: iftrue, show legend with channel labelstype::Symbol=:normal: multi-channel plot type::normal: butterfly or mean and ±95% CI:stack: stacked channels
yrev::Bool=false: iftrue, reverse the y-axisavg::Bool=true: iftrue, plot averaged MEPci95::Bool=false: iftrue, plot mean and ±95% CIsmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingzl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palettegui::Bool=false: ignored parameter (kept for compatibility)
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_mep_stack — Function
plot_mep_stack(s; <keyword arguments>)Plot Motor Evoked Potentials (MEPs) stacked by channels or epochs with customizable visualization.
Arguments
t::Union{AbstractVector, AbstractRange}: vector of time points in secondss::AbstractMatrix: signal amplitude values, shape (channel, samples)clabels::Vector{String}=string.(1:size(s, 1)): channel labels (default: auto-generated)xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlecb::Bool=true: iftrue, show color barcb_title::String="": color bar titlesmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingzl::Bool: iftrue, draw vertical line at t = 0mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_paired — Function
plot_paired(signal; <keyword arguments>)Create a paired data plot showing connections between paired observations (grouped by rows).
Arguments
s::AbstractArray: paired data to plotglabels::Vector{String}: group labels for x-axis ticksxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_phase — Function
plot_phase(ph, sf; <keyword arguments>)Plot phase values from time-frequency analysis with customizable styling and units.
Arguments
ph::Vector{Float64}: vector of phase values (radians or degrees)sf::Vector{Float64}: vector of corresponding frequencies or time pointsunit::Symbol=:rad: phase unit specification (:radradians or:degdegrees)type::Symbol=:line: plot type (:line: line plot,:stem: stem plot with markers)xlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot title
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_phsd — Function
plot_phsd(f, ph; <keyword arguments>)Plot PHSD (phase spectral density).
Arguments
f::Vector{Float64}: vector of frequency values in Hzph::Vector{Float64}: vector of phase values in radiansflim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotsxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)
Returns
GLMakie.Figure: the plotted figure
plot_phsd(f, ph; <keyword arguments>)Plot multi-channel Phase Spectral Density (PHSD) with customizable visualization options.
Arguments
f::Vector{Float64}: vector of frequency values in Hzph::Matrix{Float64}: matrix of phase values, shape (channels, frequencies)clabels::Vector{String}=string.(1:size(ph, 1)): channel labelsflim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotsxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palettefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)avg::Bool=false: iftrue, plot averaged PHSDci95::Bool=false: iftrue, plot mean and ±95% CI of averaged PHSDsleg::Bool=true: iftrue, add legend with channel labels
Returns
GLMakie.Figure: the plotted figure
plot_phsd(obj; <keyword arguments>)Plot Phase Spectral Density (PHSD) using various estimation methods with customizable visualization.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectseg::Tuple{Real, Real}=(0, 10): time segment to analyze (from, to) in seconds; default is 10 seconds or less if single epoch is shorterep::Int64=0: epoch to displaych::Union{String, Vector{String}, Regex}: channel name(s)flim::Tuple{Real, Real}=(0, sr(obj) / 2): frequency limits for the plotsfrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)xlabel::String="default": x-axis label, default is Frequency [Hz]ylabel::String="default": y-axis label, default is Phase [rad]zlabel::String="default": z-axis label for 3-d plots, default is Phase [rad]title::String="default": plot title, default is PHSD [frequency limit: 0-128 Hz] [epoch: 1, time window: 0 ms:10 s]mono::Bool=false: iftrue, use a monochrome palettetype::Symbol=:normal: plot type::normalsingle channel or butterfly for multichannel:w3d: 3-d waterfall:s3d: 3-d surface:topo: topographical
cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinateshead::Bool=true: iftrue, draw head outlineleg::Bool=true: iftrue, add legend with channel labelsavg::Bool=false: iftrue, plot averaged PSDci95::Bool=false: iftrue, plot mean and ±95% CI of averaged PSDs
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_phsd_3d — Function
plot_phsd_3d(f, ph; <keyword arguments>)Plot a 3D representation of multi-channel Phase Spectral Density (PHSD).
Arguments
f::Vector{Float64}: vector of frequency values in Hzph::Matrix{Float64}: matrix of phase values, shape (channels, frequencies)clabels::Vector{String}=string.(1:size(ph, 1)): channel labelsdb::Bool=true: whether powers are normalized to dB- `flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits
xlabel::String="": x-axis labelylabel::String="": y-axis labelzlabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palettefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)variant::Symbol=:w: 3D visualization type::w: waterfall plot:s: surface plot
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_phsd_topo — Function
plot_phsd_topo(locs, f, ph; <keyword arguments>)Plot a topographical map of Phase Spectral Density (PHSD) across channel locations.
Arguments
locs::DataFrame: channel location dataf::Vector{Float64}: vector of frequency values in Hzph::Matrix{Float64}: matrix of phase values, shape (channels, frequencies)flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotsxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinateshead::Bool=true: iftrue, draw head outline
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_polar — Function
plot_polar(s; <keyword arguments>)Create a polar plot from signal data with customizable styling.
Arguments
s::Union{AbstractVector, AbstractMatrix}: input data to plot; vector must contain 2 values: phases and lengths; matrix must contain 2 columns: phases and lengthsm::Tuple{Real, Real}=(0, 0): major value to plottitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome paletteticks::Bool=false: draw x- and y-axis ticks
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_polezero — Function
plot_polezero(pol, zer; <keyword arguments>)Plot a polar pole-zero map for digital filter analysis showing poles and zeros in the complex plane.
Arguments
fig::Vector{Complex{Float64}}: vector of complex pole locations in the z-planez::Vector{Complex{Float64}}: vector of complex zero locations in the z-planem::Tuple{Real, Real}=(0, 0): major value to plottitle::String="": plot titleticks::Bool=false: iftrue, draw x- and y-axis ticksms::Symbol=:circle: marker shape for drawing complex numbers (:circleor:xcross)mono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_psd — Function
plot_psd(f, p; <keyword arguments>)Plot the Power Spectral Density (PSD) with customizable visualization options.
Arguments
f::Vector{Float64}: vector of frequency values in Hzp::Vector{Float64}: vector of power spectral density valuesflim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotsxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)
Returns
GLMakie.Figure: the plotted figure
plot_psd(f, p; <keyword arguments>)Plot multi-channel Power Spectral Density (PSD) with customizable visualization options.
Arguments
f::Vector{Float64}: vector of frequency values in Hzp::Matrix{Float64}: matrix of power spectral density values, shape (channels, frequencies)clabels::Vector{String}=string.(1:size(p, 1)): channel labelsflim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotsxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palettefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)avg::Bool=false: iftrue, plot averaged PSD across channelsci95::Bool=false: iftrue, plot mean and ±95% confidence interval of averaged PSDsleg::Bool=true: iftrue, add legend with channel labels
Returns
GLMakie.Figure: the plotted figure
plot_psd(obj; <keyword arguments>)Plot Power Spectral Density (PSD) using various estimation methods with customizable visualization.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectseg::Tuple{Real, Real}=(0, 10): time segment to analyze (from, to) in seconds; default is 10 seconds or less if single epoch is shorterep::Int64=0: epoch to displaych::Union{String, Vector{String}, Regex}=datatype(obj): channel name(s)db::Bool=true: iftrue, normalize powers to dBmethod::Symbol=:welch: PSD estimation method::welch: Welch's periodogram:fft: fast Fourier transform:mt: multi-taper periodogram:stft: short-time Fourier transform:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=fs: window length in samples (default = 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowflim::Tuple{Real, Real}=(0, sr(obj) / 2): frequency limits for the plotsncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)gw::Real=5: Gaussian width in Hz (used by:gh)ref::Symbol=:abs: PSD reference type::abs: absolute power (no reference):total: relative to total power:delta: relative to delta band power:theta: relative to theta band power:alpha: relative to alpha band power:beta: relative to beta band power:beta_high: relative to high beta band power:gamma: relative to gamma band power:gamma_1: relative to gamma-1 band power:gamma_2: relative to gamma-2 band power:gamma_lower: relative to lower gamma band power:gamma_higher: relative to higher gamma band power
demean::Bool=true: subtract DC component before estimating PSDfrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)xlabel::String="default": x-axis labelylabel::String="default": y-axis labelzlabel::String="default": z-axis label for 3-d plotstitle::String="default": plot titlemono::Bool=false: iftrue, use a monochrome palettetype::Symbol=:normal: plot type::normalsingle channel or butterfly plot for multichannel:w3d: 3D waterfall plot:s3d: 3D surface plot:topo: topographical plot
cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinateshead::Bool=true: iftrue, draw head outlineleg::Bool=true: iftrue, add legend with channel labelsavg::Bool=false: iftrue, plot averaged PSD across channelsci95::Bool=false: iftrue, plot mean and ±95% confidence interval of averaged PSDs
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_psd_3d — Function
plot_psd_3d(f, p; <keyword arguments>)Plot a 3D representation of multi-channel Power Spectral Density (PSD).
Arguments
f::Vector{Float64}: vector of frequency values in Hzp::Matrix{Float64}: matrix of power values, shape (channels, frequencies)clabels::Vector{String}=string.(1:size(p, 1)): channel labelsdb::Bool=true: whether powers are normalized to dB- `flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits
xlabel::String="": x-axis labelylabel::String="": y-axis labelzlabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palettefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)variant::Symbol=:w: 3D visualization type::w: waterfall plot:s: surface plot
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_psd_topo — Function
plot_psd_topo(locs, f, p; <keyword arguments>)Plot a topographical map of Power Spectral Density (PSD) across channel locations.
Arguments
locs::DataFrame: channel location dataf::Vector{Float64}: vector of frequency values in Hzp::Matrix{Float64}: matrix of power spectral density values, shape (channels, frequencies)- `flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plot
xlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlefrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinateshead::Bool=true: iftrue, draw head outline
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_save — Function
plot_save(fig; <keyword arguments>)Saves plot as file (PNG/PDF).
Arguments
fig::Union{Plots.Plot{Plots.GRBackend}, Makie.Figure}: figure or plot object to savefile_name::String: output file path and name; file format is determined by the extension:.png: Portable Network Graphics (lossless).pdf: Portable Document Format (vector graphics)
Returns
Nothing
NeuroAnalyzer.plot_spectrogram — Function
plot_spectrogram(st, sf, sp; <keyword arguments>)Plot a single-channel spectrogram (time vs. frequency).
Arguments
st::Vector{Float64}: vector of time values in secondssf::Vector{Float64}: vector of frequency values in Hzsp::Matrix{Float64}: spectrogram power valuesdb::Bool=true: whether to display power values in decibelsfrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome paletteunits::String="": power unitssmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingcb::Bool=true: iftrue, show color barcb_title::String="": colorbar titlethreshold::Union{Nothing, Real, Tuple{Real, Real}}=nothing: threshold for marking regions- if
Real, use a single threshold value - if
Tuple{Real, Real}, use a range for:inor:binthresholding
- if
threshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
Returns
GLMakie.Figure: the plotted figure
plot_spectrogram(sf, sp; <keyword arguments>)Plot multiple-channel spectrogram.
Arguments
sf::Vector{Float64}: vector of frequency values in Hzsp::Matrix{Float64}: spectrogram power valuesclabels::Vector{String}=string.(1:size(sp, 1)): channel labelsdb::Bool=true: whether powers are normalized to dBfrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)flim::Tuple{Real, Real}=(f[1], f[end]): frequency limits for the plotxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome paletteunits::String="": power unitssmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingcb::Bool=true: iftrue, show color barcb_title::String="": colorbar titlethreshold::Union{Nothing, Real, Tuple{Real, Real}}=nothing: threshold for marking regions- if
Real, use a single threshold value - if
Tuple{Real, Real}, use a range for:inor:binthresholding
- if
threshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
Returns
GLMakie.Figure: the plotted figure
plot_spectrogram(obj; <keyword arguments>)Plot a spectrogram or scalogram using various time-frequency analysis methods.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectseg::Tuple{Real, Real}=(0, 10): time segment to analyze (from, to) in seconds; default is 10 seconds or less if single epoch is shorterep::Int64=0: epoch to displaych::Union{String, Vector{String}, Regex}=datatype(obj): channel name(s)db::Bool=true: iftrue, normalize powers to dB; for CWT scaleogram: normalize to the signal scale so the amplitudes of wavelet coefficients agree with the amplitudes of oscillatory components in a signalmethod::Symbol=:stft: spectrogram estimation method::stft: short-time Fourier:mt: multi-tapered periodogram:mw: Morlet wavelet convolution:gh: Gaussian and Hilbert transform:cwt: continuous wavelet transformation:hht: Hilbert-Huang transform
nt::Int64=7: number of Slepian tapers (used by:mt)wlen::Int64=sr(obj): window length in samples (default is 1 second)woverlap::Int64=round(Int64, wlen * 0.90): window overlap in samplesw::Bool=true: iftrue, apply Hanning windowgw::Real=10: Gaussian width in Hzncyc::Union{Int64, Tuple{Int64, Int64}}=32: Morlet wavelet cycles; for a tuple, cycles vary per frequency:ncyc = linspace(ncyc[1], ncyc[2], nfrq)wt<:CWT=wavelet(Morlet(2π), β=2): continuous wavelet, see ContinuousWavelets.jl documentation for the list of available waveletsfrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)flim::Tuple{Real, Real}=(0, sr(obj) / 2): y-axis frequency limits (min, max) in Hzxlabel::String="default": x-axis labelylabel::String="default": y-axis labeltitle::String="default": plot titlemono::Bool=false: iftrue, use a monochrome palettemarkers::Bool=true: iftrue, draw markers if availablesmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingcb::Bool=true: iftrue, show color barthreshold::Union{Nothing, Real, Tuple{Real, Real}}=nothing: threshold for marking regions- if
Real, use a single threshold value - if
Tuple{Real, Real}, use a range for:inor:binthresholding
- if
threshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
type::Symbol=:normal: plot type::normal: standard spectrogram:topo: topographical map of spectrograms
cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinateshead::Bool=true: iftrue, draw head outline
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_spectrogram_topo — Function
plot_spectrogram_topo(locs, st, sf, sp; <keyword arguments>)Plot a topographical map of spectrogram data across channel locations with customizable visualization.
Arguments
locs::DataFrame: channel location datast::Vector{Float64}: time points in seconds corresponding to spectrogram columnssf::Vector{Float64}: frequency values in Hz corresponding to spectrogram rowssp::Array{Float64, 3}: spectrogram power valuesdb::Bool=true: whether powers are normalized to dBflim::Tuple{Real, Real}=(sf[1], sf[end]): frequency limits for the plotxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titleunits::String="": power unitscb::Bool=true: iftrue, show color barcb_title::String="": colorbar titlesmooth::Bool=false: iftrue, apply Gaussian blur smoothingks::Int64=3: smoothing kernel size; larger kernel means more smoothingmono::Bool=false: unused, for compatibility onlyfrq::Symbol=:lin: frequency scaling (:linfor linear,:logfor logarithmic)cart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinateshead::Bool=true: iftrue, draw head outline
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_topo — Function
plot_topo(s; <keyword arguments>)Plot a topographical map of signal values across channel locations.
Arguments
s::AbstractVector: signal values to plot (one value per channel)locs::DataFrame: channel location datach::Union{Int64, Vector{Int64}}=1:DataFrames.nrow(locs): channels to include; defaults to all rows inlocssch::Union{Nothing, Int64, Vector{Int64}}=nothing: significant channels to highlightcb::Bool=true: iftrue, show colorbarcb_title::String="[A.U.]": colorbar titletitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome paletteimethod::Symbol=:sh: interpolation method::sh: Shepard:mq: Multiquadratic:imq: Inverse Multiquadratic:tp: ThinPlate:nn: Nearest Neighbour:ga: Gaussian
nmethod::Symbol=:minmax: method for normalization, seenormalize()contours::Int64=0: plot contours (if > 0) over topo plot, number specifies how many levels to plotelectrodes::Bools=true: iftrue, plot electrode locations over topographyps::Symbol: plot size::l: large (800×800 px):m: medium (300×300 px):s: small (100×100 px)
head::Bool=true: iftrue, draw head outlinecart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planesthreshold::Union{Nothing, Real, Tuple{Real, Real}}=nothing: threshold for marking regions- if
Real, use a single threshold value - if
Tuple{Real, Real}, use a range for:inor:binthresholding
- if
threshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
threshold_method::Symbol=:reg: thresholding method::reg: threshold whole topomap region (default):loc: threshold only at channel locations
Returns
GLMakie.Figure: the plotted figure
plot_topo(obj; <keyword arguments>)Plot a topographical map of signal values from a NEURO object with customizable visualization options.
Arguments
obj::NeuroAnalyzer.NEURO: input NEURO objectdata::Union{Nothing, AbstractVector, AbstractMatrix}=nothing: external data to plot:Vector: one value per channelMatrix: (channels × values), will be averaged by channelsnothing: use data from NEURO object at specified time point(s) (default)
ch::Union{String, Vector{String}, Regex}: channel name(s)sch::Union{Nothing, String, Vector{String}, Regex}=nothing: significant channels to highlighttpos::Union{Nothing, Real, AbstractVector}=nothing: time point in seconds to plot, ignored ifdatais providedtitle::String="default": plot titlemono::Bool=false: iftrue, use a monochrome palettecb::Bool=true: iftrue, show colorbarcb_title::String="[A.U.]": colorbar titleamethod::Symbol=:mean: averaging method for matrix data::mean: mean averaging:median: median averaging
imethod::Symbol=:sh: interpolation method::sh: Shepard:mq: Multiquadratic:imq: Inverse Multiquadratic:tp: ThinPlate:nn: Nearest Neighbour:ga: Gaussian
nmethod::Symbol=:minmax: method for normalization, seenormalize()contours::Int64=0: plot contours (if > 0) over topo plot, number specifies how many levels to plotelectrodes::Bools=true: iftrue, plot electrode locations over topographyps::Symbol: plot size::l: large (800×800 px):m: medium (300×300 px):s: small (100×100 px)
head::Bool=true: iftrue, draw head outlinecart::Bool=false: iftrue, use Cartesian coordinates, otherwise use polar coordinates for XY plane and spherical coordinates for XZ and YZ planesthreshold::Union{Nothing, Real, Tuple{Real, Real}}=nothing: threshold for marking regions- if
Real, use a single threshold value - if
Tuple{Real, Real}, use a range for:inor:binthresholding
- if
threshold_type::Symbol=:neq: rule for thresholding::eq: values equal to threshold:neq: values not equal to threshold:geq: values ≥ threshold:leq: values ≤ threshold:g: values > threshold:l: values < threshold:in: values in the threshold range (inclusive):bin: values in the threshold range (exclusive)
threshold_method::Symbol=:reg: thresholding method::reg: threshold whole topomap region (default):loc: threshold only at channel locations
nr::Int64=0: number of rows for arranging multiple topomapsnc::Int64=0: number of columns for arranging multiple topomaps
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_violin — Function
plot_violin(s; <keyword arguments>)Create a violin plot from matrix data with customizable labels and styling.
Arguments
s::AbstractMatrix: matrix where each row represents a group for which to create a violin plotglabels::Vector{String}: group labels for x-axis ticksxlabel::String="": x-axis labelylabel::String="": y-axis labeltitle::String="": plot titlemono::Bool=false: iftrue, use a monochrome palette
Returns
GLMakie.Figure: the plotted figure
NeuroAnalyzer.plot_xac — Function
plot_xac(m, lags; <keyword arguments>)Plot cross-correlation, auto-correlation, or covariance between signal(s) and lags.
Arguments
m::AbstractVector: cross/auto-covariance/correlation matrix oflags::AbstractVector: vector of lag values in secondsxlabel::String="Lag [s]": x-axis labelsylabel::String="": y-axis labelstitle::String="": plot title
Returns
GLMakie.Figure: the plotted figure
Notes
- Positive lags represent future correlation, negative lags represent past correlation
NeuroAnalyzer.resize_canvas — Function
resize_canvas(c; <keyword arguments>)Resize a Cairo surface by a uniform scale factor.
Arguments
c::Cairo.CairoSurfaceBase{UInt32}r::Real: scale factor (e.g.0.5halves both dimensions)
Returns
Cairo.CairoSurfaceBase{UInt32}: new surface of size(w*r, h*r)
NeuroRecorder
NeuroAnalyzer.edar — Function
edar(; <keyword arguments>)Record electrodermal activity (EDA), also called Galvanic Skin Response (GSR) or skin conductance, in CLI mode. EDA is recorded using Groove GSR sensor via Arduino attached to the PC via USB cable (virtual serial port).
Arguments
duration::Int64=20: recording duration in secondsport_name::String="/dev/ttyUSB0": serial port to which the Arduino is connected
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.iedar — Function
iedar(; <keyword arguments>)Record electrodermal activity (EDA), also called Galvanic Skin Response (GSR) or skin conductance, in GUI mode. EDA is recorded using Groove GSR sensor via Arduino attached to the PC via USB cable (virtual serial port). Sampling rate is 50 Hz.
Arguments
duration::Int64=20: recording duration in secondsport_name::String="/dev/ttyUSB0": serial port to which the Arduino is connected
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.rt_plotter — Function
rt_plotter(; <keyword arguments>)Plot recorded signal in real time.
Arguments
fs::Int64l::Int64=5: displayed segment length (in seconds)duration::Int64=20: duration of recording (in seconds)
Returns
Plots.Plot{Plots.GRBackend}
NeuroStim
NeuroAnalyzer.ect_charge — Function
ect_charge(; <keyword arguments>)Calculate the total charge delivered during an ECT stimulation session.
Each pulse contributes pw × pint of charge (pulse width × current = charge per pulse). Multiplying by the number of pulses (pf × duration) gives the total charge. The milli-prefixes cancel as follows:
ms × mA × Hz × s = 10⁻³ s × 10⁻³ A × s⁻¹ × s = 10⁻⁶ C = 10⁻³ mCso a factor of 10⁻³ is applied to convert the raw product to mC.
Arguments
pw::Real: pulse width in ms; must be > 0pint::Real: pulse intensity (current) in mA; must be > 0pf::Real: pulse frequency in Hz; must be > 0duration::Real: stimulation duration in seconds; must be > 0
Returns
Float64: total charge in mC
NeuroAnalyzer.tacs_dose — Function
tacs_dose(; <keyword arguments>)Calculate charge, current density, and charge density for tACS stimulation.
The effective current is computed by integrating one cycle of the sinusoidal waveform (including the DC offset) over a 1 ms grid using Simpson's rule, then scaling by the number of cycles.
Arguments
current::Real: peak-to-peak stimulation current in mA; must be > 0pad_area::Real: electrode pad area in cm²; must be > 0duration::Real: stimulation duration in seconds; must be > 0offset::Real: DC current offset in μAfrequency::Real: sinusoidal frequency in Hz; must be > 0phase::Real: phase shift in degrees
Returns
Named tuple:
charge::Float64: total delivered charge in Ccurrent_density::Float64: current density in A/m²charge_density::Float64: delivered charge density in kC/m²
NeuroAnalyzer.tdcs_dose — Function
tdcs_dose(; <keyword arguments>)Calculate charge, current density, and charge density for tDCS stimulation.
Arguments
current::Real: stimulation current in mA; must be > 0pad_area::Real: electrode pad area in cm²; must be > 0duration::Int64: stimulation duration in seconds; must be > 0
Returns
Named tuple:
charge::Float64: total delivered charge in Ccurrent_density::Float64: current density in A/m²charge_density::Float64: delivered charge density in kC/m²
References
Chhatbar PY, George MS, Kautz SA, Feng W. Quantitative reassessment of safety limits of tDCS for two animal studies. Brain Stimulation. 2017;10(5):1011–2.
NeuroAnalyzer.tes_protocol — Function
tes_protocol(; <keyword arguments>)Create a TES (tDCS/tACS/tRNS/tPCS) stimulation protocol dictionary.
Arguments
type::Symbol: stimulation type; one of:tDCS,:tACS,:tRNS,:tPCShd::Bool: iftrue, use high-density electrodescurrent::Real: stimulation current in mA; must be > 0frequency::Real=0: stimulation frequency in Hz; must be > 0 for:tACSand:tRNSanode_size::Tuple{Int64, Int64}: anode dimensions(width, height)in mm; both values must be > 0cathode_size::Tuple{Int64, Int64}: cathode dimensions(width, height)in mm; both values must be > 0anode_loc::Symbol: anode location (10-20 Positioning System label)cathode_loc::Symbol: cathode location (10-20 Positioning System label)duration::Real: stimulation duration in seconds; must be > 0ramp_in::Real: ramp-in duration in seconds; must be ≥ 0ramp_out::Real: ramp-out duration in seconds; must be ≥ 0sham::Bool: iftrue, the protocol includes sham stimulation
Returns
Dict: protocol dictionary with all stimulation parameters
NeuroAnalyzer.tpcs_dose — Function
tpcs_dose(; <keyword arguments>)Calculate charge, current density, and charge density for tPCS stimulation.
The effective current is computed as current × (pw / isi), i.e. scaled by the duty cycle.
Arguments
Arguments
current::Real: peak-to-peak stimulation current in mA; must be > 0pad_area::Real: electrode pad area in cm²; must be > 0duration::Real: stimulation duration in seconds; must be > 0pw::Real: pulse width in ms; must be > 0 and <isiisi::Real: inter-stimulus interval in ms; must be >pw
Returns
Named tuple:
charge::Float64: total delivered charge in Ccurrent_density::Float64: current density in A/m²charge_density::Float64: delivered charge density in kC/m²
NeuroTester
NeuroAnalyzer.ftt — Function
ftt(; <keyword arguments>)Perform Finger Tapping Test (FTT) in CLI mode. Use computer keyboard (SPACEBAR key) or switch panel attached to Raspberry Pi via a GPIO pin. Number of taps, time points and durations of taps are recorded. Also, taps during intervals (when the study subject should suppress tapping) are recorded. When using computer keyboard, only the number of taps and their time points are recorded; tap durations are set to 100 ms.
Arguments
duration::Int64=20: single trial duration in secondstrials::Int64=2: number of trialsinterval::Int64=2: interval between trials in secondsgpio::Int64=-1: Raspberry Pi GPIO to which the switch is connected (e.g.gpio=23is Pi board pin 16); set to -1 to disable using GPIOport_name::String="": serial port to which the switch is connected (e.g./dev/ttyACM0); set to "" to disable using serial port
Returns
Named tuple:
taps::Vector{Int64}: number of taps per trialtap_t::Vector{Vector{Float64}}: taps time point [ms]tap_d::Vector{Vector{Float64}}: taps duration [ms]taps_int::Vector{Int64}: number of taps per trial during intervalstap_t_int::Vector{Vector{Float64}}: taps time point [ms] during intervalstap_d_int::Vector{Vector{Float64}}: taps duration [ms] during intervals
NeuroAnalyzer.iavh — Function
iavh()Interactive tool for subjective recreation of auditory hallucinations. Four languages are available (English, German, Spanish and Polish). Four types of auditory hallucinations are available: speech (Auditory Verbal Hallucinations), whispers, noise and ringing (8000 Hz).
Patient may locate the sounds in space to recreate how distant or close they are. Also, volume of the auditory experiences may be modified. In case of AVH, emotional content (negative, neutral or positive) and voice gender (male or female) may be chosen.
When done, patient's settings may be easily exported to a CSV file for further analysis.
Arguments
Nothing
Returns
Nothing
NeuroAnalyzer.iftt — Function
iftt(; <keyword arguments>)Perform Finger Tapping Test (FTT) in GUI mode. Use computer keyboard (SPACEBAR key) or switch panel attached to Raspberry Pi via a GPIO pin and to the PC via USB (virtual serial port). Number of taps, time points and durations of taps are recorded. Also, taps during intervals (when the study subject should suppress tapping) are recorded.
Arguments
duration::Int64=20: single trial duration in secondstrials::Int64=2: number of trialsinterval::Int64=2: interval between trials in secondsgpio::Int64=-1: Raspberry Pi GPIO to which the switch is connected (e.g.gpio=23is Pi board pin 16); set to -1 to disable using GPIOport_name::String="": serial port to which the switch is connected (e.g./dev/ttyACM0); set to "" to disable using serial port
Returns
Named tuple:
taps::Vector{Int64}: number of taps per trialtap_t::Vector{Vector{Float64}}: taps time point [ms]tap_d::Vector{Vector{Float64}}: taps duration [ms]taps_int::Vector{Int64}: number of taps per trial during intervalstap_t_int::Vector{Vector{Float64}}: taps time point [ms] during intervalstap_d_int::Vector{Vector{Float64}}: taps duration [ms] during intervals
NeuroAnalyzer.itpt — Function
itpt(; <keyword arguments>)Perform Two-point Pinch Test (TPT) in GUI mode. TPT is recorded using MMA7660 accelerometer via Arduino attached to the PC via USB cable (virtual serial port). Sampling rate is 50 Hz.
Arguments
duration::Int64=20: recording duration in secondsport_name::String="/dev/ttyUSB0": serial port to which the Arduino is connected
Returns
NeuroAnalyzer.NEURO: output NEURO object
NeuroAnalyzer.tpt — Function
tpt(; <keyword arguments>)Perform Two-point Pinch Test (TPT) in CLI mode. TPT is recorded using MMA7660 accelerometer via Arduino attached to the PC via USB cable (virtual serial port). Sampling rate is 50 Hz.
Arguments
duration::Int64=20: recording duration in secondsport_name::String="/dev/ttyUSB0": serial port to which the Arduino is connected
Returns
NeuroAnalyzer.NEURO: output NEURO object