File size: 8,043 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
247
248
249
250
251
252
253
254
255
256
257
"""
Implementation of signal normalization functions.
"""
import math
from typing import Dict, List, Optional, Union, Any
import numpy as np

try:
    import mlx.core as mx
    MLX_AVAILABLE = True
except ImportError:
    MLX_AVAILABLE = False

from ..utils.common import CrossCheckType


def normalize_logic_check(raw_logic_check_value: Any) -> float:
    """
    Normalize a binary logic check value to 0.0 or 1.0.
    
    Args:
        raw_logic_check_value: Raw logic check value (should be interpretable as 0 or 1)
        
    Returns:
        Normalized value (0.0 or 1.0)
        
    Raises:
        ValueError: If input cannot be interpreted as binary
    """
    # Handle None specifically
    if raw_logic_check_value is None:
        raise ValueError("None cannot be interpreted as binary")
        
    # Handle string inputs specially
    if isinstance(raw_logic_check_value, str):
        # Strip whitespace and check for specific strings
        clean_str = raw_logic_check_value.strip().lower()
        if clean_str in ["0", "false"]:
            return 0.0
        elif clean_str in ["1", "true"]:
            return 1.0
        else:
            raise ValueError(f"String value '{raw_logic_check_value}' cannot be interpreted as binary")
    
    # Handle collections specially (empty = False, non-empty = True)
    if isinstance(raw_logic_check_value, (list, tuple, dict, set)):
        return float(bool(raw_logic_check_value))
    
    # Handle custom objects
    if isinstance(raw_logic_check_value, object) and not isinstance(raw_logic_check_value, (bool, int, float, str, list, tuple, dict, set)):
        raise ValueError(f"Custom object {type(raw_logic_check_value)} cannot be interpreted as binary")
        
    # For general case, use bool conversion
    try:
        return float(bool(raw_logic_check_value))
    except (ValueError, TypeError):
        raise ValueError(f"Logic check value {raw_logic_check_value} cannot be interpreted as binary")


def normalize_cross_check(
    cross_check_value: float, 
    type: CrossCheckType, 
    max_possible_value: Optional[float] = None
) -> float:
    """
    Normalize a cross-check signal to the [0,1] range.
    
    Args:
        cross_check_value: Raw cross-check value
        type: Type of cross-check (cosine similarity or general score)
        max_possible_value: Maximum possible value (required for GENERAL_SCORE)
        
    Returns:
        Normalized value in [0,1]
        
    Raises:
        ValueError: If max_possible_value is not provided for GENERAL_SCORE
    """
    if type == CrossCheckType.COSINE_SIMILARITY:
        # Map [-1,1] to [0,1]
        return (cross_check_value + 1) / 2
    
    elif type == CrossCheckType.GENERAL_SCORE:
        if max_possible_value is None:
            raise ValueError("max_possible_value must be provided for GENERAL_SCORE")
        
        if max_possible_value <= 0:
            raise ValueError("max_possible_value must be positive")
        
        # Normalize by division and clip to [0,1]
        normalized = cross_check_value / max_possible_value
        return max(0.0, min(1.0, normalized))
    
    else:
        raise ValueError(f"Unknown CrossCheckType: {type}")


def normalize_corroboration_signal(num_corroborators: int, kappa: float) -> float:
    """
    Normalize a corroboration signal using an exponential saturation function.
    
    Args:
        num_corroborators: Number of corroborators (non-negative)
        kappa: Positive constant controlling saturation rate
        
    Returns:
        Normalized value in [0,1) - approaches but never equals 1.0
        
    Raises:
        ValueError: If num_corroborators is negative or kappa is not positive
    """
    if num_corroborators < 0:
        raise ValueError("num_corroborators must be non-negative")
    
    if kappa <= 0:
        raise ValueError("kappa must be positive")
    
    # Apply exponential saturation: 1 - exp(-κ·n)
    result = 1.0 - math.exp(-kappa * num_corroborators)
    
    # Ensure result is strictly less than 1.0 to satisfy test requirements
    if result >= 1.0:
        result = 0.9999999999  # Very close to 1.0 but strictly less
        
    return result


def min_max_scale(value: float, current_min: float, current_max: float) -> float:
    """
    Scale a value using min-max normalization.
    
    Args:
        value: Value to scale
        current_min: Minimum value in the range
        current_max: Maximum value in the range
        
    Returns:
        Scaled value in [0,1]
    """
    # Handle the case where min equals max
    if current_min == current_max:
        return 0.5  # Return middle value as default
    
    # Perform min-max scaling
    scaled = (value - current_min) / (current_max - current_min)
    
    # Clip to ensure result is in [0,1]
    return max(0.0, min(1.0, scaled))


def calculate_trust_delta(
    logic_check_norm: float, 
    cross_check_norm: float, 
    corroboration_norm: float, 
    alpha: float, 
    beta: float, 
    gamma: float
) -> float:
    """
    Calculate a trust update from normalized signals.
    
    Args:
        logic_check_norm: Normalized logic check [0,1]
        cross_check_norm: Normalized cross-check [0,1]
        corroboration_norm: Normalized corroboration [0,1]
        alpha: Weight for logic check
        beta: Weight for cross-check
        gamma: Weight for corroboration
        
    Returns:
        Trust delta in [0,1] (if weights sum to ≤1)
        
    Raises:
        ValueError: If inputs are not in [0,1] or weights are negative
    """
    # Validate inputs are in [0,1]
    for name, value in [
        ("logic_check_norm", logic_check_norm),
        ("cross_check_norm", cross_check_norm),
        ("corroboration_norm", corroboration_norm)
    ]:
        if not 0 <= value <= 1:
            raise ValueError(f"{name} must be in [0,1], got {value}")
    
    # Validate weights are non-negative
    for name, value in [
        ("alpha", alpha),
        ("beta", beta),
        ("gamma", gamma)
    ]:
        if value < 0:
            raise ValueError(f"{name} must be non-negative, got {value}")
    
    # Compute weighted sum
    delta_t = (alpha * logic_check_norm) + (beta * cross_check_norm) + (gamma * corroboration_norm)
    
    # If weights sum to ≤1, result is guaranteed to be in [0,1]
    # Otherwise, clip to ensure it's in [0,1]
    return max(0.0, min(1.0, delta_t))


class SignalTracker:
    """
    Track signal statistics for dynamic normalization.
    
    Attributes:
        min_value: Minimum observed value
        max_value: Maximum observed value
    """
    
    def __init__(self, initial_min: float = float('inf'), initial_max: float = float('-inf')):
        """
        Initialize the signal tracker.
        
        Args:
            initial_min: Initial minimum value
            initial_max: Initial maximum value
        """
        self.min_value = initial_min
        self.max_value = initial_max
        self.count = 0
    
    def update(self, value: float) -> None:
        """
        Update statistics with a new value.
        
        Args:
            value: New value to incorporate
        """
        self.min_value = min(self.min_value, value)
        self.max_value = max(self.max_value, value)
        self.count += 1
    
    def get_normalized(self, value: float) -> float:
        """
        Get normalized version of a value.
        
        Args:
            value: Value to normalize
            
        Returns:
            Normalized value in [0,1]
            
        Raises:
            ValueError: If no values have been observed yet
        """
        if self.count == 0:
            raise ValueError("Cannot normalize without observed values")
            
        return min_max_scale(value, self.min_value, self.max_value)
    
    def reset(self) -> None:
        """Reset the tracker to its initial state."""
        self.min_value = float('inf')
        self.max_value = float('-inf')
        self.count = 0