Exemple #1
0
    def test_statistics(self):
        # This is a statistical test that has a non-zero chance of failure
        # during normal operation. Thus, we set the random seed to a value that
        # creates a realization passing the test.
        np.random.seed(seed=12345)

        for rate in [self.rate_profile, self.rate_profile.rescale(kHz)]:
            spiketrain = stgen.inhomogeneous_poisson_process(rate)
            intervals = isi(spiketrain)

            # Computing expected statistics and percentiles
            expected_spike_count = (np.sum(rate) *
                                    rate.sampling_period).simplified
            percentile_count = poisson.ppf(.999, expected_spike_count)
            expected_min_isi = (1 / np.min(rate))
            expected_max_isi = (1 / np.max(rate))
            percentile_min_isi = expon.ppf(.999, expected_min_isi)
            percentile_max_isi = expon.ppf(.999, expected_max_isi)

            # Testing (each should fail 1 every 1000 times)
            self.assertLess(spiketrain.size, percentile_count)
            self.assertLess(np.min(intervals), percentile_min_isi)
            self.assertLess(np.max(intervals), percentile_max_isi)

            # Testing t_start t_stop
            self.assertEqual(rate.t_stop, spiketrain.t_stop)
            self.assertEqual(rate.t_start, spiketrain.t_start)

        # Testing type
        spiketrain_as_array = stgen.inhomogeneous_poisson_process(
            rate, as_array=True)
        self.assertTrue(isinstance(spiketrain_as_array, np.ndarray))
        self.assertTrue(isinstance(spiketrain, neo.SpikeTrain))
    def test_statistics(self):
        # This is a statistical test that has a non-zero chance of failure
        # during normal operation. Thus, we set the random seed to a value that
        # creates a realization passing the test.
        np.random.seed(seed=12345)

        for rate in [self.rate_profile, self.rate_profile.rescale(kHz)]:
            spiketrain = stgen.inhomogeneous_poisson_process(rate)
            intervals = isi(spiketrain)

            # Computing expected statistics and percentiles
            expected_spike_count = (np.sum(
                rate) * rate.sampling_period).simplified
            percentile_count = poisson.ppf(.999, expected_spike_count)
            expected_min_isi = (1 / np.min(rate))
            expected_max_isi = (1 / np.max(rate))
            percentile_min_isi = expon.ppf(.999, expected_min_isi)
            percentile_max_isi = expon.ppf(.999, expected_max_isi)

            # Testing (each should fail 1 every 1000 times)
            self.assertLess(spiketrain.size, percentile_count)
            self.assertLess(np.min(intervals), percentile_min_isi)
            self.assertLess(np.max(intervals), percentile_max_isi)

            # Testing t_start t_stop
            self.assertEqual(rate.t_stop, spiketrain.t_stop)
            self.assertEqual(rate.t_start, spiketrain.t_start)

        # Testing type
        spiketrain_as_array = stgen.inhomogeneous_poisson_process(
            rate, as_array=True)
        self.assertTrue(isinstance(spiketrain_as_array, np.ndarray))
        self.assertTrue(isinstance(spiketrain, neo.SpikeTrain))
    def test_statistics(self):
        # This is a statistical test that has a non-zero chance of failure
        # during normal operation. Thus, we set the random seed to a value that
        # creates a realization passing the test.
        np.random.seed(seed=12345)

        for rate in (self.rate_profile, self.rate_profile.rescale(pq.kHz)):
            for refractory_period in (3 * pq.ms, None):
                spiketrain = stgen.inhomogeneous_poisson_process(
                    rate, refractory_period=refractory_period)
                intervals = isi(spiketrain)

                # Computing expected statistics and percentiles
                expected_spike_count = (np.sum(rate) *
                                        rate.sampling_period).simplified
                percentile_count = poisson.ppf(.999, expected_spike_count)
                expected_min_isi = (1 / np.min(rate))
                expected_max_isi = (1 / np.max(rate))
                percentile_min_isi = expon.ppf(.999, expected_min_isi)
                percentile_max_isi = expon.ppf(.999, expected_max_isi)

                # Check that minimal ISI is greater than the refractory_period
                if refractory_period is not None:
                    self.assertGreater(np.min(intervals), refractory_period)

                # Testing (each should fail 1 every 1000 times)
                self.assertLess(spiketrain.size, percentile_count)
                self.assertLess(np.min(intervals), percentile_min_isi)
                self.assertLess(np.max(intervals), percentile_max_isi)

                # Testing t_start t_stop
                self.assertEqual(rate.t_stop, spiketrain.t_stop)
                self.assertEqual(rate.t_start, spiketrain.t_start)

        # Testing type
        spiketrain_as_array = stgen.inhomogeneous_poisson_process(
            rate, as_array=True)
        self.assertTrue(isinstance(spiketrain_as_array, np.ndarray))
        self.assertTrue(isinstance(spiketrain, neo.SpikeTrain))

        # Testing type for refractory period
        refractory_period = 3 * pq.ms
        spiketrain = stgen.inhomogeneous_poisson_process(
            rate, refractory_period=refractory_period)
        spiketrain_as_array = stgen.inhomogeneous_poisson_process(
            rate, as_array=True, refractory_period=refractory_period)
        self.assertTrue(isinstance(spiketrain_as_array, np.ndarray))
        self.assertTrue(isinstance(spiketrain, neo.SpikeTrain))

        # Check that to high refractory period raises error
        self.assertRaises(ValueError,
                          stgen.inhomogeneous_poisson_process,
                          self.rate_profile,
                          refractory_period=1000 * pq.ms)
def inhom_poiss_2(arr, dt=0.025, speed_cm=20, field_size_cm=100):
    #length of the trajectory that mouse went
    t_sec = field_size_cm / speed_cm
    arr_len = arr.shape[1]
    t_arr = np.linspace(0, t_sec, arr_len)
    default_dt = t_sec / arr_len
    new_len = int(t_sec / dt)
    new_t_arr = np.linspace(0, t_sec, new_len)
    # arr=signal.resample(arr, new_len, axis=1)
    if dt != default_dt:
        new_len = int(t_sec / dt)
        new_t_arr = np.linspace(0, t_sec, new_len)
        f = interpolate.interp1d(t_arr, arr, axis=1)
        arr = f(new_t_arr)
    n_traj = dev_deg.shape[0]  #8
    n_cells = arr.shape[0]
    spi_arr = np.empty((n_cells, n_traj), dtype=np.ndarray)
    for grid_idc in range(n_cells):
        for i in range(dev_deg.shape[0]):
            rate_profile = arr[grid_idc, :, i]
            asig = AnalogSignal(rate_profile,
                                units=1 * pq.Hz,
                                t_start=0 * pq.s,
                                t_stop=t_sec * pq.s,
                                sampling_period=dt * pq.s,
                                sampling_interval=dt * pq.s)
            curr_train = stg.inhomogeneous_poisson_process(asig)
            spi_arr[grid_idc, i] = np.around(curr_train.times * 1000,
                                             decimals=1)
    return spi_arr
def generate_spiketrains(instantaneous_rates, num_trials, timestep):
    """
    Parameters
    ----------
    instantaneous_rates : np.ndarray
        Array containing time series.
    timestep :
        Sample period.
    num_steps : int
        Number of timesteps -> max_time = timestep*(num_steps-1).

    Returns
    -------
    spiketrains : list of neo.SpikeTrains
        List containing spiketrains of inhomogeneous Poisson
        processes based on given instantaneous rates.

    """

    spiketrains = []
    for _ in range(num_trials):
        spiketrains_per_trial = []
        for inst_rate in instantaneous_rates:
            anasig_inst_rate = neo.AnalogSignal(inst_rate, sampling_rate=1/timestep, units=pq.Hz)
            spiketrains_per_trial.append(inhomogeneous_poisson_process(anasig_inst_rate))
        spiketrains.append(spiketrains_per_trial)

    return spiketrains
 def test_zero_rate(self):
     for refractory_period in (3 * pq.ms, None):
         with warnings.catch_warnings():
             warnings.simplefilter("ignore")
             # RuntimeWarning: divide by zero encountered in true_divide
             # mean_interval = 1 / rate.magnitude, when rate == 0 Hz.
             spiketrain = stgen.inhomogeneous_poisson_process(
                 self.rate_profile_0, refractory_period=refractory_period)
         self.assertEqual(spiketrain.size, 0)
Exemple #7
0
 def test_low_rates(self):
     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         """
         Catch RuntimeWarning: divide by zero encountered in true_divide
         mean_interval = 1 / rate.magnitude, when rate == 0 Hz.
         """
         spiketrain = stgen.inhomogeneous_poisson_process(
             self.rate_profile_0)
     self.assertEqual(spiketrain.size, 0)
 def build_inhomogeneous_poisson_process(self):
     if not self._configured:
         self.configure_inhomogeneous_poisson_process()
     spike_trains = []
     for ii in range(self._size):
         spike_trains.append(
             inhomogeneous_poisson_process(
                 self.rate[:,
                           ii], refractory_period=self.refractory_period))
     return self.build_output(spike_trains)
Exemple #9
0
def rates_to_spikes( rates, t_start, t_stop, variation=False):
    """
    Generate spike train with homogenous or inhomogenous Poisson generator
    :param rates: an array or a float of quantities
    :param t_start: time to start spike train
    :param t_stop: time where the spike train stop
    :param variation: Boolean for variation of rate
    :return: one or multiple spike train
    """
    if variation:
        # the case where the variation of the rate is include
        # We generate the inhomogenous poisson
        if len(rates.shape) == 1:
            # the case where we have only one rate
            signal = AnalogSignal(rates, t_start=t_start, sampling_period=(t_stop-t_start)/rates.shape[-1])
            result = [inhomogeneous_poisson_process(signal,as_array=True)]
            return np.array(result)
        else :
            # the case where we have multiple rates
            result = []
            for rate in rates:
                signal = AnalogSignal(rate, t_start=t_start, sampling_period=(t_stop - t_start) / rates.shape[-1])
                result.append(inhomogeneous_poisson_process(signal,as_array=True))
            return np.array(result)
    else:
        # the case we have only the rate
        # We generate the homogenous poisson
        if len(rates.shape) ==0:
            # the case where we have only one rate
            result = np.array([homogeneous_poisson_process(rate=rates, t_start=t_start, t_stop=t_stop, as_array=True)])
        else:
            # the case where we have multiple rates
            result = []
            for rate in rates:
                result.append(homogeneous_poisson_process(rate=rate, t_start=t_start, t_stop=t_stop, as_array=True))
        return np.array(result)
Exemple #10
0
 def test_effective_rate_refractory_period(self):
     np.random.seed(27)
     rate_expected = 10 * pq.Hz
     refractory_period = 90 * pq.ms  # 10 ms of effective ISI
     rates = neo.AnalogSignal(np.repeat(rate_expected, 1000), units=pq.Hz,
                              t_start=0 * pq.ms, sampling_rate=1 * pq.Hz)
     spiketrain = stgen.inhomogeneous_poisson_process(
         rates, refractory_period=refractory_period)
     rate_obtained = len(spiketrain) / spiketrain.t_stop
     self.assertAlmostEqual(rate_expected, rate_obtained.simplified,
                            places=1)
     intervals_inhomo = isi(spiketrain)
     isi_mean_expected = 1. / rate_expected
     self.assertAlmostEqual(isi_mean_expected.simplified,
                            intervals_inhomo.mean().simplified,
                            places=3)
Exemple #11
0
def _inhom_poiss(arr, dur_s, poiss_seed=0, dt_s=0.025):
    np.random.seed(poiss_seed)
    n_cells = arr.shape[0]
    spi_arr = np.zeros((n_cells), dtype = np.ndarray)
    for grid_idc in range(n_cells):
        np.random.seed(poiss_seed+grid_idc)
        rate_profile = arr[grid_idc,:]
        asig = AnalogSignal(rate_profile,
                                units=1*pq.Hz,
                                t_start=0*pq.s,
                                t_stop=dur_s*pq.s,
                                sampling_period=dt_s*pq.s,
                                sampling_interval=dt_s*pq.s)
        curr_train = stg.inhomogeneous_poisson_process(asig)
        spi_arr[grid_idc] = np.array(curr_train.times*1000) #time conv to ms
    return spi_arr
def inhom_poiss(arr, n_traj, dur_s, seed_2=0, dt_s=0.025):
    #length of the trajectory that mouse went
    np.random.seed(seed_2)
    n_cells = arr.shape[0]
    spi_arr = np.empty((n_cells, n_traj), dtype=np.ndarray)
    for grid_idc in range(n_cells):
        for i in range(n_traj):
            np.random.seed(seed_2 + grid_idc)
            rate_profile = arr[grid_idc, :, i]
            asig = AnalogSignal(rate_profile,
                                units=1 * pq.Hz,
                                t_start=0 * pq.s,
                                t_stop=dur_s * pq.s,
                                sampling_period=dt_s * pq.s,
                                sampling_interval=dt_s * pq.s)
            curr_train = stg.inhomogeneous_poisson_process(asig)
            spi_arr[grid_idc,
                    i] = np.array(curr_train.times * 1000)  #time conv to ms
    return spi_arr
Exemple #13
0
def inhom_poiss(arr,
                n_traj,
                dt_s=0.0001,
                speed_cm=20,
                field_size_cm=100,
                seed=10000):
    #length of the trajectory that mouse went
    np.random.seed(seed)
    dt_ms = dt_s * 1000
    t_sec = field_size_cm / speed_cm
    arr_len = arr.shape[1]
    t_arr = np.linspace(0, t_sec, arr_len)
    default_dt_s = t_sec / arr_len
    new_len = int(t_sec / dt_s)
    new_t_arr = np.linspace(0, t_sec, new_len)
    # arr=signal.resample(arr, new_len, axis=1)
    if dt_s != default_dt_s:  #if dt given is different than default_dt(0.025), then interpolate
        new_len = int(t_sec / dt_s)
        new_t_arr = np.linspace(0, t_sec, new_len)
        f = interpolate.interp1d(t_arr, arr, axis=1)
        arr = f(new_t_arr)
    n_cells = arr.shape[0]
    spi_arr = np.empty((n_cells, n_traj), dtype=np.ndarray)
    #go through each rate profile or each cell for variable trajectory
    for grid_idc in range(n_cells):
        for i in range(n_traj):
            np.random.seed(seed + grid_idc)
            rate_profile = arr[grid_idc, :, i]
            #produce analig signal out of rate profiles
            asig = AnalogSignal(rate_profile,
                                units=1 * pq.Hz,
                                t_start=0 * pq.s,
                                t_stop=t_sec * pq.s,
                                sampling_period=dt_s * pq.s,
                                sampling_interval=dt_s * pq.s)
            #generate the spike train out of analog signal
            curr_train = stg.inhomogeneous_poisson_process(asig)
            spi_arr[grid_idc,
                    i] = np.array(curr_train.times * 1000)  #time conv to ms
    return spi_arr
Exemple #14
0
def inhom_poiss_io(rate=10, max_rate=100):
    """Generate an inhomogeneous poisson spike train with a rate profile that
    is a sine wave whose rate is given by the rate parameter and that maximum
    frequency is given by the max_rate parameter in Hz.
    min frequency is always 0Hz
    """
    sampling_interval = 0.0001 * pq.s

    t = np.arange(0, 0.3, sampling_interval.magnitude)

    rate_profile = (np.sin(t * rate * np.pi * 2 - np.pi / 2) +
                    1) * max_rate / 2

    rate_profile_as_asig = AnalogSignal(rate_profile,
                                        units=1 * pq.Hz,
                                        t_start=0 * pq.s,
                                        t_stop=0.5 * pq.s,
                                        sampling_period=sampling_interval)

    spike_trains = []
    for x in range(24):
        curr_train = stg.inhomogeneous_poisson_process(rate_profile_as_asig)
        # We have to make sure that there is sufficient space between spikes.
        # If there is not, we move the next spike by 0.1ms
        spike_trains.append(curr_train)

    array_like = np.array([
        np.around(np.array(x.times) * 1000, decimals=1) for x in spike_trains
    ])
    for arr_idx in range(array_like.shape[0]):
        bad_idc = np.argwhere(np.diff(array_like[arr_idx]) == 0).flatten()
        bad_idc = bad_idc + 1
        while bad_idc.any():
            for bad_idx in bad_idc:
                array_like[arr_idx][
                    bad_idx] = array_like[arr_idx][bad_idx] + 0.1
            bad_idc = np.argwhere(np.diff(array_like[arr_idx]) == 0).flatten()
            bad_idc = bad_idc + 1

    return array_like
Exemple #15
0
def inhom_poiss(modulation_rate=10, max_rate=100, n_cells=400):
    """Generate spike trains from an inhomogeneous poisson process.
    The rate profile is a sine wave with a frequency given my modulation_rate
    and a peak given by max_rate. Both in Hz.
    Returns a ragged array of dtype np.object with lenght n_cells. Contains the
    spike times.
    """
    sampling_interval = 0.0001 * pq.s

    t = np.arange(0, 0.5, sampling_interval.magnitude)

    rate_profile = (np.sin(t*modulation_rate*np.pi*2-np.pi/2) + 1) * max_rate / 2

    rate_profile_as_asig = AnalogSignal(rate_profile,
                                        units=1*pq.Hz,
                                        t_start=0*pq.s,
                                        t_stop=0.5*pq.s,
                                        sampling_period=sampling_interval)

    spike_trains = []
    for x in range(n_cells):
        curr_train = stg.inhomogeneous_poisson_process(rate_profile_as_asig)
        # We have to make sure that there is sufficient space between spikes.
        # If there is not, we move the next spike by 0.1ms
        spike_trains.append(curr_train)

    array_like = np.array([np.around(np.array(x.times)*1000, decimals=1)
                           for x in spike_trains], dtype=np.object)
    for arr_idx in range(array_like.shape[0]):
        bad_idc = np.argwhere(np.diff(array_like[arr_idx]) == 0).flatten()
        bad_idc = bad_idc+1
        while bad_idc.any():
            for bad_idx in bad_idc:
                array_like[arr_idx][bad_idx] = array_like[arr_idx][bad_idx] + 0.1
            bad_idc = np.argwhere(np.diff(array_like[arr_idx]) == 0).flatten()
            bad_idc = bad_idc + 1

    return array_like
def generate_sts(data_type, N=100):
    '''
    Generate a list of parallel spike trains with different statistics.

    The data are composed of background spiking activity plus possibly
    a repeated sequence of synchronous events (SSE).
    The background activity depends on the value of data_type.
    The size and occurrence count of the SSE is specified by sse_params.

    Parameters
    ----------
    data_type : int
        An integer specifying the type of background activity.
        At the moment the following types of background activity are
        supported (note: homog = across neurons; stat = over time):
        0 : 100 indep Poisson with rate 25 Hz
        1: 100 indep Poisson nonstat-step (10/60/10 Hz)
        2: 100 indep Poisson heterog (5->25 Hz), stat
        3 : 100 indep Poisson, rate increase with latency variability
    N: int 
        total number of neurons in the model. The default is N=100.
    Output
    ------
    sts : list of SpikeTrains
        a list of spike trains
    params : dict
        a dictionary of simulation parameters

    '''
    T = 1 * pq.s  # simulation time
    sampl_period = 10 * pq.ms  # sampling period of the rate profile
    params = {'nr_neurons': N, 'simul_time': T}
    # Indep Poisson homog, stat rate 25 Hz
    if data_type == 0:
        # Define a rate profile
        rate = 25 * pq.Hz
        # Generate data
        sts = stg._n_poisson(rate=rate, t_stop=T, n=N)
        # Storing rate parameter
        params['rate'] = rate
    # Indep Poisson,  homog, nonstat-step (10/60/10 Hz)
    elif data_type == 1:
        a0, a1 = 10 * pq.Hz, 60 * pq.Hz  # baseline and transient rates
        t1, t2 = 600 * pq.ms, 700 * pq.ms  # time segment of transient rate
        # Define a rate profile
        times = sampl_period.units * np.arange(
            0,
            T.rescale(sampl_period.units).magnitude, sampl_period.magnitude)
        rate_profile = np.zeros(times.shape)
        rate_profile[np.any([times < t1, times > t2], axis=0)] = a0.magnitude
        rate_profile[np.all([times >= t1, times <= t2], axis=0)] = a1.magnitude
        rate_profile = rate_profile * a0.units
        rate_profile = neo.AnalogSignal(rate_profile,
                                        sampling_period=sampl_period)
        # Generate data
        sts = [
            stg.inhomogeneous_poisson_process(rate_profile) for i in range(N)
        ]
        # Storing rate parameter
        params['rate'] = rate_profile
    # Indep Poisson, heterog (5->15 Hz), stat
    elif data_type == 2:
        rate_min = 5 * pq.Hz  # min rate. Ensures that there is >=1 spike
        rate_max = 25 * pq.Hz  # max rate
        rates = np.linspace(rate_min.magnitude, rate_max.magnitude, N) * pq.Hz
        # Define a rate profile
        # Generate data
        sts = [
            stg.homogeneous_poisson_process(rate=rate, t_stop=T)
            for rate in rates
        ]
        random.shuffle(sts)
        # Storing rate parameter
        params['rate'] = rates
    # Indep Poisson, rate increase sequence
    elif data_type == 3:
        l = 20  # 20 groups of neurons
        w = 5  # of 5 neurons each
        t0 = 50 * pq.ms  # the first of which increases the rate at time t0
        t00 = 500 * pq.ms  # and again at time t00
        ratechange_dur = 5 * pq.ms  # old: 10ms  # for a short period
        a0, a1 = 14 * pq.Hz, 100 * pq.Hz  # from rate a0 to a1
        ratechange_delay = 5 * pq.ms  # old: 10ms; followed with delay by next group
        # Define a rate profile
        times = sampl_period.units * np.arange(
            0,
            T.rescale(sampl_period.units).magnitude, sampl_period.magnitude)
        sts = []
        rate_profiles = []
        for i in range(l * w):
            t1 = t0 + (i // w) * ratechange_delay
            t2 = t1 + ratechange_dur
            t11 = t00 + (i // w) * ratechange_delay
            t22 = t11 + ratechange_dur
            rate_profile = np.zeros(times.shape)
            rate_profile[np.any([times < t1, times > t2], axis=0)] = \
                a0.magnitude
            rate_profile[np.all([times >= t1, times <= t2], axis=0)] = \
                a1.magnitude
            rate_profile[np.all([times >= t11, times <= t22], axis=0)] = \
                a1.magnitude
            rate_profile = rate_profile * a0.units
            rate_profile = neo.AnalogSignal(rate_profile,
                                            sampling_period=sampl_period)
            rate_profiles.append(rate_profile)
            # Generate data
            sts.append(stg.inhomogeneous_poisson_process(rate_profile))
        # Storing rate parameter
        params['rate'] = rate_profiles
    else:
        raise ValueError(
            'data_type %d not supported. Provide int from 0 to 10' % data_type)
    return sts, params
Exemple #17
0
# print(fr)
frf = pickle.load(open('data/filtered_firing_inhibition_on.p', 'rb'))
# print(np.shape(fr))
# print(fr)
fs = [fr, frf]
num_tsteps = len(fr[0])
dt = 20. / num_tsteps
t = np.arange(num_tsteps) * dt
for i, nam in enumerate(['filter_off', 'filter_on']):
    fr_ex = neo.AnalogSignal(100000 * fs[i][0],
                             units=pq.Hz,
                             sampling_rate=1. / dt * 1 * pq.Hz)
    fr_in = neo.AnalogSignal(100000 * fs[i][1],
                             units=pq.Hz,
                             sampling_rate=1. / dt * 1 * pq.Hz)
    spikes = stg.inhomogeneous_poisson_process(fr_ex, as_array=True)
    spikes_in = stg.inhomogeneous_poisson_process(fr_in, as_array=True)
    # # print(spikes)
    # plt.figure()
    # # plt.plot(spikes)
    # plt.plot(t,0.11*np.asarray(fr_ex),'r')
    # plt.hist(spikes,bins=np.linspace(0,21,200))
    # plt.show()

    # plt.figure()
    # # plt.plot(spikes)
    # plt.plot(t,0.11*np.asarray(fr_in),'r')
    # plt.hist(spikes_in,bins=np.linspace(0,21,200))
    # plt.show()

    pickle.dump(
 def test_low_rates(self):
     spiketrain = stgen.inhomogeneous_poisson_process(self.rate_profile_0)
     self.assertEqual(spiketrain.size, 0)
Exemple #19
0
 def test_low_rates(self):
     spiketrain = stgen.inhomogeneous_poisson_process(self.rate_profile_0)
     self.assertEqual(spiketrain.size, 0)