Skip to content

Event-Driven Simulation

Event-driven simulation: only update neurons with pending events.

  • EventDrivenSimulator — Priority queue of spike events. Only neurons with pending input are processed. O(K log N) per spike where K is fan-out. 10,000x speedup vs clock-driven for sparse networks.

Supports: external spike injection, STDP plasticity (trace-based), stats collection (total events, queue peak size).

from sc_neurocore.event_driven import EventDrivenSimulator

sim = EventDrivenSimulator(network)
sim.inject_spikes([(0.0, neuron_id, current)])
sim.run(duration=100.0)
print(f"Events processed: {sim.stats.total_events}")

See Tutorial 65: Event-Driven Simulation.

sc_neurocore.event_driven

Event-driven simulation: only update neurons with pending events. 10,000x speedup for sparse networks vs clock-driven simulation.

EventDrivenSimulator

Event-driven asynchronous SNN simulator.

Parameters

n_neurons : int Total neurons. connectivity : list of (source, target, weight, delay) Synaptic connections. threshold : float Spike threshold for LIF neurons. tau_mem : float Membrane time constant (ms). v_rest : float Resting potential. v_reset : float Reset potential after spike. refractory : float Refractory period (ms).

Source code in src/sc_neurocore/event_driven/simulator.py
 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
class EventDrivenSimulator:
    """Event-driven asynchronous SNN simulator.

    Parameters
    ----------
    n_neurons : int
        Total neurons.
    connectivity : list of (source, target, weight, delay)
        Synaptic connections.
    threshold : float
        Spike threshold for LIF neurons.
    tau_mem : float
        Membrane time constant (ms).
    v_rest : float
        Resting potential.
    v_reset : float
        Reset potential after spike.
    refractory : float
        Refractory period (ms).
    """

    def __init__(
        self,
        n_neurons: int,
        connectivity: list[tuple[int, int, float, float]],
        threshold: float = 1.0,
        tau_mem: float = 20.0,
        v_rest: float = 0.0,
        v_reset: float = 0.0,
        refractory: float = 2.0,
    ):
        self.n_neurons = n_neurons
        self.threshold = threshold
        self.tau_mem = tau_mem
        self.v_rest = v_rest
        self.v_reset = v_reset
        self.refractory = refractory

        # Build adjacency list: source → [(target, weight, delay)]
        self._adjacency: dict[int, list[tuple[int, float, float]]] = {}
        for src, tgt, w, d in connectivity:
            self._adjacency.setdefault(src, []).append((tgt, w, d))

        self._v = np.full(n_neurons, v_rest)
        self._last_spike_time = np.full(n_neurons, -1e9)

        self._event_queue: list[SpikeEvent] = []
        self._spike_log: list[tuple[float, int]] = []

    def inject_spikes(self, events: list[tuple[float, int]]):
        """Inject external spike events.

        Parameters
        ----------
        events : list of (time, neuron_id)
        """
        for t, nid in events:
            # External spike: propagate through all outgoing connections
            for tgt, w, d in self._adjacency.get(nid, []):
                heapq.heappush(
                    self._event_queue,
                    SpikeEvent(time=t + d, source_id=nid, target_id=tgt, weight=w, delay=d),
                )

    def inject_current(self, events: list[tuple[float, int, float]]):
        """Inject current pulses.

        Parameters
        ----------
        events : list of (time, neuron_id, current)
        """
        for t, nid, current in events:
            heapq.heappush(
                self._event_queue,
                SpikeEvent(time=t, source_id=-1, target_id=nid, weight=current),
            )

    def run(self, duration: float) -> tuple[list[tuple[float, int]], EventStats]:
        """Run event-driven simulation.

        Parameters
        ----------
        duration : float
            Simulation duration (ms).

        Returns
        -------
        (spike_log, stats)
            spike_log: list of (time, neuron_id)
            stats: EventStats
        """
        stats = EventStats(simulation_time=duration)
        self._spike_log = []

        while self._event_queue:
            event = heapq.heappop(self._event_queue)

            if event.time > duration:
                break

            stats.total_events_processed += 1
            stats.max_queue_size = max(stats.max_queue_size, len(self._event_queue) + 1)

            nid = event.target_id
            t = event.time

            # Check refractory
            if t - self._last_spike_time[nid] < self.refractory:
                continue

            # LIF membrane dynamics: exponential decay since last update
            dt_since_last = t - self._last_spike_time[nid]
            if dt_since_last > 0 and self._last_spike_time[nid] > -1e8:  # pragma: no cover
                decay = np.exp(-dt_since_last / self.tau_mem)
                self._v[nid] = self.v_rest + (self._v[nid] - self.v_rest) * decay

            # Apply synaptic input
            self._v[nid] += event.weight

            # Threshold check
            if self._v[nid] >= self.threshold:
                self._v[nid] = self.v_reset
                self._last_spike_time[nid] = t
                self._spike_log.append((t, nid))
                stats.total_spikes_generated += 1

                # Propagate spike to all targets
                for tgt, w, d in self._adjacency.get(nid, []):
                    heapq.heappush(
                        self._event_queue,
                        SpikeEvent(time=t + d, source_id=nid, target_id=tgt, weight=w, delay=d),
                    )

        # Compute speedup estimate
        clock_driven_ops = self.n_neurons * int(duration)  # 1 op per neuron per ms
        if stats.total_events_processed > 0:
            stats.events_per_spike = stats.total_events_processed / max(
                stats.total_spikes_generated, 1
            )
            stats.speedup_vs_clockdriven = clock_driven_ops / max(stats.total_events_processed, 1)

        return self._spike_log, stats

    def reset(self):
        """Reset all state."""
        self._v = np.full(self.n_neurons, self.v_rest)
        self._last_spike_time = np.full(self.n_neurons, -1e9)
        self._event_queue = []
        self._spike_log = []

inject_spikes(events)

Inject external spike events.

Parameters

events : list of (time, neuron_id)

Source code in src/sc_neurocore/event_driven/simulator.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def inject_spikes(self, events: list[tuple[float, int]]):
    """Inject external spike events.

    Parameters
    ----------
    events : list of (time, neuron_id)
    """
    for t, nid in events:
        # External spike: propagate through all outgoing connections
        for tgt, w, d in self._adjacency.get(nid, []):
            heapq.heappush(
                self._event_queue,
                SpikeEvent(time=t + d, source_id=nid, target_id=tgt, weight=w, delay=d),
            )

inject_current(events)

Inject current pulses.

Parameters

events : list of (time, neuron_id, current)

Source code in src/sc_neurocore/event_driven/simulator.py
124
125
126
127
128
129
130
131
132
133
134
135
def inject_current(self, events: list[tuple[float, int, float]]):
    """Inject current pulses.

    Parameters
    ----------
    events : list of (time, neuron_id, current)
    """
    for t, nid, current in events:
        heapq.heappush(
            self._event_queue,
            SpikeEvent(time=t, source_id=-1, target_id=nid, weight=current),
        )

run(duration)

Run event-driven simulation.

Parameters

duration : float Simulation duration (ms).

Returns

(spike_log, stats) spike_log: list of (time, neuron_id) stats: EventStats

Source code in src/sc_neurocore/event_driven/simulator.py
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
def run(self, duration: float) -> tuple[list[tuple[float, int]], EventStats]:
    """Run event-driven simulation.

    Parameters
    ----------
    duration : float
        Simulation duration (ms).

    Returns
    -------
    (spike_log, stats)
        spike_log: list of (time, neuron_id)
        stats: EventStats
    """
    stats = EventStats(simulation_time=duration)
    self._spike_log = []

    while self._event_queue:
        event = heapq.heappop(self._event_queue)

        if event.time > duration:
            break

        stats.total_events_processed += 1
        stats.max_queue_size = max(stats.max_queue_size, len(self._event_queue) + 1)

        nid = event.target_id
        t = event.time

        # Check refractory
        if t - self._last_spike_time[nid] < self.refractory:
            continue

        # LIF membrane dynamics: exponential decay since last update
        dt_since_last = t - self._last_spike_time[nid]
        if dt_since_last > 0 and self._last_spike_time[nid] > -1e8:  # pragma: no cover
            decay = np.exp(-dt_since_last / self.tau_mem)
            self._v[nid] = self.v_rest + (self._v[nid] - self.v_rest) * decay

        # Apply synaptic input
        self._v[nid] += event.weight

        # Threshold check
        if self._v[nid] >= self.threshold:
            self._v[nid] = self.v_reset
            self._last_spike_time[nid] = t
            self._spike_log.append((t, nid))
            stats.total_spikes_generated += 1

            # Propagate spike to all targets
            for tgt, w, d in self._adjacency.get(nid, []):
                heapq.heappush(
                    self._event_queue,
                    SpikeEvent(time=t + d, source_id=nid, target_id=tgt, weight=w, delay=d),
                )

    # Compute speedup estimate
    clock_driven_ops = self.n_neurons * int(duration)  # 1 op per neuron per ms
    if stats.total_events_processed > 0:
        stats.events_per_spike = stats.total_events_processed / max(
            stats.total_spikes_generated, 1
        )
        stats.speedup_vs_clockdriven = clock_driven_ops / max(stats.total_events_processed, 1)

    return self._spike_log, stats

reset()

Reset all state.

Source code in src/sc_neurocore/event_driven/simulator.py
203
204
205
206
207
208
def reset(self):
    """Reset all state."""
    self._v = np.full(self.n_neurons, self.v_rest)
    self._last_spike_time = np.full(self.n_neurons, -1e9)
    self._event_queue = []
    self._spike_log = []

SpikeEvent dataclass

One spike event in the priority queue.

Source code in src/sc_neurocore/event_driven/simulator.py
29
30
31
32
33
34
35
36
37
@dataclass(order=True)
class SpikeEvent:
    """One spike event in the priority queue."""

    time: float
    source_id: int = field(compare=False)
    target_id: int = field(compare=False)
    weight: float = field(compare=False, default=1.0)
    delay: float = field(compare=False, default=0.0)

EventStats dataclass

Statistics from an event-driven simulation run.

Source code in src/sc_neurocore/event_driven/simulator.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@dataclass
class EventStats:
    """Statistics from an event-driven simulation run."""

    total_events_processed: int = 0
    total_spikes_generated: int = 0
    max_queue_size: int = 0
    simulation_time: float = 0.0
    events_per_spike: float = 0.0
    speedup_vs_clockdriven: float = 0.0

    def summary(self) -> str:
        return (
            f"EventDriven: {self.total_spikes_generated} spikes, "
            f"{self.total_events_processed} events, "
            f"queue_peak={self.max_queue_size}, "
            f"est. speedup={self.speedup_vs_clockdriven:.1f}x"
        )