spiketrain.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. from scipy import signal
  2. from scipy.interpolate import interp1d
  3. import numpy as np
  4. def instantaneous_rate(spiketrain, time_bins, bin_size=10, k_width=70):
  5. """
  6. spiketrain - an array of spike times in seconds
  7. time_bins - an array of times to have instantaneous rate for
  8. """
  9. # add boundaries to match session length
  10. times = np.concatenate([np.array([0]), spiketrain, np.array([time_bins[-1]])])
  11. # histogram of spike times
  12. spikes_count, _ = np.histogram(times, bins=int(len(time_bins)/bin_size))
  13. # convolve with gaussian kernel for smoothing
  14. kernel = signal.gaussian(k_width, std=(k_width) / 7.2)
  15. i_rate = np.convolve(spikes_count/(1.0/bin_size), kernel, 'same') / kernel.sum()
  16. # interpolate to match experimental timeline
  17. lin = interp1d(np.linspace(0, time_bins[-1], len(i_rate)), i_rate)
  18. return lin(time_bins)
  19. def spike_idxs(spiketrain, time_bins):
  20. """
  21. spiketrain - an array of spike times in seconds
  22. time_bins - an array of times to have spike indices to
  23. """
  24. s_rate_tl = round(1.0 / np.diff(time_bins).mean())
  25. spiking_idxs = spiketrain * s_rate_tl
  26. spiking_idxs = spiking_idxs[spiking_idxs < len(time_bins)]
  27. return spiking_idxs.astype(np.int32)