Exemplo n.º 1
0
def sli_run(parameters=object(), fname='microcircuit.sli',
            verbosity='M_ERROR'):
    '''
    Takes parameter-class and name of main sli-script as input, initiating the
    simulation.
    
    Parameters
    ----------
    parameters : object
        parameter class instance
    fname : str
        path to sli codes to be executed
    verbosity : str,
        nest verbosity flag
    
    Returns
    -------
    None
    
    '''
    # Load parameters from params file, and pass them to nest
    # Python -> SLI
    send_nest_params_to_sli(vars(parameters))

    #set SLI verbosity
    nest.sli_run("%s setverbosity" % verbosity)

    # Run NEST/SLI simulation
    nest.sli_run('(%s) run' % fname)
Exemplo n.º 2
0
def sli_run(parameters=object(),
            fname='microcircuit.sli',
            verbosity='M_ERROR'):
    '''
    Takes parameter-class and name of main sli-script as input, initiating the
    simulation.
    
    Parameters
    ----------
    parameters : object
        parameter class instance
    fname : str
        path to sli codes to be executed
    verbosity : str,
        nest verbosity flag
    
    Returns
    -------
    None
    
    '''
    # Load parameters from params file, and pass them to nest
    # Python -> SLI
    send_nest_params_to_sli(vars(parameters))
    
    #set SLI verbosity
    nest.sli_run("%s setverbosity" % verbosity)
    
    # Run NEST/SLI simulation
    nest.sli_run('(%s) run' % fname)
Exemplo n.º 3
0
def send_nest_params_to_sli(p):
    '''
    Read parameters and send them to SLI
    '''
    for name in list(p.keys()):
        value = p[name]
        if type(value) == numpy.ndarray:
            value = value.tolist()
        if type(value) == dict:
            value = dict_of_numpyarray_to_dict_of_list(value)
        if name == 'neuron_model':  # special case as neuron_model should is a NEST model and not a string
            try:
                nest.sli_run('/' + name)
                nest.sli_push(value)
                nest.sli_run('eval')
                nest.sli_run('def')
            except:
                print('Could not put variable %s on SLI stack' % (name))
                print(type(value))
        else:
            try:
                nest.sli_run('/' + name)
                nest.sli_push(value)
                nest.sli_run('def')
            except:
                print('Could not put variable %s on SLI stack' % (name))
                print(type(value))
    return
Exemplo n.º 4
0
    def _setup_music(self):
        """
        Setup music connection.
        """
        _nest.sli_run('statusdict/have_music ::')
        if not _nest.spp():
            print('NEST was not compiled with support for MUSIC, not running.')
            _sys.exit()

        # Setup music spike output.
        self._music_spike_output = _nest.Create('music_event_out_proxy', 1)
        _nest.SetStatus(self._music_spike_output,
                        {'port_name': self._spike_port_name})

        # Connecting neurons to music event channels. In case of the BBP
        # circuit, each channel corresponds to a gid.
        for gid, neuron in self._gid_to_neuron_map.items():
            _nest.Connect([neuron], self._music_spike_output, 'one_to_one',
                          {'music_channel': gid})

        # Connecting the last music channel (value specified in the
        # configuration file) to a dummy neuron
        dummy = _nest.Create('iaf_neuron', 1)
        _nest.Connect(dummy, self._music_spike_output, 'one_to_one',
                      {'music_channel': 10000000})

        # Setup music steering input.
        self._music_steering_input = _nest.Create('music_message_in_proxy', 1)
        _nest.SetStatus(self._music_steering_input,
                        {'port_name': self._steering_port_name,
                         'acceptable_latency': 40.0})
Exemplo n.º 5
0
    def _setup_music(self):
        """
        Setup music connection.
        """
        _nest.sli_run('statusdict/have_music ::')
        if not _nest.spp():
            print('NEST was not compiled with support for MUSIC, not running.')
            _sys.exit()

        # Setup music spike output.
        self._music_spike_output = _nest.Create('music_event_out_proxy', 1)
        _nest.SetStatus(self._music_spike_output,
                        {'port_name': self._spike_port_name})

        # Connecting neurons to music event channels. In case of the BBP
        # circuit, each channel corresponds to a gid.
        for gid, neuron in self._gid_to_neuron_map.items():
            _nest.Connect([neuron], self._music_spike_output, 'one_to_one',
                          {'music_channel': gid})

        # Setup music steering input.
        self._music_steering_input = _nest.Create('music_message_in_proxy', 1)
        _nest.SetStatus(self._music_steering_input, {
            'port_name': self._steering_port_name,
            'acceptable_latency': 40.0
        })
Exemplo n.º 6
0
def prepare_simulation(master_seed, n_populations):
    """Prepare random generators with master seed."""
    nest.ResetKernel()
    # set global kernel parameters
    nest.SetKernelStatus({
        "communicate_allgather": sim.allgather,
        "print_time": True,
        "overwrite_files": False,
        "resolution": sim.dt,
        "total_num_virtual_procs": sim.n_vp
    })

    # Set random seeds
    nest.sli_run(
        '0 << /rngs [%i %i] Range { rngdict/gsl_mt19937 :: exch CreateRNG } Map >> SetStatus'
        % (master_seed, master_seed + sim.n_vp - 1))
    #nest.SetKernelStatus({"rng_seeds" : range(master_seed, master_seed + sim.n_vp)})
    nest.sli_run(
        '0 << /grng rngdict/gsl_mt19937 :: %i CreateRNG >> SetStatus' %
        (master_seed + sim.n_vp))
    #nest.SetKernelStatus({"grng_seed" : master_seed + sim.n_vp})
    pyrngs = [
        np.random.RandomState(s)
        for s in range(master_seed + sim.n_vp + 1, master_seed + 2 * sim.n_vp +
                       1)
    ]
    return pyrngs
Exemplo n.º 7
0
 def load_libraries(self, name, url, **kwargs):  # @UnusedVariable
     install_dir = self.get_install_dir(name, url)
     lib_dir = os.path.join(install_dir, 'lib')
     add_lib_path(lib_dir)
     # Add module install directory to NEST path
     nest.sli_run(
         '({}) addpath'.format(os.path.join(install_dir, 'share', 'sli')))
     # Install nest module
     nest.Install(name + 'Module')
Exemplo n.º 8
0
def setup(timestep=0.1, min_delay=0.1, max_delay=10.0, **extra_params):
    """
    Should be called at the very beginning of a script.
    extra_params contains any keyword arguments that are required by a given
    simulator but not by others.
    """
    global tempdir

    common.setup(timestep, min_delay, max_delay, **extra_params)

    if 'verbosity' in extra_params:
        nest_verbosity = extra_params['verbosity'].upper()
    else:
        nest_verbosity = "WARNING"
    nest.sli_run("M_%s setverbosity" % nest_verbosity)

    # clear the sli stack, if this is not done --> memory leak cause the stack increases
    nest.sr('clear')

    # reset the simulation kernel
    nest.ResetKernel()

    # set tempdir
    tempdir = tempfile.mkdtemp()
    tempdirs.append(tempdir)  # append tempdir to tempdirs list
    nest.SetKernelStatus({
        'data_path': tempdir,
    })

    # set kernel RNG seeds
    num_threads = extra_params.get('threads') or 1
    if 'rng_seeds' in extra_params:
        rng_seeds = extra_params['rng_seeds']
    else:
        rng_seeds_seed = extra_params.get('rng_seeds_seed') or 42
        rng = NumpyRNG(rng_seeds_seed)
        rng_seeds = (rng.rng.uniform(size=num_threads * num_processes()) *
                     100000).astype('int').tolist()
    logger.debug("rng_seeds = %s" % rng_seeds)
    nest.SetKernelStatus({
        'local_num_threads': num_threads,
        'rng_seeds': rng_seeds
    })

    # set resolution
    nest.SetKernelStatus({'resolution': timestep})

    # Set min_delay and max_delay for all synapse models
    for synapse_model in NEST_SYNAPSE_TYPES:
        nest.SetDefaults(synapse_model, {
            'delay': min_delay,
            'min_delay': min_delay,
            'max_delay': max_delay
        })
    simulator.reset()

    return rank()
Exemplo n.º 9
0
 def load_libraries(self, name, url, **kwargs):  # @UnusedVariable
     install_dir = self.get_install_dir(name, url)
     lib_dir = os.path.join(install_dir, 'lib')
     add_lib_path(lib_dir)
     # Add module install directory to NEST path
     nest.sli_run('({}) addpath'.format(
         os.path.join(install_dir, 'share', 'sli')))
     # Install nest module
     nest.Install(name + 'Module')
Exemplo n.º 10
0
    def get_help_text(self, name):

        nest.sli_run("statusdict /prgdocdir get")
        docdir = nest.sli_pop()

        helptext = "No documentation available"

        for subdir in ["cc", "sli"]:
            filename = os.path.join(docdir, "help", subdir, name + ".hlp")
            if os.path.isfile(filename):
                helptext = open(filename, 'r').read()

        return helptext
Exemplo n.º 11
0
    def get_help_text(self, name):

        nest.sli_run("statusdict /prgdocdir get")
        docdir = nest.sli_pop()

        helptext = "No documentation available"

        for subdir in ["cc", "sli"]:
            filename = os.path.join(docdir, "help", subdir, name + ".hlp")
            if os.path.isfile(filename):
                helptext = open(filename, 'r').read()

        return helptext
Exemplo n.º 12
0
def prepare_simulation(master_seed, n_populations):
    """Prepare random generators with master seed."""
    nest.ResetKernel()
    # set global kernel parameters
    nest.SetKernelStatus(
        {"communicate_allgather": sim.allgather,
        "print_time": True, 
        "overwrite_files": False,
        "resolution": sim.dt,
        "total_num_virtual_procs": sim.n_vp})
   
    # Set random seeds
    nest.sli_run('0 << /rngs [%i %i] Range { rngdict/gsl_mt19937 :: exch CreateRNG } Map >> SetStatus'%(
                 master_seed, master_seed + sim.n_vp - 1))
    #nest.SetKernelStatus({"rng_seeds" : range(master_seed, master_seed + sim.n_vp)})
    nest.sli_run('0 << /grng rngdict/gsl_mt19937 :: %i CreateRNG >> SetStatus'%(master_seed + sim.n_vp))
    #nest.SetKernelStatus({"grng_seed" : master_seed + sim.n_vp})
    pyrngs = [np.random.RandomState(s) for s in 
                range(master_seed + sim.n_vp + 1, master_seed + 2 * sim.n_vp + 1)]
    return pyrngs
Exemplo n.º 13
0
Arquivo: base.py Projeto: tclose/PyPe9
 def load_libraries(cls, name, install_dir):
     lib_dir = os.path.join(install_dir, 'lib', 'nest')
     if (sys.platform.startswith('linux') or
         sys.platform in ['os2', 'os2emx', 'cygwin', 'atheos',
                          'ricos']):
         lib_path_key = 'LD_LIBRARY_PATH'
     elif sys.platform == 'darwin':
         lib_path_key = 'DYLD_LIBRARY_PATH'
     elif sys.platform == 'win32':
         lib_path_key = 'PATH'
     if lib_path_key in os.environ:
         os.environ[lib_path_key] += os.pathsep + lib_dir
     else:
         os.environ[lib_path_key] = lib_dir
     # Add module install directory to NEST path
     nest.sli_run(
         '({}) addpath'.format(os.path.join(install_dir, 'share', 'nest',
                                            'sli')))
     # Install nest module
     nest.Install(name + 'Module')
Exemplo n.º 14
0
def prepare_simulation(master_seed, n_populations):
    """Prepare random generators with master seed."""
    nest.ResetKernel()
    # set global kernel parameters
    nest.SetKernelStatus({
        "communicate_allgather": sim.allgather,
        "overwrite_files": sim.overwrite_existing_files,
        "resolution": sim.dt,
        "total_num_virtual_procs": sim.n_vp
    })
    if sim.to_text_file:
        nest.SetKernelStatus({"data_path": data_path_test})

    # Set random seeds

    # PYNEST
    #nest.sli_run('0 << /rngs [%i %i] Range { rngdict/gsl_mt19937 :: exch CreateRNG } Map >> SetStatus'%(
    #             master_seed, master_seed + sim.n_vp - 1))
    #nest.SetKernelStatus({"rng_seeds" : range(master_seed, master_seed + sim.n_vp)})
    #nest.sli_run('0 << /grng rngdict/gsl_mt19937 :: %i CreateRNG >> SetStatus'%(master_seed + sim.n_vp))
    #nest.SetKernelStatus({"grng_seed" : master_seed + sim.n_vp})
    #pyrngs = [np.random.RandomState(s) for s in
    #            range(master_seed + sim.n_vp + 1, master_seed + 2 * sim.n_vp + 1)]

    # SLI VERSION
    sli_str = "0 << \n"
    #sli_str += "/rngs %i [0 %i 1 sub] add Range { rngdict/gsl_mt19937 :: exch CreateRNG } Map\n"%(master_seed, sim.n_vp) # local RNG, seeded
    #sli_str += "/grng rngdict/gsl_mt19937 :: %i %i add CreateRNG\n"%(master_seed, sim.n_vp) # global RNG
    sli_str += "/rng_seeds %i [0 %i 1 sub] add Range\n" % (
        master_seed, sim.n_vp)  # local RNG seeds
    sli_str += "/grng_seed %i %i add\n" % (master_seed, sim.n_vp
                                           )  # global RNG seed
    sli_str += ">> SetStatus"
    nest.sli_run(sli_str)
    sli_str2 = "/script_rngs [%i]\n" % sim.n_vp
    sli_str2 += "{%i add rngdict /gsl_mt19937 get exch CreateRNG } Table def\n" % (
        master_seed + sim.n_vp)
    sli_str2 += "/normal_rdvs script_rngs { rdevdict /normal get CreateRDV } Map def"
    nest.sli_run(sli_str2)
    pyrngs = None
    return pyrngs
Exemplo n.º 15
0
def send_nest_params_to_sli(p):
    '''
    Read parameters and send them to SLI
    
    Parameters
    ----------
    p : dict
        sli parameter name and value as dictionary key and value pairs
    
    Returns
    -------
    None
    '''
    for name in p.keys():
        value = p[name]
        if type(value) == np.ndarray:
            value = value.tolist()
        if type(value) == dict:
            value = dict_of_numpyarray_to_dict_of_list(value)
        if name == 'neuron_model': # special case as neuron_model is a
                                   # NEST model and not a string
            try:
                nest.sli_run('/'+name)
                nest.sli_push(value)
                nest.sli_run('eval')
                nest.sli_run('def')
            except: 
                print 'Could not put variable %s on SLI stack' % (name)
                print type(value)
        else:
            try:
                nest.sli_run('/'+name)
                nest.sli_push(value)
                nest.sli_run('def')
            except: 
                print 'Could not put variable %s on SLI stack' % (name)
                print type(value)
    return
Exemplo n.º 16
0
def send_nest_params_to_sli(p):
    '''
    Read parameters and send them to SLI
    
    Parameters
    ----------
    p : dict
        sli parameter name and value as dictionary key and value pairs
    
    Returns
    -------
    None
    '''
    for name in p.keys():
        value = p[name]
        if type(value) == np.ndarray:
            value = value.tolist()
        if type(value) == dict:
            value = dict_of_numpyarray_to_dict_of_list(value)
        if name == 'neuron_model':  # special case as neuron_model is a
            # NEST model and not a string
            try:
                nest.sli_run('/' + name)
                nest.sli_push(value)
                nest.sli_run('eval')
                nest.sli_run('def')
            except:
                print 'Could not put variable %s on SLI stack' % (name)
                print type(value)
        else:
            try:
                nest.sli_run('/' + name)
                nest.sli_push(value)
                nest.sli_run('def')
            except:
                print 'Could not put variable %s on SLI stack' % (name)
                print type(value)
    return
Exemplo n.º 17
0
def prepare_simulation(master_seed, n_populations):
    """Prepare random generators with master seed."""
    nest.ResetKernel()
    # set global kernel parameters
    nest.SetKernelStatus(
        {"communicate_allgather": sim.allgather,
        "overwrite_files": sim.overwrite_existing_files,
        "resolution": sim.dt,
        "total_num_virtual_procs": sim.n_vp})
    if sim.to_text_file:
        nest.SetKernelStatus({"data_path": data_path_test})
   
    # Set random seeds
    
    # PYNEST
    #nest.sli_run('0 << /rngs [%i %i] Range { rngdict/gsl_mt19937 :: exch CreateRNG } Map >> SetStatus'%(
    #             master_seed, master_seed + sim.n_vp - 1))
    #nest.SetKernelStatus({"rng_seeds" : range(master_seed, master_seed + sim.n_vp)})
    #nest.sli_run('0 << /grng rngdict/gsl_mt19937 :: %i CreateRNG >> SetStatus'%(master_seed + sim.n_vp))
    #nest.SetKernelStatus({"grng_seed" : master_seed + sim.n_vp})
    #pyrngs = [np.random.RandomState(s) for s in 
    #            range(master_seed + sim.n_vp + 1, master_seed + 2 * sim.n_vp + 1)]

    # SLI VERSION
    sli_str  = "0 << \n"
    #sli_str += "/rngs %i [0 %i 1 sub] add Range { rngdict/gsl_mt19937 :: exch CreateRNG } Map\n"%(master_seed, sim.n_vp) # local RNG, seeded
    #sli_str += "/grng rngdict/gsl_mt19937 :: %i %i add CreateRNG\n"%(master_seed, sim.n_vp) # global RNG
    sli_str += "/rng_seeds %i [0 %i 1 sub] add Range\n"%(master_seed, sim.n_vp) # local RNG seeds
    sli_str += "/grng_seed %i %i add\n"%(master_seed, sim.n_vp) # global RNG seed
    sli_str += ">> SetStatus"
    nest.sli_run(sli_str)
    sli_str2  = "/script_rngs [%i]\n"%sim.n_vp
    sli_str2 += "{%i add rngdict /gsl_mt19937 get exch CreateRNG } Table def\n"%(master_seed + sim.n_vp)
    sli_str2 += "/normal_rdvs script_rngs { rdevdict /normal get CreateRDV } Map def"
    nest.sli_run(sli_str2)
    pyrngs = None
    return pyrngs
Exemplo n.º 18
0
        # with 'Multimeter to file example' NEST tutorial \
        # params, edited for muscle_spindle
        myLabel = outputDir + "datsAndMetadata/"\
         + names[myV] + currentMuscles[myC] + "afferents"
        mm = nest.Create("multimeter", params={"interval": 0.1, \
        "record_from": ["primary_rate", "secondary_rate"], \
        "withgid": True, "to_file": myW, "label": myLabel, "to_memory":
        toM})

        nest.Connect(mm, ms)

        print(str(nest.GetStatus(sd)))
        print(str(nest.GetStatus(mm)))

        # remove some output
        nest.sli_run('M_WARNING setverbosity')

        # time simulation
        ta = []  # time array
        for c in range(myR):
            #print(str(myR))
            startTime = time.perf_counter()
            ### simulate
            before = 0.0
            #print(str(len(optLengths))) #debug
            for i in range(len(optLengths)):
                if (i == 0):
                    before = optLengths[i]
                else:
                    before = optLengths[i - 1]
                nest.SetStatus(ms, {"L": optLengths[i], "dL":\
Exemplo n.º 19
0
When run with 1, 2, or 4 MPI processes, identical network structures must
result.

Create one subdir per number of MPI processes, then move into each subdir,
run there. Afterwards, diff subdirs. Diff should output nothing.



Hans Ekkehard Plesser, 2010-11-03
"""

import nest
import nest.topology as topo
import os

nest.sli_run('M_ERROR setverbosity')
nest.SetKernelStatus({'total_num_virtual_procs': 4})

l1 = topo.CreateLayer({
    'rows': 50,
    'columns': 40,
    'elements': ['iaf_neuron', 2],
    'edge_wrap': True
})

l2 = topo.CreateLayer({
    'rows': 50,
    'columns': 40,
    'elements': ['iaf_neuron', 2],
    'edge_wrap': True
})
Create one subdir per number of MPI processes, then move into each subdir,
run there. Afterwards, diff subdirs. Diff should output nothing.

Hans Ekkehard Plesser, 2010-11-03, 2012-11-23
"""

import nest
import nest.topology as topo
import os
import sys

assert len(sys.argv) == 2, "Usage: topo_mpi_test.py convergent|divergent"

direction = sys.argv[1]

nest.sli_run("M_ERROR setverbosity")
nest.SetKernelStatus({"total_num_virtual_procs": 4})

l1 = topo.CreateLayer({"rows": 10, "columns": 20, "elements": ["iaf_neuron", 2], "edge_wrap": True})

l2 = topo.CreateLayer({"rows": 10, "columns": 20, "elements": ["iaf_neuron", 2], "edge_wrap": True})

topo.ConnectLayers(
    l1,
    l2,
    {"connection_type": direction, "mask": {"circular": {"radius": 0.4}}, "weights": {"linear": {"c": 1.0, "a": -5.0}}},
)

topo.DumpLayerNodes(l1 + l2, "topo_mpi_test.lyr_tmp")
topo.DumpLayerConnections(l1, "static_synapse", "topo_mpi_test.cnn_tmp")
Exemplo n.º 21
0
def setup(timestep=0.1, min_delay=0.1, max_delay=10.0, **extra_params):
    """
    Should be called at the very beginning of a script.
    extra_params contains any keyword arguments that are required by a given
    simulator but not by others.
    """
    global tempdir

    common.setup(timestep, min_delay, max_delay, **extra_params)
    # clear the sli stack, if this is not done --> memory leak cause the stack increases
    nest.sr('clear')

    # reset the simulation kernel
    nest.ResetKernel()

    if 'verbosity' in extra_params:
        nest_verbosity = extra_params['verbosity'].upper()
    else:
        nest_verbosity = "WARNING"
    nest.sli_run("M_%s setverbosity" % nest_verbosity)

    if "spike_precision" in extra_params:
        simulator.state.spike_precision = extra_params["spike_precision"]
        if extra_params["spike_precision"] == 'off_grid':
            simulator.state.default_recording_precision = 15
    nest.SetKernelStatus(
        {'off_grid_spiking': simulator.state.spike_precision == 'off_grid'})
    if "recording_precision" in extra_params:
        simulator.state.default_recording_precision = extra_params[
            "recording_precision"]

    # all NEST to erase previously written files (defaut with all the other simulators)
    nest.SetKernelStatus({'overwrite_files': True})

    # set tempdir
    tempdir = tempfile.mkdtemp()
    tempdirs.append(tempdir)  # append tempdir to tempdirs list
    nest.SetKernelStatus({
        'data_path': tempdir,
    })

    # set kernel RNG seeds
    num_threads = extra_params.get('threads') or 1
    if 'rng_seeds' in extra_params:
        rng_seeds = extra_params['rng_seeds']
    else:
        rng_seeds_seed = extra_params.get('rng_seeds_seed') or 42
        rng = NumpyRNG(rng_seeds_seed)
        rng_seeds = (rng.rng.uniform(size=num_threads * num_processes()) *
                     100000).astype('int').tolist()
    logger.debug("rng_seeds = %s" % rng_seeds)
    nest.SetKernelStatus({
        'local_num_threads': num_threads,
        'rng_seeds': rng_seeds
    })

    # set resolution
    nest.SetKernelStatus({'resolution': timestep})

    if 'allow_offgrid_spikes' in nest.GetDefaults('spike_generator'):
        nest.SetDefaults('spike_generator', {'allow_offgrid_spikes': True})

    # Set min_delay and max_delay for all synapse models
    NEST_SYNAPSE_TYPES = nest.Models(
        mtype='synapses')  # need to rebuild after ResetKernel
    for synapse_model in NEST_SYNAPSE_TYPES:
        nest.SetDefaults(synapse_model, {
            'delay': min_delay,
            'min_delay': min_delay,
            'max_delay': max_delay
        })
    simulator.connection_managers = []
    simulator.populations = []
    simulator.reset()

    return rank()
Exemplo n.º 22
0
Create one subdir per number of MPI processes, then move into each subdir, run there.
Afterwards, diff subdirs. Diff should output nothing.

Hans Ekkehard Plesser, 2010-11-03, 2012-11-23
"""

import nest 
import nest.topology as topo
import os
import sys

assert len(sys.argv) == 2, "Usage: topo_mpi_test.py convergent|divergent"

direction = sys.argv[1]

nest.sli_run('M_ERROR setverbosity')
nest.SetKernelStatus({'total_num_virtual_procs': 4})

l1 = topo.CreateLayer({'rows': 10,
                       'columns': 20,
                       'elements': ['iaf_neuron', 2],
                       'edge_wrap': True})

l2 = topo.CreateLayer({'rows': 10,
                       'columns': 20,
                       'elements': ['iaf_neuron', 2],
                       'edge_wrap': True})

topo.ConnectLayers(l1, l2, {'connection_type': direction,
                            'mask': {'circular': {'radius': 0.4}},
                            'weights': {'linear': {'c': 1., 'a': -5.}}})
Exemplo n.º 23
0
import nest
import nest.topology as topo
## Initialising module
nest.sli_run("topology using")
## Create layers
layer = topo.CreateLayer({"rows": 3,
"columns": 4,
"extent": [1.0, 1.0],
"elements": "iaf_neuron"})
nest.PrintNetwork(1, layer)

layer_settings = {"rows": 9,
"columns": 8,
"extent": [4.0, 5.0],
"center": [1.0, -1.0],
"elements": "iaf_neuron",
"edge_wrap": False}
source = topo.CreateLayer(layer_settings)
layer_settings["extent"] = [2.0, 2.0]
target = topo.CreateLayer(layer_settings)
## Connect layers
connection_settings = {"connection_type": "convergent",
"mask": {"circular": {"radius": 2.0}},
"weights": 1.0,
"synapse_model": "static_synapse"}
topo.ConnectLayer(source, target, connection_settings)

Exemplo n.º 24
0
# NEST is free software: you can redistribute it and/or modify
# 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

nest.sli_run("statusdict/have_music ::")
if not nest.spp():
    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)
Exemplo n.º 25
0
from . import compatibility

try:
    import libcsa
    HAVE_LIBCSA = True
except ImportError:
    HAVE_LIBCSA = False

try:
    import numpy
    HAVE_NUMPY = True
except ImportError:
    HAVE_NUMPY = False

nest.sli_run("statusdict/have_libneurosim ::")
HAVE_LIBNEUROSIM = nest.sli_pop()


@nest.check_stack
@unittest.skipIf(not HAVE_LIBCSA, 'Python libcsa package is not available')
@unittest.skipIf(not HAVE_LIBNEUROSIM,
                 'PyNEST was built without the libneurosim library')
class libcsaTestCase(unittest.TestCase):
    """libcsa tests"""
    def test_libcsa_OneToOne_subnet_1d(self):
        """One-to-one connectivity with 1-dim subnets"""

        nest.ResetKernel()

        n = 4  # number of neurons
Exemplo n.º 26
0
 def empty_stack():
     nest.sli_run('clear')
Exemplo n.º 27
0
def LambertWm1(x):
    nest.sli_push(x); nest.sli_run('LambertWm1'); y=nest.sli_pop()
    return y
Exemplo n.º 28
0
 def empty_stack():
     nest.sli_run('clear')
Exemplo n.º 29
0
def create_nodes(model, pyrngs):
    """
        Creates the following GIDs:
        neuron_GIDs
        ext_poisson
        ext_dc
        th_parrots
        th_poisson
        spike_detectors
        multimeters
        th_spike_detector
    
        Further initializes the neurons" membrane potentials.
    """
    neuron_GIDs     = []
    spike_detectors = []
    multimeters     = []
    ext_poisson     = []
    ext_dc          = []
    print(data_path_test)
    Vm0_file = open(os.path.join(data_path_test, "Vm0_pynest"), "w")
    for pop_index, population in enumerate(model.populations):
        # Neurons
        neuron_GIDs.append(nest.Create(model.neuron_model, model.n_neurons[pop_index], params=model.model_params))
        # Initialize membrane potentials locally
        # drawn from normal distribution with mu=Vm0_mean, sigma=Vm0_std
        neurons_info    = nest.GetStatus(neuron_GIDs[pop_index])
        for ni in neurons_info:                 
            if ni["local"]:                         # only adapt local nodes
                sli_str3 = "%i << /V_m normal_rdvs %i get Random %.1f mul %.1f add >> SetStatus"%(ni["global_id"], ni["vp"], model.Vm0_std, model.Vm0_mean)
                nest.sli_run(sli_str3)
                Vm_init = nest.GetStatus([ni["global_id"]])[0]["V_m"]
                #Vm_init = pyrngs[ni["vp"]].normal(model.Vm0_mean, model.Vm0_std)
                #nest.SetStatus([ni["global_id"]], {"V_m": Vm_init})
                Vm0_file.write(str(ni["global_id"]) + "\t" + str(Vm_init) + "\n")

        # Devices
        if sim.record_cortical_spikes:
            spike_detector_dict = {"label": sim.spike_detector_label + population + "_", 
                                    "to_file": sim.to_text_file}
            spike_detectors.append(nest.Create("spike_detector", 1, params=spike_detector_dict))

        if sim.record_voltage:
            multimeter_dict = {"label": sim.multimeter_label + population + "_", 
                                "to_file": sim.to_text_file, 
                                "start": sim.t_rec_volt_start,   
                                #"stop": sim.t_rec_volt_stop, 
                                "interval": 1.0, # ms
                                "withtime": True, 
                                "record_from": ["V_m"]}
            multimeters.append(nest.Create("multimeter", 1, params=multimeter_dict))
        
        # External input
        # One poisson generator per population. 
        #Rate is determined by base rate times in-degree[population]
        ext_poisson_params = {"rate": model.rate_ext * model.C_aext[pop_index]}
        ext_poisson.append(nest.Create("poisson_generator", 1, params=ext_poisson_params))
        # One dc generator per population. 
        # Amplitude is determined by base amplitude times in-degree[population]
        ext_dc_params = {"amplitude": model.dc_amplitude * model.C_aext[pop_index]}
        ext_dc.append(nest.Create("dc_generator", 1, params=ext_dc_params))
        
    # Thalamic neurons: parrot neurons and Poisson bg
    if not model.n_th == 0:
        th_parrots  = nest.Create("parrot_neuron", model.n_th, params=None)
        th_poisson  = nest.Create("poisson_generator", 1, 
            params={"rate": model.th_rate, 
                "start": model.th_start, 
                "stop": model.th_start + model.th_duration})
        if sim.record_thalamic_spikes:
            th_spike_detector_dict = {"label": sim.th_spike_detector_label, 
                                    "to_file": sim.to_text_file}
            th_spike_detector  = nest.Create("spike_detector", 1, params=th_spike_detector_dict)
        else:
            th_spike_detector = None
    else:
        th_parrots, th_poisson, th_spike_detector = (None, None, None)


    Vm0_file.close()
        
    return (neuron_GIDs, 
            spike_detectors, multimeters,
            ext_poisson, ext_dc, 
            th_parrots, th_poisson, th_spike_detector)
Exemplo n.º 30
0
def setup(timestep=0.1, min_delay=0.1, max_delay=10.0, **extra_params):
    """
    Should be called at the very beginning of a script.
    extra_params contains any keyword arguments that are required by a given
    simulator but not by others.
    """
    global tempdir
    
    common.setup(timestep, min_delay, max_delay, **extra_params)
    
    if 'verbosity' in extra_params:
        nest_verbosity = extra_params['verbosity'].upper()
    else:
        nest_verbosity = "WARNING"
    nest.sli_run("M_%s setverbosity" % nest_verbosity)
    
    if "spike_precision" in extra_params:
        simulator.state.spike_precision = extra_params["spike_precision"]
        if extra_params["spike_precision"] == 'off_grid':
            simulator.state.default_recording_precision = 15
    nest.SetKernelStatus({'off_grid_spiking': simulator.state.spike_precision=='off_grid'})
    if "recording_precision" in extra_params:
        simulator.state.default_recording_precision = extra_params["recording_precision"]
    
    
    # clear the sli stack, if this is not done --> memory leak cause the stack increases
    nest.sr('clear')
    
    # reset the simulation kernel
    nest.ResetKernel()
    
    # all NEST to erase previously written files (defaut with all the other simulators)
    nest.SetKernelStatus({'overwrite_files' : True})
    
    # set tempdir
    tempdir = tempfile.mkdtemp()
    tempdirs.append(tempdir) # append tempdir to tempdirs list
    nest.SetKernelStatus({'data_path': tempdir,})

    # set kernel RNG seeds
    num_threads = extra_params.get('threads') or 1
    if 'rng_seeds' in extra_params:
        rng_seeds = extra_params['rng_seeds']
    else:
        rng_seeds_seed = extra_params.get('rng_seeds_seed') or 42
        rng = NumpyRNG(rng_seeds_seed)
        rng_seeds = (rng.rng.uniform(size=num_threads*num_processes())*100000).astype('int').tolist() 
    logger.debug("rng_seeds = %s" % rng_seeds)
    nest.SetKernelStatus({'local_num_threads': num_threads,
                          'rng_seeds'        : rng_seeds})

    # set resolution
    nest.SetKernelStatus({'resolution': float(timestep)})

    # Set min_delay and max_delay for all synapse models
    for synapse_model in NEST_SYNAPSE_TYPES:
        nest.SetDefaults(synapse_model, {'delay'    : float(min_delay),
                                         'min_delay': float(min_delay),
                                         'max_delay': float(max_delay)})
    simulator.reset()
    
    return rank()
Exemplo n.º 31
0
from . import compatibility

try:
    import libcsa
    HAVE_LIBCSA = True
except ImportError:
    HAVE_LIBCSA = False

try:
    import numpy
    HAVE_NUMPY = True
except ImportError:
    HAVE_NUMPY = False

nest.sli_run("statusdict/have_libneurosim ::")
HAVE_LIBNEUROSIM = nest.sli_pop()


@nest.check_stack
@unittest.skipIf(not HAVE_LIBCSA, 'Python libcsa package is not available')
@unittest.skipIf(
    not HAVE_LIBNEUROSIM,
    'PyNEST was built without the libneurosim library'
)
class libcsaTestCase(unittest.TestCase):
    """libcsa tests"""

    def test_libcsa_OneToOne_subnet_1d(self):
        """One-to-one connectivity with 1-dim subnets"""
Exemplo n.º 32
0
def create_nodes(model, pyrngs):
    """
        Creates the following GIDs:
        neuron_GIDs
        ext_poisson
        ext_dc
        th_parrots
        th_poisson
        spike_detectors
        multimeters
        th_spike_detector
    
        Further initializes the neurons" membrane potentials.
    """
    neuron_GIDs = []
    spike_detectors = []
    multimeters = []
    ext_poisson = []
    ext_dc = []
    print(data_path_test)
    Vm0_file = open(os.path.join(data_path_test, "Vm0_pynest"), "w")
    for pop_index, population in enumerate(model.populations):
        # Neurons
        neuron_GIDs.append(
            nest.Create(model.neuron_model,
                        model.n_neurons[pop_index],
                        params=model.model_params))
        # Initialize membrane potentials locally
        # drawn from normal distribution with mu=Vm0_mean, sigma=Vm0_std
        neurons_info = nest.GetStatus(neuron_GIDs[pop_index])
        for ni in neurons_info:
            if ni["local"]:  # only adapt local nodes
                sli_str3 = "%i << /V_m normal_rdvs %i get Random %.1f mul %.1f add >> SetStatus" % (
                    ni["global_id"], ni["vp"], model.Vm0_std, model.Vm0_mean)
                nest.sli_run(sli_str3)
                Vm_init = nest.GetStatus([ni["global_id"]])[0]["V_m"]
                #Vm_init = pyrngs[ni["vp"]].normal(model.Vm0_mean, model.Vm0_std)
                #nest.SetStatus([ni["global_id"]], {"V_m": Vm_init})
                Vm0_file.write(
                    str(ni["global_id"]) + "\t" + str(Vm_init) + "\n")

        # Devices
        if sim.record_cortical_spikes:
            spike_detector_dict = {
                "label": sim.spike_detector_label + population + "_",
                "to_file": sim.to_text_file
            }
            spike_detectors.append(
                nest.Create("spike_detector", 1, params=spike_detector_dict))

        if sim.record_voltage:
            multimeter_dict = {
                "label": sim.multimeter_label + population + "_",
                "to_file": sim.to_text_file,
                "start": sim.t_rec_volt_start,
                #"stop": sim.t_rec_volt_stop,
                "interval": 1.0,  # ms
                "withtime": True,
                "record_from": ["V_m"]
            }
            multimeters.append(
                nest.Create("multimeter", 1, params=multimeter_dict))

        # External input
        # One poisson generator per population.
        #Rate is determined by base rate times in-degree[population]
        ext_poisson_params = {"rate": model.rate_ext * model.C_aext[pop_index]}
        ext_poisson.append(
            nest.Create("poisson_generator", 1, params=ext_poisson_params))
        # One dc generator per population.
        # Amplitude is determined by base amplitude times in-degree[population]
        ext_dc_params = {
            "amplitude": model.dc_amplitude * model.C_aext[pop_index]
        }
        ext_dc.append(nest.Create("dc_generator", 1, params=ext_dc_params))

    # Thalamic neurons: parrot neurons and Poisson bg
    if not model.n_th == 0:
        th_parrots = nest.Create("parrot_neuron", model.n_th, params=None)
        th_poisson = nest.Create("poisson_generator",
                                 1,
                                 params={
                                     "rate": model.th_rate,
                                     "start": model.th_start,
                                     "stop": model.th_start + model.th_duration
                                 })
        if sim.record_thalamic_spikes:
            th_spike_detector_dict = {
                "label": sim.th_spike_detector_label,
                "to_file": sim.to_text_file
            }
            th_spike_detector = nest.Create("spike_detector",
                                            1,
                                            params=th_spike_detector_dict)
        else:
            th_spike_detector = None
    else:
        th_parrots, th_poisson, th_spike_detector = (None, None, None)

    Vm0_file.close()

    return (neuron_GIDs, spike_detectors, multimeters, ext_poisson, ext_dc,
            th_parrots, th_poisson, th_spike_detector)
Exemplo n.º 33
0
    def test_libcsa_cgnext(self):
        """cgnext"""

        nest.ResetKernel()

        w = 10000.0
        d = 1.0
        cs = libcsa.cset(libcsa.oneToOne, w, d)

        nest.sli_push(cs)
        nest.sli_run('dup')
        nest.sli_push(numpy.array([0, 1, 2, 3]))
        nest.sli_push(numpy.array([0, 1, 2, 3]))
        nest.sli_run('cgsetmask')
        nest.sli_run('dup')
        nest.sli_run('cgstart')
        for i in range(4):
            nest.sli_run('dup')
            nest.sli_run('cgnext')
            self.assertEqual(nest.sli_pop(), True)
            self.assertEqual(nest.sli_pop(), d)
            self.assertEqual(nest.sli_pop(), w)
            self.assertEqual(nest.sli_pop(), i)
            self.assertEqual(nest.sli_pop(), i)
        nest.sli_run('cgnext')
        self.assertEqual(nest.sli_pop(), False)
Exemplo n.º 34
0
    def test_libcsa_cgnext(self):
        """cgnext"""

        nest.ResetKernel()

        w = 10000.0
        d = 1.0
        cs = libcsa.cset(libcsa.oneToOne, w, d)

        nest.sli_push(cs)
        nest.sli_run('dup')
        nest.sli_push(numpy.array([0, 1, 2, 3]))
        nest.sli_push(numpy.array([0, 1, 2, 3]))
        nest.sli_run('cgsetmask')
        nest.sli_run('dup')
        nest.sli_run('cgstart')
        for i in range(4):
            nest.sli_run('dup')
            nest.sli_run('cgnext')
            self.assertEqual(nest.sli_pop(), True)
            self.assertEqual(nest.sli_pop(), d)
            self.assertEqual(nest.sli_pop(), w)
            self.assertEqual(nest.sli_pop(), i)
            self.assertEqual(nest.sli_pop(), i)
        nest.sli_run('cgnext')
        self.assertEqual(nest.sli_pop(), False)
Exemplo n.º 35
0
 def _set_verbosity(self, verbosity):
     nest.sli_run("M_%s setverbosity" % verbosity.upper())
Exemplo n.º 36
0
 def _set_verbosity(self, verbosity):
     nest.sli_run("M_%s setverbosity" % verbosity.upper())
Exemplo n.º 37
0
def LambertWm1(x):
    nest.sli_push(x)
    nest.sli_run('LambertWm1')
    y = nest.sli_pop()
    return y
Exemplo n.º 38
0
    print("Brunel network simulation (Python)")
    print("Number of neurons : {0}".format(N_neurons))
    # including devices and noise
    print("Number of synapses: {0}".format(num_synapses))
    # neurons + noise + spike detectors
    print(
        "       Exitatory  : {0}".format(int(CE * N_neurons) + 2 * N_neurons))
    print("       Inhibitory : {0}".format(int(CI * N_neurons)))
    print("Excitatory rate   : %.2f Hz" % rate_ex)
    print("Inhibitory rate   : %.2f Hz" % rate_in)
    print("Stimulus rate     : %.2f Hz" % rate_stim)
    print("Building time     : %.2f s" % build_time)
    print("Simulation time   : %.2f s" % sim_time)

    nest.sli_run('memory_thisjob')  # virtual memory size of NEST process
    memory = nest.sli_pop()
    print("Memory            : %.2f kB" % memory)
    '''
    A dictionary for population parameters is created to allow for easier access.
    '''

    pops = {}
    pops['EX'] = {}
    pops['IN'] = {}
    pops['STIM'] = {}

    # neuron numbers
    pops['EX']['N'] = NE
    pops['IN']['N'] = NI
    pops['STIM']['N'] = N_stim
Exemplo n.º 39
0
# NEST is free software: you can redistribute it and/or modify
# 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

nest.sli_run("statusdict/have_music ::")
if not nest.spp():
    import sys
    print("NEST was not compiled with support for MUSIC, not running.")
    sys.exit()

nest.set_verbosity("M_ERROR")

sg = nest.Create('spike_generator')
nest.SetStatus(sg, {'spike_times': [1.0, 1.5, 2.0]})

n = nest.Create('iaf_neuron')

nest.Connect(sg, n, 'one_to_one', {'weight': 750.0, 'delay': 1.0})

vm = nest.Create('voltmeter')
Exemplo n.º 40
0
    def fit_single_stp(self,
                       stp_in,
                       pre_idx,
                       post_idx,
                       stat_weight,
                       stat_fr,
                       tau_rec_0=1e-10,
                       pre_type='E'):
        # fit step
        step = self.itr_dict['step']

        # STP dict
        stp = copy.deepcopy(stp_in)
        if 'E' in pre_type:
            stp['tau_psc'] = self.params.net_dict['neuron_params'][
                'tau_syn_ex']
        else:
            stp['tau_psc'] = self.params.net_dict['neuron_params'][
                'tau_syn_in']
        stp['weight'] = stat_weight
        if stp['tau_rec'] == 0:
            stp['tau_rec'] = tau_rec_0

        # cell parameters
        ctsp = self.params.net_dict['ctsp']
        neuron_params = {
            'tau_syn_ex': self.params.net_dict['neuron_params']['tau_syn_ex'],
            'tau_syn_in': self.params.net_dict['neuron_params']['tau_syn_in'],
            'E_L': ctsp['E_L'][post_idx],
            'V_th': ctsp['V_th'][post_idx],
            'C_m': ctsp['C_m'][post_idx],
            'tau_m': ctsp['tau_m'][post_idx],
            'V_reset': ctsp['V_reset'][post_idx],
            't_ref': self.params.net_dict['neuron_params']['t_ref'],
        }

        # firing data
        spk_ts = np.round(np.arange(self.params.ai['start'],
                                    self.params.ai['end'], MS_PER_S / stat_fr),
                          decimals=1)

        # iterate
        for i in range(self.itr_dict['itr_limit']):
            # reset NEST everytime
            nest.ResetKernel()
            nest.sli_run("M_ERROR setverbosity")

            # set weight recorder
            wr = nest.Create('weight_recorder',
                             params={
                                 'to_memory': True,
                                 'to_file': False
                             })
            nest.CopyModel('tsodyks_synapse', 'wr_synapse',
                           {'weight_recorder': wr[0]})
            stp['model'] = 'wr_synapse'

            # set generator and neurons
            spk_gen = nest.Create('spike_generator',
                                  params={'spike_times': spk_ts})
            pre_parrot = nest.Create('parrot_neuron')
            post_neuron = nest.Create(self.params.net_dict['neuron_model'],
                                      params=neuron_params)

            # connect and simulate
            nest.Connect(spk_gen, pre_parrot, syn_spec={'weight': 1.})
            nest.Connect(pre_parrot, post_neuron, syn_spec=stp)
            nest.Simulate(self.t_stp_test)

            # get resultant weight
            stp_steady_weight = self.get_weight_record(wr)
            tmp_str = '{}. step, static, initial, steady={:.1f}, {:.1f}, {:.1f}, {:.1f}\n'.\
                format(i, step, stat_weight, stp['weight'], stp_steady_weight)
            self.log += tmp_str

            # modify initial weight according to result
            deviation = stat_weight - stp_steady_weight
            if abs(deviation) < step:
                step *= 0.5
            if abs(deviation) < self.itr_dict['dev_cri']:
                tmp_str = 'deviation={:.2}'.format(deviation)
                print(tmp_str)
                self.log += tmp_str + '\n'
                break
            stp['weight'] += np.sign(deviation) * step

            # break when n of iteration > limit
            if i == self.itr_dict['itr_limit'] - 1:
                tmp_str = 'deviation={:.2}, stopped at {}!'.format(
                    deviation, self.itr_dict['itr_limit'])
                print(tmp_str)
                self.log += tmp_str + '\n'

        return stp['weight']