Skip to content

Spike-Level Debugger

Temporal spike debugger: trace execution, find divergence, analyze causality.

Tracer

sc_neurocore.debug.tracer

Record full SNN execution trace for post-hoc analysis.

Captures per-neuron per-timestep: voltage, spike, input current. Enables temporal debugging: find where spikes diverge, trace causal chains through synaptic connections, compare two runs.

SpikeTracer

Records execution trace during SNN simulation.

Wraps a Network and intercepts step_all to record spikes, voltages, and currents at every timestep.

Usage

tracer = SpikeTracer(network) trace = tracer.run(duration=0.1, dt=0.001) divergence = find_divergence(trace, expected_spikes)

Source code in src/sc_neurocore/debug/tracer.py
 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
class SpikeTracer:
    """Records execution trace during SNN simulation.

    Wraps a Network and intercepts step_all to record spikes,
    voltages, and currents at every timestep.

    Usage
    -----
    >>> tracer = SpikeTracer(network)
    >>> trace = tracer.run(duration=0.1, dt=0.001)
    >>> divergence = find_divergence(trace, expected_spikes)
    """

    def __init__(self, network):
        self.network = network

    def run(self, duration: float, dt: float = 0.001, seed: int = 42) -> ExecutionTrace:
        """Run the network and record full execution trace."""

        np.random.seed(seed)
        n_steps = int(round(duration / dt))

        # Map populations to global neuron indices
        pop_labels = []
        pop_ranges = []
        total_neurons = 0
        for pop in self.network.populations:
            start = total_neurons
            total_neurons += pop.n
            pop_ranges.append((start, start + pop.n))
            pop_labels.append(pop.label)

        # Allocate trace arrays
        all_spikes = np.zeros((n_steps, total_neurons), dtype=np.int8)
        all_voltages = np.zeros((n_steps, total_neurons), dtype=np.float64)
        all_currents = np.zeros((n_steps, total_neurons), dtype=np.float64)

        # Run simulation step by step
        pop_to_currents = {id(p): np.zeros(p.n, dtype=np.float64) for p in self.network.populations}
        last_spikes = {id(p): np.zeros(p.n, dtype=np.int8) for p in self.network.populations}

        for t in range(n_steps):
            for pid in pop_to_currents:
                pop_to_currents[pid][:] = 0.0

            self.network._apply_stimuli(pop_to_currents, t, dt)
            self.network._apply_projections(pop_to_currents, last_spikes)

            for pop, (start, end) in zip(self.network.populations, pop_ranges):
                pid = id(pop)
                currents = pop_to_currents[pid]
                spikes = pop.step_all(currents)
                last_spikes[pid] = spikes

                all_spikes[t, start:end] = spikes
                all_voltages[t, start:end] = pop.voltages
                all_currents[t, start:end] = currents

                # Record to monitors
                self.network._record(pop, spikes, t, dt)

            self.network._update_plasticity(last_spikes)

        return ExecutionTrace(
            n_neurons=total_neurons,
            n_steps=n_steps,
            spikes=all_spikes,
            voltages=all_voltages,
            currents=all_currents,
            population_labels=pop_labels,
            population_ranges=pop_ranges,
        )

run(duration, dt=0.001, seed=42)

Run the network and record full execution trace.

Source code in src/sc_neurocore/debug/tracer.py
 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
def run(self, duration: float, dt: float = 0.001, seed: int = 42) -> ExecutionTrace:
    """Run the network and record full execution trace."""

    np.random.seed(seed)
    n_steps = int(round(duration / dt))

    # Map populations to global neuron indices
    pop_labels = []
    pop_ranges = []
    total_neurons = 0
    for pop in self.network.populations:
        start = total_neurons
        total_neurons += pop.n
        pop_ranges.append((start, start + pop.n))
        pop_labels.append(pop.label)

    # Allocate trace arrays
    all_spikes = np.zeros((n_steps, total_neurons), dtype=np.int8)
    all_voltages = np.zeros((n_steps, total_neurons), dtype=np.float64)
    all_currents = np.zeros((n_steps, total_neurons), dtype=np.float64)

    # Run simulation step by step
    pop_to_currents = {id(p): np.zeros(p.n, dtype=np.float64) for p in self.network.populations}
    last_spikes = {id(p): np.zeros(p.n, dtype=np.int8) for p in self.network.populations}

    for t in range(n_steps):
        for pid in pop_to_currents:
            pop_to_currents[pid][:] = 0.0

        self.network._apply_stimuli(pop_to_currents, t, dt)
        self.network._apply_projections(pop_to_currents, last_spikes)

        for pop, (start, end) in zip(self.network.populations, pop_ranges):
            pid = id(pop)
            currents = pop_to_currents[pid]
            spikes = pop.step_all(currents)
            last_spikes[pid] = spikes

            all_spikes[t, start:end] = spikes
            all_voltages[t, start:end] = pop.voltages
            all_currents[t, start:end] = currents

            # Record to monitors
            self.network._record(pop, spikes, t, dt)

        self.network._update_plasticity(last_spikes)

    return ExecutionTrace(
        n_neurons=total_neurons,
        n_steps=n_steps,
        spikes=all_spikes,
        voltages=all_voltages,
        currents=all_currents,
        population_labels=pop_labels,
        population_ranges=pop_ranges,
    )

ExecutionTrace dataclass

Complete execution trace of an SNN run.

Attributes

n_neurons : int Total neurons across all populations. n_steps : int Number of simulation timesteps. spikes : ndarray of shape (n_steps, n_neurons) Binary spike matrix. voltages : ndarray of shape (n_steps, n_neurons) Membrane voltages. currents : ndarray of shape (n_steps, n_neurons) Input currents. population_labels : list of str Population names. population_ranges : list of (start, end) Neuron index ranges per population.

Source code in src/sc_neurocore/debug/tracer.py
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
@dataclass
class ExecutionTrace:
    """Complete execution trace of an SNN run.

    Attributes
    ----------
    n_neurons : int
        Total neurons across all populations.
    n_steps : int
        Number of simulation timesteps.
    spikes : ndarray of shape (n_steps, n_neurons)
        Binary spike matrix.
    voltages : ndarray of shape (n_steps, n_neurons)
        Membrane voltages.
    currents : ndarray of shape (n_steps, n_neurons)
        Input currents.
    population_labels : list of str
        Population names.
    population_ranges : list of (start, end)
        Neuron index ranges per population.
    """

    n_neurons: int
    n_steps: int
    spikes: np.ndarray
    voltages: np.ndarray
    currents: np.ndarray
    population_labels: list[str] = field(default_factory=list)
    population_ranges: list[tuple[int, int]] = field(default_factory=list)

    @property
    def spike_count(self) -> int:
        """Total spikes in the trace."""
        return int(self.spikes.sum())

    @property
    def firing_rates(self) -> np.ndarray:
        """Per-neuron firing rate (spikes per step)."""
        return self.spikes.mean(axis=0)

    def neuron_trace(self, neuron_id: int) -> dict:
        """Extract full trace for one neuron."""
        return {
            "spikes": self.spikes[:, neuron_id],
            "voltages": self.voltages[:, neuron_id],
            "currents": self.currents[:, neuron_id],
            "spike_times": np.where(self.spikes[:, neuron_id] > 0)[0],
        }

    def spike_times(self, neuron_id: int) -> np.ndarray:
        """Timesteps when a neuron spiked."""
        return np.where(self.spikes[:, neuron_id] > 0)[0]

    def population_spikes(self, pop_label: str) -> np.ndarray:
        """Spike matrix for one population."""
        for label, (start, end) in zip(self.population_labels, self.population_ranges):
            if label == pop_label:
                return self.spikes[:, start:end]
        raise ValueError(f"Population '{pop_label}' not found")

spike_count property

Total spikes in the trace.

firing_rates property

Per-neuron firing rate (spikes per step).

neuron_trace(neuron_id)

Extract full trace for one neuron.

Source code in src/sc_neurocore/debug/tracer.py
62
63
64
65
66
67
68
69
def neuron_trace(self, neuron_id: int) -> dict:
    """Extract full trace for one neuron."""
    return {
        "spikes": self.spikes[:, neuron_id],
        "voltages": self.voltages[:, neuron_id],
        "currents": self.currents[:, neuron_id],
        "spike_times": np.where(self.spikes[:, neuron_id] > 0)[0],
    }

spike_times(neuron_id)

Timesteps when a neuron spiked.

Source code in src/sc_neurocore/debug/tracer.py
71
72
73
def spike_times(self, neuron_id: int) -> np.ndarray:
    """Timesteps when a neuron spiked."""
    return np.where(self.spikes[:, neuron_id] > 0)[0]

population_spikes(pop_label)

Spike matrix for one population.

Source code in src/sc_neurocore/debug/tracer.py
75
76
77
78
79
80
def population_spikes(self, pop_label: str) -> np.ndarray:
    """Spike matrix for one population."""
    for label, (start, end) in zip(self.population_labels, self.population_ranges):
        if label == pop_label:
            return self.spikes[:, start:end]
    raise ValueError(f"Population '{pop_label}' not found")

Analyzer

sc_neurocore.debug.analyzer

Analyze execution traces to debug SNN behavior.

  • find_divergence: compare two traces, find first timestep where spikes differ
  • causal_chain: trace backward from a spike to find which input spikes caused it
  • spike_diff: summary of differences between two traces

DivergencePoint dataclass

First point where two traces diverge.

Source code in src/sc_neurocore/debug/analyzer.py
24
25
26
27
28
29
30
31
32
33
34
@dataclass
class DivergencePoint:
    """First point where two traces diverge."""

    timestep: int
    neuron_id: int
    trace_a_spike: int
    trace_b_spike: int
    trace_a_voltage: float
    trace_b_voltage: float
    voltage_diff: float

CausalEvent dataclass

One event in a causal spike chain.

Source code in src/sc_neurocore/debug/analyzer.py
37
38
39
40
41
42
43
44
45
@dataclass
class CausalEvent:
    """One event in a causal spike chain."""

    timestep: int
    neuron_id: int
    input_current: float
    voltage: float
    spiked: bool

find_divergence(trace_a, trace_b)

Find the first timestep where two traces produce different spikes.

Useful for comparing ANN-converted SNN vs directly-trained SNN, or Python simulation vs hardware output.

Returns None if traces are identical.

Source code in src/sc_neurocore/debug/analyzer.py
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
def find_divergence(
    trace_a: ExecutionTrace,
    trace_b: ExecutionTrace,
) -> DivergencePoint | None:
    """Find the first timestep where two traces produce different spikes.

    Useful for comparing ANN-converted SNN vs directly-trained SNN,
    or Python simulation vs hardware output.

    Returns None if traces are identical.
    """
    n_steps = min(trace_a.n_steps, trace_b.n_steps)
    n_neurons = min(trace_a.n_neurons, trace_b.n_neurons)

    for t in range(n_steps):
        for n in range(n_neurons):
            if trace_a.spikes[t, n] != trace_b.spikes[t, n]:
                return DivergencePoint(
                    timestep=t,
                    neuron_id=n,
                    trace_a_spike=int(trace_a.spikes[t, n]),
                    trace_b_spike=int(trace_b.spikes[t, n]),
                    trace_a_voltage=float(trace_a.voltages[t, n]),
                    trace_b_voltage=float(trace_b.voltages[t, n]),
                    voltage_diff=abs(float(trace_a.voltages[t, n]) - float(trace_b.voltages[t, n])),
                )
    return None

causal_chain(trace, neuron_id, timestep, max_depth=10)

Trace backward from a spike to find causal input events.

Starting from neuron_id at timestep, finds the chain of spikes that contributed current to this neuron in preceding timesteps.

Parameters

trace : ExecutionTrace neuron_id : int Target neuron. timestep : int Timestep of the spike to explain. max_depth : int Maximum backward steps to trace.

Returns

list of CausalEvent Causal chain from target backward to inputs.

Source code in src/sc_neurocore/debug/analyzer.py
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
def causal_chain(
    trace: ExecutionTrace,
    neuron_id: int,
    timestep: int,
    max_depth: int = 10,
) -> list[CausalEvent]:
    """Trace backward from a spike to find causal input events.

    Starting from neuron_id at timestep, finds the chain of spikes
    that contributed current to this neuron in preceding timesteps.

    Parameters
    ----------
    trace : ExecutionTrace
    neuron_id : int
        Target neuron.
    timestep : int
        Timestep of the spike to explain.
    max_depth : int
        Maximum backward steps to trace.

    Returns
    -------
    list of CausalEvent
        Causal chain from target backward to inputs.
    """
    chain = []

    # Start with the target event
    chain.append(
        CausalEvent(
            timestep=timestep,
            neuron_id=neuron_id,
            input_current=float(trace.currents[timestep, neuron_id]),
            voltage=float(trace.voltages[timestep, neuron_id]),
            spiked=bool(trace.spikes[timestep, neuron_id]),
        )
    )

    # Trace backward: at each step, find neurons that spiked and
    # contributed current to the current target
    current_targets = {neuron_id}
    for depth in range(1, max_depth + 1):
        t = timestep - depth
        if t < 0:
            break

        # Find all neurons that spiked at time t
        spiking = np.where(trace.spikes[t] > 0)[0]
        if len(spiking) == 0:
            continue

        # Any spiking neuron could have contributed current to our targets
        # (we don't have the connectivity here, so we report all spikers
        # that temporally precede the target)
        for n in spiking:
            chain.append(
                CausalEvent(
                    timestep=t,
                    neuron_id=int(n),
                    input_current=float(trace.currents[t, n]),
                    voltage=float(trace.voltages[t, n]),
                    spiked=True,
                )
            )

        # Update targets for next depth
        current_targets = set(spiking.tolist())

    return chain

spike_diff(trace_a, trace_b)

Summary of spike differences between two traces.

Returns

dict with keys: total_mismatches: int mismatch_rate: float (fraction of timestep*neuron pairs) first_divergence: DivergencePoint or None per_neuron_mismatches: ndarray

Source code in src/sc_neurocore/debug/analyzer.py
 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
def spike_diff(
    trace_a: ExecutionTrace,
    trace_b: ExecutionTrace,
) -> dict:
    """Summary of spike differences between two traces.

    Returns
    -------
    dict with keys:
        total_mismatches: int
        mismatch_rate: float (fraction of timestep*neuron pairs)
        first_divergence: DivergencePoint or None
        per_neuron_mismatches: ndarray
    """
    n_steps = min(trace_a.n_steps, trace_b.n_steps)
    n_neurons = min(trace_a.n_neurons, trace_b.n_neurons)

    diff = trace_a.spikes[:n_steps, :n_neurons] != trace_b.spikes[:n_steps, :n_neurons]
    total = int(diff.sum())
    per_neuron = diff.sum(axis=0)

    return {
        "total_mismatches": total,
        "mismatch_rate": total / max(n_steps * n_neurons, 1),
        "first_divergence": find_divergence(trace_a, trace_b),
        "per_neuron_mismatches": per_neuron,
    }