def test_traj_with_three_pauses_is_cleaned_correctly(self):

        speeds = cc([np.random.uniform(0, 1, 100) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3,
                     np.random.uniform(0, 0.01, 5),  # short pause
                     np.random.uniform(0, 1, 95) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3])

        dists = cc([np.random.uniform(0, 1, 100) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3,
                     np.random.uniform(0, 0.01, 5),  # short pause
                     np.random.uniform(0, 1, 95) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3])

        start_timepoint_id = 98

        traj = Trajectory(start_timepoint_id, speeds, dists)

        clean_portions = clean_trajectories.clean_traj(traj, CLEANING_PARAMS)

        self.assertEqual(len(clean_portions), 3)
        self.assertEqual(clean_portions[0, 0], start_timepoint_id)
        self.assertEqual(clean_portions[0, 1], start_timepoint_id + 100 - 1)
        self.assertEqual(clean_portions[1, 0], start_timepoint_id + 120)
        self.assertEqual(clean_portions[1, 1], start_timepoint_id + 300 - 1)
        self.assertEqual(clean_portions[2, 0], start_timepoint_id + 320)
        self.assertEqual(clean_portions[2, 1], traj.end_timepoint_id)
    def test_two_long_pauses_in_middle_with_too_short_traj_between_is_cleaned_correctly(self):

        speeds = cc([np.random.uniform(0, 1, 100) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 30) + 3,  # short trajectory
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3])

        dists = cc([np.random.uniform(0, 1, 100) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 30) + 3,  # short trajectory
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3])

        start_timepoint_id = 1003

        traj = Trajectory(start_timepoint_id, speeds, dists)

        clean_portions = clean_trajectories.clean_traj(traj, CLEANING_PARAMS)

        self.assertEqual(len(clean_portions), 2)
        self.assertEqual(clean_portions[0, 0], start_timepoint_id)
        self.assertEqual(clean_portions[0, 1], start_timepoint_id + 100 -1)
        self.assertEqual(clean_portions[1, 0], start_timepoint_id + 170)
        self.assertEqual(clean_portions[1, 1], traj.end_timepoint_id)
Exemple #3
0
    def initialize(self):
        """Reset insect history."""

        # check that all params are set
        for param in [
                self.r, self.d, self.a, self.tau, self.w, self.loglike_function
        ]:
            if param is None:
                param_str = ', '.join(self.param_names)
                msg = (
                    'Please make sure all of the following parameters are set:'
                    '%s.' % param_str)
                raise ValueError(msg)

        # reset clock
        self.ts = 0  # timestep
        self.t = 0.  # time

        # reset src pos logprob
        self.logprob = np.zeros(self.env.shape, dtype=float)

        # get odor domain from loglikelihood function
        self.odor_domain = self.loglike_function.domain

        # calculate extended loglikelihood map

        # get environment geometry
        xext = self.env.x - self.env.x[0]
        xext = cc([-xext[1:][::-1], xext])
        yext = self.env.y - self.env.y[0]
        yext = cc([-yext[1:][::-1], yext])
        zext = self.env.z - self.env.z[0]
        zext = cc([-zext[1:][::-1], zext])

        central_idx = ((len(xext) - 1) / 2, (len(yext) - 1) / 2,
                       (len(zext) - 1) / 2)

        map_shape = (len(xext), len(yext), len(zext))
        self.loglike_map = np.zeros((len(self.odor_domain), ) + map_shape,
                                    dtype=float)

        for odor_idx, odor in enumerate(self.odor_domain):
            loglike = self.loglike_function(odor,
                                            central_idx,
                                            xext=xext,
                                            yext=yext,
                                            zext=zext,
                                            dt=self.dt,
                                            w=self.w,
                                            r=self.r,
                                            d=self.d,
                                            a=self.a,
                                            tau=self.tau)

            self.loglike_map[odor_idx] = loglike
    def test_traj_ends_with_long_pause_has_pause_removed(self):

        speeds = cc([np.random.uniform(0, 1, 500) + 3, np.random.uniform(0, 0.01, 20)])
        dists = cc([np.random.uniform(0, 1, 500) + 9, np.random.uniform(0, 0.003, 20)])
        start_timepoint_id = 1008
        traj = Trajectory(start_timepoint_id, speeds, dists)

        clean_portions = clean_trajectories.clean_traj(traj, CLEANING_PARAMS)

        self.assertEqual(len(clean_portions), 1)
        self.assertEqual(clean_portions[0, 0], start_timepoint_id)
        self.assertEqual(clean_portions[0, 1], traj.end_timepoint_id - 20)
Exemple #5
0
    def testmergeVec(self):
        d = lammpsdata(Atoms())
        direct, phi = d.mergeVec([1, 0, 0], [0, 2, 0])
        self.assertTrue(cc(direct, [0, 0, 1]))
        self.assertEqual(phi, pi / 2)
        direct, phi = d.mergeVec([1, 0, 1], [1, 1, 1])
        self.assertTrue(cc(direct, [-1 / sqrt(2), 0, 1 / sqrt(2)]))
        self.assertEqual(cos(phi), sqrt(2.0 / 3))

        direct, phi = d.mergeVec([1, 0, 0], [1, 0, 0])
        self.assertTrue(cc(direct, [1, 0, 0]))
        self.assertEqual(cos(phi), 1)
    def test_traj_starting_with_short_pause_is_untouched(self):

        speeds = cc([np.random.uniform(0, 0.01, 5), np.random.uniform(0, 1, 500) + 3])
        dists = cc([np.random.uniform(0, 0.003, 5), np.random.uniform(0, 1, 500) + 9])
        start_timepoint_id = 20010
        traj = Trajectory(start_timepoint_id, speeds, dists)

        clean_portions = clean_trajectories.clean_traj(traj, CLEANING_PARAMS)

        self.assertEqual(len(clean_portions), 1)
        self.assertEqual(clean_portions[0, 0], start_timepoint_id)
        self.assertEqual(clean_portions[0, 1], traj.end_timepoint_id)
Exemple #7
0
	def testmergeVec(self):
		d=lammpsdata(Atoms())
		direct,phi=d.mergeVec([1,0,0],[0,2,0])
		self.assertTrue(cc(direct,[0,0,1]))
		self.assertEqual(phi,pi/2)
		direct,phi=d.mergeVec([1,0,1],[1,1,1])
		self.assertTrue(cc(direct,[-1/sqrt(2),0,1/sqrt(2)]))
		self.assertEqual(cos(phi),sqrt(2.0/3))
		
		direct,phi=d.mergeVec([1,0,0],[1,0,0])
		self.assertTrue(cc(direct,[1,0,0]))
		self.assertEqual(cos(phi),1)
Exemple #8
0
	def testwritedata(self):
		a=Atoms('C2',[[1,0,1],[0,1,1]])
		a.set_cell([[1,0,1],[0,1,1],[0,0,1]])
		d=lammpsdata(a,['C','N'])
		d.writedata()
		b=data('structure')
		self.assertEqual(b.headers["atoms"],2)
		self.assertEqual(b.headers["atom types"],2)
		self.assertEqual(b.title ,'C2\n')
		self.assertTrue(cc(b.headers["xlo xhi"],[0,sqrt(2)]))
		self.assertTrue(cc(b.headers["ylo yhi"],[0,sqrt(2)*sqrt(3)/2]))
		self.assertTrue(cc(b.headers["xy xz yz"][0:1],[sqrt(2)/2]))
		b.map(1,'id',2,'type',3,'x',4,'y',5,'z')
		atoms=b.viz(0)[2]
		self.assertTrue(cc(atoms,[[1,1,sqrt(2),0,0],[2,1,sqrt(2)/2,sqrt(2)*sqrt(3)/2,0]]))
		shell_exec('rm structure')
    def update(self, t, inputTrain):
        if inputTrain[t]:  # check for input spike
            self.t_list = cc([self.t_list, [1]])

        # Calculate synaptic current due to current and past input spikes
        self.g_syn = np.sum(self.alpha_func[self.t_list])
        self.I_syn = self.g_syn * (self.E_syn - self.V)

        # Update spike times
        if np.any(self.t_list):
            self.t_list = self.t_list + 1
            if self.t_list[
                    0] == self.synConductanceMaxDuration:  # Reached max duration of syn conductance
                self.t_list = self.t_list[1:]

        # Compute membrane voltage
        # Euler method: V(t+h) = V(t) + h*dV/dt
        if not self.fired:
            self.V = self.V + (-((self.V - self.E_leak) *
                                 (1 + self.R * self.g_ad) /
                                 (self.R * self.C)) + (self.I_syn / self.C))
            self.g_ad = self.g_ad + (-self.g_ad / self.tau_ad
                                     )  # spike rate adaptation
        else:
            self.fired -= 1
            self.V = self.V_th - 10  # reset voltage after spike
            self.g_ad = 0

        # Generate spike
        if (self.V > self.V_th) and not self.fired:
            self.V = self.V_spike
            self.fired = 4
            self.g_ad = self.g_ad + self.G_inc
    def test_trajectory_with_speed_pause_but_not_distance_pause_is_left_untouched(self):

        speeds = cc([np.random.uniform(0, 1, 500) + 3,
                     np.random.uniform(0, 0.01, 20),
                     np.random.uniform(0, 1, 500) + 3])
        dists = cc([np.random.uniform(0, 1, 500) + 9,
                    np.random.uniform(0, 0.003, 20) + 4,
                    np.random.uniform(0, 1, 500) + 9])
        start_timepoint_id = 10883

        traj = Trajectory(start_timepoint_id, speeds, dists)

        clean_portions = clean_trajectories.clean_traj(traj, CLEANING_PARAMS)

        self.assertEqual(len(clean_portions), 1)
        self.assertEqual(clean_portions[0, 0], traj.start_timepoint_id)
        self.assertEqual(clean_portions[0, 1], traj.end_timepoint_id)
Exemple #11
0
 def testget_rotated_atoms(self):
     a = Atoms('C2', [[1, 0, 1], [0, 1, 1]])
     a.set_cell([[1, 0, 1], [0, 1, 1], [0, 0, 1]])
     d = lammpsdata(a)
     unit = d.get_rotated_atoms()
     self.assertTrue(
         cc(unit.cell[:2],
            [[sqrt(2), 0, 0], [sqrt(2) / 2,
                               sqrt(2) * sqrt(3) / 2, 0]]))
Exemple #12
0
    def initialize(self):
        """Reset insect history."""

        # check that all params are set
        for param in [self.r, self.d, self.a, self.tau, self.w,
                      self.loglike_function]:
            if param is None:
                param_str = ', '.join(self.param_names)
                msg = ('Please make sure all of the following parameters are set:'
                       '%s.' % param_str)
                raise ValueError(msg)

        # reset clock
        self.ts = 0 # timestep
        self.t = 0. # time
        
        # reset src pos logprob
        self.logprob = np.zeros(self.env.shape, dtype=float)
        
        # get odor domain from loglikelihood function
        self.odor_domain = self.loglike_function.domain

        # calculate extended loglikelihood map

        # get environment geometry
        xext = self.env.x - self.env.x[0]
        xext = cc([-xext[1:][::-1], xext])
        yext = self.env.y - self.env.y[0]
        yext = cc([-yext[1:][::-1], yext])
        zext = self.env.z - self.env.z[0]
        zext = cc([-zext[1:][::-1], zext])

        central_idx = ((len(xext) - 1)/2, (len(yext) - 1)/2, (len(zext) - 1)/2)

        map_shape = (len(xext), len(yext), len(zext))
        self.loglike_map = np.zeros((len(self.odor_domain), ) + map_shape, dtype=float)

        for odor_idx, odor in enumerate(self.odor_domain):
            loglike = self.loglike_function(odor, central_idx, xext=xext,
                                            yext=yext, zext=zext, dt=self.dt,
                                            w=self.w, r=self.r, d=self.d,
                                            a=self.a, tau=self.tau)

            self.loglike_map[odor_idx] = loglike
Exemple #13
0
def segment_by_threshold(data,
                         th=1.,
                         seg_start='last',
                         seg_end='next',
                         idxs=None):
    """Function to segment a 1D data time-series."""

    # create mask of all points that at least threshold
    above_th = (np.array(data) >= th).astype(int)
    # create onset/offset trigger array
    trigger = np.diff(cc([[0], above_th, [0]]))
    # identify onsets
    onsets = (trigger == 1).nonzero()[0]
    # identify offsets
    offsets = (trigger == -1).nonzero()[0]
    offsets -= 1

    # add segment starts and ends if specified
    if seg_start == 'last':
        starts = np.zeros(onsets.shape, dtype=int)
        starts[1:] = offsets[:-1] + 1
        if idxs is not None:
            starts = idxs[starts]
        starts = starts[:, None]
    else:
        starts = np.zeros(onsets.shape + (0, ), dtype=int)
    if seg_end == 'next':
        ends = len(data) * np.ones(offsets.shape, dtype=int)
        ends[:-1] = onsets[1:]
        ends -= 1
        if idxs is not None:
            ends = idxs[ends]
        ends = ends[:, None]
    else:
        ends = np.zeros(onsets.shape + (0, ), dtype=int)

    if idxs is not None:
        onsets = idxs[onsets]
        offsets = idxs[offsets]
    onsets = onsets[:, None]
    offsets = offsets[:, None]

    return cc([starts, onsets, offsets, ends], 1)
Exemple #14
0
 def testwritedata(self):
     a = Atoms('C2', [[1, 0, 1], [0, 1, 1]])
     a.set_cell([[1, 0, 1], [0, 1, 1], [0, 0, 1]])
     d = lammpsdata(a, ['C', 'N'])
     d.writedata()
     b = data('structure')
     self.assertEqual(b.headers["atoms"], 2)
     self.assertEqual(b.headers["atom types"], 2)
     self.assertEqual(b.title, 'C2\n')
     self.assertTrue(cc(b.headers["xlo xhi"], [0, sqrt(2)]))
     self.assertTrue(cc(b.headers["ylo yhi"], [0, sqrt(2) * sqrt(3) / 2]))
     self.assertTrue(cc(b.headers["xy xz yz"][0:1], [sqrt(2) / 2]))
     b.map(1, 'id', 2, 'type', 3, 'x', 4, 'y', 5, 'z')
     atoms = b.viz(0)[2]
     self.assertTrue(
         cc(atoms, [[1, 1, sqrt(2), 0, 0],
                    [2, 1, sqrt(2) / 2,
                     sqrt(2) * sqrt(3) / 2, 0]]))
     shell_exec('rm structure')
    def test_traj_with_pause_in_middle_has_pause_removed(self):

        speeds = cc([np.random.uniform(0, 1, 500) + 3,
                     np.random.uniform(0, 0.01, 20),
                     np.random.uniform(0, 1, 500) + 3])

        dists = cc([np.random.uniform(0, 1, 500) + 9,
                    np.random.uniform(0, 0.003, 20),
                    np.random.uniform(0, 1, 500) + 9])
        start_timepoint_id = 10883

        traj = Trajectory(start_timepoint_id, speeds, dists)

        clean_portions = clean_trajectories.clean_traj(traj, CLEANING_PARAMS)

        self.assertEqual(len(clean_portions), 2)
        self.assertEqual(clean_portions[0, 0], start_timepoint_id)
        self.assertEqual(clean_portions[0, 1], start_timepoint_id + 500 - 1)
        self.assertEqual(clean_portions[1, 0], start_timepoint_id + 520)
        self.assertEqual(clean_portions[1, 1], traj.end_timepoint_id)
Exemple #16
0
    def fit(self, xs, y):
        """Fit signal & feedback filters from an input & output timeseries.
        
        Args:
            xs: list of input signals.
        """

        # convert xs into fittable data array
        ## the format of the data matrix that will be fed into the statsmodels
        ## api is D = [1, x1, x2, x3, ..., y], where rows correspond to
        ## timepoints, 1 is a column vector of ones, x1 is a sliding window matrix
        ## for the first signal, etc., and y is a toeplitz matrix for the
        ## output

        ## generate sliding window matrices for each x
        xswms = [None] * self.sig_dim

        for sctr, x in enumerate(xs):
            sf_len = self.sig_filter_lens[sctr]
            start = self.max_filter_len - sf_len
            xswms[sctr] = swm(x, sf_len, start=start, end=-1)

        ## generate sliding window matrix for y
        start = self.max_filter_len - self.fdbk_filter_len
        yswm = swm(y, self.fdbk_filter_len, start=start, end=-1)

        ## generate complete input data array
        data_in = cc(xswms + [yswm], axis=1)

        # add constant to data
        data_in = sm.add_constant(data_in)

        # count rows
        nrows = data_in.shape[0]

        # fit data
        model = sm.GLM(y[-nrows:], data_in, family=sm.families.Gaussian())

        params = model.fit().params

        # store parameters
        self.constant = params[0]

        ctr = 1
        for sctr in range(self.sig_dim):
            sf_len = self.sig_filter_lens[sctr]
            self.sig_filters[sctr] = params[ctr:ctr + sf_len][::-1]
            ctr += sf_len

        self.fdbk_filter = params[ctr:][::-1]
    def test_traj_with_middle_and_end_pause_is_cleaned_correctly(self):

        speeds = cc([np.random.uniform(0, 1, 100) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3,
                     np.random.uniform(0, 0.01, 20)])  # long pause

        dists = cc([np.random.uniform(0, 1, 100) + 3,
                     np.random.uniform(0, 0.01, 20),  # long pause
                     np.random.uniform(0, 1, 80) + 3,
                     np.random.uniform(0, 0.01, 20)])  # long pause

        start_timepoint_id = 9809

        traj = Trajectory(start_timepoint_id, speeds, dists)

        clean_portions = clean_trajectories.clean_traj(traj, CLEANING_PARAMS)

        self.assertEqual(len(clean_portions), 2)
        self.assertEqual(clean_portions[0, 0], start_timepoint_id)
        self.assertEqual(clean_portions[0, 1], start_timepoint_id + 100 - 1)
        self.assertEqual(clean_portions[1, 0], start_timepoint_id + 120)
        self.assertEqual(clean_portions[1, 1], traj.end_timepoint_id - 20)
Exemple #18
0
    def gen(self, xs):
        """Generate an output signal from an input signal.
        
        Args:
            xs: list of input signals.
        """

        # get signal length
        sig_len = len(xs[0])

        # zeropad x's to make convolution easier
        zp = np.zeros((self.max_filter_len, ), dtype=float)
        xzps = [None for x in xs]
        for xctr, x in enumerate(xs):
            xzps[xctr] = cc([zp, x])

        # generate zeropadded y
        yzp = np.zeros(xzps[0].shape, dtype=float)

        # fill in y (t refers to yzp's idx)
        for t in range(self.max_filter_len, self.max_filter_len + sig_len):
            # sequentially add components of y for each signal
            result = 0
            for sctr in range(self.sig_dim):
                # get signal filter, its length, and relevant signal
                sf = self.sig_filters[sctr]
                sf_len = self.sig_filter_lens[sctr]
                sig = xzps[sctr][t - sf_len:t]

                # dot filter with signal (remembering to flip filter)
                result += np.dot(sf[::-1], sig)

            # add output feedback component
            ## get relevant output
            output = yzp[t - self.fdbk_filter_len:t]
            ## dot filter with output (remembering to flip filter)
            result += np.dot(self.fdbk_filter[::-1], output)

            # add constant
            result += self.constant

            # add Gaussian noise
            result += np.random.normal(0, self.noise)

            # store output in correct position
            yzp[t] = result

        # remove initial zeros from yzp and return
        return yzp[self.max_filter_len:]
    ref_max = 4 / h  # Starting value of ref period counter
    t_list = np.array([], dtype=int)
    V = E_leak
    V_trace = [V]
    t_trace = [0]

    plt.figure(2)
    plt.subplot(len(t_peaks), 2, 2 * index + 1)
    plt.plot(np.arange(0, t_max, h), spike_train)
    plt.title('Input spike train')

    for t in range(tstop):

        # Compute input
        if spike_train[t]:  # check for input spike
            t_list = cc([t_list, [1]])

        # Calculate synaptic current due to current and past input spikes
        g_syn = np.sum(alpha_func[t_list])
        I_syn = g_syn * (E_syn - V)

        # Update spike times
        if np.any(t_list):
            t_list = t_list + 1
            if t_list[0] == t_a:  # Reached max duration of syn conductance
                t_list = t_list[1:]

        # Compute membrane voltage
        # Euler method: V(t+h) = V(t) + h*dV/dt
        if not ref:
            V = V + h * (-((V - E_leak) * (1 + R * g_ad) / (R * C)) +
Exemple #20
0
	def testget_rotated_atoms(self):
		a=Atoms('C2',[[1,0,1],[0,1,1]])
		a.set_cell([[1,0,1],[0,1,1],[0,0,1]])
		d=lammpsdata(a)
		unit=d.get_rotated_atoms()
		self.assertTrue(cc(unit.cell[:2],[[sqrt(2),0,0],[sqrt(2)/2,sqrt(2)*sqrt(3)/2,0]]))
# plot out vs. in-degree scatter
axs[0,0].scatter(indeg, outdeg)
axs[0,0].set_xlabel('indegree')
axs[0,0].set_ylabel('outdegree')

# plot out & in-degree distributions
axs[0,1].hist(outdeg, bins=NBINS, orientation='horizontal')
axs[0,1].set_ylabel('outdegree')
axs[0,1].set_xlabel('# nodes')

axs[1,0].hist(indeg, bins=NBINS)
axs[1,0].set_xlabel('indegree')
axs[1,0].set_ylabel('# nodes')

# plot percent_indeg & percent_outdeg distributions
axs[1,1].hist(cc([percent_indeg[None,:], percent_outdeg[None,:]]).T, bins=NBINS)
axs[1,1].set_xlabel('% indegree (blue), % outdegree (green)')
axs[1,1].set_ylabel('# nodes')
[set_fontsize(ax, FONTSIZE) for ax in axs.flatten()]


# plot total degree, vs in-out degree difference
fig, axs = plt.subplots(2, 2, facecolor=FACECOLOR, tight_layout=True)

# plot scatter
axs[0,0].scatter(deg, deg_diff)
axs[0,0].set_xlabel('degree')
axs[0,0].set_ylabel('outdegree - indegree')

# plot distributions
axs[0,1].hist(deg_diff, bins=NBINS, orientation='horizontal')
    V_spike = 50 # spike value mV
    ref_max = 4/h # Starting value of ref period counter
    t_list = np.array([], dtype=int)
    V = E_leak
    V_trace = [V]
    t_trace = [0]
    
    fig, axs = plt.subplots(2, 1)
    axs[0].plot(np.arange(0,t_max,h), spike_train)
    axs[0].set_title('Input spike train')

    for t in range(tstop):
    
        # Compute input
        if spike_train[t]: # check for input spike
            t_list = cc([t_list, [1]])
           # print(t_list)
    
        # Calculate synaptic current due to current and past input spikes
        g_syn = np.sum(alpha_func[t_list])
        I_syn = g_syn*(E_syn - V) 
    
        # Update spike times
        if np.any(t_list):
            t_list = t_list + 1
            if t_list[0] == t_a: # Reached max duration of syn conductance
                t_list = t_list[1:]
    
        # Compute membrane voltage
        # Euler method: V(t+h) = V(t) + h*dV/dt
        if not ref:
def fire_neuron(alpha_func, t_peak, t_max, ref=0):
    # alpha func synaptic conductance
    t_a = 100  # Max duration of syn conductance
    g_peak = 0.05  # nS (peak synaptic conductance)
    const = g_peak / (t_peak * np.exp(-1))
    t_vec = np.arange(0, t_a + h, h)
    alpha_func = const * t_vec * (np.exp(-t_vec / t_peak))

    plt.plot(t_vec[:80], alpha_func[:80])
    plt.xlabel('t (in ms)')
    plt.title('Alpha Function (Synaptic Conductance for Spike at t=0)')
    plt.draw()
    #time.sleep(2)

    # capacitance and leak resistance
    C = 0.5  # nF
    R = 40  # M ohms
    print('C = {}'.format(C))
    print('R = {}'.format(R))

    # conductance and associated parameters to simulate spike rate adaptation
    g_ad = 0
    G_inc = 1 / h
    tau_ad = 2

    # Initialize basic parameters
    E_leak = -60  # mV, equilibrium potential
    E_syn = 0  # Excitatory synapse (why is this excitatory?)
    g_syn = 0  # Current syn conductance
    V_th = -40  # spike threshold mV
    V_spike = 50  # spike value mV
    ref_max = 4 / h  # Starting value of ref period counter
    t_list = np.array([], dtype=int)
    V = E_leak
    V_trace = [V]
    t_trace = [0]

    fig, axs = plt.subplots(2, 1)
    axs[0].plot(np.arange(0, t_max, h), spike_train)
    axs[0].set_title('Input spike train')

    nSpikes = 0
    for t in range(tstop):

        # Compute input
        if spike_train[t]:  # check for input spike
            t_list = cc([t_list, [1]])

        # Calculate synaptic current due to current and past input spikes
        g_syn = np.sum(alpha_func[t_list])
        I_syn = g_syn * (E_syn - V)

        # Update spike times
        if np.any(t_list):
            t_list = t_list + 1
            if t_list[0] == t_a:  # Reached max duration of syn conductance
                t_list = t_list[1:]

        # Compute membrane voltage
        # Euler method: V(t+h) = V(t) + h*dV/dt
        if not ref:
            V = V + h * (-((V - E_leak) * (1 + R * g_ad) / (R * C)) +
                         (I_syn / C))
            g_ad = g_ad + h * (-g_ad / tau_ad)  # spike rate adaptation
        else:
            ref -= 1
            V = V_th - 10  # reset voltage after spike
            g_ad = 0

        # Generate spike
        if (V > V_th) and not ref:
            V = V_spike
            ref = ref_max
            g_ad = g_ad + G_inc
            nSpikes += 1

        V_trace += [V]
        t_trace += [t * h]

    axs[1].plot(t_trace, V_trace)
    plt.draw()
    axs[1].set_title('Output spike train')

    return (nSpikes, fig)
Exemple #24
0
def main(val):
    numspikes = 0
    np.random.seed(0)
    # I & F implementation dV/dt = - V/RC + I/C
    h = 1. # step size, Euler method, = dt ms
    t_max= 200 # ms, simulation time period
    tstop = int(t_max/h) # number of time steps
    ref = 0 # refractory period counter

    # Generate random input spikes
    # Note: This is not entirely realistic - no refractory period
    # Also: if you change step size h, input spike train changes too...
    thr = 0.9 # threshold for random spikes
    spike_train = np.random.rand(tstop) > thr

    # alpha func synaptic conductance
    t_a = 100 # Max duration of syn conductance
    t_peak = val # ms
    g_peak = 0.05 # nS (peak synaptic conductance)
    const = g_peak / (t_peak*np.exp(-1));
    t_vec = np.arange(0, t_a + h, h)
    alpha_func = const * t_vec * (np.exp(-t_vec/t_peak))

    '''plt.plot(t_vec[:80], alpha_func[:80])
    plt.xlabel('t (in ms)')
    plt.title('Alpha Function (Synaptic Conductance for Spike at t=0)')
    plt.draw()'''

    # capacitance and leak resistance
    C = 0.5 # nF
    R = 40 # M ohms
    #print 'C = {}'.format(C)
    #print 'R = {}'.format(R)

    # conductance and associated parameters to simulate spike rate adaptation
    g_ad = 0
    G_inc = 1/h
    tau_ad = 2

    # Initialize basic parameters
    E_leak = -60 # mV, equilibrium potential
    E_syn = 0 # Excitatory synapse (why is this excitatory?)
    g_syn = 0 # Current syn conductance
    V_th = -40 # spike threshold mV
    V_spike = 50 # selfpike value mV
    ref_max = 4/h # Starting value of ref period counter
    t_list = np.array([], dtype=int)
    V = E_leak
    V_trace = [V]
    t_trace = [0]

    fig, axs = plt.subplots(2, 1)
    axs[0].plot(np.arange(0,t_max,h), spike_train)
    axs[0].set_title('Input spike train')

    for t in range(tstop):

        # Compute input
        if spike_train[t]: # check for input spike
            t_list = cc([t_list, [1]])

        # Calculate synaptic current due to current and past input spikes
        g_syn = np.sum(alpha_func[t_list])
        I_syn = g_syn*(E_syn - V)

        # Update spike times
        if np.any(t_list):
            t_list = t_list + 1
            if t_list[0] == t_a: # Reached max duration of syn conductance
                t_list = t_list[1:]

        # Compute membrane voltage
        # Euler method: V(t+h) = V(t) + h*dV/dt
        if not ref:
            V = V + h*(-((V-E_leak)*(1+R*g_ad)/(R*C)) + (I_syn/C))
            g_ad = g_ad + h*(-g_ad/tau_ad) # spike rate adaptation
        else:
            ref -= 1
            V = V_th - 10 # reset voltage after spike
            g_ad = 0

        # Generate spike
        if (V > V_th) and not ref:
            numspikes += 1
            V = V_spike
            ref = ref_max
            g_ad = g_ad + G_inc

        V_trace += [V]
        t_trace += [t*h]

    '''