3. API Reference¶
3.1. filtertools¶
Tools and utilities for computing spiketriggered averages (filters), finding spatial and temporal components of spatiotemporal filters, and basic filter signal processing.

pyret.filtertools.
ste
(time, stimulus, spikes, nsamples_before, nsamples_after=0)¶ Constructs an iterator over spiketriggered stimuli.
Parameters:  time (ndarray) – The time array corresponding to the stimulus.
 stimulus (ndarray) – A spatiotemporal or temporal stimulus array, where time is the first dimension.
 spikes (iterable) – A list or ndarray of spike times.
 nsamples_before (int) – Number of samples to include in the STE before the spike.
 nsamples_after (int) – Number of samples to include in the STE after the spike, which defaults to 0.
Returns: ste – A generator that yields samples from the spiketriggered ensemble.
Return type: generator
Notes
The spiketriggered ensemble (STE) is the set of all stimuli immediately surrounding a spike. If the full stimulus distribution is p(s), the STE is p(s  spike).

pyret.filtertools.
sta
(time, stimulus, spikes, nsamples_before, nsamples_after=0)¶ Compute a spiketriggered average.
Parameters:  time (ndarray) – The time array corresponding to the stimulus
 stimulus (ndarray) – A spatiotemporal or temporal stimulus array (where time is the first dimension)
 spikes (iterable) – A list or ndarray of spike times
 nsamples_before (int) – Number of samples to include in the STA before the spike
 nsamples_after (int) – Number of samples to include in the STA after the spike (default: 0)
Returns:  sta (ndarray) – The spatiotemporal spiketriggered average. Note that time
increases with increasing array index, i.e. time of the spike is
at the index for which
tax == 0
.  tax (ndarray) – A time axis corresponding to the STA, giving the time relative to the spike for each time point of the STA.
Notes
The spiketriggered average (STA) is the averaged stimulus feature conditioned on the presence of a spike. This is widelyused method for estimating a neuron’s receptive field, and captures the average stimulus feature to which the neuron responds.
Formally, the STA is defined as the function [1]:
\[C(\tau) = \frac{1}{N} \sum_{i=1}^{N} s(t_i  \tau)\]where \(\tau\) is time preceding the spike, and \(t_i\) is the time of the ith spike.
The STA is often used to estimate a linear filter which captures a neuron’s responses. If the stimulus is uncorrelated (spherical), the STA is unbiased and proportional to the timereverse of the linear filter.
Note that the
tax
time values returned by this method are formally given byt_i  \tau
, i.e., they are the actual time relative to the spike of each corresponding point in the STA.References
[1] Dayan, P. and L.F. Abbott. Theoretical Neuroscience: Computational and Mathematical Modeling of Neural Systems. 2001.

pyret.filtertools.
stc
(time, stimulus, spikes, nsamples_before, nsamples_after=0)¶ Compute the spiketriggered covariance.
Parameters:  time (ndarray) – The time array corresponding to the stimulus, where time is the first dimension.
 stimulus (ndarray) – A spatiotemporal or temporal stimulus array.
 spikes (iterable) – A list or ndarray of spike times.
 nsamples_before (int) – Number of samples to include in the STC before the spike.
 nsamples_after (int) – Number of samples to include in the STC after the spike, which defaults to 0.
Returns: stc – The spiketriggered covariance (STC) matrix.
Return type: ndarray

pyret.filtertools.
lowranksta
(sta_orig, k=10)¶ Constructs a rankk approximation to the given spatiotemporal STA. This is useful for estimating a spatial and temporal kernel for an STA or for denoising.
Parameters:  sta_orig (array_like) – 3D STA to be separated, shaped as
(time, space, space)
.  k (int) – Number of components to keep (rank of the reduced STA).
Returns:  sk (array_like) – The rankk estimate of the original STA.
 u (array_like) – The top
k
temporal components (each column is a component).  s (array_like) – The top
k
singular values.  v (array_like) – The top
k
spatial components (each row is a component). These components have all spatial dimensions collapsed to one.
Notes
This method requires that the STA be 3D. To decompose a STA into a temporal and 1dimensional spatial component, simply promote the STA to 3D before calling this method.
Despite the name this method accepts both an STA or a linear filter. The components estimated for one will be flipped versions of the other.
 sta_orig (array_like) – 3D STA to be separated, shaped as

pyret.filtertools.
decompose
(sta)¶ Decomposes a spatiotemporal STA into a spatial and temporal kernel.
Parameters: sta (array_like) – The full 3dimensional STA to be decomposed, of shape (t, nx, ny)
.Returns:  s (array_like) – The spatial kernel, with shape
(nx * ny,)
.  t (array_like) – The temporal kernel, with shape
(t,)
.
 s (array_like) – The spatial kernel, with shape

pyret.filtertools.
filterpeak
(sta)¶ Find the peak (single point in space/time) of a smoothed STA or linear filter.
Parameters: sta (array_like) – STA or filter for which to find the peak. It should be shaped as (time, ...)
, where ellipses indicate any spatial dimensions to the array.Returns:  linear_index (int) – Linear index of the maximal point, i.e. treating the array as flattened.
 sidx (1 or 2element tuple) – Spatial index of the maximal point. This returns a tuple with the same number of elements as the filter has spatial dimensions.
 tidx (int) – Temporal index of the maximal point.

pyret.filtertools.
smooth
(f, spacesig=0.5, timesig=1)¶ Smooths a 3D spatiotemporal STA or linear filter using a multidimensional Gaussian filter with the given properties.
Parameters: Returns: fsmooth – The smoothed filter, with the same shape as the input.
Return type: array_like

pyret.filtertools.
cutout
(arr, idx=None, width=5)¶ Cut out a chunk of the given stimulus or filter.
Parameters:  arr (array_like) – Stimulus, STA, or filter array from which the chunk is cut out. The
array should be shaped as
(time, spatial, spatial)
.  idx (array_like, optional) – 2D array specifying the row and column indices of the center of the
section to be cut out (if None, the indices are taken from
filterpeak
).  width (int, optional) – The size of the chunk to cut out from the start indices. Defaults to 5 samples.
Returns: cut – The cut out section of the given stimulus, STA, or filter.
Return type: array_like
Notes
This method can be useful to reduce the space and time costs of computations involving stimuli and/or filters. For example, a neuron’s receptive field is often much smaller than the stimulus, but this method can be used to only compare the relevant portions of the stimulus and receptive field.
 arr (array_like) – Stimulus, STA, or filter array from which the chunk is cut out. The
array should be shaped as

pyret.filtertools.
resample
(arr, scale_factor)¶ Resamples a 1D or 2D array by the given scale.
Parameters:  arr (array_like) – The original array to be resampled.
 scale_factor (int_like) – The factor by which
arr
will be resampled. For example, a factor of 2 results in an of twice the size in each dimension, with points interpolated between existing points.
Returns: res – The resampled array. If
arr
has shape (M,N),res
has shape(scale_factor*M, scale_factor*N)
.Return type: array_like
Raises:  An AssertionError is raised if the scale factor is <= 0.
 A ValueError is raised if the input array is not 1 or 2dimensional.

pyret.filtertools.
flat2d
(x)¶ Flattens all dimensions after the first of the given array
Useful for collapsing spatial dimensions in a spatiotemporal stimulus or filter.

pyret.filtertools.
get_ellipse
(spatial_filter, sigma=2.0)¶ Get the parameters of an ellipse fit to a spatial STA or linear filter.
Parameters:  spatial_filter (array_like) – The spatial receptive field to which the ellipse should be fit.
 sigma (float, optional) – Determines the size of the ellipse contour, in units of standard deviations. (Default: 2)
Returns:  center ((float,float)) – The receptive field center (location stored as an (x,y) tuple).
 widths ([float,float]) – Twoelement list of the size of each principal axis of the RF ellipse.
 theta (float) – angle of rotation of the ellipse from the vertical axis, in radians.

pyret.filtertools.
get_regionprops
(spatial_filter, percentile=0.95)¶ Gets region properties of a 2D spatial STA or linear filter.
This returns various attributes of the nonzero area of the given spatial filter, such as its area, centroid, eccentricity, etc.
>>> regions = get_regionprops(sta_spatial) >>> print(regions[0].area) # prints the area of the first region
Parameters:  spatial_filter (array_like) – The spatial linear filter to which the ellipse should be fit.
 percentile (float, optional) – The cutoff percentile at which the contour is taken. Defaults to 0.95.
Returns: regions – List of region properties (see
skimage.measure.regionprops
for more information).Return type:

pyret.filtertools.
normalize_spatial
(frame, scale_factor=1.0, clip_negative=False)¶ Normalizes a spatial frame, for example of a stimulus or STA, by doing the following:
 mean subtraction using a robust estimate of the mean (ignoring outliers).
 scaling such that the std. dev. of the pixel values is 1.0.
Parameters:  frame (array_like) – The spatial frame to be normalized.
 scale_factor (float, optional) – The given frame is resampled at a sampling rate of this ratio times the original sampling rate (Default: 1.0).
 clip_negative (boolean, optional) – Whether or not to clip negative values to 0. (Default: False).
Returns: resampled – The normalized (and potentially resampled) frame.
Return type: array_like

pyret.filtertools.
linear_response
(filt, stim, nsamples_after=0)¶ Compute the response of a linear filter to a stimulus.
Parameters:  filt (array_like) – The linear filter whose response is to be computed. The array should
have shape
(t, ...)
, wheret
is the number of time points in the filter and the ellipsis indicates any remaining spatial dimenions. The number of dimensions and the sizes of the spatial dimensions must match that ofstim
.  stim (array_like) – The stimulus to which the predicted response is computed. The array
should have shape
(T,...)
, whereT
is the number of time points in the stimulus and the ellipsis indicates any remaining spatial dimensions. The number of dimensions and the sizes of the spatial dimenions must match that offilt
.  nsamples_after (int, optional) – The number of acausal points in the filter. Defaults to 0.
Returns: pred – The predicted linear response, of shape
(t,)
.Return type: array_like
Raises: ValueError : If the number of dimensions of ``stim`` and ``filt`` do not – match, or if the spatial dimensions differ.
Notes
Note that the first parameter is a linear filter. The values returned by
filtertools.sta
andfiltertools.revcorr
are proportional to the timereverse of the linear filter, so to use those values in this function, they must be flipped along the first dimension.Both
filtertools.sta
andfiltertools.revcorr
can estimate “acausal” components, such as points in the stimulus occuring after a spike. The value passed as parameternsamples_after
must match that value used when callingfiltertools.sta
orfiltertools.revcorr
. filt (array_like) – The linear filter whose response is to be computed. The array should
have shape

pyret.filtertools.
revcorr
(stimulus, response, nsamples_before, nsamples_after=0)¶ Compute the reversecorrelation between a stimulus and a response.
Parameters:  stimulus (array_like) – A input stimulus correlated with the
response
. Must be of shape(t, ...)
, wheret
is the time and...
indicates any spatial dimensions.  response (array_like) – A continuous output response correlated with
stimulus
. Must be onedimensional, of sizet
, the same size asstimulus
along the first axis. Note that the firsthistory
points of the response are ignored, wherehistory = nsamples_before + nsamples_after
, in order to only return the portion of the correlation during which thestimulus
andresponse
completely overlap.  nsamples_before (int) – The maximum negative lag for the correlation between stimulus and response, in samples.
 nsamples_after (int, optional) – The maximum positive lag for the correlation between stimulus and response, in samples. Defaults to 0.
Returns:  rc (array_like) – An array of shape
(nsamples_before + nsamples_after, ...)
containing the bestfitting linear filter which predicts the response from the stimulus. The ellipses indicates spatial dimensions of the filter.  lags (array_like) – An array of shape
(nsamples_before + nsamples_after,)
, which gives the lags, in samples, betweenstimulus
andresponse
for the correlation returned inrc
. This can be converted to an axis of time (like that returned fromfiltertools.sta
) by multiplying by the sampling period.
Raises:  ValueError : If the
stimulus
andresponse
arrays do not match in  size along the first dimension.
Notes
The
response
andstimulus
arrays must share the same sampling rate. As the stimulus often has a lower sampling rate, one can usestimulustools.upsample
to upsample it.Reverse correlation is a method analogous to spiketriggered averaging for continuous response variables, such as a membrane voltage recording. It estimates the stimulus feature that most strongly correlates with the response on average.
It is the timereverse of the standard crosscorrelation function, and is defined as:
\[c[k] = \sum_{n} s[n] r[n  k]\]The parameter
k
is the lag between the two signals in samples. The range of lags computed in this method are determined bynsamples_before
andnsamples_after
.Note that, as with
filtertools.sta
, the values (samples) in thelags
array increase with increasing array index. This means that time is moving forward with increasing array index.Also note that this method assumes an uncorrelated stimulus. If the stimulus is correlated, those will bias the estimated reverse correlation.
 stimulus (array_like) – A input stimulus correlated with the
3.2. nonlinearities¶
Tools for fitting nonlinear functions to data

class
pyret.nonlinearities.
Sigmoid
(baseline=0.0, peak=1.0, slope=1.0, threshold=0.0)¶ Bases:
sklearn.base.BaseEstimator
,sklearn.base.RegressorMixin
,pyret.nonlinearities.NonlinearityMixin

fit
(x, y, **kwargs)¶

predict
(x)¶


class
pyret.nonlinearities.
Binterp
(nbins, method='linear', fill_value='extrapolate')¶ Bases:
sklearn.base.BaseEstimator
,sklearn.base.RegressorMixin
,pyret.nonlinearities.NonlinearityMixin

fit
(x, y)¶

predict
(x)¶ Placeholder, this method gets overwritten when fit() is called


class
pyret.nonlinearities.
GaussianProcess
(**kwargs)¶ Bases:
sklearn.gaussian_process.gpr.GaussianProcessRegressor
,pyret.nonlinearities.NonlinearityMixin

fit
(x, y)¶ Fit Gaussian process regression model.
Parameters:  X (arraylike, shape = (n_samples, n_features)) – Training data
 y (arraylike, shape = (n_samples, [n_output_dims])) – Target values
Returns: self
Return type: returns an instance of self.

predict
(x, **kwargs)¶ Predict using the Gaussian process regression model
We can also predict based on an unfitted model by using the GP prior. In addition to the mean of the predictive distribution, also its standard deviation (return_std=True) or covariance (return_cov=True). Note that at most one of the two can be requested.
Parameters:  X (arraylike, shape = (n_samples, n_features)) – Query points where the GP is evaluated
 return_std (bool, default: False) – If True, the standarddeviation of the predictive distribution at the query points is returned along with the mean.
 return_cov (bool, default: False) – If True, the covariance of the joint predictive distribution at the query points is returned along with the mean
Returns:  y_mean (array, shape = (n_samples, [n_output_dims])) – Mean of predictive distribution a query points
 y_std (array, shape = (n_samples,), optional) – Standard deviation of predictive distribution at query points. Only returned when return_std is True.
 y_cov (array, shape = (n_samples, n_samples), optional) – Covariance of joint predictive distribution a query points. Only returned when return_cov is True.

3.3. spiketools¶
Tools for spike train analysis
Includes an object class, SpikingEvent, that is useful for detecting and analyzing firing events within a spike raster. Also provides functions for binning spike times into a histogram (binspikes) and a function for smoothing a histogram into a firing rate (estfr)

pyret.spiketools.
binspikes
(spk, time)¶ Bin spike times at the given resolution. The function has two forms.
Parameters:  spk (array_like) – Array of spike times
 time (array_like) – The left edges of the time bins.
Returns: bspk – Binned spike times
Return type: array_like

pyret.spiketools.
estfr
(bspk, time, sigma=0.01)¶ Estimate the instantaneous firing rates from binned spike counts.
Parameters:  bspk (array_like) – Array of binned spike counts (e.g. from binspikes)
 time (array_like) – Array of time points corresponding to bins
 sigma (float, optional) – The width of the Gaussian filter, in seconds (Default: 0.01 seconds)
Returns: rates – Array of estimated instantaneous firing rate
Return type: array_like

pyret.spiketools.
detectevents
(spk, threshold=(0.3, 0.05))¶ Detects spiking events given a PSTH and spike times for multiple trials
>> events = detectevents(spikes, threshold=(0.1, 0.005))
Parameters:  spk (array_like) – An (n by 2) array of spike times, indexed by trial / condition. The first column is the set of spike times in the event and the second column is a list of corresponding trial/cell/condition indices for each spike.
 threshold ((float, float), optional) – A tuple of two floats that are used as thresholds for detecting firing events. Default: (0.1, 0.005) see peakdet for more info
Returns: events – A list of ‘spikingevent’ objects, one for each firing event detected. See the spikingevent class for more info.
Return type:

pyret.spiketools.
peakdet
(v, delta, x=None)¶ Converted from MATLAB script at http://billauer.co.il/peakdet.html
Returns two arrays containing the maxima and minima of a 1D signal
Parameters:  v (array_like) – The input signal (array) to find the peaks of
 delta (float) –
 The threshold for peak detection. A point is considered a maxima
 (or minima) if it is at least delta larger (or smaller) than its neighboring points
 x (array_like, optional) – If given, the locations of the peaks are given as the corresponding values in x. Otherwise, the locations are given as indices
Returns:  maxtab (array_like) – An (N x 2) array containing the indices or locations (left column) of the local maxima in v along with the corresponding maximum values (right column).
 mintab (array_like) – An (M x 2) array containing the indices or locations (left column) of the local minima in v along with the corresponding minimum values (right column).

class
pyret.spiketools.
SpikingEvent
(start_time, stop_time, spikes)¶ Bases:
object

jitter
()¶ Computes the jitter (standard deviation) in the time to first spike
>> sigma = spkevent.jitter()

plot
(sort=False, ax=None, color='SlateGray')¶ Plots this event, as a spike raster
>> spkevent.plot()
Parameters:  sort (boolean, optional) – Whether or not to sort by the time to first spike (Default: False)
 ax (matplotlib Axes object, optional) – If None, creates a new figure (Default: None)
 color (string) – The color of the points in the raster (Default: ‘SlateGray’)

sort
()¶ Sort trial indices by the time to first spike
>> sortedspikes = spkevent.sort()

stats
()¶ Compute statistics (mean and standard deviation) across spike counts
>> mu, sigma = spkevent.event_stats()

trial_counts
()¶ Count the number of spikes per trial

ttfs
()¶ Computes the time to first spike for each trial, ignoring trials that had zero spikes
>> times = spkevent.ttfs()

3.4. stimulustools¶
Tools for dealing with spatiotemporal stimuli

pyret.stimulustools.
upsample
(stim, upsample_factor, time=None)¶ Upsample the given stimulus by the given factor.
Parameters:  stim (array_like) – The actual stimulus to be upsampled. dimensions: (time, space, space)
 upsample_factor (int) – The upsample factor.
 time (array_like, optional) – The time axis of the original stimulus.
Returns:  stim_us (array_like) – The upsampled stimulus array
 time_us (array_like) – the upsampled time vector

pyret.stimulustools.
downsample
(stim, downsample_factor, time=None)¶ Downsample the given stimulus by the given factor.
Parameters:  stim (array_like) – The original stimulus array
 downsample_factor (int) – The factor by which the stimulus will be downsampled
 time (array_like, optional) – The time axis of the original stimulus
Returns:  stim_ds (array_like) – The downsampled stimulus array
 time_ds (array_like) – The downsampled time vector

pyret.stimulustools.
slicestim
(stimulus, nsamples_before, nsamples_after=0)¶ Slices a spatiotemporal stimulus array (over time) into overlapping frames.
Parameters:  stimulus (array_like) – The spatiotemporal or temporal stimulus to slice. Should have shape
(t, ...)
, so that the time axis is first. The ellipses indicate the spatial dimensions of the stimulus, if any.  nsamples_before (int) – Integer number of time points before a hypothetical center. See Notes section for more details.
 nsamples_after (int, optional) – Integer number of time points before a hypothetical center. See Notes section for more details.
Returns: slices – A view onto the original stimulus array, giving the overlapping slices of the stimulus. The full shape of the returned array is:
(stimulus.shape[0]  history + 1, history ...)
, wherehistory == nsamples_before + nafter
. As above, the ellipses indicate any spatial dimensions to the stimulus.Return type: array_like
Examples
>>> x = np.arange(15).reshape((5, 3)) >>> slicestim(x, 3) array([[[ 0, 1, 2], [ 3, 4, 5]],
 [[ 3, 4, 5],
 [ 6, 7, 8]],
 [[ 6, 7, 8],
 [ 9, 10, 11]],
 [[ 9, 10, 11],
 [12, 13, 14]]])
Calculate rolling mean of last dimension:
>>> np.mean(slicestim(x, 3), 1) array([[ 1., 4.], [ 4., 7.], [ 7., 10.], [10., 13.]])
Notes
stimulustools.slicestim
is used to create a Toeplitz matrix from a multidimensional stimulus. This simplifies performing certain operations such as filtering, as it allows us to express the operation as a matrix product rather than via convolution.However, this product only works when the sliced stimulus and filter are temporally aligned. Because
filtertools.sta
andfiltertools.revcorr
allow computing acausal components of an STA (points after a spike occurs), this method must also allow that in order to keep the temporal alignment.Practically this means that one must always pass the same value for the
nsamples_after
argument as is passed tofiltertools.sta
orfiltertools.revcorr
. stimulus (array_like) – The spatiotemporal or temporal stimulus to slice. Should have shape

pyret.stimulustools.
cov
(stimulus, history, nsamples=None, verbose=False)¶ Computes a stimulus covariance matrix
Warning
This is computationally expensive for large stimuli
Parameters:  stimulus (array_like) – The spatiotemporal or temporal stimulus to slices. Should have shape (t, …), where the ellipses indicate any spatial dimensions.
 history (int) – Integer number of time points to keep in each slice.
Returns: stim_cov – Covariance matrix
Return type: array_like

pyret.stimulustools.
flat2d
(x)¶ Flattens all dimensions after the first of the given array
Useful for collapsing spatial dimensions in a spatiotemporal stimulus or filter.
3.5. visualizations¶
Visualization functions for displaying spikes, filters, and cells.

pyret.visualizations.
raster
(*args, **kwargs)¶ Plot a raster of spike times.
Parameters:  spikes (array_like) – An array of spike times.
 labels (array_like) – An array of labels corresponding to each spike in spikes. For example, this can indicate which cell or trial each spike came from. Spike times are plotted on the xaxis, and labels on the yaxis.
 title (string, optional) – An optional title for the plot (Default: ‘Spike raster’).
 marker_string (string, optional) – The marker string passed to matplotlib’s plot function (Default: ‘ko’).
 ax (matplotlib.axes.Axes instance, optional) – An optional axes onto which the data is plotted.
 fig (matplotlib.figure.Figure instance, optional) – An optional figure onto which the data is plotted.
 kwargs (dict) – Optional keyword arguments are passed to matplotlib’s plot function.
Returns:  fig (matplotlib.figure.Figure) – Matplotlib Figure object into which raster is plotted.
 ax (matplotlib.axes.Axes) – Matplotlib Axes object into which raster is plotted.

pyret.visualizations.
psth
(*args, **kwargs)¶ Plot a PSTH from the given spike times.
Parameters:  spikes (array_like) – An array of spike times.
 trial_length (float) – The length of each trial to stack, in seconds. If None (the default), a single PSTH is plotted. If a float is passed, PSTHs from each trial of the given length are averaged together before plotting.
 binsize (float) – The size of bins used in computing the PSTH.
 ax (matplotlib.axes.Axes instance, optional) – An optional axes onto which the data is plotted.
 fig (matplotlib.figure.Figure instance, optional) – An optional figure onto which the data is plotted.
 kwargs (dict) – Keyword arguments passed to matplotlib’s
plot
function.
Returns:  fig (matplotlib.figure.Figure) – Matplotlib Figure object into which PSTH is plotted.
 ax (matplotlib.axes.Axes) – Matplotlib Axes object into which PSTH is plotted.

pyret.visualizations.
raster_and_psth
(*args, **kwargs)¶ Plot a spike raster and a PSTH on the same set of axes.
Parameters:  spikes (array_like) – An array of spike times.
 trial_length (float) – The length of each trial to stack, in seconds. If None (the default), all spikes are plotted as part of the same trial.
 binsize (float) – The size of bins used in computing the PSTH.
 ax (matplotlib.axes.Axes instance, optional) – An optional axes onto which the data is plotted.
 fig (matplotlib.figure.Figure instance, optional) – An optional figure onto which the data is plotted.
 kwargs (dict) – Keyword arguments to matplotlib’s
plot
function.
Returns:  fig (matplotlib.figure.Figure) – Matplotlib Figure instance onto which the data is plotted.
 ax (matplotlib.axes.Axes) – Matplotlib Axes instance onto which the data is plotted.

pyret.visualizations.
spatial
(*args, **kwargs)¶ Plot the spatial component of a full linear filter.
If the given filter is 2D, it is assumed to be a 1D spatial filter, and is plotted directly. If the filter is 3D, it is decomposed into its spatial and temporal components, and the spatial component is plotted.
Parameters:  filt (array_like) – The filter whose spatial component is to be plotted. It may have temporal components.
 dx (float, optional) – The spatial sampling rate of the STA, setting the scale of the x and yaxes.
 maxval (float, optional) – The value to use as minimal and maximal values when normalizing the
colormap for this plot. See
plt.imshow()
documentation for more details.  ax (matplotlib Axes object, optional) – The axes on which to plot the data; defaults to creating a new figure.
Returns:  fig (matplotlib.figure.Figure) – The figure onto which the spatial STA is plotted.
 ax (matplotlib Axes object) – Axes into which the spatial STA is plotted.

pyret.visualizations.
temporal
(*args, **kwargs)¶ Plot the temporal component of a full linear filter.
If the given linear filter is 1D, it is assumed to be a temporal filter, and is plotted directly. If the filter is 2 or 3D, it is decomposed into its spatial and temporal components, and the temporal component is plotted.
Parameters:  time (array_like) – A time vector to plot against.
 filt (array_like) – The full filter to plot. May be than 1D, but must match in size along
the first dimension with the
time
input.  ax (matplotlib Axes object, optional) – the axes on which to plot the data; defaults to creating a new figure
Returns:  fig (matplotlib.figure.Figure) – The figure onto which the temoral STA is plotted.
 ax (matplotlib Axes object) – Axes into which the temporal STA is plotted

pyret.visualizations.
plot_sta
(time, sta, dx=1.0)¶ Plot a linear filter.
If the given filter is 1D, it is direclty plotted. If it is 2D, it is shown as an image, with space and time as its axes. If the filter is 3D, it is decomposed into its spatial and temporal components, each of which is plotted on its own axis.
Parameters:  time (array_like) – A time vector to plot against.
 dx (float, optional) – The spatial sampling rate of the STA, setting the scale of the x and yaxes.
 sta (array_like) – The filter to plot.
Returns:  fig (matplotlib.figure.Figure) – The figure onto which the STA is plotted.
 ax (matplotlib Axes object) – Axes into which the STA is plotted

pyret.visualizations.
play_sta
(sta, repeat=True, frametime=100, cmap='seismic_r', clim=None, dx=1.0)¶ Plays a spatiotemporal spiketriggered average as a movie.
Parameters:  sta (array_like) – Spiketriggered average array, shaped as
(nt, nx, ny)
.  repeat (boolean, optional) – Whether or not to repeat the animation (default is True).
 frametime (float, optional) – Length of time each frame is displayed for in milliseconds (default is 100).
 cmap (string, optional) – Name of the colormap to use (Default:
'seismic_r'
).  clim (array_like, optional) – 2element color limit for animation; e.g. [0, 255].
 dx (float, optional) – The spatial sampling rate of the STA, setting the scale of the x and yaxes.
Returns: anim
Return type: matplotlib animation object
 sta (array_like) – Spiketriggered average array, shaped as

pyret.visualizations.
ellipse
(*args, **kwargs)¶ Plot an ellipse fitted to the given receptive field.
Parameters:  filt (array_like) – A linear filter whose spatial extent is to be plotted. If this is 2D, it is assumed to be the spatial component of the receptive field. If it is 3D, it is assumed to be a full spatiotemporal receptive field; the spatial component is extracted and plotted.
 sigma (float, optional) – Determines the threshold of the ellipse contours. This is the standard deviation of a Gaussian fitted to the filter at which the contours are plotted. Default is 2.0.
 alpha (float, optional) – The alpha blending value, between 0 (transparent) and 1 (opaque) (Default: 0.8).
 fc (string, optional) – Ellipse face color. (Default: none)
 ec (string, optional) – Ellipse edge color. (Default: black)
 lw (int, optional) – Line width. (Default: 3)
 dx (float, optional) – The spatial sampling rate of the STA, setting the scale of the x and yaxes.
 ax (matplotlib Axes object, optional) – The axes onto which the ellipse should be plotted. Defaults to a new figure.
Returns:  fig (matplotlib.figure.Figure) – The figure onto which the ellipse is plotted.
 ax (matplotlib.axes.Axes) – The axes onto which the ellipse is plotted.

pyret.visualizations.
plot_cells
(*args, **kwargs)¶ Plot the spatial receptive fields for multiple cells.
Parameters:  cells (list of array_like) – A list of spatiotemporal receptive fields, each of which is a spatiotemporal array.
 dx (float, optional) – The spatial sampling rate of the STA, setting the scale of the x and yaxes.
 ax (matplotlib Axes object, optional) – The axes onto which the ellipse should be plotted. Defaults to a new figure.
Returns:  fig (matplotlib.figure.Figure) – The figure onto which the ellipses are plotted.
 ax (matplotlib.axes.Axes) – The axes onto which the ellipses are plotted.

pyret.visualizations.
play_rates
(rates, patches, num_levels=255, time=None, repeat=True, frametime=100)¶ Plays a movie representation of the firing rate of a list of cells, by coloring a list of patches with a color proportional to the firing rate. This is useful, for example, in conjunction with
plot_cells
, to color the ellipses fitted to a set of receptive fields proportional to the firing rate.Parameters:  rates (array_like) – An
(N, T)
matrix of firing rates.N
is the number of cells, andT
gives the firing rate at a each time point.  patches (list) – A list of
N
matplotlib patch elements. The facecolor of these patches is altered according to the rates values.
Returns: anim – The object representing the full animation.
Return type: matplotlib.animation.Animation
 rates (array_like) – An