Exemple #1
0
def InstallBCPNN(on_milner=False, on_beskow=False):
    '''
    This function installs the BCPNN Synapse by Phil Tully.
    The optional parameter passed, indicate whether this is on Supercomputer Milner (True) or Beskow
    or my local machine (False)
    '''
    if ('milner' in os.getcwd()):
        on_milner = True
    if ('klemming' in os.getcwd()):
        on_beskow = True
    if (not 'bcpnn_synapse' in nest.Models('synapses')):
        if on_beskow:
            nest.sr(
                '(/cfs/klemming/nobackup/f/fiebig/170501_Beskow_BCPNN/share/nest/sli) addpath'
            )
            nest.Install(
                '/cfs/klemming/nobackup/f/fiebig/170501_Beskow_BCPNN/lib/nest/pt_module'
            )
        elif on_milner:
            nest.sr(
                '(/cfs/milner/scratch/f/fiebig/140408_Milner_BCPNN/share/nest/sli) addpath'
            )
            nest.Install(
                '/cfs/milner/scratch/f/fiebig/140408_Milner_BCPNN/lib/nest/pt_module'
            )
        else:
            try:
                nest.Install('pt_module')
            except:
                nest.Install('pt_module')
Exemple #2
0
    def test_synapse_creation(self):
        for syn_model in nest.Models('synapses'):
            if syn_model not in self.exclude_synapse_model:
                nest.ResetKernel()
                syn_dict = {
                    'synapse_model': syn_model,
                    'pre_synaptic_element': 'SE1',
                    'post_synaptic_element': 'SE2'
                }
                nest.structural_plasticity_synapses = {'syn1': syn_dict}
                neurons = nest.Create('iaf_psc_alpha', 2, {
                    'synaptic_elements': {
                        'SE1': {'z': 10.0, 'growth_rate': 0.0},
                        'SE2': {'z': 10.0, 'growth_rate': 0.0}
                    }
                })
                nest.EnableStructuralPlasticity()
                nest.Simulate(10.0)
                status = nest.GetStatus(neurons, 'synaptic_elements')
                for st_neuron in status:
                    self.assertEqual(10, st_neuron['SE1']['z_connected'])
                    self.assertEqual(10, st_neuron['SE2']['z_connected'])

                self.assertEqual(
                    20, len(nest.GetConnections(neurons, neurons, syn_model)))
                break
Exemple #3
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
    def test_ConnectNeuronsWithClopathSynapse(self):
        """Ensures that the restriction to supported neuron models works."""

        nest.set_verbosity('M_WARNING')

        # Specify supported models
        supported_models = [
            'aeif_psc_delta_clopath',
            'hh_psc_alpha_clopath',
        ]

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

            n = nest.Create(nm, 2)

            nest.Connect(n, n, {"rule": "all_to_all"},
                         {"synapse_model": "clopath_synapse"})

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

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

            n = nest.Create(nm, 2)

            # try to connect with clopath_rule
            with self.assertRaises(nest.kernel.NESTError):
                nest.Connect(n, n, {"rule": "all_to_all"},
                             {"synapse_model": "clopath_synapse"})
Exemple #5
0
    def _get_nest_synapse_model(self):
        base_model = self.possible_models
        if isinstance(base_model, set):
            logger.warning("Several STDP models are available for these connections:")
            logger.warning(", ".join(model for model in base_model))
            base_model = list(base_model)[0]
            logger.warning("By default, %s is used" % base_model)
        available_models = nest.Models(mtype='synapses')
        if base_model not in available_models:
            raise ValueError("Synapse dynamics model '%s' not a valid NEST synapse model. "
                             "Possible models in your NEST build are: %s" % (base_model, available_models))

        # Defaults must be simple floats, so we use the NEST defaults
        # for any inhomogeneous parameters, and set the inhomogeneous values
        # later
        synapse_defaults = {}
        for name, value in self.native_parameters.items():
            if value.is_homogeneous:
                value.shape = (1,)
                synapse_defaults[name] = value.evaluate(simplify=True)
        synapse_defaults.pop("dendritic_delay_fraction")
        synapse_defaults.pop("w_min_always_zero_in_NEST")
        # Tau_minus is a parameter of the post-synaptic cell, not of the connection
        synapse_defaults.pop("tau_minus", None)

        synapse_defaults = make_sli_compatible(synapse_defaults)
        nest.SetDefaults(base_model + '_lbl', synapse_defaults)
        return base_model + '_lbl'
Exemple #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')
    def test_multiple_synapse_deletion_one_to_one_no_sp(self):
        for syn_model in nest.Models('synapses'):
            if syn_model not in self.exclude_synapse_model:
                nest.ResetKernel()
                nest.CopyModel('static_synapse', 'my_static_synapse')
                neurons = nest.Create('iaf_psc_alpha', 10)
                syn_dict = {'synapse_model': syn_model}
                nest.Connect(neurons, neurons, "all_to_all", syn_dict)

                src_neurons = neurons[:5]
                tgt_neurons = neurons[5:]

                conns = nest.GetConnections(src_neurons, tgt_neurons,
                                            syn_model)
                assert len(conns) == 25

                conndictionary = {'rule': 'one_to_one'}
                syndictionary = {'synapse_model': syn_model}
                nest.Disconnect(
                    src_neurons,
                    tgt_neurons,
                    conndictionary,
                    syndictionary
                )

                conns = nest.GetConnections(src_neurons, tgt_neurons,
                                            syn_model)
                assert len(conns) == 20
 def test_GetConnectionsSourceModels(self):
     """GetConnections iterating models for source"""
     for model in nest.Models():
         nest.ResetKernel()
         alpha = nest.Create('iaf_psc_alpha')
         try:
             other = nest.Create(model)
             nest.Connect(other, alpha)
         except nest.kernel.NESTError:
             # If we can't create a node with this model, or connect
             # to a node of this model, we ignore it.
             continue
         for get_conn_args in [{
                 'source': other,
                 'target': alpha
         }, {
                 'source': other
         }, {
                 'target': alpha
         }]:
             conns = nest.GetConnections(**get_conn_args)
             self.assertEqual(
                 len(conns), 1,
                 'Failed to get connection with source model {} (specifying {})'
                 .format(model, ', '.join(get_conn_args.keys())))
Exemple #9
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},
                             {"synapse_model": syn, "synapse_label": 123})

            # plain connection
            nest.Connect(a, a, {"rule": "one_to_one", "make_symmetric": symm},
                         {"synapse_model": syn})
            # try set on SetStatus
            c = nest.GetConnections(a, a)

            with self.assertRaises(nest.kernel.NESTError):
                c.set({'synapse_label': 123})
Exemple #10
0
def MyCopyModel(params, new_name):

    params = deepcopy(params)
    type_id = params['type_id']
    del params['type_id']
    if not new_name in nest.Models():
        CopyModel(type_id, new_name, params)
Exemple #11
0
    def test_SetLabelToSynapseOnConnect(self):
        """Set a label to a labeled synapse on connect."""

        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()

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

            # 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)
            self.assertTrue(
                all([
                    status['synapse_label'] == 123
                    for status in nest.GetStatus(c)
                ]))
    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)
Exemple #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, r_type = 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
            }, {
                "synapse_model": syn,
                "receptor_type": r_type
            })
            c = nest.GetConnections(a, a)
            # still unlabeled
            self.assertTrue(all([x == -1 for x in c.get('synapse_label')]))

            # set a label
            c.set({'synapse_label': 123})
            self.assertTrue(all([x == 123 for x in c.get('synapse_label')]))
    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()

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

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

            # plain connection
            nest.Connect(a, a, {"rule": "one_to_one"}, {"model": syn})
            # try set on SetStatus
            c = nest.GetConnections(a, a)
            with self.assertRaises(nest.NESTError):
                nest.SetStatus(c, {'synapse_label': 123})
    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))
    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()

            # set no label during connection
            nest.Connect(a, a, {"rule": "one_to_one"}, {"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)
                ]))
    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.)
Exemple #18
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))
Exemple #19
0
    def test_ModelCreateN(self):
        """Model Creation with N"""

        num_nodes = 10
        for model in nest.Models(mtype='nodes'):
            nodes = nest.Create(model, num_nodes)
            self.assertEqual(len(nodes), num_nodes)
    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)
                    ])
            )
Exemple #21
0
    def test_multiple_synapse_deletion_all_to_all(self):
        for syn_model in nest.Models('synapses'):
            if syn_model not in self.exclude_synapse_model:
                nest.ResetKernel()
                nest.CopyModel('static_synapse', 'my_static_synapse')
                nest.SetDefaults(syn_model, {'delay': 0.5})
                syn_dict = {
                    'model': syn_model,
                    'pre_synaptic_element': 'SE1',
                    'post_synaptic_element': 'SE2'
                }
                nest.SetKernelStatus({
                    'min_delay': 0.1,
                    'max_delay': 1.0,
                    'structural_plasticity_synapses': {
                        'syn1': syn_dict
                    }
                })
                neurons = nest.Create(
                    'iaf_psc_alpha', 10, {
                        'synaptic_elements': {
                            'SE1': {
                                'z': 0.0,
                                'growth_rate': 0.0
                            },
                            'SE2': {
                                'z': 0.0,
                                'growth_rate': 0.0
                            }
                        }
                    })

                nest.Connect(neurons, neurons, "all_to_all", syn_dict)

                # Test if the connected synaptic elements before the simulation
                # are correct
                status = nest.GetStatus(neurons, 'synaptic_elements')
                for st_neuron in status:
                    self.assertEqual(10, st_neuron['SE1']['z_connected'])
                    self.assertEqual(10, st_neuron['SE2']['z_connected'])

                srcId = range(0, 5)
                targId = range(5, 10)

                conns = nest.GetConnections(srcId, targId, syn_model)
                assert conns

                conndictionary = {'rule': 'all_to_all'}
                syndictionary = {'model': syn_model}
                nest.Disconnect([neurons[i] for i in srcId],
                                [neurons[i] for i in targId], conndictionary,
                                syndictionary)
                status = nest.GetStatus(neurons, 'synaptic_elements')
                for st_neuron in status[0:5]:
                    self.assertEqual(5, st_neuron['SE1']['z_connected'])
                    self.assertEqual(10, st_neuron['SE2']['z_connected'])
                for st_neuron in status[5:10]:
                    self.assertEqual(10, st_neuron['SE1']['z_connected'])
                    self.assertEqual(5, st_neuron['SE2']['z_connected'])
def ensure_visionary_nest_model_available(model):
    """Try to load nest and try to install 'visionarymodule'.
    Return value indicates if nest and the specified model is available
    afterwards.
    """
    try:
        import nest
    except ImportError:
        return False

    if model not in nest.Models():
        try:
            nest.Install("visionarymodule")
        except nest.pynestkernel.NESTError:
            return False

    return model in nest.Models()
Exemple #23
0
    def test_ModelCreate(self):
        """Model Creation"""

        nest.ResetKernel()

        for model in nest.Models(mtype='nodes'):
            node = nest.Create(model)
            self.assertGreater(node[0], 0)
Exemple #24
0
 def set_delays(self, min_delay, max_delay):
     if min_delay != 'auto': 
         min_delay = float(min_delay)
         max_delay = float(max_delay)
         for synapse_model in nest.Models(mtype='synapses'):
             nest.SetDefaults(synapse_model, {'delay'    : min_delay,
                                              'min_delay': min_delay,
                                              'max_delay': max_delay})
    def test_SetStatusList(self):
        """SetStatus with list"""

        for m in nest.Models():
            if 'V_m' in nest.GetDefaults(m):
                nest.ResetKernel()
                n = nest.Create(m)
                nest.SetStatus(n, [{'V_m': 2.}])
                self.assertEqual(nest.GetStatus(n, 'V_m')[0], 2.)
    def test_SetStatus(self):
        """SetStatus with dict"""

        for m in nest.Models():
            if 'V_m' in nest.GetDefaults(m):
                nest.ResetKernel()
                n = nest.Create(m)
                nest.SetStatus(n, {'V_m': 1.})
                self.assertEqual(nest.GetStatus(n, 'V_m')[0], 1.)
    def test_SetStatusParam(self):
        """SetStatus with parameter"""

        for m in nest.Models():
            if 'V_m' in nest.GetDefaults(m):
                nest.ResetKernel()
                n = nest.Create(m)
                nest.SetStatus(n, 'V_m', 3.)
                self.assertEqual(nest.GetStatus(n, 'V_m')[0], 3.)
Exemple #28
0
 def set_delays(self, min_delay, max_delay):
     if min_delay != 'auto': 
         min_delay = float(min_delay)
         max_delay = float(max_delay)
         for synapse_model in nest.Models(mtype='synapses'):
             if synapse_model not in ['gap_junction', 'gap_junction_lbl']:
                 nest.SetDefaults(synapse_model, {'delay': min_delay,
                                                  'min_delay': min_delay,
                                                  'max_delay': max_delay})
Exemple #29
0
 def test_register_synapses(self):
     for syn_model in nest.Models('synapses'):
         if syn_model not in self.exclude_synapse_model:
             nest.ResetKernel()
             nest.SetDefaults(syn_model, {'min_delay': 0.1, 'max_delay': 1.0, 'delay': 0.5})
             syn_dict = {'model': syn_model, 'pre_synaptic_element': 'SE1', 'post_synaptic_element': 'SE2'}
             nest.SetKernelStatus({'structural_plasticity_synapses': {'syn1': syn_dict}})
             kernel_status = nest.GetKernelStatus('structural_plasticity_synapses')
             self.assertIn('syn1', kernel_status)
             self.assertEqual(kernel_status['syn1'], extract_dict_a_from_b(kernel_status['syn1'], syn_dict))
Exemple #30
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)