1use serde::{Deserialize, Serialize};
45
46use std::borrow::Cow;
47use std::collections::BTreeSet;
48
49use crate::bundled;
50use crate::class::ImpulseClass;
51use crate::curve::ThrustCurve;
52use crate::delay::DelayList;
53use crate::error::MotorError;
54use crate::motor::SolidMotor;
55use crate::{eng, rse};
56
57static BUNDLED_INDEX: &str = bundled::CATALOG_JSON;
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub struct Catalog {
64 pub source: String,
66 pub snapshot: Snapshot,
68 pub selection: String,
70 pub motors: Vec<CatalogMotor>,
72 #[serde(default)]
74 pub left_out: Vec<LeftOut>,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct LeftOut {
81 pub simfile_id: String,
83 pub motor_id: String,
85 pub reason: String,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct Snapshot {
93 pub files_url: String,
95 pub captured: String,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
101#[non_exhaustive]
102pub enum MotorType {
103 #[serde(rename = "SU")]
105 SingleUse,
106 #[serde(rename = "reload")]
108 Reload,
109 #[serde(rename = "hybrid")]
112 Hybrid,
113}
114
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117pub struct CatalogMotor {
118 pub motor_id: String,
120 pub manufacturer: String,
122 pub manufacturer_abbrev: String,
124 pub designation: String,
126 pub common_name: String,
128 pub impulse_class: ImpulseClass,
130 pub motor_type: MotorType,
132 pub case_info: Option<String>,
134 pub prop_info: Option<String>,
136 pub delays: Option<String>,
139 pub diameter_mm: f64,
141 pub length_mm: f64,
143 pub total_impulse_ns: f64,
145 pub average_thrust_n: f64,
147 pub max_thrust_n: Option<f64>,
149 pub burn_time_s: f64,
151 pub propellant_mass_g: Option<f64>,
153 pub total_mass_g: Option<f64>,
155 pub stated: StatedFigures,
158 pub curves: Vec<CatalogCurve>,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
172pub struct StatedFigures {
173 pub total_impulse_ns: f64,
175 pub average_thrust_n: f64,
177 pub burn_time_s: f64,
179 pub max_thrust_n: Option<f64>,
181 #[serde(default)]
185 pub propellant_mass_g: Option<f64>,
186 #[serde(default)]
190 pub total_mass_g: Option<f64>,
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
196#[serde(rename_all = "snake_case")]
197#[non_exhaustive]
198pub enum MotorWarningKind {
199 FailedCheck,
202 LightPropellant,
205 HeavyLoadedMass,
207 LightLoadedMass,
209 BurnoutMass,
212 PropellantShare,
214}
215
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218#[non_exhaustive]
219pub struct MotorWarning {
220 pub kind: MotorWarningKind,
222 pub message: String,
224}
225
226impl MotorWarning {
227 fn new(kind: MotorWarningKind, message: String) -> Self {
228 Self { kind, message }
229 }
230}
231
232#[derive(Debug, Clone, Copy)]
234struct FlownMasses {
235 propellant_g: f64,
236 total_g: f64,
237}
238
239pub const LOADED_MASS_BOUND: f64 = 0.05;
246
247pub const BURNOUT_MASS_BOUND: f64 = 0.05;
268
269fn within_share(gap_g: f64, record_g: f64, bound: f64) -> bool {
272 gap_g.abs() <= bound * record_g
273}
274
275pub const PROPELLANT_SHARE_SPAN: (f64, f64) = (2.1 / 18.2, 0.75);
280
281pub const PROPELLANT_SHORT_BOUND: f64 = 0.05;
287
288pub const CHECK_BOUND: f64 = 0.01;
294
295pub const BORE_TOLERANCE_MM: f64 = 1.0;
302
303#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
313pub struct CurveCheck {
314 pub total_impulse_ns: f64,
316 pub average_thrust_n: f64,
318 pub burn_time_s: f64,
320 pub passes: bool,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
326#[serde(rename_all = "snake_case")]
327#[non_exhaustive]
328pub enum CheckedFigure {
329 TotalImpulse,
331 AverageThrust,
333 BurnTime,
335}
336
337impl CheckedFigure {
338 pub fn name(self) -> &'static str {
340 match self {
341 Self::TotalImpulse => "total impulse",
342 Self::AverageThrust => "average thrust",
343 Self::BurnTime => "burn time",
344 }
345 }
346}
347
348#[derive(Debug, Clone, Copy, PartialEq)]
350pub struct FigureGap {
351 pub figure: CheckedFigure,
353 pub file: f64,
355 pub stated: f64,
357}
358
359impl FigureGap {
360 pub fn relative(&self) -> f64 {
363 (self.file - self.stated) / self.stated
364 }
365
366 pub fn percent_text(&self) -> String {
371 let percent = 100.0 * self.relative();
372 let mut decimals = 2;
373 let mut text = format!("{percent:+.decimals$}%");
374 if self.within_bound() {
375 return text;
376 }
377 if self.stated.is_nan() || self.stated <= 0.0 {
378 return "n/a".to_owned();
379 }
380 while decimals < 17 && rounds_inside(&text) {
381 decimals += 1;
382 text = format!("{percent:+.decimals$}%");
383 }
384 if rounds_inside(&text) {
387 let over = if self.file > self.stated {
388 ">+1%"
389 } else {
390 "<-1%"
391 };
392 return over.to_owned();
393 }
394 text
395 }
396
397 pub fn within_bound(&self) -> bool {
401 self.stated > 0.0 && (self.file - self.stated).abs() <= CHECK_BOUND * self.stated
402 }
403}
404
405fn rounds_inside(text: &str) -> bool {
407 text.trim_start_matches(['+', '-'])
408 .trim_end_matches('%')
409 .parse::<f64>()
410 .is_ok_and(|magnitude| magnitude <= 100.0 * CHECK_BOUND)
411}
412
413impl CurveCheck {
414 pub fn of(thrust: &ThrustCurve, stated: &StatedFigures) -> Self {
416 let mut check = Self {
417 total_impulse_ns: thrust.total_impulse_ns(),
418 average_thrust_n: thrust.average_thrust_n(),
419 burn_time_s: thrust.burn_time_s(),
420 passes: false,
421 };
422 check.passes = check.gaps(stated).iter().all(FigureGap::within_bound);
423 check
424 }
425
426 pub fn gaps(&self, stated: &StatedFigures) -> [FigureGap; 3] {
428 [
429 FigureGap {
430 figure: CheckedFigure::TotalImpulse,
431 file: self.total_impulse_ns,
432 stated: stated.total_impulse_ns,
433 },
434 FigureGap {
435 figure: CheckedFigure::AverageThrust,
436 file: self.average_thrust_n,
437 stated: stated.average_thrust_n,
438 },
439 FigureGap {
440 figure: CheckedFigure::BurnTime,
441 file: self.burn_time_s,
442 stated: stated.burn_time_s,
443 },
444 ]
445 }
446}
447
448#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
451pub struct CatalogCurve {
452 pub simfile_id: String,
454 pub format: CurveFormat,
456 pub source: CurveSource,
458 #[serde(default)]
460 pub license: CurveLicense,
461 pub file: String,
463 pub sha256: String,
465 pub url: String,
467 pub info_url: Option<String>,
469 pub retrieved: String,
471 pub check: CurveCheck,
473}
474
475#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
477#[non_exhaustive]
478pub enum CurveFormat {
479 #[serde(rename = "RASP")]
481 Rasp,
482 #[serde(rename = "RockSim")]
484 RockSim,
485}
486
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
489#[non_exhaustive]
490pub enum CurveSource {
491 #[serde(rename = "cert")]
493 Certification,
494 #[serde(rename = "mfr")]
496 Manufacturer,
497 #[serde(rename = "user")]
499 User,
500}
501
502#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
505#[non_exhaustive]
506pub enum CurveLicense {
507 #[serde(rename = "PD")]
509 PublicDomain,
510 #[serde(rename = "free")]
512 Free,
513 #[serde(rename = "other")]
515 Other,
516 #[default]
518 #[serde(rename = "unknown", alias = "")]
519 Unknown,
520}
521
522impl CurveLicense {
523 pub fn is_bundleable(self) -> bool {
532 self != Self::Other
533 }
534}
535
536impl Catalog {
537 pub fn bundled() -> Result<&'static Self, MotorError> {
549 static BUNDLED: std::sync::OnceLock<Result<Catalog, MotorError>> =
551 std::sync::OnceLock::new();
552 BUNDLED
553 .get_or_init(|| Self::from_json(BUNDLED_INDEX))
554 .as_ref()
555 .map_err(Clone::clone)
556 }
557
558 pub fn from_json(text: &str) -> Result<Self, MotorError> {
566 let catalog: Self =
567 serde_json::from_str(text).map_err(|error| MotorError::Catalog(error.to_string()))?;
568 catalog.motors.iter().try_for_each(stored_passes_hold)?;
569 Ok(catalog)
570 }
571
572 pub fn bundled_named<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Self, MotorError> {
583 let keys: BTreeSet<String> = names.into_iter().map(normalize).collect();
584 Self::narrowed(BUNDLED_INDEX, &|motor| {
585 keys.iter().any(|key| {
586 normalized_is(&motor.designation, key) || normalized_is(&motor.common_name, key)
587 })
588 })
589 }
590
591 pub fn bundled_with_ids<'a>(
598 ids: impl IntoIterator<Item = &'a str>,
599 ) -> Result<Self, MotorError> {
600 let ids: BTreeSet<&str> = ids.into_iter().collect();
601 Self::narrowed(BUNDLED_INDEX, &|motor| {
602 ids.contains(motor.motor_id.as_ref())
603 })
604 }
605
606 pub fn bundled_snapshot() -> Result<Snapshot, MotorError> {
613 match snapshot_in_head(BUNDLED_INDEX) {
614 Some(snapshot) => Ok(snapshot),
615 None => Self::bundled().map(|catalog| catalog.snapshot.clone()),
616 }
617 }
618
619 fn narrowed(text: &str, keep: &dyn Fn(&MotorKeys<'_>) -> bool) -> Result<Self, MotorError> {
624 let invalid = |what: String| MotorError::Catalog(what);
625 let not_laid_out =
626 || invalid("the index isn't laid out as JSON's pretty writer does".to_owned());
627 let (head, rest) = text.split_once("\"motors\":").ok_or_else(not_laid_out)?;
628 let head = format!(
629 "{}}}",
630 head.trim_end().strip_suffix(',').ok_or_else(not_laid_out)?
631 );
632 let head: IndexHead =
633 serde_json::from_str(&head).map_err(|error| invalid(error.to_string()))?;
634 let mut motors = Vec::new();
635 const END: &str = "\n }";
639 let ends = memchr::memmem::Finder::new(END);
640 let mut left = rest;
641 loop {
642 let end = ends.find(left.as_bytes()).ok_or_else(not_laid_out)?;
644 let entry = left
645 .find('{')
646 .and_then(|start| left.get(start..end + END.len()))
647 .ok_or_else(not_laid_out)?;
648 let keys = MotorKeys::in_lines(entry).ok_or_else(not_laid_out)?;
649 if keep(&keys) {
650 let motor: CatalogMotor =
651 serde_json::from_str(entry).map_err(|error| invalid(error.to_string()))?;
652 stored_passes_hold(&motor)?;
653 motors.push(motor);
654 }
655 left = &left[end + END.len()..];
656 if !left.starts_with(',') {
658 break;
659 }
660 }
661 Ok(Self {
662 source: head.source,
663 snapshot: head.snapshot,
664 selection: head.selection,
665 motors,
666 left_out: Vec::new(),
667 })
668 }
669
670 pub fn find<'a>(&'a self, name: &str) -> impl Iterator<Item = &'a CatalogMotor> + 'a {
684 let (maker, rest) = self.maker_and_name(name);
685 self.named(rest, |motor| {
686 maker.is_none_or(|maker| maker == motor.manufacturer)
687 })
688 }
689
690 pub fn find_by_maker<'a>(
695 &'a self,
696 maker: &str,
697 name: &str,
698 ) -> impl Iterator<Item = &'a CatalogMotor> + 'a {
699 let maker = maker_key(maker);
700 self.named(name, move |motor| {
701 maker_key(&motor.manufacturer) == maker
702 || maker_key(&motor.manufacturer_abbrev) == maker
703 })
704 }
705
706 pub fn find_for_design<'a>(
717 &'a self,
718 maker: &str,
719 name: &str,
720 digest: Option<&str>,
721 diameter_mm: Option<f64>,
722 ) -> Vec<&'a CatalogMotor> {
723 let maker = maker_key(maker);
724 let of = |motor: &CatalogMotor| {
725 maker_key(&motor.manufacturer) == maker
726 || maker_key(&motor.manufacturer_abbrev) == maker
727 };
728 let all = self.matching(name, of);
729 if let Some(id) = digest.and_then(crate::openrocket_curves::file_for) {
730 let owners: Vec<&CatalogMotor> = all
731 .iter()
732 .copied()
733 .filter(|motor| motor.curves.iter().any(|curve| curve.simfile_id == id))
734 .collect();
735 if let [owner] = owners[..] {
736 return vec![owner];
737 }
738 }
739 let picked = prefer_designations(all.clone(), name);
740 let fits = |motor: &&CatalogMotor| {
741 diameter_mm.is_some_and(|mm| (motor.diameter_mm - mm).abs() <= 1.0)
742 };
743 let misfit = diameter_mm.is_some() && !picked.iter().any(fits);
744 if misfit
745 && all
746 .iter()
747 .any(|motor| fits(motor) && !picked.iter().any(|kept| std::ptr::eq(*kept, *motor)))
748 {
749 return all;
750 }
751 picked
752 }
753
754 pub fn find_for_bore<'a>(&'a self, name: &str, bore_mm: f64) -> Vec<&'a CatalogMotor> {
767 let (maker, rest) = self.maker_and_name(name);
768 let all = self.matching(rest, |motor| {
769 maker.is_none_or(|maker| maker == motor.manufacturer)
770 });
771 let picked = prefer_designations(all.clone(), rest);
772 let room = |motor: &CatalogMotor| {
773 (motor.diameter_mm <= bore_mm + BORE_TOLERANCE_MM)
774 .then_some(bore_mm - motor.diameter_mm)
775 };
776 let best = picked
777 .iter()
778 .filter_map(|motor| room(motor))
779 .fold(f64::INFINITY, f64::min);
780 let closer = all.iter().any(|motor| {
781 !picked.iter().any(|kept| std::ptr::eq(*kept, *motor))
782 && room(motor).is_some_and(|room| room + BORE_TOLERANCE_MM < best)
783 });
784 if closer { all } else { picked }
785 }
786
787 fn named<'a>(
790 &'a self,
791 name: &str,
792 of: impl Fn(&CatalogMotor) -> bool,
793 ) -> std::vec::IntoIter<&'a CatalogMotor> {
794 prefer_designations(self.matching(name, of), name).into_iter()
795 }
796
797 fn matching(&self, name: &str, of: impl Fn(&CatalogMotor) -> bool) -> Vec<&CatalogMotor> {
799 let key = normalize(name);
800 self.motors
801 .iter()
802 .filter(|motor| {
803 of(motor)
804 && (normalized_is(&motor.designation, &key)
805 || normalized_is(&motor.common_name, &key))
806 })
807 .collect()
808 }
809
810 fn maker_and_name<'a>(&'a self, name: &'a str) -> (Option<&'a str>, &'a str) {
813 let name = name.trim();
814 let mut best: Option<(&str, &str, usize)> = None;
815 for motor in &self.motors {
816 for said in [&motor.manufacturer, &motor.manufacturer_abbrev] {
817 let Some(head) = name.get(..said.len()) else {
818 continue;
819 };
820 let rest = &name[said.len()..];
821 if head.eq_ignore_ascii_case(said)
822 && rest.starts_with(char::is_whitespace)
823 && best.is_none_or(|(_, _, length)| said.len() > length)
824 {
825 best = Some((motor.manufacturer.as_str(), rest.trim_start(), said.len()));
826 }
827 }
828 }
829 best.map_or((None, name), |(maker, rest, _)| (Some(maker), rest))
830 }
831
832 pub fn selector(&self, motor: &CatalogMotor) -> String {
835 let alone = self.find(&motor.designation).count() == 1;
836 if alone {
837 motor.designation.clone()
838 } else {
839 format!("{} {}", motor.manufacturer_abbrev, motor.designation)
840 }
841 }
842}
843
844fn prefer_designations<'a>(matches: Vec<&'a CatalogMotor>, name: &str) -> Vec<&'a CatalogMotor> {
848 let key = normalize(name);
849 let exact = |motor: &CatalogMotor| normalize(&motor.designation) == key;
850 let makers_with_exact: Vec<&str> = matches
851 .iter()
852 .filter(|motor| exact(motor))
853 .map(|motor| motor.manufacturer.as_str())
854 .collect();
855 matches
856 .into_iter()
857 .filter(|motor| exact(motor) || !makers_with_exact.contains(&motor.manufacturer.as_str()))
858 .collect()
859}
860
861fn maker_key(text: &str) -> String {
865 let key: String = text
866 .chars()
867 .filter(char::is_ascii_alphanumeric)
868 .map(|c| c.to_ascii_lowercase())
869 .collect();
870 ["inc", "ltd", "llc"]
871 .iter()
872 .find_map(|suffix| key.strip_suffix(suffix).filter(|rest| !rest.is_empty()))
873 .map_or_else(|| key.clone(), str::to_owned)
874}
875
876fn normalized_is(name: &str, key: &str) -> bool {
880 name.chars()
881 .filter(|c| !c.is_whitespace() && *c != '-')
882 .map(|c| c.to_ascii_lowercase())
883 .eq(key.chars())
884}
885
886fn snapshot_in_head(text: &str) -> Option<Snapshot> {
889 #[derive(Deserialize)]
890 struct Head {
891 snapshot: Snapshot,
892 }
893 let (head, _) = text.split_once("\"motors\":")?;
894 let head = format!("{}}}", head.trim_end().strip_suffix(',')?);
895 serde_json::from_str::<Head>(&head)
896 .ok()
897 .map(|head| head.snapshot)
898}
899
900#[derive(Deserialize)]
902struct IndexHead {
903 source: String,
904 snapshot: Snapshot,
905 selection: String,
906}
907
908struct MotorKeys<'a> {
911 motor_id: Cow<'a, str>,
912 designation: Cow<'a, str>,
913 common_name: Cow<'a, str>,
914}
915
916impl<'a> MotorKeys<'a> {
917 fn in_lines(entry: &'a str) -> Option<Self> {
919 let field = |key: &str| -> Option<Cow<'a, str>> {
920 let (_, value) = entry.split_once(key)?;
921 let line = value.split('\n').next()?;
922 let line = line.strip_suffix(',').unwrap_or(line);
923 if line.contains('\\') {
924 return serde_json::from_str::<String>(line).ok().map(Cow::Owned);
925 }
926 line.strip_prefix('"')?.strip_suffix('"').map(Cow::Borrowed)
927 };
928 Some(Self {
929 motor_id: field("\n \"motor_id\": ")?,
930 designation: field("\n \"designation\": ")?,
931 common_name: field("\n \"common_name\": ")?,
932 })
933 }
934}
935
936fn stored_passes_hold(motor: &CatalogMotor) -> Result<(), MotorError> {
938 for curve in &motor.curves {
939 let passes = curve
940 .check
941 .gaps(&motor.stated)
942 .iter()
943 .all(FigureGap::within_bound);
944 if passes != curve.check.passes {
945 return Err(MotorError::Catalog(format!(
946 "{}'s curve {} stores passes: {}, but its figures give {passes}",
947 motor.designation, curve.simfile_id, curve.check.passes
948 )));
949 }
950 }
951 Ok(())
952}
953
954fn normalize(name: &str) -> String {
956 name.chars()
957 .filter(|c| !c.is_whitespace() && *c != '-')
958 .map(|c| c.to_ascii_lowercase())
959 .collect()
960}
961
962fn read_curve_file(
964 curve: &CatalogCurve,
965 text: &str,
966) -> Result<(ThrustCurve, f64, f64), MotorError> {
967 let one = |count: usize| {
968 if count == 1 {
969 Ok(())
970 } else {
971 Err(MotorError::Inconsistent(format!(
972 "the curve file {} holds {count} motors, not one",
973 curve.file
974 )))
975 }
976 };
977 match curve.format {
978 CurveFormat::Rasp => {
979 let file = eng::parse(text)?.value;
980 one(file.entries.len())?;
981 let entry = &file.entries[0];
982 Ok((
983 entry.thrust_curve()?,
984 entry.propellant_mass_kg,
985 entry.total_mass_kg,
986 ))
987 }
988 CurveFormat::RockSim => {
989 let file = rse::parse(text)?.value;
990 one(file.engines.len())?;
991 let engine = &file.engines[0];
992 Ok((
993 engine.thrust_curve()?,
994 engine.propellant_mass_g * 1e-3,
995 engine.initial_mass_g * 1e-3,
996 ))
997 }
998 }
999}
1000
1001#[non_exhaustive]
1004#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1005pub struct CatalogCounts {
1006 pub motors: usize,
1008 pub motors_flying: usize,
1010 pub files: usize,
1012 pub left_out: usize,
1014 pub files_passing: usize,
1016 pub motors_passing: usize,
1018}
1019
1020impl Catalog {
1021 #[must_use]
1023 pub fn counts(&self) -> CatalogCounts {
1024 let curves = || self.motors.iter().flat_map(|m| &m.curves);
1025 CatalogCounts {
1026 motors: self.motors.len(),
1027 motors_flying: self.motors.iter().filter(|m| !m.curves.is_empty()).count(),
1028 files: curves().count(),
1029 left_out: self.left_out.len(),
1030 files_passing: curves().filter(|c| c.check.passes).count(),
1031 motors_passing: self
1032 .motors
1033 .iter()
1034 .filter(|m| m.curves.iter().any(|c| c.check.passes))
1035 .count(),
1036 }
1037 }
1038}
1039
1040#[must_use]
1044pub fn bundled_size_bytes() -> usize {
1045 bundled::CATALOG_JSON.len()
1046 + bundled::CURVE_FILES
1047 .iter()
1048 .map(|(_, text)| text.len())
1049 .sum::<usize>()
1050}
1051
1052pub fn bundled_curve_text(file: &str) -> Option<&'static str> {
1054 bundled::CURVE_FILES
1055 .iter()
1056 .find(|(path, _)| *path == file)
1057 .map(|(_, text)| *text)
1058}
1059
1060impl CatalogMotor {
1061 pub fn delays(&self) -> DelayList {
1063 DelayList::parse(self.delays.as_deref().unwrap_or(""))
1064 }
1065
1066 pub fn thrust_curve(
1075 &self,
1076 curve: &CatalogCurve,
1077 text: &str,
1078 ) -> Result<ThrustCurve, MotorError> {
1079 self.check_own(curve)?;
1080 read_curve_file(curve, text).map(|(thrust, _, _)| thrust)
1081 }
1082
1083 fn check_own(&self, curve: &CatalogCurve) -> Result<(), MotorError> {
1086 if self.curves.contains(curve) {
1087 Ok(())
1088 } else {
1089 Err(MotorError::Inconsistent(format!(
1090 "curve {} is not one of {}'s curves",
1091 curve.simfile_id, self.designation
1092 )))
1093 }
1094 }
1095
1096 pub fn motor(&self, curve: &CatalogCurve, text: &str) -> Result<SolidMotor, MotorError> {
1107 if self.motor_type == MotorType::Hybrid {
1108 return Err(MotorError::Inconsistent(format!(
1109 "{} is a hybrid; HPR Sim models solid motors only",
1110 self.designation
1111 )));
1112 }
1113 self.check_own(curve)?;
1114 let (thrust, header_propellant_kg, header_total_kg) = read_curve_file(curve, text)?;
1115 let propellant_kg = self
1116 .propellant_mass_g
1117 .map_or(header_propellant_kg, |g| g * 1e-3);
1118 let total_kg = self.total_mass_g.map_or(header_total_kg, |g| g * 1e-3);
1119 if !(propellant_kg > 0.0 && total_kg > 0.0) {
1120 return Err(MotorError::Inconsistent(format!(
1121 "{} has no propellant and loaded masses",
1122 self.designation
1123 )));
1124 }
1125 SolidMotor::from_envelope(
1126 thrust,
1127 self.diameter_mm * 1e-3,
1128 self.length_mm * 1e-3,
1129 propellant_kg,
1130 total_kg,
1131 )
1132 }
1133
1134 pub fn bundled_motor(&self) -> Result<SolidMotor, MotorError> {
1141 let (curve, text) = self.default_curve_text().ok_or_else(|| {
1142 MotorError::Inconsistent(format!("{} has no bundled curve", self.designation))
1143 })?;
1144 self.motor(curve, text)
1145 }
1146
1147 pub fn ranked_curves(&self) -> Vec<&CatalogCurve> {
1155 let mut curves: Vec<&CatalogCurve> = self.curves.iter().collect();
1156 curves.sort_by_key(|curve| {
1158 let format = match curve.format {
1159 CurveFormat::Rasp => 0,
1160 CurveFormat::RockSim => 1,
1161 };
1162 let source = match curve.source {
1163 CurveSource::Certification => 0,
1164 CurveSource::Manufacturer => 1,
1165 CurveSource::User => 2,
1166 };
1167 (!curve.check.passes, format, source)
1168 });
1169 curves
1170 }
1171
1172 pub fn default_curve(&self) -> Option<&CatalogCurve> {
1175 self.default_curve_text().map(|(curve, _)| curve)
1176 }
1177
1178 pub fn curve_for_digest(&self, digest: Option<&str>) -> Option<(&CatalogCurve, &'static str)> {
1184 let mapped = digest.and_then(crate::openrocket_curves::file_for);
1185 mapped
1186 .and_then(|id| {
1187 let curve = self.curves.iter().find(|curve| curve.simfile_id == id)?;
1188 Some((curve, bundled_curve_text(&curve.file)?))
1189 })
1190 .or_else(|| self.default_curve_text())
1191 }
1192
1193 pub fn default_curve_text(&self) -> Option<(&CatalogCurve, &'static str)> {
1195 self.ranked_curves()
1196 .into_iter()
1197 .find_map(|curve| Some((curve, bundled_curve_text(&curve.file)?)))
1198 }
1199
1200 pub fn failing_figures(&self, curve: &CatalogCurve) -> Vec<FigureGap> {
1203 curve
1204 .check
1205 .gaps(&self.stated)
1206 .into_iter()
1207 .filter(|gap| !gap.within_bound())
1208 .collect()
1209 }
1210
1211 pub fn propellant_warning(&self, curve: &CatalogCurve) -> Option<String> {
1217 self.propellant_warning_for(curve, &self.flown_masses(curve)?)
1218 }
1219
1220 fn flown_masses(&self, curve: &CatalogCurve) -> Option<FlownMasses> {
1225 let text = bundled_curve_text(&curve.file)?;
1226 let (_, propellant_kg, total_kg) = read_curve_file(curve, text).ok()?;
1227 Some(FlownMasses {
1228 propellant_g: self.propellant_mass_g.unwrap_or(propellant_kg * 1000.0),
1229 total_g: self.total_mass_g.unwrap_or(total_kg * 1000.0),
1230 })
1231 }
1232
1233 fn propellant_warning_for(&self, curve: &CatalogCurve, masses: &FlownMasses) -> Option<String> {
1235 let record_g = self
1236 .stated
1237 .propellant_mass_g
1238 .filter(|g| g.is_finite() && *g > 0.0)?;
1239 let flown_g = masses.propellant_g;
1240 if flown_g >= record_g * (1.0 - PROPELLANT_SHORT_BOUND) {
1242 return None;
1243 }
1244 let gap = (flown_g / record_g - 1.0) * 100.0;
1245 let own = self.propellant_mass_g.is_none()
1248 || self
1249 .default_curve()
1250 .is_some_and(|default| default.simfile_id == curve.simfile_id);
1251 Some(if own {
1252 format!(
1253 "{} {}'s curve file {} gives {flown_g:.1} g of propellant, {gap:+.2}% from \
1254 ThrustCurve.org's record of {record_g:.1} g. If the file's loaded mass is right, \
1255 it flies too heavy a burnout mass and too low an apogee",
1256 self.manufacturer_abbrev, self.designation, curve.simfile_id,
1257 )
1258 } else {
1259 format!(
1260 "{} {} flies curve file {} with the default file's {flown_g:.1} g of propellant, \
1261 {gap:+.2}% from ThrustCurve.org's record of {record_g:.1} g. If the loaded mass \
1262 is right, it flies too heavy a burnout mass and too low an apogee",
1263 self.manufacturer_abbrev, self.designation, curve.simfile_id,
1264 )
1265 })
1266 }
1267
1268 pub fn mass_warnings(&self, curve: &CatalogCurve) -> Vec<String> {
1278 self.flown_masses(curve)
1279 .map(|masses| self.mass_warnings_for(&masses))
1280 .unwrap_or_default()
1281 .into_iter()
1282 .map(|warning| warning.message)
1283 .collect()
1284 }
1285
1286 fn mass_warnings_for(&self, masses: &FlownMasses) -> Vec<MotorWarning> {
1288 let FlownMasses {
1289 propellant_g,
1290 total_g,
1291 } = *masses;
1292 let mut warnings = Vec::new();
1293 let record_g = self
1294 .stated
1295 .total_mass_g
1296 .filter(|g| g.is_finite() && *g > 0.0);
1297 let loaded_off = record_g
1298 .is_some_and(|record_g| !within_share(total_g - record_g, record_g, LOADED_MASS_BOUND));
1299 let record_burnout_g = record_g.zip(
1302 self.stated
1303 .propellant_mass_g
1304 .filter(|g| g.is_finite() && *g >= 0.0),
1305 );
1306 if let Some((record_g, record_propellant_g)) = record_burnout_g
1307 && !loaded_off
1308 && record_propellant_g < record_g
1309 && !within_share(
1310 (total_g - propellant_g) - (record_g - record_propellant_g),
1311 record_g - record_propellant_g,
1312 BURNOUT_MASS_BOUND,
1313 )
1314 {
1315 let record_burnout_g = record_g - record_propellant_g;
1316 warnings.push(MotorWarning::new(
1317 MotorWarningKind::BurnoutMass,
1318 format!(
1319 "{} {} flies a burnout mass, loaded less propellant, of {:.1} g where \
1320 ThrustCurve.org's record gives {record_burnout_g:.1} g, {:+.1}%, more than \
1321 {:.0}% apart. Too heavy gives too low an apogee; too light, too high a margin \
1322 after burnout",
1323 self.manufacturer_abbrev,
1324 self.designation,
1325 total_g - propellant_g,
1326 ((total_g - propellant_g) / record_burnout_g - 1.0) * 100.0,
1327 BURNOUT_MASS_BOUND * 100.0
1328 ),
1329 ));
1330 }
1331 if let Some(record_g) = record_g
1332 && loaded_off
1333 {
1334 let kind = if total_g > record_g {
1335 MotorWarningKind::HeavyLoadedMass
1336 } else {
1337 MotorWarningKind::LightLoadedMass
1338 };
1339 warnings.push(MotorWarning::new(kind, format!(
1340 "{} {} flies a loaded mass of {total_g:.1} g, {:+.1}% from ThrustCurve.org's \
1341 record of {record_g:.1} g; the two disagree, so check which describes the motor you fly. \
1342 Too heavy a motor gives too low an apogee; too light, too high a margin after \
1343 burnout",
1344 self.manufacturer_abbrev,
1345 self.designation,
1346 (total_g / record_g - 1.0) * 100.0
1347 )));
1348 }
1349 let share = propellant_g / total_g;
1350 let (low, high) = PROPELLANT_SHARE_SPAN;
1351 if !(low..=high).contains(&share) {
1352 warnings.push(MotorWarning::new(MotorWarningKind::PropellantShare, format!(
1353 "{} {} flies {propellant_g:.1} g of propellant in a loaded mass of {total_g:.1} g, a \
1354 propellant share of {:.1}%, outside the {:.1}% to {:.0}% ThrustCurve.org's records \
1355 span; check the motor's masses",
1356 self.manufacturer_abbrev,
1357 self.designation,
1358 share * 100.0,
1359 low * 100.0,
1360 high * 100.0
1361 )));
1362 }
1363 warnings
1364 }
1365
1366 pub fn flight_warnings(&self, curve: &CatalogCurve) -> Vec<String> {
1370 self.flight_warning_kinds(curve)
1371 .into_iter()
1372 .map(|warning| warning.message)
1373 .collect()
1374 }
1375
1376 pub fn flight_warning_kinds(&self, curve: &CatalogCurve) -> Vec<MotorWarning> {
1379 let mut warnings: Vec<MotorWarning> = self
1380 .check_warning(curve)
1381 .map(|message| MotorWarning::new(MotorWarningKind::FailedCheck, message))
1382 .into_iter()
1383 .collect();
1384 if let Some(masses) = self.flown_masses(curve) {
1385 warnings.extend(
1386 self.propellant_warning_for(curve, &masses)
1387 .map(|message| MotorWarning::new(MotorWarningKind::LightPropellant, message)),
1388 );
1389 warnings.extend(self.mass_warnings_for(&masses));
1390 }
1391 warnings
1392 }
1393
1394 pub fn check_warning(&self, curve: &CatalogCurve) -> Option<String> {
1398 if curve.check.passes {
1399 return None;
1400 }
1401 let gaps: Vec<String> = self
1402 .failing_figures(curve)
1403 .iter()
1404 .map(|gap| format!("{} {}", gap.figure.name(), gap.percent_text()))
1405 .collect();
1406 Some(format!(
1407 "{}'s curve file {} is more than 1% from ThrustCurve.org's figures for it: {}",
1408 self.designation,
1409 curve.simfile_id,
1410 gaps.join(", ")
1411 ))
1412 }
1413}
1414
1415#[cfg(test)]
1416mod tests {
1417 use sha2::{Digest, Sha256};
1418
1419 use super::*;
1420 use crate::delay::Delay;
1421
1422 fn bundled() -> &'static Catalog {
1424 Catalog::bundled().unwrap()
1425 }
1426
1427 #[test]
1430 fn m5_7a_s_32_files_are_indexed_and_pass() {
1431 let fixture: serde_json::Value = serde_json::from_str(include_str!(
1432 "../../../validation/fixtures/motor/openrocket-curve-stats.json"
1433 ))
1434 .unwrap();
1435 let files: Vec<&str> = fixture["curves"]
1436 .as_array()
1437 .unwrap()
1438 .iter()
1439 .map(|c| {
1440 c["file"]
1441 .as_str()
1442 .unwrap()
1443 .trim_start_matches("crates/hpr-motor/data/thrustcurve/")
1444 })
1445 .collect();
1446 assert_eq!(files.len(), 32);
1447 for file in files {
1448 let (motor, curve) = bundled()
1449 .motors
1450 .iter()
1451 .find_map(|m| m.curves.iter().find(|c| c.file == file).map(|c| (m, c)))
1452 .unwrap_or_else(|| panic!("{file} isn't indexed"));
1453 assert!(curve.check.passes, "{file}");
1454 assert_eq!(motor.check_warning(curve), None, "{file}");
1455 }
1456 }
1457
1458 #[test]
1465 fn bundled_curves_have_permissive_license() {
1466 let catalog = bundled();
1467 assert!(!catalog.motors.is_empty());
1468 let mut files = 0;
1469 for motor in &catalog.motors {
1470 for curve in &motor.curves {
1471 assert!(
1472 curve.license.is_bundleable(),
1473 "{} {}: {:?}",
1474 motor.designation,
1475 curve.simfile_id,
1476 curve.license
1477 );
1478 assert!(bundled_curve_text(&curve.file).is_some(), "{}", curve.file);
1479 files += 1;
1480 }
1481 }
1482 assert_eq!(files, bundled::CURVE_FILES.len());
1484 for motor in &catalog.motors {
1486 for curve in &motor.curves {
1487 let text = bundled_curve_text(&curve.file).unwrap();
1488 let digest: String = Sha256::digest(text.as_bytes())
1489 .iter()
1490 .map(|byte| format!("{byte:02x}"))
1491 .collect();
1492 assert_eq!(digest, curve.sha256, "{}", curve.file);
1493 assert!(curve.url.contains(&curve.simfile_id));
1494 }
1495 }
1496 assert!(!CurveLicense::Other.is_bundleable());
1497 assert!(CurveLicense::Free.is_bundleable());
1498 assert!(CurveLicense::Unknown.is_bundleable());
1499 assert!(CurveLicense::PublicDomain.is_bundleable());
1500 }
1501
1502 #[test]
1516 fn every_bundled_curve_impulse_within_1pct_of_thrustcurve() {
1517 let oracle: AnalyzeOracle = serde_json::from_str(include_str!(
1518 "../../../validation/fixtures/motor/thrustcurve-analyze-stats.json"
1519 ))
1520 .unwrap();
1521 let catalog = bundled();
1522 let mut checked = 0;
1523 let mut listed = 0;
1524 for motor in &catalog.motors {
1525 for curve in &motor.curves {
1526 if motor.default_curve() != Some(curve)
1527 && !oracle.curves.iter().any(|c| c.file == curve.file)
1528 {
1529 continue;
1530 }
1531 let text = bundled_curve_text(&curve.file).unwrap();
1532 let thrust = motor.thrust_curve(curve, text).unwrap();
1533 let theirs = oracle
1534 .curves
1535 .iter()
1536 .find(|c| c.file == curve.file)
1537 .map(|c| c.unmerged.unwrap_or(c.standard()));
1538 for (stated, computed, by_thrustcurve, what) in [
1539 (
1540 motor.total_impulse_ns,
1541 thrust.total_impulse_ns(),
1542 theirs.map(|t| t.total_impulse_ns),
1543 "total impulse",
1544 ),
1545 (
1546 motor.average_thrust_n,
1547 thrust.average_thrust_n(),
1548 theirs.map(|t| t.average_thrust_n),
1549 "average thrust",
1550 ),
1551 (
1552 motor.burn_time_s,
1553 thrust.burn_time_s(),
1554 theirs.map(|t| t.burn_time_s),
1555 "burn time",
1556 ),
1557 (
1558 motor.max_thrust_n.unwrap(),
1559 thrust.peak_thrust_n(),
1560 theirs.map(|t| t.max_thrust_n),
1561 "peak thrust",
1562 ),
1563 ] {
1564 if curve.check.passes && what != "peak thrust" {
1565 let record = match what {
1566 "total impulse" => motor.stated.total_impulse_ns,
1567 "average thrust" => motor.stated.average_thrust_n,
1568 _ => motor.stated.burn_time_s,
1569 };
1570 assert!(
1571 (computed - record).abs() <= 0.01 * record,
1572 "{} ({}) is stored as passing, but its {what} {computed} is {:+.3}% \
1573 from its record's {record}",
1574 motor.designation,
1575 curve.simfile_id,
1576 100.0 * (computed - record) / record
1577 );
1578 }
1579 if motor.default_curve() == Some(curve) {
1580 assert_eq!(
1581 stated.to_bits(),
1582 computed.to_bits(),
1583 "{} ({}): the index's {what} {stated} is not its curve's {computed}",
1584 motor.designation,
1585 curve.simfile_id,
1586 );
1587 }
1588 let Some(by_thrustcurve) = by_thrustcurve else {
1589 continue;
1590 };
1591 let error = (computed - by_thrustcurve) / by_thrustcurve;
1592 assert!(
1593 error.abs() <= 0.01,
1594 "{} ({}): {what} {computed} against ThrustCurve's code's {by_thrustcurve} \
1595 ({:+.2}%)",
1596 motor.designation,
1597 curve.simfile_id,
1598 100.0 * error
1599 );
1600 }
1601 if motor.default_curve() == Some(curve) {
1602 assert_eq!(
1603 ImpulseClass::from_total_impulse(motor.total_impulse_ns).unwrap(),
1604 motor.impulse_class,
1605 "{}",
1606 motor.designation
1607 );
1608 listed += 1;
1609 }
1610 assert_eq!(
1611 theirs.is_some(),
1612 curve.check.passes,
1613 "{} ({}): the oracle fixture should hold exactly the files stored as passing",
1614 motor.designation,
1615 curve.simfile_id
1616 );
1617 checked += usize::from(theirs.is_some());
1618 }
1619 }
1620 assert_eq!(checked, oracle.curves.len());
1621 let passing = catalog
1622 .motors
1623 .iter()
1624 .flat_map(|m| &m.curves)
1625 .filter(|c| c.check.passes)
1626 .count();
1627 assert_eq!(checked, passing);
1628 assert_eq!(passing, 412);
1630 assert_eq!(
1631 listed,
1632 catalog
1633 .motors
1634 .iter()
1635 .filter(|m| !m.curves.is_empty())
1636 .count()
1637 );
1638 }
1639
1640 #[test]
1643 fn bundled_counts_and_size_are_the_files() {
1644 let catalog = Catalog::bundled().unwrap();
1645 let counts = catalog.counts();
1646 let mut flying = 0;
1647 let mut files = 0;
1648 let mut passing = 0;
1649 let mut motors_passing = 0;
1650 let mut bytes = bundled::CATALOG_JSON.len();
1651 for motor in &catalog.motors {
1652 flying += usize::from(!motor.curves.is_empty());
1653 files += motor.curves.len();
1654 let here = motor.curves.iter().filter(|c| c.check.passes).count();
1655 passing += here;
1656 motors_passing += usize::from(here > 0);
1657 for curve in &motor.curves {
1658 bytes += bundled_curve_text(&curve.file).unwrap().len();
1659 }
1660 }
1661 assert_eq!(
1662 (
1663 counts.motors,
1664 counts.motors_flying,
1665 counts.files,
1666 counts.left_out
1667 ),
1668 (catalog.motors.len(), flying, files, catalog.left_out.len())
1669 );
1670 assert_eq!(
1671 (counts.files_passing, counts.motors_passing),
1672 (passing, motors_passing)
1673 );
1674 assert_eq!(
1676 (
1677 counts.motors,
1678 counts.motors_flying,
1679 counts.files,
1680 counts.left_out
1681 ),
1682 (1_004, 924, 1_701, 5)
1683 );
1684 assert_eq!((counts.files_passing, counts.motors_passing), (412, 239));
1685 assert_eq!(bundled::CURVE_FILES.len(), files);
1688 assert_eq!(bundled_size_bytes(), bytes);
1689 assert_eq!(bytes, 4_196_056);
1690 }
1691
1692 #[test]
1697 fn every_bundled_size_mass_and_delay_is_the_header_s() {
1698 let catalog = bundled();
1699 for motor in &catalog.motors {
1700 let Some(curve) = motor.default_curve() else {
1701 assert!(motor.curves.is_empty(), "{}", motor.designation);
1702 continue;
1703 };
1704 let text = bundled_curve_text(&curve.file).unwrap();
1705 let (diameter_mm, length_mm, delays, propellant_g, total_g) = match curve.format {
1706 CurveFormat::Rasp => {
1707 let entry = eng::parse(text).unwrap().value.entries.remove(0);
1708 (
1709 entry.diameter_mm,
1710 entry.length_mm,
1711 Some(entry.delays),
1712 entry.propellant_mass_kg * 1e3,
1713 entry.total_mass_kg * 1e3,
1714 )
1715 }
1716 CurveFormat::RockSim => {
1717 let engine = rse::parse(text).unwrap().value.engines.remove(0);
1718 (
1719 engine.diameter_mm,
1720 engine.length_mm,
1721 engine.delays,
1722 engine.propellant_mass_g,
1723 engine.initial_mass_g,
1724 )
1725 }
1726 };
1727 let name = &motor.designation;
1728 assert_eq!(motor.diameter_mm, diameter_mm, "{name}");
1729 assert_eq!(motor.length_mm, length_mm, "{name}");
1730 assert_eq!(motor.delays, delays, "{name}");
1731 assert!(
1732 (motor.propellant_mass_g.unwrap() - propellant_g).abs() <= 5e-7,
1733 "{name}"
1734 );
1735 assert!(
1736 (motor.total_mass_g.unwrap() - total_g).abs() <= 5e-7,
1737 "{name}"
1738 );
1739 }
1740 }
1741
1742 #[test]
1746 fn bundled_index_holds_no_thrustcurve_record_fields() {
1747 for key in [
1748 "cert_org",
1749 "updated_on",
1750 "availability",
1751 "delay_adjustable",
1752 "motors_url",
1753 "api/v1",
1754 ] {
1755 assert!(
1756 !bundled::CATALOG_JSON.contains(key),
1757 "the bundled index holds {key}"
1758 );
1759 }
1760 let catalog = bundled();
1761 assert_eq!(
1762 catalog.snapshot.files_url,
1763 "https://www.thrustcurve.org/simfiles/"
1764 );
1765 for curve in catalog.motors.iter().flat_map(|m| &m.curves) {
1766 assert!(curve.url.starts_with(&catalog.snapshot.files_url));
1767 }
1768 }
1769
1770 #[test]
1776 fn metadata_overrides_header_envelope() {
1777 let catalog = bundled();
1778 let bundled_entry = catalog.find("N3300R").next().unwrap();
1779 let curve = &bundled_entry.curves[0];
1780 let text = bundled_curve_text(&curve.file).unwrap();
1781 let header = &eng::parse(text).unwrap().value.entries[0];
1782 assert_eq!(header.length_mm, 1060.0);
1783 assert_eq!(bundled_entry.length_mm, 1060.0);
1784 let motor = CatalogMotor {
1785 length_mm: 1000.0,
1786 total_mass_g: Some(12000.0),
1787 ..bundled_entry.clone()
1788 };
1789 let built = motor.motor(curve, text).unwrap();
1790 assert!((built.dry().cg_m - 0.500).abs() < 1e-12);
1792 let loaded = built.state(0.0).total;
1793 assert!((loaded.mass_kg - 12.000).abs() < 1e-9);
1794 assert!((bundled_entry.bundled_motor().unwrap().dry().cg_m - 0.530).abs() < 1e-12);
1795 let bare = CatalogMotor {
1797 propellant_mass_g: None,
1798 total_mass_g: None,
1799 ..motor.clone()
1800 };
1801 let fallback = bare.motor(curve, text).unwrap();
1802 assert!((fallback.state(0.0).total.mass_kg - header.total_mass_kg).abs() < 1e-12);
1803 assert!((fallback.dry().cg_m - 0.500).abs() < 1e-12);
1804 }
1805
1806 #[test]
1808 fn every_bundled_file_round_trips_bit_for_bit() {
1809 let catalog = bundled();
1810 for motor in &catalog.motors {
1811 for curve in &motor.curves {
1812 let text = bundled_curve_text(&curve.file).unwrap();
1813 match curve.format {
1814 CurveFormat::Rasp => {
1815 let first = eng::parse(text).unwrap().value;
1816 let written = eng::write(&first).unwrap();
1817 let second = eng::parse(&written).unwrap().value;
1818 assert_eq!(second, first, "{}", curve.file);
1819 assert_eq!(eng::tests::bits(&second), eng::tests::bits(&first));
1820 assert_eq!(eng::write(&second).unwrap(), written);
1821 }
1822 CurveFormat::RockSim => {
1823 let first = rse::parse(text).unwrap().value;
1824 let written = rse::write(&first).unwrap();
1825 let second = rse::parse(&written).unwrap().value;
1826 assert_eq!(second, first, "{}", curve.file);
1827 assert_eq!(rse::tests::bits(&second), rse::tests::bits(&first));
1828 assert_eq!(rse::write(&second).unwrap(), written);
1829 }
1830 }
1831 }
1832 }
1833 }
1834
1835 #[test]
1836 fn finds_motors_and_reads_delays() {
1837 let catalog = bundled();
1838 let j760: Vec<_> = catalog.find("j760").collect();
1839 assert!(j760.iter().any(|m| m.designation == "1266J760-19A"));
1840 assert!(j760.iter().all(|m| m.common_name == "J760"));
1841 assert_eq!(catalog.find("1266J760-19A").count(), 1);
1842 let plugged = catalog.find("L3200").next().unwrap();
1843 assert_eq!(plugged.delays().delays, [Delay::Plugged]);
1844 assert!(catalog.find("no such motor").next().is_none());
1845 let c6: Vec<_> = catalog.find("C6").collect();
1848 assert!(c6.len() > 1 && c6.iter().any(|m| m.designation == "SCR-C6"));
1849 let estes: Vec<_> = catalog.find("Estes C6").collect();
1850 assert_eq!(estes.len(), 1);
1851 assert_eq!(estes[0].manufacturer_abbrev, "Estes");
1852 assert_eq!(catalog.find("estes industries c6").count(), 1);
1853 assert_eq!(catalog.find("EstesC6").count(), 0);
1854 let d5: Vec<_> = catalog.find("D5").collect();
1855 assert_eq!(d5.len(), 1);
1856 assert_eq!(d5[0].designation, "D5");
1857 assert!(catalog.find("D5-P").all(|m| m.designation == "D5-P"));
1858 assert_eq!(catalog.find("Quest no such motor").count(), 0);
1859 for motor in &catalog.motors {
1861 let selector = catalog.selector(motor);
1862 let found: Vec<_> = catalog.find(&selector).collect();
1863 assert_eq!(found.len(), 1, "{selector}");
1864 assert_eq!(found[0].motor_id, motor.motor_id, "{selector}");
1865 }
1866 for motor in &catalog.motors {
1868 if motor.curves.is_empty() {
1869 assert!(motor.bundled_motor().is_err(), "{}", motor.designation);
1870 continue;
1871 }
1872 let built = motor.bundled_motor().unwrap();
1873 assert!(
1874 built.propellant_initial_mass_kg() > 0.0,
1875 "{}",
1876 motor.designation
1877 );
1878 }
1879 }
1880
1881 #[test]
1882 fn catalog_json_reads_thrustcurve_license_values_and_rejects_others() {
1883 assert!(matches!(
1884 Catalog::from_json("{}"),
1885 Err(MotorError::Catalog(_))
1886 ));
1887 let with = |license: &str| {
1888 Catalog::from_json(&bundled::CATALOG_JSON.replacen("\"license\": \"PD\",", license, 1))
1889 };
1890 let first_pd = bundled()
1892 .motors
1893 .iter()
1894 .flat_map(|m| &m.curves)
1895 .find(|c| c.license == CurveLicense::PublicDomain)
1896 .unwrap()
1897 .simfile_id
1898 .clone();
1899 let first_license = |catalog: Catalog| {
1900 catalog
1901 .motors
1902 .iter()
1903 .flat_map(|m| &m.curves)
1904 .find(|c| c.simfile_id == first_pd)
1905 .unwrap()
1906 .license
1907 };
1908 assert!(with("\"license\": \"GPL\",").is_err());
1909 assert_eq!(
1910 first_license(with("\"license\": \"free\",").unwrap()),
1911 CurveLicense::Free
1912 );
1913 assert_eq!(first_license(with("").unwrap()), CurveLicense::Unknown);
1915 assert_eq!(
1916 first_license(with("\"license\": \"\",").unwrap()),
1917 CurveLicense::Unknown
1918 );
1919 let hybrid = bundled::CATALOG_JSON.replacen(
1920 "\"motor_type\": \"SU\"",
1921 "\"motor_type\": \"hybrid\"",
1922 1,
1923 );
1924 let hybrid = Catalog::from_json(&hybrid).unwrap();
1925 let first_su = bundled()
1926 .motors
1927 .iter()
1928 .position(|m| m.motor_type == MotorType::SingleUse)
1929 .unwrap();
1930 assert_eq!(hybrid.motors[first_su].motor_type, MotorType::Hybrid);
1931 assert!(hybrid.motors[first_su].bundled_motor().is_err());
1932 }
1933
1934 #[test]
1935 fn a_curve_of_another_motor_is_refused() {
1936 let catalog = Catalog::bundled().unwrap();
1937 let (this, other) = (&catalog.motors[0], &catalog.motors[1]);
1938 let curve = &other.curves[0];
1939 let text = bundled_curve_text(&curve.file).unwrap();
1940 assert!(other.motor(curve, text).is_ok());
1941 assert!(matches!(
1942 this.motor(curve, text),
1943 Err(MotorError::Inconsistent(message)) if message.contains(&curve.simfile_id)
1944 ));
1945 assert!(this.thrust_curve(curve, text).is_err());
1946 }
1947
1948 #[derive(Debug, serde::Deserialize)]
1949 struct AnalyzeOracle {
1950 oracle: String,
1951 selection: String,
1952 curves: Vec<AnalyzeCurve>,
1953 }
1954
1955 #[derive(Debug, serde::Deserialize)]
1958 struct AnalyzeCurve {
1959 file: String,
1960 merged_points: usize,
1961 total_impulse_ns: f64,
1962 burn_time_s: f64,
1963 average_thrust_n: f64,
1964 max_thrust_n: f64,
1965 burn_start_s: f64,
1966 burn_end_s: f64,
1967 unmerged: Option<AnalyzeFigures>,
1968 }
1969
1970 #[derive(Debug, Clone, Copy, serde::Deserialize)]
1971 struct AnalyzeFigures {
1972 total_impulse_ns: f64,
1973 burn_time_s: f64,
1974 average_thrust_n: f64,
1975 max_thrust_n: f64,
1976 burn_start_s: f64,
1977 burn_end_s: f64,
1978 }
1979
1980 impl AnalyzeCurve {
1981 fn standard(&self) -> AnalyzeFigures {
1983 AnalyzeFigures {
1984 total_impulse_ns: self.total_impulse_ns,
1985 burn_time_s: self.burn_time_s,
1986 average_thrust_n: self.average_thrust_n,
1987 max_thrust_n: self.max_thrust_n,
1988 burn_start_s: self.burn_start_s,
1989 burn_end_s: self.burn_end_s,
1990 }
1991 }
1992 }
1993
1994 const MERGE_MOVES: &[(&str, &str, &str)] = &[
2002 ("curves/5f4294d20002e9000000013c.eng", "burn time", "+0.50"),
2003 ("curves/5f4294d20002e90000000591.rse", "peak thrust", "+6.5"),
2004 ("curves/5f4294d20002e90000000144.eng", "burn time", "+0.61"),
2005 (
2006 "curves/5f4294d20002e9000000014b.eng",
2007 "average thrust",
2008 "+0.28",
2009 ),
2010 ("curves/5f4294d20002e9000000014e.eng", "burn time", "+0.19"),
2011 (
2012 "curves/5f4294d20002e900000005a3.rse",
2013 "average thrust",
2014 "+0.023",
2015 ),
2016 ];
2017
2018 #[test]
2025 fn every_bundled_curve_matches_thrustcurve_statistics_code() {
2026 let oracle: AnalyzeOracle = serde_json::from_str(include_str!(
2027 "../../../validation/fixtures/motor/thrustcurve-analyze-stats.json"
2028 ))
2029 .unwrap();
2030 assert!(oracle.oracle.contains("analyze.js at commit 577afa6"));
2031 assert!(oracle.selection.contains("stores as passing"));
2032 let catalog = bundled();
2033 let mut worst = 0.0f64;
2034 let mut moved = Vec::new();
2035 for expected in &oracle.curves {
2036 let (motor, curve) = catalog
2037 .motors
2038 .iter()
2039 .find_map(|m| {
2040 m.curves
2041 .iter()
2042 .find(|c| c.file == expected.file)
2043 .map(|c| (m, c))
2044 })
2045 .unwrap();
2046 assert!(curve.check.passes, "{}", expected.file);
2047 assert_eq!(
2048 expected.unmerged.is_some(),
2049 expected.merged_points > 0,
2050 "{}",
2051 expected.file
2052 );
2053 let thrust = motor
2054 .thrust_curve(curve, bundled_curve_text(&curve.file).unwrap())
2055 .unwrap();
2056 let (start, end) = thrust.burn_window_s();
2057 let ours = AnalyzeFigures {
2058 total_impulse_ns: thrust.total_impulse_ns(),
2059 burn_time_s: thrust.burn_time_s(),
2060 average_thrust_n: thrust.average_thrust_n(),
2061 max_thrust_n: thrust.peak_thrust_n(),
2062 burn_start_s: start,
2063 burn_end_s: end,
2064 };
2065 let gaps = |theirs: AnalyzeFigures| {
2066 [
2067 (
2068 ours.total_impulse_ns,
2069 theirs.total_impulse_ns,
2070 "total impulse",
2071 ),
2072 (ours.burn_time_s, theirs.burn_time_s, "burn time"),
2073 (
2074 ours.average_thrust_n,
2075 theirs.average_thrust_n,
2076 "average thrust",
2077 ),
2078 (ours.max_thrust_n, theirs.max_thrust_n, "peak thrust"),
2079 (ours.burn_start_s, theirs.burn_start_s, "burn start"),
2080 (ours.burn_end_s, theirs.burn_end_s, "burn end"),
2081 ]
2082 .map(|(ours, theirs, what)| {
2083 (
2084 (ours - theirs).abs() / theirs.abs().max(1e-3),
2085 ours,
2086 theirs,
2087 what,
2088 )
2089 })
2090 };
2091 for (error, ours, theirs, what) in
2092 gaps(expected.unmerged.unwrap_or(expected.standard()))
2093 {
2094 worst = worst.max(error);
2095 assert!(
2096 error <= 1e-12,
2097 "{}: {what} {ours} against {theirs}",
2098 expected.file
2099 );
2100 }
2101 let merged = gaps(expected.standard());
2102 if merged.iter().any(|(error, ..)| *error > 1e-12) {
2103 moved.push(expected.file.as_str());
2104 let (_, ours, theirs, what) = merged[..4]
2106 .iter()
2107 .copied()
2108 .max_by(|a, b| a.0.total_cmp(&b.0))
2109 .unwrap();
2110 let named = MERGE_MOVES.iter().find(|(file, ..)| *file == expected.file);
2111 if let Some((_, figure, percent)) = named {
2112 let decimals = percent.split('.').nth(1).map_or(0, str::len);
2113 let measured = format!("{:+.decimals$}", 100.0 * (ours - theirs) / theirs);
2114 assert_eq!(
2115 (what, measured.as_str()),
2116 (*figure, *percent),
2117 "{}: the merge's largest move",
2118 expected.file
2119 );
2120 }
2121 }
2122 }
2123 let named: Vec<&str> = MERGE_MOVES.iter().map(|(file, ..)| *file).collect();
2124 assert_eq!(
2125 moved, named,
2126 "the files whose figures ThrustCurve's 50 µs merge moves aren't the ones named"
2127 );
2128 eprintln!("largest relative difference from ThrustCurve's code: {worst:.2e}");
2129 }
2130
2131 #[derive(Debug, serde::Deserialize)]
2134 struct OpenRocketRecord {
2135 openrocket: String,
2136 inputs_sha256: std::collections::BTreeMap<String, String>,
2137 jar_sha256: String,
2138 curves: Vec<OpenRocketCurve>,
2139 }
2140
2141 #[derive(Debug, serde::Deserialize)]
2142 struct OpenRocketCurve {
2143 file: String,
2144 sha256: String,
2145 #[serde(default)]
2146 motors: Vec<OpenRocketMotor>,
2147 #[serde(default)]
2148 driver_error: Option<String>,
2149 }
2150
2151 #[derive(Debug, serde::Deserialize)]
2152 struct OpenRocketMotor {
2153 common_name: String,
2154 total_impulse_ns: f64,
2155 max_thrust_n: f64,
2156 average_thrust_n: f64,
2157 burn_time_s: f64,
2158 burn_time_estimate_s: f64,
2159 first_time_s: f64,
2160 points: usize,
2161 }
2162
2163 #[test]
2181 fn openrocket_s_total_impulse_matches_every_bundled_curve() {
2182 let record: OpenRocketRecord = serde_json::from_str(include_str!(
2183 "../../../validation/fixtures/motor/openrocket-curve-stats.json"
2184 ))
2185 .unwrap();
2186 assert_eq!(record.openrocket, "24.12");
2187 assert_eq!(
2189 record.inputs_sha256["motors.py"],
2190 "1049b94c2c0da896dd84887a06b5ff8fd72865350aa98a2f9e1c8b7e14d5e3e7",
2191 );
2192 assert_eq!(
2193 record.jar_sha256,
2194 "4959b72f52f5f607941e9722abbb7b7f0c4a38ebbbf84204a329db9f31c4f897",
2195 );
2196 assert_eq!(record.curves.len(), 32);
2198 let catalog = bundled();
2199 let mut worst_impulse = 0.0f64;
2200 let mut worst_peak = 0.0f64;
2201 let mut average = Vec::new();
2202 let mut identical = true;
2203 let mut files = std::collections::BTreeSet::new();
2204 for entry in &record.curves {
2205 let file = entry
2206 .file
2207 .strip_prefix("crates/hpr-motor/data/thrustcurve/")
2208 .expect("the record names the bundled file");
2209 assert_eq!(entry.driver_error, None, "{file}");
2210 let [theirs] = &entry.motors[..] else {
2211 panic!("{file}: OpenRocket read {} motors", entry.motors.len());
2212 };
2213 let (motor, curve) = catalog
2214 .motors
2215 .iter()
2216 .find_map(|m| m.curves.iter().find(|c| c.file == file).map(|c| (m, c)))
2217 .unwrap_or_else(|| panic!("{file} is not a bundled curve"));
2218 assert_eq!(curve.sha256, entry.sha256, "{file}");
2220 assert!(files.insert(file.to_owned()), "{file} twice");
2221 assert_eq!(
2225 normalize(&motor.common_name),
2226 normalize(&theirs.common_name),
2227 "{file}"
2228 );
2229 let text = bundled_curve_text(file).unwrap();
2230 let thrust = motor.thrust_curve(curve, text).unwrap();
2231 for (ours, theirs, what, bound) in [
2232 (
2233 thrust.total_impulse_ns(),
2234 theirs.total_impulse_ns,
2235 "total impulse",
2236 1e-3,
2237 ),
2238 (
2239 thrust.peak_thrust_n(),
2240 theirs.max_thrust_n,
2241 "peak thrust",
2242 1e-12,
2243 ),
2244 (
2245 thrust.burn_time_s(),
2246 theirs.burn_time_estimate_s,
2247 "burn time",
2248 1e-12,
2249 ),
2250 (
2251 thrust.end_time_s(),
2252 theirs.burn_time_s,
2253 "curve duration",
2254 1e-12,
2255 ),
2256 ] {
2257 assert!(theirs > 0.0, "{file}: {what} {theirs}");
2258 let error = (ours - theirs).abs() / theirs;
2259 if what == "total impulse" {
2260 worst_impulse = worst_impulse.max(error);
2261 } else {
2262 worst_peak = worst_peak.max(error);
2263 }
2264 assert!(error <= bound, "{file}: {what} {ours} against {theirs}");
2265 identical &= ours == theirs;
2268 }
2269 assert_eq!(thrust.times_s()[0], 0.0, "{file}");
2272 assert_eq!(theirs.first_time_s, 0.0, "{file}");
2273 assert_eq!(thrust.times_s().len(), theirs.points, "{file}");
2274 average.push(
2277 (thrust.average_thrust_n() - theirs.average_thrust_n) / theirs.average_thrust_n,
2278 );
2279 }
2280 assert_eq!(files.len(), record.curves.len(), "a file twice or missing");
2281 assert!(
2282 identical,
2283 "impulse, peak thrust, burn time and duration are no longer bit for bit OpenRocket's"
2284 );
2285 average.sort_by(f64::total_cmp);
2286 let mid = average.len() / 2;
2287 let median = if average.len().is_multiple_of(2) {
2288 0.5 * (average[mid - 1] + average[mid])
2289 } else {
2290 average[mid]
2291 };
2292 let (low, high) = (average[0] * 100.0, average[average.len() - 1] * 100.0);
2293 assert!(low > 0.0, "hpr's average thrust is no longer the higher");
2294 eprintln!(
2295 "against OpenRocket 24.12 on {} curves: total impulse, peak thrust, the 5% burn-time \
2296 window and the curve's duration are all bit for bit equal (worst relative differences \
2297 {worst_impulse:.2e} and {worst_peak:.2e}); hpr's average thrust is higher by \
2298 {low:+.4}% to {high:+.4}% (median {:+.4}%), because its numerator is the whole curve's \
2299 impulse and OpenRocket's is the window's",
2300 average.len(),
2301 median * 100.0,
2302 );
2303 }
2304
2305 #[test]
2310 fn every_bundled_check_is_its_file_against_its_record() {
2311 let records: serde_json::Value =
2312 serde_json::from_str(include_str!("../data/thrustcurve/records.json")).unwrap();
2313 let records = records["records"].as_array().unwrap();
2314 let bits = |value: &serde_json::Value| value.as_f64().map(f64::to_bits);
2315 let catalog = bundled();
2316 let mut checked = 0;
2317 for motor in &catalog.motors {
2318 let name = &motor.designation;
2319 let record = records
2320 .iter()
2321 .find(|r| r["motorId"] == motor.motor_id.as_str())
2322 .unwrap_or_else(|| panic!("{name}: no record"));
2323 let stated = &motor.stated;
2324 assert_eq!(
2325 Some(stated.total_impulse_ns.to_bits()),
2326 bits(&record["totImpulseNs"])
2327 );
2328 assert_eq!(
2329 Some(stated.average_thrust_n.to_bits()),
2330 bits(&record["avgThrustN"])
2331 );
2332 assert_eq!(
2333 Some(stated.burn_time_s.to_bits()),
2334 bits(&record["burnTimeS"])
2335 );
2336 assert_eq!(
2337 stated.max_thrust_n.map(f64::to_bits),
2338 bits(&record["maxThrustN"])
2339 );
2340 for curve in &motor.curves {
2341 let text = bundled_curve_text(&curve.file).unwrap();
2342 let thrust = motor.thrust_curve(curve, text).unwrap();
2343 assert_eq!(CurveCheck::of(&thrust, stated), curve.check, "{name}");
2344 assert_eq!(
2346 curve.check.passes,
2347 motor.failing_figures(curve).is_empty(),
2348 "{name}"
2349 );
2350 match motor.check_warning(curve) {
2351 None => assert!(curve.check.passes, "{name}"),
2352 Some(warning) => {
2353 assert!(!curve.check.passes, "{name}");
2354 assert!(warning.contains(&curve.simfile_id), "{name}: {warning}");
2355 }
2356 }
2357 checked += 1;
2358 }
2359 }
2360 assert_eq!(checked, bundled::CURVE_FILES.len());
2361 }
2362
2363 #[test]
2366 fn a_figure_exactly_one_percent_away_passes_and_one_past_fails() {
2367 let gap = |file: f64, stated: f64| FigureGap {
2368 figure: CheckedFigure::BurnTime,
2369 file,
2370 stated,
2371 };
2372 assert!(gap(101.0, 100.0).within_bound());
2373 assert!(gap(99.0, 100.0).within_bound());
2374 assert!(gap(100.0, 100.0).within_bound());
2375 assert!(!gap(101.0_f64.next_up(), 100.0).within_bound());
2376 assert!(!gap(99.0_f64.next_down(), 100.0).within_bound());
2377 assert_eq!(gap(101.0, 100.0).relative(), 0.01);
2378 assert_eq!(gap(99.0, 100.0).relative(), -0.01);
2379 assert!(!gap(0.0, 0.0).within_bound());
2380 assert!(!gap(-1.0, -1.0).within_bound());
2381 assert!(!gap(f64::NAN, 100.0).within_bound());
2382 assert!(!gap(100.0, f64::NAN).within_bound());
2383 assert_eq!(gap(101.004, 100.0).percent_text(), "+1.004%");
2385 assert_eq!(gap(98.9996, 100.0).percent_text(), "-1.0004%");
2386 assert_eq!(
2387 gap(101.0_f64.next_up(), 100.0).percent_text(),
2388 "+1.00000000000001%"
2389 );
2390 assert_eq!(gap(101.0, 100.0).percent_text(), "+1.00%");
2391 assert_eq!(gap(100.996, 100.0).percent_text(), "+1.00%");
2392 assert_eq!(gap(102.0, 100.0).percent_text(), "+2.00%");
2393 let past = gap(242.70152480324737, 240.2985394091558);
2395 assert!(!past.within_bound());
2396 assert_eq!(past.percent_text(), "+1.0000000000000002%");
2397 assert_eq!(gap(-1.0, -1.0).percent_text(), "n/a");
2398 }
2399
2400 #[test]
2403 fn a_stored_pass_its_figures_contradict_is_refused() {
2404 let flipped = bundled::CATALOG_JSON.replacen("\"passes\": true", "\"passes\": false", 1);
2405 assert!(matches!(
2406 Catalog::from_json(&flipped),
2407 Err(MotorError::Catalog(message)) if message.contains("stores passes: false")
2408 ));
2409 }
2410
2411 #[test]
2413 fn a_narrowed_read_refuses_a_contradicted_pass_it_keeps() {
2414 let flipped = bundled::CATALOG_JSON.replacen("\"passes\": true", "\"passes\": false", 1);
2415 assert!(matches!(
2416 Catalog::narrowed(&flipped, &|_| true),
2417 Err(MotorError::Catalog(message)) if message.contains("stores passes: false")
2418 ));
2419 }
2420
2421 #[test]
2424 fn a_narrowed_read_keeping_everything_is_the_catalog() {
2425 let whole = bundled();
2426 let narrowed = Catalog::narrowed(bundled::CATALOG_JSON, &|_| true).unwrap();
2427 assert_eq!(narrowed.motors, whole.motors);
2428 assert_eq!(narrowed.source, whole.source);
2429 assert_eq!(narrowed.selection, whole.selection);
2430 assert_eq!(narrowed.snapshot, whole.snapshot);
2431 }
2432
2433 #[test]
2436 fn a_narrowed_read_takes_each_motors_own_keys() {
2437 let mut catalog = bundled().clone();
2438 catalog.motors.truncate(3);
2439 catalog.motors[0].designation = "A\"8\\n\n \"designation\": \"Z9".to_owned();
2440 catalog.motors[1].common_name = "\n }\n ]".to_owned();
2441 let text = serde_json::to_string_pretty(&catalog).unwrap();
2442 let read = Catalog::narrowed(&text, &|_| true).unwrap();
2443 assert_eq!(read.motors, catalog.motors);
2444 let named = |name: String| {
2445 let name = std::cell::RefCell::new(name);
2446 Catalog::narrowed(&text, &|keys: &MotorKeys<'_>| {
2447 keys.designation == *name.borrow()
2448 })
2449 .unwrap()
2450 .motors
2451 .len()
2452 };
2453 assert_eq!(named(catalog.motors[0].designation.clone()), 1);
2454 assert_eq!(named("Z9".to_owned()), 0);
2455 let compact = serde_json::to_string(&catalog).unwrap();
2457 assert!(Catalog::narrowed(&compact, &|_| true).is_err());
2458 }
2459
2460 #[test]
2465 fn a_narrowed_catalog_finds_for_a_design_as_the_whole_one_does() {
2466 let whole = bundled();
2467 let ids = |found: Vec<&CatalogMotor>| -> Vec<String> {
2468 found.iter().map(|motor| motor.motor_id.clone()).collect()
2469 };
2470 let mut compared = 0;
2471 let mut shared = 0;
2472 for motor in whole.motors.iter().step_by(23) {
2473 let respelled = motor.designation.to_lowercase().replace('-', " ");
2474 for name in [
2475 motor.designation.as_str(),
2476 motor.common_name.as_str(),
2477 respelled.as_str(),
2478 ] {
2479 let narrow = Catalog::bundled_named([name]).unwrap();
2480 for maker in [
2481 motor.manufacturer.as_str(),
2482 motor.manufacturer_abbrev.as_str(),
2483 ] {
2484 for diameter_mm in [None, Some(motor.diameter_mm), Some(1.0)] {
2485 let expected = whole.find_for_design(maker, name, None, diameter_mm);
2486 shared += usize::from(expected.len() > 1);
2487 assert_eq!(
2488 ids(narrow.find_for_design(maker, name, None, diameter_mm)),
2489 ids(expected),
2490 "{maker} {name} at {diameter_mm:?}"
2491 );
2492 compared += 1;
2493 }
2494 }
2495 }
2496 }
2497 assert!(compared > 500, "{compared}");
2498 assert!(shared > 0, "no name found two motors, so the check is thin");
2499 assert!(Catalog::bundled_named(["Z9999"]).unwrap().motors.is_empty());
2501 }
2502
2503 #[test]
2506 fn the_snapshot_is_read_from_the_index_head() {
2507 assert_eq!(
2508 snapshot_in_head(bundled::CATALOG_JSON).as_ref(),
2509 Some(&bundled().snapshot)
2510 );
2511 assert_eq!(Catalog::bundled_snapshot().unwrap(), bundled().snapshot);
2512 let snapshot = r#""snapshot": { "files_url": "u", "captured": "c" }"#;
2513 assert!(snapshot_in_head(&format!(r#"{{ "motors": [], {snapshot} }}"#)).is_none());
2514 assert!(snapshot_in_head(&format!(r#"{{ {snapshot} }}"#)).is_none());
2515 assert!(snapshot_in_head(&format!(r#"{{ {snapshot}, "motors": [] }}"#)).is_some());
2516 }
2517
2518 #[test]
2520 fn a_catalog_narrowed_by_id_holds_those_motors() {
2521 let whole = bundled();
2522 let wanted = [&whole.motors[3], &whole.motors[700]];
2523 let narrow =
2524 Catalog::bundled_with_ids(wanted.iter().map(|motor| motor.motor_id.as_str())).unwrap();
2525 assert_eq!(narrow.motors.len(), 2);
2526 assert_eq!(&narrow.motors[0], wanted[0]);
2527 assert_eq!(&narrow.motors[1], wanted[1]);
2528 }
2529
2530 #[test]
2533 fn a_failing_gap_never_prints_inside_one_percent() {
2534 let mut checked = 0;
2535 for i in 0..20_000 {
2536 let stated = 0.1 + f64::from(i) * 1.999_37;
2537 for (start, step) in [(stated * 1.01, 1.0), (stated * 0.99, -1.0)] {
2538 let mut file: f64 = start;
2539 for _ in 0..4 {
2540 let gap = FigureGap {
2541 figure: CheckedFigure::TotalImpulse,
2542 file,
2543 stated,
2544 };
2545 if !gap.within_bound() {
2546 let text = gap.percent_text();
2547 assert!(!rounds_inside(&text), "{file} against {stated}: {text}");
2548 checked += 1;
2549 }
2550 file = if step > 0.0 {
2551 file.next_up()
2552 } else {
2553 file.next_down()
2554 };
2555 }
2556 }
2557 }
2558 assert!(checked > 100_000, "{checked}");
2559 }
2560
2561 #[test]
2565 fn each_figure_alone_fails_the_check_and_is_named() {
2566 let catalog = bundled();
2567 let motor = catalog.find("J760").next().unwrap();
2568 let curve = &motor.curves[0];
2569 let thrust = motor
2570 .thrust_curve(curve, bundled_curve_text(&curve.file).unwrap())
2571 .unwrap();
2572 let all = [
2573 CheckedFigure::TotalImpulse,
2574 CheckedFigure::AverageThrust,
2575 CheckedFigure::BurnTime,
2576 ];
2577 for (figure, scale, gap) in [
2578 (CheckedFigure::TotalImpulse, 1.02, "+2.00%"),
2579 (CheckedFigure::AverageThrust, 0.97, "-3.00%"),
2580 (CheckedFigure::BurnTime, 1.015, "+1.50%"),
2581 ] {
2582 let mut moved = motor.clone();
2583 let check = &curve.check;
2584 match figure {
2585 CheckedFigure::TotalImpulse => {
2586 moved.stated.total_impulse_ns = check.total_impulse_ns / scale;
2587 }
2588 CheckedFigure::AverageThrust => {
2589 moved.stated.average_thrust_n = check.average_thrust_n / scale;
2590 }
2591 CheckedFigure::BurnTime => moved.stated.burn_time_s = check.burn_time_s / scale,
2592 }
2593 moved.curves[0].check = CurveCheck::of(&thrust, &moved.stated);
2594 let moved_curve = &moved.curves[0];
2595 assert!(!moved_curve.check.passes, "{figure:?}");
2596 let failing = moved.failing_figures(moved_curve);
2597 assert_eq!(failing.len(), 1, "{figure:?}");
2598 assert_eq!(failing[0].figure, figure);
2599 assert!((failing[0].relative() - (scale - 1.0)).abs() < 1e-12);
2600 let warning = moved.check_warning(moved_curve).unwrap();
2601 assert_eq!(
2602 warning,
2603 format!(
2604 "1266J760-19A's curve file {} is more than 1% from ThrustCurve.org's \
2605 figures for it: {} {gap}",
2606 curve.simfile_id,
2607 figure.name()
2608 )
2609 );
2610 for other in all.iter().filter(|other| **other != figure) {
2611 assert!(!warning.contains(other.name()), "{warning}");
2612 }
2613 }
2614 }
2615
2616 #[test]
2620 fn files_rank_passing_first_then_by_format_and_source() {
2621 let catalog = bundled();
2622 let base = &catalog.motors[0];
2623 let file = |id: &str, format, source, passes| {
2624 let mut curve = base.curves[0].clone();
2625 curve.simfile_id = id.to_owned();
2626 curve.format = format;
2627 curve.source = source;
2628 curve.check.passes = passes;
2629 curve
2630 };
2631 use CurveFormat::{Rasp, RockSim};
2632 use CurveSource::{Certification, Manufacturer, User};
2633 let mut motor = base.clone();
2634 motor.curves = vec![
2635 file("user rasp pass", Rasp, User, true),
2636 file("cert rse fail", RockSim, Certification, false),
2637 file("cert rasp fail", Rasp, Certification, false),
2638 file("mfr rse pass", RockSim, Manufacturer, true),
2639 file("user rasp fail", Rasp, User, false),
2640 file("mfr rasp pass", Rasp, Manufacturer, true),
2641 file("user rasp pass 2", Rasp, User, true),
2642 ];
2643 let order: Vec<&str> = motor
2644 .ranked_curves()
2645 .iter()
2646 .map(|curve| curve.simfile_id.as_str())
2647 .collect();
2648 assert_eq!(
2649 order,
2650 [
2651 "mfr rasp pass",
2652 "user rasp pass",
2653 "user rasp pass 2",
2654 "mfr rse pass",
2655 "cert rasp fail",
2656 "user rasp fail",
2657 "cert rse fail",
2658 ]
2659 );
2660 }
2661
2662 #[test]
2665 fn every_motor_s_default_passes_where_one_of_its_files_does() {
2666 let catalog = bundled();
2667 let mut passing = 0;
2668 for motor in &catalog.motors {
2669 let default = motor.default_curve();
2670 assert_eq!(
2671 default.is_some(),
2672 !motor.curves.is_empty(),
2673 "{}",
2674 motor.designation
2675 );
2676 if motor.curves.iter().any(|c| c.check.passes) {
2677 passing += 1;
2678 assert!(
2679 default.is_some_and(|c| c.check.passes),
2680 "{}",
2681 motor.designation
2682 );
2683 }
2684 }
2685 assert_eq!(passing, 239);
2686 }
2687
2688 #[test]
2691 fn a_digest_takes_its_own_file_first() {
2692 let catalog = bundled();
2693 let table: serde_json::Value =
2694 serde_json::from_str(include_str!("../data/openrocket-curves.json")).unwrap();
2695 let mut moved = 0;
2697 for entry in table["files"].as_array().unwrap() {
2698 let digest = entry["digest"].as_str().unwrap();
2699 let mapped = crate::openrocket_curves::file_for(digest).unwrap();
2700 let Some(motor) = catalog
2701 .motors
2702 .iter()
2703 .find(|m| m.curves.iter().any(|c| c.simfile_id == mapped))
2704 else {
2705 continue;
2706 };
2707 let default = &motor.default_curve().unwrap().simfile_id;
2708 let picked = |digest| motor.curve_for_digest(digest).map(|(c, _)| &c.simfile_id);
2709 assert_eq!(picked(Some(digest)), Some(&mapped), "{digest}");
2710 assert_eq!(picked(None), Some(default));
2711 assert_eq!(
2712 picked(Some("00000000000000000000000000000000")),
2713 Some(default)
2714 );
2715 if *default != mapped {
2716 moved += 1;
2717 let other = table["files"]
2719 .as_array()
2720 .unwrap()
2721 .iter()
2722 .filter_map(|e| e["digest"].as_str())
2723 .find(|d| {
2724 crate::openrocket_curves::file_for(d)
2725 .is_some_and(|f| motor.curves.iter().all(|c| c.simfile_id != f))
2726 })
2727 .unwrap();
2728 assert_eq!(picked(Some(other)), Some(default));
2729 }
2730 }
2731 assert!(
2732 moved > 0,
2733 "no digest in the table picks a file other than its default"
2734 );
2735 }
2736
2737 #[test]
2741 fn a_light_propellant_file_warns_and_only_then() {
2742 let catalog = bundled();
2743 let (base, curve, file_g) = catalog
2744 .motors
2745 .iter()
2746 .find_map(|motor| {
2747 let (curve, text) = motor.default_curve_text()?;
2748 let (_, propellant_kg, _) = read_curve_file(curve, text).ok()?;
2749 (propellant_kg > 0.0).then(|| (motor, curve.clone(), propellant_kg * 1000.0))
2750 })
2751 .unwrap();
2752 let warning = |record_g: Option<f64>| {
2753 let mut motor = base.clone();
2754 motor.stated.propellant_mass_g = record_g;
2755 motor.propellant_warning(&curve)
2756 };
2757 let light = warning(Some(file_g / 0.949)).expect("5.1% light warns");
2758 assert!(light.contains("-5.10%"), "{light}");
2759 assert!(light.contains(&curve.simfile_id), "{light}");
2760 assert_eq!(warning(Some(file_g / 0.951)), None, "4.9% light");
2761 assert_eq!(warning(Some(file_g)), None, "equal");
2762 assert_eq!(warning(Some(file_g * 0.5)), None, "heavier");
2763 for record in [None, Some(0.0), Some(f64::NAN), Some(f64::INFINITY)] {
2764 assert_eq!(warning(record), None, "{record:?}");
2765 }
2766 let mut motor = base.clone();
2769 motor.stated.propellant_mass_g = Some(file_g / 0.9);
2770 motor.stated.total_mass_g = None;
2771 assert!(motor.mass_warnings(&curve).is_empty());
2772 let mut failing = curve.clone();
2773 failing.check.passes = false;
2774 let warnings = motor.flight_warnings(&failing);
2775 assert_eq!(warnings.len(), 2, "{warnings:?}");
2776 assert!(warnings[0].contains("is more than 1% from"), "{warnings:?}");
2777 assert!(warnings[1].contains("of propellant"), "{warnings:?}");
2778 }
2779
2780 #[test]
2783 fn flight_warnings_carry_their_kinds() {
2784 let catalog = bundled();
2785 let d8 = catalog
2786 .motors
2787 .iter()
2788 .find(|motor| motor.manufacturer_abbrev == "Quest" && motor.designation == "D8")
2789 .expect("the Quest D8");
2790 let curve = d8.default_curve().expect("a bundled file");
2791 let typed = d8.flight_warning_kinds(curve);
2792 let words: Vec<String> = typed.iter().map(|w| w.message.clone()).collect();
2793 assert_eq!(words, d8.flight_warnings(curve));
2794 let kinds: Vec<MotorWarningKind> = typed.iter().map(|w| w.kind).collect();
2795 assert!(
2796 kinds.ends_with(&[
2797 MotorWarningKind::HeavyLoadedMass,
2798 MotorWarningKind::PropellantShare
2799 ]),
2800 "{kinds:?}"
2801 );
2802 for motor in &catalog.motors {
2804 let Some(curve) = motor.default_curve() else {
2805 continue;
2806 };
2807 let typed: Vec<String> = motor
2808 .flight_warning_kinds(curve)
2809 .into_iter()
2810 .map(|w| w.message)
2811 .collect();
2812 assert_eq!(typed, motor.flight_warnings(curve), "{}", motor.designation);
2813 }
2814 }
2815
2816 #[test]
2821 fn a_record_with_no_burnout_mass_draws_no_burnout_warning() {
2822 let catalog = bundled();
2823 let (base, curve) = catalog
2824 .motors
2825 .iter()
2826 .find_map(|motor| {
2827 let curve = motor.default_curve()?;
2828 (motor.mass_warnings(curve).is_empty()
2829 && motor.total_mass_g.is_some()
2830 && motor.propellant_mass_g.is_some())
2831 .then_some((motor, curve))
2832 })
2833 .expect("a motor drawing no mass warning");
2834 let flown_g = base.total_mass_g.expect("a loaded mass");
2835 let burnout_g = flown_g - base.propellant_mass_g.expect("a propellant mass");
2836 let kinds = |record_propellant_g: f64| -> Vec<MotorWarning> {
2837 let mut motor = base.clone();
2838 motor.stated.total_mass_g = Some(flown_g);
2839 motor.stated.propellant_mass_g = Some(record_propellant_g);
2840 motor.flight_warning_kinds(curve)
2841 };
2842 let burnout = |warnings: &[MotorWarning]| {
2843 warnings
2844 .iter()
2845 .filter(|w| w.kind == MotorWarningKind::BurnoutMass)
2846 .count()
2847 };
2848 let control = kinds(flown_g - 0.5 * burnout_g);
2851 assert_eq!(burnout(&control), 1, "{control:?}");
2852 for record_propellant_g in [flown_g, flown_g * 1.2] {
2854 let warnings = kinds(record_propellant_g);
2855 assert_eq!(burnout(&warnings), 0, "{record_propellant_g}: {warnings:?}");
2856 for warning in &warnings {
2857 assert!(
2858 !warning.message.contains("inf") && !warning.message.contains("NaN"),
2859 "{warning:?}"
2860 );
2861 }
2862 }
2863 }
2864
2865 #[test]
2871 fn a_loaded_mass_far_from_its_record_warns_naming_both() {
2872 let catalog = bundled();
2873 let d8 = catalog
2874 .motors
2875 .iter()
2876 .find(|motor| motor.manufacturer_abbrev == "Quest" && motor.designation == "D8")
2877 .expect("the Quest D8");
2878 assert_eq!(d8.stated.total_mass_g, Some(45.6));
2879 let curve = d8.default_curve().expect("a bundled file");
2880 let warnings = d8.mass_warnings(curve);
2881 assert_eq!(warnings.len(), 2, "{warnings:?}");
2882 assert!(
2883 warnings[0].contains(
2884 "a loaded mass of 454.0 g, +895.6% from ThrustCurve.org's record of 45.6 g"
2885 ),
2886 "{warnings:?}"
2887 );
2888 assert!(
2889 warnings[1].contains("a propellant share of 4.8%"),
2890 "{warnings:?}"
2891 );
2892 assert!(
2893 warnings[1].contains("outside the 11.5% to 75%"),
2894 "{warnings:?}"
2895 );
2896 assert!(d8.flight_warnings(curve).ends_with(&warnings));
2897
2898 let (base, curve) = catalog
2900 .motors
2901 .iter()
2902 .find_map(|motor| {
2903 let curve = motor.default_curve()?;
2904 (motor.mass_warnings(curve).is_empty() && motor.stated.total_mass_g.is_some())
2905 .then_some((motor, curve))
2906 })
2907 .expect("a motor drawing no mass warning");
2908 let flown_g = base.total_mass_g.expect("a loaded mass");
2909 let flown_propellant_g = base.propellant_mass_g.expect("a propellant mass");
2910 let warning = |record_g: Option<f64>| {
2913 let mut motor = base.clone();
2914 motor.stated.total_mass_g = record_g;
2915 motor.stated.propellant_mass_g = record_g.map(|g| flown_propellant_g * g / flown_g);
2916 motor.mass_warnings(curve)
2917 };
2918 let heavy = warning(Some(flown_g / 1.051));
2919 assert_eq!(heavy.len(), 1, "5.1% heavy: {heavy:?}");
2920 assert!(heavy[0].contains("a loaded mass of"), "{heavy:?}");
2921 assert!(heavy[0].contains("+5.1%"), "{heavy:?}");
2922 let light = warning(Some(flown_g / 0.949));
2923 assert_eq!(light.len(), 1, "5.1% light: {light:?}");
2924 assert!(light[0].contains("a loaded mass of"), "{light:?}");
2925 assert!(light[0].contains("-5.1%"), "{light:?}");
2926 assert!(warning(Some(flown_g / 1.049)).is_empty(), "4.9% heavy");
2927 assert!(warning(Some(flown_g / 0.951)).is_empty(), "4.9% light");
2928 for record in [None, Some(0.0), Some(f64::INFINITY)] {
2929 assert!(warning(record).is_empty(), "{record:?}");
2930 }
2931 assert_eq!(
2932 warning(Some(f64::NAN)).len(),
2933 0,
2934 "a NaN record is no record"
2935 );
2936
2937 let flown_burnout_g = flown_g - flown_propellant_g;
2941 let burnout = |gap: f64| {
2942 let mut motor = base.clone();
2944 motor.stated.total_mass_g = Some(flown_g);
2945 motor.stated.propellant_mass_g = Some(flown_g - flown_burnout_g / (1.0 + gap));
2946 motor.mass_warnings(curve)
2947 };
2948 for (gap, said) in [(0.051, "+5.1%"), (-0.051, "-5.1%")] {
2949 let warnings = burnout(gap);
2950 assert_eq!(warnings.len(), 1, "{gap}: {warnings:?}");
2951 let record_burnout = format!("gives {:.1} g", flown_burnout_g / (1.0 + gap));
2952 assert!(warnings[0].contains("burnout mass"), "{warnings:?}");
2953 assert!(
2954 warnings[0].contains(&record_burnout) && warnings[0].contains(said),
2955 "{record_burnout} {said}: {warnings:?}"
2956 );
2957 assert!(
2959 (flown_burnout_g / (1.0 + gap) - flown_burnout_g).abs()
2960 < LOADED_MASS_BOUND * flown_g,
2961 "the earlier bound passed it"
2962 );
2963 }
2964 for gap in [0.049, -0.049] {
2965 assert!(burnout(gap).is_empty(), "{gap}");
2966 }
2967 let mut light_case = base.clone();
2970 light_case.stated.total_mass_g = Some(flown_g / 0.951);
2971 light_case.stated.propellant_mass_g = Some(flown_propellant_g);
2972 let warnings = light_case.mass_warnings(curve);
2973 assert_eq!(warnings.len(), 1, "{warnings:?}");
2974 assert!(warnings[0].contains("burnout mass"), "{warnings:?}");
2975 }
2976
2977 #[test]
2981 fn a_non_default_file_is_warned_of_the_propellant_it_flies() {
2982 let catalog = bundled();
2983 let mut checked = 0;
2984 for motor in &catalog.motors {
2985 let Some(record_g) = motor.stated.propellant_mass_g.filter(|g| *g > 0.0) else {
2986 continue;
2987 };
2988 let Some(flown_g) = motor.propellant_mass_g else {
2989 continue;
2990 };
2991 for curve in &motor.curves {
2992 if bundled_curve_text(&curve.file).is_none() {
2993 continue;
2994 }
2995 let short = flown_g < record_g * (1.0 - PROPELLANT_SHORT_BOUND);
2996 assert_eq!(
2997 motor.propellant_warning(curve).is_some(),
2998 short,
2999 "{} {}",
3000 motor.designation,
3001 curve.simfile_id
3002 );
3003 checked += 1;
3004 }
3005 }
3006 assert!(checked > 1_000, "{checked}");
3007 let i225 = catalog
3008 .motors
3009 .iter()
3010 .find(|motor| motor.designation == "I225FJ")
3011 .expect("the I225FJ");
3012 let other = i225
3013 .curves
3014 .iter()
3015 .find(|curve| {
3016 Some(curve.simfile_id.as_str())
3017 != i225.default_curve().map(|c| c.simfile_id.as_str())
3018 && bundled_curve_text(&curve.file).is_some()
3019 })
3020 .expect("a second bundled file");
3021 let warning = i225.propellant_warning(other).expect("warns");
3022 assert!(
3023 warning.contains("the default file's 241.7 g of propellant"),
3024 "{warning}"
3025 );
3026 assert!(warning.contains("record of 264.0 g"), "{warning}");
3027 }
3028
3029 #[test]
3032 fn the_propellant_share_span_is_the_records() {
3033 let shares: Vec<f64> = bundled()
3034 .motors
3035 .iter()
3036 .filter_map(|motor| Some(motor.stated.propellant_mass_g? / motor.stated.total_mass_g?))
3037 .filter(|share| share.is_finite() && *share > 0.0)
3038 .collect();
3039 let impossible = shares.iter().filter(|share| **share > 1.0).count();
3040 assert_eq!(impossible, 1);
3041 let possible = shares.iter().copied().filter(|share| *share <= 1.0);
3042 let low = possible.clone().fold(f64::INFINITY, f64::min);
3043 let high = possible.fold(f64::NEG_INFINITY, f64::max);
3044 assert_eq!((low, high), PROPELLANT_SHARE_SPAN);
3045 }
3046
3047 #[test]
3051 fn a_name_never_picks_one_maker_over_another() {
3052 let catalog = bundled();
3053 for motor in &catalog.motors {
3054 for name in [&motor.designation, &motor.common_name] {
3055 let shadowed = normalize(name) != normalize(&motor.designation)
3056 && catalog.motors.iter().any(|other| {
3057 other.manufacturer == motor.manufacturer
3058 && normalize(&other.designation) == normalize(name)
3059 });
3060 let found = catalog.find(name).any(|other| std::ptr::eq(other, motor));
3061 assert_eq!(found, !shadowed, "{} by {name}", motor.motor_id);
3062 }
3063 }
3064 for name in ["G80", "J300"] {
3065 let makers: std::collections::BTreeSet<&str> = catalog
3066 .find(name)
3067 .map(|motor| motor.manufacturer.as_str())
3068 .collect();
3069 assert!(makers.len() > 1, "{name}: {makers:?}");
3070 }
3071 }
3072
3073 #[test]
3076 fn normalized_is_is_normalize_compared() {
3077 let catalog = bundled();
3078 let names: Vec<&str> = catalog
3079 .motors
3080 .iter()
3081 .take(200)
3082 .flat_map(|motor| [motor.designation.as_str(), motor.common_name.as_str()])
3083 .chain(["", "J 760", "j-760", "1266J760-19A", "ÄÖ", "K\u{a0}940"])
3084 .collect();
3085 for name in &names {
3086 for other in &names {
3087 let key = normalize(other);
3088 assert_eq!(
3089 normalized_is(name, &key),
3090 normalize(name) == key,
3091 "{name} {other}"
3092 );
3093 }
3094 }
3095 }
3096
3097 #[test]
3102 fn a_design_s_case_size_keeps_a_common_name_from_flying_another_motor() {
3103 let catalog = bundled();
3104 let found = |maker: &str, diameter_mm: Option<f64>| -> Vec<(String, f64)> {
3105 catalog
3106 .find_for_design(maker, "J360", None, diameter_mm)
3107 .into_iter()
3108 .map(|motor| (motor.designation.clone(), motor.diameter_mm))
3109 .collect()
3110 };
3111 let small = vec![("J360".to_owned(), 38.0)];
3112 assert_eq!(found("Cesaroni Technology", None), small);
3113 assert_eq!(found("Cesaroni Technology", Some(38.4)), small);
3114 assert_eq!(found("Cesaroni Technology Inc.", Some(38.0)), small);
3115 assert_eq!(found("Cesaroni", Some(54.0)).len(), 2);
3116 assert_eq!(
3117 catalog
3118 .find_by_maker("Cesaroni Technology Inc.", "J360")
3119 .count(),
3120 1
3121 );
3122 }
3123
3124 #[test]
3129 fn a_mount_s_bore_keeps_a_common_name_from_flying_another_motor() {
3130 let catalog = bundled();
3131 let found = |name: &str, bore_mm: f64| -> Vec<(String, f64)> {
3132 let mut found: Vec<(String, f64)> = catalog
3133 .find_for_bore(name, bore_mm)
3134 .into_iter()
3135 .map(|motor| (motor.designation.clone(), motor.diameter_mm))
3136 .collect();
3137 found.sort_by(|a, b| a.0.cmp(&b.0));
3138 found
3139 };
3140 let both = vec![("1016J360-15A".to_owned(), 54.0), ("J360".to_owned(), 38.0)];
3141 let small = vec![("J360".to_owned(), 38.0)];
3142 assert_eq!(found("J360", 55.1), both);
3144 assert_eq!(found("J360", 54.0), both);
3145 assert_eq!(found("Cesaroni J360", 54.0), both);
3146 assert_eq!(found("J360", 38.4), small);
3148 assert_eq!(found("J360", 37.5), small);
3149 assert_eq!(found("J360", 76.2), both);
3151 assert_eq!(
3153 found("1016J360-15A", 38.4),
3154 vec![("1016J360-15A".to_owned(), 54.0)]
3155 );
3156 for (name, bore_mm) in [("H128W", 29.0), ("G80", 29.0), ("K1100T", 55.1)] {
3158 let find: Vec<&str> = catalog.find(name).map(|m| m.designation.as_str()).collect();
3159 let bore: Vec<&str> = catalog
3160 .find_for_bore(name, bore_mm)
3161 .into_iter()
3162 .map(|m| m.designation.as_str())
3163 .collect();
3164 assert_eq!(bore, find, "{name}");
3165 }
3166 }
3167
3168 #[test]
3172 fn the_default_file_passes_where_a_bundled_one_does() {
3173 let catalog = bundled();
3174 let base = catalog
3175 .motors
3176 .iter()
3177 .find(|m| m.curves.first().is_some_and(|c| c.check.passes))
3178 .unwrap();
3179 let passing = base.curves[0].clone();
3180 let mut failing = passing.clone();
3181 failing.simfile_id = "failing".to_owned();
3182 failing.check.passes = false;
3183 let mut not_bundled = passing.clone();
3184 not_bundled.simfile_id = "not bundled".to_owned();
3185 not_bundled.file = "curves/not-bundled.eng".to_owned();
3186 let mut motor = base.clone();
3187 motor.curves = vec![failing.clone(), passing.clone()];
3188 assert_eq!(motor.default_curve(), Some(&passing));
3189 motor.curves = vec![not_bundled.clone(), failing.clone()];
3190 assert_eq!(motor.default_curve(), Some(&failing));
3191 assert!(motor.bundled_motor().is_ok());
3192 motor.curves = vec![not_bundled];
3193 assert_eq!(motor.default_curve(), None);
3194 assert!(matches!(
3195 motor.bundled_motor(),
3196 Err(MotorError::Inconsistent(message)) if message.contains("no bundled curve")
3197 ));
3198 }
3199}