Example #1
0
def verify_fixed_points_through_simulation(num=3):
    fixed_points = np.load(fps_output_fn)

    cann = CANN1D(num=512, k=k, a=a, A=A)

    for i in range(num):
        cann.u[:] = fixed_points[i]
        runner = bp.StructRunner(cann, monitors=['u'], dyn_vars=cann.vars())
        runner(100.)
        plt.plot(runner.mon.ts, runner.mon.u.max(axis=1))
        plt.ylim(0, runner.mon.u.max() + 1)
        plt.show()
def simulation():
    model = HindmarshRose()
    # model.b = 2.5
    runner = bp.StructRunner(
        model,
        monitors=['x', 'y', 'z'],
        inputs=['I', 1.5],
    )
    runner.run(2000.)
    bp.visualize.line_plot(runner.mon.ts, runner.mon.x, legend='x')
    # bp.visualize.line_plot(runner.mon.ts, runner.mon.y, legend='y')
    # bp.visualize.line_plot(runner.mon.ts, runner.mon.z, legend='z')
    plt.show()
Example #3
0
def d4_system():
    model = GJCoupledFHN(2)
    model.gjw = 0.01
    # Iext = bm.asarray([0., 0.1])
    Iext = bm.asarray([0., 0.6])

    # simulation
    runner = bp.StructRunner(model, monitors=['V'], inputs=['Iext', Iext])
    runner.run(300.)
    bp.visualize.line_plot(runner.mon.ts,
                           runner.mon.V,
                           legend='V',
                           plot_ids=list(range(model.num)),
                           show=True)

    # analysis
    def step(vw):
        v, w = bm.split(vw, 2)
        dv = model.dV(v, 0., w, Iext)
        dw = model.dw(w, 0., v)
        return bm.concatenate([dv, dw])

    finder = bp.analysis.SlowPointFinder(f_cell=step)
    # finder.find_fps_with_gd_method(
    #   candidates=bm.random.normal(0., 2., (1000, model.num * 2)),
    #   tolerance=1e-5,
    #   num_batch=200,
    #   opt_setting=dict(method=bm.optimizers.Adam, lr=bm.optimizers.ExponentialDecay(0.05, 1, 0.9999)),
    # )

    finder.find_fps_with_opt_solver(
        candidates=bm.random.normal(0., 2., (1000, model.num * 2)))
    finder.filter_loss(1e-7)
    finder.keep_unique()

    print('fixed_points: ', finder.fixed_points)
    print('losses:', finder.losses)
    if len(finder.fixed_points):
        jac = finder.compute_jacobians(finder.fixed_points)
        for i in range(len(finder.fixed_points)):
            eigval, eigvec = np.linalg.eig(np.asarray(jac[i]))
            plt.figure()
            plt.scatter(np.real(eigval), np.imag(eigval))
            plt.plot([0, 0], [-1, 1], '--')
            plt.xlabel('Real')
            plt.ylabel('Imaginary')
            plt.title(f'FP {i}')
            plt.show()
def simulation(duration=5.):
    dt = 0.1 / 1e3
    # random input uniformly distributed between 120 and 320 pulses per second
    all_ps = bm.random.uniform(120, 320, size=(int(duration / dt), 1))
    jrm = JansenRitModel(num=6,
                         C=bm.array([68., 128., 135., 270., 675., 1350.]))
    runner = bp.StructRunner(jrm,
                             monitors=['y0', 'y1', 'y2', 'y3', 'y4', 'y5'],
                             inputs=['p', all_ps, 'iter', '='],
                             dt=dt)
    runner.run(duration)

    start, end = int(2 / dt), int(duration / dt)
    fig, gs = bp.visualize.get_figure(6, 3, 2, 3)
    for i in range(6):
        fig.add_subplot(gs[i, 0])
        title = 'E' if i == 0 else None
        xlabel = 'time [s]' if i == 5 else None
        bp.visualize.line_plot(runner.mon.ts[start:end],
                               runner.mon.y1[start:end, i],
                               title=title,
                               xlabel=xlabel,
                               ylabel='Hz')
        fig.add_subplot(gs[i, 1])
        title = 'P' if i == 0 else None
        bp.visualize.line_plot(runner.mon.ts[start:end],
                               runner.mon.y0[start:end, i],
                               title=title,
                               xlabel=xlabel)
        fig.add_subplot(gs[i, 2])
        title = 'I' if i == 0 else None
        bp.visualize.line_plot(runner.mon.ts[start:end],
                               runner.mon.y2[start:end, i],
                               title=title,
                               show=i == 5,
                               xlabel=xlabel)
                inh_input = np.random.uniform(inh_bound, exc_input)
                # array created to save the values:
                bg_layer[i] = int(exc_input)
                bg_layer[i + 1] = int(inh_input)
        else:
            bg_layer = None
        return bg_layer


bm.random.seed()
net = CorticalMicrocircuit(conn_type=2,
                           poisson_freq=8.,
                           stim_type=1,
                           bg_type=0)
sps_monitors = [f'{n}.spike' for n in net.layer_name[:-1]]
runner = bp.StructRunner(net, monitors=sps_monitors)
runner.run(1000.)

spikes = np.hstack([runner.mon[name] for name in sps_monitors])
bp.visualize.raster_plot(runner.mon.ts, spikes, show=True)

# bp.visualize.line_plot(runner.mon.ts, runner.mon['L4e.V'], plot_ids=[0, 1, 2], show=True)

# def run1():
# fig, gs = bp.visualize.get_figure(8, 1, col_len=8, row_len=1)
# for i in range(8):
#   fig.add_subplot(gs[i, 0])
#   name = net.layer_name[i]
#   bp.visualize.raster_plot(runner.mon.ts, runner.mon[f'{name}.spike'],
#                            xlabel='Time [ms]' if i == 7 else None,
#                            ylabel=name, show=i == 7)
Example #6
0
    E = bp.models.LIF(num_exc, **pars, method=method)
    I = bp.models.LIF(num_inh, **pars, method=method)
    E.V[:] = bp.math.random.randn(num_exc) * 2 - 55.
    I.V[:] = bp.math.random.randn(num_inh) * 2 - 55.

    # synapses
    we = 0.6 / scale  # excitatory synaptic weight (voltage)
    wi = 6.7 / scale  # inhibitory synaptic weight
    E2E = bp.models.ExpCOBA(E, E, bp.conn.FixedProb(prob=0.02),
                            E=0., g_max=we, tau=5., method=method)
    E2I = bp.models.ExpCOBA(E, I, bp.conn.FixedProb(prob=0.02),
                            E=0., g_max=we, tau=5., method=method)
    I2E = bp.models.ExpCOBA(I, E, bp.conn.FixedProb(prob=0.02),
                            E=-80., g_max=wi, tau=10., method=method)
    I2I = bp.models.ExpCOBA(I, I, bp.conn.FixedProb(prob=0.02),
                            E=-80., g_max=wi, tau=10., method=method)

    super(EINet, self).__init__(E2E, E2I, I2E, I2I, E=E, I=I)


net = EINet(scale=1., method='exp_auto')
# simulation
runner = bp.StructRunner(net,
                         monitors=['E.spike'],
                         inputs=[('E.input', 20.), ('I.input', 20.)])
t = runner.run(100.)
print(t)

# visualization
bp.visualize.raster_plot(runner.mon.ts, runner.mon['E.spike'], show=True)
cann = CANN1D(num=512)

# Smooth tracking #
dur1, dur2, dur3 = 100., 2000., 500.
num1 = int(dur1 / bm.get_dt())
num2 = int(dur2 / bm.get_dt())
num3 = int(dur3 / bm.get_dt())
position = bm.zeros(num1 + num2 + num3)
final_pos = cann.a / cann.tau_v * 0.6 * dur2
position[num1: num1 + num2] = bm.linspace(0., final_pos, num2)
position[num1 + num2:] = final_pos
position = position.reshape((-1, 1))
Iext = cann.get_stimulus_by_pos(position)
runner = bp.StructRunner(cann,
                         inputs=('input', Iext, 'iter'),
                         monitors=['u', 'v'],
                         dyn_vars=cann.vars())
runner(dur1 + dur2 + dur3)
bp.visualize.animate_1D(
  dynamical_vars=[
    {'ys': runner.mon.u, 'xs': cann.x, 'legend': 'u'},
    {'ys': runner.mon.v, 'xs': cann.x, 'legend': 'v'},
    {'ys': Iext, 'xs': cann.x, 'legend': 'Iext'}
  ],
  frame_step=30,
  frame_delay=5,
  show=True,
  save_path='./cann_1d_oscillatory_tracking.gif'
)
Example #8
0
        E2I = ExpCOBA(pre=E,
                      post=I,
                      conn=bp.conn.FixedProb(prob=0.02),
                      E=Ee,
                      g_max=we / scale,
                      tau=taue,
                      method=method)
        I2E = ExpCOBA(pre=I,
                      post=E,
                      conn=bp.conn.FixedProb(prob=0.02),
                      E=Ei,
                      g_max=wi / scale,
                      tau=taui,
                      method=method)
        I2I = ExpCOBA(pre=I,
                      post=I,
                      conn=bp.conn.FixedProb(prob=0.02),
                      E=Ei,
                      g_max=wi / scale,
                      tau=taui,
                      method=method)

        super(COBAHH, self).__init__(E2E, E2I, I2I, I2E, E=E, I=I)


net = COBAHH(scale=1)
runner = bp.StructRunner(net, monitors=['E.spike'])
t = runner.run(100.)
print(t)
bp.visualize.raster_plot(runner.mon.ts, runner.mon['E.spike'], show=True)
Example #9
0
              (bm.pi * r * self.tau) ** 2) / self.tau

    self.int_r = bp.odeint(dr, method=method)
    self.int_v = bp.odeint(dv, method=method)

  def update(self, _t, _dt):
    self.r.value = self.int_r(self.r, _t, self.v, self.delta, _dt)
    self.v.value = self.int_v(self.v, _t, self.r, self.Iext, self.eta, _dt)
    self.Iext[:] = 0.


qif = MeanFieldQIF()


# simulation
runner = bp.StructRunner(qif, inputs=['Iext', 1.], monitors=['r', 'v'])
runner.run(100.)
bp.visualize.line_plot(runner.mon.ts, runner.mon.r, legend='r')
bp.visualize.line_plot(runner.mon.ts, runner.mon.v, legend='v', show=True)


# phase plane analysis
pp = bp.analysis.PhasePlane2D(
  qif,
  target_vars={'r': [0., 4.], 'v': [-3., 3.]},
  resolutions=0.01
)
pp.plot_vector_field()
pp.plot_nullcline()
pp.plot_fixed_point()
pp.show_figure()
Example #10
0
    self.int_e = bp.odeint(de, method=method)
    self.int_i = bp.odeint(di, method=method)

  def update(self, _t, _dt):
    self.e.value = self.int_e(self.e, _t, self.i, self.Iext, _dt)
    self.i.value = self.int_i(self.i, _t, self.e, _dt)
    self.Iext[:] = 0.


model = WilsonCowanModel(2)
model.e[:] = [-0.2, 1.]
model.i[:] = [0.0, 1.]

# simulation
runner = bp.StructRunner(model, monitors=['e', 'i'])
runner.run(100)

fig, gs = bp.visualize.get_figure(2, 1, 3, 8)
fig.add_subplot(gs[0, 0])
bp.visualize.line_plot(runner.mon.ts, runner.mon.e, plot_ids=[0], legend='e', linestyle='--')
bp.visualize.line_plot(runner.mon.ts, runner.mon.i, plot_ids=[0], legend='i', linestyle='--')
fig.add_subplot(gs[1, 0])
bp.visualize.line_plot(runner.mon.ts, runner.mon.e, plot_ids=[1], legend='e')
bp.visualize.line_plot(runner.mon.ts, runner.mon.i, plot_ids=[1], legend='i', show=True)


# phase plane analysis
pp = bp.analysis.PhasePlane2D(
  model,
  target_vars={'e': [-0.2, 1.], 'i': [-0.2, 1.]},
Example #11
0
    def test_hh_model(self):
        class HH(bp.NeuGroup):
            def __init__(self,
                         size,
                         ENa=55.,
                         EK=-90.,
                         EL=-65,
                         C=1.0,
                         gNa=35.,
                         gK=9.,
                         gL=0.1,
                         V_th=20.,
                         phi=5.0,
                         name=None,
                         method='exponential_euler'):
                super(HH, self).__init__(size=size, name=name)

                # parameters
                self.ENa = ENa
                self.EK = EK
                self.EL = EL
                self.C = C
                self.gNa = gNa
                self.gK = gK
                self.gL = gL
                self.V_th = V_th
                self.phi = phi

                # variables
                self.V = bm.Variable(bm.ones(size) * -65.)
                self.h = bm.Variable(bm.ones(size) * 0.6)
                self.n = bm.Variable(bm.ones(size) * 0.32)
                self.spike = bm.Variable(bm.zeros(size, dtype=bool))
                self.input = bm.Variable(bm.zeros(size))

                self.int_h = bp.odeint(self.dh, method=method, show_code=True)
                self.int_n = bp.odeint(self.dn, method=method, show_code=True)
                self.int_V = bp.odeint(self.dV, method=method, show_code=True)

            def dh(self, h, t, V):
                alpha = 0.07 * bm.exp(-(V + 58) / 20)
                beta = 1 / (bm.exp(-0.1 * (V + 28)) + 1)
                dhdt = self.phi * (alpha * (1 - h) - beta * h)
                return dhdt

            def dn(self, n, t, V):
                alpha = -0.01 * (V + 34) / (bm.exp(-0.1 * (V + 34)) - 1)
                beta = 0.125 * bm.exp(-(V + 44) / 80)
                dndt = self.phi * (alpha * (1 - n) - beta * n)
                return dndt

            def dV(self, V, t, h, n, Iext):
                m_alpha = -0.1 * (V + 35) / (bm.exp(-0.1 * (V + 35)) - 1)
                m_beta = 4 * bm.exp(-(V + 60) / 18)
                m = m_alpha / (m_alpha + m_beta)
                INa = self.gNa * m**3 * h * (V - self.ENa)
                IK = self.gK * n**4 * (V - self.EK)
                IL = self.gL * (V - self.EL)
                dVdt = (-INa - IK - IL + Iext) / self.C

                return dVdt

            def update(self, _t, _dt):
                h = self.int_h(self.h, _t, self.V, dt=_dt)
                n = self.int_n(self.n, _t, self.V, dt=_dt)
                V = self.int_V(self.V, _t, self.h, self.n, self.input, dt=_dt)
                self.spike.value = bm.logical_and(self.V < self.V_th,
                                                  V >= self.V_th)
                self.V.value = V
                self.h.value = h
                self.n.value = n
                self.input[:] = 0.

        hh1 = HH(1, method='exp_euler')
        runner1 = bp.StructRunner(hh1,
                                  inputs=('input', 2.),
                                  monitors=['V', 'h', 'n'])
        runner1(100)
        plt.figure()
        plt.plot(runner1.mon.ts, runner1.mon.V, label='V')
        plt.plot(runner1.mon.ts, runner1.mon.h, label='h')
        plt.plot(runner1.mon.ts, runner1.mon.n, label='n')
        # plt.show()

        hh2 = HH(1, method='exp_euler_auto')
        runner2 = bp.StructRunner(hh2,
                                  inputs=('input', 2.),
                                  monitors=['V', 'h', 'n'])
        runner2(100)
        plt.figure()
        plt.plot(runner2.mon.ts, runner2.mon.V, label='V')
        plt.plot(runner2.mon.ts, runner2.mon.h, label='h')
        plt.plot(runner2.mon.ts, runner2.mon.n, label='n')
        plt.show()

        diff = (runner2.mon.V - runner1.mon.V).mean()
        self.assertTrue(diff < 1e0)
            dw = (V + a - b * w) / self.tau
            return dw

        self.int_V = bp.odeint(dV, method=method)
        self.int_w = bp.odeint(dw, method=method)

    def update(self, _t, _dt):
        self.V.value = self.int_V(self.V, _t, self.w, self.Iext, _dt)
        self.w.value = self.int_w(self.w, _t, self.V, self.a, self.b, _dt)
        self.Iext[:] = 0.


model = FitzHughNagumoModel()

# simulation
runner = bp.StructRunner(model, monitors=['V', 'w'], inputs=['Iext', 0.])
runner.run(100.)

bp.visualize.line_plot(runner.mon.ts, runner.mon.V, legend='V')
bp.visualize.line_plot(runner.mon.ts, runner.mon.w, legend='w', show=True)

# phase plane analysis
pp = bp.analysis.PhasePlane2D(
    model=model,
    target_vars={
        'V': [-3, 3],
        'w': [-1, 3]
    },
    pars_update={'Iext': 1.},
    resolutions=0.01,
)
Example #13
0
        interaction = bm.real(bm.fft.ifft2(r * jjft))
        self.u.value = self.u + (-self.u + self.input +
                                 interaction) / self.tau * _dt
        self.input[:] = 0.


cann = CANN2D(length=512, k=0.1)
cann.show_conn()

# encoding
Iext, length = bp.inputs.section_input(
    values=[cann.get_stimulus_by_pos([0., 0.]), 0.],
    durations=[10., 20.],
    return_length=True)
runner = bp.StructRunner(cann,
                         inputs=['input', Iext, 'iter'],
                         monitors=['r'],
                         dyn_vars=cann.vars())
runner.run(length)

bp.visualize.animate_2D(values=runner.mon.r,
                        net_size=(cann.length, cann.length))

# tracking
length = 20
positions = bp.inputs.ramp_input(-bm.pi, bm.pi, duration=length, t_start=0)
positions = bm.stack([positions, positions]).T
Iext = bm.vmap(cann.get_stimulus_by_pos)(positions)
runner = bp.StructRunner(cann,
                         inputs=['input', Iext, 'iter'],
                         monitors=['r'],
                         dyn_vars=cann.vars())
Example #14
0
    self.noise2I = AMPA_One(pre=self.noise_I, post=I, g_max=g_max_ext2I_AMPA)

    # nodes
    self.A = A
    self.B = B
    self.N = N
    self.I = I
    self.IA = IA
    self.IB = IB


# %%
net = DecisionMaking(scale=1.)

# %%
runner = bp.StructRunner(net, monitors=['A.spike', 'B.spike', 'IA.freq', 'IB.freq'],
                         dyn_vars=net.vars(), jit=True)
pre_stimulus_period = 100.
stimulus_period = 1000.
delay_period = 500.
total_period = pre_stimulus_period + stimulus_period + delay_period
t = runner(total_period)
print(f'Used time: {t} s')

# %% [markdown]
# ## Visualization

# %%
fig, gs = bp.visualize.get_figure(4, 1, 3, 10)

t_start = 0.
fig.add_subplot(gs[0, 0])
Example #15
0
  def update(self, _t, _dt):
    m = self.int_m(self.m, _t, self.V, dt=_dt)
    h = self.int_h(self.h, _t, self.V, dt=_dt)
    n = self.int_n(self.n, _t, self.V, dt=_dt)
    V = self.int_V(self.V, _t, self.m, self.h, self.n, self.input, dt=_dt)
    self.spike.value = bm.logical_and(self.V < self.V_th, V >= self.V_th)
    self.V.value = V
    self.h.value = h
    self.n.value = n
    self.m.value = m
    self.input[:] = 0.


model = HH(1)
I = 5.
run = bp.StructRunner(model, inputs=('input', I), monitors=['V'])
run(100)
bp.visualize.line_plot(run.mon.ts, run.mon.V, legend='V', show=True)

# analysis
finder = bp.analysis.SlowPointFinder(lambda h: model.step(h, I))
V = bm.random.normal(0., 5., (1000, model.num)) - 50.
mhn = bm.random.random((1000, model.num * 3))
finder.find_fps_with_opt_solver(candidates=bm.hstack([V, mhn]))
finder.filter_loss(1e-7)
finder.keep_unique()
print('fixed_points: ', finder.fixed_points)
print('losses:', finder.losses)
if len(finder.fixed_points):
  jac = finder.compute_jacobians(finder.fixed_points)
  for i in range(len(finder.fixed_points)):
Example #16
0
        self.input = bm.Variable(bm.zeros(self.num))

        self.int_V = bp.odeint(self.dV, method='rk2')
        self.int_u = bp.odeint(self.du, method='rk2')

    def update(self, _t, _dt):
        V = self.int_V(self.V, _t, self.u, self.input, dt=_dt)
        u = self.int_u(self.u, _t, self.V, dt=_dt)
        spike = V >= 0.
        self.V.value = bm.where(spike, -65., V)
        self.u.value = bm.where(spike, u + 8., u)
        self.input[:] = 0.


neu1 = IzhiJoint(1)
runner = bp.StructRunner(neu1, monitors=['V'], inputs=('input', 20.), dt=0.2)
runner(800)
bp.visualize.line_plot(runner.mon.ts,
                       runner.mon.V,
                       alpha=0.6,
                       legend='V - joint',
                       show=False)

neu2 = IzhiSeparate(1)
runner = bp.StructRunner(neu2, monitors=['V'], inputs=('input', 20.), dt=0.2)
runner(800)
bp.visualize.line_plot(runner.mon.ts,
                       runner.mon.V,
                       alpha=0.6,
                       legend='V - separate',
                       show=True)