Import and review: what the opponent preparation needs

- 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 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-28 12:29:08 +03:00
parent 015fa0cfe3
commit 7d041f2a3d
6 changed files with 212 additions and 66 deletions

View file

@ -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<String> {
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<crate::MainLine> {
let Record::Game(h) = self.header(index)? else {
return None;
};
let bytes = self.read_moves(h.moves_offset)?;
let walk = |fast: bool| -> Result<crate::MainLine, moves::WalkError> {
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<Vec<u8>> {
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]

View file

@ -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<chess_core::shakmaty::Move>,
}
/// 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<MainLine> {
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,

View file

@ -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<usize>,
/// The first position it does not know; `None` when the whole line is known.
pub first_unknown: Option<usize>,
}
/// 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<bool>,
) -> Option<TheoryEnd> {
let from = from.min(total);
let linear_end = if from > 0 {
from
} else {
total.min(THEORY_LINEAR)
};
let mut last_known: Option<usize> = 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();