Opponent prep: the prep crate (openings only)

A new crate shared by the apps, no UI: what a player of a database plays
in the opening and where in the opening he goes wrong.

- Player: candidates from the database's names (initials with a full
  stop work), one or several ids, White, Black or both.
- Lines: the first N plies (default 20) of the main lines, position keys,
  UCI/SAN, result from the player's side, full date, opponent's Elo;
  games from a set-up position are skipped.
- Repertoire tree per colour by move order with position keys:
  games (+/=/-), last date, average opponent Elo, game list,
  transpositions marked.
- Opening names from lichess-org/chess-openings (CC0; revision and
  SHA-256 pinned, files in crates/prep/data, THIRD_PARTY_NOTICES): the
  deepest named position of a line, families and variations with their
  first moves, grouped by name.
- Book: a second database (or the same one without the player's games)
  says where each game left it (first position with fewer than T games,
  T = 5) and whose move it was.
- Engine: every distinct position of the lines once through
  game_review::run, judged with the game analysis rules for the player's
  moves only; errors by opening and the repeated ones (same position,
  same move in two or more games); evaluations cached per position across
  reports, the report cached by database, player and plies.
- examples/prep_report.rs prints it all for a database and a player.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-28 12:32:39 +03:00
parent 7d041f2a3d
commit d54f207889
17 changed files with 6524 additions and 0 deletions

102
crates/prep/src/book.rs Normal file
View file

@ -0,0 +1,102 @@
//! Where the player's games leave the book: a second database (a big one from the
//! shelf, or an opening database) is the book, and a game has left it at the first
//! position the book has fewer than a threshold of games for. Whose move led out —
//! the player's or the opponent's — says whether it is his own choice.
//!
//! The positions of a line are searched the way the reference panel finds the end
//! of the theory ([`theory_end`]): the first plies one by one (an opening index
//! answers them at once), then by doubling and halving. Counts are kept per
//! position within one pass: the player's games share their openings.
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use chess_core::shakmaty::uci::UciMove;
use chess_core::shakmaty::{Chess, Position};
use chess_import::Database;
use chess_import::position::{PositionQuery, theory_end};
use crate::games::{BookExit, GameInfo};
/// How the book is read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BookOptions {
/// A position with fewer games than this in the book is out of it.
pub threshold: u32,
/// The book is the database the report was built from: the player's own games
/// do not count.
pub same_database: bool,
}
impl Default for BookOptions {
fn default() -> Self {
BookOptions {
threshold: crate::DEFAULT_BOOK_THRESHOLD,
same_database: false,
}
}
}
/// Fills in [`GameInfo::book`] of every game; `progress` counts the games done.
/// Returns how many games left the book within their line. `None` when cancelled
/// (or when the book cannot be searched: a PGN book without memory for its table).
pub(crate) fn find_exits(
games: &mut [GameInfo],
book: &Database,
options: &BookOptions,
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<u32> {
let exclude: HashSet<u32> = if options.same_database {
games.iter().map(|g| g.index).collect()
} else {
HashSet::new()
};
let mut counts: HashMap<u64, u32> = HashMap::new();
let mut left = 0;
for game in games.iter_mut() {
if cancel.load(Ordering::Relaxed) {
return None;
}
progress.fetch_add(1, Ordering::Relaxed);
let mut pos = Chess::default();
let mut positions = vec![pos.clone()];
let mut moves = Vec::with_capacity(game.ucis.len());
for u in &game.ucis {
let Some(m) = u.parse::<UciMove>().ok().and_then(|u| u.to_move(&pos).ok()) else {
break;
};
pos.play_unchecked(m);
moves.push(m);
positions.push(pos.clone());
}
let keys = &game.keys;
let mut count_of = |i: usize| -> Option<u32> {
if let Some(c) = counts.get(&keys[i]) {
return Some(*c);
}
let q = PositionQuery::new(positions[i].clone(), Some(moves[..i].to_vec()));
let out = book.search_position(None, &q, &AtomicUsize::new(0), cancel)?;
let c = out
.matches
.iter()
.filter(|m| !exclude.contains(&m.index))
.count() as u32;
counts.insert(keys[i], c);
Some(c)
};
let end = theory_end(positions.len(), 0, |i| {
Some(count_of(i)? >= options.threshold)
})?;
game.book = end.first_unknown.map(|i| {
left += 1;
BookExit {
ply: i as u32,
// Position 0 is the start: a book without it is empty.
by_player: i > 0 && game.player_moves_at(i - 1),
count: counts.get(&game.keys[i]).copied().unwrap_or(0),
}
});
}
Some(left)
}