From 7d041f2a3df258c0c466f3c3b2b0d7dffd9eea7d Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Wed, 28 Oct 2026 12:29:08 +0300 Subject: [PATCH] Import and review: what the opponent preparation needs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Name queries: the full stop of an initial separates words too, so "Carlsen, M." and "Вафин Р." find the full names (suggestions and filters alike). - `Database::main_line(index, plies)`: the first moves of a game's main line; a ChessBase game is decoded without its tree (microseconds), a PGN game is parsed. `Database::player_name(id)` for both kinds. - `position::theory_end`: the linear/doubling/halving search for where a line leaves a database, taken out of the reference panel's `book_end` so another caller can use it; the panel calls it. - game-review opens `judge` and `terminal_eval`; `Judgement` is serde. Co-Authored-By: Claude Fable 5.1 --- apps/desktop/src/reference.rs | 66 ++----------- crates/chess-import/src/chessbase/base.rs | 44 ++++++++- crates/chess-import/src/lib.rs | 44 +++++++++ crates/chess-import/src/position.rs | 109 ++++++++++++++++++++++ crates/game-review/src/lib.rs | 7 +- crates/game-review/src/report.rs | 8 +- 6 files changed, 212 insertions(+), 66 deletions(-) diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs index fd57fda..a2fa374 100644 --- a/apps/desktop/src/reference.rs +++ b/apps/desktop/src/reference.rs @@ -15,7 +15,9 @@ use std::sync::atomic::AtomicBool; use chess_core::{Game, NodeId}; use chess_import::Database; -use chess_import::position::{Match, MoveStat, PositionOutcome, PositionQuery, Tally}; +use chess_import::position::{ + Match, MoveStat, PositionOutcome, PositionQuery, Tally, theory_end, +}; use egui::{RichText, Sense, Ui, vec2}; use egui_extras::{Column, TableBuilder}; use shakmaty::uci::UciMove; @@ -147,8 +149,6 @@ const MOVES_WITH_GAMES: usize = 12; const PGN_TREE_MATCHES: usize = 5_000; /// Results bigger than the cache kept apart (the start position, 1.e4). const BIG_KEPT: usize = 2; -/// Plies of the theory checked one by one before it is found by halving. -const BOOK_LINEAR: usize = 12; /// Sort of the games table. #[derive(Clone, Copy, Default, PartialEq, Eq)] @@ -654,62 +654,12 @@ fn book_end( ) }; // The first plies one by one (the opening index answers them at once), then by - // doubling and halving: a position is nearly always in the database when a later - // one of the same line is. - // `from`: the plies before it are known already (the game grew past a theory that - // reached its end). - let total = nodes.len(); - let from = from.min(total); - let linear_end = if from > 0 { - from - } else { - total.min(BOOK_LINEAR) - }; - let mut last_known: Option = from.checked_sub(1); - let mut first_unknown = None; - for ply in from..linear_end { - if known(ply)? { - last_known = Some(ply); - } else { - first_unknown = Some(ply); - break; - } - } - if first_unknown.is_none() && total > linear_end { - let mut lo = linear_end - 1; - let mut step = 2; - let mut hi = total; - while lo + step < total { - if known(lo + step)? { - lo += step; - step *= 2; - } else { - hi = lo + step; - break; - } - } - if hi == total && lo + 1 < total { - // Past the last doubling: the end of the line itself. - if known(total - 1)? { - lo = total - 1; - } - } - while hi - lo > 1 { - let mid = (lo + hi) / 2; - if known(mid)? { - lo = mid; - } else { - hi = mid; - } - } - last_known = Some(lo); - if hi < total { - first_unknown = Some(hi); - } - } + // doubling and halving (`theory_end`). `from`: the plies before it are known + // already (the game grew past a theory that reached its end). + let end = theory_end(nodes.len(), from, known)?; Some(BookEnd { - last: last_known.map(|p| nodes[p]), - to_the_end: total > 1 && first_unknown.is_none(), + last: end.last_known.map(|p| nodes[p]), + to_the_end: nodes.len() > 1 && end.first_unknown.is_none(), copies, }) } diff --git a/crates/chess-import/src/chessbase/base.rs b/crates/chess-import/src/chessbase/base.rs index 24a9bd8..3c68a8e 100644 --- a/crates/chess-import/src/chessbase/base.rs +++ b/crates/chess-import/src/chessbase/base.rs @@ -214,10 +214,11 @@ pub fn fold(s: &str) -> String { out } -/// Folded words of a search query; commas separate words too ("Carlsen, M"). +/// Folded words of a search query; commas separate words too ("Carlsen, M"), and so +/// does the full stop of an initial ("Carlsen, M." finds "Carlsen, Magnus"). pub(crate) fn words(query: &str) -> Vec { fold(query) - .split(|c: char| c.is_whitespace() || c == ',') + .split(|c: char| c.is_whitespace() || c == ',' || c == '.') .filter(|w| !w.is_empty()) .map(str::to_owned) .collect() @@ -954,6 +955,39 @@ impl Base { } } + /// The first `max_plies` moves of the main line of game `index`, decoded without + /// building the move tree (see [`moves::main_line`]). `None` for a text, a deleted + /// record or unreadable moves. + pub fn main_line(&self, index: usize, max_plies: usize) -> Option { + let Record::Game(h) = self.header(index)? else { + return None; + }; + let bytes = self.read_moves(h.moves_offset)?; + let walk = |fast: bool| -> Result { + let mut line = crate::MainLine::default(); + let mut first = true; + moves::main_line(&bytes, 0, fast, |pos, step| { + if std::mem::take(&mut first) { + line.standard_start = crate::position::same_position(pos, &shakmaty::Chess::default()); + if !line.standard_start { + return false; + } + } + match step { + moves::Step::Move(m) => { + line.moves.push(*m); + line.moves.len() < max_plies + } + // A null move or the end: the opening line stops here. + moves::Step::Null | moves::Step::End => false, + } + })?; + Ok(line) + }; + // The fast decoder trusts the data: a damaged game is read again carefully. + walk(true).or_else(|_| walk(false)).ok() + } + /// The `.cbg` record at `offset` (its size is in bytes 1-3). fn read_moves(&self, offset: u32) -> Option> { let mut f = self.cbg.lock().ok()?; @@ -1407,6 +1441,9 @@ mod tests { assert_eq!(fold("Hübner, Robert"), "hubner, robert"); assert_eq!(fold("Łukasz Ćwikła"), "lukasz cwikla"); assert_eq!(words(" Carlsen,Magnus "), vec!["carlsen", "magnus"]); + // An initial with its full stop finds the full name. + assert_eq!(words("Вафин, Р."), vec!["вафин", "р"]); + assert_eq!(words("J.R. Capablanca"), vec!["j", "r", "capablanca"]); let names = Names::new(vec![ "Carlsen, Magnus".into(), "Carlsen, Henrik".into(), @@ -1416,6 +1453,9 @@ mod tests { assert_eq!(names.matching("hubner"), vec![false, false, true]); let (list, total) = names.suggest("carl", 1); assert_eq!((list.len(), total), (1, 2)); + let (list, total) = names.suggest("Carlsen, M.", 5); + assert_eq!((list.len(), total), (1, 1)); + assert_eq!(list[0].name, "Carlsen, Magnus"); } #[test] diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index c3a20aa..efa18b4 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -171,6 +171,14 @@ impl std::ops::Deref for PgnDb { } } +/// The beginning of a game's main line (see [`Database::main_line`]). +#[derive(Clone, Debug, Default)] +pub struct MainLine { + /// The game starts from the usual position; otherwise `moves` is empty. + pub standard_start: bool, + pub moves: Vec, +} + /// An opened database. pub enum Database { Pgn(PgnDb), @@ -213,6 +221,34 @@ impl Database { } } + /// The first `max_plies` moves of the main line of record `index`, for passes + /// over the openings of many games: a ChessBase game is decoded without its tree + /// (microseconds), a PGN game is parsed. The line stops at a teaching null move. + /// `None` for a text, a deleted record or unreadable moves. + pub fn main_line(&self, index: usize, max_plies: usize) -> Option { + match self { + Database::Pgn(db) => { + let parsed = db.load_game(index)?; + let game = &parsed.game; + let mut line = MainLine { + standard_start: game.start().is_standard(), + moves: Vec::new(), + }; + if !line.standard_start { + return Some(line); + } + for id in game.mainline().into_iter().take(max_plies) { + match game.game_move(id).map(|m| &m.kind) { + Some(chess_core::MoveKind::Normal(m)) => line.moves.push(*m), + _ => break, + } + } + Some(line) + } + Database::ChessBase(b) => b.main_line(index, max_plies), + } + } + /// Bytes that identify record `index` (its content for PGN, its `.cbh` record for /// ChessBase), for remembering viewed games. pub fn identity(&self, index: usize) -> &[u8] { @@ -337,6 +373,14 @@ impl Database { } } + /// The name of player `id` (from a suggestion), as the game list shows it. + pub fn player_name(&self, id: u32) -> &str { + match self { + Database::Pgn(db) => db.catalog().player_name(id), + Database::ChessBase(b) => b.player_name(id), + } + } + pub fn suggest_events( &self, query: &str, diff --git a/crates/chess-import/src/position.rs b/crates/chess-import/src/position.rs index 1c15a15..1f0352a 100644 --- a/crates/chess-import/src/position.rs +++ b/crates/chess-import/src/position.rs @@ -281,6 +281,85 @@ pub fn uci(m: &Move) -> UciMove { m.to_uci(shakmaty::CastlingMode::Standard) } +/// Plies of a line checked one by one by [`theory_end`] before the end of the theory is +/// found by halving (an opening index answers the first plies at once). +pub const THEORY_LINEAR: usize = 12; + +/// Where a line of `total` positions leaves the "theory" of a database, as +/// [`theory_end`] finds it: indices into the line. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TheoryEnd { + /// The last position still known to the database. + pub last_known: Option, + /// The first position it does not know; `None` when the whole line is known. + pub first_unknown: Option, +} + +/// Finds how far a line of `total` positions is known to a database, with as few +/// searches as possible: `known(i)` says whether position `i` is (`None`: cancelled, +/// the search stops too). A position is nearly always known when a later one of the +/// same line is, so the first plies are checked one by one, then the end is found by +/// doubling and halving. `from`: the positions before it are known already (a game +/// that grew past a theory reaching its end checks only the new moves). +pub fn theory_end( + total: usize, + from: usize, + mut known: impl FnMut(usize) -> Option, +) -> Option { + let from = from.min(total); + let linear_end = if from > 0 { + from + } else { + total.min(THEORY_LINEAR) + }; + let mut last_known: Option = from.checked_sub(1); + let mut first_unknown = None; + for ply in from..linear_end { + if known(ply)? { + last_known = Some(ply); + } else { + first_unknown = Some(ply); + break; + } + } + if first_unknown.is_none() && total > linear_end { + let mut lo = linear_end - 1; + let mut step = 2; + let mut hi = total; + while lo + step < total { + if known(lo + step)? { + lo += step; + step *= 2; + } else { + hi = lo + step; + break; + } + } + if hi == total && lo + 1 < total { + // Past the last doubling: the end of the line itself. + if known(total - 1)? { + lo = total - 1; + } + } + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if known(mid)? { + lo = mid; + } else { + hi = mid; + } + } + last_known = Some(lo); + if hi < total { + first_unknown = Some(hi); + } + } + Some(TheoryEnd { + last_known, + first_unknown, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -304,6 +383,36 @@ mod tests { assert!(!same_position(&a, &play(&["d4", "d5"]))); } + #[test] + fn theory_end_finds_the_boundary_with_few_searches() { + for total in [1usize, 5, 12, 13, 20, 40, 100] { + for boundary in 0..=total { + // Positions before `boundary` are known. + let mut asked = 0; + let end = theory_end(total, 0, |i| { + asked += 1; + Some(i < boundary) + }) + .expect("not cancelled"); + let expect_last = boundary.checked_sub(1); + let expect_first = (boundary < total).then_some(boundary); + assert_eq!( + (end.last_known, end.first_unknown), + (expect_last, expect_first), + "total {total}, boundary {boundary}" + ); + assert!(asked <= THEORY_LINEAR + 2 * 8, "{asked} searches"); + } + } + // Cancelled: no answer. + assert_eq!(theory_end(10, 0, |_| None), None); + // Continuing from a known prefix. + let end = theory_end(10, 4, |i| Some(i < 7)).expect("end"); + assert_eq!(end, TheoryEnd { last_known: Some(6), first_unknown: Some(7) }); + let end = theory_end(10, 4, |_| Some(true)).expect("end"); + assert_eq!(end, TheoryEnd { last_known: Some(9), first_unknown: None }); + } + #[test] fn collector_counts_and_names_moves() { let pos = Chess::default(); diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs index 9af96f9..ad7a293 100644 --- a/crates/game-review/src/lib.rs +++ b/crates/game-review/src/lib.rs @@ -23,7 +23,7 @@ pub mod report; pub use features::{MoveFeatures, Rules}; pub use job::{JobEvent, JobFailure, JobSettings, Target, run}; -pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats}; +pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats, judge}; /// Engine result for one position of the main line. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -560,8 +560,9 @@ fn position_key(game: &Game, id: NodeId) -> Option<(String, EnginePosition)> { Some((key, pos)) } -/// Evaluation of a position without legal moves. -fn terminal_eval(pos: &Chess) -> Option { +/// Evaluation of a position without legal moves (checkmate or stalemate): no engine +/// is needed for it. +pub fn terminal_eval(pos: &Chess) -> Option { if pos.is_checkmate() { Some(Eval::Mate { white: pos.turn() == Color::Black, diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs index e797627..8471297 100644 --- a/crates/game-review/src/report.rs +++ b/crates/game-review/src/report.rs @@ -114,7 +114,7 @@ fn move_accuracy(before: f64, after: f64) -> f64 { (raw + 1.0).clamp(0.0, 100.0) } -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum Judgement { Inaccuracy, Mistake, @@ -203,8 +203,10 @@ fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules) -> Option .then_some(Judgement::Great) } -/// Judgement of a move from the evaluations before and after it. -fn judge(before: Eval, after: Eval, mover: Color) -> Option { +/// Judgement of a move from the evaluations before and after it: an inaccuracy, a +/// mistake or a blunder by the drop of the mover's winning chances (never for the +/// engine's own best move: the caller rules that out). +pub fn judge(before: Eval, after: Eval, mover: Color) -> Option { use Judgement::*; let (mb, ma) = (before.mate_for(mover), after.mate_for(mover)); if ma == Some(false) && mb != Some(false) {