Spikes analysis

This is a long-standing feature request.

Fortunately there are some quick-and-dirty work-arounds you could take. Here is one that I quickly hacked together. You may wish to modify how the buffer data is structured according to what is convenient or efficient for your use-case (currently it stores a list of spike times for each neuron separately).

import nengo
import numpy as np


class SpikeTimeRecorder:
    """Records a list of spike times for each neuron.
    
    Intended for use with ``nengo==3.0.0``
    
    Source: https://forum.nengo.ai/t/spikes-analysis/1348/5
    """
    
    def __init__(self, n_neurons):
        self.n_neurons = n_neurons
        self.buffer = [[] for _ in range(n_neurons)]

    def __call__(self, t, x):
        if x.shape != (self.n_neurons,):
            raise RuntimeError(
                "Expected n_neurons=%d; got shape: %s"
                % (self.n_neurons, x.shape)
            )
        # Note: if multiple spikes happen in a single time-step
        # then they will be recorded only once!
        for i in np.where(x > 0)[0]:
            self.buffer[i].append(t)


def probe_spike_times(x):
    """Helper method for probing ``x.neurons`` times using a node."""
    obj = SpikeTimeRecorder(x.n_neurons)
    output = nengo.Node(obj, size_in=x.n_neurons)
    nengo.Connection(x.neurons, output, synapse=None)
    return obj.buffer

Example usage:

with nengo.Network(seed=0) as model:
    x = nengo.Ensemble(n_neurons=10, dimensions=1)

    # Get list of spike times for each neuron
    buffer = probe_spike_times(x)


with nengo.Simulator(model) as sim:
    sim.run(1)


for i, neuron_spike_times in enumerate(buffer):
    # neuron_spike_times is a list of spike times (in seconds)
    print("Neuron %d spiked %d times" % (i, len(neuron_spike_times)))

Example output:

Neuron 0 spiked 0 times
Neuron 1 spiked 0 times
Neuron 2 spiked 99 times
Neuron 3 spiked 0 times
Neuron 4 spiked 0 times
Neuron 5 spiked 99 times
Neuron 6 spiked 163 times
Neuron 7 spiked 0 times
Neuron 8 spiked 0 times
Neuron 9 spiked 10 times

Let me know if you have any questions about how to use this snippet. :slight_smile:

3 Likes