File size: 1,907 Bytes
6811ecf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Fallback implementation of Sundew gating algorithms.
Replace with actual sundew-algorithms package for production.
"""
import math


def significance_score(
    features: dict,
    w_mag: float = 0.35,
    w_ano: float = 0.4,
    w_ctx: float = 0.15,
    w_urg: float = 0.1
) -> float:
    """
    Compute significance score for a signal window.

    Args:
        features: Dict with keys: magnitude, anomaly_score, context_relevance, urgency
        w_mag: Weight for magnitude
        w_ano: Weight for anomaly score
        w_ctx: Weight for context relevance
        w_urg: Weight for urgency

    Returns:
        Significance score in [0, 1]
    """
    score = (
        w_mag * min(features.get("magnitude", 0.0) / 100.0, 1.0) +
        w_ano * features.get("anomaly_score", 0.0) +
        w_ctx * features.get("context_relevance", 0.0) +
        w_urg * features.get("urgency", 0.0)
    )
    return max(0.0, min(1.0, score))


def gate_probability_with_hysteresis(
    significance: float,
    threshold: float = 0.6,
    temperature: float = 0.1,
    last_activation: bool = False
) -> float:
    """
    Convert significance to gate probability with hysteresis.

    Args:
        significance: Significance score in [0, 1]
        threshold: Base threshold for gating
        temperature: Softness of the gate (0 = hard threshold)
        last_activation: Whether previous window was active (for hysteresis)

    Returns:
        Probability of keeping the window in [0, 1]
    """
    # Apply hysteresis: lower threshold if last was active
    effective_threshold = threshold - (0.1 if last_activation else 0.0)

    if temperature <= 0:
        # Hard threshold
        return 1.0 if significance >= effective_threshold else 0.0

    # Soft threshold using sigmoid
    logit = (significance - effective_threshold) / temperature
    prob = 1.0 / (1.0 + math.exp(-logit))

    return prob