tradefloor 0.11.0

A reproducible evaluation environment for financial AI agents.
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
//! Business-cycle transitions, ported from the reference implementation's
//! economy module.
//!
//! Phase duration is modelled as a Weibull hazard rather than a fixed length,
//! so how long a phase has already lasted changes how likely it is to end.
//! `shape > 1` means an ageing phase grows fragile (expansions); `shape < 1`
//! means early exits dominate and late ones linger (contractions).
//!
//! # The clock every rate here is on
//!
//! Every scale in [`cycle_hazard_params`] is in MONTHS, so
//! [`weibull_hazard`] returns a rate per month, and so does the condition
//! ladder that adds to it and the clamp that bounds it.
//! `months_in_current_phase` advances by `1/30` a day, which makes the month
//! this model keeps 30 days long. [`check_cycle_transition`] draws once a
//! day, so the monthly rate is converted at the draw under
//! `cycle_hazard_per_month`. At 0.0 it is drawn as written, which is the
//! reference implementation's reading and about thirty times the rate its
//! own parameters state.

use super::state::*;
use crate::mathx::{self, clamp_via_min_max as clamp};
use crate::rng::Rng;

/// Weibull hazard, capped at 0.8.
///
/// `pow(t, shape - 1)` changes character across `shape == 1`: below it the
/// exponent is negative and the hazard falls with duration, above it the
/// hazard rises. The configured shapes straddle that boundary (0.7 for
/// contraction, 1.3–2.0 elsewhere), so both regimes are live.
pub fn weibull_hazard(months: f64, shape: f64, scale: f64) -> f64 {
    // `months <= 0` — NOT the negated form used elsewhere in the crate,
    // because the original is `if (months <= 0) return 0`. A NaN month
    // therefore falls THROUGH here and produces NaN, where `!(months > 0)`
    // would have returned 0.
    if months <= 0.0 {
        return 0.0;
    }
    let t = months / scale;
    mathx::min(0.8, (shape / scale) * mathx::pow(t, shape - 1.0))
}

/// The monthly hazard read on the day it is drawn.
///
/// A BRANCH at 0.0, so every preset before pt-v18 compares the monthly rate
/// against the uniform exactly as the reference implementation does. At 1.0
/// the arithmetic is `monthly / 30.0` to the last bit, because `30 - 29` is
/// exact and `x / 1.0` is `x`. In between, the share of the correction
/// applied is linear in the probability.
///
/// See [`crate::params::ModelParams::cycle_hazard_per_month`] for why the
/// conversion belongs here rather than inside [`weibull_hazard`] or before
/// the clamp.
#[inline]
fn per_day(monthly: f64, spec: &CycleSpec) -> f64 {
    let per_month = spec.per_month;
    if per_month == 0.0 {
        monthly
    } else {
        // `m - (m - 1.0)` with `m` = 30.0 is `30.0 - 29.0`, the literal
        // that stood here, operation for operation.
        let m = spec.month_days;
        monthly * (m - (m - 1.0) * per_month) / m
    }
}

/// The clock and the table the cycle reads.
///
/// `per_month` is `cycle_hazard_per_month`; `month_days` is the macro
/// month in economy steps (30.0 as shipped, see `MacroCalendar`); `us` is
/// `cycle_us_calibration != 0.0`, the phase table derived from NBER and BEA
/// (see [`phase_characteristics_for`]). [`CycleSpec::shipped`] is what every
/// preset reads, and the functions that take `per_month` alone take it.
///
/// `equity_hazard` and `equity_knee` are `cycle_equity_hazard` and
/// `cycle_equity_hazard_knee`: monthly hazard added in an expansion and at a
/// peak per unit of `EconomyState::spread_equity_gap` beyond the knee. 0.0
/// adds nothing, and the ladder is the one that stood.
///
/// `equity_opening` is `cycle_equity_hazard_opening` where the economy runs
/// without a market (the engine sets it only for the stationary opening and
/// the macro burn-in, and 0.0 in every session): monthly hazard added in an
/// expansion and at a peak, by the ladder and by the hazard-only law the
/// opening is drawn from. 0.0 adds nothing.
///
/// `inflation_hazard` and `rate_hazard` are `cycle_inflation_hazard` and
/// `cycle_rate_hazard`: the monthly hazard an expansion adds with inflation
/// above 4 and with the funds rate above 5. 0.0 is the legacy 0.1 each.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct CycleSpec {
    pub per_month: f64,
    pub month_days: f64,
    pub us: bool,
    pub equity_hazard: f64,
    pub equity_knee: f64,
    pub equity_opening: f64,
    pub inflation_hazard: f64,
    pub rate_hazard: f64,
}

impl CycleSpec {
    pub const fn shipped(per_month: f64) -> Self {
        CycleSpec {
            per_month, month_days: 30.0, us: false,
            equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
            inflation_hazard: 0.0, rate_hazard: 0.0,
        }
    }
}

/// Phase-specific Weibull parameters.
///
/// Every scale is in MONTHS. See this module's own note on the clock.
pub fn cycle_hazard_params(phase: CyclePhase) -> (f64, f64) {
    cycle_hazard_params_for(phase, false)
}

/// [`cycle_hazard_params`], or the NBER-derived table when `us` is set. See
/// [`phase_characteristics_for`] for the derivation.
pub fn cycle_hazard_params_for(phase: CyclePhase, us: bool) -> (f64, f64) {
    if us {
        return us_cycle_hazard_params(phase);
    }
    match phase {
        // Long expansions get increasingly fragile.
        CyclePhase::Expansion => (1.8, 36.0),
        // Peaks are unstable and transition quickly.
        CyclePhase::Peak => (2.0, 6.0),
        // Early contractions exit fast, late ones linger.
        CyclePhase::Contraction => (0.7, 12.0),
        // Troughs self-limit fairly quickly.
        CyclePhase::Trough => (1.5, 4.0),
        // Recovery builds momentum, then transitions.
        CyclePhase::Recovery => (1.3, 12.0),
    }
}

/// The daily transition probability and the phase it would move to.
///
/// This is `getCycleTransitionProbability` — the UI-safe form that computes
/// the probability **without rolling the dice**. The original duplicates the
/// condition ladder between this and [`check_cycle_transition`]; here the two
/// share `adjust_transition_probability`, on the evidence recorded there.
pub fn get_cycle_transition_probability(
    economy: &EconomyState,
    per_month: f64,
) -> (f64, CyclePhase) {
    get_cycle_transition_probability_for(economy, &CycleSpec::shipped(per_month))
}

/// [`get_cycle_transition_probability`] on a given clock and table.
pub fn get_cycle_transition_probability_for(
    economy: &EconomyState,
    spec: &CycleSpec,
) -> (f64, CyclePhase) {
    let phase = phase_characteristics_for(economy.cycle_phase, spec.us);
    let months = economy.months_in_current_phase;
    if months < phase.min_months {
        return (0.0, phase.next_phase);
    }

    let (shape, scale) = cycle_hazard_params_for(economy.cycle_phase, spec.us);
    let p = adjust_transition_probability(economy, weibull_hazard(months, shape, scale), spec);

    (per_day(clamp(p, 0.0, hazard_cap(spec.us)), spec), phase.next_phase)
}

/// The cap on the monthly hazard: 0.3 as shipped. The US table raises it,
/// see [`phase_characteristics_for`].
#[inline]
pub fn hazard_cap(us: bool) -> f64 {
    if us { US_HAZARD_CAP } else { 0.3 }
}

/// The condition ladder shared, in the original, by both entry points.
///
/// Factored out here only because the two copies in the reference implementation are
/// semantically identical — compared branch by branch, not assumed. They are
/// not textually identical (one inlines the inversion depth, the other binds
/// it to a temporary), but every condition, constant and operation matches.
/// If they ever diverge upstream this must split back into two.
fn adjust_transition_probability(economy: &EconomyState, p: f64, spec: &CycleSpec) -> f64 {
    adjust_transition_probability_in(economy, economy.cycle_phase, p, spec, None)
}

/// [`adjust_transition_probability`] with the phase read from `phase`
/// rather than from `economy`, so the forecast can read the ladder for a
/// phase the economy is not in without copying it. `equity_excess`, when
/// given, stands in for the market's fall beyond the knee,
/// `max(0, gap - knee)`: the forecast passes its expectation over the gap's
/// spread. The law passes `None`, the same arithmetic.
fn adjust_transition_probability_in(
    economy: &EconomyState,
    phase: CyclePhase,
    mut p: f64,
    spec: &CycleSpec,
    equity_excess: Option<f64>,
) -> f64 {
    // THE MARKET'S FALL (`cycle_equity_hazard`): in an expansion and at a
    // peak, monthly hazard per unit of the index's log fall below its slow
    // average beyond the knee. Added first, so the expansion's guard below
    // still takes its 0.2 off an economy that has not recovered. Guarded,
    // so at 0.0 the ladder is the one that stood, operation for operation.
    if spec.equity_hazard != 0.0
        && matches!(phase, CyclePhase::Expansion | CyclePhase::Peak)
    {
        p += spec.equity_hazard
            * equity_excess.unwrap_or_else(|| mathx::max(0.0, economy.spread_equity_gap - spec.equity_knee));
    }
    // THE MARKET'S AVERAGE WHERE THERE IS NO MARKET
    // (`cycle_equity_hazard_opening`): the engine sets it only while the
    // economy runs alone, before day zero. Guarded likewise.
    if spec.equity_opening != 0.0
        && matches!(phase, CyclePhase::Expansion | CyclePhase::Peak)
    {
        p += spec.equity_opening;
    }
    match phase {
        CyclePhase::Expansion => {
            // THE INFLATION AND RATE HAZARDS (`cycle_inflation_hazard`,
            // `cycle_rate_hazard`): the legacy 0.1 a month each, or off zero
            // the dial's. NBER peaks 1962-2025 on these two conditions and
            // the inversion term below: +0.022 and +0.001. Branches: at 0.0
            // the ladder is the one that stood, operation for operation.
            if economy.inflation_rate > 4.0 {
                p += if spec.inflation_hazard != 0.0 { spec.inflation_hazard } else { 0.1 };
            }
            if economy.federal_funds_rate > 5.0 {
                p += if spec.rate_hazard != 0.0 { spec.rate_hazard } else { 0.1 };
            }
            // Curve inversion has preceded every US recession since 1955.
            if economy.treasury_yield_2y > economy.treasury_yield_10y {
                let inversion_depth = economy.treasury_yield_2y - economy.treasury_yield_10y;
                p += mathx::min(0.15, inversion_depth * 0.08);
            }
            // Expensive markets are fragile.
            let mkt_pe = economy.market_pe.unwrap_or(18.0);
            if mkt_pe > 28.0 {
                p += mathx::min(0.1, (mkt_pe - 28.0) * 0.005);
            }
            // Guard: an expansion should not peak while unemployment is still
            // high or GDP is negative — the economy has not recovered yet.
            if economy.unemployment_rate > 8.0 || economy.gdp_growth < 1.0 {
                p = mathx::max(0.0, p - 0.2);
            }
        }
        CyclePhase::Recovery => {
            if economy.unemployment_rate > 10.0 {
                p = mathx::max(0.0, p - 0.1);
            }
        }
        CyclePhase::Contraction => {
            if economy.federal_funds_rate < 1.0 {
                p += 0.1;
            }
            // An economy cannot contract forever; it bottoms out even without
            // rate cuts.
            if economy.gdp_growth < -2.0 {
                p += 0.05;
            }
            if economy.unemployment_rate > 10.0 {
                p += 0.05;
            }
            // A steepening curve signals recovery approaching.
            if economy.treasury_yield_10y - economy.treasury_yield_2y > 1.5 {
                p += 0.05;
            }
        }
        CyclePhase::Trough => {
            if economy.federal_funds_rate < 3.0 {
                p += 0.1;
            }
            // Very high unemployment builds pent-up demand.
            if economy.unemployment_rate > 8.0 {
                p += 0.05;
            }
        }
        CyclePhase::Peak => {}
    }
    p
}

/// Roll for a cycle transition.
///
/// **Draw schedule:** exactly **one uniform**, and only when the minimum
/// phase duration has elapsed. Below `min_months` the function returns before
/// drawing, so the count is 0-or-1 and never anything else.
pub fn check_cycle_transition(
    economy: &EconomyState,
    rng: &mut impl Rng,
    per_month: f64,
) -> EconomyState {
    check_cycle_transition_for(economy, rng, &CycleSpec::shipped(per_month))
}

/// [`check_cycle_transition`] on a given clock and table.
pub fn check_cycle_transition_for(
    economy: &EconomyState,
    rng: &mut impl Rng,
    spec: &CycleSpec,
) -> EconomyState {
    let phase = phase_characteristics_for(economy.cycle_phase, spec.us);
    let months = economy.months_in_current_phase;

    if months < phase.min_months {
        return economy.clone();
    }

    let (shape, scale) = cycle_hazard_params_for(economy.cycle_phase, spec.us);
    let p = adjust_transition_probability(economy, weibull_hazard(months, shape, scale), spec);
    // The cap on the hazard, at 0.3 of whatever unit the hazard carries.
    // Under the reference implementation's reading that is a 30 per cent
    // chance on any one day; under the monthly reading it caps a rate per
    // month and the largest daily probability is 0.01. On the hazard alone
    // it binds for a peak past month 5.40 and a trough past month 2.57, and
    // under either reading a trough with its own ladder saturates it on the
    // first eligible roll. See `ModelParams::cycle_hazard_per_month` for
    // the counts.
    let transition_probability = per_day(clamp(p, 0.0, hazard_cap(spec.us)), spec);

    if rng.next_f64() < transition_probability {
        let mut next = economy.clone();
        next.cycle_phase = phase.next_phase;
        next.months_in_current_phase = 0.0;
        return next;
    }

    economy.clone()
}

// ── The stationary law of (phase, age) ────────────────────────────────────
//
// A run whose day-zero phase is a POINT starts a cohort: thirty seeds leave
// their first expansion at nearly the same age and move through the first
// cycle in step, so year two is a synchronised recession. The fixed minimum
// durations make the cycle's length nearly deterministic, so the cohort does
// not damp away on any horizon a user runs. The remedy is to open at rest,
// and that needs the law below.

/// The five phases in the chain's own cyclic order.
///
/// Walked from `next_phase` rather than restated. The order is
/// [`phase_characteristics`]'s to declare, and a list here would be a
/// second spelling of it -- the class of defect that put a variance floor
/// in three places and let two of them disagree.
pub fn phase_cycle() -> [CyclePhase; 5] {
    let mut out = [CyclePhase::Expansion; 5];
    for k in 1..out.len() {
        out[k] = phase_characteristics(out[k - 1]).next_phase;
    }
    out
}

/// The transition probability [`check_cycle_transition`] compares against
/// its uniform on the `days`-th day of a phase, on the HAZARD ALONE.
///
/// That function's own arithmetic with [`adjust_transition_probability`]
/// taken as the identity, in the same order: the hazard, then the clamp,
/// then the per-day conversion.
///
/// # Why the ladder is absent, and where it is handled instead
///
/// `adjust_transition_probability` adds to the hazard from the MACRO
/// STATE -- inflation above 4, a policy rate above 5, an inverted curve, a
/// market P/E above 28 in expansion -- so the true stationary law depends
/// on the fields, which depend on the phase path. There is no closed form
/// and this does not pretend one. The hazard-only law is what is DRAWN
/// from; the fields are then relaxed under the drawn phase by the
/// free-running burn-in, during which the ladder acts on the mix. The
/// residual is the difference between the two laws, measurable as the
/// occupancy of a long economy-only run.
///
/// # Days, not months
///
/// `months_in_current_phase` advances by `1/30` a day
/// (`economy/daily.rs`) and `check_cycle_transition` reads it AFTER that
/// advance, so the `d`-th day of a phase is checked at `d / 30` months and
/// the first check of a fresh phase is at `1/30`.
fn hazard_only_transition_probability(phase: CyclePhase, days: i64, spec: &CycleSpec) -> f64 {
    let months = days as f64 / spec.month_days;
    if months < phase_characteristics_for(phase, spec.us).min_months {
        return 0.0;
    }
    let (shape, scale) = cycle_hazard_params_for(phase, spec.us);
    let mut h = weibull_hazard(months, shape, scale);
    // The opening's stand-in for the market's hazard
    // (`cycle_equity_hazard_opening`), in an expansion and at a peak;
    // guarded, so at 0.0 the law is the one that stood.
    if spec.equity_opening != 0.0 && matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) {
        h += spec.equity_opening;
    }
    per_day(clamp(h, 0.0, hazard_cap(spec.us)), spec)
}

/// Walk a phase's hazard-only survival in days, and return the sum of it.
///
/// The visitor sees `(a, C(a))` for `a = 0, 1, 2, ...`, where
///
/// ```text
/// S(d) = prod_{t=1}^{d-1} (1 - p(t))     P(the sojourn survives d - 1 checks)
/// C(a) = sum_{d=1}^{a+1} S(d)            E[T] * P(age <= a)
/// ```
///
/// so the walk's own return value is `E[T] = sum_{d>=1} S(d)` when the
/// visitor never stops it, and the visitor is handed the unnormalised CDF
/// of the age at every step. Returning `false` stops the walk.
///
/// # Where it stops, and why that is exact rather than a tolerance
///
/// The walk ends when adding the next term leaves the f64 sum UNCHANGED --
/// the point past which no arithmetic this function could do would move
/// its answer. Nothing is chosen: the stopping rule is a property of the
/// representation. It always arrives, because `S` is non-increasing (the
/// transition probability is clamped to 0.3, so every factor is in
/// `[0.7, 1]`), is positive past the minimum duration, and the sum is
/// bounded above by `E[T]`.
///
/// Expressing `E[T]` and the age's CDF on ONE walk is what makes the age
/// law's support the mean's support by construction, rather than by two
/// truncations that happen to agree.
fn walk_survival(
    phase: CyclePhase,
    spec: &CycleSpec,
    mut visit: impl FnMut(i64, f64) -> bool,
) -> f64 {
    let (mut s, mut acc, mut a) = (1.0, 0.0, 0i64);
    loop {
        let next = acc + s;
        if next == acc {
            return acc;
        }
        acc = next;
        if !visit(a, acc) {
            return acc;
        }
        s *= 1.0 - hazard_only_transition_probability(phase, a + 1, spec);
        a += 1;
    }
}

/// `E[T]` for one phase, in DAYS, on the hazard alone.
///
/// `sum_{d>=1} S(d)`, which is the mean of a non-negative integer sojourn
/// written as the sum of its survival function.
pub fn mean_sojourn_days(phase: CyclePhase, per_month: f64) -> f64 {
    mean_sojourn_days_for(phase, &CycleSpec::shipped(per_month))
}

/// [`mean_sojourn_days`] on a given clock and table.
pub fn mean_sojourn_days_for(phase: CyclePhase, spec: &CycleSpec) -> f64 {
    walk_survival(phase, spec, |_, _| true)
}

/// The probability [`check_cycle_transition_for`] compares against for an
/// economy in `phase` on its `days`-th day, the ladder read from `economy`'s
/// fields as they stand: the hazard, the ladder, the clamp and the per-day
/// conversion, in that function's order. For the forecast's cycle
/// (`oil_forecast_cycle_growth`), which reads the law's own hazards at each
/// close on its own economy.
///
/// `gap_var` is the variance of the market's gap about `economy`'s, the
/// forecast's spread of the index's path. Off zero, the market's term reads
/// its expectation over a normal gap, `E max(0, G - knee) = x Phi(x / s) +
/// s phi(x / s)` with `x` the gap's mean less the knee, since the term is
/// convex in the gap; at zero it is the law's own.
pub fn transition_probability_for(
    economy: &EconomyState,
    phase: CyclePhase,
    days: f64,
    spec: &CycleSpec,
    gap_var: f64,
) -> f64 {
    let months = days / spec.month_days;
    if months < phase_characteristics_for(phase, spec.us).min_months {
        return 0.0;
    }
    let (shape, scale) = cycle_hazard_params_for(phase, spec.us);
    let excess = if gap_var > 0.0 && spec.equity_hazard != 0.0 {
        let s = mathx::sqrt(gap_var);
        let x = economy.spread_equity_gap - spec.equity_knee;
        let z = x / s;
        let cdf = 0.5 * mathx::erfc(-z / core::f64::consts::SQRT_2);
        let pdf = mathx::exp(-0.5 * z * z) / mathx::sqrt(2.0 * core::f64::consts::PI);
        Some(x * cdf + s * pdf)
    } else {
        None
    };
    let p = adjust_transition_probability_in(economy, phase, weibull_hazard(months, shape, scale), spec, excess);
    per_day(clamp(p, 0.0, hazard_cap(spec.us)), spec)
}

/// The `q` quantile of one phase's sojourn, in DAYS, on the hazard alone:
/// the smallest `d` with `P(T <= d) >= q`, on the same daily transition
/// probabilities [`mean_sojourn_days_for`] walks. The time-held fade's onset
/// (`market_vol_cycle_hold_onset`). `q` in [0, 1); a walk that never
/// reaches it (a hazard that is zero for good) returns `i64::MAX`.
pub fn sojourn_quantile_days_for(phase: CyclePhase, spec: &CycleSpec, q: f64) -> i64 {
    // `s` is P(T > d) after the d-th check.
    let mut s = 1.0;
    let mut d = 0i64;
    while d < 1_000_000 {
        d += 1;
        s *= 1.0 - hazard_only_transition_probability(phase, d, spec);
        if 1.0 - s >= q {
            return d;
        }
    }
    i64::MAX
}

/// The standard deviation of one phase's sojourn, in DAYS, on the hazard
/// alone: `E[T^2] = sum_{d>=1} (2d - 1) S(d)` less the square of
/// [`mean_sojourn_days_for`], on the same walk and the same stopping rule.
pub fn sojourn_sd_days_for(phase: CyclePhase, spec: &CycleSpec) -> f64 {
    let mut prev = 0.0;
    let mut second = 0.0;
    let mean = walk_survival(phase, spec, |a, c| {
        // C(a) - C(a - 1) is S(a + 1), the chance the sojourn reaches day a + 1.
        second += (2.0 * a as f64 + 1.0) * (c - prev);
        prev = c;
        true
    });
    mathx::sqrt(mathx::max(0.0, second - mean * mean))
}

/// The `q` quantile, in DAYS, of a contraction and the trough after it
/// taken together, on the hazard alone: the smallest `d` with
/// `P(T_c + T_t <= d) >= q`, the two sojourns independent as the hazard
/// draws them. `i64::MAX` when the walk never reaches `q`.
pub fn downturn_quantile_days_for(spec: &CycleSpec, q: f64) -> i64 {
    if !(q < 1.0) {
        return i64::MAX;
    }
    // pmf of the contraction, and the trough's CDF, grown together a day at a time.
    let (mut sc, mut st) = (1.0, 1.0);
    let mut pc: Vec<f64> = vec![0.0];
    let mut ft: Vec<f64> = vec![0.0];
    let mut d = 0usize;
    while d < 100_000 {
        d += 1;
        let p = hazard_only_transition_probability(CyclePhase::Contraction, d as i64, spec);
        pc.push(sc * p);
        sc *= 1.0 - p;
        st *= 1.0 - hazard_only_transition_probability(CyclePhase::Trough, d as i64, spec);
        ft.push(1.0 - st);
        let mut cdf = 0.0;
        for c in 1..d {
            cdf += pc[c] * ft[d - c];
        }
        if cdf >= q {
            return d as i64;
        }
    }
    i64::MAX
}

/// The stationary share of DAYS the chain spends in each phase, in
/// [`phase_cycle`] order, as unnormalised weights and their total.
///
/// ```text
/// pi_i = E[T_i] / sum_j E[T_j]
/// ```
///
/// The renewal-reward identity for a cyclic semi-Markov chain that visits
/// every phase exactly once per cycle: each phase is entered once per
/// cycle, so the share of days is the share of the cycle's length. That
/// the chain is cyclic is [`phase_cycle`]'s own assertion, not an
/// assumption made here.
pub fn stationary_phase_shares(per_month: f64) -> ([f64; 5], f64) {
    stationary_phase_shares_for(&CycleSpec::shipped(per_month))
}

/// [`stationary_phase_shares`] on a given clock and table.
pub fn stationary_phase_shares_for(spec: &CycleSpec) -> ([f64; 5], f64) {
    // A pure function of the spec's fields, and the engine asks for
    // it on every close through `earnings_anticipation_terms`: 755 times
    // during pt-v20's macro burn-in alone, each a survival walk of about a
    // thousand `pow` calls per phase. It was 96 per cent of pt-v20's
    // construction time. The memo holds the last spec and its answer,
    // keyed on the fields' BITS, so a hit returns the very value the walk
    // would have produced and no result can move.
    // Every field is in the key, the market's opening hazard
    // (`equity_opening`) included, which the walk reads; the two hazard
    // terms it does not read are keyed too, so a field the walk comes to
    // read later cannot be served a stale answer.
    type Key = (u64, u64, bool, u64, u64, u64);
    type Shares = ([f64; 5], f64);
    thread_local! {
        static LAST: std::cell::Cell<Option<(Key, Shares)>> =
            const { std::cell::Cell::new(None) };
    }
    let key: Key = (
        spec.per_month.to_bits(),
        spec.month_days.to_bits(),
        spec.us,
        spec.equity_hazard.to_bits(),
        spec.equity_knee.to_bits(),
        spec.equity_opening.to_bits(),
    );
    if let Some((k, v)) = LAST.with(|c| c.get()) {
        if k == key {
            return v;
        }
    }
    let v = stationary_phase_shares_walk(spec);
    LAST.with(|c| c.set(Some((key, v))));
    v
}

/// The walk behind [`stationary_phase_shares_for`], uncached.
fn stationary_phase_shares_walk(spec: &CycleSpec) -> ([f64; 5], f64) {
    #[cfg(test)]
    SHARE_WALKS.with(|n| n.set(n.get() + 1));
    let mut mean = [0.0; 5];
    let mut cycle = 0.0;
    for (k, &phase) in phase_cycle().iter().enumerate() {
        mean[k] = mean_sojourn_days_for(phase, spec);
        cycle += mean[k];
    }
    (mean, cycle)
}

#[cfg(test)]
thread_local! {
    /// How many survival walks [`stationary_phase_shares_walk`] has run on
    /// this thread. Tests read it to hold callers to the memo.
    static SHARE_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

/// Survival walks for the stationary shares run so far on this thread.
/// Test-only.
#[cfg(test)]
pub(crate) fn share_walks() -> u64 {
    SHARE_WALKS.with(|n| n.get())
}

/// The day-zero `(phase, months_in_current_phase)` drawn from the cycle's
/// own stationary law, from two uniforms.
///
/// # The identity
///
/// ```text
/// pi_i    = E[T_i] / sum_j E[T_j]         the share of days in phase i
/// f_i(a)  = S_i(a + 1) / E[T_i]           the age within phase i, in days
/// P(i, a) = S_i(a + 1) / sum_j E[T_j]     the joint law
/// ```
///
/// The second line is the renewal identity for the BACKWARD RECURRENCE
/// TIME: in equilibrium the chance of finding a phase `a` days old is
/// proportional to the chance a sojourn in it lasts longer than `a`. It is
/// the part that cannot be skipped. Drawing the phase and setting the age
/// to zero would start a smaller cohort at the same point, and at pt-v16's
/// clock 73 per cent of stationary expansions are younger than the 180-day
/// minimum a fresh one has to clear.
///
/// `a` runs over `0, 1, 2, ...` because the engine's own age does: a
/// transition sets `months_in_current_phase` to 0.0, so a phase entered
/// yesterday opens a day at age zero, and a sojourn that ends on its
/// `j`-th check has been observed at the ages `0 .. j - 1`.
///
/// # The two draws
///
/// `u_phase` picks the phase from the cumulative shares and `u_age` the age
/// from `f_i`. Both are compared against the CDF as written -- the first
/// phase, and then the first age, whose cumulative probability reaches the
/// uniform. The last phase absorbs a uniform that rounds past the final
/// cumulative share, which is a rounding fallback and not a sixth branch.
pub fn stationary_opening(per_month: f64, u_phase: f64, u_age: f64) -> (CyclePhase, f64) {
    stationary_opening_for(&CycleSpec::shipped(per_month), u_phase, u_age)
}

/// [`stationary_opening`] on a given clock and table; the age comes back in
/// that clock's months.
pub fn stationary_opening_for(spec: &CycleSpec, u_phase: f64, u_age: f64) -> (CyclePhase, f64) {
    let phases = phase_cycle();
    let (mean, cycle) = stationary_phase_shares_for(spec);

    let mut cumulative = 0.0;
    let mut pick = phases.len() - 1;
    for (k, share) in mean.iter().enumerate().take(phases.len()) {
        cumulative += share;
        if cumulative / cycle >= u_phase {
            pick = k;
            break;
        }
    }

    let phase = phases[pick];
    let mut age = 0;
    walk_survival(phase, spec, |a, cdf| {
        age = a;
        cdf / mean[pick] < u_age
    });
    (phase, age as f64 / spec.month_days)
}

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

    /// The memo in [`stationary_phase_shares_for`] hands back the walk's
    /// own answer, to the bit, and walks again only when the spec changes.
    #[test]
    fn the_memo_returns_the_walk_and_walks_once_per_spec() {
        fn bits(v: ([f64; 5], f64)) -> ([u64; 5], u64) {
            (v.0.map(f64::to_bits), v.1.to_bits())
        }
        let a = CycleSpec::shipped(1.0);
        let b = CycleSpec { us: true, ..CycleSpec::shipped(1.0) };
        let start = share_walks();
        let first = stationary_phase_shares_for(&a);
        for _ in 0..10 {
            assert_eq!(bits(stationary_phase_shares_for(&a)), bits(first));
        }
        assert_eq!(share_walks() - start, 1, "one spec, one walk");
        let other = stationary_phase_shares_for(&b);
        assert_eq!(share_walks() - start, 2, "a new spec walks again");
        assert_eq!(bits(stationary_phase_shares_for(&a)), bits(first));
        assert_eq!(bits(first), bits(stationary_phase_shares_walk(&a)));
        assert_eq!(bits(other), bits(stationary_phase_shares_walk(&b)));
    }

    /// The order is walked, so the guard is that it CLOSES: five distinct
    /// phases and the fifth's successor is the first. A `next_phase` that
    /// stopped being a cycle would break the renewal identity above --
    /// `pi_i = E[T_i] / sum_j E[T_j]` holds because every phase is entered
    /// exactly once per cycle -- and would fail here rather than silently
    /// return a law for a chain the engine no longer runs.
    #[test]
    fn the_phase_order_closes_on_itself() {
        let phases = phase_cycle();
        assert_eq!(phase_characteristics(phases[4]).next_phase, phases[0]);
        for i in 0..5 {
            for j in (i + 1)..5 {
                assert_ne!(phases[i], phases[j], "{i} and {j} are the same phase");
            }
        }
    }

    /// The law's own arithmetic must be the ENGINE's, so it is compared
    /// against `get_cycle_transition_probability` -- the UI-safe form of
    /// the roll, which computes the same probability without drawing -- on
    /// an economy whose fields fire no ladder condition. Where the hazard
    /// alone decides is where this law claims anything.
    #[test]
    fn the_hazard_only_probability_is_the_transition_the_engine_rolls() {
        for per_month in [0.0, 1.0] {
            for phase in phase_cycle() {
                for &days in &[1, 59, 60, 119, 120, 179, 180, 181, 400, 2000] {
                    let mut e = ladder_free_economy();
                    e.cycle_phase = phase;
                    e.months_in_current_phase = days as f64 / 30.0;
                    let p = hazard_only_transition_probability(phase, days, &CycleSpec::shipped(per_month));
                    let (engine_p, _) = get_cycle_transition_probability(&e, per_month);
                    assert_eq!(p, engine_p, "{phase:?} at {days} days, clock {per_month}");
                }
            }
        }
    }

    /// The sojourn's mean must be the mean of the sojourn: the survival
    /// sum is checked against `sum_j j * P(T = j)` accumulated the other
    /// way round, over the SAME support -- the walk's own horizon -- so
    /// the two truncations cannot silently differ.
    #[test]
    fn the_survival_sum_is_the_mean_of_the_sojourn() {
        for per_month in [0.0, 1.0] {
            for phase in phase_cycle() {
                let sum = mean_sojourn_days(phase, per_month);
                let mut horizon = 0;
                walk_survival(phase, &CycleSpec::shipped(per_month), |a, _| {
                    horizon = a;
                    true
                });
                let mut survival = 1.0;
                let mut mean = 0.0;
                for j in 1..=(horizon + 1) {
                    let p = hazard_only_transition_probability(phase, j, &CycleSpec::shipped(per_month));
                    mean += j as f64 * survival * p;
                    survival *= 1.0 - p;
                }
                assert!((mean - sum).abs() / sum < 1e-9,
                        "{phase:?} clock {per_month}: {mean} against {sum}");
            }
        }
    }

    /// A phase cannot be found younger than its minimum duration more
    /// often than the minimum's own share of the mean sojourn, because the
    /// survival function is exactly 1 there. This is the arithmetic behind
    /// "73 per cent of stationary expansions are younger than the
    /// minimum", and it is an identity: `P(age < min) = min_days / E[T]`.
    #[test]
    fn the_share_below_the_minimum_is_the_minimum_over_the_mean() {
        for per_month in [0.0, 1.0] {
            for phase in phase_cycle() {
                let min_days = (phase_characteristics(phase).min_months * 30.0) as i64;
                let mean = mean_sojourn_days(phase, per_month);
                let mut below = 0.0;
                walk_survival(phase, &CycleSpec::shipped(per_month), |a, cdf| {
                    if a == min_days - 1 {
                        below = cdf / mean;
                        return false;
                    }
                    true
                });
                let identity = min_days as f64 / mean;
                assert!((below - identity).abs() < 1e-12,
                        "{phase:?} clock {per_month}: {below} against {identity}");
            }
        }
    }

    /// The joint law is a law: the phase shares sum to one, and so does
    /// the age density inside each phase.
    #[test]
    fn the_shares_and_the_age_density_are_both_distributions() {
        for per_month in [0.0, 1.0] {
            let (mean, cycle) = stationary_phase_shares(per_month);
            let total: f64 = mean.iter().sum::<f64>() / cycle;
            assert!((total - 1.0).abs() < 1e-12, "shares sum to {total}");
            for (k, &phase) in phase_cycle().iter().enumerate() {
                let mut last = 0.0;
                walk_survival(phase, &CycleSpec::shipped(per_month), |_, cdf| {
                    last = cdf / mean[k];
                    true
                });
                assert!((last - 1.0).abs() < 1e-12,
                        "{phase:?} clock {per_month}: age density sums to {last}");
            }
        }
    }

    /// The phase draw is an inversion of `pi`, asserted at the INTERVAL
    /// EDGES rather than by a histogram: a uniform just inside each end of
    /// a phase's cumulative interval must select that phase, so the point
    /// just above one phase's top selects the next. That is where an
    /// off-by-one in the cumulative sum would live, and a histogram over a
    /// grid is the one instrument that cannot see it.
    #[test]
    fn the_draw_picks_the_phase_whose_interval_holds_the_uniform() {
        for per_month in [0.0, 1.0] {
            let (mean, cycle) = stationary_phase_shares(per_month);
            let phases = phase_cycle();
            let mut lower = 0.0;
            for k in 0..phases.len() {
                let upper = lower + mean[k] / cycle;
                let inside = (upper - lower) * 1e-6;
                for u in [lower + inside, (lower + upper) / 2.0, upper - inside] {
                    let (got, _) = stationary_opening(per_month, u, 0.5);
                    assert_eq!(got, phases[k],
                               "u = {u} clock {per_month} wanted {:?}", phases[k]);
                }
                lower = upper;
            }
            // And the whole of the unit interval is covered, so no uniform
            // falls through to the rounding fallback by accident.
            assert!((lower - 1.0).abs() < 1e-12, "the intervals end at {lower}");
        }
    }

    /// The age draw is an inversion of `f_i`: the drawn age must be the
    /// first whose cumulative probability reaches the uniform, computed
    /// independently from the walk, and it must arrive in the engine's own
    /// 30-day months.
    ///
    /// The monotonicity the inversion needs is asserted where it comes
    /// from -- the CDF being non-decreasing -- rather than sampled out of
    /// the inversion, which would need a grid fine enough to be its own
    /// measurement.
    #[test]
    fn the_drawn_age_is_the_quantile_of_the_age_density_in_engine_months() {
        for per_month in [0.0, 1.0] {
            let (mean, cycle) = stationary_phase_shares(per_month);
            for (k, &phase) in phase_cycle().iter().enumerate() {
                let mut cdf = Vec::new();
                walk_survival(phase, &CycleSpec::shipped(per_month), |_, c| {
                    cdf.push(c / mean[k]);
                    true
                });
                for w in cdf.windows(2) {
                    assert!(w[1] >= w[0], "{phase:?} clock {per_month}: the CDF fell");
                }
                let u_phase = (mean[..k].iter().sum::<f64>() + mean[k] / 2.0) / cycle;
                for &u in &[1e-9, 0.1, 0.25, 0.5, 0.731, 0.9, 0.999] {
                    let want = cdf.iter().position(|&c| c >= u).unwrap() as i64;
                    let (got_phase, months) = stationary_opening(per_month, u_phase, u);
                    assert_eq!(got_phase, phase, "clock {per_month} at u = {u}");
                    assert_eq!(months, want as f64 / 30.0,
                               "{phase:?} clock {per_month} at u = {u}: wanted {want} days");
                }
            }
        }
    }

    /// A degenerate uniform must not walk off either end: zero takes the
    /// first phase at age zero and a uniform at the last representable
    /// value below one takes a real phase and a finite age.
    #[test]
    fn the_ends_of_the_uniform_stay_inside_the_law() {
        let below_one = 1.0 - f64::EPSILON / 2.0;
        for per_month in [0.0, 1.0] {
            let (first, age) = stationary_opening(per_month, 0.0, 0.0);
            assert_eq!(first, phase_cycle()[0]);
            assert_eq!(age, 0.0);
            let (last, age) = stationary_opening(per_month, below_one, below_one);
            assert!(phase_cycle().contains(&last));
            assert!(age.is_finite() && age > 0.0, "age {age}");
        }
    }

    /// `cycle_equity_hazard` at 0.0 is the ladder that stood, whatever the
    /// gap and the knee read: the probability is the shipped spec's to the
    /// bit in every phase, on both tables and both clocks.
    #[test]
    fn the_equity_hazard_off_is_the_ladder_that_stood() {
        for us in [false, true] {
            for per_month in [0.0, 1.0] {
                for phase in phase_cycle() {
                    for gap in [-0.3, 0.0, 0.2, 0.9] {
                        let mut e = ladder_free_economy();
                        e.cycle_phase = phase;
                        e.months_in_current_phase = 7.0;
                        e.spread_equity_gap = gap;
                        let shipped = CycleSpec { us, ..CycleSpec::shipped(per_month) };
                        let off = CycleSpec { equity_knee: 0.05, ..shipped };
                        assert_eq!(get_cycle_transition_probability_for(&e, &shipped),
                                   get_cycle_transition_probability_for(&e, &off),
                                   "{phase:?} gap {gap} us {us} clock {per_month}");
                    }
                }
            }
        }
    }

    /// On: in an expansion and at a peak the monthly hazard gains
    /// `equity_hazard * (gap - knee)` above the knee and nothing at or
    /// below it; a contraction, a trough and a recovery read no gap. Checked
    /// on the US table read per month, where the conversion is `/ 21` after
    /// the clamp at 1.0.
    #[test]
    fn the_equity_hazard_adds_in_an_expansion_and_at_a_peak_above_the_knee() {
        let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
                               equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
                               inflation_hazard: 0.0, rate_hazard: 0.0 };
        let on = CycleSpec { equity_hazard: 4.0, equity_knee: 0.05, ..base };
        for phase in phase_cycle() {
            let mut e = ladder_free_economy();
            e.cycle_phase = phase;
            e.months_in_current_phase = 7.0;
            for gap in [-0.2, 0.0, 0.05, 0.1, 0.15] {
                e.spread_equity_gap = gap;
                let (p0, next0) = get_cycle_transition_probability_for(&e, &base);
                let (p1, next1) = get_cycle_transition_probability_for(&e, &on);
                assert_eq!(next0, next1);
                let fires = matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) && gap > 0.05;
                if fires {
                    let monthly0 = p0 * 21.0;
                    let want = (monthly0 + 4.0 * (gap - 0.05)).min(US_HAZARD_CAP) / 21.0;
                    assert!((p1 - want).abs() < 1e-12, "{phase:?} gap {gap}: {p1} against {want}");
                    assert!(p1 > p0, "{phase:?} gap {gap}");
                } else {
                    assert_eq!(p0, p1, "{phase:?} gap {gap}");
                }
            }
        }
    }

    /// The expansion's guard still takes its 0.2 off an economy that has not
    /// recovered: the gap's addition comes first, so with growth under 1 an
    /// addition of 0.1 on a hazard near 0.003 leaves the probability at 0.0,
    /// where the guard put it without the gap.
    #[test]
    fn the_expansion_guard_still_applies_to_the_equity_hazard() {
        let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
                               equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
                               inflation_hazard: 0.0, rate_hazard: 0.0 };
        let on = CycleSpec { equity_hazard: 1.0, equity_knee: 0.0, ..base };
        let mut e = ladder_free_economy();
        e.cycle_phase = CyclePhase::Expansion;
        e.months_in_current_phase = 7.0;
        e.gdp_growth = 0.5;
        e.spread_equity_gap = 0.1;
        let (p0, _) = get_cycle_transition_probability_for(&e, &base);
        let (p1, _) = get_cycle_transition_probability_for(&e, &on);
        assert_eq!(p0, 0.0);
        assert_eq!(p1, 0.0);
    }

    /// The forecast's transition probability (`oil_forecast_cycle_growth`):
    /// with no spread on the gap it is the law's own on the same day of the
    /// phase, to the bit; with one, the market's term is its expectation over
    /// a normal gap (checked against a fine quadrature), in an expansion and
    /// at a peak only.
    #[test]
    fn the_forecast_reads_the_market_term_over_the_gap_spread() {
        let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
                               equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
                               inflation_hazard: 0.0, rate_hazard: 0.0 };
        let on = CycleSpec { equity_hazard: 5.0, equity_knee: 0.1, ..base };
        for phase in phase_cycle() {
            for gap in [-0.06, 0.0, 0.12] {
                let mut e = ladder_free_economy();
                e.cycle_phase = phase;
                e.months_in_current_phase = 147.0 / 21.0;
                e.spread_equity_gap = gap;
                let (law, _) = get_cycle_transition_probability_for(&e, &on);
                assert_eq!(transition_probability_for(&e, phase, 147.0, &on, 0.0), law, "{phase:?} gap {gap}");
                let var: f64 = 0.08 * 0.08;
                let have = transition_probability_for(&e, phase, 147.0, &on, var);
                if matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) {
                    let (p0, _) = get_cycle_transition_probability_for(&e, &base);
                    let (n, sd) = (20_000, var.sqrt());
                    let mut excess = 0.0;
                    for i in 0..n {
                        let z = -8.0 + 16.0 * (i as f64 + 0.5) / n as f64;
                        let w = (-0.5 * z * z).exp() / (2.0 * std::f64::consts::PI).sqrt() * 16.0 / n as f64;
                        excess += w * (gap + sd * z - 0.1).max(0.0);
                    }
                    let want = (p0 * 21.0 + 5.0 * excess).min(US_HAZARD_CAP) / 21.0;
                    assert!((have - want).abs() < 1e-9, "{phase:?} gap {gap}: {have} against {want}");
                    assert!(have > law || gap > 0.1, "{phase:?} gap {gap}");
                } else {
                    assert_eq!(have, law, "{phase:?} gap {gap}");
                }
            }
        }
    }

    /// `equity_opening` (`cycle_equity_hazard_opening`): 0.0 is the law and
    /// the ladder that stood; off zero the ladder adds it in an expansion and
    /// at a peak, and the hazard-only law the opening is drawn from adds it
    /// too, so the expansion's mean sojourn shortens and the other phases'
    /// do not move.
    #[test]
    fn the_opening_stand_in_adds_to_the_law_and_the_ladder() {
        let base = CycleSpec { per_month: 1.0, month_days: 21.0, us: true,
                               equity_hazard: 0.0, equity_knee: 0.0, equity_opening: 0.0,
                               inflation_hazard: 0.0, rate_hazard: 0.0 };
        let on = CycleSpec { equity_opening: 0.01, ..base };
        for phase in phase_cycle() {
            let mut e = ladder_free_economy();
            e.cycle_phase = phase;
            e.months_in_current_phase = 7.0;
            let (p0, _) = get_cycle_transition_probability_for(&e, &base);
            let (p1, _) = get_cycle_transition_probability_for(&e, &on);
            let m0 = mean_sojourn_days_for(phase, &base);
            let m1 = mean_sojourn_days_for(phase, &on);
            if matches!(phase, CyclePhase::Expansion | CyclePhase::Peak) {
                let want = ((p0 * 21.0) + 0.01).min(US_HAZARD_CAP) / 21.0;
                assert!((p1 - want).abs() < 1e-12, "{phase:?}: {p1} against {want}");
                assert!(m1 < m0, "{phase:?}: {m1} against {m0}");
            } else {
                assert_eq!(p0, p1, "{phase:?}");
                assert_eq!(m0, m1, "{phase:?}");
            }
        }
        let zero = CycleSpec { equity_opening: 0.0, ..on };
        assert_eq!(stationary_phase_shares_for(&zero), stationary_phase_shares_for(&base));
    }

    #[test]
    fn the_sojourn_quantiles_and_spread_are_the_walks_own_law() {
        // Against the pmf written out day by day, on the shipped clock and on
        // pt-v21's (the US table on a 21-session month).
        let us = CycleSpec { per_month: 1.0, month_days: 21.0, us: true, ..CycleSpec::shipped(1.0) };
        for spec in [CycleSpec::shipped(1.0), us] {
            let pmf = |phase| {
                let (mut s, mut out) = (1.0, vec![0.0]);
                for d in 1..200_000i64 {
                    let p = hazard_only_transition_probability(phase, d, &spec);
                    out.push(s * p);
                    s *= 1.0 - p;
                    if s < 1e-18 {
                        break;
                    }
                }
                out
            };
            for phase in phase_cycle() {
                let f = pmf(phase);
                let mean: f64 = f.iter().enumerate().map(|(d, p)| d as f64 * p).sum();
                let second: f64 = f.iter().enumerate().map(|(d, p)| (d * d) as f64 * p).sum();
                let sd = (second - mean * mean).sqrt();
                let walked = mean_sojourn_days_for(phase, &spec);
                assert!((walked - mean).abs() < 1e-6 * mean, "{phase:?}: {walked} against {mean}");
                let got = sojourn_sd_days_for(phase, &spec);
                assert!((got - sd).abs() < 1e-6 * sd, "{phase:?}: sd {got} against {sd}");
                for q in [0.5, 0.9, 0.99] {
                    let mut c = 0.0;
                    let want = f.iter().position(|p| { c += p; c >= q }).unwrap() as i64;
                    assert_eq!(sojourn_quantile_days_for(phase, &spec, q), want, "{phase:?} {q}");
                }
            }
            let (c, t) = (pmf(CyclePhase::Contraction), pmf(CyclePhase::Trough));
            let mut sum = vec![0.0; c.len() + t.len()];
            for (i, a) in c.iter().enumerate() {
                for (j, b) in t.iter().enumerate() {
                    sum[i + j] += a * b;
                }
            }
            for q in [0.5, 0.99] {
                let mut acc = 0.0;
                let want = sum.iter().position(|p| { acc += p; acc >= q }).unwrap() as i64;
                assert_eq!(downturn_quantile_days_for(&spec, q), want, "{q}");
            }
            assert_eq!(downturn_quantile_days_for(&spec, 1.0), i64::MAX);
        }
        // pt-v21's own figures, as docs/EMBEDDING.md quotes them.
        assert_eq!(sojourn_quantile_days_for(CyclePhase::Trough, &us, 0.99), 170);
        assert_eq!(sojourn_quantile_days_for(CyclePhase::Contraction, &us, 0.99), 246);
        assert_eq!(downturn_quantile_days_for(&us, 0.99), 338);
    }

    /// An economy on which no ladder condition fires, so the hazard alone
    /// decides. Every field is set against the branch that reads it in
    /// `adjust_transition_probability`, and the expansion guard is left
    /// unfired too (unemployment under 8, growth over 1).
    fn ladder_free_economy() -> EconomyState {
        let mut e = create_initial_economy_state(&InitialEconomyOptions::default());
        e.inflation_rate = 2.0;
        e.federal_funds_rate = 3.0;
        e.treasury_yield_2y = 2.0;
        e.treasury_yield_10y = 3.0;
        e.market_pe = Some(18.0);
        e.unemployment_rate = 4.0;
        e.gdp_growth = 2.0;
        e
    }
}