File size: 8,590 Bytes
1e12712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
"""
Spike-Timing Dependent Plasticity (STDP) implementation.

STDP is a biological learning rule where:
- If pre-synaptic spike comes before post-synaptic spike: strengthen connection
- If post-synaptic spike comes before pre-synaptic spike: weaken connection
- The amount of change depends on the time difference
"""

import numpy as np
from typing import List, Tuple, Optional, Callable
import logging

logger = logging.getLogger("snow_spike.advanced_learning.stdp")


class STDPWindow:
    """
    Defines the STDP learning window shape.
    
    Classic STDP has an asymmetric window:
    - Positive change (LTP) for pre-before-post
    - Negative change (LTD) for post-before-pre
    """
    
    def __init__(self,
                 tau_plus: float = 20.0,    # Time constant for LTP
                 tau_minus: float = 20.0,   # Time constant for LTD
                 A_plus: float = 0.01,      # Max LTP amplitude
                 A_minus: float = 0.01):    # Max LTD amplitude
        """
        Initialize STDP window parameters.
        
        Args:
            tau_plus: Time constant for potentiation (ms)
            tau_minus: Time constant for depression (ms)
            A_plus: Maximum potentiation
            A_minus: Maximum depression
        """
        self.tau_plus = tau_plus
        self.tau_minus = tau_minus
        self.A_plus = A_plus
        self.A_minus = A_minus
    
    def compute_weight_change(self, dt: float) -> float:
        """
        Compute weight change based on spike timing difference.
        
        Args:
            dt: Time difference (t_post - t_pre) in ms
                Positive dt: pre comes before post (potentiation)
                Negative dt: post comes before pre (depression)
                
        Returns:
            Weight change amount
        """
        if dt > 0:
            # Pre before post: potentiation
            return self.A_plus * np.exp(-dt / self.tau_plus)
        else:
            # Post before pre: depression
            return -self.A_minus * np.exp(dt / self.tau_minus)
    
    def plot_window(self, dt_range: Tuple[float, float] = (-50, 50)) -> Tuple[List[float], List[float]]:
        """Get data for plotting the STDP window."""
        dts = np.linspace(dt_range[0], dt_range[1], 1000)
        changes = [self.compute_weight_change(dt) for dt in dts]
        return dts.tolist(), changes


class STDPRule:
    """
    Implements STDP learning rule for synaptic weight updates.
    """
    
    def __init__(self,
                 window: Optional[STDPWindow] = None,
                 learning_rate: float = 1.0,
                 weight_min: float = 0.0,
                 weight_max: float = 1.0):
        """
        Initialize STDP rule.
        
        Args:
            window: STDP window function
            learning_rate: Global learning rate multiplier
            weight_min: Minimum allowed weight
            weight_max: Maximum allowed weight
        """
        self.window = window or STDPWindow()
        self.learning_rate = learning_rate
        self.weight_min = weight_min
        self.weight_max = weight_max
        
        # Spike history for timing calculations
        self.pre_spike_times = {}   # {neuron_id: [spike_times]}
        self.post_spike_times = {}  # {neuron_id: [spike_times]}
    
    def record_spike(self, neuron_id: int, time: float, is_pre: bool = True):
        """
        Record a spike for STDP calculations.
        
        Args:
            neuron_id: ID of the spiking neuron
            time: Time of spike (ms)
            is_pre: True for pre-synaptic, False for post-synaptic
        """
        if is_pre:
            if neuron_id not in self.pre_spike_times:
                self.pre_spike_times[neuron_id] = []
            self.pre_spike_times[neuron_id].append(time)
        else:
            if neuron_id not in self.post_spike_times:
                self.post_spike_times[neuron_id] = []
            self.post_spike_times[neuron_id].append(time)
    
    def compute_stdp_update(self,
                           pre_id: int,
                           post_id: int,
                           current_weight: float,
                           time_window: float = 100.0) -> float:
        """
        Compute STDP weight update for a synapse.
        
        Args:
            pre_id: Pre-synaptic neuron ID
            post_id: Post-synaptic neuron ID
            current_weight: Current synaptic weight
            time_window: Consider spikes within this time window (ms)
            
        Returns:
            Weight change
        """
        # Get spike times
        pre_times = self.pre_spike_times.get(pre_id, [])
        post_times = self.post_spike_times.get(post_id, [])
        
        if not pre_times or not post_times:
            return 0.0
        
        # Compute all spike time differences within window
        weight_change = 0.0
        
        for t_post in post_times[-10:]:  # Consider last 10 post spikes
            for t_pre in pre_times[-10:]:  # Consider last 10 pre spikes
                dt = t_post - t_pre
                
                # Only consider pairs within time window
                if abs(dt) < time_window:
                    dw = self.window.compute_weight_change(dt)
                    weight_change += dw
        
        # Apply learning rate
        weight_change *= self.learning_rate
        
        # Apply weight bounds
        new_weight = current_weight + weight_change
        new_weight = np.clip(new_weight, self.weight_min, self.weight_max)
        
        return new_weight - current_weight
    
    def clear_old_spikes(self, current_time: float, retention_window: float = 1000.0):
        """Remove old spikes outside retention window."""
        cutoff_time = current_time - retention_window
        
        # Clean pre-synaptic spikes
        for neuron_id in list(self.pre_spike_times.keys()):
            self.pre_spike_times[neuron_id] = [
                t for t in self.pre_spike_times[neuron_id] if t > cutoff_time
            ]
            if not self.pre_spike_times[neuron_id]:
                del self.pre_spike_times[neuron_id]
        
        # Clean post-synaptic spikes
        for neuron_id in list(self.post_spike_times.keys()):
            self.post_spike_times[neuron_id] = [
                t for t in self.post_spike_times[neuron_id] if t > cutoff_time
            ]
            if not self.post_spike_times[neuron_id]:
                del self.post_spike_times[neuron_id]


def apply_stdp(weights: np.ndarray,
              pre_spikes: List[Tuple[int, float]],
              post_spikes: List[Tuple[int, float]],
              stdp_rule: STDPRule) -> np.ndarray:
    """
    Apply STDP to a weight matrix.
    
    Args:
        weights: Weight matrix (pre x post)
        pre_spikes: List of (neuron_id, spike_time) for pre-synaptic
        post_spikes: List of (neuron_id, spike_time) for post-synaptic
        stdp_rule: STDP rule to apply
        
    Returns:
        Updated weight matrix
    """
    # Record all spikes
    for neuron_id, time in pre_spikes:
        stdp_rule.record_spike(neuron_id, time, is_pre=True)
    
    for neuron_id, time in post_spikes:
        stdp_rule.record_spike(neuron_id, time, is_pre=False)
    
    # Update weights
    updated_weights = weights.copy()
    
    for i in range(weights.shape[0]):  # Pre-synaptic
        for j in range(weights.shape[1]):  # Post-synaptic
            dw = stdp_rule.compute_stdp_update(i, j, weights[i, j])
            updated_weights[i, j] += dw
    
    return updated_weights


def spike_timing_dependent_update(pre_spike: int,
                                post_spike: int,
                                weight: float,
                                dt: float,
                                window: Optional[STDPWindow] = None) -> float:
    """
    Simple STDP update for a single synapse.
    
    Args:
        pre_spike: Pre-synaptic spike (1 or 0)
        post_spike: Post-synaptic spike (1 or 0)
        weight: Current weight
        dt: Time step
        window: STDP window (optional)
        
    Returns:
        Updated weight
    """
    if not window:
        window = STDPWindow()
    
    # Only update if both neurons spiked
    if pre_spike != 0 and post_spike != 0:
        # Simplified: assume post comes slightly after pre
        timing_diff = dt * (1 if pre_spike * post_spike > 0 else -1)
        dw = window.compute_weight_change(timing_diff)
        return np.clip(weight + dw, 0, 1)
    
    return weight