def test_empty_nc_addition(self):
        """Combine NodeCollection with empty NodeCollection and connect"""
        n = 5
        vm = -50.

        nodes_a = nest.NodeCollection()
        nodes_a += nest.Create('iaf_psc_alpha', n)
        nest.Connect(nodes_a, nodes_a)
        self.assertEqual(nest.GetKernelStatus('num_connections'), n * n)
        self.assertTrue(nodes_a)
        self.assertIsNotNone(nodes_a.get())
        nodes_a.V_m = vm
        self.assertEqual(nodes_a.V_m, n * (vm, ))

        nest.ResetKernel()

        nodes_b = nest.Create('iaf_psc_alpha', n)
        nodes_b += nest.NodeCollection([])
        nest.Connect(nodes_b, nodes_b)
        self.assertEqual(nest.GetKernelStatus('num_connections'), n * n)
        self.assertTrue(nodes_b)
        self.assertIsNotNone(nodes_b.get())
        nodes_b.V_m = vm
        self.assertEqual(nodes_b.V_m, n * (vm, ))
Beispiel #2
0
    def _identify_common_synapse_properties(self):
        """
        Use the connection between the sample indices to distinguish
        between local and common synapse properties.
        """
        sample_connection = nest.GetConnections(
            source=nest.NodeCollection([next(iter(self._sources))
                                        ]),  # take any source from the set
            synapse_model=self.nest_synapse_model,
            synapse_label=self.nest_synapse_label)[:1]

        local_parameters = nest.GetStatus(sample_connection)[0].keys()
        all_parameters = nest.GetDefaults(self.nest_synapse_model).keys()
        self._common_synapse_property_names = [
            name for name in all_parameters if name not in local_parameters
        ]
Beispiel #3
0
    def test_GetStatus_JSON(self):
        """JSON data of GetStatus"""

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

        for m in models:
            nest.ResetKernel()
            n = nest.Create(m)
            d_json = nest.GetStatus(n, output='json')
            self.assertIsInstance(d_json, str)

        nest.ResetKernel()
        n = nest.NodeCollection()
        d_json = nest.GetStatus(n, output='json')
        self.assertIsInstance(d_json, str)
        self.assertEqual(d_json, '[]')
Beispiel #4
0
 def _create_cells(self):
     """
     Create cells in NEST using the celltype of the current Population.
     """
     # this method should never be called more than once
     # perhaps should check for that
     nest_model = self.celltype.nest_name[simulator.state.spike_precision]
     if isinstance(self.celltype, StandardCellType):
         self.celltype.parameter_space.shape = (self.size,)  # should perhaps do this on a copy?
         params = _build_params(self.celltype.native_parameters,
                                None,
                                size=self.size,
                                extra_parameters=self.celltype.extra_parameters)
     else:
         params = _build_params(self.celltype.parameter_space,
                                None,
                                size=self.size)
     try:
         self.node_collection = nest.Create(nest_model, self.size, params=params)
     except nest.kernel.NESTError as err:
         if "UnknownModelName" in err.args[0] and "cond" in err.args[0]:
             raise errors.InvalidModelError("%s Have you compiled NEST with the GSL (Gnu Scientific Library)?" % err)
         if "Spike times must be sorted in non-descending order" in err.args[0]:
             raise errors.InvalidParameterValueError("Spike times given to SpikeSourceArray must be in increasing order")
         raise  # errors.InvalidModelError(err)
     # create parrot neurons if necessary
     if hasattr(self.celltype, "uses_parrot") and self.celltype.uses_parrot:
         self.node_collection_source = self.node_collection          # we put the parrots into all_cells, since this will
         parrot_model = simulator.state.spike_precision == "off_grid" and "parrot_neuron_ps" or "parrot_neuron"
         self.node_collection = nest.Create(parrot_model, self.size) # be used for connections and recording. all_cells_source
                                                                     # should be used for setting parameters
         self._deferred_parrot_connections = True
         # connecting up the parrot neurons is deferred until we know the value of min_delay
         # which could be 'auto' at this point.
     if self.node_collection.local is True:
         self._mask_local = np.array([True])
     else:
         self._mask_local = np.array(self.node_collection.local)
     self.all_cells = np.array([simulator.ID(gid) for gid in self.node_collection.tolist()], simulator.ID)
     for gid in self.all_cells:
         gid.parent = self
         gid.node_collection = nest.NodeCollection([int(gid)])
     if hasattr(self.celltype, "uses_parrot") and self.celltype.uses_parrot:
         for gid, source in zip(self.all_cells, self.node_collection_source.tolist()):
             gid.source = source
Beispiel #5
0
    def test_equal(self):
        """Equality of NodeCollections"""

        n = nest.Create('iaf_psc_exp', 10)
        n_list = n.tolist()

        nest.ResetKernel()

        n_new = nest.Create('iaf_psc_exp', 10)
        new_list = n_new.tolist()
        self.assertEqual(n_list, new_list)
        self.assertEqual(n, n_new)

        nest.ResetKernel()

        nc = nest.Create("iaf_psc_alpha", 10)
        ngc = nest.NodeCollection(nc.tolist())
        self.assertEqual(nc, ngc)

        self.assertNotEqual(nc, n)
Beispiel #6
0
    def test_composite_NodeCollection(self):
        """Tests composite NodeCollection with patched node IDs"""

        num_a = 10
        num_b = 15
        num_c = 30

        n_a = nest.Create('iaf_psc_exp', num_a)
        n_b = nest.Create('iaf_psc_alpha', num_b)
        n_c = nest.Create('iaf_psc_delta', num_c)

        nodes = n_a + n_c
        nodes_step = nodes[::2]
        nodes_list = nodes_step.tolist()
        compare_list = (list(range(1, 11))[::2] + list(range(26, 55))[::2])
        self.assertEqual(nodes_list, compare_list)

        self.assertEqual(nodes_list[2], 5)
        self.assertEqual(nodes_list[5], 26)
        self.assertEqual(nodes_list[19], 54)

        # Test iteration of sliced NodeCollection
        i = 0
        for n in nodes_step:
            self.assertEqual(n, nest.NodeCollection([compare_list[i]]))
            i += 1

        n_slice_first = nodes[:10]
        n_slice_middle = nodes[2:7]
        n_slice_middle_jump = nodes[2:12:2]

        n_list_first = n_slice_first.tolist()
        n_list_middle = n_slice_middle.tolist()
        n_list_middle_jump = n_slice_middle_jump.tolist()

        compare_list_first = list(range(1, 11))
        compare_list_middle = list(range(3, 8))
        compare_list_middle_jump = [3, 5, 7, 9, 26]
        self.assertEqual(n_list_first, compare_list_first)
        self.assertEqual(n_list_middle, compare_list_middle)
        self.assertEqual(n_list_middle_jump, compare_list_middle_jump)
Beispiel #7
0
 def _set_attributes(self, parameter_space):
     if "tau_minus" in parameter_space.keys(
     ) and not parameter_space["tau_minus"].is_homogeneous:
         raise ValueError("tau_minus cannot be heterogeneous "
                          "within a single Projection with NEST.")
     # only columns for connections that exist on this machine
     parameter_space.evaluate(mask=(slice(None), self.post._mask_local))
     sources = nest.NodeCollection(sorted(self._sources))
     if self._common_synapse_property_names is None:
         self._identify_common_synapse_properties()
     for postsynaptic_cell, connection_parameters in zip(
             self.post.local_cells, parameter_space.columns()):
         connections = nest.GetConnections(
             source=sources,
             target=postsynaptic_cell.node_collection,
             synapse_model=self.nest_synapse_model,
             synapse_label=self.nest_synapse_label)
         if connections:
             source_mask = self.pre.id_to_index(list(connections.sources()))
             for name, value in connection_parameters.items():
                 if name == "weight" and self.receptor_type == 'inhibitory' and self.post.conductance_based:
                     value *= -1  # NEST uses negative values for inhibitory weights, even if these are conductances
                 if name == "tau_minus":  # set on the post-synaptic cell
                     nest.SetStatus(
                         self.post.node_collection[
                             self.post.node_collection.local],
                         {"tau_minus": simplify(value)})
                 elif name not in self._common_synapse_property_names:
                     value = make_sli_compatible(value)
                     if len(source_mask) > 1:
                         nest.SetStatus(connections, name,
                                        value[source_mask])
                     elif isinstance(value,
                                     np.ndarray):  # OneToOneConnector
                         nest.SetStatus(connections, name,
                                        value[source_mask])
                     else:
                         nest.SetStatus(connections, name, value)
                 else:
                     self._set_common_synapse_property(name, value)
Beispiel #8
0
    def test_RotatedBoxMaskByAzimuthAndPolarAngle(self):
        """Test rotated box mask with azimuth and polar angle."""

        pos = [[x * 1., y * 1., z * 1.] for x in range(-2, 3)
               for y in range(-2, 3) for z in range(-2, 3)]

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        # Test with a azimuth angle and polar angle of 45 degrees.
        maskdict = {
            'lower_left': [-0.5, -1.5, -1.5],
            'upper_right': [0.5, 1.5, 1.5],
            'azimuth_angle': 45.,
            'polar_angle': 45.
        }
        mask = nest.CreateMask('box', maskdict)
        cntr = [0., 0., 0.]
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(
            node_ids,
            nest.NodeCollection([37, 38, 43, 57, 58, 63, 68, 69, 83, 88, 89]))
    def test_FindElements(self):
        """Interface and result check for finding nearest element.
           This function is Py only, so we also need to check results."""
        # nodes at [-1,0,1]x[-1,0,1], column-wise
        nest.ResetKernel()
        layer = nest.Create('iaf_psc_alpha',
                            positions=nest.spatial.grid(shape=[3, 3],
                                                        extent=(3., 3.)))

        # single location at center
        n = nest.FindNearestElement(layer, (0., 0.))
        self.assertEqual(n, layer[4])

        # two locations, one layer
        n = nest.FindNearestElement(layer, ((0., 0.), (1., 1.)))
        self.assertEqual(n[0], layer[4])
        self.assertEqual(n[1], layer[6])

        # several closest locations, not all
        n = nest.FindNearestElement(layer, (0.5, 0.5))
        self.assertEqual(len(n), 1)
        self.assertTrue(
            n.get('global_id') in nest.NodeCollection((4, 5, 7, 8)))

        # several closest locations, all
        n = nest.FindNearestElement(layer, (0.5, 0.5), find_all=True)
        self.assertEqual(len(n), 4)
        self.assertEqual(n[0], layer[3])
        self.assertEqual(n[3], layer[7])

        # complex case
        n = nest.FindNearestElement(layer, ((0., 0.), (0.5, 0.5)),
                                    find_all=True)
        self.assertEqual(len(n), 2)
        self.assertEqual(n[0], [layer[4]])
        self.assertEqual(n[1], [layer[3], layer[4], layer[6], layer[7]])
Beispiel #10
0
    def test_RotatedRectangularMask(self):
        """Test rotated rectangular mask.

            We have:
                lower_left:  [-1., -0.5]
                upper_right: [ 1.,  0.5]

            So, if we have:

            layer:
            2  7  12  17  22
            3  8  13  18  23
            4  9  14  19  24
            5  10 15  20  25
            6  11 16  21  26

            and have azimuth_angle = 0, we should get node IDs 9, 14, 19 if we
            select node IDs by mask.
            If we have azimuth_angle = 90, we should get node IDs 13, 14, 15.
        """

        # Test 2D layer
        layer = nest.Create('iaf_psc_alpha',
                            positions=nest.spatial.grid(shape=[5, 5],
                                                        extent=[5., 5.]))

        # First test without rotation.
        maskdict = {'lower_left': [-1., -0.5], 'upper_right': [1., 0.5]}
        mask = nest.CreateMask('rectangular', maskdict)
        cntr = [0., 0.]
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection((
            8,
            13,
            18,
        )))

        # Test if we get correct node IDs when rotating 90 degrees.
        maskdict = {
            'lower_left': [-1., -0.5],
            'upper_right': [1., 0.5],
            'azimuth_angle': 90.0
        }
        mask = nest.CreateMask('rectangular', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection((
            12,
            13,
            14,
        )))

        # Test rotation with an azimuth angle of 45 degrees.
        maskdict = {
            'lower_left': [-1.5, -0.5],
            'upper_right': [1.5, 0.5],
            'azimuth_angle': 45.0
        }
        mask = nest.CreateMask('rectangular', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection((
            9,
            13,
            17,
        )))

        # Test rotation with an azimuth angle of 135 degrees.
        maskdict = {
            'lower_left': [-1.5, -0.5],
            'upper_right': [1.5, 0.5],
            'azimuth_angle': 135.0
        }
        mask = nest.CreateMask('rectangular', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection((
            7,
            13,
            19,
        )))

        # Test that an error is raised if we send in a polar angle to a 2D
        # mask.
        maskdict = {
            'lower_left': [-1.5, -0.5],
            'upper_right': [1.5, 0.5],
            'polar_angle': 45.0
        }
        with self.assertRaises(nest.kernel.NESTError):
            mask = nest.CreateMask('rectangular', maskdict)
Beispiel #11
0
burst = nngt.NeuralGroup(nodes=200,
                         neuron_model='aeif_psc_alpha',
                         neuron_type=1,
                         neuron_param=params2)

adapt = nngt.NeuralGroup(nodes=200,
                         neuron_model='aeif_psc_alpha',
                         neuron_type=1,
                         neuron_param=base_params)

model = 'model'

try:
    import nest
    nest.NodeCollection()
    model = 'synapse_model'
except:
    pass

synapses = {
    'default': {
        model: 'tsodyks2_synapse'
    },
    ('oscillators', 'bursters'): {
        model: 'tsodyks2_synapse',
        'U': 0.6
    },
    ('oscillators', 'oscillators'): {
        model: 'tsodyks2_synapse',
        'U': 0.7
Beispiel #12
0
    def test_RotatedBoxMaskByPolarAngle(self):
        """Test rotated box mask with polar angle."""

        pos = [[x * 1., y * 1., z * 1.] for x in range(-2, 3)
               for y in range(-2, 3) for z in range(-2, 3)]

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        # First test without rotation
        maskdict = {
            'lower_left': [-0.5, -1.0, -1.0],
            'upper_right': [0.5, 1.0, 1.0]
        }
        mask = nest.CreateMask('box', maskdict)
        cntr = [0., 0., 0.]
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)
        self.assertEqual(
            node_ids, nest.NodeCollection([57, 58, 59, 62, 63, 64, 67, 68,
                                           69]))

        # Test with a polar angle of 90 degrees.
        maskdict = {
            'lower_left': [-0.5, -1.0, -1.0],
            'upper_right': [0.5, 1.0, 1.0],
            'polar_angle': 90.
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)
        self.assertEqual(
            node_ids, nest.NodeCollection([33, 38, 43, 58, 63, 68, 83, 88,
                                           93]))

        # Test with a polar angle of 180 degrees, should be the same as the
        # one without a polar angle.
        maskdict = {
            'lower_left': [-0.5, -1.0, -1.0],
            'upper_right': [0.5, 1.0, 1.0],
            'polar_angle': 180.
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)
        self.assertEqual(
            node_ids, nest.NodeCollection([57, 58, 59, 62, 63, 64, 67, 68,
                                           69]))

        # Test with a polar angle of 45 degrees.
        maskdict = {
            'lower_left': [-0.5, -1.5, -1.5],
            'upper_right': [0.5, 1.5, 1.5],
            'polar_angle': 45.
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)
        self.assertEqual(
            node_ids, nest.NodeCollection([32, 37, 42, 58, 63, 68, 84, 89,
                                           94]))

        # Test with a polar angle of 135 degrees. The node IDs should be
        # perpendicular to the ones obtained by a polar angle of 45 degrees.
        maskdict = {
            'lower_left': [-0.5, -1.5, -1.5],
            'upper_right': [0.5, 1.5, 1.5],
            'polar_angle': 135.
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(
            node_ids, nest.NodeCollection([34, 39, 44, 58, 63, 68, 82, 87,
                                           92]))

        # Test two symmetric masks in x and z direction. One with no polar
        # angle and one with a polar angle of 90 degrees. As the masks are
        # symmetrical in  x and z, a polar angle of 90 degrees should give the
        # same node IDs as the one without a polar angle.
        maskdict = {
            'lower_left': [-1., -0.5, -1.],
            'upper_right': [1., 0.5, 1.]
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids_2 = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(
            node_ids_2,
            nest.NodeCollection([37, 38, 39, 62, 63, 64, 87, 88, 89]))

        maskdict = {
            'lower_left': [-1., -0.5, -1.],
            'upper_right': [1., 0.5, 1.],
            'polar_angle': 90.
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)
        self.assertEqual(
            node_ids, nest.NodeCollection([37, 38, 39, 62, 63, 64, 87, 88,
                                           89]))

        self.assertEqual(node_ids_2, node_ids)
Beispiel #13
0
def build_network(logger):
    """Builds the network including setting of simulation and neuron
    parameters, creation of neurons and connections

    Requires an instance of Logger as argument

    """

    tic = time.time()  # start timer on construction

    # unpack a few variables for convenience
    NE = brunel_params['NE']
    NI = brunel_params['NI']
    model_params = brunel_params['model_params']
    stdp_params = brunel_params['stdp_params']

    # set global kernel parameters
    nest.SetKernelStatus({
        'total_num_virtual_procs': params['nvp'],
        'resolution': params['dt'],
        'overwrite_files': True})

    nest.SetDefaults('iaf_psc_alpha', model_params)

    nest.message(M_INFO, 'build_network', 'Creating excitatory population.')
    E_neurons = nest.Create('iaf_psc_alpha', NE)

    nest.message(M_INFO, 'build_network', 'Creating inhibitory population.')
    I_neurons = nest.Create('iaf_psc_alpha', NI)

    if brunel_params['randomize_Vm']:
        nest.message(M_INFO, 'build_network',
                     'Randomzing membrane potentials.')

        random_vm = nest.random.normal(brunel_params['mean_potential'],
                                       brunel_params['sigma_potential'])
        nest.GetLocalNodeCollection(E_neurons).V_m = random_vm
        nest.GetLocalNodeCollection(I_neurons).V_m = random_vm

    # number of incoming excitatory connections
    CE = int(1. * NE / params['scale'])
    # number of incomining inhibitory connections
    CI = int(1. * NI / params['scale'])

    nest.message(M_INFO, 'build_network',
                 'Creating excitatory stimulus generator.')

    # Convert synapse weight from mV to pA
    conversion_factor = convert_synapse_weight(
        model_params['tau_m'], model_params['tau_syn_ex'], model_params['C_m'])
    JE_pA = conversion_factor * brunel_params['JE']

    nu_thresh = model_params['V_th'] / (
        CE * model_params['tau_m'] / model_params['C_m'] *
        JE_pA * np.exp(1.) * tau_syn)
    nu_ext = nu_thresh * brunel_params['eta']

    E_stimulus = nest.Create('poisson_generator', 1, {
                             'rate': nu_ext * CE * 1000.})

    nest.message(M_INFO, 'build_network',
                 'Creating excitatory spike recorder.')

    if params['record_spikes']:
        recorder_label = os.path.join(
            brunel_params['filestem'],
            'alpha_' + str(stdp_params['alpha']) + '_spikes')
        E_recorder = nest.Create('spike_recorder', params={
            'record_to': 'ascii',
            'label': recorder_label
        })

    BuildNodeTime = time.time() - tic

    logger.log(str(BuildNodeTime) + ' # build_time_nodes')
    logger.log(str(memory_thisjob()) + ' # virt_mem_after_nodes')

    tic = time.time()

    nest.SetDefaults('static_synapse_hpc', {'delay': brunel_params['delay']})
    nest.CopyModel('static_synapse_hpc', 'syn_std')
    nest.CopyModel('static_synapse_hpc', 'syn_ex',
                   {'weight': JE_pA})
    nest.CopyModel('static_synapse_hpc', 'syn_in',
                   {'weight': brunel_params['g'] * JE_pA})

    stdp_params['weight'] = JE_pA
    nest.SetDefaults('stdp_pl_synapse_hom_hpc', stdp_params)

    nest.message(M_INFO, 'build_network', 'Connecting stimulus generators.')

    # Connect Poisson generator to neuron

    nest.Connect(E_stimulus, E_neurons, {'rule': 'all_to_all'},
                 {'synapse_model': 'syn_ex'})
    nest.Connect(E_stimulus, I_neurons, {'rule': 'all_to_all'},
                 {'synapse_model': 'syn_ex'})

    nest.message(M_INFO, 'build_network',
                 'Connecting excitatory -> excitatory population.')

    nest.Connect(E_neurons, E_neurons,
                 {'rule': 'fixed_indegree', 'indegree': CE,
                  'allow_autapses': False, 'allow_multapses': True},
                 {'synapse_model': 'stdp_pl_synapse_hom_hpc'})

    nest.message(M_INFO, 'build_network',
                 'Connecting inhibitory -> excitatory population.')

    nest.Connect(I_neurons, E_neurons,
                 {'rule': 'fixed_indegree', 'indegree': CI,
                  'allow_autapses': False, 'allow_multapses': True},
                 {'synapse_model': 'syn_in'})

    nest.message(M_INFO, 'build_network',
                 'Connecting excitatory -> inhibitory population.')

    nest.Connect(E_neurons, I_neurons,
                 {'rule': 'fixed_indegree', 'indegree': CE,
                  'allow_autapses': False, 'allow_multapses': True},
                 {'synapse_model': 'syn_ex'})

    nest.message(M_INFO, 'build_network',
                 'Connecting inhibitory -> inhibitory population.')

    nest.Connect(I_neurons, I_neurons,
                 {'rule': 'fixed_indegree', 'indegree': CI,
                  'allow_autapses': False, 'allow_multapses': True},
                 {'synapse_model': 'syn_in'})

    if params['record_spikes']:
        if params['nvp'] != 1:
            local_neurons = nest.GetLocalNodeCollection(E_neurons)
            # GetLocalNodeCollection returns a stepped composite NodeCollection, which
            # cannot be sliced. In order to allow slicing it later on, we're creating a
            # new regular NodeCollection from the plain node IDs.
            local_neurons = nest.NodeCollection(local_neurons.tolist())
        else:
            local_neurons = E_neurons

        if len(local_neurons) < brunel_params['Nrec']:
            nest.message(
                M_ERROR, 'build_network',
                """Spikes can only be recorded from local neurons, but the
                number of local neurons is smaller than the number of neurons
                spikes should be recorded from. Aborting the simulation!""")
            exit(1)

        nest.message(M_INFO, 'build_network', 'Connecting spike recorders.')
        nest.Connect(local_neurons[:brunel_params['Nrec']], E_recorder,
                     'all_to_all', 'static_synapse_hpc')

    # read out time used for building
    BuildEdgeTime = time.time() - tic

    logger.log(str(BuildEdgeTime) + ' # build_edge_time')
    logger.log(str(memory_thisjob()) + ' # virt_mem_after_edges')

    return E_recorder if params['record_spikes'] else None
# Finally gap junctions are added to the network. :math:`(60*500)/2` ``gap_junction``
# connections are added randomly resulting in an average of 60 gap-junction
# connections per neuron. We must not use the ``fixed_indegree`` oder
# ``fixed_outdegree`` functionality of ``nest.Connect()`` to create the
# connections, as ``gap_junction`` connections are bidirectional connections
# and we need to make sure that the same neurons are connected in both ways.
# This is achieved by creating the connections on the Python level with the
# `random` module of the Python Standard Library and connecting the neurons
# using the ``make_symmetric`` flag for ``one_to_one`` connections.

n_connection = int(n_neuron * gap_per_neuron / 2)
neuron_list = neurons.tolist()
connections = numpy.random.choice(neuron_list, [n_connection, 2])

for source_node_id, target_node_id in connections:
    nest.Connect(nest.NodeCollection([source_node_id]),
                 nest.NodeCollection([target_node_id]), {
                     'rule': 'one_to_one',
                     'make_symmetric': True
                 }, {
                     'synapse_model': 'gap_junction',
                     'weight': gap_weight
                 })

###############################################################################
# In the end we start the simulation and plot the spike pattern.

nest.Simulate(simtime)

times = sd.get('events', 'times')
spikes = sd.get('events', 'senders')
    # We assign random initial membrane potentials to all neurons

    numpy.random.seed(seed_numpy)
    Vms = Vmin + (Vmax - Vmin) * numpy.random.rand(N)
    allnodes.V_m = Vms

    ##############################################################################
    # In the second trial, we add an extra input spike at time ``t_stim`` to the
    # neuron that fires first after perturbation time ``t_stim``. Thus, we make sure
    # that the perturbation is transmitted to the network before it fades away in
    # the perturbed neuron. (Single IAF-neurons are not chaotic.)

    if trial == 1:
        id_stim = [senders[0][spiketimes[0] > t_stim][0]]
        nest.Connect(stimulus,
                     nest.NodeCollection(id_stim),
                     syn_spec={
                         'weight': Jstim,
                         'delay': dt
                     })
        stimulus.spike_times = [t_stim]

    # Now we simulate the network and add a fade out period to discard
    # remaining spikes.

    nest.Simulate(T)
    nest.Simulate(fade_out)

    # Storing the data.

    senders += [spikedetector.get('events', 'senders')]
Beispiel #16
0
    def test_RotatedRectangleOutsideOrigin(self):
        """
        Test rotated rectangle where the mask does not contain the origin.
        """

        layer = nest.Create('iaf_psc_alpha',
                            positions=nest.spatial.grid(shape=[11, 11],
                                                        extent=[11., 11.]))

        # First test that we get the correct node IDs when our mask does not
        # contain the origin.
        maskdict = {'lower_left': [1., 1.], 'upper_right': [4., 2.]}
        mask = nest.CreateMask('rectangular', maskdict)
        cntr = [0., 0.]
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(
            node_ids, nest.NodeCollection((
                70,
                71,
                81,
                82,
                92,
                93,
                103,
                104,
            )))

        # Then test that we get the correct node IDs with a azimuth rotation angle
        # of 45 degrees when the mask does not contain the origin.
        maskdict = {
            'lower_left': [0.5, 0.5],
            'upper_right': [4.5, 2.5],
            'azimuth_angle': 45.0
        }
        mask = nest.CreateMask('rectangular', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(
            node_ids, nest.NodeCollection((
                71,
                81,
                82,
                83,
                91,
                92,
                93,
                103,
            )))

        # Test that we get the correct node IDs with a azimuth rotation angle
        # of 90 degrees when the mask does not contain the origin.
        maskdict = {
            'lower_left': [1.0, 1.0],
            'upper_right': [4.0, 2.0],
            'azimuth_angle': 90.0
        }
        mask = nest.CreateMask('rectangular', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(
            node_ids, nest.NodeCollection((
                80,
                81,
                82,
                83,
                91,
                92,
                93,
                94,
            )))
Beispiel #17
0
    def test_RotatedBoxMaskByAzimuthAngle(self):
        """Test rotated box mask with azimuth angle."""
        # Test a 3D layer.
        pos = [[x * 1., y * 1., z * 1.] for x in range(-2, 3)
               for y in range(-2, 3) for z in range(-2, 3)]

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        # First test that we get correct node IDs with box mask that is not
        # rotated.
        maskdict = {
            'lower_left': [-1., -0.5, -0.5],
            'upper_right': [1., 0.5, 0.5]
        }
        mask = nest.CreateMask('box', maskdict)
        cntr = [0., 0., 0.]
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection((
            38,
            63,
            88,
        )))

        # Test with a larger box mask.
        maskdict = {
            'lower_left': [-1., -0.5, -1.],
            'upper_right': [1., 0.5, 1.]
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)
        self.assertEqual(
            node_ids, nest.NodeCollection([37, 38, 39, 62, 63, 64, 87, 88,
                                           89]))

        # Test the smaller box mask with a rotation of 90 degrees. Only test
        # the azimuth angle, not the polar angle.
        maskdict = {
            'lower_left': [-1., -0.5, -0.5],
            'upper_right': [1., 0.5, 0.5],
            'azimuth_angle': 90.
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection((
            58,
            63,
            68,
        )))

        # Test rotation of the larger box with an azimuth angle of 90 degrees.
        maskdict = {
            'lower_left': [-1., -0.5, -1.],
            'upper_right': [1., 0.5, 1.],
            'azimuth_angle': 90.
        }
        mask = nest.CreateMask('box', maskdict)
        node_ids = nest.SelectNodesByMask(layer, cntr, mask)
        self.assertEqual(
            node_ids, nest.NodeCollection([57, 58, 59, 62, 63, 64, 67, 68,
                                           69]))
Beispiel #18
0
    def test_GetNodes(self):
        """test GetNodes"""
        all_nodes_ref = nest.NodeCollection(list(range(1, nest.GetKernelStatus('network_size') + 1)))
        all_nodes = nest.GetNodes()

        self.assertEqual(all_nodes_ref, all_nodes)
Beispiel #19
0
    '''

    # sign of NNGT versus NEST inhibitory connections
    igroup = net.population["inhibitory"]

    # in NNGT
    iedges = net.get_edges(source_node=igroup.ids)
    w_nngt = set(net.get_weights(edges=iedges))

    # in NEST
    try:
        # nest 2
        iconn = nest.GetConnections(source=list(
            net.population["inhibitory"].nest_gids),
                                    target=list(net.population.nest_gids))
    except:
        # nest 3
        import nest
        s = nest.NodeCollection(net.population["inhibitory"].nest_gids)
        t = nest.NodeCollection(net.population.nest_gids)

        iconn = nest.GetConnections(source=s, target=t)

    w_nest = set(nest.GetStatus(iconn, "weight"))

    # In NNGT, inhibitory weights are positive to work with graph analysis
    # methods; they are automatically converted to negative weights in NEST
    print("NNGT weights:", w_nngt, "versus NEST weights", w_nest)

    assert w_nngt == {1} and w_nest == {-1}
Beispiel #20
0
    def test_TiltedEllipsoidalMask(self):
        """Ellipsoidal mask contains correct node IDs when tilted with respect to
        x-axis and z-axis"""

        pos = [[x * 1., y * 1., z * 1.] for x in range(-2, 3)
               for y in range(-2, 3) for z in range(-2, 3)]

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        maskdict = {
            'major_axis': 3.0,
            'minor_axis': 1.0,
            'polar_axis': 1.0,
            'polar_angle': 90.
        }
        mask = nest.CreateMask('ellipsoidal', maskdict)

        cntr = [0., 0., 0.]

        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection((
            62,
            63,
            64,
        )))

        nest.ResetKernel()

        pos = [[x * 1., y * 1., z * 1.] for x in range(-2, 3)
               for y in range(-2, 3) for z in range(-2, 3)]

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        maskdict = {
            'major_axis': 4.0,
            'minor_axis': 1.,
            'polar_axis': 1.5,
            'azimuth_angle': 45.,
            'polar_angle': 45.
        }
        mask = nest.CreateMask('ellipsoidal', maskdict)

        cntr = [0., 0., 0.]

        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection([34, 63, 92]))

        nest.ResetKernel()

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        maskdict = {
            'major_axis': 3.0,
            'minor_axis': 2.,
            'polar_axis': 1.0,
            'polar_angle': 45.
        }
        mask = nest.CreateMask('ellipsoidal', maskdict)

        cntr = [0., 0., 0.]

        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection([39, 58, 63, 68, 87]))

        nest.ResetKernel()

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        maskdict = {
            'major_axis': 4.0,
            'minor_axis': 1.,
            'polar_axis': 1.5,
            'polar_angle': 30.
        }
        mask = nest.CreateMask('ellipsoidal', maskdict)

        cntr = [0., 0., 0.]

        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids, nest.NodeCollection([38, 39, 63, 87, 88]))

        nest.ResetKernel()

        layer = nest.Create('iaf_psc_alpha', positions=nest.spatial.free(pos))

        maskdict = {
            'major_axis': 4.0,
            'minor_axis': 2.5,
            'polar_axis': 1.0,
            'azimuth_angle': 45.,
            'polar_angle': 30.
        }
        mask = nest.CreateMask('ellipsoidal', maskdict)

        cntr = [0., 0., 0.]

        node_ids = nest.SelectNodesByMask(layer, cntr, mask)

        self.assertEqual(node_ids,
                         nest.NodeCollection([34, 38, 58, 63, 68, 88, 92]))