1use std::path::Path;
32
33use hpr_aero::{DragTable, Flow, NormalForceColumn, NormalForceTable};
34use hpr_core::DVec3;
35use hpr_core::interp::{Extrapolation, Interpolation, Table1D};
36use hpr_design::{MassProperties, Rocket};
37use hpr_sim::{
38 Device, DeviceDrag, Direction, EventKind, FlightSettings, Rail, Sample, Simulation,
39 Termination, Trigger, UserEvent,
40};
41use serde::{Deserialize, Serialize};
42use serde_json::Value;
43
44use crate::run::{AREA_AGREEMENT, MASS_AGREEMENT, ValidateError, rocketpy_environment};
45
46#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
48pub struct Release {
49 pub time_s: f64,
51 pub speed_m_s: f64,
53 pub nose_down_deg: f64,
55 pub nose_right_deg: f64,
57 pub pitch_rate_nose_down_deg_s: f64,
59 pub pitch_rate_nose_right_deg_s: f64,
61 pub angle_of_attack_deg: f64,
63 pub mach: f64,
65 pub normal_force_coefficient: f64,
68 pub pivot_moment_m: f64,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
76pub struct Flown {
77 pub apogee_agl_m: f64,
79 pub landing_east_m: f64,
81 pub landing_north_m: f64,
83 pub flight_time_s: f64,
85 pub last_guide_leaves: Release,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum NormalForce {
93 Own,
95 Recorded,
100}
101
102const RECORDED_TOP_ANGLE_RAD: f64 = 1.5;
108
109pub fn fly(
122 root: &Path,
123 case: &Value,
124 wind: &Value,
125 declared_cd0: &Value,
126 (normal_force, tip_off): (NormalForce, bool),
127) -> Result<Flown, ValidateError> {
128 let name = case["name"].as_str().unwrap_or("(unnamed)").to_owned();
129 let label = format!(
130 "{name}, {}, {}, {}",
131 wind["wind"].as_str().unwrap_or("(no wind named)"),
132 match normal_force {
133 NormalForce::Own => "its own normal force",
134 NormalForce::Recorded => "the recorded normal force",
135 },
136 if tip_off { "tip-off" } else { "guided" }
137 );
138 let refuse = |what: String| ValidateError::Flight {
139 case: label.clone(),
140 what,
141 source: None,
142 };
143 let failed = |source: hpr_sim::SimError| ValidateError::Flight {
144 case: label.clone(),
145 what: "the flight failed".to_owned(),
146 source: Some(Box::new(source)),
147 };
148 let number = |value: &Value, what: &str| {
149 value
150 .as_f64()
151 .filter(|x| x.is_finite())
152 .ok_or_else(|| refuse(format!("the record has no number for {what}")))
153 };
154 let (rail, site, carried) = (&case["rail"], &case["site"], &wind["flown_with"]);
155 let path = root.join(format!("validation/designs/rocketpy-{name}.json"));
156 let text = std::fs::read_to_string(&path).map_err(|source| ValidateError::Io {
157 what: "reading a design",
158 path: path.display().to_string(),
159 source,
160 })?;
161 let rocket: Rocket = serde_json::from_str(&text).map_err(|source| ValidateError::Json {
162 path: path.display().to_string(),
163 source: Box::new(source),
164 })?;
165 let [configuration] = rocket.configurations.as_slice() else {
166 return Err(refuse(
167 "the design has other than one configuration".to_owned(),
168 ));
169 };
170 let elevation_m = number(&site["elevation"], "the site's elevation")?;
171 let environment = rocketpy_environment(
172 number(&site["latitude"], "the site's latitude")?,
173 number(&site["longitude"], "the site's longitude")?,
174 elevation_m,
175 &[(
176 elevation_m,
177 number(&wind["wind_east_m_s"], "the wind's east part")?,
178 number(&wind["wind_north_m_s"], "the wind's north part")?,
179 )],
180 )
181 .map_err(&failed)?;
182 let rail = Rail {
183 length_m: number(&rail["rail_length_m"], "the rail's length")?,
184 azimuth_rad: number(&rail["heading_deg"], "the rail's heading")?.to_radians(),
185 elevation_rad: number(&rail["inclination_deg"], "the rail's inclination")?.to_radians(),
186 roll_rad: 0.0,
187 friction_coefficient: 0.0,
189 };
190 let rows = declared_cd0
191 .as_array()
192 .ok_or_else(|| refuse("the record declares no drag table".to_owned()))?
193 .iter()
194 .map(|row| Ok((number(&row[0], "a Mach number")?, number(&row[1], "a C_D")?)))
195 .collect::<Result<Vec<_>, ValidateError>>()?;
196 let (machs, coefficients): (Vec<f64>, Vec<f64>) = rows.into_iter().unzip();
197 let radius_m = number(&carried["reference_radius_m"], "the reference radius")?;
198 let simulation = Simulation::new(
199 &rocket,
200 &configuration.id,
201 environment,
202 rail,
203 FlightSettings {
204 max_time_s: 6000.0,
205 ..FlightSettings::default()
206 },
207 )
208 .map_err(&failed)?;
209 let table = Table1D::new(
210 machs,
211 coefficients,
212 Interpolation::Linear,
213 Extrapolation::Error,
215 )
216 .map_err(|error| refuse(format!("the declared drag table: {error}")))?;
217 let simulation = simulation.with_drag_table(
218 DragTable::new(table.clone(), Some(table))
219 .with_reference_diameter_m(2.0 * radius_m)
220 .map_err(|error| refuse(format!("the declared drag's reference diameter: {error}")))?,
221 );
222 let simulation = match normal_force {
223 NormalForce::Own => simulation,
224 NormalForce::Recorded => {
225 let recorded = &carried["normal_force"];
226 let column = |what: &str| {
227 recorded[what]
228 .as_array()
229 .ok_or_else(|| refuse(format!("the record's normal force has no {what}")))?
230 .iter()
231 .map(|value| number(value, what))
232 .collect::<Result<Vec<_>, ValidateError>>()
233 };
234 let against_mach = |values: Vec<f64>| {
235 Table1D::new(
236 column("mach")?,
237 values,
238 Interpolation::Linear,
239 Extrapolation::Clamp,
240 )
241 .map_err(|error| refuse(format!("the recorded normal force: {error}")))
242 };
243 let slope = against_mach(column("slope_per_rad")?)?;
244 let station = against_mach(column("cp_station_m")?)?;
245 let table = NormalForceTable::new(vec![
246 NormalForceColumn::new(0.0, slope.clone(), station.clone()),
247 NormalForceColumn::new(RECORDED_TOP_ANGLE_RAD, slope, station),
248 ])
249 .and_then(|table| table.with_reference_diameter_m(2.0 * radius_m))
250 .map_err(|error| refuse(format!("the recorded normal force: {error}")))?;
251 simulation.with_normal_force_table(table).map_err(&failed)?
252 }
253 };
254 let simulation = if tip_off {
255 simulation.with_tip_off()
256 } else {
257 simulation
258 };
259
260 let assembly = simulation.assembly();
263 let dry = assembly
264 .motors
265 .iter()
266 .fold(assembly.layout.structure, |sum, motor| {
267 MassProperties::combine([&sum, &motor.dry_mass_properties()])
268 });
269 let [placed] = assembly.motors.as_slice() else {
270 return Err(refuse(format!(
271 "the design flies {} motors, where RocketPy's examples fly one",
272 assembly.motors.len()
273 )));
274 };
275 let motor = &placed.mounted.motor;
276 let recorded = &carried["motor"];
277 let guides = simulation.guides();
280 let stretch_m = guides
281 .tip_off_travel_m(rail.length_m)
282 .map(|begins| guides.exit_travel_m(rail.length_m) - begins)
283 .ok_or_else(|| refuse("the design has fewer than two guides".to_owned()))?;
284 for (what, hpr, rocketpy, agreement) in [
285 (
286 "distance between the last two guides, m",
287 stretch_m,
288 number(&case["button_spacing_m"], "the button spacing")?,
289 AREA_AGREEMENT,
290 ),
291 (
292 "dry mass, kg",
293 dry.mass_kg,
294 number(&carried["dry_mass_kg"], "the dry mass")?,
295 MASS_AGREEMENT,
296 ),
297 (
298 "reference radius, m",
299 0.5 * assembly.layout.reference_diameter_m,
300 radius_m,
301 AREA_AGREEMENT,
302 ),
303 (
304 "total impulse, N s",
305 motor.curve().total_impulse_ns(),
306 number(&recorded["total_impulse_ns"], "the total impulse")?,
307 MASS_AGREEMENT,
308 ),
309 (
310 "burn-out time, s",
311 motor.burnout_time_s(),
312 number(&recorded["burn_out_time_s"], "the burn-out time")?,
313 MASS_AGREEMENT,
314 ),
315 (
316 "initial propellant mass, kg",
317 motor.propellant_initial_mass_kg(),
318 number(
319 &recorded["propellant_initial_mass_kg"],
320 "the propellant mass",
321 )?,
322 MASS_AGREEMENT,
323 ),
324 ] {
325 let gap = (hpr - rocketpy).abs() / rocketpy.abs();
326 if !gap.is_finite() || gap > agreement {
327 return Err(refuse(format!(
328 "hpr's {what} is {hpr} where the record flew {rocketpy}, a relative {gap:.3e}"
329 )));
330 }
331 }
332
333 let start = simulation.initial_state();
336 let origin = start.position_enu_m + start.attitude.mul_vec3(dry.cg_m);
337 let h0 = origin.z;
338 let devices = carried["devices"]
339 .as_array()
340 .ok_or_else(|| refuse("the record lists no devices".to_owned()))?;
341 let count = devices.len();
342 let devices = devices
343 .iter()
344 .enumerate()
345 .map(|(index, device)| {
346 let trigger = match device["trigger"]["kind"].as_str() {
347 Some("apogee") if index == 0 => Trigger::Apogee,
348 Some("descending_below_height_agl") if index > 0 => Trigger::Altitude {
349 height_above_ground_m: number(
350 &device["trigger"]["height_m"],
351 "a deployment height",
352 )? + h0,
353 },
354 other => {
355 return Err(refuse(format!(
356 "device {index} has the trigger {other:?}; RocketPy's first parachute \
357 opens at apogee and the rest at a height"
358 )));
359 }
360 };
361 let mut built = Device::new(
362 device["name"].as_str().unwrap_or("parachute"),
363 DeviceDrag::DragArea {
364 cd_s_m2: number(&device["cd_s_m2"], "a drag area")?,
365 },
366 trigger,
367 )
368 .with_lag_s(number(&device["lag_s"], "a lag")?);
369 if index + 1 < count {
372 built = built.with_release_by(index + 1);
373 }
374 Ok(built)
375 })
376 .collect::<Result<Vec<_>, ValidateError>>()?;
377 let simulation = simulation
378 .with_recovery(devices)
379 .map_err(&failed)?
380 .with_event(UserEvent {
381 name: "back at the starting height".to_owned(),
382 direction: Direction::Falling,
383 function: Box::new(move |sample: &Sample| sample.height_above_ground_m - h0),
384 });
385 let result = simulation.run(&mut ()).map_err(&failed)?;
386 if result.termination != Termination::GroundHit {
387 return Err(refuse(format!(
388 "the flight ended as {:?}, not at the ground",
389 result.termination
390 )));
391 }
392 let event = |kind: EventKind| {
393 result
394 .event(kind)
395 .map(|event| event.sample)
396 .ok_or_else(|| refuse(format!("the flight has no {kind:?} event")))
397 };
398 let (exit, apogee, landing) = (
399 event(EventKind::RailExit)?,
400 event(EventKind::Apogee)?,
401 event(EventKind::User(0))?,
402 );
403 let landed = landing.state.position_enu_m + landing.state.attitude.mul_vec3(dry.cg_m) - origin;
404
405 let (heading, inclination) = (rail.azimuth_rad, rail.elevation_rad);
408 let up = DVec3::new(
409 -inclination.sin() * heading.sin(),
410 -inclination.sin() * heading.cos(),
411 inclination.cos(),
412 );
413 let right = DVec3::new(heading.cos(), -heading.sin(), 0.0);
414 let pivot_station_m = simulation
416 .guides()
417 .pivot_station_m
418 .ok_or_else(|| refuse("the design has no guides".to_owned()))?;
419 let force = simulation
420 .aero()
421 .normal_force(&Flow::new(exit.mach, exit.angle_of_attack_rad, 0.0))
422 .map_err(|error| {
423 refuse(format!(
424 "the normal force where the last guide leaves: {error}"
425 ))
426 })?;
427 let attitude = exit.state.unit_attitude();
428 let axis = attitude.mul_vec3(DVec3::Z);
429 let turning = attitude.mul_vec3(exit.state.body_rate_rad_s.cross(DVec3::Z));
431 let flown = Flown {
432 apogee_agl_m: apogee.height_above_ground_m - h0,
433 landing_east_m: landed.x,
434 landing_north_m: landed.y,
435 flight_time_s: landing.time_s,
436 last_guide_leaves: Release {
437 time_s: exit.time_s,
438 speed_m_s: exit.state.velocity_enu_m_s.length(),
439 nose_down_deg: (-axis.dot(up)).asin().to_degrees(),
440 nose_right_deg: axis.dot(right).asin().to_degrees(),
441 pitch_rate_nose_down_deg_s: (-turning.dot(up)).to_degrees(),
442 pitch_rate_nose_right_deg_s: turning.dot(right).to_degrees(),
443 angle_of_attack_deg: exit.angle_of_attack_rad.to_degrees(),
444 mach: exit.mach,
445 normal_force_coefficient: force.coefficient,
446 pivot_moment_m: force.coefficient * pivot_station_m - force.moment_m,
447 },
448 };
449 let figures = [
450 flown.apogee_agl_m,
451 flown.landing_east_m,
452 flown.landing_north_m,
453 flown.flight_time_s,
454 flown.last_guide_leaves.time_s,
455 flown.last_guide_leaves.speed_m_s,
456 flown.last_guide_leaves.nose_down_deg,
457 flown.last_guide_leaves.nose_right_deg,
458 flown.last_guide_leaves.pitch_rate_nose_down_deg_s,
459 flown.last_guide_leaves.pitch_rate_nose_right_deg_s,
460 flown.last_guide_leaves.angle_of_attack_deg,
461 flown.last_guide_leaves.mach,
462 flown.last_guide_leaves.normal_force_coefficient,
463 flown.last_guide_leaves.pivot_moment_m,
464 ];
465 if figures.iter().any(|figure| !figure.is_finite()) {
466 return Err(refuse(format!("a figure is not a number: {flown:?}")));
467 }
468 Ok(flown)
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474 use crate::tests::root;
475
476 fn reference() -> Value {
478 let text = std::fs::read_to_string(root().join("validation/reports/tip-off.json"))
479 .expect("the reference is committed");
480 serde_json::from_str(&text).expect("the reference parses")
481 }
482
483 fn row(reference: &Value, name: &str, wind: &str) -> (Value, Value) {
484 let case = reference["flown"]["cases"]
485 .as_array()
486 .expect("the reference lists its cases")
487 .iter()
488 .find(|case| case["name"] == name)
489 .expect("the case is in the reference");
490 let wind = case["winds"]
491 .as_array()
492 .expect("the case lists its winds")
493 .iter()
494 .find(|row| row["wind"] == wind)
495 .expect("the wind is in the case");
496 (case.clone(), wind.clone())
497 }
498
499 #[test]
500 fn the_recorded_normal_force_is_rocketpys_line_at_the_angle_the_guide_leaves_at() {
501 let reference = reference();
506 let drag = &reference["flown"]["drag"]["declared_cd0"];
507 let (case, wind) = row(&reference, "valetudo", "crosswind");
508 let flown = fly(&root(), &case, &wind, drag, (NormalForce::Recorded, true))
509 .expect("the flight flies");
510 let release = flown.last_guide_leaves;
511 assert!(
512 release.angle_of_attack_deg > 20.0,
513 "the crosswind flight leaves at a large angle: {release:?}"
514 );
515 let recorded = &wind["flown_with"]["normal_force"];
516 let column = |what: &str| -> Vec<f64> {
517 recorded[what]
518 .as_array()
519 .expect("the column is recorded")
520 .iter()
521 .map(|value| value.as_f64().expect("a number"))
522 .collect()
523 };
524 let slope = Table1D::new(
525 column("mach"),
526 column("slope_per_rad"),
527 Interpolation::Linear,
528 Extrapolation::Error,
529 )
530 .expect("the recorded slope is a table")
531 .eval(release.mach)
532 .expect("the Mach number is inside the record");
533 let line = slope * release.angle_of_attack_deg.to_radians();
534 assert!(
535 (release.normal_force_coefficient - line).abs() < 1e-9 * line,
536 "C_N {} against slope × angle {line}",
537 release.normal_force_coefficient
538 );
539 let own = fly(&root(), &case, &wind, drag, (NormalForce::Own, true))
541 .expect("the flight flies")
542 .last_guide_leaves;
543 assert!(
544 own.normal_force_coefficient > 2.0 * slope * own.angle_of_attack_deg.to_radians(),
545 "{own:?}"
546 );
547 }
548
549 #[test]
550 fn a_design_that_is_not_the_rocket_the_record_flew_is_refused() {
551 let reference = reference();
554 let drag = &reference["flown"]["drag"]["declared_cd0"];
555 let (case, wind) = row(&reference, "valetudo", "still");
556 for (pointer, named) in [
557 ("/flown_with/dry_mass_kg", "dry mass"),
558 ("/flown_with/reference_radius_m", "reference radius"),
559 ("/flown_with/motor/total_impulse_ns", "total impulse"),
560 ("/flown_with/motor/burn_out_time_s", "burn-out time"),
561 (
562 "/flown_with/motor/propellant_initial_mass_kg",
563 "initial propellant mass",
564 ),
565 ] {
566 let mut other = wind.clone();
567 let figure = other
568 .pointer_mut(pointer)
569 .expect("the record has the figure");
570 *figure = (1.01 * figure.as_f64().expect("a number")).into();
571 let error = fly(&root(), &case, &other, drag, (NormalForce::Own, true))
572 .expect_err("another rocket is refused")
573 .to_string();
574 assert!(error.contains(named), "{pointer}: {error}");
575 }
576 let mut other = case.clone();
579 other["button_spacing_m"] = (1.01 * case["button_spacing_m"].as_f64().unwrap()).into();
580 let error = fly(&root(), &other, &wind, drag, (NormalForce::Own, true))
581 .expect_err("other buttons are refused")
582 .to_string();
583 assert!(
584 error.contains("distance between the last two guides"),
585 "{error}"
586 );
587 let mut bare = wind.clone();
588 bare["flown_with"]["normal_force"] = Value::Null;
589 let error = fly(&root(), &case, &bare, drag, (NormalForce::Recorded, true))
590 .expect_err("no recorded normal force, no flight on it")
591 .to_string();
592 assert!(error.contains("normal force"), "{error}");
593 fly(&root(), &case, &bare, drag, (NormalForce::Own, true)).expect("the flight flies");
595 }
596
597 #[test]
598 fn the_phase_is_only_flown_when_asked_for() {
599 let reference = reference();
603 let drag = &reference["flown"]["drag"]["declared_cd0"];
604 let (case, wind) = row(&reference, "valetudo", "still");
605 let guided = fly(&root(), &case, &wind, drag, (NormalForce::Own, false))
606 .expect("the flight flies")
607 .last_guide_leaves;
608 let tipped = fly(&root(), &case, &wind, drag, (NormalForce::Own, true))
609 .expect("the flight flies")
610 .last_guide_leaves;
611 assert!(guided.pitch_rate_nose_down_deg_s.abs() < 1e-9, "{guided:?}");
612 assert!(guided.nose_down_deg.abs() < 1e-9, "{guided:?}");
613 assert!(tipped.pitch_rate_nose_down_deg_s > 0.1, "{tipped:?}");
614 assert!(tipped.nose_down_deg > 0.0, "{tipped:?}");
615 assert!((tipped.time_s - guided.time_s).abs() < 1e-3 * guided.time_s);
616 assert!((tipped.speed_m_s - guided.speed_m_s).abs() < 1e-3 * guided.speed_m_s);
617 }
618}