""" 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