Release 2.1.5
Some checks failed
Release / linux (push) Has been cancelled
Release / flatpak (push) Has been cancelled
Release / windows (push) Has been cancelled
Release / macos (push) Has been cancelled
Release / android (push) Has been cancelled
Release / publish (push) Has been cancelled
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run
Release / version (push) Has been cancelled

Automatically save opponent preparations and start the opening-error engine when the report is ready, while preserving manual Stop and saved evaluations.

Remove the book comparison from opponent preparation: its UI, background work, algorithm and development hook are gone. Legacy saved data remains readable and is preserved for a possible future revert.

Align game counts, error counts and percentages in the preparation summary and refresh the architecture and team documentation.
This commit is contained in:
vrubelroman 2026-11-02 13:35:21 +03:00
parent 101e976c48
commit fdcb12bd80
30 changed files with 1118 additions and 1342 deletions

View file

@ -1,103 +0,0 @@
//! 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, 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).
pub(crate) fn find_exits(
games: &mut [GameInfo],
book: &Database,
options: &BookOptions,
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<(u32, HashMap<u64, 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, counts))
}

View file

@ -62,15 +62,11 @@ impl Tally {
}
}
/// Where a game left the book (see [`crate::PrepReport::find_book_exits`]).
/// Legacy book data kept so old reports still round-trip.
#[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,
}
@ -96,8 +92,8 @@ pub struct GameInfo {
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.
/// Unused legacy book data, preserved when old reports are saved again.
#[serde(default)]
pub book: Option<BookExit>,
}

View file

@ -1,11 +1,11 @@
//! 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.
//! Preparing against an opponent on the desktop: 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
//! transpositions marked, and the openings named from the Lichess `chess-openings`
//! table (family → variation → games). 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
@ -27,7 +27,6 @@ use game_review::{JobFailure, JobSettings};
use serde::{Deserialize, Serialize};
use uci::EnginePosition;
mod book;
mod errors;
mod games;
pub mod openings;
@ -35,7 +34,6 @@ mod period;
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};
@ -47,8 +45,6 @@ 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)]
@ -110,22 +106,6 @@ pub struct ColorReport {
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 {
@ -134,12 +114,11 @@ pub struct EngineInfo {
pub nodes: u64,
}
/// The book the exits were found against.
/// Legacy book data kept so old reports still round-trip.
#[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,
}
@ -172,9 +151,9 @@ pub struct PrepReport {
pub openings: Vec<Opening>,
pub white: ColorReport,
pub black: ColorReport,
/// Unused legacy book data, preserved when old reports are saved again.
#[serde(default)]
pub book: Option<BookInfo>,
/// The book's number of games in every position the book step looked at (by
/// key): the first plies of every line, then the positions around each exit.
#[serde(default)]
pub book_counts: HashMap<u64, u32>,
pub engine: Option<EngineInfo>,
@ -184,6 +163,9 @@ pub struct PrepReport {
/// ([`SEARCH_VERSION`]; 0: from before it, made with the user's engine settings).
#[serde(default)]
pub search: u32,
/// A manual Stop forbids another automatic run of this report.
#[serde(default)]
pub engine_stopped: bool,
}
/// Identity of a database for the report cache: the content of a PGN file, the
@ -312,6 +294,7 @@ pub fn build(
engine: None,
evals,
search: SEARCH_VERSION,
engine_stopped: false,
};
report.refresh();
Some(report)
@ -404,30 +387,6 @@ impl PrepReport {
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, counts) = book::find_exits(&mut games, book, options, progress, cancel)?;
self.games = games;
self.book = Some(BookInfo {
fingerprint: fingerprint(book),
threshold: options.threshold,
left,
});
self.book_counts = counts;
Some(())
}
// ----- the engine -----------------------------------------------------------
/// Every distinct position of the lines (the one after the last move included),
@ -946,70 +905,36 @@ mod tests {
}
#[test]
fn the_book_says_where_a_game_left_it() {
fn legacy_book_fields_survive_report_serde() {
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,
&AtomicBool::new(false),
)
.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,
assert!(report.book.is_none() && report.book_counts.is_empty());
let exit = BookExit {
ply: 6,
by_player: false,
count: 1,
};
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 counts of the positions looked at: the start (4 games), 1.e4 c5 2.Nf3
// (3), the rare 3...g6 (1).
let g = &report.games[0];
assert_eq!(report.book_counts.get(&g.keys[0]), Some(&4));
assert_eq!(report.book_counts.get(&g.keys[3]), Some(&3));
assert_eq!(report.book_counts.get(&g.keys[6]), Some(&1));
// 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));
report.games[0].book = Some(exit);
report.book = Some(BookInfo {
fingerprint: 17,
threshold: 5,
left: 1,
});
report.book_counts.insert(report.games[0].keys[0], 4);
let json = serde_json::to_string(&report).expect("serialize");
let restored: PrepReport = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.games[0].book, Some(exit));
assert_eq!(restored.book, report.book);
assert_eq!(restored.book_counts, report.book_counts);
}
#[test]