nstat.Covariate

class nstat.Covariate(*args, **kwargs)[source]

Bases: Covariate

Canonical 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 the SignalObj data= parameter.

  • units= is forwarded to the SignalObj yunits= 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 ci attribute is None. Attach confidence intervals via setConfInterval() or computeMeanPlusCI().

See also

SignalObj

Base time-series container.

nstat.confidence_interval.ConfidenceInterval

CI storage class used by ci.

standardize()[source]
Return type:

Covariate

classmethod from_values(time, values, *, name='covariate', units='')[source]
Parameters:
Return type:

Covariate

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 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]

property T: SignalObj

Transpose the data matrix. Matches Matlab ctranspose / transpose.

abs()

Element-wise absolute value (Matlab abs).

Return type:

SignalObj

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.

Parameters:
Return type:

None

alignToMax()

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]

areDataLabelsEmpty()

Return True if all data labels are empty strings.

Matches Matlab SignalObj.areDataLabelsEmpty().

Return type:

bool

autocorrelation()

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

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 Covariate whose CI bounds are the alphaVal/2 and 1−*alphaVal*/2 quantiles of the empirical CDF across replicates (Matlab computeMeanPlusCI).

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).

Return type:

list[int] | ndarray

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).

Parameters:

other (SignalObj)

Return type:

SignalObj

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.

Parameters:

selectorArray (Sequence[int] | ndarray | None)

Return type:

ndarray

dataToStructure(selectorArray=None)[source]

Serialize data payload (Matlab dataToStructure override).

Thin wrapper around SignalObj.dataToStructure() kept here so the MATLAB method-order parity audit pairs this Covariate-level declaration with the MATLAB dataToStructure slot just before fromStructure.

Parameters:

selectorArray (Sequence[int] | ndarray | None)

Return type:

dict[str, Any]

derivative()

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)

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

Parameters:

x0 (Sequence[float] | float)

property dimension: int

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

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:

SignalObj

filtfilt(B, A=1)[source]

Apply a zero-phase filter (Matlab filtfilt override).

Thin wrapper around SignalObj.filtfilt() that returns a Covariate so 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 (sOBj instead of sObj))

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

Parameters:

peak_type (str)

Return type:

tuple[ndarray, ndarray]

findIndFromDataMask()

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

Return type:

list[int]

findMaxima()

Convenience wrapper: findPeaks('maxima').

Return type:

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

findMinima()

Convenience wrapper: findPeaks('minima').

Return type:

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

findNearestTimeIndex(time)

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

Parameters:

time (float)

Return type:

int

findNearestTimeIndices(times)

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

Parameters:

times (Sequence[float] | ndarray)

Return type:

ndarray

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 Python

  • port fixes that.

Return type:

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

static fromStructure(structure)[source]

Reconstruct a Covariate (with optional CIs) from a dict.

Parameters:

structure (dict[str, Any])

Return type:

Covariate

get(identifier)[source]

MATLAB get / subscript alias for __getitem__().

getData()

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

Return type:

ndarray

getIndexFromLabel(label)

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

Parameters:

label (str)

Return type:

list[int]

getIndicesFromLabels(label)

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

Parameters:

label (Sequence[str] | str)

getOrigDataSig()

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

Return type:

SignalObj

getOriginalData()

Return (originalTime, originalData) copies.

Return type:

tuple[ndarray, ndarray]

getPlotProps(index)

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

Parameters:

index (int)

Return type:

Any

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).

Parameters:
Return type:

SignalObj

getSigRep(repType='standard')[source]

Return a signal representation of this covariate.

Parameters:

repType (str) – 'standard' returns self unchanged. 'zero-mean' returns self - 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 SignalObj with only the selected dimensions (0-based).

Parameters:

selectorArray (Sequence[int] | ndarray)

Return type:

SignalObj

getSubSignalFromNames(labels)

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

Parameters:

labels (Sequence[str] | str)

Return type:

SignalObj

getSubSignalsWithinNStd(nStd=2.0)

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]

getTime()

Return a copy of the time vector.

Return type:

ndarray

getValueAt(x)

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

Parameters:

x (Sequence[float] | float)

Return type:

ndarray

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 / maxTime are used.

Parameters:
Return type:

SignalObj

isConfIntervalSet()[source]

Return True if at least one dimension has a CI attached.

Return type:

bool

isLabelPresent(label)

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

Matches Matlab SignalObj.isLabelPresent().

Parameters:

label (str)

Return type:

bool

isMaskSet()

Return True if any dimension is currently masked out.

Return type:

bool

ldivide(other)

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

Matches Matlab SignalObj.ldivide().

Return type:

SignalObj

log()

Element-wise natural logarithm (Matlab log).

Return type:

SignalObj

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

tuple[SignalObj, SignalObj]

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() 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

median(axis=None)

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

merge(other, holdVals=0)

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

min(axis=None)

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

Parameters:

axis (int | None)

minus(other)[source]

MATLAB minus alias for __sub__().

mode(axis=None)

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

Parameters:

axis (int | None)

Return type:

SignalObj

property mu: SignalObj

Column-wise mean as a SignalObj (Matlab mu property).

normWindowedSignal(windowTimes, numPoints=100, lbound=None, ubound=None)

Normalize windowed signal segments to a common time axis.

Matches Matlab SignalObj.normWindowedSignal().

Parameters:
Return type:

SignalObj

periodogram(NFFT=None)

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]

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:
  • 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)

plotPropsSet()

Return True if any plot property is non-empty.

Matches Matlab SignalObj.plotPropsSet().

Return type:

bool

plotVariability(selectorArray=None, ax=None)

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

Parameters:
plus(other)[source]

MATLAB plus alias for __add__().

power(exponent)

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

Parameters:

exponent (float)

Return type:

SignalObj

resample(sample_rate)

Return a resampled copy at sample_rate Hz.

Parameters:

sample_rate (float)

Return type:

SignalObj

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

property sample_rate: float

Sampling rate in Hz (alias for sampleRate).

setConfInterval(ciObj)[source]

Attach one or more ConfidenceInterval objects 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.

Parameters:

dataLabels (Sequence[str] | str | None)

Return type:

None

setDataMask(dataMask)

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

Parameters:

dataMask (Sequence[int] | ndarray)

Return type:

None

setMask(mask=None)

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

setMaskByInd(index)

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

Parameters:

index (Sequence[int] | ndarray)

Return type:

None

setMaskByLabels(labels)

Enable only the dimensions whose data labels match labels.

Parameters:

labels (Sequence[str] | str)

Return type:

None

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.

Parameters:
Return type:

None

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.

Parameters:
Return type:

None

setName(name)

Set the signal name (y-axis label).

Parameters:

name (str)

Return type:

None

setPlotProps(plotProps, index=None)

Set per-dimension Matplotlib format strings.

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

Parameters:
Return type:

None

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.

Parameters:
  • xUnits (str)

  • yUnits (str | None)

Return type:

None

setXUnits(units)

Set the x-axis unit string.

Parameters:

units (str)

Return type:

None

setXlabel(name)

Set the x-axis label string.

Parameters:

name (str)

Return type:

None

setYLabel(name)

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

Parameters:

name (str)

Return type:

None

setYUnits(units)

Set the y-axis unit string.

Parameters:

units (str)

Return type:

None

shift(deltaT, updateLabels=False)

Return a copy with time shifted by deltaT seconds.

Parameters:
Return type:

SignalObj

shiftMe(deltaT, updateLabels=False)

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

Parameters:
Return type:

None

property sigma: SignalObj

Column-wise standard deviation as a SignalObj (Matlab sigma).

static signalFromStruct(structure)

Reconstruct a SignalObj from a dict (Matlab signalFromStruct).

Parameters:

structure (dict[str, Any])

Return type:

SignalObj

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

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]

sqrt()

Element-wise square root (Matlab sqrt).

Return type:

SignalObj

std(axis=None)

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

toStructure()[source]

Serialize to a dict, including CI payload if present.

Return type:

dict[str, Any]

property units: str

Y-axis unit string (alias for yunits).

property values: ndarray

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

windowedSignal(windowTimes)

Extract and concatenate windowed segments.

Matches Matlab SignalObj.windowedSignal().

Return type:

SignalObj

with_metadata(*, name=None, xlabelval=None, xunits=None, yunits=None)

Return a copy with selectively overridden metadata fields.

Parameters:
  • name (str | None)

  • xlabelval (str | None)

  • xunits (str | None)

  • yunits (str | None)

Return type:

SignalObj

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| ≤ maxlag samples.

Parameters:
  • other ('SignalObj' | None)

  • maxlag (int | None)

Return type:

SignalObj

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) and lags=tempLags(M-1:end).

Parameters:
Return type:

SignalObj