Esempio n. 1
0
    def _get_nest_synapse_model(self, suffix):
        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 = make_sli_compatible(synapse_defaults)

        synapse_defaults.pop("tau_minus", None)
        label = "%s_%s" % (self.nest_name, suffix)
        nest.CopyModel(self.nest_name, label, synapse_defaults)
        return label
Esempio n. 2
0
    def connect(self):
        #         print(nest.GetStatus([1],'C_m'))
        """Connect nodes"""
        if self.built == False:
            raise BuildError('Build the network first')
        nest.CopyModel("static_synapse", "excitatory", {"weight": self.J_ex})
        nest.CopyModel("static_synapse", "inhibitory", {"weight": self.J_in})
        nest.CopyModel("static_synapse", "external", {"weight": self.J_ext})

        self.syn_dict = {'model': 'excitatory', 'delay': self.delay}
        self.syn_dict_in = {'model': 'inhibitory', 'delay': self.delay}
        self.syn_dict_ext = {'model': 'external', 'delay': self.delay}

        nest.Connect(self.noise, self.nodes_ex, syn_spec=self.syn_dict_ext)
        #         if self.i_noise_off==False:
        #             print('in noise connected')
        nest.Connect(self.noise, self.nodes_in, syn_spec=self.syn_dict_ext)

        nest.Connect(self.nodes_al[:self.N_rec],
                     self.espikes,
                     syn_spec=self.syn_dict)
        if self.record_vol:
            nest.Connect(self.voltmeter,
                         self.nodes_al[:self.N_rec])  #self.N_rec
#         print("Connecting network")

#         print("Excitatory connections")
        self.conn_params_ex = {'rule': 'fixed_indegree', 'indegree': self.KE}
        nest.Connect(self.nodes_ex,
                     self.nodes_ex + self.nodes_in,
                     self.conn_params_ex,
                     syn_spec=self.syn_dict)

        #         print("Inhibitory connections")
        self.conn_params_in = {'rule': 'fixed_indegree', 'indegree': self.KI}
        nest.Connect(self.nodes_in,
                     self.nodes_ex + self.nodes_in,
                     self.conn_params_in,
                     syn_spec=self.syn_dict_in)
Esempio n. 3
0
    def test_single_synapse_deletion_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')
                syn_dict = {
                    'model': syn_model,
                    'pre_synaptic_element': 'SE1',
                    'post_synaptic_element': 'SE2'
                }
                #nest.SetKernelStatus({'structural_plasticity_synapses': {'syn1': syn_dict}})
                neurons = nest.Create(
                    'iaf_neuron', 2, {
                        '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)
                nest.Connect(neurons, neurons, "all_to_all",
                             {'model': 'my_static_synapse'})

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

                srcId = 0
                targId = 1

                conns = nest.GetConnections([neurons[srcId]],
                                            [neurons[targId]], syn_model)
                assert conns
                nest.DisconnectOneToOne(neurons[srcId], neurons[targId],
                                        syn_dict)
                status = nest.GetStatus(neurons, 'synaptic_elements')
                self.assertEqual(1, status[srcId]['SE1']['z_connected'])
                self.assertEqual(2, status[srcId]['SE2']['z_connected'])
                self.assertEqual(2, status[targId]['SE1']['z_connected'])
                self.assertEqual(1, status[targId]['SE2']['z_connected'])

                conns = nest.GetConnections([neurons[srcId]],
                                            [neurons[targId]], syn_model)
                assert not conns
    def runSimulation(self,recorded_models,recorded_spikes,record_Vm):

        recorders = []

        if record_Vm:
            nest.CopyModel('multimeter', 'RecordingNode',
                    {'interval'   : self.Params['resolution'],
                    'record_from': ['V_m'],
                    'record_to'  : ['memory'],
                    'withgid'    : True,
                    'withtime'   : False})

            for population, model in recorded_models:
                    rec = nest.Create('RecordingNode')
                    recorders.append([rec,population,model])
                    tgts = [nd for nd in nest.GetLeaves(population)[0] if nest.GetStatus([nd],
                    'model')[0]==model]
                    nest.Connect(rec, tgts)

        nest.CopyModel('spike_detector', 'RecordingSpikes',
                {"withtime": True,
                "withgid": True,
                "to_file": False})

        spike_detectors = []

        for population, model in recorded_spikes:
                rec = nest.Create('RecordingSpikes')
                spike_detectors.append([rec,population,model])
                tgts = [nd for nd in nest.GetLeaves(population)[0] if nest.GetStatus([nd],
                'model')[0]==model]
                nest.Connect(tgts, rec)

        print ("\n--- Simulation ---\n")
        nest.SetStatus([0],{'print_time': True})
        nest.Simulate(self.Params['simtime'])

        return recorders,spike_detectors
Esempio n. 5
0
    def test_prohibit_change_tic_base(self):
        """Getting error when changing tic-base in prohibited conditions"""

        nest.CopyModel('iaf_psc_alpha', 'alpha_copy')
        self._assert_ticbase_change_raises_and_reset('CopyModel')

        nest.SetDefaults("multimeter", {"record_to": "ascii"})
        self._assert_ticbase_change_raises_and_reset('SetDefaults')

        nest.Create('multimeter')
        self._assert_ticbase_change_raises_and_reset('Create')

        nest.Simulate(10.)
        self._assert_ticbase_change_raises_and_reset('Simulate')
Esempio n. 6
0
    def __init__(self,
                 presynaptic_population,
                 postsynaptic_population,
                 method,
                 source=None,
                 target=None,
                 synapse_dynamics=None,
                 label=None,
                 rng=None):
        """
        presynaptic_population and postsynaptic_population - Population objects.

        source - string specifying which attribute of the presynaptic cell
                 signals action potentials

        target - string specifying which synapse on the postsynaptic cell to
                 connect to

        If source and/or target are not given, default values are used.

        method - a Connector object, encapsulating the algorithm to use for
                 connecting the neurons.

        synapse_dynamics - a `SynapseDynamics` object specifying which
        synaptic plasticity mechanisms to use.

        rng - specify an RNG object to be used by the Connector.
        """
        common.Projection.__init__(self, presynaptic_population,
                                   postsynaptic_population, method, source,
                                   target, synapse_dynamics, label, rng)
        self.synapse_type = target or 'excitatory'
        if self.synapse_dynamics:
            synapse_dynamics = self.synapse_dynamics
            self.synapse_dynamics._set_tau_minus(self.post.local_cells)
        else:
            synapse_dynamics = NativeSynapseDynamics("static_synapse")
        synapse_model = synapse_dynamics._get_nest_synapse_model(
            "projection_%d" % Projection.nProj)
        if synapse_model is None:
            self.synapse_model = 'static_synapse_%s' % id(self)
            nest.CopyModel('static_synapse', self.synapse_model)
        else:
            self.synapse_model = synapse_model
        self._sources = []
        self._connections = None
        Projection.nProj += 1

        # Create connections
        method.connect(self)
    def assert_parameter_limits_bigger(self, param_name, limit):

        nest.ResetKernel()
        nest.CopyModel("synaptic_sampling_rewardgradient_synapse",
                       "test_synapse")

        try:
            nest.SetDefaults("test_synapse", {param_name: limit - 1})
            self.fail("Expected exception of type NESTError, but got nothing")
        except Exception as e:
            self.assertEqual(
                type(e).__name__, "NESTError",
                "Expected exception of type NESTError, but got: '" +
                type(e).__name__ + "'")

        nest.ResetKernel()
        nest.CopyModel("synaptic_sampling_rewardgradient_synapse",
                       "test_synapse")

        try:
            nest.SetDefaults("test_synapse", {param_name: limit})
            self.fail("Expected exception of type NESTError, but got nothing")
        except Exception as e:
            self.assertEqual(
                type(e).__name__, "NESTError",
                "Expected exception of type NESTError, but got: '" +
                type(e).__name__ + "'")

        nest.ResetKernel()
        nest.CopyModel("synaptic_sampling_rewardgradient_synapse",
                       "test_synapse")

        try:
            nest.SetDefaults("test_synapse", {param_name: limit + 1})
        except Exception as e:
            self.fail("Expected no exception, but got: '" + type(e).__name__ +
                      "'")
class TestGetStructuralPlasticityStatus(unittest.TestCase):
    neuron_model = 'iaf_psc_alpha'
    nest.CopyModel('static_synapse', 'synapse_ex')
    nest.SetDefaults('synapse_ex', {'weight': 1.0, 'delay': 1.0})
    nest.SetStructuralPlasticityStatus({
        'structural_plasticity_synapses': {
            'synapse_ex': {
                'synapse_model': 'synapse_ex',
                'post_synaptic_element': 'Den_ex',
                'pre_synaptic_element': 'Axon_ex',
            },
        }
    })

    growth_curve = {
        'growth_curve': "gaussian",
        'growth_rate': 0.0001,  # (elements/ms)
        'continuous': False,
        'eta': 0.0,  # Ca2+
        'eps': 0.05
    }
    '''
    Now we assign the growth curves to the corresponding synaptic
    elements
    '''
    synaptic_elements = {
        'Den_ex': growth_curve,
        'Den_in': growth_curve,
        'Axon_ex': growth_curve,
    }
    nodes = nest.Create(neuron_model, 2,
                        {'synaptic_elements': synaptic_elements})
    all = nest.GetStructuralPlasticityStatus()
    assert ('structural_plasticity_synapses' in all)
    assert ('syn1' in all['structural_plasticity_synapses'])
    assert ('structural_plasticity_update_interval' in all)
    assert (all['structural_plasticity_update_interval'] == 10000.)

    sp_synapses = nest.GetStructuralPlasticityStatus(
        'structural_plasticity_synapses')
    syn = sp_synapses['syn1']
    assert ('pre_synaptic_element' in syn)
    assert ('post_synaptic_element' in syn)
    assert (syn['pre_synaptic_element'] == 'Axon_ex')
    assert (syn['post_synaptic_element'] == 'Den_ex')

    sp_interval = nest.GetStructuralPlasticityStatus(
        'structural_plasticity_update_interval')
    assert (sp_interval == 10000.)
Esempio n. 9
0
    def do_the_nest_simulation(self):
        """
        This function is where calls to NEST reside.
        Returns the generated pre- and post spike sequences
        and the resulting weight established by the tsodyks2 synapse.
        """
        nest.set_verbosity("M_WARNING")
        nest.ResetKernel()
        nest.SetKernelStatus({"resolution": self.resolution})

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

        presynaptic_generator = nest.Create("poisson_generator",
                                            params={
                                                "rate":
                                                self.presynaptic_firing_rate,
                                                "stop":
                                                (self.simulation_duration -
                                                 self.hardcoded_trains_length)
                                            })

        spike_recorder = nest.Create("spike_recorder")

        nest.Connect(presynaptic_generator,
                     presynaptic_neuron,
                     syn_spec={"synapse_model": "static_synapse"})
        nest.Connect(presynaptic_neuron + postsynaptic_neuron,
                     spike_recorder,
                     syn_spec={"synapse_model": "static_synapse"})
        # The synapse of interest itself
        wr = nest.Create("weight_recorder")
        nest.CopyModel("tsodyks2_synapse", "tsodyks2_synapse_rec",
                       {"weight_recorder": wr})
        nest.Connect(presynaptic_neuron,
                     postsynaptic_neuron,
                     syn_spec=self.synapse_parameters)

        nest.Simulate(self.simulation_duration)

        all_spikes = spike_recorder.events
        pre_spikes = all_spikes["times"][all_spikes["senders"] ==
                                         presynaptic_neuron.get("global_id")]

        weights = wr.get("events", "weights")

        return (pre_spikes, weights)
Esempio n. 10
0
    def testMultapses(self):
        """Weight Recorder Multapses"""

        nest.ResetKernel()
        nest.local_num_threads = 2

        wr = nest.Create('weight_recorder')
        nest.CopyModel("stdp_synapse", "stdp_synapse_rec", {
            "weight_recorder": wr,
            "weight": 1.
        })

        sg = nest.Create("spike_generator",
                         params={"spike_times": [10., 15., 55., 70.]})
        pre = nest.Create("parrot_neuron", 5)
        post = nest.Create("parrot_neuron", 5)

        nest.Connect(pre, post, 'one_to_one', syn_spec="stdp_synapse_rec")
        nest.Connect(pre, post, 'one_to_one', syn_spec="stdp_synapse_rec")
        nest.Connect(sg, pre)

        # simulate before GetConnections
        # as order of connections changes at beginning of simulation (sorting)
        nest.Simulate(1)

        conn = nest.GetConnections(pre, post)
        conn_dict = conn.get(['source', 'target', 'port'])

        connections = list(
            zip(conn_dict['source'], conn_dict['target'], conn_dict['port']))

        nest.Simulate(100)

        wr_events = nest.GetStatus(wr, "events")[0]
        senders = wr_events["senders"]
        targets = wr_events["targets"]
        ports = wr_events["ports"]
        ids = list(zip(senders, targets, ports))

        # create an array of object dtype to use np.unique to get
        # unique ids
        unique_ids = np.empty(len(ids), dtype=object)
        for i, v in enumerate(ids):
            unique_ids[i] = v
        unique_ids = np.unique(unique_ids)

        self.assertEqual(sorted(unique_ids), sorted(connections))
Esempio n. 11
0
    def test_getting_kernel_status(self):
        """
        This tests the functionality of the structural plasticity status
        via GetKernelStatus.
        """
        neuron_model = 'iaf_psc_alpha'
        nest.CopyModel('static_synapse', 'synapse_ex')
        nest.SetDefaults('synapse_ex', {'weight': 1.0, 'delay': 1.0})
        nest.SetKernelStatus({
            'structural_plasticity_synapses': {
                'synapse_ex': {
                    'synapse_model': 'synapse_ex',
                    'post_synaptic_element': 'Den_ex',
                    'pre_synaptic_element': 'Axon_ex',
                },
            }
        })

        growth_curve = {
            'growth_curve': "gaussian",
            'growth_rate': 0.0001,  # (elements/ms)
            'continuous': False,
            'eta': 0.0,  # Ca2+
            'eps': 0.05
        }
        '''
        Now we assign the growth curves to the corresponding synaptic
        elements
        '''
        synaptic_elements = {
            'Den_ex': growth_curve,
            'Den_in': growth_curve,
            'Axon_ex': growth_curve,
        }
        nodes = nest.Create(neuron_model, 2,
                            {'synaptic_elements': synaptic_elements})

        sp_synapses = nest.GetKernelStatus('structural_plasticity_synapses')
        syn = sp_synapses['syn1']
        assert ('pre_synaptic_element' in syn)
        assert ('post_synaptic_element' in syn)
        assert (syn['pre_synaptic_element'] == 'Axon_ex')
        assert (syn['post_synaptic_element'] == 'Den_ex')

        sp_interval = nest.GetKernelStatus(
            'structural_plasticity_update_interval')
        assert (sp_interval == 10000.)
    def setUp_net(self, n_post, params={}):
        """Set up a net and parrots"""
        nest.set_verbosity("M_WARNING")
        nest.ResetKernel()
        nest.SetKernelStatus({"resolution": 1.})

        # set pre and postsynaptic spike times
        delay = 1.  # delay for connections

        # set the correct real spike times for generators (correcting for
        # delays)
        pre_times = [100. - delay, 200. - delay]
        post_times = [120. - delay, 140. - delay, 160. - delay]

        # create spike_generators with these times
        pre_spikes = nest.Create("spike_generator", 1,
                                 {"spike_times": pre_times})
        post_spikes = nest.Create("spike_generator", 1,
                                  {"spike_times": post_times})

        self.pre_spikes = pre_spikes
        self.post_spikes = post_spikes

        # create parrot neurons and connect spike_generators
        self.pre_parrot = nest.Create("parrot_neuron", 1)
        self.post_parrot = nest.Create("parrot_neuron", n_post)

        nest.Connect(pre_spikes, self.pre_parrot, syn_spec={"delay": delay})
        nest.Connect(post_spikes,
                     self.post_parrot,
                     syn_spec={"delay": delay},
                     conn_spec={"rule": "all_to_all"})

        # create spike detector
        self.spikes = nest.Create("spike_detector")
        nest.Connect(self.pre_parrot,
                     self.spikes,
                     conn_spec={"rule": "all_to_all"})
        nest.Connect(self.post_parrot,
                     self.spikes,
                     conn_spec={"rule": "all_to_all"})

        pars = {'tau': 0.02, 'tau_slow': 0.300, 'w0': .2, 'p_fail': .2}

        pars.update(params)
        nest.CopyModel('stdp_structpl_synapse_hom', 'testsyn', pars)
Esempio n. 13
0
    def _get_nest_synapse_model(self, suffix):
        # We create a particular synapse context for each projection, by copying
        # the one which is desired.
        if self.fast:
            if self.slow:
                raise Exception(
                    "It is not currently possible to have both short-term and long-term plasticity at the same time with this simulator."
                )
            else:
                base_model = self.fast.native_name
        elif self.slow:
            base_model = self.slow.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))

        synapse_defaults = nest.GetDefaults(base_model)
        for ignore in ('synapsemodel', 'num_connections', 'num_connectors',
                       'type', 'property_object'):
            synapse_defaults.pop(ignore, None)
        if self.fast:
            synapse_defaults.update(self.fast.parameters)
        elif self.slow:
            stdp_parameters = self.slow.all_parameters
            # NEST does not support w_min != 0
            try:
                stdp_parameters.pop("w_min_always_zero_in_NEST")
            except Exception:
                pass
            # Tau_minus is a parameter of the post-synaptic cell, not of the connection
            stdp_parameters.pop("tau_minus")
            synapse_defaults.update(stdp_parameters)

        label = "%s_%s" % (base_model, suffix)
        nest.CopyModel(base_model, label, synapse_defaults)
        return label
Esempio n. 14
0
    def build_local_network(self):
        # Create neurons
        for pop in ['E', 'I']:
            self.neurons[pop] = nest.Create('default_neuron', self.N[pop])

        # Sample subpopulations
        cut = 0
        for pop in ['low', 'high', 'E_rec']:
            self.neurons[pop] = self.neurons['E'][cut:cut + self.N[pop]]
            cut += self.N[pop]
        self.neurons['I_rec'] = self.neurons['I'][:self.N['I_rec']]
        self.neurons['E_no_S'] = tuple(
            set(self.neurons['E']) - set(self.neurons['low']) -
            set(self.neurons['high']))
        self.neurons['ALL'] = self.neurons['E'] + self.neurons['I']

        # Connect subpopulations to spike detectors
        for pop in ['low', 'high', 'E_rec', 'I_rec']:
            self.spkdets[pop] = nest.Create('spike_detector')
            nest.Connect(self.neurons[pop], self.spkdets[pop])

        # Connect neurons with each other
        for pop in ['E', 'I']:
            syn_model_name = f'cortex_{pop}_synapse'
            nest.CopyModel('default_synapse', syn_model_name,
                           {"weight": self.J[pop]})
            conn_params = {'rule': 'fixed_indegree', 'indegree': self.C[pop]}
            nest.Connect(self.neurons[pop], self.neurons['ALL'], conn_params,
                         syn_model_name)

        # Create and connect background activity
        background_activity = nest.Create('poisson_generator',
                                          params={"rate": self.bg_rate})
        nest.Connect(background_activity,
                     self.neurons['ALL'],
                     syn_spec='cortex_E_synapse')

        # initiate membrane potentials
        self.initiate_membrane_potentials_randomly()

        # Create and connect sensory stimulus
        self.stimulus = dict()
        for pop in ['low', 'high']:
            self.stimulus[pop] = nest.Create('step_current_generator')
            nest.Connect(self.stimulus[pop], self.neurons[pop])
Esempio n. 15
0
    def test_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_neuron', 2)
                syn_dict = {'model': syn_model}
                nest.Connect(neurons, neurons, "all_to_all", syn_dict)

                srcId = 0
                targId = 1

                conns = nest.GetConnections([neurons[srcId]],[neurons[targId]],syn_model)
                assert len(conns) == 1
                nest.DisconnectOneToOne(neurons[srcId], neurons[targId], syn_dict)

                conns = nest.GetConnections([neurons[srcId]],[neurons[targId]],syn_model)
                assert len(conns) == 0
Esempio n. 16
0
    def connect_background(self):
        """ Connects background input to the microcircuit."""
        # cell-type-specific membrance parameters
        ctsp = self.net_dict['ctsp']
        # for weight recording
        copysynapse = 'static_synapse_wr_bg'
        if 'weight_recorder' in self.net_dict['rec_dev']:
            if copysynapse not in self.copysynapses:
                print('copysynapse = {}'.format(copysynapse))
                nest.CopyModel('static_synapse', copysynapse, \
                    {'weight_recorder': self.weight_recorder['background'][0]})
                self.copysynapses.append(copysynapse)

        if nest.Rank() == 0:
            print('Background input is connected')

        for i, target_pop in enumerate(self.pops):
            # population specific weights
            w = tools.calc_psc(self.net_dict['PSP_exc'], ctsp['C_m'][i],
                               ctsp['tau_m'][i],
                               self.net_dict['neuron_params']['tau_syn_ex'])
            syn_dict = {
                'model': 'static_synapse',
                'weight': w,
                'delay': self.sim_resolution
            }
            # for weight recording
            if 'weight_recorder' in self.net_dict['rec_dev']:
                if i == 0:
                    syn_dict['model'] = copysynapse
            if self.net_dict['test_mode']:
                return
            # Connect poisson->parrot
            parrots = nest.Create('parrot_neuron', self.net_dict['N_full'][i])
            nest.Connect(self.poisson[i],
                         parrots,
                         conn_spec={'rule': 'all_to_all'})
            # Connect parrot->population
            if 'multisynapse' in self.net_dict['neuron_model']:
                syn_dict['receptor_type'] = 1
            nest.Connect(parrots,
                         target_pop,
                         conn_spec={'rule': 'one_to_one'},
                         syn_spec=syn_dict)
Esempio n. 17
0
    def test_neuron_synapse_multithreading(self):
        pre_spike_times = np.array([2.,   4.,   7.,   8.,  12.,  13.,  19.,  23.,  24.,  28.,  29.,  30.,  33.,  34.,
                                    35.,  36.,  38.,  40.,  42.,  46.,  51.,  53.,  54.,  55.,  56.,  59.,  63.,  64.,
                                    65.,  66.,  68.,  72.,  73.,  76.,  79.,  80.,  83.,  84.,  86.,  87.,  90.,  95.])
        post_spike_times = np.array([4.,   5.,   6.,   7.,  10.,  11.,  12.,  16.,  17.,  18.,  19.,  20.,  22.,  23.,
                                     25.,  27.,  29.,  30.,  31.,  32.,  34.,  36.,  37.,  38.,  39.,  42.,  44.,  46.,
                                     48.,  49.,  50.,  54.,  56.,  57.,  59.,  60.,  61.,  62.,  67.,  74.,  76.,  79.,
                                     80.,  81.,  83.,  88.,  93.,  94.,  97.,  99.])

        nest.set_verbosity("M_ALL")
        nest.ResetKernel()
        nest.Install(self.neuron_synapse_module)

        nest.SetKernelStatus({'resolution': 0.1, 'local_num_threads': self.number_of_threads})

        wr = nest.Create('weight_recorder')
        nest.CopyModel(self.neuron_synapse_synapse_model, "stdp_nestml_rec",
                       {"weight_recorder": wr[0], "w": 1., "the_delay": 1., "receptor_type": 0})

        # Spike generators
        pre_sg = nest.Create("spike_generator", 2,
                             params={"spike_times": pre_spike_times})
        post_sg = nest.Create("spike_generator", 2,
                              params={"spike_times": post_spike_times,
                                      'allow_offgrid_times': True})

        pre_neuron = nest.Create(self.neuron_synapse_neuron_model, 2)
        post_neuron = nest.Create(self.neuron_synapse_neuron_model, 2)
        sr_pre = nest.Create("spike_recorder")
        sr_post = nest.Create("spike_recorder")
        mm = nest.Create("multimeter", params={"record_from": ["V_m"]})

        nest.Connect(pre_sg, pre_neuron, "one_to_one", syn_spec={"delay": 1.})
        nest.Connect(post_sg, post_neuron, "one_to_one", syn_spec={"delay": 1., "weight": 9999.})
        nest.Connect(pre_neuron, post_neuron, "all_to_all", syn_spec={'synapse_model': 'stdp_nestml_rec'})
        nest.Connect(mm, post_neuron)
        nest.Connect(pre_neuron, sr_pre)
        nest.Connect(post_neuron, sr_post)

        nest.Simulate(100.)

        V_m = nest.GetStatus(mm, "events")[0]["V_m"]
        print(V_m)
        np.testing.assert_almost_equal(V_m[-4],  -59.17946541)
Esempio n. 18
0
def get_synaptic_w(STimes):

    h = 0.1
    nest.ResetKernel()
    nest.SetKernelStatus({"resolution": h})

    spks = nest.Create('spike_generator', 1, {'spike_times': STimes})
    pre = nest.Create('parrot_neuron', 1)
    post = nest.Create('iaf_psc_exp', 1)
    detector = nest.Create('weight_recorder')

    synapse_params = {
        'weight': 1000.,
        'tau_fac': params['Tau_f'],
        'weight_recorder': detector[0],
        'tau_rec': params['Tau_r'],
        'tau_1': params['Tau_FDR'],
        'tau_2': params['Tau_r0'],
        'tau_eta': params['Tau_i'],
        'x': params['p0'],
        'n': 1.0,
        'y_0': params['a_FDR'],
        'alpha_1': params['a_D'],
        'alpha_2': params['a_i'],
        'S': 1.0,
        'alpha': params['p0bar'],
        'z': params['Tau_D'],
        'p': params['p0bar']
    }

    nest.CopyModel("aibs_synapse", "syn", synapse_params)
    nest.Connect(spks, pre)
    nest.Connect(pre, post, syn_spec="syn")
    #nest.Connect(detector,pre)

    nest.Simulate(5000.0)

    weights = nest.GetStatus(detector, "events")[0]["weights"]

    weights = np.array(weights)
    weights = weights / weights[0]

    return weights
Esempio n. 19
0
    def build_local_network(self):
        # Create nodes
        self.drive = nest.Create(
            'spike_generator')  # Spike generator to drive VTA activity
        self.neurons['ALL'] = nest.Create(
            'parrot_neuron', self.N['ALL'])  #A middleman parrot neuron
        self.vt = nest.Create('volume_transmitter')  # volume transmitter

        # Connect nodes in a chain
        # We can't connect the spike generator directly to the volume transmitter due to a NEST bug)
        nest.Connect(self.drive,
                     self.neurons['ALL'],
                     syn_spec={'delay': self.dt})
        nest.Connect(self.neurons['ALL'], self.vt, syn_spec={'delay': self.dt})
        self.DA_pars['vt'] = self.vt[0]

        # Create synapse that will be used by cortico-striatal neurons
        nest.CopyModel('stdp_dopamine_synapse', 'corticostriatal_synapse',
                       self.DA_pars)
Esempio n. 20
0
    def _constructNetwork(self):
        '''Construct the E/I network'''
        self.i_model_name = "iaf_gridcells"
        self.e_neuron_params = gc_neurons.getENeuronParams(self.no)
        self.i_neuron_params = gc_neurons.getINeuronParams(self.no)
        self.i_receptors = nest.GetDefaults(
            self.i_model_name)['receptor_types']

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

        self.e_model_name = "iaf_gridcells"
        self.i_model_name = "iaf_gridcells"
        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)
Esempio n. 21
0
def build_topology(syn_specification):
    # create neurons
    neurons_pre = nest.Create("hh_cond_exp_traub", 101, nrn_params)
    neurons_post = nest.Create("hh_cond_exp_traub", 101, nrn_params)
    # create weight recorder
    wr = nest.Create('weight_recorder', n=1, params=wr_params)
    syn_specification['weight_recorder'] = wr[0]
    nest.CopyModel("stdp_synapse",
                   "stdp_synapse_rec",
                   params=syn_specification)
    # pair by pair
    for nrn_pre, nrn_post, pre_spike_time, post_spike_time in zip(
            neurons_pre, neurons_post, pre_spike_times, post_spike_times):
        # create generators
        # the spikes at the end of the simulation is need to re-calculate weights of synapses
        generator_pre = nest.Create('spike_generator',
                                    n=1,
                                    params={
                                        'spike_times': [pre_spike_time, 225.0],
                                        'spike_weights': [350.0, 350.0]
                                    })
        generator_post = nest.Create('spike_generator',
                                     n=1,
                                     params={
                                         'spike_times':
                                         [post_spike_time, 225.0],
                                         'spike_weights': [350.0, 350.0]
                                     })
        nest.Connect(generator_pre, [nrn_pre], syn_spec=static_synapse_spec)
        nest.Connect(generator_post, [nrn_post], syn_spec=static_synapse_spec)
        # create detector
        detector = nest.Create('spike_detector', n=1, params=detector_params)
        nest.Connect([nrn_pre, nrn_post], detector)
        spike_detectors[(nrn_pre, nrn_post)] = detector
        # create multimeter
        multimeter = nest.Create('multimeter', n=1, params=multimeter_params)
        nest.Connect(multimeter, [nrn_pre, nrn_post])
        multimeters[(nrn_pre, nrn_post)] = multimeter
        # connect neurons
        nest.Connect([nrn_pre], [nrn_post], syn_spec="stdp_synapse_rec")
    return neurons_pre, neurons_post, wr
Esempio n. 22
0
    def connect(self):
        """Connect nodes"""
        if self.built == False:
            raise BuildError('Build the network first')

        nest.CopyModel("static_synapse", "excitatory", {"weight": self.J_ex})
        if len(self.delay) < 2:
            self.delay = self.delay[0]
            print('sinlge delay')
            self.syn_dict = {
                'model': 'excitatory',
                'delay': self.delay,
            }
        else:
            self.d_min = self.delay[0]  #3.5
            self.d_max = self.delay[1]  #5.5
            self.syn_dict = {
                'model': 'excitatory',
                'delay': {
                    'distribution': 'uniform',
                    'low': self.d_min,
                    'high': self.d_max
                },
            }
            print('uniform delay')
        nest.Connect(self.noise, self.nodes_ex, syn_spec=self.syn_dict)

        nest.Connect(self.nodes_al[:self.N_rec],
                     self.espikes,
                     syn_spec=self.syn_dict)
        #nest.Connect(self.nodes_in[:self.N_rec] ,self.ispikes, syn_spec=self.syn_dict)

        print("Connecting network")

        print("Excitatory connections")

        self.conn_params_ex = {'rule': 'fixed_indegree', 'indegree': self.CE}
        nest.Connect(self.nodes_ex,
                     self.nodes_ex,
                     self.conn_params_ex,
                     syn_spec=self.syn_dict)
Esempio n. 23
0
 def __init__(self, synapse_type, synapse_model=None, parent=None):
     """
     Create a new ConnectionManager.
     
     `synapse_type` -- the 'physiological type' of the synapse, e.g.
                       'excitatory' or 'inhibitory'
     `synapse_model` -- the NEST synapse model to be used for all connections
                        created with this manager.
     `parent` -- the parent `Projection`, if any.
     """
     self.sources = []
     if synapse_model is None:
         self.synapse_model = 'static_synapse_%s' % id(self)
         nest.CopyModel('static_synapse', self.synapse_model)
     else:
         self.synapse_model = synapse_model
     self.synapse_type = synapse_type
     self.parent = parent
     if parent is not None:
         assert parent.plasticity_name == self.synapse_model
     self._connections = None
    def testMultapses(self):
        """Weight Recorder Multapses"""

        nest.ResetKernel()
        nest.SetKernelStatus({"local_num_threads": 2})

        wr = nest.Create('weight_recorder', params={"withport": True})
        nest.CopyModel("stdp_synapse", "stdp_synapse_rec", {
            "weight_recorder": wr[0],
            "weight": 1.
        })

        sg = nest.Create("spike_generator",
                         params={"spike_times": [10., 15., 55., 70.]})
        pre = nest.Create("parrot_neuron", 5)
        post = nest.Create("parrot_neuron", 5)

        nest.Connect(pre, post, 'one_to_one', syn_spec="stdp_synapse_rec")
        nest.Connect(pre, post, 'one_to_one', syn_spec="stdp_synapse_rec")
        nest.Connect(sg, pre)

        connections = [(c[0], c[1], c[4])
                       for c in nest.GetConnections(pre, post)]

        nest.Simulate(100)

        wr_events = nest.GetStatus(wr, "events")[0]
        senders = wr_events["senders"]
        targets = wr_events["targets"]
        ports = wr_events["ports"]
        ids = list(zip(senders, targets, ports))

        # create an array of object dtype to use np.unique to get
        # unique ids
        unique_ids = np.empty(len(ids), dtype=object)
        for i, v in enumerate(ids):
            unique_ids[i] = v
        unique_ids = np.unique(unique_ids)

        self.assertEqual(sorted(unique_ids), sorted(connections))
Esempio n. 25
0
    def __init__(self, modelList):

        """
        Create TCD computer for given modelList.
        The constructor instantiates NEST, including a call to
        ResetKernel() and instantiates all models in modelList.
        From all models derived from ht_model, synapse information
        is extracted and stored. Afterward, ResetKernel() is called
        once more.

        modelList: tuples of (parent, model, dict)

        Note: nest must have been imported before and all necessary modules
              loaded.
        """
        import nest
        nest.ResetKernel()

        # keep "list" over all models derived from ht_neuron
        ht_kids = set(["ht_neuron"])

        for parent, model, props in modelList:
            if parent in ht_kids and model not in ht_kids:
                nest.CopyModel(parent, model, props)
                ht_kids.add(model)

        # ht_kids now contains all models derived from ht_neuron
        # We collect in _tcd_info a mapping from (targetmodel, synapstype)
        # to an object containing all required information for TCD computation.
        self._tcd_info = {}
        for mod in ht_kids:
            props = nest.GetDefaults(mod)
            for syn in ['AMPA', 'GABA_A', 'GABA_B']:
                self._tcd_info[(mod, syn)] = self._TcdBeta(syn, props)
            self._tcd_info[(mod, 'NMDA')] = self._TcdNMDA(props)

        # delete models we created
        nest.ResetKernel()
Esempio n. 26
0
    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 = {'model': syn_model}
                nest.Connect(neurons, neurons, "all_to_all", syn_dict)

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

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

                conndictionary = {'rule': 'one_to_one'}
                syndictionary = {'model': syn_model}
                nest.Disconnect([neurons[i] for i in srcId],
                                [neurons[i] for i in targId], conndictionary,
                                syndictionary)

                conns = nest.GetConnections(srcId, targId, syn_model)
                assert len(conns) == 16
    def _create_extra_models(self):
        c = self.config

        # models for plastic connections
        if c['synapse'] == 'stdp_synapse_sem':
            # SE: connections from other spaces to E-pool
            nest.CopyModel('stdp_synapse_sem', self.name+'_syn_SE', {
                'Wmax': c['w_SE_max'],
                'lambda': c['eta_SE'] / c['w_SE_max'],
                'tau_plus': c['tau_plus_SE'],
                'A_minus': c['A_minus_SE'],
                'alpha': c['alpha_SE'],
            })
        else:
            raise ValueError('Bad synapse type set.')

        # model dictionaries for connections
        model_dicts = {}

        # SE
        model_dicts['SE'] = {
            'model': self.name+'_syn_SE',
            'lambda': c['eta_SE'] / c['w_SE_max'],
            'weight': {
                'distribution': 'uniform',
                'low': c['w_SE_low'],
                'high': c['w_SE_high']},
            'delay': {
                'distribution': 'uniform',
                'low': c['synd_SE_low'],
                'high': c['synd_SE_high']}
        }

        # rule dictionaries for connections
        # cannot create rule_dict for SE connections since it depends on N_S

        self.model_dicts.update(model_dicts)
Esempio n. 28
0
    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
Esempio n. 29
0
def create_GR(subCB):
    """GR

    Example:

    ::

        create_GR()
    """
    configuration = {}
    # Membrane potential in mV
    # configuration['V_m'] = 0.0
    # Leak reversal Potential (aka resting potential) in mV
    configuration['E_L'] = -58.0
    # Membrane Capacitance in pF
    configuration['C_m'] = 3.1
    # Refractory period in ms
    configuration['t_ref'] = 5.0
    # Threshold Potential in mV
    configuration['V_th'] = -35.0
    # Reset Potential in mV
    configuration['V_reset'] = -82.0
    # Excitatory reversal Potential in mV
    configuration['E_ex'] = 0.0
    # Inhibitory reversal Potential in mV
    configuration['E_in'] = -82.0
    # Leak Conductance in nS
    configuration['g_L'] = 0.43
    # Time constant of the excitatory synaptic exponential function in ms
    configuration['tau_syn_ex'] = 52.0
    # Time constant of the inhibitory synaptic exponential function in ms
    configuration['tau_syn_in'] = 59.0
    # Constant Current in pA
    configuration['I_e'] = 0.0
    print(subCB)
    nest.CopyModel('iaf_cond_exp', subCB + '_layer_gr', configuration)
Esempio n. 30
0
    def testDefinedTargetsAndSenders(self):
        """Weight Recorder Defined Subset Of Targets and Senders"""

        nest.ResetKernel()
        nest.local_num_threads = 1

        wr = nest.Create('weight_recorder')
        nest.CopyModel("stdp_synapse", "stdp_synapse_rec", {
            "weight_recorder": wr,
            "weight": 1.
        })

        sg = nest.Create("spike_generator",
                         params={"spike_times": [10., 15., 55., 70.]})
        pre = nest.Create("parrot_neuron", 5)
        post = nest.Create("parrot_neuron", 5)

        nest.Connect(pre, post, syn_spec="stdp_synapse_rec")
        nest.Connect(sg, pre)

        nest.SetStatus(wr, {"senders": pre[1:3], "targets": post[:3]})

        # simulate before GetConnections
        # as order of connections changes at beginning of simulation (sorting)
        nest.Simulate(1)

        connections = nest.GetConnections(pre[1:3], post[:3])
        targets = np.array([])
        for i in range(1):
            nest.Simulate(1)
            targets = np.append(targets, connections.get("target"))

        wr_targets = nest.GetStatus(wr, "events")[0]["targets"]

        self.addTypeEqualityFunc(type(wr_targets), self.is_subset)
        self.assertEqual(wr_targets, targets)