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)¶ 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)¶ 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)¶ 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
-
spikelib.fitting.two_cascades_min(params, x, raw_data)¶ Difference of two cascades to minimize.
io module¶
Set of tools to manipulate input and output files.
-
spikelib.io.load_matstim(filepath, matvar='stim')¶ 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)¶ 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_spk_txt()¶
-
spikelib.io.load_stim(filepath, normed=True, channel='g', dataset='checkerboard')¶ 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')¶ 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.init_multi_sta(stim, stim_shape)¶ Set stim array to a global variable.
-
spikelib.models.multi_sta(spiketimes, stim_time, nsamples_before=30, nsamples_after=0)¶ 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')¶ 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)¶ 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)¶ 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¶
Implementing of classes and function to prepare raw data.
-
class
spikelib.preprocessing.Sync(exp_name, real_fps=59.7596)¶ Get the sinchronization times from a record.
Class provide a complete enviroment to explore, cumpute and recovery sincronization signal in a record using a SamplingInteface script. SamplingInteface scripts send images to the projector and it use someone of RGB channel (in a VGA cable) to target the exact time when a frame was showed. That channel use different intensity levels to mark different frames. The following image show a simple example how to work it. https://tinyurl.com/ydxlvds9
Parameters: - exp_name (str) – The name of the experiment
- real_fps (float) – The real refresh rate used by the projector. Please check log file to get this number.
-
data¶ Raw data from mcd file.
Type: neuroshare.File object
-
event_list¶ Table with all description about sync events.
Type: pandas.DataFrame
-
exp_name¶ Name of experiment
Type: str
-
real_fps¶ Real frame per second of monitor. Check log file of SamplingIntereface2
Type: float
-
repeted_start_frames¶ Array with all repeted frames.
Type: array_like
-
sample_rate¶ Sample rate of record (from mcd file)
Type: int
-
start_end_frame¶ Array with all frames detected on sync
-
total_duration¶ Total duration of record.
Type: float
-
add_repeated()¶ Add repeated frames to event list.
For each event in event_list attribute add the repeated frame points. This point is the right frame showed and next frame is the repeated frame.
-
analyzer(channel)¶ Get the sinchronization times from MCD file.
Recovery the exact time when a frame was showed on the screen using one of VGA channels as trigger. This channel use different intensity levels to mark when a frame started. The following image show a simple example how to make it. https://tinyurl.com/y84n4xjh Update the following attibutes, start_end_frames, repeted_frames, total_duration, sample_rate.
Parameters: channel (int) – channel number where is the analog signal in .mcd file. Use showEntities() to check number. Todo
Detection method should be change for one more robust technique because now use search point to point where are the end of pulse. Try using a find_peak algorithm.
-
close_file()¶ Close mcd file.
-
create_events()¶ Create a list of events of sincronization.
Use start time from each frame to detect a sequence of images (event) and create a dataframe with all event. This dataframe has start, end, duration, number of frame and time to next event. This image show a example of 2 events. https://tinyurl.com/ydxlvds9
-
create_separated_sync(output_folder)¶ Split syncronization times for each event.
Take start_end times of syncronization and split it in individual files.
Parameters: output_folder (str) – directory path to save files.
-
get_raw_data(channel, start=0, windows=-1)¶ Load all raw data in a specific channel.
Parameters: - channel (int) – number of channel to get raw data in mcd file.
- start (int) – Start point to get data.
- windows (int) – Number of point (window) after start point to get data.
Returns: - entity_data (array) – Record values in a channel [samples].
- analog_time (array) – Time of Record values in a channel [s].
- dur (int) – Duration of record in a channel [samples]
Examples
>>> sync = Sync('name') >>> sync.read_mcd(mcd_path) >>> data, dur = sync.get_raw_data(channel) >>> sync.close_file()
-
get_raw_samples(channel, start=0, windows=-1)¶ Load all raw data in a specific channel.
Parameters: - channel (int) – number of channel to get raw data in mcd file.
- start (int) – Start point to get data.
- windows (int) – Number of point (window) after start point to get data.
Returns: - entity_data (array) – Record values in a channel [samples].
- dur (int) – Duration of record in a channel [samples]
Examples
>>> sync = Sync('name') >>> sync.read_mcd(mcd_path) >>> data, dur = sync.get_raw_samples(channel) >>> sync.close_file()
-
load_analyzed(src_folder)¶ Load output files from Analizer mathod.
Load the result of analysed mcd file with analyzer method and saved previously. Those file have start_end points, repeated frame points and duration of analyzed experiment.
Parameters: src_folder (str) – path of directory with result files.
-
load_events(source_file, **kwargs)¶ Read csv file with event for a experiment.
Update event_list atribute from csv file as dataframe.
Parameters: source_file (str) – path csv file with list of event for a experiment.
-
plot_window(channel, start_point, window)¶ Plot analog signal of syncronization in a specific time.
Take a window time of the analog signal in MCD file and plot it to show the raw values.
Parameters: - channel (int) – number of channel to plot
- start_point (int) – start point to plot
- window (int) – number of points to plot
-
read_mcd(mcd_file)¶ Load mcd file to be analyze.
Parameters: mcd_file (str) – Path to mcd file
-
save_analyzed(output_folder, stype='txt')¶ Save attributes generated by analyzer method.
Save start_end frames, repeated frames, duration and sample rate of a record generated by analyzer method.
Parameters: - output_folder (str) – directory path to save files.
- stype (str) – type of output file. text file or hdf5 (Default txt)
-
save_events(output_folder, **kwargs)¶ Save event list in a csv file.
Take the event list dataframe and save it as csv.
Parameters: output_folder (str) – directory path to save files.
-
show_entities()¶ Show all channel in mcd file.
-
class
spikelib.preprocessing.SyncDigital(exp_name, real_fps=59.7596)¶ Bases:
spikelib.preprocessing.SyncGet the sinchronization times from a digital record.
Class provide a complete enviroment to explore, cumpute and recovery sincronization signal in a digital record.
spiketools module¶
Set of functions to work with spike times.
-
spikelib.spiketools.bias_index(fr_max_on, fr_max_off, thr=0.65)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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')¶ 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)¶ 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)¶ 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)¶ 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)¶ 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='')¶ 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)¶ 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)¶ 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