nstat.SignalObj

class nstat.SignalObj(time, data, name='', xlabelval='time', xunits='s', yunits='', dataLabels=None, plotProps=None, **kwargs)[source]

Bases: object

Multi-dimensional time-series signal object (Matlab SignalObj).

SignalObj is the foundational data container in nSTAT. It stores one or more signal channels sampled on a common time axis, along with metadata (name, units, labels) and supports element-wise arithmetic, resampling, filtering, correlation analysis, and spectral estimation.

Parameters:
  • time (array_like) – Monotonically increasing time vector of length n.

  • data (array_like) – Signal values. Shape (n,) for a scalar signal or (n, d) for a d-dimensional signal.

  • name (str, optional) – Human-readable signal name (used as y-axis label in plots).

  • xlabelval (str, optional) – X-axis label string (default 'time').

  • xunits (str, optional) – X-axis unit string (default 's').

  • yunits (str, optional) – Y-axis unit string.

  • dataLabels (sequence of str or str, optional) – Per-dimension labels. A single string is broadcast to all dimensions.

  • plotProps (sequence or str, optional) – Per-dimension Matplotlib format strings.

See also

Covariate

SignalObj subclass with confidence-interval support.

nspikeTrain

Point-process (spike train) companion class.

__init__(time, data, name='', xlabelval='time', xunits='s', yunits='', dataLabels=None, plotProps=None, **kwargs)[source]

Construct a multi-dimensional signal object (Matlab SignalObj).

Parameters:
  • time (array_like, shape (n,)) – Monotonically increasing time vector in seconds.

  • data (array_like, shape (n,) or (n, d) or (d, n)) – Signal values. Either a 1-D vector of length n for a scalar signal, or a 2-D matrix. Both (n, d) and (d, n) orientations are accepted — the layout is inferred from the time-vector length.

  • name (str, optional) – Human-readable signal name. Used as the y-axis label in plots. Default "".

  • xlabelval (str, optional) – X-axis label string. Default "time". Also accepts the keyword alias xlabel= for backwards compatibility.

  • xunits (str, optional) – X-axis unit string. Default "s" (seconds).

  • yunits (str, optional) – Y-axis unit string. Default "".

  • dataLabels (sequence of str or str or None, optional) – Per-dimension labels. A single string is broadcast to all d dimensions. Also accepts the keyword alias data_labels= for backwards compatibility.

  • plotProps (sequence or str or None, optional) – Per-dimension Matplotlib format strings (one per channel).

  • **kwargs – Reserved for the xlabel / data_labels legacy aliases above. Any other keyword raises TypeError.

Return type:

None

Notes

The sample rate is inferred from mean(diff(time)). For single-sample signals (or non-finite/zero deltas) it falls back to 1000.0 Hz, matching the MATLAB toolbox.

Raises:
  • ValueError – If time is not a 1-D array-like, or if data dimensions do not match time length.

  • TypeError – If unexpected keyword arguments are passed.

Parameters:
Return type:

None

See also

Covariate

SignalObj subclass with confidence-interval support.

nspikeTrain

Point-process companion class for spike data.

property dimension: int

Number of signal channels (columns in the data matrix).

property values: ndarray

Signal data as a 1-D array (scalar) or 2-D matrix.

property units: str

Y-axis unit string (alias for yunits).

property sample_rate: float

Sampling rate in Hz (alias for sampleRate).

copySignal()[source]

Return a deep copy of this signal (Matlab copySignal).

Return type:

SignalObj

setName(name)[source]

Set the signal name (y-axis label).

Parameters:

name (str)

Return type:

None

setXlabel(name)[source]

Set the x-axis label string.

Parameters:

name (str)

Return type:

None

setYLabel(name)[source]

Set the y-axis label (alias for setName).

Parameters:

name (str)

Return type:

None

setUnits(xUnits, yUnits=None)[source]

Set x-axis and optionally y-axis units.

Parameters:
  • xUnits (str)

  • yUnits (str | None)

Return type:

None

setXUnits(units)[source]

Set the x-axis unit string.

Parameters:

units (str)

Return type:

None

setYUnits(units)[source]

Set the y-axis unit string.

Parameters:

units (str)

Return type:

None

setSampleRate(sampleRate)[source]

Set the sample rate, resampling the data if it differs from current.

Parameters:

sampleRate (float)

Return type:

None

setDataLabels(dataLabels)[source]

Set per-dimension data labels.

A single string is broadcast to all dimensions. A sequence must have length equal to dimension.

Parameters:

dataLabels (Sequence[str] | str | None)

Return type:

None

setMinTime(minTime=None, holdVals=0)[source]

Extend or trim the signal to start at minTime.

If holdVals is 1, endpoint values are held when extending; otherwise the signal is zero-padded.

Parameters:
Return type:

None

setMaxTime(maxTime=None, holdVals=0)[source]

Extend or trim the signal to end at maxTime.

If holdVals is 1, endpoint values are held when extending; otherwise the signal is zero-padded.

Parameters:
Return type:

None

setPlotProps(plotProps, index=None)[source]

Set per-dimension Matplotlib format strings.

When index (0-based) is given, only that dimension is updated.

Parameters:
Return type:

None

setDataMask(dataMask)[source]

Set binary data mask (1 = visible, 0 = hidden) for each dimension.

Parameters:

dataMask (Sequence[int] | ndarray)

Return type:

None

setMaskByInd(index)[source]

Enable only the dimensions at the given 0-based indices.

Parameters:

index (Sequence[int] | ndarray)

Return type:

None

setMaskByLabels(labels)[source]

Enable only the dimensions whose data labels match labels.

Parameters:

labels (Sequence[str] | str)

Return type:

None

setMask(mask=None)[source]

Flexible mask setter accepting indices, labels, or a binary vector.

None clears the mask (all hidden). A binary vector of length dimension is used directly. A list of labels or 0-based indices enables only those dimensions.

Parameters:

mask (Sequence[int] | Sequence[str] | ndarray | None)

Return type:

None

getTime()[source]

Return a copy of the time vector.

Return type:

ndarray

getData()[source]

Return signal data as a matrix (alias for dataToMatrix()).

Return type:

ndarray

getOriginalData()[source]

Return (originalTime, originalData) copies.

Return type:

tuple[ndarray, ndarray]

getOrigDataSig()[source]

Return the original (pre-resample) data as a new SignalObj.

Return type:

SignalObj

getValueAt(x)[source]

Return signal value(s) at time(s) x via nearest-neighbour lookup.

Parameters:

x (Sequence[float] | float)

Return type:

ndarray

getPlotProps(index)[source]

Return the plot property for dimension index (0-based).

Parameters:

index (int)

Return type:

Any

getIndexFromLabel(label)[source]

Return 0-based indices of dimensions whose label equals label.

Parameters:

label (str)

Return type:

list[int]

getIndicesFromLabels(label)[source]

Return 0-based index(es) for one or more data-label strings.

Parameters:

label (Sequence[str] | str)

areDataLabelsEmpty()[source]

Return True if all data labels are empty strings.

Matches Matlab SignalObj.areDataLabelsEmpty().

Return type:

bool

isLabelPresent(label)[source]

Return True if label matches any data label or equals 'all'.

Matches Matlab SignalObj.isLabelPresent().

Parameters:

label (str)

Return type:

bool

convertNamesToIndices(selectorArray)[source]

Convert label names (or mixed) to 0-based indices.

Matches Matlab SignalObj.convertNamesToIndices() (the Python port is 0-based throughout).

Return type:

list[int] | ndarray

dataToMatrix(selectorArray=None)[source]

Return signal data as an (n, d) matrix.

selectorArray is an optional sequence of 0-based dimension indices. When None, the data mask selects visible dimensions.

Parameters:

selectorArray (Sequence[int] | ndarray | None)

Return type:

ndarray

getSubSignalFromInd(selectorArray)[source]

Return a new SignalObj with only the selected dimensions (0-based).

Parameters:

selectorArray (Sequence[int] | ndarray)

Return type:

SignalObj

getSubSignalFromNames(labels)[source]

Return a sub-signal selected by data-label name(s).

Parameters:

labels (Sequence[str] | str)

Return type:

SignalObj

getSubSignal(identifier)[source]

Return a sub-signal selected by labels, indices, or mixed.

Return type:

SignalObj

findNearestTimeIndex(time)[source]

Return the 0-based index of the sample nearest to time.

Parameters:

time (float)

Return type:

int

findNearestTimeIndices(times)[source]

Return 0-based indices of the samples nearest to each time in times.

Parameters:

times (Sequence[float] | ndarray)

Return type:

ndarray

merge(other, holdVals=0)[source]

Merge other signal columns into self.

Matlab calls makeCompatible first so that signals with different time grids are reconciled automatically. The Python version now does the same.

Parameters:
  • other (SignalObj) – Signal whose data columns will be appended.

  • holdVals (int, optional) – Passed to makeCompatible – 1 holds endpoint values when the time range is extended; 0 (default) pads with zeros.

Return type:

SignalObj

power(exponent)[source]

Element-wise power data ** exponent (Matlab power).

Parameters:

exponent (float)

Return type:

SignalObj

sqrt()[source]

Element-wise square root (Matlab sqrt).

Return type:

SignalObj

ldivide(other)[source]

Element-wise left division (Matlab .\): other ./ self.

Matches Matlab SignalObj.ldivide().

Return type:

SignalObj

property T: SignalObj

Transpose the data matrix. Matches Matlab ctranspose / transpose.

clearPlotProps(index=None)[source]

Clear plot properties. Matches Matlab clearPlotProps.

Return type:

None

plotPropsSet()[source]

Return True if any plot property is non-empty.

Matches Matlab SignalObj.plotPropsSet().

Return type:

bool

getSigInTimeWindow(wMin=None, wMax=None, holdVals=0)[source]

Extract signal within [wMin, wMax].

Multiple windows can be specified by passing equal-length sequences for wMin and wMax; the extracted segments are concatenated as additional dimensions (Matlab getSigInTimeWindow).

Parameters:
Return type:

SignalObj

restoreToOriginal(rMask=0)[source]

Restore time, data, and sample rate to their original values.

If rMask is 1, the data mask is also reset (all visible).

Parameters:

rMask (int)

Return type:

None

resetMask()[source]

Reset the data mask so all dimensions are visible.

Return type:

None

findIndFromDataMask()[source]

Return 0-based indices of dimensions currently visible (mask == 1).

Return type:

list[int]

isMaskSet()[source]

Return True if any dimension is currently masked out.

Return type:

bool

derivative()[source]

Return the per-sample forward-difference derivative.

Matches MATLAB SignalObj.m:761 which is a method (called as s.derivative()), not a property. The previous Python implementation was a @property so MATLAB-ported code calling sig.derivative() silently failed with TypeError: 'SignalObj' object is not callable. This is now a regular method; access sig.derivative() (with parentheses) to compute the derivative.

Return type:

SignalObj

derivativeAt(x0)[source]

Return the derivative value(s) at time(s) x0.

Parameters:

x0 (Sequence[float] | float)

integral(t0=None, tf=None)[source]

Cumulative integral of the signal from t0 to tf.

Computed via a causal IIR accumulator: y[n] = y[n-1] + x[n] * deltaT. If t0 / tf are not specified, minTime / maxTime are used.

Parameters:
Return type:

SignalObj

filter(B, A=1)[source]

Apply a causal IIR/FIR filter (B, A) to each dimension.

Equivalent to scipy.signal.lfilter(B, A, data).

Return type:

SignalObj

filtfilt(B, A=1)[source]

Apply a zero-phase IIR/FIR filter (B, A) to each dimension.

Equivalent to scipy.signal.filtfilt(B, A, data).

Return type:

SignalObj

makeCompatible(other, holdVals=0)[source]
Parameters:
Return type:

tuple[SignalObj, SignalObj]

abs()[source]

Element-wise absolute value (Matlab abs).

Return type:

SignalObj

log()[source]

Element-wise natural logarithm (Matlab log).

Return type:

SignalObj

with_metadata(*, name=None, xlabelval=None, xunits=None, yunits=None)[source]

Return a copy with selectively overridden metadata fields.

Parameters:
  • name (str | None)

  • xlabelval (str | None)

  • xunits (str | None)

  • yunits (str | None)

Return type:

SignalObj

median(axis=None)[source]

Column-wise median (default) or row-wise median of signal data.

median() or median(0) computes the median of each component across time. median(1) computes the median value at each time point across dimensions.

Parameters:

axis (int | None)

Return type:

SignalObj

mode(axis=None)[source]

Column-wise mode of signal data (Matlab mode).

Parameters:

axis (int | None)

Return type:

SignalObj

mean(axis=None)[source]

Column-wise mean (default) or row-wise mean of signal data.

mean() or mean(0) computes the mean of each component across time. mean(1) computes the mean value at each time point across dimensions.

Parameters:

axis (int | None)

Return type:

SignalObj

std(axis=None)[source]

Column-wise standard deviation (sample, ddof=1) of signal data.

std() or std(0) computes std of each component across time. std(1) computes std at each time point across dimensions.

Parameters:

axis (int | None)

Return type:

SignalObj

max(axis=None)[source]

Return (values, indices, times) of column-wise maxima.

Parameters:

axis (int | None)

min(axis=None)[source]

Return (values, indices, times) of column-wise minima.

Parameters:

axis (int | None)

resample(sample_rate)[source]

Return a resampled copy at sample_rate Hz.

Parameters:

sample_rate (float)

Return type:

SignalObj

resampleMe(newSampleRate)[source]

Resample data in-place to newSampleRate Hz via cubic interpolation.

Parameters:

newSampleRate (float)

Return type:

None

autocorrelation()[source]

Normalized auto-correlation for each signal dimension.

Returns a new SignalObj whose time axis is lag (in the original x-units) and whose data are the correlation coefficients normalised to unity at lag zero (Matlab autocorrelation).

Return type:

SignalObj

crosscorrelation(other)[source]

Normalized cross-correlation between two scalar signals.

Both signals must be one-dimensional. The result is normalised so that the peak equals the Pearson correlation coefficient (Matlab crosscorrelation).

Parameters:

other (SignalObj)

Return type:

SignalObj

xcorr(other=None, maxlag=None)[source]

Raw (un-normalised) cross-correlation (Matlab xcorr).

Computes pairwise cross-correlation for all dimension pairs. When other is None (auto-correlation), only non-negative lags are returned. maxlag truncates to |lag| ≤ maxlag samples.

Parameters:
  • other ('SignalObj' | None)

  • maxlag (int | None)

Return type:

SignalObj

shift(deltaT, updateLabels=False)[source]

Return a copy with time shifted by deltaT seconds.

Parameters:
Return type:

SignalObj

shiftMe(deltaT, updateLabels=False)[source]

In-place time shift by deltaT seconds (Matlab shiftMe).

Parameters:
Return type:

None

alignTime(timeMarker, newTime=0.0)[source]

Shift so that timeMarker becomes newTime (Matlab alignTime).

Only shifts if timeMarker falls within [minTime, maxTime], matching the Matlab implementation’s bounds check.

Parameters:
Return type:

None

findPeaks(peak_type='maxima', minDistance=None)[source]

Find local peaks in each signal dimension.

Parameters:
  • peak_type ('maxima' or 'minima')

  • minDistance (minimum sample distance between peaks (default:) – sampleRate * duration / 10).

Returns:

  • indices, values (lists of arrays (one per dimension).)

  • Note (The Matlab original has a bug where the 'minima' branch)

  • does not negate the data before calling findpeaks. This Python

  • port fixes that.

Return type:

tuple[list[ndarray], list[ndarray]]

findMaxima()[source]

Convenience wrapper: findPeaks('maxima').

Return type:

tuple[list[ndarray], list[ndarray]]

findMinima()[source]

Convenience wrapper: findPeaks('minima').

Return type:

tuple[list[ndarray], list[ndarray]]

findGlobalPeak(peak_type='maxima')[source]

Find the global max or min across each dimension.

Returns:

  • times (1-D array of times at which the peak occurs (one per dim).)

  • values (1-D array of peak values (one per dim).)

  • Note (The Matlab original has a typo (sOBj instead of sObj))

  • in the minima branch. This Python port fixes that.

Parameters:

peak_type (str)

Return type:

tuple[ndarray, ndarray]

alignToMax()[source]

Align all dimensions so their peaks coincide at the mean peak time.

Returns (aligned_signal, mean_peak_time). Matches Matlab SignalObj.alignToMax().

Return type:

tuple[SignalObj, float]

windowedSignal(windowTimes)[source]

Extract and concatenate windowed segments.

Matches Matlab SignalObj.windowedSignal().

Return type:

SignalObj

normWindowedSignal(windowTimes, numPoints=100, lbound=None, ubound=None)[source]

Normalize windowed signal segments to a common time axis.

Matches Matlab SignalObj.normWindowedSignal().

Parameters:
Return type:

SignalObj

getSubSignalsWithinNStd(nStd=2.0)[source]

Return sub-signals within nStd standard deviations of the mean.

Returns (filtered_signal, selected_indices). Matches Matlab SignalObj.getSubSignalsWithinNStd().

Parameters:

nStd (float)

Return type:

tuple[SignalObj, ndarray]

plotAllVariability(faceColor=None, linewidth=3.0, ciUpper=1.96, ciLower=None, ax=None)[source]

Plot mean ± CI shaded area. Matches Matlab plotAllVariability.

Parameters:
  • faceColor (color, optional) – Fill colour (default: tab:blue).

  • linewidth (float) – Width of mean line.

  • ciUpper (float or array) – Number of std-devs (scalar) or explicit bounds (array).

  • ciLower (float or array) – Number of std-devs (scalar) or explicit bounds (array).

  • ax (matplotlib Axes, optional)

plotVariability(selectorArray=None, ax=None)[source]

Plot mean ± CI for each label group. Matches Matlab plotVariability.

Parameters:
xcov(other=None, maxlag=None, scaleOpt='none')[source]

Cross-covariance (mean-removed xcorr). Matches Matlab xcov.

When called with no other argument (auto-covariance), only non-negative lags are returned — matching Matlab behaviour where data=tempC(M-1:end,index) and lags=tempLags(M-1:end).

Parameters:
Return type:

SignalObj

periodogram(NFFT=None)[source]

Power spectral density via periodogram (Matlab periodogram).

Loops over all signal dimensions like the Matlab implementation.

When NFFT is None we match MATLAB’s default of max(256, 2**nextpow2(N)) rather than scipy’s default of N, producing the denser frequency grid (and characteristic zero-notch comb) seen in the MATLAB reference figures.

Returns (frequencies, psd) where psd has shape (nfreqs,) for 1-D signals or (nfreqs, dimension) for multi-dimensional signals.

Parameters:

NFFT (int | None)

Return type:

tuple[ndarray, ndarray]

MTMspectrum(NW=4.0, NFFT=None, Pval=0.95, Kmax=None)[source]

Multi-taper spectral estimate (Matlab MTMspectrum).

Uses discrete prolate spheroidal sequences (DPSS / Slepian tapers). Loops over all signal dimensions like the Matlab implementation.

Parameters:
  • NW (float) – Time-bandwidth product (default 4).

  • NFFT (int, optional) – FFT length (default next power of 2 >= N).

  • Pval (float, optional) – Confidence level for the chi-squared confidence interval (default 0.95). Set to None to skip CI computation.

  • Kmax (int, optional) – Number of tapers (default 2*NW - 1).

Returns:

  • frequencies (ndarray)

  • psd (ndarray) – Shape (nfreqs,) for 1-D or (nfreqs, dimension).

  • psd_ci (ndarray or None) – Shape (nfreqs, 2) for 1-D or (nfreqs, 2*dimension) containing [lower, upper] columns per dimension. None when Pval is None.

Return type:

tuple[ndarray, ndarray, ndarray | None]

spectrogram(nperseg=256, noverlap=None, NFFT=None, window='hann')[source]

Short-time Fourier transform spectrogram (Matlab spectrogram).

Returns (frequencies, times, Sxx).

Parameters:
  • nperseg (int)

  • noverlap (int | None)

  • NFFT (int | None)

  • window (str)

Return type:

tuple[ndarray, ndarray, ndarray]

setConfInterval(bounds)[source]

Attach (lower, upper) confidence bounds aligned with time.

Parameters:

bounds (tuple[ndarray, ndarray])

Return type:

None

dataToStructure(selectorArray=None)[source]

Serialize signal data to a plain dict (Matlab dataToStructure).

Parameters:

selectorArray (Sequence[int] | ndarray | None)

Return type:

dict[str, Any]

toStructure()[source]

Serialize the full signal to a plain dict (Matlab toStructure).

Return type:

dict[str, Any]

static signalFromStruct(structure)[source]

Reconstruct a SignalObj from a dict (Matlab signalFromStruct).

Parameters:

structure (dict[str, Any])

Return type:

SignalObj

plot(selectorArray=None, plotPropsIn=None, handle=None)[source]

Plot selected signal dimensions (Matlab plot).

Parameters:
  • selectorArray (optional) – Dimension selector (labels, 0-based indices, or None for all visible dimensions).

  • plotPropsIn (optional) – Override Matplotlib format strings for each dimension.

  • handle (matplotlib Axes, optional) – Axes to draw into; defaults to plt.gca().

Return type:

list of Line2D