API
spikeanalysis
- class spikeanalysis.SpikeAnalysis(save_parameters: bool = False, verbose: bool = False)
Class for spike train analysis utilizing a SpikeData object and a StimulusData object
- autocorrelogram(time_ms: float = 500)
function for calculating the autocorrelogram of the spikes
Parameters
- time_ms: float, default:500
The number of millseconds to look after each spike
- compute_event_interspike_intervals(time_ms: float = 200)
Calculates the interspike intervals during baseline time before stimulus events and after during stimulus events for the time given by time_ms
Parameters
- time_msfloat,
Time in which to assess interspike intervals given in milliseconds. The default is 200 (ms)
- get_interspike_intervals()
Function for obtaining the raw interspike intervals in samples. Organized by unit.
- get_raw_firing_rate(time_bin_ms: Union[list[float], float], fr_window: Union[list, list[list]], mode: str, bsl_window: Optional[Union[list, list[list]]] = None, sm_time_ms: Optional[Union[list[float], float]] = None)
Function for talking the raw firing rates based on the PSTH
Parameters
- time_bin_msUnion[list[float], float]
The time bin desired for generating firing rates(larger bins lead to smoother data). Either a single float applied to all stim or a list with a value for each stimulus
- fr_windowUnion[list, list[list]],
The event window for finding the firing rate/time_bin. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- mode: str in (‘raw’, ‘smooth’, ‘bsl-subtracted’)
Value to return firing rate as either a raw firing rate based on time_bin_ms, as a gaussian smoothed firing rate (requires sm_time_ms), or with baseline subtraction in which the mean firing rate during the baseline is subtracted from each bin
- bsl_windowUnion[list, list[list]]
The baseline window for finding the baseline mean and std firing rate. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- sm_time_ms: Optional[Union[list[float], float]], default None
The smoothing standard deviation to use for the gaussian smoothing. Default is None, but this value must be given if mode is set to ‘smooth’
- get_raw_psth(window: Union[list, list[list]], time_bin_ms: float = 1.0)
function for generating the raw psth with spike counts for each bin
Parameters
- windowUnion[list, list[list]]
window to analyze the psth either given as one squence of (start, end) or nested list of lists which each nested list giving (start, end) for a stimulus.
- time_bin_msfloat, optional
time bin size given in milliseconds. Small enough to have 1 or less spikes in each bin The default is 1.0 (ms).
- get_responsive_neurons(z_parameters: Optional[dict] = None, latency_threshold_ms: Optional[dict] = None)
function for assessing only responsive neurons based on z scored parameters.
Parameters
- z_parametersOptional[dict], optional
gives the manual classes of response type. Run ` _generate_sample_z_parameter` The default is None.
Raises
- Exception
General exception if there is no json or dictonary of desried z values.
Returns
None.
- latencies(bsl_window: Union[list, list[float]], time_bin_ms: float = 50.0, num_shuffles: int = 300)
Calculates the latency to fire for each neuron based on either Chase & Young 2007 or Mormann et al. 2012 with the cutoff being a baseline firing rate of 2Hz
Parameters
- bsl_windowUnion[list, list[float]]
The baseline window for determining baseline firing rate given as sequence of (start, end) for all stim or a list of lists with each stimulus having (start, end)
- time_bin_ms: float, default:50
Size of new time bins to use.
- num_shufflesint, default: 300
The number of shuffles to perform for finding the shuffled distribution
- save_responsive_neurons(overwrite: bool = False)
Saves responsive neurons as a json file
Parameters
- overwrite: bool, default: False
Whether to overwrite the json caching
- save_z_parameters(z_parameters: dict, overwrite: bool = False)
saves the z parameters to be used in the future
Parameters
- overwrite: bool, default: False
Whether to overwirte the z parameters file
- set_spike_data(sp: SpikeData, cluster_ids: np.array | list | None = None, same_folder: bool = True)
loads in spike data from phy for analysis
Parameters
- spSpikeData
A SpikeData object to analyze spike trains
- cluster_ids: np.array | list | None, default: None
If one decides to run a subset of clusters of their own choice enter here
- same_folder: bool, default: True
whether stim and spike data are in the same folder
- set_spike_data_si(sorting: Sorting)
loads in a spikeinterface sorting object to serve as spike data
Parameters
- sorting: Sorting
spikeinterface sorting
- set_stimulus_data(event_times: StimulusData, same_folder: bool = True)
loads in the stimulus data for anayzing spike trains
Parameters
- event_timesStimulusData
The StimulusData object which suplies the stimulus data
- same_folderbool, default: True
whether stim and spike data are in same folder
- trial_correlation(window: Union[list, list[list]], time_bin_ms: Optional[float] = None, dataset: psth' | 'raw' | 'z_scores = 'psth', method: pearson' | 'kendall' | 'spearman = 'pearson')
Function to calculate pairwise pearson correlation coefficents of z scored or raw firing rate data/time bin. Organized by trial groupings.
Parameters
- windowUnion[list, list[list]]
The window over which to calculate the correlation given as a single list of (start, stop) or as a list of lists with each list have the (start, stop) for its associated stimulus
- time_bin_msfloat, optional
Size of time bins to use given in milliseconds. Bigger time bins smooths the data which can remove some artificial differences in trials.
- dataset“psth” | “raw” | “z_scores”, default: “psth”
Whether to use the psth (raw spike counts) raw (the firing rates) or z_scored data.
- method: “pearson”, “kendall”, “spearman”, default: “pearson”
the correlation method to be used in the pandas.DataFrame.corr() function
- z_score_data(time_bin_ms: Union[list[float], float], bsl_window: Union[list, list[list]], z_window: Union[list, list[list]], eps: float = 0)
z scores data the psth data
Parameters
- time_bin_msUnion[list[float], float]
The time bin desired for generating z scores (larger bins lead to smoother data). Either a single float applied to all stim or a list with a value for each stimulus
- bsl_windowUnion[list, list[list]]
The baseline window for finding the baseline mean and std firing rate. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- z_windowUnion[list, list[list]],
The event window for finding the z scores/time_bin. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- eps: float, default: 0
Value to prevent nans from occurring during z-scoring
- class spikeanalysis.SpikeData(file_path: Union[str, Path], cache: bool = False)
Class for loading “phy” type data files including generating some qc metrics and raw waveforms. To be used by SpikeAnalysis
- denoise_data()
Function for removing clusters labeled as noise in Phy
- generate_pcs()
Reorganizes the Phy pc values based on manual curation
Returns
None, stored as pc_feat, and pc_feat_ind
- generate_qcmetrics()
Using pc_feat from generate_pcs() this runs isolation distance (mahal distance) as well as simplified silhouette score on all clusters. isolation distance ranges from 0-inf and silhouette score ranges from -1, 1
Returns
None, values stored as isolation_distances and silhouette_scores, respectively
- get_amplitudes(std: float = 2)
function for assessing amplitude distribution.
Parameters
- std: float, default: 2
The number of standard deviations to use when assessing the desired spread of the data
Returns
None.
- get_template_positions(depth: float = 0)
Function for determining template depths. Good for assessing drift
Parameters
- depth: float
The depth within the tissue if true depth desired.
- get_waveform_values(depth: float = 0)
Function that uses weighted average of waveforms to calculate waveform metrics such as duration, amplitude, depths
Parameters
- depthfloat, optional
If given this is the true depth of the probe in the tissue and will cause the depths to corrected to depth in tissue rather than distance from probe tip. The default is 0.
Returns
None.
- get_waveforms(wf_window: tuple = (-40, 41), n_wfs: int = 500)
collects raw waveforms from the associated binary file used in Kilosort/Phy.
Parameters
- wf_windowtuple, optional
This is the sample window to assess around each spike. The default is (-40,41).
- n_wfsint, optional
The number of waveforms to save for each cluster. The default is 500.
Returns
None, saves the spikes used in waveform_spike_times and the waveforms as waveforms
- qc_preprocessing(idthres: Optional[float] = None, rpv: Optional[float] = None, sil: Optional[float] = None, amp_cutoff: Optional[float] = None, recurated: bool = False)
function for curating data based on qc metrics and refractory periods
Parameters
- idthresOptional[float], default: None
The cutoff isolation distance, 0 means no curation.
- rpvOptional[float], default: None
Fractional rate of refractory period violations, 0 is no violations and 1 would be all violations okay
- silOptional[float], default: None
Minimum silhouette score, [-1, 1], where bigger is better.
- amp_cutoff: Optional[float], default = None
The percentage of spikes allowed to be over the user specified standard deviations (default 2) given as the desired percentage. E.g. 0.98 means 98% of spikes are within 2 stds.
- recuratedbool, default: False
If data has been recurated in phy since the last data run. The default is False.
Raises
- Exception
If various functions haven’t been run
Returns
None.
- refractory_violation(ref_dur_ms: float)
Calculates the number of refractory period violations for each cluster of spikes
Parameters
- ref_dur_msfloat
The biological refractory period given in milliseconds. This is the value in which neurons should not be able to fire again.
Returns
None, but value stored as refractory_period_violations
- reload_data()
Function to reload raw values for after running denoise_data
- run_all(ref_dur_ms: float, idthres: float, rpv: float, sil: float, amp_std: float, amp_cutoff: float, recurated: bool = False, set_caching: bool = True, depth: float = 0)
Pipeline function to run all functionality of SpikeData in a row including change chaching state, doing refractory periods, qcmetrics, denoising data, and getting waveform values.
Parameters
- ref_dur_ms: float
Refractory period time in ms
- idthres: float
the isolation distance cutoff value to use (ID values vary from 0 to + inf)
- rpv: float
the refractory period violation fraction allowed: 0.02 would be 2% violations
- sil: float
the silhouette score allowed -1 (bad) to 1 (perfect)
- amp_std: float
the std to use for calculating the number of spikes which past that range
- amp_cutoff: float
the cutoff value to use for qc for the amplitudes values, example .98 means 98% fall within amp_std stds of the mean amplitude
- recurated: bool
If more Phy curation has occurred such that any cached or currently loaded values need to be overwritten (True), Default False
- set_caching: bool
Whether to save files for future analysis, default True
- depth: float
The depth of the probe in order to provide ‘Real’ depth rather than distance from probe
- samples_to_seconds()
utility function which converts spike_times from samples to seconds
- set_caching(cache: bool = True)
Function for determining whether to save data generated from session or not.
Parameters
- cache: bool
Whether to save all data generated during this session, default True
- set_qc()
Function to load the qc mask onto the cluster ids.
- class spikeanalysis.StimulusData(file_path: str, recordingless: bool = False, verbose: bool = True)
Class for preprocessing stimulus data for spike train analysis
- create_neo_reader(file_name: str | pathlib.Path | None = None)
Function that creates a Neo IntanRawIO reader and then parses the header
Parameters
- file_name: Optional[filename]
Default None uses the internal function, whereas providing a file_name will call the neo function get_rawio_class to return a neo reader that can be used
Returns
- neo_class: neo.rawio
Returns a neo.rawio class if filename is given otherwise stores values internally
- delete_events(del_index: int | list[int], digital: bool = True, channel_name: str | None = None, channel_index: str | None = None)
Function for deleting a spurious event, eg, an accident trigger event
Parameters
- digital: bool, default: True
Whether to delete digital or analog events
- channel_name: str | None, default: None
the channel name of a digital signal to clean up, must be given if digital=True
- channel_index: int | None, default: None
the channel index of an analog event to delete, must be given if digital=False
- del_index: int | None, default: None
the index of the event which is to be delete
- digitize_analog_data(analog_index: int | None = None, stim_length_seconds: float | None = None, stim_name: list[str] | None = None, min_threshold: None | list = None)
Function to digitize the analog data for stimuli that have “events” rather than assessing them as continually changing values
- generate_stimulus_trains(channel_name: str | list[str], stim_freq: float | list[float], stim_time_secs: float | list[float])
Function for converting events into event trains, eg for optogenetic stimulus trains
Parameters
- channel_nameUnion[str, list[str]]
Then channel_name which needs to be converted from individual events to trains.
- stim_freqUnion[float, list[float]]
Stimulation frequency (eg. 20.0 for 20 Hz).
- stim_time_secsUnion[float, list[float]]
Length of time the stimulus is occurring in seconds (for example 0.5 would be 500 ms).
- get_all_files()
function to load all stimulus data from a previous instance of the class if saved
- get_analog_data(time_slice: tuple = (None, None))
Function to load analog data from an Intan file. Requires the IntanRawIO to be generated with create_neo_reader
Parameters
- time_slice: tuple[start, stop]
time slice of the data to analyze given in seconds with format (start, stop) None for start indicates start at 0, None for stop indicates go to end of recording
- get_final_digital_data()
Function for converting the digital memmap info into actual digital channels.
- get_raw_digital_data(time_slice: tuple = (None, None))
This is a function that in the future will get the digital data, but currently due to the inability to grab digital from neo automatically. Calls on internal hack to call digital data.
- get_stimulus_channels() dict
function to give names of stimulus channels since they are a bit long for Intan
Raises
- Exception
If there are no digital events then this function can’t be run
Returns
- dict
Keys are the correct channel names. Values are empty strings that can be replaced for other functions.
- run_all(stim_index: int | None = None, stim_length_seconds: float | None = None, stim_name: list | None = None, time_slice: tuple = (None, None), min_threshold: None | list = None)
Pipeline function to run through all steps necessary to load intan data
Parameters
- stim_indexOptional[int], optional
If there are particular desired analog stimuli to assess. The default is None.
- stim_length_secondsOptional[float], optional
The length (seconds) of the analog stimuli to digitize them. The default is None.
- stim_nameOptional[list], optional
Name of the stimulus. The default is None.
- time_slice: tuple[start, stop]
time slice of recording to use, given in seconds with start and stop
- min_threshold: None | list, deafult: None,
Whether to set a distinct threshold for analog stim
- save_events()
Function for saving events in json for nested structures and .npy files for simple arrays
- set_trial_groups(trial_dictionary: dict)
function for setting trial groups.
Parameters
- trial_dictionarydict
Dictionary where key is the channel name and value is an np.array or list with n elements = len(events) (filled with ints.)
Raises
- Exception
If keys do not exist it warns and gives the current channel names
Returns
None.
- class spikeanalysis.IntrinsicPlotter(**kwargs)
Class for plotting acgs, waveforms, cdfs
- plot_acgs(sp: Union[SpikeData, SpikeAnalysis], window_ms: Optional[float] = None, ref_dur_ms: Optional[float] = None)
Function for plotting autocorrelograms.
Parameters
- sp: SpikeData, SpikeAnalysis
the data to use to calculate autocorrelograms
- window_ms: Optional[float]:
The window to use to generate autocorrelogram given in milliseconds. If None given it will use a default of 300 ms, default None.
- ref_dur_ms: Optional[float]
refractory period to mark with a red line in the acg. Just for visualization. Does not change the calculations., default is None, meaning no marking
- plot_pcs(sp: SpikeData)
Plotting function to give represent a cluster vs all other clusters in its top two PCs. If the top two PCs describe a large portion of variability this is accurate assesment of cluster quality otherwise it is a poor assessment of cluster quality.
Parameters
- sp: spikeanalysis.SpikeData
The SpikeData over which to determine PCs. The SpikeData must have pc features so generate_pcs should be run before using this function.
- plot_spike_depth_fr(sp: SpikeData)
Function for plotting the firing rates at all depths of a recording. If depth was set during the SpikeData.get_waveform_values then this is true depth in the tissue. If not then the depth is relatively to the 0 point of the probe.
Parameters
- sp: spikeanalysis.SpikeData
The SpikeData object to obtain firing rates and depths from
- class spikeanalysis.SpikePlotter(analysis: Optional[Union[SpikeAnalysis, CuratedSpikeAnalysis, MergedSpikeAnalysis]] = None, **kwargs)
SpikePlotter is a plotting class which allows for plotting of PSTHs, z score heatmaps in the future it will plot other values
- plot_correlations(plot_type='whisker', mode='mean', colors='r', sem=True, plot_kwargs=None)
Function for plotting correlations in different formats
Parameters
- plot_type: ‘whisker’ | ‘violin’ | ‘bar’, default: ‘whisker’
Type of plot for plotting
- mode: ‘mean’ | ‘median’, default: ‘mean’
Whether to calculate and show the mean or median this is plot dependent
- colors: matplotlib color | dict[matplotlib colors]:
for plot_type = ‘bar’ the color for the different stimuli can be one color for all bars or a dict with keys of stim and values of colors
- sem: bool, default: True
If plot_type = ‘bar’ whether to use sem or std
- plot_kwargs: dict() | None, default: None
To directly provide kwargs to the underlying matlplotlib functions
- plot_event_isi(colors: str | dict, include_ids: list | np.array | None = None, plot_kwargs: dict = {})
Function for plotting changes in isi during events/trials
Parameters
- colors: str | dict[str]
matplotlib color or dict of colors with key:stim value:color
- include_ids: list | np.array | None, default: None
A sequence of cluster ids to plot
- plot_kwargs: dict, default: {}
plotting kwargs
- plot_isi()
Function for plotting ISI distributions
- plot_latencies(colors='red', plot_kwargs={})
Function for plotting latencies Parameters ———- colors: colormap color | dict[colormap color], default = ‘red’
Either the color for all stim or a dict of colors for each stim
- plot_kwargs: dict default: {}
matplot lib kwargs to overide the global kwargs for just the function
- plot_raster(window: Union[list, list[list]], show_stim: bool = True, include_ids: list | np.nadarry | None = None, color_raster: bool = False, plot_kwargs: dict = {})
Function to plot rasters
Parameters
- windowUnion[list, list[list]]
The window [start, stop] to plot the raster over. Either one global list or nested list of [start, stop] format
- show_stim: bool, default True
Show lines where stim onset and offset are
- include_ids: list | np.ndarray | None, default: None
sub ids to include
- plot_kwargs: dict default: {}
matplot lib kwargs to overide the global kwargs for just the function
- plot_raw_firing(figsize: Optional[tuple] = (24, 10), sorting_index: Union[int, None, list[int]] = None, bar: Optional[list[int]] = None, indices: bool = False, show_stim: bool = True, exclusion_dict: dict | None = None, plot_kwargs: dict = {}) Optional[numpy.array]
Function to plot heatmaps of raw firing rate data. Can be baseline subtracted, raw or smoothed Based on what was run in SpikeAnalysis. All trial groups are plotted on the same axes. So it is best to have a figsize that wide to fit all different trial groups. In this plot each row across all heat maps is the same unit/neuron and all plots share the same min/max firing score colormap.
Parameters
- figsizeOptional[tuple], optional
Matplotlib figsize tuple. For multiple trial groups bigger is better. The default is (24, 10).
- sorting_indexOptional[int] | list[int], optional
The trial group to sort all values on. The default is None (which uses the largest trial group).
- bar: list[int]
If given a list with min firing rate for the cbar at index 0 and the max at index 1. Overrides cbar generation
- indices: bool, default False
If true will return the cluster ids sorted in the order they appear in the graph
- show_stim: bool, default True
Show lines where stim onset and offset are
- plot_kwargs: dict default: {}
matplot lib kwargs to overide the global kwargs for just the function
Returns
- ordered_cluster_ids: Optional[dict]
if indices is True, the function will return the cluster ids as displayed in the z bar graph
- plot_response_trace(fr_type: Literal['zscore', 'raw'] = 'zscore', by_neuron: bool = False, by_trial: bool = False, by_trialgroup: bool = False, ebar: bool = False, colors='black', show_stim: bool = True, sem: bool = False, mode: Literal['mean', 'median', 'max', 'min'] = 'mean', plot_kwargs: dict = {})
Function for plotting response traces for either z scored or raw firing rates
Parameters
- fr_type: Literal[‘zscore’, ‘raw’], default: ‘zscore’
Whether to generate traces with zscored data or raw firing rate data
- by_neuron: bool, default: False
Whether to plot each neuron separate (True) or average over all neurons (False)
- by_trial: bool, default: False
Whether to plot each trial separately (True) or average over all neurons (False)
- ebar: bool, default: False
Whether to include error bars in the traces
- color: matplotlib color | dict[matplotlib color], default: ‘black’
Color to plot the traces in, or dict of how to color the stim
- show_stim: bool, default=True
Whether to show stimulus lines
- mode: ‘mean’| ‘median’ | ‘max’ | ‘min’ | func default: ‘mean’
How to calculate values for plotting, can be a string in which case the appropriate nan-based numpy function is used. Otherwise the user can give an appropriate function to use (it needs to be able to handle) data with nans
- plot_kwargs: dict default: {}
matplot lib kwargs to overide the global kwargs for just the function
- plot_sm_fr(window: Union[list, list[list]], time_bin_ms: Union[float, list[float]], sm_time_ms: Union[float, list[float]], show_stim: bool = True, include_ids: list | np.ndarray | None = None, plot_kwargs: dict = {})
Function to plot smoothed firing rates
Parameters
- windowUnion[list, list[list]]
The window [start, stop] to plot the raster over. Either one global list or nested list of [start, stop] format
- time_bin_ms: Union[list, list[float]]
The new time bin size desired.
- sm_time_msUnion[float, list[float]]
Smoothing time in milliseconds. Either one global smoothing time or a list of smoothing time stds for each stimulus
- show_stim: bool, default True
Show lines where stim onset and offset are
- include_ids: list | np.ndarray | None
The ids to include for plotting
- plot_kwargs: dict default: {}
matplot lib kwargs to overide the global kwargs for just the function
- plot_zscores(figsize: Optional[tuple] = (24, 10), sorting_index: Union[int, None, list[int]] = None, z_bar: Optional[list[int]] = None, indices: bool = False, show_stim: bool = True, exclusion_dict: dict = None, plot_kwargs: dict = {}) Optional[numpy.array]
Function to plot heatmaps of z scored firing rate. All trial groups are plotted on the same axes. So it is best to have a figsize that wide to fit all different trial groups. In this plot each row across all heat maps is the same unit/neuron and all plots share the same min/max z score colormap.
Parameters
- figsizeOptional[tuple], optional
Matplotlib figsize tuple. For multiple trial groups bigger is better. The default is (24, 10).
- sorting_indexOptional[int] | list[int], optional
The trial group to sort all values on. The default is None (which uses the largest trial group).
- z_bar: list[int]
If given a list with min z score for the cbar at index 0 and the max at index 1. Overrides cbar generation
- indices: bool, default False
If true will return the cluster ids sorted in the order they appear in the graph
- show_stim: bool, default True
Show lines where stim onset and offset are
- plot_kwargs: dict default: {}
matplot lib kwargs to overide the global kwargs for just the function
Returns
- sorted_cluster_ids: np.array
if indices is True, the function will return the cluster ids as displayed in the z bar graph
- plot_zscores_ind(z_bar: Optional[list[int]] = None, show_stim: bool = True)
Function for plotting z scored heatmaps by trial group rather than all trial groups on the same set of axes. In This function all data is ordered based on the most responsive unit/trial group. Rows can be different units since each trial group is handled individually. Scaling is also handled individual some the max/min values represented by the color map may be different between trial groups.
Parameters
- z_bar: list[int]
If given a list with min z score for the cbar at index 0 and the max at index 1. Overrides cbar generation
- show_stim: bool, default: True
Whether to mark at the stim onset and offset
- set_analysis(analysis: spikeanalysis.spike_analysis.SpikeAnalysis | spikeanalysis.curated_spike_analysis.CuratedSpikeAnalysis | spikeanalysis.merged_spike_analysis.MergedSpikeAnalysis)
Set the SpikeAnalysis object for plotting
Parameters
- analysis: spikeanalysis.SpikeAnalysis
The SpikeAnalysis object for plotting
- class spikeanalysis.AnalogAnalysis(sp: SpikeData, event_times: StimulusData)
Class for analyzing analog stimulus data along with spiking data
- class spikeanalysis.MergedSpikeAnalysis(spikeanalysis_list=None, name_list=None, save_parameters=False, verbose=False)
- compute_event_interspike_intervals()
Calculates the interspike intervals during baseline time before stimulus events and after during stimulus events for the time given by time_ms
Parameters
- time_msfloat,
Time in which to assess interspike intervals given in milliseconds. The default is 200 (ms)
- get_interspike_intervals()
Function for obtaining the raw interspike intervals in samples. Organized by unit.
- get_raw_firing_rate(time_bin_ms: list[float] | float, fr_window: list | list[list], mode: str, bsl_window: list | list[list] | None = None, sm_time_ms: list[float] | float | None = None, fill=numpy.nan)
Function for talking the raw firing rates based on the PSTH
Parameters
- time_bin_msUnion[list[float], float]
The time bin desired for generating firing rates(larger bins lead to smoother data). Either a single float applied to all stim or a list with a value for each stimulus
- fr_windowUnion[list, list[list]],
The event window for finding the firing rate/time_bin. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- mode: str in (‘raw’, ‘smooth’, ‘bsl-subtracted’)
Value to return firing rate as either a raw firing rate based on time_bin_ms, as a gaussian smoothed firing rate (requires sm_time_ms), or with baseline subtraction in which the mean firing rate during the baseline is subtracted from each bin
- bsl_windowUnion[list, list[list]]
The baseline window for finding the baseline mean and std firing rate. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- sm_time_ms: Optional[Union[list[float], float]], default None
The smoothing standard deviation to use for the gaussian smoothing. Default is None, but this value must be given if mode is set to ‘smooth’
- get_raw_psth(window, time_bin_ms)
function for generating the raw psth with spike counts for each bin
Parameters
- windowUnion[list, list[list]]
window to analyze the psth either given as one squence of (start, end) or nested list of lists which each nested list giving (start, end) for a stimulus.
- time_bin_msfloat, optional
time bin size given in milliseconds. Small enough to have 1 or less spikes in each bin The default is 1.0 (ms).
- latencies()
Calculates the latency to fire for each neuron based on either Chase & Young 2007 or Mormann et al. 2012 with the cutoff being a baseline firing rate of 2Hz
Parameters
- bsl_windowUnion[list, list[float]]
The baseline window for determining baseline firing rate given as sequence of (start, end) for all stim or a list of lists with each stimulus having (start, end)
- time_bin_ms: float, default:50
Size of new time bins to use.
- num_shufflesint, default: 300
The number of shuffles to perform for finding the shuffled distribution
- trial_correlation()
Function to calculate pairwise pearson correlation coefficents of z scored or raw firing rate data/time bin. Organized by trial groupings.
Parameters
- windowUnion[list, list[list]]
The window over which to calculate the correlation given as a single list of (start, stop) or as a list of lists with each list have the (start, stop) for its associated stimulus
- time_bin_msfloat, optional
Size of time bins to use given in milliseconds. Bigger time bins smooths the data which can remove some artificial differences in trials.
- dataset“psth” | “raw” | “z_scores”, default: “psth”
Whether to use the psth (raw spike counts) raw (the firing rates) or z_scored data.
- method: “pearson”, “kendall”, “spearman”, default: “pearson”
the correlation method to be used in the pandas.DataFrame.corr() function
- z_score_data(time_bin_ms, bsl_window, z_window, eps=0, fill=numpy.nan)
z scores data the psth data
Parameters
- time_bin_msUnion[list[float], float]
The time bin desired for generating z scores (larger bins lead to smoother data). Either a single float applied to all stim or a list with a value for each stimulus
- bsl_windowUnion[list, list[list]]
The baseline window for finding the baseline mean and std firing rate. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- z_windowUnion[list, list[list]],
The event window for finding the z scores/time_bin. Either a single sequence of (start, end) in relation to stim onset at 0 applied for all stim. Or a list of lists where each stimulus has its own (start, end)
- eps: float, default: 0
Value to prevent nans from occurring during z-scoring
- spikeanalysis.kolmo_smir_stats(distribution_container: Union[dict, list], datatype: str) Union[dict, numpy.ndarray]
Function to calculate the Kolmogorov-Smirnov for various neuronal metrics
Parameters
- distribution_container: Union[dict, list]
Either a dictionary containing the stimulus key with the distributions to test as values or a list with two distributions to evaluate
- type: str
If using SpikeAnalysis dicts indicate whether isi, or latency
Returns
- ks_values: Union[dict, np.ndarray]
Returns a dict of np.ndarrays of pvalues for null of same distribution or an np.ndarray of the pvalues
- spikeanalysis.prevalence_counts(responsive_neurons: dict | str | 'Path', stim: list[str] | None = None, trial_index: dict | None = None, all_trials: bool = False, exclusive_list: list | None = None, inclusive_list: list | None = None, by_trialgroup: bool = False, cross_stim: bool = False, by_neuron: bool = False) dict
Function for counting number of neurons with specific response properties for each stimulus
Parameters
- responsive_neurons: dict | str | Path
Either a dictionary to assess with format of {stim: {response:array[bool]}} or the path given as str of Path to the json containing the same structure
- stim: list[str] | None, defualt: None
If only wanting to analyze a single stim or group of stim give as a list None means analyze all stim
- trial_index: dict | None, default: None
- A dict containing the {stim: indices | all | any}
if indices can be given as array of [start, stop] or as the indicies to use, eg. 1, 4,6
if all it will require all trial groups for a stim to be positive
if any it will require at least one trial group of a stim to be positive
- all_trials: bool, default False
Sets the trial_index to ‘all’ if true or ‘any’ if false if trial_index is None If trial_index give whether any or all of the given trial indices must be positive
- exclusive_list: list | None, default: None
The list of stimuli which are assessed in order. If given a neuron can only be in one of the categories
- inclusive_list: list | None, deafult: None
This allows a neuron to be this category even if exclusive_list is provided
- by_trialgroup: bool, default: False
If True returns the counts on a per trial group basis rather than as a total basis
- cross_stim: bool, deafult: False
If True returns counts based on ‘all’ or ‘any’ counts (any response type) for all stimuli in stim
Returns
- prevalence_dict: dict
Dict of prevalence counts with each key being a stim and the values being a ‘labels’ of response types ‘counts’ the prevalence counts If cross_stim true a dict with keys of ‘Total Neurons’, ‘All Stim Neurons’, and ‘Any Stim Neurons’ with the associated counts