def test_trim_as_convolve_mode(self): cutoff = 5 sampling_period = 0.01 * pq.s t_spikes = np.linspace(-cutoff, cutoff, num=(2 * cutoff + 1)) * pq.s spiketrain = neo.SpikeTrain(t_spikes, t_start=t_spikes[0], t_stop=t_spikes[-1]) kernel = kernels.RectangularKernel(sigma=1 * pq.s) assert cutoff > kernel.min_cutoff, "Choose larger cutoff" kernel_types = tuple(kern_cls for kern_cls in kernels.__dict__.values() if isinstance(kern_cls, type) and issubclass(kern_cls, kernels.SymmetricKernel) and kern_cls is not kernels.SymmetricKernel) kernels_symmetric = [ kern_cls(sigma=1 * pq.s, invert=False) for kern_cls in kernel_types ] for kernel in kernels_symmetric: for trim in (False, True): rate_centered = statistics.instantaneous_rate( spiketrain, sampling_period=sampling_period, kernel=kernel, cutoff=cutoff, trim=trim) rate_convolve = statistics.instantaneous_rate( spiketrain, sampling_period=sampling_period, kernel=kernel, cutoff=cutoff, trim=trim, center_kernel=False) assert_array_almost_equal(rate_centered, rate_convolve)
def test_instantaneous_rate_regression_245(self): # This test makes sure that the correct kernel width is chosen when # selecting 'auto' as kernel spiketrain = neo.SpikeTrain( range(1, 30) * pq.ms, t_start=0*pq.ms, t_stop=30*pq.ms) # This is the correct procedure to attain the kernel: first, the result # of sskernel retrieves the kernel bandwidth of an optimal Gaussian # kernel in terms of its standard deviation sigma, then uses this value # directly in the function for creating the Gaussian kernel kernel_width_sigma = es.sskernel( spiketrain.magnitude, tin=None, bootstrap=False)['optw'] kernel = kernels.GaussianKernel(kernel_width_sigma * spiketrain.units) result_target = es.instantaneous_rate( spiketrain, 10*pq.ms, kernel=kernel) # Here, we check if the 'auto' argument leads to the same operation. In # the regression, it was incorrectly assumed that the sskernel() # function returns the actual bandwidth of the kernel, which is defined # as approximately bandwidth = sigma * 5.5 = sigma * (2 * 2.75). # factor 2.0 connects kernel width with its half width, # factor 2.7 connects half width of Gaussian distribution with # 99% probability mass with its standard deviation. result_automatic = es.instantaneous_rate( spiketrain, 10*pq.ms, kernel='auto') assert_array_almost_equal(result_target, result_automatic)
def test_instantaneous_rate_spiketrainlist(self): np.random.seed(19) duration_effective = self.st_dur - 2 * self.st_margin st_num_spikes = np.random.poisson(self.st_rate * duration_effective) spike_train2 = sorted( np.random.rand(st_num_spikes) * duration_effective + self.st_margin) spike_train2 = neo.SpikeTrain(spike_train2 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s) st_rate_1 = statistics.instantaneous_rate(self.spike_train, sampling_period=0.01 * pq.s, kernel=self.kernel) st_rate_2 = statistics.instantaneous_rate(spike_train2, sampling_period=0.01 * pq.s, kernel=self.kernel) combined_rate = statistics.instantaneous_rate( [self.spike_train, spike_train2], sampling_period=0.01 * pq.s, kernel=self.kernel) summed_rate = st_rate_1 + st_rate_2 # equivalent for identical kernels # 'time_vector.dtype' in instantaneous_rate() is changed from float64 # to float32 which results in 3e-6 abs difference assert_array_almost_equal(combined_rate.magnitude, summed_rate.magnitude, decimal=5)
def test_rate_estimation_consistency(self): """ Test, whether the integral of the rate estimation curve is (almost) equal to the number of spikes of the spike train. """ kernel_types = [ obj for obj in kernels.__dict__.values() if isinstance(obj, type) and issubclass(obj, kernels.Kernel) and hasattr(obj, "_evaluate") and obj is not kernels.Kernel and obj is not kernels.SymmetricKernel ] kernel_list = [ kernel_type(sigma=0.5 * pq.s, invert=False) for kernel_type in kernel_types ] kernel_resolution = 0.01 * pq.s for kernel in kernel_list: rate_estimate_a0 = es.instantaneous_rate( self.spike_train, sampling_period=kernel_resolution, kernel='auto', t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False) rate_estimate0 = es.instantaneous_rate( self.spike_train, sampling_period=kernel_resolution, kernel=kernel) rate_estimate1 = es.instantaneous_rate( self.spike_train, sampling_period=kernel_resolution, kernel=kernel, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False) rate_estimate2 = es.instantaneous_rate( self.spike_train, sampling_period=kernel_resolution, kernel=kernel, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=True) ### test consistency rate_estimate_list = [ rate_estimate0, rate_estimate1, rate_estimate2, rate_estimate_a0 ] for rate_estimate in rate_estimate_list: num_spikes = len(self.spike_train) auc = spint.cumtrapz( y=rate_estimate.magnitude[:, 0], x=rate_estimate.times.rescale('s').magnitude)[-1] self.assertAlmostEqual(num_spikes, auc, delta=0.05 * num_spikes)
def test_rate_estimation_consistency(self): """ Test, whether the integral of the rate estimation curve is (almost) equal to the number of spikes of the spike train. """ kernel_types = [obj for obj in kernels.__dict__.values() if isinstance(obj, type) and issubclass(obj, kernels.Kernel) and hasattr(obj, "_evaluate") and obj is not kernels.Kernel and obj is not kernels.SymmetricKernel] kernel_list = [kernel_type(sigma=0.5*pq.s, invert=False) for kernel_type in kernel_types] kernel_resolution = 0.01*pq.s for kernel in kernel_list: rate_estimate_a0 = es.instantaneous_rate(self.spike_train, sampling_period=kernel_resolution, kernel='auto', t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False) rate_estimate0 = es.instantaneous_rate(self.spike_train, sampling_period=kernel_resolution, kernel=kernel) rate_estimate1 = es.instantaneous_rate(self.spike_train, sampling_period=kernel_resolution, kernel=kernel, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False) rate_estimate2 = es.instantaneous_rate(self.spike_train, sampling_period=kernel_resolution, kernel=kernel, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=True) ### test consistency rate_estimate_list = [rate_estimate0, rate_estimate1, rate_estimate2, rate_estimate_a0] for rate_estimate in rate_estimate_list: num_spikes = len(self.spike_train) auc = spint.cumtrapz(y=rate_estimate.magnitude[:, 0], x=rate_estimate.times.rescale('s').magnitude)[-1] self.assertAlmostEqual(num_spikes, auc, delta=0.05*num_spikes)
def test_spikes_on_edges(self): # this test demonstrates that the trimming (convolve valid mode) # removes the edge spikes, underestimating the true firing rate and # thus is not able to reconstruct the number of spikes in a # spiketrain (see test_rate_estimation_consistency) cutoff = 5 sampling_period = 0.01 * pq.s t_spikes = np.array([-cutoff, cutoff]) * pq.s spiketrain = neo.SpikeTrain(t_spikes, t_start=t_spikes[0], t_stop=t_spikes[-1]) kernel_types = tuple( kern_cls for kern_cls in kernels.__dict__.values() if isinstance(kern_cls, type) and issubclass( kern_cls, kernels.Kernel) and kern_cls is not kernels.Kernel and kern_cls is not kernels.SymmetricKernel) kernels_available = [ kern_cls(sigma=1 * pq.s, invert=False) for kern_cls in kernel_types ] for kernel in kernels_available: for center_kernel in (False, True): rate = statistics.instantaneous_rate( spiketrain, sampling_period=sampling_period, kernel=kernel, cutoff=cutoff, trim=True, center_kernel=center_kernel) assert_array_almost_equal(rate.magnitude, 0, decimal=3)
def test_small_kernel_sigma(self): # Test that the instantaneous rate is overestimated when # kernel.sigma << sampling_period and center_kernel is True. # The setup is set to match the issue 288. np.random.seed(9) sampling_period = 200 * pq.ms sigma = 5 * pq.ms rate_expected = 10 * pq.Hz spiketrain = homogeneous_poisson_process(rate_expected, t_start=0 * pq.s, t_stop=10 * pq.s) kernel_types = tuple( kern_cls for kern_cls in kernels.__dict__.values() if isinstance(kern_cls, type) and issubclass( kern_cls, kernels.Kernel) and kern_cls is not kernels.Kernel and kern_cls is not kernels.SymmetricKernel) for kern_cls, invert in itertools.product(kernel_types, (False, True)): kernel = kern_cls(sigma=sigma, invert=invert) with self.subTest(kernel=kernel): rate = statistics.instantaneous_rate( spiketrain, sampling_period=sampling_period, kernel=kernel, center_kernel=True) self.assertGreater(rate.mean(), rate_expected)
def __init__(self, name, kernel, spikes, step=10*ms, min_rate=0.01*Hz): """Create a Rate instance.""" # Create empty instance. self.name = name self.rates = None self.tvec = None self.kernel = kernel self.step = step # Calculate firing rates. with warnings.catch_warnings(): # Let's ignore warnings about negative firing rate values, # they are fixed below. warnings.simplefilter('ignore', UserWarning) rates = len(spikes) * [[]] for i, sp in enumerate(spikes): # Estimate firing rates. rts = instantaneous_rate(sp, step, kernel) rates[i] = pd.Series(np.array(rts)[:, 0], index=rts.times.rescale(ms)) # Stack rate vectors into dataframe, adding NaNs to samples missing # from any trials. rates = pd.concat(rates, axis=1).T # Zero out negative and tiny positive values. if min_rate is not None: rates[rates < float(min_rate)] = 0 # Store rate and time sample values. self.rates = rates self.tvec = np.array(rates.columns) * ms
def test_rate_estimation_consistency(self): """ Test, whether the integral of the rate estimation curve is (almost) equal to the number of spikes of the spike train. """ kernel_types = tuple( kern_cls for kern_cls in kernels.__dict__.values() if isinstance(kern_cls, type) and issubclass( kern_cls, kernels.Kernel) and kern_cls is not kernels.Kernel and kern_cls is not kernels.SymmetricKernel) kernels_available = [ kern_cls(sigma=0.5 * pq.s, invert=False) for kern_cls in kernel_types ] kernels_available.append('auto') kernel_resolution = 0.01 * pq.s for kernel in kernels_available: for center_kernel in (False, True): rate_estimate = statistics.instantaneous_rate( self.spike_train, sampling_period=kernel_resolution, kernel=kernel, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, center_kernel=center_kernel) num_spikes = len(self.spike_train) auc = spint.cumtrapz( y=rate_estimate.magnitude.squeeze(), x=rate_estimate.times.simplified.magnitude)[-1] self.assertAlmostEqual(num_spikes, auc, delta=0.01 * num_spikes)
def test_instantaneous_rate(self): st = self.spike_train sampling_period = 0.01 * pq.s inst_rate = es.instantaneous_rate(st, sampling_period, "TRI", 0.03 * pq.s) self.assertIsInstance(inst_rate, neo.core.AnalogSignalArray) self.assertEquals(inst_rate.sampling_period.simplified, sampling_period.simplified) self.assertEquals(inst_rate.simplified.units, pq.Hz) self.assertEquals(inst_rate.t_stop.simplified, st.t_stop.simplified) self.assertEquals(inst_rate.t_start.simplified, st.t_start.simplified)
def _get_rates(_spiketrains): kernel_sigma = kernel_width / 2. / np.sqrt(3.) kernel = kernels.RectangularKernel(sigma=kernel_sigma) rates = [statistics.instantaneous_rate( st, kernel=kernel, sampling_period=1 * pq.ms) for st in _spiketrains] return rates
def test_annotations(self): spiketrain = neo.SpikeTrain([1, 2], t_stop=2 * pq.s, units=pq.s) kernel = kernels.AlphaKernel(sigma=100 * pq.ms) rate = statistics.instantaneous_rate(spiketrain, sampling_period=10 * pq.ms, kernel=kernel) kernel_annotation = dict(type=type(kernel).__name__, sigma=str(kernel.sigma), invert=kernel.invert) self.assertIn('kernel', rate.annotations) self.assertEqual(rate.annotations['kernel'], kernel_annotation)
def test_instantaneous_rate(self): st = self.spike_train sampling_period = 0.01 * pq.s inst_rate = es.instantaneous_rate(st, sampling_period, 'TRI', 0.03 * pq.s) self.assertIsInstance(inst_rate, neo.core.AnalogSignalArray) self.assertEquals(inst_rate.sampling_period.simplified, sampling_period.simplified) self.assertEquals(inst_rate.simplified.units, pq.Hz) self.assertEquals(inst_rate.t_stop.simplified, st.t_stop.simplified) self.assertEquals(inst_rate.t_start.simplified, st.t_start.simplified)
def test_instantaneous_rate_spiketrainlist(self): st_num_spikes = np.random.poisson( self.st_rate*(self.st_dur-2*self.st_margin)) spike_train2 = np.random.rand( st_num_spikes) * (self.st_dur - 2 * self.st_margin) + self.st_margin spike_train2.sort() spike_train2 = neo.SpikeTrain(spike_train2 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s) st_rate_1 = es.instantaneous_rate(self.spike_train, sampling_period=0.01*pq.s, kernel=self.kernel) st_rate_2 = es.instantaneous_rate(spike_train2, sampling_period=0.01*pq.s, kernel=self.kernel) combined_rate = es.instantaneous_rate([self.spike_train, spike_train2], sampling_period=0.01*pq.s, kernel=self.kernel) summed_rate = st_rate_1 + st_rate_2 # equivalent for identical kernels for a, b in zip(combined_rate.magnitude, summed_rate.magnitude): self.assertAlmostEqual(a, b, delta=0.0001)
def test_instantaneous_rate_and_warnings(self): st = self.spike_train sampling_period = 0.01*pq.s with self.assertWarns(UserWarning): # Catches warning: The width of the kernel was adjusted to a # minimally allowed width. inst_rate = es.instantaneous_rate( st, sampling_period, self.kernel, cutoff=0) self.assertIsInstance(inst_rate, neo.core.AnalogSignal) self.assertEqual( inst_rate.sampling_period.simplified, sampling_period.simplified) self.assertEqual(inst_rate.simplified.units, pq.Hz) self.assertEqual(inst_rate.t_stop.simplified, st.t_stop.simplified) self.assertEqual(inst_rate.t_start.simplified, st.t_start.simplified)
def test_regression_288(self): np.random.seed(9) sampling_period = 200 * pq.ms spiketrain = homogeneous_poisson_process(10 * pq.Hz, t_start=0 * pq.s, t_stop=10 * pq.s) kernel = kernels.AlphaKernel(sigma=5 * pq.ms, invert=True) # check that instantaneous_rate "works" for kernels with small sigma # without triggering an incomprehensible error rate = statistics.instantaneous_rate(spiketrain, sampling_period=sampling_period, kernel=kernel) self.assertEqual(len(rate), (spiketrain.t_stop / sampling_period).simplified.item())
def get_rate_estimate(spike_times, kernel_width, start_time, train_duration, sampling_period): t_start = spike_times[0] if start_time is None else start_time t_stop = spike_times[ -1] if train_duration is None else t_start + train_duration train = SpikeTrain( spike_times[(spike_times > t_start) & (spike_times < t_stop)] * ms, t_start=t_start, t_stop=t_stop, ) kernel = GaussianKernel(sigma=kernel_width * ms) rate = spkstat.instantaneous_rate(train, kernel=kernel, sampling_period=sampling_period * ms) return np.array(rate)[:, 0]
def test_centered_at_origin(self): # Skip RectangularKernel because it doesn't have a strong peak. kernel_types = tuple( kern_cls for kern_cls in kernels.__dict__.values() if isinstance(kern_cls, type) and issubclass( kern_cls, kernels.SymmetricKernel) and kern_cls not in ( kernels.SymmetricKernel, kernels.RectangularKernel)) kernels_symmetric = [ kern_cls(sigma=50 * pq.ms, invert=False) for kern_cls in kernel_types ] # first part: a symmetric spiketrain with a symmetric kernel spiketrain = neo.SpikeTrain(np.array([-0.0001, 0, 0.0001]) * pq.s, t_start=-1, t_stop=1) for kernel in kernels_symmetric: rate = statistics.instantaneous_rate(spiketrain, sampling_period=20 * pq.ms, kernel=kernel) # the peak time must be centered at origin self.assertEqual(rate.times[np.argmax(rate)], 0) # second part: a single spike at t=0 periods = [2**c for c in range(-3, 6)] for period in periods: with self.subTest(period=period): spiketrain = neo.SpikeTrain(np.array([0]) * pq.s, t_start=-period * 10 * pq.ms, t_stop=period * 10 * pq.ms) for kernel in kernels_symmetric: rate = statistics.instantaneous_rate( spiketrain, sampling_period=period * pq.ms, kernel=kernel) self.assertEqual(rate.times[np.argmax(rate)], 0)
def test_instantaneous_rate_grows_with_sampling_period(self): np.random.seed(0) rate_expected = 10 * pq.Hz spiketrain = homogeneous_poisson_process(rate=rate_expected, t_stop=10 * pq.s) kernel = kernels.GaussianKernel(sigma=100 * pq.ms) rates_mean = [] for sampling_period in np.linspace(1, 1000, num=10) * pq.ms: with self.subTest(sampling_period=sampling_period): rate = statistics.instantaneous_rate( spiketrain, sampling_period=sampling_period, kernel=kernel) rates_mean.append(rate.mean()) # rate means are greater or equal the expected rate assert_array_less(rate_expected, rates_mean) # check sorted self.assertTrue(np.all(rates_mean[:-1] < rates_mean[1:]))
def test_regression_288(self): np.random.seed(9) sampling_period = 200 * pq.ms spiketrain = homogeneous_poisson_process(10 * pq.Hz, t_start=0 * pq.s, t_stop=10 * pq.s) kernel = kernels.AlphaKernel(sigma=5 * pq.ms, invert=True) rate = statistics.instantaneous_rate(spiketrain, sampling_period=sampling_period, kernel=kernel) self.assertEqual(len(rate), (spiketrain.t_stop / sampling_period).simplified.item()) # 3 Hz is not a target - it's meant to test the non-negativity of the # result rate; ideally, for smaller sampling rates, the integral # should match the num. of spikes in the spiketrain self.assertGreater(rate.mean(), 3 * pq.Hz)
def test_instantaneous_rate_and_warnings(self): st = self.spike_train sampling_period = 0.01*pq.s with warnings.catch_warnings(record=True) as w: inst_rate = es.instantaneous_rate( st, sampling_period, self.kernel, cutoff=0) self.assertEqual("The width of the kernel was adjusted to a minimally " "allowed width.", str(w[-2].message)) self.assertEqual("Instantaneous firing rate approximation contains " "negative values, possibly caused due to machine " "precision errors.", str(w[-1].message)) self.assertIsInstance(inst_rate, neo.core.AnalogSignal) self.assertEquals( inst_rate.sampling_period.simplified, sampling_period.simplified) self.assertEquals(inst_rate.simplified.units, pq.Hz) self.assertEquals(inst_rate.t_stop.simplified, st.t_stop.simplified) self.assertEquals(inst_rate.t_start.simplified, st.t_start.simplified)
def test_instantaneous_rate_and_warnings(self): st = self.spike_train sampling_period = 0.01*pq.s with warnings.catch_warnings(record=True) as w: inst_rate = es.instantaneous_rate( st, sampling_period, self.kernel, cutoff=0) self.assertEqual("The width of the kernel was adjusted to a minimally " "allowed width.", str(w[-2].message)) self.assertEqual("Instantaneous firing rate approximation contains " "negative values, possibly caused due to machine " "precision errors.", str(w[-1].message)) self.assertIsInstance(inst_rate, neo.core.AnalogSignalArray) self.assertEquals( inst_rate.sampling_period.simplified, sampling_period.simplified) self.assertEquals(inst_rate.simplified.units, pq.Hz) self.assertEquals(inst_rate.t_stop.simplified, st.t_stop.simplified) self.assertEquals(inst_rate.t_start.simplified, st.t_start.simplified)
def test_not_center_kernel(self): # issue 107 t_spike = 1 * pq.s st = neo.SpikeTrain([t_spike], t_start=0 * pq.s, t_stop=2 * pq.s, units=pq.s) kernel = kernels.AlphaKernel(200 * pq.ms) fs = 0.1 * pq.ms rate = statistics.instantaneous_rate(st, sampling_period=fs, kernel=kernel, center_kernel=False) rate_nonzero_index = np.nonzero(rate > 1e-6)[0] # where the mass is concentrated rate_mass = rate.times.rescale(t_spike.units)[rate_nonzero_index] all_after_response_onset = (rate_mass >= t_spike).all() self.assertTrue(all_after_response_onset)
def test_recovered_firing_rate_profile(self): np.random.seed(54) t_start = 0 * pq.s t_stop = 4 * np.round(np.pi, decimals=3) * pq.s # 2 full periods sampling_period = 0.001 * pq.s # an arbitrary rate profile profile = 0.5 * (1 + np.sin( np.arange(t_start.item(), t_stop.item(), sampling_period.item()))) time_generation = 0 n_trials = 200 rtol = 0.05 # 5% of deviation allowed kernel = kernels.RectangularKernel(sigma=0.25 * pq.s) for rate in (10 * pq.Hz, 100 * pq.Hz): rate_profile = neo.AnalogSignal(rate * profile, sampling_period=sampling_period) # the recovered firing rate profile should not depend on the # shape factor; here we test float and integer values of the shape # factor: the method supports float values that is not trivial # for inhomogeneous gamma process generation for shape_factor in (1, 2.5, 10.): spiketrains = \ [stgen.inhomogeneous_gamma_process( rate_profile, shape_factor=shape_factor) for _ in range(n_trials)] rate_recovered = instantaneous_rate( spiketrains, sampling_period=sampling_period, kernel=kernel, t_start=t_start, t_stop=t_stop, trim=True).sum(axis=1) / n_trials rate_recovered = rate_recovered.flatten().magnitude trim = (rate_profile.shape[0] - rate_recovered.shape[0]) // 2 rate_profile_valid = rate_profile.magnitude.squeeze() rate_profile_valid = rate_profile_valid[trim:-trim - 1] assert_allclose(rate_recovered, rate_profile_valid, rtol=0, atol=rtol * rate.item())
def convert_one_population_to_rates(self, recordings_index, trial_index, brain_area): path = self.all_data_path + '/' + self.selected_recordings[ recordings_index] trials = np.load(path + '/' + 'trials.intervals.npy') spike_times_lst = self.get_spikes_of_one_population( recordings_index, brain_area) rates_lst = [] spk_tr_lst = [] for spk_tms_one_neuron in spike_times_lst: spks_range = np.bitwise_and( spk_tms_one_neuron >= trials[trial_index][0], spk_tms_one_neuron <= trials[trial_index][1]) subset = spk_tms_one_neuron[spks_range] #Create elephant SpikeTrain object spk_tr = neo.SpikeTrain(subset * pq.s, t_start=trials[trial_index][0] * pq.s, t_stop=trials[trial_index][1] * pq.s) #plt.eventplot(spk_tr) #plt.show() kernel = kernels.GaussianKernel(sigma=0.1 * pq.s, invert=True) #sampling_rate the same as behavior r = instantaneous_rate(spk_tr, t_start=trials[trial_index][0] * pq.s, t_stop=trials[trial_index][1] * pq.s, sampling_period=0.02524578 * pq.s, kernel=kernel) #cutoff=5.0) binned_spk_tr = conv.BinnedSpikeTrain( spk_tr, binsize=0.02524578 * pq.s, t_start=trials[trial_index][0] * pq.s) binned_spk_tr = binned_spk_tr.to_array() spk_tr_lst.append(binned_spk_tr) rates_lst.append(r.flatten()) rates_lst = np.array(rates_lst) spk_tr_lst = np.array(spk_tr_lst) print(spk_tr_lst) #print(rates_lst.shape) return rates_lst, spk_tr_lst
def compute_rate_time_series(self, spikes_train, number_of_neurons=1, **elephant_kwargs): """A method to compute instantaneous spiking rate time series, using the elephant.statistics.instantaneous_rate method. Arguments: - spikes_train: a neo.core.SpikeTrain instance or an array of spikes' times or a dict with a key-value pair of "times" and spikes' times array - number_of_neurons=1: the number (integer) of neurons **elephant_kwargs: keyword arguments for the elephant.statistics.instantaneous_rate method Returns: - a dictionary of the following key-value pair(s): "rate_time_series": a xarray.DataArray of dimensions (Time,) "spikes_train": the neo.core.SpikeTrain used for the computation """ res_type = self._get_comput_res_type() t_start, t_stop = self._assert_start_end_times_from_spikes_times( spikes_train) # ...the time vector time = np.arange(t_start, t_stop + self._fmin_resolution, self.period) # ...and that the input spikes are in a neo.core.SpikeTrain instance spikes_train = self._assert_spike_train(spikes_train) if len(spikes_train) > 0: from quantities import ms from elephant.statistics import instantaneous_rate kwargs = deepcopy(elephant_kwargs) # Prepare the kernel spikes_kernel = kwargs.pop("kernel", str(self.spikes_kernel).lower()) if spikes_kernel != "auto": # If automatic computation of the spike kernel is not used... from elephant import kernels from elephant.statistics import optimal_kernel_bandwidth if not isinstance(spikes_kernel, kernels.Kernel): # If it is note a Kernel instance, it has to be a Kernel module... if isinstance(spikes_kernel, string_types): # ...or a Kernel class name (string) spikes_kernel = getattr(kernels, spikes_kernel + "Kernel") # Set or compute in this case also the (optimal) kernel width sigma parameter. if self.spikes_kernel_width: spikes_kernel_width = self.spikes_kernel_width * ms else: spikes_kernel_width = optimal_kernel_bandwidth( np.sort(spikes_train.__array__()))["optw"] * ms spikes_kernel = spikes_kernel(spikes_kernel_width * ms) kwargs["t_start"] = elephant_kwargs.get( "t_start", t_start - self._fmin_resolution) kwargs["t_stop"] = elephant_kwargs.get( "t_stop", t_stop + self._fmin_resolution) kwargs["kernel"] = spikes_kernel try: # Call the elephant method for the actual computation rates = instantaneous_rate(spikes_train, self.period * ms, **kwargs).flatten().__array__() except: # If it fails, compute a delta spike instantaneous rate with any kernel smoothing: # LOG.warning("Failed to compute instantaneous rate with a sliding timing window!\n" # "Computing instantaneous rate without any smoothing...") rates = 1000 * self._compute_delta_rate( time, spikes_train.__array__(), t_start, t_stop) else: rates = 0.0 * time # TODO: A better solution for handling the last time point with elephant! try: return { res_type: DataArray(rates, dims=["Time"], coords={"Time": time}), self.spikes_train_name: spikes_train } except Exception as e: LOG.warning("Failed with exception %s!\n" "Length of time is %d and of rates is %d.\n" "Removing last time point and retrying!" % (str(e), len(time), len(rates))) return { res_type: DataArray(rates, dims=["Time"], coords={"Time": time[:-1]}), self.spikes_train_name: spikes_train }
def test_re_consistency(self): """ test, whether the integral of the rate estimation curve is (almost) equal to the number of spikes of the spike train. """ shapes = ['GAU', 'gaussian', 'TRI', 'triangle', 'BOX', 'boxcar', 'EPA', 'epanechnikov', 'ALP', 'alpha', 'EXP', 'exponential'] kernel_resolution = 0.01*pq.s for shape in shapes: rate_estimate0 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, m_idx=None) rate_estimate1 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False, acausal=False) rate_estimate2 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=True, acausal=True) rate_estimate3 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=True, acausal=False) rate_estimate4 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False, acausal=True) kernel = es.make_kernel(form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, direction=-1) ### test consistency rate_estimate_list = [rate_estimate0, rate_estimate1, rate_estimate2, rate_estimate3, rate_estimate4] for rate_estimate in rate_estimate_list: num_spikes = len(self.spike_train) # re_diff = np.diff(rate_estimate) re_diff = rate_estimate.magnitude[1:]-rate_estimate.magnitude[:-1] re_fixed = (rate_estimate.magnitude[:-1] + re_diff)[:,0] re_times_diff = np.diff(rate_estimate.times.rescale('s')) integral = 0 for i, rate in enumerate(re_fixed): integral += rate*re_times_diff.magnitude[i] integral = integral self.assertAlmostEqual(num_spikes, integral)
def test_re_consistency(self): """ test, whether the integral of the rate estimation curve is (almost) equal to the number of spikes of the spike train. """ shapes = [ "GAU", "gaussian", "TRI", "triangle", "BOX", "boxcar", "EPA", "epanechnikov", "ALP", "alpha", "EXP", "exponential", ] kernel_resolution = 0.01 * pq.s for shape in shapes: rate_estimate_a0 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma="auto", t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=False, ) rate_estimate0 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s ) rate_estimate1 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=False, ) rate_estimate2 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=True, acausal=True, ) rate_estimate3 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=True, acausal=False, ) rate_estimate4 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=True, ) kernel = es.make_kernel(form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, direction=-1) ### test consistency rate_estimate_list = [ rate_estimate0, rate_estimate1, rate_estimate2, rate_estimate3, rate_estimate4, rate_estimate_a0, ] for rate_estimate in rate_estimate_list: num_spikes = len(self.spike_train) auc = spint.cumtrapz(y=rate_estimate.magnitude[:, 0], x=rate_estimate.times.rescale("s").magnitude)[-1] self.assertAlmostEqual(num_spikes, auc, delta=0.01 * num_spikes) self.assertRaises( TypeError, es.instantaneous_rate, self.spike_train, form="GAU", sampling_period=kernel_resolution, sigma="wrong_string", t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=True, )
def test_re_consistency(self): """ test, whether the integral of the rate estimation curve is (almost) equal to the number of spikes of the spike train. """ shapes = ['GAU', 'gaussian', 'TRI', 'triangle', 'BOX', 'boxcar', 'EPA', 'epanechnikov', 'ALP', 'alpha', 'EXP', 'exponential'] kernel_resolution = 0.01*pq.s for shape in shapes: rate_estimate_a0 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma='auto', t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False, acausal=False) rate_estimate0 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s) rate_estimate1 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False, acausal=False) rate_estimate2 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=True, acausal=True) rate_estimate3 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=True, acausal=False) rate_estimate4 = es.instantaneous_rate(self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False, acausal=True) kernel = es.make_kernel(form=shape, sampling_period=kernel_resolution, sigma=0.5*pq.s, direction=-1) ### test consistency rate_estimate_list = [rate_estimate0, rate_estimate1, rate_estimate2, rate_estimate3, rate_estimate4, rate_estimate_a0] for rate_estimate in rate_estimate_list: num_spikes = len(self.spike_train) auc = spint.cumtrapz(y=rate_estimate.magnitude[:, 0], x=rate_estimate.times.rescale('s').magnitude)[-1] self.assertAlmostEqual(num_spikes, auc, delta=0.01*num_spikes) self.assertRaises(TypeError, es.instantaneous_rate, self.spike_train, form='GAU', sampling_period=kernel_resolution, sigma='wrong_string', t_start=self.st_tr[0]*pq.s, t_stop=self.st_tr[1]*pq.s, trim=False, acausal=True)
def test_re_consistency(self): """ test, whether the integral of the rate estimation curve is (almost) equal to the number of spikes of the spike train. """ shapes = [ 'GAU', 'gaussian', 'TRI', 'triangle', 'BOX', 'boxcar', 'EPA', 'epanechnikov', 'ALP', 'alpha', 'EXP', 'exponential' ] kernel_resolution = 0.01 * pq.s for shape in shapes: rate_estimate_a0 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma='auto', t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=False) rate_estimate0 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s) rate_estimate1 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=False) rate_estimate2 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=True, acausal=True) rate_estimate3 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=True, acausal=False) rate_estimate4 = es.instantaneous_rate( self.spike_train, form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=True) kernel = es.make_kernel(form=shape, sampling_period=kernel_resolution, sigma=0.5 * pq.s, direction=-1) ### test consistency rate_estimate_list = [ rate_estimate0, rate_estimate1, rate_estimate2, rate_estimate3, rate_estimate4, rate_estimate_a0 ] for rate_estimate in rate_estimate_list: num_spikes = len(self.spike_train) auc = spint.cumtrapz( y=rate_estimate.magnitude[:, 0], x=rate_estimate.times.rescale('s').magnitude)[-1] self.assertAlmostEqual(num_spikes, auc, delta=0.01 * num_spikes) self.assertRaises(TypeError, es.instantaneous_rate, self.spike_train, form='GAU', sampling_period=kernel_resolution, sigma='wrong_string', t_start=self.st_tr[0] * pq.s, t_stop=self.st_tr[1] * pq.s, trim=False, acausal=True)
def plot_one_trial_one_neuron(self, recordings_index, trial_index, neuron_index): ''' Plots spikes, rates and behavior over a specified trial and neuron. ''' path = self.all_data_path + '/' + self.selected_recordings[ recordings_index] #Neural data neuron_inds = np.load(path + '/' + 'spikes.clusters.npy') spk_tms = np.load(path + '/' + 'spikes.times.npy') trials = np.load(path + '/' + 'trials.intervals.npy') #Behavioral data mot_timestamps = np.load(path + '/' + 'face.timestamps.npy') mot_energy = np.load(path + '/' + 'face.motionEnergy.npy') spk_ids = np.where(neuron_inds == neuron_index) spk_tms_one_neuron = spk_tms[spk_ids] #Select spikes in the trial for the neuron that we care about spks_range = np.bitwise_and( spk_tms_one_neuron >= trials[trial_index][0], spk_tms_one_neuron <= trials[trial_index][1]) subset = spk_tms_one_neuron[spks_range] #Create elephant SpikeTrain object spk_tr = neo.SpikeTrain(subset * pq.s, t_start=trials[trial_index][0] * pq.s, t_stop=trials[trial_index][1] * pq.s) #print(spk_tr) print((trials[trial_index][1] - trials[trial_index][0])) #Plot spike train plt.eventplot(spk_tr) plt.title('Spike train for one trial. trial ' + str(trial_index) + ' ' + ', neuron: ' + str(neuron_index)) plt.show() #Plot instantaneous firing rate kernel = kernels.GaussianKernel(sigma=0.1 * pq.s, invert=True) #sampling_rate the same as behavior r = instantaneous_rate(spk_tr, t_start=trials[trial_index][0] * pq.s, t_stop=trials[trial_index][1] * pq.s, sampling_period=0.02524578 * pq.s, kernel=kernel) #cutoff=5.0) plt.plot(r) plt.title('Instantaneous rate for one trial') plt.show() print('r shape', r.shape) #Plot behavior motion energy beh_range = np.bitwise_and( mot_timestamps[:, 1] >= trials[trial_index][0], mot_timestamps[:, 1] <= trials[trial_index][1]) #print(np.where(beh_range==True)) #print(mot_timestamps[beh_range]) beh_subset = mot_energy[beh_range] plt.plot(mot_timestamps[beh_range][:, 1].flatten(), beh_subset) plt.title('Motion energy in trial') plt.show() print('beh shp', beh_subset.shape) rate = np.array(r).flatten() beh_subset_aligned = self.align_rate_and_behavior(beh_subset, rate).flatten() print('Correlation coefficient between rate and behavior: ' + str(np.corrcoef(beh_subset_aligned, rate)[0, 1]))
X = [ np.random.uniform(-3, 3, size=(np.random.randint(9000, 11000), )) for i in range(100) ] kernel_sigma = 0.05 kernel = kernels.GaussianKernel(50 * pq.ms) t0 = time.time() Rate = list() for i in range(len(X)): spiketrain = SpikeTrain(X[i] * pq.s, t_start=-3 * pq.s, t_stop=3 * pq.s) rate = instantaneous_rate(spiketrain, sampling_period=0.01 * pq.s, t_start=-2 * pq.s, t_stop=2 * pq.s, kernel=kernel) Rate.append(rate.magnitude[:, 0]) Rate = np.array(Rate).T time_taken0 = (time.time() - t0) t0 = time.time() Rate2, times = myrate(X, sampling_period=0.01, t_start=-2, t_stop=2, kernel=kernel) time_taken1 = (time.time() - t0) print('Original {:0.4f}s, New {:0.4f}s, Speed up {:0.2f}X'.format( time_taken0, time_taken1, time_taken0 / time_taken1))
kernel = 'binned' if method in ['subsample', 'full']: time_series = pop_rate_time_series(spike_data, N, 500., T, resolution=1.) if method == 'auto_kernel': # To reduce the computational load, the time series is only computed until 10500. ms T = 10500. N = M.N[area][pop] # Assumes that all neurons were recorded st = neo.SpikeTrain(spike_data[:, 1] * pq.ms, t_stop=T * pq.ms) time_series = instantaneous_rate(st, 1. * pq.ms, t_start=500. * pq.ms, t_stop=T * pq.ms) time_series = np.array(time_series)[:, 0] / N kernel = 'auto' time_series_list.append(time_series) N_list.append(N) fp = '_'.join(('rate_time_series', method, area, pop)) np.save('{}/{}.npy'.format(save_path, fp), time_series) time_series_list = np.array(time_series_list) area_time_series = np.average(time_series_list, axis=0, weights=N_list) fp = '_'.join(('rate_time_series', method, area))
np.random.seed(i) sts.append(stg.homogeneous_poisson_process(rate, t_stop=T)) MultiTimer("generate data") # ======================================================================= # ASSET Method # ======================================================================= imat, xx, yy = asset.intersection_matrix(sts, binsize=binsize, dt=T) MultiTimer("intersection_matrix") # Compute the probability matrix, either analytically or via bootstrapping if prob_method == 'a': # Estimate rates fir_rates = list(np.zeros(shape=len(sts))) for st_id, st_trial in enumerate(sts): fir_rates[st_id] = estats.instantaneous_rate( st_trial, sampling_period=sampl_period) fir_rates[st_id] = neo.AnalogSignal(fir_rates[st_id], t_start=t_pre, t_stop=t_post, sampling_period=sampl_period) # Compute the probability matrix analytically pmat, x_edges, y_edges = asset.probability_matrix_analytical( sts, binsize, dt=T, fir_rates=fir_rates) elif prob_method == 'b': # Compute the probability matrix via bootstrapping (Montecarlo) pmat, x_edges, y_edges = asset.probability_matrix_montecarlo(sts, binsize, dt=T, j=dither_T, n_surr=n_surr) MultiTimer("prob_method")
# %% #values # %% #set(weight_InputE["w"][0]) # %% #plt.plot(weight_InputE["w"][0][:-1]-sse_w[:,1]) # %% plt.plot(np.array(spikes_E['t']) - np.array(spikes_e)[:, 0]) ## L'écart entre les spikes est proportionnel à l'écart de la plasticité # %% print(len(spikes_E['t'])) print(len(np.array(spikes_e)[:, 0])) # %% fig = go.Figure(data=go.Scatter(y=inh_g_ampa[:, 1])) fig.add_trace(go.Scatter(y=inhibitory["gampa"][0])) fig.show() # %% fig = go.Figure(data=go.Scatter(y=membrane_i[:, 1])) fig.add_trace(go.Scatter(y=inhibitory["U"][0])) fig.show() # %% brianSpk = SpikeTrain(spikes_E['t'] * pq.s, t_stop=max(spikes_E['t'])) # %% brianRate = instantaneous_rate(brianSpk, 1 * pq.s) # %% plt.plot(brianRate) # %%