API reference¶
fitting module¶
Set of function to fit a raw data.
-
spikelib.fitting.fit_temp_sta(temporal_sta, time, fit_time, tau1=None, tau2=None, amp1=None, amp2=None, min_time=None, max_time=None, min_amp=-1, max_amp=1, max_n=20)[source]¶ Fit the temporal integration of the sta.
Use the difference of two cascades of low-pass filters to fit the raw temporal integration of STA. It uses the time before of the spike to compute the fitting.
Parameters: - temporal_sta (ndarray) – array with the raw temporal integration of the sta.
- time (ndarray) – array with the time of the raw temporal integration.
- fit_time (ndarray) – array with the time of fitting curve.
- tau1 (float default:None) – estimated time for positive peak of temporal integration
- tau2 (float default:None) – estimated time for negative peak of temporal integration
- amp1 (float default:None) – estimated amplitude for positive peak of temporal integration
- amp2 (float default:None) – estimated amplitude for negative peak of temporal integration
- min_time (float default:None) – minimum time to fit tau1 or tau2
- max_time (float default:None) – maximum time to fit tau1 or tau2
- min_amp (float default:-1) – minimum amplitude to fit amp1 or amp2
- max_amp (float default:1) – minimum amplitude to fit amp1 or amp2
- max_n= (float default:20) – maximum order of a model to fit
Returns: - fit_parameters (lmfit.Params.params) – parameters of the fitting for two_cascades model
- fit_temp (ndarray) – array with the values of the fitting using fit_time
-
spikelib.fitting.gaussian2d(xy, amp, x0, y0, sigma_x, sigma_y, theta, offset, revel=True)[source]¶ Make a two dimentional gaussian array.
Parameters: - xy (tuple (x, y)) – a meshgrid matrix of x and y axis.
- amplitude (float) – maximum amplitude of gaussian function
- x0 (float) – value where gaussian function has maximum value on x axis.
- y0 (float) – value where gaussian function has maximum value on y axis.
- sigma_x (float) – Standard deviation on x axis
- sigma_y (float) – Standard deviation on y axis
- theta (float) – rotation on x axis counterclockwise, in [radians]
- offset (flaot) – offset value for every point in array.
- revel (bool) – If revel is True, array is trnsformed to a vector.
Returns: Return type: Array o vector with the values od a 2 dimentional gaussian function.
Examples
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> from spikelib.fitting import gaussian2d
>>> y_size, x_size = (35, 30) >>> xy = np.meshgrid(np.linspace(0, x_size - 1, x_size), np.linspace(0, y_size - 1, y_size),) >>> arr = gaussian2d(xy=xy, amp=10, x0=12, y0=22, sigma_x=1.5, sigma_y=3.5, theta=np.pi/4, offset=0) >>> plt.pcolor(arr.reshape(y_size, x_size)) >>> plt.show()
-
spikelib.fitting.two_cascades(params, time)[source]¶ Model for temporal integration of sta.
This function return the model of the difference of two cascades of low-pass filters for temporal integration of spike triggered average (sta). It was propouse by Chichilnisky and Kalmar in ‘Functional Asymmetries In ON and OFF Ganglion Cells Of Primate Retina’.
function
Parameters: - params (dict or lmfit.Params.params) – The dictionary has 5 element for each parameter of model, ‘amp1’, ‘amp2’, ‘tau1’, ‘tau2’, ‘n’
- time (ndarray) – Array with the time to compute the model.
Returns: model – return values of the function for each element in time array
Return type: ndarray
io module¶
Set of tools to manipulate input and output files.
-
spikelib.io.load_matstim(filepath, matvar='stim')[source]¶ Get checkerboard stim from .mat file.
Read checkerboard stimulus generate by matlab and transpose dimesion to make compatible with numpy convencion of multidimentional array. The stimulus must have 4 dimension, nframe, yblock, xbock, nchannels.
Parameters: - filepath (str) – relative or full path of matlab file.
- var (str default: 'stim') – name of stim variable in mat file
Returns: stim – 4D array stimulus with the Numpy convention for dimensions (frame,y,x,channel).
Return type: ndarray
Notes
scipy.io.loadmat read matfile in mantain the matlab axis order to access array, ej. shape (y,x,channel,frame) = (35,35,3,72000) and python should be (frame,y,x,channel) = (72000,35,35,3), for this reason the output file keep python format. https://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/ http://scikit-image.org/docs/dev/user_guide/numpy_images.html
-
spikelib.io.load_spk_hdf5(filepath, group, datasets=None)[source]¶ Get spiketimes from hdf5 file.
Read HDF5 file and get all spike inside a group
Parameters: - filepath (str) – relative or full path of hdf5 file.
- group (str) – name of the group where timestams are
- datasets (list) – list of a specifict name of datasets in the group
Returns: spks – dictionary with timestams
Return type: dic
-
spikelib.io.load_stim(filepath, normed=True, channel='g', dataset='checkerboard')[source]¶ Get checkerboard stim from hdf5 file.
Read checkerboard stimulus from hdf5 file. It file was obtained from load_matstim() function and sava to a hdf5 file. The stimulus must has 4 dimension, nframe, yblock, xbock, nchannels.
Parameters: - filepath (str) – relative or full path of hdf5 file.
- normed (bool default: True) – Normalize stimulus between -1 and 1.
- channel ({'r', 'g', 'b'}) – stimulus has 3 channels, ‘r’, ‘g’ and ‘b’. Set one of these to retrive stim intensity.
- dataset (str default: 'checkerboard') – name of stim dataset in hdf5 file
Returns: stim – 3D array stimulus with the Numpy convention for dimensions.
Return type: ndarray
-
spikelib.io.load_stim_multi(filepath, normed=True, channel='g', dataset='checkerboard')[source]¶ Get checkerboard stim from hdf5 file to run multiprocessing sta.
Read checkerboard stimulus generate by matlab and transpose dimesion to make compatible with numpy convencion of multidimentional array. The stimulus must have 4 dimension, nframe, yblock, xbock, nchannels.
Parameters: - filepath (str) – relative or full path of hdf5 file.
- normed (bool default: True) – Normalize stimulus between -1 and 1.
- channel ({'r', 'g', 'b'}) – stimulus has 3 channels, ‘r’, ‘g’ and ‘b’. Set one of these to retrive stim intensity.
- dataset (str default: 'checkerboard') – name of stim dataset in hdf5 file
Returns: - stim (RawArray) – 3D array stimulus with the Numpy convention for dimensions.
- stim_shape (tuple)
models module¶
Set of lineal and no lineal neuron model.
For example Spike Triggered Average (STA) is a algorithm to compute a lineal filter to estimate receptive field of a cell.
-
spikelib.models.multi_sta(spiketimes, stim_time, nsamples_before=30, nsamples_after=0)[source]¶ Compute the Spike Triggered Average for a cell.
Parameters: - spiketimes (tuple) – tuple(name, spiketimes) to compute STA
- stim_time (array_like) – array with start time of each frame of stim
- 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: - unit_name (str) – name of the unit
- sta_array (array_like) – STA array
-
spikelib.models.run_multi_sta(stim_path, stim_time, spiketimes, nsamples_before=30, nsamples_after=0, normed_stim=True, channel_stim='g')[source]¶ Run sta in multiprocessing.
Parameters: - stim_path (str) – file of the stim
- stim_time (array_like) – times of start and end of stim
- spiketimes (dict) – spiketimes to compute sta
Returns: stats – return a list of tuple with unit_name and sta_array
Return type: list of tuple
-
spikelib.models.sta(stim, stim_time, spikes, nsamples_before=30, nsamples_after=0)[source]¶ Compute a spike-triggered average.
Parameters: - stim (array_like) – A spatiotemporal or temporal stimulus array, where time is the first dimension.
- stim_time (array_like) – The time array corresponding to the start of each frame in the stimulus.
- spikes (array_like) – A list or array of spike times
- nsamples_before (int) – Number of samples to include in the STA before the spike, defaults: 30.
- nsamples_after (int) – Number of samples to include in the STA after the spike, efaults: 0
Returns: sta – The spatiotemporal spike-triggered average.
Return type: array_like
References
A simple white noise analysis of neuronal light responses. E J Chichilnisky
-
spikelib.models.ste(stim, stim_time, spikes, nsamples_before=30, nsamples_after=0)[source]¶ Get all windows of stimulis triggered by a spike.
This function create a iterator to get a set of stimulus for a spike.
Parameters: - time_stim (array_like) – The time array corresponding to the start of each frame in the stimulus.
- stimulus (array_like) – A spatiotemporal or temporal stimulus array, where time is the first dimension.
- spikes (array_like) – A list or ndarray of spike times.
- nsamples_before (int) – Number of samples to include in the STE before the spike, defaults: 30.
- nsamples_after (int) – Number of samples to include in the STE after the spike, defaults: 0.
Returns: ste – A generator that yields samples from the spike-triggered ensemble.
Return type: generator
Notes
The spike-triggered 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).
preprocessing module¶
spiketools module¶
Set of functions to work with spike times.
-
spikelib.spiketools.bias_index(fr_max_on, fr_max_off, thr=0.65)[source]¶ Get the bias index from a On Off response.
The bias index compare the response to 2 differente stimuli, ON and OFF, and classify between, ON, OFF and ONOFF response. .. math:: bias_index = \frac{ON_{max}-OFF_{max}}{ON_{max}+OFF_{max}}
Parameters: - fr_max_on (float) – firing rate maximum for On response
- fr_max_off (float) – firing rate maximum for Off response
- thr (float) – threshold to split On, Off and On-Off groups
Returns: bias_index (float) – number between -1 and 1.
response_type (int) –
- clasification for type of response
0: null response 1: On response 2: Off response 3: On-Off response
See also
-
spikelib.spiketools.chunk_spikes(spikes, start, end)[source]¶ Get a subset of spike between start and end time.
Parameters: - spikes (array_like) – array with timestams of a cell
- start (float) – time of start the chunk
- end (float) – time of end the chunk
Returns: chunk – subset of spikes
Return type: array_like
See also
-
spikelib.spiketools.decay_time(response, time, peaktime, max_resp, decrease_factor=2.718281828459045)[source]¶ Get the time of the response dalay to dacay.
Dacay time is the time that the response take to dacay $n$ factor to the max response.
Parameters: - response (array_like) – psth or estimated firingrate
- time (array_like) – time of response
- peaktime (float) – time where is the max response
- max_resp (int) – value of the max response
- decrease_factor (float) – number of time that maximum response should dacay to get decay_time
Returns: resp_index – value between 0 to 1, where 0 mean that the response don’t change to the stimulus and 1 mean the previous response was 0 and response was max.
Return type: float
See also
-
spikelib.spiketools.est_pdf(trails, time, bandwidth=0.02, norm_factor=1)[source]¶ Estimate the probability density function from spike.
This function estimate the pdf of a cell to get a instantaneous firing rates.
Parameters: - spikes (list of array_like) – List with all spike times in each trial
- time (array_like) – Array of time points where pdf will be estimate.
Returns: estimated pdf from trails
Return type: array_like
-
spikelib.spiketools.flatten_trials(trials)[source]¶ Put spike times from different trial in a 1D array.
Parameters: trials (list of array_like) – list with all spike in each trial Returns: 1D array with all spike together Return type: array_like See also
-
spikelib.spiketools.get_features_flash(response, time_resp, bound, resp_thr=0.3, bias_thr=0.65, ri_thr=0.3, fpeak_thr=0.3, fpeak_min_dist=10, ri_span=0.1, sust_time=0.4, decrease_factor=2.718281828459045)[source]¶ Get temporal characteristic of flash response.
Parameters: - response (array_like) – psth or estimated firingrate
- array (time_resp,) – time of response in seg
- bound (tuple) – (start_time_on, end_time_on, start_time_off, end_time_off)
- resp_thr (float default=0.3) – threshold to define if response is valid
- bias_thr (float default=0.65) – threshold for bias index
- ri_thr (float default=0.3) – threshold for response index
- fpeak_thr (float default=0.3) – threshold for find peak response
- fpeak_min_dist (int default=10) – number of point minimum to detect peak response
- ri_span=0.1 (float default=0.1) – windows time to compute response index in seg
- sust_time (float default=0.4) – windows time to compute sutained index in seg
- decrease_factor (float default=np.e) – feaactor to get decrease time
Returns: - flash_type (int) – Flash clasification, 0, 1, 2 or 3 that represent Null, ON, OFF and ONOFF.
- flash_char (array_like) – Array with the follow paramiters: [latency_on, latency_off, bias_idx, decay_on, decay_off, resp_index_on, resp_index_off, sust_index_on, sust_index_off, fr_max_on, fr_max_off]
-
spikelib.spiketools.get_trials(spikes, start_trials, end_trials, offset=0)[source]¶ Get a list of spiketime for each trails.
Search spike times in set of period of time(s) defined in start_trials and end_trails and return a list of spiketimes for each trails and set the start time to 0 for each trail.
Parameters: - spikes (array_like) – Array of all spike times.
- start_trials (array_like) – Set of start time for each trail.
- end_trials (array_like) – Set of end time for each trail.
- offset (float, optional) – offset allow move the reference of start time, default is 0.
Returns: List of array of all spikes for each trial.
Return type: list
See also
-
spikelib.spiketools.response_index(response, prev_response, ri_span, max_resp=None)[source]¶ Get the response index.
The response index compare the response to a stimulus against previous response to the stimulus. It measure allow cuantify how much to change the response to a stimulus. .. math:: resp_index = frac{resp_{max}-avg_{prev_resp}}{resp_{max}+avg_{prev_resp}}
Parameters: - response (array_like) – response for analysis
- prev_response (array_like) – previous response for analysis
- ri_span (int) – number of de points to analize in response and prev_resp
- max_resp (float) – peak of response
Returns: resp_index – value between 0 to 1, where 0 mean that the response don’t change to the stimulus and 1 mean the previous response was 0 and response was max.
Return type: float
See also
-
spikelib.spiketools.sustain_index(response)[source]¶ Get the sustained index.
Sustained Index (SI) measure if the response is transient or sustained, where 0 is completly sustained and 1 is completly transient.
Parameters: response (array_like) – PSTH or estimated response array of a cell in a specific estimulation. Returns: sust_index – index between 0 and 1. Return type: float See also
stimtools module¶
Tools to manipulate stumulus.
-
spikelib.stimtools.correct_checkerboard(stimpath, syncpath, repeatedpath, outputpath, matvar='stim', output_group='/', output_dataset='checkerboard')[source]¶ Create a new stimulus with all repeated frames.
Take a checkerboar stimulus and add all repeated frame found in a experiment and create a new stim file.
Parameters: - stimpath (str) – path to original stim file (.mat).
- syncpath (str) – path to the syncronization file with start and end time for checkerboard (txt format).
- repeatedpath (str) – path to file with all repeated times of experiment (txt format).
- outputpath (str) – path to save stim to hdf5 file.
Notes
scipy.io.loadmat read matfile in mantain the matlab axis order to access array, ej. shape (y,x,channel,frame) = (35,35,3,72000) and python should be (frame,y,x,channel) = (72000,35,35,3), for this reason the output file keep python format. https://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/ http://scikit-image.org/docs/dev/user_guide/numpy_images.html
utils module¶
spikelib utilities.
-
spikelib.utils.check_directory(inputfolder)[source]¶ Check if exist the directory, else make a new folder.
If the directory doesn’t exist then this directory is create.
Parameters: inputfolder (str) – path of directory Examples
>>> checkDirectory('../myFolder')
-
spikelib.utils.check_groups(fdata, groups)[source]¶ Review if a list of groups exist in a hdf file.
Parameters: - fdata (object) – h5py object to check if a list of group exist
- groups (list of str) – list of group name to check
-
spikelib.utils.clean_directory(inputfolder)[source]¶ Delete all files and drectories in input directory.
If the directory doesn’t exist then this directory is create.
Parameters: inputfolder (str) – path of directory Examples
>>> from mealib.utils import clean_directory >>> clean_directory('../myinputfolder')
-
spikelib.utils.datasets_to_array(fgroup)[source]¶ Transform all datasets in a group to an array.
Parameters: fgroup (object) – h5py object to retrive all dataset inside of it Returns: - ds_array (array_like) – NxM array, where N if the number of dataset and M is the lenght of each dataset
- names (list of str) – list of names for each row in ds_array
Examples
>>> with h5py.File(fdata) as data: >>> array, keys = datasets_to_array(data[group]) >>> array.shape (889,7)
visualizations module¶
Set of tools for visualization.
-
spikelib.visualizations.plot_sta(sta_array, name='')[source]¶ Get a plot with all frame of the STA.
Parameters: - sta_array (array_like) – STA array
- name (str) – name of unit
Returns: - fig (figure object) – current figure of the plot
- ax (axis object) – axis with psth
-
spikelib.visualizations.psth(spks, ax=None, **kwargs)[source]¶ Draw psth for spikes.
Parameters: - spks (array_like) – 1D array with spiketimes for each trial
- **kwargs – kwargs of axis of matplotlib
Returns: - fig (figure object) – current figure of the plot
- ax (axis object) – axis with psth
-
spikelib.visualizations.raster(trials, ax=None, **kwargs)[source]¶ Draw raster for a cell.
Parameters: - trials (list of array_like or numpy obj) – list with spiketimes for each trial
- **kwargs – kwargs of axis of matplotlib
Returns: - fig (figure object) – current figure of the plot
- ax (axis object) – axis with raster
Module contents¶
spikelib.
A Python package to analyse neuronal activity from spiketimes
Modules¶
fitting - Models of neuronal behaviour. io - Tools for manupulate Input/Output files. models - Methods of linear and no lineal filters preprocessing - Classes to processes syncronization times. spiketools - Tools for manipulating spike trains. stimtools - Tools for manipulating stimuli. utils - General functions for check folder, groups, etc. visualizations - Tools for plotting, psth, raster, receptive fields, etc.
For more information, see the accompanying README.md