Beispiel #1
0
delay = 3.0
syn_dict_stdp={"weight":weight_stdp, "delay":delay, \
               "synapse_model":"stdp_synapse",
               "tau_plus":tau_plus, \
               "lambda":lambd, "alpha":alpha, "mu_plus":mu_plus, \
               "mu_minus":mu_minus,  "Wmax":Wmax, "den_delay":den_delay,
               # set receptor 1 presynaptically, to not generate extra spikes
               "receptor_type": 1}

nest.Connect(neuron_pre, neuron_post, "one_to_one", syn_dict_stdp)

nest.Simulate(sim_time)

conn_id = nest.GetConnections(neuron_pre, neuron_post)
w = nest.GetStatus(conn_id, "weight")

print("Initial weight: ", weight_stdp)
print("Simulated weight: ", w[0])

Wplus = Wmax*lambd
Dt1 = 1.0
w1 = STDPUpdate(weight_stdp, Dt1, tau_plus, tau_minus, Wplus, \
                alpha, mu_plus, mu_minus, Wmax)
Dt2 = -3.0
w2 = STDPUpdate(w1, Dt2, tau_plus, tau_minus, Wplus, \
                alpha, mu_plus, mu_minus, Wmax)

print("Expected theoretical weight: ", w2)

print("dw/w: ", (w2 - w[0])/w2)
Beispiel #2
0
 def _get_delay(self):
     """Synaptic delay in ms."""
     return nest.GetStatus(self.id(), 'delay')[0]
Beispiel #3
0
def execute():
    nest.ResetKernel()

    neuron_params = {
        'E_L': -65.,
        'C_m': 1.0,
        'tau_m': 20.9,
        't_ref': 2.0,
        'V_th': -50.,
        'V_reset': -55.
    }

    # single input neuron
    input_neuron = nest.Create("iaf_psc_alpha", params=neuron_params)

    # single output neuron
    output_neuron = nest.Create("iaf_psc_alpha", params=neuron_params)

    # plastic connection
    nest.CopyModel('stdp_synapse_hom', 'plastic', {'alpha': 0.1, 'Wmax': 1000.})

    syn_spec = {'weight': 200., 'model': 'plastic'}
    nest.Connect(input_neuron, output_neuron, syn_spec=syn_spec)
    connection = nest.GetConnections(input_neuron, output_neuron)

    # voltmeters setup
    monitors = []
    rec_params = {'record_from': ['V_m'], 'withtime': True}
    for node in [input_neuron, output_neuron]:
        voltmeter = nest.Create('multimeter', params=rec_params)
        nest.Connect(voltmeter, node)
        monitors.append(voltmeter[0])

    # simulation
    scales = []
    for t in range(10):  # 10 seconds in total
        state = nest.GetStatus(connection)[0]
        scales.append(state)

        dc = nest.Create("dc_generator")
        nest.SetStatus(dc, [{
            "amplitude": 10.0 if t < 2 else 1.0,
            "start": t*1000.0 + 200.0,
            "stop": t*1000.0 + 220.0
        }])

        nest.ConvergentConnect(dc, input_neuron)

        nest.Simulate(1000.0)

    # simulation
    print scales

    output = []
    for node_id in monitors:
        output.append(nest.GetStatus([node_id], 'events')[0])

    events = np.array([event['V_m'] for event in output])
    fig = multiple_time_series(events, output[0]['times'])

    plt.show()
Beispiel #4
0
def potential_raster_multiple_models(fig, recorders, plot_models, labels,
                                     areas, starting_neurons_list,
                                     number_cells_list, simtime, resolution,
                                     starting_pos):

    pos = starting_pos
    rec_from = ["rate", "V_m"]

    rows = max([len(plot_model) for plot_model in plot_models])
    cols = len(plot_models)

    fig, subplots = plt.subplots(rows,
                                 cols,
                                 sharex=True,
                                 sharey=True,
                                 figsize=(3 * rows, 3 * cols))

    fig.subplots_adjust(hspace=0.4)

    for row in range(rows):

        for col in range(cols):

            plot_model = plot_models[col][row]

            if not len(plot_model) == 2:

                print('Not plotting subplot (%i,%i): no data' % (row, col))

            else:

                population, model = plot_model

                rec = [
                    nd for nd in np.arange(0, len(recorders))
                    if (recorders[nd][1] == population
                        and recorders[nd][2] == model)
                ]
                if not len(rec) == 0:

                    l = rec[0]
                    data = nest.GetStatus(recorders[l][0], keys='events')
                    pop = [
                        nd for nd in nest.GetLeaves(population)[0]
                        if nest.GetStatus([nd], 'model')[0] == model
                    ]

                    if l == 0:
                        rf = rec_from[0]
                    else:
                        rf = rec_from[1]

                    raster = np.zeros(
                        (number_cells_list[row],
                         round((simtime - resolution) / resolution)))
                    senders = data[0]['senders']

                    for neuron in range(0, len(raster)):
                        selected_senders = np.where(
                            senders == pop[neuron +
                                           starting_neurons_list[row]])
                        raster[neuron, :] = (data[0][rf])[selected_senders[0]]

                    ax = subplots[row, col]

                    if l > 0:
                        cax = ax.matshow(raster,
                                         interpolation='none',
                                         aspect='auto',
                                         vmin=-70.0,
                                         vmax=-45.0)
                        ax.axes.get_xaxis().set_ticks([])
                    else:
                        # cax = Vax.matshow(raster,aspect='auto') # original
                        cax = ax.matshow(raster,
                                         interpolation='none',
                                         aspect='auto',
                                         vmin=0.0,
                                         vmax=200.0)  # keiko
                        # fig.colorbar(cax, ticks=[0.0, 100.0, 200.0], orientation='horizontal')  # keiko

                    ax.xaxis.tick_top()
                    plt.setp(
                        ax,
                        yticks=[0, number_cells_list[row]],
                        yticklabels=['0', str(number_cells_list[row] - 1)])
                    # ax.set_ylabel(yleg+model)

    # Add titles and labels
    for subp, label in zip(subplots[0], labels):
        subp.set_title(label)

    for subp, area in zip(subplots[:, 0], areas):
        subp.set_ylabel(area, size='large')

    #fig.tight_layout()

    return fig
Beispiel #5
0
 def source(self):
     """The ID of the pre-synaptic neuron."""
     src = ID(nest.GetStatus(self.id(), 'source')[0])
     src.parent = self.parent.pre
     return src
Beispiel #6
0
    def test_fir_filter(self):
        nestml_model_file = 'FIR_filter.nestml'
        nestml_model_name = 'fir_filter_nestml'
        target_path = '/tmp/fir-filter'
        logging_level = 'INFO'
        module_name = 'nestmlmodule'
        store_log = False
        suffix = '_nestml'
        dev = True

        # Generate the NEST code
        input_path = os.path.join(os.path.realpath(os.path.join(os.path.dirname(__file__), 'resources', nestml_model_file)))
        nest_path = nest.ll_api.sli_func("statusdict/prefix ::")
        to_nest(input_path, target_path, logging_level, module_name, store_log, suffix, dev)
        install_nest(target_path, nest_path)

        t_sim = 101.
        resolution = 0.1

        nest.set_verbosity("M_ALL")
        nest.Install(module_name)

        nest.ResetKernel()

        # Create a fir_filter node
        neuron = nest.Create(nestml_model_name, {"N": 256})

        # Create a spike generator
        spikes = [1.0, 1.0, 1.5, 1.5, 1.5, 6.7, 10.0, 10.5, 10.5, 10.5, 10.5, 11.3, 11.3, 11.4, 11.4, 20., 22.5, 30.,
                  40., 42., 42., 42., 50.5, 50.5, 75., 88., 93., 93.]
        sg = nest.Create("spike_generator", params={"spike_times": spikes})
        nest.Connect(sg, neuron, syn_spec=dict(delay=resolution))

        # Get N (order of the filter)
        n = nest.GetStatus(neuron, "N")[0]
        print("N: {}".format(n))

        # Set filter coefficients
        h = self.generate_filter_coefficients(n)
        nest.SetStatus(neuron, {"h": h})
        print("h: ", h)

        # Multimeter
        multimeter = nest.Create('multimeter')
        nest.SetStatus(multimeter, {'interval': resolution})
        multimeter.set({"record_from": ["y"]})  # output of the filter
        nest.Connect(multimeter, neuron)

        # Spike recorder
        sr = nest.Create("spike_recorder")
        nest.Connect(sg, sr)
        nest.Connect(neuron, sr)

        # Simulate
        nest.Simulate(t_sim)

        # Record from multimeter
        events = multimeter.get("events")
        y = events["y"]
        times = events["times"]
        spike_times = nest.GetStatus(sr, keys='events')[0]['times']

        # Scipy filtering
        spikes, bin_edges = np.histogram(spike_times, np.arange(0, t_sim, resolution))
        output = scipy.signal.lfilter(h, 1, spikes)

        # Plots
        if TEST_PLOTS:
            self.plot_output(spike_times, times, y, title='FIR FILTER (NESTML)',
                             filename='fir_filter_output_nestml.png')
            self.plot_output(spike_times, bin_edges[1:], output, title='FIR FILTER (scipy)',
                             filename='fir_filter_output_scipy.png')

        np.testing.assert_allclose(y, output)
Beispiel #7
0
def topographic_representation(fig,
                               recorders,
                               recorded_models,
                               labels,
                               number_cells,
                               simtime,
                               resolution,
                               rows,
                               cols,
                               start,
                               stop,
                               starting_pos,
                               col_paint,
                               input_data='V_m',
                               area_label=[]):

    col_ind = col_paint
    pos = starting_pos
    counter = 0

    for population, model in recorded_models:

        l = [
            nd for nd in np.arange(0, len(recorders))
            if (recorders[nd][1] == population and recorders[nd][2] == model)
        ][0]
        data = nest.GetStatus(recorders[l][0], keys='events')
        pop = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]

        raster = np.zeros((number_cells, number_cells))
        mult_pos = 0
        senders = data[0]['senders']
        for x in range(0, number_cells):
            for y in range(0, number_cells):

                selected_senders = np.where(senders == pop[mult_pos])
                ind_rec = (data[0][input_data])[selected_senders[0]]
                raster[y, x] = np.sum(
                    ind_rec[int(start /
                                resolution):int(stop / resolution)]) / (
                                    (stop - start) / resolution)
                mult_pos += 1

        Iax = plt.subplot2grid((rows, cols), (pos, col_ind), colspan=1)
        if input_data == 'V_m':
            cax2 = Iax.matshow(raster, aspect='auto', vmin=-70.0, vmax=-45.0)
        else:
            cax2 = Iax.matshow(raster,
                               aspect='auto',
                               vmin=raster.min(),
                               vmax=raster.max())

        Iax.xaxis.tick_bottom()
        Iax.axes.get_xaxis().set_ticks([])
        Iax.axes.get_yaxis().set_ticks([])
        if len(area_label) > 0:
            Iax.set_ylabel(area_label)
        Iax.set_xlabel(labels[counter])
        counter += 1
        col_ind += 1

    if input_data == 'V_m':
        fig.colorbar(cax2, ticks=[-70.0, -57.5, -45.0])
    else:
        fig.colorbar(cax2, ticks=[raster.min(), raster.max()])
Beispiel #8
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# NEST is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST.  If not, see <http://www.gnu.org/licenses/>.

import nest

if not nest.ll_api.sli_func("statusdict/have_music ::"):
    import sys

    print("NEST was not compiled with support for MUSIC, not running.")
    sys.exit()

mmip = nest.Create('music_message_in_proxy')
nest.SetStatus(mmip, {'port_name': 'msgdata'})

# Simulate and get message data with a granularity of 10 ms:
time = 0
while time < 1000:
    nest.Simulate(10)
    data = nest.GetStatus(mmip, 'data')
    print(data)
    time += 10
def from_device(detec,
                neurons=None,
                title=None,
                grayscale=False,
                timeunit="ms"):
    """Plot the membrane potential of a set of neurons recorded by
    the given Voltmeter or Multimeter.

    Parameters
    ----------
    detec : list
        Global id of Voltmeter or Multimeter in a list, e.g. [1]
    neurons : list, optional
        Indices of of neurons to plot
    title : str, optional
        Plot title
    grayscale : bool, optional
        Plot in grayscale
    timeunit : str, optional
        Unit of time

    Raises
    ------
    nest.kernel.NESTError
        Description
    """

    if len(detec) > 1:
        raise nest.kernel.NESTError("Please provide a single voltmeter.")

    type_id = nest.GetDefaults(nest.GetStatus(detec, 'model')[0], 'type_id')
    if not type_id.name in ('voltmeter', 'multimeter'):
        raise nest.kernel.NESTError("Please provide a voltmeter or a \
            multimeter measuring V_m.")
    elif type_id.name == 'multimeter':
        if "V_m" not in nest.GetStatus(detec, "record_from")[0]:
            raise nest.kernel.NESTError("Please provide a multimeter \
                measuring V_m.")
        elif (not nest.GetStatus(detec, "to_memory")[0]
              and len(nest.GetStatus(detec, "record_from")[0]) > 1):
            raise nest.kernel.NESTError("Please provide a multimeter \
                measuring only V_m or record to memory!")

    if nest.GetStatus(detec, "to_memory")[0]:

        timefactor = 1.0
        if not nest.GetStatus(detec)[0]['time_in_steps']:
            if timeunit == "s":
                timefactor = 1000.0
            else:
                timeunit = "ms"

        times, voltages = _from_memory(detec)

        if not len(times):
            raise nest.kernel.NESTError("No events recorded! Make sure that \
                withtime and withgid are set to True.")

        if neurons is None:
            neurons = voltages.keys()

        plotids = []
        for neuron in neurons:
            time_values = numpy.array(times[neuron]) / timefactor

            if grayscale:
                line_style = "k"
            else:
                line_style = ""

            try:
                plotids.append(
                    pylab.plot(time_values,
                               voltages[neuron],
                               line_style,
                               label="Neuron %i" % neuron))
            except KeyError:
                print("INFO: Wrong ID: {0}".format(neuron))

        if not title:
            title = "Membrane potential"
        pylab.title(title)

        pylab.ylabel("Membrane potential (mV)")

        if nest.GetStatus(detec)[0]['time_in_steps']:
            pylab.xlabel("Steps")
        else:
            pylab.xlabel("Time (%s)" % timeunit)

        pylab.legend(loc="best")
        pylab.draw()

        return plotids

    elif nest.GetStatus(detec, "to_file")[0]:
        fname = nest.GetStatus(detec, "filenames")[0]
        return from_file(fname, title, grayscale)
    else:
        raise nest.kernel.NESTError("Provided devices neither records to \
            file, nor to memory.")
    for model in ["iaf_psc_exp", "iaf_psc_exp_ps"]:
        nest.ResetKernel()
        nest.SetKernelStatus({'resolution': h})

        neuron = nest.Create(model)
        voltmeter = nest.Create("voltmeter", params={"interval": h})
        dc = nest.Create("dc_generator", params={"amplitude": stim_current})
        sd = nest.Create("spike_detector", params={"precise_times": True})

        nest.Connect(voltmeter, neuron)
        nest.Connect(dc, neuron)
        nest.Connect(neuron, sd)

        nest.Simulate(simtime)

        vm_status = nest.GetStatus(voltmeter, 'events')[0]
        sd_status = nest.GetStatus(sd, 'events')[0]
        data[h][model] = {
            "vm_times": vm_status['times'],
            "vm_values": vm_status['V_m'],
            "spikes": sd_status['times'],
            "V_th": nest.GetStatus(neuron, 'V_th')[0]
        }

###############################################################################
# After simulation, we plot the results from the simulation. The figure
# illustrates the membrane potential excursion of the two models due to
# injected current simulated for 100 ms for a different timestep in each panel.
# The blue line is the voltage trace of the discrete-time neuron, the red line
# is that of the precise spiking version of the same model.
#
Beispiel #11
0
    vm, sd = build_network(dt)
    '''
    First using build_network the network is build and the handles of
    the spike detector and the voltmeter are stored in vm and sd
    '''

    nest.Simulate(1000.0)
    '''
    The network is simulated using `Simulate`, which takes the desired
    simulation time in milliseconds and advances the network state by
    this amount of time. During simulation, the `spike_detector`
    counts the spikes of the target neuron and the total number is
    read out at the end of the simulation period.
    '''

    potentials = nest.GetStatus(vm, "events")[0]["V_m"]
    times = nest.GetStatus(vm, "events")[0]["times"]
    '''
    The values of the voltage recorded by the voltmeter are read out
    and the values for the membrane potential are stored in potential
    and the corresponding times in the times array
    '''

    pylab.plot(times, potentials, label="dt=%.2f" % dt)
    print("  Number of spikes: {0}".format(nest.GetStatus(sd, "n_events")[0]))
    '''
    Using the pylab library the voltage trace is plotted over time
    '''

    pylab.legend(loc=3)
    pylab.xlabel("time (ms)")
Beispiel #12
0
def simulation(Params):

    #! =================
    #! Import network
    #! =================

    # NEST Kernel and Network settings
    nest.ResetKernel()
    nest.ResetNetwork()
    nest.SetKernelStatus({"local_num_threads": Params['threads'],'resolution': Params['resolution']})
    nest.SetStatus([0],{'print_time': True})

    import network_full_keiko
    reload(network_full_keiko)
    models, layers, conns  = network_full_keiko.get_Network(Params)


    # Create models
    for m in models:
            nest.CopyModel(m[0], m[1], m[2])

    # Create layers, store layer info in Python variable
    for l in layers:
            exec '%s = tp.CreateLayer(l[1])' % l[0]

    # Create connections, need to insert variable names
    for c in conns:
            eval('tp.ConnectLayers(%s,%s,c[2])' % (c[0], c[1]))


    # --------------------------------------------------------------------#
    # ---------- SET IB NEURONS ----------------------------------------- #
    # --------------------------------------------------------------------#

    # 30% of Cortex L56 excitatory neurons are intrinsically bursting(IB) neuron.
    # That is achieved by setting pacemaker current I_h.
    # So select 30% of L56_exc neuron, and change h_g_peak from 0.0 to 1.0.
    # (Other cortical neuron do not have I_h, thus h_g_peak=0.0)

    L56_vertical_idx = [nd for nd in nest.GetLeaves(Vp_vertical)[0] if nest.GetStatus([nd], 'model')[0]=='L56_exc']
    L56_horizontal_idx = [nd for nd in nest.GetLeaves(Vp_horizontal)[0] if nest.GetStatus([nd], 'model')[0]=='L56_exc']

    num_neuron = len(L56_vertical_idx)
    num_ib = int(num_neuron*0.3)

    ridx_vertical = np.random.randint(num_neuron, size=(1,num_ib))[0]
    ridx_horizontal = np.random.randint(num_neuron, size=(1,num_ib))[0]

    for i in range(1,num_ib,1):
        nest.SetStatus([L56_vertical_idx[ridx_vertical[i]]], {'h_g_peak': 1.0})
        nest.SetStatus([L56_horizontal_idx[ridx_horizontal[i]]], {'h_g_peak': 1.0})

    # ==============================
    # initiate network activity
    # ==============================
    #nest.SetStatus(nest.GetLeaves(Retina_layer)[0], {'rate': 20.0})
    #nest.SetStatus(nest.GetLeaves(Retina_layer)[0], {'amplitude': 0.0})
    #nest.Simulate(500.0)

    '''
    initiation_frate = 50
    initiation_time = 500
    for i in range(1, Params['Np']*Params['Np'], 1):
        tmp_rand

    nest.Simulate(initiation_time)
    '''
    #! =================
    #! Recording devices
    #! =================

    nest.CopyModel('multimeter', 'RecordingNode',
            params = {'interval'   : Params['resolution'],
            #'record_from': ['V_m'],
            'record_from': ['V_m',
                            'I_syn_AMPA',
                            'I_syn_NMDA',
                            'I_syn_GABA_A',
                            'I_syn_GABA_B',
                            'g_AMPA',
                            'g_NMDA',
                            'g_GABAA',
                            'g_GABAB',
                            'I_NaP',
                            'I_KNa',
                            'I_T',
                            'I_h'],
            'record_to'  : ['memory'],
            'withgid'    : True,
            'withtime'   : True})

    recorders = []
    for population, model in [(Retina_layer, 'Retina'),
                              (Tp_layer  , 'Tp_exc'),
                              (Tp_layer  , 'Tp_inh'),
                              (Vp_vertical, 'L4_exc'),
                              (Vp_horizontal, 'L4_exc')]:
        rec = nest.Create('RecordingNode')
        recorders.append([rec,population,model])
        if (model=='Retina'):
            nest.SetStatus(rec,{'record_from': ['rate']})
        tgts = [nd for nd in nest.GetLeaves(population)[0] if nest.GetStatus([nd], 'model')[0]==model]
        nest.Connect(rec, tgts)

    #! =================
    #! Spike detector
    #! =================
    detectors = []
    retina_failed_detectors = []
    for population, model in [(Retina_layer, 'Retina'),
                              (Tp_layer  , 'Tp_exc'),
                              (Tp_layer  , 'Tp_inh'),
                              (Vp_vertical, 'L4_exc'),
                              (Vp_horizontal, 'L4_exc')]:
        rec = nest.Create('spike_detector', params={"withgid": True, "withtime": True})
        #rec = nest.Create('spike_detector')
        detectors.append([rec,population,model])
        tgts = [nd for nd in nest.GetLeaves(population)[0] if nest.GetStatus([nd], 'model')[0]==model]
        if model == 'Retina':
            for t in tgts:
                try:
                    #nest.Connect(rec, [t])
                    nest.Connect([t], rec)
                    #print('connected %d' % t)
                except:
                    print('%d did not work' % t)
                    retina_failed_detectors.append(t)
        else:
            nest.Connect(tgts, rec)

    sg = [nd for nd in nest.GetLeaves(Retina_layer)[0] if nest.GetStatus([nd], 'model')[0] == 'Retina']

    # ====================
    # Set inputs
    # ====================
    retina_spikes = input_util.create_movie_input(Params)

    num_files = retina_spikes.shape[0]
    num_retina = retina_spikes.shape[1]
    if num_retina != Params['Np']*Params['Np']:
        print('num_retina should be equal as Np*Np')


    for i in range(0, num_retina, 1):

        src_firing_times = np.where(retina_spikes.transpose()[i])[0] + 1
        firing_times = []

        if len(src_firing_times) > 0:
            for l in range(0, int(Params['intervals'] / num_files) + 1, 1):
                offset = float(l*num_files)
                tmp = src_firing_times + offset
                firing_times = firing_times + tmp.astype(float).tolist()

            nest.SetStatus([sg[i]], {'spike_times': firing_times})
        else:
            nest.SetStatus([sg[i]], {'spike_times': [1.0]})



    '''
    for l in range(0, int(Params['intervals'] / num_files) + 1, 1):

        for i in range(0, num_retina, 1):
            tmp_spk = nest.GetStatus([sg[i]])[0]['spike_times']
            spk = tmp_spk.tolist()
            spk.append( float(l*num_retina+(i+1)) )
            nest.SetStatus([sg[i]],{'spike_times': spk})
    '''

    #! ====================
    #! Initiation
    #! ====================
    #nest.Simulate(num_files)
    nest.Simulate(500.0)


    #! ====================
    #! Simulation
    #! ====================
    nest.Simulate(Params['intervals'])



    #! ====================
    #! Save Results
    #! ====================

    print('save recorders data')
    # Set folder
    #rootdir = '/home/kfujii2/newNEST2/ht_model_pablo_based/data/'
    #expdir = 'random/'
    # expdir = 'random_full/'
    # expdir = 'structured_full/'
    # data_folder = rootdir + expdir
    data_folder = Params['data_folder']

    if not os.path.isdir(data_folder):
        os.makedirs(data_folder)

    # To save spike data, set pairs of population id and its name
    population_name = [ {'population': Retina_layer, 'name': 'Retina'},
                        {'population': Vp_vertical, 'name': 'Vp_v'},
                        {'population': Vp_horizontal, 'name': 'Vp_h'},
                        {'population': Rp_layer, 'name': 'Rp'},
                        {'population': Tp_layer, 'name': 'Tp'},
                        {'population': Vs_vertical, 'name': 'Vs_v'},
                        {'population': Vs_horizontal, 'name': 'Vs_h'}]

    for rec, population, model in recorders:

        # Get name of population
        for p in range(0, len(population_name), 1):
            if population_name[p]['population'] == population:
                p_name = population_name[p]['name']

        data = nest.GetStatus(rec)[0]['events']

        if model == 'Retina':
            scipy.io.savemat(data_folder + '/recorder_' + p_name + '_' + model + '.mat',
                             mdict={'senders': data['senders'],
                                    'rate': data['rate']})
        else:
            scipy.io.savemat(data_folder + '/recorder_' + p_name + '_' + model + '.mat',
                             mdict={'senders': data['senders'],
                                    'V_m': data['V_m'],
                                    'I_syn_AMPA': data['I_syn_AMPA'],
                                    'I_syn_NMDA': data['I_syn_NMDA'],
                                    'I_syn_GABA_A': data['I_syn_GABA_A'],
                                    'I_syn_GABA_B': data['I_syn_GABA_B'],
                                    'g_AMPA': data['g_AMPA'],
                                    'g_NMDA': data['g_NMDA'],
                                    'g_GABAA': data['g_GABAA'],
                                    'g_GABAB': data['g_GABAB']} )



    print('save raster images')
    plt.close()
    for rec, population, model in detectors:
        spikes = nest.GetStatus(rec, 'events')[0]

        # Get name of population
        for p in range(0, len(population_name), 1):
            if population_name[p]['population'] == population:
                p_name = population_name[p]['name']

        if len(nest.GetStatus(rec)[0]['events']['senders']) > 3:
            raster = raster_plot.from_device(rec, hist=True)
            pylab.title( p_name + '_' + model )
            f = raster[0].figure
            f.set_size_inches(15, 9)
            f.savefig(data_folder + 'spikes_' + p_name + '_' + model + '.png', dpi=100)
            plt.close()

            # Set filename and save spike data
            filename = data_folder + 'spike_' + p_name + '_' + model + '.pickle'
            pickle.dump(spikes, open(filename, 'w'))
            scipy.io.savemat(data_folder + '/spike_' + p_name + '_' + model + '.mat', mdict={'senders': spikes['senders'], 'times': spikes['times']})

    shutil.copy2('network_full_keiko.py', Params['data_folder'] + 'network_full_keiko.py')
    shutil.copy2('figure_3_plot.py', Params['data_folder'] + 'figure_3_plot.py')
    shutil.copy2('main.py', Params['data_folder'] + 'main.py')
    #scipy.io.savemat(data_folder + '/retina_failed_detectors.mat', mdict={'detectors': retina_failed_detectors})
    scipy.io.savemat(data_folder + '/retina_spike_times.mat', mdict={'spike_times': retina_spikes})

    print('end')
pn2 = nest.Create('parrot_neuron')

nest.Connect(mg, pn1)
nest.Connect(mg, pn2)
nest.Connect(pn1, sd)
nest.Connect(pn2, sd)

nest.SetDefaults('static_synapse', {'weight': 1.0, 'receptor_type': 0})
nest.Connect(pn1, cd)

nest.SetDefaults('static_synapse', {'weight': 1.0, 'receptor_type': 1})
nest.Connect(pn2, cd)

nest.Simulate(T)

n_events = nest.GetStatus(cd)[0]['n_events']
n1 = n_events[0]
n2 = n_events[1]

lmbd1 = (n1 / (T - tau_max)) * 1000.0
lmbd2 = (n2 / (T - tau_max)) * 1000.0

h = 0.1
tau_max = 100.0  # ms correlation window
t_bin = 10.0  # ms bin size

spikes = nest.GetStatus(sd)[0]['events']['senders']

sp1 = find(spikes[:] == 4)
sp2 = find(spikes[:] == 5)
"""
Start simulation
"""

wuptime = 100.
nest.Simulate(wuptime)

simtime = 2000.
nest.Simulate(simtime)


"""
Get data from memory
"""

sdE = nest.GetStatus(sd, 'events')[0]
ts, gids = sdE['times'], sdE['senders']

idx = ts > wuptime
ts, gids = ts[idx]-wuptime, gids[idx]


"""
Get data from file
"""

# sd_id = 18003
# output_file = 'EI_networks_sequence_20180417-091947'
# data = []
# for i in range(4):
#     d = np.loadtxt('./Data/%s-%s-%s.gdf' % (output_file, sd[0], i))
Beispiel #15
0
    x_start = x_starts[i] * scale
    x_end  = x_ends[i] * scale
    y_start = y_starts[i] * scale
    y_end  = y_ends[i] * scale
    # x and y distances
    x_dist = x_end - x_start
    y_dist = y_end - y_start
    step_x = x_dist / steps_per_border
    step_y = y_dist / steps_per_border    
    for n in range(0, steps_per_border): rat_x.append(x_start + n*step_x)
    for m in range(0, steps_per_border): rat_y.append(y_start + m*step_y)
nest.SetStatus(border_cells, {"rat_pos_x": rat_x})
nest.SetStatus(border_cells, {"rat_pos_y": rat_y})

# run simulation
nest.Simulate(sim_time)

# get results
dSD = nest.GetStatus(spike_detectors,keys='events')
evs = []
ts = []
for d in dSD: 
    evs.append(d["senders"])
    ts.append(d["times"])

# plot results
pylab.figure(1)
for i in range(len(ts)):
    pylab.plot(ts[i], evs[i], ".")
pylab.show()
Beispiel #16
0
    def do_the_nest_simulation(self):
        """
        This function is where calls to NEST reside.
        Returns the generated pre- and post spike sequences
        and the resulting weight established by STDP.
        """
        nest.set_verbosity('M_WARNING')
        nest.ResetKernel()
        nest.SetKernelStatus({'resolution': self.resolution})

        neurons = nest.Create(
            "parrot_neuron",
            2,
            params=self.neuron_parameters)
        presynaptic_neuron = neurons[0]
        postsynaptic_neuron = neurons[1]

        generators = nest.Create(
            "poisson_generator",
            2,
            params=({"rate": self.presynaptic_firing_rate,
                     "stop": (self.simulation_duration - self.hardcoded_trains_length)},
                    {"rate": self.postsynaptic_firing_rate,
                     "stop": (self.simulation_duration - self.hardcoded_trains_length)}))
        presynaptic_generator = generators[0]
        postsynaptic_generator = generators[1]

        # While the random sequences, fairly long, would supposedly
        # reveal small differences in the weight change between NEST
        # and ours, some low-probability events (say, coinciding
        # spikes) can well not have occured. To generate and
        # test every possible combination of pre/post precedence, we
        # append some hardcoded spike sequences:
        # pre: 1       5 6 7   9    11 12 13
        # post:  2 3 4       8 9 10    12
        (
            hardcoded_pre_times,
            hardcoded_post_times
        ) = [
            [
                self.simulation_duration - self.hardcoded_trains_length + t
                for t in train
            ] for train in (
                (1, 5, 6, 7, 9, 11, 12, 13),
                (2, 3, 4, 8, 9, 10, 12)
            )
        ]

        spike_senders = nest.Create(
            "spike_generator",
            2,
            params=({"spike_times": hardcoded_pre_times},
                    {"spike_times": hardcoded_post_times})
        )
        pre_spike_generator = spike_senders[0]
        post_spike_generator = spike_senders[1]

        # The recorder is to save the randomly generated spike trains.
        spike_recorder = nest.Create("spike_recorder")

        nest.Connect(presynaptic_generator + pre_spike_generator, presynaptic_neuron,
                     syn_spec={"synapse_model": "static_synapse"})
        nest.Connect(postsynaptic_generator + post_spike_generator, postsynaptic_neuron,
                     syn_spec={"synapse_model": "static_synapse"})
        nest.Connect(presynaptic_neuron + postsynaptic_neuron, spike_recorder,
                     syn_spec={"synapse_model": "static_synapse"})
        # The synapse of interest itself
        nest.Connect(presynaptic_neuron, postsynaptic_neuron,
                     syn_spec=self.synapse_parameters)
        plastic_synapse_of_interest = nest.GetConnections(synapse_model=self.synapse_parameters["synapse_model"])

        nest.Simulate(self.simulation_duration)

        all_spikes = nest.GetStatus(spike_recorder, keys='events')[0]
        pre_spikes = all_spikes['times'][all_spikes['senders'] == presynaptic_neuron.tolist()[0]]
        post_spikes = all_spikes['times'][all_spikes['senders'] == postsynaptic_neuron.tolist()[0]]
        weight = nest.GetStatus(plastic_synapse_of_interest, keys='weight')[0]
        return (pre_spikes, post_spikes, weight)
    nest.SetStatus(dc, {'amplitude': I_dep})
    nest.Simulate(t_sim_dep)

    nest.SetStatus(dc, {'amplitude': I_hyp})
    nest.Simulate(t_sim_hyp)

###############################################################################
# We now fetch the data recorded by the multimeter. The data are returned as
# a dictionary with entry ``times`` containing timestamps for all recorded
# data, plus one entry per recorded quantity.
#
# All data is contained in the ``events`` entry of the status dictionary
# returned by the multimeter. Because all NEST function return arrays,
# we need to pick out element `0` from the result of ``GetStatus``.

data = nest.GetStatus(mm)[0]['events']
t = data['times']

###############################################################################
# The next step is to plot the results. We create a new figure, add a single
# subplot and plot at first membrane potential and threshold.

fig = plt.figure()
Vax = fig.add_subplot(111)
Vax.plot(t, data['V_m'], 'b-', lw=2, label=r'$V_m$')
Vax.plot(t, data['theta'], 'g-', lw=2, label=r'$\Theta$')
Vax.set_ylim(-80., 0.)
Vax.set_ylabel('Voltageinf [mV]')
Vax.set_xlabel('Time [ms]')

###############################################################################
Beispiel #18
0
def runNestModel(model_type, neuron_config, amp_times, amp_vals, dt_ms,
                 simulation_time_ms):
    """
    Creates and runs four NEST glif neurons and returns the voltages and spike-times
    One neuron is without synaptic port, the other three are with 2 synaptic ports (one port with time constant of 2.0ms and one port is 1.0ms)
    The first neuron is connected the first port of the second neuron
    The first neuron is connected the second port of the third neuron
    The first neuron is also connected both ports of the fourth neuron
    The weights between first neuron and other neurons are all 1000.0
    """

    # By default NEST has a 0.1 ms resolution
    nest.ResetKernel()
    nest.SetKernelStatus({'resolution': dt_ms})

    n = 4
    w = 1000.0
    syn_tau = [2.0, 1.0]
    neurons = []
    if model_type == asdk.LIF:
        neurons.append(create_lif(neuron_config))
        for i in range(n - 1):
            neurons.append(create_lif_psc(neuron_config, syn_tau))
    elif model_type == asdk.LIF_ASC:
        neurons.append(create_lif_asc(neuron_config))
        for i in range(n - 1):
            neurons.append(create_lif_asc_psc(neuron_config, syn_tau))
    elif model_type == asdk.LIF_R:
        neurons.append(create_lif_r(neuron_config))
        for i in range(n - 1):
            neurons.append(create_lif_r_psc(neuron_config, syn_tau))
    elif model_type == asdk.LIF_R_ASC:
        neurons.append(create_lif_r_asc(neuron_config))
        for i in range(n - 1):
            neurons.append(create_lif_r_asc_psc(neuron_config, syn_tau))
    elif model_type == asdk.LIF_R_ASC_A:
        neurons.append(create_lif_r_asc_a(neuron_config))
        for i in range(n - 1):
            neurons.append(create_lif_r_asc_a_psc(neuron_config, syn_tau))

    # Create voltmeter and spike reader
    voltmeters = []
    spikedetectors = []
    for i in range(n):
        voltmeters.append(
            nest.Create("voltmeter",
                        params={
                            "withgid": True,
                            "withtime": True,
                            'interval': dt_ms
                        }))
        # grid spike time
        #spikedetectors.append(nest.Create("spike_detector", params={"withgid": True, "withtime": True,  "precise_times": False}))
        # precise spike time
        spikedetectors.append(
            nest.Create("spike_detector",
                        params={
                            "withgid": True,
                            "withtime": True
                        }))

        nest.Connect(voltmeters[i], neurons[i])
        if i != 0 and i < n - 1:
            nest.Connect(neurons[0],
                         neurons[i],
                         syn_spec={
                             'delay': dt_ms,
                             'weight': w,
                             'receptor_type': i
                         })
        elif i == n - 1:
            nest.Connect(neurons[0],
                         neurons[i],
                         syn_spec={
                             'delay': dt_ms,
                             'weight': w,
                             'receptor_type': i - 2
                         })
            nest.Connect(neurons[0],
                         neurons[i],
                         syn_spec={
                             'delay': dt_ms,
                             'weight': w,
                             'receptor_type': i - 1
                         })

        nest.Connect(neurons[i], spikedetectors[i])

    # Step current for first neuron
    scg = nest.Create("step_current_generator",
                      params={
                          'amplitude_times': amp_times[1:],
                          'amplitude_values': np.array(amp_vals[1:]) * 1.0e12
                      })  # convert to pF
    nest.Connect(scg, neurons[0], syn_spec={'delay': dt_ms})

    # Simulate, grab run values and return
    nest.Simulate(simulation_time_ms)

    # output
    voltages = []
    times = []
    spike_times = []

    for i in range(n):
        voltages.append(nest.GetStatus(voltmeters[i])[0]['events']['V_m'])
        times.append(nest.GetStatus(voltmeters[i])[0]['events']['times'])
        spike_times.append(
            nest.GetStatus(spikedetectors[i])[0]['events']['times'])

    return times, voltages, spike_times
Beispiel #19
0
nest.Connect(input_generators,
             exc_neurons + inh_neurons,
             conn_spec=gen_to_neurons_dict['conn_spec'],
             syn_spec=gen_to_neurons_dict['syn_spec'])

# Defining Recorders
target_recorder_dict = {'record_from': ['V_m', 'inc_weight_sum']}
target_recorder = nest.Create("multimeter", 4, params=target_recorder_dict)
nest.Connect(target_recorder, exc_neurons[3:7], conn_spec='one_to_one')

# Defining Spike Recorder
spike_recorder = nest.Create("spike_detector", 1)
nest.Connect(exc_neurons, spike_recorder)

nest.Simulate(30000)

target_recorder_records = nest.GetStatus(target_recorder, 'events')

plt.figure()
plt.plot(target_recorder_records[0]['times'][2000:3000],
         target_recorder_records[0]['inc_weight_sum'][2000:3000])

nest.raster_plot.from_device(spike_recorder)

plt.figure()
plt.plot(target_recorder_records[0]['times'][2000:3000],
         target_recorder_records[0]['V_m'][2000:3000])

plt.show()
Beispiel #20
0
def main():

    # Pop is the dictionary that will contain the Nest IDs of all populations in the model
    #-------------------------
    print 'Creating neurons'

    # creation of STN neurons
    #-------------------------
    nbSim['STN'] = 10.
    print '* STN:', nbSim['STN'], 'neurons with parameters:', BGparams['STN']

    Pop['STN'] = nest.Create("iaf_psc_alpha_multisynapse",
                             int(nbSim['STN']),
                             params=BGparams['STN'])

    #-------------------------
    # creation of external inputs (ctx, CMPf)
    #-------------------------
    rate = {
    }  # the dictionary used to store the desired discharge rates of the various Poisson generators that will be used as external inputs

    # CSN
    #-------------------------
    #Pop['CSN']  = nest.Create('poisson_generator')
    #nest.SetStatus(Pop['CSN'],{'rate': 2.0})

    # PTN
    #-------------------------
    nbSim['PTN'] = 5 * nbSim['STN']
    rate['PTN'] = 15.
    print '* PTN:', nbSim['PTN'], 'Poisson generators with avg rate:', rate[
        'PTN']
    Pop['PTN'] = nest.Create('poisson_generator', int(nbSim['PTN']))
    nest.SetStatus(Pop['PTN'], {'rate': rate['PTN']})

    connect('ex', 'PTN', 'STN', inDegree=5)

    # CMPf
    #-------------------------
    nbSim['CMPf'] = nbSim['STN']
    rate['CMPf'] = 4.
    print '* CMPf:', nbSim['CMPf'], 'Poisson generators with avg rate:', rate[
        'CMPf']
    Pop['CMPf'] = nest.Create('poisson_generator', int(nbSim['CMPf']))
    nest.SetStatus(Pop['CMPf'], {'rate': rate['CMPf']})

    connect('ex', 'CMPf', 'STN', inDegree=1)

    # Fake GPe
    #-------------------------
    nbSim['GPe'] = int(
        neuronCounts['GPe'] / neuronCounts['STN']) * nbSim['STN']
    rate['GPe'] = 62.6
    print '* GPe:', nbSim['GPe'], 'Poisson generators with avg rate:', rate[
        'GPe']
    Pop['GPe'] = nest.Create('poisson_generator', int(nbSim['GPe']))
    nest.SetStatus(Pop['GPe'], {'rate': rate['GPe']})

    connect('in',
            'GPe',
            'STN',
            inDegree=int(neuronCounts['GPe'] / neuronCounts['STN']))

    #-------------------------
    # measures
    #-------------------------

    mSTN = nest.Create("multimeter")
    nest.SetStatus(mSTN, {
        "withtime": True,
        "record_from": ["V_m", "currents"]
    })
    nest.Connect(mSTN, Pop['STN'])

    spkDetect = nest.Create("spike_detector",
                            params={
                                "withgid": True,
                                "withtime": True
                            })
    nest.Connect(Pop['STN'], spkDetect)

    # Simulation
    #-------------------------
    nest.Simulate(simDuration)

    # Experimental estimation of the firing rate:
    print '\n Spike Detector n_events', nest.GetStatus(spkDetect,
                                                       'n_events')[0]
    expeRate = nest.GetStatus(spkDetect, 'n_events')[0] / float(
        nbSim['STN'] * simDuration)
    print '\n Rate:', expeRate * 1000, 'Hz'

    # Displays
    #-------------------------

    showSynCurr = False
    showSTNVolt = False

    #print nest.GetStatus(mSTN)
    #print "============================="
    #print nest.GetStatus(mSTN)[0]

    dmSTN = nest.GetStatus(mSTN)[0]
    VmSTN = dmSTN["events"]["V_m"]
    ImSTN = dmSTN["events"]["currents"]
    tSTN = dmSTN["events"]["times"]

    dSD = nest.GetStatus(spkDetect, keys="events")[0]
    evs = dSD["senders"]
    ts = dSD["times"]

    if interactive:
        pylab.figure('STN spikes')
        pylab.plot(ts, evs, ".")

        if showSTNVolt:
            pylab.figure('STN Voltage')
            pylab.plot(tSTN, VmSTN)

        if (showSynCurr):
            pylab.figure("STN input PSPs")
            pylab.plot(tSTN, ImSTN)

        pylab.show()
Beispiel #21
0
def potential_raster(fig, recorders, recorded_models, starting_neuron,
                     number_cells, simtime, resolution, rows, cols,
                     starting_pos):

    pos = starting_pos
    rec_from = ["rate", "V_m"]

    for population, model in recorded_models:

        l = [
            nd for nd in np.arange(0, len(recorders))
            if (recorders[nd][1] == population and recorders[nd][2] == model)
        ][0]
        data = nest.GetStatus(recorders[l][0], keys='events')
        pop = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]

        # Retina layer always the first (l=0)
        if l == 0:
            rf = rec_from[0]
        else:
            rf = rec_from[1]

        raster = np.zeros(
            (number_cells, round((simtime - resolution) / resolution)))
        senders = data[0]['senders']

        for neuron in range(0, len(raster)):
            selected_senders = np.where(senders == pop[neuron +
                                                       starting_neuron])
            raster[neuron, :] = (data[0][rf])[selected_senders[0]]

        Vax = plt.subplot2grid((rows, cols), (pos, 0), colspan=cols)

        if l > 0:
            cax = Vax.matshow(raster,
                              interpolation='none',
                              aspect='auto',
                              vmin=-70.0,
                              vmax=-45.0)
            Vax.axes.get_xaxis().set_ticks([])
        else:
            # cax = Vax.matshow(raster,aspect='auto') # original
            # cax = Vax.matshow(raster, interpolation='none', aspect='auto',vmin=0.0,vmax=200.0) # keiko
            # fig.colorbar(cax,ticks=[0.0, 100.0, 200.0],orientation='horizontal') # keiko
            cax = Vax.matshow(raster,
                              interpolation='none',
                              aspect='auto',
                              vmin=np.min(raster),
                              vmax=np.max(raster))  # Tom
            fig.colorbar(cax,
                         ticks=[np.min(raster), np.max(raster)],
                         orientation='horizontal')  # Tom

        Vax.xaxis.tick_top()
        plt.setp(Vax,
                 yticks=[0, number_cells],
                 yticklabels=['0', str(number_cells - 1)])
        Vax.set_ylabel(model)
        pos += 1

    fig.colorbar(cax, ticks=[-70.0, -57.5, -45.0], orientation='horizontal')
Beispiel #22
0
N_rec= 50
nest.Connect(nodes_E[:N_rec], spikes_E)
nest.Connect(nodes_I[:N_rec], spikes_I)


simtime=300
nest.Simulate(simtime)

msd=1000
n_vp=nest.GetKernelStatus('total_num_virtual_procs')
msdrange1=range(msd, msd+n_vp)
pyrngs=[numpy.random.RandomState(s) for s in msdrange1]
msdrange2= range(msd+n_vp+1, msd+1+2*n_vp)
nest.SetKernelStatus({'grng_seed': msd+n_vp, 'rng_seeds':msdrange2})

node_info=nest.GetStatus(nodes)
local_nodes=[(ni['global_id'], ni['vp']) for ni in node_info if ni['local']]

for gid, vp in local_nodes:
  nest.SetStatus([gid], {'V_m':pyrngs[vp].uniform(-V_th, V_th)})



pylab.figure()
V_E=nest.GetStatus(nodes_E[:N_rec], 'Vm')
pylab.hist(V_E, bins=10)
pylab.figure()
ex_conns=nest.GetConnections(nodes_E[:N_rec], synapse_model='excitatory')

w= nest.GetStatus(ex_conns, 'weight')
pylab.hist(w, bins=100)
nest.Connect(mm, nrn)

###############################################################################
# We are now ready to simulate.

nest.Simulate(t_sim)

###############################################################################
# We now fetch the data recorded by the multimeter. The data are returned as
# a dictionary with entry ``times`` containing timestamps for all
# recorded data, plus one entry per recorded quantity.
# All data is contained in the ``events`` entry of the status dictionary
# returned by the multimeter. Because all NEST function return arrays,
# we need to pick out element `0` from the result of ``GetStatus``.

data = nest.GetStatus(mm)[0]['events']
t = data['times']

###############################################################################
# The following function turns a name such as ``I_NaP`` into proper TeX code
# :math:`I_{\mathrm{NaP}}` for a pretty label.


def texify_name(name):
    return r'${}_{{\mathrm{{{}}}}}$'.format(*name.split('_'))

###############################################################################
# The next step is to plot the results. We create a new figure, and add one
# subplot each for membrane and threshold potential, synaptic conductances,
# and intrinsic currents.
def adjust_weight(adjacency_matrix=None,
                  burstrate_target=BURSTRATE_TARGET,
                  burstrate_tol=BURSTRATE_TOL,
                  weight=JE_WEIGHT_INIT,
                  noise_weight=NOISE_WEIGHT,
                  noise_rate=NOISE_RATE,
                  resolution=RESOLUTION,
                  simtime=SIMTIME_ADAPT,
                  maxiter_adapt=MAXITER_ADAPT,
                  verbose=True,
                  print_time=False,
                  ):

    if adjacency_matrix is None:
        # construct a default network
        adjacency_matrix = fake_network.construct_network()

    # convert into network_object
    network_obj = adjacency2netobj(adjacency_matrix)

    adaptParList = []
    burst_rate = -1
    adaptation_iteration = 1
    last_burst_rates = []
    last_JEs = []

    if verbose:
        print "Starting adaptation phase..."

    while abs(burst_rate - burstrate_target) > burstrate_tol:

        if (len(last_burst_rates) < 2
                or last_burst_rates[-1] == last_burst_rates[-2]):

            if len(last_burst_rates) > 0:
                if verbose:
                    print 'Auto-burst stage II. - changing weight by 10%'
                if burst_rate > burstrate_target:
                    weight *= 0.9
                else:
                    weight *= 1.1
            else:
                if verbose:
                    print 'Auto-burst stage I. - initial run'
        else:
            if verbose:
                print 'Auto-burst stage III. - linear extrapolation'
            weight = (((burstrate_target - last_burst_rates[-2])
                       * (last_JEs[-1] - last_JEs[-2])
                       / (last_burst_rates[-1] - last_burst_rates[-2]))
                      + last_JEs[-2])
        assert weight > 0.

        if verbose:
            print "adaptation %i, setting weight to %g ..." % (
                adaptation_iteration, weight)
            print 'Setting up network...'
        ncells, ncons, neuronsE, espikes, noise, GIDoffset = create_network(
            network_obj, weight, noise_weight, noise_rate,
            resolution=resolution, verbose=verbose, print_time=print_time,
        )
        if verbose:
            print 'Simulating...'
        nest.Simulate(simtime)
        if verbose:
            print 'Calculating the burst rate...'
        spike_times = nest.GetStatus(espikes, "events")[0]["times"]
        burst_rate = determine_burst_rate(spike_times, simtime, ncells)
        if verbose:
            print "-> the burst rate is %g Hz" % burst_rate
        adaptation_iteration += 1
        last_burst_rates.append(burst_rate)
        last_JEs.append(weight)
        assert adaptation_iteration < maxiter_adapt

    return weight, burst_rate
Beispiel #25
0
 def target(self):
     """The ID of the post-synaptic neuron."""
     tgt = ID(nest.GetStatus(self.id(), 'target')[0])
     tgt.parent = self.parent.post
     return tgt
def run_simulation(adjacency_matrix=None,
                   weight=None,
                   noise_rate=NOISE_RATE,
                   noise_weight=NOISE_WEIGHT,
                   resolution=RESOLUTION,
                   simtime=SIMTIME_RUN,
                   save=False, output_path='data/', basename='nest_sim_',
                   overwrite=False, verbose=True, print_time=False):

    if adjacency_matrix is None:
        # construct a network according to defaults
        adjacency_matrix = fake_network.construct_network()

    if weight is None:
        # if unspecified, find the weight automatically according to defaults
        weight, _ = adjust_weight(adjacency_matrix, noise_weight=noise_weight,
                                  noise_rate=noise_rate, resolution=resolution,
                                  verbose=verbose, print_time=print_time)

    # convert into network_object
    network_obj = adjacency2netobj(adjacency_matrix)

    ncells, ncons, neuronsE, espikes, noise, GIDoffset = create_network(
        network_obj, weight, noise_weight, noise_rate, resolution=resolution,
        verbose=verbose, print_time=print_time,
    )

    if verbose:
        print 'Simulating %s of activity for %i neurons' % (
            s2h(simtime / 1000.), ncells)

    startsimulate = time.time()
    nest.Simulate(simtime)
    endsimulate = time.time()

    sim_elapsed = endsimulate - startsimulate

    totalspikes = nest.GetStatus(espikes, "n_events")[0]
    events = nest.GetStatus(espikes, "events")[0]

    # NEST increments the GID whenever a new node is created. we therefore
    # subtract the GID offset, so that the output cell indices are correct
    # regardless of when the corresponding nodes were created in NEST
    cell_indices = events["senders"] - GIDoffset
    spike_times = events["times"]

    burst_rate = determine_burst_rate(spike_times, simtime, ncells)

    if verbose:
        print "\n" + "-" * 60
        print "Number of neurons: ", ncells
        print "Number of spikes recorded: ", totalspikes
        print "Avg. spike rate of neurons: %.2f Hz" % (
            totalspikes / (ncells * simtime / 1000.))
        print "Network burst rate: %.2f Hz" % burst_rate
        print "Simulation time: %s" % s2h(sim_elapsed)
        print "-" * 60

    # resample at 50Hz to make an [ncells, ntimesteps] array of bin counts
    resampled = resample_spikes(spike_times, cell_indices,
                                output_resolution=20, simtime=simtime,
                                ncells=ncells)

    if save:

        today = str(datetime.date.today())
        fname = basename + today
        if os.path.exists(fname) & ~overwrite:
            suffix = 0
            while os.path.exists(fname):
                suffix += 1
                fname = '%s%s_%i.npz' % (basename, today, suffix)
        fullpath = os.path.join(output_path, fname)
        np.savez(fullpath, spike_times=spike_times, cell_indices=cell_indices,
                 resampled=resampled)

        if verbose:
            print "Saved output in '%s'" % fullpath

    return spike_times, cell_indices, resampled
Beispiel #27
0
 def _get(self):
     return nest.GetStatus(self.id(), name)[0]
Beispiel #28
0
#!/usr/bin/env  python3

import nest
import pylab
import pandas as pd

nest.SetKernelStatus({'resolution': 1.0})

#GENERATOR
g_params = [{"start": 0.0, "stop": 500.0, "spike_times": [100.0, 300.0]}]
spikeGenerator = nest.Create("spike_generator", 1, g_params)
print(nest.GetStatus(spikeGenerator))
print()

#NEURON
n_params = [{"I_e": 0.0}]
neuron = nest.Create("iaf_psc_alpha", 1, n_params)
print(nest.GetStatus(neuron))
print()

#SPIKE DETECTOR
spikeDetector = nest.Create('spike_detector', n=1)

#MULTIMETER
m_params = {"withtime": True, "record_from": ["I_syn_ex"]}
multimeter = nest.Create("multimeter", 1, params=m_params)

#CONNECTIONS
syn_dict = {"model": "static_synapse", "weight": 1.0, "delay": 1.0}
nest.Connect(spikeGenerator, spikeDetector, 'one_to_one')
nest.Connect(spikeGenerator, neuron, "one_to_one", syn_dict)
Beispiel #29
0
             list(target_list2),
             conn_spec=conn_dict,
             syn_spec=syn_dict)

source_list1 = list(All_cells['V1_1l23pyr'][0])
source_list2 = list(All_cells['V1_2l23pyr'][0])
target_list = list(All_cells['LMl4pyr'][0])

pref_pref_bu = nest.GetConnections(source_list1, target_list)
nonpref_pref_bu = nest.GetConnections(source_list2, target_list)

#print pref_pref_bu

weights = {}

pref_pref_bu_weight = nest.GetStatus(pref_pref_bu)
nonpref_pref_bu_weight = nest.GetStatus(nonpref_pref_bu)
p_p = []
np_p = []
for xin in pref_pref_bu_weight:
    p_p.append(xin['weight'])
for xin in nonpref_pref_bu_weight:
    np_p.append(xin['weight'])

print 'initial weights'
print 'pref_pref', numpy.mean(numpy.array(p_p))
print 'nonpref_pref', numpy.mean(numpy.array(np_p))

weights['before_p_p'] = p_p
weights['before_np_p'] = np_p
    def _test_model_subthreshold(self,
                                 referenceModel,
                                 testant,
                                 gsl_error_tol,
                                 tolerance=0.000001,
                                 nest_ref_model_opts=None,
                                 custom_model_opts=None):
        t_stop = 1000.  # [ms]

        I_stim_vec = np.linspace(10E-12, 1E-9, 100)  # [A]
        rate_testant = float("nan") * np.ones_like(I_stim_vec)
        rate_reference = float("nan") * np.ones_like(I_stim_vec)
        for i, I_stim in enumerate(I_stim_vec):

            nest.ResetKernel()
            neuron1 = nest.Create(referenceModel, params=nest_ref_model_opts)
            neuron2 = nest.Create(testant, params=custom_model_opts)

            if gsl_error_tol is not None:
                nest.SetStatus(neuron2, {"gsl_error_tol": gsl_error_tol})

            dc = nest.Create("dc_generator",
                             params={"amplitude":
                                     I_stim * 1E12})  # 1E12: convert A to pA

            nest.Connect(dc, neuron1)
            nest.Connect(dc, neuron2)

            multimeter1 = nest.Create('multimeter')
            multimeter2 = nest.Create('multimeter')

            V_m_specifier = 'V_m'  # 'delta_V_m'
            nest.SetStatus(multimeter1, {"record_from": [V_m_specifier]})
            nest.SetStatus(multimeter2, {"record_from": [V_m_specifier]})

            nest.Connect(multimeter1, neuron1)
            nest.Connect(multimeter2, neuron2)

            sd_reference = nest.Create('spike_recorder')
            nest.Connect(neuron1, sd_reference)
            sd_testant = nest.Create('spike_recorder')
            nest.Connect(neuron2, sd_testant)

            nest.Simulate(t_stop)
            dmm1 = nest.GetStatus(multimeter1)[0]
            Vms1 = dmm1["events"][V_m_specifier]
            ts1 = dmm1["events"]["times"]

            dmm2 = nest.GetStatus(multimeter2)[0]
            Vms2 = dmm2["events"][V_m_specifier]
            ts2 = dmm2["events"]["times"]

            rate_testant[i] = sd_testant.n_events / t_stop * 1000
            rate_reference[i] = sd_reference.n_events / t_stop * 1000

            if TEST_PLOTS and False:
                fig, ax = plt.subplots(2, 1)
                ax[0].plot(ts1, Vms1, label="Reference " + referenceModel)
                ax[1].plot(ts2, Vms2, label="Testant " + testant)
                for _ax in ax:
                    _ax.legend(loc='upper right')
                    _ax.grid()
                fig.suptitle("Rate: " + str(rate_testant[i]) + " Hz")
                plt.savefig(
                    "/tmp/nestml_nest_integration_test_subthreshold_[" +
                    referenceModel + "]_[" + testant + "]_[I_stim=" +
                    str(I_stim) + "].png")
                plt.close(fig)

        if TEST_PLOTS:
            if len(I_stim_vec) < 20:
                marker = "o"
            else:
                marker = None
            fig, ax = plt.subplots(2, 1)
            ax[0].plot(I_stim_vec * 1E12,
                       rate_reference,
                       marker=marker,
                       label="Reference " + referenceModel)
            ax[1].plot(I_stim_vec * 1E12,
                       rate_testant,
                       marker=marker,
                       label="Testant " + testant)
            for _ax in ax:
                _ax.legend(loc='upper right')
                _ax.grid()
                _ax.set_ylabel("Firing rate [Hz]")
            ax[1].set_xlabel("$I_{inj}$ [pA]")
            plt.savefig("/tmp/nestml_nest_integration_test_subthreshold_[" +
                        referenceModel + "]_[" + testant + "].png")
            plt.close(fig)

        if TEST_PLOTS:
            if len(I_stim_vec) < 20:
                marker = "o"
            else:
                marker = None
            for figsize, fname_snip in zip([(8, 5), (4, 3)], ["", "_small"]):
                fig, ax = plt.subplots(1, 1, figsize=figsize)
                ax = [ax]
                ax[0].plot(I_stim_vec * 1E12,
                           rate_testant,
                           marker=marker,
                           label=referenceModel)
                for _ax in ax:
                    _ax.grid()
                    _ax.set_ylabel("Firing rate [Hz]")
                ax[0].set_xlabel("$I_{inj}$ [pA]")
                plt.tight_layout()
                plt.savefig("/tmp/nestml_models_library_[" + referenceModel +
                            "]_f-I_curve" + fname_snip + ".png")
                plt.close(fig)

        print(testant + " PASSED")