Skip to content

Specific Populations#

ANNarchy provides a set of predefined Population objects to ease the definition of standard networks.

ANNarchy.core.SpecificPopulation.PoissonPopulation #

Bases: SpecificPopulation

Population of spiking neurons following a Poisson distribution.

Case 1: Input population

Each neuron of the population will randomly emit spikes, with a mean firing rate defined by the rates argument.

The mean firing rate in Hz can be a fixed value for all neurons:

pop = PoissonPopulation(geometry=100, rates=100.0)

but it can be modified later as a normal parameter:

pop.rates = np.linspace(10, 150, 100)

It is also possible to define a temporal equation for the rates, by passing a string to the argument:

pop = PoissonPopulation(
    geometry=100, 
    rates="100.0 * (1.0 + sin(2*pi*t/1000.0) )/2.0"
)

The syntax of this equation follows the same structure as neural variables.

It is also possible to add parameters to the population which can be used in the equation of rates:

pop = PoissonPopulation(
    geometry=100,
    parameters = '''
        amp = 100.0
        frequency = 1.0
    ''',
    rates="amp * (1.0 + sin(2*pi*frequency*t/1000.0) )/2.0"
)

Note: The preceding definition is fully equivalent to the definition of this neuron:

poisson = Neuron(
    parameters = '''
        amp = 100.0
        frequency = 1.0
    ''',
    equations = '''
        rates = amp * (1.0 + sin(2*pi*frequency*t/1000.0) )/2.0
        p = Uniform(0.0, 1.0) * 1000.0 / dt
    ''',
    spike = '''
        p < rates
    '''
)

The refractory period can also be set, so that a neuron can not emit two spikes too close from each other.

Case 2: Hybrid population

If the rates argument is not set, the population can be used as an interface from a rate-coded population.

The target argument specifies which incoming projections will be summed to determine the instantaneous firing rate of each neuron.

See the example in examples/hybrid/Hybrid.py for a usage.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
class PoissonPopulation(SpecificPopulation):
    """
    Population of spiking neurons following a Poisson distribution.

    **Case 1:** Input population

    Each neuron of the population will randomly emit spikes, with a mean firing rate defined by the *rates* argument.

    The mean firing rate in Hz can be a fixed value for all neurons:

    ```python
    pop = PoissonPopulation(geometry=100, rates=100.0)
    ```

    but it can be modified later as a normal parameter:

    ```python
    pop.rates = np.linspace(10, 150, 100)
    ```

    It is also possible to define a temporal equation for the rates, by passing a string to the argument:

    ```python
    pop = PoissonPopulation(
        geometry=100, 
        rates="100.0 * (1.0 + sin(2*pi*t/1000.0) )/2.0"
    )
    ```

    The syntax of this equation follows the same structure as neural variables.

    It is also possible to add parameters to the population which can be used in the equation of `rates`:

    ```python
    pop = PoissonPopulation(
        geometry=100,
        parameters = '''
            amp = 100.0
            frequency = 1.0
        ''',
        rates="amp * (1.0 + sin(2*pi*frequency*t/1000.0) )/2.0"
    )
    ```

    **Note:** The preceding definition is fully equivalent to the definition of this neuron:

    ```python
    poisson = Neuron(
        parameters = '''
            amp = 100.0
            frequency = 1.0
        ''',
        equations = '''
            rates = amp * (1.0 + sin(2*pi*frequency*t/1000.0) )/2.0
            p = Uniform(0.0, 1.0) * 1000.0 / dt
        ''',
        spike = '''
            p < rates
        '''
    )
    ```

    The refractory period can also be set, so that a neuron can not emit two spikes too close from each other.

    **Case 2:** Hybrid population

    If the ``rates`` argument is not set, the population can be used as an interface from a rate-coded population.

    The ``target`` argument specifies which incoming projections will be summed to determine the instantaneous firing rate of each neuron.

    See the example in ``examples/hybrid/Hybrid.py`` for a usage.

    """

    def __init__(self, geometry, name=None, rates=None, target=None, parameters=None, refractory=None, copied=False):
        """
        :param geometry: population geometry as tuple.
        :param name: unique name of the population (optional).
        :param rates: mean firing rate of each neuron. It can be a single value (e.g. 10.0) or an equation (as string).
        :param target: the mean firing rate will be the weighted sum of inputs having this target name (e.g. "exc").
        :param parameters: additional parameters which can be used in the *rates* equation.
        :param refractory: refractory period in ms.
        """
        if rates is None and target is None:
            Global._error('A PoissonPopulation must define either rates or target.')

        self.target = target
        self.parameters = parameters
        self.refractory_init = refractory
        self.rates_init = rates

        if target is not None: # hybrid population
            # Create the neuron
            poisson_neuron = Neuron(
                parameters = """
                %(params)s
                """ % {'params': parameters if parameters else ''},
                equations = """
                rates = sum(%(target)s)
                p = Uniform(0.0, 1.0) * 1000.0 / dt
                _sum_%(target)s = 0.0
                """ % {'target': target},
                spike = """
                    p < rates
                """,
                refractory=refractory,
                name="Hybrid",
                description="Hybrid spiking neuron emitting spikes according to a Poisson distribution at a frequency determined by the weighted sum of inputs."
            )


        elif isinstance(rates, str):
            # Create the neuron
            poisson_neuron = Neuron(
                parameters = """
                %(params)s
                """ % {'params': parameters if parameters else ''},
                equations = """
                rates = %(rates)s
                p = Uniform(0.0, 1.0) * 1000.0 / dt
                _sum_exc = 0.0
                """ % {'rates': rates},
                spike = """
                    p < rates
                """,
                refractory=refractory,
                name="Poisson",
                description="Spiking neuron with spikes emitted according to a Poisson distribution."
            )

        elif isinstance(rates, np.ndarray):
            poisson_neuron = Neuron(
                parameters = """
                rates = 10.0
                """,
                equations = """
                p = Uniform(0.0, 1.0) * 1000.0 / dt
                """,
                spike = """
                p < rates
                """,
                refractory=refractory,
                name="Poisson",
                description="Spiking neuron with spikes emitted according to a Poisson distribution."
            )
        else:
            poisson_neuron = Neuron(
                parameters = """
                rates = %(rates)s
                """ % {'rates': rates},
                equations = """
                p = Uniform(0.0, 1.0) * 1000.0 / dt
                """,
                spike = """
                p < rates
                """,
                refractory=refractory,
                name="Poisson",
                description="Spiking neuron with spikes emitted according to a Poisson distribution."
            )
        SpecificPopulation.__init__(self, geometry=geometry, neuron=poisson_neuron, name=name, copied=copied)

        if isinstance(rates, np.ndarray):
            self.rates = rates

    def _copy(self):
        "Returns a copy of the population when creating networks."
        return PoissonPopulation(self.geometry, name=self.name, rates=self.rates_init, target=self.target, parameters=self.parameters, refractory=self.refractory_init, copied=True)

    def _generate_st(self):
        """
        Generate single thread code.

        We don't need any separate code snippets. All is done during the
        normal code generation path.
        """
        pass

    def _generate_omp(self):
        """
        Generate openMP code.

        We don't need any separate code snippets. All is done during the
        normal code generation path.
        """
        pass

    def _generate_cuda(self):
        """
        Generate CUDA code.

        We don't need any separate code snippets. All is done during the
        normal code generation path.
        """
        pass

__init__(geometry, name=None, rates=None, target=None, parameters=None, refractory=None, copied=False) #

Parameters:

  • geometry

    population geometry as tuple.

  • name

    unique name of the population (optional).

  • rates

    mean firing rate of each neuron. It can be a single value (e.g. 10.0) or an equation (as string).

  • target

    the mean firing rate will be the weighted sum of inputs having this target name (e.g. "exc").

  • parameters

    additional parameters which can be used in the rates equation.

  • refractory

    refractory period in ms.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def __init__(self, geometry, name=None, rates=None, target=None, parameters=None, refractory=None, copied=False):
    """
    :param geometry: population geometry as tuple.
    :param name: unique name of the population (optional).
    :param rates: mean firing rate of each neuron. It can be a single value (e.g. 10.0) or an equation (as string).
    :param target: the mean firing rate will be the weighted sum of inputs having this target name (e.g. "exc").
    :param parameters: additional parameters which can be used in the *rates* equation.
    :param refractory: refractory period in ms.
    """
    if rates is None and target is None:
        Global._error('A PoissonPopulation must define either rates or target.')

    self.target = target
    self.parameters = parameters
    self.refractory_init = refractory
    self.rates_init = rates

    if target is not None: # hybrid population
        # Create the neuron
        poisson_neuron = Neuron(
            parameters = """
            %(params)s
            """ % {'params': parameters if parameters else ''},
            equations = """
            rates = sum(%(target)s)
            p = Uniform(0.0, 1.0) * 1000.0 / dt
            _sum_%(target)s = 0.0
            """ % {'target': target},
            spike = """
                p < rates
            """,
            refractory=refractory,
            name="Hybrid",
            description="Hybrid spiking neuron emitting spikes according to a Poisson distribution at a frequency determined by the weighted sum of inputs."
        )


    elif isinstance(rates, str):
        # Create the neuron
        poisson_neuron = Neuron(
            parameters = """
            %(params)s
            """ % {'params': parameters if parameters else ''},
            equations = """
            rates = %(rates)s
            p = Uniform(0.0, 1.0) * 1000.0 / dt
            _sum_exc = 0.0
            """ % {'rates': rates},
            spike = """
                p < rates
            """,
            refractory=refractory,
            name="Poisson",
            description="Spiking neuron with spikes emitted according to a Poisson distribution."
        )

    elif isinstance(rates, np.ndarray):
        poisson_neuron = Neuron(
            parameters = """
            rates = 10.0
            """,
            equations = """
            p = Uniform(0.0, 1.0) * 1000.0 / dt
            """,
            spike = """
            p < rates
            """,
            refractory=refractory,
            name="Poisson",
            description="Spiking neuron with spikes emitted according to a Poisson distribution."
        )
    else:
        poisson_neuron = Neuron(
            parameters = """
            rates = %(rates)s
            """ % {'rates': rates},
            equations = """
            p = Uniform(0.0, 1.0) * 1000.0 / dt
            """,
            spike = """
            p < rates
            """,
            refractory=refractory,
            name="Poisson",
            description="Spiking neuron with spikes emitted according to a Poisson distribution."
        )
    SpecificPopulation.__init__(self, geometry=geometry, neuron=poisson_neuron, name=name, copied=copied)

    if isinstance(rates, np.ndarray):
        self.rates = rates

ANNarchy.core.SpecificPopulation.SpikeSourceArray #

Bases: SpecificPopulation

Spike source generating spikes at the times given in the spike_times array.

Depending on the initial array provided, the population will have one or several neurons, but the geometry can only be one-dimensional.

You can later modify the spike_times attribute of the population, but it must have the same number of neurons as the initial one.

The spike times are by default relative to the start of a simulation (ANNarchy.get_time() is 0.0). If you call the reset() method of a SpikeSourceArray, this will set the spike times relative to the current time. You can then repeat a stimulation many times.

# 2 neurons firing at 100Hz with a 1 ms delay
times = [
    [ 10, 20, 30, 40],
    [ 11, 21, 31, 41]
]
inp = SpikeSourceArray(spike_times=times)

compile()

# Spikes at 10/11, 20/21, etc
simulate(50)

# Reset the internal time of the SpikeSourceArray
inp.reset()

# Spikes at 60/61, 70/71, etc
simulate(50)
Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
class SpikeSourceArray(SpecificPopulation):
    """
    Spike source generating spikes at the times given in the spike_times array.

    Depending on the initial array provided, the population will have one or several neurons, but the geometry can only be one-dimensional.

    You can later modify the spike_times attribute of the population, but it must have the same number of neurons as the initial one.

    The spike times are by default relative to the start of a simulation (``ANNarchy.get_time()`` is 0.0).
    If you call the ``reset()`` method of a ``SpikeSourceArray``, this will set the spike times relative to the current time.
    You can then repeat a stimulation many times.

    ```python
    # 2 neurons firing at 100Hz with a 1 ms delay
    times = [
        [ 10, 20, 30, 40],
        [ 11, 21, 31, 41]
    ]
    inp = SpikeSourceArray(spike_times=times)

    compile()

    # Spikes at 10/11, 20/21, etc
    simulate(50)

    # Reset the internal time of the SpikeSourceArray
    inp.reset()

    # Spikes at 60/61, 70/71, etc
    simulate(50)
    ```
    """
    def __init__(self, spike_times, name=None, copied=False):
        """
        :param spike_times: a list of times at which a spike should be emitted if the population should have only 1 neuron, a list of lists otherwise. Times are defined in milliseconds, and will be rounded to the closest multiple of the discretization time step dt.
        :param name: optional name for the population.
        """

        if not isinstance(spike_times, list):
            Global._error('In a SpikeSourceArray, spike_times must be a Python list.')

        if isinstance(spike_times[0], list): # several neurons
            nb_neurons = len(spike_times)
        else: # a single Neuron
            nb_neurons = 1
            spike_times = [ spike_times ]

        # Create a fake neuron just to be sure the description has the correct parameters
        neuron = Neuron(
            parameters="",
            equations="",
            spike=" t == 0",
            reset="",
            name="Spike source",
            description="Spike source array."
        )

        SpecificPopulation.__init__(self, geometry=nb_neurons, neuron=neuron, name=name, copied=copied)

        self.init['spike_times'] = spike_times


    def _copy(self):
        "Returns a copy of the population when creating networks."
        return SpikeSourceArray(self.init['spike_times'], self.name, copied=True)

    def _sort_spikes(self, spike_times):
        "Sort, unify the spikes and transform them into steps."
        return [sorted(list(set([round(t/Global.config['dt']) for t in neur_times]))) for neur_times in spike_times]

    def _generate_st(self):
        """
        Code generation for single-thread.
        """
        self._generate_omp()

    def _generate_omp(self):
        """
        Code generation for openMP paradigm.
        """
        # Add possible targets
        for target in self.targets:
            tpl = {
                'name': 'g_%(target)s' % {'target': target},
                'locality': 'local',
                'eq': '',
                'bounds': {},
                'flags': [],
                'ctype': Global.config['precision'],
                'init': 0.0,
                'transformed_eq': '',
                'pre_loop': {},
                'cpp': '',
                'switch': '',
                'untouched': {},
                'method': 'exponential',
                'dependencies': []
            }
            self.neuron_type.description['variables'].append(tpl)
            self.neuron_type.description['local'].append('g_'+target)

        self._specific_template['declare_additional'] = """
    // Custom local parameter spike_times
    // std::vector< %(float_prec)s > r ;
    std::vector< std::vector< long int > > spike_times ;
    std::vector< long int >  next_spike ;
    std::vector< int > idx_next_spike;
    long int _t;

    // Recompute the spike times
    void recompute_spike_times(){
        std::fill(next_spike.begin(), next_spike.end(), -10000);
        std::fill(idx_next_spike.begin(), idx_next_spike.end(), 0);
        for(int i=0; i< size; i++){
            if(!spike_times[i].empty()){
                int idx = 0;
                // Find the first spike time which is not in the past
                while(spike_times[i][idx] < _t){
                    idx++;
                }
                // Set the next spike
                if(idx < spike_times[i].size())
                    next_spike[i] = spike_times[i][idx];
                else
                    next_spike[i] = -10000;
            }
        }
    }
"""% { 'float_prec': Global.config['precision'] }

        #self._specific_template['access_parameters_variables'] = ""

        self._specific_template['init_additional'] = """
        _t = 0;
        next_spike = std::vector<long int>(size, -10000);
        idx_next_spike = std::vector<int>(size, 0);
        this->recompute_spike_times();
""" 

        self._specific_template['reset_additional'] = """
        _t = 0;
        this->recompute_spike_times();
"""

        if Global.config["num_threads"] == 1:
            self._specific_template['update_variables'] = """
        if(_active){
            spiked.clear();
            for(int i = 0; i < size; i++){
                // Emit spike
                if( _t == next_spike[i] ){
                    last_spike[i] = _t;
                    idx_next_spike[i]++ ;
                    if(idx_next_spike[i] < spike_times[i].size()){
                        next_spike[i] = spike_times[i][idx_next_spike[i]];
                    }
                    spiked.push_back(i);
                }
            }
            _t++;
        }
"""
        else:
            self._specific_template['update_variables'] = """
        if(_active){
            #pragma omp single
            {
                spiked.clear();
            }

            #pragma omp for
            for(int i = 0; i < size; i++){
                // Emit spike
                if( _t == next_spike[i] ){
                    last_spike[i] = _t;
                    idx_next_spike[i]++ ;
                    if(idx_next_spike[i] < spike_times[i].size()){
                        next_spike[i] = spike_times[i][idx_next_spike[i]];
                    }

                    #pragma omp critical
                    spiked.push_back(i);
                }
            }

            #pragma omp single
            {
                _t++;
            }
        }
"""
        self._specific_template['test_spike_cond'] = ""

        self._specific_template['export_additional'] ="""
        vector[vector[long]] spike_times
        void recompute_spike_times()
"""

        self._specific_template['wrapper_args'] = "size, times, delay"
        self._specific_template['wrapper_init'] = """
        pop%(id)s.spike_times = times
        pop%(id)s.set_size(size)
        pop%(id)s.set_max_delay(delay)""" % {'id': self.id}

        self._specific_template['wrapper_access_additional'] = """
    # Local parameter spike_times
    cpdef get_spike_times(self):
        return pop%(id)s.spike_times
    cpdef set_spike_times(self, value):
        pop%(id)s.spike_times = value
        pop%(id)s.recompute_spike_times()
""" % {'id': self.id}

    def _generate_cuda(self):
        """
        Code generation for the CUDA paradigm.

        As the spike time generation is not a very compute intensive step but
        requires dynamic data structures, we don't implement it on the CUDA
        devices for now. Consequently, we use the CPU side implementation and
        transfer after computation the results to the GPU.
        """
        self._generate_st()

        # attach transfer of spiked array to gpu
        # IMPORTANT: the outside transfer is necessary.
        # Otherwise, previous spike counts will be not reseted.
        self._specific_template['update_variables'] += """
        if ( _active ) {
            // Update Spike Count on GPU
            spike_count = spiked.size();
            cudaMemcpy( gpu_spike_count, &spike_count, sizeof(unsigned int), cudaMemcpyHostToDevice);

            // Transfer generated spikes to GPU
            if( spike_count > 0 ) {
                cudaMemcpy( gpu_spiked, spiked.data(), spike_count * sizeof(int), cudaMemcpyHostToDevice);
            }
        }
        """
        self._specific_template['update_variable_body'] = ""
        self._specific_template['update_variable_header'] = ""
        self._specific_template['update_variable_call'] = """
    // host side update of neurons
    pop%(id)s.update();
""" % {'id': self.id}

    def _instantiate(self, module):
        # Create the Cython instance
        self.cyInstance = getattr(module, self.class_name+'_wrapper')(self.size, self.init['spike_times'], self.max_delay)

    def __setattr__(self, name, value):
        if name == 'spike_times':
            if not isinstance(value[0], list): # several neurons
                value = [ value ]
            if not len(value) == self.size:
                Global._error('SpikeSourceArray: the size of the spike_times attribute must match the number of neurons in the population.')

            self.init['spike_times'] = value # when reset is called
            if self.initialized:
                self.cyInstance.set_spike_times(self._sort_spikes(value))
        else:
            Population.__setattr__(self, name, value)

    def __getattr__(self, name):
        if name == 'spike_times':
            if self.initialized:
                return [ [Global.config['dt']*time for time in neur] for neur in self.cyInstance.get_spike_times()]
            else:
                return self.init['spike_times']
        else:
            return Population.__getattribute__(self, name)

__init__(spike_times, name=None, copied=False) #

Parameters:

  • spike_times

    a list of times at which a spike should be emitted if the population should have only 1 neuron, a list of lists otherwise. Times are defined in milliseconds, and will be rounded to the closest multiple of the discretization time step dt.

  • name

    optional name for the population.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
def __init__(self, spike_times, name=None, copied=False):
    """
    :param spike_times: a list of times at which a spike should be emitted if the population should have only 1 neuron, a list of lists otherwise. Times are defined in milliseconds, and will be rounded to the closest multiple of the discretization time step dt.
    :param name: optional name for the population.
    """

    if not isinstance(spike_times, list):
        Global._error('In a SpikeSourceArray, spike_times must be a Python list.')

    if isinstance(spike_times[0], list): # several neurons
        nb_neurons = len(spike_times)
    else: # a single Neuron
        nb_neurons = 1
        spike_times = [ spike_times ]

    # Create a fake neuron just to be sure the description has the correct parameters
    neuron = Neuron(
        parameters="",
        equations="",
        spike=" t == 0",
        reset="",
        name="Spike source",
        description="Spike source array."
    )

    SpecificPopulation.__init__(self, geometry=nb_neurons, neuron=neuron, name=name, copied=copied)

    self.init['spike_times'] = spike_times

ANNarchy.core.SpecificPopulation.TimedArray #

Bases: SpecificPopulation

Data structure holding sequential inputs for a rate-coded network.

The input values are stored in the (recordable) attribute r, without any further processing. You will need to connect this population to another one using the connect_one_to_one() method.

By default, the firing rate of this population will iterate over the different values step by step:

inputs = np.array(
    [
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
    ]
)

inp = TimedArray(rates=inputs)

pop = Population(10, ...)

proj = Projection(inp, pop, 'exc')
proj.connect_one_to_one(1.0)

compile()

simulate(10.)

This creates a population of 10 neurons whose activity will change during the first 10*dt milliseconds of the simulation. After that delay, the last input will be kept (i.e. 1 for the last neuron).

If you want the TimedArray to "loop" over the different input vectors, you can specify a period for the inputs:

inp = TimedArray(rates=inputs, period=10.)

If the period is smaller than the length of the rates, the last inputs will not be set.

If you do not want the inputs to be set at every step, but every 10 ms for example, youcan use the schedule argument:

inp = TimedArray(rates=inputs, schedule=10.)

The input [1, 0, 0,...] will stay for 10 ms, then[0, 1, 0, ...] for the next 10 ms, etc...

If you need a less regular schedule, you can specify it as a list of times:

inp = TimedArray(rates=inputs, schedule=[10., 20., 50., 60., 100., 110.])

The first input is set at t = 10 ms (r = 0.0 in the first 10 ms), the second at t = 20 ms, the third at t = 50 ms, etc.

If you specify less times than in the array of rates, the last ones will be ignored.

Scheduling can be combined with periodic cycling. Note that you can use the reset() method to manually reinitialize the TimedArray, times becoming relative to that call:

simulate(100.) # ten inputs are shown with a schedule of 10 ms
inp.reset()
simulate(100.) # the same ten inputs are presented again.
Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
class TimedArray(SpecificPopulation):
    """
    Data structure holding sequential inputs for a rate-coded network.

    The input values are stored in the (recordable) attribute `r`, without any further processing. 
    You will need to connect this population to another one using the ``connect_one_to_one()`` method.

    By default, the firing rate of this population will iterate over the different values step by step:

    ```python
    inputs = np.array(
        [
            [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
        ]
    )

    inp = TimedArray(rates=inputs)

    pop = Population(10, ...)

    proj = Projection(inp, pop, 'exc')
    proj.connect_one_to_one(1.0)

    compile()

    simulate(10.)
    ```

    This creates a population of 10 neurons whose activity will change during the first 10*dt milliseconds of the simulation. After that delay, the last input will be kept (i.e. 1 for the last neuron).

    If you want the TimedArray to "loop" over the different input vectors, you can specify a period for the inputs:

    ```python
    inp = TimedArray(rates=inputs, period=10.)
    ```

    If the period is smaller than the length of the rates, the last inputs will not be set.

    If you do not want the inputs to be set at every step, but every 10 ms for example, youcan use the ``schedule`` argument:

    ```python
    inp = TimedArray(rates=inputs, schedule=10.)
    ```

    The input [1, 0, 0,...] will stay for 10 ms, then[0, 1, 0, ...] for the next 10 ms, etc...

    If you need a less regular schedule, you can specify it as a list of times:

    ```python
    inp = TimedArray(rates=inputs, schedule=[10., 20., 50., 60., 100., 110.])
    ```

    The first input is set at t = 10 ms (r = 0.0 in the first 10 ms), the second at t = 20 ms, the third at t = 50 ms, etc.

    If you specify less times than in the array of rates, the last ones will be ignored.

    Scheduling can be combined with periodic cycling. Note that you can use the ``reset()`` method to manually reinitialize the TimedArray, times becoming relative to that call:

    ```python
    simulate(100.) # ten inputs are shown with a schedule of 10 ms
    inp.reset()
    simulate(100.) # the same ten inputs are presented again.
    ```

    """
    def __init__(self, rates, schedule=0., period= -1., name=None, copied=False):
        """
        :param rates: array of firing rates. The first axis corresponds to time, the others to the desired dimensions of the population.
        :param schedule: either a single value or a list of time points where inputs should be set. Default: every timestep.
        :param period: time when the timed array will be reset and start again, allowing cycling over the inputs. Default: no cycling (-1.).
        """
        neuron = Neuron(
            parameters="",
            equations=" r = 0.0",
            name="Timed Array",
            description="Timed array source."
        )
        # Geometry of the population
        geometry = rates.shape[1:]

        # Check the schedule
        if isinstance(schedule, (int, float)):
            if float(schedule) <= 0.0:
                schedule = Global.config['dt']
            schedule = [ float(schedule*i) for i in range(rates.shape[0])]

        if len(schedule) > rates.shape[0]:
            Global._error('TimedArray: the length of the schedule parameter cannot exceed the first dimension of the rates parameter.')

        if len(schedule) < rates.shape[0]:
            Global._warning('TimedArray: the length of the schedule parameter is smaller than the first dimension of the rates parameter (more data than time points). Make sure it is what you expect.')

        SpecificPopulation.__init__(self, geometry=geometry, neuron=neuron, name=name, copied=copied)

        self.init['schedule'] = schedule
        self.init['rates'] = rates
        self.init['period'] = period

    def _copy(self):
        "Returns a copy of the population when creating networks."
        return TimedArray(self.init['rates'] , self.init['schedule'], self.init['period'], self.name, copied=True)

    def _generate_st(self):
        """
        adjust code templates for the specific population for single thread and openMP.
        """
        self._specific_template['declare_additional'] = """
    // Custom local parameters of a TimedArray
    std::vector< int > _schedule; // List of times where new inputs should be set
    std::vector< std::vector< %(float_prec)s > > _buffer; // buffer holding the data
    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}
        self._specific_template['access_additional'] = """
    // Custom local parameters of a TimedArray
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }
    void set_buffer(std::vector< std::vector< %(float_prec)s > > buffer) { _buffer = buffer; r = _buffer[0]; }
    std::vector< std::vector< %(float_prec)s > > get_buffer() { return _buffer; }
    void set_period(int period) { _period = period; }
    int get_period() { return _period; }
""" % {'float_prec': Global.config['precision']}
        self._specific_template['init_additional'] = """
        // Initialize counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters of a TimedArray
        void set_schedule(vector[int])
        vector[int] get_schedule()
        void set_buffer(vector[vector[%(float_prec)s]])
        vector[vector[%(float_prec)s]] get_buffer()
        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}

        self._specific_template['reset_additional'] ="""
        _t = 0;
        _block = 0;

        r.clear();
        r = std::vector<%(float_prec)s>(size, 0.0);
""" % {'float_prec': Global.config['precision']}

        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters of a TimedArray
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_rates( self, buffer ):
        pop%(id)s.set_buffer( buffer )
    cpdef np.ndarray get_rates( self ):
        return np.array(pop%(id)s.get_buffer( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_period(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id }

        self._specific_template['update_variables'] = """
        if(_active){
            //std::cout << _t << " " << _block<< " " << _schedule[_block] << std::endl;

            // Check if it is time to set the input
            if(_t == _schedule[_block]){
                // Set the data
                r = _buffer[_block];
                // Move to the next block
                _block++;
                // If was the last block, go back to the first block
                if (_block == _schedule.size()){
                    _block = 0;
                }
            }

            // If the timedarray is periodic, check if we arrive at that point
            if(_period > -1 && (_t == _period-1)){
                // Reset the counters
                _block=0;
                _t = -1;
            }

            // Always increment the internal time
            _t++;
        }
"""

        self._specific_template['size_in_bytes'] = """
        // schedule
        size_in_bytes += _schedule.capacity() * sizeof(int);

        // buffer
        size_in_bytes += _buffer.capacity() * sizeof(std::vector<%(float_prec)s>);
        for( auto it = _buffer.begin(); it != _buffer.end(); it++ )
            size_in_bytes += it->capacity() * sizeof(%(float_prec)s);
""" % {'float_prec': Global.config['precision']}

    def _generate_omp(self):
        """
        adjust code templates for the specific population for single thread and openMP.
        """
        self._specific_template['declare_additional'] = """
    // Custom local parameters of a TimedArray
    std::vector< int > _schedule; // List of times where new inputs should be set
    std::vector< std::vector< %(float_prec)s > > _buffer; // buffer holding the data
    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}
        self._specific_template['access_additional'] = """
    // Custom local parameters of a TimedArray
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }
    void set_buffer(std::vector< std::vector< %(float_prec)s > > buffer) { _buffer = buffer; r = _buffer[0]; }
    std::vector< std::vector< %(float_prec)s > > get_buffer() { return _buffer; }
    void set_period(int period) { _period = period; }
    int get_period() { return _period; }
""" % {'float_prec': Global.config['precision']}
        self._specific_template['init_additional'] = """
        // Initialize counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters of a TimedArray
        void set_schedule(vector[int])
        vector[int] get_schedule()
        void set_buffer(vector[vector[%(float_prec)s]])
        vector[vector[%(float_prec)s]] get_buffer()
        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}

        self._specific_template['reset_additional'] ="""
        _t = 0;
        _block = 0;

        r.clear();
        r = std::vector<%(float_prec)s>(size, 0.0);
""" % {'float_prec': Global.config['precision']}

        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters of a TimedArray
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_rates( self, buffer ):
        pop%(id)s.set_buffer( buffer )
    cpdef np.ndarray get_rates( self ):
        return np.array(pop%(id)s.get_buffer( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_period(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id }

        self._specific_template['update_variables'] = """
        if(_active){
            #pragma omp single
            {
                // Check if it is time to set the input
                if(_t == _schedule[_block]){
                    // Set the data
                    r = _buffer[_block];
                    // Move to the next block
                    _block++;
                    // If was the last block, go back to the first block
                    if (_block == _schedule.size()){
                        _block = 0;
                    }
                }

                // If the timedarray is periodic, check if we arrive at that point
                if(_period > -1 && (_t == _period-1)){
                    // Reset the counters
                    _block=0;
                    _t = -1;
                }

                // Always increment the internal time
                _t++;
            }
        }
"""

        self._specific_template['size_in_bytes'] = """
        // schedule
        size_in_bytes += _schedule.capacity() * sizeof(int);

        // buffer
        size_in_bytes += _buffer.capacity() * sizeof(std::vector<%(float_prec)s>);
        for( auto it = _buffer.begin(); it != _buffer.end(); it++ )
            size_in_bytes += it->capacity() * sizeof(%(float_prec)s);
""" % {'float_prec': Global.config['precision']}

    def _generate_cuda(self):
        """
        adjust code templates for the specific population for single thread and CUDA.
        """
        # HD (18. Nov 2016)
        # I suppress the code generation for allocating the variable r on gpu, as
        # well as memory transfer codes. This is only possible as no other variables
        # allowed in TimedArray.
        self._specific_template['init_parameters_variables'] = ""
        self._specific_template['host_device_transfer'] = ""
        self._specific_template['device_host_transfer'] = ""

        #
        # Code for handling the buffer and schedule parameters
        self._specific_template['declare_additional'] = """
    // Custom local parameter timed array
    std::vector< int > _schedule;
    std::vector< %(float_prec)s* > gpu_buffer;
    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}
        self._specific_template['access_additional'] = """
    // Custom local parameter timed array
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }
    void set_buffer(std::vector< std::vector< %(float_prec)s > > buffer) {
        if ( gpu_buffer.empty() ) {
            gpu_buffer = std::vector< %(float_prec)s* >(buffer.size(), nullptr);
            // allocate gpu arrays
            for(int i = 0; i < buffer.size(); i++) {
                cudaMalloc((void**)&gpu_buffer[i], buffer[i].size()*sizeof(%(float_prec)s));
            }
        }

        auto host_it = buffer.begin();
        auto dev_it = gpu_buffer.begin();
        for (; host_it < buffer.end(); host_it++, dev_it++) {
            cudaMemcpy( *dev_it, host_it->data(), host_it->size()*sizeof(%(float_prec)s), cudaMemcpyHostToDevice);
        }

        gpu_r = gpu_buffer[0];
    }
    std::vector< std::vector< %(float_prec)s > > get_buffer() {
        std::vector< std::vector< %(float_prec)s > > buffer = std::vector< std::vector< %(float_prec)s > >( gpu_buffer.size(), std::vector<%(float_prec)s>(size,0.0) );

        auto host_it = buffer.begin();
        auto dev_it = gpu_buffer.begin();
        for (; host_it < buffer.end(); host_it++, dev_it++) {
            cudaMemcpy( host_it->data(), *dev_it, size*sizeof(%(float_prec)s), cudaMemcpyDeviceToHost );
        }

        return buffer;
    }
    void set_period(int period) { _period = period; }
    int get_period() { return _period; }
""" % {'float_prec': Global.config['precision']}
        self._specific_template['init_additional'] = """
        // counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['reset_additional'] = """
        // counters
        _t = 0;
        _block = 0;
        gpu_r = gpu_buffer[0];
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters timed array
        void set_schedule(vector[int])
        vector[int] get_schedule()
        void set_buffer(vector[vector[%(float_prec)s]])
        vector[vector[%(float_prec)s]] get_buffer()
        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}
        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters timed array
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_rates( self, buffer ):
        pop%(id)s.set_buffer( buffer )
    cpdef np.ndarray get_rates( self ):
        return np.array(pop%(id)s.get_buffer( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_periodic(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id, 'float_prec': Global.config['precision'] }

        self._specific_template['update_variables'] = """
        if(_active) {
            // std::cout << _t << " " << _block<< " " << _schedule[_block] << std::endl;
            // Check if it is time to set the input
            if(_t == _schedule[_block]){
                // Set the data
                gpu_r = gpu_buffer[_block];
                // Move to the next block
                _block++;
                // If was the last block, go back to the first block
                if ( _block == _schedule.size() ) {
                    _block = 0;
                }
            }

            // If the timedarray is periodic, check if we arrive at that point
            if( (_period > -1) && (_t == _period-1) ) {
                // Reset the counters
                _block=0;
                _t = -1;
            }

            // Always increment the internal time
            _t++;
        }
"""

        self._specific_template['update_variable_body'] = ""
        self._specific_template['update_variable_header'] = ""
        self._specific_template['update_variable_call'] = """
    // host side update of neurons
    pop%(id)s.update();
""" % {'id': self.id}

        self._specific_template['size_in_bytes'] = "//TODO: "

    def _instantiate(self, module):
        # Create the Cython instance
        self.cyInstance = getattr(module, self.class_name+'_wrapper')(self.size, self.max_delay)

    def __setattr__(self, name, value):
        if name == 'schedule':
            if self.initialized:
                self.cyInstance.set_schedule( np.array(value) / Global.config['dt'] )
            else:
                self.init['schedule'] = value
        elif name == 'rates':
            if self.initialized:
                if len(value.shape) > 2:
                    # we need to flatten the provided data
                    flat_values = value.reshape( (value.shape[0], self.size) )
                    self.cyInstance.set_rates( flat_values )
                else:
                    self.cyInstance.set_rates( value )
            else:
                self.init['rates'] = value
        elif name == "period":
            if self.initialized:
                self.cyInstance.set_period(int(value /Global.config['dt']))
            else:
                self.init['period'] = value
        else:
            Population.__setattr__(self, name, value)

    def __getattr__(self, name):
        if name == 'schedule':
            if self.initialized:
                return Global.config['dt'] * self.cyInstance.get_schedule()
            else:
                return self.init['schedule']
        elif name == 'rates':
            if self.initialized:
                if len(self.geometry) > 1:
                    # unflatten the data
                    flat_values = self.cyInstance.get_rates()
                    values = np.zeros( tuple( [len(self.schedule)] + list(self.geometry) ) )
                    for x in range(len(self.schedule)):
                        values[x] = np.reshape( flat_values[x], self.geometry)
                    return values
                else:
                    return self.cyInstance.get_rates()
            else:
                return self.init['rates']
        elif name == 'period':
            if self.initialized:
                return self.cyInstance.get_period() * Global.config['dt']
            else:
                return self.init['period']
        else:
            return Population.__getattribute__(self, name)

__init__(rates, schedule=0.0, period=-1.0, name=None, copied=False) #

Parameters:

  • rates

    array of firing rates. The first axis corresponds to time, the others to the desired dimensions of the population.

  • schedule

    either a single value or a list of time points where inputs should be set. Default: every timestep.

  • period

    time when the timed array will be reset and start again, allowing cycling over the inputs. Default: no cycling (-1.).

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def __init__(self, rates, schedule=0., period= -1., name=None, copied=False):
    """
    :param rates: array of firing rates. The first axis corresponds to time, the others to the desired dimensions of the population.
    :param schedule: either a single value or a list of time points where inputs should be set. Default: every timestep.
    :param period: time when the timed array will be reset and start again, allowing cycling over the inputs. Default: no cycling (-1.).
    """
    neuron = Neuron(
        parameters="",
        equations=" r = 0.0",
        name="Timed Array",
        description="Timed array source."
    )
    # Geometry of the population
    geometry = rates.shape[1:]

    # Check the schedule
    if isinstance(schedule, (int, float)):
        if float(schedule) <= 0.0:
            schedule = Global.config['dt']
        schedule = [ float(schedule*i) for i in range(rates.shape[0])]

    if len(schedule) > rates.shape[0]:
        Global._error('TimedArray: the length of the schedule parameter cannot exceed the first dimension of the rates parameter.')

    if len(schedule) < rates.shape[0]:
        Global._warning('TimedArray: the length of the schedule parameter is smaller than the first dimension of the rates parameter (more data than time points). Make sure it is what you expect.')

    SpecificPopulation.__init__(self, geometry=geometry, neuron=neuron, name=name, copied=copied)

    self.init['schedule'] = schedule
    self.init['rates'] = rates
    self.init['period'] = period

ANNarchy.core.SpecificPopulation.HomogeneousCorrelatedSpikeTrains #

Bases: SpecificPopulation

Population of spiking neurons following a homogeneous distribution with correlated spike trains.

The method describing the generation of homogeneous correlated spike trains is described in:

Brette, R. (2009). Generation of correlated spike trains. Neural Computation 21(1). http://romainbrette.fr/WordPress3/wp-content/uploads/2014/06/Brette2008NC.pdf

The implementation is based on the one provided by Brian http://briansimulator.org.

To generate correlated spike trains, the population rate of the group of Poisson-like spiking neurons varies following a stochastic differential equation:

\[\frac{dx}{dt} = \frac{(\mu - x)}{\tau} + \sigma \, \frac{\xi}{\sqrt{\tau}}\]

where \(\xi\) is a random variable. In short, \(x\) will randomly vary around mu over time, with an amplitude determined by sigma and a speed determined by tau.

This doubly stochastic process is called a Cox process or Ornstein-Uhlenbeck process.

To avoid that x becomes negative, the values of mu and sigma are computed from a rectified Gaussian distribution, parameterized by the desired population rate rates, the desired correlation strength corr and the time constant tau. See Brette's paper for details.

In short, you should only define the parameters rates, corr and tau, and let the class compute mu and sigma for you. Changing rates, corr or tau after initialization automatically recomputes mu and sigma.

Example:

from ANNarchy import *
setup(dt=0.1)

pop_corr = HomogeneousCorrelatedSpikeTrains(200, rates=10., corr=0.3, tau=10.)

compile()

simulate(1000.)

pop_corr.rates=30.

simulate(1000.)

Alternatively, a schedule can be provided to change automatically the value of rates and corr (but not tau) at the required times (as in TimedArray or TimedPoissonPopulation):

from ANNarchy import *
setup(dt=0.1)

pop_corr = HomogeneousCorrelatedSpikeTrains(
    geometry=200, 
    rates= [10., 30.], 
    corr=[0.3, 0.5], 
    tau=10.,
    schedule=[0., 1000.]
)

compile()

simulate(2000.)

Even when using a schedule, corr accepts a single constant value. The first value of schedule must be 0. period specifies when the schedule "loops" back to its initial value.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
class HomogeneousCorrelatedSpikeTrains(SpecificPopulation):
    """
    Population of spiking neurons following a homogeneous distribution with correlated spike trains.

    The method describing the generation of homogeneous correlated spike trains is described in:

    > Brette, R. (2009). Generation of correlated spike trains. Neural Computation 21(1). <http://romainbrette.fr/WordPress3/wp-content/uploads/2014/06/Brette2008NC.pdf>

    The implementation is based on the one provided by Brian <http://briansimulator.org>.

    To generate correlated spike trains, the population rate of the group of Poisson-like spiking neurons varies following a stochastic differential equation:

    $$\\frac{dx}{dt} = \\frac{(\\mu - x)}{\\tau} + \\sigma \\, \\frac{\\xi}{\\sqrt{\\tau}}$$

    where $\\xi$ is a random variable. In short, $x$ will randomly vary around mu over time, with an amplitude determined by sigma and a speed determined by tau.

    This doubly stochastic process is called a Cox process or Ornstein-Uhlenbeck process.

    To avoid that x becomes negative, the values of mu and sigma are computed from a rectified Gaussian distribution, parameterized by the desired population rate **rates**, the desired correlation strength **corr** and the time constant **tau**. See Brette's paper for details.

    In short, you should only define the parameters ``rates``, ``corr`` and ``tau``, and let the class compute mu and sigma for you. Changing ``rates``, ``corr`` or ``tau`` after initialization automatically recomputes mu and sigma.

    Example:

    ```python
    from ANNarchy import *
    setup(dt=0.1)

    pop_corr = HomogeneousCorrelatedSpikeTrains(200, rates=10., corr=0.3, tau=10.)

    compile()

    simulate(1000.)

    pop_corr.rates=30.

    simulate(1000.)
    ```

    Alternatively, a schedule can be provided to change automatically the value of `rates` and ``corr`` (but not ``tau``) at the required times (as in TimedArray or TimedPoissonPopulation):

    ```python
    from ANNarchy import *
    setup(dt=0.1)

    pop_corr = HomogeneousCorrelatedSpikeTrains(
        geometry=200, 
        rates= [10., 30.], 
        corr=[0.3, 0.5], 
        tau=10.,
        schedule=[0., 1000.]
    )

    compile()

    simulate(2000.)
    ```

    Even when using a schedule, ``corr`` accepts a single constant value. The first value of ``schedule`` must be 0. ``period`` specifies when the schedule "loops" back to its initial value. 

    """
    def __init__(self, 
        geometry, 
        rates, 
        corr, 
        tau, 
        schedule=None, 
        period=-1., 
        name=None, 
        refractory=None, 
        copied=False):
        """    
        :param geometry: population geometry as tuple.
        :param rates: rate in Hz of the population (must be a positive float or a list)
        :param corr: total correlation strength (float in [0, 1], or a list)
        :param tau: correlation time constant in ms.
        :param schedule: list of times where new values of ``rates``and ``corr``will be used to computre mu and sigma.
        :param period: time when the array will be reset and start again, allowing cycling over the schedule. Default: no cycling (-1.)
        :param name: unique name of the population (optional).
        :param refractory: refractory period in ms (careful: may break the correlation)
        """
        if schedule is not None:
            self._has_schedule = True
            # Rates
            if not isinstance(rates, (list, np.ndarray)):
                Global._error("TimedHomogeneousCorrelatedSpikeTrains: the rates argument must be a list or a numpy array.")
            rates = np.array(rates)

            # Schedule
            schedule = np.array(schedule)

            nb_schedules = rates.shape[0]
            if nb_schedules != schedule.size:
                Global._error("TimedHomogeneousCorrelatedSpikeTrains: the length of rates must be the same length as for schedule.")

            # corr
            corr = np.array(corr)
            if corr.size == 1:
                corr = np.full(nb_schedules, corr)
        else:
            self._has_schedule = False
            rates = np.array([float(rates)])
            schedule = np.array([0.0])
            corr = np.array([corr])


        # Store refractory
        self.refractory_init = refractory

        # Correction of mu and sigma
        mu_list, sigma_list = self._correction(rates, corr, tau)

        self.rates = rates
        self.corr = corr
        self.tau = tau

        # Create the neuron
        corr_neuron = Neuron(
            parameters = """
                tau = %(tau)s : population
                mu = %(mu)s : population
                sigma = %(sigma)s : population
            """ % {'tau': tau, 'mu': mu_list[0], 'sigma': sigma_list[0]},
            equations = """
                x += dt*(mu - x)/tau + sqrt(dt/tau) * sigma * Normal(0., 1.) : population, init=%(mu)s
                p = Uniform(0.0, 1.0) * 1000.0 / dt
            """ % {'mu': mu_list[0]},
            spike = "p < x",
            refractory=refractory,
            name="HomogeneousCorrelated",
            description="Homogeneous correlated spike trains."
        )

        SpecificPopulation.__init__(self, geometry=geometry, neuron=corr_neuron, name=name, copied=copied)

        # Initial values
        self.init['schedule'] = schedule
        self.init['rates'] = rates
        self.init['corr'] = corr
        self.init['tau'] = tau
        self.init['period'] = period


        if self._has_schedule:
            self.init['mu'] = mu_list
            self.init['sigma'] = sigma_list
        else:
            self.init['mu'] = mu_list[0]
            self.init['sigma'] = sigma_list[0]

    def _copy(self):
        "Returns a copy of the population when creating networks."
        return HomogeneousCorrelatedSpikeTrains(
            geometry=self.geometry, 
            rates=self.init['rates'], 
            corr=self.init['corr'], 
            tau=self.init['tau'], 
            schedule=self.init['schedule'], 
            period=self.init['period'], 
            name=self.name, 
            refractory=self.refractory_init, 
            copied=True)

    def _correction(self, rates, corr, tau):

        # Correction of mu and sigma
        mu_list = []
        sigma_list = []

        for i in range(len(rates)):
            if isinstance(corr, list):
                c = corr[i]
            else:
                c = float(corr)
            mu, sigma = _rectify(rates[i], c, tau)
            mu_list.append(mu)
            sigma_list.append(sigma)

        return mu_list, sigma_list

    def _generate_st(self):
        """
        adjust code templates for the specific population for single thread.
        """
        self._specific_template['declare_additional'] = """
    // Custom local parameters of a HomogeneousCorrelatedSpikeTrains
    std::vector< int > _schedule; // List of times where new inputs should be set

    std::vector< %(float_prec)s > _mu; // buffer holding the data
    std::vector< %(float_prec)s > _sigma; // buffer holding the data

    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}

        self._specific_template['access_additional'] = """
    // Custom local parameters of a HomogeneousCorrelatedSpikeTrains
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }

    void set_mu_list(std::vector< %(float_prec)s > buffer) { _mu = buffer; mu = _mu[0]; }
    std::vector< %(float_prec)s > get_mu_list() { return _mu; }

    void set_sigma_list(std::vector< %(float_prec)s > buffer) { _sigma = buffer; sigma = _sigma[0]; }
    std::vector< %(float_prec)s > get_sigma_list() { return _sigma; }

    void set_period(int period) { _period = period; }
    int get_period() { return _period; }

""" % {'float_prec': Global.config['precision']}

        self._specific_template['init_additional'] = """
        // Initialize counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters of a HomogeneousCorrelatedSpikeTrains
        void set_schedule(vector[int])
        vector[int] get_schedule()

        void set_mu_list(vector[%(float_prec)s])
        vector[%(float_prec)s] get_mu_list()

        void set_sigma_list(vector[%(float_prec)s])
        vector[%(float_prec)s] get_sigma_list()

        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}

        self._specific_template['reset_additional'] ="""
        _t = 0;
        _block = 0;

        r.clear();
        r = std::vector<%(float_prec)s>(size, 0.0);
""" % {'float_prec': Global.config['precision']}

        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters of a HomogeneousCorrelatedSpikeTrains
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_mu_list( self, buffer ):
        pop%(id)s.set_mu_list( buffer )
    cpdef np.ndarray get_mu_list( self ):
        return np.array(pop%(id)s.get_mu_list( ))

    cpdef set_sigma_list( self, buffer ):
        pop%(id)s.set_sigma_list( buffer )
    cpdef np.ndarray get_sigma_list( self ):
        return np.array(pop%(id)s.get_sigma_list( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_period(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id }

        scheduling_block = """
        if(_active){
            // Check if it is time to set the input
            if(_t == _schedule[_block]){
                // Set the data
                mu = _mu[_block];
                sigma = _sigma[_block];
                // Move to the next block
                _block++;
                // If was the last block, go back to the first block
                if (_block == _schedule.size()){
                    _block = 0;
                }
            }

            // If the timedarray is periodic, check if we arrive at that point
            if(_period > -1 && (_t == _period-1)){
                // Reset the counters
                _block=0;
                _t = -1;
            }

            // Always increment the internal time
            _t++;
        }
        """

        update_block = """
        if( _active ) {
            spiked.clear();

            // x += dt*(mu - x)/tau + sqrt(dt/tau) * sigma * Normal(0., 1.)
            x += dt*(mu - x)/tau + rand_0*sigma*sqrt(dt/tau);

            %(float_prec)s _step = 1000.0/dt;

            #pragma omp simd
            for(int i = 0; i < size; i++){

                // p = Uniform(0.0, 1.0) * 1000.0 / dt
                p[i] = _step*rand_1[i];

            }
        } // active
""" % {'float_prec': Global.config['precision']}

        if self._has_schedule:
            self._specific_template['update_variables'] = scheduling_block + update_block
        else:
            self._specific_template['update_variables'] = update_block

        self._specific_template['size_in_bytes'] = """
        // schedule
        size_in_bytes += _schedule.capacity() * sizeof(int);
""" % {'float_prec': Global.config['precision']}

    def _generate_omp(self):
        """
        adjust code templates for the specific population for openMP.
        """
        self._specific_template['declare_additional'] = """
    // Custom local parameters of a HomogeneousCorrelatedSpikeTrains
    std::vector< int > _schedule; // List of times where new inputs should be set

    std::vector< %(float_prec)s > _mu; // buffer holding the data
    std::vector< %(float_prec)s > _sigma; // buffer holding the data

    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}

        self._specific_template['access_additional'] = """
    // Custom local parameters of a HomogeneousCorrelatedSpikeTrains
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }

    void set_mu_list(std::vector< %(float_prec)s > buffer) { _mu = buffer; mu = _mu[0]; }
    std::vector< %(float_prec)s > get_mu_list() { return _mu; }

    void set_sigma_list(std::vector< %(float_prec)s > buffer) { _sigma = buffer; sigma = _sigma[0]; }
    std::vector< %(float_prec)s > get_sigma_list() { return _sigma; }

    void set_period(int period) { _period = period; }
    int get_period() { return _period; }

""" % {'float_prec': Global.config['precision']}

        self._specific_template['init_additional'] = """
        // Initialize counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters of a HomogeneousCorrelatedSpikeTrains
        void set_schedule(vector[int])
        vector[int] get_schedule()

        void set_mu_list(vector[%(float_prec)s])
        vector[%(float_prec)s] get_mu_list()

        void set_sigma_list(vector[%(float_prec)s])
        vector[%(float_prec)s] get_sigma_list()

        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}

        self._specific_template['reset_additional'] ="""
        _t = 0;
        _block = 0;

        r.clear();
        r = std::vector<%(float_prec)s>(size, 0.0);
""" % {'float_prec': Global.config['precision']}

        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters of a HomogeneousCorrelatedSpikeTrains
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_mu_list( self, buffer ):
        pop%(id)s.set_mu_list( buffer )
    cpdef np.ndarray get_mu_list( self ):
        return np.array(pop%(id)s.get_mu_list( ))

    cpdef set_sigma_list( self, buffer ):
        pop%(id)s.set_sigma_list( buffer )
    cpdef np.ndarray get_sigma_list( self ):
        return np.array(pop%(id)s.get_sigma_list( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_period(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id }

        scheduling_block = """
        if(_active){
            // Check if it is time to set the input
            if(_t == _schedule[_block]){
                // Set the data
                mu = _mu[_block];
                sigma = _sigma[_block];
                // Move to the next block
                _block++;
                // If was the last block, go back to the first block
                if (_block == _schedule.size()){
                    _block = 0;
                }
            }

            // If the timedarray is periodic, check if we arrive at that point
            if(_period > -1 && (_t == _period-1)){
                // Reset the counters
                _block=0;
                _t = -1;
            }

            // Always increment the internal time
            _t++;
        }
        """

        update_block = """
        if( _active ) {
            #pragma omp single
            {
                spiked.clear();

                // x += dt*(mu - x)/tau + sqrt(dt/tau) * sigma * Normal(0., 1.)
                x += dt*(mu - x)/tau + rand_0*sigma*sqrt(dt/tau);

                %(float_prec)s _step = 1000.0/dt;

                #pragma omp simd
                for(int i = 0; i < size; i++){

                    // p = Uniform(0.0, 1.0) * 1000.0 / dt
                    p[i] = _step*rand_1[i];

                }
            }
        } // active
""" % {'float_prec': Global.config['precision']}

        if self._has_schedule:
            self._specific_template['update_variables'] = scheduling_block + update_block
        else:
            self._specific_template['update_variables'] = update_block

        self._specific_template['size_in_bytes'] = """
        // schedule
        size_in_bytes += _schedule.capacity() * sizeof(int);
""" % {'float_prec': Global.config['precision']}

    def _generate_cuda(self):
        """
        Code generation if the CUDA paradigm is set.
        """
        #
        # Code for handling the buffer and schedule parameters
        self._specific_template['declare_additional'] = """
    // Custom local parameter HomogeneousCorrelatedSpikeTrains
    std::vector< int > _schedule;

    std::vector<%(float_prec)s> mu_buffer;      // buffer
    std::vector<%(float_prec)s> sigma_buffer;   // buffer

    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}
        self._specific_template['access_additional'] = """
    // Custom local parameter HomogeneousCorrelatedSpikeTrains
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }

    void set_mu_list(std::vector< %(float_prec)s > buffer) { mu_buffer = buffer; }
    void set_sigma_list(std::vector< %(float_prec)s > buffer) { sigma_buffer = buffer; }
    std::vector< %(float_prec)s > get_mu_list() { return mu_buffer; }
    std::vector< %(float_prec)s > get_sigma_list() { return sigma_buffer; }

    void set_period(int period) { _period = period; }
    int get_period() { return _period; }
""" % {'float_prec': Global.config['precision'], 'id': self.id}
        self._specific_template['init_additional'] = """
        // counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['reset_additional'] = """
        // counters
        _t = 0;
        _block = 0;
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters timed array
        void set_schedule(vector[int])
        vector[int] get_schedule()
        void set_mu_list(vector[%(float_prec)s])
        vector[%(float_prec)s] get_mu_list()
        void set_sigma_list(vector[%(float_prec)s])
        vector[%(float_prec)s] get_sigma_list()
        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}
        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters timed array
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))
    cpdef set_mu_list( self, buffer ):
        pop%(id)s.set_mu_list( buffer )
    cpdef np.ndarray get_mu_list( self ):
        return np.array(pop%(id)s.get_mu_list( ))
    cpdef set_sigma_list( self, buffer ):
        pop%(id)s.set_sigma_list( buffer )
    cpdef np.ndarray get_sigma_list( self ):
        return np.array(pop%(id)s.get_sigma_list( ))
    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_periodic(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id, 'float_prec': Global.config['precision'] }

        if not self._has_schedule:
            # we can use the normal code generation for GPU kernels
            pass

        else:
            self._specific_template['update_variables'] = """
        if(_active) {
            // Check if it is time to set the input
            if(_t == _schedule[_block]){
                // Set the data
                mu = mu_buffer[_block];
                sigma = sigma_buffer[_block];
                // Move to the next block
                _block++;
                // If was the last block, go back to the first block
                if ( _block == _schedule.size() ) {
                    _block = 0;
                }
            }

            // If the timedarray is periodic, check if we arrive at that point
            if( (_period > -1) && (_t == _period-1) ) {
                // Reset the counters
                _block=0;
                _t = -1;
            }

            // Always increment the internal time
            _t++;
        }
"""

            self._specific_template['update_variable_body'] = """
// Updating global variables of population %(id)s
__global__ void cuPop%(id)s_global_step( const long int t, const double dt, const double tau, double mu, double* x, curandState* rand_0, double sigma )
{
    // x += dt*(mu - x)/tau + sqrt(dt/tau) * sigma * Normal(0., 1.)
    x[0] += dt*(mu - x[0])/tau + curand_normal_double( &rand_0[0] )*sigma*sqrt(dt/tau);
}

// Updating local variables of population %(id)s
__global__ void cuPop%(id)s_local_step( const long int t, const double dt, curandState* rand_1, double* x, unsigned int* num_events, int* spiked, long int* last_spike )
{
    int i = threadIdx.x + blockDim.x * blockIdx.x;

    %(float_prec)s step = 1000.0/dt;

    while ( i < %(size)s )
    {
        // p = Uniform(0.0, 1.0) * 1000.0 / dt
        %(float_prec)s p = curand_uniform_double( &rand_1[i] ) * step;

        if (p < x[0]) {
            int pos = atomicAdd ( num_events, 1);
            spiked[pos] = i;
            last_spike[i] = t;
        }

        i += blockDim.x;
    }

    __syncthreads();
}
""" % {
    'id': self.id,
    'size': self.size,
    'float_prec': Global.config['precision']
}

            self._specific_template['update_variable_header'] = """__global__ void cuPop%(id)s_global_step( const long int t, const double dt, const double tau, double mu, double* x, curandState* rand_0, double sigma );
__global__ void cuPop%(id)s_local_step( const long int t, const double dt, curandState* rand_1, double* x, unsigned int* num_events, int* spiked, long int* last_spike );
""" % {'id': self.id}

            # Please notice, that the GPU kernels can be launched only with one block. Otherwise, the
            # atomicAdd which is called inside the kernel is not working correct (HD: April 1st, 2021)
            self._specific_template['update_variable_call'] = """
    if (pop%(id)s._active) {
        // Update the scheduling
        pop%(id)s.update();

        // Reset old events
        clear_num_events<<< 1, 1, 0, pop%(id)s.stream >>>(pop%(id)s.gpu_spike_count);
    #ifdef _DEBUG
        cudaError_t err_clear_num_events_%(id)s = cudaGetLastError();
        if (err_clear_num_events_%(id)s != cudaSuccess)
            std::cout << "pop%(id)s_spike_gather: " << cudaGetErrorString(err_clear_num_events_%(id)s) << std::endl;
    #endif

        // compute the value of x based on mu/sigma
        cuPop%(id)s_global_step<<< 1, 1, 0, pop%(id)s.stream >>>(
            t, dt,
            pop%(id)s.tau,
            pop%(id)s.mu,
            pop%(id)s.gpu_x,
            pop%(id)s.gpu_rand_0,
            pop%(id)s.sigma 
        );
        #ifdef _DEBUG
            cudaError_t err_pop%(id)s_global_step = cudaGetLastError();
            if( err_pop%(id)s_global_step != cudaSuccess) {
                std::cout << "pop%(id)s_step: " << cudaGetErrorString(err_pop%(id)s_global_step) << std::endl;
                exit(0);
            }
        #endif

        // Generate new spike events
        cuPop%(id)s_local_step<<< 1, pop%(id)s._threads_per_block, 0, pop%(id)s.stream >>>(
            t, dt,
            pop%(id)s.gpu_rand_1,
            pop%(id)s.gpu_x,
            pop%(id)s.gpu_spike_count,
            pop%(id)s.gpu_spiked,
            pop%(id)s.gpu_last_spike
        );
    #ifdef _DEBUG
        cudaError_t err_pop_spike_gather_%(id)s = cudaGetLastError();
        if(err_pop_spike_gather_%(id)s != cudaSuccess) {
            std::cout << "pop%(id)s_spike_gather: " << cudaGetErrorString(err_pop_spike_gather_%(id)s) << std::endl;
            exit(0);
        }
    #endif

        // transfer back the spike counter (needed by record)
        cudaMemcpy( &pop%(id)s.spike_count, pop%(id)s.gpu_spike_count, sizeof(unsigned int), cudaMemcpyDeviceToHost);
    #ifdef _DEBUG
        cudaError_t err_pop%(id)s_async_copy = cudaGetLastError();
        if ( err_pop%(id)s_async_copy != cudaSuccess ) {
            std::cout << "record_spike_count: " << cudaGetErrorString(err_pop%(id)s_async_copy) << std::endl;
            exit(0);
        }
    #endif

        // transfer back the spiked array (needed by record)
        if (pop%(id)s.spike_count > 0) {
            cudaMemcpy( pop%(id)s.spiked.data(), pop%(id)s.gpu_spiked, pop%(id)s.spike_count*sizeof(int), cudaMemcpyDeviceToHost);
        #ifdef _DEBUG
            cudaError_t err_pop%(id)s_async_copy2 = cudaGetLastError();
            if ( err_pop%(id)s_async_copy2 != cudaSuccess ) {
                std::cout << "record_spike: " << cudaGetErrorString(err_pop%(id)s_async_copy2) << std::endl;
                exit(0);
            }
        #endif
        }
    }
""" % {'id': self.id}

        self._specific_template['size_in_bytes'] = "//TODO: "

    def _instantiate(self, module):
        # Create the Cython instance
        self.cyInstance = getattr(module, self.class_name+'_wrapper')(self.size, self.max_delay)

    def __setattr__(self, name, value):

        if not hasattr(self, 'initialized'):
            Population.__setattr__(self, name, value)
        elif name == 'schedule':
            if self.initialized:
                self.cyInstance.set_schedule( np.array(value) / Global.config['dt'] )
            else:
                self.init['schedule'] = value
        elif name == 'mu':
            if self.initialized:
                if self._has_schedule:
                    self.cyInstance.set_mu_list( value )
                else:
                    self.cyInstance.set_global_attribute( "mu", value, Global.config["precision"] )
            else:
                self.init['mu'] = value
        elif name == 'sigma':
            if self.initialized:
                if self._has_schedule:
                    self.cyInstance.set_sigma_list( value )
                else:
                    self.cyInstance.set_global_attribute( "sigma", value, Global.config["precision"] )
            else:
                self.init['sigma'] = value
        elif name == "period":
            if self.initialized:
                self.cyInstance.set_period(int(value /Global.config['dt']))
            else:
                self.init['period'] = value
        elif name == 'rates': 
            if self._has_schedule:
                value = np.array(value)
                if not value.size == self.schedule.size:
                    Global._error("HomogeneousCorrelatedSpikeTrains: rates must have the same length as schedule.")
            else:
                value = np.array([float(value)])
            if self.initialized:
                Population.__setattr__(self, name, value)
                # Correction of mu and sigma everytime r, c or tau is changed
                try:
                    mu, sigma = self._correction(self.rates, self.corr, self.tau)
                    if self._has_schedule:
                        self.mu = mu
                        self.sigma = sigma
                    else:
                        self.mu = mu[0]
                        self.sigma = sigma[0]
                except Exception as e:
                    print(e)
            else:
                self.init[name] = value
                Population.__setattr__(self, name, value)
        elif name == 'corr': 
            if self._has_schedule:
                if not isinstance(value, (list, np.ndarray)):
                    value = np.full((self.schedule.size, ), value)
                else:
                    value = np.array(value)
                    if not value.size == self.schedule.size:
                        Global._error("HomogeneousCorrelatedSpikeTrains: corr must have the same length as schedule.")
            else:
                value = np.array([float(value)])
            if self.initialized:
                Population.__setattr__(self, name, value)
                try:
                    # Correction of mu and sigma everytime r, c or tau is changed
                    mu, sigma = self._correction(self.rates, self.corr, self.tau)
                    if self._has_schedule:
                        self.mu = mu
                        self.sigma = sigma
                    else:
                        self.mu = mu[0]
                        self.sigma = sigma[0]
                except Exception as e:
                    print(e)
            else:
                self.init[name] = value
                Population.__setattr__(self, name, value)
        elif name == 'tau': 
            if self.initialized:
                Population.__setattr__(self, name, value)
                # Correction of mu and sigma everytime r, c or tau is changed
                mu, sigma = self._correction(self.rates, self.corr, self.tau)
                if self._has_schedule:
                    self.mu = mu
                    self.sigma = sigma
                else:
                    self.mu = mu[0]
                    self.sigma = sigma[0]
            else:
                self.init[name] = value
                Population.__setattr__(self, name, value)
        else:
            Population.__setattr__(self, name, value)

    def __getattr__(self, name):
        if name == 'schedule':
            if self.initialized:
                if self._has_schedule:
                    return Global.config['dt'] * self.cyInstance.get_schedule()
                else:
                    return np.array([0.0])
            else:
                return self.init['schedule']
        elif name == 'mu':
            if self.initialized:
                if self._has_schedule:
                    return self.cyInstance.get_mu_list()
                else:
                    return self.cyInstance.get_global_attribute( "mu", Global.config["precision"] )
            else:
                return self.init['mu']
        elif name == 'sigma':
            if self.initialized:
                if self._has_schedule:
                    return self.cyInstance.get_sigma_list()
                else:
                    return self.cyInstance.get_global_attribute( "sigma", Global.config["precision"] )
            else:
                return self.init['sigma']
        elif name == 'tau':
            if self.initialized:
                return self.cyInstance.get_global_attribute( "tau", Global.config["precision"] )
            else:
                return self.init['tau']
        elif name == 'period':
            if self.initialized:
                return self.cyInstance.get_period() * Global.config['dt']
            else:
                return self.init['period']
        else:
            return Population.__getattribute__(self, name)

__init__(geometry, rates, corr, tau, schedule=None, period=-1.0, name=None, refractory=None, copied=False) #

Parameters:

  • geometry

    population geometry as tuple.

  • rates

    rate in Hz of the population (must be a positive float or a list)

  • corr

    total correlation strength (float in [0, 1], or a list)

  • tau

    correlation time constant in ms.

  • schedule

    list of times where new values of ratesand corrwill be used to computre mu and sigma.

  • period

    time when the array will be reset and start again, allowing cycling over the schedule. Default: no cycling (-1.)

  • name

    unique name of the population (optional).

  • refractory

    refractory period in ms (careful: may break the correlation)

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
def __init__(self, 
    geometry, 
    rates, 
    corr, 
    tau, 
    schedule=None, 
    period=-1., 
    name=None, 
    refractory=None, 
    copied=False):
    """    
    :param geometry: population geometry as tuple.
    :param rates: rate in Hz of the population (must be a positive float or a list)
    :param corr: total correlation strength (float in [0, 1], or a list)
    :param tau: correlation time constant in ms.
    :param schedule: list of times where new values of ``rates``and ``corr``will be used to computre mu and sigma.
    :param period: time when the array will be reset and start again, allowing cycling over the schedule. Default: no cycling (-1.)
    :param name: unique name of the population (optional).
    :param refractory: refractory period in ms (careful: may break the correlation)
    """
    if schedule is not None:
        self._has_schedule = True
        # Rates
        if not isinstance(rates, (list, np.ndarray)):
            Global._error("TimedHomogeneousCorrelatedSpikeTrains: the rates argument must be a list or a numpy array.")
        rates = np.array(rates)

        # Schedule
        schedule = np.array(schedule)

        nb_schedules = rates.shape[0]
        if nb_schedules != schedule.size:
            Global._error("TimedHomogeneousCorrelatedSpikeTrains: the length of rates must be the same length as for schedule.")

        # corr
        corr = np.array(corr)
        if corr.size == 1:
            corr = np.full(nb_schedules, corr)
    else:
        self._has_schedule = False
        rates = np.array([float(rates)])
        schedule = np.array([0.0])
        corr = np.array([corr])


    # Store refractory
    self.refractory_init = refractory

    # Correction of mu and sigma
    mu_list, sigma_list = self._correction(rates, corr, tau)

    self.rates = rates
    self.corr = corr
    self.tau = tau

    # Create the neuron
    corr_neuron = Neuron(
        parameters = """
            tau = %(tau)s : population
            mu = %(mu)s : population
            sigma = %(sigma)s : population
        """ % {'tau': tau, 'mu': mu_list[0], 'sigma': sigma_list[0]},
        equations = """
            x += dt*(mu - x)/tau + sqrt(dt/tau) * sigma * Normal(0., 1.) : population, init=%(mu)s
            p = Uniform(0.0, 1.0) * 1000.0 / dt
        """ % {'mu': mu_list[0]},
        spike = "p < x",
        refractory=refractory,
        name="HomogeneousCorrelated",
        description="Homogeneous correlated spike trains."
    )

    SpecificPopulation.__init__(self, geometry=geometry, neuron=corr_neuron, name=name, copied=copied)

    # Initial values
    self.init['schedule'] = schedule
    self.init['rates'] = rates
    self.init['corr'] = corr
    self.init['tau'] = tau
    self.init['period'] = period


    if self._has_schedule:
        self.init['mu'] = mu_list
        self.init['sigma'] = sigma_list
    else:
        self.init['mu'] = mu_list[0]
        self.init['sigma'] = sigma_list[0]

ANNarchy.core.SpecificPopulation.TimedPoissonPopulation #

Bases: SpecificPopulation

Poisson population whose rate vary with the provided schedule.

Example:

inp = TimedPoissonPopulation(
    geometry = 100,
    rates = [10., 20., 100., 20., 5.],
    schedule = [0., 100., 200., 500., 600.],
)

This creates a population of 100 Poisson neurons whose rate will be:

  • 10 Hz during the first 100 ms.
  • 20 HZ during the next 100 ms.
  • 100 Hz during the next 300 ms.
  • 20 Hz during the next 100 ms.
  • 5 Hz until the end of the simulation.

If you want the TimedPoissonPopulation to "loop" over the schedule, you can specify a period:

inp = TimedPoissonPopulation(
    geometry = 100,
    rates = [10., 20., 100., 20., 5.],
    schedule = [0., 100., 200., 500., 600.],
    period = 1000.,
)

Here the rate will become 10Hz again every 1 second of simulation. If the period is smaller than the schedule, the remaining rates will not be set.

Note that you can use the reset() method to manually reinitialize the schedule, times becoming relative to that call:

simulate(1200.) # Should switch to 100 Hz due to the period of 1000.
inp.reset()
simulate(1000.) # Starts at 10 Hz again.

The rates were here global to the population. If you want each neuron to have a different rate, rates must have additional dimensions corresponding to the geometry of the population.

inp = TimedPoissonPopulation(
    geometry = 100,
    rates = [ 
        [10. + 0.05*i for i in range(100)], 
        [20. + 0.05*i for i in range(100)],
    ],
    schedule = [0., 100.],
    period = 1000.,
)
Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
class TimedPoissonPopulation(SpecificPopulation):
    """
    Poisson population whose rate vary with the provided schedule.

    Example:

    ```python
    inp = TimedPoissonPopulation(
        geometry = 100,
        rates = [10., 20., 100., 20., 5.],
        schedule = [0., 100., 200., 500., 600.],
    )
    ```


    This creates a population of 100 Poisson neurons whose rate will be:

    * 10 Hz during the first 100 ms.
    * 20 HZ during the next 100 ms.
    * 100 Hz during the next 300 ms.
    * 20 Hz during the next 100 ms.
    * 5 Hz until the end of the simulation.


    If you want the TimedPoissonPopulation to "loop" over the schedule, you can specify a period:

    ```python
    inp = TimedPoissonPopulation(
        geometry = 100,
        rates = [10., 20., 100., 20., 5.],
        schedule = [0., 100., 200., 500., 600.],
        period = 1000.,
    )
    ```

    Here the rate will become 10Hz again every 1 second of simulation. If the period is smaller than the schedule, the remaining rates will not be set.

    Note that you can use the ``reset()`` method to manually reinitialize the schedule, times becoming relative to that call:

    ```python
    simulate(1200.) # Should switch to 100 Hz due to the period of 1000.
    inp.reset()
    simulate(1000.) # Starts at 10 Hz again.
    ```

    The rates were here global to the population. If you want each neuron to have a different rate, ``rates`` must have additional dimensions corresponding to the geometry of the population.

    ```python
    inp = TimedPoissonPopulation(
        geometry = 100,
        rates = [ 
            [10. + 0.05*i for i in range(100)], 
            [20. + 0.05*i for i in range(100)],
        ],
        schedule = [0., 100.],
        period = 1000.,
    )
    ```

    """
    def __init__(self, geometry, rates, schedule, period= -1., name=None, copied=False):
        """    
        :param rates: array of firing rates. The first axis corresponds to the times where the firing rate should change. If a different rate should be used by the different neurons, the other dimensions must match the geometry of the population.
        :param schedule: list of times (in ms) where the firing rate should change.
        :param period: time when the timed array will be reset and start again, allowing cycling over the schedule. Default: no cycling (-1.).
        """

        neuron = Neuron(
            parameters = """
            proba = 1.0
            """,
            equations = """
            p = Uniform(0.0, 1.0) * 1000.0 / dt
            """,
            spike = """
            p < proba
            """,
            name="TimedPoisson",
            description="Spiking neuron following a Poisson distribution."
        )

        SpecificPopulation.__init__(self, geometry=geometry, neuron=neuron, name=name, copied=copied)

        # Check arguments
        try:
            rates = np.array(rates)
        except:
            Global._error("TimedPoissonPopulation: the rates argument must be a numpy array.")

        schedule = np.array(schedule)

        nb_schedules = rates.shape[0]
        if nb_schedules != schedule.size:
            Global._error("TimedPoissonPopulation: the first axis of the rates argument must be the same length as schedule.")


        if rates.ndim == 1 : # One rate for the whole population
            rates = np.array([np.full(self.size, rates[i]) for i in range(nb_schedules)]) 

        # Initial values
        self.init['schedule'] = schedule
        self.init['rates'] = rates
        self.init['period'] = period

    def _copy(self):
        "Returns a copy of the population when creating networks."
        return TimedPoissonPopulation(self.geometry, self.init['rates'] , self.init['schedule'], self.init['period'], self.name, copied=True)

    def _generate_st(self):
        """
        adjust code templates for the specific population for single thread.
        """
        self._specific_template['declare_additional'] = """
    // Custom local parameters of a TimedPoissonPopulation
    std::vector< int > _schedule; // List of times where new inputs should be set
    std::vector< std::vector< %(float_prec)s > > _buffer; // buffer holding the data
    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}
        self._specific_template['access_additional'] = """
    // Custom local parameters of a TimedPoissonPopulation
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }
    void set_buffer(std::vector< std::vector< %(float_prec)s > > buffer) { _buffer = buffer; r = _buffer[0]; }
    std::vector< std::vector< %(float_prec)s > > get_buffer() { return _buffer; }
    void set_period(int period) { _period = period; }
    int get_period() { return _period; }
""" % {'float_prec': Global.config['precision']}
        self._specific_template['init_additional'] = """
        // Initialize counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters of a TimedPoissonPopulation
        void set_schedule(vector[int])
        vector[int] get_schedule()
        void set_buffer(vector[vector[%(float_prec)s]])
        vector[vector[%(float_prec)s]] get_buffer()
        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}

        self._specific_template['reset_additional'] ="""
        _t = 0;
        _block = 0;

        r.clear();
        r = std::vector<%(float_prec)s>(size, 0.0);
""" % {'float_prec': Global.config['precision']}

        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters of a TimedArray
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_rates( self, buffer ):
        pop%(id)s.set_buffer( buffer )
    cpdef np.ndarray get_rates( self ):
        return np.array(pop%(id)s.get_buffer( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_period(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id }

        self._specific_template['update_variables'] = """
        if(_active){
            //std::cout << _t << " " << _block<< " " << _schedule[_block] << std::endl;

            // Check if it is time to set the input
            if(_t == _schedule[_block]){
                // Set the data
                proba = _buffer[_block];
                // Move to the next block
                _block++;
                // If was the last block, go back to the first block
                if (_block == _schedule.size()){
                    _block = 0;
                }
            }

            // If the timedarray is periodic, check if we arrive at that point
            if(_period > -1 && (_t == _period-1)){
                // Reset the counters
                _block=0;
                _t = -1;
            }

            // Always increment the internal time
            _t++;
        }

        if( _active ) {
            spiked.clear();

            // Updating local variables
            %(float_prec)s step = 1000.0/dt;

            #pragma omp simd
            for(int i = 0; i < size; i++){

                // p = Uniform(0.0, 1.0) * 1000.0 / dt
                p[i] = step*rand_0[i];


            }
        } // active
""" % {'float_prec': Global.config['precision']}

        self._specific_template['size_in_bytes'] = """
        // schedule
        size_in_bytes += _schedule.capacity() * sizeof(int);

        // buffer
        size_in_bytes += _buffer.capacity() * sizeof(std::vector<%(float_prec)s>);
        for( auto it = _buffer.begin(); it != _buffer.end(); it++ )
            size_in_bytes += it->capacity() * sizeof(%(float_prec)s);
""" % {'float_prec': Global.config['precision']}

    def _generate_omp(self):
        """
        adjust code templates for the specific population for openMP.
        """
        self._specific_template['declare_additional'] = """
    // Custom local parameters of a TimedPoissonPopulation
    std::vector< int > _schedule; // List of times where new inputs should be set
    std::vector< std::vector< %(float_prec)s > > _buffer; // buffer holding the data
    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}
        self._specific_template['access_additional'] = """
    // Custom local parameters of a TimedPoissonPopulation
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }
    void set_buffer(std::vector< std::vector< %(float_prec)s > > buffer) { _buffer = buffer; r = _buffer[0]; }
    std::vector< std::vector< %(float_prec)s > > get_buffer() { return _buffer; }
    void set_period(int period) { _period = period; }
    int get_period() { return _period; }
""" % {'float_prec': Global.config['precision']}
        self._specific_template['init_additional'] = """
        // Initialize counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters of a TimedPoissonPopulation
        void set_schedule(vector[int])
        vector[int] get_schedule()
        void set_buffer(vector[vector[%(float_prec)s]])
        vector[vector[%(float_prec)s]] get_buffer()
        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}

        self._specific_template['reset_additional'] ="""
        _t = 0;
        _block = 0;

        r.clear();
        r = std::vector<%(float_prec)s>(size, 0.0);
""" % {'float_prec': Global.config['precision']}

        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters of a TimedArray
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_rates( self, buffer ):
        pop%(id)s.set_buffer( buffer )
    cpdef np.ndarray get_rates( self ):
        return np.array(pop%(id)s.get_buffer( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_period(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id }

        self._specific_template['update_variables'] = """
        if(_active){
            #pragma omp single
            {
                //std::cout << _t << " " << _block<< " " << _schedule[_block] << std::endl;

                // Check if it is time to set the input
                if(_t == _schedule[_block]){
                    // Set the data
                    proba = _buffer[_block];
                    // Move to the next block
                    _block++;
                    // If was the last block, go back to the first block
                    if (_block == _schedule.size()){
                        _block = 0;
                    }
                }

                // If the timedarray is periodic, check if we arrive at that point
                if(_period > -1 && (_t == _period-1)){
                    // Reset the counters
                    _block=0;
                    _t = -1;
                }

                // Always increment the internal time
                _t++;
            }
        }

        if( _active ) {
            spiked.clear();

            // Updating local variables
            %(float_prec)s step = 1000.0/dt;

            #pragma omp for simd
            for(int i = 0; i < size; i++){

                // p = Uniform(0.0, 1.0) * 1000.0 / dt
                p[i] = step*rand_0[i];


            }
        } // active
""" % {'float_prec': Global.config['precision']}

        self._specific_template['size_in_bytes'] = """
        // schedule
        size_in_bytes += _schedule.capacity() * sizeof(int);

        // buffer
        size_in_bytes += _buffer.capacity() * sizeof(std::vector<%(float_prec)s>);
        for( auto it = _buffer.begin(); it != _buffer.end(); it++ )
            size_in_bytes += it->capacity() * sizeof(%(float_prec)s);
""" % {'float_prec': Global.config['precision']}

    def _generate_cuda(self):
        """
        Code generation if the CUDA paradigm is set.
        """
        # I suppress the code generation for allocating the variable r on gpu, as
        # well as memory transfer codes. This is only possible as no other variables
        # allowed in TimedArray.
        self._specific_template['init_parameters_variables'] = """
        // Random numbers
        cudaMalloc((void**)&gpu_rand_0, size * sizeof(curandState));
        init_curand_states( size, gpu_rand_0, global_seed );
"""
        self._specific_template['host_device_transfer'] = ""
        self._specific_template['device_host_transfer'] = ""

        #
        # Code for handling the buffer and schedule parameters
        self._specific_template['declare_additional'] = """
    // Custom local parameter timed array
    std::vector< int > _schedule;
    std::vector< %(float_prec)s* > gpu_buffer;
    int _period; // Period of cycling
    long int _t; // Internal time
    int _block; // Internal block when inputs are set not at each step
""" % {'float_prec': Global.config['precision']}
        self._specific_template['access_additional'] = """
    // Custom local parameter timed array
    void set_schedule(std::vector<int> schedule) { _schedule = schedule; }
    std::vector<int> get_schedule() { return _schedule; }
    void set_buffer(std::vector< std::vector< %(float_prec)s > > buffer) {
        if ( gpu_buffer.empty() ) {
            gpu_buffer = std::vector< %(float_prec)s* >(buffer.size(), nullptr);
            // allocate gpu arrays
            for(int i = 0; i < buffer.size(); i++) {
                cudaMalloc((void**)&gpu_buffer[i], buffer[i].size()*sizeof(%(float_prec)s));
            }
        }

        auto host_it = buffer.begin();
        auto dev_it = gpu_buffer.begin();
        for( ; host_it < buffer.end(); host_it++, dev_it++ ) {
            cudaMemcpy( *dev_it, host_it->data(), host_it->size()*sizeof(%(float_prec)s), cudaMemcpyHostToDevice);
        }

        gpu_proba = gpu_buffer[0];
    }
    std::vector< std::vector< %(float_prec)s > > get_buffer() {
        std::vector< std::vector< %(float_prec)s > > buffer = std::vector< std::vector< %(float_prec)s > >( gpu_buffer.size(), std::vector<%(float_prec)s>(size,0.0) );

        auto host_it = buffer.begin();
        auto dev_it = gpu_buffer.begin();
        for( ; host_it < buffer.end(); host_it++, dev_it++ ) {
            cudaMemcpy( host_it->data(), *dev_it, size*sizeof(%(float_prec)s), cudaMemcpyDeviceToHost );
        }

        return buffer;
    }
    void set_period(int period) { _period = period; }
    int get_period() { return _period; }
""" % {'float_prec': Global.config['precision']}
        self._specific_template['init_additional'] = """
        // counters
        _t = 0;
        _block = 0;
        _period = -1;
"""
        self._specific_template['reset_additional'] = """
        // counters
        _t = 0;
        _block = 0;
        gpu_proba = gpu_buffer[0];
"""
        self._specific_template['export_additional'] = """
        # Custom local parameters timed array
        void set_schedule(vector[int])
        vector[int] get_schedule()
        void set_buffer(vector[vector[%(float_prec)s]])
        vector[vector[%(float_prec)s]] get_buffer()
        void set_period(int)
        int get_period()
""" % {'float_prec': Global.config['precision']}
        self._specific_template['wrapper_access_additional'] = """
    # Custom local parameters timed array
    cpdef set_schedule( self, schedule ):
        pop%(id)s.set_schedule( schedule )
    cpdef np.ndarray get_schedule( self ):
        return np.array(pop%(id)s.get_schedule( ))

    cpdef set_rates( self, buffer ):
        pop%(id)s.set_buffer( buffer )
    cpdef np.ndarray get_rates( self ):
        return np.array(pop%(id)s.get_buffer( ))

    cpdef set_period( self, period ):
        pop%(id)s.set_period(period)
    cpdef int get_periodic(self):
        return pop%(id)s.get_period()
""" % { 'id': self.id, 'float_prec': Global.config['precision'] }

        self._specific_template['update_variables'] = """
        if(_active) {
            // std::cout << _t << " " << _block<< " " << _schedule[_block] << std::endl;
            // Check if it is time to set the input
            if(_t == _schedule[_block]){
                // Set the data
                gpu_proba = gpu_buffer[_block];
                // Move to the next block
                _block++;
                // If was the last block, go back to the first block
                if ( _block == _schedule.size() ) {
                    _block = 0;
                }
            }

            // If the timedarray is periodic, check if we arrive at that point
            if( (_period > -1) && (_t == _period-1) ) {
                // Reset the counters
                _block=0;
                _t = -1;
            }

            // Always increment the internal time
            _t++;
        }
"""

        self._specific_template['update_variable_body'] = """
__global__ void cuPop%(id)s_local_step( const long int t, const double dt, curandState* rand_0, double* proba, unsigned int* num_events, int* spiked, long int* last_spike )
{
    int i = threadIdx.x + blockDim.x * blockIdx.x;
    %(float_prec)s step = 1000.0/dt;

    while ( i < %(size)s )
    {
        // p = Uniform(0.0, 1.0) * 1000.0 / dt
        %(float_prec)s p = curand_uniform_double( &rand_0[i] ) * step;

        if (p < proba[i]) {
            int pos = atomicAdd ( num_events, 1);
            spiked[pos] = i;
            last_spike[i] = t;
        }

        i += blockDim.x;
    }

    __syncthreads();
}
""" % {
    'id': self.id,
    'size': self.size,
    'float_prec': Global.config['precision']
}

        self._specific_template['update_variable_header'] = "__global__ void cuPop%(id)s_local_step( const long int t, const double dt, curandState* rand_0, double* proba, unsigned int* num_events, int* spiked, long int* last_spike );" % {'id': self.id}
        # Please notice, that the GPU kernels can be launched only with one block. Otherwise, the
        # atomicAdd which is called inside the kernel is not working correct (HD: April 1st, 2021)
        self._specific_template['update_variable_call'] = """
    // host side update of neurons
    pop%(id)s.update();

    // Reset old events
    clear_num_events<<< 1, 1, 0, pop%(id)s.stream >>>(pop%(id)s.gpu_spike_count);
#ifdef _DEBUG
    cudaError_t err_clear_num_events_%(id)s = cudaGetLastError();
    if(err_clear_num_events_%(id)s != cudaSuccess)
        std::cout << "pop%(id)s_spike_gather: " << cudaGetErrorString(err_clear_num_events_%(id)s) << std::endl;
#endif

    // Compute current events
    cuPop%(id)s_local_step<<< 1, pop%(id)s._threads_per_block, 0, pop%(id)s.stream >>>(
        t, dt,
        pop%(id)s.gpu_rand_0,
        pop%(id)s.gpu_proba,
        pop%(id)s.gpu_spike_count,
        pop%(id)s.gpu_spiked,
        pop%(id)s.gpu_last_spike
    );
#ifdef _DEBUG
    cudaError_t err_pop_spike_gather_%(id)s = cudaGetLastError();
    if(err_pop_spike_gather_%(id)s != cudaSuccess)
        std::cout << "pop%(id)s_spike_gather: " << cudaGetErrorString(err_pop_spike_gather_%(id)s) << std::endl;
#endif

    // transfer back the spike counter (needed by record)
    cudaMemcpyAsync( &pop%(id)s.spike_count, pop%(id)s.gpu_spike_count, sizeof(unsigned int), cudaMemcpyDeviceToHost, pop%(id)s.stream );
#ifdef _DEBUG
    cudaError_t err = cudaGetLastError();
    if ( err != cudaSuccess )
        std::cout << "record_spike_count: " << cudaGetErrorString(err) << std::endl;
#endif

    // transfer back the spiked array (needed by record)
    cudaMemcpyAsync( pop%(id)s.spiked.data(), pop%(id)s.gpu_spiked, pop%(id)s.spike_count*sizeof(int), cudaMemcpyDeviceToHost, pop%(id)s.stream );
#ifdef _DEBUG
    err = cudaGetLastError();
    if ( err != cudaSuccess )
        std::cout << "record_spike: " << cudaGetErrorString(err) << std::endl;
#endif

""" % {'id': self.id}

        self._specific_template['size_in_bytes'] = "//TODO: "

    def _instantiate(self, module):
        # Create the Cython instance
        self.cyInstance = getattr(module, self.class_name+'_wrapper')(self.size, self.max_delay)

    def __setattr__(self, name, value):
        if name == 'schedule':
            if self.initialized:
                self.cyInstance.set_schedule( np.array(value) / Global.config['dt'] )
            else:
                self.init['schedule'] = value
        elif name == 'rates':
            if self.initialized:
                value = np.array(value)
                if value.shape[0] != self.schedule.shape[0]:
                    Global._error("TimedPoissonPopulation: the first dimension of rates must match the schedule.")
                if value.ndim > 2:
                    # we need to flatten the provided data
                    values = value.reshape( (value.shape[0], self.size) )
                    self.cyInstance.set_rates(values)
                elif value.ndim == 2:
                    if value.shape[1] != self.size:
                        if value.shape[1] == 1:
                            value = np.array([np.full(self.size, value[i]) for i in range(value.shape[0])])
                        else:
                            Global._error("TimedPoissonPopulation: the second dimension of rates must match the number of neurons.")
                    self.cyInstance.set_rates(value)
                elif value.ndim == 1:
                    value = np.array([np.full(self.size, value[i]) for i in range(value.shape[0])]) 
                    self.cyInstance.set_rates(value)

            else:
                self.init['rates'] = value
        elif name == "period":
            if self.initialized:
                self.cyInstance.set_period(int(value /Global.config['dt']))
            else:
                self.init['period'] = value
        else:
            Population.__setattr__(self, name, value)

    def __getattr__(self, name):
        if name == 'schedule':
            if self.initialized:
                return Global.config['dt'] * self.cyInstance.get_schedule()
            else:
                return self.init['schedule']
        elif name == 'rates':
            if self.initialized:
                if len(self.geometry) > 1:
                    # unflatten the data
                    flat_values = self.cyInstance.get_rates()
                    values = np.zeros( tuple( [len(self.schedule)] + list(self.geometry) ) )
                    for x in range(len(self.schedule)):
                        values[x] = np.reshape( flat_values[x], self.geometry)
                    return values
                else:
                    return self.cyInstance.get_rates()
            else:
                return self.init['rates']
        elif name == 'period':
            if self.initialized:
                return self.cyInstance.get_period() * Global.config['dt']
            else:
                return self.init['period']
        else:
            return Population.__getattribute__(self, name)

__init__(geometry, rates, schedule, period=-1.0, name=None, copied=False) #

Parameters:

  • rates

    array of firing rates. The first axis corresponds to the times where the firing rate should change. If a different rate should be used by the different neurons, the other dimensions must match the geometry of the population.

  • schedule

    list of times (in ms) where the firing rate should change.

  • period

    time when the timed array will be reset and start again, allowing cycling over the schedule. Default: no cycling (-1.).

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/SpecificPopulation.py
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
def __init__(self, geometry, rates, schedule, period= -1., name=None, copied=False):
    """    
    :param rates: array of firing rates. The first axis corresponds to the times where the firing rate should change. If a different rate should be used by the different neurons, the other dimensions must match the geometry of the population.
    :param schedule: list of times (in ms) where the firing rate should change.
    :param period: time when the timed array will be reset and start again, allowing cycling over the schedule. Default: no cycling (-1.).
    """

    neuron = Neuron(
        parameters = """
        proba = 1.0
        """,
        equations = """
        p = Uniform(0.0, 1.0) * 1000.0 / dt
        """,
        spike = """
        p < proba
        """,
        name="TimedPoisson",
        description="Spiking neuron following a Poisson distribution."
    )

    SpecificPopulation.__init__(self, geometry=geometry, neuron=neuron, name=name, copied=copied)

    # Check arguments
    try:
        rates = np.array(rates)
    except:
        Global._error("TimedPoissonPopulation: the rates argument must be a numpy array.")

    schedule = np.array(schedule)

    nb_schedules = rates.shape[0]
    if nb_schedules != schedule.size:
        Global._error("TimedPoissonPopulation: the first axis of the rates argument must be the same length as schedule.")


    if rates.ndim == 1 : # One rate for the whole population
        rates = np.array([np.full(self.size, rates[i]) for i in range(nb_schedules)]) 

    # Initial values
    self.init['schedule'] = schedule
    self.init['rates'] = rates
    self.init['period'] = period

ANNarchy.extensions.image.ImagePopulation.ImagePopulation #

Bases: Population

Specific rate-coded Population allowing to represent images (png, jpg...) as the firing rate of a population (each neuron represents one pixel).

This extension requires the Python Image Library (pip install Pillow).

Usage:

from ANNarchy import *
from ANNarchy.extensions.image import ImagePopulation

pop = ImagePopulation(geometry=(480, 640))
pop.set_image('image.jpg')

About the geometry:

  • If the geometry is 2D, it corresponds to the (height, width) of the image. Only the luminance of the pixels will be represented (grayscale image).
  • If the geometry is 3D, the third dimension can be either 1 (grayscale) or 3 (color).

If the third dimension is 3, each will correspond to the RGB values of the pixels.

Warning: due to the indexing system of Numpy, a 640*480 image should be fed into a (480, 640) or (480, 640, 3) population.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class ImagePopulation(Population):
    """ 
    Specific rate-coded Population allowing to represent images (png, jpg...) as the firing rate of a population (each neuron represents one pixel).

    This extension requires the Python Image Library (pip install Pillow).

    Usage:

    ```python
    from ANNarchy import *
    from ANNarchy.extensions.image import ImagePopulation

    pop = ImagePopulation(geometry=(480, 640))
    pop.set_image('image.jpg')
    ```

    About the geometry:

    * If the geometry is 2D, it corresponds to the (height, width) of the image. Only the luminance of the pixels will be represented (grayscale image).
    * If the geometry is 3D, the third dimension can be either 1 (grayscale) or 3 (color).

    If the third dimension is 3, each will correspond to the RGB values of the pixels.

    **Warning:** due to the indexing system of Numpy, a 640*480 image should be fed into a (480, 640) or (480, 640, 3) population.
    """

    def __init__(self, geometry, name=None, copied=False):
        """            
        :param geometry: population geometry as tuple. It must correspond to the image size and be fixed through the whole simulation.
        :param name: unique name of the population (optional).     
        """   
        # Check geometry
        if isinstance(geometry, int) or len(geometry)==1:
            Global._error('The geometry of an ImagePopulation should be 2D (grayscale) or 3D (color).')

        if len(geometry)==3 and (geometry[2]!=3 and geometry[2]!=1):
            Global._error('The third dimension of an ImagePopulation should be either 1 (grayscale) or 3 (color).') 

        if len(geometry)==3 and geometry[2]==1:
            geometry = (int(geometry[0]), int(geometry[1]))

        # Create the population     
        Population.__init__(self, geometry = geometry, name=name, neuron = Neuron(parameters="r = 0.0"), copied=copied)

    def _copy(self):
        "Returns a copy of the population when creating networks. Internal use only."
        return ImagePopulation(geometry=self.geometry, name=self.name, copied=True)

    def set_image(self, image_name):
        """ 
        Sets an image (.png, .jpg or whatever is supported by PIL) into the firing rate of the population.

        If the image has a different size from the population, it will be resized.

        """
        try:
            im = Image.open(image_name)
        except : # image does not exist
            Global._error('The image ' + image_name + ' does not exist.')

        # Resize the image if needed
        (width, height) = (self.geometry[1], self.geometry[0])
        if im.size != (width, height):
            Global._warning('The image ' + image_name + ' does not have the same size '+str(im.size)+' as the population ' + str((width, height)) + '. It will be resized.')
            im = im.resize((width, height))

        # Check if only the luminance should be extracted
        if self.dimension == 2 or self.geometry[2] == 1:
            im=im.convert("L")

        # Set the rate of the population
        self.r = np.array(im).reshape(self.size)/255.

__init__(geometry, name=None, copied=False) #

Parameters:

  • geometry

    population geometry as tuple. It must correspond to the image size and be fixed through the whole simulation.

  • name

    unique name of the population (optional).

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def __init__(self, geometry, name=None, copied=False):
    """            
    :param geometry: population geometry as tuple. It must correspond to the image size and be fixed through the whole simulation.
    :param name: unique name of the population (optional).     
    """   
    # Check geometry
    if isinstance(geometry, int) or len(geometry)==1:
        Global._error('The geometry of an ImagePopulation should be 2D (grayscale) or 3D (color).')

    if len(geometry)==3 and (geometry[2]!=3 and geometry[2]!=1):
        Global._error('The third dimension of an ImagePopulation should be either 1 (grayscale) or 3 (color).') 

    if len(geometry)==3 and geometry[2]==1:
        geometry = (int(geometry[0]), int(geometry[1]))

    # Create the population     
    Population.__init__(self, geometry = geometry, name=name, neuron = Neuron(parameters="r = 0.0"), copied=copied)

set_image(image_name) #

Sets an image (.png, .jpg or whatever is supported by PIL) into the firing rate of the population.

If the image has a different size from the population, it will be resized.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def set_image(self, image_name):
    """ 
    Sets an image (.png, .jpg or whatever is supported by PIL) into the firing rate of the population.

    If the image has a different size from the population, it will be resized.

    """
    try:
        im = Image.open(image_name)
    except : # image does not exist
        Global._error('The image ' + image_name + ' does not exist.')

    # Resize the image if needed
    (width, height) = (self.geometry[1], self.geometry[0])
    if im.size != (width, height):
        Global._warning('The image ' + image_name + ' does not have the same size '+str(im.size)+' as the population ' + str((width, height)) + '. It will be resized.')
        im = im.resize((width, height))

    # Check if only the luminance should be extracted
    if self.dimension == 2 or self.geometry[2] == 1:
        im=im.convert("L")

    # Set the rate of the population
    self.r = np.array(im).reshape(self.size)/255.

ANNarchy.extensions.image.ImagePopulation.VideoPopulation #

Bases: ImagePopulation

Specific rate-coded Population allowing to feed a webcam input into the firing rate of a population (each neuron represents one pixel).

This extension requires the C++ library OpenCV >= 4.0 (apt-get/yum install opencv). pkg-config opencv4 --cflags --libs should not return an error. vtk might additionally have to be installed.

Usage:

from ANNarchy import *
from ANNarchy.extensions.image import VideoPopulation

pop = VideoPopulation(geometry=(480, 640))

compile()

pop.start_camera(0)

while(True):
    pop.grab_image()
    simulate(10.0)

About the geometry:

  • If the geometry is 2D, it corresponds to the (height, width) of the image. Only the luminance of the pixels will be represented (grayscale image).
  • If the geometry is 3D, the third dimension can be either 1 (grayscale) or 3 (color).

If the third dimension is 3, each will correspond to the RGB values of the pixels.

Warning: due to the indexing system of Numpy, a 640*480 image should be fed into a (480, 640) or (480, 640, 3) population.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class VideoPopulation(ImagePopulation):
    """ 
    Specific rate-coded Population allowing to feed a webcam input into the firing rate of a population (each neuron represents one pixel).

    This extension requires the C++ library OpenCV >= 4.0 (apt-get/yum install opencv). ``pkg-config opencv4 --cflags --libs`` should not return an error. `vtk` might additionally have to be installed.

    Usage:

    ```python
    from ANNarchy import *
    from ANNarchy.extensions.image import VideoPopulation

    pop = VideoPopulation(geometry=(480, 640))

    compile()

    pop.start_camera(0)

    while(True):
        pop.grab_image()
        simulate(10.0)
    ```

    About the geometry:

    * If the geometry is 2D, it corresponds to the (height, width) of the image. Only the luminance of the pixels will be represented (grayscale image).
    * If the geometry is 3D, the third dimension can be either 1 (grayscale) or 3 (color).

    If the third dimension is 3, each will correspond to the RGB values of the pixels.

    **Warning:** due to the indexing system of Numpy, a 640*480 image should be fed into a (480, 640) or (480, 640, 3) population.

    """

    def __init__(self, geometry, opencv_version="4", name=None, copied=False):
        """        
        :param geometry: population geometry as tuple. It must be fixed through the whole simulation. If the camera provides images of a different size, it will be resized.
        :param opencv_version: OpenCV version (default=4).
        :param name: unique name of the population (optional).       
        """         
        # Create the population     
        ImagePopulation.__init__(self, geometry = geometry, name=name, copied=copied)

        self.opencv_version = opencv_version

    def _copy(self):
        "Returns a copy of the population when creating networks. Internal use only."
        return VideoPopulation(geometry=self.geometry, name=self.name, copied=True)

    def _generate(self):
        "Code generation"      
        # Add corresponding libs to the Makefile
        extra_libs.append('`pkg-config opencv' + str(self.opencv_version) + ' --cflags --libs`')

        # Include opencv
        self._specific_template['include_additional'] = """#include <opencv2/opencv.hpp>
using namespace cv;
"""
        # Class for the camera device
        self._specific_template['struct_additional'] = """
// VideoPopulation
class CameraDeviceCPP : public cv::VideoCapture {
public:
    CameraDeviceCPP (int id, int width, int height, int depth) : cv::VideoCapture(id){
        width_ = width;
        height_ = height;
        depth_ = depth;      
        img_ = std::vector<%(float_prec)s>(width*height*depth, 0.0);
    }
    std::vector<%(float_prec)s> GrabImage(){
        if(isOpened()){
            // Read a new frame from the video
            Mat frame;
            read(frame); 
            // Resize the image
            Mat resized_frame;
            resize(frame, resized_frame, Size(width_, height_) );
            // If depth=1, only luminance
            if(depth_==1){
                // Convert to luminance
                cvtColor(resized_frame, resized_frame, COLOR_BGR2GRAY);
                for(int i = 0; i < resized_frame.rows; i++){
                    for(int j = 0; j < resized_frame.cols; j++){
                        this->img_[j+width_*i] = float(resized_frame.at<uchar>(i, j))/255.0;
                    }
                }
            }
            else{ //BGR
                for(int i = 0; i < resized_frame.rows; i++){
                    for(int j = 0; j < resized_frame.cols; j++){
                        Vec3b intensity = resized_frame.at<Vec3b>(i, j);
                        this->img_[(j+width_*i)*3 + 0] = %(float_prec)s(intensity.val[2])/255.0;
                        this->img_[(j+width_*i)*3 + 1] = %(float_prec)s(intensity.val[1])/255.0;
                        this->img_[(j+width_*i)*3 + 2] = %(float_prec)s(intensity.val[0])/255.0;
                    }
                }
            }            
        }
        return this->img_;
    };

protected:
    // Width and height of the image, depth_ is 1 (grayscale) or 3 (RGB)
    int width_, height_, depth_;
    // Vector of floats for the returned image
    std::vector<%(float_prec)s> img_;
};
""" % {'float_prec': Global.config['precision']}

        self._specific_template['declare_additional'] = """
    // Camera
    CameraDeviceCPP* camera_;
    void StartCamera(int id, int width, int height, int depth){
        camera_ = new CameraDeviceCPP(id, width, height, depth);
        if(!camera_->isOpened()){
            std::cout << "Error: could not open the camera." << std::endl;   
        }
    };
    void GrabImage(){
        if(camera_->isOpened()){
            r = camera_->GrabImage();   
        }
    };
    void ReleaseCamera(){
        camera_->release(); 
    };
"""

        self._specific_template['update_variables'] = ""

        self._specific_template['export_additional'] = """
        void StartCamera(int id, int width, int height, int depth)
        void GrabImage()
        void ReleaseCamera()
""" 

        self._specific_template['wrapper_access_additional'] = """
    # CameraDevice
    def start_camera(self, int id, int width, int height, int depth):
        pop%(id)s.StartCamera(id, width, height, depth)

    def grab_image(self):
        pop%(id)s.GrabImage()

    def release_camera(self):
        pop%(id)s.ReleaseCamera()
""" % {'id': self.id}



    def start_camera(self, camera_port=0):
        """
        Starts the webcam with the corresponding device (default = 0).

        On linux, the camera port corresponds to the number in /dev/video0, /dev/video1, etc.
        """

        self.cyInstance.start_camera(camera_port, self.geometry[1], self.geometry[0], 3 if self.dimension==3 else 1)

    def grab_image(self):
        """
        Grabs one image from the camera and feeds it into the population.

        The camera must be first started with:

            pop.start_camera(0)
        """
        self.cyInstance.grab_image()

    def release(self):
        """
        Releases the camera:

            pop.release()
        """
        self.cyInstance.release_camera()

__init__(geometry, opencv_version='4', name=None, copied=False) #

Parameters:

  • geometry

    population geometry as tuple. It must be fixed through the whole simulation. If the camera provides images of a different size, it will be resized.

  • opencv_version

    OpenCV version (default=4).

  • name

    unique name of the population (optional).

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
121
122
123
124
125
126
127
128
129
130
def __init__(self, geometry, opencv_version="4", name=None, copied=False):
    """        
    :param geometry: population geometry as tuple. It must be fixed through the whole simulation. If the camera provides images of a different size, it will be resized.
    :param opencv_version: OpenCV version (default=4).
    :param name: unique name of the population (optional).       
    """         
    # Create the population     
    ImagePopulation.__init__(self, geometry = geometry, name=name, copied=copied)

    self.opencv_version = opencv_version

grab_image() #

Grabs one image from the camera and feeds it into the population.

The camera must be first started with:

pop.start_camera(0)
Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
246
247
248
249
250
251
252
253
254
def grab_image(self):
    """
    Grabs one image from the camera and feeds it into the population.

    The camera must be first started with:

        pop.start_camera(0)
    """
    self.cyInstance.grab_image()

release() #

Releases the camera:

pop.release()
Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
256
257
258
259
260
261
262
def release(self):
    """
    Releases the camera:

        pop.release()
    """
    self.cyInstance.release_camera()

start_camera(camera_port=0) #

Starts the webcam with the corresponding device (default = 0).

On linux, the camera port corresponds to the number in /dev/video0, /dev/video1, etc.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/extensions/image/ImagePopulation.py
237
238
239
240
241
242
243
244
def start_camera(self, camera_port=0):
    """
    Starts the webcam with the corresponding device (default = 0).

    On linux, the camera port corresponds to the number in /dev/video0, /dev/video1, etc.
    """

    self.cyInstance.start_camera(camera_port, self.geometry[1], self.geometry[0], 3 if self.dimension==3 else 1)