kshana 0.27.1

Open, reproducible PNT-resilience simulator with quantum-sensor performance models
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
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
// SPDX-License-Identifier: AGPL-3.0-only
//! **Deep-space communications link budget** — the Friis transmission account that turns transmit
//! power, antenna gains, range and noise temperature into the carrier-to-noise-density `C/N₀`, the
//! energy-per-bit-to-noise-density `Eb/N₀`, and the **link margin** over a required `Eb/N₀`. This is
//! the telecom-design half of a deep-space mission, the companion to the navigation observable model
//! in [`crate::radiometric`]: the navigation kernel says *where* the spacecraft is from the signal's
//! timing; the link budget says *whether the signal closes at all* across the same Earth–Mars range.
//!
//! ## What it computes
//!
//! For a one-way link (transmit EIRP, receive `G/T`) the standard deep-space account is
//!
//! ```text
//!   C/N₀ = EIRP − L_fs − L_other + G/T − k       [dB-Hz]
//!   Eb/N₀ = C/N₀ − 10·log10(R_b)                 [dB]
//!   margin = Eb/N₀ − (Eb/N₀)_required            [dB],   closes ⇔ margin ≥ 0
//! ```
//!
//! with `L_fs` the free-space path loss ([`free_space_loss_db`]), `L_other` the lumped
//! pointing/polarisation/atmosphere/implementation loss, `R_b` the information bit rate (bit/s), and
//! `k = −228.6 dBW/K/Hz` Boltzmann's constant in decibel form (`10·log10(1.380649e-23)`). This is
//! the CCSDS-401 / DSN-810-005 telecom-design-control-table convention; each band's carrier
//! frequency is taken from the DSN deep-space allocations ([`band_frequency_hz`]).
//!
//! ## What it is, and is not
//!
//! This is an **engineering link budget**, not a terminal datasheet. The per-(band, profile) defaults
//! in [`default_params`] are *cited order-of-magnitude* EIRP / `G/T` / loss values representative of a
//! MARCONI-class Mars relay link (a high-gain orbiter dish to a DSN 34 m station, a lower-gain
//! lander/surface terminal on the user end); they reproduce the published deep-space envelope but are
//! **not** the calibrated budget of any specific transponder. A real mission replaces them with its
//! own design-control table. The numbers' provenance (DSN 810-005 station `G/T`, typical deep-space
//! EIRP) is documented at each default.
//!
//! ## References
//!
//! * CCSDS 401.0-B, *Radio Frequency and Modulation Systems — Part 1* (deep-space band allocations,
//!   telecom design conventions).
//! * DSN 810-005, *Deep Space Network Telecommunications Link Design Handbook* (station `G/T`, EIRP,
//!   the design-control-table form of the link equation).
//! * Friis, *A Note on a Simple Transmission Formula* (Proc. IRE, 1946) — the free-space loss.

use crate::radiometric::Band;
use crate::timegeo::C_M_PER_S;
use std::f64::consts::PI;

/// **Boltzmann's constant in decibel form**, `k = 10·log10(1.380649e-23) = −228.599…` dBW/K/Hz. The
/// thermal-noise floor term in the link equation: a system of noise temperature `T` (K) over a
/// bandwidth `B` (Hz) carries noise power `N = k·T·B`, so `N₀ = k·T` is the noise spectral density
/// and `−k` (dB) enters `C/N₀` positively. The SI 2019 fixed value of `k` is used.
pub const BOLTZMANN_DBW_PER_K_PER_HZ: f64 = -228.599_1;

/// The **mission phase** of a link, which sets the antenna / EIRP / `G/T` / range regime the
/// [`default_params`] picks. The phases mirror the deep-space mission arc the rest of the deep-space
/// engine models (cf. [`crate::mars_pnt::UserKind`]): a cruising transfer vehicle, an orbiter, a
/// descending/landed vehicle, and a fixed surface user — each with a different antenna it can point
/// and a different geometry to the relay/station.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Profile {
    /// **Transfer / cruise**: a vehicle on the Earth–Mars transfer arc, carrying a deployed
    /// high-gain antenna and tracked directly by a DSN station over the full interplanetary range.
    Transfer,
    /// **Orbital**: a Mars orbiter (a MARCONI relay or a science orbiter) with a high-gain dish,
    /// either relaying to a DSN station or carrying the direct-to-Earth link.
    Orbital,
    /// **Lander**: a vehicle on descent or just landed, with a constrained medium-gain antenna,
    /// typically relaying through an orbiter (a short, high-elevation hop) rather than direct to
    /// Earth.
    Lander,
    /// **Surface**: a fixed surface user (a rover or static lander) with a small low-gain antenna,
    /// relaying through an overhead orbiter — the most power- and gain-constrained terminal.
    Surface,
}

/// The inputs to a one-way link budget: transmit EIRP, receive `G/T`, the geometry (range), the data
/// rate, and the lumped non-free-space loss. All decibel quantities are in their conventional units.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinkParams {
    /// The carrier band (sets the frequency the free-space loss is computed at, [`band_frequency_hz`]).
    pub band: Band,
    /// Transmit **effective isotropic radiated power** (dBW): transmit power plus transmit antenna
    /// gain minus transmit-side losses.
    pub eirp_dbw: f64,
    /// Receive **gain-to-noise-temperature ratio** `G/T` (dB/K): the receive antenna gain over the
    /// system noise temperature, the standard figure of merit of a receiving terminal.
    pub g_over_t_db: f64,
    /// One-way link range (metres) — the transmitter-to-receiver distance.
    pub range_m: f64,
    /// Information **bit rate** (bit/s) carried on the link.
    pub data_rate_bps: f64,
    /// Lumped **other losses** (dB ≥ 0): antenna pointing, polarisation mismatch, atmospheric /
    /// tropospheric attenuation on the ground segment, and modem implementation loss — every loss
    /// term that is not the free-space spreading loss.
    pub other_losses_db: f64,
}

/// The result of a link budget: the path loss, the two carrier figures, and the margin / closure
/// verdict over the required `Eb/N₀`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinkResult {
    /// **Free-space path loss** (dB), [`free_space_loss_db`].
    pub fsl_db: f64,
    /// **Carrier-to-noise-density** `C/N₀` (dB-Hz).
    pub cn0_dbhz: f64,
    /// **Energy-per-bit to noise-density** `Eb/N₀` (dB).
    pub eb_n0_db: f64,
    /// **Link margin** (dB): `Eb/N₀ − (Eb/N₀)_required`.
    pub margin_db: f64,
    /// Whether the link closes, i.e. `margin_db ≥ 0`.
    pub closes: bool,
}

/// The **representative carrier frequency** (Hz) for a deep-space `band`, taken at the **downlink**
/// allocation — the leg that almost always limits a deep-space budget (the spacecraft's transmit
/// power is the scarce resource, and the highest data rate is on the downlink). These are the DSN
/// deep-space band centres (CCSDS 401 / DSN 810-005), the same downlink frequencies
/// [`Band::downlink_hz`] returns:
///
/// | band | downlink centre |
/// |------|-----------------|
/// | S    | ≈ 2.295 GHz     |
/// | X    | ≈ 8.420 GHz     |
/// | Ka   | ≈ 32.0 GHz      |
///
/// The DSN deep-space allocations are S ≈ 2.29–2.30 GHz, X ≈ 8.40–8.45 GHz, Ka ≈ 31.8–32.3 GHz on
/// the downlink (with the corresponding ≈ 2.11 / 7.15 / 34.4 GHz uplinks); the band-keyed budget here
/// uses the downlink centre. Delegates to [`Band::downlink_hz`] so there is a single source of truth
/// for the band frequencies across the navigation ([`crate::radiometric`]) and telecom modules.
pub fn band_frequency_hz(band: Band) -> f64 {
    band.downlink_hz()
}

/// **Free-space path loss** (dB) for a one-way link of range `range_m` (metres) at carrier frequency
/// `freq_hz` (Hz):
///
/// ```text
///   L_fs = 20·log10( 4π·R·f / c )       [dB],
/// ```
///
/// the Friis spreading loss written in range × frequency form (equivalently `20·log10(4πR/λ)` with
/// `λ = c/f`). It is the dominant term of any deep-space budget — at the Earth–Mars range it is
/// ≈ 270–290 dB — and grows by 6 dB per range doubling and 6 dB per frequency doubling (so Ka loses
/// ≈ 12 dB to X at the same range, recovered by Ka's far higher antenna gain). Uses the crate's
/// speed of light [`C_M_PER_S`] for consistency with the navigation kernel.
pub fn free_space_loss_db(range_m: f64, freq_hz: f64) -> f64 {
    20.0 * (4.0 * PI * range_m * freq_hz / C_M_PER_S).log10()
}

/// Compute the one-way **link budget** for `p` against a required `Eb/N₀` (`required_eb_n0_db`, dB).
///
/// Applies the deep-space link equation
///
/// ```text
///   C/N₀  = EIRP − L_fs − L_other + G/T − k       [dB-Hz]
///   Eb/N₀ = C/N₀ − 10·log10(R_b)                  [dB]
///   margin = Eb/N₀ − (Eb/N₀)_required             [dB]
/// ```
///
/// with `L_fs` from [`free_space_loss_db`] at the band frequency ([`band_frequency_hz`]),
/// `k = −228.6 dBW/K/Hz` ([`BOLTZMANN_DBW_PER_K_PER_HZ`]), and `R_b = p.data_rate_bps`. The link
/// **closes** when the margin is non-negative. (CCSDS 401 / DSN 810-005 telecom-design-control-table
/// form.)
pub fn link_budget(p: &LinkParams, required_eb_n0_db: f64) -> LinkResult {
    let freq_hz = band_frequency_hz(p.band);
    let fsl_db = free_space_loss_db(p.range_m, freq_hz);

    // C/N₀ = EIRP − FSL − other losses + G/T − k. Subtracting the (negative) Boltzmann term raises
    // C/N₀, i.e. −k = +228.6 dB.
    let cn0_dbhz =
        p.eirp_dbw - fsl_db - p.other_losses_db + p.g_over_t_db - BOLTZMANN_DBW_PER_K_PER_HZ;

    // Eb/N₀ = C/N₀ − 10·log10(data rate).
    let eb_n0_db = cn0_dbhz - 10.0 * p.data_rate_bps.log10();

    let margin_db = eb_n0_db - required_eb_n0_db;

    LinkResult {
        fsl_db,
        cn0_dbhz,
        eb_n0_db,
        margin_db,
        closes: margin_db >= 0.0,
    }
}

/// The **required receive `G/T`** (dB/K) for the link to close: the figure of merit at which
/// `margin_db` is exactly zero, assembled straight from the link equation's own terms,
///
/// ```text
///   (G/T)_required = L_fs + L_other − EIRP + k + 10·log10(R_b) + (Eb/N₀)_required     [dB/K]
/// ```
///
/// with `L_fs` the free-space loss at the band frequency and `k` the (negative) Boltzmann term
/// [`BOLTZMANN_DBW_PER_K_PER_HZ`]. Because the margin is linear in `G/T` with unit slope, this is
/// also exactly `p.g_over_t_db − margin_db` — the same quantity reached from the other end, which
/// is what [`link_budget`] already reports. It is stated here because a *requirement* is the
/// question a terminal-sizing study actually asks ("how big an antenna do I need?"), and reading it
/// out of a margin is a subtraction every caller would otherwise redo by hand against constants the
/// report did not state.
pub fn required_g_over_t_db(p: &LinkParams, required_eb_n0_db: f64) -> f64 {
    let fsl_db = free_space_loss_db(p.range_m, band_frequency_hz(p.band));
    fsl_db + p.other_losses_db - p.eirp_dbw
        + BOLTZMANN_DBW_PER_K_PER_HZ
        + 10.0 * p.data_rate_bps.log10()
        + required_eb_n0_db
}

/// The **link constant** (dBW): `EIRP − L_other − (Eb/N₀)_required`.
///
/// This is the *only* combination in which a budget's three absolute constants enter the required
/// `G/T`: rearranging [`required_g_over_t_db`] gives
///
/// ```text
///   (G/T)_required = L_fs + 10·log10(R_b) + k − (EIRP − L_other − (Eb/N₀)_required)
/// ```
///
/// so two budgets sharing this one number have the same required `G/T` at **every** range and data
/// rate, whatever their individual EIRP, loss and threshold. The converse is the reason it is worth
/// naming: a published rate/gain table fixes this combination and nothing finer, so the three
/// constants cannot be recovered separately from such a table — only their difference can. Stating
/// it turns what would otherwise be a back-solved fitting constant into a reported quantity with a
/// definition.
pub fn link_constant_dbw(p: &LinkParams, required_eb_n0_db: f64) -> f64 {
    p.eirp_dbw - p.other_losses_db - required_eb_n0_db
}

/// The receive **antenna gain** (dBi) implied by a figure of merit `g_over_t_db` (dB/K) and a system
/// noise temperature `tsys_k` (K): `G = G/T + 10·log10(T_sys)`.
///
/// `G/T` is a ratio, so it does not on its own carry a gain — a terminal with `G/T = 0 dB/K` is a
/// 24.8 dBi antenna on a 300 K system and a 14.6 dBi antenna on a 29 K one. The engine's link
/// equation needs only the ratio and therefore never forms the split; a study that wants an antenna
/// *size* has to supply the noise temperature it assumed. Returns `None` unless `tsys_k` is finite
/// and positive, since `10·log10(T)` is undefined otherwise — an absent split is reported as absent,
/// never as zero.
pub fn rx_gain_from_g_over_t_dbi(g_over_t_db: f64, tsys_k: f64) -> Option<f64> {
    if !tsys_k.is_finite() || tsys_k <= 0.0 {
        return None;
    }
    Some(g_over_t_db + 10.0 * tsys_k.log10())
}

/// Received navigation-signal power (dBW) at the user antenna output for a transmitter
/// of `eirp_dbw` (transmit power + transmit antenna gain) and receive antenna gain
/// `rx_gain_dbi`, over one-way `range_m` at carrier `freq_hz`: `P_rx = EIRP + G_user −
/// L_fs`. This is the radiometric (received-power) form of the budget, distinct from the
/// telecom Eb/N₀ closure in [`link_budget`]; it is the P1 AFS surface-power result and
/// the reference the jamming/spoofing margins are taken against.
pub fn received_signal_power_dbw(
    eirp_dbw: f64,
    rx_gain_dbi: f64,
    range_m: f64,
    freq_hz: f64,
) -> f64 {
    eirp_dbw + rx_gain_dbi - free_space_loss_db(range_m, freq_hz)
}

/// Power deficit (dB) of a received navigation signal versus a reference received power
/// (e.g. terrestrial GPS L1 C/A at ≈ −125 dBW): `reference_dbw − received_dbw`. A
/// positive value means the signal is weaker than the reference by that many dB, so
/// every jamming and spoofing threshold sits proportionally lower in absolute watts;
/// the linear power factor is `10^(deficit/10)`.
pub fn power_deficit_db(reference_dbw: f64, received_dbw: f64) -> f64 {
    reference_dbw - received_dbw
}

/// Linear power factor of a `deficit_db` power deficit: `10^(deficit_db/10)`.
///
/// This is the "×N weaker" reading of a dB deficit. It is also the reconciliation of the
/// P1 headline figures: the AFS deficit versus terrestrial GPS is 15.6 dB, which is
/// `10^(15.6/10) ≈ 36×` at full precision but `10^(15/10) ≈ 32×` when the deficit is
/// quoted to a whole dB — the "32× (rounded) vs 36× (unrounded)" figures are one deficit
/// read at two dB precisions (they differ only by the 0.6 dB rounding), not two results.
pub fn deficit_power_factor(deficit_db: f64) -> f64 {
    10.0_f64.powf(deficit_db / 10.0)
}

/// The power-deficit sensitivity band of a received navigation signal versus a reference,
/// with the nominal-deficit linear factor read at both full and whole-dB precision.
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
pub struct DeficitBand {
    /// Smallest deficit over the swept grid (dB).
    pub band_lo_db: f64,
    /// Largest deficit over the swept grid (dB).
    pub band_hi_db: f64,
    /// Linear power factor at the low band edge, `10^(band_lo_db/10)`.
    pub band_lo_factor: f64,
    /// Linear power factor at the high band edge, `10^(band_hi_db/10)`.
    pub band_hi_factor: f64,
    /// Nominal (headline) deficit: strongest reference, highest EIRP, shortest range (dB).
    pub nominal_deficit_db: f64,
    /// Nominal deficit as a linear factor at full precision — the "36×" (unrounded) figure.
    pub nominal_factor: f64,
    /// Nominal deficit as a linear factor with the deficit quoted to a whole dB — the
    /// "32×" (rounded) figure (`10^(⌊nominal_deficit_db⌋/10)`).
    pub nominal_factor_whole_db: f64,
}

/// Compute the power-deficit sensitivity band as a **genuine multi-axis sweep over the
/// link-budget inputs**, built on [`crate::sweep::SweepAxis`] and evaluated through
/// [`received_signal_power_dbw`] — not a hand-picked offset array.
///
/// Three axes are swept as the Cartesian product:
///  * the terrestrial GNSS **reference** received power `ref_lo_dbw..ref_hi_dbw`
///    (e.g. −128.5..−125 dBW — the GPS L1 C/A received-power spread),
///  * the AFS satellite **EIRP** `eirp_lo_dbw..eirp_hi_dbw` (dBW), and
///  * the AFS **slant range** `range_lo_m..range_hi_m` (m).
///
/// At each grid node the AFS received power is `received_signal_power_dbw(eirp, rx_gain,
/// range, freq)` and the deficit is `reference − received`; the band is the [min, max]
/// deficit over the grid. With the P1 inputs (reference −128.5..−125 dBW, EIRP fixed at
/// 26 dBW, user gain 3 dBi, slant 3000..3954 km, 2.4 GHz) the band reproduces the paper's
/// Sec-6 **12–18 dB** sensitivity band and a 15.6 dB nominal deficit. The band is monotone
/// in every input (each dB of reference or received power moves the deficit by its own dB).
#[allow(clippy::too_many_arguments)]
pub fn deficit_sensitivity_band(
    ref_lo_dbw: f64,
    ref_hi_dbw: f64,
    eirp_lo_dbw: f64,
    eirp_hi_dbw: f64,
    rx_gain_dbi: f64,
    range_lo_m: f64,
    range_hi_m: f64,
    freq_hz: f64,
    steps: usize,
) -> DeficitBand {
    let axis = |name: &str, start: f64, stop: f64| crate::sweep::SweepAxis {
        parameter: name.to_string(),
        start,
        stop,
        steps,
        scale: "linear".to_string(),
    };
    let ref_vals = axis("gnss_reference_dbw", ref_lo_dbw, ref_hi_dbw).values();
    let eirp_vals = axis("afs_eirp_dbw", eirp_lo_dbw, eirp_hi_dbw).values();
    let range_vals = axis("afs_slant_range_m", range_lo_m, range_hi_m).values();

    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for &r in &ref_vals {
        for &eirp in &eirp_vals {
            for &range in &range_vals {
                let received = received_signal_power_dbw(eirp, rx_gain_dbi, range, freq_hz);
                let d = power_deficit_db(r, received);
                lo = lo.min(d);
                hi = hi.max(d);
            }
        }
    }

    // Nominal headline: strongest reference (least-negative dBW), highest EIRP, shortest
    // range — the best-case AFS signal against the strongest GPS reference.
    let nominal_ref = ref_lo_dbw.max(ref_hi_dbw);
    let nominal_eirp = eirp_lo_dbw.max(eirp_hi_dbw);
    let nominal_range = range_lo_m.min(range_hi_m);
    let nominal_received =
        received_signal_power_dbw(nominal_eirp, rx_gain_dbi, nominal_range, freq_hz);
    let nominal_deficit_db = power_deficit_db(nominal_ref, nominal_received);

    DeficitBand {
        band_lo_db: lo,
        band_hi_db: hi,
        band_lo_factor: deficit_power_factor(lo),
        band_hi_factor: deficit_power_factor(hi),
        nominal_deficit_db,
        nominal_factor: deficit_power_factor(nominal_deficit_db),
        nominal_factor_whole_db: deficit_power_factor(nominal_deficit_db.trunc()),
    }
}

/// Representative [`LinkParams`] for a **MARCONI-class relay link** at the given `band` and mission
/// `profile`, parameterised by the link `range_m` and `data_rate_bps`.
///
/// The EIRP / `G/T` / loss figures are **engineering defaults**, cited to order of magnitude — *not*
/// the calibrated budget of any specific terminal. They are set so the relative regimes are sensible
/// (an orbiter's high-gain dish has more EIRP than a lander's medium-gain or a surface terminal's
/// low-gain antenna; the per-band antenna gain rises with frequency, partly recovering the higher
/// free-space loss) and the absolute numbers sit inside the published deep-space envelope:
///
/// * **EIRP** by profile is a typical deep-space spacecraft transmit EIRP (a few tens of dBW at a
///   few-metre high-gain dish, less for the constrained lander/surface antennas), plus a per-band
///   gain bump (≈ X +6 dB, Ka +14 dB over S, the `20·log10(f)` aperture-gain scaling for a fixed
///   dish size) — DSN 810-005 spacecraft-EIRP envelope.
/// * **G/T** is the receiving terminal figure of merit: for the orbiter/transfer direct-to-Earth
///   legs this is a DSN 34 m beam-waveguide station (`G/T` ≈ 53 dB/K at X-band, higher at Ka, lower
///   at S — DSN 810-005 module 101/104); for the lander/surface relay legs it is the lower `G/T` of
///   an overhead orbiter's relay receiver.
/// * **other_losses_db** is a lumped pointing + polarisation + atmosphere + implementation budget
///   (≈ 3–6 dB), larger for the constrained terminals.
///
/// These reproduce the right closure behaviour (an X-band orbiter link closes across the typical
/// Earth–Mars range and breaks near solar-conjunction maximum range) without claiming datasheet
/// fidelity.
pub fn default_params(
    band: Band,
    profile: Profile,
    range_m: f64,
    data_rate_bps: f64,
) -> LinkParams {
    // Per-band antenna-gain bump over S-band for a fixed dish: gain ∝ f², i.e. 20·log10(f/f_S) dB.
    // X ≈ +11 dB, Ka ≈ +23 dB over S in pure aperture terms; we use a damped, conservative version
    // (X +6, Ka +14) so the higher-band budgets stay representative rather than optimistic.
    let band_gain_db = match band {
        Band::S => 0.0,
        Band::X => 6.0,
        Band::Ka => 14.0,
    };

    // Base spacecraft transmit EIRP (S-band reference, dBW) and lumped loss by mission phase.
    let (eirp_base_dbw, other_losses_db) = match profile {
        // Cruise vehicle, deployed high-gain antenna, direct-to-Earth.
        Profile::Transfer => (55.0, 4.0),
        // Orbiter high-gain dish — the strongest terminal.
        Profile::Orbital => (60.0, 4.0),
        // Descent/landed medium-gain antenna, relaying through an orbiter.
        Profile::Lander => (42.0, 5.0),
        // Fixed surface low-gain antenna — the most constrained.
        Profile::Surface => (38.0, 6.0),
    };

    // Receive G/T (dB/K): the DSN-34 m direct-to-Earth legs see the big-station figure of merit;
    // the lander/surface relay legs are received by a lower-G/T overhead orbiter.
    let g_over_t_db = match profile {
        // DSN 34 m beam-waveguide station, X-band ≈ 53 dB/K; +Ka bump, −S deficit follow the band.
        Profile::Transfer | Profile::Orbital => 47.0 + band_gain_db,
        // Overhead-orbiter relay receiver — a far smaller aperture, lower G/T.
        Profile::Lander | Profile::Surface => 12.0 + band_gain_db,
    };

    LinkParams {
        band,
        eirp_dbw: eirp_base_dbw + band_gain_db,
        g_over_t_db,
        range_m,
        data_rate_bps,
        other_losses_db,
    }
}

fn lb_default_band() -> String {
    "x".to_string()
}
fn lb_default_eirp() -> f64 {
    55.0
}
fn lb_default_gt() -> f64 {
    53.0
}
fn lb_default_range_km() -> f64 {
    2000.0
}
fn lb_default_rate() -> f64 {
    1.0e6
}
fn lb_default_other() -> f64 {
    3.0
}
fn lb_default_req() -> f64 {
    4.5
}

/// The `link-budget` scenario: a one-way link budget (free-space loss, C/N₀,
/// Eb/N₀, margin and closure) over the CCSDS 401 / DSN 810-005 link equation, for a
/// transmit EIRP, receive G/T, range, data rate and band against a required Eb/N₀.
#[derive(serde::Deserialize)]
pub struct LinkBudgetScenario {
    /// Carrier band: `s`, `x` or `ka` (sets the free-space-loss frequency).
    #[serde(default = "lb_default_band")]
    pub band: String,
    /// Transmit EIRP (dBW).
    #[serde(default = "lb_default_eirp")]
    pub eirp_dbw: f64,
    /// Receive figure of merit G/T (dB/K).
    #[serde(default = "lb_default_gt")]
    pub g_over_t_db: f64,
    /// One-way link range (km).
    #[serde(default = "lb_default_range_km")]
    pub range_km: f64,
    /// Information bit rate (bit/s).
    #[serde(default = "lb_default_rate")]
    pub data_rate_bps: f64,
    /// Lumped non-free-space losses (dB ≥ 0).
    #[serde(default = "lb_default_other")]
    pub other_losses_db: f64,
    /// Required Eb/N₀ for closure (dB).
    #[serde(default = "lb_default_req")]
    pub required_eb_n0_db: f64,
    /// Receive **system noise temperature** (K), optional. The link equation needs only the
    /// figure of merit `G/T`, so this is not an input to the budget; supplying it lets the
    /// report also state the receive antenna gain the figure of merit implies
    /// (`G = G/T + 10·log10(T_sys)`, [`rx_gain_from_g_over_t_dbi`]). Omitted by default, and
    /// then the gain split is **absent from the report** rather than assumed.
    pub tsys_k: Option<f64>,
}

impl LinkBudgetScenario {
    /// Run the scenario, returning `(json, summary)`.
    pub fn run_json(&self) -> Result<(String, String), String> {
        let band = match self.band.to_ascii_lowercase().as_str() {
            "s" => Band::S,
            "x" => Band::X,
            "ka" => Band::Ka,
            other => return Err(format!("unknown band '{other}' (expected s|x|ka)")),
        };
        if !self.range_km.is_finite() || self.range_km <= 0.0 {
            return Err("range_km must be finite and positive".to_string());
        }
        if !self.data_rate_bps.is_finite() || self.data_rate_bps <= 0.0 {
            return Err("data_rate_bps must be finite and positive".to_string());
        }
        if !self.other_losses_db.is_finite() || self.other_losses_db < 0.0 {
            return Err("other_losses_db must be finite and >= 0".to_string());
        }
        let p = LinkParams {
            band,
            eirp_dbw: self.eirp_dbw,
            g_over_t_db: self.g_over_t_db,
            range_m: self.range_km * 1000.0,
            data_rate_bps: self.data_rate_bps,
            other_losses_db: self.other_losses_db,
        };
        if let Some(t) = self.tsys_k {
            if !t.is_finite() || t <= 0.0 {
                return Err("tsys_k must be finite and positive when supplied".to_string());
            }
        }
        let r = link_budget(&p, self.required_eb_n0_db);
        let mut json = serde_json::json!({
            "kind": "link-budget",
            "label": "One-way link budget over the CCSDS 401 / DSN 810-005 link \
                      equation (EIRP − FSPL − L_other + G/T − k); a deterministic \
                      engineering calculation from the supplied inputs, NOT a \
                      calibrated terminal datasheet",
            "band": self.band.to_ascii_lowercase(),
            "range_km": self.range_km,
            "data_rate_bps": self.data_rate_bps,
            "free_space_loss_db": r.fsl_db,
            "cn0_dbhz": r.cn0_dbhz,
            "eb_n0_db": r.eb_n0_db,
            "required_eb_n0_db": self.required_eb_n0_db,
            "margin_db": r.margin_db,
            "closes": r.closes,
            // The absolute constants the equation was evaluated at. Every term of the link
            // equation is now named in the report, so `margin_db` can be recomputed from the
            // report alone; before this, the carrier frequency, EIRP, G/T, lumped loss and the
            // Boltzmann term all had to be supplied from outside, and a published table fixed
            // only their combination (`link_constant_dbw`).
            "link_constants": {
                "carrier_frequency_hz": band_frequency_hz(band),
                "eirp_dbw": self.eirp_dbw,
                "g_over_t_db": self.g_over_t_db,
                "other_losses_db": self.other_losses_db,
                "boltzmann_dbw_per_k_per_hz": BOLTZMANN_DBW_PER_K_PER_HZ,
                "link_constant_dbw": link_constant_dbw(&p, self.required_eb_n0_db),
            },
            "required_g_over_t_db": required_g_over_t_db(&p, self.required_eb_n0_db),
            "margin_definition": "margin_db = eb_n0_db - required_eb_n0_db, with \
                                  eb_n0_db = eirp_dbw - free_space_loss_db - other_losses_db \
                                  + g_over_t_db - boltzmann_dbw_per_k_per_hz \
                                  - 10*log10(data_rate_bps); the link closes when margin_db >= 0",
            "units": {
                "free_space_loss_db": {"unit": "dB", "provenance": "computed"},
                "cn0_dbhz": {"unit": "dB-Hz", "provenance": "computed"},
                "eb_n0_db": {"unit": "dB", "provenance": "computed"},
                "margin_db": {"unit": "dB", "provenance": "computed"},
                "required_g_over_t_db": {"unit": "dB/K", "provenance": "computed", "note": "the G/T at which margin_db is zero"},
                "link_constants.carrier_frequency_hz": {"unit": "Hz", "provenance": "computed", "note": "DSN downlink band centre for the selected band"},
                "link_constants.eirp_dbw": {"unit": "dBW", "provenance": "input"},
                "link_constants.g_over_t_db": {"unit": "dB/K", "provenance": "input"},
                "link_constants.other_losses_db": {"unit": "dB", "provenance": "input", "note": "lumped pointing + polarisation + atmosphere + implementation; this engine does not resolve the split, and no bandwidth or system noise temperature enters the equation at all"},
                "link_constants.boltzmann_dbw_per_k_per_hz": {"unit": "dBW/K/Hz", "provenance": "constant", "note": "10*log10 of the SI 2019 fixed Boltzmann constant"},
                "link_constants.link_constant_dbw": {"unit": "dBW", "provenance": "computed", "note": "eirp_dbw - other_losses_db - required_eb_n0_db; the only combination of the three that required_g_over_t_db depends on"},
                "required_eb_n0_db": {"unit": "dB", "provenance": "input"},
                "range_km": {"unit": "km", "provenance": "input"},
                "data_rate_bps": {"unit": "bit/s", "provenance": "input"},
            },
        });

        // The G/T-to-gain split exists only if the caller states the noise temperature it
        // assumed; G/T is a ratio and carries no gain by itself. Absent input, absent block.
        if let Some(tsys_k) = self.tsys_k {
            if let Some(gain) = rx_gain_from_g_over_t_dbi(self.g_over_t_db, tsys_k) {
                json["receive_terminal"] = serde_json::json!({
                    "tsys_k": tsys_k,
                    "rx_gain_dbi": gain,
                    "g_over_t_to_gain_offset_db": 10.0 * tsys_k.log10(),
                });
                json["units"]["receive_terminal.tsys_k"] =
                    serde_json::json!({"unit": "K", "provenance": "input"});
                json["units"]["receive_terminal.rx_gain_dbi"] = serde_json::json!({"unit": "dBi", "provenance": "computed", "note": "g_over_t_db + 10*log10(tsys_k)"});
                json["units"]["receive_terminal.g_over_t_to_gain_offset_db"] =
                    serde_json::json!({"unit": "dB", "provenance": "computed"});
            }
        }
        let summary = format!(
            "link-budget: {}-band, {:.0} km, {:.0} bit/s -> FSPL {:.1} dB, Eb/N0 {:.1} dB, \
             margin {:.1} dB ({})",
            self.band.to_ascii_lowercase(),
            self.range_km,
            self.data_rate_bps,
            r.fsl_db,
            r.eb_n0_db,
            r.margin_db,
            if r.closes { "closes" } else { "does NOT close" }
        );
        let json = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
        Ok((json, summary))
    }
}

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

    /// 1 AU in metres (IAU 2012), for expressing Earth–Mars ranges.
    const AU_M: f64 = 1.495_978_707e11;

    /// The free-space loss matches the `20·log10(4π·R·f/c)` hand value, computed independently in the
    /// test, to better than 1e-6 dB. The reference point: R = 1.0e8 m, f = 8.42e9 Hz (X-band
    /// downlink). The hand value is formed from the raw constants, not from `free_space_loss_db`.
    #[test]
    fn free_space_loss_matches_hand_value() {
        let range_m = 1.0e8;
        let freq_hz = 8.42e9;

        // Hand value: 4π·R·f / c, then 20·log10.
        let c = 299_792_458.0_f64;
        let arg = 4.0 * std::f64::consts::PI * range_m * freq_hz / c;
        let hand_db = 20.0 * arg.log10();

        // Sanity: the literal magnitude is ≈ 211.0 dB at this geometry (a cross-check on the hand
        // value itself, independent of the implementation).
        assert!(
            (hand_db - 210.96).abs() < 0.05,
            "hand FSL {hand_db} dB not ≈ 211.0 dB at R=1e8 m, f=8.42 GHz"
        );

        let got = free_space_loss_db(range_m, freq_hz);
        assert!(
            (got - hand_db).abs() < 1e-6,
            "free_space_loss_db {got} dB vs hand {hand_db} dB (Δ = {} dB)",
            (got - hand_db).abs()
        );
    }

    /// External-oracle cross-check against a **published deep-space telemetry
    /// design-control table**: J. H. Yuen (ed.), *Deep Space Telecommunications
    /// Systems Engineering* (DESCANSO / JPL Publication 82-76), Table 1-1 — the
    /// Galileo X-band (8420.43 MHz) downlink at 6.37 AU (R = 9.529×10⁸ km). The
    /// CCSDS-401 / DSN-810-005 link equation reproduces the table's published
    /// free-space loss (−290.54 dB) and received carrier-to-noise density
    /// (Pr/N₀ = 54.6 dB-Hz). The DCT component values are converted to the
    /// EIRP / (G/T) / lumped-loss inputs the link equation takes; the link-budget
    /// assembly (C/N₀ = EIRP − FSL − L + G/T − k) is what is under test.
    #[test]
    fn link_equation_reproduces_descanso_galileo_dct() {
        let range_m = 9.529e11; // 9.529e8 km = 6.37 AU
        let freq_hz = 8.42043e9; // X-band downlink channel in the table

        // (a) Free-space loss: the table prints −290.54 dB.
        let fsl = free_space_loss_db(range_m, freq_hz);
        assert!(
            (fsl - 290.54).abs() < 0.05,
            "FSPL {fsl} dB vs published 290.54 dB"
        );

        // (b) Full carrier-to-noise-density chain. Table 1-1 components:
        //   EIRP = Pt(10.5 dBW) − circuit loss(0.2) + Gt(50.0)   = 60.3 dBW
        //   G/T  = Gr(71.7 dBi) − 10·log10(Tsys = 26.30 K)       = 57.50 dB/K
        //   other losses = Tx pointing(1.2) + polarisation(0.04) = 1.24 dB
        // The table prints received Pr/N₀ = 54.6 dB-Hz.
        let g_over_t = 71.7 - 10.0 * 26.30_f64.log10();
        let p = LinkParams {
            band: Band::X, // band centre 8.420 GHz ≈ the table's 8420.43 MHz channel
            eirp_dbw: 60.3,
            g_over_t_db: g_over_t,
            range_m,
            data_rate_bps: 134_400.0, // table line 19; affects Eb/N₀, not C/N₀
            other_losses_db: 1.24,
        };
        let r = link_budget(&p, 2.31); // required Eb/N₀, table line 25
        assert!(
            (r.cn0_dbhz - 54.6).abs() < 0.2,
            "C/N0 {} dB-Hz vs published 54.6 dB-Hz",
            r.cn0_dbhz
        );

        // The band frequencies sit inside the DSN/CCSDS-401 deep-space downlink
        // allocations (DSN 810-005 Module 201, Table 2): S 2290–2300, X 8400–8450,
        // Ka 31800–32300 MHz.
        assert!((2.290e9..=2.300e9).contains(&band_frequency_hz(Band::S)));
        assert!((8.400e9..=8.450e9).contains(&band_frequency_hz(Band::X)));
        assert!((31.800e9..=32.300e9).contains(&band_frequency_hz(Band::Ka)));
    }

    /// The band carrier frequencies are in the right DSN GHz bands: S ≈ 2.3 GHz, X ≈ 8.4 GHz,
    /// Ka ≈ 32 GHz (downlink centres), and strictly ordered S < X < Ka.
    #[test]
    fn band_frequencies_are_dsn() {
        let fs = band_frequency_hz(Band::S);
        let fx = band_frequency_hz(Band::X);
        let fka = band_frequency_hz(Band::Ka);

        assert!(
            (2.2e9..=2.4e9).contains(&fs),
            "S-band {fs} Hz not in the ~2.3 GHz DSN band"
        );
        assert!(
            (8.3e9..=8.5e9).contains(&fx),
            "X-band {fx} Hz not in the ~8.4 GHz DSN band"
        );
        assert!(
            (31.0e9..=33.0e9).contains(&fka),
            "Ka-band {fka} Hz not in the ~32 GHz DSN band"
        );
        assert!(
            fs < fx && fx < fka,
            "band frequencies must increase S < X < Ka"
        );
    }

    /// A nominal X-band orbital MARCONI link closes at a realistic Earth–Mars range, and goes
    /// negative beyond a documented long range (the link breaks near solar-conjunction maximum
    /// range). Both directions are asserted.
    ///
    /// Geometry: R = 1.67 AU ≈ 2.5e11 m (a mid-range Earth–Mars distance) vs R = 2.7 AU ≈ 4.0e11 m
    /// (near solar-conjunction maximum Earth–Mars range), at **1 Mbit/s** with a required
    /// Eb/N₀ = 2.0 dB (a strongly-coded turbo/LDPC threshold). The high-gain orbital default has
    /// comfortable margin at low rates, so the range-dependent break is exercised at the demanding
    /// 1 Mbit/s downlink: at the near range the link closes (margin ≈ +2.7 dB, Eb/N₀ ≈ 4.7 dB), and
    /// the ≈ +4.2 dB of extra free-space loss out at conjunction maximum drives the margin negative
    /// (margin ≈ −1.5 dB, Eb/N₀ ≈ 0.5 dB) — the link breaks. The exact figures are computed by the
    /// link equation; the test asserts the sign of the margin (close / break) in both regimes.
    #[test]
    fn x_band_orbital_link_closes() {
        let data_rate = 1.0e6; // 1 Mbit/s — a demanding deep-space downlink rate
        let required = 2.0; // dB, coded threshold

        // Mid-range Earth–Mars: closes.
        let near = 1.67 * AU_M; // ≈ 2.50e11 m
        let p_near = default_params(Band::X, Profile::Orbital, near, data_rate);
        let r_near = link_budget(&p_near, required);
        assert!(
            r_near.closes && r_near.margin_db > 0.0,
            "X-band orbital link must close at {near:.3e} m: margin {} dB, Eb/N0 {} dB, FSL {} dB",
            r_near.margin_db,
            r_near.eb_n0_db,
            r_near.fsl_db
        );

        // Near solar-conjunction maximum range: breaks.
        let far = 2.7 * AU_M; // ≈ 4.04e11 m
        let p_far = default_params(Band::X, Profile::Orbital, far, data_rate);
        let r_far = link_budget(&p_far, required);
        assert!(
            !r_far.closes && r_far.margin_db < 0.0,
            "X-band orbital link must break at {far:.3e} m: margin {} dB, Eb/N0 {} dB, FSL {} dB",
            r_far.margin_db,
            r_far.eb_n0_db,
            r_far.fsl_db
        );

        // The break is driven by the extra free-space loss of the longer range (≈ 6 dB per range
        // doubling): the far FSL exceeds the near FSL.
        assert!(
            r_far.fsl_db > r_near.fsl_db,
            "longer range must have larger FSL: far {} dB vs near {} dB",
            r_far.fsl_db,
            r_near.fsl_db
        );
    }

    /// At the same range Ka-band free-space loss exceeds X-band (higher frequency → more path loss):
    /// `L_fs ∝ 20·log10(f)`, so the ≈ 3.8× frequency ratio is ≈ 11.6 dB of extra loss. Ka recovers
    /// this (and more) through far higher antenna gain, but here we assert only the FSL ordering.
    #[test]
    fn ka_higher_loss_than_x_same_range() {
        let range_m = 2.0e11;
        let fsl_x = free_space_loss_db(range_m, band_frequency_hz(Band::X));
        let fsl_ka = free_space_loss_db(range_m, band_frequency_hz(Band::Ka));
        assert!(
            fsl_ka > fsl_x,
            "Ka FSL {fsl_ka} dB must exceed X FSL {fsl_x} dB at the same range"
        );

        // The gap is the 20·log10(f_Ka / f_X) dispersion difference, ≈ 11.6 dB.
        let expected_gap =
            20.0 * (band_frequency_hz(Band::Ka) / band_frequency_hz(Band::X)).log10();
        assert!(
            (fsl_ka - fsl_x - expected_gap).abs() < 1e-6,
            "FSL gap {} dB must equal 20·log10(f_Ka/f_X) = {} dB",
            fsl_ka - fsl_x,
            expected_gap
        );
    }

    /// Profile sanity: at the same band/range/rate, the orbiter (high-gain dish, big-station receive
    /// G/T) carries more EIRP and a stronger margin than the transfer cruise vehicle, which in turn
    /// beats the lander, which beats the surface terminal. The EIRP and margin orderings both hold,
    /// reflecting the constrained-antenna mission phases.
    #[test]
    fn profile_relative_eirp_and_margin() {
        let band = Band::X;
        let range_m = 1.5 * AU_M;
        let data_rate = 1.0e4; // 10 kbit/s, so the constrained terminals are still meaningful
        let required = 2.0;

        let mk = |prof| {
            let p = default_params(band, prof, range_m, data_rate);
            (p.eirp_dbw, link_budget(&p, required))
        };
        let (eirp_orb, r_orb) = mk(Profile::Orbital);
        let (eirp_xfer, r_xfer) = mk(Profile::Transfer);
        let (eirp_land, r_land) = mk(Profile::Lander);
        let (eirp_surf, r_surf) = mk(Profile::Surface);

        // EIRP ordering: orbiter ≥ transfer > lander > surface.
        assert!(
            eirp_orb >= eirp_xfer && eirp_xfer > eirp_land && eirp_land > eirp_surf,
            "EIRP must order orbital≥transfer>lander>surface: {eirp_orb}, {eirp_xfer}, {eirp_land}, {eirp_surf}"
        );

        // Margin ordering: the orbiter has the strongest link, the surface terminal the weakest.
        assert!(
            r_orb.margin_db >= r_xfer.margin_db
                && r_xfer.margin_db > r_land.margin_db
                && r_land.margin_db > r_surf.margin_db,
            "margin must order orbital≥transfer>lander>surface: {} {} {} {}",
            r_orb.margin_db,
            r_xfer.margin_db,
            r_land.margin_db,
            r_surf.margin_db
        );

        // The strong orbiter link closes; the most-constrained surface link is weaker by a wide
        // margin (the low-gain antenna + low relay-receiver G/T cost tens of dB).
        assert!(
            r_orb.closes,
            "orbital link should close at 1.5 AU / 10 kbit/s"
        );
        assert!(
            r_orb.margin_db - r_surf.margin_db > 20.0,
            "orbiter should beat surface by >20 dB: Δ = {} dB",
            r_orb.margin_db - r_surf.margin_db
        );
    }

    /// The carrier figures compose consistently: Eb/N₀ = C/N₀ − 10·log10(R_b), and the closure flag
    /// agrees with the sign of the margin. A direct check of the link equation wiring.
    #[test]
    fn carrier_figures_compose() {
        let p = LinkParams {
            band: Band::X,
            eirp_dbw: 60.0,
            g_over_t_db: 53.0,
            range_m: 2.0e11,
            data_rate_bps: 1.0e5,
            other_losses_db: 4.0,
        };
        let required = 2.0;
        let r = link_budget(&p, required);

        // Eb/N₀ = C/N₀ − 10·log10(data rate).
        let eb_hand = r.cn0_dbhz - 10.0 * p.data_rate_bps.log10();
        assert!(
            (r.eb_n0_db - eb_hand).abs() < 1e-9,
            "Eb/N0 {} dB vs C/N0 − 10log10(Rb) {} dB",
            r.eb_n0_db,
            eb_hand
        );

        // margin = Eb/N₀ − required, and closes ⇔ margin ≥ 0.
        assert!((r.margin_db - (r.eb_n0_db - required)).abs() < 1e-9);
        assert_eq!(r.closes, r.margin_db >= 0.0);

        // C/N₀ = EIRP − FSL − other + G/T − k, hand-recomposed.
        let cn0_hand =
            p.eirp_dbw - r.fsl_db - p.other_losses_db + p.g_over_t_db - BOLTZMANN_DBW_PER_K_PER_HZ;
        assert!(
            (r.cn0_dbhz - cn0_hand).abs() < 1e-9,
            "C/N0 {} dB vs hand {} dB",
            r.cn0_dbhz,
            cn0_hand
        );
    }

    // --- L44 AFS radiometric received power + power-deficit band ----------

    #[test]
    fn afs_received_power_and_deficit_reproduce_p1() {
        // P1 Table 1: EIRP = P_sat 13 dBW + G_sat 13 dBi = 26 dBW; user gain 3 dBi;
        // slant 3000 km; carrier 2.4 GHz → P_rx ≈ −140.6 dBW. GPS L1 C/A reference
        // −125 dBW → deficit 15.6 dB. Oracle: closed-form dB radiometry (Eq. prx).
        let p_rx = received_signal_power_dbw(26.0, 3.0, 3.0e6, 2.4e9);
        assert!(
            (p_rx - (-140.6)).abs() < 0.1,
            "P_rx = {p_rx} dBW (want −140.6)"
        );
        assert!(
            (power_deficit_db(-125.0, p_rx) - 15.6).abs() < 0.1,
            "deficit"
        );
    }

    // P1 Sec 6 sensitivity band, computed as a GENUINE multi-axis sweep over the link
    // inputs (reference, EIRP, slant range) via [`deficit_sensitivity_band`] — the band
    // edges are read off the sweep, not asserted from a hand-picked offset array. A
    // +2.4 dB slant-range spread is range 3000 km → 3000·10^(2.4/20) ≈ 3955 km. Oracle:
    // monotone closed-form dB radiometry anchored on the P1 −125/−128.5 dBW inputs.
    const P1_RANGE_HI_M: f64 = 3.0e6 * 1.318_256_738_556_407; // 3000 km × 10^(2.4/20)

    #[test]
    fn deficit_band_reproduces_p1_12_to_18_via_sweep() {
        let b = deficit_sensitivity_band(
            -128.5,
            -125.0, // GNSS reference −128.5..−125 dBW
            26.0,
            26.0, // AFS EIRP fixed at 26 dBW
            3.0,  // user gain 3 dBi
            3.0e6,
            P1_RANGE_HI_M, // slant 3000..~3955 km
            2.4e9,
            8,
        );
        // Band edges emerge from the sweep at ~12.1 and ~18.0 dB.
        assert!(
            b.band_lo_db > 12.0 && b.band_lo_db < 12.3,
            "band_lo = {} dB (want ≈12.1)",
            b.band_lo_db
        );
        assert!(
            b.band_hi_db > 17.9 && b.band_hi_db < 18.1,
            "band_hi = {} dB (want ≈18.0)",
            b.band_hi_db
        );
        // Nominal headline deficit vs GPS −125 is 15.6 dB.
        assert!(
            (b.nominal_deficit_db - 15.6).abs() < 0.1,
            "nominal = {} dB",
            b.nominal_deficit_db
        );
        // Linear-factor band edges ~16× and ~63×.
        assert!(
            (b.band_lo_factor - 16.2).abs() < 0.6,
            "lo× = {}",
            b.band_lo_factor
        );
        assert!(
            (b.band_hi_factor - 63.1).abs() < 1.0,
            "hi× = {}",
            b.band_hi_factor
        );
    }

    #[test]
    fn deficit_factor_reconciles_32x_rounded_and_36x_unrounded() {
        // The P1 "32× (rounded) vs 36× (unrounded)" figures are ONE 15.6 dB deficit read
        // at two dB precisions — they differ only by the 0.6 dB rounding, not two results.
        // Oracle: the 10^(dB/10) closed form.
        assert!(
            (deficit_power_factor(15.0) - 31.62).abs() < 0.05,
            "15 dB → {}× (want ≈32)",
            deficit_power_factor(15.0)
        );
        assert!(
            (deficit_power_factor(15.6) - 36.31).abs() < 0.05,
            "15.6 dB → {}× (want ≈36)",
            deficit_power_factor(15.6)
        );
        let b = deficit_sensitivity_band(
            -128.5,
            -125.0,
            26.0,
            26.0,
            3.0,
            3.0e6,
            P1_RANGE_HI_M,
            2.4e9,
            8,
        );
        // Whole-dB reading of the SAME nominal deficit is the rounded 32× figure…
        assert!(
            (b.nominal_factor_whole_db - 31.62).abs() < 0.05,
            "whole-dB factor = {}× (want ≈32)",
            b.nominal_factor_whole_db
        );
        assert_eq!(b.nominal_factor_whole_db.round(), 32.0);
        // …and the full-precision reading is the unrounded 36× figure.
        assert!(
            (b.nominal_factor - 36.3).abs() < 1.0,
            "full factor = {}× (want ≈36)",
            b.nominal_factor
        );
    }

    #[test]
    fn deficit_band_is_monotone_in_received_power() {
        // Monotone closed-form dB arithmetic: a weaker AFS signal (lower EIRP) raises the
        // whole band dB-for-dB; a stronger GNSS reference raises it too.
        let base = deficit_sensitivity_band(
            -128.5,
            -125.0,
            26.0,
            26.0,
            3.0,
            3.0e6,
            P1_RANGE_HI_M,
            2.4e9,
            8,
        );
        let weaker_eirp = deficit_sensitivity_band(
            -128.5,
            -125.0,
            22.0,
            22.0,
            3.0,
            3.0e6,
            P1_RANGE_HI_M,
            2.4e9,
            8,
        );
        assert!(
            weaker_eirp.band_lo_db > base.band_lo_db + 3.9
                && weaker_eirp.band_hi_db > base.band_hi_db + 3.9,
            "4 dB weaker EIRP must raise the band ~4 dB: base [{:.1},{:.1}] vs [{:.1},{:.1}]",
            base.band_lo_db,
            base.band_hi_db,
            weaker_eirp.band_lo_db,
            weaker_eirp.band_hi_db
        );
    }

    // -----------------------------------------------------------------------------------
    // G1 — the report states its own absolute constants.
    //
    // Before these, `link-budget` reported five derived numbers and none of the constants
    // they were derived from: not the carrier frequency the free-space loss used, not the
    // EIRP, not the G/T, not the lumped loss, not the Boltzmann term. A published table
    // built on such a report could only be reproduced by back-solving, and — see
    // `the_requirement_sees_only_the_link_constant` below — back-solving cannot in
    // principle recover the three absolute constants separately, only their difference.
    // -----------------------------------------------------------------------------------

    /// Four configurations spanning the three bands, four decades of range and both closure
    /// verdicts. Each report must carry enough to **recompute its own `margin_db`** — and the
    /// free-space loss underneath it — with nothing supplied from outside, to 1e-9 dB.
    #[test]
    fn the_report_states_every_term_of_its_own_margin() {
        let cases = [
            ("x", 55.0, 53.0, 2000.0, 1.0e6, 3.0, 4.5),
            ("s", 38.0, 12.0, 400_000.0, 100.0, 6.0, 2.0),
            ("ka", 74.0, 61.0, 3.6e8, 1.0e5, 4.0, 1.0),
            ("x", 0.0, 0.0, 12_499.0, 1000.0, 0.0, 0.0),
        ];
        for (band, eirp, gt, range_km, rate, other, req) in cases {
            let src = format!(
                "band = \"{band}\"\neirp_dbw = {eirp}\ng_over_t_db = {gt}\n\
                 range_km = {range_km}\ndata_rate_bps = {rate}\n\
                 other_losses_db = {other}\nrequired_eb_n0_db = {req}\n"
            );
            let scn: LinkBudgetScenario = toml::from_str(&src).expect("parse");
            let (json, _) = scn.run_json().expect("run");
            let v: serde_json::Value = serde_json::from_str(&json).expect("json");

            let f = |p: &str| -> f64 {
                let mut cur = &v;
                for seg in p.split('.') {
                    cur = &cur[seg];
                }
                cur.as_f64()
                    .unwrap_or_else(|| panic!("report has no numeric field {p}"))
            };

            // (a) the free-space loss, from the report's own carrier frequency and range.
            let fsl = 20.0
                * (4.0 * PI * f("range_km") * 1000.0 * f("link_constants.carrier_frequency_hz")
                    / C_M_PER_S)
                    .log10();
            assert!(
                (fsl - f("free_space_loss_db")).abs() < 1e-9,
                "{band}: FSL from the report's own constants {fsl} vs reported {}",
                f("free_space_loss_db")
            );

            // (b) the margin, from the report's own constants alone.
            let eb_n0 = f("link_constants.eirp_dbw")
                - f("free_space_loss_db")
                - f("link_constants.other_losses_db")
                + f("link_constants.g_over_t_db")
                - f("link_constants.boltzmann_dbw_per_k_per_hz")
                - 10.0 * f("data_rate_bps").log10();
            let margin = eb_n0 - f("required_eb_n0_db");
            assert!(
                (margin - f("margin_db")).abs() < 1e-9,
                "{band}: margin recomputed from the report {margin} dB vs reported {} dB",
                f("margin_db")
            );
        }
    }

    /// The reported `required_g_over_t_db` really is the figure of merit that zeroes the
    /// margin: re-running the same budget at it lands on `margin_db = 0`. It is assembled in
    /// [`required_g_over_t_db`] from the equation's terms, and checked here against the
    /// budget reached from the other end — two different expressions, so a sign or
    /// transcription slip in either one fails.
    #[test]
    fn required_g_over_t_is_the_figure_of_merit_that_zeroes_the_margin() {
        for (band, range_m, rate, eirp, other, req) in [
            (Band::X, 2.0e6, 1.0e6, 55.0, 3.0, 4.5),
            (Band::S, 4.0e8, 100.0, 38.0, 6.0, 2.0),
            (Band::Ka, 3.6e11, 1.0e5, 74.0, 4.0, 1.0),
        ] {
            let p = LinkParams {
                band,
                eirp_dbw: eirp,
                g_over_t_db: 17.0, // arbitrary; the requirement must not depend on it
                range_m,
                data_rate_bps: rate,
                other_losses_db: other,
            };
            let need = required_g_over_t_db(&p, req);

            // (a) at the required G/T the margin is zero.
            let at_need = link_budget(
                &LinkParams {
                    g_over_t_db: need,
                    ..p
                },
                req,
            );
            assert!(
                at_need.margin_db.abs() < 1e-9,
                "margin at the required G/T is {} dB, not 0",
                at_need.margin_db
            );

            // (b) the identity: the requirement is the actual G/T less the margin it earns.
            let actual = link_budget(&p, req);
            assert!(
                (p.g_over_t_db - actual.margin_db - need).abs() < 1e-9,
                "G/T − margin = {} vs required {need}",
                p.g_over_t_db - actual.margin_db
            );
        }
    }

    /// **Why a published rate/gain table cannot yield the three absolute constants.** The
    /// required `G/T` depends on EIRP, lumped loss and the required `Eb/N₀` **only** through
    /// `link_constant_dbw = EIRP − L_other − (Eb/N₀)_req`. Three budgets whose constants
    /// differ wildly but whose link constant agrees give an identical requirement at every
    /// range and rate; move the constant by 1 dB and the requirement moves by exactly 1 dB.
    ///
    /// This is the formal statement of what reproducing D1's released table cost: only the
    /// combination was ever recoverable, so reporting it is not a convenience — it is the
    /// only honest thing a report can say about those three numbers after the fact.
    #[test]
    fn the_requirement_sees_only_the_link_constant() {
        let base = |eirp: f64, other: f64, req: f64| {
            (
                LinkParams {
                    band: Band::X,
                    eirp_dbw: eirp,
                    g_over_t_db: 0.0,
                    range_m: 1.2499e7,
                    data_rate_bps: 1000.0,
                    other_losses_db: other,
                },
                req,
            )
        };
        // Same constant (20.79 dBW) reached three different ways.
        let same = [
            base(20.79, 0.0, 0.0),
            base(55.0, 30.0, 4.21),
            base(30.79, 6.0, 4.0),
        ];
        let mut reqs = Vec::new();
        for (p, r) in &same {
            assert!(
                (link_constant_dbw(p, *r) - 20.79).abs() < 1e-12,
                "test setup: link constant is not 20.79"
            );
            reqs.push(required_g_over_t_db(p, *r));
        }
        for w in reqs.windows(2) {
            assert!(
                (w[0] - w[1]).abs() < 1e-12,
                "equal link constants must give an equal requirement: {} vs {}",
                w[0],
                w[1]
            );
        }

        // And the requirement is not simply insensitive: 1 dB on the constant moves it 1 dB.
        let (p, r) = base(21.79, 0.0, 0.0);
        assert!(
            (required_g_over_t_db(&p, r) - (reqs[0] - 1.0)).abs() < 1e-12,
            "1 dB more link constant must lower the requirement by exactly 1 dB"
        );
    }

    /// `G/T` is a ratio and carries no antenna gain by itself, so the split is reported only
    /// when the caller states the system noise temperature it assumed — and is **absent**,
    /// not zero, when they do not. At 300 K the offset is the 24.77 dB a 300 K terminal has;
    /// at 29 K it is a different number, which is the point.
    #[test]
    fn the_gain_split_is_absent_unless_the_noise_temperature_is_stated() {
        let run = |extra: &str| -> serde_json::Value {
            let src = format!(
                "band = \"x\"\neirp_dbw = 20.79\ng_over_t_db = 0.0\nrange_km = 12499.0\n\
                 data_rate_bps = 1000.0\nother_losses_db = 0.0\nrequired_eb_n0_db = 0.0\n{extra}"
            );
            let scn: LinkBudgetScenario = toml::from_str(&src).expect("parse");
            let (json, _) = scn.run_json().expect("run");
            serde_json::from_str(&json).expect("json")
        };

        let without = run("");
        assert!(
            without.get("receive_terminal").is_none(),
            "no noise temperature was stated, so no gain split may be reported"
        );

        let warm = run("tsys_k = 300.0\n");
        let offset = warm["receive_terminal"]["g_over_t_to_gain_offset_db"]
            .as_f64()
            .expect("offset");
        assert!(
            (offset - 10.0 * 300.0_f64.log10()).abs() < 1e-12,
            "300 K offset is {offset} dB"
        );
        assert!(
            (offset - 24.771_212_5).abs() < 1e-6,
            "a 300 K terminal's G/T-to-gain offset is 24.77 dB, got {offset}"
        );
        assert!(
            (warm["receive_terminal"]["rx_gain_dbi"].as_f64().unwrap() - offset).abs() < 1e-12,
            "at G/T = 0 dB/K the gain is exactly the offset"
        );

        // A cryogenic station has a different offset — the split is a real function of T.
        let cold = run("tsys_k = 29.0\n");
        let cold_offset = cold["receive_terminal"]["g_over_t_to_gain_offset_db"]
            .as_f64()
            .unwrap();
        assert!(
            (cold_offset - 10.0 * 29.0_f64.log10()).abs() < 1e-12
                && (cold_offset - offset).abs() > 10.0,
            "29 K offset {cold_offset} must differ from the 300 K offset {offset}"
        );

        // A nonsensical temperature is refused, not silently dropped.
        let src = "band = \"x\"\ntsys_k = 0.0\n";
        let scn: LinkBudgetScenario = toml::from_str(src).expect("parse");
        assert!(
            scn.run_json().is_err(),
            "a non-positive noise temperature must be an error"
        );
    }

    /// Every field the `units` block describes must actually exist in the report. A units
    /// block naming a field nobody emits is worse than none: it reads as a promise the
    /// report keeps elsewhere, and sends a reader looking for a number that is not there.
    #[test]
    fn the_units_block_describes_only_fields_that_exist() {
        for extra in ["", "tsys_k = 300.0\n"] {
            let src = format!(
                "band = \"ka\"\neirp_dbw = 74.0\ng_over_t_db = 61.0\nrange_km = 3.6e8\n\
                 data_rate_bps = 1.0e5\nother_losses_db = 4.0\nrequired_eb_n0_db = 1.0\n{extra}"
            );
            let scn: LinkBudgetScenario = toml::from_str(&src).expect("parse");
            let (json, _) = scn.run_json().expect("run");
            let v: serde_json::Value = serde_json::from_str(&json).expect("json");
            let units = v["units"].as_object().expect("a units block");
            assert!(!units.is_empty());
            for (field, meta) in units {
                let mut cur = &v;
                for seg in field.split('.') {
                    cur = cur.get(seg).unwrap_or_else(|| {
                        panic!("units names {field}, which the report does not emit")
                    });
                }
                assert!(
                    meta.get("unit").and_then(|u| u.as_str()).is_some(),
                    "{field} must state a unit"
                );
                assert!(
                    meta.get("provenance").and_then(|u| u.as_str()).is_some(),
                    "{field} must state a provenance class"
                );
            }
            // The gain split is described exactly when it is emitted.
            assert_eq!(
                units.contains_key("receive_terminal.rx_gain_dbi"),
                v.get("receive_terminal").is_some(),
                "the units block and the report must agree on whether a gain split exists"
            );
        }
    }
}