add some util functions

This commit is contained in:
Jan Grewe 2020-09-16 16:54:40 +02:00
parent 90d8c9d7a3
commit 2212e435c1

36
util.py Normal file
View File

@ -0,0 +1,36 @@
import numpy as np
def gaussKernel(sigma, dt):
""" Creates a Gaussian kernel with a given standard deviation and an integral of 1.
Args:
sigma (float): The standard deviation of the kernel.
dt (float): The temporal resolution of the kernel, given in seconds.
Returns:
numpy.ndarray : the kernel in the range -4 to +4 sigma
"""
x = np.arange(-4. * sigma, 4. * sigma, dt)
y = np.exp(-0.5 * (x / sigma) ** 2) / np.sqrt(2. * np.pi) / sigma
return y
def firing_rate(spikes, duration, sigma=0.005, dt=1./20000.):
"""Convert spike times to a firing rate using the kernel convolution with a Gaussian kernel
Args:
spikes (iterable): list of spike times, times should be in seconds
duration (float): duration of the trial in seconds
sigma (float, optional): standard deviation of the Gaussian kernel. Defaults to 0.005s.
dt (float, optional): The stepsize of the trace. Defaults to 1./20000.s.
Returns:
np.ndarray: the firing rate
"""
binary = np.zeros(int(np.round(duration/dt)))
indices = np.asarray(np.round(spikes / dt), dtype=np.int)
binary[indices[indices < len(binary)]] = 1
kernel = gaussKernel(sigma, dt)
rate = np.convolve(kernel, binary, mode="same")
return rate