1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// SPDX-License-Identifier: AGPL-3.0-only
//! Python bindings (PyO3), built with `maturin` and the `python` feature.
//!
//! ```python
//! import kshana, json
//! result = json.loads(kshana.run(open("scenarios/clock-holdover.toml").read()))
//! print(kshana.version())
//! ```
// The #[pyfunction] macro expands to a `.into()` on the PyErr return, which Clippy
// flags as a useless conversion in macro-generated code we don't control.
#![allow(clippy::useless_conversion)]
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
/// Recursively convert a `serde_json::Value` into a native Python object
/// (`dict`/`list`/`str`/`int`/`float`/`bool`/`None`), so callers get structured
/// data instead of a JSON string to re-parse.
fn json_to_py<'py>(py: Python<'py>, v: &serde_json::Value) -> PyResult<pyo3::Bound<'py, PyAny>> {
use serde_json::Value;
Ok(match v {
Value::Null => py.None().into_bound(py),
Value::Bool(b) => (*b).into_pyobject(py)?.to_owned().into_any(),
Value::Number(n) => {
if let Some(i) = n.as_i64() {
i.into_pyobject(py)?.into_any()
} else if let Some(u) = n.as_u64() {
u.into_pyobject(py)?.into_any()
} else {
n.as_f64().unwrap_or(f64::NAN).into_pyobject(py)?.into_any()
}
}
Value::String(s) => s.into_pyobject(py)?.into_any(),
Value::Array(a) => {
let list = PyList::empty(py);
for item in a {
list.append(json_to_py(py, item)?)?;
}
list.into_any()
}
Value::Object(o) => {
let dict = PyDict::new(py);
for (k, val) in o {
dict.set_item(k, json_to_py(py, val)?)?;
}
dict.into_any()
}
})
}
/// A scenario run result: the result JSON, the chart SVG, the human summary, and
/// — for the scenario kinds that emit one — the reproducibility table CSV, with a
/// `data()` accessor that returns the parsed result as a Python dict.
// pyo3 0.29 makes the auto `FromPyObject` derive for `Clone` pyclasses opt-in.
// `RunOutput` is only ever returned to Python, never accepted as an argument, so
// we explicitly skip the derive rather than opt in.
#[pyclass(name = "RunOutput", skip_from_py_object)]
#[derive(Clone)]
struct PyRunOutput {
#[pyo3(get)]
json: String,
#[pyo3(get)]
svg: String,
#[pyo3(get)]
summary: String,
/// The reproducibility table the CLI writes as `<scenario>.table.csv`, for
/// the kinds that emit one (`realtime-frame-eop`, `lunar-time-budget`,
/// `lunar-jamming`, and `moonlight-service-volume` only when both
/// `export_site_lat_deg` and `export_site_lon_deg` are set — the shipped
/// scenario leaves them commented out, so it emits none); `None` otherwise. It is the
/// byte-stable, golden-pinned form of the table the papers cite, so a
/// reviewer reproducing one from the wheel needs it here and not only from
/// the command line.
#[pyo3(get)]
csv: Option<String>,
}
#[pymethods]
impl PyRunOutput {
/// The result document parsed into a Python `dict` (figures of merit,
/// time series, provenance, ...). NumPy users can wrap any numeric list with
/// `numpy.asarray(...)`.
fn data<'py>(&self, py: Python<'py>) -> PyResult<pyo3::Bound<'py, PyAny>> {
let v: serde_json::Value =
serde_json::from_str(&self.json).map_err(|e| PyValueError::new_err(e.to_string()))?;
json_to_py(py, &v)
}
/// Write the reproducibility table to `path`, returning the number of bytes
/// written — 0 when this scenario kind emits no table. Mirrors
/// `kshana::api::RunOutput::write_csv`, which is what the CLI uses.
fn write_csv(&self, path: &str) -> PyResult<usize> {
match &self.csv {
Some(csv) => std::fs::write(path, csv)
.map(|()| csv.len())
.map_err(|e| PyValueError::new_err(e.to_string())),
None => Ok(0),
}
}
fn __repr__(&self) -> String {
format!(
"RunOutput(json={} bytes, svg={} bytes, csv={} bytes, summary={:?})",
self.json.len(),
self.svg.len(),
self.csv.as_ref().map_or(0, |c| c.len()),
self.summary.chars().take(48).collect::<String>()
)
}
}
/// Run a scenario from a TOML string and return a typed [`RunOutput`] (with
/// `.json`, `.svg`, `.summary`, `.csv`, `.write_csv()`, and `.data()`). Raises
/// `ValueError` if invalid.
#[pyfunction]
fn run_typed(toml: &str) -> PyResult<PyRunOutput> {
crate::api::run_toml(toml)
.map(|o| PyRunOutput {
json: o.json,
svg: o.svg,
summary: o.summary,
csv: o.csv,
})
.map_err(PyValueError::new_err)
}
/// The available scenario kinds and their metadata, as a Python list of dicts
/// (name, description, required/optional fields) — introspectable without source.
/// Assess a real receiver log described by a `receiver-trust` scenario (TOML text). The
/// log must be given inline (`text` or `base64`) or by a path the Python process can
/// read. Returns the result document, the trust-timeline CSV, the chart and a summary.
#[pyfunction]
fn receiver_trust(toml: &str) -> PyResult<PyRunOutput> {
crate::receiver_trust::scenario::run_toml(toml)
.map(|o| PyRunOutput {
json: o.json,
svg: o.svg,
summary: o.summary,
csv: Some(o.csv),
})
.map_err(PyValueError::new_err)
}
#[pyfunction]
fn scenario_kinds<'py>(py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let json = crate::api::list_scenario_kinds_json();
let v: serde_json::Value =
serde_json::from_str(&json).map_err(|e| PyValueError::new_err(e.to_string()))?;
json_to_py(py, &v)
}
/// Validate a scenario TOML string without raising: returns a list of error
/// messages (empty if the scenario is valid). Note: this executes the scenario,
/// so it surfaces both parse/config errors and runtime failures.
#[pyfunction]
fn validate_toml(toml: &str) -> Vec<String> {
match crate::api::run_scenario(toml) {
Ok(_) => vec![],
Err(e) => vec![e.to_string()],
}
}
/// Run a scenario given as a TOML string; returns the result document as a JSON
/// string. Raises `ValueError` if the scenario is invalid.
#[pyfunction]
fn run(toml: &str) -> PyResult<String> {
crate::api::run_toml(toml)
.map(|o| o.json)
.map_err(PyValueError::new_err)
}
/// Run a scenario; returns `(json, svg, summary)`.
#[pyfunction]
fn run_full(toml: &str) -> PyResult<(String, String, String)> {
crate::api::run_toml(toml)
.map(|o| (o.json, o.svg, o.summary))
.map_err(PyValueError::new_err)
}
/// List the available scenario kinds and their metadata as ONE JSON-array string (name,
/// description, required and optional fields) — a `str`, not a Python list. It predates
/// [`scenario_kinds`], which returns the same metadata already parsed, and keeps its
/// string return so existing callers do not break; new code should call `scenario_kinds`.
#[pyfunction]
fn list_kinds() -> String {
crate::api::list_scenario_kinds_json()
}
/// Run a scenario; on failure return the structured error *kind* tag
/// (`invalid_input`, `non_convergence`, `unsupported`, `io_error`) instead of
/// raising, so a caller can pattern-match on the failure category. Returns `None`
/// on success.
#[pyfunction]
fn error_kind(toml: &str) -> Option<String> {
crate::api::run_scenario(toml)
.err()
.map(|e| e.kind_tag().to_string())
}
/// Engine version (the crate version).
#[pyfunction]
fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
#[pymodule]
fn kshana(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyRunOutput>()?;
m.add_function(wrap_pyfunction!(run, m)?)?;
m.add_function(wrap_pyfunction!(run_full, m)?)?;
m.add_function(wrap_pyfunction!(run_typed, m)?)?;
m.add_function(wrap_pyfunction!(scenario_kinds, m)?)?;
m.add_function(wrap_pyfunction!(validate_toml, m)?)?;
m.add_function(wrap_pyfunction!(list_kinds, m)?)?;
m.add_function(wrap_pyfunction!(error_kind, m)?)?;
m.add_function(wrap_pyfunction!(version, m)?)?;
m.add_function(wrap_pyfunction!(receiver_trust, m)?)?;
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
Ok(())
}