Array API Reference

Simulating Spiketrains

spiketimes.simulate.homogeneous_poisson_process(rate: float, t_stop: float, t_start: float = 0)[source]

Simulate a poisson process.

Parameters
  • rate – The intensity of the poisson process. The average number of events per second.

  • t_stop – The time after which sampling stops

  • t_start – The time from which sampling starts

Returns

A numpy array containing event times in seconds

spiketimes.simulate.imhomogeneous_poisson_process(time_rate: list, t_start: float = 0)[source]

Simulate an imhomogeneous poisson process.

Parameters
  • time_rate – List of tuples with elements (time_period, rate). The first element in each tuple is the time period. The second element is the average number of events per second during that time period.

  • t_start – The time from which sampling starts

Returns

A numpy array containing event timings in seconds

Surrogates

spiketimes.surrogates.jitter_spiketrain(spiketrain: numpy.ndarray, jitter_window_size: float, t_start: float = None, t_stop: float = None)[source]

Return a jitter spiketrain surrogate from a parent spiketrain.

Jitter spiketrains contain similar firing rate dynamics to the parent spiketrain but with spiketimes randomised. This is done by binning spikecounts over time and then randomising spiketimes within time bins.

Parameters
  • spiketrain – The parent numpy spiketrain.

  • jitter_window_size – The size of the timebins in seconds

  • t_start – If specified, spikes before this limit will be discarded

  • t_stop – If specified, spikes after this limit will be discarded

Returns

A numpy array spiketrain containing spiketimes in seconds

spiketimes.surrogates.jitter_spiketrains(spiketrain: numpy.ndarray, n: int, jitter_window_size: float, t_start: float = None, t_stop: float = None)[source]

Return a jitter spiketrain surrogate from a parent spiketrain.

Jitter spiketrains contain similar firing rate dynamics to the parent spiketrain but with spiketimes randomised. This is done by binning spikecounts over time and then randomising spiketimes within time bins.

Parameters
  • spiketrain – The parent numpy spiketrain.

  • jitter_window_size – The size of the timebins in seconds

  • t_start – If specified, spikes before this limit will be discarded

  • t_stop – If specified, spikes after this limit will be discarded

Returns

A list of numpy array spiketrain containing spiketimes in seconds

spiketimes.surrogates.shuffled_isi_spiketrain(spiketrain: numpy.ndarray)[source]

Return a surrogate spiketrain with shuffled inter spike intervals.

Parameters

spiketrain – The parent array spiketrain from which to create the surrogate

Returns

A numpy array spiketrain containing spiketimes in seconds

spiketimes.surrogates.shuffled_isi_spiketrains(spiketrain: numpy.ndarray, n: int = 1)[source]

Return n surrogate spiketrains with shuffled inter spike intervals.

Parameters
  • spiketrain – The parent array spiketrain from which to create the surrogate

  • n – The number of surrogate spiketrains to return

Returns

A list of numpy array spiketrain containing spiketimes in seconds

Alignment

spiketimes.alignment.align_around(to_be_aligned: numpy.ndarray, to_align_to: numpy.ndarray, t_before: float = None, max_latency: float = None, drop=False)[source]

Align one array to another.

Useful for aligning data to events. Default behaviour is to align to closest smaller event. If t_before is specified

Parameters
  • to_be_aligned – A numpy array to align

  • to_align_to – A numpy to align to (events)

  • t_before – The time window before each aligning event.

  • max_latency – Maximum aligned latency. Latencies above this threshold will be returned as NaN

  • drop – Whether to drop NaN elements of the aligned array

Returns

A numpy array of aligned data

spiketimes.alignment.split_by_trial(spiketrain: numpy.ndarray, trial_starts: numpy.ndarray, max_latency: bool = None, before: float = None)[source]

Splits a spiketrain into a list of spiketrains by trial.

Parameters
  • to_be_aligned – A numpy array to align

  • to_align_to – A numpy to align to (events)

  • t_before – The time window before each aligning event.

  • max_latency – Maximum aligned latency. Latencies above this threshold will be returned as NaN

Returns

A list of numpy arrays of spiketimes in seconds

Binning

spiketimes.binning.bin_to_bool(binned_arr: numpy.ndarray)[source]

Convert a binned array to a binary array: 1s for nonzero elements, 0s for zeros.

Parameters

binned_arr – A numpy array of counts

Returns

A numpy array of 1s and 0s

spiketimes.binning.binned_spiketrain(spiketrain: numpy.ndarray, fs: float, t_stop: float = None, t_start: float = None, as_df: bool = False)[source]

Get event counts at regular time bins.

Parameters
  • spiketrain – A numpy array of spiketimes in seconds

  • fs – The sampling rate used to create time bins. The number of samples per second.

  • t_start – The left edge of first bin

  • t_stop – The right edge of final bin

  • as_df – If true, returns reseults as a pandas DataFrame

Returns

edges, counts

spiketimes.binning.binned_spiketrain_bins_provided(spiketrain: numpy.ndarray, bins: numpy.ndarray)[source]

Get event counts at specified time bins.

Parameters
  • spiketrain – A numpy array of spiketimes in seconds

  • bins – A numpy array of bin edges

Returns

A numpy array of spike counts per bin

spiketimes.binning.spike_count_around_event(spiketrain: numpy.ndarray, events: numpy.ndarray, binsize: float)[source]

Calculate the spike count around events.

Parameters
  • spiketrain – A numpy array of spiketimes

  • events – A numpy array of events

  • binsize – The size of window in which to count spikes

Returns

A numpy array of spike counts per each event

spiketimes.binning.which_bin(spiketrain: numpy.ndarray, bin_edges: numpy.ndarray, before: float = None, allow_before: bool = False, max_latency: float = None, as_df: bool = False)[source]

Get the corresponding bin for each spike in a spiketrain.

Useful for splitting spiketrains into trials.

Parameters
  • spiketrain – A numpy array of spiketimes

  • bin_edges – A numpy array of bin edges

  • before – The time window before each event to include in the alignment.

  • allow_before – If False, spikes occuring before the first time are returned as NaN

  • max_latency – If specified, spikes occuring this quantity after the maximum bin_edge are returned as NaN

  • as_df – Whether to returned the result as a pandas DataFrame.

Returns

bin_idx, bin_values

Statistics

spiketimes.statistics.auc_roc(spike_counts: numpy.ndarray, which_condition: numpy.ndarray, return_distance_from_chance: bool = False)[source]

Calculates the Area Under the Receiver Operating Characteristic Curve of spike counts from two conditions.

The AUCROC can be used as a metric of the separability of two distrobutions.

Parameters
  • spike_counts – A numpy array containing spike counts from both conditions

  • which_condition – A numpy array indicating the condition of each spike count entry. 0s for the first condition, and 1s for the second condition. For example, if the first two elements in spike_counts were from the first condition and the third element from the second condition, which_condition would contain [0, 0, 1]

  • return_distance_from_chance – If True, returns distance from 0.5

Returns

The AUCROC score

spiketimes.statistics.auc_roc_test(spike_counts: numpy.ndarray, which_condition: numpy.ndarray, n_boot: int = 1000, return_distance_from_chance: bool = False)[source]

Calculates the Area Under the Receiver Operating Characteristic Curve of spike counts from two conditions. Also Test significance.

The AUCROC can be used as a metric of the separability of two distrobutions. Significance tested using a permutation test.

Parameters
  • spike_counts – A numpy array containing spike counts from both conditions

  • which_condition – A numpy array indicating the condition of each spike count entry. 0s for the first condition, and 1s for the second condition. For example, if the first two elements in spike_counts were from the first condition and the third element from the second condition, which_condition would contain [0, 0, 1]

  • n_boot – The number of bootstrap replicates to draw

  • return_distance_from_chance – If True, returns distance from 0.5

Returns

The AUCROC score, p

spiketimes.statistics.cov(arr: numpy.ndarray, axis: int = 0)[source]

Computes the coefficient of variation.

Simply wraps the scipy.stats variation function

Parameters
  • arr – A numpy array

  • axis – The axis over which to calculate cov

Returns

The coefficient of variation

spiketimes.statistics.cv2(arr: numpy.ndarray)[source]

Compute the cv2 of an array.

The Cv2 is a metric similar to the coefficient of variation but which includes a correction for signals which slowly fluctuate over time. [Suitable for long term neuronal recordings.]

Parameters

arr – A numpy array on which to calculate cv2

Returns

The cv2 of the array

spiketimes.statistics.cv2_isi(spiketrain: numpy.ndarray)[source]

Calculate the cv2 of inter-spike-intervals.

The Cv2 is a metric similar to the coefficient of variation but which includes a correction for signals which slowly fluctuate over time. [Suitable for long term neuronal recordings.]

Parameters

spiketrain – a numpy array of spiketimes in seconds

Returns

The cv2 of inter-spike-intervaks value

spiketimes.statistics.cv_isi(spiketrain: numpy.ndarray)[source]

Caluclate the coefficient of variation of inter-spike-intervals.

Parameters

spiketrain – A numpy array of spiketimes

Returns

The coeffient of variation of inter-spike-intervals

spiketimes.statistics.diffmeans_test(spike_counts: numpy.ndarray, which_condition: numpy.ndarray, n_boot: int = 1000)[source]

Calculates the difference between means of spike counts and tests significance using a permutation test.

Parameters
  • spike_counts – A numpy array containing spike counts from both conditions

  • which_condition – A numpy array indicating the condition of each spike count entry. 0s for the first condition, and 1s for the second condition. For example, if the first two elements in spike_counts were from the first condition and the third element from the second condition, which_condition would contain [0, 0, 1] 1 is subtracted from 2 in the difference calculation.

  • n_boot – The number of bootstrap replicates to draw

Returns

Difference of means, p

spiketimes.statistics.ifr(spiketrain: numpy.ndarray, fs: float, t_start: float = None, t_stop: float = None, sigma: float = None, as_df: float = False)[source]

Estimate instantaneous firing rate at a regular sampling rate.

Parameters
  • spiketrain – A numpy array of spiketimes in seconds

  • fs – The sampling rate at which to estimate firing rate

  • t_start – If specified, only returns times after this point

  • t_stop – If specified, only returns times before this point

  • sigma – Parameter controling degree of smooting of firing rate estimates. Set to 0 for no smoothing.

  • as_df – Whether to return results as pandas DataFrame

Returns

time_bins, ifr

spiketimes.statistics.inter_spike_intervals(spiketrain: numpy.ndarray)[source]

Get the inter-spike-intervals of a spiketrain

Parameters

spiketrain – a numpy array spike times

Returns

A numpy array of inter spike intervals

spiketimes.statistics.mean_firing_rate(spiketrain: numpy.ndarray, t_start: float = None, t_stop: float = None)[source]

Calculate the mean firing rate of a spiketrain by summing total spikes and dividing by time.

Parameters
  • spiketrain – A numpy array of spiketimes in seconds

  • t_start – The start of the time over which mean firing rate will be calculated. Defaults to the timepoint of the first spike

  • t_end – The end of the time over which mean firing rate will be calculated defaults to the timepoint of the last spike

Returns

The mean firing rate of the spiketrain

spiketimes.statistics.mean_firing_rate_ifr(spiketrain: numpy.ndarray, fs: float, sigma: float = None, t_start: float = None, t_stop: float = None, exclude_below: float = None)[source]

Calculate the mean firing rate of a spiketrain by first estimating the instantaneous firing rate at some sampling interval and then taking the median.

Usefull when firing rate during active periods only is desired.

Parameters
  • spiketrain – A numpy array of spiketimes in seconds

  • fs – The sampling rate at which instantaneous rate is calculated

  • sigma – A oarameter controlling the degree of smoothing level of firing rate estimates.

  • t_start – The start of the time over which mean firing rate will be calculated. Defaults to the timepoint of the first spike

  • t_end – The end of the time over which mean firing rate will be calculated defaults to the timepoint of the last spike

  • min_fr – If specified, calculates mean over time bins where mean firing rate is greater than this threshold

Returns

A firing rate estiamte

spiketimes.statistics.zscore_standardise(to_standardise: numpy.ndarray, baseline: numpy.ndarray)[source]

Convert an array to zscores calculated on a baseline period.

Parameters
  • to_normalise – A numpy array to be converted to zscores.

  • baseline – A numpy array containing data used to calculate the mean and standard deviation for zscore conversions. This is usually (but not necessarily) a subsection of to_standardise

Returns

A numpy array of zscores

Correlating Spiketrains

spiketimes.correlate.auto_corr(spiketrain: numpy.ndarray, binsize: float = 0.01, num_lags: int = 100, as_df: bool = False, t_start: float = None, t_stop: float = None)[source]

Returns the autocorrelation function of a spiketrain.

Parameters
  • spiketrain – A numpy array of spiketimes

  • binsize – The size of the time bin in seconds

  • num_lags – The number of lags forward and backwards around lag 0 to return

  • t_start – Minimum timepoint

  • t_stop – Maximum timepoint

  • as_df – Whether to return results as pandas DataFrame

Returns

time_bins, autocorrelation_values

spiketimes.correlate.cross_corr(spiketrain_1: numpy.ndarray, spiketrain_2: numpy.ndarray, binsize: float = 0.01, num_lags: int = 100, as_df: bool = False, t_start: float = None, t_stop: float = None, delete_0_lag: bool = False)[source]

Calculate crosscorrelation between two spiketrains.

Parameters
  • spiketrain_1 – A numpy array of spiketimes.

  • spiketrain_2 – A numpy array of spiketimes

  • binsize – The size of the time bin in seconds

  • num_lags – The number of lags forward and backwards around lag 0 to return

  • as_df – Whether to return results as pandas DataFrame

  • t_start – Minimum timepoint

  • t_stop – Maximum timepoint

  • delete_0_lag – Wheter to remove the 0-lag element

Returns

time_bins, crosscorrelation_values

spiketimes.correlate.cross_corr_test(spiketrain_1: numpy.ndarray, spiketrain_2: numpy.ndarray, binsize: float = 0.01, num_lags: int = 100, as_df: bool = False, t_start: float = None, t_stop: float = None, tail: str = 'two_tailed', adjust_p: bool = True, p_adjust_method: str = 'Benjamini-Hochberg')[source]

Calculate crosscorrelation between two spiketrains. Also test significance of each bin.

Significance test performed by comparing observed crosscorrelation to expected cross correlation of poisson spiketrains.

Parameters
  • spiketrain_1 – A numpy array of spiketimes.

  • spiketrain_2 – A numpy array of spiketimes

  • binsize – The size of the time bin in seconds

  • num_lags – The number of lags forward and backwards around lag 0 to return

  • as_df – Whether to return results as pandas DataFrame

  • t_start – Minimum timepoint

  • t_stop – Maximum timepoint

  • delete_0_lag – Wheter to remove the 0-lag element

  • tail – Tail for hypothesis test {“two_tailed”, “upper”, “lower”}. Two tailed reccomended

  • adjust_p – Whether to adjust p-values for multiple comparisons.

  • p_adjust_method – If adjusting p-values, specified which method to use {Benjamini-Hochberg’, ‘Bonferroni’, ‘Bonferroni-Holm’}

Returns

time_bins, crosscorrelation_values, p

spiketimes.correlate.spike_count_correlation(spiketrain_1: numpy.ndarray, spiketrain_2: numpy.ndarray, binsize: float, min_firing_rate: float = None, t_start: float = None, t_stop: float = None)[source]

Calculate spike count correlation between two spiketrains.

Parameters
  • spiketrain_1 – A numpy array of spiketimes.

  • spiketrain_2 – A numpy array of spiketimes

  • binsize – The size of the time bin in seconds

  • min_firing_rate – If selected, selects only bins where the geometric mean firing rate of the two spiketrains exeedes this value.

  • t_start – Minimum timepoint

  • t_stop – Maximum timepoint

Returns

Pearson’s correlation coefficient

spiketimes.correlate.spike_count_correlation_test(spiketrain_1: numpy.ndarray, spiketrain_2: numpy.ndarray, binsize: float, n_boot: int = 500, min_firing_rate: float = None, t_start: float = None, t_stop: float = None, tail: str = 'two_tailed')[source]

Calculate peason’s correlation coefficient between spikecounts of a pair of spiketrains.

Parameters
  • spiketrain_1 – The first spiketrain to correlate. Should be an nd.array of spiketimes in seconds.

  • spiketrain_2 – The second spiketrain to correlate. Should be an nd.array of spiketimes in seconds.

  • binsize – The size of time bins used in seconds.

  • min_firing_rate – If selected, selects only bins where the geometric mean firing rate of the two spiketrains exeedes this value

  • t_start – The startpoint of the first bin. Defaults to the first spike in the two trains

  • t_stop – The maximum time for a time bin. Defaults to the last spike in the two trians

Returns

R, p

Population Analysis

spiketimes.population.population_coupling(spiketrain: numpy.ndarray, spiketrain_list: list, bin_window: float = 0.01, num_lags: int = 100, as_df: bool = False, t_start: float = None, t_stop: float = None, frac_zscore: float = 0.25, return_all: bool = False)[source]

Calculate the population-coupling index between a spiketrain and the population.

The metric is calculated by computing and standardising cross correlation between an individual spiketrain and the “population spiketrain”, consisting of all other neurons. Large Z score cross correlation at lag=0 is indicative of high population coupling.

Parameters
  • spiketrain – A numpy array of spiketimes

  • spiketrain_list – A list of numpy-array spiketrains

  • binsize – The size of the time bin in seconds

  • num_lags – The number of lags forward and backwards around lag 0 to return

  • as_df – Whether to return results as pandas DataFrame

  • t_start – Minimum timepoint

  • t_stop – Maximum timepoint

  • return_all – If true, all time bins and cross correlation values are returned

Returns

The zscore at lag=0 between the spiketrain and the population

Plots

spiketimes.plots.add_event_vlines(ax, events: numpy.ndarray, t_min: float = None, t_max: float = None, vline_kwargs: dict = None)[source]

Add vertical lines to a matplotlib axes object at the point(s) specified in events. t_min and t_max define minimum and maximum timepoints for events i.e. no events outside these limits will be plotted.

Parameters
  • ax – the axes to plot on top of

  • events – an array of points on the x axis to plot

  • t_min – if specified, no points less than this will be plotted

  • t_max – if specified, no points greater than this will be plotted

Returns

matplotlib axes

spiketimes.plots.aligned_raster(spiketrain: numpy.ndarray, trial_starts: numpy.ndarray, before: float = None, max_latency: float = None, ax=None, raster_kwargs=None)[source]

Constructs a raster plot with each row containing spikes from a single trial.

Parameters
  • spiketrain – a spiketrain containing spiketimes in seconds.

  • trial_starts – an array of trial starts in seconds.

  • before – if specified, include this amount of time (in seconds) before each trial

  • max_latency – if specified, exclude spikes occuring this amount of time (in seconds) after the final event.

  • ax – matplotlib axes object to plot on.

Returns

A matplotlib axes object

spiketimes.plots.grouped_raster(st_lists: list, color_list: list = None, ax=None, skip_empty=True, t_start: float = None, t_stop: float = None, plot_kwargs=None, space_between_groups: int = 2)[source]

Construct a raster plot of multiple groups of spiketrains.

Parameters
  • st_lists – A list of lists of spiketrains. Each sublist contains one group of spiketrains.

  • color_list – A list containing one color for each group to be plotted/

  • ax – A matplotlib axes object

  • skip_empty – Whether to skip spiketrains with no spikes in the plotting interval

  • t_start – Minimum timepoint

  • t_stop – Maximum timepoint

  • plot_kwargs – Additional key-word arguments will be passed into matplotlib.pyplot.plot

  • space_between_groups – Number of spaces between groups in the y direction.

Returns

A matloblib axes object

spiketimes.plots.psth(spiketimes: numpy.ndarray, events: numpy.ndarray, binwidth: float = 0.01, t_before: float = 0.2, max_latency: float = 2, ax=None, hist_kwargs: dict = None, vline_kwargs: dict = None)[source]

Contruct a peristimulus time histogram of spiketimes latencies to events.

t_before defines the time before time 0 (when the event occured) to include in the histogram

Parameters
  • spiketimes – A numpy array of spiketimes

  • events – A numpy array of event times in the same units as spiketimes

  • binwidth – The width of time bins

  • t_before – The time before the aligned event to include in the psth

  • max_latency – The maximum allowed latency. Useful for excluding spikes occuring after the final event.

  • ax – An optional matloblib axes object to use

  • hist_kwargs – A dict of kwargs to pass to matplotlib.pyplot.hist

Returns

A matplotlib.pyplot.axes object

spiketimes.plots.raster(spiketrain_list: list, ax=None, skip_empty=True, t_start: float = None, t_stop: float = None, _starting_ytick=None, **kwargs)[source]

Construct a raster plot of multiple spiketrains

Parameters
  • spiketrain_list – A list of numpy arrays containing the timings of spiking events

  • ax – A matplotlib axes object on which to plot

  • skip_empty – Whether to skip spiketrains with no spikes in the plotting interval

  • t_start – Minimum timepoint

  • t_stop – Maximum timepoint

  • _starting_y_tick – The position on the y axis to start.

  • kwargs – Additional key-word arguments will be passed into matplotlib.pyplot.plot

Returns

A matloblib axes object