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