aprender-core 0.29.1

Next-generation machine learning library in pure Rust
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Convergence diagnostics for Monte Carlo simulations
//!
//! Implements effective sample size (ESS), Monte Carlo standard error (MCSE),
//! and autocorrelation analysis for assessing simulation quality.
//!
//! Reference: Gelman et al. (2013), "Bayesian Data Analysis", Ch. 11

use super::types::SimulationPath;

/// Diagnostics for monitoring simulation convergence
#[derive(Debug, Clone, Default)]
pub struct ConvergenceDiagnostics {
    /// Effective sample size
    pub ess: f64,
    /// Monte Carlo standard error
    pub mcse: f64,
    /// Relative precision (MCSE / mean)
    pub relative_precision: f64,
    /// Running mean history for convergence tracking
    pub running_mean_history: Vec<f64>,
    /// Running count
    count: usize,
    /// Running sum
    sum: f64,
    /// Running sum of squares (for variance)
    sum_sq: f64,
}

impl ConvergenceDiagnostics {
    /// Create new diagnostics tracker
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Update diagnostics with new paths
    pub fn update(&mut self, paths: &[SimulationPath]) {
        if paths.is_empty() {
            return;
        }

        let returns: Vec<f64> = paths
            .iter()
            .filter_map(SimulationPath::total_return)
            .collect();

        if returns.is_empty() {
            return;
        }

        let n = returns.len();
        let mean = returns.iter().sum::<f64>() / n as f64;
        let variance =
            returns.iter().map(|r| (r - mean).powi(2)).sum::<f64>() / (n - 1).max(1) as f64;
        let std = variance.sqrt();

        // Calculate ESS using batch means
        self.ess = calculate_ess(&returns);

        // Calculate MCSE
        self.mcse = if self.ess > 0.0 {
            std / self.ess.sqrt()
        } else {
            f64::INFINITY
        };

        // Calculate relative precision
        self.relative_precision = if mean.abs() > 1e-10 {
            self.mcse / mean.abs()
        } else {
            f64::INFINITY
        };

        // Track running mean history
        self.running_mean_history.push(mean);
    }

    /// Update with a single value (Welford's online algorithm)
    pub fn update_single(&mut self, value: f64) {
        self.count += 1;
        self.sum += value;
        self.sum_sq += value * value;

        let mean = self.sum / self.count as f64;
        self.running_mean_history.push(mean);

        // Estimate variance and ESS from running statistics
        if self.count > 1 {
            let variance =
                (self.sum_sq - self.sum * self.sum / self.count as f64) / (self.count - 1) as f64;
            let std = variance.sqrt();

            // Approximate ESS as n (assuming independence)
            self.ess = self.count as f64;
            self.mcse = std / self.ess.sqrt();
            self.relative_precision = if mean.abs() > 1e-10 {
                self.mcse / mean.abs()
            } else {
                f64::INFINITY
            };
        }
    }

    /// Check if simulation has converged to target precision
    #[must_use]
    pub fn is_converged(&self, target_precision: f64) -> bool {
        self.relative_precision < target_precision && self.ess > 100.0
    }

    /// Get the current estimate of the mean
    #[must_use]
    pub fn current_mean(&self) -> Option<f64> {
        self.running_mean_history.last().copied()
    }

    /// Get confidence interval for the mean
    #[must_use]
    pub fn confidence_interval(&self, confidence: f64) -> Option<(f64, f64)> {
        let mean = self.current_mean()?;
        if !self.mcse.is_finite() {
            return None;
        }

        // z-score for confidence level (approximate)
        let z = match confidence {
            c if c >= 0.99 => 2.576,
            c if c >= 0.95 => 1.96,
            c if c >= 0.90 => 1.645,
            _ => 1.28,
        };

        let margin = z * self.mcse;
        Some((mean - margin, mean + margin))
    }
}

/// Calculate Effective Sample Size using batch means
///
/// ESS = n / (1 + 2 * sum of autocorrelations)
#[must_use]
pub fn calculate_ess(values: &[f64]) -> f64 {
    let n = values.len();
    if n < 10 {
        return n as f64;
    }

    // Use batch means method
    let batch_size = (n as f64).sqrt().ceil() as usize;
    let n_batches = n / batch_size;

    if n_batches < 2 {
        return n as f64;
    }

    // Calculate batch means
    let batch_means: Vec<f64> = (0..n_batches)
        .map(|i| {
            let start = i * batch_size;
            let end = ((i + 1) * batch_size).min(n);
            values[start..end].iter().sum::<f64>() / (end - start) as f64
        })
        .collect();

    // Overall mean
    let grand_mean = values.iter().sum::<f64>() / n as f64;

    // Variance of batch means
    let var_batch = batch_means
        .iter()
        .map(|m| (m - grand_mean).powi(2))
        .sum::<f64>()
        / (n_batches - 1) as f64;

    // Sample variance
    let var_sample = values.iter().map(|x| (x - grand_mean).powi(2)).sum::<f64>() / (n - 1) as f64;

    // ESS = n * var_sample / (batch_size * var_batch)
    if var_batch > 0.0 {
        (n as f64 * var_sample / (batch_size as f64 * var_batch)).min(n as f64)
    } else {
        n as f64
    }
}

/// Calculate autocorrelation at a given lag
#[must_use]
pub fn autocorrelation(values: &[f64], lag: usize) -> f64 {
    let n = values.len();
    if lag >= n {
        return 0.0;
    }

    let mean = values.iter().sum::<f64>() / n as f64;
    let variance: f64 = values.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / n as f64;

    if variance < 1e-15 {
        return 0.0;
    }

    let covariance: f64 = values[..n - lag]
        .iter()
        .zip(values[lag..].iter())
        .map(|(x, y)| (x - mean) * (y - mean))
        .sum::<f64>()
        / n as f64;

    covariance / variance
}

/// Calculate ESS using autocorrelation method
///
/// Computes autocorrelations until they become negligible,
/// then calculates ESS = n / (1 + 2 * `sum(ρ_k)`)
#[must_use]
pub fn ess_autocorr(values: &[f64]) -> f64 {
    let n = values.len();
    if n < 4 {
        return n as f64;
    }

    let max_lag = (n / 2).min(100);
    let mut sum_rho = 0.0;

    for lag in 1..max_lag {
        let rho = autocorrelation(values, lag);

        // Stop when autocorrelation becomes negligible
        if rho.abs() < 0.05 {
            break;
        }

        sum_rho += rho;
    }

    let tau = 1.0 + 2.0 * sum_rho;
    if tau > 0.0 {
        (n as f64 / tau).min(n as f64)
    } else {
        n as f64
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::monte_carlo::engine::types::PathMetadata;

    fn create_test_paths(n: usize, seed: u64) -> Vec<SimulationPath> {
        use crate::monte_carlo::engine::MonteCarloRng;

        let mut rng = MonteCarloRng::new(seed);

        (0..n)
            .map(|i| {
                let returns: Vec<f64> = (0..12)
                    .map(|j| {
                        if j == 0 {
                            100.0
                        } else {
                            100.0 * (1.0 + rng.normal(0.01, 0.05))
                        }
                    })
                    .collect();

                SimulationPath::new(
                    (0..12).map(|j| j as f64 / 12.0).collect(),
                    returns,
                    PathMetadata {
                        path_id: i,
                        seed,
                        is_antithetic: false,
                    },
                )
            })
            .collect()
    }

    #[test]
    fn test_convergence_diagnostics_basic() {
        let paths = create_test_paths(1000, 42);
        let mut diag = ConvergenceDiagnostics::new();
        diag.update(&paths);

        assert!(diag.ess > 0.0);
        assert!(diag.mcse.is_finite());
        assert!(diag.relative_precision.is_finite());
    }

    #[test]
    fn test_convergence_check() {
        let paths = create_test_paths(10000, 42);
        let mut diag = ConvergenceDiagnostics::new();
        diag.update(&paths);

        // With enough samples, should converge
        let converged = diag.is_converged(0.10);
        assert!(diag.ess > 100.0);
        // May or may not converge depending on data
        let _ = converged;
    }

    #[test]
    fn test_running_mean_history() {
        let mut diag = ConvergenceDiagnostics::new();

        for i in 1..=100 {
            diag.update_single(i as f64);
        }

        assert_eq!(diag.running_mean_history.len(), 100);
        // Final mean should be close to 50.5
        assert!((diag.current_mean().unwrap() - 50.5).abs() < 0.1);
    }

    #[test]
    fn test_calculate_ess() {
        // IID samples should have ESS close to n
        let iid: Vec<f64> = (0..1000).map(|i| (i % 10) as f64).collect();
        let ess = calculate_ess(&iid);
        assert!(ess > 0.0);
        assert!(ess <= 1000.0);
    }

    #[test]
    fn test_autocorrelation_lag_zero() {
        let values = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let rho_0 = autocorrelation(&values, 0);
        // Autocorrelation at lag 0 should be 1
        assert!((rho_0 - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_autocorrelation_random() {
        // Random values should have low autocorrelation
        // Use a more scrambled sequence to avoid hidden patterns
        use crate::monte_carlo::engine::MonteCarloRng;
        let mut rng = MonteCarloRng::new(42);
        let values: Vec<f64> = (0..200).map(|_| rng.uniform()).collect();
        let rho_1 = autocorrelation(&values, 1);
        // ChaCha20 should produce uncorrelated samples
        assert!(rho_1.abs() < 0.2, "Autocorrelation should be low: {rho_1}");
    }

    #[test]
    fn test_ess_autocorr() {
        let values: Vec<f64> = (0..1000).map(|i| (i % 10) as f64).collect();
        let ess = ess_autocorr(&values);
        assert!(ess > 0.0);
        assert!(ess <= 1000.0);
    }

    #[test]
    fn test_confidence_interval() {
        let mut diag = ConvergenceDiagnostics::new();
        for i in 1..=1000 {
            diag.update_single(i as f64);
        }

        let ci = diag.confidence_interval(0.95);
        assert!(ci.is_some());
        let (lower, upper) = ci.unwrap();
        assert!(lower < upper);
        assert!(lower < diag.current_mean().unwrap());
        assert!(upper > diag.current_mean().unwrap());
    }

    #[test]
    fn test_empty_paths() {
        let mut diag = ConvergenceDiagnostics::new();
        diag.update(&[]);
        assert!(diag.running_mean_history.is_empty());
    }

    // Property-based tests
    #[cfg(test)]
    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn prop_ess_bounded(values in prop::collection::vec(0.0..100.0f64, 10..500)) {
                let ess = calculate_ess(&values);
                prop_assert!(ess >= 0.0);
                prop_assert!(ess <= values.len() as f64);
            }

            #[test]
            fn prop_autocorr_bounded(values in prop::collection::vec(-10.0..10.0f64, 20..200)) {
                for lag in 1..5 {
                    let rho = autocorrelation(&values, lag);
                    prop_assert!(rho >= -1.0 && rho <= 1.0, "Autocorrelation out of bounds: {rho}");
                }
            }

            #[test]
            fn prop_ess_autocorr_bounded(values in prop::collection::vec(0.0..100.0f64, 10..200)) {
                let ess = ess_autocorr(&values);
                prop_assert!(ess >= 0.0);
                prop_assert!(ess <= values.len() as f64);
            }
        }
    }
}