예제 #1
0
def visualise_connectivity(S):
    Ns = len(S.source)
    Nt = len(S.target)
    b.figure(figsize=(10, 4))
    b.subplot(121)
    b.plot(b.zeros(Ns), b.arange(Ns), 'ok', ms=10)
    b.plot(b.ones(Nt), b.arange(Nt), 'ok', ms=10)
    for i, j in zip(S.i, S.j):
        b.plot([0, 1], [i, j], '-k')
    b.xticks([0, 1], ['Source', 'Target'])
    b.ylabel('Neuron index')
    b.xlim(-0.1, 1.1)
    b.ylim(-1, max(Ns, Nt))
    b.subplot(122)
    b.plot(S.i, S.j, 'ok')
    b.xlim(-1, Ns)
    b.ylim(-1, Nt)
    b.xlabel('Source neuron index')
    b.ylabel('Target neuron index')
예제 #2
0
파일: snn.py 프로젝트: syntapy/brian_mnist
def Plot(monitor, number):
    #pudb.set_trace()
    br.plot(211)
    if type(monitor) == list or type(monitor) == tuple:
        br.plot(monitor[0].t/br.ms,monitor[0].v[0]/br.mV, label='v')
        #br.plot(monitor[1].t/br.ms,monitor[1].u[0]/br.mV, label='u')
        #br.plot(monitor[2].t/br.ms,monitor[0].ge[0]/br.mV, label='v')
    else:
        br.plot(monitor.t/br.ms,monitor.v[0]/br.mV, label='v')
    #br.plot(monitor[0].t/br.ms,monitor[0].u[0]/br.mV, label='u')
    #br.plot((monitor[2].t)/br.ms,(monitor[2][0]/br.mV), label='ge')
    br.legend()
    br.show()
예제 #3
0
def Plot(monitor, number):
    #pudb.set_trace()
    br.plot(211)
    if type(monitor) == list or type(monitor) == tuple:
        br.plot(monitor[0].t / br.ms, monitor[0].v[0] / br.mV, label='v')
        #br.plot(monitor[1].t/br.ms,monitor[1].u[0]/br.mV, label='u')
        #br.plot(monitor[2].t/br.ms,monitor[0].ge[0]/br.mV, label='v')
    else:
        br.plot(monitor.t / br.ms, monitor.v[0] / br.mV, label='v')
    #br.plot(monitor[0].t/br.ms,monitor[0].u[0]/br.mV, label='u')
    #br.plot((monitor[2].t)/br.ms,(monitor[2][0]/br.mV), label='ge')
    br.legend()
    br.show()
예제 #4
0
    N_traces = 5
    conv_width = 10 * b2.ms
    leaveout_steps = int(conv_width / b2.defaultclock.dt)
    # leaveout_steps = 10
    b2.figure()
    for trace in range(N_traces):
        net = run_model(net=net)
        r1 = net['r1']
        r2 = net['r2']
        r0 = net['r0']
        rI = net['rI']
        # ri1 = net['ri1']
        # ri2 = net['ri2']

        b2.plot(
            r1.smooth_rate(width=conv_width)[:-leaveout_steps] / b2.Hz,
            r2.smooth_rate(width=conv_width)[:-leaveout_steps] / b2.Hz)
    ymin, ymax = b2.ylim()
    xmin, xmax = b2.xlim()
    b2.ylim([min(xmin, ymin), max(xmax, ymax)])
    b2.xlim([min(xmin, ymin), max(xmax, ymax)])

    b2.figure()
    b2.plot(r1.t[:-leaveout_steps] / b2.ms,
            r1.smooth_rate(width=conv_width)[:-leaveout_steps] / b2.Hz,
            label='1')
    b2.plot(r2.t[:-leaveout_steps] / b2.ms,
            r2.smooth_rate(width=conv_width)[:-leaveout_steps] / b2.Hz,
            label='2')
    b2.plot(r0.t[:-leaveout_steps] / b2.ms,
            r0.smooth_rate(width=conv_width)[:-leaveout_steps] / b2.Hz,
예제 #5
0
if not test_mode:
    save_connections()
else:
    np.save(data_path + 'activity/resultPopVecs' + str(num_examples), result_monitor)
    np.save(data_path + 'activity/inputNumbers' + str(num_examples), input_numbers)


#------------------------------------------------------------------------------
# plot results
#------------------------------------------------------------------------------
if rate_monitors:
    b2.figure(fig_num)
    fig_num += 1
    for i, name in enumerate(rate_monitors):
        b2.subplot(len(rate_monitors), 1, 1+i)
        b2.plot(rate_monitors[name].t/b2.second, rate_monitors[name].rate, '.')
        b2.title('Rates of population ' + name)

if spike_monitors:
    b2.figure(fig_num)
    fig_num += 1
    for i, name in enumerate(spike_monitors):
        b2.subplot(len(spike_monitors), 1, 1+i)
        b2.plot(spike_monitors[name].t/b2.ms, spike_monitors[name].i, '.')
        b2.title('Spikes of population ' + name)

if spike_counters:
    b2.figure(fig_num)
    fig_num += 1
    b2.plot(spike_monitors['Ae'].count[:])
    b2.title('Spike count of population Ae')
예제 #6
0
파일: if.py 프로젝트: syntapy/brian_mnist
#Ni = br.NeuronGroup(3, '''dv/dt = (vt - vr)/period : volt (unless refractory)
#                                period: second
#                                fire_once: boolean''', \
#                                threshold='v>vt', reset='v=vr',
#                                refractory='fire_once')
#Ni.period = [1, 1, 7] * br.ms
#Ni.fire_once[:] = [True] * 3

indices = np.asarray([0])
times = np.asarray([6]) * br.ms

Ni = br.SpikeGeneratorGroup(3, indices=indices, times=times)
#Nh = br.NeuronGroup(1, model="""dv/dt=(gtot-v)/(10*ms) : 1
#                                  gtot : 1""")
Nh = br.NeuronGroup(1, model="""v = I :1
                                I : 1""")
S = br.Synapses(Ni, Nh,
           model='''tl : second
                    alpha=exp((tl - t)/tau1) - exp((tl - t)/tau2) : 1
                    w : 1
                    I_post = w*alpha : 1 (summed)
                 ''',
           pre='tl+=t - tl')
S.connect('True')
S.w[:, :] = '(80+rand())'
S.tl[:, :] = '0*second'
M = br.StateMonitor(Nh, 'v', record=True)
br.run(20*br.ms)
br.plot(M[0].t, M[0].v)
br.show()
예제 #7
0
    r[l_idx] = la
    r[r_idx] = ra
    return r * b.Hz


b.defaultclock.dt = 1 * b.ms
b.prefs.codegen.target = 'numpy'

num_parts = 3
theta_max = 25.0
e = env.WormFoodEnv((2, 3), num_parts=num_parts, theta_max=theta_max)

N_i = num_parts * 4
N_h = 200
N_o = num_parts * 4

inp_eq = 'rates: Hz '
inp_th = 'rand() < rates*dt'

inp_group = b.NeuronGroup(N_i, inp_eq, threshold=inp_th)

inp_group.run_regularly('rates=inp_rates(i)', dt=b.defaultclock.dt)
M = b.StateMonitor(inp_group, 'rates', record=True)

b.run(100 * b.ms)

for ri in M.rates:
    b.plot(M.t / b.ms, ri / b.Hz)

b.show()
    # for i in range(N_out):
    synapse_mu.mu = f'(j / {float(N_out)})'

    mon = b2.StateMonitor(synapse_mu, 'w', record=[0, 1])

    mu_vals = np.array(synapse_mu.mu)
    # print(mu_vals.shape)
    # b2.plot(mu_vals[synapse_mu.i == 0])
    # b2.show()

    net = b2.Network(b2.collect())
    net.store('initialised')  # not used...

    net.run(100 * b2.second, report='stdout')

    b2.plot(mon.t / b2.second, mon.w.T / w_max)
    b2.show()

    weights_rates = b2.array(synapse_rates.w)
    rates_weight_histograms = b2.empty((N_bins, N_out))
    for i in range(N_out):
        # brian2 uses i->j synapse syntax, while I use j->i
        mask = synapse_rates.j == i
        rates_weight_histograms[:,
                                i] = np.histogram(weights_rates[mask] / w_max,
                                                  bins=N_bins,
                                                  density=True,
                                                  range=(0., 1.))[0]

    weights_mu = b2.array(synapse_mu.w)
    mu_weight_histograms = b2.empty((N_bins, N_out))
if not test_mode:
    save_connections()
else:
    np.save(data_path + 'activity/resultPopVecs' + str(num_examples), result_monitor)
    np.save(data_path + 'activity/inputNumbers' + str(num_examples), input_numbers)


#------------------------------------------------------------------------------
# plot results
#------------------------------------------------------------------------------
if rate_monitors:
    b2.figure(fig_num)
    fig_num += 1
    for i, name in enumerate(rate_monitors):
        b2.subplot(len(rate_monitors), 1, 1+i)
        b2.plot(rate_monitors[name].t/b2.second, rate_monitors[name].rate, '.')
        b2.title('Rates of population ' + name)

if spike_monitors:
    b2.figure(fig_num)
    fig_num += 1
    for i, name in enumerate(spike_monitors):
        b2.subplot(len(spike_monitors), 1, 1+i)
        b2.plot(spike_monitors[name].t/b2.ms, spike_monitors[name].i, '.')
        b2.title('Spikes of population ' + name)

if spike_counters:
    b2.figure(fig_num)
    fig_num += 1
    b2.plot(spike_monitors['Ae'].count[:])
    b2.title('Spike count of population Ae')
예제 #10
0
oa_group = b.Synapses(op_group, act_group, model=syn_oa.model, on_pre=syn_oa.on_pre)
oa_group.connect(j='i')

# spikemon = b.SpikeMonitor(inp_group)
# spikemon1 = b.SpikeMonitor(neuron_group)
# M = b.StateMonitor(hh_group, ['z', 'zeta'], record=True)
# M1 = b.StateMonitor(ih_group, 'w', record=True)
# M2 = b.StateMonitor(hh_group, 'w', record=True)
# Ma = b.StateMonitor(oa_group, 'a', record=True)

print e.disToFood
b.run(1 * b.second)
print e.disToFood
e.plot()
b.figure()
b.plot(e.d_history)

# b.figure()
# b.plot(spikemon.t / b.ms, spikemon.i, '.k')
# b.xlabel('Time (in ms)')
# b.ylabel('Neuron index')
#
# b.figure()
# b.plot(spikemon1.t / b.ms, spikemon1.i, '.k')
# b.xlabel('Time (in ms)')
# b.ylabel('Neuron index')
#
# b.figure()
# for ai in Ma.a[:5]:
#     b.plot(Ma.t / b.ms, ai)
#
예제 #11
0
    def _plot_slice(time,
                    var,
                    sind,
                    eind,
                    var_name,
                    ind_names,
                    title,
                    unit,
                    folder=None,
                    miny=None,
                    maxy=None):
        """Plot a time slice for a variable recording.

        Args:
            time: The time array.
            var: The recorded values.
            sind: Start index of slice.
            eind: End index of slice.
            var_name: Name of the recorded variable.
            ind_names: Names of the recorded indices.
            title: Plot titel.
            unit: Variable unit.
            folder: Where to store plot.
            miny: Minimum y limit.
            maxy: Maximum y limit.

        Returns:
        """
        if len(var.shape) == 2:
            for i in range(var.shape[0]):
                label = '%s_%d' % (var_name, ind_names[i])

                values = var[i, sind:eind]
                b2.plot(time[sind:eind], values, label=label)
        else:
            label = var_name
            values = var[sind:eind]
            b2.plot(time[sind:eind], values, label=label)

        plt.legend()
        plt.title(title)
        plt.xlabel('time (seconds)')
        unit = str(unit)
        if unit == 'rad':
            plt.ylabel('%s' % (var_name))
        else:
            plt.ylabel('%s (%s)' % (var_name, unit))
        axes = plt.gca()
        # Make sure one also can see min and max vals in plot.
        if miny is not None and maxy is not None:
            eps = 0.01 * (maxy - miny)
            miny -= eps
            maxy += eps
        if miny is not None:
            axes.set_ylim(bottom=miny)
        if maxy is not None:
            axes.set_ylim(top=maxy)
        if folder is not None:
            plot_name = 'plot_%s_%d_%d.png' % (var_name, sind, eind)
            plot_name = os.path.join(folder, plot_name)
            plt.savefig(plot_name)
        plt.close()
예제 #12
0
#                                fire_once: boolean''', \
#                                threshold='v>vt', reset='v=vr',
#                                refractory='fire_once')
#Ni.period = [1, 1, 7] * br.ms
#Ni.fire_once[:] = [True] * 3

indices = np.asarray([0])
times = np.asarray([6]) * br.ms

Ni = br.SpikeGeneratorGroup(3, indices=indices, times=times)
#Nh = br.NeuronGroup(1, model="""dv/dt=(gtot-v)/(10*ms) : 1
#                                  gtot : 1""")
Nh = br.NeuronGroup(1,
                    model="""v = I :1
                                I : 1""")
S = br.Synapses(Ni,
                Nh,
                model='''tl : second
                    alpha=exp((tl - t)/tau1) - exp((tl - t)/tau2) : 1
                    w : 1
                    I_post = w*alpha : 1 (summed)
                 ''',
                pre='tl+=t - tl')
S.connect('True')
S.w[:, :] = '(80+rand())'
S.tl[:, :] = '0*second'
M = br.StateMonitor(Nh, 'v', record=True)
br.run(20 * br.ms)
br.plot(M[0].t, M[0].v)
br.show()
예제 #13
0
    def show_state_monitor(self,
                           monitor,
                           window='',
                           figure_title='',
                           name='Element {}',
                           name_values=None,
                           linestyle='-',
                           xlab='Time (ms)',
                           ylab='',
                           use_grid=True,
                           is_figure=True):
        """
        Plots a line chart for a specific `StateMonitor`.

        Parameters
        ----------
        monitor : str
            Name of the `StateMonitor`.
        window : str, optional
            Name of the window. Default value is ``monitor``.
        figure_title : str, optional
            Name of the figure.
            Default value 'Evolution of ``variable`` over time'.
        name : str, optional
            Name of each set. `{}` is replaced by the set ID.
        name_values list of str, optional
            Values replacing the set IDs for ``name``.
        linestyle : str, optional
            Line style.
        xlab : str, optional
            X-axis label.
        ylab : str, optional
            Y-axis label. Default value is '``variable`` (`dimension`)'.
        use_grid : bool, optional
            Is the grid activated?

        Warnings
        --------
        `dimension` of Volt is "m^2 kg s^-3 A^-1"!
        """
        var = self._state_monitors[monitor]
        values = getattr(self[monitor], var)

        try:
            dim = values.dim
        except AttributeError:
            dim = '1'
        if is_figure:
            figure(monitor if window == '' else window)
            title('Evolution of {} over time'.format(var) if figure_title ==
                  '' else figure_title)
        i = 0
        for v in values:
            plot(
                self[monitor].t / ms,
                v,
                linestyle=linestyle,
                label=(
                    name.format(i if name_values is None else name_values[i])))
            i += 1
        xlabel(xlab)
        ylabel('{} ({})'.format(var, dim) if ylab == '' else ylab)
        if use_grid:
            grid()
        if name != '':
            legend()