nstat.SpikeTrainCollection

class nstat.SpikeTrainCollection(trains=None)[source]

Bases: SpikeTrainCollection

Collection of aligned spike trains for ensemble analyses.

Parameters:

trains (Sequence[nspikeTrain] | nspikeTrain | None)

__init__(trains=None)[source]

Construct an ordered spike-train collection (Matlab nstColl).

Parameters:

trains (nspikeTrain, sequence of nspikeTrain, or None) – Initial spike train(s) to add. None creates an empty collection.

Return type:

None

Notes

On construction the collection captures the maximal sample rate across all input trains (in Hz) and the union of their observation windows (in seconds), and initialises the neuron mask to all ones (no neurons masked out).

Indexing is 0-based to match MATLAB (coll.getNST(0) is the first spike train). Trains added after construction are deep-copied (via nspikeTrain.nstCopy()) to prevent shared mutable state.

See also

nspikeTrain

Single-neuron point-process representation.

Trial

Combines a SpikeTrainCollection with covariates.

to_matrix(bin_edges)[source]
Parameters:

bin_edges (Sequence[float])

Return type:

ndarray

BinarySigRep()[source]

Return True if every train’s signal representation is binary.

Return type:

bool

addNeuronNamesToEnsCovColl(ensembleCovariates)[source]

Prefix ensemble-covariate labels with their neuron name.

Parameters:

ensembleCovariates (CovariateCollection)

Return type:

None

addSingleSpikeToColl(nst)[source]

Append a single spike train (deep-copied) to the collection.

Parameters:

nst (nspikeTrain)

Return type:

None

addToColl(nst)[source]

Add one or more spike trains (or another collection) to this collection.

Parameters:

nst (Sequence[nspikeTrain] | nspikeTrain | 'SpikeTrainCollection')

Return type:

None

areNeighborsSet()[source]

Return True if the neighbour matrix has been initialized.

Return type:

bool

dataToMatrix(selectorArray=None, binwidth=None, minTime=None, maxTime=None)[source]

Return an (nTimeBins, nNeurons) binary spike-count matrix.

Parameters:
Return type:

ndarray

enforceSampleRate()[source]

Resample any train whose rate differs from the collection rate.

Accesses self.nstrain directly (not via getNST) because the intent is in-place mutation of the stored trains.

Return type:

None

ensureConsistancy()[source]

Enforce consistent sample rate and time bounds across all trains.

Return type:

None

estimateVarianceAcrossTrials(numBasis=None, windowTimes=None, numIter=None, fitType=None)[source]

Estimate the state-noise covariance Q from bootstrap GLM fits.

Used internally by ssglm() / ssglmFB() to initialise the EM algorithm’s state-noise prior.

Parameters:
  • numBasis (int | None)

  • numIter (int | None)

  • fitType (str | None)

Return type:

ndarray

findMaxSampleRate()[source]

Return the highest sample rate among all trains.

Return type:

float

static fromStructure(structure)[source]

Reconstruct from a dict produced by toStructure() (Matlab nstColl.fromStructure).

Parameters:

structure (dict[str, Any])

Return type:

SpikeTrainCollection

static generateUnitImpulseBasis(basisWidth, minTime, maxTime, sampleRate=1000.0)[source]

Create a piecewise-constant (unit impulse) basis Covariate.

Each column is a rectangular pulse spanning one basisWidth interval, used as the design matrix for GLM-PSTH estimation.

Parameters:
Return type:

Covariate

get(name=None)[source]

Return spike train(s) by neuron name (Matlab nstColl.get).

Mirrors MATLAB’s get.uniqueNeuronNames property accessor, which delegates to getUniqueNSTnames(). When name is None the list of unique neuron names is returned; when a name is supplied the corresponding spike train(s) are returned via getNSTFromName().

Parameters:

name (str | None)

getEnsembleNeuronCovariates(neuronNum=1, neighborIndex=None, windowTimes=None)[source]

Build ensemble-history covariates for neuronNum from its neighbours.

Parameters:

neuronNum (int)

getFieldVal(fieldName)[source]

Collect a named field from every spike train (Matlab nstColl.getFieldVal).

Parameters:

fieldName (str)

getFirstSpikeTime()[source]

Return the earliest time boundary across all trains.

Return type:

float

getISIs(selectorArray=None, minTime=None, maxTime=None)[source]

Return a list of ISI arrays, one per selected neuron.

Parameters:
Return type:

list[ndarray]

getIndFromMask()[source]

Return 0-based indices of neurons currently enabled by the mask.

Return type:

list[int]

getIndFromMaskMinusOne(neuron)[source]

Return active indices excluding neuron (0-based).

Parameters:

neuron (int)

Return type:

list[int]

getLastSpikeTime()[source]

Return the latest time boundary across all trains.

Return type:

float

getMaxBinSizeBinary()[source]

Return the largest bin-width that keeps all active trains binary.

Return type:

float

getMinISIs(selectorArray=None, minTime=None, maxTime=None)[source]

Return the minimum ISI for each selected neuron.

Parameters:
Return type:

ndarray

getNST(idx)[source]

Return spike train(s) by 0-based index (Matlab nstColl.getNST).

Always returns a deep copy of the stored train (never the stored reference itself). This is intentional — the PR #80 non-destructive contract for getNST was previously implemented as copy-only-when-rates-differ, which meant callers in the common path got a reference and could silently mutate the stored train via attribute assignment. All in-place collection-wide operations (e.g. enforceSampleRate) access self.nstrain directly and bypass this method.

Return type:

nspikeTrain | list[nspikeTrain]

getNSTFromName(neuronName=None)[source]

Return spike train(s) matching the given neuron name(s).

getNSTIndicesFromName(name)[source]

Return 0-based index(es) for a neuron name (or list of names).

Parameters:

name (Sequence[str] | str)

getNSTnameFromInd(ind)[source]

Return the neuron name for 0-based index ind.

Parameters:

ind (int)

Return type:

str

getNSTnames(selectorArray=None)[source]

Return neuron names, optionally filtered by selectorArray (0-based indices).

Return type:

list[str]

getNeighbors(neuronNum)[source]

Return the 0-based neighbour indices for one or more neurons.

Parameters:

neuronNum (int | Sequence[int])

getSpikeTimes(minTime=None, maxTime=None)[source]

Return a list of spike-time arrays, one per active neuron.

Parameters:
Return type:

list[ndarray]

getUniqueNSTnames(selectorArray=None)[source]

Return unique, insertion-ordered neuron names.

Return type:

list[str]

get_nst(idx)[source]

Return a spike train by 0-based index (Pythonic API).

Parameters:

idx (int)

Return type:

nspikeTrain

isNeuronMaskSet()[source]

Return True if any neuron is currently masked out.

Return type:

bool

isSigRepBinary()[source]

Alias for BinarySigRep().

Return type:

bool

length()[source]

Return the number of spike trains (Matlab nstColl.length).

Return type:

int

merge(nstColl2)[source]

Merge another collection into this one (in-place).

Parameters:

nstColl2 (SpikeTrainCollection)

Return type:

SpikeTrainCollection

property neuronNames: list[str]

Neuron name for each spike train in the collection.

Mirrors the MATLAB neuronNames stored property. In Python this is derived dynamically from each train’s .name attribute so it is always consistent with the underlying data.

property num_spike_trains: int

Number of spike trains in this collection.

plot(selectorArray=None, minTime=None, maxTime=None, handle=None, reverseOrder=False, **__)[source]

Plot a spike-train raster.

Parameters:
  • selectorArray (sequence of int, optional) – 0-based indices of neurons to plot. Defaults to the neuron mask (or all neurons if no mask is set). Matches Matlab positional arg.

  • minTime (float, optional) – Time window to display. Defaults to the collection’s time span.

  • maxTime (float, optional) – Time window to display. Defaults to the collection’s time span.

  • handle (matplotlib Axes, optional) – Axes to plot into.

  • reverseOrder (bool) – If True, reverse the display order so the last neuron is at the top. Matches Matlab reverseOrderPlot parameter.

plotExponentialFit(selectorArray=None, minTime=None, maxTime=None, numBins=None, handle=None)[source]

Plot exponential-distribution fits of ISIs for selected neurons.

Parameters:
plotISIHistogram(selectorArray=None, minTime=None, maxTime=None, handle=None)[source]

Plot ISI histograms for each selected neuron in stacked subplots.

Parameters:
psth(binwidth=0.1, selectorArray=None, minTime=None, maxTime=None)[source]

Compute the peri-stimulus time histogram (standard binned PSTH).

Returns a Covariate with firing rate in Hz.

Parameters:
Return type:

Covariate

psthBars(binwidth=0.1, selectorArray=None, minTime=None, maxTime=None)[source]

Deterministic pure-Python fallback for MATLAB nstColl.psthBars.

MATLAB delegates this method to an external BARS package that is not bundled with the source tree. The Python port preserves the public surface and return structure with a smoothed PSTH approximation.

Parameters:
Return type:

SignalObj

psthGLM(basisWidth=None, history=None, fitType='poisson', selectorArray=None, minTime=None, maxTime=None, sampleRate=None, *, binwidth=None, windowTimes=None, alphaVal=0.05, Mc=1000)[source]

GLM-based PSTH estimation (Matlab nstColl.psthGLM).

Parameters match MATLAB: psthGLM(basisWidth, history, fitType, selectorArray, minTime, maxTime, sampleRate)

The Python keyword-only binwidth and windowTimes are accepted as aliases for basisWidth and history respectively.

Returns (psth_covariate, histSignal, psthFitResult) matching the Matlab signature.

Parameters:
resample(sampleRate)[source]

Resample all trains to sampleRate and align time bounds.

Parameters:

sampleRate (float)

Return type:

None

resetMask()[source]

Enable all neurons (ones-mask).

Return type:

None

restoreToOriginal(rMask=0)[source]

Restore all trains to their original state; optionally reset the mask.

Parameters:

rMask (int)

Return type:

None

setMask(mask)[source]

Set the neuron mask from a binary array or 0-based indices.

Parameters:

mask (Sequence[int] | ndarray)

Return type:

None

setMaxTime(value=None)[source]

Set the maximum time for every train in the collection.

Parameters:

value (float | None)

Return type:

None

setMinTime(value=None)[source]

Set the minimum time for every train in the collection.

Parameters:

value (float | None)

Return type:

None

setNeighbors(neighborArray=None)[source]

Set or auto-generate the neuron neighbour matrix.

If neighborArray is None, every neuron is a neighbour of every other neuron (all-to-all minus self).

Parameters:

neighborArray (Sequence[Sequence[int]] | ndarray | None)

Return type:

None

setNeuronMask(mask)[source]

Set the binary neuron mask directly (length must match numSpikeTrains).

Parameters:

mask (Sequence[int] | ndarray)

Return type:

None

setNeuronMaskFromInd(mask)[source]

Set the neuron mask from 0-based neuron indices.

Parameters:

mask (Sequence[int] | ndarray)

Return type:

None

shiftTime(timeShift=None)[source]

Return a new collection with spike times shifted by timeShift.

Parameters:

timeShift (float | None)

Return type:

SpikeTrainCollection

ssglm(windowTimes=None, numBasis=None, numVarEstIter=None, fitType=None, rng=None)[source]

State-space GLM via EM algorithm (forward only).

Matches Matlab nstColl.ssglm(). Estimates time-varying firing rate using a state-space model with EM parameter estimation.

Parameters:
  • rng (np.random.Generator, optional) – Random number generator used to jitter zero entries in the initial variance estimate. Defaults to np.random.default_rng() (non-reproducible across runs). Pass an explicit seeded generator for reproducible fits.

  • windowTimes (array-like or None) – History window boundaries. None for no history.

  • numBasis (int or None) – Number of basis functions. Defaults to duration/0.02.

  • numVarEstIter (int or None) – Iterations for variance estimation. Default 10.

  • fitType ('poisson' or 'binomial')

Returns:

  • xK ((R, K) estimated state trajectories)

  • WK ((R, R, K) estimated state covariances)

  • Qhat ((R,) estimated state noise variance)

  • gammahat ((J,) estimated history coefficients)

  • logll (float, log-likelihood)

  • fitResults (FitResult)

ssglmFB(windowTimes=None, numBasis=None, numVarEstIter=None, fitType=None, rng=None)[source]

State-space GLM via EM Forward-Backward algorithm.

Enhanced version of ssglm() that uses forward-backward-forward iterations for improved convergence. Calls PPSS_EMFB.

Parameters:
  • rng (np.random.Generator, optional) – Random number generator for Q0 jitter; see ssglm().

  • windowTimes (array-like or None) – History window boundaries.

  • numBasis (int or None) – Number of basis functions.

  • numVarEstIter (int or None) – Iterations for variance estimation.

  • fitType ('poisson' or 'binomial')

Returns:

  • xK, WK, Wku, Qhat, gammahat, fitResults, stimulus, stimCIs, logll,

  • QhatAll, gammahatAll, nIter

toSpikeTrain(selectorArray=None, minTime=None, maxTime=None, windowTimes=None)[source]

Collapse selected spike trains into a single nspikeTrain.

Concatenates spike times end-to-end, optionally rescaling each trial into windows defined by windowTimes.

Parameters:
Return type:

nspikeTrain

toStructure()[source]

Serialize to a plain dict (Matlab nstColl.toStructure).

Return type:

dict[str, Any]

property uniqueNeuronNames: list[str]

Unique, insertion-ordered neuron names in the collection.

updateTimes(nst)[source]

Expand collection time bounds to include nst, or clamp nst.

Parameters:

nst (nspikeTrain)

Return type:

None