hpr_py/lib.rs
1//! Python bindings for FusionSpace HPR ยท Sim: the `fusionspace-hpr` Python package, imported as
2//! `fusionspace.hpr`.
3//!
4//! The guide's [Python][guide-python] page shows the package in use, and [Start
5//! here][guide-start] says what works today and how far to trust it.
6//!
7//! [guide-python]: https://hpr.fusionspace.co/python.html
8//! [guide-start]: https://hpr.fusionspace.co/start-here.html
9//!
10//! The package wraps the [`hpr`] builder, the same four types in the same order, and a Monte
11//! Carlo run of them:
12//!
13//! - `Environment`: the launch site, the standard atmosphere, a wind (constant, or a Python
14//! function of height) and a gravity model.
15//! - `Motor`: a motor from the built-in catalog, or a RASP `.eng` or RockSim `.rse` file.
16//! - `Rocket`: parts added from the nose back, the motor and the parachutes; or a design read
17//! from a `.hpr`, `.hprz`, `.ork` or rocket JSON file.
18//! - `Flight`: the rocket flown from a rail as soon as it is made, with its metrics, its events
19//! and its recording as NumPy arrays. A `DragTable` or a Python function of the Mach number
20//! can fly another drag in place of HPR Sim's (`models`).
21//! - `MonteCarlo`: the rocket flown many times, each flight's inputs scattered about the nominal
22//! flight's, as `hpr mc` flies it (`montecarlo`). It's the library's
23//! `hpr_analysis::montecarlo::MonteCarlo` run on every core, its `RunTable` as NumPy arrays.
24//!
25//! > **How far to trust it.** The bindings add no physics. Each call hands its arguments to the
26//! > [`hpr`] builder and returns what it returns. So a flight made in Python runs the same code as
27//! > the one the Rust builder makes from the same numbers. The package's tests fly the builder's
28//! > example rocket and match every digit the Rust example prints. The last digits can differ
29//! > between a release and a debug build. The guide's [Accuracy][guide-accuracy] page says how
30//! > good the models themselves are.
31//!
32//! [guide-accuracy]: https://hpr.fusionspace.co/accuracy.html
33//!
34//! Values cross into Python in SI units, named in every argument and attribute (`length_m`,
35//! `apogee_m`, `max_speed_m_s`), as in the Rust API. Records such as a flight's summary cross as
36//! dictionaries, made from the same `serde` form the Rust types write as JSON. Errors raise
37//! `fusionspace.hpr.HprError`, a `ValueError`, whose message is the Rust error's.
38//!
39//! The crate is built by maturin (`crates/hpr-py/pyproject.toml`) into one wheel per operating
40//! system, on CPython's stable ABI (abi3), so it serves CPython 3.10 and later. Its tests are
41//! Python's, in `crates/hpr-py/tests/`, run by pytest on the built wheel.
42
43#![allow(
44 clippy::disallowed_methods,
45 reason = "the bindings are an I/O boundary, as the command line is: `Motor.from_file`, \
46 `Rocket.from_file` and `FlightLog.read` read the files Python names"
47)]
48
49mod flight;
50mod log;
51mod models;
52mod montecarlo;
53mod rocket;
54
55use pyo3::create_exception;
56use pyo3::exceptions::PyValueError;
57use pyo3::prelude::*;
58use serde::Serialize;
59use serde::de::DeserializeOwned;
60
61create_exception!(
62 fusionspace.hpr,
63 HprError,
64 PyValueError,
65 "An error from FusionSpace HPR. It's an input out of its domain, a part out of order, a motor \
66 or material that isn't there, or a flight that failed. The message is the library's."
67);
68
69/// The Python exception for a library error.
70fn error(error: impl std::fmt::Display) -> PyErr {
71 HprError::new_err(error.to_string())
72}
73
74/// A value the library serializes, as the Python object `json.loads` makes of its JSON: numbers,
75/// strings, lists, dictionaries and `None`.
76fn to_python<'py>(py: Python<'py>, value: &impl Serialize) -> PyResult<Bound<'py, PyAny>> {
77 let text = serde_json::to_string(value).map_err(error)?;
78 py.import("json")?.call_method1("loads", (text,))
79}
80
81/// A name as the bindings compare it: trimmed, in lower case, with hyphens and spaces as
82/// underscores, so `"Flat circular"` and `"flat-circular"` are `"flat_circular"`.
83fn key(name: &str) -> String {
84 name.trim().to_ascii_lowercase().replace(['-', ' '], "_")
85}
86
87/// A unit enum of the library, by its `serde` name: `"flat_circular"` is
88/// `CanopyType::FlatCircular`. The names are the ones the library writes in JSON, so the two
89/// can't drift apart.
90fn by_name<T: DeserializeOwned>(what: &str, name: &str) -> PyResult<T> {
91 serde_json::from_value(serde_json::Value::String(key(name)))
92 .map_err(|_| error(format!("no {what} `{name}`")))
93}
94
95/// The built-in materials' ids, the names `Rocket`'s parts take: `"abs"`, `"kraft_phenolic"`,
96/// `"birch_plywood"` and the rest. The Rust documentation of `hpr_design::materials` gives the
97/// source of each one's density.
98#[pyfunction]
99fn materials() -> Vec<&'static str> {
100 hpr::hpr_design::materials::BUILTIN
101 .iter()
102 .map(|material| material.id)
103 .collect()
104}
105
106/// The package's native module, `fusionspace.hpr._hpr`. `fusionspace/hpr/__init__.py` re-exports it.
107#[pymodule]
108fn _hpr(m: &Bound<'_, PyModule>) -> PyResult<()> {
109 m.add("HprError", m.py().get_type::<HprError>())?;
110 m.add("__version__", env!("CARGO_PKG_VERSION"))?;
111 m.add_function(wrap_pyfunction!(materials, m)?)?;
112 m.add_class::<flight::Environment>()?;
113 m.add_class::<rocket::Motor>()?;
114 m.add_class::<rocket::Rocket>()?;
115 m.add_class::<flight::DragTable>()?;
116 m.add_class::<flight::Flight>()?;
117 m.add_class::<log::FlightLog>()?;
118 m.add_class::<montecarlo::MonteCarlo>()?;
119 Ok(())
120}