spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / evaluator / stats.rs
| 1 | use crate::evaluator::metrics::LatencyDistribution; |
| 2 | use serde::{Deserialize, Serialize}; |
| 3 | |
| 4 | #[derive(Debug, Clone)] |
| 5 | pub struct FastPrng { |
| 6 | s: [u64; 4], |
| 7 | } |
| 8 | |
| 9 | impl FastPrng { |
| 10 | pub fn new(seed: u64) -> Self { |
| 11 | let mut sm = seed; |
| 12 | let mut next_u64 = || { |
| 13 | sm = sm.wrapping_add(0x9e3779b97f4a7c15); |
| 14 | let mut z = sm; |
| 15 | z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); |
| 16 | z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); |
| 17 | z ^ (z >> 31) |
| 18 | }; |
| 19 | let s0 = next_u64(); |
| 20 | let s1 = next_u64(); |
| 21 | let s2 = next_u64(); |
| 22 | let s3 = next_u64(); |
| 23 | Self { |
| 24 | s: [ |
| 25 | if s0 == 0 { 1 } else { s0 }, |
| 26 | if s1 == 0 { 2 } else { s1 }, |
| 27 | if s2 == 0 { 3 } else { s2 }, |
| 28 | if s3 == 0 { 4 } else { s3 }, |
| 29 | ], |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | #[inline] |
| 34 | pub fn next_u64(&mut self) -> u64 { |
| 35 | let res = (self.s[0].wrapping_add(self.s[3])) |
| 36 | .rotate_left(23) |
| 37 | .wrapping_add(self.s[0]); |
| 38 | let t = self.s[1] << 17; |
| 39 | self.s[2] ^= self.s[0]; |
| 40 | self.s[3] ^= self.s[1]; |
| 41 | self.s[1] ^= self.s[2]; |
| 42 | self.s[0] ^= self.s[3]; |
| 43 | self.s[2] ^= t; |
| 44 | self.s[3] = self.s[3].rotate_left(45); |
| 45 | res |
| 46 | } |
| 47 | |
| 48 | #[inline] |
| 49 | pub fn gen_range(&mut self, upper: usize) -> usize { |
| 50 | if upper <= 1 { |
| 51 | return 0; |
| 52 | } |
| 53 | (self.next_u64() as usize) % upper |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 58 | pub struct PairedSample { |
| 59 | pub iteration: usize, |
| 60 | pub seed: u64, |
| 61 | pub parent_metric: f64, |
| 62 | pub candidate_metric: f64, |
| 63 | pub delta: f64, |
| 64 | } |
| 65 | |
| 66 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 67 | pub struct BootstrapEstimate { |
| 68 | pub sample_size: usize, |
| 69 | pub resamples_count: usize, |
| 70 | pub observed_parent_mean: f64, |
| 71 | pub observed_candidate_mean: f64, |
| 72 | pub observed_delta_mean: f64, |
| 73 | pub delta_pct: f64, |
| 74 | pub ci_99_lower: f64, |
| 75 | pub ci_99_upper: f64, |
| 76 | pub p_value: f64, |
| 77 | pub is_statistically_significant: bool, |
| 78 | } |
| 79 | |
| 80 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 81 | pub struct TailNonInferiorityResult { |
| 82 | pub percentile: f64, |
| 83 | pub parent_val: f64, |
| 84 | pub candidate_val: f64, |
| 85 | pub observed_degradation_pct: f64, |
| 86 | pub ci_95_upper_pct: f64, |
| 87 | pub non_inferiority_margin_pct: f64, |
| 88 | pub passes_non_inferiority: bool, |
| 89 | } |
| 90 | |
| 91 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 92 | pub struct FishersExactResult { |
| 93 | pub parent_successes: u64, |
| 94 | pub parent_failures: u64, |
| 95 | pub candidate_successes: u64, |
| 96 | pub candidate_failures: u64, |
| 97 | pub parent_rate: f64, |
| 98 | pub candidate_rate: f64, |
| 99 | pub p_value_two_sided: f64, |
| 100 | pub p_value_greater: f64, |
| 101 | pub p_value_less: f64, |
| 102 | pub is_significant: bool, |
| 103 | } |
| 104 | |
| 105 | pub struct StatisticalEngine; |
| 106 | |
| 107 | impl StatisticalEngine { |
| 108 | pub const DEFAULT_BOOTSTRAP_RESAMPLES: usize = 10_000; |
| 109 | pub const DEFAULT_PAIRED_ITERATIONS: usize = 30; |
| 110 | |
| 111 | pub fn bootstrap_paired_comparison( |
| 112 | parent_samples: &[f64], |
| 113 | candidate_samples: &[f64], |
| 114 | resamples_count: usize, |
| 115 | seed: Option<u64>, |
| 116 | ) -> Result<BootstrapEstimate, String> { |
| 117 | let m = parent_samples.len(); |
| 118 | if m == 0 || m != candidate_samples.len() { |
| 119 | return Err(format!( |
| 120 | "Invalid paired sample lengths: parent={}, candidate={}", |
| 121 | m, |
| 122 | candidate_samples.len() |
| 123 | )); |
| 124 | } |
| 125 | |
| 126 | let mut diffs = Vec::with_capacity(m); |
| 127 | let mut sum_parent = 0.0; |
| 128 | let mut sum_candidate = 0.0; |
| 129 | let mut sum_diff = 0.0; |
| 130 | |
| 131 | for i in 0..m { |
| 132 | let p = parent_samples[i]; |
| 133 | let c = candidate_samples[i]; |
| 134 | let d = c - p; |
| 135 | diffs.push(d); |
| 136 | sum_parent += p; |
| 137 | sum_candidate += c; |
| 138 | sum_diff += d; |
| 139 | } |
| 140 | |
| 141 | let observed_parent_mean = sum_parent / (m as f64); |
| 142 | let observed_candidate_mean = sum_candidate / (m as f64); |
| 143 | let observed_delta_mean = sum_diff / (m as f64); |
| 144 | |
| 145 | let delta_pct = if observed_parent_mean.abs() > 1e-9 { |
| 146 | (observed_delta_mean / observed_parent_mean) * 100.0 |
| 147 | } else { |
| 148 | 0.0 |
| 149 | }; |
| 150 | |
| 151 | let b = if resamples_count > 0 { |
| 152 | resamples_count |
| 153 | } else { |
| 154 | Self::DEFAULT_BOOTSTRAP_RESAMPLES |
| 155 | }; |
| 156 | |
| 157 | let mut prng = FastPrng::new(seed.unwrap_or(0x1337_c0d3_beef)); |
| 158 | let mut boot_means = Vec::with_capacity(b); |
| 159 | |
| 160 | for _ in 0..b { |
| 161 | let mut boot_sum = 0.0; |
| 162 | for _ in 0..m { |
| 163 | let idx = prng.gen_range(m); |
| 164 | boot_sum += diffs[idx]; |
| 165 | } |
| 166 | boot_means.push(boot_sum / (m as f64)); |
| 167 | } |
| 168 | |
| 169 | boot_means.sort_by(|a, b_val| a.partial_cmp(b_val).unwrap_or(std::cmp::Ordering::Equal)); |
| 170 | |
| 171 | let lower_idx = ((0.005 * (b as f64)).floor() as usize).min(b - 1); |
| 172 | let upper_idx = ((0.995 * (b as f64)).ceil() as usize).min(b - 1); |
| 173 | let ci_99_lower = boot_means[lower_idx]; |
| 174 | let ci_99_upper = boot_means[upper_idx]; |
| 175 | |
| 176 | let count_leq_zero = boot_means.iter().filter(|&&v| v <= 0.0).count(); |
| 177 | let count_geq_zero = boot_means.iter().filter(|&&v| v >= 0.0).count(); |
| 178 | let p_val_two_sided = |
| 179 | (2.0 * ((count_leq_zero.min(count_geq_zero) as f64) / (b as f64))).min(1.0); |
| 180 | |
| 181 | let is_statistically_significant = |
| 182 | p_val_two_sided < 0.01 && (ci_99_lower > 0.0 || ci_99_upper < 0.0); |
| 183 | |
| 184 | Ok(BootstrapEstimate { |
| 185 | sample_size: m, |
| 186 | resamples_count: b, |
| 187 | observed_parent_mean, |
| 188 | observed_candidate_mean, |
| 189 | observed_delta_mean, |
| 190 | delta_pct, |
| 191 | ci_99_lower, |
| 192 | ci_99_upper, |
| 193 | p_value: p_val_two_sided, |
| 194 | is_statistically_significant, |
| 195 | }) |
| 196 | } |
| 197 | |
| 198 | pub fn evaluate_tail_non_inferiority( |
| 199 | parent_latencies: &[f64], |
| 200 | candidate_latencies: &[f64], |
| 201 | percentile: f64, |
| 202 | margin_pct: f64, |
| 203 | resamples_count: usize, |
| 204 | seed: Option<u64>, |
| 205 | ) -> Result<TailNonInferiorityResult, String> { |
| 206 | let n_p = parent_latencies.len(); |
| 207 | let n_c = candidate_latencies.len(); |
| 208 | if n_p == 0 || n_c == 0 { |
| 209 | return Err("Latency sample vectors must not be empty".to_string()); |
| 210 | } |
| 211 | |
| 212 | let mut sorted_parent = parent_latencies.to_vec(); |
| 213 | sorted_parent.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 214 | let parent_val = LatencyDistribution::calculate_percentile(&sorted_parent, percentile); |
| 215 | |
| 216 | let mut sorted_cand = candidate_latencies.to_vec(); |
| 217 | sorted_cand.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 218 | let candidate_val = LatencyDistribution::calculate_percentile(&sorted_cand, percentile); |
| 219 | |
| 220 | let observed_degradation_pct = if parent_val > 1e-9 { |
| 221 | ((candidate_val - parent_val) / parent_val) * 100.0 |
| 222 | } else { |
| 223 | 0.0 |
| 224 | }; |
| 225 | |
| 226 | let b = if resamples_count > 0 { |
| 227 | resamples_count |
| 228 | } else { |
| 229 | Self::DEFAULT_BOOTSTRAP_RESAMPLES |
| 230 | }; |
| 231 | |
| 232 | let mut prng = FastPrng::new(seed.unwrap_or(0x42_cafe_babe)); |
| 233 | let mut degradation_samples = Vec::with_capacity(b); |
| 234 | |
| 235 | let mut boot_p = vec![0.0; n_p]; |
| 236 | let mut boot_c = vec![0.0; n_c]; |
| 237 | let paired = n_p == n_c; |
| 238 | |
| 239 | for _ in 0..b { |
| 240 | if paired { |
| 241 | for i in 0..n_p { |
| 242 | let idx = prng.gen_range(n_p); |
| 243 | boot_p[i] = parent_latencies[idx]; |
| 244 | boot_c[i] = candidate_latencies[idx]; |
| 245 | } |
| 246 | } else { |
| 247 | for i in 0..n_p { |
| 248 | boot_p[i] = parent_latencies[prng.gen_range(n_p)]; |
| 249 | } |
| 250 | for i in 0..n_c { |
| 251 | boot_c[i] = candidate_latencies[prng.gen_range(n_c)]; |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | boot_p.sort_by(|a, b_val| a.partial_cmp(b_val).unwrap_or(std::cmp::Ordering::Equal)); |
| 256 | boot_c.sort_by(|a, b_val| a.partial_cmp(b_val).unwrap_or(std::cmp::Ordering::Equal)); |
| 257 | |
| 258 | let p_val_boot = LatencyDistribution::calculate_percentile(&boot_p, percentile); |
| 259 | let c_val_boot = LatencyDistribution::calculate_percentile(&boot_c, percentile); |
| 260 | |
| 261 | let deg = if p_val_boot > 1e-9 { |
| 262 | ((c_val_boot - p_val_boot) / p_val_boot) * 100.0 |
| 263 | } else { |
| 264 | 0.0 |
| 265 | }; |
| 266 | degradation_samples.push(deg); |
| 267 | } |
| 268 | |
| 269 | degradation_samples |
| 270 | .sort_by(|a, b_val| a.partial_cmp(b_val).unwrap_or(std::cmp::Ordering::Equal)); |
| 271 | let p95_idx = ((0.95 * (b as f64)).ceil() as usize).min(b - 1); |
| 272 | let ci_95_upper_pct = degradation_samples[p95_idx]; |
| 273 | |
| 274 | let passes_non_inferiority = ci_95_upper_pct <= margin_pct; |
| 275 | |
| 276 | Ok(TailNonInferiorityResult { |
| 277 | percentile, |
| 278 | parent_val, |
| 279 | candidate_val, |
| 280 | observed_degradation_pct, |
| 281 | ci_95_upper_pct, |
| 282 | non_inferiority_margin_pct: margin_pct, |
| 283 | passes_non_inferiority, |
| 284 | }) |
| 285 | } |
| 286 | |
| 287 | pub fn fishers_exact_test( |
| 288 | parent_successes: u64, |
| 289 | parent_failures: u64, |
| 290 | candidate_successes: u64, |
| 291 | candidate_failures: u64, |
| 292 | ) -> Result<FishersExactResult, String> { |
| 293 | let a = parent_successes as f64; |
| 294 | let b = parent_failures as f64; |
| 295 | let c = candidate_successes as f64; |
| 296 | let d = candidate_failures as f64; |
| 297 | |
| 298 | let r1 = a + b; |
| 299 | let r2 = c + d; |
| 300 | let c1 = a + c; |
| 301 | let c2 = b + d; |
| 302 | let n = r1 + r2; |
| 303 | |
| 304 | if n == 0.0 { |
| 305 | return Err("Total observations in contingency table cannot be zero".to_string()); |
| 306 | } |
| 307 | |
| 308 | let parent_rate = if r1 > 0.0 { a / r1 } else { 0.0 }; |
| 309 | let candidate_rate = if r2 > 0.0 { c / r2 } else { 0.0 }; |
| 310 | |
| 311 | let max_k = r1.min(c1) as usize; |
| 312 | let min_k = (0.0f64).max(r1 + c1 - n) as usize; |
| 313 | |
| 314 | let mut ln_fact = vec![0.0f64; (n as usize) + 1]; |
| 315 | for i in 2..=n as usize { |
| 316 | ln_fact[i] = ln_fact[i - 1] + (i as f64).ln(); |
| 317 | } |
| 318 | |
| 319 | let prob_k = |k: usize| -> f64 { |
| 320 | let k_f = k as f64; |
| 321 | let log_p = ln_fact[r1 as usize] |
| 322 | + ln_fact[r2 as usize] |
| 323 | + ln_fact[c1 as usize] |
| 324 | + ln_fact[c2 as usize] |
| 325 | - ln_fact[n as usize] |
| 326 | - ln_fact[k] |
| 327 | - ln_fact[(r1 - k_f) as usize] |
| 328 | - ln_fact[(c1 - k_f) as usize] |
| 329 | - ln_fact[(r2 - c1 + k_f) as usize]; |
| 330 | log_p.exp() |
| 331 | }; |
| 332 | |
| 333 | let observed_k = a as usize; |
| 334 | let p_obs = prob_k(observed_k); |
| 335 | |
| 336 | let mut p_two_sided = 0.0; |
| 337 | let mut p_greater = 0.0; |
| 338 | let mut p_less = 0.0; |
| 339 | |
| 340 | for k in min_k..=max_k { |
| 341 | let p = prob_k(k); |
| 342 | if p <= p_obs * (1.0 + 1e-7) { |
| 343 | p_two_sided += p; |
| 344 | } |
| 345 | if k <= observed_k { |
| 346 | p_greater += p; |
| 347 | } |
| 348 | if k >= observed_k { |
| 349 | p_less += p; |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | let p_value_two_sided = p_two_sided.min(1.0); |
| 354 | let p_value_greater = p_greater.min(1.0); |
| 355 | let p_value_less = p_less.min(1.0); |
| 356 | let is_significant = p_value_two_sided < 0.05; |
| 357 | |
| 358 | Ok(FishersExactResult { |
| 359 | parent_successes, |
| 360 | parent_failures, |
| 361 | candidate_successes, |
| 362 | candidate_failures, |
| 363 | parent_rate, |
| 364 | candidate_rate, |
| 365 | p_value_two_sided, |
| 366 | p_value_greater, |
| 367 | p_value_less, |
| 368 | is_significant, |
| 369 | }) |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | #[cfg(test)] |
| 374 | mod tests { |
| 375 | use super::*; |
| 376 | |
| 377 | #[test] |
| 378 | fn test_fast_prng_distribution() { |
| 379 | let mut prng = FastPrng::new(12345); |
| 380 | let mut counts = [0usize; 10]; |
| 381 | let n = 10_000; |
| 382 | for _ in 0..n { |
| 383 | let idx = prng.gen_range(10); |
| 384 | counts[idx] += 1; |
| 385 | } |
| 386 | for count in counts.iter() { |
| 387 | assert!(*count > 800 && *count < 1200); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | #[test] |
| 392 | fn test_bootstrap_paired_identical_samples() { |
| 393 | let parent = vec![10.0; 30]; |
| 394 | let candidate = vec![10.0; 30]; |
| 395 | let res = |
| 396 | StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 1000, Some(42)) |
| 397 | .unwrap(); |
| 398 | |
| 399 | assert_eq!(res.sample_size, 30); |
| 400 | assert!((res.observed_delta_mean - 0.0).abs() < 1e-9); |
| 401 | assert!((res.delta_pct - 0.0).abs() < 1e-9); |
| 402 | assert!(!res.is_statistically_significant); |
| 403 | } |
| 404 | |
| 405 | #[test] |
| 406 | fn test_bootstrap_paired_significant_improvement() { |
| 407 | let parent = vec![ |
| 408 | 100.0, 102.0, 101.0, 99.0, 100.5, 101.2, 98.9, 100.1, 102.3, 100.8, 100.0, 102.0, |
| 409 | 101.0, 99.0, 100.5, 101.2, 98.9, 100.1, 102.3, 100.8, 100.0, 102.0, 101.0, 99.0, 100.5, |
| 410 | 101.2, 98.9, 100.1, 102.3, 100.8, |
| 411 | ]; |
| 412 | let candidate = vec![ |
| 413 | 120.0, 122.0, 121.0, 119.0, 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, 120.0, 122.0, |
| 414 | 121.0, 119.0, 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, 120.0, 122.0, 121.0, 119.0, |
| 415 | 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, |
| 416 | ]; |
| 417 | |
| 418 | let res = |
| 419 | StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 5000, Some(42)) |
| 420 | .unwrap(); |
| 421 | assert!(res.observed_delta_mean > 19.0); |
| 422 | assert!(res.is_statistically_significant); |
| 423 | assert!(res.p_value < 0.01); |
| 424 | assert!(res.ci_99_lower > 15.0); |
| 425 | } |
| 426 | |
| 427 | #[test] |
| 428 | fn test_tail_non_inferiority_passes() { |
| 429 | let parent: Vec<f64> = (1..=100).map(|x| x as f64).collect(); |
| 430 | let candidate: Vec<f64> = (1..=100).map(|x| (x as f64) * 1.002).collect(); |
| 431 | |
| 432 | let res = StatisticalEngine::evaluate_tail_non_inferiority( |
| 433 | &parent, |
| 434 | &candidate, |
| 435 | 95.0, |
| 436 | 1.0, |
| 437 | 2000, |
| 438 | Some(42), |
| 439 | ) |
| 440 | .unwrap(); |
| 441 | |
| 442 | assert_eq!(res.percentile, 95.0); |
| 443 | assert!(res.passes_non_inferiority); |
| 444 | assert!(res.ci_95_upper_pct <= 1.0); |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn test_tail_non_inferiority_fails_on_regression() { |
| 449 | let parent: Vec<f64> = (1..=100).map(|x| x as f64).collect(); |
| 450 | let candidate: Vec<f64> = (1..=100).map(|x| (x as f64) * 1.05).collect(); |
| 451 | |
| 452 | let res = StatisticalEngine::evaluate_tail_non_inferiority( |
| 453 | &parent, |
| 454 | &candidate, |
| 455 | 95.0, |
| 456 | 1.0, |
| 457 | 2000, |
| 458 | Some(42), |
| 459 | ) |
| 460 | .unwrap(); |
| 461 | |
| 462 | assert!(!res.passes_non_inferiority); |
| 463 | assert!(res.ci_95_upper_pct > 1.0); |
| 464 | } |
| 465 | |
| 466 | #[test] |
| 467 | fn test_fishers_exact_test_known_distribution() { |
| 468 | let res = StatisticalEngine::fishers_exact_test(1, 9, 11, 3).unwrap(); |
| 469 | assert!(res.p_value_two_sided < 0.05); |
| 470 | assert!(res.is_significant); |
| 471 | } |
| 472 | |
| 473 | #[test] |
| 474 | fn test_fishers_exact_test_identical_rates() { |
| 475 | let res = StatisticalEngine::fishers_exact_test(10, 10, 10, 10).unwrap(); |
| 476 | assert!(!res.is_significant); |
| 477 | assert!((res.p_value_two_sided - 1.0).abs() < 1e-6); |
| 478 | } |
| 479 | } |