ftui-runtime 0.11.0

Elm-style runtime loop and subscriptions for FrankenTUI.
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! Alpha-Investing: sequential alpha-spending with partial refund for multiple alerts.
//!
//! When many monitors fire sequentially (budget alerts, degradation triggers,
//! capability detection decisions), testing each at a fixed alpha level inflates
//! expected false discoveries. This module implements a **multiplicative
//! alpha-spending rule with partial refund** inspired by Foster & Stine (2008).
//!
//! # Mathematical Model (Implemented Partial-Refund Rule)
//!
//! The investor maintains a **wealth** $W_t \ge 0$ starting at $W_0 = \text{initial\_wealth}$:
//!
//! ```text
//! W₀ = initial_wealth   (default 0.5)
//! ```
//!
//! For each sequential hypothesis $H_i$ ($i = 1, 2, \dots$) while $W_{i-1} \ge \text{min\_wealth}$:
//! 1. **Invest**: allocate $\alpha_i = \text{clamp}(\text{investment\_fraction} \cdot W_{i-1},\; 0,\; W_{i-1})$.
//! 2. **Deduct upfront**: $W_i \leftarrow W_{i-1} - \alpha_i$.
//! 3. **Test & partial refund**:
//!    - If $p_i \le \alpha_i$ (**Rejected** / discovery, $R_i = 1$):
//!      $W_i \leftarrow W_i + \psi \alpha_i$, where $\psi = \text{reward\_fraction} \in (0, 1]$ (default $0.5$).
//!    - If $p_i > \alpha_i$ (**NotRejected**, $R_i = 0$):
//!      $W_i$ remains $W_{i-1} - \alpha_i$.
//!
//! # Comparison with Foster & Stine (2008) and Exact Guarantees
//!
//! Foster & Stine (2008) charge $\alpha_i / (1 - \alpha_i)$, grant an additive payout $\omega$
//! on rejection, and control the **stabilized modified false discovery rate**:
//!
//! ```text
//! mFDR_η = E[V] / (E[R] + η) ≤ α    (for stabilizer η > 0, e.g. η = 1 or 1 - W₀)
//! ```
//!
//! (Note: unstabilized $E\[V\]/E\[R\]$ is undefined when $E\[R\] = 0$, and $R / m$ is the raw
//! rejection rate, not the false discovery proportion $\text{FDP} = V / \max(R, 1)$.)
//!
//! Because this implementation deducts $\alpha_i$ upfront and refunds only $\psi \alpha_i \le \alpha_i$
//! on rejection, net wealth change is $\Delta W_i = -\alpha_i(1 - \psi R_i) \le 0$. Under the
//! conditional null assumption $P(p_i \le \alpha_i \mid \mathcal{F}_{i-1}) \le \alpha_i$ for true
//! nulls $i \in \mathcal{H}_0$:
//!
//! 1. **Bounded total alpha expenditure ($\psi < 1$)**:
//!    $$\sum_{i=1}^m \alpha_i \le \frac{W_0 - W_m}{1 - \psi} \le \frac{W_0}{1 - \psi}$$
//! 2. **Expected false discoveries & stabilized $\text{mFDR}_\eta$**:
//!    With $\alpha_{\max} = \sup_i \alpha_i \le \text{investment\_fraction} \cdot W_0$, the process
//!    $A_t = (1 - \psi \alpha_{\max}) V_t + W_t$ is a nonnegative supermartingale, yielding:
//!    $$E\[V\] \le E\left[\sum_{i=1}^m \alpha_i\right] \le \frac{W_0}{1 - \psi \alpha_{\max}} \le \frac{W_0}{1 - \psi}$$
//!    and for any stabilizer $\eta \ge 1$:
//!    $$\text{mFDR}_\eta = \frac{E\[V\]}{E\[R\] + \eta} \le \frac{E\[V\]}{\eta} \le \frac{W_0}{\eta (1 - \psi \alpha_{\max})}$$
//!
//! # Integration
//!
//! Pair with `conformal_alert` for individual alert calibration:
//!
//! ```text
//! conformal_alert → p-value → alpha_investing → gated decision
//! ```
//!
//! # Failure Modes
//!
//! | Condition | Behavior | Rationale |
//! |-----------|----------|-----------|
//! | Wealth exhausted ($W < \text{min\_wealth}$) | All tests skipped | Alpha budget spent |
//! | Negative p-value | Clamped to 0.0 | Invalid input guard |
//! | p-value > 1.0 | Clamped to 1.0 | Invalid input guard |
//! | Zero investment | Test skipped | No alpha allocated |
//! | Positively dependent / anti-conservative p-values | Bound degrades | Requires super-uniform null $P(p_i \le \alpha_i \mid \mathcal{F}_{i-1}) \le \alpha_i$ |
//!
//! # Reference
//!
//! Foster & Stine (2008), "α-investing: a procedure for sequential control
//! of expected false discoveries", JRSS-B 70(2):429-444.

/// Configuration for the Alpha-Investing procedure.
#[derive(Debug, Clone)]
pub struct AlphaInvestingConfig {
    /// Initial wealth (significance budget). Controls the mFDR bound.
    /// Typical values: 0.05 to 0.5.
    pub initial_wealth: f64,
    /// Fraction of alpha returned on discovery. Must be in (0, 1].
    /// Higher values make the procedure more liberal after discoveries.
    /// Foster & Stine recommend ψ = 0.5.
    pub reward_fraction: f64,
    /// Default fraction of current wealth to invest per test.
    /// Each test spends `investment_fraction * current_wealth`.
    /// Typical: 0.05 to 0.5.
    pub investment_fraction: f64,
    /// Minimum wealth below which all tests are skipped.
    /// Prevents degenerate behavior near zero.
    pub min_wealth: f64,
}

impl Default for AlphaInvestingConfig {
    fn default() -> Self {
        Self {
            initial_wealth: 0.5,
            reward_fraction: 0.5,
            investment_fraction: 0.1,
            min_wealth: 1e-10,
        }
    }
}

/// Outcome of testing a single hypothesis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TestOutcome {
    /// Hypothesis rejected (discovery). The alert is significant.
    Rejected,
    /// Hypothesis not rejected. The alert is not significant at invested level.
    NotRejected,
    /// Test skipped because wealth was insufficient.
    Skipped,
}

/// Record of a single hypothesis test within the Alpha-Investing sequence.
#[derive(Debug, Clone)]
pub struct TestRecord {
    /// Hypothesis index (0-based).
    pub index: usize,
    /// The p-value for this hypothesis.
    pub p_value: f64,
    /// Alpha invested in this test.
    pub alpha_invested: f64,
    /// Outcome of the test.
    pub outcome: TestOutcome,
    /// Wealth after this test.
    pub wealth_after: f64,
}

/// Alpha-Investing controller for sequential FDR control.
///
/// Maintains a wealth process that gates alert significance decisions.
/// Each call to [`test`](AlphaInvestor::test) either rejects (discovery)
/// or fails to reject, updating the wealth accordingly.
#[derive(Debug, Clone)]
pub struct AlphaInvestor {
    config: AlphaInvestingConfig,
    /// Current wealth (remaining significance budget).
    wealth: f64,
    /// Number of hypotheses tested so far.
    tests_run: usize,
    /// Number of discoveries (rejections).
    discoveries: usize,
    /// Full test history (bounded by practical use; callers can drain).
    history: Vec<TestRecord>,
}

impl AlphaInvestor {
    /// Create a new investor with the given configuration.
    pub fn new(config: AlphaInvestingConfig) -> Self {
        let wealth = config.initial_wealth;
        Self {
            config,
            wealth,
            tests_run: 0,
            discoveries: 0,
            history: Vec::new(),
        }
    }

    /// Create an investor with default configuration.
    pub fn with_defaults() -> Self {
        Self::new(AlphaInvestingConfig::default())
    }

    /// Current wealth (remaining significance budget).
    pub fn wealth(&self) -> f64 {
        self.wealth
    }

    /// Number of hypotheses tested.
    pub fn tests_run(&self) -> usize {
        self.tests_run
    }

    /// Number of discoveries (rejected hypotheses).
    pub fn discoveries(&self) -> usize {
        self.discoveries
    }

    /// Empirical rejection (discovery) rate: `discoveries / tests_run` ($R / m$).
    ///
    /// Note: this is the raw fraction of tested hypotheses rejected, **not** the
    /// false discovery proportion $\text{FDP} = V / \max(R, 1)$ (which requires
    /// ground-truth null/alternative labels $H_0$ vs. $H_1$). Returns `0.0` if no
    /// tests have been run.
    pub fn discovery_rate(&self) -> f64 {
        if self.tests_run == 0 {
            0.0
        } else {
            self.discoveries as f64 / self.tests_run as f64
        }
    }

    /// Test a hypothesis with the given p-value.
    ///
    /// The procedure invests `investment_fraction * wealth` as the alpha
    /// level for this test. If p_value ≤ alpha, the hypothesis is rejected
    /// (discovery) and wealth is replenished by `reward_fraction * alpha`.
    ///
    /// Returns the outcome and updates internal state.
    pub fn test(&mut self, p_value: f64) -> TestOutcome {
        self.test_with_investment(p_value, None)
    }

    /// Test with a custom investment amount (overrides `investment_fraction`).
    ///
    /// `custom_alpha` is clamped to `[0, current_wealth]`.
    pub fn test_with_investment(&mut self, p_value: f64, custom_alpha: Option<f64>) -> TestOutcome {
        let p = p_value.clamp(0.0, 1.0);

        // Check if we have enough wealth to test.
        if self.wealth < self.config.min_wealth {
            let record = TestRecord {
                index: self.tests_run,
                p_value: p,
                alpha_invested: 0.0,
                outcome: TestOutcome::Skipped,
                wealth_after: self.wealth,
            };
            self.history.push(record);
            self.tests_run += 1;
            return TestOutcome::Skipped;
        }

        // Determine investment.
        let alpha = match custom_alpha {
            Some(a) => a.clamp(0.0, self.wealth),
            None => (self.config.investment_fraction * self.wealth).min(self.wealth),
        };

        if alpha <= 0.0 {
            let record = TestRecord {
                index: self.tests_run,
                p_value: p,
                alpha_invested: 0.0,
                outcome: TestOutcome::Skipped,
                wealth_after: self.wealth,
            };
            self.history.push(record);
            self.tests_run += 1;
            return TestOutcome::Skipped;
        }

        // Spend alpha.
        self.wealth -= alpha;

        // Test: reject if p ≤ alpha.
        let outcome = if p <= alpha {
            // Discovery — replenish wealth.
            let reward = self.config.reward_fraction * alpha;
            self.wealth += reward;
            self.discoveries += 1;
            TestOutcome::Rejected
        } else {
            TestOutcome::NotRejected
        };

        let record = TestRecord {
            index: self.tests_run,
            p_value: p,
            alpha_invested: alpha,
            outcome,
            wealth_after: self.wealth,
        };
        self.history.push(record);
        self.tests_run += 1;

        outcome
    }

    /// Batch-test multiple hypotheses, returning outcomes for each.
    ///
    /// P-values are tested in the order given. The wealth evolves
    /// sequentially, so ordering matters.
    pub fn test_batch(&mut self, p_values: &[f64]) -> Vec<TestOutcome> {
        p_values.iter().map(|&p| self.test(p)).collect()
    }

    /// Reset the investor to its initial state.
    pub fn reset(&mut self) {
        self.wealth = self.config.initial_wealth;
        self.tests_run = 0;
        self.discoveries = 0;
        self.history.clear();
    }

    /// Access the test history.
    pub fn history(&self) -> &[TestRecord] {
        &self.history
    }

    /// Drain the test history (returns ownership, clears internal log).
    pub fn drain_history(&mut self) -> Vec<TestRecord> {
        std::mem::take(&mut self.history)
    }
}

// ---------------------------------------------------------------------------
// Bonferroni fallback (simple but conservative)
// ---------------------------------------------------------------------------

/// Simple Bonferroni correction: test each hypothesis at α/m.
///
/// Returns a vector of booleans (true = rejected).
/// This is the conservative fallback mentioned in the bead spec.
pub fn bonferroni_test(p_values: &[f64], alpha: f64) -> Vec<bool> {
    if p_values.is_empty() {
        return Vec::new();
    }
    let threshold = alpha / p_values.len() as f64;
    p_values.iter().map(|&p| p <= threshold).collect()
}

/// Benjamini-Hochberg step-up procedure for FDR control.
///
/// Returns indices of rejected hypotheses (sorted ascending).
/// Controls FDR at level α under independence.
///
/// A NaN p-value is read as 1.0 - no evidence. `f64::clamp` passes NaN
/// through, and the step-up below rejects the first `max_k` entries *in sorted
/// order* rather than re-testing them, so an unhandled NaN is both rejected
/// itself (`NaN <= threshold` is false, so it never sets `max_k`, but it can
/// sit below one that does) and, by occupying a rank, inflates the threshold
/// of every real p-value after it. Both fail permissively: with α = 0.05,
/// `[0.02, 0.9, 0.95]` rejects nothing, while `[NaN, 0.02, 0.9, 0.95]`
/// rejected the NaN *and* manufactured a discovery at 0.02.
///
/// Reading it as 1.0 rather than dropping it keeps `m` equal to the number of
/// hypotheses tested, which is the denominator FDR control is defined over,
/// and sorts it last so the real p-values keep their ranks among themselves.
pub fn benjamini_hochberg(p_values: &[f64], alpha: f64) -> Vec<usize> {
    if p_values.is_empty() {
        return Vec::new();
    }
    let m = p_values.len();
    // Sort p-values with original indices.
    let mut indexed: Vec<(usize, f64)> = p_values
        .iter()
        .enumerate()
        .map(|(i, &p)| (i, if p.is_nan() { 1.0 } else { p.clamp(0.0, 1.0) }))
        .collect();
    // `total_cmp`, not `partial_cmp().unwrap_or(Equal)`: the latter is an
    // intransitive comparator, which std's sort is documented to panic on.
    indexed.sort_by(|a, b| a.1.total_cmp(&b.1));

    // Find largest k where p_(k) ≤ k/m * α.
    let mut max_k = 0;
    for (rank, &(_, p)) in indexed.iter().enumerate() {
        let threshold = (rank + 1) as f64 / m as f64 * alpha;
        if p <= threshold {
            max_k = rank + 1;
        }
    }

    // Reject the first max_k sorted hypotheses.
    indexed[..max_k].iter().map(|&(i, _)| i).collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_config() {
        let cfg = AlphaInvestingConfig::default();
        assert_eq!(cfg.initial_wealth, 0.5);
        assert_eq!(cfg.reward_fraction, 0.5);
        assert_eq!(cfg.investment_fraction, 0.1);
    }

    #[test]
    fn investor_initial_state() {
        let inv = AlphaInvestor::with_defaults();
        assert_eq!(inv.wealth(), 0.5);
        assert_eq!(inv.tests_run(), 0);
        assert_eq!(inv.discoveries(), 0);
        assert_eq!(inv.discovery_rate(), 0.0);
    }

    #[test]
    fn single_rejection() {
        let mut inv = AlphaInvestor::with_defaults();
        // Invest 0.1 * 0.5 = 0.05; p=0.01 < 0.05 → reject
        let outcome = inv.test(0.01);
        assert_eq!(outcome, TestOutcome::Rejected);
        assert_eq!(inv.discoveries(), 1);
        // Wealth: 0.5 - 0.05 + 0.5*0.05 = 0.475
        assert!((inv.wealth() - 0.475).abs() < 1e-10);
    }

    #[test]
    fn single_non_rejection() {
        let mut inv = AlphaInvestor::with_defaults();
        // Invest 0.05; p=0.9 > 0.05 → not rejected
        let outcome = inv.test(0.9);
        assert_eq!(outcome, TestOutcome::NotRejected);
        assert_eq!(inv.discoveries(), 0);
        // Wealth: 0.5 - 0.05 = 0.45
        assert!((inv.wealth() - 0.45).abs() < 1e-10);
    }

    #[test]
    fn wealth_exhaustion() {
        let cfg = AlphaInvestingConfig {
            initial_wealth: 0.01,
            investment_fraction: 1.0, // spend everything each time
            min_wealth: 0.005,
            ..Default::default()
        };
        let mut inv = AlphaInvestor::new(cfg);
        // First test: invest 0.01, p=0.5 → not rejected → wealth=0
        let o1 = inv.test(0.5);
        assert_eq!(o1, TestOutcome::NotRejected);
        // Second test: wealth < min_wealth → skipped
        let o2 = inv.test(0.001);
        assert_eq!(o2, TestOutcome::Skipped);
    }

    #[test]
    fn batch_test() {
        let mut inv = AlphaInvestor::with_defaults();
        let outcomes = inv.test_batch(&[0.001, 0.001, 0.9, 0.9, 0.001]);
        assert_eq!(outcomes.len(), 5);
        // First two very small p-values should be rejected
        assert_eq!(outcomes[0], TestOutcome::Rejected);
        assert_eq!(outcomes[1], TestOutcome::Rejected);
        // Large p-values should not be rejected
        assert_eq!(outcomes[2], TestOutcome::NotRejected);
        assert_eq!(outcomes[3], TestOutcome::NotRejected);
    }

    #[test]
    fn custom_investment() {
        let mut inv = AlphaInvestor::with_defaults();
        // Invest exactly 0.2 (custom)
        let outcome = inv.test_with_investment(0.1, Some(0.2));
        assert_eq!(outcome, TestOutcome::Rejected);
        // Wealth: 0.5 - 0.2 + 0.5*0.2 = 0.4
        assert!((inv.wealth() - 0.4).abs() < 1e-10);
    }

    #[test]
    fn custom_investment_clamped_to_wealth() {
        let cfg = AlphaInvestingConfig {
            initial_wealth: 0.1,
            ..Default::default()
        };
        let mut inv = AlphaInvestor::new(cfg);
        // Try to invest 1.0 but only have 0.1
        let outcome = inv.test_with_investment(0.01, Some(1.0));
        assert_eq!(outcome, TestOutcome::Rejected);
        // Clamped to 0.1, so wealth: 0.1 - 0.1 + 0.5*0.1 = 0.05
        assert!((inv.wealth() - 0.05).abs() < 1e-10);
    }

    #[test]
    fn p_value_clamping() {
        let mut inv = AlphaInvestor::with_defaults();
        // Negative p-value clamped to 0
        let o1 = inv.test(-0.5);
        assert_eq!(o1, TestOutcome::Rejected);
        // p > 1 clamped to 1
        let o2 = inv.test(2.0);
        assert_eq!(o2, TestOutcome::NotRejected);
    }

    #[test]
    fn reset() {
        let mut inv = AlphaInvestor::with_defaults();
        inv.test(0.001);
        inv.test(0.9);
        assert!(inv.tests_run() > 0);
        inv.reset();
        assert_eq!(inv.tests_run(), 0);
        assert_eq!(inv.discoveries(), 0);
        assert_eq!(inv.wealth(), 0.5);
        assert!(inv.history().is_empty());
    }

    #[test]
    fn history_tracking() {
        let mut inv = AlphaInvestor::with_defaults();
        inv.test(0.01);
        inv.test(0.9);
        assert_eq!(inv.history().len(), 2);
        let h = inv.drain_history();
        assert_eq!(h.len(), 2);
        assert!(inv.history().is_empty());
    }

    #[test]
    fn bonferroni_basic() {
        let p_values = [0.01, 0.03, 0.04, 0.05, 0.10];
        let results = bonferroni_test(&p_values, 0.05);
        // threshold = 0.05/5 = 0.01 → only first rejected
        assert_eq!(results, vec![true, false, false, false, false]);
    }

    #[test]
    fn bonferroni_empty() {
        assert!(bonferroni_test(&[], 0.05).is_empty());
    }

    #[test]
    fn benjamini_hochberg_basic() {
        // Classic BH example
        let p_values = [0.001, 0.008, 0.039, 0.041, 0.23, 0.35, 0.78, 0.90];
        let rejected = benjamini_hochberg(&p_values, 0.05);
        // BH at 0.05 with 8 tests:
        // rank 1: 0.001 ≤ 1/8*0.05=0.00625 ✓
        // rank 2: 0.008 ≤ 2/8*0.05=0.0125  ✓
        // rank 3: 0.039 ≤ 3/8*0.05=0.01875 ✗
        // rank 4: 0.041 ≤ 4/8*0.05=0.025   ✗
        // max_k=2, reject first 2 sorted
        assert_eq!(rejected.len(), 2);
        assert!(rejected.contains(&0));
        assert!(rejected.contains(&1));
    }

    #[test]
    fn benjamini_hochberg_all_significant() {
        let p_values = [0.001, 0.002, 0.003];
        let rejected = benjamini_hochberg(&p_values, 0.05);
        assert_eq!(rejected.len(), 3);
    }

    #[test]
    fn benjamini_hochberg_none_significant() {
        let p_values = [0.5, 0.6, 0.7];
        let rejected = benjamini_hochberg(&p_values, 0.05);
        assert!(rejected.is_empty());
    }

    #[test]
    fn benjamini_hochberg_empty() {
        assert!(benjamini_hochberg(&[], 0.05).is_empty());
    }

    #[test]
    fn benjamini_hochberg_never_rejects_a_nan_hypothesis() {
        // A NaN carries no evidence, so it must never come back as a discovery.
        assert_eq!(benjamini_hochberg(&[f64::NAN, 0.001], 0.05), vec![1]);
        assert_eq!(benjamini_hochberg(&[0.001, f64::NAN], 0.05), vec![0]);
        assert!(benjamini_hochberg(&[f64::NAN, f64::NAN], 0.05).is_empty());
        assert_eq!(
            benjamini_hochberg(&[f64::NAN, f64::NAN, 0.001], 0.05),
            vec![2]
        );
    }

    #[test]
    fn benjamini_hochberg_nan_does_not_manufacture_a_discovery() {
        // These three are correctly rejected by nobody at alpha = 0.05.
        let real = [0.02, 0.9, 0.95];
        assert!(benjamini_hochberg(&real, 0.05).is_empty());

        // Adding a NaN must not change that. Read as 1.0 it sorts last, so the
        // real p-values keep their ranks relative to each other; only `m` grows,
        // which can shrink the thresholds but never widen them.
        let poisoned = [f64::NAN, 0.02, 0.9, 0.95];
        assert!(
            benjamini_hochberg(&poisoned, 0.05).is_empty(),
            "a NaN must not promote 0.02 into a rejection"
        );
    }

    #[test]
    fn benjamini_hochberg_clamps_out_of_range_p_values() {
        // +/-inf are ordinary out-of-range values and clamp to the boundaries.
        assert_eq!(
            benjamini_hochberg(&[f64::NEG_INFINITY, 0.9, 0.95], 0.05),
            vec![0],
            "p <= 0 is maximally significant"
        );
        assert!(benjamini_hochberg(&[f64::INFINITY, 0.9, 0.95], 0.05).is_empty());
    }

    #[test]
    fn fdr_control_simulation() {
        // Simulate: 100 hypotheses, 90 null (p ~ Uniform[0,1]), 10 real (p ~ 0.001)
        // Verify that discovery rate is reasonable
        let mut inv = AlphaInvestor::new(AlphaInvestingConfig {
            initial_wealth: 0.5,
            reward_fraction: 0.5,
            investment_fraction: 0.1,
            min_wealth: 1e-12,
        });

        // 10 real signals
        let mut p_values = vec![0.001; 10];
        // 90 null hypotheses with uniform-ish p-values
        for i in 0..90 {
            p_values.push(0.1 + (i as f64 * 0.01));
        }

        let outcomes = inv.test_batch(&p_values);
        let rejections: usize = outcomes
            .iter()
            .filter(|&&o| o == TestOutcome::Rejected)
            .count();

        // Should reject at least some of the real signals
        assert!(rejections >= 1, "Should reject at least 1 real signal");
        // Should not reject most of the null hypotheses
        assert!(
            rejections <= 20,
            "Should not reject too many (got {})",
            rejections
        );
    }

    #[test]
    fn null_mfdr_and_expected_false_discoveries_with_confidence_interval() {
        // Deterministic SplitMix64 PRNG for reproducible Monte Carlo under H_0.
        fn splitmix64(state: &mut u64) -> f64 {
            *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = *state;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^= z >> 31;
            ((z >> 11) as f64) * (1.0 / ((1u64 << 53) as f64))
        }

        let cfg = AlphaInvestingConfig {
            initial_wealth: 0.5,
            reward_fraction: 0.5,
            investment_fraction: 0.1,
            min_wealth: 1e-10,
        };
        let trials = 2_000usize;
        let m = 100usize;
        let mut rng = 0xA1FA_2026_0906_0043u64;

        let mut v_samples = Vec::with_capacity(trials);
        let mut fdp_samples = Vec::with_capacity(trials);
        let mut max_alpha_sum = 0.0f64;

        for _ in 0..trials {
            let mut inv = AlphaInvestor::new(cfg.clone());
            for _ in 0..m {
                let p_null = splitmix64(&mut rng);
                inv.test(p_null);
            }
            // Under the global null, every rejection is a false discovery (V = R).
            let v = inv.discoveries() as f64;
            let r = v;
            let fdp = if r > 0.0 { v / r } else { 0.0 };
            let alpha_sum: f64 = inv.history().iter().map(|rec| rec.alpha_invested).sum();
            max_alpha_sum = max_alpha_sum.max(alpha_sum);
            v_samples.push(v);
            fdp_samples.push(fdp);
        }

        let n = trials as f64;
        let mean_v = v_samples.iter().sum::<f64>() / n;
        let var_v = v_samples.iter().map(|&v| (v - mean_v).powi(2)).sum::<f64>() / (n - 1.0);
        let se_v = (var_v / n).sqrt();
        let ci99_upper_v = mean_v + 2.576 * se_v;

        let mean_fdp = fdp_samples.iter().sum::<f64>() / n;
        let var_fdp = fdp_samples
            .iter()
            .map(|&x| (x - mean_fdp).powi(2))
            .sum::<f64>()
            / (n - 1.0);
        let se_fdp = (var_fdp / n).sqrt();
        let ci99_upper_fdp = mean_fdp + 2.576 * se_fdp;

        // Stabilized mFDR_1 = E[V] / (E[R] + 1.0) under global null (V = R).
        let mfdr_1 = mean_v / (mean_v + 1.0);

        // Deterministic expenditure bound: sum(alpha_i) <= W_0 / (1 - psi) = 0.5 / 0.5 = 1.0.
        let expenditure_bound = cfg.initial_wealth / (1.0 - cfg.reward_fraction);
        assert!(
            max_alpha_sum <= expenditure_bound + 1e-12,
            "Total alpha spent {} exceeded W_0/(1-psi)={}",
            max_alpha_sum,
            expenditure_bound
        );

        // Supermartingale bound: E[V] <= W_0 / (1 - psi * alpha_max) = 0.5 / 0.975 ≈ 0.51282.
        let alpha_max = cfg.investment_fraction * cfg.initial_wealth;
        let ev_bound = cfg.initial_wealth / (1.0 - cfg.reward_fraction * alpha_max);
        assert!(
            mean_v <= ev_bound + 2.576 * se_v,
            "Empirical E[V]={:.4} (99% CI upper {:.4}) exceeded theoretical bound {:.4}",
            mean_v,
            ci99_upper_v,
            ev_bound
        );
        assert!(
            mfdr_1 <= cfg.initial_wealth,
            "Stabilized mFDR_1={:.4} exceeded W_0={}",
            mfdr_1,
            cfg.initial_wealth
        );
        assert!(
            ci99_upper_fdp <= cfg.initial_wealth + 0.05,
            "Empirical FDR={:.4} (99% CI upper {:.4}) exceeded bound",
            mean_fdp,
            ci99_upper_fdp
        );
    }

    #[test]
    fn mixed_null_and_alternative_tracks_true_fdp_vs_raw_discovery_rate() {
        // Demonstrate that `discovery_rate()` is R / m (raw rejection rate),
        // while true FDP = V / max(R, 1) and mFDR_1 = E[V] / (E[R] + 1) require
        // ground-truth labels (is_null).
        fn splitmix64(state: &mut u64) -> f64 {
            *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = *state;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^= z >> 31;
            ((z >> 11) as f64) * (1.0 / ((1u64 << 53) as f64))
        }

        let cfg = AlphaInvestingConfig::default();
        let trials = 1_000usize;
        let m = 50usize;
        let mut rng = 0x5EED_2026_1016_0045u64;

        let mut total_v = 0.0f64;
        let mut total_r = 0.0f64;
        let mut total_raw_rate = 0.0f64;

        for _ in 0..trials {
            let mut inv = AlphaInvestor::new(cfg.clone());
            let mut v_trial = 0usize;
            for idx in 0..m {
                // Every 5th hypothesis is a strong non-null alternative (p in [0, 0.002]).
                let is_null = idx % 5 != 0;
                let u = splitmix64(&mut rng);
                let p = if is_null { u } else { u * 0.002 };
                if inv.test(p) == TestOutcome::Rejected && is_null {
                    v_trial += 1;
                }
            }
            total_v += v_trial as f64;
            total_r += inv.discoveries() as f64;
            total_raw_rate += inv.discovery_rate();
        }

        let mean_v = total_v / trials as f64;
        let mean_r = total_r / trials as f64;
        let mean_raw_rate = total_raw_rate / trials as f64;
        let mfdr_1 = mean_v / (mean_r + 1.0);

        // True signals are detected (mean_r > 4), so raw discovery_rate = mean_r / m
        // is well above mean_v / m, while stabilized mFDR_1 remains well below W_0.
        assert!(
            mean_r > 4.0,
            "Expected strong alternatives to be discovered, got mean_r={mean_r}"
        );
        assert!((mean_raw_rate - mean_r / m as f64).abs() < 1e-12);
        assert!(
            mfdr_1 < cfg.initial_wealth,
            "Expected mFDR_1={mfdr_1:.4} < W_0={}",
            cfg.initial_wealth
        );
    }

    #[test]
    fn wealth_monotone_on_null() {
        // Under pure null (all p > alpha), wealth strictly decreases
        let mut inv = AlphaInvestor::with_defaults();
        let mut prev_wealth = inv.wealth();
        for _ in 0..20 {
            inv.test(0.9);
            assert!(
                inv.wealth() <= prev_wealth,
                "Wealth should not increase on non-rejection"
            );
            prev_wealth = inv.wealth();
        }
    }
}