ruvector_tiny_dancer_core/
uncertainty.rs

1//! Uncertainty quantification with conformal prediction
2
3/// Uncertainty estimator for routing decisions
4pub struct UncertaintyEstimator {
5    /// Calibration quantile for conformal prediction
6    calibration_quantile: f32,
7}
8
9impl UncertaintyEstimator {
10    /// Create a new uncertainty estimator
11    pub fn new() -> Self {
12        Self {
13            calibration_quantile: 0.9, // 90% confidence
14        }
15    }
16
17    /// Create with custom calibration quantile
18    pub fn with_quantile(quantile: f32) -> Self {
19        Self {
20            calibration_quantile: quantile,
21        }
22    }
23
24    /// Estimate uncertainty for a prediction
25    ///
26    /// Uses a simple heuristic based on:
27    /// 1. Distance from decision boundary (0.5)
28    /// 2. Feature variance
29    /// 3. Model confidence
30    pub fn estimate(&self, _features: &[f32], prediction: f32) -> f32 {
31        // Distance from decision boundary (0.5)
32        let boundary_distance = (prediction - 0.5).abs();
33
34        // Higher uncertainty when close to boundary
35        let boundary_uncertainty = 1.0 - (boundary_distance * 2.0);
36
37        // Clip to [0, 1]
38        boundary_uncertainty.max(0.0).min(1.0)
39    }
40
41    /// Calibrate the estimator with a set of predictions and outcomes
42    pub fn calibrate(&mut self, _predictions: &[f32], _outcomes: &[bool]) {
43        // TODO: Implement conformal prediction calibration
44        // This would compute the quantile of non-conformity scores
45    }
46
47    /// Get the calibration quantile
48    pub fn calibration_quantile(&self) -> f32 {
49        self.calibration_quantile
50    }
51}
52
53impl Default for UncertaintyEstimator {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn test_uncertainty_estimation() {
65        let estimator = UncertaintyEstimator::new();
66
67        // High confidence prediction should have low uncertainty
68        let features = vec![0.5; 10];
69        let high_conf = estimator.estimate(&features, 0.95);
70        assert!(high_conf < 0.5);
71
72        // Low confidence prediction should have high uncertainty
73        let low_conf = estimator.estimate(&features, 0.52);
74        assert!(low_conf > 0.5);
75    }
76
77    #[test]
78    fn test_boundary_uncertainty() {
79        let estimator = UncertaintyEstimator::new();
80        let features = vec![0.5; 10];
81
82        // Prediction exactly at boundary (0.5) should have maximum uncertainty
83        let boundary = estimator.estimate(&features, 0.5);
84        assert!((boundary - 1.0).abs() < 0.01);
85    }
86}