Skip to content

Monitoring#

Recording of neural or synaptic variables during the simulation is possible through a Monitor object.

ANNarchy.Monitor #

Monitoring class allowing to record easily parameters or variables from Population, PopulationView, Dendrite or Projection objects.

Example:

m = Monitor(pop, ['g_exc', 'v', 'spike'], period=10.0)

It is also possible to record the sum of inputs to each neuron in a rate-coded population:

m = Monitor(pop, ['sum(exc)', 'r'])
Source code in ANNarchy/core/Monitor.py
 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
 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
271
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
class Monitor :
    """
    Monitoring class allowing to record easily parameters or variables from Population, PopulationView, Dendrite or Projection objects.

    Example:

    ```python
    m = Monitor(pop, ['g_exc', 'v', 'spike'], period=10.0)
    ```

    It is also possible to record the sum of inputs to each neuron in a rate-coded population:

    ```python
    m = Monitor(pop, ['sum(exc)', 'r'])
    ```

    """

    def __init__(self, obj, variables=[], period=None, period_offset=None, start=True, net_id=0):
        """
        :param obj: object to monitor. Must be a Population, PopulationView, Dendrite or Projection object.
        :param variables: single variable name or list of variable names to record (default: []).
        :param period: delay in ms between two recording (default: dt). Not valid for the ``spike`` variable of a Population(View).
        :param period_offset: determine the moment in ms of recording within the period (default 0). Must be smaller than **period**.
        :param start: defines if the recording should start immediately (default: True). If not, you should later start the recordings with the ``start()`` method.
        """
        # Object to record (Population, PopulationView, Dendrite)
        self.object = obj
        self.cyInstance = None
        self.net_id = net_id
        self.name = 'Monitor'

        # Check type of the object
        if not isinstance(self.object, (Population, PopulationView, Dendrite, Projection)):
            Global._error('Monitor: the object must be a Population, PopulationView, Dendrite or Projection object')

        # Variables to record
        if not isinstance(variables, list):
            self._variables = [variables]
        else:
            self._variables = variables

        # Sanity check: we want only record variables
        for var in self._variables:
            if var == "w" and var in self.object.variables:
                continue

            if var in self.object.parameters:
                Global._error('Parameters are not recordable')

            if not var in self.object.variables and not var in ['spike', 'axon_spike'] and not var.startswith('sum('):
                Global._error('Monitor: the object does not have an attribute named', var)

        # Period
        if not period:
            self._period = Global.config['dt']
        else:
            self._period = float(period)

        # Period Offset
        if not period_offset:
            self._period_offset = 0
        else:
            # check validity
            if period_offset >= period:
                Global._error("Monitor(): value of period_offset must be smaller than period.")
            else:
                self._period_offset = period_offset

        # Warn users when recording projections
        if isinstance(self.object, Projection) and self._period == Global.config['dt']:
            Global._warning('Monitor(): it is a bad idea to record synaptic variables of a projection at each time step!')

        # Start
        self._start = start
        self._recorded_variables = {}
        self._last_recorded_variables = {}

        # Add the monitor to the global variable
        self.id = len(Global._network[self.net_id]['monitors'])

        Global._network[self.net_id]['monitors'].append(self)

        if Global._network[self.net_id]['compiled']: # Already compiled
            self._init_monitoring()

    # Extend the period attribute
    @property
    def period(self):
        "Period of recording in ms"
        if not self.cyInstance:
            return self._period
        else:
            return self.cyInstance.period * Global.config['dt']
    @period.setter
    def period(self, val):
        if not self.cyInstance:
            self._period = val
        else:
            self.cyInstance.period = int(val/Global.config['dt'])

    # Extend the period_offset attribute
    @property
    def period_offset(self):
        "Shift of moment of time of recording in ms within a period"
        if not self.cyInstance:
            return self._period
        else:
            return self.cyInstance.period_offset * Global.config['dt']

    @period_offset.setter
    def period_offset(self, val):
        if not self.cyInstance:
            self._period = val
        else:
            self.cyInstance.period_offset = int(val/Global.config['dt'])

    # Extend the variables attribute
    @property
    def variables(self):
        "Returns a copy of the current variable list."
        return copy(self._variables)

    @variables.setter
    def variables(self, val):
        Global._error("Modifying of a Monitors variable list is not allowed")

    def size_in_bytes(self):
        """
        Get the size of allocated memory on C++ side. Please note, this is only valid if compile() was invoked.

        :return: size in bytes of all allocated C++ data.
        """
        if hasattr(self.cyInstance, 'size_in_bytes'):
            return self.cyInstance.size_in_bytes()

    def _clear(self):
        """
        Deallocates the container within the C++ instance. The population object is not usable anymore after calling this function.

        Warning: should be only called by the net deconstructor (in the context of parallel_run).
        """
        if hasattr(self.cyInstance, 'clear'):
            self.cyInstance.clear()

    def _add_variable(self, var):
        """
        Adds a variable to the list of recorded attributes.
        """
        if not var in self._variables:
            self._variables.append(var)

        self._recorded_variables[var] = {
            'start': [Global.get_current_step(self.net_id)],
            'stop': [None],
        }

        self._last_recorded_variables[var] = {
            'start': [Global.get_current_step(self.net_id)],
            'stop': [None],
        }

    def reset(self):
        """
        Reset the monitor to its initial state.
        """
        for var in self._variables:
            # Flush the data
            data = self.get(var)
            del data
            # Reinitializes the timings
            self._add_variable(var)

    def _init_monitoring(self):
        "To be called after compile() as it accesses cython objects"
        # Start recording dependent on the recorded object
        from ANNarchy.extensions.bold import BoldMonitor
        if isinstance(self, BoldMonitor):
            self._start_bold_monitor() # pylint: disable=no-member
        elif isinstance(self.object, (Population, PopulationView)):
            self._start_population()
        elif isinstance(self.object, (Dendrite, Projection)):
            self._start_dendrite()

    def _start_population(self):
        "Creates the C++ object and starts the recording for a population."

        if isinstance(self.object, PopulationView):
            self.ranks = list(self.object.ranks)
        else:
            self.ranks = [-1]

        # Create the wrapper
        period = int(self._period/Global.config['dt'])
        period_offset = int(self._period_offset/Global.config['dt'])
        offset = Global.get_current_step(self.net_id) % period
        self.cyInstance = getattr(Global._network[self.net_id]['instance'], 'PopRecorder'+str(self.object.id)+'_wrapper')(self.ranks, period, period_offset, offset)

        for var in self._variables:
            self._add_variable(var)

        # Start recordings if enabled
        if self._start:
            self.start()

    def _start_dendrite(self):
        "Creates the C++ object and starts the recording for a dendrite."

        if isinstance(self.object, Dendrite):
            self.ranks = self.object.post_rank
            self.idx = [self.object.idx]
            proj_id = self.object.proj.id
        else: # Projection
            self.ranks = [-1]
            self.idx = self.object.post_ranks
            proj_id = self.object.id

        # Compute the period and offset
        period = int(self._period/Global.config['dt'])
        period_offset = int(self._period_offset / Global.config['dt'])
        offset = Global.get_current_step(self.net_id) % period

        # Create the wrapper
        self.cyInstance = getattr(Global._network[self.net_id]['instance'], 'ProjRecorder'+str(proj_id)+'_wrapper')(self.idx, period, period_offset, offset)

        # Add the variables
        for var in self._variables:
            self._add_variable(var)

        # Start recordings if enabled
        if self._start:
            self.start()

    def start(self, variables=None, period=None):
        """Starts recording the variables.

        It is called automatically after ``compile()`` if the flag ``start`` was not passed to the constructor.

        :param variables: single variable name or list of variable names to start recording (default: the ``variables`` argument passed to the constructor).
        :param period: delay in ms between two recording (default: dt). Not valid for the ``spike`` variable of a Population(View).
        """
        if variables:
            if not isinstance(variables, list):
                self._add_variable(variables)
                variables = [variables]
            else:
                for var in variables:
                    self._add_variable(var)
        else:
            variables = self.variables

        if period:
            self._period = period
            self.cyInstance.period = int(self._period/Global.config['dt'])
            self.cyInstance.offset = Global.get_current_step(self.net_id)

        for var in variables:
            name = var
            # Sums of inputs for rate-coded populations
            if var.startswith('sum('):
                target = re.findall(r"\(([\w]+)\)", var)[0]
                name = '_sum_' + target
            try:
                setattr(self.cyInstance, 'record_'+name, True)
            except:
                obj_desc = ''
                if isinstance(self.object, (Population, PopulationView)):
                    obj_desc = 'population ' + self.object.name
                elif isinstance(self.object, Projection):
                    obj_desc = 'projection between '+self.object.pre.name+' and '+self.object.post.name
                else:
                    obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
                    if var in self.object.proj.parameters:
                        Global._print('\t', var, 'is a parameter, its value is constant')

                Global._warning('Monitor: ' + var + ' can not be recorded ('+obj_desc+')')


    def pause(self):
        "Pauses the recordings."
        # Start recording the variables
        for var in self.variables:
            name = var
            # Sums of inputs for rate-coded populations
            if var.startswith('sum('):
                target = re.findall(r"\(([\w]+)\)", var)[0]
                name = '_sum_' + target
            try:
                setattr(self.cyInstance, 'record_'+name, False)
            except:
                obj_desc = ''
                if isinstance(self.object, (Population, PopulationView)):
                    obj_desc = 'population ' + self.object.name
                elif isinstance(self.object, Projection):
                    obj_desc = 'projection between ' + self.object.pre.name+' and '+self.object.post.name
                else:
                    obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
                Global._warning('Monitor:' + var + ' can not be recorded ('+obj_desc+')')

            self._recorded_variables[var]['stop'][-1] = Global.get_current_step(self.net_id)


    def resume(self):
        "Resumes the recordings."
        # Start recording the variables
        for var in self.variables:
            name = var
            # Sums of inputs for rate-coded populations
            if var.startswith('sum('):
                target = re.findall(r"\(([\w]+)\)", var)[0]
                name = '_sum_' + target
            try:
                setattr(self.cyInstance, 'record_'+name, True)
            except:
                obj_desc = ''
                if isinstance(self.object, (Population, PopulationView)):
                    obj_desc = 'population '+self.object.name
                elif isinstance(self.object, Projection):
                    obj_desc = 'projection between '+self.object.pre.name+' and '+self.object.post.name
                else:
                    obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
                Global._warning('Monitor:' + var + ' can not be recorded ('+obj_desc+')')

            self._recorded_variables[var]['start'].append(Global.get_current_step(self.net_id))
            self._recorded_variables[var]['stop'].append(None)

    def stop(self):
        """
        Stops the recording.

        Warning: This will delete the content of the C++ object and all data not previously retrieved is lost.
        """
        try:
            self._variables = []
            self._recorded_variables = {}
            self.cyInstance.clear()
            self.cyInstance = None

        except:
            obj_desc = ''
            if isinstance(self.object, (Population, PopulationView)):
                obj_desc = 'population '+self.object.name
            elif isinstance(self.object, Projection):
                obj_desc = 'projection between '+self.object.pre.name+' and '+self.object.post.name
            else:
                obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
            Global._warning('Monitor:' + obj_desc + 'cannot be stopped')


    def get(self, variables=None, keep=False, reshape=False, force_dict=False):
        """
        Returns the recorded variables as a Numpy array (first dimension is time, second is neuron index).

        If a single variable name is provided, the recorded values for this variable are directly returned.
        If a list is provided or the argument left empty, a dictionary with all recorded variables is returned.

        The ``spike`` variable of a population will be returned as a dictionary of lists, where the spike times (in steps) for each recorded neurons are returned.

        :param variables: (list of) variables. By default, a dictionary with all variables is returned.
        :param keep: defines if the content in memory for each variable should be kept (default: False).
        :param reshape: transforms the second axis of the array to match the population's geometry (default: False).
        """

        def reshape_recording(self, data):
            if not reshape:
                return data
            else:
                return data.reshape((data.shape[0],) + self.object.geometry)

        def return_variable(self, name, keep):
            if isinstance(self.object, (Population, PopulationView)):
                return reshape_recording(self, self._get_population(self.object, name, keep))
            elif isinstance(self.object, (Dendrite, Projection)):
                data = self._get_dendrite(self.object, name, keep)
                # Dendrites have one empty dimension
                if isinstance(self.object, Dendrite):
                    data = data.squeeze()
                return data
            else:
                return None


        if variables:
            if not isinstance(variables, list):
                variables = [variables]
        else:
            variables = self.variables
            force_dict = True

        data = {}
        for var in variables:
            name = var
            # Sums of inputs for rate-coded populations
            if var.startswith('sum('):
                target = re.findall(r"\(([\w]+)\)", var)[0]
                name = '_sum_' + target

            # Retrieve the data
            data[var] = return_variable(self, name, keep)

            # Update stopping time
            self._recorded_variables[var]['stop'][-1] = Global.get_current_step(self.net_id)

            self._last_recorded_variables[var]['start'] = self._recorded_variables[var]['start']
            self._last_recorded_variables[var]['stop'] = self._recorded_variables[var]['stop']

            if not keep:
                self._recorded_variables[var]['start'] = [Global.get_current_step(self.net_id)]
                self._recorded_variables[var]['stop'] = [None]

        if not force_dict and len(variables)==1:
            return data[variables[0]]
        else:
            return data

    def _get_population(self, pop, name, keep):
        try:
            data = getattr(self.cyInstance, name)
            if not keep:
                getattr(self.cyInstance, 'clear_' + name)()
        except:
            data = []

        if name not in ['spike', 'axon_spike']:
            return np.array(data)
        else:
            return data

    def _get_dendrite(self, proj, name, keep):
        try:
            data = getattr(self.cyInstance, name)
            if not keep:
                getattr(self.cyInstance, 'clear_' + name)()
        except:
            data = []
        return np.array(data, dtype=object)

    def times(self, variables=None):
        """
        Returns the start and stop times (in ms) of the recorded variables.

        It should only be called after a call to ``get()``, so that it describes when the variables have been recorded.

        :param variables: (list of) variables. By default, the times for all variables is returned.
        """
        t = {}
        if variables:
            if not isinstance(variables, list):
                variables = [variables]
        else:
            variables = self._variables

        for var in variables:
            # check for spelling mistakes
            if not var in self._variables:
                Global._warning("Variable '"+str(var)+"' is not monitored.")
                continue

            t[var] = deepcopy(self._last_recorded_variables[var])

        return t

    ###############################
    ### Spike visualisation stuff
    ###############################
    def raster_plot(self, spikes=None):
        """
        Returns two vectors representing for each recorded spike 1) the spike times and 2) the ranks of the neurons.

        Example:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        spike_times, spike_ranks = m.raster_plot()
        plt.plot(spike_times, spike_ranks, '.')
        ```

        or:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        spikes = m.get('spike')
        spike_times, spike_ranks = m.raster_plot(spikes)
        plt.plot(spike_times, spike_ranks, '.')
        ```

        :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
        """
        times = []; ranks=[]
        if not 'spike' in self._variables:
            Global._error('Monitor: spike was not recorded')

        # Get data
        if not spikes:
            data = self.get('spike')
        else:
            if 'spike' in spikes.keys():
                data = spikes['spike']
            elif 'axon_spike' in spikes.keys():
                data = spikes['axon_spike']
            else:
                data = spikes

        # Compute raster
        for n in data.keys():
            for t in data[n]:
                times.append(t)
                ranks.append(n)

        return Global.dt()* np.array(times), np.array(ranks)

    def histogram(self, spikes=None, bins=None, per_neuron=False, recording_window=None):
        """
        Returns a histogram for the recorded spikes in the population.

        Example:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        histo = m.histogram()
        plt.plot(histo)
        ```

        or:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        spikes = m.get('spike')
        histo = m.histogram(spikes)
        plt.plot(histo)
        ```

        :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
        :param bins: the bin size in ms (default: dt).
        """
        if not 'spike' in self._variables:
            Global._error('Monitor: spike was not recorded')

        # Get data
        if not spikes:
            data = self.get('spike')
        else:
            if 'spike' in spikes.keys():
                data = spikes['spike']
            else:
                data = spikes

        return histogram(data, bins=bins, per_neuron=per_neuron, recording_window=recording_window)

    def inter_spike_interval(self, spikes=None, ranks=None, per_neuron=False):
        """
        Computes the inter-spike interval for the recorded spikes in the population.

        :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
        :ranks:        a list of neurons that should be evaluated. By default (None), all neurons are evaluated.
        :per_neuron:   if set to True, the computed inter-spike intervals are stored per neuron (analog to spikes), otherwise all values are stored in one huge vector (default: False).
        """
        # Get data
        if not spikes:
            data = self.get('spike')
        else:
            if 'spike' in spikes.keys():
                data = spikes['spike']
            else:
                data = spikes

        return inter_spike_interval(data, ranks=ranks, per_neuron=per_neuron)

    def coefficient_of_variation(self, spikes=None, ranks=None):
        """
        Computes the coefficient of variation for the recorded spikes in the population.

        :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
        :ranks:        a list of neurons that should be evaluated. By default (None), all neurons are evaluated.
        """
        # Get data
        if not spikes:
            data = self.get('spike')
        else:
            if 'spike' in spikes.keys():
                data = spikes['spike']
            else:
                data = spikes

        return coefficient_of_variation(data, ranks=ranks)

    def mean_fr(self, spikes=None):
        """
        Computes the mean firing rate in the population during the recordings.

        Example:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        fr = m.mean_fr()
        ```

        or:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        spikes = m.get('spike')
        fr = m.mean_fr(spikes)
        ```

        :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.

        """
        if not 'spike' in self._variables:
            Global._error('Monitor: spike was not recorded')

        # Get data
        if not spikes:
            data = self.get('spike')
        else:
            if 'spike' in spikes.keys():
                data = spikes['spike']
            else:
                data = spikes


        # Compute the duration of the recordings
        duration = self._last_recorded_variables['spike']['stop'][-1] - self._last_recorded_variables['spike']['start'][-1]

        # Number of neurons
        neurons = self.object.ranks if isinstance(self.object, PopulationView) else range(self.object.size)

        # Compute fr
        fr = 0
        for neuron in neurons:
            fr += len(data[neuron])

        return fr/float(len(neurons))/duration/Global.dt()*1000.0



    def smoothed_rate(self, spikes=None, smooth=0.):
        """
        Computes the smoothed firing rate of the recorded spiking neurons.

        The first axis is the neuron index, the second is time.

        Example:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        r = m.smoothed_rate(smooth=100.)
        ```

        :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
        :param smooth: smoothing time constant. Default: 0.0 (no smoothing).

        """
        if not 'spike' in self._variables:
            Global._error('Monitor: spike was not recorded')

        # Get data
        if not spikes:
            data = self.get('spike')
        else:
            if 'spike' in spikes.keys():
                data = spikes['spike']
            else:
                data = spikes

        import ANNarchy.core.cython_ext.Transformations as Transformations
        return Transformations.smoothed_rate(
            {
                'data': data,
                'start': self._last_recorded_variables['spike']['start'][-1],
                'stop': self._last_recorded_variables['spike']['stop'][-1]
            },
            smooth
        )

    def population_rate(self, spikes=None, smooth=0.):
        """
        Takes the recorded spikes of a population and returns a smoothed firing rate for the population of recorded neurons.

        This method is faster than calling ``smoothed_rate`` and then averaging.

        The first axis is the neuron index, the second is time.

        If ``spikes`` is left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.

        Example:

        ```python
        m = Monitor(P[:1000], 'spike')
        simulate(1000.0)
        r = m.population_rate(smooth=100.)
        ```

        :param spikes: the dictionary of spikes returned by ``get('spike')``.
        :param smooth: smoothing time constant. Default: 0.0 (no smoothing).

        """
        if not 'spike' in self._variables:
            Global._error('Monitor: spike was not recorded')

        # Get data
        if not spikes:
            data = self.get('spike')
        else:
            if 'spike' in spikes.keys():
                data = spikes['spike']
            else:
                data = spikes

        import ANNarchy.core.cython_ext.Transformations as Transformations
        return Transformations.population_rate(
            {
                'data': data,
                'start': self._last_recorded_variables['spike']['start'][-1],
                'stop': self._last_recorded_variables['spike']['stop'][-1]
            },
            smooth
        )

__init__(obj, variables=[], period=None, period_offset=None, start=True, net_id=0) #

Parameters:

  • obj

    object to monitor. Must be a Population, PopulationView, Dendrite or Projection object.

  • variables

    single variable name or list of variable names to record (default: []).

  • period

    delay in ms between two recording (default: dt). Not valid for the spike variable of a Population(View).

  • period_offset

    determine the moment in ms of recording within the period (default 0). Must be smaller than period.

  • start

    defines if the recording should start immediately (default: True). If not, you should later start the recordings with the start() method.

Source code in ANNarchy/core/Monitor.py
 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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def __init__(self, obj, variables=[], period=None, period_offset=None, start=True, net_id=0):
    """
    :param obj: object to monitor. Must be a Population, PopulationView, Dendrite or Projection object.
    :param variables: single variable name or list of variable names to record (default: []).
    :param period: delay in ms between two recording (default: dt). Not valid for the ``spike`` variable of a Population(View).
    :param period_offset: determine the moment in ms of recording within the period (default 0). Must be smaller than **period**.
    :param start: defines if the recording should start immediately (default: True). If not, you should later start the recordings with the ``start()`` method.
    """
    # Object to record (Population, PopulationView, Dendrite)
    self.object = obj
    self.cyInstance = None
    self.net_id = net_id
    self.name = 'Monitor'

    # Check type of the object
    if not isinstance(self.object, (Population, PopulationView, Dendrite, Projection)):
        Global._error('Monitor: the object must be a Population, PopulationView, Dendrite or Projection object')

    # Variables to record
    if not isinstance(variables, list):
        self._variables = [variables]
    else:
        self._variables = variables

    # Sanity check: we want only record variables
    for var in self._variables:
        if var == "w" and var in self.object.variables:
            continue

        if var in self.object.parameters:
            Global._error('Parameters are not recordable')

        if not var in self.object.variables and not var in ['spike', 'axon_spike'] and not var.startswith('sum('):
            Global._error('Monitor: the object does not have an attribute named', var)

    # Period
    if not period:
        self._period = Global.config['dt']
    else:
        self._period = float(period)

    # Period Offset
    if not period_offset:
        self._period_offset = 0
    else:
        # check validity
        if period_offset >= period:
            Global._error("Monitor(): value of period_offset must be smaller than period.")
        else:
            self._period_offset = period_offset

    # Warn users when recording projections
    if isinstance(self.object, Projection) and self._period == Global.config['dt']:
        Global._warning('Monitor(): it is a bad idea to record synaptic variables of a projection at each time step!')

    # Start
    self._start = start
    self._recorded_variables = {}
    self._last_recorded_variables = {}

    # Add the monitor to the global variable
    self.id = len(Global._network[self.net_id]['monitors'])

    Global._network[self.net_id]['monitors'].append(self)

    if Global._network[self.net_id]['compiled']: # Already compiled
        self._init_monitoring()

start(variables=None, period=None) #

Starts recording the variables.

It is called automatically after compile() if the flag start was not passed to the constructor.

Parameters:

  • variables

    single variable name or list of variable names to start recording (default: the variables argument passed to the constructor).

  • period

    delay in ms between two recording (default: dt). Not valid for the spike variable of a Population(View).

Source code in ANNarchy/core/Monitor.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def start(self, variables=None, period=None):
    """Starts recording the variables.

    It is called automatically after ``compile()`` if the flag ``start`` was not passed to the constructor.

    :param variables: single variable name or list of variable names to start recording (default: the ``variables`` argument passed to the constructor).
    :param period: delay in ms between two recording (default: dt). Not valid for the ``spike`` variable of a Population(View).
    """
    if variables:
        if not isinstance(variables, list):
            self._add_variable(variables)
            variables = [variables]
        else:
            for var in variables:
                self._add_variable(var)
    else:
        variables = self.variables

    if period:
        self._period = period
        self.cyInstance.period = int(self._period/Global.config['dt'])
        self.cyInstance.offset = Global.get_current_step(self.net_id)

    for var in variables:
        name = var
        # Sums of inputs for rate-coded populations
        if var.startswith('sum('):
            target = re.findall(r"\(([\w]+)\)", var)[0]
            name = '_sum_' + target
        try:
            setattr(self.cyInstance, 'record_'+name, True)
        except:
            obj_desc = ''
            if isinstance(self.object, (Population, PopulationView)):
                obj_desc = 'population ' + self.object.name
            elif isinstance(self.object, Projection):
                obj_desc = 'projection between '+self.object.pre.name+' and '+self.object.post.name
            else:
                obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
                if var in self.object.proj.parameters:
                    Global._print('\t', var, 'is a parameter, its value is constant')

            Global._warning('Monitor: ' + var + ' can not be recorded ('+obj_desc+')')

stop() #

Stops the recording.

Warning: This will delete the content of the C++ object and all data not previously retrieved is lost.

Source code in ANNarchy/core/Monitor.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def stop(self):
    """
    Stops the recording.

    Warning: This will delete the content of the C++ object and all data not previously retrieved is lost.
    """
    try:
        self._variables = []
        self._recorded_variables = {}
        self.cyInstance.clear()
        self.cyInstance = None

    except:
        obj_desc = ''
        if isinstance(self.object, (Population, PopulationView)):
            obj_desc = 'population '+self.object.name
        elif isinstance(self.object, Projection):
            obj_desc = 'projection between '+self.object.pre.name+' and '+self.object.post.name
        else:
            obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
        Global._warning('Monitor:' + obj_desc + 'cannot be stopped')

pause() #

Pauses the recordings.

Source code in ANNarchy/core/Monitor.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def pause(self):
    "Pauses the recordings."
    # Start recording the variables
    for var in self.variables:
        name = var
        # Sums of inputs for rate-coded populations
        if var.startswith('sum('):
            target = re.findall(r"\(([\w]+)\)", var)[0]
            name = '_sum_' + target
        try:
            setattr(self.cyInstance, 'record_'+name, False)
        except:
            obj_desc = ''
            if isinstance(self.object, (Population, PopulationView)):
                obj_desc = 'population ' + self.object.name
            elif isinstance(self.object, Projection):
                obj_desc = 'projection between ' + self.object.pre.name+' and '+self.object.post.name
            else:
                obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
            Global._warning('Monitor:' + var + ' can not be recorded ('+obj_desc+')')

        self._recorded_variables[var]['stop'][-1] = Global.get_current_step(self.net_id)

resume() #

Resumes the recordings.

Source code in ANNarchy/core/Monitor.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def resume(self):
    "Resumes the recordings."
    # Start recording the variables
    for var in self.variables:
        name = var
        # Sums of inputs for rate-coded populations
        if var.startswith('sum('):
            target = re.findall(r"\(([\w]+)\)", var)[0]
            name = '_sum_' + target
        try:
            setattr(self.cyInstance, 'record_'+name, True)
        except:
            obj_desc = ''
            if isinstance(self.object, (Population, PopulationView)):
                obj_desc = 'population '+self.object.name
            elif isinstance(self.object, Projection):
                obj_desc = 'projection between '+self.object.pre.name+' and '+self.object.post.name
            else:
                obj_desc = 'dendrite between '+self.object.proj.pre.name+' and '+self.object.proj.post.name
            Global._warning('Monitor:' + var + ' can not be recorded ('+obj_desc+')')

        self._recorded_variables[var]['start'].append(Global.get_current_step(self.net_id))
        self._recorded_variables[var]['stop'].append(None)

get(variables=None, keep=False, reshape=False, force_dict=False) #

Returns the recorded variables as a Numpy array (first dimension is time, second is neuron index).

If a single variable name is provided, the recorded values for this variable are directly returned. If a list is provided or the argument left empty, a dictionary with all recorded variables is returned.

The spike variable of a population will be returned as a dictionary of lists, where the spike times (in steps) for each recorded neurons are returned.

Parameters:

  • variables

    (list of) variables. By default, a dictionary with all variables is returned.

  • keep

    defines if the content in memory for each variable should be kept (default: False).

  • reshape

    transforms the second axis of the array to match the population's geometry (default: False).

Source code in ANNarchy/core/Monitor.py
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
def get(self, variables=None, keep=False, reshape=False, force_dict=False):
    """
    Returns the recorded variables as a Numpy array (first dimension is time, second is neuron index).

    If a single variable name is provided, the recorded values for this variable are directly returned.
    If a list is provided or the argument left empty, a dictionary with all recorded variables is returned.

    The ``spike`` variable of a population will be returned as a dictionary of lists, where the spike times (in steps) for each recorded neurons are returned.

    :param variables: (list of) variables. By default, a dictionary with all variables is returned.
    :param keep: defines if the content in memory for each variable should be kept (default: False).
    :param reshape: transforms the second axis of the array to match the population's geometry (default: False).
    """

    def reshape_recording(self, data):
        if not reshape:
            return data
        else:
            return data.reshape((data.shape[0],) + self.object.geometry)

    def return_variable(self, name, keep):
        if isinstance(self.object, (Population, PopulationView)):
            return reshape_recording(self, self._get_population(self.object, name, keep))
        elif isinstance(self.object, (Dendrite, Projection)):
            data = self._get_dendrite(self.object, name, keep)
            # Dendrites have one empty dimension
            if isinstance(self.object, Dendrite):
                data = data.squeeze()
            return data
        else:
            return None


    if variables:
        if not isinstance(variables, list):
            variables = [variables]
    else:
        variables = self.variables
        force_dict = True

    data = {}
    for var in variables:
        name = var
        # Sums of inputs for rate-coded populations
        if var.startswith('sum('):
            target = re.findall(r"\(([\w]+)\)", var)[0]
            name = '_sum_' + target

        # Retrieve the data
        data[var] = return_variable(self, name, keep)

        # Update stopping time
        self._recorded_variables[var]['stop'][-1] = Global.get_current_step(self.net_id)

        self._last_recorded_variables[var]['start'] = self._recorded_variables[var]['start']
        self._last_recorded_variables[var]['stop'] = self._recorded_variables[var]['stop']

        if not keep:
            self._recorded_variables[var]['start'] = [Global.get_current_step(self.net_id)]
            self._recorded_variables[var]['stop'] = [None]

    if not force_dict and len(variables)==1:
        return data[variables[0]]
    else:
        return data

reset() #

Reset the monitor to its initial state.

Source code in ANNarchy/core/Monitor.py
182
183
184
185
186
187
188
189
190
191
def reset(self):
    """
    Reset the monitor to its initial state.
    """
    for var in self._variables:
        # Flush the data
        data = self.get(var)
        del data
        # Reinitializes the timings
        self._add_variable(var)

histogram(spikes=None, bins=None, per_neuron=False, recording_window=None) #

Returns a histogram for the recorded spikes in the population.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
histo = m.histogram()
plt.plot(histo)

or:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
histo = m.histogram(spikes)
plt.plot(histo)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike'). If left empty, get('spike') will be called. Beware: this erases the data from memory.

  • bins

    the bin size in ms (default: dt).

Source code in ANNarchy/core/Monitor.py
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
def histogram(self, spikes=None, bins=None, per_neuron=False, recording_window=None):
    """
    Returns a histogram for the recorded spikes in the population.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    histo = m.histogram()
    plt.plot(histo)
    ```

    or:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    histo = m.histogram(spikes)
    plt.plot(histo)
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
    :param bins: the bin size in ms (default: dt).
    """
    if not 'spike' in self._variables:
        Global._error('Monitor: spike was not recorded')

    # Get data
    if not spikes:
        data = self.get('spike')
    else:
        if 'spike' in spikes.keys():
            data = spikes['spike']
        else:
            data = spikes

    return histogram(data, bins=bins, per_neuron=per_neuron, recording_window=recording_window)

mean_fr(spikes=None) #

Computes the mean firing rate in the population during the recordings.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
fr = m.mean_fr()

or:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
fr = m.mean_fr(spikes)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike'). If left empty, get('spike') will be called. Beware: this erases the data from memory.

Source code in ANNarchy/core/Monitor.py
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
def mean_fr(self, spikes=None):
    """
    Computes the mean firing rate in the population during the recordings.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    fr = m.mean_fr()
    ```

    or:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    fr = m.mean_fr(spikes)
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.

    """
    if not 'spike' in self._variables:
        Global._error('Monitor: spike was not recorded')

    # Get data
    if not spikes:
        data = self.get('spike')
    else:
        if 'spike' in spikes.keys():
            data = spikes['spike']
        else:
            data = spikes


    # Compute the duration of the recordings
    duration = self._last_recorded_variables['spike']['stop'][-1] - self._last_recorded_variables['spike']['start'][-1]

    # Number of neurons
    neurons = self.object.ranks if isinstance(self.object, PopulationView) else range(self.object.size)

    # Compute fr
    fr = 0
    for neuron in neurons:
        fr += len(data[neuron])

    return fr/float(len(neurons))/duration/Global.dt()*1000.0

population_rate(spikes=None, smooth=0.0) #

Takes the recorded spikes of a population and returns a smoothed firing rate for the population of recorded neurons.

This method is faster than calling smoothed_rate and then averaging.

The first axis is the neuron index, the second is time.

If spikes is left empty, get('spike') will be called. Beware: this erases the data from memory.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
r = m.population_rate(smooth=100.)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike').

  • smooth

    smoothing time constant. Default: 0.0 (no smoothing).

Source code in ANNarchy/core/Monitor.py
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
def population_rate(self, spikes=None, smooth=0.):
    """
    Takes the recorded spikes of a population and returns a smoothed firing rate for the population of recorded neurons.

    This method is faster than calling ``smoothed_rate`` and then averaging.

    The first axis is the neuron index, the second is time.

    If ``spikes`` is left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    r = m.population_rate(smooth=100.)
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``.
    :param smooth: smoothing time constant. Default: 0.0 (no smoothing).

    """
    if not 'spike' in self._variables:
        Global._error('Monitor: spike was not recorded')

    # Get data
    if not spikes:
        data = self.get('spike')
    else:
        if 'spike' in spikes.keys():
            data = spikes['spike']
        else:
            data = spikes

    import ANNarchy.core.cython_ext.Transformations as Transformations
    return Transformations.population_rate(
        {
            'data': data,
            'start': self._last_recorded_variables['spike']['start'][-1],
            'stop': self._last_recorded_variables['spike']['stop'][-1]
        },
        smooth
    )

raster_plot(spikes=None) #

Returns two vectors representing for each recorded spike 1) the spike times and 2) the ranks of the neurons.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spike_times, spike_ranks = m.raster_plot()
plt.plot(spike_times, spike_ranks, '.')

or:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
spike_times, spike_ranks = m.raster_plot(spikes)
plt.plot(spike_times, spike_ranks, '.')

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike'). If left empty, get('spike') will be called. Beware: this erases the data from memory.

Source code in ANNarchy/core/Monitor.py
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
def raster_plot(self, spikes=None):
    """
    Returns two vectors representing for each recorded spike 1) the spike times and 2) the ranks of the neurons.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spike_times, spike_ranks = m.raster_plot()
    plt.plot(spike_times, spike_ranks, '.')
    ```

    or:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    spike_times, spike_ranks = m.raster_plot(spikes)
    plt.plot(spike_times, spike_ranks, '.')
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
    """
    times = []; ranks=[]
    if not 'spike' in self._variables:
        Global._error('Monitor: spike was not recorded')

    # Get data
    if not spikes:
        data = self.get('spike')
    else:
        if 'spike' in spikes.keys():
            data = spikes['spike']
        elif 'axon_spike' in spikes.keys():
            data = spikes['axon_spike']
        else:
            data = spikes

    # Compute raster
    for n in data.keys():
        for t in data[n]:
            times.append(t)
            ranks.append(n)

    return Global.dt()* np.array(times), np.array(ranks)

smoothed_rate(spikes=None, smooth=0.0) #

Computes the smoothed firing rate of the recorded spiking neurons.

The first axis is the neuron index, the second is time.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
r = m.smoothed_rate(smooth=100.)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike'). If left empty, get('spike') will be called. Beware: this erases the data from memory.

  • smooth

    smoothing time constant. Default: 0.0 (no smoothing).

Source code in ANNarchy/core/Monitor.py
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
def smoothed_rate(self, spikes=None, smooth=0.):
    """
    Computes the smoothed firing rate of the recorded spiking neurons.

    The first axis is the neuron index, the second is time.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    r = m.smoothed_rate(smooth=100.)
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
    :param smooth: smoothing time constant. Default: 0.0 (no smoothing).

    """
    if not 'spike' in self._variables:
        Global._error('Monitor: spike was not recorded')

    # Get data
    if not spikes:
        data = self.get('spike')
    else:
        if 'spike' in spikes.keys():
            data = spikes['spike']
        else:
            data = spikes

    import ANNarchy.core.cython_ext.Transformations as Transformations
    return Transformations.smoothed_rate(
        {
            'data': data,
            'start': self._last_recorded_variables['spike']['start'][-1],
            'stop': self._last_recorded_variables['spike']['stop'][-1]
        },
        smooth
    )

times(variables=None) #

Returns the start and stop times (in ms) of the recorded variables.

It should only be called after a call to get(), so that it describes when the variables have been recorded.

Parameters:

  • variables

    (list of) variables. By default, the times for all variables is returned.

Source code in ANNarchy/core/Monitor.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def times(self, variables=None):
    """
    Returns the start and stop times (in ms) of the recorded variables.

    It should only be called after a call to ``get()``, so that it describes when the variables have been recorded.

    :param variables: (list of) variables. By default, the times for all variables is returned.
    """
    t = {}
    if variables:
        if not isinstance(variables, list):
            variables = [variables]
    else:
        variables = self._variables

    for var in variables:
        # check for spelling mistakes
        if not var in self._variables:
            Global._warning("Variable '"+str(var)+"' is not monitored.")
            continue

        t[var] = deepcopy(self._last_recorded_variables[var])

    return t

Plotting methods#

ANNarchy.raster_plot(spikes) #

Returns two vectors representing for each recorded spike 1) the spike times and 2) the ranks of the neurons.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
spike_times, spike_ranks = raster_plot(spikes)
plt.plot(spike_times, spike_ranks, '.')

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike').

Source code in ANNarchy/core/Monitor.py
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
def raster_plot(spikes):
    """
    Returns two vectors representing for each recorded spike 1) the spike times and 2) the ranks of the neurons.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    spike_times, spike_ranks = raster_plot(spikes)
    plt.plot(spike_times, spike_ranks, '.')
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``.
    """
    times = []; ranks=[]

    # Compute raster
    for n in spikes.keys():
        for t in spikes[n]:
            times.append(t)
            ranks.append(n)

    return Global.dt()* np.array(times), np.array(ranks)

ANNarchy.histogram(spikes, bins=None, per_neuron=False, recording_window=None) #

Returns a histogram for the recorded spikes in the population.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
histo = histogram(spikes)
plt.plot(histo)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike').

  • bins

    the bin size in ms (default: dt).

Source code in ANNarchy/core/Monitor.py
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
def histogram(spikes, bins=None, per_neuron=False, recording_window=None):
    """
    Returns a histogram for the recorded spikes in the population.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    histo = histogram(spikes)
    plt.plot(histo)
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``.
    :param bins: the bin size in ms (default: dt).
    """
    if bins is None:
        bins =  Global.config['dt']

    bin_step = int(bins/Global.config['dt'])

    # Compute the duration of the recordings
    t_maxes = []
    t_mines = []
    for neuron in spikes.keys():
        if len(spikes[neuron]) == 0 : continue
        t_maxes.append(np.max(spikes[neuron]))
        t_mines.append(np.min(spikes[neuron]))

    if recording_window is None:
        t_max = np.max(t_maxes)
        t_min = np.min(t_mines)
    else:
        t_min = recording_window[0]
        t_max = recording_window[1]
    duration = t_max - t_min

    # Number of bins
    nb_bins = int(duration/bin_step)
    #print(t_min, t_max, duration, nb_bins)

    if per_neuron:
        max_rank = np.amax([x for x in spikes.keys()])+1
        # Initialize histogram
        histo = [ [0 for _ in range(nb_bins+1)] for _ in range(max_rank) ]

        # Compute per step histogram
        for neuron in spikes.keys():
            for t in spikes[neuron]:
                histo[neuron][int((t-t_min)/float(bin_step))] += 1

    else:
        # Initialize histogram
        histo = [0 for t in range(nb_bins+1)]

        # Compute per step histogram
        for neuron in spikes.keys():
            for t in spikes[neuron]:
                histo[int((t-t_min)/float(bin_step))] += 1

    return np.array(histo)

ANNarchy.mean_fr(spikes, duration=None) #

Computes the mean firing rate in the population during the recordings.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
fr = mean_fr(spikes)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike').

  • duration

    duration of the recordings. By default, the mean firing rate is computed between the first and last spikes of the recordings.

Source code in ANNarchy/core/Monitor.py
1040
1041
1042
1043
1044
1045
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
def mean_fr(spikes, duration=None):
    """
    Computes the mean firing rate in the population during the recordings.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    fr = mean_fr(spikes)
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``.
    :param duration: duration of the recordings. By default, the mean firing rate is computed between the first and last spikes of the recordings.


    """
    if duration is None:

        # Compute the duration of the recordings
        t_maxes = []
        t_mines = []
        for neuron in spikes.keys():
            if len(spikes[neuron]) == 0 : continue
            t_maxes.append(np.max(spikes[neuron]))
            t_mines.append(np.min(spikes[neuron]))

        t_max = np.max(t_maxes)
        t_min = np.min(t_mines)
        duration = t_max - t_min

    nb_neurons = len(spikes.keys())

    # Compute fr
    fr = 0
    for neuron in spikes:
        fr += len(spikes[neuron])

    return fr/float(nb_neurons)/duration/Global.dt()*1000.0

ANNarchy.smoothed_rate(spikes, smooth=0.0) #

Computes the smoothed firing rate of the recorded spiking neurons.

The first axis is the neuron index, the second is time.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
r = smoothed_rate(smooth=100.)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike'). If left empty, get('spike') will be called. Beware: this erases the data from memory.

  • smooth

    smoothing time constant. Default: 0.0 (no smoothing).

Source code in ANNarchy/core/Monitor.py
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
def smoothed_rate(spikes, smooth=0.):
    """
    Computes the smoothed firing rate of the recorded spiking neurons.

    The first axis is the neuron index, the second is time.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    r = smoothed_rate(smooth=100.)
    ```


    :param spikes: the dictionary of spikes returned by ``get('spike')``. If left empty, ``get('spike')`` will be called. Beware: this erases the data from memory.
    :param smooth: smoothing time constant. Default: 0.0 (no smoothing).
    """
    # Compute the duration of the recordings
    t_maxes = []
    t_mines = []
    for neuron in spikes.keys():
        if len(spikes[neuron]) == 0 : continue
        t_maxes.append(np.max(spikes[neuron]))
        t_mines.append(np.min(spikes[neuron]))

    t_max = np.max(t_maxes)
    t_min = np.min(t_mines)

    import ANNarchy.core.cython_ext.Transformations as Transformations
    return Transformations.smoothed_rate(
        {
            'data': spikes,
            'start': t_min,
            'stop': t_max
        },
        smooth
    )

ANNarchy.population_rate(spikes, smooth=0.0) #

Takes the recorded spikes of a population and returns a smoothed firing rate for the population of recorded neurons.

This method is faster than calling smoothed_rate and then averaging.

The first axis is the neuron index, the second is time.

Example:

m = Monitor(P[:1000], 'spike')
simulate(1000.0)
spikes = m.get('spike')
r = population_rate(smooth=100.)

Parameters:

  • spikes

    the dictionary of spikes returned by get('spike').

  • smooth

    smoothing time constant. Default: 0.0 (no smoothing).

Source code in ANNarchy/core/Monitor.py
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
def population_rate(spikes, smooth=0.0):
    """
    Takes the recorded spikes of a population and returns a smoothed firing rate for the population of recorded neurons.

    This method is faster than calling ``smoothed_rate`` and then averaging.

    The first axis is the neuron index, the second is time.

    Example:

    ```python
    m = Monitor(P[:1000], 'spike')
    simulate(1000.0)
    spikes = m.get('spike')
    r = population_rate(smooth=100.)
    ```

    :param spikes: the dictionary of spikes returned by ``get('spike')``.
    :param smooth: smoothing time constant. Default: 0.0 (no smoothing).
    """
    # Compute the duration of the recordings
    t_maxes = []
    t_mines = []
    for neuron in spikes.keys():
        if len(spikes[neuron]) == 0 : continue
        t_maxes.append(np.max(spikes[neuron]))
        t_mines.append(np.min(spikes[neuron]))

    t_max = np.max(t_maxes)
    t_min = np.min(t_mines)

    import ANNarchy.core.cython_ext.Transformations as Transformations
    return Transformations.population_rate(
        {
            'data': spikes,
            'start':t_min,
            'stop': t_max
        },
        smooth
    )