nstat.Trial

class nstat.Trial(spike_collection=None, covariate_collection=None, events=None, hist=None, ensCovHist=None, ensCovMask=None, *, spikeColl=None, covarColl=None, event=None)[source]

Bases: object

Single-trial data container binding spikes, covariates, and events (Matlab Trial).

A Trial enforces consistent time bounds and sample rate across its spike collection, covariate collection, and optional event stream. It provides the design-matrix construction used by Analysis to fit point-process GLMs.

Parameters:
  • spike_collection (SpikeTrainCollection) – Neural spike data.

  • covariate_collection (CovariateCollection) – Stimulus or task covariates.

  • events (Events, optional) – Discrete event markers.

  • hist (History or array_like, optional) – Self-history specification.

  • ensCovHist (History or array_like, optional) – Ensemble-history specification.

  • ensCovMask (array_like, optional) – Binary mask for ensemble neighbours.

  • spikeColl (SpikeTrainCollection | None)

  • covarColl (CovariateCollection | None)

  • event (Events | None)

__init__(spike_collection=None, covariate_collection=None, events=None, hist=None, ensCovHist=None, ensCovMask=None, *, spikeColl=None, covarColl=None, event=None)[source]

Construct a Trial bundling spikes, covariates, and events (Matlab Trial).

Parameters:
  • spike_collection (SpikeTrainCollection) – Neural spike data. Required. Also accepted as the MATLAB-style keyword spikeColl=.

  • covariate_collection (CovariateCollection) – Stimulus or task covariates. Required. Also accepted as the MATLAB-style keyword covarColl=.

  • events (Events, optional) – Discrete event markers (e.g. trial onsets). Also accepted as the MATLAB-style keyword event=.

  • hist (History or array_like, optional) – Self-history specification. May be a History object or a vector of window boundary times (seconds). An empty list / None is the “unset” sentinel for MATLAB parity.

  • ensCovHist (History or array_like, optional) – Ensemble-history specification (history terms aggregated across neighbour neurons).

  • ensCovMask (array_like, optional) – Binary mask selecting which neighbours contribute ensemble history.

  • spikeColl (SpikeTrainCollection | None)

  • covarColl (CovariateCollection | None)

  • event (Events | None)

Return type:

None

Notes

The constructor enforces consistent time bounds (in seconds) and sample rate (in Hz) across the spike collection and covariate collection. Resampling is performed automatically when the two disagree.

Raises:

ValueError – If spike_collection or covariate_collection is missing or of the wrong type.

Parameters:
Return type:

None

property spike_collection: SpikeTrainCollection

The trial’s spike-train collection.

property covariate_collection: CovariateCollection

The trial’s covariate collection.

property spikeColl: SpikeTrainCollection

Alias for spike_collection (Matlab compat).

property numCov: int

Number of covariates in the trial’s covariate collection (delegates to CovariateCollection.numCov).

property numSpikeTrains: int

Number of spike trains in the trial’s spike collection (delegates to SpikeTrainCollection.numSpikeTrains).

setTrialEvents(event)[source]

Attach an Events object (or None to clear).

Parameters:

event (Events | None)

Return type:

None

getEvents()[source]

Return the attached Events, or None.

Return type:

Events | None

property covarColl: CovariateCollection
setTrialPartition(partitionTimes)[source]

Set training and validation time windows from a 3- or 4-element array.

Return type:

None

getTrialPartition()[source]

Return [trainMin, trainMax, valMin, valMax] partition times.

Return type:

ndarray

setTrialTimesFor(partitionName='training')[source]

Set trial time bounds to either the 'training' or 'validation' window.

Parameters:

partitionName (str)

Return type:

None

setMinTime(minTime=None)[source]

Set minimum time across spikes, covariates, and ensemble covariates.

Parameters:

minTime (float | None)

Return type:

None

setMaxTime(maxTime=None)[source]

Set maximum time across spikes, covariates, and ensemble covariates.

Parameters:

maxTime (float | None)

Return type:

None

updateTimePartitions()[source]

Clamp training/validation windows to current min/max time.

Return type:

None

plotRaster(handle=None)[source]

Plot only the spike raster for this trial.

Parameters:

handle (matplotlib Figure or Axes, optional) – If an Axes is provided the raster is drawn there. If a Figure is provided a new axes is added. If None a new figure is created.

Return type:

matplotlib.figure.Figure

plotCovariates(handle=None)[source]

Plot covariates (and events, if set) for this trial.

Layout adapts to the number of active covariates, following the Matlab Trial.plotCovariates behaviour.

Parameters:

handle (matplotlib Figure, optional) – Figure to draw on. If None a new figure is created.

Return type:

matplotlib.figure.Figure

plot(*_, handle=None, **__)[source]

Plot spike raster, covariates, and events in a multi-panel figure.

Return type:

matplotlib.figure.Figure

setSampleRate(sampleRate)[source]

Resample spikes, covariates, and ensemble covariates to sampleRate.

Parameters:

sampleRate (float)

Return type:

None

resample(sampleRate)[source]

Alias for setSampleRate().

Parameters:

sampleRate (float)

Return type:

None

setEnsCovMask(mask=None)[source]

Set the ensemble-covariate neighbour mask (default: all-to-all minus self).

Return type:

None

setCovMask(mask)[source]

Set the covariate mask; 'all' resets to full visibility.

Return type:

None

resetCovMask()[source]

Reset the covariate mask to all-visible.

Return type:

None

setNeuronMask(mask)[source]

Set the neuron (spike-train) mask and sync to self.neuronMask.

Return type:

None

resetNeuronMask()[source]

Reset the neuron mask to all-visible.

Return type:

None

setNeighbors(*args)[source]

Set the neighbour structure for ensemble-history covariates.

Return type:

None

setHistory(hist)[source]

Set the spike-history configuration.

Parameters:

hist (History, array-like, or list[History]) – A History object, an array of window-edge times (seconds), or a list of History objects for per-neuron history orders.

Return type:

None

resetHistory()[source]

Clear the spike-history configuration.

Return type:

None

setEnsCovHist(hist=None)[source]

Set the ensemble-covariate history and rebuild the ensemble collection.

Parameters:

hist (History or array-like, optional) – A History object or window-edge array. Passing None clears the ensemble history and removes the ensCovColl.

Return type:

None

isNeuronMaskSet()[source]

Return True if any neuron is currently masked out.

Return type:

bool

isCovMaskSet()[source]

Return True if any covariate dimension is currently masked out.

Return type:

bool

isMaskSet()[source]

Return True if either the neuron or covariate mask is active.

Return type:

bool

isHistSet()[source]

Return True if a spike-history configuration has been set.

Return type:

bool

isEnsCovHistSet()[source]

Return True if an ensemble-covariate history has been set.

Return type:

bool

getNumHist()[source]

Return the number of history coefficients.

If a single History object is set, returns the number of history window coefficients (len(windowTimes) - 1). If a list of History objects is set, returns a list with the count for each. Returns 0 when no history is set.

Matches Matlab Trial.getNumHist().

Return type:

int | list[int]

addCov(cov)[source]

Add a covariate and enforce consistent sample rate / time bounds.

Parameters:

cov (Covariate)

Return type:

None

removeCov(identifier)[source]

Remove a covariate by 0-based index or name.

Parameters:

identifier (int | str)

Return type:

None

getSpikeVector(*args, neuron_index=1)[source]

Return the spike data as a column matrix.

Parameters:
  • *args – When empty, returns all neurons via dataToMatrix(). An int selects a single neuron (0-based). A sequence of bin edges returns binned counts for the neuron given by neuron_index.

  • neuron_index (int, default 1) – Neuron to bin when args provides bin edges (0-based).

Return type:

ndarray

get_covariate_matrix(selected_covariates=None)[source]

Return (time, data, names) for the covariate collection.

Parameters:

selected_covariates (Sequence[str] | None)

Return type:

tuple[ndarray, ndarray, list[str]]

getDesignMatrix(neuronNum, dataSelector=None)[source]

Build the full design matrix for neuron neuronNum (0-based).

Horizontally concatenates covariates, spike-history columns, and ensemble-history columns — the complete regressor matrix used by the GLM fitter.

Parameters:

neuronNum (int)

Return type:

ndarray

getHistForNeurons(neuronIndex)[source]

Compute the spike-history covariates for one neuron.

Parameters:

neuronIndex (int) – 0-based neuron index whose spike train supplies the history.

Returns:

Collection of history-basis covariates aligned to the trial time grid.

Return type:

CovariateCollection

getHistMatrices(neuronIndex)[source]

Return the spike-history columns as a 2-D array for neuronIndex (0-based).

Parameters:

neuronIndex (int)

Return type:

ndarray

getEnsembleNeuronCovariates(*args)[source]

Delegate to SpikeTrainCollection.getEnsembleNeuronCovariates.

getEnsCovMatrix(neuronNum, includedNeurons=None)[source]

Return the ensemble-covariate design-matrix columns for neuronNum.

Uses ensCovMask to exclude self-history and applies neighbour filtering when includedNeurons is not specified.

Parameters:

neuronNum (int)

Return type:

ndarray

getNeuronIndFromMask()[source]

Return 0-based indices of currently unmasked neurons.

Return type:

list[int]

getNumUniqueNeurons()[source]

Return the number of distinct neuron names in the collection.

Return type:

int

getNeuronNames()[source]

Return all neuron names (may contain duplicates for repeated trials).

Return type:

list[str]

getUniqueNeuronNames()[source]

Return deduplicated neuron names.

Return type:

list[str]

getNeuronIndFromName(neuronName)[source]

Return 0-based indices matching neuronName, filtered by the neuron mask.

Parameters:

neuronName (str)

neuronMask_indices()[source]

Return 0-based indices of unmasked neurons (alias for getNeuronIndFromMask).

Return type:

list[int]

getNeuronNeighbors(neuronNum=None)[source]

Return the neighbour list for neuronNum (defaults to all unmasked neurons).

getCovSelectorFromMask()[source]

Return the per-covariate selector list derived from the current mask.

getCov(identifier)[source]

Return a Covariate by 0-based index or name.

getNeuron(identifier)[source]

Return an nspikeTrain by 0-based index or name.

getAllCovLabels()[source]

Return labels for all covariate dimensions (ignoring mask).

Return type:

list[str]

getCovLabelsFromMask()[source]

Return labels for only the currently unmasked covariate dimensions.

Return type:

list[str]

getHistLabels()[source]

Return string labels for all spike-history basis columns.

Return type:

list[str]

getEnsCovLabels()[source]

Return string labels for all ensemble-covariate columns.

Return type:

list[str]

getEnsCovLabelsFromMask(neuronNum)[source]

Return ensemble-covariate labels for neuronNum, filtered by ensCovMask.

Parameters:

neuronNum (int)

Return type:

list[str]

getAllLabels()[source]

Return all covariate + history + ensemble labels (no mask filtering).

Matlab equivalent: Trial.getAllLabels.

Return type:

list[str]

getLabelsFromMask(neuronNum)[source]

Return all design-matrix labels for neuronNum, respecting masks.

Parameters:

neuronNum (int)

Return type:

list[str]

flattenCovMask()[source]

Flatten the per-covariate mask list into a single 1-D int array.

Return type:

ndarray

flattenMask()[source]

Flatten the full mask (covariates + history + ensemble) into 1-D.

Return type:

ndarray

shiftCovariates(*args)[source]

Apply a time shift to covariates and re-synchronize time bounds.

Return type:

None

resetEnsCovMask()[source]

Reset the ensemble-covariate mask to the default (all-to-all minus self).

Return type:

None

resampleEnsColl()[source]

Rebuild the ensemble-covariate collection at the current sample rate.

Return type:

None

restoreToOriginal()[source]

Reset all collections to their original state and re-synchronize.

Return type:

None

toStructure()[source]

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

Return type:

dict[str, Any]

static fromStructure(structure)[source]

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

Parameters:

structure (dict[str, Any])

Return type:

Trial

makeConsistentSampleRate()[source]

Resample all collections to the maximum sample rate found.

Return type:

None

makeConsistentTime()[source]

Set all collections to the union of min/max time across sub-collections.

Return type:

None

isSampleRateConsistent()[source]

Return True if spike and covariate collections share the same sample rate.

Return type:

bool

findMaxSampleRate()[source]

Return the maximum sample rate across spike and covariate collections.

Return type:

float

findMinSampleRate()[source]

Return the minimum sample rate across spike collection, covariate collection, and trial.

Matches Matlab Trial.findMinSampleRate().

Return type:

float

findMinTime()[source]

Return the earliest start time across sub-collections.

Return type:

float

findMaxTime()[source]

Return the latest end time across sub-collections.

Return type:

float