Cotton code
682 lines · 32.2 KB · RustRaw
//! THE CORPUS REPLAYED (`pnpm ink:corpus`): the groups the phone kept//! (`captured`), each labelled with the letter its writer meant, read again//! by the reader as it stands now — two ways. Each group as it was kept,//! through `Reader::runs`; and every stroke on its own clock through the//! grouping (`stream`) and the letters written (`letters`), as the shell//! would have read them. Both end in a confusion table, intended → read with//! scores, and the accuracy. Each labelled group is read as the surface//! meant for it reads (owner, 3 Nov 2026): a letter meant among the//! letters, a digit among the digits (`admits`).//!//! And THE LAG (owner, 3 Nov 2026: "there's a bit of a lag between writing//! a letter and that getting filled"): how long each letter waits, from the//! lift of its last stroke to its final reading, on strokes laid at a//! finger's pace (`lag`).//!//! Pure: the files are read and the model asked by the caller//! (`examples/ink_corpus.rs`, the model a Core ML child on the Mac).use std::collections::BTreeMap;use serde_json::Value;use super::captured::Captured;use super::letters::Letters;use super::marks;use super::reader::{Model, Reader};use super::stream::{Stream, TimedStroke};use super::{Admits, Point, Reading, Run, Symbol};/// A group kept and the letter meant by it (None: unlabelled; also `clear`/// for a scratch-out, `swipe` for a page swipe), and the case written where/// the line says it (a dataset's `case`).#[derive(Debug, Clone)]pub struct Labelled {    pub source: String,    pub group: Captured,    pub intended: Option<String>,    pub written: Option<String>,}/// The labels for `files` (name, groups, in that order): `labels` is either/// one list for every group of every file in order, or an object giving each/// file's own list. A count that does not match is an error, never a guess.pub fn labels(labels: &Value, files: &[(String, usize)]) -> Result<Vec<Vec<Option<String>>>, String> {    fn list(value: &Value, name: &str) -> Result<Vec<Option<String>>, String> {        let items = value.as_array().ok_or(format!("{name}: not a list"))?;        Ok(items.iter().map(|item| item.as_str().filter(|label| !label.is_empty()).map(str::to_lowercase)).collect())    }    if let Some(by_file) = labels.as_object() {        return files            .iter()            .map(|(name, groups)| {                let value = by_file.get(name).ok_or(format!("labels.json: no labels for {name}"))?;                let labels = list(value, name)?;                if labels.len() != *groups {                    return Err(format!("labels.json: {name}: {} labels for {groups} groups", labels.len()));                }                Ok(labels)            })            .collect();    }    let all = list(labels, "labels.json")?;    let total: usize = files.iter().map(|(_, groups)| groups).sum();    if all.len() != total {        return Err(format!("labels.json: {} labels for {total} groups", all.len()));    }    let mut rest = all.into_iter();    Ok(files.iter().map(|(_, groups)| rest.by_ref().take(*groups).collect()).collect())}/// What a surface written on for `intended` admits: the letters for a letter/// meant (or a mark: `clear`, `swipe`), the digits for a digit, both for a/// group meaning both ("a+7").pub fn admits(intended: &str) -> Admits {    Admits::of(&intended.split('+').map(Symbol::of).collect::<Vec<_>>())}/// What a reading is called in the table.pub fn said(reading: &Reading) -> String {    match reading {        Reading::Letter { letter, .. } | Reading::Doubtful { letter, .. } => letter.clone(),        Reading::Clear => "clear".into(),        Reading::Mark(name) => name.clone(),        Reading::Line { from, to } => {            if (to.x - from.x).abs() > (to.y - from.y).abs() {                if to.x < from.x { "line←".into() } else { "line→".into() }            } else {                "line|".into()            }        }        Reading::Nothing => "nothing".into(),    }}/// One labelled group read again as kept.#[derive(Debug, Clone)]pub struct Outcome {    pub intended: String,    pub read: String,    pub detail: String,}impl Outcome {    pub fn right(&self) -> bool {        self.read == self.intended    }}fn detail(runs: &[Run]) -> String {    runs.iter()        .map(|run| {            let mut text = said(&run.reading);            match &run.reading {                Reading::Letter { score, .. } => text += &format!(" {score:.2}"),                Reading::Doubtful { score, .. } => text += &format!(" {score:.2} doubtful"),                _ => {}            }            if !run.runners.is_empty() {                text += &format!(" ({})", run.runners.iter().map(|runner| format!("{} {:.2}", runner.letter, runner.score)).collect::<Vec<_>>().join(", "));            }            let count = run.strokes.len();            text + &format!(" [{count} stroke{}]", if count == 1 { "" } else { "s" })        })        .collect::<Vec<_>>()        .join(" + ")}/// Every labelled group read again as it was kept, among what its surface/// admits.pub fn as_kept(groups: &[Labelled], reader: &Reader, model: &mut dyn Model) -> Vec<Outcome> {    groups        .iter()        .filter_map(|labelled| {            let intended = labelled.intended.clone()?;            let strokes: Vec<Vec<Point>> = labelled.group.timed(0.0).into_iter().map(|stroke| stroke.points).collect();            let runs = reader.runs(&strokes, labelled.group.height, admits(&intended), model);            let read: Vec<String> = runs.iter().map(|run| said(&run.reading)).filter(|read| read != "nothing").collect();            let mut shown = if read.is_empty() { "nothing".to_string() } else { read.join("+") };            // A page swipe reads as a level line long enough to turn the page.            if intended == "swipe" && (shown == "line←" || shown == "line→") {                shown = "swipe".into();            }            let phone = labelled.group.score.map(|score| format!("{} {score:.2}", labelled.group.read)).unwrap_or_else(|| labelled.group.read.clone());            Some(Outcome { intended, read: shown, detail: format!("{}  — on the phone: {phone}", detail(&runs)) })        })        .collect()}/// The whole stream regrouped: what was meant and what was read, aligned/// (None on one side is a letter missed or one extra), the letters after/// each group read, and how many groups.pub struct Streamed {    pub pairs: Vec<(Option<String>, Option<String>)>,    pub shown: Vec<String>,    pub groups: usize,}/// Every stroke of every group on its own clock, grouped and read as the/// shell would, through the letters written.pub fn streamed(groups: &[Labelled], reader: &Reader, model: &mut dyn Model) -> Streamed {    // A line with no time of its own (a dataset's) follows the one before it    // after a pause longer than any wait.    let mut clock = 0.0f64;    let mut strokes: Vec<TimedStroke> = Vec::new();    for labelled in groups {        let timed = labelled.group.timed(clock + 3.0);        clock = timed.iter().map(|stroke| stroke.up).fold(clock, f64::max);        strokes.extend(timed);    }    let height = groups.last().and_then(|labelled| labelled.group.height);    // One stream on one surface: it admits what every group meant does.    let meant = groups.iter().filter_map(|labelled| labelled.intended.as_deref()).fold(Admits::default(), |held, intended| held.union(admits(intended)));    let admitted = if meant == Admits::default() { Admits::EVERY } else { meant };    let reads = Stream::replay(&strokes, reader.clone(), height, admitted, model);    let mut said_: Vec<String> = Vec::new();    let mut letters = Letters::default();    let mut shown = Vec::new();    for group in &reads {        for run in &group.runs {            match &run.reading {                Reading::Letter { letter, .. } | Reading::Doubtful { letter, .. } => {                    said_.push(letter.clone());                    letters = letters.adding(letter, false);                }                Reading::Clear => {                    said_.push("clear".into());                    letters = Letters::default();                }                Reading::Line { from, to } => {                    if let Some(edit) = letters.edit_by_line(*from, *to, &reader.knobs) {                        letters = letters.applying(edit);                    } else if (to.x - from.x).abs() > (to.y - from.y).abs() {                        said_.push("swipe".into());                    }                }                Reading::Mark(name) => said_.push(name.clone()),                Reading::Nothing => {}            }        }        shown.push(letters.letters.clone());    }    // A group's label names each letter it meant, `+` between them.    let intended: Vec<String> = groups.iter().filter_map(|labelled| labelled.intended.as_deref()).flat_map(|intended| intended.split('+').map(str::to_string)).collect();    Streamed { pairs: aligned(&intended, &said_), shown, groups: reads.len() }}/// The two sequences aligned by least edits (a misread is one, a letter/// missed or extra one).pub fn aligned(a: &[String], b: &[String]) -> Vec<(Option<String>, Option<String>)> {    let mut cost = vec![vec![0usize; b.len() + 1]; a.len() + 1];    for (i, row) in cost.iter_mut().enumerate() {        row[0] = i;    }    for j in 0..=b.len() {        cost[0][j] = j;    }    for i in 1..=a.len() {        for j in 1..=b.len() {            let swap = cost[i - 1][j - 1] + usize::from(a[i - 1] != b[j - 1]);            cost[i][j] = swap.min(cost[i - 1][j] + 1).min(cost[i][j - 1] + 1);        }    }    let mut pairs = Vec::new();    let (mut i, mut j) = (a.len(), b.len());    while i > 0 || j > 0 {        if i > 0 && j > 0 && cost[i][j] == cost[i - 1][j - 1] + usize::from(a[i - 1] != b[j - 1]) {            pairs.push((Some(a[i - 1].clone()), Some(b[j - 1].clone())));            i -= 1;            j -= 1;        } else if i > 0 && cost[i][j] == cost[i - 1][j] + 1 {            pairs.push((Some(a[i - 1].clone()), None));            i -= 1;        } else {            pairs.push((None, Some(b[j - 1].clone())));            j -= 1;        }    }    pairs.reverse();    pairs}/// Both readings as a table, intended → read, and their accuracy.pub struct Report {    pub text: String,    pub kept_accuracy: f64,    pub stream_accuracy: f64,}fn sorted_counts(counts: BTreeMap<String, usize>) -> Vec<(String, usize)> {    let mut counts: Vec<(String, usize)> = counts.into_iter().collect();    counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));    counts}pub fn report(groups: &[Labelled], reader: &Reader, model: &mut dyn Model) -> Report {    let mut lines: Vec<String> = Vec::new();    let kept = as_kept(groups, reader, model);    let kept_right = kept.iter().filter(|outcome| outcome.right()).count();    let kept_accuracy = if kept.is_empty() { 0.0 } else { kept_right as f64 / kept.len() as f64 };    lines.push(format!("INK CORPUS — {} groups kept, {} labelled", groups.len(), kept.len()));    lines.push(String::new());    lines.push(format!("Each group as kept (ink::reader): {kept_right}/{} right, {:.1}%", kept.len(), kept_accuracy * 100.0));    let mut intended: Vec<&String> = kept.iter().map(|outcome| &outcome.intended).collect();    intended.sort();    intended.dedup();    for meant in intended {        let mine: Vec<&Outcome> = kept.iter().filter(|outcome| &outcome.intended == meant).collect();        let right = mine.iter().filter(|outcome| outcome.right()).count();        let mut counts = BTreeMap::new();        for outcome in mine.iter().filter(|outcome| !outcome.right()) {            *counts.entry(outcome.read.clone()).or_insert(0) += 1;        }        let wrong = sorted_counts(counts).into_iter().map(|(read, count)| format!("{read}×{count}")).collect::<Vec<_>>().join(" ");        lines.push(format!("  {meant:<6} {right}/{}{}", mine.len(), if wrong.is_empty() { String::new() } else { format!("  → {wrong}") }));    }    let labelled: Vec<&Labelled> = groups.iter().filter(|labelled| labelled.intended.is_some()).collect();    let mut by_case: BTreeMap<String, (usize, usize)> = BTreeMap::new();    for (labelled, outcome) in labelled.iter().zip(&kept) {        let entry = by_case.entry(labelled.written.clone().unwrap_or_default()).or_insert((0, 0));        entry.1 += 1;        entry.0 += usize::from(outcome.right());    }    if by_case.keys().any(|written| !written.is_empty()) {        for (written, (right, all)) in &by_case {            lines.push(format!("  {} case: {right}/{all} right, {:.1}%", if written.is_empty() { "unsaid" } else { written }, 100.0 * *right as f64 / *all as f64));        }    }    lines.push(String::new());    lines.push("Every group, intended → read (score; next best) :".into());    for outcome in &kept {        lines.push(format!("  {} {} → {}", if outcome.right() { " " } else { "✗" }, outcome.intended, outcome.detail));    }    let stream = streamed(groups, reader, model);    let right = stream.pairs.iter().filter(|(meant, read)| meant.is_some() && meant == read).count();    let meant = stream.pairs.iter().filter(|(meant, _)| meant.is_some()).count();    let stream_accuracy = if meant == 0 { 0.0 } else { right as f64 / meant as f64 };    lines.push(String::new());    lines.push(format!(        "Regrouped on the real timings (ink::stream + ink::letters): {} groups, {right}/{meant} letters right, {:.1}%",        stream.groups,        stream_accuracy * 100.0    ));    let mut confusions = BTreeMap::new();    for (meant, read) in stream.pairs.iter().filter(|(meant, read)| meant != read) {        *confusions.entry(format!("{} → {}", meant.as_deref().unwrap_or("∅"), read.as_deref().unwrap_or("∅"))).or_insert(0) += 1;    }    for (pair, count) in sorted_counts(confusions) {        lines.push(format!("  {pair} ×{count}"));    }    lines.push(format!("  intended: {}", stream.pairs.iter().map(|(meant, _)| meant.as_deref().unwrap_or("∅")).collect::<Vec<_>>().join(" ")));    lines.push(format!("  read:     {}", stream.pairs.iter().map(|(_, read)| read.as_deref().unwrap_or("∅")).collect::<Vec<_>>().join(" ")));    lines.push(format!("  readout after each group: {}", stream.shown.iter().map(|shown| if shown.is_empty() { "·" } else { shown.as_str() }).collect::<Vec<_>>().join(" ")));    Report { text: lines.join("\n") + "\n", kept_accuracy, stream_accuracy }}/// A set of writing measured: its letters' lags, seconds.pub struct Measured {    pub name: String,    pub lags: Vec<f64>,}impl Measured {    pub fn line(&self) -> String {        let mut sorted = self.lags.clone();        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));        let at = |share: f64| if sorted.is_empty() { 0.0 } else { sorted[((sorted.len() as f64 * share) as usize).min(sorted.len() - 1)] };        format!("{}: {} letters, p50 {:.2} s, p95 {:.2} s, max {:.2} s", self.name, sorted.len(), at(0.5), at(0.95), sorted.last().copied().unwrap_or(0.0))    }}/// Each letter read from `strokes` and how long after its last lift it was/// read final.pub fn lags(strokes: &[TimedStroke], reader: &Reader, height: Option<f64>, model: &mut dyn Model) -> Vec<f64> {    Stream::replay(strokes, reader.clone(), height, Admits::EVERY, model)        .iter()        .flat_map(|group| {            group.runs.iter().filter_map(move |run| {                // A letter is said as one letter; a mark by its name.                if said(&run.reading).chars().count() != 1 {                    return None;                }                let up = run.strokes.iter().map(|at| group.strokes[*at].up).fold(f64::NEG_INFINITY, f64::max);                up.is_finite().then(|| group.read - up)            })        })        .collect()}/// `shape`'s strokes (0–100 box, y down) drawn `size` tall with its left edge/// at `left`, each at 450 points a second, from `start`, `gap` between one/// lift and the next touch.pub fn timed(shape: &[Vec<Vec<f64>>], size: f64, left: f64, top: f64, start: f64, gap: f64) -> Vec<TimedStroke> {    let pace = 450.0;    let min_x = shape.iter().flatten().filter_map(|point| point.first()).cloned().fold(f64::INFINITY, f64::min);    let min_x = if min_x.is_finite() { min_x } else { 0.0 };    let mut clock = start;    shape        .iter()        .map(|stroke| {            let points: Vec<Point> = stroke.iter().map(|p| Point::new(left + (p[0] - min_x) * size / 100.0, top + p[1] * size / 100.0)).collect();            let mut times = vec![clock];            for pair in points.windows(2) {                times.push(times[times.len() - 1] + (pair[1].x - pair[0].x).hypot(pair[1].y - pair[0].y) / pace);            }            let written = TimedStroke { down: clock, up: times[times.len() - 1], points, times };            clock = written.up + gap;            written        })        .collect()}/// `word`'s letters from `natural` written side by side, a seventh of their/// height apart, each stroke `gap` after the last.pub fn word(word: &str, natural: &BTreeMap<String, Vec<Vec<Vec<f64>>>>, gap: f64, start: f64) -> Vec<TimedStroke> {    let size = 110.0;    let mut strokes: Vec<TimedStroke> = Vec::new();    let mut left = 40.0;    for letter in word.chars() {        let Some(shape) = natural.get(&letter.to_string()) else { continue };        let xs: Vec<f64> = shape.iter().flatten().filter_map(|point| point.first()).cloned().collect();        let from = strokes.last().map(|stroke| stroke.up + gap).unwrap_or(start);        strokes.extend(timed(shape, size, left, 300.0, from, gap));        let spread = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max) - xs.iter().cloned().fold(f64::INFINITY, f64::min);        left += if spread.is_finite() { spread } else { 0.0 } * size / 100.0 + size / 7.0;    }    strokes}/// The synthetic walk and the walk traces, measured: `synthetic` is/// `ink-synthetic.json`, `traces` `ink-traces.json`.pub fn lag(synthetic: &str, traces: &str, reader: &Reader, model: &mut dyn Model) -> Result<Vec<Measured>, String> {    #[derive(serde::Deserialize)]    struct Synthetic {        natural: BTreeMap<String, Vec<Vec<Vec<f64>>>>,    }    #[derive(serde::Deserialize)]    struct Trace {        wrote: String,        strokes: Vec<Vec<Vec<f64>>>,    }    let natural = serde_json::from_str::<Synthetic>(synthetic).map_err(|error| error.to_string())?.natural;    let page = Some(450.0);    let (mut alone, mut words) = (Vec::new(), Vec::new());    for letter in natural.keys() {        for gap in [0.2, 0.5, 0.9] {            alone.extend(lags(&word(letter, &natural, gap, 1_000.0), reader, page, model));        }    }    for written in ["ca", "cl", "lo", "ab", "in", "cat", "cab", "tin", "Ha"] {        for gap in [0.2, 0.3, 0.4, 0.6, 0.9] {            words.extend(lags(&word(written, &natural, gap, 1_000.0), reader, page, model));        }    }    // The traces as written: each at a finger's pace, its strokes 0.3 s    // apart; alone (10 s after the last), and as one line of writing, each    // letter beside the last 0.3 s after it.    let letters: Vec<Vec<Vec<Vec<f64>>>> = serde_json::from_str::<Vec<Trace>>(traces)        .map_err(|error| error.to_string())?        .into_iter()        .filter(|trace| trace.wrote.chars().count() == 1)        .map(|trace| trace.strokes.into_iter().map(|stroke| stroke.into_iter().filter(|point| point.len() == 2).collect()).collect())        .collect();    let unit = |strokes: &[Vec<Vec<f64>>]| {        let points: Vec<Point> = strokes.iter().flatten().map(|p| Point::new(p[0], p[1])).collect();        let held = marks::bounds(&points);        let scale = held.height.max(1.0);        let shape: Vec<Vec<Vec<f64>>> =            strokes.iter().map(|stroke| stroke.iter().map(|p| vec![(p[0] - held.x) * 100.0 / scale, (p[1] - held.y) * 100.0 / scale]).collect()).collect();        (held, shape)    };    let mut trace_alone = Vec::new();    let mut clock = 1_000.0;    for strokes in &letters {        let (held, shape) = unit(strokes);        trace_alone.extend(lags(&timed(&shape, held.height, held.x, held.y, clock, 0.3), reader, page, model));        clock += 10.0;    }    let mut line: Vec<TimedStroke> = Vec::new();    let mut left = 20.0;    for strokes in &letters {        let (held, shape) = unit(strokes);        let from = line.last().map(|stroke| stroke.up + 0.3).unwrap_or(1_000.0);        line.extend(timed(&shape, held.height, left, held.y, from, 0.3));        left += held.width + held.height / 7.0;    }    let trace_line = lags(&line, reader, page, model);    Ok(vec![        Measured { name: "synthetic walk, each letter alone".into(), lags: alone },        Measured { name: "synthetic walk, words side by side".into(), lags: words },        Measured { name: "24 traces, each letter alone".into(), lags: trace_alone },        Measured { name: "24 traces, one line of writing".into(), lags: trace_line },    ])}/// A corpus folder's files, read by the caller: each `*.jsonl` by name/// with its text, and its labels (`labels.json`, else each file's own/// `<name>.labels.json`, else the label each line carries), as the phone/// kept them. A file whose first line holds no strokes is left out and/// named in the second list.pub fn load(files: &[(String, String)], labels_json: Option<&str>, own_labels: &BTreeMap<String, String>) -> Result<(Vec<Labelled>, Vec<String>), String> {    let mut sorted: Vec<&(String, String)> = files.iter().collect();    sorted.sort_by(|a, b| a.0.cmp(&b.0));    let mut read: Vec<(String, Vec<Captured>, Vec<Option<String>>)> = Vec::new();    let mut left_out = Vec::new();    for (name, text) in sorted {        let lines: Vec<&str> = text.split('\n').filter(|line| !line.trim().is_empty()).collect();        let first: Option<Value> = lines.first().and_then(|line| serde_json::from_str(line).ok());        if !first.as_ref().is_some_and(|value| value["strokes"].is_array()) {            left_out.push(name.clone());            continue;        }        let mut groups = Vec::new();        let mut cases = Vec::new();        for (at, line) in lines.iter().enumerate() {            let value: Value = serde_json::from_str(line).map_err(|error| format!("{name}:{}: {error}", at + 1))?;            cases.push(value["case"].as_str().map(str::to_string));            groups.push(serde_json::from_value::<Captured>(value).map_err(|error| format!("{name}:{}: {error}", at + 1))?);        }        read.push((name.clone(), groups, cases));    }    let labelled: Vec<Vec<Option<String>>> = match labels_json {        Some(text) => {            let value: Value = serde_json::from_str(text).map_err(|error| format!("labels.json: {error}"))?;            labels(&value, &read.iter().map(|(name, groups, _)| (name.clone(), groups.len())).collect::<Vec<_>>())?        }        None => read            .iter()            .map(|(name, groups, _)| match own_labels.get(name) {                Some(text) => {                    let value: Value = serde_json::from_str(text).map_err(|error| format!("{name} labels: {error}"))?;                    Ok(labels(&value, &[(name.clone(), groups.len())])?.remove(0))                }                None => Ok(groups.iter().map(|group| group.label.as_deref().map(str::to_lowercase).filter(|label| !label.is_empty())).collect()),            })            .collect::<Result<_, String>>()?,    };    let groups = read        .into_iter()        .zip(labelled)        .flat_map(|((name, groups, cases), labels)| {            groups.into_iter().zip(labels).zip(cases).map(move |((group, intended), written)| Labelled { source: name.clone(), group, intended, written })        })        .collect();    Ok((groups, left_out))}/// A corpus that says what the model read on it (`expected.json`, from/// `scripts/ink/corpus-heldout.py`) read through the phone's path, each/// group as kept among what its surface admits, at the floor it names: the/// lines to print, and whether it reads within the tolerance it gives.pub fn expected(groups: &[Labelled], expected: &str, model: &mut dyn Model) -> Result<(String, bool), String> {    #[derive(serde::Deserialize)]    struct Expected {        letter_confidence: f64,        kept: f64,        within: f64,        groups: usize,    }    let expected: Expected = serde_json::from_str(expected).map_err(|error| format!("expected.json: {error}"))?;    let alphabet = super::shipped().with(&serde_json::json!({ "letter_confidence": expected.letter_confidence }))?;    let kept = as_kept(groups, &Reader::new(&alphabet), model);    let right = kept.iter().filter(|outcome| outcome.right()).count();    let read = right as f64 / kept.len().max(1) as f64;    let mut lines = vec![format!(        "phone path at floor {:.2}: {right}/{} = {:.1}% (the model alone: {:.1}%, within {:.1})",        expected.letter_confidence,        kept.len(),        read * 100.0,        expected.kept * 100.0,        expected.within * 100.0    )];    for symbol in Symbol::EVERY {        let mine: Vec<&Outcome> = kept.iter().filter(|outcome| admits(&outcome.intended) == Admits::of(&[symbol])).collect();        let right = mine.iter().filter(|outcome| outcome.right()).count();        let name = if symbol == Symbol::Letter { "letters" } else { "digits" };        lines.push(format!("phone path, {name} alone: {right}/{} = {:.1}%", mine.len(), 100.0 * right as f64 / mine.len().max(1) as f64));    }    if kept.len() != expected.groups {        lines.push(format!("✗ the corpus holds {} labelled groups, the model was measured on {}", kept.len(), expected.groups));    }    let holds = kept.len() == expected.groups && (read - expected.kept).abs() <= expected.within;    Ok((lines.join("\n") + "\n", holds))}/// The input contract's own fixtures (`contract/fixtures.jsonl`, written by/// `scripts/ink/ink_input.py`) encoded by the core: the line to print, and/// whether every one matches to 1e-4, its stroke count exactly.pub fn contract(fixtures: &str) -> Result<(String, bool), String> {    #[derive(serde::Deserialize)]    struct Fixture {        strokes: Vec<Vec<Vec<f64>>>,        points: Vec<Vec<f64>>,        stroke_count: f64,    }    let (mut worst, mut count, mut holds) = (0.0_f64, 0, true);    for (at, line) in fixtures.lines().filter(|line| !line.trim().is_empty()).enumerate() {        let fixture: Fixture = serde_json::from_str(line).map_err(|error| format!("contract/fixtures.jsonl:{}: {error}", at + 1))?;        let strokes: Vec<Vec<Point>> =            fixture.strokes.iter().map(|stroke| stroke.iter().filter(|p| p.len() >= 2).map(|p| Point::new(p[0], p[1])).collect()).collect();        count += 1;        let Some(features) = super::input::encode(&strokes) else {            holds = false;            continue;        };        holds &= features.strokes == fixture.stroke_count && features.points.len() == fixture.points.len();        for (a, b) in features.points.iter().zip(&fixture.points) {            for j in 0..3 {                worst = worst.max((a[j] - b.get(j).copied().unwrap_or(f64::NAN)).abs());            }        }    }    holds &= count > 0 && worst <= 1e-4;    Ok((format!("encoder: {count} fixtures, max |diff| {worst:e}\n"), holds))}/// Each group as kept, read again with the model's floor/// (`letter_confidence` and `letter_floor` both) at each of `floors`: the/// share of the labelled groups read right, as one wrong letter, as/// nothing, as more than one letter, and as a mark (a line or a clear) —/// the curve `letter_confidence` is chosen on.pub fn curve(groups: &[Labelled], floors: &[f64], model: &mut dyn Model) -> Result<String, String> {    let mut lines = vec!["floor | right | wrong letter | nothing | split into letters | line or clear".to_string()];    for floor in floors {        let alphabet = super::shipped().with(&serde_json::json!({ "letter_confidence": floor, "letter_floor": floor }))?;        let outcomes = as_kept(groups, &Reader::new(&alphabet), model);        let mut tally: BTreeMap<&str, usize> = BTreeMap::new();        for outcome in &outcomes {            let kind = if outcome.right() {                "right"            } else if outcome.read == "nothing" {                "nothing"            } else if outcome.read.contains('+') {                "split"            } else if outcome.read == "clear" || outcome.read.starts_with("line") {                "mark"            } else {                "wrong"            };            *tally.entry(kind).or_insert(0) += 1;        }        let share = |kind: &str| format!("{:.1}%", 100.0 * *tally.get(kind).unwrap_or(&0) as f64 / outcomes.len().max(1) as f64);        lines.push(format!("{floor:.2} | {}", ["right", "wrong", "nothing", "split", "mark"].map(share).join(" | ")));    }    Ok(lines.join("\n") + "\n")}/// What the model's best letter scores, binned at `edges`, over the/// labelled groups read as one letter (right or wrong) and over `noise`,/// strokes that are no letter handed to the model: the table `letter_floor`/// and `letter_confidence` are chosen on. Every group is read with no floor/// at all, so each has a score.pub fn band(groups: &[Labelled], edges: &[f64], noise: &[Vec<Vec<Point>>], model: &mut dyn Model) -> Result<String, String> {    let reader = Reader::new(&super::shipped().with(&serde_json::json!({ "letter_confidence": 1.01, "letter_floor": 0 }))?);    let bin = |score: f64| edges.iter().rposition(|edge| score >= *edge).unwrap_or(0);    let (mut right, mut wrong, mut noisy) = (vec![0; edges.len()], vec![0; edges.len()], vec![0; edges.len()]);    let (mut marks, mut split) = (0, 0);    for labelled in groups {        let Some(intended) = &labelled.intended else { continue };        let strokes: Vec<Vec<Point>> = labelled.group.timed(0.0).into_iter().map(|stroke| stroke.points).collect();        let runs = reader.runs(&strokes, labelled.group.height, admits(intended), model);        match runs.as_slice() {            [Run { reading: Reading::Doubtful { letter, score }, .. }] => {                if letter == intended {                    right[bin(*score)] += 1;                } else {                    wrong[bin(*score)] += 1;                }            }            [_] => marks += 1,            _ => split += 1,        }    }    let mut noise_marks = 0;    for strokes in noise {        let runs = reader.runs(strokes, None, Admits::EVERY, model);        let scores: Vec<f64> = runs.iter().filter_map(|run| if let Reading::Doubtful { score, .. } = run.reading { Some(score) } else { None }).collect();        if scores.is_empty() {            noise_marks += 1;        }        for score in scores {            noisy[bin(score)] += 1;        }    }    let mut lines = vec!["best letter's score | held-out right | held-out wrong | noise (no letter)".to_string()];    for (index, edge) in edges.iter().enumerate() {        let top = edges.get(index + 1).map(|top| format!("{top:.2}")).unwrap_or_else(|| "1".into());        lines.push(format!("{edge:.2}–{top} | {} | {} | {}", right[index], wrong[index], noisy[index]));    }    lines.push(format!("held-out read as a mark: {marks}, split into letters: {split}; noise read as a mark: {noise_marks} of {}", noise.len()));    Ok(lines.join("\n") + "\n")}/// `count` scrawls that are no letter, from `seed`: a finger wandering/// 30–60 points, turning at random, in a box of 60–160 pt — what a stroke/// that is no letter at all looks like to the model.pub fn scrawls(count: usize, seed: u64) -> Vec<Vec<Vec<Point>>> {    let mut state = seed;    let mut random = move || {        state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);        (state >> 11) as f64 / (1u64 << 53) as f64    };    (0..count)        .map(|_| {            let size = 60.0 + 100.0 * random();            let steps = 30 + (30.0 * random()) as usize;            let mut point = Point::new(200.0, 300.0);            let (mut heading, mut turn) = (2.0 * std::f64::consts::PI * random(), 0.0);            let mut points = vec![point];            for _ in 0..steps {                turn = 0.7 * turn + (random() - 0.5) * 0.9;                heading += turn;                point = Point::new(point.x + heading.cos() * size / 12.0, point.y + heading.sin() * size / 12.0);                points.push(point);            }            vec![points]        })        .collect()}#[cfg(test)]#[path = "replay_tests.rs"]mod replay_tests;