nstat.Covariate
- class nstat.Covariate(*args, **kwargs)[source]
Bases:
CovariateCanonical covariate type for model design matrices.
- __init__(*args, **kwargs)[source]
Construct a covariate signal (Matlab
Covariate).Accepts the same positional / keyword arguments as
SignalObj, with two convenience aliases for users coming from earlier Python releases:values=is forwarded to theSignalObjdata=parameter.units=is forwarded to theSignalObjyunits=parameter.
- Parameters:
*args – Forwarded to
SignalObj.__init__. Time is in seconds and the inferred sample rate is in Hz.**kwargs – Forwarded to
SignalObj.__init__. Time is in seconds and the inferred sample rate is in Hz.
- Return type:
None
Notes
After construction the
ciattribute isNone. Attach confidence intervals viasetConfInterval()orcomputeMeanPlusCI().See also
SignalObjBase time-series container.
nstat.confidence_interval.ConfidenceIntervalCI storage class used by
ci.
- 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
- computeMeanPlusCI(alphaVal=0.05)[source]
Compute row-wise mean with empirical confidence intervals.
Treats each column as a replicate. Returns a scalar
Covariatewhose CI bounds are the alphaVal/2 and 1−*alphaVal*/2 quantiles of the empirical CDF across replicates (MatlabcomputeMeanPlusCI).- Parameters:
alphaVal (float)
- Return type:
Covariate
- convertNamesToIndices(selectorArray)
Convert label names (or mixed) to 0-based indices.
Matches Matlab
SignalObj.convertNamesToIndices()(the Python port is 0-based throughout).
- copySignal()[source]
Deep-copy including confidence intervals (Matlab
copySignal).- Return type:
Covariate
- 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)[source]
Serialize data payload (Matlab
dataToStructureoverride).Thin wrapper around
SignalObj.dataToStructure()kept here so the MATLAB method-order parity audit pairs this Covariate-level declaration with the MATLABdataToStructureslot just beforefromStructure.
- 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)[source]
Apply a zero-phase filter (Matlab
filtfiltoverride).Thin wrapper around
SignalObj.filtfilt()that returns aCovariateso confidence-interval propagation continues to work on the result.- Return type:
Covariate
- 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).
- getSigRep(repType='standard')[source]
Return a signal representation of this covariate.
- Parameters:
repType (str) –
'standard'returnsselfunchanged.'zero-mean'returnsself - mean(self)with confidence intervals propagated (Matlab parity: uses operator overload so CIs shift by the same constant).- Return type:
Covariate
- getSubSignal(identifier)[source]
Return a sub-covariate preserving matching CIs.
- Return type:
Covariate
- 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)[source]
Plot signal dimensions with shaded confidence intervals.
- 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(ciObj)[source]
Attach one or more
ConfidenceIntervalobjects to this covariate.- Return type:
None
- 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.
- 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).