// generated by hxc 1.0.0-acgt-compiler from src/replay_lesson.hlx -- do not edit by hand
#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
// hlx:2
use super::Json;
// hlx:3
use std::collections::{BTreeMap, BTreeSet};
// hlx:5
fn field<'a>(obj: &'a Json, key: &str) -> Result<&'a Json, String> {
// hlx:6
obj.get(key)
.ok_or_else(|| format!("missing GNOSIS field {key}"))
// hlx:7
}
// hlx:8
fn text<'a>(obj: &'a Json, key: &str) -> Result<&'a str, String> {
// hlx:9
field(obj, key)?
.as_str()
.filter(|s| !s.trim().is_empty() && s.trim() == *s && !s.chars().any(char::is_control))
// hlx:10
.ok_or_else(|| format!("{key} must contain a nonempty single-line label"))
// hlx:11
}
// hlx:12
fn rows<'a>(obj: &'a Json, key: &str) -> Result<&'a [Json], String> {
// hlx:13
match field(obj, key)? {
Json::Arr(a) => Ok(a),
_ => Err(format!("{key} must be an array")),
}
// hlx:14
}
// hlx:15
fn check_row_units(row: &Json) -> Result<(), String> {
// hlx:16
// v1 has report-level x/y units only. A row override has no defined conversion or association.
// hlx:17
if [
"unit",
"units",
"x_unit",
"y_unit",
"observed_unit",
"predicted_unit",
]
.iter()
.any(|key| row.get(key).is_some())
{
// hlx:18
return Err("gnosis-1 requires uniform report-level units".into());
// hlx:19
}
// hlx:20
Ok(())
// hlx:21
}
// hlx:22
fn positive(obj: &Json, key: &str) -> Result<f64, String> {
// hlx:23
field(obj, key)?
.as_f64()
.filter(|v| v.is_finite() && *v > 0.0)
.ok_or_else(|| format!("{key} must be finite and positive"))
// hlx:24
}
// hlx:25
fn same(a: f64, b: f64) -> bool {
// hlx:26
a.is_finite() && b.is_finite() && (a - b).abs() <= 32.0 * f64::EPSILON * a.abs().max(b.abs())
// hlx:27
}
// hlx:28
fn verify_num(obj: &Json, key: &str, expected: f64) -> Result<(), String> {
// hlx:29
if field(obj, key)?.as_f64().is_some_and(|v| same(v, expected)) {
// hlx:30
Ok(())
// hlx:31
} else {
// hlx:32
Err(format!("reported {key} disagrees with the paired data"))
// hlx:33
}
// hlx:34
}
// hlx:35
fn unique_fields(value: &Json) -> Result<(), String> {
// hlx:36
let mut pending = vec![value];
// hlx:37
while let Some(node) = pending.pop() {
// hlx:38
match node {
// hlx:39
Json::Obj(fields) => {
// hlx:40
let mut seen = BTreeSet::new();
// hlx:41
for (key, child) in fields {
// hlx:42
if !seen.insert(key) {
return Err(format!("duplicate GNOSIS field {key}"));
}
// hlx:43
pending.push(child);
// hlx:44
}
// hlx:45
}
// hlx:46
Json::Arr(items) => pending.extend(items),
// hlx:47
_ => (),
// hlx:48
}
// hlx:49
}
// hlx:50
Ok(())
// hlx:51
}
// hlx:53
fn axis(report: &Json, key: &str) -> Result<String, String> {
// hlx:54
let obj = field(report, key)?;
// hlx:55
let name = text(obj, "name")?;
// hlx:56
let unit = text(obj, "unit")?;
// hlx:57
// A v1 axis declares its own units. A label records the measurement convention; it does not authorize conversion.
// hlx:58
let placeholder = matches!(
unit.to_ascii_lowercase().as_str(),
"unknown"
| "unspecified"
| "not specified"
| "not provided"
| "not available"
| "n/a"
| "na"
| "none"
| "null"
| "tbd"
| "-"
) || unit.chars().all(|c| c == '?');
// hlx:59
if unit.len() > 256 || placeholder || unit.contains(['\u{2028}', '\u{2029}']) {
return Err(format!(
"{key} requires an explicit single-line unit label of at most 256 bytes"
));
}
// hlx:60
Ok(format!("{name} [{unit}]"))
// hlx:61
}
// hlx:63
#[derive(Default)]
// hlx:64
struct Errors {
// hlx:65
covered: usize,
// hlx:66
log: f64,
// hlx:67
percent: f64,
// hlx:68
worst_percent: f64,
// hlx:69
absolute: f64,
// hlx:70
}
// hlx:71
impl Errors {
// hlx:72
fn add(&mut self, predicted: f64, observed: f64, n: usize) {
// hlx:73
let total = n as f64;
// hlx:74
let absolute = (predicted - observed).abs();
// hlx:75
let relative = absolute / observed;
// hlx:76
self.covered += 1;
// hlx:77
self.log += (predicted.ln() - observed.ln()).abs() / total;
// hlx:78
self.absolute += absolute / total;
// hlx:79
self.percent += relative * (100.0 / total);
// hlx:80
self.worst_percent = self.worst_percent.max(relative * 100.0);
// hlx:81
}
// hlx:82
fn verify(&self, summary: &Json, n: usize) -> Result<(), String> {
// hlx:83
verify_num(summary, "covered", self.covered as f64)?;
// hlx:84
for (key, val) in [
("mean_absolute_log_error", self.log),
("mae", self.absolute),
("mape_percent", self.percent),
("max_absolute_percent_error", self.worst_percent),
] {
// hlx:85
if self.covered == n {
// hlx:86
verify_num(summary, key, val)?;
// hlx:87
} else if !matches!(field(summary, key)?, Json::Null) {
// hlx:88
return Err(format!("partial forecast must have null {key}"));
// hlx:89
}
// hlx:90
}
// hlx:91
Ok(())
// hlx:92
}
// hlx:93
}
// hlx:96
fn model_columns<'a>(
report: &'a Json,
summaries: &str,
column: &str,
paired: &[(&Json, f64)],
) -> Result<Vec<(&'a str, Option<f64>)>, String> {
// hlx:97
let summaries = rows(report, summaries)?;
// hlx:98
let mut errors = BTreeMap::new();
// hlx:99
for summary in summaries {
// hlx:100
if errors
.insert(text(summary, "family")?, Errors::default())
.is_some()
{
return Err("duplicate model summary".into());
}
// hlx:101
}
// hlx:102
for &(row, observed) in paired {
// hlx:103
let Json::Obj(models) = field(row, column)? else {
return Err(format!("{column} must be an object"));
};
// hlx:104
if models.len() != errors.len() {
return Err(format!("incomplete {column}"));
}
// hlx:105
for (name, value) in models {
// hlx:106
let model = errors
.get_mut(name.as_str())
.ok_or_else(|| format!("unreported forecast {name}"))?;
// hlx:107
match value {
// hlx:108
Json::Null => (),
// hlx:109
Json::Num(p) if p.is_finite() && *p > 0.0 => model.add(*p, observed, paired.len()),
// hlx:110
_ => return Err(format!("invalid forecast for {name}")),
// hlx:111
}
// hlx:112
}
// hlx:113
}
// hlx:114
let mut scores = Vec::new();
// hlx:115
for summary in summaries {
// hlx:116
let name = text(summary, "family")?;
// hlx:117
let e = &errors[name];
// hlx:118
e.verify(summary, paired.len())?;
// hlx:119
scores.push((name, (e.covered == paired.len()).then_some(e.log)));
// hlx:120
}
// hlx:121
Ok(scores)
// hlx:122
}
// hlx:124
pub(super) fn from_gnosis(report: &Json) -> Result<Json, String> {
// hlx:125
unique_fields(report)?;
// hlx:126
if text(report, "protocol")? != "gnosis-1"
|| text(report, "mode")? != "check"
|| text(report, "metric")? != "mean_absolute_log_error"
{
// hlx:127
return Err("expected a scored gnosis-1 check using mean_absolute_log_error".into());
// hlx:128
}
// hlx:129
let case = text(report, "case_id")?;
// hlx:130
let title = text(report, "title")?;
// hlx:131
let source = field(report, "source")?;
// hlx:132
let citation = text(source, "title")?;
// hlx:133
let url = text(source, "url")?;
// hlx:134
let limits = match report.get("limits") {
// hlx:135
None => "Only the supplied source, units and held-out split were tested.",
// hlx:136
Some(_) => text(report, "limits")?,
// hlx:137
};
// hlx:138
let x = axis(report, "x")?;
// hlx:139
let y = axis(report, "y")?;
// hlx:140
let selected = text(report, "selected_family")?;
// hlx:141
let recommended = text(report, "recommended_model")?;
// hlx:142
let evaluation = field(report, "evaluation")?;
// hlx:143
let training = rows(report, "training")?;
// hlx:144
let forecasts = rows(report, "predictions")?;
// hlx:145
let observations = rows(evaluation, "observations")?;
// hlx:146
let n = forecasts.len();
// hlx:147
if !(4..=128).contains(&training.len()) || !(1..=512).contains(&n) || observations.len() != n {
// hlx:148
return Err("incomplete or out-of-range GNOSIS split".into());
// hlx:149
}
// hlx:150
verify_num(report, "n_train", training.len() as f64)?;
// hlx:151
verify_num(report, "n_test", n as f64)?;
// hlx:152
let mut ids = BTreeSet::new();
// hlx:153
for row in training {
// hlx:154
check_row_units(row)?;
// hlx:155
if !ids.insert(text(row, "id")?) {
return Err("duplicate training ID".into());
}
// hlx:156
positive(row, "x")?;
// hlx:157
positive(row, "y")?;
// hlx:158
}
// hlx:159
let mut outcomes = BTreeMap::new();
// hlx:160
for obs in observations {
// hlx:161
check_row_units(obs)?;
// hlx:162
if outcomes.insert(text(obs, "id")?, obs).is_some() {
return Err("duplicate observed ID".into());
}
// hlx:163
}
// hlx:164
let mut paired = Vec::with_capacity(n);
// hlx:165
let mut selected_errors = Errors::default();
// hlx:166
let mut recommended_errors = Errors::default();
// hlx:167
for row in forecasts {
// hlx:168
check_row_units(row)?;
// hlx:169
let id = text(row, "id")?;
// hlx:170
if !ids.insert(id) {
return Err("duplicate forecast ID or overlap with training".into());
}
// hlx:171
positive(row, "x")?;
// hlx:172
let obs = outcomes
.remove(id)
.ok_or("forecast has no matching observation")?;
// hlx:173
let observed = positive(obs, "observed")?;
// hlx:174
let forecast = positive(row, "predicted")?;
// hlx:175
let advice = positive(row, "recommended")?;
// hlx:176
let controls = field(row, "control_predictions")?;
// hlx:177
if let Some(value) = controls.get(selected) {
if value.as_f64() != Some(forecast) {
return Err("selected family disagrees with its control column".into());
}
}
// hlx:178
let advised_forecast = if selected == recommended {
Some(forecast)
} else {
controls.get(recommended).and_then(Json::as_f64)
};
// hlx:179
if advised_forecast != Some(advice) {
return Err("recommended model disagrees with its forecast column".into());
}
// hlx:180
verify_num(obs, "absolute_error", (forecast - observed).abs())?;
// hlx:181
selected_errors.add(forecast, observed, n);
// hlx:182
recommended_errors.add(advice, observed, n);
// hlx:183
paired.push((row, observed));
// hlx:184
}
// hlx:185
for (key, name, errors) in [
("selected", selected, &selected_errors),
("recommended", recommended, &recommended_errors),
] {
// hlx:186
let summary = field(evaluation, key)?;
// hlx:187
if text(summary, "family")? != name {
return Err(format!("mismatched {key} family"));
}
// hlx:188
errors.verify(summary, n)?;
// hlx:189
}
// hlx:190
let controls = model_columns(report, "controls", "control_predictions", &paired)?;
// hlx:191
// gnosis-1 always produces these controls, even when a particular fit yields only null predictions.
// hlx:192
for required in [
"median",
"linear",
"local_linear",
"local_log_log",
"local_reciprocal_log",
] {
// hlx:193
if !controls.iter().any(|(name, _)| *name == required) {
return Err(format!("missing gnosis-1 control {required}"));
}
// hlx:194
}
// hlx:195
model_columns(report, "transfer_scores", "donor_predictions", &paired)?;
// hlx:196
let full: Vec<_> = controls
.into_iter()
.filter_map(|(name, score)| Some((name, score?)))
.collect();
// hlx:197
let declared = text(evaluation, "strongest_observed_control")?;
// hlx:198
let best = full
.iter()
.min_by(|a, b| a.1.total_cmp(&b.1))
.ok_or("no fully covered control")?;
// hlx:199
if !full
.iter()
.any(|(name, score)| *name == declared && *score == best.1)
{
return Err("strongest observed control disagrees with recomputed scores".into());
}
// hlx:200
let margin = 0.001;
// hlx:201
verify_num(evaluation, "margin_log_units", margin)?;
// hlx:202
let verdict = |s: f64, c: f64| {
if s + margin < c {
"lower_error_on_this_split"
} else if c + margin < s {
"control_wins"
} else {
"within_margin"
}
};
// hlx:203
if text(evaluation, "verdict")? != verdict(selected_errors.log, best.1) {
return Err("reported verdict disagrees with recomputed scores".into());
}
// hlx:204
// The producer's controls can include the selected model itself. Use a distinct family for the lesson.
// hlx:205
let (rival, other) = full
.iter()
.filter(|(name, _)| *name != selected)
.min_by(|a, b| a.1.total_cmp(&b.1))
.ok_or("no distinct fully covered rival")?;
// hlx:206
let decision = match verdict(selected_errors.log, *other) {
"control_wins" => format!("{rival} had lower error"),
"lower_error_on_this_split" => format!("{selected} had lower error"),
_ => "the difference was within the comparison margin".into(),
};
// hlx:207
let observation_word = if n == 1 {
"observation"
} else {
"observations"
};
// hlx:208
let values = [
// hlx:209
("title", format!("Compare held-out model errors for {title}")),
// hlx:210
("when", format!("Comparing forecasts for {y} from {x} on the {case} case, or planning a paired held-out comparison in a new case.")),
// hlx:211
("found", format!("On the {case} split, {decision}. Mean absolute log error was {:.8e} for {selected} and {:.8e} for {rival} across {n} paired {observation_word}.", selected_errors.log,other)),
// hlx:212
("how", "Freeze competing forecasts before measuring outcomes. Match each forecast to its held-out observation by unique ID. Use the same positive observations and units for every model. Compute the mean absolute difference of their natural logs. Compare the selected family with the lowest-error, fully covered alternative and apply the declared margin.".into()),
// hlx:213
("evidence", format!("GNOSIS check {case}. {citation} ({url}). Split size {} training and {n} held out. Input {x}. Output {y}. Units recorded as declared, without conversion. Comparison margin {margin} log units.",training.len())),
// hlx:214
("reconsider",format!("{limits} Recompute the comparison on fresh observations when the source, units, range or competing models change.")),
// hlx:215
("tags","gnosis;held-out prediction;model comparison".into())];
// hlx:216
Ok(Json::Obj(
values
.into_iter()
.map(|(key, value)| (key.into(), Json::Str(value)))
.collect(),
))
// hlx:217
}
// hlx:219
#[cfg(test)]
// hlx:220
mod tests {
// hlx:221
use super::*;
// hlx:222
use crate::parse_json;
// hlx:225
fn paired_report() -> String {
// hlx:226
let good = r#"{"covered":2,"mean_absolute_log_error":0,"mae":0,"mape_percent":0,"max_absolute_percent_error":0}"#;
// hlx:227
let bad = r#"{"covered":2,"mean_absolute_log_error":0.6931471805599453,"mae":3,"mape_percent":100,"max_absolute_percent_error":100}"#;
// hlx:228
let partial = r#"{"covered":1,"mean_absolute_log_error":null,"mae":null,"mape_percent":null,"max_absolute_percent_error":null}"#;
// hlx:229
let summary = |name: &str, s: &str| format!(r#"{{"family":"{name}",{}"#, &s[1..]);
// hlx:230
let controls = [
("median", bad),
("linear", partial),
("local_linear", good),
("local_log_log", bad),
("local_reciprocal_log", bad),
]
.map(|(name, data)| summary(name, data))
.join(",");
// hlx:231
let forecasts = [("held-red",4,2,"null"),("held-blue",8,4,"5")].map(|(id,p,y,linear)|
// hlx:232
format!(r#"{{"id":"{id}","x":1,"predicted":{p},"recommended":{y},"control_predictions":{{"median":{p},"linear":{linear},"local_linear":{y},"local_log_log":{p},"local_reciprocal_log":{p}}},"donor_predictions":{{}}}}"#)).join(",");
// hlx:233
let training = (0..4)
.map(|i| format!(r#"{{"id":"train-{i}","x":1,"y":1}}"#))
.collect::<Vec<_>>()
.join(",");
// hlx:234
format!(
r#"{{"protocol":"gnosis-1","mode":"check","metric":"mean_absolute_log_error","title":"Synthetic instrument","case_id":"synth","source":{{"title":"Test records","url":"urn:instrument:S","notes":"Synthetic values"}},"limits":"This instrument only.","x":{{"name":"time","unit":"s"}},"y":{{"name":"length","unit":"m"}},"n_train":4,"n_test":2,"training":[{training}],"predictions":[{forecasts}],"selected_family":"power","recommended_model":"local_linear","controls":[{controls}],"transfer_scores":[],"evaluation":{{"selected":{},"recommended":{},"strongest_observed_control":"local_linear","margin_log_units":0.001,"verdict":"control_wins","observations":[{{"id":"held-blue","observed":4,"absolute_error":4}},{{"id":"held-red","observed":2,"absolute_error":2}}]}}}}"#,
summary("power", bad),
summary("local_linear", good)
)
// hlx:235
}
// hlx:237
#[test]
// hlx:238
fn learns_only_a_scoped_method_from_identically_paired_rows() {
// hlx:239
let lesson = from_gnosis(&parse_json(&paired_report()).unwrap()).unwrap();
// hlx:240
assert!(text(&lesson, "found")
.unwrap()
.contains("local_linear had lower error"));
// hlx:241
assert!(text(&lesson, "evidence")
.unwrap()
.contains("urn:instrument:S"));
// hlx:242
assert!(text(&lesson, "reconsider")
.unwrap()
.contains("This instrument only."));
// hlx:243
let Json::Obj(fields) = lesson else {
panic!("expected lesson object");
};
// hlx:244
assert_eq!(fields.len(), 7);
// hlx:245
assert!(fields
.iter()
.all(|(_, v)| !v.as_str().unwrap().contains("held-red")));
// hlx:246
}
// hlx:248
#[test]
// hlx:249
fn absent_study_limits_fall_back_to_the_tested_split() {
// hlx:250
let study = paired_report().replace(r#""limits":"This instrument only.","#, "");
// hlx:251
let lesson = from_gnosis(&parse_json(&study).unwrap()).unwrap();
// hlx:252
assert!(text(&lesson, "reconsider")
.unwrap()
.contains("Only the supplied source, units and held-out split were tested."));
// hlx:253
}
// hlx:255
#[test]
// hlx:256
fn records_declared_compound_and_assay_units_verbatim() {
// hlx:257
let report = paired_report();
// hlx:258
for unit in [
"cm\u{b2}",
"ppm",
"astronomical units",
"A17 calibrated assay units",
] {
// hlx:259
let study = report.replace(r#""unit":"m""#, &format!(r#""unit":"{unit}""#));
// hlx:260
let lesson = from_gnosis(&parse_json(&study).unwrap()).unwrap();
// hlx:261
let evidence = text(&lesson, "evidence").unwrap();
// hlx:262
assert!(evidence.contains(&format!("length [{unit}]")));
// hlx:263
assert!(evidence.contains("without conversion"));
// hlx:264
}
// hlx:265
let overlong = report.replace(r#""unit":"m""#, &format!(r#""unit":"{}""#, "u".repeat(257)));
// hlx:266
assert!(from_gnosis(&parse_json(&overlong).unwrap()).is_err());
// hlx:267
}
// hlx:269
#[test]
// hlx:270
fn rejects_unscored_wrongly_paired_or_tampered_reports() {
// hlx:271
let report = paired_report();
// hlx:272
let mutations = [
// hlx:273
(r#""mode":"check""#, r#""mode":"predict""#),
// hlx:274
(r#""unit":"s""#, r#""unit":"unknown""#),
// hlx:275
(r#""unit":"s""#, r#""unit":"?""#),
// hlx:276
(r#""unit":"s""#, r#""unit":"""#),
// hlx:277
(r#","unit":"s""#, ""),
// hlx:278
(r#""unit":"s""#, r#""unit":"a\nb""#),
// hlx:279
(r#""unit":"s""#, r#""unit":"a\u2028b""#),
// hlx:280
(
r#""id":"held-blue","observed""#,
r#""id":"held-red","observed""#,
),
// hlx:281
(
r#""id":"held-red","observed""#,
r#""id":"no-match","observed""#,
),
// hlx:282
(r#""id":"held-blue","x""#, r#""id":"train-1","x""#),
// hlx:283
(r#""observed":2"#, r#""observed":0"#),
// hlx:284
(r#""observed":2"#, r#""observed":2,"unit":"km""#),
// hlx:285
(r#""n_test":2"#, r#""n_test":3"#),
// hlx:286
(r#""predicted":4"#, r#""predicted":null"#),
// hlx:287
(
r#""control_predictions":{"median":4"#,
r#""control_predictions":{"median":-4"#,
),
// hlx:288
(
r#""strongest_observed_control":"local_linear""#,
r#""strongest_observed_control":"median""#,
),
// hlx:289
(
r#""verdict":"control_wins""#,
r#""verdict":"within_margin""#,
),
// hlx:290
(
r#""mean_absolute_log_error":0.6931471805599453"#,
r#""mean_absolute_log_error":0.7"#,
),
// hlx:291
(
r#""mean_absolute_log_error":null"#,
r#""mean_absolute_log_error":0"#,
),
// hlx:292
(r#""margin_log_units":0.001"#, r#""margin_log_units":1"#),
// hlx:293
(r#""covered":1"#, r#""covered":2"#),
// hlx:294
(r#""mape_percent":100"#, r#""mape_percent":10"#),
// hlx:295
(r#""recommended":2"#, r#""recommended":4"#),
// hlx:296
(r#""limits":"This instrument only.""#, r#""limits":"""#),
// hlx:297
(r#""limits":"This instrument only.""#, r#""limits":null"#),
// hlx:298
(
r#""case_id":"synth""#,
r#""case_id":"synth","case_id":"other""#,
),
// hlx:299
];
// hlx:300
for (old, new) in mutations {
// hlx:301
let tampered = report.replacen(old, new, 1);
// hlx:302
assert_ne!(report, tampered, "fixture mutation {old}");
// hlx:303
assert!(
from_gnosis(&parse_json(&tampered).unwrap()).is_err(),
"accepted {new}"
);
// hlx:304
}
// hlx:305
}
// hlx:306
}