Cotton code
369 lines · 16.7 KB · RustRaw
//! THE READING OF A GROUP (owner, 3 Nov 2026: "the model is the letter//! reader"): the marks are read by rule (`marks`), and every other run of//! strokes is a letter the platform's letter model reads.//!//! Strokes written one after another (`stream`) are split into the fewest//! letters they read as (owner, 3 Nov 2026: an H in three tall strokes read//! "iii"): a run of up to `most_strokes` strokes that overlap one another//! across, as one letter's parts do, that the model reads as a letter at//! `letter_floor` is that letter — doubtful under `letter_confidence`, shown//! lighter, and narrowing all the same — unless a cut of it into two reads//! `doubt_cut` surely. A letter the model reads under `turn_under` is read//! turned by `read_turns` too, averaged, so a slanting hand reads. Letters//! written side by side never overlap, so "cl" is never the d the two make,//! nor "co" the O. A dot (an i's, a j's) starts no run: it is read with the//! strokes before it, as the model was trained.//!//! The model reads digits too (owner, 3 Nov 2026: "I also want to include//! having numbers"), and the surface decides what it takes (`admits`): the//! best admitted reading at `letter_floor` is taken, else nothing — a 0 on//! People is the o, an o on an amount the 0.use std::collections::HashMap;use super::input::{self, Features};use super::marks;use super::{Admits, Alphabet, Knobs, Point, Reading, Run, Score, Symbol};/// The platform's letter model, as the reader asks it.pub trait Model {    /// The model's 62 probabilities for `features`, in `input::CLASSES`'    /// order; None when it has not read them, which the reader takes as no    /// letter for now (the shell's boundary asks the shell and reads again).    fn probabilities(&mut self, features: &Features) -> Option<Vec<f64>>;}/// The reader: the marks' rules and the cut of a group into letters, over/// the alphabet's knobs.#[derive(Debug, Clone)]pub struct Reader {    pub knobs: Knobs,}impl Reader {    pub fn new(alphabet: &Alphabet) -> Self {        Self { knobs: alphabet.knobs.clone() }    }    /// The reader this build ships.    pub fn shipped() -> Self {        Self::new(super::shipped())    }    /// A dot (an i's, a j's) or a tap's slide.    pub fn dot(&self, points: &[Point]) -> bool {        marks::dot(points, &self.knobs)    }    /// A line, or a thin stroke a little arced.    pub fn straight(&self, points: &[Point]) -> bool {        marks::straight(points, &self.knobs)    }    /// The stroke as a mark, or None when it is a letter's.    pub fn mark(&self, points: &[Point], height: Option<f64>) -> Option<Reading> {        marks::mark(points, height, &self.knobs)    }    /// Strokes written one after another, read: each letter they make, among    /// the symbols `admits` holds.    pub fn read_group(&self, strokes: &[Vec<Point>], height: Option<f64>, admits: Admits, model: &mut dyn Model) -> Vec<Reading> {        self.runs(strokes, height, admits, model).into_iter().map(|run| run.reading).collect()    }    /// Strokes written one after another, split into the fewest letters they    /// read as: a run of up to `most_strokes` strokes, all linked by    /// overlapping across (`marks::across`), that the model reads as a letter    /// at `letter_floor` is that letter (doubtful under `letter_confidence`);    /// a stroke joining nothing reads alone (`read`); among as many letters    /// the more surely read wins. A mark that edits the letters is never a    /// letter's part (`together`). A run starts at a stroke that is no dot and    /// takes the dots after it. `height` is the page's, which a lone upright    /// line is measured against; `admits` what the surface holds.    pub fn runs(&self, strokes: &[Vec<Point>], height: Option<f64>, admits: Admits, model: &mut dyn Model) -> Vec<Run> {        let kept: Vec<usize> = (0..strokes.len()).filter(|at| !self.dot(&strokes[*at])).collect();        if kept.is_empty() {            return Vec::new();        }        let mut cut = Cut { reader: self, strokes, kept: &kept, height, admits, read: HashMap::new(), model };        // The fewest runs; among as many, the most surely read (the sum of        // each run's log `sureness`).        let mut best: Vec<Option<(usize, f64, Vec<Run>)>> = vec![None; kept.len() + 1];        best[0] = Some((0, 0.0, Vec::new()));        for end in 1..=kept.len() {            for length in 1..=self.knobs.most_strokes.min(end) {                let Some(before) = best[end - length].clone() else { continue };                let Some(run) = cut.letter(end - length, end) else { continue };                let score = before.1 + self.sureness(&run).max(1e-9).ln();                let mut runs = before.2;                runs.push(run);                let next = (before.0 + 1, score, runs);                if let Some(held) = &best[end] {                    if held.0 < next.0 || (held.0 == next.0 && held.1 >= next.1) {                        continue;                    }                }                best[end] = Some(next);            }        }        best[kept.len()].take().map(|best| best.2).unwrap_or_default()    }    /// Whether the group may go on after `points`, and waits    /// `group_near_seconds` for the next stroke: a line (an upright one too:    /// a stem), a stroke the model reads as no letter of its own, or one it    /// reads as a letter that often begins a longer one (`opens_after`).    pub fn opens(&self, points: &[Point], height: Option<f64>, admits: Admits, model: &mut dyn Model) -> bool {        if self.dot(points) {            return false;        }        if self.straight(points) {            return true;        }        match self.read(points, height, admits, model) {            Reading::Line { .. } | Reading::Nothing => true,            Reading::Letter { letter, .. } => self.knobs.opens_after.contains(&letter),            // A letter the model doubts may be a longer one begun.            Reading::Doubtful { .. } => true,            Reading::Clear | Reading::Mark(_) => false,        }    }    /// The stroke `points` alone: a mark, or the model's letter among those    /// `admits` holds.    pub fn read(&self, points: &[Point], height: Option<f64>, admits: Admits, model: &mut dyn Model) -> Reading {        if points.is_empty() {            return Reading::Nothing;        }        let strokes = [points.to_vec()];        self.alone(&[0], 0, &strokes, height, admits, model).reading    }    /// One stroke (`stroke`, the place among `places` that is no dot) as a    /// run of its own with its dots: a mark, or the model's best letter    /// `admits` holds.    fn alone(&self, places: &[usize], stroke: usize, strokes: &[Vec<Point>], height: Option<f64>, admits: Admits, model: &mut dyn Model) -> Run {        if let Some(mark) = self.mark(&strokes[stroke], height) {            return Run { strokes: places.to_vec(), reading: mark, runners: Vec::new() };        }        let group: Vec<Vec<Point>> = places.iter().map(|at| strokes[*at].clone()).collect();        let letters = self.scores(&group, admits, model);        match letters.first() {            Some(best) if best.score >= self.knobs.letter_floor => {                Run { strokes: places.to_vec(), reading: self.reading(best), runners: letters.iter().skip(1).take(3).cloned().collect() }            }            _ => Run { strokes: places.to_vec(), reading: Reading::Nothing, runners: letters.iter().take(3).cloned().collect() },        }    }    /// The model's best letter at or over `letter_floor`: sure, or doubtful    /// under `letter_confidence`.    fn reading(&self, best: &Score) -> Reading {        if best.score >= self.knobs.letter_confidence {            Reading::Letter { letter: best.letter.clone(), score: best.score }        } else {            Reading::Doubtful { letter: best.letter.clone(), score: best.score }        }    }    /// How surely a run reads, for weighing one cut of a group against    /// another: a letter by its probability, a stroke that is no letter by    /// its best letter's; a mark that edits the letters as sure; any other    /// line — a bar, a slant, most likely a letter's part — as    /// `letter_confidence`.    fn sureness(&self, run: &Run) -> f64 {        match &run.reading {            Reading::Letter { score, .. } | Reading::Doubtful { score, .. } => *score,            Reading::Nothing => run.runners.first().map(|runner| runner.score).unwrap_or(0.0),            Reading::Clear | Reading::Line { .. } | Reading::Mark(_) => {                if self.edits(run) {                    1.0                } else {                    self.knobs.letter_confidence                }            }        }    }    /// A mark that edits the letters, never a letter's part: a scratch-out,    /// or a short level stroke to the left (the letters' backspace).    fn edits(&self, run: &Run) -> bool {        match &run.reading {            Reading::Clear => true,            Reading::Line { from, to } => {                let dx = to.x - from.x;                dx < 0.0 && dx.abs() > (to.y - from.y).abs() && dx.abs() < self.knobs.swipe_at_once            }            _ => false,        }    }    /// The model's letters for `group` that `admits` holds, best first: as    /// written, and when the best of those is under `turn_under`, read again    /// turned by each of `read_turns` degrees about its box's centre, their    /// probabilities averaged — a hand that slants its letters (owner, 3 Nov    /// 2026: "c written at a slant") reads as an upright one does. A symbol    /// the surface cannot hold is never among them, and each is read as the    /// model's probability given that the symbol is one the surface holds    /// (those it holds summing to 1).    fn scores(&self, group: &[Vec<Point>], admits: Admits, model: &mut dyn Model) -> Vec<Score> {        let upright = admitted(read_model(group, model), admits);        let turns = &self.knobs.read_turns;        let Some(best) = upright.first() else { return upright };        if !turns.iter().any(|degrees| *degrees != 0.0) || best.score >= self.knobs.turn_under {            return upright;        }        let points: Vec<Point> = group.iter().flatten().copied().collect();        let held = marks::bounds(&points);        let (mid_x, mid_y) = (held.mid_x(), held.mid_y());        let mut sum: Vec<Score> = Vec::new();        for degrees in turns {            let reads = if *degrees == 0.0 {                upright.clone()            } else {                let angle = degrees * std::f64::consts::PI / 180.0;                let (c, s) = (angle.cos(), angle.sin());                let turned: Vec<Vec<Point>> = group                    .iter()                    .map(|stroke| {                        stroke                            .iter()                            .map(|p| Point { x: mid_x + (p.x - mid_x) * c - (p.y - mid_y) * s, y: mid_y + (p.x - mid_x) * s + (p.y - mid_y) * c })                            .collect()                    })                    .collect();                admitted(read_model(&turned, model), admits)            };            for read in reads {                let share = read.score / turns.len() as f64;                match sum.iter_mut().find(|held| held.letter == read.letter) {                    Some(held) => held.score += share,                    None => sum.push(Score { letter: read.letter, score: share }),                }            }        }        input::sort(&mut sum);        sum    }}/// The model's 36 symbols for `group`, best first; none while it has not/// read them.fn read_model(group: &[Vec<Point>], model: &mut dyn Model) -> Vec<Score> {    input::encode(group).and_then(|features| model.probabilities(&features)).and_then(|answer| input::fold(&answer)).unwrap_or_default()}/// Those of `read` the surface holds, each as the model's probability given/// that the symbol is one it holds.fn admitted(read: Vec<Score>, admits: Admits) -> Vec<Score> {    let count = read.len();    let kept: Vec<Score> = read.into_iter().filter(|score| admits.contains(Symbol::of(&score.letter))).collect();    let total: f64 = kept.iter().map(|score| score.score).sum();    if kept.len() >= count || total <= 0.0 {        return kept;    }    kept.into_iter().map(|score| Score { letter: score.letter, score: score.score / total }).collect()}/// One group's cut into letters, each run of kept strokes read once.struct Cut<'a> {    reader: &'a Reader,    strokes: &'a [Vec<Point>],    kept: &'a [usize],    height: Option<f64>,    admits: Admits,    read: HashMap<(usize, usize), Option<Run>>,    model: &'a mut dyn Model,}impl Cut<'_> {    /// The strokes from the `start`th kept stroke to the `end`th, with the    /// dots after them (and before the first, with the first).    fn places(&self, start: usize, end: usize) -> Vec<usize> {        let from = if start == 0 { 0 } else { self.kept[start] };        let to = if end == self.kept.len() { self.strokes.len() } else { self.kept[end] };        (from..to).collect()    }    /// The run of kept strokes [start, end) as one letter, read once.    fn letter(&mut self, start: usize, end: usize) -> Option<Run> {        if let Some(known) = self.read.get(&(start, end)) {            return known.clone();        }        let places = self.places(start, end);        let run = if end - start == 1 {            Some(self.reader.alone(&places, self.kept[start], self.strokes, self.height, self.admits, self.model))        } else {            self.together(start, end, &places)        };        self.read.insert((start, end), run.clone());        run    }    /// The run of kept strokes [start, end) (with their dots, `places`) as    /// one letter, if they stand together — each overlapping another across,    /// all linked (an H's two stems by its bar) — and the model reads them as    /// a letter at `letter_floor`, more surely than any cut of them into two    /// runs one of which edits the letters: a backspace across an O is never    /// the O's. A run the model only doubts is no letter when a cut of it    /// reads at least `doubt_cut` surely: an "at" written quickly is the a    /// and the t, never the doubtful e the three strokes make.    fn together(&mut self, start: usize, end: usize, places: &[usize]) -> Option<Run> {        let reader: &Reader = self.reader;        let knobs = &reader.knobs;        let kept: Vec<&Vec<Point>> = self.kept[start..end].iter().map(|at| &self.strokes[*at]).collect();        let boxes: Vec<_> = kept.iter().map(|stroke| marks::bounds(stroke)).collect();        let mut linked = vec![false; boxes.len()];        linked[0] = true;        let mut reached = vec![0usize];        while let Some(at) = reached.pop() {            for other in 0..boxes.len() {                if !linked[other] && marks::across(&boxes[at], &boxes[other], knobs) {                    linked[other] = true;                    reached.push(other);                }            }        }        if linked.iter().any(|held| !held) {            return None;        }        let joined: Vec<Point> = kept.iter().flat_map(|stroke| stroke.iter().copied()).collect();        let held = marks::bounds(&joined);        if held.width.max(held.height) < knobs.smallest {            return None;        }        let group: Vec<Vec<Point>> = places.iter().map(|at| self.strokes[*at].clone()).collect();        let letters = reader.scores(&group, self.admits, self.model);        // A run holding a stroke that alone edits the letters (a backspace        // across "co") is a letter only when the model is sure of it.        let mut editing = false;        for at in start..end {            if self.letter(at, at + 1).is_some_and(|run| reader.edits(&run)) {                editing = true;                break;            }        }        let best = letters.first()?;        if best.score < if editing { knobs.letter_confidence } else { knobs.letter_floor } {            return None;        }        let doubted = best.score < knobs.letter_confidence;        let (doubt_cut, best_score) = (knobs.doubt_cut, best.score);        for cut in (start + 1)..end {            let Some(left) = self.letter(start, cut) else { continue };            let Some(right) = self.letter(cut, end) else { continue };            let sureness = reader.sureness(&left) * reader.sureness(&right);            if (reader.edits(&left) || reader.edits(&right)) && sureness > best_score {                return None;            }            if doubted && sureness >= doubt_cut {                return None;            }        }        Some(Run { strokes: places.to_vec(), reading: reader.reading(&letters[0]), runners: letters.iter().skip(1).take(3).cloned().collect() })    }}#[cfg(test)]#[path = "reader_tests.rs"]mod reader_tests;