RustedSciThe 0.4.11

Rust framework for symbolic and numerical computing:BVP ( Newton-Raphson frozen/damped/with collocations ), IVP( BDF, Radau, Backward Euler, LSODE, LSODA, RK45, DoPri), nonlinear equations ( Levenberg, Gavin) and more
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
pub const LSODE2_MAX_ADAMS_ORDER: usize = 12;
pub const LSODE2_MAX_BDF_ORDER: usize = 5;
pub const LSODE2_DEFAULT_STIFFNESS_RATIO_THRESHOLD: f64 = 100.0;
/// ODEPACK-like initial `ICOUNT` value before method-switch probing.
///
/// In DSTODA the gate is updated as:
/// `ICOUNT = ICOUNT - 1; IF (ICOUNT .GE. 0) skip switch probe`.
/// With initial `ICOUNT = 20`, the first probe occurs on accepted step 21.
pub const LSODE2_DEFAULT_METHOD_SWITCH_PROBE_STEPS: usize = 20;

/// LSODE-style time-integration family.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lsode2MethodFamily {
    Adams,
    Bdf,
}

impl Lsode2MethodFamily {
    pub fn label(self) -> &'static str {
        match self {
            Self::Adams => "adams",
            Self::Bdf => "bdf",
        }
    }
}

/// High-level LSODE2 algorithm controller mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lsode2ControllerMode {
    AdamsOnly,
    BdfOnly,
    AutomaticAdamsBdf,
}

impl Default for Lsode2ControllerMode {
    fn default() -> Self {
        Self::BdfOnly
    }
}

impl Lsode2ControllerMode {
    pub fn label(self) -> &'static str {
        match self {
            Self::AdamsOnly => "adams_only",
            Self::BdfOnly => "bdf_only",
            Self::AutomaticAdamsBdf => "automatic_adams_bdf",
        }
    }
}

/// Lightweight telemetry consumed by the Adams/BDF selection policy.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Lsode2SwitchTelemetry {
    pub stiffness_ratio: Option<f64>,
    pub accepted_steps: usize,
    pub rejected_steps: usize,
    pub convergence_failures: usize,
    /// Optional ODEPACK-like per-step cost estimate for Adams path.
    pub adams_step_cost_estimate: Option<f64>,
    /// Optional ODEPACK-like per-step cost estimate for BDF path.
    pub bdf_step_cost_estimate: Option<f64>,
    /// Number of Adams cost samples contributing to `adams_step_cost_estimate`.
    pub adams_cost_samples: usize,
    /// Number of BDF cost samples contributing to `bdf_step_cost_estimate`.
    pub bdf_cost_samples: usize,
    /// Optional DSTODA-style step-size capability proxy for Adams (`rh1`-like).
    pub adams_step_size_cap_estimate: Option<f64>,
    /// Optional DSTODA-style step-size capability proxy for BDF (`rh2`-like).
    pub bdf_step_size_cap_estimate: Option<f64>,
}

impl Lsode2SwitchTelemetry {
    pub fn quiet_nonstiff() -> Self {
        Self {
            stiffness_ratio: Some(0.0),
            accepted_steps: 0,
            rejected_steps: 0,
            convergence_failures: 0,
            adams_step_cost_estimate: None,
            bdf_step_cost_estimate: None,
            adams_cost_samples: 0,
            bdf_cost_samples: 0,
            adams_step_size_cap_estimate: None,
            bdf_step_size_cap_estimate: None,
        }
    }

    pub fn with_stiffness_ratio(mut self, ratio: f64) -> Self {
        self.stiffness_ratio = Some(ratio);
        self
    }

    pub fn with_rejected_steps(mut self, rejected_steps: usize) -> Self {
        self.rejected_steps = rejected_steps;
        self
    }

    pub fn with_accepted_steps(mut self, accepted_steps: usize) -> Self {
        self.accepted_steps = accepted_steps;
        self
    }

    pub fn with_convergence_failures(mut self, convergence_failures: usize) -> Self {
        self.convergence_failures = convergence_failures;
        self
    }

    pub fn with_adams_step_cost_estimate(mut self, cost: f64) -> Self {
        self.adams_step_cost_estimate = Some(cost);
        self
    }

    pub fn with_bdf_step_cost_estimate(mut self, cost: f64) -> Self {
        self.bdf_step_cost_estimate = Some(cost);
        self
    }

    pub fn with_adams_cost_samples(mut self, samples: usize) -> Self {
        self.adams_cost_samples = samples;
        self
    }

    pub fn with_bdf_cost_samples(mut self, samples: usize) -> Self {
        self.bdf_cost_samples = samples;
        self
    }

    pub fn with_adams_step_size_cap_estimate(mut self, rh1_like: f64) -> Self {
        self.adams_step_size_cap_estimate = Some(rh1_like);
        self
    }

    pub fn with_bdf_step_size_cap_estimate(mut self, rh2_like: f64) -> Self {
        self.bdf_step_size_cap_estimate = Some(rh2_like);
        self
    }
}

impl Default for Lsode2SwitchTelemetry {
    fn default() -> Self {
        Self::quiet_nonstiff()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lsode2SwitchReason {
    FixedController,
    SwitchProbeWarmup,
    InsufficientCostEvidence,
    SwitchAdvantageNotMet,
    NonstiffPreference,
    CostPreferenceAdams,
    CostPreferenceBdf,
    StiffnessSuspected,
    ConvergenceTrouble,
    AdamsEngineUnavailable,
}

impl Lsode2SwitchReason {
    pub fn label(self) -> &'static str {
        match self {
            Self::FixedController => "fixed_controller",
            Self::SwitchProbeWarmup => "switch_probe_warmup",
            Self::InsufficientCostEvidence => "insufficient_cost_evidence",
            Self::SwitchAdvantageNotMet => "switch_advantage_not_met",
            Self::NonstiffPreference => "nonstiff_preference",
            Self::CostPreferenceAdams => "cost_preference_adams",
            Self::CostPreferenceBdf => "cost_preference_bdf",
            Self::StiffnessSuspected => "stiffness_suspected",
            Self::ConvergenceTrouble => "convergence_trouble",
            Self::AdamsEngineUnavailable => "adams_engine_unavailable",
        }
    }
}

/// One method-family decision produced by the LSODE2 controller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Lsode2SwitchDecision {
    pub preferred_family: Lsode2MethodFamily,
    pub executable_family: Option<Lsode2MethodFamily>,
    pub uses_fallback: bool,
    pub reason: Lsode2SwitchReason,
    pub message: &'static str,
}

impl Lsode2SwitchDecision {
    pub fn executed_family(self) -> Option<Lsode2MethodFamily> {
        self.executable_family
    }
}

/// ODEPACK-like method-switch state (`MUSED`/`MCUR`) for observability.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Lsode2MethodSwitchState {
    pub mused: Lsode2MethodFamily,
    pub mcur: Lsode2MethodFamily,
    pub tsw: Option<f64>,
    pub last_handoff_jstart: Option<i32>,
    pub switch_count: usize,
    pub decision_count: usize,
    pub fallback_count: usize,
    pub switch_probe_initial_countdown: usize,
    pub switch_probe_countdown: isize,
    pub switch_probe_ready: bool,
}

impl Default for Lsode2MethodSwitchState {
    fn default() -> Self {
        Self {
            mused: Lsode2MethodFamily::Bdf,
            mcur: Lsode2MethodFamily::Bdf,
            tsw: None,
            last_handoff_jstart: None,
            switch_count: 0,
            decision_count: 0,
            fallback_count: 0,
            switch_probe_initial_countdown: LSODE2_DEFAULT_METHOD_SWITCH_PROBE_STEPS,
            switch_probe_countdown: LSODE2_DEFAULT_METHOD_SWITCH_PROBE_STEPS as isize,
            switch_probe_ready: false,
        }
    }
}

impl Lsode2MethodSwitchState {
    pub fn record_decision(&mut self, decision: Lsode2SwitchDecision) {
        self.record_decision_at(decision, None);
    }

    pub fn record_decision_at(&mut self, decision: Lsode2SwitchDecision, switch_time: Option<f64>) {
        self.decision_count += 1;
        if decision.uses_fallback {
            self.fallback_count += 1;
        }
        let next = decision
            .executed_family()
            .unwrap_or(decision.preferred_family);
        if self.mcur != next {
            self.switch_count += 1;
            self.mused = self.mcur;
            self.mcur = next;
            self.tsw = switch_time.filter(|value| value.is_finite());
            self.last_handoff_jstart = Some(-1);
            // ODEPACK DSTODA parity:
            // after a successful method switch, `ICOUNT` is reset to its
            // initial value (20 by default) before the next probe window.
            self.switch_probe_countdown = self.switch_probe_initial_countdown as isize;
            self.switch_probe_ready = false;
        } else {
            self.mused = self.mcur;
            self.last_handoff_jstart = None;
        }
    }

    pub fn set_switch_probe_initial_countdown(&mut self, initial_countdown: usize) {
        self.switch_probe_initial_countdown = initial_countdown;
        self.switch_probe_countdown = initial_countdown as isize;
        self.switch_probe_ready = false;
    }

    pub fn switch_probe_countdown(&self) -> isize {
        self.switch_probe_countdown
    }

    pub fn switch_probe_ready(&self) -> bool {
        self.switch_probe_ready
    }

    pub fn record_accepted_step_for_probe(&mut self) {
        self.switch_probe_countdown -= 1;
        if self.switch_probe_countdown < 0 {
            self.switch_probe_ready = true;
        }
    }

    pub fn record_accepted_steps_for_probe(&mut self, accepted_steps: usize) {
        for _ in 0..accepted_steps {
            self.record_accepted_step_for_probe();
        }
    }

    pub fn consume_switch_probe_gate(&mut self) -> bool {
        let ready = self.switch_probe_ready;
        self.switch_probe_ready = false;
        ready
    }
}

/// Extracted method-switch policy for Adams/BDF decision logic.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Lsode2MethodSwitchPolicy {
    pub stiffness_ratio_threshold: f64,
    /// Optional override for forcing BDF on repeated convergence trouble.
    ///
    /// DSTODA method switching is primarily step-size/cost driven; this
    /// threshold is therefore disabled by default and can be enabled
    /// explicitly when such override is desired.
    pub convergence_failure_threshold: usize,
    /// Optional override for forcing BDF on repeated rejected steps.
    ///
    /// Disabled by default for DSTODA-faithful automatic switching.
    pub rejection_threshold: usize,
    pub minimum_accepted_steps_for_nonstiff_probe: usize,
    /// Require Adams to be this much cheaper than BDF to trigger cost-based
    /// Adams preference (`adams_cost <= ratio * bdf_cost`).
    pub adams_cost_ratio_for_switch: f64,
    /// Require BDF to be this much cheaper than Adams to trigger cost-based
    /// BDF preference (`bdf_cost <= ratio * adams_cost`).
    pub bdf_cost_ratio_for_switch: f64,
    /// Minimum number of cost samples for each family before allowing
    /// cost-driven Adams/BDF switching.
    pub min_cost_samples_for_switch: usize,
    /// DSTODA ratio gate used in Adams<->BDF method-switch tests.
    ///
    /// In the original DSTODA choreography this is initialized to 5.0 and
    /// participates in the `rh1/rh2` step-advantage tests.
    pub switch_advantage_ratio: f64,
}

impl Default for Lsode2MethodSwitchPolicy {
    fn default() -> Self {
        Self {
            stiffness_ratio_threshold: LSODE2_DEFAULT_STIFFNESS_RATIO_THRESHOLD,
            convergence_failure_threshold: usize::MAX,
            rejection_threshold: usize::MAX,
            minimum_accepted_steps_for_nonstiff_probe: LSODE2_DEFAULT_METHOD_SWITCH_PROBE_STEPS,
            adams_cost_ratio_for_switch: 0.85,
            bdf_cost_ratio_for_switch: 0.85,
            min_cost_samples_for_switch: 3,
            switch_advantage_ratio: 5.0,
        }
    }
}

impl Lsode2MethodSwitchPolicy {
    pub fn with_stiffness_ratio_threshold(mut self, threshold: f64) -> Self {
        self.stiffness_ratio_threshold = threshold;
        self
    }

    pub fn with_minimum_accepted_steps_for_nonstiff_probe(mut self, accepted_steps: usize) -> Self {
        self.minimum_accepted_steps_for_nonstiff_probe = accepted_steps;
        self
    }

    pub fn with_adams_cost_ratio_for_switch(mut self, ratio: f64) -> Self {
        self.adams_cost_ratio_for_switch = ratio;
        self
    }

    pub fn with_bdf_cost_ratio_for_switch(mut self, ratio: f64) -> Self {
        self.bdf_cost_ratio_for_switch = ratio;
        self
    }

    pub fn with_min_cost_samples_for_switch(mut self, samples: usize) -> Self {
        self.min_cost_samples_for_switch = samples.max(1);
        self
    }

    pub fn with_switch_advantage_ratio(mut self, ratio: f64) -> Self {
        self.switch_advantage_ratio = ratio;
        self
    }

    fn should_probe_nonstiff_switch(self, accepted_steps: usize) -> bool {
        // Stateless approximation of DSTODA's ICOUNT gate:
        // with initial ICOUNT = 20 the first probe is on accepted step 21.
        // (Stateful controller path keeps exact per-step gate semantics.)
        accepted_steps > self.minimum_accepted_steps_for_nonstiff_probe
    }

    pub fn preferred_family_and_reason(
        self,
        mode: Lsode2ControllerMode,
        telemetry: Lsode2SwitchTelemetry,
    ) -> (Lsode2MethodFamily, Lsode2SwitchReason) {
        self.preferred_family_and_reason_with_probe_gate(mode, telemetry, None)
    }

    pub fn preferred_family_and_reason_with_probe_gate(
        self,
        mode: Lsode2ControllerMode,
        telemetry: Lsode2SwitchTelemetry,
        probe_gate: Option<bool>,
    ) -> (Lsode2MethodFamily, Lsode2SwitchReason) {
        self.preferred_family_and_reason_with_probe_gate_and_current(
            mode, telemetry, probe_gate, None,
        )
    }

    pub fn preferred_family_and_reason_with_probe_gate_and_current(
        self,
        mode: Lsode2ControllerMode,
        telemetry: Lsode2SwitchTelemetry,
        probe_gate: Option<bool>,
        current_family: Option<Lsode2MethodFamily>,
    ) -> (Lsode2MethodFamily, Lsode2SwitchReason) {
        match mode {
            Lsode2ControllerMode::AdamsOnly => (
                Lsode2MethodFamily::Adams,
                Lsode2SwitchReason::FixedController,
            ),
            Lsode2ControllerMode::BdfOnly => {
                (Lsode2MethodFamily::Bdf, Lsode2SwitchReason::FixedController)
            }
            Lsode2ControllerMode::AutomaticAdamsBdf => {
                let current = current_family.unwrap_or(Lsode2MethodFamily::Bdf);
                let force_bdf_on_convergence_trouble = self.convergence_failure_threshold
                    != usize::MAX
                    && telemetry.convergence_failures >= self.convergence_failure_threshold;
                let force_bdf_on_rejections = self.rejection_threshold != usize::MAX
                    && telemetry.rejected_steps >= self.rejection_threshold;
                if force_bdf_on_convergence_trouble || force_bdf_on_rejections {
                    return (
                        Lsode2MethodFamily::Bdf,
                        Lsode2SwitchReason::ConvergenceTrouble,
                    );
                }
                if telemetry
                    .stiffness_ratio
                    .is_some_and(|ratio| ratio >= self.stiffness_ratio_threshold)
                {
                    return (
                        Lsode2MethodFamily::Bdf,
                        Lsode2SwitchReason::StiffnessSuspected,
                    );
                }
                let probe_nonstiff = probe_gate
                    .unwrap_or_else(|| self.should_probe_nonstiff_switch(telemetry.accepted_steps));
                if !probe_nonstiff {
                    return (current, Lsode2SwitchReason::SwitchProbeWarmup);
                }
                // DSTODA-style method-switch gate via step-size advantage:
                // - if currently BDF: switch to Adams only if `rh1 * ratio >= 5 * rh2`;
                // - if currently Adams: switch to BDF only if `rh2 >= ratio * rh1`.
                let has_any_step_advantage_telemetry =
                    telemetry.adams_step_size_cap_estimate.is_some()
                        || telemetry.bdf_step_size_cap_estimate.is_some();
                if let (Some(rh1), Some(rh2)) = (
                    telemetry.adams_step_size_cap_estimate,
                    telemetry.bdf_step_size_cap_estimate,
                ) {
                    if rh1.is_finite()
                        && rh2.is_finite()
                        && rh1 > 0.0
                        && rh2 > 0.0
                        && self.switch_advantage_ratio.is_finite()
                        && self.switch_advantage_ratio > 0.0
                    {
                        if current == Lsode2MethodFamily::Bdf {
                            if rh1 * self.switch_advantage_ratio >= 5.0 * rh2 {
                                return (
                                    Lsode2MethodFamily::Adams,
                                    Lsode2SwitchReason::NonstiffPreference,
                                );
                            }
                        } else if rh2 >= self.switch_advantage_ratio * rh1 {
                            return (
                                Lsode2MethodFamily::Bdf,
                                Lsode2SwitchReason::StiffnessSuspected,
                            );
                        }
                        return (current, Lsode2SwitchReason::SwitchAdvantageNotMet);
                    }
                    return (current, Lsode2SwitchReason::SwitchAdvantageNotMet);
                }
                // Fortran-style branch precedence: once DSTODA-style RH
                // telemetry participates in the switch branch, incomplete
                // telemetry is still a step-advantage hold, not permission to
                // fall through to the cost branch.
                if has_any_step_advantage_telemetry {
                    return (current, Lsode2SwitchReason::SwitchAdvantageNotMet);
                }
                if let (Some(adams_cost), Some(bdf_cost)) = (
                    telemetry.adams_step_cost_estimate,
                    telemetry.bdf_step_cost_estimate,
                ) {
                    if telemetry.adams_cost_samples < self.min_cost_samples_for_switch
                        || telemetry.bdf_cost_samples < self.min_cost_samples_for_switch
                    {
                        return (current, Lsode2SwitchReason::InsufficientCostEvidence);
                    }
                    if adams_cost.is_finite()
                        && bdf_cost.is_finite()
                        && adams_cost > 0.0
                        && bdf_cost > 0.0
                    {
                        if adams_cost <= self.adams_cost_ratio_for_switch * bdf_cost {
                            return (
                                Lsode2MethodFamily::Adams,
                                Lsode2SwitchReason::CostPreferenceAdams,
                            );
                        }
                        if bdf_cost <= self.bdf_cost_ratio_for_switch * adams_cost {
                            return (
                                Lsode2MethodFamily::Bdf,
                                Lsode2SwitchReason::CostPreferenceBdf,
                            );
                        }
                        return (current, Lsode2SwitchReason::SwitchAdvantageNotMet);
                    }
                }
                (current, Lsode2SwitchReason::SwitchAdvantageNotMet)
            }
        }
    }
}

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

    #[test]
    fn policy_prefers_adams_for_quiet_automatic_case() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let (family, reason) = policy.preferred_family_and_reason(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            Lsode2SwitchTelemetry::quiet_nonstiff().with_accepted_steps(21),
        );
        assert_eq!(family, Lsode2MethodFamily::Bdf);
        assert_eq!(reason, Lsode2SwitchReason::SwitchAdvantageNotMet);
    }

    #[test]
    fn policy_keeps_bdf_during_switch_probe_warmup() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let (family, reason) = policy.preferred_family_and_reason(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            Lsode2SwitchTelemetry::quiet_nonstiff().with_accepted_steps(3),
        );
        assert_eq!(family, Lsode2MethodFamily::Bdf);
        assert_eq!(reason, Lsode2SwitchReason::SwitchProbeWarmup);
    }

    #[test]
    fn policy_only_probes_on_icount_equivalent_boundaries() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let (f20, r20) = policy.preferred_family_and_reason(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            Lsode2SwitchTelemetry::quiet_nonstiff().with_accepted_steps(20),
        );
        assert_eq!(f20, Lsode2MethodFamily::Bdf);
        assert_eq!(r20, Lsode2SwitchReason::SwitchProbeWarmup);

        let (f21, r21) = policy.preferred_family_and_reason(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            Lsode2SwitchTelemetry::quiet_nonstiff().with_accepted_steps(21),
        );
        assert_eq!(f21, Lsode2MethodFamily::Bdf);
        assert_eq!(r21, Lsode2SwitchReason::SwitchAdvantageNotMet);
    }

    #[test]
    fn policy_prefers_bdf_for_stiffness_or_convergence_signals() {
        let policy = Lsode2MethodSwitchPolicy {
            convergence_failure_threshold: 1,
            rejection_threshold: 2,
            ..Lsode2MethodSwitchPolicy::default().with_stiffness_ratio_threshold(10.0)
        };
        let (stiff_family, stiff_reason) = policy.preferred_family_and_reason(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            Lsode2SwitchTelemetry::default().with_stiffness_ratio(12.0),
        );
        assert_eq!(stiff_family, Lsode2MethodFamily::Bdf);
        assert_eq!(stiff_reason, Lsode2SwitchReason::StiffnessSuspected);

        let (conv_family, conv_reason) = policy.preferred_family_and_reason(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            Lsode2SwitchTelemetry::default().with_convergence_failures(1),
        );
        assert_eq!(conv_family, Lsode2MethodFamily::Bdf);
        assert_eq!(conv_reason, Lsode2SwitchReason::ConvergenceTrouble);
    }

    #[test]
    fn policy_default_does_not_force_bdf_from_convergence_override() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let (family, reason) = policy.preferred_family_and_reason(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            Lsode2SwitchTelemetry::default()
                .with_accepted_steps(32)
                .with_convergence_failures(999)
                .with_rejected_steps(999),
        );
        assert_eq!(family, Lsode2MethodFamily::Bdf);
        assert_eq!(reason, Lsode2SwitchReason::SwitchAdvantageNotMet);
    }

    #[test]
    fn policy_can_use_cost_based_preference_after_probe_gate() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let telemetry = Lsode2SwitchTelemetry::quiet_nonstiff()
            .with_accepted_steps(32)
            .with_adams_step_cost_estimate(0.5)
            .with_bdf_step_cost_estimate(1.0)
            .with_adams_cost_samples(3)
            .with_bdf_cost_samples(3);
        let (family_adams, reason_adams) =
            policy.preferred_family_and_reason(Lsode2ControllerMode::AutomaticAdamsBdf, telemetry);
        assert_eq!(family_adams, Lsode2MethodFamily::Adams);
        assert_eq!(reason_adams, Lsode2SwitchReason::CostPreferenceAdams);

        let telemetry = Lsode2SwitchTelemetry::quiet_nonstiff()
            .with_accepted_steps(32)
            .with_adams_step_cost_estimate(1.0)
            .with_bdf_step_cost_estimate(0.5)
            .with_adams_cost_samples(3)
            .with_bdf_cost_samples(3);
        let (family_bdf, reason_bdf) =
            policy.preferred_family_and_reason(Lsode2ControllerMode::AutomaticAdamsBdf, telemetry);
        assert_eq!(family_bdf, Lsode2MethodFamily::Bdf);
        assert_eq!(reason_bdf, Lsode2SwitchReason::CostPreferenceBdf);
    }

    #[test]
    fn policy_requires_minimum_cost_samples_for_cost_based_switch() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let telemetry = Lsode2SwitchTelemetry::quiet_nonstiff()
            .with_accepted_steps(32)
            .with_adams_step_cost_estimate(0.5)
            .with_bdf_step_cost_estimate(1.0)
            .with_adams_cost_samples(1)
            .with_bdf_cost_samples(3);
        let (family, reason) =
            policy.preferred_family_and_reason(Lsode2ControllerMode::AutomaticAdamsBdf, telemetry);
        assert_eq!(family, Lsode2MethodFamily::Bdf);
        assert_eq!(reason, Lsode2SwitchReason::InsufficientCostEvidence);
    }

    #[test]
    fn policy_dstoda_step_advantage_gate_can_switch_bdf_to_adams() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let telemetry = Lsode2SwitchTelemetry::quiet_nonstiff()
            .with_accepted_steps(32)
            .with_adams_step_size_cap_estimate(2.0)
            .with_bdf_step_size_cap_estimate(1.0);
        let (family, reason) = policy.preferred_family_and_reason_with_probe_gate_and_current(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            telemetry,
            Some(true),
            Some(Lsode2MethodFamily::Bdf),
        );
        assert_eq!(family, Lsode2MethodFamily::Adams);
        assert_eq!(reason, Lsode2SwitchReason::NonstiffPreference);
    }

    #[test]
    fn policy_dstoda_step_advantage_gate_can_switch_adams_to_bdf() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let telemetry = Lsode2SwitchTelemetry::quiet_nonstiff()
            .with_accepted_steps(32)
            .with_adams_step_size_cap_estimate(1.0)
            .with_bdf_step_size_cap_estimate(5.0);
        let (family, reason) = policy.preferred_family_and_reason_with_probe_gate_and_current(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            telemetry,
            Some(true),
            Some(Lsode2MethodFamily::Adams),
        );
        assert_eq!(family, Lsode2MethodFamily::Bdf);
        assert_eq!(reason, Lsode2SwitchReason::StiffnessSuspected);
    }

    #[test]
    fn policy_dstoda_step_advantage_gate_reports_hold_when_advantage_not_met() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let telemetry = Lsode2SwitchTelemetry::quiet_nonstiff()
            .with_accepted_steps(32)
            .with_adams_step_size_cap_estimate(0.9)
            .with_bdf_step_size_cap_estimate(1.0);
        let (family, reason) = policy.preferred_family_and_reason_with_probe_gate_and_current(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            telemetry,
            Some(true),
            Some(Lsode2MethodFamily::Bdf),
        );
        assert_eq!(family, Lsode2MethodFamily::Bdf);
        assert_eq!(reason, Lsode2SwitchReason::SwitchAdvantageNotMet);
    }

    #[test]
    fn policy_prefers_step_advantage_hold_reason_when_dstoda_telemetry_is_partial() {
        let policy = Lsode2MethodSwitchPolicy::default();
        let telemetry = Lsode2SwitchTelemetry::quiet_nonstiff()
            .with_accepted_steps(32)
            .with_adams_step_size_cap_estimate(1.2);
        let (family, reason) = policy.preferred_family_and_reason_with_probe_gate_and_current(
            Lsode2ControllerMode::AutomaticAdamsBdf,
            telemetry,
            Some(true),
            Some(Lsode2MethodFamily::Bdf),
        );
        assert_eq!(family, Lsode2MethodFamily::Bdf);
        assert_eq!(reason, Lsode2SwitchReason::SwitchAdvantageNotMet);
    }

    #[test]
    fn state_tracks_mused_mcur_and_fallbacks() {
        let mut state = Lsode2MethodSwitchState::default();
        let first = Lsode2SwitchDecision {
            preferred_family: Lsode2MethodFamily::Adams,
            executable_family: Some(Lsode2MethodFamily::Bdf),
            uses_fallback: true,
            reason: Lsode2SwitchReason::AdamsEngineUnavailable,
            message: "fallback",
        };
        state.record_decision(first);
        assert_eq!(state.decision_count, 1);
        assert_eq!(state.fallback_count, 1);
        assert_eq!(state.switch_count, 0);
        assert_eq!(state.mcur, Lsode2MethodFamily::Bdf);
        assert_eq!(state.mused, Lsode2MethodFamily::Bdf);

        let second = Lsode2SwitchDecision {
            preferred_family: Lsode2MethodFamily::Adams,
            executable_family: Some(Lsode2MethodFamily::Adams),
            uses_fallback: false,
            reason: Lsode2SwitchReason::NonstiffPreference,
            message: "adams",
        };
        state.record_decision(second);
        assert_eq!(state.decision_count, 2);
        assert_eq!(state.fallback_count, 1);
        assert_eq!(state.switch_count, 1);
        assert_eq!(state.mcur, Lsode2MethodFamily::Adams);
        assert_eq!(state.mused, Lsode2MethodFamily::Bdf);
    }

    #[test]
    fn stateful_probe_countdown_mirrors_icount_style_periodicity() {
        let mut state = Lsode2MethodSwitchState::default();
        state.set_switch_probe_initial_countdown(20);

        for _ in 0..20 {
            state.record_accepted_step_for_probe();
            assert!(!state.switch_probe_ready());
        }
        assert_eq!(state.switch_probe_countdown(), 0);

        state.record_accepted_step_for_probe();
        assert!(state.switch_probe_ready());
        assert_eq!(state.switch_probe_countdown(), -1);
        assert!(state.consume_switch_probe_gate());
        assert!(!state.switch_probe_ready());

        state.record_accepted_step_for_probe();
        assert!(state.switch_probe_ready());
        assert_eq!(state.switch_probe_countdown(), -2);
    }

    #[test]
    fn switch_resets_icount_like_probe_countdown() {
        let mut state = Lsode2MethodSwitchState::default();
        state.set_switch_probe_initial_countdown(20);
        state.record_accepted_steps_for_probe(21);
        assert!(state.switch_probe_ready());

        state.record_decision(Lsode2SwitchDecision {
            preferred_family: Lsode2MethodFamily::Adams,
            executable_family: Some(Lsode2MethodFamily::Adams),
            uses_fallback: false,
            reason: Lsode2SwitchReason::NonstiffPreference,
            message: "switch",
        });

        assert_eq!(state.switch_probe_countdown(), 20);
        assert!(!state.switch_probe_ready());
    }
}