File size: 7,619 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
"""
Hill function implementation for corroboration signals.

The Hill function models cooperative effects where multiple pieces of
evidence work together to produce a stronger signal than they would individually.
"""

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

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


class HillFunction:
    """
    Implements the Hill function for modeling corroboration signals.
    
    Hill equation: y = (x^n) / (K^n + x^n)
    Where:
    - x: Input signal (evidence strength)
    - n: Hill coefficient (cooperativity)
    - K: Half-maximal constant
    - y: Output response
    """
    
    def __init__(self,
                 n: float = 2.0,        # Hill coefficient
                 K: float = 0.5,        # Half-maximal constant
                 y_max: float = 1.0):   # Maximum response
        """
        Initialize Hill function.
        
        Args:
            n: Hill coefficient (>1 for positive cooperativity)
            K: Concentration for half-maximal response
            y_max: Maximum possible response
        """
        self.n = n
        self.K = K
        self.y_max = y_max
    
    def compute(self, x: float) -> float:
        """
        Compute Hill function output.
        
        Args:
            x: Input signal strength
            
        Returns:
            Output response
        """
        if x < 0:
            return 0.0
        
        x_n = np.power(x, self.n)
        K_n = np.power(self.K, self.n)
        
        return self.y_max * x_n / (K_n + x_n)
    
    def compute_batch(self, x_values: np.ndarray) -> np.ndarray:
        """Compute Hill function for multiple inputs."""
        x_values = np.maximum(x_values, 0)  # Ensure non-negative
        
        x_n = np.power(x_values, self.n)
        K_n = np.power(self.K, self.n)
        
        return self.y_max * x_n / (K_n + x_n)
    
    def inverse(self, y: float) -> float:
        """
        Compute inverse Hill function.
        
        Given output y, find input x.
        """
        if y <= 0:
            return 0.0
        if y >= self.y_max:
            return float('inf')
        
        # Rearrange: x = K * (y/(y_max - y))^(1/n)
        ratio = y / (self.y_max - y)
        return self.K * np.power(ratio, 1.0 / self.n)
    
    def sensitivity(self, x: float) -> float:
        """
        Compute sensitivity (derivative) at given input.
        
        This tells us how responsive the system is at this point.
        """
        x_n = np.power(x, self.n)
        K_n = np.power(self.K, self.n)
        
        numerator = self.n * self.y_max * K_n * np.power(x, self.n - 1)
        denominator = np.power(K_n + x_n, 2)
        
        return numerator / denominator if denominator > 0 else 0


def corroboration_signal(evidence_strengths: List[float],
                        hill_func: Optional[HillFunction] = None,
                        combination_method: str = "sum") -> float:
    """
    Compute corroboration signal from multiple evidence sources.
    
    Args:
        evidence_strengths: List of evidence strength values
        hill_func: Hill function to apply
        combination_method: How to combine evidence ("sum", "product", "max")
        
    Returns:
        Corroboration signal strength
    """
    if not evidence_strengths:
        return 0.0
    
    if not hill_func:
        hill_func = HillFunction()
    
    # Combine evidence
    if combination_method == "sum":
        combined = sum(evidence_strengths)
    elif combination_method == "product":
        combined = np.prod(evidence_strengths)
    elif combination_method == "max":
        combined = max(evidence_strengths)
    else:
        combined = np.mean(evidence_strengths)
    
    # Apply Hill function
    return hill_func.compute(combined)


def evidence_accumulation(evidence_stream: List[Tuple[float, float]],
                         current_time: float,
                         time_window: float = 100.0,
                         hill_func: Optional[HillFunction] = None) -> float:
    """
    Accumulate evidence over time with Hill function response.
    
    Args:
        evidence_stream: List of (timestamp, evidence_value) tuples
        current_time: Current time
        time_window: Time window for evidence consideration
        hill_func: Hill function for response
        
    Returns:
        Accumulated evidence signal
    """
    if not hill_func:
        hill_func = HillFunction(n=2.5, K=0.3)  # Steep response
    
    # Filter evidence within time window
    recent_evidence = [
        value for timestamp, value in evidence_stream
        if current_time - timestamp <= time_window
    ]
    
    if not recent_evidence:
        return 0.0
    
    # Weight by recency (more recent = higher weight)
    weighted_evidence = []
    for timestamp, value in evidence_stream:
        if current_time - timestamp <= time_window:
            recency_weight = 1.0 - (current_time - timestamp) / time_window
            weighted_evidence.append(value * recency_weight)
    
    # Sum weighted evidence
    total_evidence = sum(weighted_evidence)
    
    # Apply Hill function
    return hill_func.compute(total_evidence)


class CorroborationNetwork:
    """
    Network of neurons that use Hill functions for corroboration.
    """
    
    def __init__(self,
                 num_neurons: int,
                 hill_n: float = 2.0,
                 hill_K: float = 0.5):
        """
        Initialize corroboration network.
        
        Args:
            num_neurons: Number of neurons
            hill_n: Hill coefficient for all neurons
            hill_K: Half-maximal constant
        """
        self.num_neurons = num_neurons
        self.hill_functions = [
            HillFunction(n=hill_n, K=hill_K) for _ in range(num_neurons)
        ]
        
        # Evidence buffers for each neuron
        self.evidence_buffers: List[List[float]] = [[] for _ in range(num_neurons)]
        
    def add_evidence(self, neuron_id: int, evidence: float):
        """Add evidence to a neuron's buffer."""
        if 0 <= neuron_id < self.num_neurons:
            self.evidence_buffers[neuron_id].append(evidence)
            # Keep only recent evidence (last 10 entries)
            if len(self.evidence_buffers[neuron_id]) > 10:
                self.evidence_buffers[neuron_id].pop(0)
    
    def compute_responses(self) -> List[float]:
        """Compute Hill function responses for all neurons."""
        responses = []
        
        for i in range(self.num_neurons):
            if self.evidence_buffers[i]:
                # Use sum of recent evidence
                total_evidence = sum(self.evidence_buffers[i])
                response = self.hill_functions[i].compute(total_evidence)
            else:
                response = 0.0
            
            responses.append(response)
        
        return responses
    
    def get_corroboration_matrix(self) -> np.ndarray:
        """
        Compute pairwise corroboration between neurons.
        
        Returns:
            Matrix where element (i,j) is corroboration between neurons i and j
        """
        matrix = np.zeros((self.num_neurons, self.num_neurons))
        responses = self.compute_responses()
        
        for i in range(self.num_neurons):
            for j in range(self.num_neurons):
                if i != j:
                    # Corroboration is product of responses
                    matrix[i, j] = responses[i] * responses[j]
        
        return matrix