nstat.Signal
- class nstat.Signal(time, data, name='', xlabelval='time', xunits='s', yunits='', dataLabels=None, plotProps=None, **kwargs)[source]
Bases:
SignalObjCanonical Pythonic signal abstraction for nSTAT.
- Parameters:
- __init__(time, data, name='', xlabelval='time', xunits='s', yunits='', dataLabels=None, plotProps=None, **kwargs)
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.
- sub_signal(index)[source]
Return one channel as a new signal.
Uses zero-based indexing in Python, unlike MATLAB’s one-based indexing.
- MTMspectrum(NW=4.0, NFFT=None, Pval=0.95, Kmax=None)
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:
- alignTime(timeMarker, newTime=0.0)
Shift so that timeMarker becomes newTime (Matlab
alignTime).Only shifts if timeMarker falls within
[minTime, maxTime], matching the Matlab implementation’s bounds check.
- alignToMax()
Align all dimensions so their peaks coincide at the mean peak time.
Returns
(aligned_signal, mean_peak_time). Matches MatlabSignalObj.alignToMax().
- areDataLabelsEmpty()
Return
Trueif all data labels are empty strings.Matches Matlab
SignalObj.areDataLabelsEmpty().- Return type:
- autocorrelation()
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:
- clearPlotProps(index=None)
Clear plot properties. Matches Matlab
clearPlotProps.- Return type:
None
- convertNamesToIndices(selectorArray)
Convert label names (or mixed) to 0-based indices.
Matches Matlab
SignalObj.convertNamesToIndices()(the Python port is 0-based throughout).
- crosscorrelation(other)
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).
- dataToMatrix(selectorArray=None)
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.
- dataToStructure(selectorArray=None)
Serialize signal data to a plain dict (Matlab
dataToStructure).
- derivative()
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:
- derivativeAt(x0)
Return the derivative value(s) at time(s) x0.
- filter(B, A=1)
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)
Apply a zero-phase IIR/FIR filter
(B, A)to each dimension.Equivalent to
scipy.signal.filtfilt(B, A, data).- Return type:
- findGlobalPeak(peak_type='maxima')
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:
- findIndFromDataMask()
Return 0-based indices of dimensions currently visible (mask == 1).
- findMaxima()
Convenience wrapper:
findPeaks('maxima').
- findMinima()
Convenience wrapper:
findPeaks('minima').
- findNearestTimeIndex(time)
Return the 0-based index of the sample nearest to time.
- findNearestTimeIndices(times)
Return 0-based indices of the samples nearest to each time in times.
- findPeaks(peak_type='maxima', minDistance=None)
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:
- getIndexFromLabel(label)
Return 0-based indices of dimensions whose label equals label.
- getIndicesFromLabels(label)
Return 0-based index(es) for one or more data-label strings.
- getOrigDataSig()
Return the original (pre-resample) data as a new
SignalObj.- Return type:
- getPlotProps(index)
Return the plot property for dimension index (0-based).
- getSigInTimeWindow(wMin=None, wMax=None, holdVals=0)
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).
- getSubSignal(identifier)
Return a sub-signal selected by labels, indices, or mixed.
- Return type:
- getSubSignalFromInd(selectorArray)
Return a new
SignalObjwith only the selected dimensions (0-based).
- getSubSignalFromNames(labels)
Return a sub-signal selected by data-label name(s).
- getSubSignalsWithinNStd(nStd=2.0)
Return sub-signals within nStd standard deviations of the mean.
Returns
(filtered_signal, selected_indices). Matches MatlabSignalObj.getSubSignalsWithinNStd().
- getValueAt(x)
Return signal value(s) at time(s) x via nearest-neighbour lookup.
- integral(t0=None, tf=None)
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.
- isLabelPresent(label)
Return
Trueif label matches any data label or equals'all'.Matches Matlab
SignalObj.isLabelPresent().
- ldivide(other)
Element-wise left division (Matlab
.\):other ./ self.Matches Matlab
SignalObj.ldivide().- Return type:
- makeCompatible(other, holdVals=0)
- max(axis=None)
Return
(values, indices, times)of column-wise maxima.- Parameters:
axis (int | None)
- mean(axis=None)
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.
- median(axis=None)
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.
- merge(other, holdVals=0)
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.
- min(axis=None)
Return
(values, indices, times)of column-wise minima.- Parameters:
axis (int | None)
- mode(axis=None)
Column-wise mode of signal data (Matlab
mode).
- normWindowedSignal(windowTimes, numPoints=100, lbound=None, ubound=None)
Normalize windowed signal segments to a common time axis.
Matches Matlab
SignalObj.normWindowedSignal().
- periodogram(NFFT=None)
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.
- plot(selectorArray=None, plotPropsIn=None, handle=None)
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
- plotAllVariability(faceColor=None, linewidth=3.0, ciUpper=1.96, ciLower=None, ax=None)
Plot mean ± CI shaded area. Matches Matlab
plotAllVariability.- Parameters:
- plotPropsSet()
Return
Trueif any plot property is non-empty.Matches Matlab
SignalObj.plotPropsSet().- Return type:
- plotVariability(selectorArray=None, ax=None)
Plot mean ± CI for each label group. Matches Matlab
plotVariability.
- power(exponent)
Element-wise power
data ** exponent(Matlabpower).
- resample(sample_rate)
Return a resampled copy at sample_rate Hz.
- resampleMe(newSampleRate)
Resample data in-place to newSampleRate Hz via cubic interpolation.
- Parameters:
newSampleRate (float)
- Return type:
None
- resetMask()
Reset the data mask so all dimensions are visible.
- Return type:
None
- restoreToOriginal(rMask=0)
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
- setConfInterval(bounds)
Attach
(lower, upper)confidence bounds aligned with time.
- setDataLabels(dataLabels)
Set per-dimension data labels.
A single string is broadcast to all dimensions. A sequence must have length equal to
dimension.
- setDataMask(dataMask)
Set binary data mask (1 = visible, 0 = hidden) for each dimension.
- setMask(mask=None)
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.
- setMaskByInd(index)
Enable only the dimensions at the given 0-based indices.
- setMaskByLabels(labels)
Enable only the dimensions whose data labels match labels.
- setMaxTime(maxTime=None, holdVals=0)
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.
- setMinTime(minTime=None, holdVals=0)
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.
- setPlotProps(plotProps, index=None)
Set per-dimension Matplotlib format strings.
When index (0-based) is given, only that dimension is updated.
- setSampleRate(sampleRate)
Set the sample rate, resampling the data if it differs from current.
- Parameters:
sampleRate (float)
- Return type:
None
- setUnits(xUnits, yUnits=None)
Set x-axis and optionally y-axis units.
- shift(deltaT, updateLabels=False)
Return a copy with time shifted by deltaT seconds.
- shiftMe(deltaT, updateLabels=False)
In-place time shift by deltaT seconds (Matlab
shiftMe).
- static signalFromStruct(structure)
Reconstruct a
SignalObjfrom a dict (MatlabsignalFromStruct).
- spectrogram(nperseg=256, noverlap=None, NFFT=None, window='hann')
Short-time Fourier transform spectrogram (Matlab
spectrogram).Returns
(frequencies, times, Sxx).
- std(axis=None)
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.
- toStructure()
Serialize the full signal to a plain dict (Matlab
toStructure).
- windowedSignal(windowTimes)
Extract and concatenate windowed segments.
Matches Matlab
SignalObj.windowedSignal().- Return type:
- with_metadata(*, name=None, xlabelval=None, xunits=None, yunits=None)
Return a copy with selectively overridden metadata fields.
- xcorr(other=None, maxlag=None)
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.
- xcov(other=None, maxlag=None, scaleOpt='none')
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).