pub const GOLDEN: &str = include_str!("../tests/policy-golden.json");
pub const CONTRACT_VERSION: u32 = 1;
pub const META_CONTRACT: &str = "botstadia.contract";
pub const META_ARENA: &str = "botstadia.arena";
pub const META_PAYLOAD_SCHEMA: &str = "botstadia.payload_schema";
pub const META_TRAIN_VERSION: &str = "botstadia.train_version";
pub const META_OPSET: &str = "botstadia.opset";
pub const STATE_IN: &str = "state_in";
pub const STATE_OUT: &str = "state_out";
pub const NOISE: &str = "noise";
pub const MAX_STATE: u32 = 1024;
pub const EXPORT_OPSET: i64 = 18;
pub fn to_bounds(value: f32, min: f32, max: f32) -> f32 {
let unit = if value.is_nan() {
0.0
} else {
value.clamp(-1.0, 1.0)
};
let mapped = min + (unit + 1.0) * 0.5 * (max - min);
mapped.clamp(min, max)
}
pub fn from_bounds(value: f32, min: f32, max: f32) -> f32 {
if max <= min {
return 0.0;
}
((value - min) / (max - min) * 2.0 - 1.0).clamp(-1.0, 1.0)
}
pub fn feed_u8(value: u8) -> f32 {
f32::from(value) / 255.0
}
pub fn argmax(logits: &[f32]) -> usize {
let mut best = 0;
let mut best_value = f32::NEG_INFINITY;
for (index, value) in logits.iter().enumerate() {
if *value > best_value {
best = index;
best_value = *value;
}
}
best
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(serde::Deserialize)]
struct Golden {
#[serde(rename = "_doc")]
_doc: String,
to_bounds: Vec<(f32, f32, f32, f32)>,
feed_u8: Vec<(u8, f32)>,
argmax: Vec<(Vec<f32>, usize)>,
}
#[test]
fn matches_the_shared_golden_file() {
let golden: Golden = serde_json::from_str(GOLDEN).unwrap();
for (value, min, max, expected) in golden.to_bounds {
assert_eq!(
to_bounds(value, min, max),
expected,
"{value} in {min}..{max}"
);
}
for (value, expected) in golden.feed_u8 {
assert_eq!(feed_u8(value), expected);
}
for (logits, expected) in golden.argmax {
assert_eq!(argmax(&logits), expected);
}
}
#[test]
fn nan_is_the_midpoint_and_the_map_inverts() {
assert_eq!(to_bounds(f32::NAN, -2.0, 4.0), 1.0);
for value in [-1.0, -0.25, 0.0, 0.6, 1.0] {
let there = to_bounds(value, -2.5, 2.88);
assert!((from_bounds(there, -2.5, 2.88) - value).abs() < 1e-6);
}
}
}