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)
}

391
crates/prep/src/errors.rs Normal file
View file

@ -0,0 +1,391 @@
//! Opening errors found by the engine: every distinct position of the first plies of
//! the player's games is evaluated once (the games repeat their openings, so about
//! half the positions are shared), and the player's moves are judged from the
//! evaluations before and after them with the rules of the game analysis. The same
//! error in several games — the same position and the same move — is what matters
//! most for preparation, so those are listed on their own.
//!
//! Evaluations are kept per position in a cache file shared by every report: another
//! player of the same database, or the same player later, is judged from the cache.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use chess_core::shakmaty::san::SanPlus;
use chess_core::shakmaty::uci::UciMove;
use chess_core::shakmaty::{Chess, Color, Position};
use game_review::{Eval, Judgement, PosEval};
use serde::{Deserialize, Serialize};
use crate::games::{GameInfo, Tally};
/// Nodes of an evaluation that needs no engine (checkmate, stalemate): better than any
/// search.
pub const EXACT: u64 = u64::MAX;
/// The engine's result for one position.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PositionEval {
/// Nodes of the search ([`EXACT`] for a position without legal moves).
pub nodes: u64,
pub eval: Eval,
/// The engine's line in UCI; the first move is its best move.
pub pv: Vec<String>,
pub depth: u32,
}
impl PositionEval {
pub fn from_engine(nodes: u64, e: &PosEval) -> PositionEval {
PositionEval {
nodes,
eval: e.eval,
pv: e.pv.iter().take(8).cloned().collect(),
depth: e.depth,
}
}
pub fn best(&self) -> Option<&str> {
self.pv.first().map(String::as_str)
}
}
/// How many inaccuracies, mistakes and blunders.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorCounts {
pub inaccuracies: u32,
pub mistakes: u32,
pub blunders: u32,
}
impl ErrorCounts {
pub fn add(&mut self, j: Judgement) {
match j {
Judgement::Inaccuracy => self.inaccuracies += 1,
Judgement::Mistake => self.mistakes += 1,
Judgement::Blunder => self.blunders += 1,
Judgement::Great | Judgement::Brilliant => {}
}
}
pub fn total(&self) -> u32 {
self.inaccuracies + self.mistakes + self.blunders
}
}
/// A move of the player judged an inaccuracy, a mistake or a blunder.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OpeningError {
/// Index into [`crate::PrepReport::games`].
pub game: u32,
/// The move's place in the line (0-based; see [`GameInfo::move_label`]).
pub ply: u32,
/// The position before the move.
pub key: u64,
pub uci: String,
pub san: String,
/// The engine's move instead.
pub best_uci: String,
pub best_san: String,
pub judgement: Judgement,
pub before: Eval,
pub after: Eval,
/// The game's opening ([`crate::PrepReport::openings`]).
pub opening: Option<usize>,
}
/// The same error in several games: the same position and the same move.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RepeatedError {
pub key: u64,
pub ply: u32,
pub uci: String,
pub san: String,
pub best_san: String,
pub judgement: Judgement,
/// The games (indices into [`crate::PrepReport::games`]), in order.
pub games: Vec<u32>,
/// How those games ended.
pub tally: Tally,
/// The opening of the first of them.
pub opening: Option<usize>,
}
impl RepeatedError {
pub fn times(&self) -> u32 {
self.games.len() as u32
}
}
/// Judges the player's moves in `games[g]` for `g` in `which` from `evals`: the
/// move is not the engine's best, and the evaluations before and after it say it
/// lost enough (the rules of the game analysis, [`game_review::judge`]).
pub fn judge_games(
games: &[GameInfo],
which: &[u32],
evals: &HashMap<u64, PositionEval>,
) -> Vec<OpeningError> {
let mut out = Vec::new();
for &g in which {
let game = &games[g as usize];
let mover = if game.white { Color::White } else { Color::Black };
let mut pos = Chess::default();
for (i, uci) in game.ucis.iter().enumerate() {
let Some(m) = uci.parse::<UciMove>().ok().and_then(|u| u.to_move(&pos).ok()) else {
break;
};
if game.player_moves_at(i)
&& let (Some(before), Some(after)) =
(evals.get(&game.keys[i]), evals.get(&game.keys[i + 1]))
&& let Some(best) = before.best()
&& best != uci
&& let Some(judgement) = game_review::judge(before.eval, after.eval, mover)
{
let best_san = best
.parse::<UciMove>()
.ok()
.and_then(|u| u.to_move(&pos).ok())
.map(|bm| SanPlus::from_move(pos.clone(), bm).to_string())
.unwrap_or_else(|| best.to_owned());
out.push(OpeningError {
game: g,
ply: i as u32,
key: game.keys[i],
uci: uci.clone(),
san: game.sans.get(i).cloned().unwrap_or_default(),
best_uci: best.to_owned(),
best_san,
judgement,
before: before.eval,
after: after.eval,
opening: game.opening,
});
}
pos.play_unchecked(m);
}
}
out
}
/// The errors made in two or more games (same position, same move), most repeated
/// first, then the worst first.
pub fn repeated(errors: &[OpeningError], games: &[GameInfo]) -> Vec<RepeatedError> {
let mut groups: HashMap<(u64, &str), Vec<&OpeningError>> = HashMap::new();
for e in errors {
groups.entry((e.key, e.uci.as_str())).or_default().push(e);
}
let mut out: Vec<RepeatedError> = groups
.into_values()
.filter(|g| g.len() >= 2)
.map(|g| {
let first = g[0];
let mut tally = Tally::default();
let mut list: Vec<u32> = g.iter().map(|e| e.game).collect();
list.sort_unstable();
list.dedup();
for &game in &list {
tally.add(games[game as usize].outcome);
}
RepeatedError {
key: first.key,
ply: first.ply,
uci: first.uci.clone(),
san: first.san.clone(),
best_san: first.best_san.clone(),
judgement: first.judgement,
games: list,
tally,
opening: first.opening,
}
})
.filter(|r| r.games.len() >= 2)
.collect();
out.sort_by(|a, b| {
b.games
.len()
.cmp(&a.games.len())
.then(b.judgement.cmp(&a.judgement))
.then(a.ply.cmp(&b.ply))
.then(a.games.cmp(&b.games))
});
out
}
// ----- the cache of evaluations by position --------------------------------------
const CACHE_FILE: &str = "positions.json";
const CACHE_VERSION: u32 = 1;
/// Positions kept at most (about 100 bytes each on disk).
const CACHE_LIMIT: usize = 1_000_000;
#[derive(Serialize, Deserialize)]
struct CacheFile {
version: u32,
positions: Vec<(u64, PositionEval)>,
}
/// Engine evaluations by position, shared by every report: the best quality (most
/// nodes) seen for each position is kept.
#[derive(Default)]
pub struct PositionCache {
entries: HashMap<u64, PositionEval>,
dirty: bool,
}
impl PositionCache {
fn path(dir: &Path) -> PathBuf {
dir.join(CACHE_FILE)
}
/// The cache in `dir` (empty when there is none, or it cannot be read).
pub fn load(dir: &Path) -> PositionCache {
let entries = std::fs::read(Self::path(dir))
.ok()
.and_then(|bytes| serde_json::from_slice::<CacheFile>(&bytes).ok())
.filter(|f| f.version == CACHE_VERSION)
.map(|f| f.positions.into_iter().collect())
.unwrap_or_default();
PositionCache {
entries,
dirty: false,
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn get(&self, key: u64) -> Option<&PositionEval> {
self.entries.get(&key)
}
/// Keeps `eval` unless the cache has one with more nodes; says whether it was kept.
pub fn insert(&mut self, key: u64, eval: PositionEval) -> bool {
if self.entries.get(&key).is_some_and(|e| e.nodes >= eval.nodes) {
return false;
}
self.entries.insert(key, eval);
self.dirty = true;
true
}
/// Something was added since the load or the last save.
pub fn dirty(&self) -> bool {
self.dirty
}
/// Writes the cache to `dir` (through a temporary file, so a crash never leaves
/// half a file); nothing when nothing changed.
pub fn save(&mut self, dir: &Path) -> std::io::Result<()> {
if !self.dirty {
return Ok(());
}
let mut positions: Vec<(u64, PositionEval)> =
self.entries.iter().map(|(k, v)| (*k, v.clone())).collect();
if positions.len() > CACHE_LIMIT {
// Over the limit the searches with the fewest nodes go first.
positions.sort_by_key(|a| std::cmp::Reverse(a.1.nodes));
positions.truncate(CACHE_LIMIT);
}
let file = CacheFile {
version: CACHE_VERSION,
positions,
};
let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?;
write_atomic(&Self::path(dir), &bytes)?;
self.dirty = false;
Ok(())
}
}
/// Writes through a temporary file and a rename.
pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("json.tmp");
std::fs::write(&tmp, bytes)?;
std::fs::rename(&tmp, path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tree::tests::game;
fn eval(nodes: u64, cp: i32, best: &str) -> PositionEval {
PositionEval {
nodes,
eval: Eval::Cp(cp),
pv: vec![best.to_owned()],
depth: 10,
}
}
#[test]
fn the_same_error_in_two_games_is_repeated() {
// Three games of the player with White: 1.e4 e5 2.Qh5?! twice, 2.Nf3 once.
let games = vec![
game(0, true, &["e4", "e5", "Qh5", "Nc6"], "1-0", "", 0),
game(1, true, &["e4", "e5", "Qh5", "Nf6"], "0-1", "", 0),
game(2, true, &["e4", "e5", "Nf3", "Nc6"], "1/2-1/2", "", 0),
game(3, false, &["e4", "e5", "Qh5", "Nc6"], "0-1", "", 0),
];
let mut evals = HashMap::new();
evals.insert(games[0].keys[0], eval(1000, 30, "e2e4"));
evals.insert(games[0].keys[1], eval(1000, 30, "e7e5"));
// 2.Qh5 drops from +0.3 to −1.0: a mistake; 2.Nf3 is the engine's move.
evals.insert(games[0].keys[2], eval(1000, 30, "g1f3"));
evals.insert(games[0].keys[3], eval(1000, -100, "b8c6"));
evals.insert(games[1].keys[3], eval(1000, -100, "g8f6"));
evals.insert(games[2].keys[3], eval(1000, 30, "b8c6"));
let errors = judge_games(&games, &[0, 1, 2], &evals);
assert_eq!(errors.len(), 2);
assert_eq!(errors[0].game, 0);
assert_eq!(errors[0].ply, 2);
assert_eq!(errors[0].san, "Qh5");
assert_eq!(errors[0].best_san, "Nf3");
assert_eq!(errors[0].judgement, Judgement::Mistake);
assert_eq!(errors[1].game, 1);
let rep = repeated(&errors, &games);
assert_eq!(rep.len(), 1);
assert_eq!(rep[0].games, vec![0, 1]);
assert_eq!(rep[0].times(), 2);
assert_eq!((rep[0].tally.wins, rep[0].tally.losses), (1, 1));
// Black's moves in game 3 are the player's: 2.Qh5 is the opponent's there.
let evals_black = evals.clone();
assert!(judge_games(&games, &[3], &evals_black).is_empty());
// A position without an evaluation after the move is not judged (the two
// games share the position after 2.Qh5).
let mut partial = evals.clone();
partial.remove(&games[1].keys[3]);
assert!(judge_games(&games, &[0, 1, 2], &partial).is_empty());
// One game less: nothing repeats.
assert!(repeated(&judge_games(&games, &[0, 2], &evals), &games).is_empty());
}
#[test]
fn the_position_cache_keeps_the_best_quality_and_survives_a_save() {
let dir = std::env::temp_dir().join(format!("prep-cache-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut c = PositionCache::load(&dir);
assert!(c.is_empty());
assert!(c.insert(1, eval(1000, 10, "e2e4")));
assert!(!c.insert(1, eval(250, 20, "d2d4")), "fewer nodes: not kept");
assert!(c.insert(1, eval(3000, 30, "c2c4")));
assert!(c.insert(2, eval(EXACT, 0, "")));
assert_eq!(c.get(1).map(|e| e.nodes), Some(3000));
assert!(c.dirty());
c.save(&dir).expect("saved");
assert!(!c.dirty());
let d = PositionCache::load(&dir);
assert_eq!(d.len(), 2);
assert_eq!(d.get(1), c.get(1));
assert_eq!(d.get(2).map(|e| e.nodes), Some(EXACT));
assert_eq!(d.get(3), None);
let _ = std::fs::remove_dir_all(&dir);
}
}

227
crates/prep/src/games.rs Normal file
View file

@ -0,0 +1,227 @@
//! The player's games as the report sees them: the first plies of the main line with
//! the keys of its positions, the result from the player's side, the date and the
//! opponent's rating. Games from a set-up position are left out.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use chess_core::shakmaty::san::SanPlus;
use chess_core::shakmaty::{Chess, Position};
use chess_import::Database;
use chess_import::pgn_catalog::date_number;
use chess_import::position::{key, uci};
use serde::{Deserialize, Serialize};
use crate::openings::{self, OpeningSet};
/// A game's result from the player's side.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Outcome {
Win,
Draw,
Loss,
Unknown,
}
impl Outcome {
/// From the result tag and the player's colour.
pub fn of(result: &str, white: bool) -> Outcome {
match (result.trim(), white) {
("1-0", true) | ("0-1", false) => Outcome::Win,
("1-0", false) | ("0-1", true) => Outcome::Loss,
("1/2-1/2" | "½-½", _) => Outcome::Draw,
_ => Outcome::Unknown,
}
}
}
/// Games and their results from the player's side.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tally {
pub games: u32,
pub wins: u32,
pub draws: u32,
pub losses: u32,
}
impl Tally {
pub fn add(&mut self, outcome: Outcome) {
self.games += 1;
match outcome {
Outcome::Win => self.wins += 1,
Outcome::Draw => self.draws += 1,
Outcome::Loss => self.losses += 1,
Outcome::Unknown => {}
}
}
/// Points per game, 0..1, over the games with a result.
pub fn score(&self) -> Option<f64> {
let decided = self.wins + self.draws + self.losses;
(decided > 0).then(|| (f64::from(self.wins) + 0.5 * f64::from(self.draws)) / f64::from(decided))
}
}
/// Where a game left the book (see [`crate::PrepReport::find_book_exits`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BookExit {
/// Moves played when the line reached its first position the book rarely has:
/// move `ply - 1` (0-based, [`GameInfo::ucis`]) led out of the book.
pub ply: u32,
/// That move was the player's.
pub by_player: bool,
/// Games of the book with the position (below the threshold).
pub count: u32,
}
/// One game of the player.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GameInfo {
/// Record index in the database.
pub index: u32,
/// The player had White.
pub white: bool,
pub opponent: String,
/// 0: unknown.
pub opponent_elo: u16,
/// PGN form ("2026.10.18", "1997.05.??"), empty when unknown.
pub date: String,
pub outcome: Outcome,
/// The first moves of the main line (at most the report's plies), UCI and SAN.
pub ucis: Vec<String>,
pub sans: Vec<String>,
/// Keys of the positions before each move and after the last: `ucis.len() + 1`.
pub keys: Vec<u64>,
/// The deepest named position of the line ([`crate::PrepReport::openings`]).
pub opening: Option<usize>,
/// Plies of the line up to the named position (`keys[named]` is it).
pub named: Option<u32>,
/// Filled in by [`crate::PrepReport::find_book_exits`]; `None` while the line
/// is within the book, or before the book was looked at.
pub book: Option<BookExit>,
}
impl GameInfo {
/// `yyyymmdd` for ordering (0: no date).
pub fn date_number(&self) -> u32 {
date_number(&self.date)
}
/// Move `ply` (0-based) was the player's.
pub fn player_moves_at(&self, ply: usize) -> bool {
ply.is_multiple_of(2) == self.white
}
/// "12. Nf3" / "12... Nf6" for move `ply` (0-based).
pub fn move_label(&self, ply: usize) -> String {
let san = self.sans.get(ply).map_or("", String::as_str);
move_label(ply, san)
}
}
/// "12. Nf3" / "12... Nf6" for move `ply` (0-based from the usual start position).
pub fn move_label(ply: usize, san: &str) -> String {
let number = ply / 2 + 1;
if ply.is_multiple_of(2) {
format!("{number}. {san}")
} else {
format!("{number}... {san}")
}
}
/// What a pass over the games produced.
pub struct Collected {
pub games: Vec<GameInfo>,
pub openings: OpeningSet,
/// Games left out: from a set-up position, or unreadable.
pub skipped: u32,
/// Final positions of lines that end in checkmate or stalemate: (key, position).
pub terminal: Vec<(u64, Chess)>,
}
/// Reads the first `plies` of each of `found` (record, the player had White);
/// `progress` counts the games done. `None` when cancelled.
pub fn collect(
db: &Database,
found: &[(u32, bool)],
plies: usize,
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<Collected> {
let mut out = Collected {
games: Vec::with_capacity(found.len()),
openings: OpeningSet::default(),
skipped: 0,
terminal: Vec::new(),
};
for &(index, white) in found {
if cancel.load(Ordering::Relaxed) {
return None;
}
progress.fetch_add(1, Ordering::Relaxed);
let Some(line) = db.main_line(index as usize, plies) else {
out.skipped += 1;
continue;
};
if !line.standard_start {
out.skipped += 1;
continue;
}
let row = db.row(index as usize);
let mut pos = Chess::default();
let mut keys = Vec::with_capacity(line.moves.len() + 1);
let mut ucis = Vec::with_capacity(line.moves.len());
let mut sans = Vec::with_capacity(line.moves.len());
keys.push(key(&pos));
for m in &line.moves {
ucis.push(uci(m).to_string());
sans.push(SanPlus::from_move_and_play_unchecked(&mut pos, *m).to_string());
keys.push(key(&pos));
}
if pos.is_checkmate() || pos.is_stalemate() {
out.terminal.push((key(&pos), pos));
}
let (opening, named) = match openings::deepest(&keys) {
Some((at, id)) => (Some(out.openings.intern(id)), Some(at as u32)),
None => (None, None),
};
out.games.push(GameInfo {
index,
white,
opponent: if white { row.black } else { row.white },
opponent_elo: if white { row.black_elo } else { row.white_elo },
date: row.date,
outcome: Outcome::of(row.result, white),
ucis,
sans,
keys,
opening,
named,
book: None,
});
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn outcomes_and_tallies() {
assert_eq!(Outcome::of("1-0", true), Outcome::Win);
assert_eq!(Outcome::of("1-0", false), Outcome::Loss);
assert_eq!(Outcome::of("0-1", false), Outcome::Win);
assert_eq!(Outcome::of("1/2-1/2", true), Outcome::Draw);
assert_eq!(Outcome::of("*", true), Outcome::Unknown);
let mut t = Tally::default();
for o in [Outcome::Win, Outcome::Win, Outcome::Draw, Outcome::Loss, Outcome::Unknown] {
t.add(o);
}
assert_eq!((t.games, t.wins, t.draws, t.losses), (5, 2, 1, 1));
assert_eq!(t.score(), Some(0.625));
assert_eq!(Tally::default().score(), None);
assert_eq!(move_label(0, "e4"), "1. e4");
assert_eq!(move_label(1, "c5"), "1... c5");
assert_eq!(move_label(22, "Nf3"), "12. Nf3");
}
}

943
crates/prep/src/lib.rs Normal file
View file

@ -0,0 +1,943 @@
//! Preparing against an opponent, shared by the desktop and the Android app: what a
//! player of a database plays in the opening and where in the opening he goes wrong.
//!
//! The [`PrepReport`] is built in a moment from the player's games ([`build`]): his
//! main lines up to a number of plies, the repertoire tree of each colour with
//! transpositions marked, the openings named from the Lichess `chess-openings` table
//! (family → variation → games), and, with a second database as the book, where each
//! game left it. The engine step is apart and optional: every distinct position of
//! the lines is evaluated once ([`PrepReport::targets`], run by
//! [`game_review::run`], results taken in by [`PrepReport::apply`]), the player's
//! moves are judged with the rules of the game analysis, and the errors are listed by
//! opening and, when the same error was made in several games, as repeated. The
//! report is cached by database, player and plies; evaluations by position, across
//! reports ([`PositionCache`]).
//!
//! Nothing here touches the database or the games; no user interface.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::time::SystemTime;
use chess_import::Database;
use game_review::{JobEvent, JobFailure, JobSettings, Target};
use serde::{Deserialize, Serialize};
use uci::EnginePosition;
mod book;
mod errors;
mod games;
pub mod openings;
mod players;
mod tree;
pub use book::BookOptions;
pub use chess_import::chessbase::base::Side;
pub use errors::{
EXACT, ErrorCounts, OpeningError, PositionCache, PositionEval, RepeatedError,
};
pub use game_review::{Eval, Judgement};
pub use games::{BookExit, GameInfo, Outcome, Tally, move_label};
pub use openings::Opening;
pub use players::{Candidate, Player, candidates, games_of};
pub use tree::{Node, Tree};
/// Plies of the opening a report looks at unless told otherwise.
pub const DEFAULT_PLIES: usize = 20;
/// A position with fewer games than this in the book is out of it.
pub const DEFAULT_BOOK_THRESHOLD: u32 = 5;
/// What a report covers.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Options {
/// Plies of each game's main line.
pub plies: usize,
/// The player's colour(s).
pub side: Side,
}
impl Default for Options {
fn default() -> Self {
Options {
plies: DEFAULT_PLIES,
side: Side::Any,
}
}
}
/// An opening as played by the player: the games with the same name.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Variation {
/// Index into [`PrepReport::openings`]; `None`: no named position in the line.
pub opening: Option<usize>,
pub tally: Tally,
/// Indices into [`PrepReport::games`], in order.
pub games: Vec<u32>,
pub errors: ErrorCounts,
/// Indices into [`ColorReport::errors`].
pub error_list: Vec<u32>,
}
/// The openings with the same family name ("Sicilian Defense"), most played first.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Family {
/// Empty for games without a named position.
pub name: String,
pub tally: Tally,
/// Most played first.
pub variations: Vec<Variation>,
pub errors: ErrorCounts,
}
/// The report for one colour of the player.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ColorReport {
pub white: bool,
/// Indices into [`PrepReport::games`], in record order.
pub games: Vec<u32>,
pub tree: Tree,
pub families: Vec<Family>,
/// The player's opening errors, by game and ply (after the engine step).
pub errors: Vec<OpeningError>,
/// The errors made in two or more games.
pub repeated: Vec<RepeatedError>,
pub counts: ErrorCounts,
}
impl ColorReport {
/// Games that left the book, by whose move: (the player's, the opponent's);
/// the rest stayed in the book for the whole line (or no book was looked at).
pub fn book_exits(&self, games: &[GameInfo]) -> (u32, u32) {
let mut out = (0, 0);
for &g in &self.games {
match games[g as usize].book {
Some(b) if b.by_player => out.0 += 1,
Some(_) => out.1 += 1,
None => {}
}
}
out
}
}
/// The engine the evaluations came from.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct EngineInfo {
pub name: String,
/// Nodes per position asked for (an evaluation from the cache may have more).
pub nodes: u64,
}
/// The book the exits were found against.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct BookInfo {
pub fingerprint: u64,
pub threshold: u32,
/// Games that left the book within their line.
pub left: u32,
}
const REPORT_VERSION: u32 = 1;
/// Everything the preparation knows about the player.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrepReport {
pub version: u32,
/// Of the database ([`fingerprint`]).
pub fingerprint: u64,
pub player: Player,
/// The player's names in the database.
pub names: Vec<String>,
pub plies: usize,
pub side_white: bool,
pub side_black: bool,
pub games: Vec<GameInfo>,
/// Games left out: from a set-up position, or unreadable.
pub skipped: u32,
/// The openings the games and trees refer to.
pub openings: Vec<Opening>,
pub white: ColorReport,
pub black: ColorReport,
pub book: Option<BookInfo>,
pub engine: Option<EngineInfo>,
/// Engine evaluations by position key.
pub evals: HashMap<u64, PositionEval>,
}
/// Identity of a database for the report cache: the content of a PGN file, the
/// path, size and time of a ChessBase database.
pub fn fingerprint(db: &Database) -> u64 {
match db {
Database::Pgn(p) => {
let f = p.fingerprint();
fnv(f.content_hash.to_le_bytes().iter().chain(f.len.to_le_bytes().iter()))
}
Database::ChessBase(b) => {
let meta = std::fs::metadata(b.path()).ok();
let len = meta.as_ref().map_or(0, std::fs::Metadata::len);
let modified = meta
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_secs());
fnv(b.path()
.to_string_lossy()
.bytes()
.chain(len.to_le_bytes())
.chain(modified.to_le_bytes())
.collect::<Vec<u8>>()
.iter())
}
}
}
fn fnv<'a>(bytes: impl Iterator<Item = &'a u8>) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in bytes {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
/// Builds the report of `player` in `db`: his games ([`games_of`]), their first
/// plies, the trees, the names and the opening tables. `progress` counts the games
/// read. `None` when cancelled. Milliseconds for hundreds of games.
pub fn build(
db: &Database,
player: &Player,
options: &Options,
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<PrepReport> {
let found = games_of(db, player, options.side, cancel)?;
let collected = games::collect(db, &found, options.plies, progress, cancel)?;
let mut openings = collected.openings;
let games = collected.games;
let mut evals = HashMap::new();
for (key, pos) in &collected.terminal {
if let Some(eval) = game_review::terminal_eval(pos) {
evals.insert(
*key,
PositionEval {
nodes: EXACT,
eval,
pv: Vec::new(),
depth: 0,
},
);
}
}
let color = |white: bool, openings: &mut openings::OpeningSet| -> ColorReport {
let which: Vec<u32> = games
.iter()
.enumerate()
.filter(|(_, g)| g.white == white)
.map(|(i, _)| i as u32)
.collect();
let tree = Tree::build(&games, &which, options.plies, openings);
let families = families(&games, &which, &openings.list);
ColorReport {
white,
games: which,
tree,
families,
errors: Vec::new(),
repeated: Vec::new(),
counts: ErrorCounts::default(),
}
};
let white = color(true, &mut openings);
let black = color(false, &mut openings);
let mut report = PrepReport {
version: REPORT_VERSION,
fingerprint: fingerprint(db),
player: player.clone(),
names: player.names(db),
plies: options.plies,
side_white: options.side != Side::Black,
side_black: options.side != Side::White,
games,
skipped: collected.skipped,
openings: openings.list,
white,
black,
book: None,
engine: None,
evals,
};
report.refresh();
Some(report)
}
/// Groups `games[g]` for `g` in `which` by opening name: families, most played
/// first, each with its variations, most played first. A name the table gives to
/// several positions ("Sicilian Defense: Closed" after 2.Nc3 and after 2...e6) is one
/// variation, shown with its shortest line.
fn families(games: &[GameInfo], which: &[u32], openings: &[Opening]) -> Vec<Family> {
let mut out: Vec<Family> = Vec::new();
let mut family_of: HashMap<String, usize> = HashMap::new();
let mut variation_of: HashMap<(usize, String), usize> = HashMap::new();
for &g in which {
let game = &games[g as usize];
let opening = game.opening.map(|o| &openings[o]);
let name = opening.map(|o| o.family().to_owned()).unwrap_or_default();
let f = *family_of.entry(name.clone()).or_insert_with(|| {
out.push(Family {
name,
..Family::default()
});
out.len() - 1
});
let full = opening.map(|o| o.name.clone()).unwrap_or_default();
let v = *variation_of.entry((f, full)).or_insert_with(|| {
out[f].variations.push(Variation {
opening: game.opening,
..Variation::default()
});
out[f].variations.len() - 1
});
out[f].tally.add(game.outcome);
let var = &mut out[f].variations[v];
if let (Some(o), Some(shown)) = (game.opening, var.opening)
&& openings[o].plies < openings[shown].plies
{
var.opening = Some(o);
}
var.tally.add(game.outcome);
var.games.push(g);
}
let variation_name = |v: &Variation| -> String {
v.opening
.map(|o| openings[o].name.clone())
.unwrap_or_default()
};
for f in &mut out {
f.variations.sort_by(|a, b| {
b.tally
.games
.cmp(&a.tally.games)
.then_with(|| variation_name(a).cmp(&variation_name(b)))
});
}
out.sort_by(|a, b| {
b.tally
.games
.cmp(&a.tally.games)
.then_with(|| a.name.cmp(&b.name))
});
out
}
impl PrepReport {
/// The colour(s) the report was built for.
pub fn side(&self) -> Side {
match (self.side_white, self.side_black) {
(true, false) => Side::White,
(false, true) => Side::Black,
_ => Side::Any,
}
}
pub fn color(&self, white: bool) -> &ColorReport {
if white { &self.white } else { &self.black }
}
// ----- the book -------------------------------------------------------------
/// Finds where each game left `book` (see [`book`]); `progress` counts the games
/// done. `None` when cancelled or the book cannot be searched; the report is
/// then left as it was.
pub fn find_book_exits(
&mut self,
book: &Database,
options: &BookOptions,
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<()> {
let mut games = self.games.clone();
let left = book::find_exits(&mut games, book, options, progress, cancel)?;
self.games = games;
self.book = Some(BookInfo {
fingerprint: fingerprint(book),
threshold: options.threshold,
left,
});
Some(())
}
// ----- the engine -----------------------------------------------------------
/// Every distinct position of the lines (the one after the last move included),
/// first met first; those without legal moves left out.
fn positions(&self) -> Vec<(u64, &GameInfo, usize)> {
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for g in &self.games {
for (i, &k) in g.keys.iter().enumerate() {
if self.evals.get(&k).is_some_and(|e| e.nodes == EXACT) {
continue;
}
if seen.insert(k) {
out.push((k, g, i));
}
}
}
out
}
/// Distinct positions an engine run looks at.
pub fn distinct_positions(&self) -> usize {
self.positions().len()
}
/// Positions without an evaluation of at least `nodes`.
pub fn missing(&self, nodes: u64) -> usize {
self.positions()
.iter()
.filter(|(k, _, _)| !self.evals.get(k).is_some_and(|e| e.nodes >= nodes))
.count()
}
/// Takes from `cache` the evaluations of at least `nodes` the report lacks;
/// returns how many.
pub fn take_cached(&mut self, cache: &PositionCache, nodes: u64) -> usize {
let keys: Vec<u64> = self.positions().iter().map(|(k, _, _)| *k).collect();
let mut taken = 0;
for k in keys {
if self.evals.get(&k).is_some_and(|e| e.nodes >= nodes) {
continue;
}
if let Some(e) = cache.get(k).filter(|e| e.nodes >= nodes) {
self.evals.insert(k, e.clone());
taken += 1;
}
}
if taken > 0 {
self.refresh();
}
taken
}
/// The positions still to evaluate at `nodes`, for [`game_review::run`] (one
/// search each, no second search for !! and !). Their keys are the position keys
/// in hexadecimal, as [`PrepReport::apply`] reads them.
pub fn targets(&self, nodes: u64) -> Vec<Target> {
self.positions()
.into_iter()
.filter(|(k, _, _)| !self.evals.get(k).is_some_and(|e| e.nodes >= nodes))
.map(|(k, g, i)| Target {
key: format!("{k:016x}"),
pos: EnginePosition::startpos(g.ucis[..i].iter().cloned()),
turn: if i.is_multiple_of(2) {
uci::Side::White
} else {
uci::Side::Black
},
played: None,
others: Vec::new(),
known: None,
})
.collect()
}
/// Takes in what the engine job reported for a run at `nodes`; the evaluation
/// it carried (to cache), if any. The errors are re-judged on the next
/// [`PrepReport::refresh`].
pub fn apply(&mut self, event: &JobEvent, nodes: u64) -> Option<(u64, PositionEval)> {
match event {
JobEvent::Engine(name) => {
self.engine = Some(EngineInfo {
name: name.clone(),
nodes,
});
None
}
JobEvent::Eval { key, eval, .. } => {
let k = u64::from_str_radix(key, 16).ok()?;
let e = PositionEval::from_engine(nodes, eval);
self.engine.get_or_insert_with(|| EngineInfo {
name: String::new(),
nodes,
});
self.evals.insert(k, e.clone());
Some((k, e))
}
}
}
/// Re-judges the player's moves from the evaluations: the errors by colour,
/// opening and repetition. Cheap (the lines of the games).
pub fn refresh(&mut self) {
let PrepReport {
games,
evals,
white,
black,
..
} = self;
for cr in [white, black] {
let errors = errors::judge_games(games, &cr.games, evals);
cr.repeated = errors::repeated(&errors, games);
cr.counts = ErrorCounts::default();
let mut at: HashMap<u32, (usize, usize)> = HashMap::new();
for (f, fam) in cr.families.iter_mut().enumerate() {
fam.errors = ErrorCounts::default();
for (v, var) in fam.variations.iter_mut().enumerate() {
var.errors = ErrorCounts::default();
var.error_list.clear();
for &g in &var.games {
at.insert(g, (f, v));
}
}
}
for (i, e) in errors.iter().enumerate() {
cr.counts.add(e.judgement);
if let Some(&(f, v)) = at.get(&e.game) {
let fam = &mut cr.families[f];
fam.errors.add(e.judgement);
fam.variations[v].errors.add(e.judgement);
fam.variations[v].error_list.push(i as u32);
}
}
cr.errors = errors;
}
}
// ----- the report cache -----------------------------------------------------
/// The cache file of a report in `dir`.
pub fn cache_path(dir: &Path, fingerprint: u64, player: &Player, options: &Options) -> PathBuf {
let mut bytes = fingerprint.to_le_bytes().to_vec();
for id in &player.ids {
bytes.extend(id.to_le_bytes());
}
bytes.extend((options.plies as u64).to_le_bytes());
bytes.push(match options.side {
Side::Any => 0,
Side::White => 1,
Side::Black => 2,
});
dir.join(format!("{:016x}.json", fnv(bytes.iter())))
}
/// The report cached in `dir` for this database, player and options, if any.
pub fn load(dir: &Path, db: &Database, player: &Player, options: &Options) -> Option<PrepReport> {
let fp = fingerprint(db);
let bytes = std::fs::read(Self::cache_path(dir, fp, player, options)).ok()?;
let report: PrepReport = serde_json::from_slice(&bytes).ok()?;
(report.version == REPORT_VERSION
&& report.fingerprint == fp
&& report.player == *player
&& report.plies == options.plies
&& report.side() == options.side)
.then_some(report)
}
/// Keeps the report in `dir` (atomically).
pub fn save(&self, dir: &Path) -> std::io::Result<()> {
let options = Options {
plies: self.plies,
side: self.side(),
};
let path = Self::cache_path(dir, self.fingerprint, &self.player, &options);
let bytes = serde_json::to_vec(self).map_err(std::io::Error::other)?;
errors::write_atomic(&path, &bytes)
}
}
/// Progress of [`analyse`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Progress {
/// Positions evaluated in this run.
pub done: usize,
/// Positions the run has to evaluate.
pub total: usize,
/// The engine's speed in the last search (0 if it did not say).
pub nps: u64,
}
/// Runs the engine over the positions `report` lacks at `settings.nodes` (the cache
/// is consulted first and fed as results come; `cache_dir` saves it every few
/// hundred positions and at the end), updating the report as results come in.
/// Returns when done, or soon after `cancel` is set (what was evaluated stays).
pub fn analyse(
report: &mut PrepReport,
cache: &mut PositionCache,
cache_dir: Option<&Path>,
config: uci::EngineConfig,
settings: &JobSettings,
cancel: &AtomicBool,
on_progress: &mut dyn FnMut(Progress),
) -> Result<(), JobFailure> {
let nodes = settings.nodes;
report.take_cached(cache, nodes);
let targets = report.targets(nodes);
let total = targets.len();
let mut progress = Progress {
done: 0,
total,
nps: 0,
};
on_progress(progress);
if total == 0 {
return Ok(());
}
let mut since_save = 0;
let result = game_review::run(config, settings, targets, cancel, &mut |event| {
if let JobEvent::Eval { nps, .. } = &event {
progress.done += 1;
progress.nps = *nps;
}
if let Some((key, eval)) = report.apply(&event, nodes) {
cache.insert(key, eval);
since_save += 1;
if since_save >= 200
&& let Some(dir) = cache_dir
{
let _ = cache.save(dir);
since_save = 0;
}
}
if matches!(event, JobEvent::Eval { .. }) {
on_progress(progress);
}
});
report.refresh();
if let Some(dir) = cache_dir {
let _ = cache.save(dir);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use chess_core::PgnDatabase;
use chess_import::PgnDb;
fn database(pgn: &str) -> Database {
let db = PgnDatabase::from_bytes(
pgn.as_bytes().to_vec(),
None,
&mut |_| {},
&AtomicBool::new(false),
)
.expect("pgn");
Database::Pgn(PgnDb::new(db))
}
const PGN: &str = "\
[White \"Вафин Радель\"]
[Black \"Иванов Иван\"]
[Date \"2026.01.10\"]
[BlackElo \"1500\"]
[Result \"1-0\"]
1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 1-0
[White \"Петров Пётр\"]
[Black \"Вафин Радель\"]
[Date \"2026.02.11\"]
[WhiteElo \"1700\"]
[Result \"0-1\"]
1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 0-1
[White \"Вафин Радель\"]
[Black \"Вафина Раяна\"]
[Date \"2026.03.12\"]
[Result \"1/2-1/2\"]
1. e4 c5 2. Nf3 Nc6 3. Bb5 e6 1/2-1/2
[White \"Вафин Р.\"]
[Black \"Сидоров\"]
[Date \"2026.04.01\"]
[Result \"0-1\"]
1. d4 d5 2. c4 0-1
[White \"Вафин Радель\"]
[Black \"Set Up\"]
[FEN \"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1\"]
[SetUp \"1\"]
[Result \"*\"]
1... e5 *
";
#[test]
fn candidates_games_and_openings_of_a_player() {
let db = database(PGN);
// Every name with both words ("Вафина Раяна" has them too): the user picks.
let (list, total) = candidates(&db, "Вафин Р.", 10);
assert_eq!(total, 3, "{list:?}");
assert_eq!(list[0].name, "Вафин Радель");
assert_eq!(list[0].games, 4);
assert_eq!(list[1].name, "Вафин Р.");
assert_eq!(list[2].name, "Вафина Раяна");
let (one, _) = candidates(&db, "Радель", 10);
assert_eq!(one.len(), 1);
// Two spellings merged.
let player = Player::new([list[0].id, list[1].id]);
let never = AtomicBool::new(false);
let found = games_of(&db, &player, Side::Any, &never).expect("games");
assert_eq!(found, vec![(0, true), (1, false), (2, true), (3, true), (4, true)]);
assert_eq!(
games_of(&db, &player, Side::Black, &never).expect("games"),
vec![(1, false)]
);
let report = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
.expect("report");
assert_eq!(report.games.len(), 4, "the set-up game is left out");
assert_eq!(report.skipped, 1);
assert_eq!(report.names, vec!["Вафин Радель", "Вафин Р."]);
let g = &report.games[0];
assert_eq!((g.index, g.white, g.opponent.as_str(), g.opponent_elo), (0, true, "Иванов Иван", 1500));
assert_eq!(g.date, "2026.01.10");
assert_eq!(g.outcome, Outcome::Win);
assert_eq!(g.sans, vec!["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O", "Bg7"]);
assert_eq!(g.keys.len(), 9);
let o = &report.openings[g.opening.expect("named")];
assert!(o.name.starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), "{}", o.name);
assert_eq!(g.named, Some(6));
assert_eq!(report.games[1].outcome, Outcome::Win);
assert_eq!(report.games[1].opponent_elo, 1700);
// White: two Rossolimo games and one Queen's Gambit; the family first.
let w = &report.white;
assert_eq!(w.games, vec![0, 2, 3]);
assert_eq!(w.families.len(), 2);
assert_eq!(w.families[0].name, "Sicilian Defense");
assert_eq!(w.families[0].tally.games, 3 - 1);
assert_eq!(w.families[0].variations.len(), 2, "3...g6 and 3...e6 are named apart");
assert_eq!(w.families[1].name, "Queen's Gambit");
assert_eq!(w.tree.nodes[0].tally.games, 3);
assert_eq!(w.tree.nodes[0].last_date, "2026.04.01");
assert_eq!(w.tree.nodes[0].average_elo(), Some(1500));
let b = &report.black;
assert_eq!(b.games, vec![1]);
assert_eq!(b.families[0].name, "Sicilian Defense");
let name = &report.openings[b.families[0].variations[0].opening.unwrap()].name;
assert!(name.contains("Najdorf"), "{name}");
assert!(report.evals.is_empty() && report.engine.is_none());
assert_eq!(report.side(), Side::Any);
// Only White.
let white_only = build(
&db,
&player,
&Options {
plies: 4,
side: Side::White,
},
&AtomicUsize::new(0),
&never,
)
.expect("report");
assert_eq!(white_only.games.len(), 3);
assert!(white_only.black.games.is_empty());
assert!(white_only.games.iter().all(|g| g.ucis.len() <= 4));
assert_eq!(white_only.side(), Side::White);
// Cancelled.
let cancelled = AtomicBool::new(true);
assert!(build(&db, &player, &Options::default(), &AtomicUsize::new(0), &cancelled).is_none());
}
#[test]
fn one_name_for_several_positions_is_one_variation() {
// "Sicilian Defense: Closed" is the table's name after 2.Nc3 and after 2...e6.
let db = database(
"[White \"A\"]\n[Black \"B\"]\n[Result \"1-0\"]\n\n1. e4 c5 2. Nc3 e6 1-0\n\n\
[White \"A\"]\n[Black \"C\"]\n[Result \"0-1\"]\n\n1. e4 c5 2. Nc3 0-1\n\n",
);
let player = Player::new([candidates(&db, "A", 1).0[0].id]);
let report = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &AtomicBool::new(false))
.expect("report");
let fam = &report.white.families[0];
assert_eq!(fam.name, "Sicilian Defense");
assert_eq!(fam.variations.len(), 1);
let v = &fam.variations[0];
assert_eq!(v.games, vec![0, 1]);
let o = &report.openings[v.opening.unwrap()];
assert_eq!((o.name.as_str(), o.line.as_str()), ("Sicilian Defense: Closed", "1. e4 c5 2. Nc3"));
}
#[test]
fn the_book_says_where_a_game_left_it() {
let db = database(PGN);
let (list, _) = candidates(&db, "Вафин Р.", 2);
let player = Player::new([list[0].id, list[1].id]);
let never = AtomicBool::new(false);
let mut report = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
.expect("report");
// The database itself as the book, threshold 2: 1.e4 c5 2.Nf3 is in three
// games; game 0 (3...g6) and game 2 (3...e6) part after 3.Bb5, which is in
// both. `ply` counts the moves to the first rare position.
let options = BookOptions {
threshold: 2,
same_database: false,
};
report
.find_book_exits(&db, &options, &AtomicUsize::new(0), &never)
.expect("book");
let exits: Vec<Option<BookExit>> = report.games.iter().map(|g| g.book).collect();
assert_eq!(
exits[0],
Some(BookExit {
ply: 6,
by_player: false,
count: 1
})
);
assert_eq!(exits[1].map(|b| (b.ply, b.by_player)), Some((4, true)), "2...d6 is his");
assert_eq!(exits[2].map(|b| (b.ply, b.by_player)), Some((6, false)));
assert_eq!(exits[3].map(|b| (b.ply, b.by_player)), Some((1, true)), "1.d4 is his own");
assert_eq!(report.book.as_ref().map(|b| (b.threshold, b.left)), Some((2, 4)));
assert_eq!(report.white.book_exits(&report.games), (1, 2));
// The player's own games excluded: everything is out of the book at once.
let own = BookOptions {
threshold: 1,
same_database: true,
};
report
.find_book_exits(&db, &own, &AtomicUsize::new(0), &never)
.expect("book");
assert_eq!(report.games[0].book.map(|b| b.ply), Some(0));
assert_eq!(report.book.as_ref().map(|b| b.left), Some(4));
}
#[test]
fn evaluations_give_the_errors_by_opening_and_the_report_is_cached() {
let db = database(PGN);
let (list, _) = candidates(&db, "Вафин Радель", 1);
let player = Player::new([list[0].id]);
let never = AtomicBool::new(false);
let mut report = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
.expect("report");
let total = report.distinct_positions();
// 9 + 11 + 7 positions; the start and 1.e4 c5 2.Nf3 shared by three games,
// 2...Nc6 3.Bb5 by two.
assert_eq!(total, 27 - 10);
let targets = report.targets(1000);
assert_eq!(targets.len(), total);
assert_eq!(targets[0].key, format!("{:016x}", report.games[0].keys[0]));
assert!(targets[0].pos.moves.is_empty());
assert_eq!(targets[3].pos.moves, vec!["e2e4", "c7c5", "g1f3"]);
assert_eq!(targets[3].turn, uci::Side::Black);
assert!(targets.iter().all(|t| t.played.is_none() && t.known.is_none()));
// The engine says: every move fine but 3.Bb5, a blunder (+0.3 → −1.5).
let mut cache = PositionCache::default();
for t in &targets {
let key = u64::from_str_radix(&t.key, 16).unwrap();
let after_bb5 = report.games[0].keys[5];
let eval = if key == after_bb5 { Eval::Cp(-150) } else { Eval::Cp(30) };
let before_bb5 = report.games[0].keys[4];
let pv = if key == before_bb5 { vec!["d2d4".to_owned()] } else { Vec::new() };
let event = JobEvent::Eval {
key: t.key.clone(),
eval: game_review::PosEval {
eval,
pv,
depth: 12,
second: None,
},
nps: 0,
};
let (k, e) = report.apply(&event, 1000).expect("an evaluation");
cache.insert(k, e);
}
assert_eq!(report.missing(1000), 0);
assert_eq!(report.missing(2000), total);
report.refresh();
assert_eq!(report.engine.as_ref().map(|e| e.nodes), Some(1000));
let w = &report.white;
assert_eq!(w.counts.blunders, 2);
assert_eq!(w.errors.len(), 2);
assert_eq!(w.errors[0].san, "Bb5");
assert_eq!(w.errors[0].best_san, "d4");
assert_eq!(w.errors[0].ply, 4);
assert_eq!(report.games[w.errors[0].game as usize].move_label(4), "3. Bb5");
assert_eq!(w.families[0].errors.blunders, 2);
assert_eq!(w.families[0].variations[0].errors.blunders, 1);
assert_eq!(w.families[0].variations[0].error_list.len(), 1);
assert_eq!(w.families.len(), 1);
assert_eq!(w.repeated.len(), 1);
assert_eq!(w.repeated[0].games, vec![0, 2]);
assert_eq!(w.repeated[0].tally.draws, 1);
assert!(report.black.errors.is_empty());
// Cached: the report by database, player and options; the evaluations by
// position, for anyone.
let dir = std::env::temp_dir().join(format!("prep-report-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert!(PrepReport::load(&dir, &db, &player, &Options::default()).is_none());
report.save(&dir).expect("saved");
let again = PrepReport::load(&dir, &db, &player, &Options::default()).expect("cached");
assert_eq!(again.white.errors, report.white.errors);
assert_eq!(again.evals.len(), report.evals.len());
assert!(PrepReport::load(&dir, &db, &player, &Options { plies: 10, side: Side::Any }).is_none());
let other = Player::new([list[0].id + 1]);
assert!(PrepReport::load(&dir, &db, &other, &Options::default()).is_none());
let mut fresh = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
.expect("report");
assert_eq!(fresh.take_cached(&cache, 1000), total);
assert_eq!(fresh.white.repeated, report.white.repeated);
assert_eq!(fresh.take_cached(&cache, 1000), 0);
let _ = std::fs::remove_dir_all(&dir);
}
/// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`).
#[test]
fn the_engine_run_fills_the_report_and_the_cache() {
let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci");
assert!(
std::path::Path::new(fake).exists(),
"build the fake engine first: cargo build -p uci --bin fake_uci"
);
let db = database(PGN);
let (list, _) = candidates(&db, "Вафин Радель", 1);
let player = Player::new([list[0].id]);
let never = AtomicBool::new(false);
let mut report = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
.expect("report");
let total = report.distinct_positions();
let settings = JobSettings {
threads: 1,
hash_mb: 16,
nodes: 1000,
eval_file: None,
};
let mut cache = PositionCache::default();
let mut last = Progress::default();
analyse(
&mut report,
&mut cache,
None,
uci::EngineConfig::new(fake),
&settings,
&never,
&mut |p| last = p,
)
.expect("the job runs");
assert_eq!((last.done, last.total), (total, total));
assert_eq!(report.missing(1000), 0);
assert_eq!(cache.len(), total);
assert_eq!(report.engine.as_ref().map(|e| e.name.as_str()), Some("Fake UCI"));
// A second run has nothing to do; a cancelled one ends at once.
let mut again = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
.expect("report");
let cancelled = AtomicBool::new(true);
let mut calls = 0;
analyse(
&mut again,
&mut cache,
None,
uci::EngineConfig::new(fake),
&settings,
&cancelled,
&mut |_| calls += 1,
)
.expect("nothing to do");
assert_eq!(again.missing(1000), 0, "all from the cache");
assert_eq!(calls, 1);
}
}

213
crates/prep/src/openings.rs Normal file
View file

@ -0,0 +1,213 @@
//! Opening names from the Lichess `chess-openings` table: a position's ECO code and
//! name, looked up by the position itself, so a line reaching a named position by
//! another move order gets its name too. A line is named by its deepest named
//! position, as the table's README says ("go back through the moves until a named
//! position is found").
//!
//! The five TSV files in `data/` (`eco`, `name`, `pgn`) were downloaded unmodified from
//! <https://github.com/lichess-org/chess-openings> at revision
//! `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27), on 2026-10-28; the data set is
//! in the public domain (CC0 1.0). Their SHA-256 sums are in `THIRD_PARTY_NOTICES.md`.
//! The table is parsed on first use (3 865 lines, a fraction of a second).
use std::collections::HashMap;
use std::sync::OnceLock;
use chess_core::shakmaty::san::SanPlus;
use chess_core::shakmaty::{Chess, Position};
use chess_import::position::key;
use serde::{Deserialize, Serialize};
const FILES: [&str; 5] = [
include_str!("../data/a.tsv"),
include_str!("../data/b.tsv"),
include_str!("../data/c.tsv"),
include_str!("../data/d.tsv"),
include_str!("../data/e.tsv"),
];
/// A named opening position of the table.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Opening {
/// "B30".
pub eco: String,
/// "Sicilian Defense: Nyezhmetdinov-Rossolimo Attack".
pub name: String,
/// The table's moves to the position, in SAN ("1. e4 c5 2. Nf3 Nc6 3. Bb5").
pub line: String,
/// Half-moves of `line`.
pub plies: u8,
}
impl Opening {
/// The part of the name before the colon ("Sicilian Defense").
pub fn family(&self) -> &str {
self.name.split(':').next().unwrap_or(&self.name).trim()
}
/// The part after the colon ("Nyezhmetdinov-Rossolimo Attack"), if any.
pub fn variation(&self) -> Option<&str> {
self.name.split_once(':').map(|(_, v)| v.trim())
}
}
struct Table {
entries: Vec<Opening>,
/// Position key → entry. A position reached by two lines of the table keeps the
/// first (the files are in ECO order).
by_key: HashMap<u64, usize>,
}
fn table() -> &'static Table {
static TABLE: OnceLock<Table> = OnceLock::new();
TABLE.get_or_init(|| {
let mut t = Table {
entries: Vec::with_capacity(4000),
by_key: HashMap::with_capacity(4000),
};
for text in FILES {
for line in text.lines().skip(1) {
let mut cols = line.split('\t');
let (Some(eco), Some(name), Some(pgn)) = (cols.next(), cols.next(), cols.next())
else {
continue;
};
let Some((pos, plies)) = play(pgn) else {
continue;
};
let k = key(&pos);
if t.by_key.contains_key(&k) {
continue;
}
t.by_key.insert(k, t.entries.len());
t.entries.push(Opening {
eco: eco.to_owned(),
name: name.to_owned(),
line: pgn.to_owned(),
plies,
});
}
}
t
})
}
/// Plays a table line ("1. e4 c5 2. Nf3"); `None` if a move is not legal.
fn play(pgn: &str) -> Option<(Chess, u8)> {
let mut pos = Chess::default();
let mut plies = 0u8;
for tok in pgn.split_whitespace() {
if tok.ends_with('.') {
continue;
}
let m = tok.parse::<SanPlus>().ok()?.san.to_move(&pos).ok()?;
pos.play_unchecked(m);
plies = plies.checked_add(1)?;
}
Some((pos, plies))
}
/// Number of named positions.
pub fn count() -> usize {
table().entries.len()
}
/// The entry of a named position (by its [`key`]).
pub fn by_position(k: u64) -> Option<usize> {
table().by_key.get(&k).copied()
}
/// Entry `id` (from [`by_position`] or [`deepest`]).
pub fn get(id: usize) -> &'static Opening {
&table().entries[id]
}
/// The deepest named position among `keys` (the positions of a line, in order): its
/// index in `keys` and its entry.
pub fn deepest(keys: &[u64]) -> Option<(usize, usize)> {
keys.iter()
.enumerate()
.rev()
.find_map(|(i, k)| by_position(*k).map(|id| (i, id)))
}
/// The openings a report refers to, each once, in the order they were first met.
#[derive(Default)]
pub struct OpeningSet {
pub list: Vec<Opening>,
by_table: HashMap<usize, usize>,
}
impl OpeningSet {
/// The place of table entry `id` in [`OpeningSet::list`].
pub fn intern(&mut self, id: usize) -> usize {
if let Some(&i) = self.by_table.get(&id) {
return i;
}
self.list.push(get(id).clone());
self.by_table.insert(id, self.list.len() - 1);
self.list.len() - 1
}
}
#[cfg(test)]
mod tests {
use super::*;
use chess_core::shakmaty::san::San;
fn keys(moves: &[&str]) -> Vec<u64> {
let mut pos = Chess::default();
let mut out = vec![key(&pos)];
for s in moves {
let m = s.parse::<San>().unwrap().to_move(&pos).unwrap();
pos.play_unchecked(m);
out.push(key(&pos));
}
out
}
#[test]
fn the_table_loads() {
// 3 865 lines; a few positions are reached by two lines of the table.
assert!(count() > 3800, "{}", count());
let start = by_position(key(&Chess::default()));
assert!(start.is_none(), "the start position has no name");
}
#[test]
fn the_deepest_named_position_names_the_line_whatever_the_move_order() {
// 1.e4 c5 2.Nf3 Nc6 3.Bb5: the Rossolimo; 3...g6 is named too, 4.O-O is not.
let k = keys(&["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O"]);
let (at, id) = deepest(&k).expect("named");
let o = get(id);
assert_eq!(o.eco, "B31");
assert!(o.name.starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), "{}", o.name);
assert_eq!(at, 6, "the position after 3...g6");
assert_eq!(o.family(), "Sicilian Defense");
assert!(o.variation().is_some_and(|v| v.starts_with("Nyezhmetdinov")));
assert_eq!(o.plies, 6);
assert_eq!(o.line, "1. e4 c5 2. Nf3 Nc6 3. Bb5 g6");
// A transposition: 1.Nf3 d5 2.d4 reaches the table's 1.d4 d5 2.Nf3.
let a = deepest(&keys(&["Nf3", "d5", "d4"])).expect("named");
let b = deepest(&keys(&["d4", "d5", "Nf3"])).expect("named");
assert_eq!(a.1, b.1);
assert_eq!(get(a.1).line, "1. d4 d5 2. Nf3");
// A family without a variation.
let o = get(deepest(&keys(&["e4", "c5"])).expect("named").1);
assert_eq!(o.name, "Sicilian Defense");
assert_eq!(o.variation(), None);
// Nothing before the first move.
assert_eq!(deepest(&keys(&[])), None);
}
#[test]
fn a_set_keeps_each_opening_once() {
let mut set = OpeningSet::default();
let id = deepest(&keys(&["e4", "c5"])).unwrap().1;
let other = deepest(&keys(&["d4"])).unwrap().1;
assert_eq!(set.intern(id), 0);
assert_eq!(set.intern(other), 1);
assert_eq!(set.intern(id), 0);
assert_eq!(set.list.len(), 2);
}
}

View file

@ -0,0 +1,92 @@
//! The player: picked from the names of the database (never free text, so that
//! "Вафин" offers "Вафин Радель · 271" and "Вафина Раяна · 10" and the user chooses),
//! as one or several name ids when the database spells the same person in several
//! ways ("Kasparov, G." and "Kasparov, Garry"), and the player's games by colour.
use std::sync::atomic::{AtomicBool, AtomicUsize};
use chess_import::Database;
use chess_import::chessbase::base::{Filter, NameFilter, Side, SortKey};
use serde::{Deserialize, Serialize};
/// A name of the database that matches a query, with its number of games.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Candidate {
pub id: u32,
pub name: String,
pub games: u32,
}
/// Up to `limit` names containing every word of `query` (an initial with its full
/// stop finds the full name), names starting with the first word first, then by
/// number of games; and the number of all matches.
pub fn candidates(db: &Database, query: &str, limit: usize) -> (Vec<Candidate>, usize) {
let (list, total) = db.suggest_players(query, limit);
let list = list
.into_iter()
.map(|s| Candidate {
id: s.id,
name: s.name,
games: s.games,
})
.collect();
(list, total)
}
/// The player of a report: one or more name ids of the database.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Player {
pub ids: Vec<u32>,
}
impl Player {
pub fn new(ids: impl IntoIterator<Item = u32>) -> Player {
let mut ids: Vec<u32> = ids.into_iter().collect();
ids.sort_unstable();
ids.dedup();
Player { ids }
}
/// The names behind the ids, as the game list shows them.
pub fn names(&self, db: &Database) -> Vec<String> {
self.ids
.iter()
.map(|&id| db.player_name(id).to_owned())
.collect()
}
}
/// The player's games for `side`: (record index, the player had White), in record
/// order. `None` when cancelled.
pub fn games_of(
db: &Database,
player: &Player,
side: Side,
cancel: &AtomicBool,
) -> Option<Vec<(u32, bool)>> {
let mut out = Vec::new();
for &id in &player.ids {
for (s, white) in [(Side::White, true), (Side::Black, false)] {
if side != Side::Any && side != s {
continue;
}
let filter = Filter {
player: NameFilter {
text: String::new(),
exact: Some(id),
},
side: s,
games_only: true,
..Filter::default()
};
let found = db.query(&filter, SortKey::Number, true, &AtomicUsize::new(0), cancel)?;
out.extend(found.into_iter().map(|i| (i, white)));
}
}
// The same record with the same colour twice: two ids of the player on one side
// cannot happen, but two ids on both sides of one game can (a game against
// oneself in a spelling-merged list): it is kept once per colour.
out.sort_unstable();
out.dedup();
Some(out)
}

266
crates/prep/src/tree.rs Normal file
View file

@ -0,0 +1,266 @@
//! The repertoire tree of one colour: the player's games laid over each other by
//! move order (it reads as a repertoire: 1.e4 c5 2.Nf3 …), every node carrying the
//! key of its position, so that two nodes reached by different move orders are seen
//! to be the same position (a transposition) and get the same opening name.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::games::{GameInfo, Tally};
use crate::openings::{self, OpeningSet};
/// A position of the tree: the move that led to it from its parent, and the games
/// that went through it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
pub key: u64,
/// Half-moves from the start (0: the root).
pub ply: u8,
/// The move from the parent (empty for the root).
pub uci: String,
pub san: String,
pub parent: Option<u32>,
/// Most played first.
pub children: Vec<u32>,
pub tally: Tally,
/// The latest date among the games (PGN form; empty when none has one).
pub last_date: String,
/// Sum and number of the known opponent ratings, for the average.
pub elo_sum: u64,
pub elo_count: u32,
/// Games through the node: indices into [`crate::PrepReport::games`], in order.
pub games: Vec<u32>,
/// The same position is reached elsewhere in the tree by another move order.
pub transposition: bool,
/// The deepest named position on the path to the node
/// ([`crate::PrepReport::openings`]); `named` when it is this one.
pub opening: Option<usize>,
pub named: bool,
}
impl Node {
pub fn average_elo(&self) -> Option<u32> {
(self.elo_count > 0).then(|| (self.elo_sum / u64::from(self.elo_count)) as u32)
}
}
/// The tree of one colour; `nodes[0]` is the root (the start position).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Tree {
pub nodes: Vec<Node>,
}
impl Tree {
/// Lays the lines of `games[g]` for `g` in `which` over each other, `plies` deep.
pub fn build(
games: &[GameInfo],
which: &[u32],
plies: usize,
openings: &mut OpeningSet,
) -> Tree {
let mut tree = Tree {
nodes: vec![Node {
key: games
.first()
.and_then(|g| g.keys.first().copied())
.unwrap_or_default(),
ply: 0,
uci: String::new(),
san: String::new(),
parent: None,
children: Vec::new(),
tally: Tally::default(),
last_date: String::new(),
elo_sum: 0,
elo_count: 0,
games: Vec::new(),
transposition: false,
opening: None,
named: false,
}],
};
for &g in which {
let game = &games[g as usize];
if let Some(&k) = game.keys.first() {
tree.nodes[0].key = k;
}
tree.count(0, g, game);
let mut at = 0usize;
for i in 0..game.ucis.len().min(plies) {
let next = match tree.nodes[at]
.children
.iter()
.find(|&&c| tree.nodes[c as usize].uci == game.ucis[i])
{
Some(&c) => c as usize,
None => {
let key = game.keys[i + 1];
let named = openings::by_position(key);
let opening = named
.map(|id| openings.intern(id))
.or(tree.nodes[at].opening);
tree.nodes.push(Node {
key,
ply: u8::try_from(i + 1).unwrap_or(u8::MAX),
uci: game.ucis[i].clone(),
san: game.sans[i].clone(),
parent: Some(at as u32),
children: Vec::new(),
tally: Tally::default(),
last_date: String::new(),
elo_sum: 0,
elo_count: 0,
games: Vec::new(),
transposition: false,
opening,
named: named.is_some(),
});
let c = tree.nodes.len() - 1;
tree.nodes[at].children.push(c as u32);
c
}
};
tree.count(next, g, game);
at = next;
}
}
// Most played first among the children.
let played: Vec<u32> = tree.nodes.iter().map(|n| n.tally.games).collect();
for n in &mut tree.nodes {
n.children
.sort_by(|a, b| played[*b as usize].cmp(&played[*a as usize]).then(a.cmp(b)));
}
// Transpositions: one key in several nodes.
let mut seen: HashMap<u64, u32> = HashMap::new();
for n in &tree.nodes {
*seen.entry(n.key).or_default() += 1;
}
for n in &mut tree.nodes {
n.transposition = seen.get(&n.key).is_some_and(|c| *c > 1);
}
tree
}
fn count(&mut self, node: usize, g: u32, game: &GameInfo) {
let n = &mut self.nodes[node];
n.tally.add(game.outcome);
n.games.push(g);
if game.opponent_elo > 0 {
n.elo_sum += u64::from(game.opponent_elo);
n.elo_count += 1;
}
if game.date_number() > chess_import::pgn_catalog::date_number(&n.last_date) {
n.last_date = game.date.clone();
}
}
/// The statistics of the position with `key` over all its move orders (the
/// sum of its nodes).
pub fn position_tally(&self, key: u64) -> Tally {
let mut t = Tally::default();
for n in self.nodes.iter().filter(|n| n.key == key) {
t.games += n.tally.games;
t.wins += n.tally.wins;
t.draws += n.tally.draws;
t.losses += n.tally.losses;
}
t
}
/// The path of moves to `node`, in SAN.
pub fn path(&self, node: usize) -> Vec<&str> {
let mut out = Vec::new();
let mut at = Some(node);
while let Some(i) = at {
let n = &self.nodes[i];
if n.parent.is_some() {
out.push(n.san.as_str());
}
at = n.parent.map(|p| p as usize);
}
out.reverse();
out
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::games::Outcome;
use chess_core::shakmaty::san::SanPlus;
use chess_core::shakmaty::Chess;
use chess_import::position::{key, uci};
pub(crate) fn game(index: u32, white: bool, moves: &[&str], result: &str, date: &str, elo: u16) -> GameInfo {
let mut pos = Chess::default();
let (mut ucis, mut sans, mut keys) = (Vec::new(), Vec::new(), vec![key(&pos)]);
for s in moves {
let m = s.parse::<SanPlus>().unwrap().san.to_move(&pos).unwrap();
ucis.push(uci(&m).to_string());
sans.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string());
keys.push(key(&pos));
}
GameInfo {
index,
white,
opponent: "Opp".into(),
opponent_elo: elo,
date: date.into(),
outcome: Outcome::of(result, white),
ucis,
sans,
keys,
opening: None,
named: None,
book: None,
}
}
#[test]
fn the_tree_counts_games_and_marks_transpositions() {
let games = vec![
game(0, true, &["d4", "d5", "Nf3", "Nf6"], "1-0", "2026.01.05", 1500),
game(1, true, &["Nf3", "d5", "d4", "Nf6"], "0-1", "2026.03.01", 0),
game(2, true, &["d4", "d5", "c4"], "1/2-1/2", "2025.12.31", 1700),
game(3, false, &["e4", "c5"], "0-1", "2026.02.02", 1600),
game(4, true, &["d4", "d5", "c4", "e6", "Nc3", "Nf6", "h3"], "1-0", "", 0),
];
let mut set = OpeningSet::default();
let tree = Tree::build(&games, &[0, 1, 2], 20, &mut set);
let root = &tree.nodes[0];
assert_eq!(root.tally.games, 3);
assert_eq!(root.last_date, "2026.03.01");
assert_eq!(root.average_elo(), Some(1600));
assert_eq!(root.games, vec![0, 1, 2]);
// 1.d4 (2 games) before 1.Nf3 (1 game).
let kids: Vec<&str> = root.children.iter().map(|&c| tree.nodes[c as usize].san.as_str()).collect();
assert_eq!(kids, vec!["d4", "Nf3"]);
// The position after 1.d4 d5 2.Nf3 / 1.Nf3 d5 2.d4 is in two nodes.
let shared: Vec<&Node> = tree.nodes.iter().filter(|n| n.transposition).collect();
let keys: Vec<u64> = shared.iter().map(|n| n.key).collect();
assert_eq!(shared.len(), 4, "{keys:?}");
let after_nf3 = tree.nodes.iter().find(|n| n.ply == 3 && n.san == "Nf3").unwrap();
let after_d4 = tree.nodes.iter().find(|n| n.ply == 3 && n.san == "d4").unwrap();
assert_eq!(after_nf3.key, after_d4.key);
assert_eq!(tree.position_tally(after_nf3.key).games, 2);
assert!(!tree.nodes.iter().find(|n| n.san == "c4").unwrap().transposition);
assert_eq!(tree.path(after_d4.parent.unwrap() as usize), vec!["Nf3", "d5"]);
// Names: 1.d4 d5 2.Nf3 is named in the table, 2...Nf6 is too (Zukertort);
// both move orders get the same name.
assert!(after_nf3.named && after_d4.named);
assert_eq!(after_nf3.opening, after_d4.opening);
let name = &set.list[after_nf3.opening.unwrap()].name;
assert!(name.starts_with("Queen's Pawn Game"), "{name}");
// A node that is not named (4.h3 in the Queen's Gambit Declined) inherits the
// name of its path.
let tree = Tree::build(&games, &[0, 1, 2, 4], 20, &mut set);
let h3 = tree.nodes.iter().find(|n| n.san == "h3").unwrap();
assert!(!h3.named);
assert_eq!(h3.opening, tree.nodes[h3.parent.unwrap() as usize].opening);
assert!(set.list[h3.opening.unwrap()].name.starts_with("Queen's Gambit Declined"));
// Depth limit.
let short = Tree::build(&games, &[0, 1, 2], 1, &mut set);
assert_eq!(short.nodes.len(), 3);
}
}