Skip to main content

hpr_aero/
lib.rs

1//! Aerodynamics: Barrowman normal force and center of pressure with extensions, drag buildup,
2//! compressibility and override tables.
3//!
4//! The guide's [Aerodynamics][guide-aero] page gives the models, their sources, how well they are
5//! validated and what they leave out.
6//!
7//! [guide-aero]: https://hpr.fusionspace.co/physics/aero.html
8//! [guide-cp]: https://hpr.fusionspace.co/physics/aero.html#your-rockets-centre-of-pressure
9//! [guide-flight]: https://hpr.fusionspace.co/physics/flight.html#aerodynamics-in-flight
10//! [guide-roll]: https://hpr.fusionspace.co/physics/aero.html#roll-forcing-and-damping
11//! [guide-fins-mach]: https://hpr.fusionspace.co/physics/aero.html#fins-through-mach-1
12//! [guide-drag-mach]: https://hpr.fusionspace.co/physics/aero.html#drag-through-mach-1
13//! [guide-override]: https://hpr.fusionspace.co/physics/aero.html#the-normal-force-from-rasaero-ii
14//!
15//! - [`body`]: nose cones, body tubes and transitions: Barrowman's slope and center of pressure.
16//! - [`crossflow`]: body lift, the crossflow's push on a body at an angle of attack. It's
17//!   Jorgensen's `η C_dn` against the body's fineness and the crossflow Mach number, or Galejs's
18//!   constant.
19//! - [`fins`]: fin sets: Barrowman's slope with Prandtl–Glauert, the mean aerodynamic chord,
20//!   supersonic linear theory and the transonic join between them. It also holds the fin-count and
21//!   roll terms, and fin–body interference.
22//! - [`drag`]: the terms of Niskanen's zero-lift drag buildup, and axial drag at an angle of
23//!   attack.
24//! - [`nose_drag`]: the pressure drag of noses, shoulders and steps from rest through Mach 1 to
25//!   supersonic speeds, with Stoney's measured curves.
26//! - [`afterbody`]: a boattail's wave drag faster than sound, and the base pressure behind it.
27//! - [`shock_expansion`]: the second-order shock-expansion method for a pointed body faster than
28//!   sound (NACA TN 3527).
29//! - [`supersonic_boattail`]: a boattail's measured share of the normal force faster than sound
30//!   (Washington and Pettis, RD-TM-68-5).
31//! - [`table`]: override tables from another tool, read from RASAero II's export. A drag table
32//!   gives the drag coefficient against Mach number. A normal-force table gives the normal force
33//!   and center of pressure against Mach number and angle of attack ([The normal force from
34//!   RASAero II][guide-override]).
35//! - [`tube_fins`]: tube fins, each tube an annular wing: Weissinger's slope with Göthert's rule,
36//!   Fletcher's measured aerodynamic center, below Mach 0.8.
37//! - [`custom`]: drag models of your own: the [`DragModel`] trait, flown in place of the drag
38//!   buildup.
39//! - [`model`]: a rocket's terms built from a [`hpr_design::Layout`] and summed at a [`Flow`].
40//!
41//! A rocket's center of pressure is [`NormalForce::cp_station_m`], in meters aft of the nose tip.
42//! It comes from [`AeroModel::normal_force`] at [`Flow::axial`] ([Your rocket's center of
43//! pressure][guide-cp] in the guide).
44//!
45//! The normal force and center of pressure run from Mach 0 to 5. Fins go through the transonic
46//! region to supersonic linear theory ([Fins through Mach 1][guide-fins-mach]). The drag buildup
47//! runs from Mach 0 to 5, too. Noses, shoulders and steps go through Mach 1 by Niskanen's
48//! appendix B ([Drag through Mach 1][guide-drag-mach]). Drag override tables, and drag models of a
49//! program's own ([`custom`]), work at any Mach number. The roll forcing of canted fins and the
50//! roll damping run from Mach 0 to 5 ([`AeroModel::roll`], [Roll: forcing and
51//! damping][guide-roll]).
52//!
53//! Pitch and yaw damping in a flight come only from the flight engine (`hpr_sim`). It evaluates
54//! each component in its own local flow, which includes the speed the rocket's rotation adds there
55//! ([Rigid-body flight][guide-flight] in the guide). Only components with a normal-force slope
56//! give that damping: nose cones, transitions and fin sets. Body tubes give none at small angles:
57//! their own slope is 0, and their body lift grows with `sin² α`. The crate has no pitch or yaw
58//! damping coefficients; they would have to replace the local-flow damping, not add to it.
59
60pub mod afterbody;
61pub mod blunt_tip;
62pub mod body;
63pub mod crossflow;
64pub mod custom;
65pub mod drag;
66pub mod error;
67pub mod fins;
68pub mod model;
69pub mod nose_drag;
70pub mod shock_expansion;
71pub mod supersonic_boattail;
72pub mod table;
73pub mod tube_fins;
74
75pub use afterbody::Boattail;
76pub use body::{BODY_LIFT_K, BodyGeometry};
77pub use crossflow::BodyLift;
78pub use custom::{DragModel, DragQuery};
79pub use drag::{
80    BaseBehindBoattail, BoattailTerm, ComponentDrag, ComponentDragTerms, Drag, DragConditions,
81    MOTOR_POD_SETS, MergedBoattail, PressureDragTerm, ReliefSource, WakeTerm,
82};
83pub use error::AeroError;
84pub use fins::{
85    FinAero, FinGeometry, FinLoading, FinOutline, FinRoll, FinRollTerms, fin_count_factor,
86    interference_factor, roll_damping_interference, roll_forcing_interference, roll_sum, side_sum,
87};
88pub use model::{
89    AeroModel, BodyAero, BodyModel, ComponentNormalForce, FinSetAero, Flow, MAX_CANT_RAD,
90    NORMAL_FORCE_MACH_LIMIT, NormalForce, PodFins, PodSetAero, Roll, SUPERSONIC_JOIN_START_MACH,
91    SUPERSONIC_JOIN_WIDTH_MACH, SupersonicBoattail, SupersonicBody, SupersonicFallback,
92    SupersonicFlare, keep_supersonic_tables,
93};
94pub use nose_drag::{PressureDragCurve, StoneyNose};
95pub use table::{
96    DragTable, NormalForceColumn, NormalForceLookup, NormalForceTable, TableReference,
97    parse_mach_csv,
98};
99pub use tube_fins::TubeFinSetAero;
100
101#[cfg(test)]
102mod testing;
103
104#[cfg(test)]
105mod tests {
106    use std::f64::consts::PI;
107
108    use hpr_design::{
109        FinPlanform, NoseShape, Overrides, Position, ReferenceDiameter, Rocket, Stage,
110    };
111    use serde::Deserialize;
112
113    use super::*;
114    use crate::testing::{body_part, committed_design, component, fin_set, nose, one_stage};
115
116    const INCH: f64 = 0.0254;
117
118    fn close(got: f64, want: f64, rel: f64, what: &str) {
119        let err = ((got - want) / want).abs();
120        assert!(
121            err <= rel,
122            "{what}: got {got}, want {want}, rel err {err:e}"
123        );
124    }
125
126    fn component_force(model: &AeroModel, id: &str) -> NormalForce {
127        model
128            .components(&Flow::axial(0.0))
129            .unwrap()
130            .into_iter()
131            .find(|c| c.id == id)
132            .unwrap()
133            .normal_force
134    }
135
136    /// Loft lesson L89: Barrowman hand values. A cone has `C_Nα = 2` and its CP at `2L/3`; a
137    /// conical transition from 20 to 40 mm radius over 0.1 m, with a 40 mm reference radius, has
138    /// `C_Nα = 1.5` and its CP 0.05556 m aft of its fore end; a boattail back to 20 mm has −1.5 at
139    /// the mirrored CP; an elliptical fin's CP is 0.28779 `c_r` aft of its root leading edge.
140    #[test]
141    fn barrowman_hand_values() {
142        let cone = one_stage(
143            vec![
144                component("nose", nose(NoseShape::Conical {}, 0.2, 0.025), None),
145                component("tube", body_part(0.6, 0.025, 0.025), None),
146            ],
147            ReferenceDiameter::Maximum {},
148        );
149        let model = AeroModel::new(&cone.layout().unwrap()).unwrap();
150        let total = model.normal_force(&Flow::axial(0.0)).unwrap();
151        close(total.slope_per_rad, 2.0, 1e-15, "cone slope");
152        close(
153            total.cp_station_m.unwrap(),
154            0.2 * 2.0 / 3.0,
155            1e-11,
156            "cone CP",
157        );
158        assert_eq!(component_force(&model, "tube").slope_per_rad, 0.0);
159        assert_eq!(component_force(&model, "tube").cp_station_m, None);
160
161        let shoulder = one_stage(
162            vec![
163                component("nose", nose(NoseShape::Conical {}, 0.1, 0.02), None),
164                component("shoulder", body_part(0.1, 0.02, 0.04), None),
165                component("tube", body_part(0.5, 0.04, 0.04), None),
166                component("boattail", body_part(0.1, 0.04, 0.02), None),
167            ],
168            ReferenceDiameter::Custom { diameter_m: 0.08 },
169        );
170        let model = AeroModel::new(&shoulder.layout().unwrap()).unwrap();
171        let s = component_force(&model, "shoulder");
172        close(s.slope_per_rad, 1.5, 1e-15, "shoulder slope");
173        close(s.cp_station_m.unwrap() - 0.1, 0.05556, 1e-4, "shoulder CP");
174        close(
175            s.cp_station_m.unwrap() - 0.1,
176            0.1 / 3.0 * (1.0 + 1.0 / 1.5),
177            1e-11,
178            "eq. 44",
179        );
180        let b = component_force(&model, "boattail");
181        close(b.slope_per_rad, -1.5, 1e-15, "boattail slope");
182        close(
183            b.cp_station_m.unwrap() - 0.7,
184            0.1 / 3.0 * (1.0 + 1.0 / 3.0),
185            1e-11,
186            "boattail CP",
187        );
188
189        let (c_r, s) = (0.1, 0.06);
190        let mut tube = component("tube", body_part(0.6, 0.025, 0.025), None);
191        tube.children = vec![component(
192            "fins",
193            fin_set(
194                4,
195                FinPlanform::Elliptical {
196                    root_chord_m: c_r,
197                    span_m: s,
198                },
199            ),
200            Some(Position::Bottom { aft_offset_m: 0.0 }),
201        )];
202        let finned = one_stage(
203            vec![
204                component("nose", nose(NoseShape::Conical {}, 0.2, 0.025), None),
205                tube,
206            ],
207            ReferenceDiameter::Maximum {},
208        );
209        let layout = finned.layout().unwrap();
210        let model = AeroModel::new(&layout).unwrap();
211        let root_le = layout.find("fins").unwrap().1.fore_station_m;
212        let fins = component_force(&model, "fins");
213        close(
214            (fins.cp_station_m.unwrap() - root_le) / c_r,
215            0.28779,
216            2e-5,
217            "elliptical fin CP",
218        );
219        close(
220            (fins.cp_station_m.unwrap() - root_le) / c_r,
221            0.5 - 2.0 / (3.0 * PI),
222            1e-12,
223            "elliptical fin CP, exact",
224        );
225    }
226
227    #[derive(Deserialize)]
228    struct Fixture {
229        tolerance_rel: f64,
230        examples: Vec<Example>,
231    }
232
233    #[derive(Deserialize)]
234    struct Example {
235        id: String,
236        reference_diameter_in: f64,
237        station_offset_in: f64,
238        nose: NoseIn,
239        body: Vec<BodyIn>,
240        fin_sets: Vec<FinsIn>,
241        printed: Vec<Printed>,
242    }
243
244    #[derive(Deserialize)]
245    struct NoseIn {
246        shape: String,
247        length_in: f64,
248        base_diameter_in: f64,
249    }
250
251    #[derive(Deserialize)]
252    struct BodyIn {
253        id: String,
254        #[serde(default)]
255        stage: Option<String>,
256        length_in: f64,
257        fore_diameter_in: f64,
258        aft_diameter_in: f64,
259    }
260
261    #[derive(Deserialize)]
262    struct FinsIn {
263        id: String,
264        on: String,
265        count: u32,
266        root_chord_in: f64,
267        tip_chord_in: f64,
268        span_in: f64,
269        sweep_in: f64,
270        root_leading_edge_station_in: f64,
271    }
272
273    #[derive(Deserialize)]
274    struct Printed {
275        what: String,
276        cn_alpha: f64,
277        cp_in: f64,
278        #[serde(default)]
279        six_fin_rule: bool,
280    }
281
282    /// The design of a worked example, and of its first stage alone.
283    fn example_rockets(example: &Example) -> (Rocket, Rocket) {
284        let offset = example.station_offset_in;
285        let shape = match example.nose.shape.as_str() {
286            "cone" => NoseShape::Conical {},
287            "tangent_ogive" => NoseShape::Ogive { radius_ratio: 1.0 },
288            other => panic!("unknown nose shape {other}"),
289        };
290        let mut stages = vec![Stage {
291            id: "sustainer".to_owned(),
292            name: String::new(),
293            components: vec![component(
294                "nose",
295                nose(
296                    shape,
297                    example.nose.length_in * INCH,
298                    0.5 * example.nose.base_diameter_in * INCH,
299                ),
300                None,
301            )],
302            overrides: Overrides::default(),
303            override_rule: Default::default(),
304            added_mass: None,
305            drag_override: None,
306            parallel: None,
307        }];
308        for b in &example.body {
309            let mut part = component(
310                &b.id,
311                body_part(
312                    b.length_in * INCH,
313                    0.5 * b.fore_diameter_in * INCH,
314                    0.5 * b.aft_diameter_in * INCH,
315                ),
316                None,
317            );
318            part.children = example
319                .fin_sets
320                .iter()
321                .filter(|f| f.on == b.id)
322                .map(|f| {
323                    component(
324                        &f.id,
325                        fin_set(
326                            f.count,
327                            FinPlanform::Trapezoidal {
328                                root_chord_m: f.root_chord_in * INCH,
329                                tip_chord_m: f.tip_chord_in * INCH,
330                                span_m: f.span_in * INCH,
331                                sweep_m: f.sweep_in * INCH,
332                            },
333                        ),
334                        Some(Position::Absolute {
335                            station_m: (f.root_leading_edge_station_in + offset) * INCH,
336                        }),
337                    )
338                })
339                .collect();
340            match &b.stage {
341                Some(stage) if stages.last().is_some_and(|s| &s.id != stage) => {
342                    stages.push(Stage {
343                        id: stage.clone(),
344                        name: String::new(),
345                        components: vec![part],
346                        overrides: Overrides::default(),
347                        override_rule: Default::default(),
348                        added_mass: None,
349                        drag_override: None,
350                        parallel: None,
351                    });
352                }
353                _ => stages.last_mut().unwrap().components.push(part),
354            }
355        }
356        let reference = ReferenceDiameter::Custom {
357            diameter_m: example.reference_diameter_in * INCH,
358        };
359        let whole = Rocket {
360            name: example.id.clone(),
361            stages,
362            reference_diameter: reference,
363            configurations: Vec::new(),
364        };
365        let first = Rocket {
366            stages: whole.stages[..1].to_vec(),
367            ..whole.clone()
368        };
369        (whole, first)
370    }
371
372    /// TIR-33's six-fin rule over hpr's for a six-fin set of span `s` on a body of radius `r`:
373    /// `(1 + 0.5 r/(s + r)) / (0.913 (1 + r/(s + r)))` (TIR-33 p. 25; ADR-008).
374    fn six_fin_rule_ratio(set: &FinSetAero) -> f64 {
375        let r_over = (set.interference - 1.0).max(0.0);
376        (1.0 + 0.5 * r_over) / (set.count_factor * set.interference)
377    }
378
379    /// M1.5a done-when: `C_Nα` and CP reproduce Barrowman's worked examples within 1%: Testbed II
380    /// and the Aerobee 350 (NARAM-8, 1966), and the Javelin, Recruiter and Arcon-Hi (TIR-33,
381    /// 1970), component by component and in total. Inputs and printed results are in
382    /// `validation/fixtures/aero/barrowman-worked-examples.json`, with page numbers and notes.
383    ///
384    /// The Recruiter's six-fin slopes follow TIR-33's own six-fin rule. They are checked with that
385    /// rule substituted into the slope and the CP weighting; hpr's own values are reported, and
386    /// must miss the print by about the rules' difference, which exceeds the tolerance.
387    #[test]
388    fn barrowman_worked_examples() {
389        let fixture: Fixture = serde_json::from_str(include_str!(
390            "../../../validation/fixtures/aero/barrowman-worked-examples.json"
391        ))
392        .unwrap();
393        let tolerance = fixture.tolerance_rel;
394        assert_eq!(tolerance, 0.01);
395        let flow = Flow::axial(0.0);
396        let mut worst: f64 = 0.0;
397        let mut worst_own = (0.0, String::new());
398        let mut outside_own = Vec::new();
399        assert_eq!(fixture.examples.len(), 5);
400        let printed_values: usize = fixture.examples.iter().map(|e| e.printed.len()).sum();
401        assert_eq!(printed_values, 19);
402        for example in &fixture.examples {
403            let (whole, first) = example_rockets(example);
404            let model = AeroModel::new(&whole.layout().unwrap()).unwrap();
405            let components = model.components(&flow).unwrap();
406            let six_fin: Option<&FinSetAero> = model.fin_sets().iter().find(|s| s.count == 6);
407            for printed in &example.printed {
408                let force = match printed.what.as_str() {
409                    "total" => model.normal_force(&flow).unwrap(),
410                    "sustainer-alone" => AeroModel::new(&first.layout().unwrap())
411                        .unwrap()
412                        .normal_force(&flow)
413                        .unwrap(),
414                    id => {
415                        components
416                            .iter()
417                            .find(|c| c.id == id)
418                            .unwrap_or_else(|| panic!("{}: no component {id}", example.id))
419                            .normal_force
420                    }
421                };
422                let mut slope = force.slope_per_rad;
423                let mut cp_m = force.cp_station_m.unwrap();
424                let own_cp_err = (cp_m / INCH - example.station_offset_in) / printed.cp_in - 1.0;
425                let own = (slope / printed.cn_alpha - 1.0).abs().max(own_cp_err.abs());
426                if own > worst_own.0 {
427                    worst_own = (own, format!("{} {}", example.id, printed.what));
428                }
429                if own > tolerance {
430                    outside_own.push(format!("{} {}", example.id, printed.what));
431                }
432                if printed.six_fin_rule {
433                    let set = six_fin.expect("a six-fin set");
434                    let set_slope = set
435                        .fin
436                        .geometry()
437                        .single_fin_slope(model.reference_area_m2(), 0.0)
438                        .unwrap()
439                        * roll_sum(set.count, set.base_angle_rad, 0.0)
440                        * set.count_factor
441                        * set.interference;
442                    let extra = set_slope * (six_fin_rule_ratio(set) - 1.0);
443                    let tir33_slope = slope + extra;
444                    // The two six-fin rules differ by more than the tolerance, and hpr's own slope
445                    // misses the print by about that difference.
446                    let rule_gap = slope / tir33_slope - 1.0;
447                    let printed_gap = slope / printed.cn_alpha - 1.0;
448                    assert!(
449                        rule_gap > 0.02 && (printed_gap - rule_gap).abs() < tolerance,
450                        "{} {}: rule gap {rule_gap:e}, gap to print {printed_gap:e}",
451                        example.id,
452                        printed.what
453                    );
454                    eprintln!(
455                        "{} {}: hpr C_Nα {slope:.4} is {:+.2}% from the print; \
456                         TIR-33's six-fin rule alone accounts for {:+.2}%",
457                        example.id,
458                        printed.what,
459                        100.0 * printed_gap,
460                        100.0 * rule_gap
461                    );
462                    eprintln!(
463                        "{} {}: with hpr's rule, CP {:.4} in",
464                        example.id,
465                        printed.what,
466                        cp_m / INCH - example.station_offset_in
467                    );
468                    cp_m = (cp_m * slope + extra * set.cp_station_m(0.0).unwrap()) / tir33_slope;
469                    slope = tir33_slope;
470                }
471                let cp_in = cp_m / INCH - example.station_offset_in;
472                let slope_err = slope / printed.cn_alpha - 1.0;
473                let cp_err = cp_in / printed.cp_in - 1.0;
474                eprintln!(
475                    "{} {}: C_Nα {slope:.4} vs {} ({:+.3}%), CP {cp_in:.4} in vs {} ({:+.3}%)",
476                    example.id,
477                    printed.what,
478                    printed.cn_alpha,
479                    100.0 * slope_err,
480                    printed.cp_in,
481                    100.0 * cp_err
482                );
483                assert!(
484                    slope_err.abs() <= tolerance && cp_err.abs() <= tolerance,
485                    "{} {}: C_Nα error {slope_err:e}, CP error {cp_err:e}",
486                    example.id,
487                    printed.what
488                );
489                worst = worst.max(slope_err.abs()).max(cp_err.abs());
490            }
491        }
492        eprintln!(
493            "worst relative error, hpr's own model: {:.2}% ({}); with TIR-33's six-fin rule for \
494             the Recruiter: {:.3}%",
495            100.0 * worst_own.0,
496            worst_own.1,
497            100.0 * worst
498        );
499        // With hpr's own six-fin rule (ADR-008), exactly the Recruiter's six-fin slopes miss 1%.
500        assert_eq!(outside_own, ["recruiter fins", "recruiter total"]);
501    }
502
503    #[derive(Deserialize)]
504    struct DragCurves {
505        mach: f64,
506        reynolds_per_m: f64,
507        tolerance_rel: f64,
508        cases: Vec<DragCurveCase>,
509    }
510
511    #[derive(Deserialize)]
512    struct DragCurveCase {
513        id: String,
514        design: String,
515        variant_of: Option<String>,
516        thrusting: bool,
517        curve_cd0: f64,
518        hpr_cd0: f64,
519        relative_error: f64,
520    }
521
522    /// M1.5b done-when: subsonic `C_D0` of RocketPy's example rockets against the drag curves
523    /// that ship with them, at Mach 0.3 and USSA76 sea level (RASAero II computes its exports'
524    /// Reynolds numbers at sea level). The curves have unclear terms and stay in
525    /// `refs/`; `cargo xtask aero` writes the relative errors to
526    /// `validation/fixtures/aero/rocketpy-drag-curves.json`. This test recomputes hpr's values
527    /// from the committed designs, so the recorded errors can't go stale, and checks them against
528    /// the tolerance.
529    #[test]
530    fn rocketpy_drag_curves_at_mach_0_3() {
531        let fixture: DragCurves = serde_json::from_str(include_str!(
532            "../../../validation/fixtures/aero/rocketpy-drag-curves.json"
533        ))
534        .unwrap();
535        assert_eq!(fixture.mach, 0.3);
536        assert_eq!(fixture.tolerance_rel, 0.10);
537        let air = hpr_atmos::Ussa76::standard().sample(0.0).unwrap().air;
538        close(
539            fixture.reynolds_per_m,
540            0.3 * air.speed_of_sound_m_s / air.kinematic_viscosity_m2_s(),
541            1e-12,
542            "sea-level Reynolds number per meter",
543        );
544        let mut outside = Vec::new();
545        for case in &fixture.cases {
546            let rocket = committed_design(&case.design);
547            let model = AeroModel::new(&rocket.layout().unwrap()).unwrap();
548            // Every motor's area comes off the airframe's base, as no fixture design has pods.
549            assert!(model.pod_sets().is_empty(), "{}", case.design);
550            let motor_area: f64 = if case.thrusting {
551                rocket.configurations[0]
552                    .motors
553                    .iter()
554                    .map(|m| 0.25 * PI * m.diameter_m * m.diameter_m)
555                    .sum()
556            } else {
557                0.0
558            };
559            let conditions = if case.thrusting {
560                DragConditions::thrusting(fixture.reynolds_per_m, motor_area)
561            } else {
562                DragConditions::coasting(fixture.reynolds_per_m)
563            };
564            let drag = model.drag(&Flow::axial(fixture.mach), &conditions).unwrap();
565            // A stale fixture: rerun `cargo xtask aero`.
566            close(drag.zero_lift_coefficient, case.hpr_cd0, 1e-12, &case.id);
567            let error = drag.zero_lift_coefficient / case.curve_cd0 - 1.0;
568            assert!(
569                (error - case.relative_error).abs() < 1e-12,
570                "{}: recorded error {}, recomputed {error}",
571                case.id,
572                case.relative_error
573            );
574            eprintln!(
575                "{}: C_D0 {:.4} ({:.4} friction, {:.4} pressure, {:.4} base, {:.4} parasitic), \
576                 {:+.1}% from the curve",
577                case.id,
578                drag.zero_lift_coefficient,
579                drag.friction,
580                drag.pressure,
581                drag.base,
582                drag.parasitic,
583                100.0 * case.relative_error
584            );
585            if error.abs() > fixture.tolerance_rel {
586                outside.push(case.id.as_str());
587            }
588        }
589        // Six comparisons over four rockets, and one variant (Calisto's getting-started fins on
590        // the same export).
591        assert_eq!(fixture.cases.len(), 7);
592        let variants: Vec<&str> = fixture
593            .cases
594            .iter()
595            .filter(|c| c.variant_of.is_some())
596            .map(|c| c.id.as_str())
597            .collect();
598        assert_eq!(variants, ["calisto-getting-started-power-off"]);
599        // Outside the tolerance (ADR-009): Cavour under power, where the table carries at most
600        // 0.001 of relief at Mach 0.3 and hpr's depends on the unrecorded motor diameter; and
601        // Valetudo's table, 1.44 times the OpenRocket export for the same rocket, which hpr
602        // matches to 2% with that file's inputs. Since M1.14i3 relieves a boattailed base below
603        // Mach 0.8 (ADR-362), Calisto's getting-started fins (−11.5%, from −7.3%) and Juno III
604        // (−10.3%, from −6.0%) are outside too, where Calisto's own export comes to +0.2%, from
605        // +4.4%: one code against another, which sizes the difference and doesn't say which is
606        // right.
607        assert_eq!(
608            outside,
609            [
610                "calisto-getting-started-power-off",
611                "juno-iii-power-off",
612                "cavour-power-on",
613                "valetudo-power-off",
614                "valetudo-power-on"
615            ]
616        );
617    }
618
619    #[derive(Deserialize)]
620    struct NormalForceVsMach {
621        targets: Targets,
622        references: Vec<NormalForceReference>,
623    }
624
625    #[derive(Deserialize)]
626    struct Targets {
627        cp_calibers: f64,
628        cn_alpha_rel: f64,
629    }
630
631    #[derive(Deserialize)]
632    struct NormalForceReference {
633        id: String,
634        design: String,
635        reference_diameter_m: f64,
636        rows: Vec<NormalForceRow>,
637    }
638
639    #[derive(Deserialize)]
640    struct NormalForceRow {
641        mach: f64,
642        reference_cn_alpha_per_rad: f64,
643        reference_cp_m: f64,
644        hpr_cn_alpha_per_rad: f64,
645        hpr_cp_m: f64,
646        cn_alpha_error: f64,
647        cp_error_calibers: f64,
648        within_targets: bool,
649        reference_body_cn_alpha_per_rad: Option<f64>,
650        hpr_body_cn_alpha_per_rad: Option<f64>,
651    }
652
653    #[derive(Deserialize)]
654    struct WindTunnel {
655        configurations: Vec<WindTunnelConfiguration>,
656    }
657
658    #[derive(Deserialize)]
659    struct WindTunnelConfiguration {
660        id: String,
661        length_m: f64,
662        cn_alpha: Vec<WindTunnelCurve>,
663        cn_alpha_fins_off: Vec<WindTunnelCurve>,
664        cp: Vec<WindTunnelCp>,
665    }
666
667    #[derive(Deserialize)]
668    struct WindTunnelCurve {
669        mach: f64,
670        alpha_deg_c_n: Vec<[f64; 2]>,
671    }
672
673    #[derive(Deserialize)]
674    struct WindTunnelCp {
675        mach: f64,
676        percent_length: f64,
677    }
678
679    /// The least-squares slope of `ys` against `xs`, with an intercept.
680    fn lsq_slope(xs: &[f64], ys: &[f64]) -> f64 {
681        let n = xs.len() as f64;
682        let (mx, my) = (xs.iter().sum::<f64>() / n, ys.iter().sum::<f64>() / n);
683        let sxy: f64 = xs.iter().zip(ys).map(|(x, y)| (x - mx) * (y - my)).sum();
684        let sxx: f64 = xs.iter().map(|x| (x - mx) * (x - mx)).sum();
685        sxy / sxx
686    }
687
688    /// hpr's `C_N` and its moment about the nose tip at `alpha_deg`, odd in the angle, of the
689    /// whole rocket or of its bodies alone.
690    fn force_at(model: &AeroModel, mach: f64, alpha_deg: f64, bodies_only: bool) -> (f64, f64) {
691        let parts = model
692            .components(&Flow::new(mach, alpha_deg.abs().to_radians(), 0.0))
693            .unwrap();
694        let kept = if bodies_only {
695            &parts[..model.bodies().len()]
696        } else {
697            &parts[..]
698        };
699        let sign = alpha_deg.signum();
700        (
701            sign * kept.iter().map(|p| p.normal_force.coefficient).sum::<f64>(),
702            sign * kept.iter().map(|p| p.normal_force.moment_m).sum::<f64>(),
703        )
704    }
705
706    /// M1.8a done-when: hpr's `C_Nα` and CP against Mach, against RASAero II's Calisto export
707    /// (Mach 0.1–2.0; hpr's small-angle values) and NASA's Arcas Robin wind-tunnel models
708    /// (TN D-4013 and TN D-4014, Mach 0.6–4.63; hpr fitted as the plots are). `cargo xtask aero`
709    /// writes `validation/fixtures/aero/normal-force-vs-mach.json`; this test recomputes every
710    /// hpr value from the committed designs, and every wind-tunnel slope from the committed
711    /// points, so the recorded errors can't go stale, and pins the set of rows outside the
712    /// targets set before measuring (CP within 0.5 calibers, `C_Nα` within 15%). Each miss is
713    /// explained in `docs/physics/aero.md` and ADR-027.
714    #[test]
715    fn normal_force_against_mach() {
716        let fixture: NormalForceVsMach = serde_json::from_str(include_str!(
717            "../../../validation/fixtures/aero/normal-force-vs-mach.json"
718        ))
719        .unwrap();
720        let tunnel: WindTunnel = serde_json::from_str(include_str!(
721            "../../../validation/fixtures/aero/arcas-robin-wind-tunnel.json"
722        ))
723        .unwrap();
724        assert_eq!(fixture.targets.cp_calibers, 0.5);
725        assert_eq!(fixture.targets.cn_alpha_rel, 0.15);
726        let cp_angles: Vec<f64> = [-2.0_f64, -1.0, 0.0, 1.0, 2.0]
727            .iter()
728            .map(|a| a.to_radians())
729            .collect();
730        let mut misses = Vec::new();
731        for reference in &fixture.references {
732            let model =
733                AeroModel::new(&committed_design(&reference.design).layout().unwrap()).unwrap();
734            let d = (4.0 * model.reference_area_m2() / PI).sqrt();
735            close(reference.reference_diameter_m, d, 1e-15, &reference.id);
736            let configuration = tunnel.configurations.iter().find(|c| c.id == reference.id);
737            for row in &reference.rows {
738                let what = format!("{} at Mach {}", reference.id, row.mach);
739                let (cn_alpha, cp_m, hpr_cn_alpha, hpr_cp_m) = match configuration {
740                    // RASAero II's export: hpr's small-angle slope and CP.
741                    None => {
742                        let force = model.normal_force(&Flow::axial(row.mach)).unwrap();
743                        (
744                            row.reference_cn_alpha_per_rad,
745                            row.reference_cp_m,
746                            force.slope_per_rad,
747                            force.cp_station_m.unwrap(),
748                        )
749                    }
750                    // The wind tunnel: both slopes fitted at the plotted angles, the CP over
751                    // -2 to 2 degrees.
752                    Some(configuration) => {
753                        let fit = |curves: &[WindTunnelCurve], bodies_only: bool| {
754                            let curve = curves.iter().find(|c| c.mach == row.mach).unwrap();
755                            let alphas: Vec<f64> = curve
756                                .alpha_deg_c_n
757                                .iter()
758                                .map(|p| p[0].to_radians())
759                                .collect();
760                            let measured: Vec<f64> =
761                                curve.alpha_deg_c_n.iter().map(|p| p[1]).collect();
762                            let hpr: Vec<f64> = curve
763                                .alpha_deg_c_n
764                                .iter()
765                                .map(|p| force_at(&model, row.mach, p[0], bodies_only).0)
766                                .collect();
767                            (lsq_slope(&alphas, &measured), lsq_slope(&alphas, &hpr))
768                        };
769                        let (measured, hpr) = fit(&configuration.cn_alpha, false);
770                        if let Some(curve_body) = row.reference_body_cn_alpha_per_rad {
771                            let (body, hpr_body) = fit(&configuration.cn_alpha_fins_off, true);
772                            close(curve_body, body, 1e-12, &format!("{what}: body"));
773                            close(
774                                row.hpr_body_cn_alpha_per_rad.unwrap(),
775                                hpr_body,
776                                1e-12,
777                                &format!("{what}: hpr's body"),
778                            );
779                        }
780                        let cp = configuration
781                            .cp
782                            .iter()
783                            .find(|c| c.mach == row.mach)
784                            .unwrap();
785                        let forces: Vec<(f64, f64)> = [-2.0, -1.0, 0.0, 1.0, 2.0]
786                            .iter()
787                            .map(|&a| force_at(&model, row.mach, a, false))
788                            .collect();
789                        let normal: Vec<f64> = forces.iter().map(|f| f.0).collect();
790                        let moment: Vec<f64> = forces.iter().map(|f| f.1).collect();
791                        (
792                            measured,
793                            0.01 * cp.percent_length * configuration.length_m,
794                            hpr,
795                            lsq_slope(&cp_angles, &moment) / lsq_slope(&cp_angles, &normal),
796                        )
797                    }
798                };
799                // A stale fixture: rerun `cargo xtask aero`.
800                close(row.reference_cn_alpha_per_rad, cn_alpha, 1e-12, &what);
801                close(row.reference_cp_m, cp_m, 1e-12, &what);
802                close(row.hpr_cn_alpha_per_rad, hpr_cn_alpha, 1e-12, &what);
803                close(row.hpr_cp_m, hpr_cp_m, 1e-12, &what);
804                let cn_error = hpr_cn_alpha / cn_alpha - 1.0;
805                let cp_error = (hpr_cp_m - cp_m) / d;
806                assert!((row.cn_alpha_error - cn_error).abs() < 1e-12, "{what}");
807                assert!((row.cp_error_calibers - cp_error).abs() < 1e-12, "{what}");
808                let within = cn_error.abs() <= 0.15 && cp_error.abs() <= 0.5;
809                assert_eq!(row.within_targets, within, "{what}");
810                eprintln!(
811                    "{what}: C_Na {hpr_cn_alpha:.3} against {cn_alpha:.3} ({:+.1}%), CP {:+.2} \
812                     calibers",
813                    100.0 * cn_error,
814                    cp_error
815                );
816                if !within {
817                    misses.push(format!("{}@{}", reference.id, row.mach));
818                }
819            }
820        }
821        assert_eq!(fixture.references.len(), 3);
822        assert_eq!(
823            misses,
824            [
825                // Calisto against RASAero II: hpr's Prandtl-Glauert rise and aft CP near Mach 1,
826                // which RASAero II's constant subsonic slope doesn't have, and the linear join's
827                // peak at M_s = 1.28. Since M1.8e7 its von Karman nose's vertical tip flies the
828                // shock-expansion method behind a Newtonian cap, so its body carries lift on the
829                // cylinder past Mach 1.2: Mach 2 reads +8.8% (-16.8% on slender-body theory) and
830                // Mach 1.5 +13.2% (-3.1%; ADR-038).
831                "calisto-rasaero-ii@0.8",
832                "calisto-rasaero-ii@0.9",
833                "calisto-rasaero-ii@0.95",
834                "calisto-rasaero-ii@1.3",
835                // The Arcas Robin: the measured transonic dip in the fins' lift and the join's
836                // peak (Mach 0.8 to 1.2). Since M1.8e8 the committed designs fly the
837                // shock-expansion method to their base (their vertical tip behind a Newtonian cap
838                // since M1.8e7, their lip carrying nothing in the boattail's wake since e8), so
839                // every row from Mach 1.5 is within the slope's target, where the short model read
840                // -16.3% to -28.0% before. What is left on the long model at Mach 1.8 and 2.3 is
841                // the center of pressure, 0.53 and 0.52 calibers forward of the measured, where
842                // the body reads 15% to 19% high fins off (ADR-039).
843                "arcas-robin-short@0.8",
844                "arcas-robin-short@0.9",
845                "arcas-robin-short@0.95",
846                "arcas-robin-short@1.2",
847                "arcas-robin-long@0.9",
848                "arcas-robin-long@1",
849                "arcas-robin-long@1.2",
850                "arcas-robin-long@1.8",
851                "arcas-robin-long@2.3",
852            ]
853        );
854    }
855
856    #[derive(Deserialize)]
857    struct DragVsMach {
858        target_rel: f64,
859        reynolds_per_m: f64,
860        references: Vec<DragReference>,
861    }
862
863    #[derive(Deserialize)]
864    struct DragReference {
865        id: String,
866        design: String,
867        rows: Vec<DragRow>,
868    }
869
870    #[derive(Deserialize)]
871    struct DragRow {
872        mach: f64,
873        fins: String,
874        reference_forebody_c_a: f64,
875        hpr_forebody_c_d: f64,
876        hpr_base: f64,
877        error: f64,
878        within_target: bool,
879    }
880
881    #[derive(Deserialize)]
882    struct AxialTunnel {
883        configurations: Vec<AxialConfiguration>,
884    }
885
886    #[derive(Deserialize)]
887    struct AxialConfiguration {
888        id: String,
889        design: String,
890        axial_force: Vec<AxialPoint>,
891    }
892
893    #[derive(Deserialize)]
894    struct AxialPoint {
895        mach: f64,
896        fins: String,
897        forebody_c_a: f64,
898        c_a: Option<f64>,
899        chamber_c_a: Option<f64>,
900        forebody_c_a_chamber_only: Option<f64>,
901    }
902
903    /// M1.8b1 done-when: hpr's forebody drag (`C_D0` less the base drag) against the Arcas Robin
904    /// wind-tunnel models' forebody axial force at every Mach number the reports give, fins on
905    /// and off (TN D-4013's `C_A,corr`, Mach 0.6–1.2; TN D-4014's `C_A` less its chamber force,
906    /// Mach 1.5–4.63). `cargo xtask aero` writes `validation/fixtures/aero/drag-vs-mach.json`;
907    /// this test recomputes every hpr value from the committed designs at the tunnels' Reynolds
908    /// number, checks every measured point is compared, and pins the rows within the 10% target
909    /// set before measuring, so every other row is a pinned miss (42 of 44). Each miss is
910    /// explained in `docs/physics/aero.md`, ADR-028 and ADR-030.
911    #[test]
912    fn drag_against_mach() {
913        let fixture: DragVsMach = serde_json::from_str(include_str!(
914            "../../../validation/fixtures/aero/drag-vs-mach.json"
915        ))
916        .unwrap();
917        let tunnel: AxialTunnel = serde_json::from_str(include_str!(
918            "../../../validation/fixtures/aero/arcas-robin-wind-tunnel.json"
919        ))
920        .unwrap();
921        assert_eq!(fixture.target_rel, 0.10);
922        assert_eq!(fixture.reynolds_per_m, 3.0e6 / 0.3048);
923        let conditions = DragConditions::coasting(fixture.reynolds_per_m);
924        let (mut within, mut rows) = (Vec::new(), 0);
925        assert_eq!(fixture.references.len(), tunnel.configurations.len());
926        for (reference, configuration) in fixture.references.iter().zip(&tunnel.configurations) {
927            assert_eq!(reference.id, configuration.id);
928            assert_eq!(reference.design, configuration.design);
929            assert_eq!(
930                reference.rows.len(),
931                configuration.axial_force.len(),
932                "{}: every measured point is compared",
933                reference.id
934            );
935            let model =
936                AeroModel::new(&committed_design(&reference.design).layout().unwrap()).unwrap();
937            let fin_ids: Vec<&str> = model.fin_sets().iter().map(|f| f.id.as_str()).collect();
938            for (row, point) in reference.rows.iter().zip(&configuration.axial_force) {
939                let what = format!("{}@{} fins {}", reference.id, row.mach, row.fins);
940                assert_eq!((row.mach, &row.fins), (point.mach, &point.fins), "{what}");
941                assert_eq!(row.reference_forebody_c_a, point.forebody_c_a, "{what}");
942                // TN D-4014's forebody is its `C_A` less the chamber's force over the whole base,
943                // `1.383 C_A,c` with 1.383 = (1.470/1.250)², to the readings' 4 decimals; the
944                // chamber-only bound is `C_A − C_A,c`.
945                if let (Some(c_a), Some(chamber)) = (point.c_a, point.chamber_c_a) {
946                    let factor = (1.470f64 / 1.250).powi(2);
947                    assert!(
948                        (point.forebody_c_a - (c_a - factor * chamber)).abs() < 1.5e-4,
949                        "{what}"
950                    );
951                    let bound = point.forebody_c_a_chamber_only.unwrap_or(f64::NAN);
952                    assert!((bound - (c_a - chamber)).abs() < 1.5e-4, "{what}");
953                }
954                let parts = model
955                    .buildup_components(&Flow::axial(row.mach), &conditions)
956                    .unwrap();
957                let kept = parts
958                    .iter()
959                    .filter(|p| row.fins == "on" || !fin_ids.contains(&p.id.as_str()));
960                let (mut forebody, mut base) = (0.0, 0.0);
961                for part in kept {
962                    forebody += part.drag.friction + part.drag.pressure + part.drag.parasitic;
963                    base += part.drag.base;
964                }
965                close(row.hpr_forebody_c_d, forebody, 1e-12, &what);
966                close(row.hpr_base, base, 1e-12, &what);
967                let error = forebody / point.forebody_c_a - 1.0;
968                assert!((row.error - error).abs() < 1e-12, "{what}");
969                assert_eq!(
970                    row.within_target,
971                    error.abs() <= fixture.target_rel,
972                    "{what}"
973                );
974                rows += 1;
975                if row.within_target {
976                    within.push(what);
977                }
978            }
979        }
980        assert_eq!(rows, 44);
981        // Since the boattail's supersonic wave drag and the lip in its wake (ADR-030): before,
982        // 8 rows were within 10%, six of them because the lip's 0.085 made up for the missing
983        // wave drag.
984        assert_eq!(
985            within,
986            ["arcas-robin-short@1 fins on", "arcas-robin-long@1 fins on",]
987        );
988    }
989
990    /// M1.8b2 and M1.8b3 (ADR-029, ADR-030): Calisto's rows within 10% of its RASAero II export
991    /// over the inputs the export doesn't record. The export's values at the sweep's Mach numbers
992    /// come back from the committed fixture (hpr's value over one plus its error), and hpr flies
993    /// the 2018 design with square, rounded and airfoil fins 2 to 6.35 mm thick, smooth or painted
994    /// (20 µm), every 0.05 from Mach 0.1 to 2.0 at sea level. Before the boattail's supersonic
995    /// wave drag no combination had rows within 10% in both the subsonic and the supersonic bands
996    /// (the test was named `calistos_supersonic_gap_survives_every_plausible_fin_and_finish`).
997    /// Then the committed inputs (square, 3 mm, smooth, ADR-009's rule) had 15, 3 and 8, and
998    /// rounded fins 4.76 mm thick, smooth, had 15, 4 and 14: most of the supersonic gap left is
999    /// within what the unrecorded inputs span. The committed design keeps ADR-009's rule. Since
1000    /// M1.14i3's relief of a boattailed base below Mach 0.8 (ADR-362) they have 15, 5 and 8, and
1001    /// 6, 5 and 14: the committed inputs' subsonic rows read −1.7% to +3.3% of the export, where
1002    /// they read +3.9% to +8.9%, and the rounded fins' fall to −12.6% to −0.4%, from −8.4% to
1003    /// +5.8%. These rows are one code against another: they size the difference, not which is
1004    /// right.
1005    #[test]
1006    fn calistos_rows_by_fin_and_finish() {
1007        use hpr_design::{Component, FinCrossSection, Finish, Part};
1008
1009        let fixture: serde_json::Value = serde_json::from_str(include_str!(
1010            "../../../validation/fixtures/aero/rocketpy-drag-curves.json"
1011        ))
1012        .unwrap();
1013        let case = fixture["cases"]
1014            .as_array()
1015            .unwrap()
1016            .iter()
1017            .find(|c| c["id"] == "calisto-power-off")
1018            .unwrap();
1019        let rows: Vec<(f64, f64)> = case["sweep"]["rows"]
1020            .as_array()
1021            .unwrap()
1022            .iter()
1023            .map(|r| {
1024                let hpr = r["hpr_cd0"].as_f64().unwrap();
1025                let error = r["relative_error"].as_f64().unwrap();
1026                (r["mach"].as_f64().unwrap(), hpr / (1.0 + error))
1027            })
1028            .collect();
1029        assert_eq!(rows.len(), 39);
1030        let air = hpr_atmos::Ussa76::standard().sample(0.0).unwrap().air;
1031        fn set(components: &mut [Component], section: FinCrossSection, t: f64, finish: Finish) {
1032            for c in components {
1033                c.finish = Some(finish);
1034                if let Part::FinSet(fins) = &mut c.part {
1035                    fins.cross_section = section;
1036                    fins.thickness_m = t;
1037                }
1038                set(&mut c.children, section, t, finish);
1039            }
1040        }
1041        let (mut counts, mut ranges) = (Vec::new(), Vec::new());
1042        for section in [
1043            FinCrossSection::Square,
1044            FinCrossSection::Rounded,
1045            FinCrossSection::Airfoil,
1046        ] {
1047            for t in [0.002, 0.003, 0.00476, 0.00635] {
1048                for finish in [Finish::Mirror {}, Finish::MassProductionPaint {}] {
1049                    let mut rocket =
1050                        committed_design("rocketpy-calisto-tests-motor-at-minus-1.373.json");
1051                    set(&mut rocket.stages[0].components, section, t, finish);
1052                    let model = AeroModel::new(&rocket.layout().unwrap()).unwrap();
1053                    // Rows within 10% by band: subsonic to 0.8, transonic below 1.2, supersonic.
1054                    let mut within = [0usize; 3];
1055                    let mut errors: [Vec<f64>; 3] = Default::default();
1056                    for &(mach, curve) in &rows {
1057                        let conditions = DragConditions::coasting(
1058                            mach * air.speed_of_sound_m_s / air.kinematic_viscosity_m2_s(),
1059                        );
1060                        let drag = model.drag(&Flow::axial(mach), &conditions).unwrap();
1061                        let error = drag.zero_lift_coefficient / curve - 1.0;
1062                        let band = if mach <= 0.8 {
1063                            0
1064                        } else if mach < 1.2 {
1065                            1
1066                        } else {
1067                            2
1068                        };
1069                        if error.abs() <= 0.10 {
1070                            within[band] += 1;
1071                        }
1072                        errors[band].push(error);
1073                    }
1074                    counts.push(within);
1075                    // Each band's least and greatest error, in percent to 0.1.
1076                    let pct = |e: f64| (e * 1000.0).round() / 10.0;
1077                    ranges.push(errors.map(|band| {
1078                        let min = band.iter().copied().fold(f64::INFINITY, f64::min);
1079                        let max = band.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1080                        (pct(min), pct(max))
1081                    }));
1082                }
1083            }
1084        }
1085        // By section (square, rounded, airfoil), thickness (2, 3, 4.76, 6.35 mm) and finish
1086        // (smooth, painted): rows within 10% of 15 subsonic, 7 transonic and 17 supersonic.
1087        assert_eq!(
1088            counts,
1089            [
1090                [15, 4, 1],
1091                [14, 4, 8],
1092                [15, 5, 8],
1093                [6, 4, 15],
1094                [4, 3, 17],
1095                [0, 3, 17],
1096                [0, 3, 17],
1097                [0, 1, 2],
1098                [1, 4, 0],
1099                [13, 3, 4],
1100                [2, 3, 1],
1101                [13, 4, 9],
1102                [6, 5, 14],
1103                [13, 3, 17],
1104                [9, 4, 17],
1105                [12, 3, 17],
1106                [0, 4, 0],
1107                [12, 4, 2],
1108                [1, 4, 0],
1109                [12, 4, 7],
1110                [2, 5, 9],
1111                [12, 4, 17],
1112                [3, 4, 17],
1113                [12, 3, 17],
1114            ]
1115        );
1116        // The committed inputs (square, 3 mm, smooth) and rounded fins 4.76 mm thick, smooth:
1117        // no combination has every row within 10%.
1118        assert_eq!(ranges[2], [(-1.7, 3.3), (-10.1, 13.4), (-14.9, -5.1)]);
1119        assert_eq!(ranges[12], [(-12.6, -0.4), (-8.9, 19.5), (-11.7, -3.4)]);
1120        assert!(counts.iter().all(|c| c != &[15, 7, 17]));
1121    }
1122
1123    /// M1.8b3 (ADR-030): hpr's boattail pressure drag and the base pressure behind a boattail
1124    /// against measured conical boattails, and the boattail chart against Jack's second-order
1125    /// theory. `cargo xtask aero` writes each comparison into
1126    /// `validation/fixtures/aero/drag-vs-mach.json` from the transcribed references in
1127    /// `measured-boattails.json`; this recomputes every hpr value from the rows' geometry and pins
1128    /// the ranges the guide quotes. The targets were M1.8's 10%; how far each group misses is
1129    /// explained in `docs/physics/aero.md`.
1130    #[test]
1131    fn boattails_against_measurements() {
1132        use crate::afterbody::Boattail;
1133        let references: serde_json::Value = serde_json::from_str(include_str!(
1134            "../../../validation/fixtures/aero/measured-boattails.json"
1135        ))
1136        .unwrap();
1137        let fixture: serde_json::Value = serde_json::from_str(include_str!(
1138            "../../../validation/fixtures/aero/drag-vs-mach.json"
1139        ))
1140        .unwrap();
1141        let f = |row: &serde_json::Value, key: &str| row[key].as_f64().unwrap();
1142        // The subsonic rule gives long boattails exactly 0.
1143        let same = |got: f64, want: f64, what: &str| {
1144            assert!(
1145                (got - want).abs() <= 1e-12 * want.abs().max(1e-3),
1146                "{what}: {got} against {want}"
1147            );
1148        };
1149        let boattail = |row: &serde_json::Value| {
1150            let (l, r) = (f(row, "length_ratio"), f(row, "diameter_ratio").min(1.0));
1151            Boattail::new(l, 1.0, r).unwrap()
1152        };
1153        let rows = |section: &str| {
1154            let reference = references[section]["rows"].as_array().unwrap();
1155            let compared = fixture[section]["rows"].as_array().unwrap();
1156            assert_eq!(reference.len(), compared.len(), "{section}");
1157            compared.clone()
1158        };
1159        // Errors in percent to 0.1, as the guide quotes them.
1160        let range = |errors: &[f64]| {
1161            let pct = |e: f64| (e * 1000.0).round() / 10.0;
1162            let min = errors.iter().copied().fold(f64::INFINITY, f64::min);
1163            let max = errors.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1164            (errors.len(), pct(min), pct(max))
1165        };
1166
1167        // Measured boattail pressure drag, grouped by angle and speed: attached boattails of 12°
1168        // and gentler under Niskanen's rule (to Mach 0.8), in the straight-line rise (to Mach 1),
1169        // where the Mach 1.2 value is held (to 1.2), and faster; Cubbage's 16° ones; and his
1170        // separated 30° and 45° ones. Compton's points near Mach 1 that his report calls
1171        // questionable are a group of their own.
1172        let mut groups: std::collections::BTreeMap<&str, Vec<f64>> = Default::default();
1173        let mut absolute: Vec<f64> = Vec::new();
1174        for row in rows("boattails") {
1175            let b = boattail(&row);
1176            let mach = f(&row, "mach");
1177            let hpr = b.pressure_drag_coefficient(mach).unwrap();
1178            same(f(&row, "hpr"), hpr, "boattail");
1179            let error = hpr / f(&row, "cd") - 1.0;
1180            assert!((f(&row, "error") - error).abs() < 1e-12);
1181            let deg = b.half_angle_rad.to_degrees();
1182            let group = if row["flow"] == "separated" {
1183                "separated"
1184            } else if row["questionable"] == true {
1185                "questionable"
1186            } else if deg > 12.0 {
1187                if mach >= 1.0 {
1188                    "steep"
1189                } else {
1190                    "steep, subsonic"
1191                }
1192            } else if mach >= 1.2 {
1193                absolute.push(hpr - f(&row, "cd"));
1194                "supersonic"
1195            } else if mach >= 1.0 {
1196                "held"
1197            } else if mach > 0.8 {
1198                "rise"
1199            } else {
1200                "rule"
1201            };
1202            groups.entry(group).or_default().push(error);
1203        }
1204        let got: Vec<(&str, (usize, f64, f64))> =
1205            groups.iter().map(|(k, v)| (*k, range(v))).collect();
1206        assert_eq!(
1207            got,
1208            [
1209                ("held", (4, -18.2, -5.4)),
1210                ("questionable", (27, -46.2, 60.0)),
1211                ("rise", (28, -77.5, 7.6)),
1212                ("rule", (58, -100.0, -83.5)),
1213                ("separated", (3, -2.8, 6.6)),
1214                ("steep", (9, 26.4, 54.2)),
1215                ("steep, subsonic", (6, -30.2, 60.4)),
1216                ("supersonic", (58, -21.9, 28.3)),
1217            ]
1218        );
1219        // From Mach 1.2 the biggest misses in percent are the smallest drags, 3° and 5°
1220        // boattails of 0.01 to 0.02; in drag coefficient every row is within 0.0123.
1221        assert!(absolute.iter().all(|e| e.abs() < 0.0123));
1222
1223        // The base pressure behind a boattail: the error in base drag on the cylinder's area.
1224        let mut differences = Vec::new();
1225        for row in rows("base_pressures") {
1226            let b = boattail(&row);
1227            let k = b
1228                .base_pressure_ratio(f(&row, "mach"), b.area_ratio)
1229                .unwrap();
1230            same(f(&row, "k_hpr"), k, "base ratio");
1231            let measured = f(&row, "boattail_cp") / f(&row, "cylinder_cp");
1232            let difference = (k - measured) * -f(&row, "cylinder_cp") * b.area_ratio;
1233            assert!((f(&row, "base_cd_difference") - difference).abs() < 1e-12);
1234            differences.push(difference);
1235        }
1236        assert_eq!(differences.len(), 12);
1237        assert!(differences.iter().all(|d| d.abs() < 0.0102));
1238        assert_eq!(differences.iter().filter(|d| d.abs() <= 0.004).count(), 10);
1239
1240        // The chart, held to the 2D limit, against Jack's second-order theory.
1241        let (mut inside, mut past, mut shallow) = (Vec::new(), Vec::new(), Vec::new());
1242        for row in rows("second_order_theory") {
1243            let a = f(&row, "area_ratio");
1244            let theta = f(&row, "half_angle_deg").to_radians();
1245            let r = a.sqrt();
1246            let b = Boattail::new((1.0 - r) / (2.0 * theta.tan()), 1.0, r).unwrap();
1247            let mach = f(&row, "mach");
1248            let hpr = b.attached_pressure_drag(mach).unwrap();
1249            same(f(&row, "hpr"), hpr, "theory");
1250            let error = hpr / f(&row, "cd") - 1.0;
1251            assert!((f(&row, "error") - error).abs() < 1e-12);
1252            if a > 0.6 + 1e-9 {
1253                shallow.push(error);
1254            } else if f(&row, "x") <= 1.4 {
1255                inside.push(error);
1256            } else {
1257                past.push(error);
1258            }
1259        }
1260        assert_eq!(range(&inside), (83, -10.4, 8.0));
1261        assert_eq!(range(&past), (28, -2.7, 8.0));
1262        // The 0.7 and 0.8 curves read high against Jack past x ≈ 1.
1263        assert_eq!(range(&shallow), (40, -1.5, 32.4));
1264    }
1265
1266    #[derive(Deserialize)]
1267    struct HandbookDrag {
1268        calculations: Vec<HandbookCalculation>,
1269    }
1270
1271    #[derive(Deserialize)]
1272    struct HandbookCalculation {
1273        design: String,
1274        rows: Vec<HandbookComparison>,
1275    }
1276
1277    #[derive(Deserialize)]
1278    struct HandbookComparison {
1279        mach: f64,
1280        reynolds_per_m: f64,
1281        reference: HandbookParts,
1282        hpr: HandbookParts,
1283        compared: HandbookCompared,
1284        error: f64,
1285        within_target: bool,
1286    }
1287
1288    #[derive(Deserialize)]
1289    struct HandbookCompared {
1290        reference: f64,
1291        hpr: f64,
1292    }
1293
1294    #[derive(Deserialize)]
1295    struct HandbookParts {
1296        friction: f64,
1297        nose: f64,
1298        fins: f64,
1299        base: f64,
1300        #[serde(default)]
1301        other: f64,
1302        total: f64,
1303    }
1304
1305    #[derive(Deserialize)]
1306    struct HandbookReference {
1307        rows: Vec<HandbookRow>,
1308    }
1309
1310    #[derive(Deserialize)]
1311    struct HandbookRow {
1312        mach: f64,
1313        reynolds_per_m: f64,
1314        body_friction: f64,
1315        fin_friction: f64,
1316        friction: f64,
1317        nose_wave: Option<f64>,
1318        fin_wave: Option<f64>,
1319        fin_base: f64,
1320        fins: f64,
1321        base: f64,
1322        total_jet_off: f64,
1323    }
1324
1325    /// M1.8b2: hpr's `C_D0`, base drag included, against MIL-HDBK-762's sample drag calculation
1326    /// (Table 5-4, pp. 5-58 to 5-66) for the rocket of its Fig. 5-155, term by term, at the
1327    /// table's Reynolds numbers. A calculation with every input known, not a measurement: it
1328    /// shows which way hpr's methods lean where RASAero II's curves can't, because their inputs
1329    /// are unrecorded (ADR-029). The handbook's fins are single wedges, sharp at the leading edge,
1330    /// which hpr can't represent, so the fins' pressure drag is recorded but compared on neither
1331    /// side. `cargo xtask aero` writes the comparison to
1332    /// `validation/fixtures/aero/drag-vs-mach.json`; this checks the transcription's sums,
1333    /// recomputes hpr's terms, and pins the rows within M1.8's 10%.
1334    #[test]
1335    fn drag_against_mil_hdbk_762_sample() {
1336        let reference: HandbookReference = serde_json::from_str(include_str!(
1337            "../../../validation/fixtures/aero/mil-hdbk-762-sample-drag.json"
1338        ))
1339        .unwrap();
1340        // Each printed row's parts add up to its totals, to the table's 3 decimals.
1341        for row in &reference.rows {
1342            let what = format!("Table 5-4 at Mach {}", row.mach);
1343            assert!(
1344                (row.body_friction + row.fin_friction - row.friction).abs() < 1.5e-3,
1345                "{what}"
1346            );
1347            assert!(
1348                (row.fin_wave.unwrap_or(0.0) + row.fin_base - row.fins).abs() < 1.5e-3,
1349                "{what}"
1350            );
1351            let sum = row.friction + row.nose_wave.unwrap_or(0.0) + row.fins + row.base;
1352            assert!((sum - row.total_jet_off).abs() < 1.5e-3, "{what}");
1353            assert_eq!(row.nose_wave.is_none(), row.mach < 0.9, "{what}");
1354            assert_eq!(row.fin_wave.is_none(), row.mach < 0.95, "{what}");
1355        }
1356        let fixture: HandbookDrag = serde_json::from_str(include_str!(
1357            "../../../validation/fixtures/aero/drag-vs-mach.json"
1358        ))
1359        .unwrap();
1360        let [calculation] = fixture.calculations.as_slice() else {
1361            panic!("one calculation")
1362        };
1363        let model =
1364            AeroModel::new(&committed_design(&calculation.design).layout().unwrap()).unwrap();
1365        assert_eq!(calculation.rows.len(), reference.rows.len());
1366        let mut within = Vec::new();
1367        for (row, printed) in calculation.rows.iter().zip(&reference.rows) {
1368            let what = format!("Mach {}", row.mach);
1369            assert_eq!(
1370                (row.mach, row.reynolds_per_m),
1371                (printed.mach, printed.reynolds_per_m)
1372            );
1373            let r = &row.reference;
1374            assert_eq!(
1375                (r.friction, r.nose, r.fins, r.base, r.total),
1376                (
1377                    printed.friction,
1378                    printed.nose_wave.unwrap_or(0.0),
1379                    printed.fins,
1380                    printed.base,
1381                    printed.total_jet_off
1382                ),
1383                "{what}"
1384            );
1385            let conditions = DragConditions::coasting(printed.reynolds_per_m);
1386            let flow = Flow::axial(row.mach);
1387            let drag = model.drag(&flow, &conditions).unwrap();
1388            let parts = model.buildup_components(&flow, &conditions).unwrap();
1389            let pressure = |id: &str| {
1390                parts
1391                    .iter()
1392                    .filter(|p| p.id == id)
1393                    .map(|p| p.drag.pressure)
1394                    .sum::<f64>()
1395            };
1396            let h = &row.hpr;
1397            // To 1e-12, not bit for bit: the nose's drag goes through `powf`, `ln` and `atan`,
1398            // whose last bit differs between platforms' maths libraries.
1399            close(h.total, drag.zero_lift_coefficient, 1e-12, &what);
1400            close(h.friction, drag.friction, 1e-12, &what);
1401            close(h.base, drag.base, 1e-12, &what);
1402            close(h.nose, pressure("nose"), 1e-12, &what);
1403            close(h.fins, pressure("fins"), 1e-12, &what);
1404            assert_eq!(
1405                h.other, 0.0,
1406                "{what}: only the nose and fins have pressure drag"
1407            );
1408            assert!(
1409                (h.friction + h.nose + h.fins + h.base - h.total).abs() < 1e-12,
1410                "{what}"
1411            );
1412            let c = &row.compared;
1413            close(c.hpr, h.total - h.fins, 1e-12, &what);
1414            close(
1415                c.reference,
1416                printed.total_jet_off - printed.fins,
1417                1e-12,
1418                &what,
1419            );
1420            let error = c.hpr / c.reference - 1.0;
1421            assert!((row.error - error).abs() < 1e-12, "{what}");
1422            assert_eq!(row.within_target, error.abs() <= 0.10, "{what}");
1423            if row.within_target {
1424                within.push(row.mach);
1425            }
1426        }
1427        // Within 10% at Mach 0.7 and from 1.6 (ADR-029). From Mach 0.9 to 1.2 hpr reads 12% to
1428        // 32% high, the nose (Niskanen's ogive, 0.234 against the handbook's 0.109 at Mach 1.1)
1429        // and the base (Fleeman's 0.25 against 0.183 at Mach 1.0). From Mach 1.6 it reads 6% to
1430        // 10% low: friction (hpr's body form factor 1.02 against the handbook's 1.15) and base
1431        // drag (0.125 against 0.147 at Mach 2). At Mach 0.5 it is 10.3% low, the friction.
1432        assert_eq!(within, [0.7, 1.6, 2.0, 2.4, 2.8, 3.2]);
1433    }
1434
1435    /// The Arcas Robin comparison's two input choices (validation audit): of the 44 rows, none
1436    /// within 10% with the square section and the default 20 µm finish, none with the airfoil
1437    /// section, none with a polished finish, and 2 with both (the committed designs); before the
1438    /// boattail's supersonic wave drag (ADR-030) these were 3, 5, 6 and 8. Taking the chamber's
1439    /// force over the chamber alone changes none of the four. Allowing each reading its
1440    /// uncertainty and the reports' ±0.004, neither of the committed design's 2 could fall the
1441    /// other side of 10%.
1442    #[test]
1443    fn drag_against_mach_depends_on_the_fins_and_finish() {
1444        use hpr_design::{FinCrossSection, Finish, Part};
1445        let tunnel: serde_json::Value = serde_json::from_str(include_str!(
1446            "../../../validation/fixtures/aero/arcas-robin-wind-tunnel.json"
1447        ))
1448        .unwrap();
1449        let conditions = DragConditions::coasting(3.0e6 / 0.3048);
1450        let mut counts = Vec::new();
1451        for (section, finish) in [
1452            (FinCrossSection::Square, None),
1453            (FinCrossSection::Airfoil, None),
1454            (FinCrossSection::Square, Some(Finish::Polished {})),
1455            (FinCrossSection::Airfoil, Some(Finish::Polished {})),
1456        ] {
1457            let (mut within, mut chamber_only, mut fragile) = (0, 0, 0);
1458            for configuration in tunnel["configurations"].as_array().unwrap() {
1459                let mut rocket = committed_design(configuration["design"].as_str().unwrap());
1460                for component in &mut rocket.stages[0].components {
1461                    component.finish = finish;
1462                    for child in &mut component.children {
1463                        child.finish = finish;
1464                        if let Part::FinSet(set) = &mut child.part {
1465                            set.cross_section = section;
1466                        }
1467                    }
1468                }
1469                let model = AeroModel::new(&rocket.layout().unwrap()).unwrap();
1470                let fin_ids: Vec<&str> = model.fin_sets().iter().map(|f| f.id.as_str()).collect();
1471                for point in configuration["axial_force"].as_array().unwrap() {
1472                    let mach = point["mach"].as_f64().unwrap();
1473                    let fins = point["fins"] == "on";
1474                    let hpr: f64 = model
1475                        .buildup_components(&Flow::axial(mach), &conditions)
1476                        .unwrap()
1477                        .iter()
1478                        .filter(|part| fins || !fin_ids.contains(&part.id.as_str()))
1479                        .map(|part| part.drag.friction + part.drag.pressure + part.drag.parasitic)
1480                        .sum();
1481                    let measured = point["forebody_c_a"].as_f64().unwrap();
1482                    let inside = |reference: f64| (hpr / reference - 1.0).abs() <= 0.10;
1483                    within += usize::from(inside(measured));
1484                    let bound = point["forebody_c_a_chamber_only"]
1485                        .as_f64()
1486                        .unwrap_or(measured);
1487                    chamber_only += usize::from(inside(bound));
1488                    let spread = point["uncertainty"].as_f64().unwrap() + 0.004;
1489                    fragile += usize::from(
1490                        inside(measured)
1491                            && !(inside(measured - spread) && inside(measured + spread)),
1492                    );
1493                }
1494            }
1495            assert_eq!(within, chamber_only, "{section:?}, {finish:?}");
1496            counts.push((within, fragile));
1497        }
1498        assert_eq!(counts.iter().map(|c| c.0).collect::<Vec<_>>(), [0, 0, 0, 2]);
1499        assert_eq!(counts[3].1, 0);
1500    }
1501
1502    /// M1.14b1: hpr's normal-force slope and center of pressure for the Basic Finner against
1503    /// DREV-TM-9703 Table IX's range fits (Dupuis and Hathaway 1997, PDF pp. 48–49), as
1504    /// `cargo xtask aero` writes them to `basic-finner-normal-force.json`. Every figure is
1505    /// recomputed here from the committed design and the committed reference, so the report
1506    /// can't go stale: the measured center of pressure, `x_ref − C_mα / C_Nα`; its probable
1507    /// error, the ratio's; hpr's small-angle slope and CP; and both errors.
1508    ///
1509    /// It also pins which way hpr errs, and by how much, on each row. Its center of pressure
1510    /// lies forward of the measured one at all six Mach numbers, which understates stability:
1511    /// the side that doesn't flatter. Its slope reads low at all six. Both hold as the angle
1512    /// of attack goes to zero and at each fit's root-mean-square yaw, where hpr's body lift adds
1513    /// to its slope: the fits hold their cubic terms at zero, so the measured slopes are linear
1514    /// fits over the angles flown.
1515    #[expect(
1516        clippy::approx_constant,
1517        reason = "the table's fifth Mach number is 2.718: a Mach number, not e"
1518    )]
1519    #[test]
1520    fn basic_finner_normal_force_against_drev() {
1521        use serde_json::Value;
1522        let report: Value = serde_json::from_str(include_str!(
1523            "../../../validation/fixtures/aero/basic-finner-normal-force.json"
1524        ))
1525        .unwrap();
1526        let reference: Value = serde_json::from_str(include_str!(
1527            "../../../validation/fixtures/aero/basic-finner-drev.json"
1528        ))
1529        .unwrap();
1530        let f = |v: &Value| v.as_f64().unwrap();
1531        let design = reference["design"].as_str().unwrap();
1532        assert_eq!(report["design"], design);
1533        let model = AeroModel::new(&committed_design(design).layout().unwrap()).unwrap();
1534        let d = model.reference_diameter_m();
1535        close(
1536            f(&reference["geometry"]["diameter_m"]),
1537            d,
1538            1e-15,
1539            "diameter",
1540        );
1541        // The report's Fig. 2: 10 calibers overall, the fins flush with the base.
1542        close(model.length_m() / d, 10.0, 1e-12, "length in calibers");
1543        let x_ref = f(&reference["moment_reference_calibers"]);
1544        assert_eq!(x_ref, 5.5);
1545        assert_eq!(f(&report["moment_reference_calibers"]), x_ref);
1546        close(f(&report["reference_diameter_m"]), d, 1e-15, "diameter");
1547        let measured = reference["rows"].as_array().unwrap();
1548        let rows = report["rows"].as_array().unwrap();
1549        assert_eq!(rows.len(), measured.len());
1550        // Mach, the row's band, hpr's slope error and hpr's CP error in calibers (positive aft)
1551        // as the angle goes to zero, as the accuracy and aerodynamics pages quote them; then the
1552        // same two at the fit's root-mean-square yaw.
1553        let (below, core, extended) = (
1554            "below Mach 1.5",
1555            "core, Mach 1.5 to 2.5",
1556            "extended, Mach 2.5 to 3.5",
1557        );
1558        let pinned = [
1559            (1.077, below, (-0.249, -0.07), (-0.241, -0.10)),
1560            (1.293, below, (-0.249, -0.03), (-0.239, -0.07)),
1561            (1.832, core, (-0.112, -0.34), (-0.101, -0.36)),
1562            (2.375, core, (-0.161, -0.18), (-0.146, -0.21)),
1563            (2.718, extended, (-0.093, -0.27), (-0.069, -0.31)),
1564            (3.147, extended, (-0.130, -0.23), (-0.109, -0.26)),
1565        ];
1566        assert_eq!(rows.len(), pinned.len());
1567        let (mut cp_inside_the_fit, mut cp_inside_the_fit_at_yaw) = (Vec::new(), Vec::new());
1568        for ((row, reading), (mach, band, (slope_error, cp_error), at_yaw)) in
1569            rows.iter().zip(measured).zip(pinned)
1570        {
1571            let what = format!("the Basic Finner at Mach {mach}");
1572            assert_eq!(f(&row["mach"]), mach, "{what}");
1573            assert_eq!(row["band"], band, "{what}");
1574            assert_eq!(f(&reading["mach"]), mach, "{what}");
1575            let (cn_alpha, cm_alpha) = (f(&reading["cn_alpha"]), f(&reading["cm_alpha"]));
1576            assert_eq!(f(&row["reference_cn_alpha_per_rad"]), cn_alpha, "{what}");
1577            // The measured center of pressure and its probable error, by the ratio's rule; a
1578            // probable error the table prints as 0% is taken as half a percent.
1579            let arm = -cm_alpha / cn_alpha;
1580            let relative = |key: &str| 0.01 * f(&reading[key]).max(0.5);
1581            let (e_n, e_m) = (
1582                relative("cn_alpha_probable_error_percent"),
1583                relative("cm_alpha_probable_error_percent"),
1584            );
1585            let cp = x_ref + arm;
1586            let cp_probable_error = arm * (e_n * e_n + e_m * e_m).sqrt();
1587            close(f(&row["reference_cp_calibers"]), cp, 1e-12, &what);
1588            close(
1589                f(&row["reference_cn_alpha_probable_error"]),
1590                e_n,
1591                1e-12,
1592                &what,
1593            );
1594            close(
1595                f(&row["reference_cp_probable_error_calibers"]),
1596                cp_probable_error,
1597                1e-12,
1598                &what,
1599            );
1600            // hpr, straight into the wind.
1601            let force = model.normal_force(&Flow::axial(mach)).unwrap();
1602            let hpr_cp = force.cp_station_m.unwrap() / d;
1603            close(
1604                f(&row["hpr_cn_alpha_per_rad"]),
1605                force.slope_per_rad,
1606                1e-12,
1607                &what,
1608            );
1609            close(f(&row["hpr_cp_calibers"]), hpr_cp, 1e-12, &what);
1610            // hpr's slope by part: the bodies come first, then the fin set. The parts sum to
1611            // the whole, and their moments to the whole's.
1612            let parts = model.components(&Flow::axial(mach)).unwrap();
1613            let (bodies, fins) = parts.split_at(model.bodies().len());
1614            assert_eq!(fins.len(), 1, "{what}");
1615            let sum = |kept: &[ComponentNormalForce]| {
1616                (
1617                    kept.iter()
1618                        .map(|p| p.normal_force.slope_per_rad)
1619                        .sum::<f64>(),
1620                    kept.iter()
1621                        .map(|p| p.normal_force.moment_slope_m)
1622                        .sum::<f64>(),
1623                )
1624            };
1625            let ((body, body_moment), (fin, fin_moment)) = (sum(bodies), sum(fins));
1626            close(body + fin, force.slope_per_rad, 1e-12, &what);
1627            close(
1628                (body_moment + fin_moment) / (body + fin) / d,
1629                hpr_cp,
1630                1e-12,
1631                &what,
1632            );
1633            close(f(&row["hpr_body_cn_alpha_per_rad"]), body, 1e-12, &what);
1634            close(f(&row["hpr_fins_cn_alpha_per_rad"]), fin, 1e-12, &what);
1635            close(
1636                f(&row["hpr_body_cp_calibers"]),
1637                body_moment / body / d,
1638                1e-12,
1639                &what,
1640            );
1641            close(
1642                f(&row["hpr_fins_cp_calibers"]),
1643                fin_moment / fin / d,
1644                1e-12,
1645                &what,
1646            );
1647            let got_slope_error = force.slope_per_rad / cn_alpha - 1.0;
1648            let got_cp_error = hpr_cp - cp;
1649            close(f(&row["cn_alpha_error"]), got_slope_error, 1e-9, &what);
1650            close(f(&row["cp_error_calibers"]), got_cp_error, 1e-9, &what);
1651            // Which way, and how far: the slope low, the CP forward (negative), on every row.
1652            assert!(got_slope_error < 0.0, "{what}: slope {got_slope_error}");
1653            assert!(got_cp_error < 0.0, "{what}: CP {got_cp_error}");
1654            assert!(
1655                (got_slope_error - slope_error).abs() < 5e-4,
1656                "{what}: slope error {got_slope_error}"
1657            );
1658            assert!(
1659                (got_cp_error - cp_error).abs() < 5e-3,
1660                "{what}: CP error {got_cp_error}"
1661            );
1662            // The slope's miss is the model's, not the fit's scatter: larger than the fit's
1663            // probable error on every row.
1664            assert!(got_slope_error.abs() > e_n, "{what}");
1665            if got_cp_error.abs() <= cp_probable_error {
1666                cp_inside_the_fit.push(mach);
1667            }
1668            // Nearer like for like: hpr at the fit's root-mean-square yaw, where its body lift
1669            // adds to the slope. The slope is still low and the CP still forward, on every row.
1670            let rms_yaw_deg = f(&reading["mean_squared_yaw_deg2"]).sqrt();
1671            close(f(&row["rms_yaw_deg"]), rms_yaw_deg, 1e-12, &what);
1672            let yawed = model
1673                .normal_force(&Flow::new(mach, rms_yaw_deg.to_radians(), 0.0))
1674                .unwrap();
1675            assert!(yawed.slope_per_rad > force.slope_per_rad, "{what}");
1676            let yawed_cp = yawed.cp_station_m.unwrap() / d;
1677            close(
1678                f(&row["hpr_cn_over_alpha_at_rms_yaw_per_rad"]),
1679                yawed.slope_per_rad,
1680                1e-12,
1681                &what,
1682            );
1683            close(
1684                f(&row["hpr_cp_at_rms_yaw_calibers"]),
1685                yawed_cp,
1686                1e-12,
1687                &what,
1688            );
1689            let (yawed_slope_error, yawed_cp_error) =
1690                (yawed.slope_per_rad / cn_alpha - 1.0, yawed_cp - cp);
1691            close(
1692                f(&row["cn_alpha_error_at_rms_yaw"]),
1693                yawed_slope_error,
1694                1e-9,
1695                &what,
1696            );
1697            close(
1698                f(&row["cp_error_at_rms_yaw_calibers"]),
1699                yawed_cp_error,
1700                1e-9,
1701                &what,
1702            );
1703            assert!(
1704                yawed_slope_error < -e_n,
1705                "{what}: slope at yaw {yawed_slope_error}"
1706            );
1707            assert!(yawed_cp_error < 0.0, "{what}: CP at yaw {yawed_cp_error}");
1708            assert!(
1709                (yawed_slope_error - at_yaw.0).abs() < 5e-4,
1710                "{what}: slope error at yaw {yawed_slope_error}"
1711            );
1712            assert!(
1713                (yawed_cp_error - at_yaw.1).abs() < 5e-3,
1714                "{what}: CP error at yaw {yawed_cp_error}"
1715            );
1716            if yawed_cp_error.abs() <= cp_probable_error {
1717                cp_inside_the_fit_at_yaw.push(mach);
1718            }
1719        }
1720        assert_eq!(cp_inside_the_fit_at_yaw, [1.293]);
1721        // So is the CP's, on every row but one: at Mach 1.293 it is inside the fit's.
1722        assert_eq!(cp_inside_the_fit, [1.293]);
1723    }
1724
1725    /// M1.14b2: hpr's zero-lift drag and pitch damping for the Basic Finner against DREV-TM-9703
1726    /// Table IX's range fits (Dupuis and Hathaway 1997, PDF pp. 48–49), as `cargo xtask aero`
1727    /// writes them to `basic-finner-drag-damping.json`. Every figure is recomputed here from the
1728    /// committed design, the committed reference and the wedge's cited figures
1729    /// (`basic-finner-wedge.json`): the shots' Reynolds number; the buildup as drawn; the square
1730    /// fins' two edge terms swapped for the single wedge's faces (the attached oblique shock, or
1731    /// Vincenti and Wagoner's transonic value at Mach 1.077) and its trailing edges'
1732    /// two-dimensional base drag; and the pitch-damping read-out about the fits' moment
1733    /// reference, 5.5 calibers, with its fins' part.
1734    ///
1735    /// It pins which way hpr errs, and by how much, on each row. At Mach 1.077 the drag's nominal
1736    /// value (the faces at their upper bound, the trailing edges at their band's middle) reads
1737    /// high, but its band reaches below every shot there; it reads low at 1.293, inside the
1738    /// shots' spread; and low from Mach 1.832 up, below every shot at both ends of the wedge's
1739    /// band and even with the trailing edges at vacuum. The pitch
1740    /// damping reads low in size by more than the fit's probable error on every row but Mach
1741    /// 1.077, where it reads high: there HPR Sim overstates the damping, the side that flatters.
1742    #[expect(
1743        clippy::approx_constant,
1744        reason = "the table's fifth Mach number is 2.718: a Mach number, not e"
1745    )]
1746    #[test]
1747    fn basic_finner_drag_and_damping_against_drev() {
1748        use crate::blunt_tip::{wedge_detachment_angle_rad, wedge_pressure_coefficient};
1749        use crate::drag::{base_drag_coefficient, stagnation_drag_coefficient};
1750        use serde_json::Value;
1751        let report: Value = serde_json::from_str(include_str!(
1752            "../../../validation/fixtures/aero/basic-finner-drag-damping.json"
1753        ))
1754        .unwrap();
1755        let reference: Value = serde_json::from_str(include_str!(
1756            "../../../validation/fixtures/aero/basic-finner-drev.json"
1757        ))
1758        .unwrap();
1759        let wedge_figures: Value = serde_json::from_str(include_str!(
1760            "../../../validation/fixtures/aero/basic-finner-wedge.json"
1761        ))
1762        .unwrap();
1763        let f = |v: &Value| v.as_f64().unwrap();
1764        let design = reference["design"].as_str().unwrap();
1765        assert_eq!(report["design"], design);
1766        let model = AeroModel::new(&committed_design(design).layout().unwrap()).unwrap();
1767        let d = model.reference_diameter_m();
1768        close(f(&report["reference_diameter_m"]), d, 1e-15, "diameter");
1769        let x_ref = f(&reference["moment_reference_calibers"]);
1770        assert_eq!(f(&report["moment_reference_calibers"]), x_ref);
1771        // The wedge: each face turns the flow by half the trailing edge's 0.08 calibers over the
1772        // 1-caliber chord, 2.29°.
1773        let wedge = (0.5 * 0.08_f64).atan();
1774        close(f(&report["wedge_deflection_rad"]), wedge, 1e-15, "wedge");
1775        // The fins' frontal area, four 0.08 by 1 caliber edges on π/4 square calibers.
1776        let frontal = 4.0 * 0.08 / (0.25 * PI);
1777        close(
1778            f(&report["fins_frontal_area_ratio"]),
1779            frontal,
1780            1e-12,
1781            "frontal",
1782        );
1783        let measured = reference["rows"].as_array().unwrap();
1784        let rows = report["rows"].as_array().unwrap();
1785        let bases = wedge_figures["trailing_edge_base"].as_array().unwrap();
1786        // Mach, band, the drag's error with the wedge modeled, and the pitch damping's.
1787        let (below, core, extended) = (
1788            "below Mach 1.5",
1789            "core, Mach 1.5 to 2.5",
1790            "extended, Mach 2.5 to 3.5",
1791        );
1792        let pinned = [
1793            (1.077, below, 0.101, 0.254),
1794            (1.293, below, -0.035, -0.168),
1795            (1.832, core, -0.165, -0.247),
1796            (2.375, core, -0.206, -0.262),
1797            (2.718, extended, -0.213, -0.396),
1798            (3.147, extended, -0.193, -0.304),
1799        ];
1800        assert_eq!(rows.len(), pinned.len());
1801        assert_eq!(measured.len(), pinned.len());
1802        assert_eq!(bases.len(), pinned.len());
1803        for (((row, reading), base), (mach, band, drag_error, cmq_error)) in
1804            rows.iter().zip(measured).zip(bases).zip(pinned)
1805        {
1806            let what = format!("the Basic Finner at Mach {mach}");
1807            assert_eq!(f(&row["mach"]), mach, "{what}");
1808            assert_eq!(f(&reading["mach"]), mach, "{what}");
1809            assert_eq!(f(&base["mach"]), mach, "{what}");
1810            assert_eq!(row["band"], band, "{what}");
1811            let (cx0, cmq) = (f(&reading["cx0"]), f(&reading["cmq"]));
1812            assert_eq!(f(&row["reference_cx0"]), cx0, "{what}");
1813            assert_eq!(f(&row["reference_cmq"]), cmq, "{what}");
1814            let cmq_probable_error = 0.01 * f(&reading["cmq_probable_error_percent"]).max(0.5);
1815            close(
1816                f(&row["reference_cmq_probable_error"]),
1817                cmq_probable_error,
1818                1e-12,
1819                &what,
1820            );
1821            let cx0_probable_error = 0.01 * f(&reading["cx0_probable_error_percent"]).max(0.5);
1822            close(
1823                f(&row["reference_cx0_probable_error"]),
1824                cx0_probable_error,
1825                1e-12,
1826                &what,
1827            );
1828            assert_eq!(
1829                row["reference_cx0_fitted_in_the_row"], reading["cx0_fitted_in_the_row"],
1830                "{what}"
1831            );
1832            // The shots: their C_X0's spread and their mean Reynolds number on the 10-caliber
1833            // length.
1834            let shots = reading["shots"].as_array().unwrap();
1835            let shot = |key: &str| shots.iter().map(|s| f(&s[key])).collect::<Vec<_>>();
1836            let (cx0s, reynolds) = (shot("cx0"), shot("reynolds_on_length"));
1837            assert_eq!(row["shots"].as_u64(), Some(shots.len() as u64), "{what}");
1838            let low = cx0s.iter().copied().fold(f64::INFINITY, f64::min);
1839            let high = cx0s.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1840            assert_eq!(f(&row["shots_cx0_low"]), low, "{what}");
1841            assert_eq!(f(&row["shots_cx0_high"]), high, "{what}");
1842            let re = reynolds.iter().sum::<f64>() / reynolds.len() as f64 / (10.0 * d);
1843            close(f(&row["reynolds_per_m"]), re, 1e-12, &what);
1844            // The buildup as drawn, then the square edges' two terms swapped for the wedge's.
1845            let drag = model
1846                .drag(&Flow::axial(mach), &DragConditions::coasting(re))
1847                .unwrap();
1848            let drawn = drag.zero_lift_coefficient;
1849            close(f(&row["hpr_cd0_as_drawn"]), drawn, 1e-12, &what);
1850            close(f(&row["hpr_friction"]), drag.friction, 1e-12, &what);
1851            close(f(&row["hpr_pressure"]), drag.pressure, 1e-12, &what);
1852            close(f(&row["hpr_base"]), drag.base, 1e-12, &what);
1853            let leading = frontal * stagnation_drag_coefficient(mach).unwrap();
1854            let trailing = frontal * base_drag_coefficient(mach).unwrap();
1855            close(f(&row["hpr_fins_leading_edge"]), leading, 1e-12, &what);
1856            close(f(&row["hpr_fins_trailing_edge"]), trailing, 1e-12, &what);
1857            let attached = wedge <= wedge_detachment_angle_rad(mach).unwrap();
1858            assert_eq!(attached, mach > 1.2, "{what}");
1859            assert_eq!(row["wedge_shock_attached"], attached, "{what}");
1860            let (faces, faces_low, faces_high) = if attached {
1861                let faces = frontal * wedge_pressure_coefficient(mach, wedge).unwrap();
1862                (faces, faces, faces)
1863            } else {
1864                // Vincenti and Wagoner's front wedge at ξ₀ = 0.763: t/c = 0.04 on the double
1865                // wedge's chord, twice c_d on the fin's own, 16/π fins' planform per reference.
1866                // Their two-dimensional value is an approximate upper bound for a finite wing,
1867                // with nothing below it: the low end takes the faces at zero.
1868                let detached = &wedge_figures["detached_faces"];
1869                let xi = (mach * mach - 1.0) / (2.4 * 0.04_f64).powf(2.0 / 3.0);
1870                assert!(
1871                    (xi - f(&detached["similarity_parameter"])).abs() < 5e-4,
1872                    "{what}"
1873                );
1874                let on = |c: f64| 2.0 * c * 0.04_f64.powf(5.0 / 3.0) / 2.4_f64.cbrt() * 16.0 / PI;
1875                let (c, e) = (
1876                    f(&detached["front_wedge_generalized_drag"]),
1877                    f(&detached["reading_error"]),
1878                );
1879                (on(c), 0.0, on(c + e))
1880            };
1881            close(f(&row["wedge_faces"]), faces, 1e-12, &what);
1882            // Relative, but exact where the low end is zero.
1883            let written_low = f(&row["wedge_faces_low"]);
1884            assert!(
1885                (written_low - faces_low).abs() <= 1e-12 * faces_low.abs(),
1886                "{what}: faces' low end {written_low}, want {faces_low}"
1887            );
1888            close(f(&row["wedge_faces_high"]), faces_high, 1e-12, &what);
1889            let (edge_low, edge_high) = (frontal * f(&base["low"]), frontal * f(&base["high"]));
1890            close(f(&row["wedge_trailing_edge_low"]), edge_low, 1e-12, &what);
1891            close(f(&row["wedge_trailing_edge_high"]), edge_high, 1e-12, &what);
1892            let vacuum = frontal * 2.0 / (1.4 * mach * mach);
1893            close(
1894                f(&row["wedge_trailing_edge_at_vacuum"]),
1895                vacuum,
1896                1e-12,
1897                &what,
1898            );
1899            // The two-dimensional band lies above HPR Sim's own trailing-edge rule and below
1900            // vacuum, on every row.
1901            assert!(trailing < edge_low && edge_high < vacuum, "{what}");
1902            let unedged = drawn - leading - trailing;
1903            let hpr = unedged + faces + 0.5 * (edge_low + edge_high);
1904            let (hpr_low, hpr_high) = (
1905                unedged + faces_low + edge_low,
1906                unedged + faces_high + edge_high,
1907            );
1908            close(f(&row["hpr_cd0"]), hpr, 1e-12, &what);
1909            close(f(&row["hpr_cd0_low"]), hpr_low, 1e-12, &what);
1910            close(f(&row["hpr_cd0_high"]), hpr_high, 1e-12, &what);
1911            let rule = unedged + faces + trailing;
1912            close(
1913                f(&row["hpr_cd0_with_its_trailing_edge_rule"]),
1914                rule,
1915                1e-12,
1916                &what,
1917            );
1918            close(
1919                f(&row["cd0_error_with_its_trailing_edge_rule"]),
1920                rule / cx0 - 1.0,
1921                1e-9,
1922                &what,
1923            );
1924            let got = hpr / cx0 - 1.0;
1925            close(f(&row["cd0_error"]), got, 1e-9, &what);
1926            close(f(&row["cd0_error_low"]), hpr_low / cx0 - 1.0, 1e-9, &what);
1927            close(f(&row["cd0_error_high"]), hpr_high / cx0 - 1.0, 1e-9, &what);
1928            close(
1929                f(&row["cd0_error_as_drawn"]),
1930                drawn / cx0 - 1.0,
1931                1e-9,
1932                &what,
1933            );
1934            assert!((got - drag_error).abs() < 5e-4, "{what}: drag error {got}");
1935            // As drawn, the square leading edge's stagnation pressure puts it far above DREV's.
1936            assert!(drawn > 1.3 * cx0, "{what}");
1937            // Which way. At Mach 1.077 the nominal value is high, above every shot, and so is
1938            // the high end, but with the faces at zero the low end is below every shot: the sign
1939            // there is not settled. Low at 1.293, at both ends, the nominal value inside the
1940            // shots' spread. From 1.832 up, low at both ends, below every shot, and still below DREV's
1941            // with the trailing edges at vacuum.
1942            if mach < 1.1 {
1943                assert!(hpr > high, "{what}: {hpr} not above the shots' {high}");
1944                assert!(
1945                    hpr_low < low,
1946                    "{what}: {hpr_low} not below the shots' {low}"
1947                );
1948            } else if mach < 1.5 {
1949                assert!(hpr_high < cx0 && low < hpr && hpr < high, "{what}");
1950            } else {
1951                assert!(
1952                    hpr_high < low,
1953                    "{what}: {hpr_high} not below the shots' {low}"
1954                );
1955                assert!(unedged + faces_high + vacuum < cx0, "{what}: at vacuum");
1956            }
1957            // The pitch damping about the fits' reference, and its parts.
1958            let hpr_cmq = model.pitch_damping(mach, x_ref * d).unwrap();
1959            close(f(&row["hpr_cmq"]), hpr_cmq, 1e-12, &what);
1960            // The fins' part: the same sum over the fin sets' components alone, and the rest's
1961            // over the others, adding up to the whole.
1962            let (fins, count) = (model.fin_set_start(), model.component_count());
1963            let fins_cmq = model
1964                .pitch_damping_of(mach, x_ref * d, fins..count)
1965                .unwrap();
1966            let rest_cmq = model.pitch_damping_of(mach, x_ref * d, 0..fins).unwrap();
1967            close(fins_cmq + rest_cmq, hpr_cmq, 1e-12, &what);
1968            close(f(&row["hpr_cmq_fins"]), fins_cmq, 1e-12, &what);
1969            close(f(&row["hpr_cmq_body"]), hpr_cmq - fins_cmq, 1e-12, &what);
1970            // Most of it is the fins'.
1971            assert!(
1972                f(&row["hpr_cmq_fins"]) < 2.0 * f(&row["hpr_cmq_body"]),
1973                "{what}"
1974            );
1975            let got = hpr_cmq / cmq - 1.0;
1976            close(f(&row["cmq_error"]), got, 1e-9, &what);
1977            assert!((got - cmq_error).abs() < 5e-4, "{what}: C_mq error {got}");
1978            // Which way: less damping than measured, by more than the fit's probable error, on
1979            // every row but Mach 1.077, where it is more, the side that flatters.
1980            if mach < 1.1 {
1981                assert!(got > cmq_probable_error, "{what}: C_mq {got}");
1982            } else {
1983                assert!(got < -cmq_probable_error, "{what}: C_mq {got}");
1984            }
1985        }
1986    }
1987
1988    /// The pitch-damping read-out refuses a reference station that isn't finite and a component
1989    /// index past the last, and its parts over a split of the components add up to the whole.
1990    #[test]
1991    fn pitch_damping_refuses_what_it_cant_read() {
1992        let model = AeroModel::new(
1993            &committed_design("range-basic-finner.json")
1994                .layout()
1995                .unwrap(),
1996        )
1997        .unwrap();
1998        let x_r = 5.5 * model.reference_diameter_m();
1999        for bad in [f64::NAN, f64::INFINITY] {
2000            assert!(matches!(
2001                model.pitch_damping(2.0, bad),
2002                Err(AeroError::Domain { .. })
2003            ));
2004        }
2005        let count = model.component_count();
2006        assert!(model.pitch_damping_of(2.0, x_r, 0..count + 1).is_err());
2007        let whole = model.pitch_damping(2.0, x_r).unwrap();
2008        let split = model.fin_set_start();
2009        let parts = model.pitch_damping_of(2.0, x_r, 0..split).unwrap()
2010            + model.pitch_damping_of(2.0, x_r, split..count).unwrap();
2011        close(parts, whole, 1e-12, "the parts");
2012        assert!(whole < 0.0, "{whole}");
2013    }
2014
2015    /// M1.8c: hpr's roll forcing against the Arcas Robin's measured roll effectiveness (TN D-4014
2016    /// Fig. 14) and its roll damping against the Basic Finner's (Barrowman 1967 Fig. 5-7), as
2017    /// `cargo xtask aero` writes them: every row recomputed from the committed designs and
2018    /// references, and the ranges the guide quotes.
2019    #[test]
2020    fn roll_against_mach() {
2021        use serde_json::Value;
2022        let fixture: Value = serde_json::from_str(include_str!(
2023            "../../../validation/fixtures/aero/roll-vs-mach.json"
2024        ))
2025        .unwrap();
2026        let tunnel: Value = serde_json::from_str(include_str!(
2027            "../../../validation/fixtures/aero/arcas-robin-wind-tunnel.json"
2028        ))
2029        .unwrap();
2030        let finner: Value = serde_json::from_str(include_str!(
2031            "../../../validation/fixtures/aero/basic-finner-roll-damping.json"
2032        ))
2033        .unwrap();
2034        let f = |v: &Value| v.as_f64().unwrap();
2035        let mut errors: Vec<(f64, f64)> = Vec::new();
2036        for configuration in fixture["arcas_robin"].as_array().unwrap() {
2037            let design = configuration["design"].as_str().unwrap();
2038            let model = AeroModel::new(&committed_design(design).layout().unwrap()).unwrap();
2039            let set = &model.fin_sets()[0];
2040            let measured = tunnel["configurations"]
2041                .as_array()
2042                .unwrap()
2043                .iter()
2044                .find(|c| c["design"] == design)
2045                .unwrap();
2046            for row in configuration["rows"].as_array().unwrap() {
2047                let mach = f(&row["mach"]);
2048                let what = format!("{design} at Mach {mach}");
2049                let fin = set
2050                    .fin
2051                    .roll(mach, set.body_radius_m, model.reference_diameter_m())
2052                    .unwrap();
2053                let hpr =
2054                    f64::from(set.count) * fin.forcing_per_rad * set.roll_forcing_interference * PI
2055                        / 180.0;
2056                close(f(&row["hpr_c_l_delta_per_deg"]), hpr, 1e-12, &what);
2057                let reading = measured["roll_effectiveness"]
2058                    .as_array()
2059                    .unwrap()
2060                    .iter()
2061                    .find(|c| f(&c["mach"]) == mach)
2062                    .unwrap()["alpha_deg_c_l_delta_per_deg"]
2063                    .as_array()
2064                    .unwrap()
2065                    .iter()
2066                    .find(|p| f(&p[0]).abs() < 0.5)
2067                    .map(|p| f(&p[1]))
2068                    .unwrap();
2069                assert_eq!(f(&row["reference_c_l_delta_per_deg"]), reading, "{what}");
2070                close(f(&row["error"]), hpr / reading - 1.0, 1e-12, &what);
2071                errors.push((mach, hpr / reading - 1.0));
2072            }
2073        }
2074        // The guide's summary: from Mach 2.3, all 8 within 5.3%; below, at Mach 1.5 and 1.8, 3
2075        // rows 14.3% to 47.8% high.
2076        assert_eq!(errors.len(), 11);
2077        let high: Vec<f64> = errors.iter().filter(|e| e.0 >= 2.3).map(|e| e.1).collect();
2078        let low: Vec<f64> = errors.iter().filter(|e| e.0 < 2.3).map(|e| e.1).collect();
2079        assert_eq!(high.len(), 8);
2080        assert!(high.iter().all(|e| e.abs() < 0.0535));
2081        let (lo, hi) = low
2082            .iter()
2083            .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &e| {
2084                (a.min(e), b.max(e))
2085            });
2086        assert!(
2087            (lo - 0.143).abs() < 5e-4 && (hi - 0.478).abs() < 5e-4,
2088            "{lo} {hi}"
2089        );
2090
2091        // The Basic Finner: four square fins on a body one diameter across.
2092        let basic = &fixture["basic_finner"];
2093        let d = 1.0;
2094        let fin = FinAero::new(
2095            &FinPlanform::Trapezoidal {
2096                root_chord_m: d,
2097                tip_chord_m: d,
2098                span_m: d,
2099                sweep_m: 0.0,
2100            },
2101            0.25 * PI * d * d,
2102        )
2103        .unwrap();
2104        let k_r = roll_damping_interference(d, 0.5 * d, 1.0).unwrap();
2105        close(f(&basic["roll_damping_interference"]), k_r, 1e-15, "k_R(B)");
2106        for (key, source) in [
2107            ("nol_tunnel", "nol_tunnel_c_lp"),
2108            ("wind_tunnel", "wind_tunnel_c_lp"),
2109            ("barrowman_theory", "barrowman_theory_c_lp"),
2110        ] {
2111            let rows = basic[key].as_array().unwrap();
2112            let readings = finner[source].as_array().unwrap();
2113            assert_eq!(rows.len(), readings.len());
2114            for (row, reading) in rows.iter().zip(readings) {
2115                let mach = f(&row["mach"]);
2116                assert_eq!(mach, f(&reading["mach"]));
2117                assert_eq!(f(&row["reference_c_lp"]), f(&reading["c_lp"]));
2118                let hpr = 4.0 * fin.roll(mach, 0.5 * d, d).unwrap().damping * k_r;
2119                close(f(&row["hpr_c_lp"]), hpr, 1e-12, key);
2120                close(
2121                    f(&row["error"]),
2122                    hpr / f(&reading["c_lp"]) - 1.0,
2123                    1e-12,
2124                    key,
2125                );
2126            }
2127        }
2128        // The guide's summary: 11.7% to 27.5% high against NOL's tunnel (NAVORD 6652 Table 2,
2129        // the scored reference, #763); 5.9% to 16.2% low against Barrowman's Fig. 5-7 points,
2130        // which sit a flat 1.27 times the range data (disputed); 2.0% against Barrowman's own
2131        // computed value.
2132        let range = |key: &str| {
2133            basic[key]
2134                .as_array()
2135                .unwrap()
2136                .iter()
2137                .map(|r| f(&r["error"]))
2138                .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), e| {
2139                    (a.min(e), b.max(e))
2140                })
2141        };
2142        let (lo, hi) = range("nol_tunnel");
2143        assert_eq!(basic["nol_tunnel"].as_array().unwrap().len(), 5);
2144        assert!(
2145            (lo - 0.117).abs() < 5e-4 && (hi - 0.275).abs() < 5e-4,
2146            "{lo} {hi}"
2147        );
2148        // NOL's printed coefficient is on one panel and the 3 d span: 144/π converts it.
2149        for (row, reading) in basic["nol_tunnel"]
2150            .as_array()
2151            .unwrap()
2152            .iter()
2153            .zip(finner["nol_tunnel_c_lp"].as_array().unwrap())
2154        {
2155            let printed = f(&reading["printed_average"]);
2156            close(
2157                f(&row["reference_c_lp"]),
2158                -printed * 144.0 / PI,
2159                5e-6,
2160                "NOL's conversion",
2161            );
2162        }
2163        let (lo, hi) = range("wind_tunnel");
2164        assert!(
2165            (lo + 0.162).abs() < 5e-4 && (hi + 0.059).abs() < 5e-4,
2166            "{lo} {hi}"
2167        );
2168        let theory = f(&basic["barrowman_theory"][0]["error"]);
2169        assert!((theory + 0.020).abs() < 5e-4, "{theory}");
2170    }
2171
2172    /// The whole rocket's roll sums its fin sets, each with its cant, count and body factors: two
2173    /// sets canted each way at Mach 0.5 to 4.5; a positive cant rolls toward `−z_B`; Mach 5 is
2174    /// refused; no cant, no steady roll.
2175    #[test]
2176    fn a_rocket_rolls_by_the_sum_of_its_fin_sets() {
2177        let fins = |count: u32, cant: f64, planform: FinPlanform| {
2178            let mut part = fin_set(count, planform);
2179            if let hpr_design::Part::FinSet(set) = &mut part {
2180                set.cant_rad = cant;
2181            }
2182            part
2183        };
2184        let rocket = |cants: [f64; 2]| {
2185            let mut tube = component("tube", body_part(0.8, 0.03, 0.03), None);
2186            tube.children = vec![
2187                component(
2188                    "fore",
2189                    fins(
2190                        3,
2191                        cants[0],
2192                        FinPlanform::Trapezoidal {
2193                            root_chord_m: 0.05,
2194                            tip_chord_m: 0.02,
2195                            span_m: 0.03,
2196                            sweep_m: 0.02,
2197                        },
2198                    ),
2199                    Some(Position::Top { aft_offset_m: 0.1 }),
2200                ),
2201                component(
2202                    "aft",
2203                    fins(
2204                        4,
2205                        cants[1],
2206                        FinPlanform::Elliptical {
2207                            root_chord_m: 0.08,
2208                            span_m: 0.05,
2209                        },
2210                    ),
2211                    Some(Position::Bottom { aft_offset_m: 0.0 }),
2212                ),
2213            ];
2214            one_stage(
2215                vec![
2216                    component(
2217                        "nose",
2218                        nose(NoseShape::Ogive { radius_ratio: 1.0 }, 0.2, 0.03),
2219                        None,
2220                    ),
2221                    tube,
2222                ],
2223                ReferenceDiameter::Maximum {},
2224            )
2225        };
2226        let (a, b) = (0.02, -0.01);
2227        let model = AeroModel::new(&rocket([a, b]).layout().unwrap()).unwrap();
2228        let d = model.reference_diameter_m();
2229        for mach in [0.5, 0.9, 1.1, 2.0, 4.5] {
2230            let roll = model.roll(mach).unwrap();
2231            let (mut forcing, mut damping) = (0.0, 0.0);
2232            for set in model.fin_sets() {
2233                let fin = set.fin.roll(mach, set.body_radius_m, d).unwrap();
2234                let n = f64::from(set.count);
2235                forcing -= n * fin.forcing_per_rad * set.roll_forcing_interference * set.cant_rad;
2236                damping += n * fin.damping * set.roll_damping_interference;
2237            }
2238            close(roll.forcing, forcing, 1e-13, "forcing");
2239            close(roll.damping, damping, 1e-13, "damping");
2240            assert!(roll.damping < 0.0);
2241        }
2242        let one = AeroModel::new(&rocket([a, 0.0]).layout().unwrap()).unwrap();
2243        assert!(one.roll(0.5).unwrap().forcing < 0.0);
2244        assert!(model.roll(5.0).is_err());
2245        let still = AeroModel::new(&rocket([0.0, 0.0]).layout().unwrap()).unwrap();
2246        // Past 15° of cant, or a NaN, the model refuses.
2247        for cant in [0.3, -0.3, f64::NAN] {
2248            let refused = rocket([cant, 0.0])
2249                .layout()
2250                .map_or(true, |layout| AeroModel::new(&layout).is_err());
2251            assert!(refused, "cant {cant}");
2252        }
2253        assert_eq!(still.steady_roll_rate_rad_s(0.5, 170.0).unwrap(), 0.0);
2254        assert!(model.steady_roll_rate_rad_s(0.5, -1.0).is_err());
2255    }
2256}