Cotton code
131 lines · 7.6 KB · RustRaw
//! The corpus replay and the lag, over the recorded model.use serde_json::json;use super::*;use crate::ink::captured::{Captured, Context};use crate::ink::testing::{timed as written, Always, Recorded, SYNTHETIC, TRACES};use crate::ink::{shipped, Point};fn h() -> Captured {    let shapes = vec![vec![vec![0.0, 0.0], vec![0.0, 100.0]], vec![vec![100.0, 0.0], vec![100.0, 100.0]], vec![vec![0.0, 50.0], vec![100.0, 50.0]]];    let strokes = written(&shapes, 300.0, Some(190.0), Point::new(200.0, 400.0), &[0.7, 0.7], 1_793_000_000.0, 1);    let mut model = Recorded::default();    let read = Stream::replay(&strokes, Reader::shipped(), Some(450.0), Admits::EVERY, &mut model);    model.all_read();    let context = Context { screen: [402.0, 640.0], on_card: true, tier: "deck".into(), letters: "h".into(), ..Default::default() };    Captured::of(&read[0], &context)}/// RULE: the replay's labels are one list for every line in order (null skips one) or one per file, and a count that does not match is an error, never a guess.#[test]fn labels_match_the_groups() {    let files = vec![("a.jsonl".to_string(), 2), ("b.jsonl".to_string(), 1)];    assert_eq!(labels(&json!(["h", null, "A"]), &files).unwrap(), vec![vec![Some("h".to_string()), None], vec![Some("a".to_string())]]);    let files = vec![("a.jsonl".to_string(), 1), ("b.jsonl".to_string(), 2)];    let each = labels(&json!({"a.jsonl": ["n"], "b.jsonl": ["x", "clear"]}), &files).unwrap();    assert_eq!(each, vec![vec![Some("n".to_string())], vec![Some("x".to_string()), Some("clear".to_string())]]);    assert!(labels(&json!(["h"]), &[("a.jsonl".to_string(), 2)]).is_err());}/// RULE: a corpus replays two ways — each group as kept, and every stroke regrouped on its own clock — into a confusion table and an accuracy.#[test]fn a_corpus_replays_into_a_table() {    let kept = h();    let groups = vec![        Labelled { source: "synthetic.jsonl".into(), group: kept.clone(), intended: Some("h".into()), written: None },        Labelled { source: "synthetic.jsonl".into(), group: kept, intended: Some("n".into()), written: None },    ];    let mut model = Recorded::default();    let report = report(&groups, &Reader::shipped(), &mut model);    model.all_read();    assert_eq!(report.kept_accuracy, 0.5);    assert!(report.text.contains("n      0/1  → h×1"), "{}", report.text);    assert!(report.text.contains("Regrouped on the real timings"), "{}", report.text);}/// RULE: two sequences align by least edits: a misread is one, a letter missed or extra one.#[test]fn sequences_align_by_least_edits() {    let a: Vec<String> = ["c", "a", "t"].iter().map(|s| s.to_string()).collect();    let b: Vec<String> = ["c", "t"].iter().map(|s| s.to_string()).collect();    assert_eq!(aligned(&a, &b), vec![(Some("c".into()), Some("c".into())), (Some("a".into()), None), (Some("t".into()), Some("t".into()))]);}/// RULE: the lag from a letter's last lift to its final reading, on the synthetic walk and the 24 traces, is printed for the report; written as a line, half the traces' letters are final within the wait.#[test]fn the_lag_is_measured() {    let mut model = Recorded::default();    let measured = lag(SYNTHETIC, TRACES, &Reader::shipped(), &mut model).unwrap();    model.all_read();    for set in &measured {        println!("ink-measure lag {}", set.line());    }    let mut line = measured.last().unwrap().lags.clone();    line.sort_by(|a, b| a.partial_cmp(b).unwrap());    assert!(line[line.len() / 2] < shipped().knobs.group_near_seconds, "half the letters of a line are final within the wait");}/// RULE: a corpus folder loads as the phone kept it: its files in name order, a file holding no strokes left out and named, labels from labels.json, else a file's own <name>.labels.json, else the label each line carries; a line's `case` is kept.#[test]fn a_folder_loads_as_kept() {    let line = h().line();    let mut labelled: serde_json::Value = serde_json::from_str(&line).unwrap();    labelled["label"] = json!("H");    let mut cased = labelled.clone();    cased["case"] = json!("upper");    let files = vec![        ("b.jsonl".to_string(), format!("{labelled}\n{cased}\n")),        ("a.jsonl".to_string(), format!("{line}\n")),        ("notes.jsonl".to_string(), "{\"said\": \"no strokes\"}\n".to_string()),    ];    let (groups, left_out) = load(&files, Some(r#"["n", "h", null]"#), &Default::default()).unwrap();    assert_eq!(left_out, vec!["notes.jsonl".to_string()]);    assert_eq!(groups.iter().map(|g| (g.source.as_str(), g.intended.as_deref(), g.written.as_deref())).collect::<Vec<_>>(),               vec![("a.jsonl", Some("n"), None), ("b.jsonl", Some("h"), None), ("b.jsonl", None, Some("upper"))]);    let own = [("a.jsonl".to_string(), r#"["x"]"#.to_string())].into_iter().collect();    let (groups, _) = load(&files, None, &own).unwrap();    assert_eq!(groups.iter().map(|g| g.intended.as_deref()).collect::<Vec<_>>(), vec![Some("x"), Some("h"), Some("h")], "a file's own labels, else each line's label");    assert!(load(&files, Some(r#"["n"]"#), &Default::default()).is_err(), "a count that does not match");}/// RULE: the floor's curve and the doubtful band are printed from the corpus as kept, one row per floor and per score bin, and the noise is scrawls that are no letter, the same every run.#[test]fn the_curve_and_the_band_print() {    let groups = vec![Labelled { source: "s.jsonl".into(), group: h(), intended: Some("h".into()), written: None }];    let curve = curve(&groups, &[0.0, 0.95], &mut Always("h", 0.9)).unwrap();    let rows: Vec<&str> = curve.lines().collect();    assert_eq!(rows.len(), 3, "{curve}");    assert_eq!(rows[1], "0.00 | 100.0% | 0.0% | 0.0% | 0.0% | 0.0%", "{curve}");    assert!(rows[2].starts_with("0.95 | 0.0% |"), "under the floor it no longer reads h: {curve}");    let noise = scrawls(20, 7);    assert_eq!(noise, scrawls(20, 7));    assert_eq!(noise.len(), 20);    let band = band(&groups, &[0.0, 0.25, 0.5], &noise, &mut Always("h", 0.3)).unwrap();    assert!(band.contains("0.25–0.50 | 1 | 0 |"), "{band}");    assert!(band.ends_with("of 20\n"), "{band}");}/// RULE: a held-out folder's expected.json holds when the phone's path reads its groups within the tolerance it gives, and fails when it does not or the count differs; the contract's fixtures hold to 1e-4 and fail beyond it.#[test]fn a_held_out_folder_is_held_to_what_it_says() {    let groups = vec![Labelled { source: "s.jsonl".into(), group: h(), intended: Some("h".into()), written: None }];    let said = |kept: f64, count: usize| json!({ "letter_confidence": 0.5, "kept": kept, "within": 0.005, "groups": count }).to_string();    let (lines, holds) = expected(&groups, &said(1.0, 1), &mut Always("h", 0.99)).unwrap();    assert!(holds, "{lines}");    assert!(lines.contains("letters alone: 1/1 = 100.0%"), "{lines}");    assert!(!expected(&groups, &said(0.5, 1), &mut Always("h", 0.99)).unwrap().1);    assert!(!expected(&groups, &said(1.0, 2), &mut Always("h", 0.99)).unwrap().1);    let strokes = vec![vec![[0.0, 0.0], [0.0, 100.0]], vec![[0.0, 50.0], [60.0, 50.0]]];    let points: Vec<Vec<Point>> = strokes.iter().map(|s| s.iter().map(|p| Point::new(p[0], p[1])).collect()).collect();    let features = crate::ink::input::encode(&points).unwrap();    let fixture = |nudge: f64| {        let mut encoded: Vec<Vec<f64>> = features.points.iter().map(|p| p.to_vec()).collect();        encoded[3][0] += nudge;        json!({ "strokes": strokes, "points": encoded, "stroke_count": features.strokes }).to_string()    };    assert!(contract(&fixture(5e-5)).unwrap().1);    assert!(!contract(&fixture(2e-4)).unwrap().1);    assert!(!contract("").unwrap().1, "no fixtures holds nothing");}