Cotton code
111 lines · 5.3 KB · RustRaw
//! The model's input contract, held to `scripts/ink/ink_input.py`.use super::*;use crate::ink::testing::{SYNTHETIC_SHAPES, TRACES};use crate::ink::Point;/// RULE: the model reads 62 classes — a–z, A–Z, 0–9 — and folds them to 36: each letter's two cases summed, the digits as they are, best first.#[test]fn the_model_reads_letters_and_digits() {    assert_eq!(CLASSES.len(), 62);    assert_eq!(&CLASSES[52..], &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);    let mut answer = vec![0.0; 62];    answer[14] = 0.3; // o    answer[40] = 0.2; // O    answer[52] = 0.45; // 0    answer[0] = 0.05;    let folded = fold(&answer).unwrap();    assert_eq!(folded.len(), 36);    assert_eq!(folded[0].letter, "o");    assert!((folded[0].score - 0.5).abs() < 1e-12);    assert_eq!(folded[1].letter, "0");    assert!((folded.iter().map(|score| score.score).sum::<f64>() - 1.0).abs() < 1e-12);    assert!(fold(&[0.5; 3]).is_none(), "an answer of another size is none");}/// RULE: a group is 64 samples in the unit box, its longer side spanning 0–1 and its shorter centred, the jump between strokes pen-up; a dot is its first point 64 times; no point at all is no input.#[test]fn a_group_is_64_samples_in_the_unit_box() {    let strokes = vec![vec![Point::new(0.0, 0.0), Point::new(0.0, 100.0)], vec![Point::new(50.0, 0.0), Point::new(50.0, 100.0)]];    let features = encode(&strokes).unwrap();    assert_eq!(features.points.len(), 64);    assert_eq!(features.strokes, 2.0);    assert_eq!(features.points[0], [0.25, 0.0, 0.0]);    assert_eq!(features.points[63], [0.75, 1.0, 0.0]);    assert!(features.points.iter().any(|point| point[2] == 1.0), "the jump is pen-up");    let dot = encode(&[vec![Point::new(3.0, 4.0)]]).unwrap();    assert!(dot.points.iter().all(|point| *point == [0.5, 0.5, 0.0]));    assert!(encode(&[vec![]]).is_none());    assert_eq!(features.key(), encode(&strokes).unwrap().key(), "a group's key is its own");    assert_ne!(features.key(), dot.key());}/// Every stroke group of the two fixtures, as the drift test reads them.fn fixture_groups() -> Vec<Vec<Vec<[f64; 2]>>> {    #[derive(serde::Deserialize)]    struct Trace {        strokes: Vec<Vec<Vec<f64>>>,    }    let traces: Vec<Trace> = serde_json::from_str(TRACES).unwrap();    let mut groups: Vec<Vec<Vec<[f64; 2]>>> =        traces.iter().map(|trace| trace.strokes.iter().map(|stroke| stroke.iter().map(|p| [p[0], p[1]]).collect()).collect()).collect();    let shapes = &*SYNTHETIC_SHAPES;    for letter in &shapes.letters {        for stroke in &letter.strokes {            groups.push(vec![stroke.iter().map(|p| [p[0], p[1]]).collect()]);        }    }    for letter in &shapes.multistroke {        for way in &letter.ways {            groups.push(way.iter().map(|stroke| stroke.iter().map(|p| [p[0], p[1]]).collect()).collect());        }    }    for way in shapes.natural.values() {        groups.push(way.iter().map(|stroke| stroke.iter().map(|p| [p[0], p[1]]).collect()).collect());    }    groups}/// RULE: the Rust encoder is the input contract's: `scripts/ink/ink_input.py`, the reference the model was trained on, run over every group of ink-traces.json and ink-synthetic.json, matches it to 1e-4, the stroke count exactly. The drift is printed for the report.#[test]fn the_encoder_matches_the_python_contract() {    let groups = fixture_groups();    let root = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR")).join("../../scripts/ink");    let script = "import json, sys\nsys.path.insert(0, sys.argv[1])\nimport ink_input\nfor line in sys.stdin:\n    pts, n = ink_input.encode(json.loads(line))\n    print(json.dumps({'points': pts, 'strokes': n}))\n";    let mut child = std::process::Command::new("python3")        .args(["-I", "-c", script, root.to_str().unwrap()])        .stdin(std::process::Stdio::piped())        .stdout(std::process::Stdio::piped())        .spawn()        .expect("python3 runs the input contract (scripts/ink/ink_input.py)");    {        use std::io::Write;        let mut stdin = child.stdin.take().unwrap();        for group in &groups {            writeln!(stdin, "{}", serde_json::to_string(group).unwrap()).unwrap();        }    }    let output = child.wait_with_output().unwrap();    assert!(output.status.success(), "ink_input.py failed");    #[derive(serde::Deserialize)]    struct Encoded {        points: Vec<[f64; 3]>,        strokes: f64,    }    let answers: Vec<Encoded> = String::from_utf8(output.stdout).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect();    assert_eq!(answers.len(), groups.len());    let mut worst: f64 = 0.0;    for (group, python) in groups.iter().zip(&answers) {        let strokes: Vec<Vec<Point>> = group.iter().map(|stroke| stroke.iter().map(|p| Point::new(p[0], p[1])).collect()).collect();        let rust = encode(&strokes).unwrap();        assert_eq!(rust.strokes, python.strokes);        assert_eq!(rust.points.len(), python.points.len());        for (a, b) in rust.points.iter().zip(&python.points) {            for j in 0..3 {                worst = worst.max((a[j] - b[j]).abs());            }        }    }    println!("ink-measure encoder drift against ink_input.py: {} groups, max |diff| {worst:e}", groups.len());    assert!(worst <= 1e-4, "the Rust encoder drifted {worst} from ink_input.py");}