chessbaseLinux/crates/prep/src/book.rs

104 lines
3.8 KiB
Rust
Raw Permalink Normal View History

2026-10-28 12:32:39 +03:00
//! 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.
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
/// Returns how many games left the book within their line, and the book's count of
/// every position looked at (by key). `None` when cancelled (or when the book cannot
/// be searched: a PGN book without memory for its table).
2026-10-28 12:32:39 +03:00
pub(crate) fn find_exits(
games: &mut [GameInfo],
book: &Database,
options: &BookOptions,
progress: &AtomicUsize,
cancel: &AtomicBool,
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
) -> Option<(u32, HashMap<u64, u32>)> {
2026-10-28 12:32:39 +03:00
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),
}
});
}
Opponent prep: the desktop screen (dialog, report, engine run) The «Prepare against…» entry points in the library (the filter panel's button when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog (database, the player's spellings with the similar names apart, colour, book) and the report screen in the stack between the library and the game: the repertoire tree with transpositions, opening names, scores and the book column, the openings table by family and variation, the errors tab (repeated errors and by opening), the board of the chosen position with the line under it, and the games of the selection, which open in the game screen at that move with «⬅ Back to preparation». The engine run reuses the game analysis job over the distinct opening positions of the chosen colour: the launch dialog shares the engine picker and the quality/threads/memory grid with review.rs (quality «Fast» by default, its own setting), marks appear as positions are evaluated, «Stop» keeps what was done, the evaluations and the report are cached under <cache>/prep. One engine job per program: game analysis and the live engine are blocked meanwhile. Core: targets and counts by colour (`targets_for`, `missing_for`), the book step keeps its per-position counts (`book_counts`) for the tree column. Narrow windows: the board stacks over the lists under 804 px and folds into a button under 720 px of height; the right column is split explicitly (a nested bottom panel is not reserved from the content above it in egui). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 15:43:15 +03:00
Some((left, counts))
2026-10-28 12:32:39 +03:00
}