1use hpr_design::fins::FinSet;
17
18#[must_use]
42pub fn openrocket_fin_set_roll_kg_m2(
43 fins: &FinSet,
44 body_radius_m: f64,
45 mass_kg: f64,
46) -> Option<f64> {
47 let area_m2 = fins.planform.geometry().ok()?.area_m2;
48 rod_roll_kg_m2(
49 fins.count,
50 area_m2,
51 fins.planform.span_m(),
52 fins.planform.root_chord_m(),
53 body_radius_m,
54 mass_kg,
55 )
56}
57
58fn rod_roll_kg_m2(
61 count: u32,
62 area_m2: f64,
63 span_m: f64,
64 root_m: f64,
65 body_radius_m: f64,
66 mass_kg: f64,
67) -> Option<f64> {
68 let usable = |x: f64| x.is_finite() && x >= 0.0;
69 if count == 0
70 || !(usable(area_m2) && usable(span_m) && usable(body_radius_m) && usable(mass_kg))
71 || !(root_m.is_finite() && root_m > 0.0)
72 {
73 return None;
74 }
75 let reach2 = area_m2 * span_m / root_m;
76 if count == 1 {
77 return Some(mass_kg * reach2 / 12.0);
78 }
79 let r = body_radius_m;
80 Some(mass_kg * (r * r + r * reach2.sqrt() + reach2 / 3.0))
81}
82
83#[cfg(test)]
84mod tests {
85 use hpr_design::tree::{Layout, Part};
86 use hpr_io::ork::{self, StoredReferenceExclusion, StoredSimulation};
87 use serde_json::Value;
88
89 fn record() -> Value {
90 let text = include_str!("../../../validation/fixtures/ork/openrocket-conventions.json");
91 serde_json::from_str(text).expect("the committed record is JSON")
92 }
93
94 fn probe<'a>(record: &'a Value, question: &str) -> &'a Value {
95 let probe = &record["probes"][question];
96 assert!(probe.is_object(), "no probe asks {question:?}");
97 probe
98 }
99
100 fn hpr(probe: &Value) -> (Layout, Vec<String>) {
102 let document = probe["document"].as_str().expect("the probe's document");
103 let read = ork::read(document.as_bytes()).expect("a probe reads");
104 let spine = ork::rocket(&read.value.document);
105 let layout = spine.value.layout().expect("a probe lays out");
106 let warnings = spine.warnings.iter().map(|w| w.message.clone()).collect();
107 (layout, warnings)
108 }
109
110 fn both(probe: &Value) -> ([f64; 4], [f64; 4], Vec<String>) {
115 let (layout, warnings) = hpr(probe);
116 let s = &layout.structure;
117 let i = s.inertia_kg_m2;
118 let ours = [
119 s.mass_kg,
120 -s.cg_m.z,
122 i.z_axis.z,
123 (i.x_axis.x + i.y_axis.y) / 2.0,
124 ];
125 let or = &probe["structure"];
126 let number = |key: &str| or[key].as_f64().expect("a number");
127 let theirs = [
128 number("mass_kg"),
129 number("cm_x_m"),
130 number("ixx"),
131 (number("iyy") + number("izz")) / 2.0,
132 ];
133 (ours, theirs, warnings)
134 }
135
136 fn relative(ours: f64, theirs: f64) -> f64 {
137 (ours - theirs) / theirs
138 }
139
140 fn stored(status: &str, results_xml: Option<&str>) -> StoredSimulation {
141 let xml = format!(
142 r#"<openrocket version="1.10"><rocket><name>R</name></rocket><simulations>
143 <simulation status="{status}"><name>stored</name><simulator>RK4Simulator</simulator><calculator>BarrowmanCalculator</calculator>{results}</simulation>
144 </simulations></openrocket>"#,
145 results = results_xml.unwrap_or_default(),
146 );
147 ork::design(
148 &ork::read(xml.as_bytes())
149 .expect("stored fixture reads")
150 .value,
151 )
152 .value
153 .simulations
154 .into_iter()
155 .next()
156 .expect("stored simulation")
157 }
158
159 fn plausible_results_xml() -> &'static str {
160 r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"/>"#
161 }
162
163 fn stored_with_provenance(
164 simulator: Option<&str>,
165 calculator: Option<&str>,
166 ) -> StoredSimulation {
167 let simulator = simulator.map_or_else(String::new, |value| {
168 format!("<simulator>{value}</simulator>")
169 });
170 let calculator = calculator.map_or_else(String::new, |value| {
171 format!("<calculator>{value}</calculator>")
172 });
173 let xml = format!(
174 r#"<openrocket version="1.10"><rocket><name>R</name></rocket><simulations>
175 <simulation status="uptodate"><name>stored</name>{simulator}{calculator}{results}</simulation>
176 </simulations></openrocket>"#,
177 results = plausible_results_xml(),
178 );
179 ork::design(
180 &ork::read(xml.as_bytes())
181 .expect("stored fixture reads")
182 .value,
183 )
184 .value
185 .simulations
186 .into_iter()
187 .next()
188 .expect("stored simulation")
189 }
190
191 fn stored_with_results(results_xml: &str) -> StoredSimulation {
192 stored("uptodate", Some(results_xml))
193 }
194
195 fn results_with_branches(apogee: &str, branches: &str) -> String {
196 format!(
197 r#"<flightdata maxaltitude="{apogee}" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20">{branches}</flightdata>"#
198 )
199 }
200
201 #[test]
204 fn stale_and_implausible_stored_results_are_excluded_from_gates_and_census() {
205 let cases = [
206 (stored("uptodate", Some(plausible_results_xml())), None),
207 (
208 stored(
209 "uptodate",
210 Some(
211 r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,1</datapoint><datapoint>2,1</datapoint></databranch></flightdata>"#,
212 ),
213 ),
214 Some(StoredReferenceExclusion::InconsistentResults),
215 ),
216 (
217 stored(
218 "uptodate",
219 Some(
220 r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,100</datapoint><datapoint>2,100.05</datapoint></databranch></flightdata>"#,
221 ),
222 ),
223 None,
224 ),
225 (
226 stored(
227 "uptodate",
228 Some(
229 r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,100</datapoint><datapoint>2,100.2</datapoint></databranch></flightdata>"#,
230 ),
231 ),
232 Some(StoredReferenceExclusion::InconsistentResults),
233 ),
234 (
235 stored("outdated", Some(plausible_results_xml())),
236 Some(StoredReferenceExclusion::Outdated),
237 ),
238 (
239 stored("notsimulated", Some(plausible_results_xml())),
240 Some(StoredReferenceExclusion::NotSimulated),
241 ),
242 (
243 stored("uptodate", None),
244 Some(StoredReferenceExclusion::MissingResults),
245 ),
246 (
247 stored(
248 "uptodate",
249 Some(
250 r#"<flightdata maxaltitude="-1" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"/>"#,
251 ),
252 ),
253 Some(StoredReferenceExclusion::ImpossibleSummary),
254 ),
255 (
256 stored(
257 "uptodate",
258 Some(
259 r#"<flightdata maxaltitude="NaN" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"/>"#,
260 ),
261 ),
262 Some(StoredReferenceExclusion::MissingSummary),
263 ),
264 (
265 stored(
266 "uptodate",
267 Some(
268 r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>2,10</datapoint><datapoint>1,20</datapoint></databranch></flightdata>"#,
269 ),
270 ),
271 Some(StoredReferenceExclusion::InconsistentResults),
272 ),
273 (
274 stored(
275 "uptodate",
276 Some(
277 r#"<flightdata maxaltitude="100" maxvelocity="80" maxacceleration="120" maxmach="0.23" timetoapogee="5" flighttime="20"><databranch name="Sustainer" types="Time,Altitude"><datapoint>1,-1</datapoint><datapoint>2,20</datapoint></databranch></flightdata>"#,
278 ),
279 ),
280 Some(StoredReferenceExclusion::ImpossibleSummary),
281 ),
282 ];
283 let classified = cases
284 .iter()
285 .filter(|(simulation, exclusion)| simulation.reference_exclusion() == *exclusion)
286 .count();
287 assert_eq!(classified, cases.len());
288 assert_eq!(
289 cases
290 .iter()
291 .filter(|(_, exclusion)| exclusion.is_none())
292 .count(),
293 2
294 );
295 assert_eq!(
296 StoredReferenceExclusion::Outdated.reason(),
297 "status-outdated"
298 );
299 assert_eq!(
300 StoredReferenceExclusion::MissingResults.reason(),
301 "missing-results"
302 );
303 assert_eq!(
304 stored_with_provenance(None, Some("BarrowmanCalculator")).reference_exclusion(),
305 Some(StoredReferenceExclusion::MissingSimulator)
306 );
307 assert_eq!(
308 stored_with_provenance(Some("OtherSimulator"), Some("BarrowmanCalculator"))
309 .reference_exclusion(),
310 Some(StoredReferenceExclusion::UnsupportedSimulator)
311 );
312 assert_eq!(
313 stored_with_provenance(Some("RK4Simulator"), None).reference_exclusion(),
314 Some(StoredReferenceExclusion::MissingCalculator)
315 );
316 assert_eq!(
317 stored_with_provenance(Some("RK4Simulator"), Some("OtherCalculator"))
318 .reference_exclusion(),
319 Some(StoredReferenceExclusion::UnsupportedCalculator)
320 );
321 }
322
323 #[test]
326 fn stored_apogee_uses_the_first_apogee_branch() {
327 let branches = r#"
328 <databranch name="Sustainer" types="Time,Altitude">
329 <event time="5" type="apogee"/><datapoint>0,0</datapoint><datapoint>5,100</datapoint>
330 </databranch>
331 <databranch name="Booster" types="Time,Altitude">
332 <event time="4" type="apogee"/><datapoint>0,0</datapoint><datapoint>4,99.9</datapoint>
333 </databranch>"#;
334 let simulation = stored_with_results(&results_with_branches("100", branches));
335 assert_eq!(simulation.reference_exclusion(), None);
336 }
337
338 #[test]
341 fn stored_apogee_branch_requires_unambiguous_branch_evidence() {
342 let single = r#"<databranch name="Sustainer" types="Time,Altitude">
343 <datapoint>0,0</datapoint><datapoint>5,100</datapoint>
344 </databranch>"#;
345 assert_eq!(
346 stored_with_results(&results_with_branches("100", single)).reference_exclusion(),
347 None
348 );
349 let multiple = format!(
350 r#"{single}<databranch name="Booster" types="Time,Altitude"><datapoint>0,0</datapoint><datapoint>5,99</datapoint></databranch>"#
351 );
352 assert_eq!(
353 stored_with_results(&results_with_branches("100", &multiple)).reference_exclusion(),
354 Some(StoredReferenceExclusion::UninspectableSeries)
355 );
356 }
357
358 #[test]
361 fn stored_apogee_comparison_uses_the_two_sided_allowance() {
362 let check = |apogee: &str, series: &str| {
363 let branch = format!(
364 r#"<databranch name="Sustainer" types="Time,Altitude"><datapoint>0,0</datapoint><datapoint>5,{series}</datapoint></databranch>"#
365 );
366 stored_with_results(&results_with_branches(apogee, &branch)).reference_exclusion()
367 };
368 assert_eq!(check("100", "100.1"), None);
369 assert_eq!(
370 check("100", "100.1000001"),
371 Some(StoredReferenceExclusion::InconsistentResults)
372 );
373 assert_eq!(check("1", "1.001"), None);
374 assert_eq!(
375 check("1", "1.0010001"),
376 Some(StoredReferenceExclusion::InconsistentResults)
377 );
378 assert_eq!(
379 check("0.5", "0.501"),
380 Some(StoredReferenceExclusion::InconsistentResults)
381 );
382 assert_eq!(check("0.5", "0.5009999"), None);
383 assert_eq!(check("100", "99.9"), None);
384 assert_eq!(
385 check("100", "99.8999999"),
386 Some(StoredReferenceExclusion::InconsistentResults)
387 );
388 }
389
390 #[test]
391 fn stored_times_agree_with_flight_and_apogee_summaries() {
392 let branch = |last_time: &str, apogee_time: &str| {
393 format!(
394 r#"<databranch name="Sustainer" types="Time,Altitude"><event time="{apogee_time}" type="apogee"/><datapoint>0,0</datapoint><datapoint>{last_time},100</datapoint></databranch>"#
395 )
396 };
397 let run = |last_time: &str, apogee_time: &str| {
398 stored_with_results(&results_with_branches(
399 "100",
400 &branch(last_time, apogee_time),
401 ))
402 .reference_exclusion()
403 };
404 assert_eq!(run("20.0009", "5"), None);
405 assert_eq!(run("20", "5.0009"), None);
406 assert_eq!(
407 run("20.0011", "5"),
408 Some(StoredReferenceExclusion::InconsistentResults)
409 );
410 assert_eq!(
411 run("20", "5.0011"),
412 Some(StoredReferenceExclusion::InconsistentResults)
413 );
414 }
415
416 #[test]
417 fn non_finite_event_times_exclude_stored_results() {
418 let mut simulation = stored_with_results(&results_with_branches(
419 "100",
420 r#"<databranch name="Sustainer" types="Time,Altitude"><event time="5" type="launch"/><datapoint>0,0</datapoint><datapoint>5,100</datapoint></databranch>"#,
421 ));
422 simulation.results.as_mut().unwrap().branches[0].events[0].time_s = f64::NAN;
423 assert_eq!(
424 simulation.reference_exclusion(),
425 Some(StoredReferenceExclusion::ImpossibleSummary)
426 );
427 }
428
429 #[test]
430 fn fatal_events_and_events_outside_the_flight_exclude_stored_results() {
431 let with_event = |time: &str, kind: &str| {
432 let branch = format!(
433 r#"<databranch name="Sustainer" types="Time,Altitude"><event time="{time}" type="{kind}"/><datapoint>0,0</datapoint><datapoint>5,100</datapoint></databranch>"#
434 );
435 stored_with_results(&results_with_branches("100", &branch)).reference_exclusion()
436 };
437 assert_eq!(
438 with_event("6", "SIM_ABORT"),
439 Some(StoredReferenceExclusion::FatalEvent)
440 );
441 assert_eq!(
442 with_event("6", "Simulation-Abort"),
443 Some(StoredReferenceExclusion::FatalEvent)
444 );
445 assert_eq!(
446 with_event("-0.1", "launch"),
447 Some(StoredReferenceExclusion::ImpossibleSummary)
448 );
449 assert_eq!(
450 with_event("21", "simulationend"),
451 Some(StoredReferenceExclusion::InconsistentResults)
452 );
453 }
454
455 const PRECEDENCE: [(&str, f64); 12] = [
459 (
460 "a centre of gravity override on a nose with a shoulder",
461 0.0,
462 ),
463 (
464 "a centre of gravity override on a transition with a fore shoulder",
465 0.0,
466 ),
467 ("a mass override on a nose with a shoulder", 0.0),
468 ("a mass override on a tube, not the part inside", 0.0),
469 ("a mass override on the part inside only", 0.0),
470 (
471 "a centre of gravity override on a tube, not the part inside",
472 0.0,
473 ),
474 (
475 "a centre of gravity override on a tube and the part inside",
476 0.0,
477 ),
478 ("a mass override on the stage", 0.0),
479 ("both overrides on the stage", 0.0),
480 ("a stage override over a part's own", 0.0),
481 ("a mass override on a tube and the part inside", -0.003686),
482 (
483 "a mass override on a tube and the part inside, which has its own",
484 -0.019690,
485 ),
486 ];
487
488 const DISAGREEING: [(&str, f64); 2] = [
490 (
491 "both overrides on a tube, the centre covering the part inside and the mass not",
492 0.004672,
493 ),
494 (
495 "both overrides on a tube, the mass covering the part inside and the centre not",
496 0.0,
497 ),
498 ];
499
500 #[test]
519 fn override_precedence_matches_oracle() {
520 let record = record();
521 for (question, apart_m) in PRECEDENCE {
522 let (ours, theirs, warnings) = both(probe(&record, question));
523 assert!(
524 relative(ours[0], theirs[0]).abs() < 1e-5,
525 "{question}: mass {ours:?} {theirs:?}"
526 );
527 assert!(
528 (ours[1] - theirs[1] - apart_m).abs() < 1e-6,
529 "{question}: center {} m apart, not {apart_m}",
530 ours[1] - theirs[1]
531 );
532 assert!(warnings.is_empty(), "{question}: {warnings:?}");
533 }
534 for (question, apart_m) in DISAGREEING {
537 let (ours, theirs, warnings) = both(probe(&record, question));
538 assert!(relative(ours[0], theirs[0]).abs() < 1e-9, "{question}");
539 assert!(
540 (ours[1] - theirs[1] - apart_m).abs() < 1e-6,
541 "{question}: center {} m apart, not {apart_m}",
542 ours[1] - theirs[1]
543 );
544 assert_eq!(warnings.len(), 1, "{question}: {warnings:?}");
545 assert!(
546 warnings[0].contains("the mass flag was taken"),
547 "{warnings:?}"
548 );
549 }
550 }
551
552 const STAGE_ADDS: [&str; 19] = [
559 "a mass override on the stage, not its parts",
560 "a centre of gravity override on the stage, not its parts",
561 "both overrides on the stage, not its parts",
562 "a mass override on the stage with no flag",
563 "both overrides on the stage with no flag",
564 "a center of gravity override on the stage with no flag",
565 "a mass override on the stage, not its parts, over a part's own",
566 "both overrides on the stage, not its parts, over a part's own",
567 "a mass override of nothing on the stage, not its parts",
568 "both overrides on the stage, not its parts, the center ahead of the tip",
569 "both overrides on the stage, only the mass flag written, false",
570 "both overrides on the stage, only the center flag written, false",
571 "the old flag, false, on a stage's mass override, schema 1.4",
572 "the old flag, false, on both of a stage's overrides, schema 1.4",
573 "two stages with no override",
574 "a lower stage's mass override, not its parts",
575 "a lower stage's overrides, not its parts",
576 "an upper stage's mass override, not its parts, above another stage",
577 "two stages' overrides, not their parts",
578 ];
579
580 const STAGE_WHOLE: [&str; 8] = [
586 "a center of gravity override on the stage",
587 "a mass override on the stage",
588 "both overrides on the stage",
589 "a stage override over a part's own",
590 "a mass override on the stage, not its parts, and a center that covers them",
591 "both overrides on the stage, only the center flag written, true",
592 "both overrides on the stage, only the mass flag written, true",
593 "a mass override that covers the stage's parts and a center that doesn't",
594 ];
595
596 const STAGE_WHOLE_BELOW: [(&str, [f64; 2]); 2] = [
601 (
602 "a lower stage's mass override, not its parts, and a center that covers them",
603 [0.0, 0.0495],
604 ),
605 (
606 "a lower stage's mass override that covers its parts and a center that doesn't",
607 [0.0, 0.0333],
608 ),
609 ];
610
611 #[test]
626 fn a_stage_override_covering_its_parts_beside_one_that_does_not() {
627 let record = record();
628 let structure = |question: &str| both(probe(&record, question)).1;
629 assert_eq!(
630 structure("a mass override that covers the stage's parts and a center that doesn't"),
631 structure("both overrides on the stage")
632 );
633 for (one_flag, both_flags) in [
638 (
639 "both overrides on the stage, only the mass flag written, true",
640 "both overrides on the stage",
641 ),
642 (
643 "both overrides on the stage, only the center flag written, true",
644 "a mass override on the stage, not its parts, and a center that covers them",
645 ),
646 (
647 "both overrides on the stage, only the mass flag written, false",
648 "both overrides on the stage, not its parts",
649 ),
650 (
651 "both overrides on the stage, only the center flag written, false",
652 "both overrides on the stage, not its parts",
653 ),
654 ] {
655 assert_eq!(structure(one_flag), structure(both_flags), "{one_flag}");
656 }
657 for question in STAGE_WHOLE {
661 let (layout, warnings) = hpr(probe(&record, question));
662 assert!(warnings.is_empty(), "{question}: {warnings:?}");
663 let (ours, theirs, _) = both(probe(&record, question));
664 assert!(
665 relative(ours[0], theirs[0]).abs() < 5e-7,
666 "{question}: mass {ours:?} {theirs:?}"
667 );
668 assert!(
669 (ours[1] - theirs[1]).abs() < 2e-7,
670 "{question}: center {ours:?} {theirs:?}"
671 );
672 for k in [2, 3] {
673 assert!(
674 relative(ours[k], theirs[k]).abs() < 3e-6,
675 "{question}: inertia {k} {ours:?} {theirs:?}"
676 );
677 }
678 let rescaled = rescaled_pitch(&record, question, &layout);
679 assert!(
680 relative(rescaled, theirs[3]).abs() > 0.10,
681 "{question}: {rescaled} against {}",
682 theirs[3]
683 );
684 }
685 for (question, pinned) in STAGE_WHOLE_BELOW {
686 let (ours, theirs, warnings) = both(probe(&record, question));
687 assert!(warnings.is_empty(), "{question}: {warnings:?}");
688 assert!(
689 relative(ours[0], theirs[0]).abs() < 5e-7,
690 "{question}: mass {ours:?} {theirs:?}"
691 );
692 assert!(
693 (ours[1] - theirs[1]).abs() < 2e-7,
694 "{question}: center {ours:?} {theirs:?}"
695 );
696 let found = [2, 3].map(|k| (relative(ours[k], theirs[k]) * 1e4).round() / 1e4);
697 assert_eq!(found, pinned, "{question}");
698 assert!(
699 relative(ours[2], theirs[2]).abs() < 3e-6,
700 "{question}: roll {ours:?} {theirs:?}"
701 );
702 }
703 }
704
705 fn rescaled_pitch(record: &Value, question: &str, layout: &Layout) -> f64 {
709 let document = probe(record, question)["document"]
710 .as_str()
711 .expect("the probe's document");
712 let read = ork::read(document.as_bytes()).expect("a probe reads");
713 let mut design = ork::rocket(&read.value.document).value;
714 let mut switched = 0;
715 for stage in &mut design.stages {
716 if !stage.override_rule.is_rescaled() {
717 stage.override_rule = hpr_design::StageOverrideRule::Rescaled;
718 switched += 1;
719 }
720 }
721 assert_eq!(switched, 1, "{question}");
722 let rescaled = design.layout().expect("a probe lays out").structure;
723 assert_eq!(rescaled.mass_kg, layout.structure.mass_kg, "{question}");
724 let i = rescaled.inertia_kg_m2;
725 (i.x_axis.x + i.y_axis.y) / 2.0
726 }
727
728 #[test]
744 fn openrockets_lower_stage_sum_is_below_its_parts_in_place() {
745 let record = record();
746 let structure = |question: &str| {
747 let or = &probe(&record, question)["structure"];
748 ["mass_kg", "cm_x_m", "iyy"].map(|key| or[key].as_f64().expect("a number"))
749 };
750 let [added_kg, upper_m, upper_i] = structure("a mass override on the stage, not its parts");
753 let upper_kg = added_kg - 2.0;
754 let [both_kg, both_m, both_i] = structure("two stages with no override");
755 let tube_kg = both_kg - upper_kg;
756 let tube_m = (both_kg * both_m - upper_kg * upper_m) / tube_kg;
757 let tube_i = both_i
758 - upper_i
759 - upper_kg * (upper_m - both_m).powi(2)
760 - tube_kg * (tube_m - both_m).powi(2);
761 assert!((tube_m - 1.05).abs() < 1e-9, "{tube_m}");
762 let center_m = 1.2;
764 for (question, _) in STAGE_WHOLE_BELOW {
765 let [kg, at_m, inertia] = structure(question);
766 let sum = upper_i
767 + upper_kg * (upper_m - at_m).powi(2)
768 + tube_i
769 + tube_kg * (tube_m - at_m).powi(2)
770 + 2.0 * (center_m - at_m).powi(2);
771 assert!(
772 relative(sum, inertia).abs() < 1e-12,
773 "{question}: {sum} {inertia}"
774 );
775 let stage_kg = kg - upper_kg;
777 assert!(
778 ((kg * at_m - upper_kg * upper_m) / stage_kg - center_m).abs() < 1e-9,
779 "{question}"
780 );
781 let rigid = inertia
783 - upper_i
784 - upper_kg * (upper_m - at_m).powi(2)
785 - stage_kg * (center_m - at_m).powi(2);
786 let in_place = tube_i + tube_kg * (tube_m - center_m).powi(2);
789 assert!(
790 rigid < 0.6 * in_place,
791 "{question}: {rigid} against {in_place}"
792 );
793 if (stage_kg - 2.0).abs() < 1e-12 {
794 assert!(tube_kg + 2.0 > stage_kg + 0.3, "{question}: {tube_kg}");
796 } else {
797 assert!(
798 (stage_kg - tube_kg - 2.0).abs() < 1e-12,
799 "{question}: {stage_kg}"
800 );
801 assert!(rigid < 0.6 * tube_i, "{question}: {rigid} against {tube_i}");
802 }
803 }
804 }
805
806 #[test]
814 fn a_stage_override_not_covering_its_parts_adds_to_them() {
815 let record = record();
816 for question in STAGE_ADDS {
817 let (ours, theirs, warnings) = both(probe(&record, question));
818 assert!(warnings.is_empty(), "{question}: {warnings:?}");
819 assert!(
820 relative(ours[0], theirs[0]).abs() < 5e-7,
821 "{question}: mass {ours:?} {theirs:?}"
822 );
823 assert!(
824 (ours[1] - theirs[1]).abs() < 2e-7,
825 "{question}: center {ours:?} {theirs:?}"
826 );
827 for k in [2, 3] {
828 assert!(
829 relative(ours[k], theirs[k]).abs() < 3e-6,
830 "{question}: inertia {ours:?} {theirs:?}"
831 );
832 }
833 }
834 let structure = |question: &str| both(probe(&record, question)).1;
836 let parts = structure("a center of gravity override on the stage with no flag");
837 let added = structure("a mass override on the stage, not its parts");
838 assert!((added[0] - parts[0] - 2.0).abs() < 1e-12, "{added:?}");
839 assert_eq!(added[1..], parts[1..]);
841 let two = structure("two stages with no override");
842 let both_add = structure("two stages' overrides, not their parts");
843 assert!((both_add[0] - two[0] - 3.0).abs() < 1e-12, "{both_add:?}");
844 }
845
846 const STAGE_ADDS_TO_NOTHING: &str =
849 "a mass override on a stage of parts that weigh nothing, not its parts";
850
851 #[test]
856 fn a_stages_added_mass_on_parts_that_weigh_nothing_is_refused() {
857 let record = record();
858 let probe = probe(&record, STAGE_ADDS_TO_NOTHING);
859 let theirs = &probe["structure"];
860 assert_eq!(theirs["mass_kg"], 2.0);
861 assert_eq!(theirs["cm_x_m"], 0.0);
862 let document = probe["document"].as_str().expect("the probe's document");
863 let read = ork::read(document.as_bytes()).expect("a probe reads");
864 let spine = ork::rocket(&read.value.document);
865 assert!(spine.warnings.is_empty(), "{:?}", spine.warnings);
866 let refused = spine.value.layout().expect_err("no center to sit at");
867 let hpr_design::DesignError::InComponent { id, source } = &refused else {
868 panic!("{refused:?}");
869 };
870 assert_eq!(id, &spine.value.stages[0].id);
871 assert!(
872 matches!(
873 **source,
874 hpr_design::DesignError::Domain { what, value }
875 if what == "added mass with no station, on parts that weigh nothing (kg)"
876 && value == 2.0
877 ),
878 "{refused:?}"
879 );
880 }
881
882 fn placement_record() -> Value {
884 let text =
885 include_str!("../../../validation/fixtures/ork/openrocket-added-mass-placement.json");
886 let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
887 assert_eq!(record["openrocket"], "24.12");
888 for (name, bytes) in [
889 (
890 "added_mass_placement.py",
891 include_bytes!("../../../validation/oracles/openrocket/added_mass_placement.py")
892 .as_slice(),
893 ),
894 (
895 "pod_probes.py",
896 include_bytes!("../../../validation/oracles/openrocket/pod_probes.py").as_slice(),
897 ),
898 (
899 "conventions.py",
900 include_bytes!("../../../validation/oracles/openrocket/conventions.py").as_slice(),
901 ),
902 (
903 "events.py",
904 include_bytes!("../../../validation/oracles/openrocket/events.py").as_slice(),
905 ),
906 (
907 "automatic_radius.py",
908 include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
909 .as_slice(),
910 ),
911 ] {
912 assert_eq!(
913 record["inputs_sha256"][name],
914 crate::real_flight::sha256_hex(bytes).as_str(),
915 "{name} changed since the record was written: rerun it"
916 );
917 }
918 record
919 }
920
921 type Body = [f64; 5];
924
925 fn their_body(or: &Value) -> Body {
927 let number = |key: &str| or[key].as_f64().expect("a number");
928 [
929 number("mass_kg"),
930 number("cm_x_m"),
931 number("cm_y_m").hypot(number("cm_z_m")),
932 number("ixx"),
933 (number("iyy") + number("izz")) / 2.0,
934 ]
935 }
936
937 fn our_body(mass: &hpr_design::MassProperties) -> Body {
945 let i = mass.inertia_kg_m2;
946 if mass.cg_m.x.hypot(mass.cg_m.y) < 1e-12 {
947 assert!(
948 (i.x_axis.x - i.y_axis.y).abs() <= 1e-10 * i.x_axis.x.abs(),
949 "a body on the axis, unequal across it: {i:?}"
950 );
951 }
952 [
953 mass.mass_kg,
954 -mass.cg_m.z,
955 mass.cg_m.x.hypot(mass.cg_m.y),
956 i.z_axis.z,
957 i.x_axis.x.min(i.y_axis.y),
958 ]
959 }
960
961 struct Placement {
963 rocket: Body,
964 alone: [Body; 2],
965 }
966
967 fn placement_design(record: &Value, question: &str) -> hpr_design::Rocket {
969 let document = probe(record, question)["document"]
970 .as_str()
971 .expect("the probe's document");
972 let read = ork::read(document.as_bytes()).expect("a probe reads");
973 let spine = ork::rocket(&read.value.document);
974 assert!(
975 spine.warnings.is_empty(),
976 "{question}: {:?}",
977 spine.warnings
978 );
979 spine.value
980 }
981
982 fn our_placement(layout: &Layout) -> Placement {
983 assert_eq!(layout.stages.len(), 2);
984 Placement {
985 rocket: our_body(&layout.structure),
986 alone: [0, 1].map(|k| our_body(&layout.stages[k].mass)),
987 }
988 }
989
990 fn placements(record: &Value, question: &str) -> (Placement, Placement) {
992 let layout = placement_design(record, question)
993 .layout()
994 .unwrap_or_else(|e| panic!("{question}: {e}"));
995 (our_placement(&layout), their_placement(record, question))
996 }
997
998 fn their_placement(record: &Value, question: &str) -> Placement {
999 let probe = probe(record, question);
1000 Placement {
1001 rocket: their_body(&probe["structure"]),
1002 alone: [0, 1].map(|k| their_body(&probe["alone"][k])),
1003 }
1004 }
1005
1006 fn same_mass_and_center(ours: &Body, theirs: &Body, what: &str) {
1009 assert!(
1010 relative(ours[0], theirs[0]).abs() < 5e-7,
1011 "{what}: mass {ours:?} {theirs:?}"
1012 );
1013 for k in [1, 2] {
1014 assert!(
1015 (ours[k] - theirs[k]).abs() < 2e-7,
1016 "{what}: center {ours:?} {theirs:?}"
1017 );
1018 }
1019 }
1020
1021 fn same_inertias(ours: &Body, theirs: &Body, what: &str) {
1023 for k in [3, 4] {
1024 assert!(
1025 relative(ours[k], theirs[k]).abs() < 3e-6,
1026 "{what}: inertia {ours:?} {theirs:?}"
1027 );
1028 }
1029 }
1030
1031 fn adds_the_same_inertias(ours: [&Body; 2], theirs: [&Body; 2], what: &str) {
1047 for k in [3, 4] {
1048 let (ours_adds, theirs_adds) = (ours[0][k] - ours[1][k], theirs[0][k] - theirs[1][k]);
1049 assert!(
1050 (ours_adds - theirs_adds).abs() < (5e-7 * theirs_adds.abs()).max(1e-9),
1051 "{what}: inertia {k} gains {ours_adds:e}, OpenRocket's {theirs_adds:e}"
1052 );
1053 }
1054 }
1055
1056 const BOOSTERS: [(&str, f64); 2] = [("three boosters", 0.0), ("one booster", 0.052)];
1059
1060 const ADDS_TO_THE_BOOSTERS: [&str; 2] = [
1062 "a mass override on the parallel stage, not its parts",
1063 "both overrides on the parallel stage, not its parts",
1064 ];
1065 const ADDS_WITH_NO_FLAG: [(&str, &str); 2] = [
1067 (
1068 "three boosters and a mass override on the parallel stage with no flag",
1069 "three boosters and a mass override on the parallel stage, not its parts",
1070 ),
1071 (
1072 "three boosters and both overrides on the parallel stage with no flag",
1073 "three boosters and both overrides on the parallel stage, not its parts",
1074 ),
1075 ];
1076 const ADDS_BESIDE_A_COVERING_CENTER: (&str, [f64; 2], f64) = (
1081 "a mass override on the parallel stage, not its parts, and a center that covers them",
1082 [-0.006_289, -0.002_172],
1083 0.0,
1084 );
1085 const COVERS_THE_BOOSTERS: [(&str, [f64; 2], f64); 4] = [
1088 (
1089 "a mass override on the parallel stage",
1090 [-0.002_091, -0.000_703],
1091 -0.001_025,
1092 ),
1093 (
1094 "both overrides on the parallel stage",
1095 [-0.007_879, -0.002_676],
1096 -0.001_025,
1097 ),
1098 (
1099 "a mass override that covers the parallel stage's parts and a center that doesn't",
1100 [-0.007_879, -0.002_676],
1101 -0.001_025,
1102 ),
1103 (
1104 "a center of gravity override on the parallel stage",
1105 [-0.046_730, -0.018_921],
1106 0.0,
1107 ),
1108 ];
1109 const A_CENTER_ALONE_NOT_COVERING: &str =
1110 "a center of gravity override on the parallel stage, not its parts";
1111
1112 #[test]
1126 fn a_parallel_stages_override_not_covering_its_parts_adds_to_them() {
1127 let record = placement_record();
1128 for (boosters, off_axis_m) in BOOSTERS {
1129 let none = format!("{boosters} and no override");
1130 let (bare_ours, bare_theirs) = placements(&record, &none);
1131 assert!((bare_theirs.alone[1][2] - off_axis_m).abs() < 1e-12);
1132 same_mass_and_center(&bare_ours.rocket, &bare_theirs.rocket, &none);
1133 same_mass_and_center(&bare_ours.alone[0], &bare_theirs.alone[0], &none);
1134 same_mass_and_center(&bare_ours.alone[1], &bare_theirs.alone[1], &none);
1135 same_inertias(&bare_ours.alone[1], &bare_theirs.alone[1], &none);
1136
1137 for (k, question) in ADDS_TO_THE_BOOSTERS.into_iter().enumerate() {
1138 let question = format!("{boosters} and {question}");
1139 let (ours, theirs) = placements(&record, &question);
1140
1141 let [stage, bare] = [theirs.alone[1], bare_theirs.alone[1]];
1144 assert!((stage[0] - bare[0] - 2.0).abs() < 1e-12, "{question}");
1145 assert!((stage[2] - bare[2]).abs() < 1e-12, "{question}");
1146 if k == 0 {
1147 assert!((stage[1] - bare[1]).abs() < 1e-12, "{question}");
1148 assert_eq!([stage[3], stage[4]], [bare[3], bare[4]], "{question}");
1149 } else {
1150 let want = (bare[0] * bare[1] + 2.0 * 0.55) / (bare[0] + 2.0);
1153 assert!((stage[1] - want).abs() < 1e-12, "{question}: {stage:?}");
1154 assert!(bare[1] - stage[1] > 0.06, "{question}: {stage:?}");
1155 }
1156 assert_eq!(theirs.alone[0], bare_theirs.alone[0], "{question}");
1157
1158 same_mass_and_center(&ours.alone[1], &theirs.alone[1], &question);
1160 same_inertias(&ours.alone[1], &theirs.alone[1], &question);
1161 assert_eq!(ours.alone[0], bare_ours.alone[0], "{question}");
1162 same_mass_and_center(&ours.rocket, &theirs.rocket, &question);
1163 assert!(
1166 theirs.rocket[4] - bare_theirs.rocket[4] > 9e-3,
1167 "{question}"
1168 );
1169 adds_the_same_inertias(
1170 [&ours.rocket, &bare_ours.rocket],
1171 [&theirs.rocket, &bare_theirs.rocket],
1172 &question,
1173 );
1174 if k == 0 {
1178 let adds = |body: &Placement, bare: &Placement| body.rocket[4] - bare.rocket[4];
1179 let (ours_adds, theirs_adds) =
1180 (adds(&ours, &bare_ours), adds(&theirs, &bare_theirs));
1181 let apart = (ours_adds - theirs_adds).abs();
1182 assert!(theirs_adds > 0.018, "{question}: {theirs_adds}");
1183 assert!(apart > 1.3e-9 && apart < 1.6e-9, "{question}: {apart:e}");
1184 assert!(apart < 8e-8 * theirs_adds, "{question}: {apart:e}");
1185 }
1186 }
1187 }
1188 for (unflagged, flagged) in ADDS_WITH_NO_FLAG {
1189 let (ours, theirs) = placements(&record, unflagged);
1190 let (flagged_ours, flagged_theirs) = placements(&record, flagged);
1191 assert_eq!(theirs.rocket, flagged_theirs.rocket, "{unflagged}");
1192 assert_eq!(theirs.alone, flagged_theirs.alone, "{unflagged}");
1193 assert_eq!(ours.rocket, flagged_ours.rocket, "{unflagged}");
1194 assert_eq!(ours.alone, flagged_ours.alone, "{unflagged}");
1195 }
1196 }
1197
1198 fn rescaled_boosters(record: &Value, question: &str) -> f64 {
1201 let mut design = placement_design(record, question);
1202 assert_eq!(
1203 design.stages[1].override_rule,
1204 hpr_design::StageOverrideRule::PartsInPlace,
1205 "{question}"
1206 );
1207 design.stages[1].override_rule = hpr_design::StageOverrideRule::Rescaled;
1208 let layout = design
1209 .layout()
1210 .expect("the probe lays out under either rule");
1211 our_body(&layout.stages[1].mass)[4]
1212 }
1213
1214 #[test]
1239 fn a_parallel_stages_override_covering_its_parts_leaves_them_in_place() {
1240 let record = placement_record();
1241 for (n, (boosters, _)) in BOOSTERS.into_iter().enumerate() {
1242 let none = format!("{boosters} and no override");
1243 let (bare_ours, bare_theirs) = placements(&record, &none);
1244
1245 let alone = format!("{boosters} and {A_CENTER_ALONE_NOT_COVERING}");
1246 let (ours, theirs) = placements(&record, &alone);
1247 assert_eq!(theirs.rocket, bare_theirs.rocket, "{alone}");
1248 assert_eq!(theirs.alone, bare_theirs.alone, "{alone}");
1249 assert_eq!(ours.rocket, bare_ours.rocket, "{alone}");
1250 assert_eq!(ours.alone, bare_ours.alone, "{alone}");
1251
1252 let covering =
1253 std::iter::once(ADDS_BESIDE_A_COVERING_CENTER).chain(COVERS_THE_BOOSTERS);
1254 for (question, across, about_with_one) in covering {
1255 let question = format!("{boosters} and {question}");
1256 let (ours, theirs) = placements(&record, &question);
1257
1258 let [stage, bare] = [theirs.alone[1], bare_theirs.alone[1]];
1260 assert_eq!(stage[3], bare[3], "{question}");
1261 let moved = stage[1] - bare[1];
1262 let in_place = bare[4] + bare[0] * moved * moved;
1263 assert!(
1264 relative(stage[4], in_place).abs() < 1e-12,
1265 "{question}: {stage:?} against {in_place}"
1266 );
1267 assert_eq!(theirs.alone[0], bare_theirs.alone[0], "{question}");
1268
1269 same_mass_and_center(&ours.alone[1], &theirs.alone[1], &question);
1271 same_inertias(&ours.alone[1], &theirs.alone[1], &question);
1272 let rescaled = rescaled_boosters(&record, &question);
1273 assert!(
1274 relative(rescaled, stage[4]).abs() > 0.37,
1275 "{question}: {rescaled} against {stage:?}"
1276 );
1277 assert_eq!(ours.alone[0], bare_ours.alone[0], "{question}");
1278
1279 same_mass_and_center(&ours.rocket, &theirs.rocket, &question);
1281 let roll = (ours.rocket[3] - bare_ours.rocket[3])
1282 - (theirs.rocket[3] - bare_theirs.rocket[3]);
1283 if n == 0 || about_with_one == 0.0 {
1284 assert!(
1285 roll.abs() < 1e-9,
1286 "{question}: roll gains differ by {roll:e}"
1287 );
1288 } else {
1289 let short = roll / theirs.rocket[3];
1290 assert!(
1291 (short - about_with_one).abs() < 5e-6,
1292 "{question}: about the axis {short} against {about_with_one}"
1293 );
1294 }
1295 let short = ((ours.rocket[4] - bare_ours.rocket[4])
1298 - (theirs.rocket[4] - bare_theirs.rocket[4]))
1299 / theirs.rocket[4];
1300 assert!(
1301 (short - across[n]).abs() < 5e-6,
1302 "{question}: across the axis {short} against {}",
1303 across[n]
1304 );
1305 }
1306 }
1307 }
1308
1309 #[test]
1327 fn openrockets_sum_with_a_parallel_stages_covering_center_is_no_bodys() {
1328 let record = placement_record();
1329 let bare = their_placement(&record, "three boosters and no override");
1330 let question = format!("three boosters and {}", ADDS_BESIDE_A_COVERING_CENTER.0);
1331 let theirs = their_placement(&record, &question);
1332 let [core, boosters] = bare.alone;
1333 let (at, center) = (theirs.rocket[1], 0.55);
1334 assert!((theirs.alone[1][1] - center).abs() < 1e-12);
1335 let about = |body: &Body| body[4] + body[0] * (body[1] - at).powi(2);
1336 let sum = about(&core) + about(&boosters) + 2.0 * (center - at).powi(2);
1337 assert!(
1338 relative(sum, theirs.rocket[4]).abs() < 1e-12,
1339 "{sum} against {:?}",
1340 theirs.rocket
1341 );
1342 let body = about(&core) + about(&theirs.alone[1]);
1344 let more = 2.0 * boosters[0] * (boosters[1] - center) * (center - at);
1345 assert!((sum - body - more).abs() < 1e-12, "{sum} {body} {more}");
1346 assert!(
1347 (more / theirs.rocket[4] + ADDS_BESIDE_A_COVERING_CENTER.1[0]).abs() < 5e-6,
1348 "{more} of {:?}",
1349 theirs.rocket
1350 );
1351
1352 for (question, _, about_with_one) in COVERS_THE_BOOSTERS {
1357 if about_with_one == 0.0 {
1358 continue;
1359 }
1360 let bare = their_placement(&record, "one booster and no override");
1361 let theirs = their_placement(&record, &format!("one booster and {question}"));
1362 let ([core, pod], stage, off) = (bare.alone, theirs.alone[1], theirs.rocket[2]);
1363 let about = |body: &Body| body[3] + body[0] * (body[2] - off).powi(2);
1364 let sum = about(&core) + about(&pod) + stage[0] * (stage[2] - off).powi(2);
1365 assert!(
1366 relative(sum, theirs.rocket[3]).abs() < 1e-11,
1367 "{question}: {sum} against {:?}",
1368 theirs.rocket
1369 );
1370 let body = about(&core) + about(&stage);
1371 assert!(
1372 ((body - sum) / theirs.rocket[3] - about_with_one).abs() < 5e-6,
1373 "{question}: {body} {sum}"
1374 );
1375 }
1376
1377 let covering = std::iter::once(ADDS_BESIDE_A_COVERING_CENTER).chain(COVERS_THE_BOOSTERS);
1383 for (k, (question, _, _)) in covering.enumerate() {
1384 let covers_the_mass = matches!(k, 1..=3);
1385 assert_eq!(
1386 covers_the_mass,
1387 !question.contains("not its parts") && question.contains("mass")
1388 || question.starts_with("both"),
1389 "{question}"
1390 );
1391 for (boosters, _) in BOOSTERS {
1392 let bare = their_placement(&record, &format!("{boosters} and no override"));
1393 let theirs = their_placement(&record, &format!("{boosters} and {question}"));
1394 let ([core, pods], stage, at) = (bare.alone, theirs.alone[1], theirs.rocket[1]);
1395 let about = |body: &Body| body[4] + body[0] * (body[1] - at).powi(2);
1396 let point_kg = if covers_the_mass {
1397 assert_eq!(stage[0], 2.0, "{boosters} and {question}");
1398 stage[0]
1399 } else {
1400 stage[0] - pods[0]
1401 };
1402 let sum = about(&core) + about(&pods) + point_kg * (stage[1] - at).powi(2);
1403 assert!(
1404 relative(sum, theirs.rocket[4]).abs() < 1e-11,
1405 "{boosters} and {question}: {sum} against {:?}",
1406 theirs.rocket
1407 );
1408 }
1409 }
1410 }
1411
1412 #[test]
1425 fn an_added_mass_at_a_station_on_the_stage_boosters_hang_on() {
1426 let record = placement_record();
1427 let none = "three boosters and no override";
1428 let (bare_ours, bare_theirs) = placements(&record, none);
1429 for (question, on_boosters) in [
1430 (
1431 "both overrides on the stage they hang on, not its parts",
1432 "no override",
1433 ),
1434 (
1435 "both overrides on each stage, not its parts",
1436 ADDS_TO_THE_BOOSTERS[1],
1437 ),
1438 ] {
1439 let question = format!("three boosters and {question}");
1440 let (ours, theirs) = placements(&record, &question);
1441 let (beside_ours, beside_theirs) =
1442 placements(&record, &format!("three boosters and {on_boosters}"));
1443
1444 let [stage, bare] = [theirs.alone[0], bare_theirs.alone[0]];
1445 let want = (bare[0] * bare[1] + 2.0 * 0.4) / (bare[0] + 2.0);
1446 assert!((stage[0] - bare[0] - 2.0).abs() < 1e-12, "{question}");
1447 assert!((stage[1] - want).abs() < 1e-12, "{question}: {stage:?}");
1448 assert_eq!(theirs.alone[1], beside_theirs.alone[1], "{question}");
1449
1450 same_mass_and_center(&ours.alone[0], &theirs.alone[0], &question);
1451 assert!(stage[4] - bare[4] > 8e-4, "{question}: {stage:?}");
1452 adds_the_same_inertias(
1453 [&ours.alone[0], &bare_ours.alone[0]],
1454 [&theirs.alone[0], &bare_theirs.alone[0]],
1455 &question,
1456 );
1457 assert_eq!(ours.alone[1], beside_ours.alone[1], "{question}");
1458 same_mass_and_center(&ours.alone[1], &theirs.alone[1], &question);
1459 same_inertias(&ours.alone[1], &theirs.alone[1], &question);
1460 same_mass_and_center(&ours.rocket, &theirs.rocket, &question);
1461 adds_the_same_inertias(
1462 [&ours.rocket, &bare_ours.rocket],
1463 [&theirs.rocket, &bare_theirs.rocket],
1464 &question,
1465 );
1466 }
1467
1468 let bare = their_placement(&record, "one booster and no override");
1469 for question in [
1470 "one booster and both overrides on the stage they hang on, not its parts",
1471 "one booster and both overrides on each stage, not its parts",
1472 ] {
1473 let refused = placement_design(&record, question)
1474 .layout()
1475 .expect_err("one booster off the axis");
1476 assert!(
1477 refused.to_string().contains("one pod off the axis"),
1478 "{question}: {refused}"
1479 );
1480 }
1481 let theirs = their_placement(
1482 &record,
1483 "one booster and both overrides on the stage they hang on, not its parts",
1484 );
1485 assert!((theirs.rocket[2] - bare.rocket[2]).abs() < 1e-12);
1486 assert!(
1487 (bare.rocket[2] - 0.002_749).abs() < 1e-6,
1488 "{:?}",
1489 bare.rocket
1490 );
1491 let on_the_axis = bare.rocket[0] * bare.rocket[2] / theirs.rocket[0];
1492 assert!((on_the_axis - 0.000_441).abs() < 1e-6, "{on_the_axis}");
1493 assert_eq!(theirs.alone[0][2], 0.0);
1494 let each = their_placement(
1497 &record,
1498 "one booster and both overrides on each stage, not its parts",
1499 );
1500 let beside = their_placement(
1501 &record,
1502 &format!("one booster and {}", ADDS_TO_THE_BOOSTERS[1]),
1503 );
1504 assert!((each.rocket[2] - beside.rocket[2]).abs() < 1e-12);
1505 assert!(
1506 (beside.rocket[2] - 0.044_105).abs() < 1e-6,
1507 "{:?}",
1508 beside.rocket
1509 );
1510 let on_the_axis = beside.rocket[0] * beside.rocket[2] / each.rocket[0];
1511 assert!((on_the_axis - 0.023_974).abs() < 1e-6, "{on_the_axis}");
1512 assert_eq!(each.alone[0][2], 0.0);
1513 }
1514
1515 const STILL_REFUSED_ON_THE_CORE: [(&str, &str); 6] = [
1518 (
1519 "a mass override on the stage they hang on, not its parts",
1520 "carries an added mass with no station",
1521 ),
1522 (
1523 "a mass override on each stage, not its parts",
1524 "carries an added mass with no station",
1525 ),
1526 (
1527 "a mass override on the stage they hang on, not its parts, and a center that covers them",
1528 "carries an added mass with no station",
1529 ),
1530 (
1531 "a mass override on the stage they hang on",
1532 "under a mass override that covers",
1533 ),
1534 (
1535 "both overrides on the stage they hang on",
1536 "under a mass override that covers",
1537 ),
1538 (
1539 "a center of gravity override on the stage they hang on",
1540 "under a mass override that covers",
1541 ),
1542 ];
1543
1544 #[test]
1561 fn the_stage_boosters_hang_on_is_weighed_with_them_in_openrocket() {
1562 let record = placement_record();
1563 for (boosters, gap_m) in [("three boosters", 0.039), ("one booster", 0.014)] {
1564 for (question, says) in STILL_REFUSED_ON_THE_CORE {
1565 let question = format!("{boosters} and {question}");
1566 let refused = placement_design(&record, &question)
1567 .layout()
1568 .expect_err("refused");
1569 assert!(refused.to_string().contains(says), "{question}: {refused}");
1570 }
1571 let asked =
1572 |question: &str| their_placement(&record, &format!("{boosters} and {question}"));
1573 let bare = asked("no override");
1574 let [added, each, beside, whole, both, center] =
1575 STILL_REFUSED_ON_THE_CORE.map(|(question, _)| asked(question));
1576 assert!((added.rocket[0] - bare.rocket[0] - 2.0).abs() < 1e-12);
1578 for k in [1, 2] {
1579 assert!(
1580 (added.rocket[k] - bare.rocket[k]).abs() < 1e-12,
1581 "{boosters}"
1582 );
1583 assert!(
1584 (added.alone[0][k] - bare.alone[0][k]).abs() < 1e-12,
1585 "{boosters}"
1586 );
1587 }
1588 let moves = added.rocket[1] - added.alone[0][1];
1589 assert!((moves - gap_m).abs() < 5e-4, "{boosters}: {moves}");
1590 assert_eq!(added.alone[1], bare.alone[1]);
1591 let rest = asked(ADDS_TO_THE_BOOSTERS[0]);
1592 assert!((each.rocket[0] - rest.rocket[0] - 2.0).abs() < 1e-12);
1593 for k in [1, 2] {
1594 assert!(
1595 (each.rocket[k] - rest.rocket[k]).abs() < 1e-12,
1596 "{boosters}"
1597 );
1598 }
1599 for covered in [&beside, &both, ¢er] {
1602 assert!((covered.rocket[1] - 0.4).abs() < 1e-12, "{boosters}");
1603 assert!((covered.alone[0][1] - 0.4).abs() < 1e-12, "{boosters}");
1604 assert!(
1605 (covered.rocket[2] - bare.rocket[2]).abs() < 1e-12,
1606 "{boosters}"
1607 );
1608 assert_eq!(covered.alone[1], bare.alone[1]);
1609 }
1610 assert!((beside.rocket[0] - bare.rocket[0] - 2.0).abs() < 1e-12);
1611 assert!((center.rocket[0] - bare.rocket[0]).abs() < 1e-12);
1612 for covered in [&whole, &both] {
1614 assert_eq!(covered.rocket[0], 2.0, "{boosters}");
1615 assert_eq!(covered.alone[0][0], 2.0, "{boosters}");
1616 assert_eq!(covered.alone[1], bare.alone[1]);
1617 }
1618 }
1619 }
1620
1621 const NO_PLACE_TO_SIT: [(&str, usize); 8] = [
1624 (
1625 "a lower stage that weighs nothing, a mass override on it, not its parts",
1626 1,
1627 ),
1628 (
1629 "a lower stage that weighs nothing, a mass override on it, not its parts, and a center that covers them",
1630 1,
1631 ),
1632 (
1633 "an upper stage that weighs nothing, a mass override on it, not its parts",
1634 0,
1635 ),
1636 (
1637 "an upper stage that weighs nothing, a mass override on it, not its parts, and a center that covers them",
1638 0,
1639 ),
1640 (
1641 "two stages that weigh nothing, a mass override on the lower, not its parts",
1642 1,
1643 ),
1644 (
1645 "two stages that weigh nothing, a mass override on the upper, not its parts",
1646 0,
1647 ),
1648 (
1649 "two stages that weigh nothing, a mass override on each, not its parts",
1650 0,
1651 ),
1652 (
1653 "three boosters that weigh nothing and a mass override on the parallel stage, not its parts",
1654 1,
1655 ),
1656 ];
1657
1658 #[test]
1671 fn an_added_mass_on_parts_that_weigh_nothing_sits_at_the_tip_in_openrocket() {
1672 let record = placement_record();
1673 for (question, stage) in NO_PLACE_TO_SIT {
1674 let design = placement_design(&record, question);
1675 let refused = design.layout().expect_err("no center to sit at");
1676 let hpr_design::DesignError::InComponent { id, source } = &refused else {
1677 panic!("{question}: {refused:?}");
1678 };
1679 assert_eq!(id, &design.stages[stage].id, "{question}");
1680 assert!(
1681 matches!(
1682 **source,
1683 hpr_design::DesignError::Domain { what, value }
1684 if what == "added mass with no station, on parts that weigh nothing (kg)"
1685 && value == 2.0
1686 ),
1687 "{question}: {refused:?}"
1688 );
1689 let theirs = their_placement(&record, question).alone[stage];
1690 let covered = question.ends_with("a center that covers them");
1691 let station = match (covered, stage) {
1692 (false, _) => 0.0,
1693 (true, 0) => 0.4,
1694 (true, _) => 1.2,
1695 };
1696 assert!(
1697 (theirs[1] - station).abs() < 1e-12,
1698 "{question}: {theirs:?}"
1699 );
1700 let whole = their_placement(&record, question);
1702 let moment = |body: &Body| body[0] * body[1];
1703 let summed: f64 = whole.alone.iter().map(moment).sum();
1704 assert!(
1705 (moment(&whole.rocket) - summed).abs() < 1e-12,
1706 "{question}: {whole_rocket:?}",
1707 whole_rocket = whole.rocket
1708 );
1709 let weighed: f64 = whole.alone.iter().map(|body| body[0]).sum();
1710 assert!((whole.rocket[0] - weighed).abs() < 1e-12, "{question}");
1711 assert_eq!(
1712 [theirs[0], theirs[2], theirs[3], theirs[4]],
1713 [2.0, 0.0, 0.0, 0.0],
1714 "{question}"
1715 );
1716 }
1717 let none = "a lower stage that weighs nothing, with no override";
1720 let (ours, theirs) = placements(&record, none);
1721 assert_eq!(theirs.alone[1], [0.0; 5]);
1722 assert_eq!(ours.alone[1][0], 0.0);
1723 same_mass_and_center(&ours.rocket, &theirs.rocket, none);
1724 same_inertias(&ours.rocket, &theirs.rocket, none);
1725 let stationed = "a lower stage that weighs nothing, both overrides on it, not its parts";
1726 let (ours, theirs) = placements(&record, stationed);
1727 for alone in [theirs.alone[1], ours.alone[1]] {
1728 assert!((alone[1] - 1.2).abs() < 1e-12, "{alone:?}");
1729 assert_eq!(
1730 [alone[0], alone[2], alone[3], alone[4]],
1731 [2.0, 0.0, 0.0, 0.0]
1732 );
1733 }
1734 same_mass_and_center(&ours.rocket, &theirs.rocket, stationed);
1735 same_inertias(&ours.rocket, &theirs.rocket, stationed);
1736 }
1737
1738 const BOOSTERS_WITH_A_MOTOR: [&str; 3] = [
1741 "three boosters, a motor in the airframe and no override",
1742 "three boosters, a motor in the airframe and a mass override on the parallel stage, not its parts",
1743 "three boosters, a motor in the airframe and both overrides on the parallel stage, not its parts",
1744 ];
1745
1746 #[test]
1755 fn a_motor_aboard_does_not_move_a_parallel_stages_added_mass() {
1756 let record = placement_record();
1757 let weighed = |question: &str, when: &str| {
1758 let body = &probe(&record, question)[when];
1759 ["mass_kg", "cm_x_m"].map(|key| body[key].as_f64().expect("a number"))
1760 };
1761 let none = BOOSTERS_WITH_A_MOTOR[0];
1762 let [bare_kg, bare_m] = weighed(none, "structure");
1763 for when in ["launch", "burnout"] {
1764 let [with_kg, with_m] = weighed(none, when);
1765 let motor_kg = with_kg - bare_kg;
1766 let motor_m = (with_kg * with_m - bare_kg * bare_m) / motor_kg;
1767 assert!(motor_kg > 0.05 && motor_m > bare_m, "{motor_kg} {motor_m}");
1768 for question in &BOOSTERS_WITH_A_MOTOR[1..] {
1769 let [structure_kg, structure_m] = weighed(question, "structure");
1770 let [got_kg, got_m] = weighed(question, when);
1771 assert!(
1772 (got_kg - (structure_kg + motor_kg)).abs() < 1e-12,
1773 "{question} at {when}: {got_kg}"
1774 );
1775 let want_m =
1776 (structure_kg * structure_m + motor_kg * motor_m) / (structure_kg + motor_kg);
1777 assert!(
1778 (got_m - want_m).abs() < 1e-12,
1779 "{question} at {when}: {got_m} against {want_m}"
1780 );
1781 }
1782 assert!(with_m - bare_m > 0.06, "{when}: {with_m} {bare_m}");
1785 }
1786 let (bare_ours, bare_theirs) = placements(&record, none);
1787 for question in BOOSTERS_WITH_A_MOTOR {
1788 let (ours, theirs) = placements(&record, question);
1789 same_mass_and_center(&ours.rocket, &theirs.rocket, question);
1790 same_mass_and_center(&ours.alone[1], &theirs.alone[1], question);
1791 same_inertias(&ours.alone[1], &theirs.alone[1], question);
1792 adds_the_same_inertias(
1793 [&ours.rocket, &bare_ours.rocket],
1794 [&theirs.rocket, &bare_theirs.rocket],
1795 question,
1796 );
1797 }
1798 }
1799
1800 #[test]
1802 fn every_placement_probe_is_checked() {
1803 let record = placement_record();
1804 let mut read: Vec<String> = Vec::new();
1805 for (boosters, _) in BOOSTERS {
1806 read.push(format!("{boosters} and no override"));
1807 let on_the_boosters = ADDS_TO_THE_BOOSTERS
1808 .into_iter()
1809 .chain([ADDS_BESIDE_A_COVERING_CENTER.0, A_CENTER_ALONE_NOT_COVERING])
1810 .chain(COVERS_THE_BOOSTERS.map(|(question, ..)| question));
1811 let on_the_core = [
1812 "both overrides on the stage they hang on, not its parts",
1813 "both overrides on each stage, not its parts",
1814 ]
1815 .into_iter()
1816 .chain(STILL_REFUSED_ON_THE_CORE.map(|(question, _)| question));
1817 read.extend(
1818 on_the_boosters
1819 .chain(on_the_core)
1820 .map(|question| format!("{boosters} and {question}")),
1821 );
1822 }
1823 read.extend(ADDS_WITH_NO_FLAG.map(|(unflagged, _)| unflagged.to_owned()));
1824 read.extend(NO_PLACE_TO_SIT.map(|(question, _)| question.to_owned()));
1825 read.extend(
1826 [
1827 "a lower stage that weighs nothing, with no override",
1828 "a lower stage that weighs nothing, both overrides on it, not its parts",
1829 ]
1830 .map(str::to_owned),
1831 );
1832 read.extend(BOOSTERS_WITH_A_MOTOR.map(str::to_owned));
1833 read.sort_unstable();
1834 let mut recorded: Vec<&str> = record["probes"]
1835 .as_object()
1836 .expect("the record's probes")
1837 .keys()
1838 .map(String::as_str)
1839 .collect();
1840 recorded.sort_unstable();
1841 assert_eq!(read, recorded);
1842 let laid_out = recorded
1846 .iter()
1847 .filter(|question| placement_design(&record, question).layout().is_ok())
1848 .count();
1849 assert_eq!((recorded.len(), laid_out), (49, 27));
1850 let with_boosters = recorded
1852 .iter()
1853 .map(|question| placement_design(&record, question))
1854 .filter(|design| design.stages.iter().any(|stage| stage.parallel.is_some()))
1855 .filter(|design| design.layout().is_ok())
1856 .count();
1857 assert_eq!(with_boosters, 25);
1858 assert_eq!(
1859 2 * STILL_REFUSED_ON_THE_CORE.len() + 2 + NO_PLACE_TO_SIT.len(),
1860 22
1861 );
1862 }
1863
1864 fn added_mass_record() -> Value {
1866 let text =
1867 include_str!("../../../validation/fixtures/ork/openrocket-stage-added-mass.json");
1868 let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
1869 assert_eq!(record["openrocket"], "24.12");
1870 for (name, bytes) in [
1871 (
1872 "stage_added_mass.py",
1873 include_bytes!("../../../validation/oracles/openrocket/stage_added_mass.py")
1874 .as_slice(),
1875 ),
1876 (
1877 "pod_probes.py",
1878 include_bytes!("../../../validation/oracles/openrocket/pod_probes.py").as_slice(),
1879 ),
1880 (
1881 "conventions.py",
1882 include_bytes!("../../../validation/oracles/openrocket/conventions.py").as_slice(),
1883 ),
1884 (
1885 "events.py",
1886 include_bytes!("../../../validation/oracles/openrocket/events.py").as_slice(),
1887 ),
1888 (
1889 "automatic_radius.py",
1890 include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
1891 .as_slice(),
1892 ),
1893 ] {
1894 assert_eq!(
1895 record["inputs_sha256"][name],
1896 crate::real_flight::sha256_hex(bytes).as_str(),
1897 "{name} changed since the record was written: rerun it"
1898 );
1899 }
1900 record
1901 }
1902
1903 const ADDED_WITH_PODS: [(&str, &[&str]); 2] = [
1906 (
1907 "three pods and no override",
1908 &["three pods and a mass override on the stage, not its parts"],
1909 ),
1910 (
1911 "one pod and no override",
1912 &[
1913 "one pod and a mass override on the stage, not its parts",
1914 "one pod and both overrides on the stage, not its parts",
1915 "one pod and a mass override on the stage, not its parts, and a center that covers them",
1916 ],
1917 ),
1918 ];
1919
1920 #[test]
1930 fn a_stages_added_mass_sits_among_its_pods_and_level_with_their_center() {
1931 let record = added_mass_record();
1932 let theirs = |question: &str, key: &str| {
1933 probe(&record, question)["structure"][key]
1934 .as_f64()
1935 .expect("a number")
1936 };
1937 let off_axis_m =
1938 |question: &str| theirs(question, "cm_y_m").hypot(theirs(question, "cm_z_m"));
1939 let [three, three_added] = [
1942 "three pods and no override",
1943 "three pods and a mass override on the stage, not its parts",
1944 ];
1945 assert!(theirs(three, "cm_x_m") - theirs("no override", "cm_x_m") > 0.03);
1946 assert!((theirs(three_added, "cm_x_m") - theirs(three, "cm_x_m")).abs() < 1e-12);
1947 assert!((theirs(three_added, "mass_kg") - theirs(three, "mass_kg") - 2.0).abs() < 1e-12);
1948 let (one, one_added) = ADDED_WITH_PODS[1];
1951 assert!(off_axis_m(one) > 0.0025, "{}", off_axis_m(one));
1952 for question in one_added {
1953 assert!(
1954 (off_axis_m(question) - off_axis_m(one)).abs() < 1e-12,
1955 "{question}: {}",
1956 off_axis_m(question)
1957 );
1958 }
1959
1960 let mut read: Vec<&str> = std::iter::once("no override")
1962 .chain(ADDED_WITH_A_MOTOR)
1963 .collect();
1964 for (bare, added) in ADDED_WITH_PODS {
1965 read.push(bare);
1966 read.extend(added);
1967 }
1968 read.sort_unstable();
1969 let mut recorded: Vec<&str> = record["probes"]
1970 .as_object()
1971 .expect("the record's probes")
1972 .keys()
1973 .map(String::as_str)
1974 .collect();
1975 recorded.sort_unstable();
1976 assert_eq!(read, recorded);
1977
1978 let gained = (theirs(one_added[1], "iyy") + theirs(one_added[1], "izz")) / 2.0
1981 - (theirs(one, "iyy") + theirs(one, "izz")) / 2.0;
1982 assert!(gained > 2.9e-4, "{gained:e}");
1983 for (bare, added) in ADDED_WITH_PODS {
1984 let (bare_ours, bare_theirs, _) = both(probe(&record, bare));
1985 for question in std::iter::once(bare).chain(added.iter().copied()) {
1986 let (layout, warnings) = hpr(probe(&record, question));
1987 let (ours, theirs_, _) = both(probe(&record, question));
1988 assert!(warnings.is_empty(), "{question}: {warnings:?}");
1989 assert!(
1990 relative(ours[0], theirs_[0]).abs() < 5e-7,
1991 "{question}: mass {ours:?} {theirs_:?}"
1992 );
1993 assert!(
1994 (ours[1] - theirs_[1]).abs() < 2e-7,
1995 "{question}: center {ours:?} {theirs_:?}"
1996 );
1997 let center = layout.structure.cg_m;
1998 assert!(
1999 (center.x.hypot(center.y) - off_axis_m(question)).abs() < 2e-7,
2000 "{question}: {center:?} against {}",
2001 off_axis_m(question)
2002 );
2003 if question.ends_with("a center that covers them") {
2008 let adds = theirs_[3] - bare_theirs[3];
2009 assert!((adds - 3.490e-4).abs() < 1e-7, "{question}: {adds:e}");
2010 }
2011 for k in [2, 3] {
2012 let (ours_adds, theirs_adds) =
2013 (ours[k] - bare_ours[k], theirs_[k] - bare_theirs[k]);
2014 assert!(
2015 (ours_adds - theirs_adds).abs() < 1e-9,
2016 "{question}: inertia {k} gains {ours_adds:e}, OpenRocket's {theirs_adds:e}"
2017 );
2018 }
2019 }
2020 }
2021 }
2022
2023 const ADDED_WITH_A_MOTOR: [&str; 3] = [
2025 "a mass override on the stage, not its parts",
2026 "both overrides on the stage, not its parts",
2027 "a mass override on the stage, not its parts, and a center that covers them",
2028 ];
2029
2030 #[test]
2039 fn a_motor_aboard_does_not_move_a_stages_added_mass() {
2040 let record = added_mass_record();
2041 let weighed = |question: &str, when: &str| {
2042 let body = &probe(&record, question)[when];
2043 ["mass_kg", "cm_x_m"].map(|key| body[key].as_f64().expect("a number"))
2044 };
2045 let [bare_kg, bare_m] = weighed("no override", "structure");
2046 for when in ["launch", "burnout"] {
2047 let [with_kg, with_m] = weighed("no override", when);
2048 let motor_kg = with_kg - bare_kg;
2049 let motor_m = (with_kg * with_m - bare_kg * bare_m) / motor_kg;
2050 assert!(motor_kg > 0.05 && motor_m > bare_m, "{motor_kg} {motor_m}");
2051 for question in ADDED_WITH_A_MOTOR {
2052 let [structure_kg, structure_m] = weighed(question, "structure");
2053 let [got_kg, got_m] = weighed(question, when);
2054 assert!(
2055 (got_kg - (structure_kg + motor_kg)).abs() < 1e-12,
2056 "{question} at {when}: {got_kg}"
2057 );
2058 let want_m =
2059 (structure_kg * structure_m + motor_kg * motor_m) / (structure_kg + motor_kg);
2060 assert!(
2061 (got_m - want_m).abs() < 1e-12,
2062 "{question} at {when}: {got_m} against {want_m}"
2063 );
2064 }
2065 let [_, got_m] = weighed(ADDED_WITH_A_MOTOR[0], when);
2068 assert!(with_m - got_m > 0.05, "{when}: {with_m} {got_m}");
2069 }
2070 let (bare_ours, bare_theirs, _) = both(probe(&record, "no override"));
2072 for question in std::iter::once("no override").chain(ADDED_WITH_A_MOTOR) {
2073 let (ours, theirs, warnings) = both(probe(&record, question));
2074 assert!(warnings.is_empty(), "{question}: {warnings:?}");
2075 assert!(
2076 relative(ours[0], theirs[0]).abs() < 5e-7,
2077 "{question}: mass {ours:?} {theirs:?}"
2078 );
2079 assert!(
2080 (ours[1] - theirs[1]).abs() < 2e-7,
2081 "{question}: center {ours:?} {theirs:?}"
2082 );
2083 if question == ADDED_WITH_A_MOTOR[2] {
2088 let adds = theirs[3] - bare_theirs[3];
2089 assert!((adds - 7.006e-4).abs() < 1e-7, "{question}: {adds:e}");
2090 }
2091 for k in [2, 3] {
2092 let (ours_adds, theirs_adds) = (ours[k] - bare_ours[k], theirs[k] - bare_theirs[k]);
2093 assert!(
2094 (ours_adds - theirs_adds).abs() < 1e-9,
2095 "{question}: inertia {k} gains {ours_adds:e}, OpenRocket's {theirs_adds:e}"
2096 );
2097 }
2098 }
2099 let gained = both(probe(&record, ADDED_WITH_A_MOTOR[1])).1[3] - bare_theirs[3];
2100 assert!(gained > 5.9e-4, "{gained:e}");
2101 let [added_kg, _] = weighed(ADDED_WITH_A_MOTOR[0], "structure");
2102 assert!((added_kg - bare_kg - 2.0).abs() < 1e-12, "{added_kg}");
2103 }
2104
2105 #[test]
2114 fn openrockets_inertia_with_a_motor_aboard_is_the_same_sum() {
2115 let record = added_mass_record();
2116 let body = |question: &str, when: &str| {
2117 let body = &probe(&record, question)[when];
2118 ["mass_kg", "cm_x_m", "iyy"].map(|key| body[key].as_f64().expect("a number"))
2119 };
2120 let [parts_kg, parts_m, parts_i] = body("no override", "structure");
2121 let at_m = [parts_m, 0.4, 0.4];
2124 for when in ["launch", "burnout"] {
2125 let [with_kg, with_m, with_i] = body("no override", when);
2126 let motor_kg = with_kg - parts_kg;
2127 let motor_m = (with_kg * with_m - parts_kg * parts_m) / motor_kg;
2128 let motor_i = with_i
2129 - parts_i
2130 - parts_kg * (parts_m - with_m).powi(2)
2131 - motor_kg * (motor_m - with_m).powi(2);
2132 for (question, point_m) in ADDED_WITH_A_MOTOR.into_iter().zip(at_m) {
2133 let [_, x_m, inertia] = body(question, when);
2134 let sum = parts_i
2135 + parts_kg * (parts_m - x_m).powi(2)
2136 + 2.0 * (point_m - x_m).powi(2)
2137 + motor_i
2138 + motor_kg * (motor_m - x_m).powi(2);
2139 assert!(
2140 relative(sum, inertia).abs() < 1e-12,
2141 "{question} at {when}: {sum} {inertia}"
2142 );
2143 }
2144 let question = ADDED_WITH_A_MOTOR[2];
2146 let [stage_kg, stage_m, stage_i] = body(question, "structure");
2147 let [_, x_m, inertia] = body(question, when);
2148 let rigid = stage_i
2149 + stage_kg * (stage_m - x_m).powi(2)
2150 + motor_i
2151 + motor_kg * (motor_m - x_m).powi(2);
2152 let apart = (relative(rigid, inertia) * 1e3).round() / 1e3;
2153 assert_eq!(
2154 apart,
2155 if when == "launch" { -0.016 } else { -0.011 },
2156 "{when}"
2157 );
2158 }
2159 }
2160
2161 const OLD_FLAG: [(&str, f64); 11] = [
2164 (
2165 "the old flag on both of a stage's overrides, schema 1.4",
2166 0.0,
2167 ),
2168 (
2169 "the old flag on a tube's mass override, schema 1.4",
2170 -0.003686,
2171 ),
2172 (
2173 "the old flag on a tube's mass override, schema 1.8",
2174 -0.003686,
2175 ),
2176 (
2177 "the old flag, false, on a tube's mass override, schema 1.8",
2178 0.0,
2179 ),
2180 (
2181 "the old flag on a tube's mass override, schema 1.10",
2182 -0.003686,
2183 ),
2184 ("the old flag after a mass flag that says false", -0.003686),
2185 ("the old flag before a mass flag that says false", 0.0),
2186 ("the old flag before a drag flag that says false", -0.003686),
2187 ("the old flag after a drag flag that says false", -0.003686),
2188 (
2189 "the old flag, false, after a centre flag that says true",
2190 0.0,
2191 ),
2192 (
2193 "the old flag, false, before a centre flag that says true",
2194 0.0,
2195 ),
2196 ];
2197
2198 fn with_id<'a>(element: &'a ork::Element, id: &str) -> Option<&'a ork::Element> {
2200 if element
2201 .child("id")
2202 .is_some_and(|own| own.text().trim() == id)
2203 {
2204 return Some(element);
2205 }
2206 element.elements().find_map(|child| with_id(child, id))
2207 }
2208
2209 #[test]
2216 fn the_old_subcomponent_flag_reads_as_openrocket_reads_it() {
2217 let record = record();
2218 for (question, apart_m) in OLD_FLAG {
2219 let probe = probe(&record, question);
2220 let (ours, theirs, warnings) = both(probe);
2221 assert!(
2222 relative(ours[0], theirs[0]).abs() < 1e-9,
2223 "{question}: mass {ours:?} {theirs:?}"
2224 );
2225 assert!(
2226 (ours[1] - theirs[1] - apart_m).abs() < 1e-6,
2227 "{question}: center {} m apart, not {apart_m}",
2228 ours[1] - theirs[1]
2229 );
2230 assert!(warnings.is_empty(), "{question}: {warnings:?}");
2231
2232 let document = probe["document"].as_str().expect("the probe's document");
2233 let parsed = ork::read(document.as_bytes()).expect("a probe reads");
2234 let flags = probe["override_flags"].as_object().expect("the flags");
2235 assert!(flags.len() >= 3, "{question}: {flags:?}");
2236 for (id, recorded) in flags {
2237 let element = with_id(&parsed.value.document.root, id).expect("the part");
2238 let mut part_warnings = Vec::new();
2239 let overrides = ork::Values::new(element, "probe", &mut part_warnings).overrides();
2240 let flags_ours = [
2241 overrides.subcomponents_mass,
2242 overrides.subcomponents_cg,
2243 overrides.subcomponents_cd,
2244 ]
2245 .map(Option::unwrap_or_default);
2246 let flags_theirs =
2247 ["mass", "cg", "cd"].map(|k| recorded[k].as_bool().expect("a flag"));
2248 assert_eq!(flags_ours, flags_theirs, "{question}: {id}");
2249 assert!(part_warnings.is_empty(), "{question}: {part_warnings:?}");
2250 }
2251 }
2252 }
2253
2254 const INERTIA: [(&str, [f64; 2]); 8] = [
2256 ("a mass override on a nose with a shoulder", [0.0, 0.0]),
2257 ("a mass override on a tube, not the part inside", [0.0, 0.0]),
2258 ("a mass override on the part inside only", [0.0, 0.0]),
2259 (
2260 "a mass override on a tube and the part inside",
2261 [-0.0693, -0.0667],
2262 ),
2263 (
2264 "a mass override on a tube and the part inside, which has its own",
2265 [-0.3713, -0.3724],
2266 ),
2267 (
2268 "a centre of gravity override on a tube and the part inside",
2269 [0.0, -0.0265],
2270 ),
2271 (
2272 "both overrides on a tube, the centre covering the part inside and the mass not",
2273 [0.0, -0.0010],
2274 ),
2275 (
2276 "both overrides on a tube, the mass covering the part inside and the centre not",
2277 [-0.0693, -0.0818],
2278 ),
2279 ];
2280
2281 #[test]
2290 fn inertia_under_an_override_departs_as_written() {
2291 let record = record();
2292 for (question, pinned) in INERTIA {
2293 let (ours, theirs, _) = both(probe(&record, question));
2294 let found = [2, 3].map(|k| (relative(ours[k], theirs[k]) * 1e4).round() / 1e4);
2295 assert_eq!(found, pinned, "{question}");
2296 }
2297 }
2298
2299 const READINGS: [&str; 18] = [
2301 "a nose with no shoulder",
2302 "a nose with a walled shoulder",
2303 "a nose whose shoulder has no wall",
2304 "a nose whose shoulder has no wall, capped",
2305 "a filled nose whose shoulder has no wall",
2306 "a filled nose with a walled shoulder",
2307 "a transition whose shoulders have no wall",
2308 "a nose of no wall",
2309 "a transition of no wall",
2310 "a tube of no wall",
2311 "a tube holding an inner tube, a coupler and a lug of no wall",
2312 "a mass override on a nose of no wall",
2313 "a nose, a shoulder and a tube that write no thickness at all",
2314 "a narrower nose and tube that write no thickness at all",
2315 "a transition that writes no thickness at all",
2316 "a nose and a tube that name no material, with one part of each kind inside",
2317 "a transition, and more kinds inside a tube, that name no material",
2318 "a tube holding an inner tube, a coupler and a lug that write no thickness",
2320 ];
2321
2322 const PART_GAPS: [(&str, f64, f64); 1] = [("EllipticalFinSet", 0.001830, 0.0)];
2330
2331 #[test]
2347 fn walls_shoulders_and_unnamed_materials_read_as_openrocket_does() {
2348 let record = record();
2349 for question in READINGS {
2350 let probe = probe(&record, question);
2351 let unwritten = question.ends_with("that write no thickness");
2352 let (ours, theirs, warnings) = both(probe);
2353 if unwritten {
2354 assert_eq!(warnings.len(), 3, "{question}: {warnings:?}");
2355 } else {
2356 assert!(warnings.is_empty(), "{question}: {warnings:?}");
2357 }
2358 if theirs[0] == 0.0 {
2359 assert_eq!(ours[0], 0.0, "{question}");
2361 assert!(ours[1].is_finite(), "{question}");
2362 continue;
2363 }
2364 let (layout, _) = hpr(probe);
2365 let mut gap_kg = 0.0;
2367 let mut gap_moment = 0.0;
2368 let mut plain = true;
2369 for part in probe["parts"].as_array().expect("parts") {
2370 let class = part["class"].as_str().expect("a class");
2371 if matches!(class, "Rocket" | "AxialStage") {
2372 continue; }
2374 let id = part["id"].as_str().expect("an id");
2375 let (_, placed) = layout
2376 .find(id)
2377 .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
2378 let mass = part["mass_kg"].as_f64().expect("a mass");
2379 let station = part["cm_x_m"].as_f64().expect("a station");
2380 plain &= !matches!(
2381 class,
2382 "TrapezoidFinSet"
2383 | "EllipticalFinSet"
2384 | "FreeformFinSet"
2385 | "RailButton"
2386 | "Parachute"
2387 | "Streamer"
2388 | "ShockCord"
2389 );
2390 let (mass_gap, station_gap) =
2391 if unwritten && matches!(class, "InnerTube" | "LaunchLug") {
2392 (-1.0, 0.0)
2394 } else {
2395 PART_GAPS
2396 .iter()
2397 .find(|(kind, _, _)| *kind == class)
2398 .map_or((0.0, 0.0), |(_, m, z)| (*m, *z))
2399 };
2400 if mass == 0.0 {
2401 assert_eq!(placed.own.mass_kg, 0.0, "{question}: {id}");
2402 continue;
2403 }
2404 let found = relative(placed.own.mass_kg, mass);
2405 assert!(
2406 (found - mass_gap).abs() < 1e-5,
2407 "{question}: {id} is {found} from OpenRocket's mass, not {mass_gap}"
2408 );
2409 if placed.own.mass_kg > 0.0 {
2410 let apart_m = -placed.own.cg_m.z - station;
2411 assert!(
2412 (apart_m - station_gap).abs() < 1e-6,
2413 "{question}: {id} is {apart_m} m from OpenRocket's station"
2414 );
2415 }
2416 gap_kg += placed.own.mass_kg - mass;
2417 gap_moment += placed.own.mass_kg * (-placed.own.cg_m.z) - mass * station;
2418 }
2419 assert!(
2420 (ours[0] - theirs[0] - gap_kg).abs() < 1e-5 * theirs[0],
2421 "{question}: mass {ours:?} {theirs:?}"
2422 );
2423 let expected_m = (theirs[0] * theirs[1] + gap_moment) / (theirs[0] + gap_kg);
2424 assert!(
2425 (ours[1] - expected_m).abs() < 1e-6,
2426 "{question}: center {ours:?} {theirs:?}"
2427 );
2428 if plain && !unwritten {
2429 for k in [2, 3] {
2430 let (a, b) = (ours[k], theirs[k]);
2431 assert!(
2432 (a - b).abs() <= 1e-5 * b.abs().max(1e-12),
2433 "{question}: inertia {ours:?} {theirs:?}"
2434 );
2435 }
2436 }
2437 }
2438 }
2439
2440 const ALONE: [(&str, [f64; 4]); 50] = [
2481 ("a tube and a bulkhead", [0.0, 0.0, 0.0, 0.0]),
2482 (
2483 "a tube and a canted fin set",
2484 [-4.19e-5, -4.54e-6, -2.66e-5, 7.58e-5],
2485 ),
2486 ("a tube and a centering ring", [0.0, 0.0, 0.0, 0.0]),
2487 (
2488 "a tube and a fin set of airfoil section",
2489 [-0.0165, 0.000935, 0.0, -0.00488],
2490 ),
2491 (
2492 "a tube and a fin set of rounded section",
2493 [0.00014, -1.24e-5, 0.0, 7.37e-5],
2494 ),
2495 (
2496 "a tube and a fin set of square section",
2497 [0.0, 0.0, 0.0, 4.57e-5],
2498 ),
2499 ("a tube and a fin set with a tab", [0.0, 0.0, 0.0, -0.00109]),
2500 (
2501 "a tube and a fin set with fillets",
2502 [0.0, 0.0, 0.0, -0.00035],
2503 ),
2504 (
2505 "a tube and a fin set with wider fillets",
2506 [0.0, 0.0, 0.0, -0.00129],
2507 ),
2508 (
2509 "a tube and a fin set with fillets of 30 mm",
2510 [0.0, 0.0, 0.0, -0.00638],
2511 ),
2512 (
2513 "a tube and a fin set with fillets of their own material",
2514 [0.0, 0.0, 0.0, -0.000749],
2515 ),
2516 (
2517 "a tube and a fin set with fillets that name no material",
2518 [0.0, 0.0, 0.0, -0.000223],
2519 ),
2520 (
2521 "a tube and a single fin with fillets",
2522 [0.0, 0.0, 7.78e-6, 0.00425],
2523 ),
2524 (
2525 "a tube and four fins of rounded section with fillets",
2526 [0.000179, -1.52e-5, 0.0, -0.000428],
2527 ),
2528 (
2529 "a tube and a freeform fin set with fillets",
2530 [0.0, 0.0, 0.0, -7.74e-5],
2531 ),
2532 (
2533 "a wider tube and a fin set with fillets",
2534 [0.0, 0.0, 0.0, -0.00123],
2535 ),
2536 ("a tube and a freeform fin set", [0.0, 0.0, 0.0, 4.57e-5]),
2537 ("a tube and a launch lug", [0.0, 0.0, 0.0, 0.000313]),
2538 ("a tube and a mass component", [0.0, 0.0, 0.0, 0.0]),
2539 ("a tube and a parachute", [0.0, 0.0, 0.0, 0.0]),
2540 (
2541 "a tube and a parachute that writes no packed size",
2542 [0.0, 0.0, 0.0, 0.0],
2543 ),
2544 (
2545 "a tube and a parachute that writes only a packed length",
2546 [0.0, 0.0, 0.0, 0.0],
2547 ),
2548 (
2549 "a tube and a parachute that writes only a packed radius",
2550 [0.0, 0.0, 0.0, 0.0],
2551 ),
2552 (
2553 "a tube and a streamer that writes no packed size",
2554 [0.0, 0.0, 0.0, 0.0],
2555 ),
2556 (
2557 "a tube and a shock cord that writes no packed size",
2558 [0.0, 0.0, 0.0, 0.0],
2559 ),
2560 (
2561 "a tube and a mass component that writes no packed size",
2562 [0.0, 0.0, 0.0, 0.0],
2563 ),
2564 (
2565 "a tube and a mass component of no mass, under a mass override",
2566 [0.0, 0.0, 0.0, 0.0],
2567 ),
2568 (
2569 "a tube and a shock cord of no length, under a mass override",
2570 [0.0, 0.0, 0.0, 0.0],
2571 ),
2572 (
2573 "a wider tube and a parachute that writes no packed size",
2574 [0.0, 0.0, 0.0, 0.0],
2575 ),
2576 (
2577 "a narrow tube and a parachute that writes no packed size",
2578 [0.0, 0.0, 0.0, 0.0],
2579 ),
2580 (
2581 "a tube and a parachute with a mass override",
2582 [0.0, 0.0, 0.0, 0.0],
2583 ),
2584 ("a tube and a rail button", [0.0, 0.0, 7.16e-6, 9.23e-5]),
2585 (
2586 "a tube and a rail button from the bottom",
2587 [0.0, 0.0, 7.16e-6, 9.23e-5],
2588 ),
2589 (
2590 "a tube and a rail button from the middle",
2591 [0.0, 0.0, 7.16e-6, 9.24e-5],
2592 ),
2593 (
2594 "a tube and a row of two rail buttons from the bottom",
2595 [0.0, 0.0, 1.43e-5, 0.000497],
2596 ),
2597 (
2598 "a tube and a row of two rail buttons from the middle",
2599 [0.0, 0.0, 1.43e-5, 0.000499],
2600 ),
2601 (
2602 "a tube and a row of two rail buttons from the top",
2603 [0.0, 0.0, 1.43e-5, 0.000499],
2604 ),
2605 ("a tube and a shock cord", [0.0, 0.0, 0.0, 0.0]),
2606 ("a tube and a streamer", [0.0, 0.0, 0.0, 0.0]),
2607 (
2608 "a tube and a thicker fin set of airfoil section",
2609 [-0.0305, 0.00155, 0.0, -0.00842],
2610 ),
2611 (
2612 "a tube and an elliptical fin set",
2613 [0.000188, -1.69e-5, 0.000122, -0.000328],
2614 ),
2615 ("a tube and an inner tube", [0.0, 0.0, 0.0, 0.0]),
2616 (
2617 "a tube and a clustered inner tube",
2618 [0.0, 0.0, 0.0511, 0.00273],
2619 ),
2620 ("a tube and rectangular fins", [0.0, 0.0, 0.0, 2.3e-6]),
2621 (
2622 "a tube and rectangular fins of twice the chord",
2623 [0.0, 0.0, 0.0, 4.49e-6],
2624 ),
2625 (
2626 "a tube and rectangular fins of twice the span",
2627 [0.0, 0.0, 0.0, 4.2e-6],
2628 ),
2629 ("a tube and a single fin", [0.0, 0.0, 0.0, 0.00406]),
2630 (
2631 "a tube and a parachute of no canopy, under a mass override",
2632 [0.0, 0.0, 0.0, 0.0],
2633 ),
2634 ("a tube and triangular fins", [0.0, 0.0, 0.0, 0.00028]),
2635 ("a wider tube and rectangular fins", [0.0, 0.0, 0.0, 1e-6]),
2636 ];
2637
2638 #[test]
2639 fn each_part_alone_is_openrocket_s_or_pinned() {
2640 let record = record();
2641 for (question, pinned) in ALONE {
2642 let probe = probe(&record, question);
2643 let (ours, theirs, warnings) = both(probe);
2644 assert!(warnings.is_empty(), "{question}: {warnings:?}");
2645 let (layout, _) = hpr(probe);
2646 let mut roll = ours[2];
2647 for part in probe["parts"].as_array().expect("parts") {
2648 let Some((_, placed)) = part["id"].as_str().and_then(|id| layout.find(id)) else {
2649 continue;
2650 };
2651 if let Part::FinSet(fins) = &placed.part {
2652 let mass_kg = part["mass_kg"].as_f64().expect("a mass");
2653 let radius_m = placed.body_radius_m.expect("fins sit on a tube");
2654 let rule = super::openrocket_fin_set_roll_kg_m2(fins, radius_m, mass_kg)
2655 .expect("three fins");
2656 roll += rule - placed.own.inertia_kg_m2.z_axis.z;
2657 }
2658 }
2659 let found = [
2660 relative(ours[0], theirs[0]),
2661 ours[1] - theirs[1],
2662 relative(roll, theirs[2]),
2663 relative(ours[3], theirs[3]),
2664 ];
2665 for (k, (found, pinned)) in found.iter().zip(pinned).enumerate() {
2666 let bound = if pinned == 0.0 {
2667 1e-12
2668 } else {
2669 5e-3 * pinned.abs()
2670 };
2671 assert!(
2672 (found - pinned).abs() <= bound,
2673 "{question}: quantity {k} is {found:e}, not {pinned:e}"
2674 );
2675 }
2676 }
2677 }
2678
2679 #[test]
2686 fn hpr_s_own_fin_roll_departs_as_pinned() {
2687 let record = record();
2688 let departures = [
2689 ("a tube and rectangular fins", 0.000_129),
2690 ("a tube and a fin set of square section", 0.0241),
2691 ("a tube and triangular fins", -0.0214),
2692 ("a tube and a fin set with a tab", -0.0512),
2693 ];
2694 for (question, pinned) in departures {
2695 let probe = probe(&record, question);
2696 let (ours, theirs, _) = both(probe);
2697 let (layout, _) = hpr(probe);
2698 let fins = layout
2699 .components
2700 .iter()
2701 .find(|placed| matches!(placed.part, Part::FinSet(_)))
2702 .expect("a fin set");
2703 let hpr_fins = fins.own.inertia_kg_m2.z_axis.z;
2704 let their_fins = theirs[2] - (ours[2] - hpr_fins);
2705 let found = relative(hpr_fins, their_fins);
2706 assert!(
2707 (found - pinned).abs() <= 5e-3 * pinned.abs(),
2708 "{question}: {found:e}, not {pinned:e}"
2709 );
2710 }
2711 }
2712
2713 #[test]
2721 fn a_fin_section_is_weighed_as_pinned() {
2722 let record = record();
2723 let fins = |question: &str| -> (f64, f64) {
2724 let probe = probe(&record, question);
2725 let (layout, _) = hpr(probe);
2726 let theirs = probe["parts"]
2727 .as_array()
2728 .expect("parts")
2729 .iter()
2730 .find(|part| part["class"] == "TrapezoidFinSet")
2731 .expect("a fin set");
2732 let id = theirs["id"].as_str().expect("an id");
2733 let (_, ours) = layout.find(id).expect("hpr's fin set");
2734 (
2735 ours.own.mass_kg,
2736 theirs["mass_kg"].as_f64().expect("a mass"),
2737 )
2738 };
2739 let square = fins("a tube and a fin set of square section");
2740 assert!((square.0 - square.1).abs() < 1e-15, "{square:?}");
2741 let sections = [
2742 (
2743 "a tube and a fin set of rounded section",
2744 1.0,
2745 0.99,
2746 0.991_416,
2747 ),
2748 (
2749 "a tube and a fin set of airfoil section",
2750 1.0,
2751 0.85,
2752 0.685_083,
2753 ),
2754 (
2755 "a tube and a thicker fin set of airfoil section",
2756 2.0,
2757 0.85,
2758 0.685_083,
2759 ),
2760 ];
2761 for (question, thickness, openrocket, ours) in sections {
2762 let (hpr, theirs) = fins(question);
2763 let slab = thickness * square.1;
2764 assert!(
2765 (theirs / slab - openrocket).abs() < 1e-12,
2766 "{question}: {}",
2767 theirs / slab
2768 );
2769 assert!(
2770 (hpr / slab - ours).abs() < 1e-6,
2771 "{question}: {}",
2772 hpr / slab
2773 );
2774 }
2775 }
2776
2777 #[test]
2783 fn the_loft_boattail_s_roll_is_the_rule_on_openrocket_s_ellipse() {
2784 let text = include_str!("../../../validation/fixtures/ork/openrocket-mass-loft-demo.json");
2785 let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
2786 let file = "validation/fixtures/ork/loft-demo/demo-boattail.ork";
2787 let design = record["designs"]
2788 .as_array()
2789 .expect("designs")
2790 .iter()
2791 .find(|design| design["file"] == file)
2792 .expect("the boattail's record");
2793 let theirs = design["structure"]["ixx"].as_f64().expect("a roll inertia");
2794 let bytes = include_bytes!("../../../validation/fixtures/ork/loft-demo/demo-boattail.ork");
2795 let read = ork::read(bytes.as_slice()).expect("the design reads");
2796 let layout = ork::design(&read.value)
2797 .value
2798 .rocket
2799 .layout()
2800 .expect("it lays out");
2801 let polygon = (std::f64::consts::PI / 30.0).sin() / (std::f64::consts::PI / 30.0);
2802 let mut ours = layout.structure.inertia_kg_m2.z_axis.z;
2803 let mut fins = 0;
2804 for placed in &layout.components {
2805 let Part::FinSet(set) = &placed.part else {
2806 continue;
2807 };
2808 assert!(matches!(
2809 set.planform,
2810 hpr_design::fins::FinPlanform::Elliptical { .. }
2811 ));
2812 let rule = super::rod_roll_kg_m2(
2814 set.count,
2815 set.planform.geometry().expect("an outline").area_m2 * polygon,
2816 set.planform.span_m(),
2817 set.planform.root_chord_m(),
2818 placed.body_radius_m.expect("fins sit on a tube"),
2819 placed.own.mass_kg * polygon,
2820 )
2821 .expect("three fins");
2822 ours += rule - placed.own.inertia_kg_m2.z_axis.z;
2823 fins += 1;
2824 }
2825 assert_eq!(fins, 1);
2826 let apart = relative(ours, theirs);
2827 assert!(apart.abs() < 2e-6, "{apart:e}");
2828 }
2829
2830 fn pods() -> Value {
2831 let text = include_str!("../../../validation/fixtures/ork/openrocket-pods.json");
2832 serde_json::from_str(text).expect("the committed record is JSON")
2833 }
2834
2835 #[test]
2846 fn every_pod_is_where_openrocket_puts_it() {
2847 let record = pods();
2848 let probes = record["probes"].as_object().expect("probes");
2849 assert_eq!(probes.len(), 18);
2850 for (question, probe) in probes {
2851 let (layout, warnings) = hpr(probe);
2852 if question.ends_with("its mass overridden to 0.1 kg") {
2853 assert_eq!(warnings.len(), 1, "{question}: {warnings:?}");
2854 assert!(warnings[0].contains("at the rocket's tip"), "{warnings:?}");
2855 } else {
2856 assert!(warnings.is_empty(), "{question}: {warnings:?}");
2857 }
2858 let mut inside = 0;
2859 for (id, theirs) in probe["components"].as_object().expect("components") {
2860 let Some((_, placed)) = layout.find(id) else {
2861 continue;
2862 };
2863 if !in_a_pod(&layout, id) {
2864 continue;
2865 }
2866 inside += 1;
2867 let theirs: Vec<[f64; 3]> = theirs["locations_m"]
2868 .as_array()
2869 .expect("locations")
2870 .iter()
2871 .map(|l| {
2872 let at = |k: usize| l[k].as_f64().expect("a number");
2873 [at(1), at(2), at(0)]
2874 })
2875 .collect();
2876 let ours = where_hpr_puts(placed);
2877 assert_eq!(ours.len(), theirs.len(), "{question}: {id}");
2878 let near = |a: &[f64; 3], b: &[f64; 3]| {
2879 (a[0] - b[0]).hypot(a[1] - b[1]) <= 1e-15 && (a[2] - b[2]).abs() <= 1e-15
2880 };
2881 if matches!(placed.part, Part::FinSet(_)) {
2882 let mut left = ours.clone();
2883 for place in &theirs {
2884 let k = left.iter().position(|o| near(o, place));
2885 let k = k.unwrap_or_else(|| panic!("{question}: {id} {place:?} {ours:?}"));
2886 left.swap_remove(k);
2887 }
2888 } else {
2889 for (o, t) in ours.iter().zip(&theirs) {
2890 assert!(near(o, t), "{question}: {id} {o:?} vs {t:?}");
2891 }
2892 }
2893 }
2894 let least = if question.starts_with("an empty") {
2895 0
2896 } else {
2897 2
2898 };
2899 assert!(inside >= least, "{question}: {inside} parts in the pod");
2900 }
2901 }
2902
2903 fn in_a_pod(layout: &Layout, id: &str) -> bool {
2905 let mut at = layout.find(id).expect("the part").1.parent;
2906 while let Some(index) = at {
2907 let parent = &layout.components[index];
2908 if matches!(parent.part, Part::PodSet(_)) {
2909 return true;
2910 }
2911 at = parent.parent;
2912 }
2913 false
2914 }
2915
2916 fn where_hpr_puts(placed: &hpr_design::tree::PlacedComponent) -> Vec<[f64; 3]> {
2922 let fore = placed.fore_station_m;
2923 let out = |offset: [f64; 2], radius: f64, angle: f64| {
2924 [
2925 offset[0] + radius * angle.cos(),
2926 offset[1] + radius * angle.sin(),
2927 fore,
2928 ]
2929 };
2930 let body = placed.body_radius_m.unwrap_or_default();
2931 let mut places = Vec::new();
2932 for copy in &placed.copies {
2933 match &placed.part {
2934 Part::FinSet(set) => {
2935 let step = std::f64::consts::TAU / f64::from(set.count);
2936 for k in 0..set.count {
2937 let angle = copy.roll_rad + set.base_angle_rad + step * f64::from(k);
2938 places.push(out(copy.offset_m, body, angle));
2939 }
2940 }
2941 Part::LaunchLug(lug) => {
2942 let angle = copy.roll_rad + lug.angle_rad;
2943 places.push(out(copy.offset_m, body + lug.outer_radius_m, angle));
2944 }
2945 _ => places.push(out(copy.offset_m, 0.0, 0.0)),
2946 }
2947 }
2948 places
2949 }
2950
2951 #[test]
2981 fn pods_weigh_as_openrocket_s() {
2982 const PART: (f64, f64) = (2e-15, 2e-15);
2984 const NOSE: (f64, f64) = (1e-7, 5e-9);
2985 const FIN_PITCH: [(&str, f64); 4] = [
2987 (
2988 "one pod of no length 0.01 in radius, relative 0.02, two fins at 90",
2989 3.35e-5,
2990 ),
2991 (
2992 "one pod of no length, relative 0.03, bottom 0.0, two fins at 90",
2993 9.35e-6,
2994 ),
2995 (
2996 "two pods of no length 0.01 in radius, relative 0.02, at 30, three fins at 20",
2997 2.58e-7,
2998 ),
2999 (
3000 "two pods of no length, relative 0.02, at 45, three fins",
3001 -9.05e-7,
3002 ),
3003 ];
3004 let pinned = |got: f64, want: f64| (got - want).abs() <= 0.005 * want.abs();
3005 let record = pods();
3006 let probes = record["probes"].as_object().expect("probes");
3007 let empty = &probes["an empty pod set, relative 0.004"];
3008 let (ours, theirs, _) = both(empty);
3009 let bare = [relative(ours[0], theirs[0]), relative(ours[1], theirs[1])];
3010 assert!(pinned(bare[0], 1.17e-7), "{bare:?}");
3011 assert!(pinned(bare[1], -1.125e-7), "{bare:?}");
3012 let (layout, _) = hpr(empty);
3013 let nose = &empty["parts"][0];
3014 assert_eq!(nose["class"], "NoseCone");
3015 let (_, placed) = layout.find(conventions_id(1)).expect("the nose");
3016 let apart = relative(
3017 placed.own.mass_kg,
3018 nose["mass_kg"].as_f64().expect("a mass"),
3019 );
3020 assert!(pinned(apart, 5.10e-7), "{apart:e}");
3021 let apart = relative(
3022 -placed.own.cg_m.z,
3023 nose["cm_x_m"].as_f64().expect("a station"),
3024 );
3025 assert!(pinned(apart, -4.64e-7), "{apart:e}");
3026 let tube = &empty["parts"][1];
3028 assert_eq!(tube["class"], "BodyTube");
3029 let (_, placed) = layout.find(conventions_id(2)).expect("the tube");
3030 let apart = relative(
3031 placed.own.mass_kg,
3032 tube["mass_kg"].as_f64().expect("a mass"),
3033 );
3034 assert!(apart.abs() < PART.0, "{apart:e}");
3035
3036 for (question, probe) in probes {
3037 let (ours, theirs, _) = both(probe);
3038 let (layout, _) = hpr(probe);
3039 if question.ends_with("its mass overridden to 0.1 kg") {
3040 let (bare_ours, bare_theirs, _) = both(empty);
3041 assert_eq!(ours, bare_ours, "{question}");
3042 let mass = theirs[0] - bare_theirs[0];
3043 assert!((mass - 0.1).abs() < 1e-15, "{question}: {mass:e}");
3044 let moment = theirs[0] * theirs[1] - bare_theirs[0] * bare_theirs[1];
3045 assert!(moment.abs() < 1e-15, "{question}: {moment:e}");
3046 assert_eq!(theirs[2], bare_theirs[2], "{question}");
3047 continue;
3048 }
3049 let airframe = [conventions_id(1), conventions_id(2)];
3050 let mut weighed = 0;
3051 let mut in_pods = 0;
3052 for part in probe["parts"].as_array().expect("parts") {
3053 let id = part["id"].as_str().expect("an id");
3054 let class = part["class"].as_str().expect("a class");
3055 if matches!(class, "Rocket" | "AxialStage") || airframe.contains(&id) {
3056 continue;
3057 }
3058 in_pods += 1;
3059 let (_, placed) = layout
3060 .find(id)
3061 .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
3062 assert!(
3063 in_a_pod(&layout, id) || matches!(placed.part, Part::PodSet(_)),
3064 "{question}: {id}"
3065 );
3066 weighed += 1;
3067 let mass = part["mass_kg"].as_f64().expect("a mass");
3068 let own = placed.own;
3069 if mass == 0.0 {
3070 assert_eq!(own.mass_kg, 0.0, "{question}: {id}");
3071 continue;
3072 }
3073 let (mass_bound, center_bound) = if matches!(placed.part, Part::NoseCone(_)) {
3074 NOSE
3075 } else {
3076 PART
3077 };
3078 let apart = relative(own.mass_kg, mass);
3079 assert!(apart.abs() < mass_bound, "{question}: {id} mass {apart:e}");
3080 let station = part["cm_x_m"].as_f64().expect("a station");
3081 let apart = relative(-own.cg_m.z, station);
3082 assert!(
3083 apart.abs() < center_bound,
3084 "{question}: {id} center {apart:e}"
3085 );
3086 }
3087 assert_eq!(weighed, in_pods, "{question}");
3088 let holds_nothing = question.starts_with("an empty");
3089 let least = if holds_nothing { 1 } else { 3 };
3090 assert!(in_pods >= least, "{question}: {in_pods}");
3091
3092 let of_length = !(holds_nothing || question.contains("of no length"));
3093 let center_bound = if of_length { 1.1e-7 } else { 1.13e-7 };
3094 for (k, bound) in [(0, 1.2e-7), (1, center_bound)] {
3095 let apart = relative(ours[k], theirs[k]);
3096 assert!(apart.abs() < bound, "{question}: quantity {k}, {apart:e}");
3097 assert!(
3098 apart.abs() <= bare[k].abs(),
3099 "{question}: quantity {k}, {apart:e}"
3100 );
3101 }
3102
3103 let mut roll = ours[2];
3104 for placed in &layout.components {
3105 let Part::FinSet(set) = &placed.part else {
3106 continue;
3107 };
3108 let radius = placed.body_radius_m.expect("fins sit on a tube");
3109 let one = placed
3110 .part
3111 .mass_properties(Some(radius))
3112 .expect("a fin set");
3113 let copies = f64::from(u32::try_from(placed.copies.len()).expect("a few pods"));
3114 let rule = super::openrocket_fin_set_roll_kg_m2(set, radius, one.mass_kg)
3115 .expect("two or more fins");
3116 roll += copies * (rule - one.inertia_kg_m2.z_axis.z);
3117 }
3118 let apart = relative(roll, theirs[2]);
3119 assert!(apart.abs() < 2e-9, "{question}: roll {apart:e}");
3120
3121 let i = layout.structure.inertia_kg_m2;
3122 let pitch = probe["structure"]["iyy"].as_f64().expect("a number");
3123 assert_eq!(
3124 probe["structure"]["izz"].as_f64(),
3125 Some(pitch),
3126 "{question}"
3127 );
3128 let about_x = relative(i.x_axis.x, pitch);
3129 if let Some((_, want)) = FIN_PITCH.iter().find(|(q, _)| q == question) {
3130 assert!(pinned(about_x, *want), "{question}: {about_x:e}");
3131 continue;
3132 }
3133 assert!(
3134 !layout
3135 .components
3136 .iter()
3137 .any(|c| matches!(c.part, Part::FinSet(_))),
3138 "{question}: fins not pinned"
3139 );
3140 assert!(about_x.abs() < 6.1e-7, "{question}: {about_x:e}");
3141 let about_y = relative(i.y_axis.y, pitch);
3142 if question.starts_with("three") {
3143 assert!(about_y.abs() < 6.1e-7, "{question}: {about_y:e}");
3144 } else if of_length {
3145 assert!((0.002..0.011).contains(&about_y), "{question}: {about_y:e}");
3146 }
3147 }
3148 }
3149
3150 fn conventions_id(n: u32) -> &'static str {
3152 match n {
3153 1 => "00000000-0000-4000-8000-000000000001",
3154 2 => "00000000-0000-4000-8000-000000000002",
3155 _ => unreachable!("only the probes' nose and tube are asked for"),
3156 }
3157 }
3158
3159 fn clusters() -> Value {
3160 let text = include_str!("../../../validation/fixtures/ork/openrocket-clusters.json");
3161 serde_json::from_str(text).expect("the committed record is JSON")
3162 }
3163
3164 #[test]
3169 fn every_tube_of_a_cluster_is_where_openrocket_puts_it() {
3170 let record = clusters();
3171 let patterns = record["patterns"].as_object().expect("patterns");
3172 assert_eq!(patterns.len(), 14);
3173 for name in patterns.keys() {
3174 assert!(
3175 record["probes"][format!("{name} at scale 1")].is_object(),
3176 "no probe of {name}"
3177 );
3178 }
3179 for (question, probe) in record["probes"].as_object().expect("probes") {
3180 let (layout, warnings) = hpr(probe);
3181 let unnamed = question == "a pattern OpenRocket has no name for";
3182 assert_eq!(
3183 warnings.len(),
3184 usize::from(unnamed),
3185 "{question}: {warnings:?}"
3186 );
3187 if unnamed {
3188 assert!(
3189 warnings[0].contains("is not one of OpenRocket's cluster patterns"),
3190 "{warnings:?}"
3191 );
3192 }
3193 for (id, tube) in probe["tubes"].as_object().expect("tubes") {
3194 let (_, placed) = layout.find(id).expect("the tube");
3195 let Part::InnerTube(inner) = &placed.part else {
3196 panic!("{question}: {id} is not an inner tube");
3197 };
3198 let [x, y] = placed.part.axis_offset_m();
3199 let ours: Vec<[f64; 2]> = inner
3200 .tubes_m()
3201 .expect("finite")
3202 .iter()
3203 .map(|[u, v]| [x + u, y + v])
3204 .collect();
3205 let theirs: Vec<[f64; 2]> = tube["instance_offsets_m"]
3206 .as_array()
3207 .expect("offsets")
3208 .iter()
3209 .map(|c| [c[1].as_f64().expect("y"), c[2].as_f64().expect("z")])
3210 .collect();
3211 assert_eq!(ours.len(), theirs.len(), "{question}");
3212 assert_eq!(
3213 tube["count"].as_u64(),
3214 Some(ours.len() as u64),
3215 "{question}"
3216 );
3217 for (ours, theirs) in ours.iter().zip(&theirs) {
3218 let apart = (ours[0] - theirs[0]).hypot(ours[1] - theirs[1]);
3219 assert!(apart <= 1e-15, "{question}: {ours:?} vs {theirs:?}");
3220 }
3221 }
3222 }
3223 }
3224
3225 #[test]
3238 fn a_cluster_weighs_as_openrocket_s_but_for_its_tubes_spread() {
3239 const OFF_AXIS: [(&str, [f64; 2]); 3] = [
3240 (
3241 "an unclustered tube 10 mm off the axis at 30",
3242 [0.00303, 0.000164],
3243 ),
3244 ("a 2-row 10 mm off the axis at 30", [0.0, 0.00015]),
3245 (
3246 "a 3-ring 10 mm off the axis at 30, turned 20",
3247 [0.0, 0.000206],
3248 ),
3249 ];
3250 let record = clusters();
3251 for (question, probe) in record["probes"].as_object().expect("probes") {
3252 let (ours, theirs, _) = both(probe);
3253 assert!(
3254 relative(ours[0], theirs[0]).abs() <= 1e-12,
3255 "{question}: mass"
3256 );
3257 assert!((ours[1] - theirs[1]).abs() <= 1e-12, "{question}: center");
3258 let (layout, _) = hpr(probe);
3259 let mut spread = 0.0;
3260 for id in probe["tubes"].as_object().expect("tubes").keys() {
3261 let (_, placed) = layout.find(id).expect("the tube");
3262 let Part::InnerTube(inner) = &placed.part else {
3263 panic!("{question}: {id} is not an inner tube");
3264 };
3265 let tubes = inner.tubes_m().expect("finite");
3266 let each_kg = placed.own.mass_kg / tubes.len() as f64;
3267 spread += tubes
3268 .iter()
3269 .map(|[u, v]| each_kg * (u * u + v * v))
3270 .sum::<f64>();
3271 }
3272 let found = [
3274 relative(ours[2] - spread, theirs[2]),
3275 relative(ours[3] - spread / 2.0, theirs[3]),
3276 ];
3277 let pinned = OFF_AXIS
3278 .iter()
3279 .find(|(q, _)| q == question)
3280 .map_or([0.0, 0.0], |(_, pinned)| *pinned);
3281 for (k, (found, pinned)) in found.iter().zip(pinned).enumerate() {
3282 let bound = if pinned == 0.0 {
3283 1e-12
3284 } else {
3285 5e-3 * pinned.abs()
3286 };
3287 assert!(
3288 (found - pinned).abs() <= bound,
3289 "{question}: inertia {k} less the spread is {found:e}, not {pinned:e}"
3290 );
3291 }
3292 }
3293 }
3294
3295 #[test]
3298 fn the_cluster_record_is_openrocket_s() {
3299 let record = clusters();
3300 assert_eq!(record["openrocket"], "24.12");
3301 assert_eq!(
3302 record["source"],
3303 "validation/oracles/openrocket/clusters.py"
3304 );
3305 assert!(record["probes"].as_object().expect("probes").len() >= 22);
3306 }
3307
3308 const BORES: [&str; 13] = [
3311 "a nose holding a coupler of automatic radius at its bottom",
3312 "an ogive nose holding a coupler of automatic radius at its bottom",
3313 "a nose holding a coupler of automatic radius past its base",
3314 "a nose with a shoulder, holding a coupler of automatic radius past its base",
3315 "a nose holding a long coupler of automatic radius from its middle",
3316 "a nose holding an engine block of automatic radius",
3317 "a nose holding a centering ring and a bulkhead of automatic radius",
3318 "a nose holding a coupler of automatic radius and a wall thicker than its bore",
3319 "a nose holding a coupler of automatic radius with a mass inside",
3320 "a transition holding a coupler of automatic radius",
3321 "a tube holding a coupler of automatic radius and a wall thicker than its bore",
3322 "a tube holding an inner tube of automatic radius",
3323 "a nose holding an inner tube of automatic radius",
3324 ];
3325
3326 const BORE_REFUSED: &str = "a nose holding a coupler of automatic radius at its tip";
3328
3329 #[test]
3347 fn an_automatic_radius_inside_a_nose_reads_as_openrocket_does() {
3348 let record = record();
3349 for question in BORES {
3350 let probe = probe(&record, question);
3351 let (layout, warnings) = hpr(probe);
3352 assert!(warnings.is_empty(), "{question}: {warnings:?}");
3353 for part in probe["parts"].as_array().expect("parts") {
3354 let class = part["class"].as_str().expect("a class");
3355 if matches!(class, "Rocket" | "AxialStage") {
3356 continue;
3357 }
3358 let id = part["id"].as_str().expect("an id");
3359 let (_, placed) = layout
3360 .find(id)
3361 .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
3362 let mass = part["mass_kg"].as_f64().expect("a mass");
3363 let station = part["cm_x_m"].as_f64().expect("a station");
3364 let (mass_bound, station_gap, station_bound) = match class {
3365 "NoseCone" | "Transition" => (5e-5, 0.0, 5e-6),
3366 "MassComponent" => (1e-15, 0.020755, 1e-6),
3367 _ => (1e-14, 0.0, 1e-15),
3368 };
3369 let found = relative(placed.own.mass_kg, mass);
3370 assert!(
3371 found.abs() <= mass_bound,
3372 "{question}: {class} {id} is {found:e} from OpenRocket's mass"
3373 );
3374 let apart_m = -placed.own.cg_m.z - station;
3375 assert!(
3376 (apart_m - station_gap).abs() <= station_bound,
3377 "{question}: {class} {id} is {apart_m:e} m from OpenRocket's station"
3378 );
3379 }
3380 }
3381
3382 let probe = probe(&record, BORE_REFUSED);
3383 let coupler = probe["parts"]
3384 .as_array()
3385 .expect("parts")
3386 .iter()
3387 .find(|part| part["class"] == "TubeCoupler")
3388 .expect("the coupler");
3389 assert_eq!(coupler["mass_kg"].as_f64(), Some(0.0));
3390 let document = probe["document"].as_str().expect("the probe's document");
3391 let read = ork::read(document.as_bytes()).expect("a probe reads");
3392 let error = ork::rocket(&read.value.document)
3393 .value
3394 .layout()
3395 .expect_err("a tube of no radius");
3396 assert!(
3397 matches!(
3398 &error,
3399 hpr_design::DesignError::InComponent { source, .. }
3400 if matches!(
3401 **source,
3402 hpr_design::DesignError::Domain { what: "outer radius", value }
3403 if value == 0.0
3404 )
3405 ),
3406 "{error:?}"
3407 );
3408 }
3409
3410 const TUBE_FINS: [&str; 19] = [
3412 "a tube and 1 tube fins of automatic radius",
3413 "a tube and 2 tube fins of automatic radius",
3414 "a tube and 3 tube fins of automatic radius",
3415 "a tube and 4 tube fins of automatic radius",
3416 "a tube and 5 tube fins of automatic radius",
3417 "a tube and 6 tube fins of automatic radius",
3418 "a tube and 8 tube fins of automatic radius",
3419 "a tube and 9 tube fins of automatic radius",
3420 "a tube and 12 tube fins of automatic radius",
3421 "a tube and 20 tube fins of automatic radius",
3422 "a tube and 6 tube fins of a stated radius",
3423 "a tube and 6 tube fins of automatic radius and a wall thicker than it",
3424 "a tube and 6 tube fins of a stated radius, offset from the body",
3425 "a tube of automatic radius and 4 tube fins of automatic radius",
3426 "a tube and 12 tube fins of a stated radius",
3427 "a tube and 100 tube fins of automatic radius",
3428 "a 20 mm tube and 1 tube fins of automatic radius",
3429 "a 20 mm tube and 2 tube fins of automatic radius",
3430 "a 20 mm tube and 5 tube fins of automatic radius",
3431 ];
3432
3433 #[test]
3441 fn a_tube_fin_sets_automatic_radius_reads_as_openrocket_does() {
3442 let record = record();
3443 for question in TUBE_FINS {
3444 let probe = probe(&record, question);
3445 let (layout, warnings) = hpr(probe);
3446 let capped = ["9", "12", "20", "100"]
3449 .iter()
3450 .any(|n| question.contains(&format!(" and {n} tube fins")));
3451 let offset = question.contains("offset");
3452 assert_eq!(
3453 warnings.len(),
3454 usize::from(capped || offset),
3455 "{question}: {warnings:?}"
3456 );
3457 let said = if offset {
3458 "read sitting on it"
3459 } else {
3460 "reads at most 8"
3461 };
3462 assert!(
3463 warnings.iter().all(|w| w.contains(said)),
3464 "{question}: {warnings:?}"
3465 );
3466 for part in probe["parts"].as_array().expect("parts") {
3467 let class = part["class"].as_str().expect("a class");
3468 if matches!(class, "Rocket" | "AxialStage") {
3469 continue;
3470 }
3471 let id = part["id"].as_str().expect("an id");
3472 let (_, placed) = layout
3473 .find(id)
3474 .unwrap_or_else(|| panic!("{question}: no part {id} in hpr"));
3475 let (mass_bound, station_bound) = match class {
3477 "NoseCone" => (5e-5, 5e-6),
3478 _ => (1e-14, 1e-15),
3479 };
3480 let mass = part["mass_kg"].as_f64().expect("a mass");
3481 let found = relative(placed.own.mass_kg, mass);
3482 assert!(
3483 found.abs() <= mass_bound,
3484 "{question}: {class} is {found:e} from OpenRocket's mass"
3485 );
3486 let apart_m = -placed.own.cg_m.z - part["cm_x_m"].as_f64().expect("a station");
3487 assert!(
3488 apart_m.abs() <= station_bound,
3489 "{question}: {class} is {apart_m:e} m from OpenRocket's"
3490 );
3491 }
3492 let (id, theirs) = probe["tube_fins"]
3493 .as_object()
3494 .and_then(|sets| sets.iter().next())
3495 .expect("one tube fin set");
3496 let (_, placed) = layout.find(id).expect("the tube fin set");
3497 let Part::TubeFinSet(ours) = &placed.part else {
3498 panic!("{question}: {:?}", placed.part);
3499 };
3500 let number = |key: &str| theirs[key].as_f64().expect(key);
3501 assert_eq!(
3502 theirs["automatic"].as_bool(),
3503 Some(!question.contains("stated"))
3504 );
3505 assert_eq!(
3506 Some(u64::from(ours.count)),
3507 theirs["count"].as_u64(),
3508 "{question}"
3509 );
3510 let r = number("outer_radius_m");
3511 assert!(
3512 relative(ours.outer_radius_m, r).abs() <= 1e-15,
3513 "{question}: radius {} against OpenRocket's {r}",
3514 ours.outer_radius_m
3515 );
3516 assert!(
3517 relative(ours.thickness_m, number("thickness_m")).abs() <= 1e-15,
3518 "{question}: wall {} against {}",
3519 ours.thickness_m,
3520 number("thickness_m")
3521 );
3522 let body_radius_m = number("body_radius_m");
3523 assert_eq!(placed.body_radius_m, Some(body_radius_m), "{question}");
3524 let (r_i, length_m) = (number("inner_radius_m"), 0.1);
3527 let across = (r * r + r_i * r_i) / 4.0 + length_m * length_m / 12.0;
3528 let about = (r * r + r_i * r_i) / 2.0;
3529 let d2 = (body_radius_m + r).powi(2);
3530 let unit = |i: f64| i / placed.own.mass_kg;
3531 let inertia = &placed.own.inertia_kg_m2;
3532 let their_pitch = number("longitudinal_unit_inertia_m2");
3535 let n = f64::from(ours.count);
3536 assert!(
3537 relative(their_pitch, n * across).abs() <= 1e-14,
3538 "{question}: {their_pitch}"
3539 );
3540 if ours.count == 1 {
3541 let [_, y, z] =
3543 [0, 1, 2].map(|k| theirs["component_cg_xyz_m"][k].as_f64().expect("a center"));
3544 let off = y.hypot(z);
3545 assert!(
3546 (off - (body_radius_m + r)).abs() <= 1e-15,
3547 "{question}: {off}"
3548 );
3549 let ours_off = placed.own.cg_m.x.hypot(placed.own.cg_m.y);
3550 assert!(
3551 (ours_off - off).abs() <= 1e-15,
3552 "{question}: hpr's center {ours_off}"
3553 );
3554 let roll = number("rotational_unit_inertia_m2");
3555 assert!(relative(roll, about).abs() <= 1e-15, "{question}: {roll}");
3556 assert!(
3557 relative(unit(inertia.z_axis.z), roll).abs() <= 1e-14,
3558 "{question}"
3559 );
3560 assert!(
3562 relative(unit(inertia.x_axis.x), across).abs() <= 1e-13,
3563 "{question}"
3564 );
3565 assert!(relative(their_pitch, across).abs() <= 1e-14, "{question}");
3566 } else {
3567 assert!(
3570 relative(unit(inertia.z_axis.z), about + d2).abs() <= 1e-13,
3571 "{question}"
3572 );
3573 let bound = (body_radius_m + 2.0 * r).powi(2);
3574 let roll = number("rotational_unit_inertia_m2");
3575 assert!(
3576 roll > bound,
3577 "{question}: OpenRocket's {roll} within {bound}"
3578 );
3579 if ours.count >= 3 {
3580 let pitch = unit(inertia.x_axis.x);
3581 assert!(
3582 relative(pitch, across + d2 / 2.0).abs() <= 1e-13,
3583 "{question}: {pitch}"
3584 );
3585 assert!(
3586 relative(unit(inertia.y_axis.y), pitch).abs() <= 1e-13,
3587 "{question}"
3588 );
3589 assert!(
3590 their_pitch > pitch * 1.2,
3591 "{question}: {their_pitch} against hpr's {pitch}"
3592 );
3593 }
3594 }
3595 }
3596 }
3597
3598 #[test]
3603 fn every_probe_is_checked() {
3604 let record = record();
3605 assert_eq!(record["openrocket"], "24.12");
3606 assert_eq!(
3607 record["source"],
3608 "validation/oracles/openrocket/conventions.py"
3609 );
3610 assert_eq!(record["saved_default_materials"], serde_json::json!({}));
3611 let mut read: Vec<&str> = READINGS.to_vec();
3612 read.extend(PRECEDENCE.iter().map(|(question, _)| *question));
3613 read.extend(DISAGREEING.iter().map(|(question, _)| *question));
3614 read.extend(INERTIA.iter().map(|(question, _)| *question));
3615 read.extend(ALONE.iter().map(|(question, _)| *question));
3616 read.extend(OLD_FLAG.iter().map(|(question, _)| *question));
3617 read.extend(STAGE_ADDS);
3618 read.push(STAGE_ADDS_TO_NOTHING);
3619 read.extend(STAGE_WHOLE);
3620 read.extend(STAGE_WHOLE_BELOW.iter().map(|(question, _)| *question));
3621 read.extend(BORES);
3622 read.push(BORE_REFUSED);
3623 read.extend(TUBE_FINS);
3624 let probes: Vec<&str> = record["probes"]
3625 .as_object()
3626 .expect("probes")
3627 .keys()
3628 .map(String::as_str)
3629 .collect();
3630 for question in &probes {
3631 assert!(
3632 read.contains(question),
3633 "no test reads the probe {question:?}"
3634 );
3635 }
3636 for question in &read {
3637 assert!(probes.contains(question), "no probe asks {question:?}");
3638 }
3639 }
3640
3641 struct TubeFinsSeen {
3643 probe: String,
3644 mach: f64,
3645 slope_ratio: f64,
3647 over_long_ring_limit: f64,
3649 gap_cal: f64,
3651 center_only_cal: f64,
3654 slope_only_cal: f64,
3655 }
3656
3657 fn tube_fin_record() -> Value {
3659 let text = include_str!("../../../validation/fixtures/ork/openrocket-tube-fin-aero.json");
3660 let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
3661 for (name, bytes) in [
3662 (
3663 "tube_fin_aero.py",
3664 include_bytes!("../../../validation/oracles/openrocket/tube_fin_aero.py")
3665 .as_slice(),
3666 ),
3667 (
3668 "automatic_radius.py",
3669 include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
3670 .as_slice(),
3671 ),
3672 ] {
3673 assert_eq!(
3674 record["inputs_sha256"][name],
3675 crate::real_flight::sha256_hex(bytes).as_str(),
3676 "{name} changed since the record was written: rerun it"
3677 );
3678 }
3679 record
3680 }
3681
3682 fn tube_fins_seen(record: &Value) -> Vec<TubeFinsSeen> {
3686 let number = |value: &Value| value.as_f64().expect("a number");
3687 let mut seen = Vec::new();
3688 let probes = record["probes"].as_object().expect("probes");
3689 assert_eq!(probes.len(), 14);
3690 for (name, probe) in probes {
3691 let document = probe["document"].as_str().expect("the probe's document");
3692 let read = ork::read(document.as_bytes()).expect("a probe reads");
3693 let layout = ork::rocket(&read.value.document)
3694 .value
3695 .layout()
3696 .expect("a probe lays out");
3697 let model = hpr_aero::AeroModel::new(&layout).expect("hpr models the probe");
3698 let [set] = model.tube_fin_sets() else {
3699 panic!("{name}: not one tube fin set in hpr");
3700 };
3701 let mut slopes = Vec::new();
3702 for asked in probe["machs"].as_array().expect("machs") {
3703 let mach = number(&asked["mach"]);
3704 let cal = number(&asked["reference_length_m"]);
3705 let components = asked["components"].as_object().expect("components");
3706 let of = |class: &str| {
3707 let mut found = components.values().filter(|c| c["class"] == class);
3708 let one = found.next().expect("the component");
3709 assert!(found.next().is_none(), "{name}: two of {class}");
3710 one
3711 };
3712 let rocket = of("Rocket");
3713 let tubes = &components[&set.id];
3714 assert_eq!(tubes["class"], "TubeFinSet", "{name}");
3715 let (outer, inner) = (
3718 number(&tubes["outer_radius_m"]),
3719 number(&tubes["inner_radius_m"]),
3720 );
3721 assert!(
3722 (set.mean_diameter_m - (outer + inner)).abs() <= 1e-12,
3723 "{name}"
3724 );
3725 let axis = number(&tubes["body_radius_m"]) + outer;
3726 assert!((set.axis_radius_m - axis).abs() <= 1e-12, "{name}");
3727 assert!(
3728 (model.reference_area_m2() / number(&asked["reference_area_m2"]) - 1.0).abs()
3729 <= 1e-12,
3730 "{name}"
3731 );
3732 assert_eq!(
3733 tubes["count"].as_u64(),
3734 Some(u64::from(set.count)),
3735 "{name}"
3736 );
3737 let fore_m = number(&tubes["leading_edge_x_m"]);
3738 let length_m = number(&tubes["length_m"]);
3739 assert!((set.fore_station_m - fore_m).abs() <= 1e-12, "{name}");
3740 assert!((set.length_m - length_m).abs() <= 1e-12, "{name}");
3741 let (theirs, their_x) = (number(&tubes["cna_per_rad"]), number(&tubes["cp_x_m"]));
3745 slopes.push(theirs);
3746 let quarter = if mach <= 0.5 { 0.25 } else { 0.0 };
3747 assert!(
3748 ((their_x - fore_m) / length_m - quarter).abs() <= 1e-9,
3749 "{name} at Mach {mach}"
3750 );
3751 if mach >= hpr_aero::tube_fins::TUBE_FIN_MACH_LIMIT {
3752 continue;
3753 }
3754 let (ours, our_x) = set.loading(mach).expect("below the limit");
3755 let whole = model
3756 .normal_force(&hpr_aero::Flow::new(mach, 0.0, 0.0))
3757 .expect("hpr's normal force");
3758 let our_cp = whole.cp_station_m.expect("a center of pressure");
3759 let (their_whole, their_cp) =
3760 (number(&rocket["cna_per_rad"]), number(&rocket["cp_x_m"]));
3761 let rest = whole.slope_per_rad - ours;
3765 let rest_moment = whole.moment_slope_m - ours * our_x;
3766 let (their_rest, their_rest_moment) = (
3767 their_whole - theirs,
3768 their_whole * their_cp - theirs * their_x,
3769 );
3770 assert!(
3771 (rest - their_rest).abs() <= 0.005,
3772 "{name}: {rest} {their_rest}"
3773 );
3774 assert!(
3775 (rest_moment / rest - their_rest_moment / their_rest).abs() <= 0.02 * cal,
3776 "{name}"
3777 );
3778 let center = |slope: f64, x: f64| (rest_moment + slope * x) / (rest + slope);
3779 assert!(
3782 (center(theirs, their_x) - their_cp).abs() <= 0.01 * cal,
3783 "{name} at Mach {mach}: {}",
3784 (center(theirs, their_x) - their_cp) / cal
3785 );
3786 let pi_d2 = std::f64::consts::PI * set.mean_diameter_m * set.mean_diameter_m;
3787 seen.push(TubeFinsSeen {
3788 probe: name.clone(),
3789 mach,
3790 slope_ratio: theirs / ours,
3791 over_long_ring_limit: theirs
3792 / (f64::from(set.count) * pi_d2 / model.reference_area_m2()),
3793 gap_cal: (our_cp - their_cp) / cal,
3794 center_only_cal: (center(ours, their_x) - our_cp) / cal,
3795 slope_only_cal: (center(theirs, our_x) - our_cp) / cal,
3796 });
3797 }
3798 assert!(
3799 slopes.iter().all(|s| (s / slopes[0] - 1.0).abs() <= 1e-12),
3800 "{name}: {slopes:?}"
3801 );
3802 }
3803 seen
3804 }
3805
3806 const TUBE_FIN_GAPS_CAL: [(&str, [f64; 5]); 14] = [
3809 (
3810 "3 tubes of 6 mm radius",
3811 [-2.7269, -2.7278, -2.7294, -2.2099, -2.2126],
3812 ),
3813 (
3814 "4 tubes of 6 mm radius",
3815 [-2.5611, -2.5624, -2.5648, -2.0028, -2.0068],
3816 ),
3817 (
3818 "5 tubes of 6 mm radius",
3819 [-2.3960, -2.3976, -2.4007, -1.8097, -1.8147],
3820 ),
3821 (
3822 "6 tubes of 6 mm radius",
3823 [-2.2474, -2.2493, -2.2529, -1.6410, -1.6468],
3824 ),
3825 (
3826 "8 tubes of 6 mm radius",
3827 [-2.0048, -2.0070, -2.0115, -1.3712, -1.3784],
3828 ),
3829 (
3830 "six touching tubes",
3831 [-1.0427, -1.0501, -1.0647, -0.3634, -0.3867],
3832 ),
3833 (
3834 "six touching tubes 0.025 m long",
3835 [-0.4262, -0.4237, -0.4197, -0.1844, -0.1834],
3836 ),
3837 (
3838 "six touching tubes 0.05 m long",
3839 [-0.7755, -0.7816, -0.7937, -0.3301, -0.3502],
3840 ),
3841 (
3842 "six touching tubes 0.15 m long",
3843 [-1.7202, -1.7285, -1.7448, -0.3262, -0.3518],
3844 ),
3845 (
3846 "six touching tubes 0.3 m long",
3847 [-2.9728, -2.9815, -2.9984, -0.1432, -0.1699],
3848 ),
3849 (
3850 "six touching tubes with a 0.001 m wall",
3851 [-1.0252, -1.0323, -1.0463, -0.3486, -0.3710],
3852 ),
3853 (
3854 "six touching tubes with a 0.003 m wall",
3855 [-0.8964, -0.9026, -0.9150, -0.2324, -0.2521],
3856 ),
3857 (
3858 "six tubes of 0.004 m radius",
3859 [-2.8034, -2.8039, -2.8048, -2.3076, -2.3091],
3860 ),
3861 (
3862 "six tubes of 0.008 m radius",
3863 [-1.7089, -1.7124, -1.7194, -1.0576, -1.0688],
3864 ),
3865 ];
3866
3867 #[test]
3881 fn tube_fin_cp_against_the_oracle_measured_and_pinned() {
3882 let record = tube_fin_record();
3883 let seen = tube_fins_seen(&record);
3884 let close = |found: f64, pinned: f64, what: &str| {
3885 assert!(
3886 (found - pinned).abs() <= 5e-4,
3887 "{what}: {found} against {pinned}"
3888 );
3889 };
3890 assert_eq!(seen.len(), TUBE_FIN_GAPS_CAL.len() * 5);
3892 for (probe, gaps) in TUBE_FIN_GAPS_CAL {
3893 let found: Vec<&TubeFinsSeen> = seen.iter().filter(|s| s.probe == probe).collect();
3894 assert_eq!(found.len(), gaps.len(), "{probe}");
3895 for (s, gap) in found.iter().zip(gaps) {
3896 close(s.gap_cal, gap, &format!("{probe} at Mach {}", s.mach));
3897 }
3898 }
3899 let range = |values: Vec<f64>| {
3900 let least = values.iter().copied().fold(f64::INFINITY, f64::min);
3901 (
3902 least,
3903 values.iter().copied().fold(f64::NEG_INFINITY, f64::max),
3904 )
3905 };
3906 let (least, most) = range(seen.iter().map(|s| s.slope_ratio).collect());
3908 close(least, 1.2631, "the least slope ratio");
3909 close(most, 1.8638, "the largest slope ratio");
3910 let (least, most) = range(seen.iter().map(|s| s.over_long_ring_limit).collect());
3911 close(least, 1.2038, "the least share of the long-ring limit");
3912 close(most, 1.8556, "the largest share of the long-ring limit");
3913 let per_tube: Vec<f64> = [3, 4, 5, 6, 8]
3916 .iter()
3917 .map(|count| {
3918 let asked = &record["probes"][format!("{count} tubes of 6 mm radius")]["machs"][0];
3919 let tubes = asked["components"]
3920 .as_object()
3921 .and_then(|all| all.values().find(|c| c["class"] == "TubeFinSet"))
3922 .expect("the tubes");
3923 tubes["cna_per_rad"].as_f64().expect("a slope") / f64::from(*count)
3924 })
3925 .collect();
3926 assert!(
3927 per_tube
3928 .iter()
3929 .all(|s| (s / per_tube[0] - 1.0).abs() <= 1e-15),
3930 "{per_tube:?}"
3931 );
3932 let touching = seen
3935 .iter()
3936 .find(|s| s.probe == "six touching tubes")
3937 .expect("the probe");
3938 close(
3939 touching.center_only_cal,
3940 0.4952,
3941 "OpenRocket's center alone",
3942 );
3943 close(touching.slope_only_cal, 0.5319, "OpenRocket's slope alone");
3944 let within: Vec<(&str, f64)> = seen
3948 .iter()
3949 .filter(|s| s.gap_cal.abs() <= 0.25)
3950 .map(|s| (s.probe.as_str(), s.mach))
3951 .collect();
3952 assert_eq!(
3953 within,
3954 [
3955 ("six touching tubes 0.025 m long", 0.6),
3956 ("six touching tubes 0.025 m long", 0.75),
3957 ("six touching tubes 0.3 m long", 0.6),
3958 ("six touching tubes 0.3 m long", 0.75),
3959 ("six touching tubes with a 0.003 m wall", 0.6),
3960 ]
3961 );
3962 let flights: Value = serde_json::from_str(include_str!(
3966 "../../../validation/reports/openrocket-flights.json"
3967 ))
3968 .expect("the flight record");
3969 let flight = flights["flights"]
3970 .as_array()
3971 .and_then(|all| all.iter().find(|f| f["design"] == "Tube fin rocket"))
3972 .expect("the Tube fin rocket's flight");
3973 let at = &flight["at_rod_clearance"];
3974 let number = |value: &Value| value.as_f64().expect("a number");
3975 let example = &record["example"]["machs"][0];
3976 assert_eq!(number(&example["mach"]), 0.05);
3977 let rocket = example["components"]
3978 .as_object()
3979 .and_then(|all| all.values().find(|c| c["class"] == "Rocket"))
3980 .expect("the example's rocket");
3981 let theirs = number(&at["openrocket"]["cp_from_nose_m"]);
3982 assert!((number(&rocket["cp_x_m"]) - theirs).abs() <= 1e-4);
3985 assert!(
3986 number(&at["mach"]) < 0.5,
3987 "OpenRocket's quarter-length center"
3988 );
3989 let gap = (number(&at["hpr"]["cp_from_nose_m"]) - theirs)
3990 / number(&at["openrocket"]["reference_length_m"]);
3991 close(gap, -1.0747, "the Tube fin rocket at rod clearance");
3992 }
3993
3994 fn drag_override_record() -> Value {
3996 let text = include_str!("../../../validation/fixtures/ork/openrocket-drag-override.json");
3997 let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
3998 for (name, bytes) in [
3999 (
4000 "drag_override.py",
4001 include_bytes!("../../../validation/oracles/openrocket/drag_override.py")
4002 .as_slice(),
4003 ),
4004 (
4005 "automatic_radius.py",
4006 include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
4007 .as_slice(),
4008 ),
4009 ] {
4010 assert_eq!(
4011 record["inputs_sha256"][name],
4012 crate::real_flight::sha256_hex(bytes).as_str(),
4013 "{name} changed since the record was written: rerun it"
4014 );
4015 }
4016 record
4017 }
4018
4019 fn probe_drag(document: &str, mach: f64) -> f64 {
4021 let reynolds_per_m = mach * 340.294 / 1.4607e-5;
4023 let read = ork::read(document.as_bytes()).expect("a probe reads");
4024 let layout = ork::rocket(&read.value.document)
4025 .value
4026 .layout()
4027 .expect("a probe lays out");
4028 hpr_aero::AeroModel::new(&layout)
4029 .expect("hpr models the probe")
4030 .drag(
4031 &hpr_aero::Flow::axial(mach),
4032 &hpr_aero::DragConditions::coasting(reynolds_per_m),
4033 )
4034 .expect("hpr's drag")
4035 .zero_lift_coefficient
4036 }
4037
4038 #[test]
4066 fn a_stated_drag_coefficient_moves_the_drag_as_openrocket_s() {
4067 let (fore, aft) = (0.025_f64, 0.018_f64);
4070 let relief =
4071 |mach: f64| (0.12 + 0.13 * mach * mach) * (aft / fore).powi(2) * (1.0 - aft / fore);
4072 let record = drag_override_record();
4073 let variants = record["variants"].as_object().expect("variants");
4074 assert_eq!(variants.len(), 25);
4075 let mut changes = std::collections::BTreeMap::new();
4077 for (name, variant) in variants {
4078 let airframe = &variants[variant["airframe"].as_str().expect("an airframe")];
4079 let document = variant["document"].as_str().expect("a document");
4080 let plain = airframe["document"].as_str().expect("a document");
4081 let mut rows = Vec::new();
4082 for (asked, plain_asked) in variant["machs"]
4083 .as_array()
4084 .expect("machs")
4085 .iter()
4086 .zip(airframe["machs"].as_array().expect("machs"))
4087 {
4088 let mach = asked["mach"].as_f64().expect("a Mach number");
4089 let cd = asked["rocket"]["cd"].as_f64().expect("a coefficient");
4090 let theirs = cd - plain_asked["rocket"]["cd"].as_f64().expect("a coefficient");
4091 let ours_cd = probe_drag(document, mach);
4092 rows.push((mach, ours_cd, cd, ours_cd - probe_drag(plain, mach), theirs));
4093 }
4094 changes.insert(name.as_str(), rows);
4095 }
4096 let gap_of = |name: &str, at: usize| {
4097 let (_, _, _, ours, theirs) = changes[name][at];
4098 ours - theirs
4099 };
4100 let mut largest_body_gap: f64 = 0.0;
4101 for (name, rows) in &changes {
4102 let exact = ["the stage at 0.5", "the inner tube", "the ring", "the mass"]
4103 .iter()
4104 .any(|part| name.ends_with(&format!("{part} at 0.5")) || name.ends_with(part));
4105 let lugs_or_buttons = name.contains("the lugs") || name.contains("the buttons");
4106 let subsonic_only = name.contains("the nose") || name.contains("the boattail at");
4107 for (at, &(mach, ours_cd, theirs_cd, ours, theirs)) in rows.iter().enumerate() {
4108 let mut gap = ours - theirs;
4109 let what =
4110 format!("{name} at Mach {mach}: hpr {ours:+.5}, OpenRocket {theirs:+.5}");
4111 if *name == "flare, the stage at 0.5 with its children" {
4112 assert!((ours_cd - 0.5).abs() <= 1e-12, "{what}: hpr {ours_cd}");
4113 assert!(
4114 (theirs_cd - 0.5).abs() <= 1e-12,
4115 "{what}: OpenRocket {theirs_cd}"
4116 );
4117 continue;
4118 }
4119 if *name == "flare, the tube at 0.5 with its children" {
4120 gap -= gap_of("flare, the lugs at 0.5", at)
4121 + gap_of("flare, the buttons at 0.5", at);
4122 }
4123 if *name == "boattail, the boattail at 0.2" && mach <= 0.8 {
4124 gap -= relief(mach);
4125 }
4126 if exact {
4127 assert!(gap.abs() <= 1e-9, "{what}");
4128 } else if name.contains("the fins") {
4129 assert!(gap.abs() <= 1e-4, "{what}");
4130 } else if lugs_or_buttons {
4131 assert!(gap.abs() <= 0.075, "{what}");
4132 } else if mach <= 0.6 || !subsonic_only {
4133 assert!(gap.abs() <= 0.0065, "{what}");
4134 largest_body_gap = largest_body_gap.max(gap.abs());
4135 }
4136 }
4137 }
4138 assert!(
4139 (largest_body_gap - 0.0059).abs() < 1e-4,
4140 "{largest_body_gap}"
4141 );
4142 }
4143
4144 fn nose_pressure_drag_record() -> Value {
4146 let text =
4147 include_str!("../../../validation/fixtures/ork/openrocket-nose-pressure-drag.json");
4148 let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
4149 for (name, bytes) in [
4150 (
4151 "nose_pressure_drag.py",
4152 include_bytes!("../../../validation/oracles/openrocket/nose_pressure_drag.py")
4153 .as_slice(),
4154 ),
4155 (
4156 "automatic_radius.py",
4157 include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
4158 .as_slice(),
4159 ),
4160 ] {
4161 assert_eq!(
4162 record["inputs_sha256"][name],
4163 crate::real_flight::sha256_hex(bytes).as_str(),
4164 "{name} changed since the record was written: rerun it"
4165 );
4166 }
4167 record
4168 }
4169
4170 fn probe_part_pressure_drag(document: &str, id: &str, mach: f64, area_m2: f64) -> f64 {
4173 let reynolds_per_m = mach * 340.294 / 1.4607e-5;
4175 let read = ork::read(document.as_bytes()).expect("a probe reads");
4176 let layout = ork::rocket(&read.value.document)
4177 .value
4178 .layout()
4179 .expect("a probe lays out");
4180 let model = hpr_aero::AeroModel::new(&layout).expect("hpr models the probe");
4181 let parts = model
4182 .buildup_components(
4183 &hpr_aero::Flow::axial(mach),
4184 &hpr_aero::DragConditions::coasting(reynolds_per_m),
4185 )
4186 .expect("hpr's drag by part");
4187 let mut found = parts.iter().filter(|part| part.id == id);
4188 let part = found.next().expect("the part is in the buildup");
4189 assert!(found.next().is_none(), "one part of that id");
4190 part.drag.pressure * model.reference_area_m2() / area_m2
4191 }
4192
4193 fn probe_nose(document: &str, id: &str) -> (hpr_design::NoseCone, f64) {
4196 let read = ork::read(document.as_bytes()).expect("a probe reads");
4197 let layout = ork::rocket(&read.value.document)
4198 .value
4199 .layout()
4200 .expect("a probe lays out");
4201 let nose = layout
4202 .components
4203 .iter()
4204 .find_map(|placed| match &placed.part {
4205 Part::NoseCone(nose) if placed.id == id => Some(nose.clone()),
4206 _ => None,
4207 })
4208 .expect("the nose");
4209 let widest_m = layout
4210 .components
4211 .iter()
4212 .filter_map(|placed| match &placed.part {
4213 Part::Transition(transition) => Some(transition.aft_radius_m),
4214 _ => None,
4215 })
4216 .fold(0.0, f64::max);
4217 (nose, widest_m)
4218 }
4219
4220 #[test]
4245 fn a_tangent_ogive_s_pressure_drag_past_mach_1_beside_openrocket_24_12_s() {
4246 let record = nose_pressure_drag_record();
4247 assert_eq!(record["openrocket"], "24.12");
4248 assert_eq!(
4249 record["cites"],
4250 "https://github.com/openrocket/openrocket/issues/3391"
4251 );
4252 let number = |value: &Value| value.as_f64().expect("a number");
4253 let nose = record["nose_id"].as_str().expect("the nose's id");
4254 let base_area_m2 = number(&record["nose_base_area_m2"]);
4255 let fineness =
4256 number(&record["nose_length_m"]) / (2.0 * (base_area_m2 / std::f64::consts::PI).sqrt());
4257 assert!((fineness - 3.0).abs() < 1e-12, "fineness {fineness}");
4258 let sin_half_angle = 1.0 / (1.0 + 4.0 * fineness * fineness).sqrt();
4259 let equivalent_cone = |mach: f64| {
4260 2.1 * sin_half_angle * sin_half_angle
4261 + 0.5 * sin_half_angle / (mach * mach - 1.0).sqrt()
4262 };
4263 let designs = record["designs"].as_object().expect("designs");
4264 assert_eq!(
4265 designs.keys().map(String::as_str).collect::<Vec<_>>(),
4266 ["cone", "cone, wider body", "tangent ogive"]
4267 );
4268 let pinned = [
4273 (1.3, 0.155_71, 0.155_71, 0.000_98, -4.8e-6, 1e-7),
4274 (1.5, 0.130_28, 0.130_28, 0.000_73, 0.0, 1e-12),
4275 (2.0, 0.104_21, 0.104_21, 0.000_47, 0.0, 1e-12),
4276 ];
4277 let rows = |design: &str, area_ratio: f64| {
4280 let design = &designs[design];
4281 let document = design["document"].as_str().expect("a document").to_owned();
4282 let machs = design["machs"].as_array().expect("machs").clone();
4283 assert_eq!(machs.len(), pinned.len(), "one row a Mach number");
4284 for (row, pin) in machs.iter().zip(&pinned) {
4285 assert!((number(&row["mach"]) - pin.0).abs() < 1e-12);
4286 let ratio = number(&row["reference_area_m2"]) / base_area_m2;
4287 assert!((ratio - area_ratio).abs() < 1e-12, "area ratio {ratio}");
4288 }
4289 (document, machs)
4290 };
4291 let (ogive, ogive_rows) = rows("tangent ogive", 1.0);
4292 let (cone, cone_rows) = rows("cone", 1.0);
4293 let (wide, wide_rows) = rows("cone, wider body", 2.56);
4294 for (document, shape, widest_m) in [
4298 (
4299 &ogive,
4300 hpr_design::NoseShape::Ogive { radius_ratio: 1.0 },
4301 0.0,
4302 ),
4303 (&cone, hpr_design::NoseShape::Conical {}, 0.0),
4304 (&wide, hpr_design::NoseShape::Conical {}, 0.04),
4305 ] {
4306 let (read, read_widest_m) = probe_nose(document, nose);
4307 assert_eq!(read.shape, shape);
4308 assert!((read.length_m - number(&record["nose_length_m"])).abs() < 1e-12);
4309 let read_base_m2 = std::f64::consts::PI * read.base_radius_m * read.base_radius_m;
4310 assert!((read_base_m2 - base_area_m2).abs() < 1e-12);
4311 assert!(
4312 (read_widest_m - widest_m).abs() < 1e-12,
4313 "the body widens to {read_widest_m} m"
4314 );
4315 }
4316 let column = |row: &Value| number(&row["components"][nose]["pressure"]);
4318 let theirs = |row: &Value| column(row) * number(&row["reference_area_m2"]) / base_area_m2;
4319 for (at, (mach, cone_pin, ours_pin, theirs_pin, cone_gap_pin, cone_gap_within)) in
4320 pinned.into_iter().enumerate()
4321 {
4322 let closed_form = equivalent_cone(mach);
4323 assert!(
4324 (closed_form - cone_pin).abs() < 5e-6,
4325 "{mach}: {closed_form}"
4326 );
4327
4328 let ours = probe_part_pressure_drag(&ogive, nose, mach, base_area_m2);
4330 assert!((ours - ours_pin).abs() < 5e-6, "hpr at Mach {mach}: {ours}");
4331 assert!(
4332 (ours - closed_form).abs() < 1e-12,
4333 "hpr at Mach {mach}: {ours}"
4334 );
4335 for document in [&cone, &wide] {
4336 let ours_cone = probe_part_pressure_drag(document, nose, mach, base_area_m2);
4337 assert!(
4338 (ours_cone - closed_form).abs() < 1e-12,
4339 "hpr's cone at Mach {mach}: {ours_cone}"
4340 );
4341 }
4342
4343 let cone_gap = theirs(&cone_rows[at]) - closed_form;
4346 assert!(
4347 (cone_gap - cone_gap_pin).abs() < cone_gap_within,
4348 "OpenRocket's cone at Mach {mach}: {cone_gap:e} from the closed form"
4349 );
4350 let wide_column = column(&wide_rows[at]);
4353 assert!(
4354 (wide_column * 2.56 - column(&cone_rows[at])).abs() < 1e-12,
4355 "OpenRocket's cone on the wider body at Mach {mach}: {wide_column}"
4356 );
4357 let wide_gap = theirs(&wide_rows[at]) - closed_form;
4358 assert!(
4359 (wide_gap - cone_gap_pin).abs() < cone_gap_within,
4360 "OpenRocket's cone on the wider body at Mach {mach}: {wide_gap:e}"
4361 );
4362
4363 let their_ogive = theirs(&ogive_rows[at]);
4365 assert!(
4366 (their_ogive - theirs_pin).abs() < 5e-6,
4367 "OpenRocket's tangent ogive at Mach {mach}: {their_ogive}"
4368 );
4369 assert!(
4370 their_ogive > 0.0 && their_ogive < 0.01 * closed_form,
4371 "OpenRocket's tangent ogive at Mach {mach}: {their_ogive} of {closed_form}"
4372 );
4373 }
4374 }
4375
4376 fn nose_pressure_drag_transonic_record() -> Value {
4378 let text = include_str!(
4379 "../../../validation/fixtures/ork/openrocket-nose-pressure-drag-transonic.json"
4380 );
4381 let record: Value = serde_json::from_str(text).expect("the committed record is JSON");
4382 for (name, bytes) in [
4383 (
4384 "nose_pressure_drag_transonic.py",
4385 include_bytes!(
4386 "../../../validation/oracles/openrocket/nose_pressure_drag_transonic.py"
4387 )
4388 .as_slice(),
4389 ),
4390 (
4391 "nose_pressure_drag.py",
4392 include_bytes!("../../../validation/oracles/openrocket/nose_pressure_drag.py")
4393 .as_slice(),
4394 ),
4395 (
4396 "automatic_radius.py",
4397 include_bytes!("../../../validation/oracles/openrocket/automatic_radius.py")
4398 .as_slice(),
4399 ),
4400 ] {
4401 assert_eq!(
4402 record["inputs_sha256"][name],
4403 crate::real_flight::sha256_hex(bytes).as_str(),
4404 "{name} changed since the record was written: rerun it"
4405 );
4406 }
4407 record
4408 }
4409
4410 #[test]
4431 fn a_tangent_ogive_s_pressure_drag_from_mach_1_to_1_3_beside_openrocket_24_12_s() {
4432 let record = nose_pressure_drag_transonic_record();
4433 let first = nose_pressure_drag_record();
4434 assert_eq!(record["openrocket"], "24.12");
4435 for key in [
4436 "nose_id",
4437 "nose_length_m",
4438 "nose_base_area_m2",
4439 "cites",
4440 "jar_sha256",
4441 "java",
4442 ] {
4443 assert_eq!(record[key], first[key], "{key}");
4444 }
4445 let number = |value: &Value| value.as_f64().expect("a number");
4446 let nose = record["nose_id"].as_str().expect("the nose's id");
4447 let base_area_m2 = number(&record["nose_base_area_m2"]);
4448 let designs = record["designs"].as_object().expect("designs");
4449 assert_eq!(
4450 designs.keys().map(String::as_str).collect::<Vec<_>>(),
4451 ["cone", "tangent ogive"]
4452 );
4453 for name in ["cone", "tangent ogive"] {
4456 assert_eq!(
4457 designs[name]["document"],
4458 first["designs"][name]["document"]
4459 );
4460 }
4461 let rows = |name: &str| designs[name]["machs"].as_array().expect("machs").clone();
4462 let (ogive_rows, cone_rows) = (rows("tangent ogive"), rows("cone"));
4463 assert_eq!((ogive_rows.len(), cone_rows.len()), (31, 31));
4464 let column = |row: &Value| number(&row["components"][nose]["pressure"]);
4465 for (step, (ogive_row, cone_row)) in ogive_rows.iter().zip(&cone_rows).enumerate() {
4466 for row in [ogive_row, cone_row] {
4467 let mach = 1.0 + 0.01 * step as f64;
4468 assert!((number(&row["mach"]) - mach).abs() < 1e-12);
4469 assert!((number(&row["reference_area_m2"]) - base_area_m2).abs() < 1e-15);
4470 }
4471 }
4472 let first_at_1_3 = |name: &str| first["designs"][name]["machs"][0].clone();
4474 assert_eq!(number(&first_at_1_3("cone")["mach"]), 1.3);
4475 assert_eq!(
4476 column(&ogive_rows[30]),
4477 column(&first_at_1_3("tangent ogive"))
4478 );
4479 assert_eq!(column(&cone_rows[30]), column(&first_at_1_3("cone")));
4480
4481 let document = |name: &str| designs[name]["document"].as_str().expect("a document");
4482 let (ogive, cone) = (document("tangent ogive"), document("cone"));
4483 let at_1 = probe_part_pressure_drag(cone, nose, 1.0, base_area_m2);
4485 assert!((at_1 - 37_f64.sqrt().recip()).abs() < 1e-12, "{at_1}");
4486 let (mut least_gap, mut most_gap) = (f64::INFINITY, f64::NEG_INFINITY);
4487 let mut least_share = (f64::INFINITY, 0.0);
4488 let mut most_share = (f64::NEG_INFINITY, 0.0);
4489 let (mut odd_gap, mut odd_share, mut odd_at) = (0.0_f64, 0.0_f64, 0.0);
4490 let mut highest = (f64::NEG_INFINITY, 0.0);
4491 for (step, (ogive_row, cone_row)) in ogive_rows.iter().zip(&cone_rows).enumerate() {
4492 let mach = number(&ogive_row["mach"]);
4493 let ours = probe_part_pressure_drag(ogive, nose, mach, base_area_m2);
4494 let ours_cone = probe_part_pressure_drag(cone, nose, mach, base_area_m2);
4495 assert_eq!(ours, ours_cone, "hpr's ogive is its cone at Mach {mach}");
4496 if ours > highest.0 {
4497 highest = (ours, mach);
4498 }
4499 let cone_gap = column(cone_row) - ours_cone;
4502 if step % 2 == 0 {
4503 assert!(cone_gap.abs() < 5e-6, "Mach {mach}: {cone_gap:e}");
4504 } else {
4505 for rows in [&ogive_rows, &cone_rows] {
4506 let mean = 0.5 * (column(&rows[step - 1]) + column(&rows[step + 1]));
4507 let off = column(&rows[step]) - mean;
4508 assert!(off.abs() < 1e-15, "Mach {mach}: {off:e} from the mean");
4509 }
4510 if cone_gap.abs() > odd_gap {
4511 (odd_gap, odd_at) = (cone_gap.abs(), mach);
4512 }
4513 odd_share = odd_share.max(cone_gap.abs() / ours_cone);
4514 }
4515 let gap = ours - column(ogive_row);
4517 assert!(gap > 0.0, "Mach {mach}");
4518 least_gap = least_gap.min(gap);
4519 most_gap = most_gap.max(gap);
4520 let share = column(ogive_row) / ours;
4521 if share < least_share.0 {
4522 least_share = (share, mach);
4523 }
4524 if share > most_share.0 {
4525 most_share = (share, mach);
4526 }
4527 }
4528 assert!((odd_gap - 0.000_94).abs() < 5e-6, "{odd_gap}");
4529 assert!((odd_at - 1.01_f64).abs() < 1e-12, "{odd_at}");
4530 assert!((highest.1 - 1.1_f64).abs() < 1e-12, "{highest:?}");
4531 assert!((odd_share - 0.0053).abs() < 5e-5, "{odd_share}");
4532 let share_at_1 = column(&ogive_rows[0]) / at_1;
4533 assert!((share_at_1 - 0.0099).abs() < 5e-5, "{share_at_1}");
4534 assert!((least_gap - 0.1547).abs() < 1e-4, "{least_gap}");
4535 assert!((most_gap - 0.1628).abs() < 1e-4, "{most_gap}");
4536 assert!((least_share.0 - 0.0063).abs() < 1e-4, "{least_share:?}");
4537 assert!((least_share.1 - 1.3_f64).abs() < 1e-12, "{least_share:?}");
4538 assert!((most_share.0 - 0.3223).abs() < 1e-4, "{most_share:?}");
4539 assert!((most_share.1 - 1.1_f64).abs() < 1e-12, "{most_share:?}");
4540
4541 let shown = [
4544 (1.0, 0.164_40, 0.001_62, 0.164_40),
4545 (1.05, 0.218_16, 0.058_58, 0.217_41),
4546 (1.1, 0.234_28, 0.075_51, 0.234_27),
4547 (1.15, 0.224_41, 0.063_54, 0.224_12),
4548 (1.2, 0.200_24, 0.038_24, 0.200_24),
4549 (1.25, 0.173_45, 0.012_94, 0.173_63),
4550 (1.3, 0.155_71, 0.000_98, 0.155_71),
4551 ];
4552 for (mach, ours_pin, ogive_pin, cone_pin) in shown {
4553 let at = ((mach - 1.0) / 0.01_f64).round() as usize;
4554 assert!((number(&ogive_rows[at]["mach"]) - mach).abs() < 1e-12);
4555 let ours = probe_part_pressure_drag(ogive, nose, mach, base_area_m2);
4556 assert!((ours - ours_pin).abs() < 5e-6, "hpr at Mach {mach}: {ours}");
4557 let theirs = column(&ogive_rows[at]);
4558 assert!(
4559 (theirs - ogive_pin).abs() < 5e-6,
4560 "OpenRocket at Mach {mach}: {theirs}"
4561 );
4562 let theirs_cone = column(&cone_rows[at]);
4563 assert!(
4564 (theirs_cone - cone_pin).abs() < 5e-6,
4565 "OpenRocket's cone at Mach {mach}: {theirs_cone}"
4566 );
4567 }
4568 }
4569}