Ejemplo n.º 1
0
    def _constructNetwork(self):
        '''Construct the E/I network'''
        self.e_neuron_params = gc_neurons.getENeuronParams(self.no)
        self.i_neuron_params = gc_neurons.getINeuronParams(self.no)

        self.B_GABA = 1.0  # Must be here for compatibility with brian code

        self.e_model_name = "iaf_gridcells"
        self.i_model_name = "iaf_gridcells"
        self.e_receptors = \
            nest.GetDefaults(self.e_model_name)['receptor_types']
        self.i_receptors = \
            nest.GetDefaults(self.i_model_name)['receptor_types']
        self.E_pop = nest.Create(self.e_model_name,
                                 self.net_Ne,
                                 params=self.e_neuron_params)
        self.I_pop = nest.Create(self.i_model_name,
                                 self.net_Ni,
                                 params=self.i_neuron_params)

        nest.CopyModel('static_synapse',
                       'I_AMPA_NMDA',
                       params={'receptor_type': self.i_receptors['AMPA_NMDA']})
        nest.CopyModel('static_synapse',
                       'E_GABA_A',
                       params={'receptor_type': self.e_receptors['GABA_A']})
        nest.CopyModel('static_synapse',
                       'PC_AMPA',
                       params={'receptor_type': self.e_receptors['AMPA']})

        # Connect E-->I and I-->E
        self._connect_network()
Ejemplo n.º 2
0
    def run(self, simtime=300):
        '''
        Simulate the model for simtime milliseconds and print the firing 
        rates of the network during this period.
        '''
        if not self.connected:
            self.connect()
        nest.Simulate(simtime)

        events_ex = nest.GetStatus(self.espikes, "n_events")[0]
        events_in = nest.GetStatus(self.ispikes, "n_events")[0]

        rate_ex = events_ex / simtime * 1000.0 / self.N_rec
        rate_in = events_in / simtime * 1000.0 / self.N_rec

        num_synapses = (nest.GetDefaults("excitatory")["num_connections"] +
                        nest.GetDefaults("inhibitory")["num_connections"])

        print("Brunel network simulation (Python)")
        print("Number of neurons : {0}".format(self.N_neurons))
        print("Number of synapses: {0}".format(num_synapses))
        print("       Exitatory  : {0}".format(int(self.CE * self.N_neurons) + self.N_neurons))
        print("       Inhibitory : {0}".format(int(self.CI * self.N_neurons)))
        print("Excitatory rate   : %.2f Hz" % rate_ex)
        print("Inhibitory rate   : %.2f Hz" % rate_in)
        # print("Building time     : %.2f s" % build_time)
        # print("Simulation time   : %.2f s" % sim_time)

        nest.raster_plot.from_device(self.espikes, hist=True)
        pl.show()
Ejemplo n.º 3
0
    def test_CopyModel(self):
        """CopyModel"""

        nest.ResetKernel()
        nest.CopyModel('iaf_neuron', 'new_neuron', {'V_m': 10.0})
        vm = nest.GetDefaults('new_neuron')['V_m']
        self.assertEqual(vm, 10.0)

        n = nest.Create('new_neuron', 10)
        vm = nest.GetStatus([n[0]])[0]['V_m']
        self.assertEqual(vm, 10.0)

        nest.CopyModel('static_synapse', 'new_synapse', {'weight': 10.})
        nest.Connect([n[0]], [n[1]], model='new_synapse')
        w = nest.GetDefaults('new_synapse')['weight']
        self.assertEqual(w, 10.0)

        try:
            nest.CopyModel('iaf_neuron',
                           'new_neuron')  # shouldn't be possible a second time
            self.fail('an error should have risen!')  # should not be reached
        except nest.NESTError:
            info = sys.exc_info()[1]
            if not "NewModelNameExists" in info.__str__():
                self.fail('could not pass error message to NEST!')
        # another error has been thrown, this is wrong
        except:
            self.fail('wrong error has been thrown')
    def testAAAResetKernel(self):
        """Test reset of recording backend defaults.

        As ResetKernel is used by many of the tests in this file to
        ensure a consistent initial state, this test has to be run
        before all others. This is ensured by prefix "AAA" in front of
        the name. See https://docs.python.org/3/library/unittest.html
        for details on test execution order.
        """

        nest.ResetKernel()

        mm_defaults = nest.GetDefaults("multimeter")
        rb_properties = ["record_to", "time_in_steps"]
        rb_defaults_initial = [mm_defaults[k] for k in rb_properties]

        self.assertEqual(rb_defaults_initial, ["memory", False])

        mm_defaults = {"record_to": "ascii", "time_in_steps": True}
        nest.SetDefaults("multimeter", mm_defaults)

        mm_defaults = nest.GetDefaults("multimeter")
        rb_properties = ["record_to", "time_in_steps"]
        rb_defaults = [mm_defaults[k] for k in rb_properties]

        self.assertEqual(rb_defaults, ["ascii", True])

        nest.ResetKernel()

        mm_defaults = nest.GetDefaults("multimeter")
        rb_properties = ["record_to", "time_in_steps"]
        rb_defaults = [mm_defaults[k] for k in rb_properties]

        self.assertEqual(rb_defaults_initial, rb_defaults)
Ejemplo n.º 5
0
    def test_SetStatusVth_E_L(self):
        """SetStatus of reversal and threshold potential """

        excluded = ['a2eif_cond_exp_HW', 'mat2_psc_exp', 'amat2_psc_exp']
        models = [m for m in nest.Models() if m not in excluded]

        for m in models:
            if all(key in nest.GetDefaults(m) for key in ('V_th', 'E_L')):
                nest.ResetKernel()

                neuron1 = nest.Create(m)
                neuron2 = nest.Create(m)

                # must not depend on the order
                new_EL = -90.
                new_Vth = -10.

                if 'V_reset' in nest.GetDefaults(m):
                    nest.SetStatus(neuron1 + neuron2, {'V_reset': new_EL})

                nest.SetStatus(neuron1, {'E_L': new_EL})
                nest.SetStatus(neuron2, {'V_th': new_Vth})
                nest.SetStatus(neuron1, {'V_th': new_Vth})
                nest.SetStatus(neuron2, {'E_L': new_EL})
                vth1, vth2 = nest.GetStatus(neuron1 + neuron2, 'V_th')
                self.assertEqual(vth1, vth2)
Ejemplo n.º 6
0
    def test_SetDefaults(self):
        """SetDefaults"""

        models = nest.Models()

        # sli_neuron does not work under PyNEST
        models.remove('sli_neuron')

        for m in models:
            if nest.GetDefaults(m).has_key('V_m'):
                nest.ResetKernel()
                v_m = nest.GetDefaults(m)['V_m']
                nest.SetDefaults(m, {'V_m': -1.})
                self.assertEqual(nest.GetDefaults(m)['V_m'], -1.)
                nest.SetDefaults(m, {'V_m': v_m})

                try:
                    nest.SetDefaults(m, {'DUMMY': 0})
                except nest.NESTError:
                    info = sys.exc_info()[1]
                    if not "DictError" in info.__str__():
                        self.fail('wrong error message')
                # any other error is wrongly thrown
                except:
                    self.fail('wrong error has been thrown')
Ejemplo n.º 7
0
    def test_GetDefaults_JSON(self):
        """JSON data of GetDefaults"""

        for model in nest.node_models + nest.synapse_models:
            d_json = nest.GetDefaults(model, output='json')
            self.assertIsInstance(d_json, str)

            d = nest.GetDefaults(model)
            d_json = nest.to_json(d)
            self.assertIsInstance(d_json, str)
Ejemplo n.º 8
0
    def test_GetDefaults_JSON(self):
        """JSON data of GetDefaults"""

        for m in nest.Models():
            d_json = nest.GetDefaults(m, output='json')
            self.assertIsInstance(d_json, str)

            d = nest.GetDefaults(m)
            d_json = nest.hl_api.to_json(d)
            self.assertIsInstance(d_json, str)
    def test_ConnectNeuronsWithUrbanczikSynapse(self):
        """Ensures that the restriction to supported neuron models works."""

        nest.set_verbosity('M_WARNING')

        # Multi-compartment models
        mc_models = [
            "iaf_cond_alpha_mc",
            "pp_cond_exp_mc_urbanczik",
        ]

        # Supported models
        supported_models = [
            "pp_cond_exp_mc_urbanczik",
        ]

        # Compute not supported models
        not_supported_models = [
            n for n in nest.Models(mtype='nodes') if n not in supported_models
        ]

        # Connect supported models with Urbanczik synapse
        for nm in supported_models:
            nest.ResetKernel()

            r_type = 0
            if nm in mc_models:
                syns = nest.GetDefaults(nm)["receptor_types"]
                r_type = syns["soma_exc"]

            n = nest.Create(nm, 2)

            nest.Connect(n, n, {"rule": "all_to_all"}, {
                "synapse_model": "urbanczik_synapse",
                "receptor_type": r_type
            })

        # Ensure that connecting not supported models fails
        for nm in not_supported_models:
            nest.ResetKernel()

            r_type = 0
            if nm in mc_models:
                syns = nest.GetDefaults(nm)["receptor_types"]
                r_type = syns["soma_exc"]

            n = nest.Create(nm, 2)

            # try to connect with urbanczik synapse
            with self.assertRaises(nest.kernel.NESTError):
                nest.Connect(n, n, {"rule": "all_to_all"}, {
                    "synapse_model": "urbanczik_synapse",
                    "receptor_type": r_type
                })
Ejemplo n.º 10
0
    def test_GetDefaults_JSON(self):
        """JSON data of GetDefaults"""

        # sli_neuron does not work under PyNEST
        models = (m for m in nest.Models() if m != 'sli_neuron')

        for m in models:
            d_json = nest.GetDefaults(m, output='json')
            self.assertIsInstance(d_json, str)

            d = nest.GetDefaults(m)
            d_json = nest.hl_api.to_json(d)
            self.assertIsInstance(d_json, str)
Ejemplo n.º 11
0
    def test_models(self):
        """Time objects in models correctly updated"""
        # Generate a dictionary of reference values for each model.
        reference = {}
        for model in nest.Models():
            if model in self.ignored_models:
                continue
            try:
                reference[model] = nest.GetDefaults(model)
            except nest.kernel.NESTError:
                # If we can't get the defaults, we ignore the model.
                pass

        # Change the tic-base.
        nest.set(resolution=0.5, tics_per_ms=1500.0)

        # At this point, Time objects in models should have been updated to
        # account for the new tic-base. Values in model defaults should therefore
        # be equal (within a tolerance) to the reference values.

        failing_models = []
        for model in reference.keys():
            model_reference = reference[model]
            model_defaults = nest.GetDefaults(model)
            # Remove entries where the item contains more than one value, as this causes issues when comparing.
            array_keys = [
                key for key, value in model_defaults.items()
                if isinstance(value, (list, tuple, dict, np.ndarray))
            ]
            for key in array_keys:
                del model_defaults[key]
                del model_reference[key]

            keydiff = []
            for key, value in model_defaults.items():
                # value may not be a number, so we test for equality first.
                # If it's not equal to the reference value, we assume it is a number.
                if value != model_reference[key] and abs(
                        value - model_reference[key]) > self.eps:
                    print(value - model_reference[key])
                    keydiff.append([key, model_reference[key], value])
            # If any keys have values different from the reference, the model fails.
            if len(keydiff) > 0:
                print(model, keydiff)
                failing_models.append(model)

        # No models should fail for the test to pass.
        self.assertEqual([], failing_models)
Ejemplo n.º 12
0
    def test_GetLabeledSynapses(self):
        """Get labeled synapses with GetConnections."""

        labeled_synapse_models = [s for s in nest.Models(
            mtype='synapses') if s.endswith("_lbl")]
        for syn in labeled_synapse_models:
            a = self.default_network(syn)

            # see if symmetric connections are required
            symm = nest.GetDefaults(syn, 'requires_symmetric')

            # some more connections
            synapse_type = "static_synapse"
            if syn in self.rate_model_connections:
                synapse_type = "rate_connection_instantaneous"
            if syn in self.siegert_connections:
                synapse_type = "diffusion_connection"
            nest.Connect(a, a, {"rule": "one_to_one"},
                         {"model": synapse_type})
            # set a label during connection
            nest.Connect(a, a, {"rule": "one_to_one", "make_symmetric": symm},
                         {"model": syn, "synapse_label": 123})
            c = nest.GetConnections(a, a, synapse_label=123)
            self.assertTrue(
                all([
                    status['synapse_label'] == 123
                    for status in nest.GetStatus(c)
                    ])
            )
Ejemplo n.º 13
0
    def test_SetLabelToSynapseSetStatus(self):
        """Set a label to a labeled synapse on SetStatus."""

        labeled_synapse_models = [s for s in nest.Models(
            mtype='synapses') if s.endswith("_lbl")]
        for syn in labeled_synapse_models:
            a = self.default_network(syn)

            # see if symmetric connections are required
            symm = nest.GetDefaults(syn, 'requires_symmetric')

            # set no label during connection
            nest.Connect(a, a, {"rule": "one_to_one", "make_symmetric": symm},
                         {"model": syn})
            c = nest.GetConnections(a, a)
            # still unlabeled
            self.assertTrue(
                all([
                    status['synapse_label'] == -1
                    for status in nest.GetStatus(c)
                    ])
            )

            # set a label
            nest.SetStatus(c, {'synapse_label': 123})
            self.assertTrue(
                all([
                    status['synapse_label'] == 123
                    for status in nest.GetStatus(c)
                    ])
            )
Ejemplo n.º 14
0
def extract_nestvalid_dict(d, param_type='neuron'):
    """
    Verify whether the parameters dictionary are in the correct format, with adequate keys, in agreement with the nest
    parameters dictionaries so that they can later be passed as direct input to nest.

    :param d: parameter dictionary
    :param param_type: type of parameters - kernel, neuron, population, network, connections, topology
    :return: valid dictionary
    """
    if param_type == 'neuron' or param_type == 'synapse' or param_type == 'device':
        assert d['model'] in nest.Models(
        ), "Model %s not currently implemented in %s" % (d['model'],
                                                         nest.version())

        accepted_keys = nest.GetDefaults(d['model']).keys()
        accepted_keys.remove('model')
        nest_dict = {k: v for k, v in d.iteritems() if k in accepted_keys}
    elif param_type == 'kernel':
        accepted_keys = nest.GetKernelStatus().keys()
        nest_dict = {k: v for k, v in d.iteritems() if k in accepted_keys}
    else:
        # TODO
        logger.error("{!s} not implemented yet".format(param_type))
        exit(-1)

    return nest_dict
Ejemplo n.º 15
0
    def test_GetStatus(self):
        """GetStatus"""

        for m in nest.Models():
            if 'V_m' in nest.GetDefaults(m):
                nest.ResetKernel()

                n = nest.Create(m)

                d = nest.GetStatus(n)
                self.assertIsInstance(d, tuple)
                self.assertIsInstance(d[0], dict)
                self.assertGreater(len(d[0]), 1)

                v1 = nest.GetStatus(n)[0]['V_m']
                v2 = nest.GetStatus(n, 'V_m')[0]
                self.assertEqual(v1, v2)

                n = nest.Create(m, 10)
                d = nest.GetStatus(n, 'V_m')
                self.assertEqual(len(d), len(n))
                self.assertIsInstance(d[0], float)

                test_keys = ("V_m", ) * 3
                d = nest.GetStatus(n, test_keys)
                self.assertEqual(len(d), len(n))
                self.assertEqual(len(d[0]), len(test_keys))
Ejemplo n.º 16
0
 def create(self):
     from nest import topology as tp
     import nest
     # Create sublayers
     self._layer_call('create')
     # Set the GID
     self._gid = flatten(self._layer_get('gid'))
     # Connect stimulators to parrots, one-to-one
     # IMPORTANT: This assumes that all layers are the same size!
     radius = self.extent_units(0.1)
     one_to_one_connection = {
         'sources': {
             'model': self.stimulator_model
         },
         'targets': {
             'model': self.PARROT_MODEL
         },
         'connection_type': 'convergent',
         'synapse_model': 'static_synapse',
         'mask': {
             'circular': {
                 'radius': radius
             }
         }
     }
     tp.ConnectLayers(self._gid, self._gid, one_to_one_connection)
     # Get stimulator type
     self.stimulator_type = nest.GetDefaults(self.stimulator_model,
                                             'type_id')
    def test_w_decay(self):
        """Decay of w_jk, proportional to alpha"""
        self.setUp_decay(
            params={
                'p_fail': 1.,
                'n_pot_conns': 1,
                'A2_corr': 0.,
                'A4_corr': 0.,
                'A4_post': 0.
            })

        nest.SetStatus(self.syn, {'w_jk': [1.]})

        syn_defaults = nest.GetDefaults('testsyn')
        alpha = syn_defaults['alpha']

        nest.Simulate(101.)
        syn_status = nest.GetStatus(self.syn)

        nest.Simulate(100.)
        syn_status = nest.GetStatus(self.syn)

        dt = 0.001
        prop = np.exp(-dt * alpha)

        val = syn_status[0]['w_jk'][0]
        val_exp = 1. * prop**200.

        self.assertAlmostEqualDetailed(val_exp, val,
                                       "Weight decay (alpha) not correct.")
Ejemplo n.º 18
0
def _monitor(gids, nest_recorder, params):
    new_record = []
    recorders = []
    for i, rec in enumerate(nest_recorder):
        # multi/volt/conductancemeter
        if "meter" in rec:
            device = None
            di_spec = {"rule": "all_to_all"}
            if not params[i].get("to_accumulator", True):
                device = nest.Create(rec, len(gids))
                di_spec["rule"] = "one_to_one"
            else:
                device = nest.Create(rec)
            recorders.append(device)
            device_params = nest.GetDefaults(rec)
            device_params.update(params[i])
            new_record.append(device_params["record_from"])
            nest.SetStatus(device, params[i])
            nest.Connect(device, gids, conn_spec=di_spec)
        # event detectors
        elif "detector" in rec:
            device = nest.Create(rec)
            recorders.append(device)
            new_record.append("spikes")
            nest.SetStatus(device, params[i])
            nest.Connect(gids, device)
        else:
            raise InvalidArgument('Invalid recorder item in `nest_recorder`: '
                                  '{} is unknown.'.format(nest_recorder))
    return tuple(recorders), new_record
Ejemplo n.º 19
0
    def test_GetStatus(self):
        """GetStatus"""

        # sli_neuron does not work under PyNEST
        models = (m for m in nest.Models() if m != 'sli_neuron')

        for m in models:
            if 'V_m' in nest.GetDefaults(m):
                nest.ResetKernel()

                n = nest.Create(m)

                d = nest.GetStatus(n)
                self.assertIsInstance(d, tuple)
                self.assertIsInstance(d[0], dict)
                self.assertGreater(len(d[0]), 1)

                v1 = nest.GetStatus(n)[0]['V_m']
                v2 = nest.GetStatus(n, 'V_m')[0]
                self.assertEqual(v1, v2)

                n = nest.Create(m, 10)
                d = nest.GetStatus(n, 'V_m')
                self.assertEqual(len(d), len(n))
                self.assertIsInstance(d[0], float)

                test_keys = ("V_m", ) * 3
                d = nest.GetStatus(n, test_keys)
                self.assertEqual(len(d), len(n))
                self.assertEqual(len(d[0]), len(test_keys))
Ejemplo n.º 20
0
    def test_refractory_time(self):
        '''
        Check that refractory time implementation is correct.
        '''
        for model in tested_models:
            self.reset()

            if "t_ref" not in nest.GetDefaults(model):
                continue

            # Randomly set a refractory period
            t_ref = 1.7
            # Create the neuron and devices
            nparams = {"t_ref": t_ref}
            neuron = nest.Create(model, params=nparams)

            name_Vm = "V_m.s" if model in mc_models else "V_m"
            vm_params = {"interval": resolution, "record_from": [name_Vm]}
            vm = nest.Create("voltmeter", params=vm_params)
            sr = nest.Create("spike_recorder")
            cg = nest.Create("dc_generator", params={"amplitude": 1200.})

            # For models that do not clamp V_m, use very large current to
            # trigger almost immediate spiking => t_ref almost equals
            # interspike
            if model in neurons_interspike_ps:
                nest.SetStatus(cg, "amplitude", 10000000.)
            elif model == 'ht_neuron':
                # ht_neuron use too long time with a very large amplitude
                nest.SetStatus(cg, "amplitude", 2000.)
            elif model in neurons_interspike:
                nest.SetStatus(cg, "amplitude", 15000.)

            # Connect them and simulate
            nest.Connect(vm, neuron)
            nest.Connect(cg, neuron, syn_spec=add_connect_param.get(model, {}))
            nest.Connect(neuron, sr)

            nest.Simulate(simtime)

            # Get and compare t_ref
            t_ref_sim = self.compute_reftime(model, sr, vm, neuron)

            if model in neurons_with_clamping:
                t_ref_sim = t_ref_sim - nest.GetStatus(neuron, "t_clamp")[0]

            # Approximate result for precise spikes (interpolation error)
            if model in neurons_interspike_ps:
                self.assertAlmostEqual(t_ref,
                                       t_ref_sim,
                                       places=3,
                                       msg='''Error in model {}:
                                       {} != {}'''.format(
                                           model, t_ref, t_ref_sim))
            else:
                self.assertAlmostEqual(t_ref,
                                       t_ref_sim,
                                       msg='''Error in model {}:
                                       {} != {}'''.format(
                                           model, t_ref, t_ref_sim))
    def testGlobalRecordingBackendProperties(self):
        """Test setting of global backend properties.

        This sets and gets global backend properties and only runs if
        compiled with SIONlib, as the corresponding backend is the
        only backend with global parameters.
        """

        nest.ResetKernel()

        if HAVE_SIONLIB:
            chunksize_before = nest.GetDefaults("sionlib", "sion_chunksize")
            sionlib_options = {"sion_chunksize": chunksize_before + 1}
            nest.SetDefaults("sionlib", sionlib_options)
            chunksize_after = nest.GetDefaults("sionlib", "sion_chunksize")
            self.assertEqual(chunksize_after, chunksize_before + 1)
Ejemplo n.º 22
0
def get_defaults(model_name):
    valid_types = (int, float, Sequence, np.ndarray)
    defaults = nest.GetDefaults(model_name)
    variables = defaults.get('recordables', [])
    ignore = [
        'archiver_length', 'available', 'Ca', 'capacity', 'elementsize',
        'frozen', 'instantiations', 'local', 'model', 'needs_prelim_update',
        'recordables', 'state', 't_spike', 'tau_minus', 'tau_minus_triplet',
        'thread', 'vp', 'receptor_types', 'events', 'global_id',
        'element_type', 'type', 'type_id', 'has_connections', 'n_synapses',
        'thread_local_id', 'node_uses_wfr', 'supports_precise_spikes',
        'synaptic_elements', 'y_0', 'y_1', 'allow_offgrid_spikes',
        'shift_now_spikes', 'post_trace'
    ]
    default_params = {}
    default_initial_values = {}
    for name, value in defaults.items():
        if name in variables:
            default_initial_values[name] = value
        elif name not in ignore:
            if isinstance(value, valid_types):
                default_params[name] = conversion.make_pynn_compatible(value)
            else:
                warnings.warn(
                    "Ignoring parameter '%s' since PyNN does not support %s" %
                    (name, type(value)))
    return default_params, default_initial_values
    def testSetDefaultRecordingBackend(self):
        """Test setting the default recording backend.

        Test if setting another default recording backend for a
        recording device works and does not influence the default
        backend of all other recording devices.
        """

        nest.ResetKernel()

        nest.SetDefaults("multimeter", {"record_to": "ascii"})
        rb_defaults_mm = nest.GetDefaults("multimeter")["record_to"]
        rb_defaults_sr = nest.GetDefaults("spike_recorder")["record_to"]

        self.assertEqual(rb_defaults_mm, "ascii")
        self.assertEqual(rb_defaults_sr, "memory")
Ejemplo n.º 24
0
    def test_GetLabeledSynapses(self):
        """Get labeled synapses with GetConnections."""

        for syn in [s for s in nest.synapse_models if s.endswith("_lbl")]:
            a, r_type = self.default_network(syn)

            # see if symmetric connections are required
            symm = nest.GetDefaults(syn, 'requires_symmetric')

            # some more connections
            synapse_type = "static_synapse"
            if syn in self.rate_model_connections:
                synapse_type = "rate_connection_instantaneous"
            if syn in self.siegert_connections:
                synapse_type = "diffusion_connection"
            nest.Connect(a, a, {"rule": "one_to_one"}, {
                "synapse_model": synapse_type,
                "receptor_type": r_type
            })
            # set a label during connection
            nest.Connect(a, a, {
                "rule": "one_to_one",
                "make_symmetric": symm
            }, {
                "synapse_model": syn,
                "synapse_label": 123,
                "receptor_type": r_type
            })
            c = nest.GetConnections(a, a, synapse_label=123)
            self.assertTrue(all([x == 123 for x in c.get('synapse_label')]))
Ejemplo n.º 25
0
    def test_SetLabelToNotLabeledSynapse(self):
        """Try set a label to an 'un-label-able' synapse."""
        labeled_synapse_models = [s for s in nest.Models(
            mtype='synapses') if not s.endswith("_lbl")]
        for syn in labeled_synapse_models:
            a = self.default_network(syn)

            # see if symmetric connections are required
            symm = nest.GetDefaults(syn, 'requires_symmetric')

            # try set a label during SetDefaults
            with self.assertRaises(nest.kernel.NESTError):
                nest.SetDefaults(syn, {'synapse_label': 123})

            # try set on connect
            with self.assertRaises(nest.kernel.NESTError):
                nest.Connect(a, a, {"rule": "one_to_one",
                                    "make_symmetric": symm},
                             {"model": syn, "synapse_label": 123})

            # plain connection
            nest.Connect(a, a, {"rule": "one_to_one", "make_symmetric": symm},
                         {"model": syn})
            # try set on SetStatus
            c = nest.GetConnections(a, a)
            with self.assertRaises(nest.kernel.NESTError):
                nest.SetStatus(c, {'synapse_label': 123})
    def test_decay_Rpre_half_fail(self):
        """Stochastic and selective increase of r_jk, plus decay"""
        self.setUp_decay(params={'p_fail': .2, 'n_pot_conns': 2})

        # this seed lets the first spike on syn 0 and the second spike on syn 1
        # pass
        msd = 4
        N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
        nest.SetKernelStatus({'grng_seed': msd + N_vp})
        nest.SetKernelStatus(
            {'rng_seeds': range(msd + N_vp + 1, msd + 2 * N_vp + 1)})

        nest.Simulate(210.)

        syn_status = nest.GetStatus(self.syn)
        syn_defaults = nest.GetDefaults('testsyn')
        val = syn_status[0]['r_jk']
        dt = 0.001
        tau = syn_defaults['tau']
        prop = np.exp(-dt / tau)

        spike0 = 1. / tau * prop**100.  # propagate spike 1 by 100ms
        # no spike increase on 1, only second spike increase on 2
        val_exp = [spike0, 1. / tau]
        for k in range(len(val)):
            self.assertAlmostEqualDetailed(
                val_exp[k], val[k],
                "Decay of r_jk[%i] not as expected (stochastic case)" % k)
Ejemplo n.º 27
0
    def _apply_generators_to_neurons(self, uuid, parameters, gids, multiple):
        """
        Creates the generator(s), sets status and does the mapping
        between gids and nest neurons.
        """
        generator_name = str(parameters['model'][0])
        del parameters['model']  # Removed to avoid a spurious exception
        generators = _nest.Create(generator_name, len(gids) if multiple else 1)
        try:
            # Coercing numeric parameter types to avoid errors
            defaults = _nest.GetDefaults(generator_name)
            for key, value in parameters.items():
                value_type = type(defaults[key])
                type_name = value_type.__name__
                if type_name == 'int' or type_name == 'float':
                    parameters[key] = value_type(value)
            _nest.SetStatus(generators, parameters)
        except _nest.pynestkernel.NESTError as e:
            if 'DictError' not in str(e):
                print(e)

        self._generator_dict[uuid] = generators

        neurons = []
        for gid in gids:
            neurons.append(self._gid_to_neuron_map[gid])

        self._apply_generators_to_neurons_function(generators, neurons)
Ejemplo n.º 28
0
def syn(specs):
    if isinstance(specs, str):
        return specs
    if len(specs) == 0:
        return 'static_synapse'
    spec_defaults = nest.GetDefaults(specs.get('model', 'static_synapse'))
    return _paramify(specs, spec_defaults)
Ejemplo n.º 29
0
 def setUpNodes(self):
     self.n = nest.Create('iaf_cond_alpha_mc')
     rqs = nest.GetDefaults('iaf_cond_alpha_mc')['recordables']
     self.mm = nest.Create('multimeter',
                           params={
                               'record_from': rqs,
                               'interval': 0.1
                           })
     self.cgs = nest.Create('dc_generator', 3)
     nest.SetStatus(self.cgs, [
         self.rec_dic_dc_soma, self.rec_dic_dc_proximal,
         self.rec_dic_dc_distal
     ])
     self.sgs = nest.Create('spike_generator', 6)
     nest.SetStatus(self.sgs, [{
         'spike_times': self.rec_sp_soma_ex
     }, {
         'spike_times': self.rec_sp_soma_in
     }, {
         'spike_times': self.rec_sp_prox_ex
     }, {
         'spike_times': self.rec_sp_prox_in
     }, {
         'spike_times': self.rec_sp_dist_ex
     }, {
         'spike_times': self.rec_sp_dist_in
     }])
Ejemplo n.º 30
0
    def test_nest_instantiability(self):
        # N.B. all models are assumed to have been already built (see .travis.yml)

        nest.ResetKernel()
        nest.set_verbosity("M_ALL")
        nest.Install("nestml_allmodels_module")

        models = nest.Models(mtype="nodes")
        neuron_models = [
            m for m in models
            if str(nest.GetDefaults(m, "element_type")) == "neuron"
        ]
        _neuron_models = strip_suffix(neuron_models, "_neuron")

        nestml_unit_test_models = [
            neuron_model_name for neuron_model_name in _neuron_models
            if neuron_model_name.endswith("_nestml")
        ]

        nest.ResetKernel()

        for neuron_model in nestml_unit_test_models:
            print("Instantiating neuron model: " + str(neuron_model))
            nest.Create(neuron_model)

        nest.Simulate(100.)