Cotton code
128 lines · 5.2 KB · RustRaw
//! THE MODEL'S INPUT CONTRACT: `scripts/ink/ink_input.py` is the reference the//! letter model was trained on, and this is its twin, held to the contract's//! fixtures to 1e-4 (`input_tests`, and the drift test that runs the Python//! over the same strokes). The model itself is the platform's: the shell//! feeds it `Features` and hands back its 62 probabilities.use serde::Serialize;use super::{Point, Score};/// The model's classes, in its output's order: a–z, A–Z, then 0–9.pub const CLASSES: [&str; 62] = [    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C",    "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4",    "5", "6", "7", "8", "9",];/// How many samples the model reads.pub const SAMPLES: usize = 64;/// What the model reads for a group of strokes: 64 samples [x, y, pen_up] in/// the unit box, and the number of non-empty strokes.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Features {    pub points: Vec<[f64; 3]>,    pub strokes: f64,}impl Features {    /// The group's name between the core and the shell: FNV-1a 64 over every    /// value to 1e-5 and the stroke count, as 16 hex digits. Two groups the    /// model cannot tell apart share it.    pub fn key(&self) -> String {        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;        let mut eat = |value: i64| {            for byte in value.to_le_bytes() {                hash ^= byte as u64;                hash = hash.wrapping_mul(0x0000_0100_0000_01b3);            }        };        for point in &self.points {            for value in point {                eat((value * 1e5).round() as i64);            }        }        eat(self.strokes.round() as i64);        format!("{hash:016x}")    }}/// `strokes` (points in the order written) as the model reads them; None for/// no point at all.pub fn encode(strokes: &[Vec<Point>]) -> Option<Features> {    let strokes: Vec<&Vec<Point>> = strokes.iter().filter(|stroke| !stroke.is_empty()).collect();    let mut points: Vec<Point> = Vec::new();    let mut jump: Vec<bool> = Vec::new();    for stroke in &strokes {        for (at, point) in stroke.iter().enumerate() {            if !points.is_empty() {                jump.push(at == 0);            }            points.push(*point);        }    }    let first = *points.first()?;    let segments: Vec<f64> = points.windows(2).map(|pair| (pair[1].x - pair[0].x).hypot(pair[1].y - pair[0].y)).collect();    let total: f64 = segments.iter().sum();    let mut samples: Vec<[f64; 3]> = Vec::with_capacity(SAMPLES);    if total == 0.0 {        samples = vec![[first.x, first.y, 0.0]; SAMPLES];    } else {        let mut cumulative = vec![0.0];        for segment in &segments {            cumulative.push(cumulative[cumulative.len() - 1] + segment);        }        let nonzero: Vec<usize> = (0..segments.len()).filter(|at| segments[*at] > 0.0).collect();        let mut j = 0;        for k in 0..SAMPLES {            let distance = total * k as f64 / (SAMPLES - 1) as f64;            let i = if k == SAMPLES - 1 {                nonzero[nonzero.len() - 1]            } else {                while cumulative[nonzero[j] + 1] < distance {                    j += 1;                }                nonzero[j]            };            let u = ((distance - cumulative[i]) / segments[i]).clamp(0.0, 1.0);            let (a, b) = (points[i], points[i + 1]);            samples.push([a.x + (b.x - a.x) * u, a.y + (b.y - a.y) * u, if jump[i] { 1.0 } else { 0.0 }]);        }    }    let min_x = points.iter().map(|p| p.x).fold(f64::INFINITY, f64::min);    let min_y = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);    let w = points.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max) - min_x;    let h = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max) - min_y;    let mut s = w.max(h);    if s < 1e-6 {        s = 1.0;    }    let (ox, oy) = ((1.0 - w / s) / 2.0, (1.0 - h / s) / 2.0);    Some(Features {        points: samples.iter().map(|sample| [(sample[0] - min_x) / s + ox, (sample[1] - min_y) / s + oy, sample[2]]).collect(),        strokes: strokes.len() as f64,    })}/// The model's 62 probabilities as the deck reads them: each letter's lower/// and upper case summed, each digit's as it is — 36 symbols, the most/// probable first (a tie by the symbol). None for an answer that is not 62.pub fn fold(probabilities: &[f64]) -> Option<Vec<Score>> {    if probabilities.len() != CLASSES.len() {        return None;    }    let mut scores: Vec<Score> = (0..26).map(|at| Score { letter: CLASSES[at].to_string(), score: probabilities[at] + probabilities[at + 26] }).collect();    scores.extend((52..CLASSES.len()).map(|at| Score { letter: CLASSES[at].to_string(), score: probabilities[at] }));    sort(&mut scores);    Some(scores)}/// Best first; a tie by the symbol.pub fn sort(scores: &mut [Score]) {    scores.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal).then_with(|| a.letter.cmp(&b.letter)));}#[cfg(test)]#[path = "input_tests.rs"]mod input_tests;