Release 2.1.0
Some checks failed
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
Release / macos (push) Has been cancelled
Release / android (push) Has been cancelled
Release / linux (push) Has been cancelled
Release / flatpak (push) Has been cancelled
Release / windows (push) Has been cancelled
Release / publish (push) Has been cancelled

Preparing against an opponent (openings), one fixed engine search for the game
review everywhere, !! and ! recalibrated on chess.com (check set of 15 games),
100 classic sample games that update with the program. Formatting by cargo fmt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-28 20:37:06 +03:00
parent dd26e7261a
commit 262c0b1711
28 changed files with 1621 additions and 495 deletions

View file

@ -968,7 +968,8 @@ impl Base {
let mut first = true;
moves::main_line(&bytes, 0, fast, |pos, step| {
if std::mem::take(&mut first) {
line.standard_start = crate::position::same_position(pos, &shakmaty::Chess::default());
line.standard_start =
crate::position::same_position(pos, &shakmaty::Chess::default());
if !line.standard_start {
return false;
}

View file

@ -408,9 +408,21 @@ mod tests {
assert_eq!(theory_end(10, 0, |_| None), None);
// Continuing from a known prefix.
let end = theory_end(10, 4, |i| Some(i < 7)).expect("end");
assert_eq!(end, TheoryEnd { last_known: Some(6), first_unknown: Some(7) });
assert_eq!(
end,
TheoryEnd {
last_known: Some(6),
first_unknown: Some(7)
}
);
let end = theory_end(10, 4, |_| Some(true)).expect("end");
assert_eq!(end, TheoryEnd { last_known: Some(9), first_unknown: None });
assert_eq!(
end,
TheoryEnd {
last_known: Some(9),
first_unknown: None
}
);
}
#[test]

View file

@ -23,8 +23,9 @@ fn main() {
eprintln!("usage: chesscom_check <engine>");
std::process::exit(2);
};
let nodes: u64 = std::env::var("CP_REVIEW_NODES")
.map_or(SEARCH_NODES, |n| n.parse().expect("CP_REVIEW_NODES: a number"));
let nodes: u64 = std::env::var("CP_REVIEW_NODES").map_or(SEARCH_NODES, |n| {
n.parse().expect("CP_REVIEW_NODES: a number")
});
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
// Evaluations of one version of the fixed search are the same on every machine;
// those of other nodes go apart.
@ -82,7 +83,11 @@ fn main() {
);
for (i, j) in a.report.judgements.iter().enumerate() {
if let Some(j @ (Judgement::Brilliant | Judgement::Great)) = j {
let mark = if *j == Judgement::Brilliant { "!!" } else { "!" };
let mark = if *j == Judgement::Brilliant {
"!!"
} else {
"!"
};
let label = game.move_label(line[i + 1]).unwrap_or_default();
println!(" ours {label:<14} {mark}");
}

View file

@ -254,14 +254,12 @@ fn taking_loses(before: &Board, pos: &Chess, sq: Square, threat: i32) -> bool {
let mut after = pos.clone();
after.play_unchecked(take);
let mover = after.turn();
threats(&after)
.iter()
.any(|t| {
t.2 != sq
&& t.0 >= threat
&& pseudo_threat(pos.board(), t.2, mover) >= threat
&& pseudo_threat(before, t.2, mover) < threat
})
threats(&after).iter().any(|t| {
t.2 != sq
&& t.0 >= threat
&& pseudo_threat(pos.board(), t.2, mover) >= threat
&& pseudo_threat(before, t.2, mover) < threat
})
}
/// What `by` would win taking on `sq`, whoever is to move (a piece already hanging).
@ -403,8 +401,14 @@ mod tests {
let f = last(Chess::default(), PILLSBURY);
assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}");
// 18.fxe6! just before: takes back the knight taken on c3, no gain.
let f = last(Chess::default(), &PILLSBURY[..PILLSBURY.rfind(" Ra3").unwrap()]);
assert!(f.winning_capture && f.takes_back && f.great_shape(Rules::ChessCom), "{f:?}");
let f = last(
Chess::default(),
&PILLSBURY[..PILLSBURY.rfind(" Ra3").unwrap()],
);
assert!(
f.winning_capture && f.takes_back && f.great_shape(Rules::ChessCom),
"{f:?}"
);
assert!(!f.great_shape(Rules::Strict), "the first rules stay: {f:?}");
}
@ -418,7 +422,10 @@ mod tests {
15. O-O Ne5 16. Nxe5 Bxe5 17. f4 Bc7 18. e4 Rac8 19. e5 Bb6+ 20. Kh1 Ng4 \
21. Be4 Qh4 22. g3 Rxc3 23. gxh4 Rd2 24. Qxd2 Bxe4+",
);
assert!(f.winning_capture && !f.takes_back && !f.great_shape(Rules::ChessCom), "{f:?}");
assert!(
f.winning_capture && !f.takes_back && !f.great_shape(Rules::ChessCom),
"{f:?}"
);
}
#[test]

View file

@ -54,7 +54,9 @@ const SEARCH_GUARD: Duration = Duration::from_secs(300);
pub fn processes(limit: usize) -> usize {
let cpus = std::thread::available_parallelism().map_or(1, |n| n.get());
let memory = available_mb().map_or(usize::MAX, |mb| {
(mb.saturating_sub(SHARED_MB) / PROCESS_MB).try_into().unwrap_or(usize::MAX)
(mb.saturating_sub(SHARED_MB) / PROCESS_MB)
.try_into()
.unwrap_or(usize::MAX)
});
cpus.min(limit).min(memory).clamp(1, MAX_PROCESSES)
}
@ -158,7 +160,10 @@ pub fn run(
if targets.is_empty() {
return Ok(());
}
let workers = settings.processes.clamp(1, MAX_PROCESSES).min(targets.len());
let workers = settings
.processes
.clamp(1, MAX_PROCESSES)
.min(targets.len());
let next = AtomicUsize::new(0);
let failed = AtomicBool::new(false);
let halted = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed);
@ -228,7 +233,14 @@ fn worker(
let mut search = |pos: &EnginePosition, among: Vec<String>| {
next_id += 1;
let _ = handle.new_game();
search_once(&handle, pos, SearchId(next_id), among, settings.nodes, halted)
search_once(
&handle,
pos,
SearchId(next_id),
among,
settings.nodes,
halted,
)
};
while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
if halted() {

View file

@ -23,8 +23,8 @@ pub mod report;
pub use features::{MoveFeatures, Rules};
pub use job::{
JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB, SEARCH_NODES,
SEARCH_VERSION, Target, estimate_secs, processes, run,
JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB,
SEARCH_NODES, SEARCH_VERSION, Target, estimate_secs, processes, run,
};
pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats, judge};
@ -313,7 +313,11 @@ impl GameAnalysis {
/// !! and ! ("Update" fills them in without evaluating anything again). None for
/// evaluations from the PGN, which have no engine lines.
pub fn seconds_missing(&self) -> usize {
if self.meta.as_ref().is_none_or(|m| m.nodes == 0 || m.is_stale()) {
if self
.meta
.as_ref()
.is_none_or(|m| m.nodes == 0 || m.is_stale())
{
return 0;
}
(0..self.played.len())

View file

@ -805,7 +805,10 @@ mod tests {
Rules::Strict,
);
assert_eq!(r.judgements[0], None);
let mate = Some(Eval::Mate { white: true, moves: 5 });
let mate = Some(Eval::Mate {
white: true,
moves: 5,
});
let r = Report::build(&evals, &[noted(w, true, mate)], Phases::default());
assert_eq!(r.judgements[0], None);
// No best other move known (an older analysis): nothing said.

View file

@ -661,7 +661,10 @@ mod tests {
fn comments_and_variations_come_along() {
// The Opera game of the samples has comments and a variation.
let db = classics();
let g = db.game(0).expect("a game");
let g = (0..db.len())
.map(|i| db.game(i).expect("a game"))
.find(|g| g.nodes.iter().any(|n| n.san == "Qb8+"))
.expect("the Opera game");
assert!(
g.nodes
.iter()

View file

@ -474,8 +474,8 @@ mod tests {
// Evaluations from the PGN have no lines: nothing to show on the board.
assert!(ke7.best.is_none() && ke7.reply_from.is_none());
assert!(s.white.accuracy.is_some());
// Nothing to analyse: every position has an evaluation.
assert!(!review.start("/nonexistent".into(), String::new(), false));
// The engine never fills in evaluations from the PGN: it would analyse the whole
// game (GameAnalysis::begin), so nothing is started here.
}
/// With the fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`).

View file

@ -203,10 +203,18 @@ mod tests {
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!(
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!(
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.
@ -226,8 +234,14 @@ mod tests {
let after_d4 = by_position(line[5]).map(|id| get(id).name.clone());
assert_eq!(after_d4.as_deref(), Some("Sicilian Defense"));
let (at, id) = deepest(&line).expect("named");
assert_eq!((at, get(id).name.as_str()), (4, "Sicilian Defense: Modern Variations"));
assert!(is_prefix_name("Sicilian Defense", "Sicilian Defense: Modern Variations"));
assert_eq!(
(at, get(id).name.as_str()),
(4, "Sicilian Defense: Modern Variations")
);
assert!(is_prefix_name(
"Sicilian Defense",
"Sicilian Defense: Modern Variations"
));
assert!(is_prefix_name("A: B", "A: B, C"));
assert!(!is_prefix_name("Sicilian Defense", "Sicilian Defense"));
assert!(!is_prefix_name("English", "English Opening"));
@ -236,11 +250,22 @@ mod tests {
#[test]
fn book_positions_and_keys() {
// The Greco Gambit lines pass 6...Bb4+; 7...d5 is on none of them.
let k = keys(&["e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+"]);
assert!(in_book(k[12]) && by_position(k[12]).is_none(), "on the way, not named");
let more = keys(&["e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+", "Nc3", "d5"]);
let k = keys(&[
"e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+",
]);
assert!(
in_book(k[12]) && by_position(k[12]).is_none(),
"on the way, not named"
);
let more = keys(&[
"e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+",
"Nc3", "d5",
]);
assert!(in_book(more[13]) && !in_book(more[14]));
assert!(!in_book(k[0]), "the start position is no move into the book");
assert!(
!in_book(k[0]),
"the start position is no move into the book"
);
// The key is the one the rest of the program uses.
let pos = Chess::default();
assert_eq!(key(&pos), chess_import::position::key(&pos));

View file

@ -16,9 +16,7 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::time::Instant;
use prep::{
BookOptions, ColorReport, Options, Player, PrepReport, PositionCache, Side, Tree,
};
use prep::{BookOptions, ColorReport, Options, Player, PositionCache, PrepReport, Side, Tree};
struct Args {
db: PathBuf,
@ -50,10 +48,16 @@ fn args() -> Args {
"--book" => a.book = it.next().map(PathBuf::from),
"--plies" => a.plies = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.plies),
"--processes" => {
a.processes = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.processes)
a.processes = it
.next()
.and_then(|v| v.parse().ok())
.unwrap_or(a.processes)
}
"--min-games" => {
a.min_games = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.min_games)
a.min_games = it
.next()
.and_then(|v| v.parse().ok())
.unwrap_or(a.min_games)
}
"--no-cache" => a.cache = false,
_ => positional.push(arg),
@ -70,8 +74,8 @@ fn args() -> Args {
fn open(path: &Path) -> chess_import::Database {
let t = Instant::now();
let opened = chess_import::open(path, &mut |_| {}, &AtomicBool::new(false))
.unwrap_or_else(|e| {
let opened =
chess_import::open(path, &mut |_| {}, &AtomicBool::new(false)).unwrap_or_else(|e| {
eprintln!("cannot open {}: {e}", path.display());
std::process::exit(1);
});
@ -105,7 +109,8 @@ fn print_tree(tree: &Tree, node: usize, depth: usize, min_games: u32, report: &P
prep::move_label(usize::from(n.ply) - 1, &n.san),
tally(&n.tally),
n.last_date,
n.average_elo().map_or(String::new(), |e| format!(" Elo {e}")),
n.average_elo()
.map_or(String::new(), |e| format!(" Elo {e}")),
if n.transposition { " ↔" } else { "" },
name,
indent = depth * 2
@ -118,7 +123,11 @@ fn print_tree(tree: &Tree, node: usize, depth: usize, min_games: u32, report: &P
fn print_color(report: &PrepReport, cr: &ColorReport, min_games: u32) {
let colour = if cr.white { "White" } else { "Black" };
println!("\n==== {colour}: {} games, {} tree nodes ====", cr.games.len(), cr.tree.nodes.len());
println!(
"\n==== {colour}: {} games, {} tree nodes ====",
cr.games.len(),
cr.tree.nodes.len()
);
println!("-- repertoire (nodes with at least {min_games} games; ↔ = transposition)");
print_tree(&cr.tree, 0, 0, min_games, report);
println!("-- openings");
@ -126,7 +135,11 @@ fn print_color(report: &PrepReport, cr: &ColorReport, min_games: u32) {
println!(
"{} {}{}",
tally(&f.tally),
if f.name.is_empty() { "(unnamed)" } else { &f.name },
if f.name.is_empty() {
"(unnamed)"
} else {
&f.name
},
errors_text(&f.errors)
);
for v in &f.variations {
@ -239,7 +252,11 @@ fn main() {
let t = Instant::now();
let (list, total) = prep::candidates(&db, &a.player, 10);
println!("[candidates] {total} for «{}», {:.1} ms:", a.player, t.elapsed().as_secs_f64() * 1000.0);
println!(
"[candidates] {total} for «{}», {:.1} ms:",
a.player,
t.elapsed().as_secs_f64() * 1000.0
);
for c in &list {
println!(" {} · {} games (id {})", c.name, c.games, c.id);
}
@ -264,7 +281,10 @@ fn main() {
.and_then(|d| PrepReport::load(d, &db, &player, &options));
let mut report = match cached {
Some(r) => {
println!("[report] from the cache, {:.1} ms", t.elapsed().as_secs_f64() * 1000.0);
println!(
"[report] from the cache, {:.1} ms",
t.elapsed().as_secs_f64() * 1000.0
);
r
}
None => {
@ -290,7 +310,11 @@ fn main() {
};
let book = a.book.as_deref().map(open);
let book_db = book.as_ref().unwrap_or(&db);
if report.book.as_ref().is_some_and(|b| b.fingerprint == prep::fingerprint(book_db)) {
if report
.book
.as_ref()
.is_some_and(|b| b.fingerprint == prep::fingerprint(book_db))
{
println!("[book] from the cached report");
} else {
let progress = AtomicUsize::new(0);
@ -341,7 +365,13 @@ fn main() {
first = false;
}
if last_shown.elapsed().as_secs_f64() >= 5.0 {
println!(" {} / {} ({:.0} s, nps {})", p.done, p.total, t.elapsed().as_secs_f64(), p.nps);
println!(
" {} / {} ({:.0} s, nps {})",
p.done,
p.total,
t.elapsed().as_secs_f64(),
p.nps
);
last_shown = Instant::now();
}
},

View file

@ -127,10 +127,18 @@ pub fn judge_games(
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 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 {
let Some(m) = uci
.parse::<UciMove>()
.ok()
.and_then(|u| u.to_move(&pos).ok())
else {
break;
};
if game.player_moves_at(i)
@ -268,7 +276,11 @@ impl PositionCache {
/// 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) {
if self
.entries
.get(&key)
.is_some_and(|e| e.nodes >= eval.nodes)
{
return false;
}
self.entries.insert(key, eval);

View file

@ -57,7 +57,8 @@ impl Tally {
/// 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))
(decided > 0)
.then(|| (f64::from(self.wins) + 0.5 * f64::from(self.draws)) / f64::from(decided))
}
}
@ -214,7 +215,13 @@ mod tests {
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] {
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));

View file

@ -34,9 +34,7 @@ mod tree;
pub use book::BookOptions;
pub use chess_import::chessbase::base::Side;
pub use errors::{
EXACT, ErrorCounts, OpeningError, PositionCache, PositionEval, RepeatedError,
};
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;
@ -179,7 +177,11 @@ 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()))
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();
@ -188,7 +190,8 @@ pub fn fingerprint(db: &Database) -> u64 {
.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()
fnv(b
.path()
.to_string_lossy()
.bytes()
.chain(len.to_le_bytes())
@ -562,7 +565,12 @@ impl PrepReport {
}
/// 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> {
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 mut report: PrepReport = serde_json::from_slice(&bytes).ok()?;
@ -733,24 +741,44 @@ mod tests {
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!(
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");
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.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.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!(
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);
@ -760,7 +788,11 @@ mod tests {
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[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");
@ -790,7 +822,16 @@ mod tests {
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());
assert!(
build(
&db,
&player,
&Options::default(),
&AtomicUsize::new(0),
&cancelled
)
.is_none()
);
}
#[test]
@ -801,15 +842,24 @@ mod tests {
[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 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"));
assert_eq!(
(o.name.as_str(), o.line.as_str()),
("Sicilian Defense: Closed", "1. e4 c5 2. Nc3")
);
}
#[test]
@ -818,8 +868,14 @@ mod tests {
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");
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.
@ -839,10 +895,21 @@ mod tests {
count: 1
})
);
assert_eq!(exits[1].map(|b| (b.ply, b.by_player)), Some((4, true)), "2...d6 is his");
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!(
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).
@ -868,8 +935,14 @@ mod tests {
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 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.
@ -886,15 +959,27 @@ mod tests {
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()));
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 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 pv = if key == before_bb5 {
vec!["d2d4".to_owned()]
} else {
Vec::new()
};
let event = JobEvent::Eval {
key: t.key.clone(),
eval: game_review::PosEval {
@ -918,7 +1003,10 @@ mod tests {
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!(
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);
@ -936,14 +1024,34 @@ mod tests {
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());
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");
let mut fresh = build(
&db,
&player,
&Options::default(),
&AtomicUsize::new(0),
&never,
)
.expect("report");
assert!(!fresh.evaluated());
assert_eq!(fresh.take_cached(&cache), total);
assert!(fresh.evaluated(), "evaluations from the cache judge the errors too");
assert!(
fresh.evaluated(),
"evaluations from the cache judge the errors too"
);
assert_eq!(fresh.white.repeated, report.white.repeated);
assert_eq!(fresh.take_cached(&cache), 0);
// A report of another search (from before the fixed one) keeps its games but
@ -972,8 +1080,14 @@ mod tests {
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 mut report = build(
&db,
&player,
&Options::default(),
&AtomicUsize::new(0),
&never,
)
.expect("report");
let total = report.distinct_positions();
let settings = JobSettings::new(2, None);
let mut cache = PositionCache::default();
@ -991,10 +1105,19 @@ mod tests {
assert_eq!((last.done, last.total), (total, total));
assert_eq!(report.missing(), 0);
assert_eq!(cache.len(), total);
assert_eq!(report.engine.as_ref().map(|e| e.name.as_str()), Some("Fake UCI"));
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 mut again = build(
&db,
&player,
&Options::default(),
&AtomicUsize::new(0),
&never,
)
.expect("report");
let cancelled = AtomicBool::new(true);
let mut calls = 0;
analyse(

View file

@ -98,11 +98,13 @@ impl Tree {
let key = game.keys[i + 1];
// A more general name than the path's keeps the path's
// (see `openings::deepest`).
let parent = tree.nodes[at].opening.map(|o| openings.list[o].name.clone());
let parent = tree.nodes[at]
.opening
.map(|o| openings.list[o].name.clone());
let named = openings::by_position(key).filter(|&id| {
parent
.as_deref()
.is_none_or(|p| !openings::is_prefix_name(&openings::get(id).name, p))
parent.as_deref().is_none_or(|p| {
!openings::is_prefix_name(&openings::get(id).name, p)
})
});
let opening = named
.map(|id| openings.intern(id))
@ -161,9 +163,12 @@ impl Tree {
if let Some(&o) = best.get(&tree.nodes[i].key) {
tree.nodes[i].opening = Some(o);
}
let parent = tree.nodes[i].parent.and_then(|p| tree.nodes[p as usize].opening);
let parent = tree.nodes[i]
.parent
.and_then(|p| tree.nodes[p as usize].opening);
let name = |o: Option<usize>| o.map(|o| openings.list[o].name.as_str());
tree.nodes[i].named = tree.nodes[i].opening.is_some() && name(tree.nodes[i].opening) != name(parent);
tree.nodes[i].named =
tree.nodes[i].opening.is_some() && name(tree.nodes[i].opening) != name(parent);
}
tree
}
@ -238,11 +243,18 @@ impl Tree {
pub(crate) mod tests {
use super::*;
use crate::games::Outcome;
use chess_core::shakmaty::san::SanPlus;
use chess_core::shakmaty::Chess;
use chess_core::shakmaty::san::SanPlus;
use chess_import::position::{key, uci};
pub(crate) fn game(index: u32, white: bool, moves: &[&str], result: &str, date: &str, elo: u16) -> GameInfo {
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 {
@ -270,11 +282,25 @@ pub(crate) mod tests {
#[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(
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),
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);
@ -284,20 +310,42 @@ pub(crate) mod tests {
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();
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();
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_eq!(tree.position_games(after_nf3.key), vec![0, 1]);
assert_eq!(tree.position_last_date(after_nf3.key), "2026.03.01");
assert!(!tree.nodes.iter().find(|n| n.san == "c4").unwrap().transposition);
assert_eq!(tree.path(after_d4.parent.unwrap() as usize), vec!["Nf3", "d5"]);
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);
@ -310,7 +358,11 @@ pub(crate) mod tests {
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"));
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);