1use std::f64::consts::PI;
31
32use serde::{Deserialize, Serialize};
33
34use crate::curve::ThrustCurve;
35use crate::error::MotorError;
36use crate::grains::BatesGrains;
37use crate::mass::MassElement;
38
39pub const UNITS_HINT: &str = "check the units of the masses and the curve";
43
44pub const STANDARD_SEA_LEVEL_PRESSURE_PA: f64 = 101_325.0;
50
51#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
53#[serde(deny_unknown_fields)]
54pub struct PropellantColumn {
55 pub mass_kg: f64,
57 pub center_m: f64,
59 pub outer_radius_m: f64,
61 pub inner_radius_m: f64,
63 pub length_m: f64,
65}
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
72#[serde(tag = "model", rename_all = "snake_case")]
73#[non_exhaustive]
74pub enum Propellant {
75 Column(PropellantColumn),
77 Grains(BatesGrains),
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
83#[serde(deny_unknown_fields)]
84pub struct Nozzle {
85 pub exit_radius_m: f64,
87 pub throat_radius_m: Option<f64>,
89 #[serde(deserialize_with = "Option::deserialize")]
103 #[schemars(required, extend("type" = ["number", "null"]))]
105 pub reference_pressure_pa: Option<f64>,
106}
107
108impl Nozzle {
109 pub fn exit_area_m2(&self) -> f64 {
111 PI * self.exit_radius_m * self.exit_radius_m
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
121#[serde(try_from = "MotorData", into = "MotorData")]
122pub struct SolidMotor {
123 curve: ThrustCurve,
124 propellant: Propellant,
125 dry: MassElement,
126 nozzle: Option<Nozzle>,
127 propellant_mass_kg: f64,
129}
130
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
133#[serde(deny_unknown_fields)]
134struct MotorData {
135 curve: ThrustCurve,
136 propellant: Propellant,
137 dry: MassElement,
138 nozzle: Option<Nozzle>,
139}
140
141impl TryFrom<MotorData> for SolidMotor {
142 type Error = MotorError;
143
144 fn try_from(data: MotorData) -> Result<Self, Self::Error> {
145 Self::new(data.curve, data.propellant, data.dry, data.nozzle)
146 }
147}
148
149impl From<SolidMotor> for MotorData {
150 fn from(motor: SolidMotor) -> Self {
151 Self {
152 curve: motor.curve,
153 propellant: motor.propellant,
154 dry: motor.dry,
155 nozzle: motor.nozzle,
156 }
157 }
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
162pub struct MotorState {
163 pub time_s: f64,
165 pub thrust_n: f64,
167 pub mass_flow_kg_s: f64,
170 pub propellant: MassElement,
172 pub total: MassElement,
174}
175
176pub const EXHAUST_VELOCITY_RANGE_M_S: std::ops::RangeInclusive<f64> = 200.0..=5000.0;
199
200impl SolidMotor {
201 pub fn new(
216 curve: ThrustCurve,
217 propellant: Propellant,
218 dry: MassElement,
219 nozzle: Option<Nozzle>,
220 ) -> Result<Self, MotorError> {
221 dry.validate([
222 "dry mass (kg)",
223 "dry center of mass (m)",
224 "dry axial inertia (kg·m²)",
225 "dry transverse inertia (kg·m²)",
226 ])?;
227 if dry.mass_kg <= 0.0 {
228 return Err(MotorError::Domain {
229 what: "dry mass (kg), which must be positive",
230 value: dry.mass_kg,
231 });
232 }
233 let propellant_mass_kg = match &propellant {
234 Propellant::Column(column) => {
235 for (value, what) in [
236 (column.mass_kg, "propellant mass (kg)"),
237 (column.outer_radius_m, "propellant outer radius (m)"),
238 (column.length_m, "propellant length (m)"),
239 ] {
240 if !(value.is_finite() && value > 0.0) {
241 return Err(MotorError::Domain { what, value });
242 }
243 }
244 if !column.center_m.is_finite() {
245 return Err(MotorError::Domain {
246 what: "propellant center (m)",
247 value: column.center_m,
248 });
249 }
250 if !(column.inner_radius_m.is_finite() && column.inner_radius_m >= 0.0) {
251 return Err(MotorError::Domain {
252 what: "propellant bore radius (m)",
253 value: column.inner_radius_m,
254 });
255 }
256 if column.inner_radius_m >= column.outer_radius_m {
257 return Err(MotorError::Inconsistent(format!(
258 "propellant bore radius {} m is not inside the outer radius {} m",
259 column.inner_radius_m, column.outer_radius_m
260 )));
261 }
262 column.mass_kg
263 }
264 Propellant::Grains(grains) => {
265 grains.validate()?;
266 grains.initial_mass_kg()
267 }
268 };
269 if let Some(nozzle) = &nozzle {
270 if !(nozzle.exit_radius_m.is_finite() && nozzle.exit_radius_m > 0.0) {
271 return Err(MotorError::Domain {
272 what: "nozzle exit radius (m)",
273 value: nozzle.exit_radius_m,
274 });
275 }
276 if let Some(throat) = nozzle.throat_radius_m
277 && !(throat.is_finite() && throat > 0.0 && throat <= nozzle.exit_radius_m)
278 {
279 return Err(MotorError::Domain {
280 what: "nozzle throat radius (m), which must be in (0, exit radius]",
281 value: throat,
282 });
283 }
284 if let Some(reference) = nozzle.reference_pressure_pa
285 && !(reference.is_finite() && reference >= 0.0)
286 {
287 return Err(MotorError::Domain {
288 what: "thrust-curve reference pressure (Pa)",
289 value: reference,
290 });
291 }
292 }
293 let exhaust_velocity_m_s = curve.total_impulse_ns() / propellant_mass_kg;
297 if !EXHAUST_VELOCITY_RANGE_M_S.contains(&exhaust_velocity_m_s) {
298 return Err(MotorError::Inconsistent(format!(
299 "a total impulse of {} N·s from {propellant_mass_kg} kg of propellant is an \
300 effective exhaust velocity of {exhaust_velocity_m_s} m/s. A solid motor can have \
301 only {} to {} m/s; {UNITS_HINT}",
302 curve.total_impulse_ns(),
303 EXHAUST_VELOCITY_RANGE_M_S.start(),
304 EXHAUST_VELOCITY_RANGE_M_S.end()
305 )));
306 }
307 Ok(Self {
308 curve,
309 propellant,
310 dry,
311 nozzle,
312 propellant_mass_kg,
313 })
314 }
315
316 pub fn from_envelope(
336 curve: ThrustCurve,
337 diameter_m: f64,
338 length_m: f64,
339 propellant_mass_kg: f64,
340 loaded_mass_kg: f64,
341 ) -> Result<Self, MotorError> {
342 for (value, what) in [
343 (propellant_mass_kg, "propellant mass (kg)"),
344 (loaded_mass_kg, "loaded motor mass (kg)"),
345 (diameter_m, "motor diameter (m)"),
346 (length_m, "motor length (m)"),
347 ] {
348 if !(value.is_finite() && value > 0.0) {
349 return Err(MotorError::Domain { what, value });
350 }
351 }
352 if propellant_mass_kg >= loaded_mass_kg {
353 return Err(MotorError::Inconsistent(format!(
354 "propellant mass {propellant_mass_kg} kg is not below the loaded mass \
355 {loaded_mass_kg} kg"
356 )));
357 }
358 let radius = 0.5 * diameter_m;
359 let center = 0.5 * length_m;
360 let column = PropellantColumn {
361 mass_kg: propellant_mass_kg,
362 center_m: center,
363 outer_radius_m: radius,
364 inner_radius_m: 0.0,
365 length_m,
366 };
367 let dry = MassElement::thin_tube(
368 loaded_mass_kg - propellant_mass_kg,
369 center,
370 radius,
371 length_m,
372 );
373 Self::new(curve, Propellant::Column(column), dry, None)
374 }
375
376 pub fn with_added_dry_mass(mut self, hardware: MassElement) -> Result<Self, MotorError> {
384 hardware.validate([
385 "added dry mass (kg)",
386 "added dry mass center (m)",
387 "added dry axial inertia (kg·m²)",
388 "added dry transverse inertia (kg·m²)",
389 ])?;
390 self.dry = MassElement::combine([&self.dry, &hardware]);
391 Ok(self)
392 }
393
394 pub fn curve(&self) -> &ThrustCurve {
396 &self.curve
397 }
398
399 pub fn propellant(&self) -> &Propellant {
401 &self.propellant
402 }
403
404 pub fn dry(&self) -> MassElement {
406 self.dry
407 }
408
409 pub fn nozzle(&self) -> Option<Nozzle> {
411 self.nozzle
412 }
413
414 pub fn propellant_initial_mass_kg(&self) -> f64 {
416 self.propellant_mass_kg
417 }
418
419 pub fn exhaust_velocity_m_s(&self) -> f64 {
421 self.curve.total_impulse_ns() / self.propellant_mass_kg
422 }
423
424 pub fn burnout_time_s(&self) -> f64 {
426 self.curve.end_time_s()
427 }
428
429 pub fn propellant_mass_kg(&self, t: f64) -> f64 {
431 if t.is_nan() {
432 return f64::NAN;
433 }
434 let fraction = self.curve.impulse_ns(t) / self.curve.total_impulse_ns();
435 (self.propellant_mass_kg * (1.0 - fraction)).max(0.0)
436 }
437
438 pub fn mass_flow_kg_s(&self, t: f64) -> f64 {
441 self.curve.thrust_n(t) / self.exhaust_velocity_m_s()
442 }
443
444 pub fn state(&self, t: f64) -> MotorState {
447 let thrust_n = self.curve.thrust_n(t);
448 let mass = self.propellant_mass_kg(t);
449 let propellant = match &self.propellant {
450 Propellant::Column(column) => MassElement::hollow_cylinder(
451 mass,
452 column.center_m,
453 column.outer_radius_m,
454 column.inner_radius_m,
455 column.length_m,
456 ),
457 Propellant::Grains(grains) => grains.mass_element(mass),
458 };
459 MotorState {
460 time_s: t,
461 thrust_n,
462 mass_flow_kg_s: thrust_n / self.exhaust_velocity_m_s(),
463 propellant,
464 total: MassElement::combine([&self.dry, &propellant]),
465 }
466 }
467
468 pub fn thrust_at_pressure_n(&self, t: f64, ambient_pa: f64) -> f64 {
479 let thrust = self.curve.thrust_n(t);
480 match self.nozzle {
481 Some(
482 nozzle @ Nozzle {
483 reference_pressure_pa: Some(reference_pa),
484 ..
485 },
486 ) if t > 0.0 && t < self.curve.end_time_s() && (thrust > 0.0 || thrust.is_nan()) => {
487 let corrected = thrust + (reference_pa - ambient_pa) * nozzle.exit_area_m2();
488 if corrected.is_nan() {
489 corrected
490 } else {
491 corrected.max(0.0)
492 }
493 }
494 _ => thrust,
495 }
496 }
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502
503 fn curve() -> ThrustCurve {
504 ThrustCurve::new(vec![0.0, 0.1, 1.0, 1.2], vec![0.0, 500.0, 400.0, 0.0]).unwrap()
505 }
506
507 #[test]
508 fn column_mass_follows_the_impulse_fraction() {
509 let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
510 let total = motor.curve().total_impulse_ns();
511 assert!((total - (25.0 + 405.0 + 40.0)).abs() < 1e-12);
512 assert!((motor.exhaust_velocity_m_s() - total / 0.3).abs() < 1e-9);
513 for t in [-1.0, 0.0, 0.05, 0.5, 1.1, 1.2, 5.0] {
514 let state = motor.state(t);
515 let expected = 0.3 * (1.0 - motor.curve().impulse_ns(t) / total);
516 assert!((state.propellant.mass_kg - expected).abs() < 1e-15, "{t}");
517 assert!((state.total.mass_kg - (0.3 + expected)).abs() < 1e-15);
518 assert!(
519 (state.mass_flow_kg_s * motor.exhaust_velocity_m_s() - state.thrust_n).abs() < 1e-9
520 );
521 }
522 assert_eq!(motor.state(0.0).propellant.mass_kg, 0.3);
523 assert_eq!(motor.state(1.2).propellant.mass_kg, 0.0);
524 let n = 12_000;
526 let dt = 1.2 / f64::from(n);
527 let burned: f64 = (0..n)
528 .map(|i| {
529 let (a, b) = (f64::from(i) * dt, f64::from(i + 1) * dt);
530 0.5 * (motor.state(a).mass_flow_kg_s + motor.state(b).mass_flow_kg_s) * dt
531 })
532 .sum();
533 assert!((burned - 0.3).abs() < 1e-6, "{burned}");
534 }
535
536 #[test]
537 fn the_mass_flow_alone_is_the_states_to_the_bit() {
538 let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
541 let grid = (0..=1_200).map(|i| f64::from(i) * 1e-3);
544 for t in [-1.0, 5.0].into_iter().chain(grid) {
545 assert_eq!(
546 motor.mass_flow_kg_s(t).to_bits(),
547 motor.state(t).mass_flow_kg_s.to_bits(),
548 "{t}"
549 );
550 }
551 }
552
553 #[test]
554 fn a_units_slip_is_refused_by_its_exhaust_velocity() {
555 let i175 = ThrustCurve::new(vec![0.0, 0.1, 2.3, 2.4], vec![0.0, 220.0, 150.0, 0.0])
560 .expect("a plausible I-class curve");
561 let impulse = i175.total_impulse_ns();
563 assert!((impulse - 425.5).abs() < 0.1, "{impulse}");
564 let slipped = SolidMotor::from_envelope(i175.clone(), 38.0, 245.0, 228.9, 437.5)
565 .expect_err("millimeters and grams read as meters and kilograms");
566 assert!(
567 matches!(&slipped, MotorError::Inconsistent(message)
568 if message.contains("exhaust velocity") && message.contains("check the units")),
569 "{slipped}"
570 );
571 let motor = SolidMotor::from_envelope(i175.clone(), 0.038, 0.245, 0.2289, 0.4375)
575 .expect("the same motor in meters and kilograms");
576 let c = motor.curve().total_impulse_ns() / motor.propellant_mass_kg(0.0);
577 assert!((1700.0..1900.0).contains(&c), "{c}");
578
579 let dry = MassElement::thin_tube(0.2086, 0.1225, 0.019, 0.245);
581 let column = PropellantColumn {
582 mass_kg: 2.289,
583 center_m: 0.1225,
584 outer_radius_m: 0.017,
585 inner_radius_m: 0.005,
586 length_m: 0.2,
587 };
588 let ten_times = SolidMotor::new(i175, Propellant::Column(column), dry, None)
589 .expect_err("ten times the propellant for the same impulse");
590 assert!(
591 matches!(&ten_times, MotorError::Inconsistent(message) if message.contains("185.8")),
593 "{ten_times}"
594 );
595
596 assert!(!EXHAUST_VELOCITY_RANGE_M_S.contains(&1.8));
597 }
598
599 #[test]
600 fn every_bundled_motor_is_inside_the_range() {
601 let catalog = crate::Catalog::bundled().expect("the bundled catalog parses");
606 let mut lowest = f64::INFINITY;
607 let mut highest: f64 = 0.0;
608 let (mut low_name, mut high_name) = (String::new(), String::new());
609 for entry in catalog.motors.iter().filter(|m| !m.curves.is_empty()) {
610 let motor = entry
611 .bundled_motor()
612 .unwrap_or_else(|error| panic!("{}: {error}", entry.designation));
613 let c = motor.curve().total_impulse_ns() / motor.propellant_mass_kg(0.0);
614 assert!(
615 EXHAUST_VELOCITY_RANGE_M_S.contains(&c),
616 "{}: c = {c} m/s",
617 entry.designation
618 );
619 if c < lowest {
620 lowest = c;
621 low_name = entry.common_name.clone();
622 }
623 if c > highest {
624 highest = c;
625 high_name = entry.common_name.clone();
626 }
627 }
628 assert!((lowest - 296.83).abs() < 0.01, "{low_name} at {lowest}");
630 assert!((highest - 4128.18).abs() < 0.01, "{high_name} at {highest}");
631 }
632
633 #[test]
634 fn a_curve_ending_above_zero_is_empty_and_silent_at_its_end() {
635 let cut = ThrustCurve::new(vec![0.0, 1.0], vec![20.0, 20.0]).unwrap();
636 let motor = SolidMotor::from_envelope(cut, 0.038, 0.25, 0.01, 0.5).unwrap();
639 let before = motor.state(1.0 - 1e-9);
640 assert_eq!(before.thrust_n, 20.0);
641 assert!(before.mass_flow_kg_s > 0.0 && before.propellant.mass_kg > 0.0);
642 let end = motor.state(motor.burnout_time_s());
643 assert_eq!(
644 (end.thrust_n, end.mass_flow_kg_s, end.propellant.mass_kg),
645 (0.0, 0.0, 0.0)
646 );
647 assert_eq!(end.total.mass_kg, 0.49);
648 }
649
650 #[test]
651 fn envelope_defaults_are_centered_tubes_and_columns() {
652 let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
653 let loaded = motor.state(0.0);
654 assert_eq!(loaded.total.cg_m, 0.125);
655 let r2 = 0.019f64 * 0.019;
656 let dry_axial = 0.3 * r2;
657 let prop_axial = 0.5 * 0.3 * r2;
658 assert!((loaded.total.axial_inertia_kg_m2 - (dry_axial + prop_axial)).abs() < 1e-15);
659 let dry_t = 0.3 * (r2 / 2.0 + 0.25f64.powi(2) / 12.0);
660 let prop_t = 0.3 * (r2 / 4.0 + 0.25f64.powi(2) / 12.0);
661 assert!((loaded.total.transverse_inertia_kg_m2 - (dry_t + prop_t)).abs() < 1e-15);
662 assert!(motor.nozzle().is_none());
663 assert_eq!(
664 motor.thrust_at_pressure_n(0.5, 0.0),
665 motor.curve().thrust_n(0.5)
666 );
667 }
668
669 #[test]
670 fn pressure_correction_uses_the_exit_area() {
671 let dry = MassElement::thin_tube(0.3, 0.125, 0.019, 0.25);
672 let column = PropellantColumn {
673 mass_kg: 0.3,
674 center_m: 0.15,
675 outer_radius_m: 0.017,
676 inner_radius_m: 0.005,
677 length_m: 0.2,
678 };
679 let nozzle = Nozzle {
680 exit_radius_m: 0.01,
681 throat_radius_m: Some(0.004),
682 reference_pressure_pa: Some(STANDARD_SEA_LEVEL_PRESSURE_PA),
683 };
684 let motor =
685 SolidMotor::new(curve(), Propellant::Column(column), dry, Some(nozzle)).unwrap();
686 let area = PI * 1e-4;
687 let f = motor.curve().thrust_n(0.5);
688 let vacuum = motor.thrust_at_pressure_n(0.5, 0.0);
689 assert!((vacuum - (f + 101_325.0 * area)).abs() < 1e-9);
690 assert_eq!(motor.thrust_at_pressure_n(0.5, 101_325.0), f);
691 assert_eq!(motor.thrust_at_pressure_n(2.0, 0.0), 0.0);
692 assert_eq!(motor.thrust_at_pressure_n(0.001, 1e9), 0.0);
693 let high = SolidMotor::new(
695 curve(),
696 Propellant::Column(column),
697 dry,
698 Some(Nozzle {
699 reference_pressure_pa: Some(80_000.0),
700 ..nozzle
701 }),
702 )
703 .unwrap();
704 assert!((high.thrust_at_pressure_n(0.5, 0.0) - (f + 80_000.0 * area)).abs() < 1e-9);
705 assert!((high.thrust_at_pressure_n(0.5, 101_325.0) - (f - 21_325.0 * area)).abs() < 1e-9);
706 let uncorrected = SolidMotor::new(
709 curve(),
710 Propellant::Column(column),
711 dry,
712 Some(Nozzle {
713 reference_pressure_pa: None,
714 ..nozzle
715 }),
716 )
717 .unwrap();
718 for pressure in [0.0, 50_000.0, 101_325.0, 1e9] {
719 assert_eq!(uncorrected.thrust_at_pressure_n(0.5, pressure), f);
720 }
721 let read = |text: &str| serde_json::from_str::<Nozzle>(text);
724 assert_eq!(
725 read(
726 r#"{"exit_radius_m": 0.01, "throat_radius_m": null, "reference_pressure_pa": null}"#
727 )
728 .unwrap()
729 .reference_pressure_pa,
730 None
731 );
732 assert!(read(r#"{"exit_radius_m": 0.01, "throat_radius_m": null}"#).is_err());
733 assert_eq!(motor.thrust_at_pressure_n(0.0, 0.0), 0.0);
735 assert_eq!(motor.thrust_at_pressure_n(1.2, 0.0), 0.0);
736 assert!(motor.thrust_at_pressure_n(0.5, f64::NAN).is_nan());
737 assert!(motor.thrust_at_pressure_n(f64::NAN, 0.0).is_nan());
738 let state = motor.state(f64::NAN);
740 assert!(state.total.mass_kg.is_nan() && state.propellant.mass_kg.is_nan());
741 assert!(state.total.cg_m.is_nan());
742 let gap = ThrustCurve::new(
746 vec![0.0, 1.0, 1.0, 2.0, 2.0, 3.0],
747 vec![400.0, 400.0, 0.0, 0.0, 400.0, 0.0],
748 )
749 .unwrap();
750 let gapped = SolidMotor::new(gap, Propellant::Column(column), dry, Some(nozzle)).unwrap();
751 assert_eq!(gapped.thrust_at_pressure_n(1.5, 0.0), 0.0);
752 assert!(gapped.thrust_at_pressure_n(2.5, 0.0) > gapped.curve().thrust_n(2.5));
753 }
754
755 #[test]
756 fn rejects_bad_inputs() {
757 let dry = MassElement::thin_tube(0.3, 0.125, 0.019, 0.25);
758 let column = PropellantColumn {
759 mass_kg: 0.3,
760 center_m: 0.15,
761 outer_radius_m: 0.017,
762 inner_radius_m: 0.005,
763 length_m: 0.2,
764 };
765 let build = |column: PropellantColumn, dry: MassElement, nozzle: Option<Nozzle>| {
766 SolidMotor::new(curve(), Propellant::Column(column), dry, nozzle)
767 };
768 assert!(build(column, dry, None).is_ok());
769 assert!(
770 build(
771 PropellantColumn {
772 mass_kg: 0.0,
773 ..column
774 },
775 dry,
776 None
777 )
778 .is_err()
779 );
780 assert!(
781 build(
782 PropellantColumn {
783 inner_radius_m: 0.017,
784 ..column
785 },
786 dry,
787 None
788 )
789 .is_err()
790 );
791 assert!(
792 build(
793 PropellantColumn {
794 center_m: f64::NAN,
795 ..column
796 },
797 dry,
798 None
799 )
800 .is_err()
801 );
802 assert!(
803 build(
804 column,
805 MassElement {
806 mass_kg: -0.1,
807 ..dry
808 },
809 None
810 )
811 .is_err()
812 );
813 assert!(
815 build(
816 column,
817 MassElement {
818 mass_kg: 0.0,
819 ..dry
820 },
821 None
822 )
823 .is_err()
824 );
825 let nozzle = |exit, throat, reference| {
826 Some(Nozzle {
827 exit_radius_m: exit,
828 throat_radius_m: throat,
829 reference_pressure_pa: Some(reference),
830 })
831 };
832 assert!(build(column, dry, nozzle(0.01, Some(0.004), 101_325.0)).is_ok());
833 assert!(build(column, dry, nozzle(0.0, None, 101_325.0)).is_err());
834 assert!(build(column, dry, nozzle(0.01, Some(0.02), 101_325.0)).is_err());
835 assert!(build(column, dry, nozzle(0.01, None, -1.0)).is_err());
836 assert!(build(column, dry, nozzle(0.01, None, f64::NAN)).is_err());
837 assert!(SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.7, 0.6).is_err());
838 assert!(SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.6, 0.6).is_err());
839 assert!(matches!(
840 SolidMotor::from_envelope(curve(), 0.038, 0.25, f64::NAN, 0.6),
841 Err(MotorError::Domain {
842 what: "propellant mass (kg)",
843 ..
844 })
845 ));
846 assert!(SolidMotor::from_envelope(curve(), 0.0, 0.25, 0.3, 0.6).is_err());
847 }
848
849 #[test]
850 fn added_hardware_joins_the_dry_mass() {
851 let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
852 let retainer = MassElement::thin_tube(0.05, -0.01, 0.022, 0.02);
853 let with = motor.clone().with_added_dry_mass(retainer).unwrap();
854 let burnout = with.state(with.burnout_time_s()).total;
855 let expected = MassElement::combine([&motor.dry(), &retainer]);
856 assert_eq!(
857 burnout,
858 MassElement::combine([
859 &expected,
860 &MassElement {
861 cg_m: 0.125,
862 ..MassElement::ZERO
863 }
864 ])
865 );
866 assert!((burnout.mass_kg - 0.35).abs() < 1e-15);
867 assert!(burnout.cg_m < 0.125);
868 assert!(
869 motor
870 .with_added_dry_mass(MassElement {
871 mass_kg: f64::NAN,
872 ..retainer
873 })
874 .is_err()
875 );
876 }
877
878 #[derive(Debug, serde::Deserialize)]
879 struct Oracle {
880 oracle: String,
881 cases: Vec<OracleCase>,
882 }
883
884 #[derive(Debug, serde::Deserialize)]
885 struct OracleCase {
886 name: String,
887 inputs: OracleInputs,
888 scalars: OracleScalars,
889 series: OracleSeries,
890 }
891
892 #[derive(Debug, serde::Deserialize)]
893 struct OracleInputs {
894 thrust_file: String,
895 thrust_file_sha256: String,
896 dry_mass: f64,
897 dry_inertia: [f64; 3],
898 center_of_dry_mass_position: f64,
899 nozzle_position: f64,
900 nozzle_radius: f64,
901 throat_radius: f64,
902 grain_number: u32,
903 grain_density: f64,
904 grain_outer_radius: f64,
905 grain_initial_inner_radius: f64,
906 grain_initial_height: f64,
907 grain_separation: f64,
908 grains_center_of_mass_position: f64,
909 coordinate_system_orientation: String,
910 only_radial_burn: bool,
911 interpolation_method: String,
912 burn_time: Option<f64>,
913 }
914
915 #[derive(Debug, serde::Deserialize)]
916 struct OracleScalars {
917 total_impulse_ns: f64,
918 burn_out_time_s: f64,
919 exhaust_velocity_mps: f64,
920 propellant_initial_mass_kg: f64,
921 }
922
923 #[derive(Debug, serde::Deserialize)]
924 struct OracleSeries {
925 time_s: Vec<f64>,
926 thrust: Vec<f64>,
927 mass_flow_rate: Vec<f64>,
928 propellant_mass: Vec<f64>,
929 total_mass: Vec<f64>,
930 center_of_propellant_mass: Vec<f64>,
931 center_of_mass: Vec<f64>,
932 grain_inner_radius: Vec<f64>,
933 grain_height: Vec<f64>,
934 #[serde(rename = "propellant_I_11")]
935 propellant_i_11: Vec<f64>,
936 #[serde(rename = "propellant_I_33")]
937 propellant_i_33: Vec<f64>,
938 #[serde(rename = "I_11")]
939 i_11: Vec<f64>,
940 #[serde(rename = "I_33")]
941 i_33: Vec<f64>,
942 }
943
944 #[test]
962 fn matches_rocketpy_solid_motor_for_three_bundled_motors() {
963 let oracle: Oracle = serde_json::from_str(include_str!(
964 "../../../validation/fixtures/motor/rocketpy-solid-motor.json"
965 ))
966 .unwrap();
967 assert_eq!(oracle.oracle, "rocketpy 1.13.0");
968 assert_eq!(oracle.cases.len(), 3);
969 let catalog = crate::catalog::Catalog::bundled().unwrap();
970 let mut own_gap = (0.0, String::new(), 0.0);
973 let mut center_gap: f64 = 0.0;
974 for case in &oracle.cases {
975 let inputs = &case.inputs;
976 let (entry, curve) = catalog
977 .motors
978 .iter()
979 .find_map(|m| {
980 m.curves
981 .iter()
982 .find(|c| c.file == inputs.thrust_file)
983 .map(|c| (m, c))
984 })
985 .unwrap();
986 assert_eq!(curve.sha256, inputs.thrust_file_sha256, "{}", case.name);
988 let text = crate::catalog::bundled_curve_text(&curve.file).unwrap();
989 let thrust = entry.thrust_curve(curve, text).unwrap();
990
991 let sign = match inputs.coordinate_system_orientation.as_str() {
994 "nozzle_to_combustion_chamber" => 1.0,
995 "combustion_chamber_to_nozzle" => -1.0,
996 other => panic!("unknown orientation {other}"),
997 };
998 let to_hpr = |z: f64| sign * (z - inputs.nozzle_position);
999 let grains = BatesGrains {
1000 count: inputs.grain_number,
1001 density_kg_m3: inputs.grain_density,
1002 outer_radius_m: inputs.grain_outer_radius,
1003 initial_inner_radius_m: inputs.grain_initial_inner_radius,
1004 initial_height_m: inputs.grain_initial_height,
1005 separation_m: inputs.grain_separation,
1006 center_m: to_hpr(inputs.grains_center_of_mass_position),
1007 inhibited_ends: inputs.only_radial_burn,
1008 };
1009 let dry = MassElement {
1010 mass_kg: inputs.dry_mass,
1011 cg_m: to_hpr(inputs.center_of_dry_mass_position),
1012 axial_inertia_kg_m2: inputs.dry_inertia[2],
1013 transverse_inertia_kg_m2: inputs.dry_inertia[0],
1014 };
1015 let nozzle = Nozzle {
1016 exit_radius_m: inputs.nozzle_radius,
1017 throat_radius_m: Some(inputs.throat_radius),
1018 reference_pressure_pa: Some(STANDARD_SEA_LEVEL_PRESSURE_PA),
1019 };
1020 let motor =
1021 SolidMotor::new(thrust, Propellant::Grains(grains), dry, Some(nozzle)).unwrap();
1022 assert_eq!(inputs.interpolation_method, "linear");
1024 assert_eq!(inputs.burn_time, None);
1025 let hand = match case.name.as_str() {
1028 "cti-411i175-38mm-radial-burnout" => (0.2086, 0.11, 0.13),
1030 "cti-1633k940-54mm-axial-burnout-chamber-to-nozzle" => (0.5985, 0.154, 0.214),
1033 "loki-m1378lr-54mm-inhibited-ends" => (1.731, 0.50, 0.56),
1035 other => panic!("no hand values for {other}"),
1036 };
1037 let (dry_kg, dry_z, grains_z) = hand;
1038 let m_p = case.scalars.propellant_initial_mass_kg;
1039 let loaded_cg = (dry_kg * dry_z + m_p * grains_z) / (dry_kg + m_p);
1040 assert!(
1041 (motor.state(0.0).total.cg_m - loaded_cg).abs() < 1e-12,
1042 "{}",
1043 case.name
1044 );
1045 assert!(
1046 (motor.state(motor.burnout_time_s()).total.cg_m - dry_z).abs() < 1e-12,
1047 "{}",
1048 case.name
1049 );
1050
1051 let scalars = &case.scalars;
1052 let close = |a: f64, b: f64| (a - b).abs() <= 1e-9 * b.abs();
1053 assert!(
1054 close(motor.curve().total_impulse_ns(), scalars.total_impulse_ns),
1055 "{}",
1056 case.name
1057 );
1058 assert!(
1059 close(motor.burnout_time_s(), scalars.burn_out_time_s),
1060 "{}",
1061 case.name
1062 );
1063 assert!(close(
1064 motor.propellant_initial_mass_kg(),
1065 scalars.propellant_initial_mass_kg
1066 ));
1067 assert!(close(
1068 motor.exhaust_velocity_m_s(),
1069 scalars.exhaust_velocity_mps
1070 ));
1071
1072 let series = &case.series;
1073 let length = entry.length_mm * 1e-3;
1074 let mut worst: Vec<(&str, f64)> = Vec::new();
1075 let mut record = |what: &'static str, error: f64| match worst
1076 .iter_mut()
1077 .find(|(name, _)| *name == what)
1078 {
1079 Some((_, max)) => *max = max.max(error),
1080 None => worst.push((what, error)),
1081 };
1082 let loaded = motor.state(0.0);
1083 let peak_flow = motor.curve().peak_thrust_n() / motor.exhaust_velocity_m_s();
1084 for (i, &t) in series.time_s.iter().enumerate() {
1085 let state = motor.state(t);
1086 let shape = grains.shape(state.propellant.mass_kg);
1087 let relative = |ours: f64, theirs: f64| (ours - theirs).abs() / theirs.abs();
1088 let scaled = |ours: f64, theirs: f64, scale: f64| (ours - theirs).abs() / scale;
1089 record(
1090 "thrust",
1091 scaled(
1092 state.thrust_n,
1093 series.thrust[i],
1094 motor.curve().peak_thrust_n(),
1095 ),
1096 );
1097 record(
1098 "mass flow",
1099 scaled(state.mass_flow_kg_s, -series.mass_flow_rate[i], peak_flow),
1100 );
1101 record(
1102 "propellant mass",
1103 scaled(
1104 state.propellant.mass_kg,
1105 series.propellant_mass[i],
1106 scalars.propellant_initial_mass_kg,
1107 ),
1108 );
1109 if t < scalars.burn_out_time_s {
1112 let gap = relative(state.propellant.mass_kg, series.propellant_mass[i]);
1113 assert!(gap.is_finite(), "{} at {t} s", case.name);
1114 if gap > own_gap.0 {
1115 own_gap = (gap, case.name.clone(), series.propellant_mass[i]);
1116 }
1117 }
1118 record(
1119 "total mass",
1120 relative(state.total.mass_kg, series.total_mass[i]),
1121 );
1122 record(
1123 "propellant center",
1124 scaled(
1125 state.propellant.cg_m,
1126 to_hpr(series.center_of_propellant_mass[i]),
1127 length,
1128 ),
1129 );
1130 let center = scaled(state.total.cg_m, to_hpr(series.center_of_mass[i]), length);
1131 assert!(center.is_finite(), "{} at {t} s", case.name);
1132 center_gap = center_gap.max(center);
1133 record("center of mass", center);
1134 record(
1135 "grain bore radius",
1136 relative(shape.inner_radius_m, series.grain_inner_radius[i]),
1137 );
1138 record(
1139 "grain height",
1140 scaled(
1141 shape.height_m,
1142 series.grain_height[i],
1143 inputs.grain_initial_height,
1144 ),
1145 );
1146 record(
1147 "propellant I_11",
1148 scaled(
1149 state.propellant.transverse_inertia_kg_m2,
1150 series.propellant_i_11[i],
1151 loaded.propellant.transverse_inertia_kg_m2,
1152 ),
1153 );
1154 record(
1155 "propellant I_33",
1156 scaled(
1157 state.propellant.axial_inertia_kg_m2,
1158 series.propellant_i_33[i],
1159 loaded.propellant.axial_inertia_kg_m2,
1160 ),
1161 );
1162 record(
1163 "motor I_11",
1164 relative(state.total.transverse_inertia_kg_m2, series.i_11[i]),
1165 );
1166 record(
1167 "motor I_33",
1168 relative(state.total.axial_inertia_kg_m2, series.i_33[i]),
1169 );
1170 }
1171 eprintln!("{}: largest errors against RocketPy", case.name);
1172 for (what, error) in &worst {
1173 eprintln!(" {what:<18} {:.3e}", error);
1174 assert!(
1175 *error <= 1e-3,
1176 "{}: {what} differs from RocketPy by {:.4}%",
1177 case.name,
1178 100.0 * error
1179 );
1180 }
1181 }
1182 let (gap, gap_case, gap_theirs_kg) = own_gap;
1186 eprintln!("propellant, own: {gap:.4e} in {gap_case} at {gap_theirs_kg:.3e} kg");
1187 eprintln!("center of mass: {center_gap:.4e} of the motor length");
1188 assert!((0.688..0.689).contains(&gap), "{gap}");
1189 assert_eq!(gap_case, "cti-411i175-38mm-radial-burnout");
1190 assert!((6.9e-6..7.0e-6).contains(&gap_theirs_kg), "{gap_theirs_kg}");
1191 assert!((5.8e-6..5.9e-6).contains(¢er_gap), "{center_gap}");
1192 }
1193
1194 #[test]
1195 fn serde_round_trips_and_rechecks() {
1196 let motor = SolidMotor::from_envelope(curve(), 0.038, 0.25, 0.3, 0.6).unwrap();
1197 let json = serde_json::to_string(&motor).unwrap();
1198 assert_eq!(serde_json::from_str::<SolidMotor>(&json).unwrap(), motor);
1199 let broken = json.replace(
1200 "\"mass_kg\":0.3,\"center_m\"",
1201 "\"mass_kg\":-0.3,\"center_m\"",
1202 );
1203 assert_ne!(broken, json);
1204 assert!(serde_json::from_str::<SolidMotor>(&broken).is_err());
1205 }
1206}