Cotton code
291 lines · 10.8 KB · RustRaw
//! What the ink's tests write with: synthetic strokes as a finger lays them//! (`ink-synthetic.json`'s shapes, sized, turned, wobbled by a seeded//! generator — the same numbers the Swift tests drew before the move), and//! the letter model as it answered on the simulator (`model.jsonl`: every//! group the Swift tests and `swift-readings.json` had it read, by its//! `Features::key`, recorded from Core ML before the reader moved here).use std::collections::{BTreeMap, HashMap};use std::sync::LazyLock;use serde::Deserialize;use super::reader::Model;use super::stream::TimedStroke;use super::{Features, Point};pub const SYNTHETIC: &str = include_str!("../../tests/fixtures/ink/ink-synthetic.json");pub const TRACES: &str = include_str!("../../tests/fixtures/ink/ink-traces.json");const MODEL: &str = include_str!("../../tests/fixtures/ink/model.jsonl");/// Synthetic writing: the shapes the letter templates once drew, in a 0–100/// box, y down.#[derive(Debug, Deserialize)]pub struct Synthetic {    pub letters: Vec<SyntheticLetter>,    pub multistroke: Vec<SyntheticWays>,    pub natural: BTreeMap<String, Vec<Vec<Vec<f64>>>>,}#[derive(Debug, Deserialize)]pub struct SyntheticLetter {    pub letter: String,    pub strokes: Vec<Vec<Vec<f64>>>,}#[derive(Debug, Deserialize)]pub struct SyntheticWays {    pub letter: String,    pub ways: Vec<Vec<Vec<Vec<f64>>>>,}pub static SYNTHETIC_SHAPES: LazyLock<Synthetic> = LazyLock::new(|| serde_json::from_str(SYNTHETIC).expect("ink-synthetic.json reads"));/// The first one-stroke way of `letter`.pub fn shape(letter: &str) -> Vec<Vec<f64>> {    SYNTHETIC_SHAPES.letters.iter().find(|held| held.letter == letter).map(|held| held.strokes[0].clone()).expect("a synthetic letter")}/// A small deterministic generator (SplitMix64), the Swift tests' own.pub struct Seeded(u64);impl Seeded {    pub fn new(seed: u64) -> Self {        Seeded(seed.wrapping_add(0x9E37_79B9_7F4A_7C15))    }    pub fn next(&mut self) -> u64 {        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);        let mut z = self.0;        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);        z ^ (z >> 31)    }    pub fn unit(&mut self) -> f64 {        (self.next() >> 11) as f64 / (1u64 << 53) as f64    }    pub fn centred(&mut self) -> f64 {        self.unit() * 2.0 - 1.0    }}pub fn points(shape: &[Vec<f64>]) -> Vec<Point> {    shape.iter().map(|point| Point::new(point[0], point[1])).collect()}/// A shape's points made dense, a point every `step` or so.pub fn dense(points: &[Point], step: f64) -> Vec<Point> {    let Some(first) = points.first() else { return Vec::new() };    let mut out = vec![*first];    for pair in points.windows(2) {        let (a, b) = (pair[0], pair[1]);        let n = (((b.x - a.x).hypot(b.y - a.y) / step) as i64).max(1);        for j in 1..=n {            out.push(Point::new(a.x + (b.x - a.x) * j as f64 / n as f64, a.y + (b.y - a.y) * j as f64 / n as f64));        }    }    out}/// How a shape is written.#[derive(Debug, Clone, Copy)]pub struct Hand {    pub size: f64,    pub origin: Point,    pub stretch: (f64, f64),    pub degrees: f64,    pub wobble: f64,    pub seed: u64,}impl Hand {    pub fn at(size: f64, x: f64, y: f64) -> Hand {        Hand { size, origin: Point::new(x, y), stretch: (1.0, 1.0), degrees: 0.0, wobble: 0.0, seed: 0 }    }    pub fn wobble(self, wobble: f64, seed: u64) -> Hand {        Hand { wobble, seed, ..self }    }    pub fn turned(self, degrees: f64) -> Hand {        Hand { degrees, ..self }    }    pub fn stretched(self, x: f64, y: f64) -> Hand {        Hand { stretch: (x, y), ..self }    }}/// A shape (0–100) as a finger lays it: made dense, sized, stretched, turned,/// placed, and wobbled — slow drift and a little tremor.pub fn written(shape: &[Vec<f64>], hand: Hand) -> Vec<Point> {    let points = dense(&points(shape), 3.0);    let angle = hand.degrees * std::f64::consts::PI / 180.0;    let (c, s) = (angle.cos(), angle.sin());    let placed: Vec<Point> = points        .iter()        .map(|p| {            let x = (p.x - 50.0) * hand.stretch.0 * hand.size / 100.0;            let y = (p.y - 50.0) * hand.stretch.1 * hand.size / 100.0;            Point::new(hand.origin.x + x * c - y * s, hand.origin.y + x * s + y * c)        })        .collect();    if hand.wobble <= 0.0 {        return placed;    }    let mut random = Seeded::new(hand.seed);    let phase = (random.unit() * SYNTH_TURN, random.unit() * SYNTH_TURN);    let amount = hand.wobble * hand.size / 100.0;    let n = placed.len() as f64;    placed        .iter()        .enumerate()        .map(|(i, p)| {            let t = i as f64 / n * SYNTH_TURN;            let x = p.x + amount * 2.0 * (t * 1.5 + phase.0).sin() + amount * 0.4 * random.centred();            let y = p.y + amount * 2.0 * (t * 1.1 + phase.1).sin() + amount * 0.4 * random.centred();            Point::new(x, y)        })        .collect()}/// The synthetic hand's whole turn, 6.28 as Swift's synth wrote it, never/// TAU: the recorded model's answers are keyed by the exact points drawn.#[allow(clippy::approx_constant)]const SYNTH_TURN: f64 = 6.28;pub fn line(from: Point, to: Point) -> Vec<Point> {    dense(&[from, to], 4.0)}pub fn circle(centre: Point, radius: f64) -> Vec<Point> {    (0..=24).map(|i| Point::new(centre.x + radius * (i as f64 / 24.0 * SYNTH_TURN).cos(), centre.y + radius * (i as f64 / 24.0 * SYNTH_TURN).sin())).collect()}pub fn arc(centre: Point, radius: f64, from: f64, to: f64) -> Vec<Point> {    (0..=30)        .map(|i| {            let a = (from + (to - from) * i as f64 / 30.0) * std::f64::consts::PI / 180.0;            Point::new(centre.x + radius * a.cos(), centre.y + radius * a.sin())        })        .collect()}/// A way's strokes as a finger writes them, in `order`, those `flips` marks/// backwards, each a little off its place (`slip`, in percent of the size)/// and wobbled on its own.pub fn written_way(way: &[Vec<Vec<f64>>], order: &[usize], flips: usize, hand: Hand, slip: f64) -> Vec<Vec<Point>> {    let mut random = Seeded::new(hand.seed);    order        .iter()        .enumerate()        .map(|(place, index)| {            let mut stroke = way[*index].clone();            if flips & (1 << place) != 0 {                stroke.reverse();            }            let (dx, dy) = (slip * random.centred(), slip * random.centred());            let moved: Vec<Vec<f64>> = stroke.iter().map(|point| vec![point[0] + dx, point[1] + dy]).collect();            written(&moved, Hand { seed: random.next(), ..hand })        })        .collect()}/// Strokes as a finger lays them, on a clock: the shapes drawn `size` tall/// (and `width` wide), each at a finger's pace (`pace` pt a second), the gaps/// between one lift and the next touch given.pub fn timed(shapes: &[Vec<Vec<f64>>], size: f64, width: Option<f64>, origin: Point, gaps: &[f64], start: f64, seed: u64) -> Vec<TimedStroke> {    let pace = 450.0;    let mut clock = start;    shapes        .iter()        .enumerate()        .map(|(index, shape)| {            let hand = Hand { size, origin, stretch: (width.unwrap_or(size) / size, 1.0), degrees: 0.0, wobble: 1.0, seed: seed.wrapping_add(index as u64) };            let points = written(shape, hand);            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 stroke = TimedStroke { down: clock, up: times[times.len() - 1], points, times };            clock = stroke.up + gaps.get(index).copied().unwrap_or(0.0);            stroke        })        .collect()}static ANSWERS: LazyLock<HashMap<String, Vec<f64>>> = LazyLock::new(|| {    #[derive(Deserialize)]    struct Answer {        key: String,        p: Vec<f64>,    }    MODEL        .lines()        .filter(|line| !line.trim().is_empty())        .map(|line| serde_json::from_str::<Answer>(line).expect("model.jsonl's lines read"))        .map(|answer| (answer.key, answer.p))        .collect()});/// The letter model as Core ML answered it on the simulator: a group it never/// read is said (`missed`), and the test holding it fails on it.#[derive(Default)]pub struct Recorded {    pub missed: Vec<String>,}impl Model for Recorded {    fn probabilities(&mut self, features: &Features) -> Option<Vec<f64>> {        let key = features.key();        let answer = ANSWERS.get(&key).cloned();        if answer.is_none() && !self.missed.contains(&key) {            self.missed.push(key);        }        answer    }}impl Recorded {    /// Every group asked was one the model had read.    pub fn all_read(&self) {        assert!(self.missed.is_empty(), "the recorded model never read {} of the groups asked: {:?}", self.missed.len(), self.missed);    }}/// A model that answers one letter for every group, surely: for the rules/// that never hang on what the letter is.pub struct Always(pub &'static str, pub f64);impl Model for Always {    fn probabilities(&mut self, _features: &Features) -> Option<Vec<f64>> {        let at = super::input::CLASSES.iter().position(|class| *class == self.0)?;        let rest = (1.0 - self.1) / 61.0;        Some((0..62).map(|i| if i == at { self.1 } else { rest }).collect())    }}/// Checks as a finger draws them, 0–100, y down: a short leg down to a corner, a long one up and on.pub fn checks() -> Vec<(&'static str, Vec<Vec<f64>>)> {    let v = |points: &[[f64; 2]]| points.iter().map(|p| p.to_vec()).collect::<Vec<_>>();    vec![        ("tick", v(&[[0., 60.], [25., 85.], [100., 0.]])),        ("steep", v(&[[0., 50.], [20., 80.], [100., 0.]])),        ("wide", v(&[[0., 40.], [18., 70.], [100., 10.]])),        ("swoosh", v(&[[0., 55.], [22., 82.], [50., 62.], [75., 35.], [100., 0.]])),    ]}pub fn zigzag_letters() -> Vec<(&'static str, Vec<Vec<f64>>, f64)> {    let v = |points: &[[f64; 2]]| points.iter().map(|p| p.to_vec()).collect::<Vec<_>>();    vec![        ("W", v(&[[0., 0.], [25., 100.], [50., 30.], [75., 100.], [100., 0.]]), 110.0),        ("M", v(&[[0., 100.], [0., 0.], [50., 70.], [100., 0.], [100., 100.]]), 110.0),        ("w", v(&[[0., 30.], [25., 100.], [50., 50.], [75., 100.], [100., 30.]]), 70.0),        (            "m",            v(&[[0., 40.], [0., 100.], [0., 55.], [15., 42.], [30., 45.], [35., 60.], [35., 100.], [35., 55.], [50., 42.], [65., 45.], [70., 60.], [70., 100.]]),            80.0,        ),        ("z", v(&[[0., 0.], [100., 0.], [0., 100.], [100., 100.]]), 70.0),        ("N", v(&[[0., 100.], [0., 0.], [100., 100.], [100., 0.]]), 110.0),        ("B", v(&[[0., 100.], [0., 0.], [60., 5.], [70., 25.], [55., 45.], [0., 50.], [70., 55.], [80., 75.], [65., 95.], [0., 100.]]), 110.0),    ]}