nstat.SignalObj
- class nstat.SignalObj(time, data, name='', xlabelval='time', xunits='s', yunits='', dataLabels=None, plotProps=None, **kwargs)[source]
Bases:
objectMulti-dimensional time-series signal object (Matlab
SignalObj).SignalObjis 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
CovariateSignalObj subclass with confidence-interval support.
nspikeTrainPoint-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 aliasxlabel=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_labelslegacy aliases above. Any other keyword raisesTypeError.
- 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 to1000.0Hz, 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
CovariateSignalObj subclass with confidence-interval support.
nspikeTrainPoint-process companion class for spike data.
- setYLabel(name)[source]
Set the y-axis label (alias for
setName).- Parameters:
name (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.
- 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.
- 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.
- setPlotProps(plotProps, index=None)[source]
Set per-dimension Matplotlib format strings.
When index (0-based) is given, only that dimension is updated.
- setMask(mask=None)[source]
Flexible mask setter accepting indices, labels, or a binary vector.
Noneclears the mask (all hidden). A binary vector of lengthdimensionis used directly. A list of labels or 0-based indices enables only those dimensions.
- areDataLabelsEmpty()[source]
Return
Trueif all data labels are empty strings.Matches Matlab
SignalObj.areDataLabelsEmpty().- Return type:
- isLabelPresent(label)[source]
Return
Trueif label matches any data label or equals'all'.Matches Matlab
SignalObj.isLabelPresent().
- convertNamesToIndices(selectorArray)[source]
Convert label names (or mixed) to 0-based indices.
Matches Matlab
SignalObj.convertNamesToIndices()(the Python port is 0-based throughout).
- 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.
- getSubSignalFromInd(selectorArray)[source]
Return a new
SignalObjwith only the selected dimensions (0-based).
- getSubSignal(identifier)[source]
Return a sub-signal selected by labels, indices, or mixed.
- Return type:
- findNearestTimeIndices(times)[source]
Return 0-based indices of the samples nearest to each time in times.
- merge(other, holdVals=0)[source]
Merge other signal columns into self.
Matlab calls
makeCompatiblefirst so that signals with different time grids are reconciled automatically. The Python version now does the same.
- ldivide(other)[source]
Element-wise left division (Matlab
.\):other ./ self.Matches Matlab
SignalObj.ldivide().- Return type:
- clearPlotProps(index=None)[source]
Clear plot properties. Matches Matlab
clearPlotProps.- Return type:
None
- plotPropsSet()[source]
Return
Trueif any plot property is non-empty.Matches Matlab
SignalObj.plotPropsSet().- Return type:
- 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).
- 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
- derivative()[source]
Return the per-sample forward-difference derivative.
Matches MATLAB
SignalObj.m:761which is a method (called ass.derivative()), not a property. The previous Python implementation was a@propertyso MATLAB-ported code callingsig.derivative()silently failed withTypeError: 'SignalObj' object is not callable. This is now a regular method; accesssig.derivative()(with parentheses) to compute the derivative.- Return type:
- 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/maxTimeare used.
- 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:
- 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:
- with_metadata(*, name=None, xlabelval=None, xunits=None, yunits=None)[source]
Return a copy with selectively overridden metadata fields.
- median(axis=None)[source]
Column-wise median (default) or row-wise median of signal data.
median()ormedian(0)computes the median of each component across time.median(1)computes the median value at each time point across dimensions.
- mean(axis=None)[source]
Column-wise mean (default) or row-wise mean of signal data.
mean()ormean(0)computes the mean of each component across time.mean(1)computes the mean value at each time point across dimensions.
- std(axis=None)[source]
Column-wise standard deviation (sample, ddof=1) of signal data.
std()orstd(0)computes std of each component across time.std(1)computes std at each time point across dimensions.
- 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)
- 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
SignalObjwhose time axis is lag (in the original x-units) and whose data are the correlation coefficients normalised to unity at lag zero (Matlabautocorrelation).- Return type:
- 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).
- 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| ≤ maxlagsamples.
- shiftMe(deltaT, updateLabels=False)[source]
In-place time shift by deltaT seconds (Matlab
shiftMe).
- 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.
- 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 Pythonport fixes that.
- Return type:
- 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 (
sOBjinstead ofsObj))in the minima branch. This Python port fixes that.
- Parameters:
peak_type (str)
- Return type:
- alignToMax()[source]
Align all dimensions so their peaks coincide at the mean peak time.
Returns
(aligned_signal, mean_peak_time). Matches MatlabSignalObj.alignToMax().
- windowedSignal(windowTimes)[source]
Extract and concatenate windowed segments.
Matches Matlab
SignalObj.windowedSignal().- Return type:
- normWindowedSignal(windowTimes, numPoints=100, lbound=None, ubound=None)[source]
Normalize windowed signal segments to a common time axis.
Matches Matlab
SignalObj.normWindowedSignal().
- getSubSignalsWithinNStd(nStd=2.0)[source]
Return sub-signals within nStd standard deviations of the mean.
Returns
(filtered_signal, selected_indices). Matches MatlabSignalObj.getSubSignalsWithinNStd().
- plotAllVariability(faceColor=None, linewidth=3.0, ciUpper=1.96, ciLower=None, ax=None)[source]
Plot mean ± CI shaded area. Matches Matlab
plotAllVariability.- Parameters:
- plotVariability(selectorArray=None, ax=None)[source]
Plot mean ± CI for each label group. Matches Matlab
plotVariability.
- 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)andlags=tempLags(M-1:end).
- periodogram(NFFT=None)[source]
Power spectral density via periodogram (Matlab
periodogram).Loops over all signal dimensions like the Matlab implementation.
When NFFT is
Nonewe match MATLAB’s default ofmax(256, 2**nextpow2(N))rather than scipy’s default ofN, 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.
- 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
Noneto 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.Nonewhen Pval isNone.
- Return type:
- spectrogram(nperseg=256, noverlap=None, NFFT=None, window='hann')[source]
Short-time Fourier transform spectrogram (Matlab
spectrogram).Returns
(frequencies, times, Sxx).
- dataToStructure(selectorArray=None)[source]
Serialize signal data to a plain dict (Matlab
dataToStructure).
- static signalFromStruct(structure)[source]
Reconstruct a
SignalObjfrom a dict (MatlabsignalFromStruct).
- plot(selectorArray=None, plotPropsIn=None, handle=None)[source]
Plot selected signal dimensions (Matlab
plot).- Parameters:
selectorArray (optional) – Dimension selector (labels, 0-based indices, or
Nonefor 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