diff --git a/crates/game-review/chesscom/README.md b/crates/game-review/chesscom/README.md index 6ee4104..26dd21d 100644 --- a/crates/game-review/chesscom/README.md +++ b/crates/game-review/chesscom/README.md @@ -17,6 +17,10 @@ cargo run --release -p game-review --example chesscom_check -- повторный прогон после правки правил идёт без движка. - `CP_REVIEW_NODES=N` — другое число узлов, только для подбора константы (кэш в `target/chesscom-check/v<версия>-N/`); программа так не считает. +- `CP_SHALLOW_NODES`, `CP_GREAT_HARD`, `CP_BRILLIANT_HARD`, `CP_GREAT_GAP`, + `CP_BRILLIANT_GAP`, `CP_GREAT_BANS`, `CP_HARD_DEPTH` — опыты с «трудностью» хода + (неглубокий поиск, `Hardness`; 2026-10-29, программа их пока не использует), см. + `examples/chesscom_check.rs`. Неглубокие поиски хранятся в том же кэше. - Новую партию от владельца — сюда же, с источником в теге `Annotator`. ## Порядок калибровки diff --git a/crates/game-review/examples/chesscom_check.rs b/crates/game-review/examples/chesscom_check.rs index f40bf40..3ba4afc 100644 --- a/crates/game-review/examples/chesscom_check.rs +++ b/crates/game-review/examples/chesscom_check.rs @@ -9,13 +9,29 @@ //! //! `CP_REVIEW_NODES=N` searches N nodes instead, for choosing the program's nodes (the //! program itself never does): its evaluations are cached apart. +//! +//! How hard a move is to find (`game_review::Hardness`, being tried out; the program +//! does not use it yet), only for choosing its rules here: +//! - `CP_GREAT_HARD=P` — ! only for a move at least P % (win) hard to find; +//! - `CP_BRILLIANT_HARD=P` — !! also for the only good move at least P % hard; +//! - `CP_GREAT_GAP=P` — the gap of ! (default 25); +//! - `CP_BRILLIANT_GAP=P` — the gap of a hard move's !! (default 25); +//! - `CP_GREAT_BANS=0` — captures and quiet retreats can be ! too; +//! - `CP_HARD_DEPTH=1` — difficulty as the shallow search's underrating of the move +//! against the deep one (`Measure::Depth`), not against its own best move; +//! - `CP_SHALLOW_NODES=S` — the shallow search's nodes (default +//! `game_review::SHALLOW_NODES`), kept with the evaluations (other nodes are searched +//! again). use std::path::{Path, PathBuf}; use std::sync::atomic::AtomicBool; use chess_core::shakmaty::Color; use chess_core::{Game, Nag}; -use game_review::{GameAnalysis, JobSettings, Judgement, SEARCH_NODES, SEARCH_VERSION}; +use game_review::{ + GameAnalysis, Hardness, JobSettings, Judgement, Measure, SEARCH_NODES, SEARCH_VERSION, + SHALLOW_NODES, +}; fn main() { let args: Vec = std::env::args().collect(); @@ -26,6 +42,29 @@ fn main() { let nodes: u64 = std::env::var("CP_REVIEW_NODES").map_or(SEARCH_NODES, |n| { n.parse().expect("CP_REVIEW_NODES: a number") }); + let number = |name: &str| { + std::env::var(name).ok().map(|v| { + v.parse::() + .unwrap_or_else(|_| panic!("{name}: a number")) + }) + }; + let defaults = Hardness::default(); + let hardness = Hardness { + great: number("CP_GREAT_HARD"), + gap: number("CP_GREAT_GAP").unwrap_or(defaults.gap), + bans: number("CP_GREAT_BANS").is_none_or(|b| b != 0.0), + brilliant: number("CP_BRILLIANT_HARD"), + brilliant_gap: number("CP_BRILLIANT_GAP").unwrap_or(defaults.brilliant_gap), + measure: if number("CP_HARD_DEPTH").is_some_and(|d| d != 0.0) { + Measure::Depth + } else { + Measure::Choice + }, + }; + let shallow = number("CP_SHALLOW_NODES").map_or(SHALLOW_NODES, |n| n as u64); + if hardness != defaults { + println!("{hardness:?}, shallow search {shallow} nodes"); + } 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. @@ -52,6 +91,8 @@ fn main() { let text = std::fs::read_to_string(&file).expect("pgn"); let game = chess_core::parse_str(&text).game; let mut a = GameAnalysis::new(&game, Some(&cache)); + a.set_hardness(hardness); + a.set_shallow_nodes(shallow); review(&mut a, &game, engine, nodes); a.save_cache(&cache).expect("cache"); let compared = game.tag("ChessComMarks").unwrap_or("!! !").to_owned(); @@ -118,13 +159,30 @@ fn main() { t.extra += u32::from(ours_compared == mark && theirs != mark); } let label = game.move_label(node).unwrap_or_default(); + // How hard the move was to find, when the shallow search was made. + let hard = a + .eval_at(i) + .and_then(|e| Some((e.eval, e.shallow.as_ref()?))) + .filter(|(_, s)| s.nodes == shallow) + .map_or(String::new(), |(deep, s)| { + let [choice, depth] = [Measure::Choice, Measure::Depth] + .map(|m| m.difficulty(deep, s.best_eval, s.played_eval, a.movers()[i])); + format!( + " (hard: choice {choice:.1} %, depth {depth:.1} %; shallow {} {}, \ + played {}, deep {})", + s.best, + s.best_eval.format(), + s.played_eval.format(), + deep.format() + ) + }); if theirs == ours_compared { agree += 1; - println!(" ok {label:<14} {theirs}"); + println!(" ok {label:<14} {theirs}{hard}"); } else { differ += 1; println!( - " DIFF {label:<14} chess.com {:<3} ours {}", + " DIFF {label:<14} chess.com {:<3} ours {}{hard}", or_dash(theirs), or_dash(ours_compared) ); diff --git a/crates/game-review/examples/review_bench.rs b/crates/game-review/examples/review_bench.rs index 2b8475e..d7ce1fc 100644 --- a/crates/game-review/examples/review_bench.rs +++ b/crates/game-review/examples/review_bench.rs @@ -2,11 +2,14 @@ //! number of engine processes: prints the time and a digest of every evaluation. //! //! `cargo run --release -p game-review --example review_bench -- ...` +//! +//! `CP_SHALLOW_NODES=S` adds the shallow searches of S nodes (for how hard a move was to +//! find, `game_review::Hardness`), as rules that use them would. use std::sync::atomic::AtomicBool; use std::time::Instant; -use game_review::{GameAnalysis, JobSettings}; +use game_review::{GameAnalysis, Hardness, JobSettings}; fn main() { let args: Vec = std::env::args().collect(); @@ -16,13 +19,23 @@ fn main() { } let text = std::fs::read_to_string(&args[2]).expect("pgn"); let game = chess_core::parse_str(&text).game; + let shallow: Option = std::env::var("CP_SHALLOW_NODES") + .ok() + .map(|n| n.parse().expect("CP_SHALLOW_NODES: a number")); let mut digests = Vec::new(); for p in &args[3..] { let processes: usize = p.parse().expect("processes"); let mut a = GameAnalysis::new(&game, None); + if let Some(nodes) = shallow { + a.set_shallow_nodes(nodes); + a.set_hardness(Hardness { + brilliant: Some(100.0), + ..Hardness::default() + }); + } let targets = a.begin(&game, true); let positions = targets.len(); - let mut searches = 0; + let (mut searches, mut shallows) = (0, 0); let started = Instant::now(); game_review::run( uci::EngineConfig::new(&args[1]), @@ -32,6 +45,9 @@ fn main() { &mut |e| { if let game_review::JobEvent::Eval { eval, .. } = &e { searches += 1 + usize::from(eval.second.is_some()); + if let Some(s) = &eval.shallow { + shallows += 1 + usize::from(s.best != s.played); + } } a.apply(e); }, @@ -45,8 +61,8 @@ fn main() { (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3) }); println!( - "processes {processes:>2}: {positions} positions, {searches} searches, {secs:.1} s, \ - evaluations {digest:016x}" + "processes {processes:>2}: {positions} positions, {searches} searches \ + (+{shallows} shallow), {secs:.1} s, evaluations {digest:016x}" ); digests.push(digest); } diff --git a/crates/game-review/src/features.rs b/crates/game-review/src/features.rs index 550e9e1..67aaa69 100644 --- a/crates/game-review/src/features.rs +++ b/crates/game-review/src/features.rs @@ -143,8 +143,9 @@ impl MoveFeatures { /// Could be great: not a forced, obvious or finishing move. With [`Rules::ChessCom`] /// a piece saving itself on the only good square can be (13.Qa4 of the Evergreen - /// game), a book move cannot (6…Bb4+ of Steinitz — von Bardeleben). - pub fn great_shape(&self, rules: Rules) -> bool { + /// game), a book move cannot (6…Bb4+ of Steinitz — von Bardeleben). `bans`: the + /// quiet retreat is not ([`crate::report::Hardness::bans`]). + pub fn great_shape(&self, rules: Rules, bans: bool) -> bool { self.legal > 1 && !(rules == Rules::ChessCom && self.book) && !self.mates @@ -154,15 +155,17 @@ impl MoveFeatures { // An attacked piece stepping quietly to its one good square is plain, not // great (10.Be2 of an online game, the owner: «какой же это !»); stepping away // with check is an attack (19…Ne2+ of Byrne — Fischer, chess.com's !). - && !(rules == Rules::ChessCom && self.escape && !self.gives_check) + && !(rules == Rules::ChessCom && bans && self.escape && !self.gives_check) } - /// Worth asking the engine for the best other move. - /// (Under either rules: one analysis serves both.) - pub fn candidate(&self) -> bool { - [Rules::Strict, Rules::ChessCom] - .into_iter() - .any(|r| self.brilliant_shape(r) || self.pawn_shape(r) || self.great_shape(r)) + /// Worth asking the engine for the best other move (under either rules: one analysis + /// serves both); `bans` as for [`Self::great_shape`]. + pub fn candidate(&self, bans: bool) -> bool { + [Rules::Strict, Rules::ChessCom].into_iter().any(|r| { + self.brilliant_shape(r) + || self.pawn_shape(r) + || self.great_shape(r, r == Rules::Strict || bans) + }) } /// Could be brilliant for a quicker mate only: a pawn offered ([`Rules::ChessCom`]). @@ -326,10 +329,13 @@ mod tests { fn a_queen_offered_for_mate_is_a_sacrifice() { let f = last(Chess::default(), OPERA); assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); - assert!(!f.mates && f.candidate()); + assert!(!f.mates && f.candidate(true)); // 15.Bxd7+ Nxd7: taken back, not a move of note. let f = last(Chess::default(), &OPERA[..OPERA.find(" 16.").unwrap()]); - assert!(f.recapture && !f.great_shape(Rules::ChessCom), "{f:?}"); + assert!( + f.recapture && !f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); } #[test] @@ -342,7 +348,7 @@ mod tests { // A free knight taken: a winning capture, never !. let f = features("4k3/8/8/3n4/8/8/8/3QK3 w - - 0 1", "Qxd5"); assert!( - f.winning_capture && !f.great_shape(Rules::ChessCom) && !f.sacrifice, + f.winning_capture && !f.great_shape(Rules::ChessCom, true) && !f.sacrifice, "{f:?}" ); } @@ -352,7 +358,10 @@ mod tests { // The bishop on c4 attacked by the pawn on d5: Bb3 saves it — never a sacrifice, // and a quiet step away is not great either. let f = features("4k3/8/8/3p4/2B5/8/8/4K3 w - - 0 1", "Bb3"); - assert!(f.escape && !f.sacrifice && !f.great_shape(Rules::ChessCom), "{f:?}"); + assert!( + f.escape && !f.sacrifice && !f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); // Taking the pawn instead, into the knight: it was lost anyway (desperado). let f = features("4k3/8/5n2/3p4/2B5/8/8/4K3 w - - 0 1", "Bxd5"); assert!(!f.sacrifice, "{f:?}"); @@ -413,10 +422,13 @@ mod tests { &PILLSBURY[..PILLSBURY.rfind(" Ra3").unwrap()], ); assert!( - f.winning_capture && f.takes_back && f.great_shape(Rules::ChessCom), + f.winning_capture && f.takes_back && f.great_shape(Rules::ChessCom, true), "{f:?}" ); - assert!(!f.great_shape(Rules::Strict), "the first rules stay: {f:?}"); + assert!( + !f.great_shape(Rules::Strict, true), + "the first rules stay: {f:?}" + ); } #[test] @@ -430,7 +442,7 @@ mod tests { 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.winning_capture && !f.takes_back && !f.great_shape(Rules::ChessCom, true), "{f:?}" ); } @@ -458,10 +470,19 @@ mod tests { 8. Bd3 Nh4 9. O-O c4 10. Be2", ); assert!(f.escape && !f.gives_check, "{f:?}"); - assert!(!f.great_shape(Rules::ChessCom), "{f:?}"); + assert!(!f.great_shape(Rules::ChessCom, true), "{f:?}"); + assert!(!f.candidate(true), "{f:?}"); + // Without the bans it is up to how hard it was to find. + assert!( + f.great_shape(Rules::ChessCom, false) && f.candidate(false), + "{f:?}" + ); // Stepping away with check can be great. let f = features("4k3/8/8/8/2p5/1B6/8/4K3 w - - 0 1", "Ba4+"); - assert!(f.escape && f.gives_check && f.great_shape(Rules::ChessCom), "{f:?}"); + assert!( + f.escape && f.gives_check && f.great_shape(Rules::ChessCom, true), + "{f:?}" + ); } #[test] diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs index 55108f6..1c8c34b 100644 --- a/crates/game-review/src/job.rs +++ b/crates/game-review/src/job.rs @@ -17,12 +17,20 @@ use std::time::{Duration, Instant}; use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; -use crate::{Eval, PosEval, Second}; +use crate::{Eval, PosEval, Second, Shallow}; /// Nodes of every search of a game analysis (0.85 s on one thread of an i7-13700KF, /// depth about 24). pub const SEARCH_NODES: u64 = 1_000_000; +/// Nodes of the shallow search, for how hard a move is to find ([`crate::Measure`]): +/// made only for a move that could be brilliant or great and was the engine's best, and +/// only when the rules ask for it ([`crate::Hardness`]). At 5 000 nodes (depth about 10) +/// Stockfish already finds nearly every move of note itself; above 10 000 hardly any is +/// hard (the chess.com check set, 2026-10-29). Its time is lost in that of the full +/// searches (+0.2 % for a game). +pub const SHALLOW_NODES: u64 = 5_000; + /// The engine's hash of every search, in MB. Part of the search: another size gives /// other evaluations. pub const SEARCH_HASH_MB: u32 = 32; @@ -88,8 +96,10 @@ pub struct Target { pub played: Option, /// The other legal moves (UCI). pub others: Vec, - /// The evaluation already there: only the second search is left. + /// The evaluation already there: only the second or shallow search is left. pub known: Option, + /// Nodes of the shallow search of `played`, when the rules want it. + pub shallow: Option, } /// How the job runs; the search itself is fixed (see the module). @@ -230,17 +240,10 @@ fn worker( let _ = handle.set_multipv(1); let mut next_id = 0; // Every search starts from a clear hash, so that it depends on its position alone. - let mut search = |pos: &EnginePosition, among: Vec| { + let mut search = |pos: &EnginePosition, among: Vec, nodes: u64| { 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, nodes, halted) }; while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) { if halted() { @@ -249,7 +252,7 @@ fn worker( let (mut eval, nps) = match &t.known { Some(e) => (e.clone(), 0), None => { - let Some((info, best)) = search(&t.pos, Vec::new())? else { + let Some((info, best)) = search(&t.pos, Vec::new(), settings.nodes)? else { continue; }; let Some(score) = info.score else { continue }; @@ -264,6 +267,7 @@ fn worker( pv, depth: info.depth.unwrap_or(0), second: None, + shallow: None, }; (eval, info.nps.unwrap_or(0)) } @@ -274,12 +278,15 @@ fn worker( Side::White => chess_core::shakmaty::Color::White, Side::Black => chess_core::shakmaty::Color::Black, }; - if let Some(played) = &t.played - && eval.pv.first() == Some(played) - && !t.others.is_empty() - && crate::report::worth_second(eval.eval, mover) + let played = t.played.as_ref().filter(|p| { + eval.pv.first() == Some(*p) + && !t.others.is_empty() + && crate::report::worth_second(eval.eval, mover) + }); + if let Some(played) = played + && eval.second.as_ref().map(|s| &s.without) != Some(played) { - match search(&t.pos, t.others.clone())? { + match search(&t.pos, t.others.clone(), settings.nodes)? { // An engine that ignores `searchmoves` answers with the move played: // no second move then. Some((info, best)) @@ -296,6 +303,19 @@ fn worker( _ => {} } } + // How hard it was to find: what a shallow search makes of it. + if let (Some(played), Some(nodes)) = (played, t.shallow) + && !eval + .shallow + .as_ref() + .is_some_and(|s| &s.played == played && s.nodes == nodes) + { + match shallow(&mut search, t, played, nodes)? { + Some(s) => eval.shallow = Some(s), + None if halted() => break, + None => {} + } + } on_event(JobEvent::Eval { key: t.key.clone(), eval, @@ -306,6 +326,52 @@ fn worker( Ok(()) } +/// What a search gave: its last full line and the best move, `None` when there is none +/// (see [`search_once`]). +type SearchResult = Result)>, JobFailure>; + +/// The shallow search of `played` at `t`: the best move at `nodes` and, when it is +/// another, the move played alone. `None` when the engine gave no answer (or ignored +/// `searchmoves`) or the job was halted. +fn shallow( + search: &mut dyn FnMut(&EnginePosition, Vec, u64) -> SearchResult, + t: &Target, + played: &str, + nodes: u64, +) -> Result, JobFailure> { + let eval_of = |info: &uci::SearchInfo| { + info.score + .map(|s| Eval::from_white_eval(s.to_white(t.turn).eval)) + }; + let Some((info, best)) = search(&t.pos, Vec::new(), nodes)? else { + return Ok(None); + }; + let (Some(best), Some(best_eval)) = (best.or_else(|| info.pv.first().cloned()), eval_of(&info)) + else { + return Ok(None); + }; + let played_eval = if best == played { + best_eval + } else { + match search(&t.pos, vec![played.to_owned()], nodes)? { + Some((info, b)) if b.as_deref().is_none_or(|b| b == played) => { + let Some(e) = eval_of(&info) else { + return Ok(None); + }; + e + } + _ => return Ok(None), + } + }; + Ok(Some(Shallow { + nodes, + played: played.to_owned(), + best, + best_eval, + played_eval, + })) +} + /// One node-limited search: its last full line and the best move. `None` when it gave /// no line or the job was halted. fn search_once( @@ -315,7 +381,7 @@ fn search_once( among: Vec, nodes: u64, halted: &dyn Fn() -> bool, -) -> Result)>, JobFailure> { +) -> SearchResult { handle .search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among) .map_err(|e| JobFailure::Engine(e.to_string()))?; @@ -456,6 +522,114 @@ mod tests { assert_eq!(evaluate(8, true), one); } + /// The shallow search is made only when the rules ask how hard a move was to find, + /// for the engine's best move that could be brilliant or great; an analysis without + /// it is filled in, without evaluating anything again. The fake engine (from a FEN + /// it always says e2e4) honours `searchmoves`, and below the nodes given prefers + /// d2d4 (+0.40) to e2e4 (+0.10 searched alone). + #[test] + fn the_shallow_search_says_how_hard_the_move_was() { + let game = chess_core::parse_str( + "[FEN \"rnbqkbnr/1ppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\"] 1. e4 e5 *", + ) + .game; + let engine = |shallow_best: bool| { + let mut config = uci::EngineConfig::new(fake()); + config.args = vec!["--searchmoves".into()]; + if shallow_best { + config.args.extend([ + "--shallow".into(), + (SHALLOW_NODES + 1).to_string().into(), + "d2d4".into(), + ]); + } + config + }; + let job = |a: &mut GameAnalysis, shallow_best: bool| { + let targets = a.begin(&game, false); + let n = targets.len(); + run( + engine(shallow_best), + &settings(2), + targets, + &AtomicBool::new(false), + &mut |e| a.apply(e), + ) + .expect("the job runs"); + a.refresh(&game); + n + }; + let mut a = GameAnalysis::new(&game, None); + assert_eq!(job(&mut a, true), 3); + let e = a.eval_at(0).expect("evaluated").clone(); + assert_eq!(e.pv.first().map(String::as_str), Some("e2e4")); + assert_eq!(e.second.as_ref().map(|s| s.eval), Some(Eval::Cp(10))); + assert!(e.shallow.is_none(), "the rules do not ask for it"); + assert_eq!(a.seconds_missing(), 0); + + // Rules that ask for it: the earlier analysis wants the shallow search only. + let hard = crate::Hardness { + great: Some(1.0), + gap: 1.0, + ..Default::default() + }; + a.set_hardness(hard); + a.refresh(&game); + assert_eq!(a.seconds_missing(), 1); + assert_eq!(a.report.judgements[0], None, "not known to be hard"); + assert_eq!(job(&mut a, true), 1); + assert_eq!(a.seconds_missing(), 0); + let e = a.eval_at(0).expect("evaluated"); + let s = e.shallow.as_ref().expect("the shallow search"); + assert_eq!( + (s.nodes, s.played.as_str(), s.best.as_str()), + (SHALLOW_NODES, "e2e4", "d2d4") + ); + assert_eq!((s.best_eval, s.played_eval), (Eval::Cp(40), Eval::Cp(10))); + assert_eq!(e.second.as_ref().map(|s| s.eval), Some(Eval::Cp(10))); + // 2.8 % harder than the shallow best: great at 1 %, not at 5 %, brilliant at 2 %. + let d = crate::Measure::Choice.difficulty( + e.eval, + s.best_eval, + s.played_eval, + chess_core::shakmaty::Color::White, + ); + assert!((2.0..5.0).contains(&d), "{d}"); + assert_eq!(a.report.judgements[0], Some(crate::Judgement::Great)); + a.set_hardness(crate::Hardness { + great: Some(5.0), + ..hard + }); + a.refresh(&game); + assert_eq!(a.report.judgements[0], None); + a.set_hardness(crate::Hardness { + brilliant: Some(2.0), + brilliant_gap: 1.0, + ..hard + }); + a.refresh(&game); + assert_eq!(a.report.judgements[0], Some(crate::Judgement::Brilliant)); + // Shallow searches of other nodes are made again. + a.set_shallow_nodes(SHALLOW_NODES / 2); + a.refresh(&game); + assert_eq!(a.seconds_missing(), 1); + assert_eq!(a.report.judgements[0], None); + + // The shallow search finding the move itself: not hard at all. + let mut b = GameAnalysis::new(&game, None); + b.set_hardness(hard); + assert_eq!(job(&mut b, false), 3); + let s = b + .eval_at(0) + .and_then(|e| e.shallow.clone()) + .expect("shallow"); + assert_eq!( + (s.best.as_str(), s.best_eval, s.played_eval), + ("e2e4", Eval::Cp(40), Eval::Cp(40)) + ); + assert_eq!(b.report.judgements[0], None, "0 % is below 1 %"); + } + #[test] fn a_failing_engine_fails_the_job() { let game = chess_core::parse_str("1. e4 e5 *").game; diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs index b891810..cc75bbf 100644 --- a/crates/game-review/src/lib.rs +++ b/crates/game-review/src/lib.rs @@ -24,9 +24,11 @@ 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, + SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes, run, +}; +pub use report::{ + Eval, Hardness, Judgement, Measure, Phase, Phases, Ply, Report, SideStats, judge, }; -pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats, judge}; /// Engine result for one position of the main line. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -41,6 +43,26 @@ pub struct PosEval { /// be brilliant or great (older analyses have none). #[serde(default, skip_serializing_if = "Option::is_none")] pub second: Option, + /// What a shallow search makes of the move played, for how hard it was to find + /// (when the rules ask for it, see [`Hardness`]; older analyses have none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub shallow: Option, +} + +/// The shallow search of a position whose move could be brilliant or great and was the +/// engine's best: the same fixed search as every other, to `nodes` nodes only. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Shallow { + /// Nodes of the search ([`SHALLOW_NODES`] in the programs). + pub nodes: u64, + /// The move played (UCI), as [`Second::without`]. + pub played: String, + /// The shallow search's best move (UCI) and its evaluation. + pub best: String, + pub best_eval: Eval, + /// The move played at the same nodes: `best_eval` when it is `best`, else a search + /// of the move played alone. + pub played_eval: Eval, } /// The best of the other moves: how the position stood without the move played. @@ -127,6 +149,10 @@ pub struct GameAnalysis { pub marks: HashMap, /// The rules of !! and ! the report follows. rules: Rules, + /// How the difficulty of a move counts in them. + hardness: Hardness, + /// Nodes of the shallow search ([`SHALLOW_NODES`]; another only in an experiment). + shallow_nodes: u64, } impl GameAnalysis { @@ -149,6 +175,8 @@ impl GameAnalysis { report: Report::default(), marks: HashMap::new(), rules: Rules::default(), + hardness: Hardness::default(), + shallow_nodes: SHALLOW_NODES, }; a.rebuild(game); if cache_dir.is_some_and(|d| a.load_cache(d)) || a.load_pgn_evals(game) { @@ -206,7 +234,7 @@ impl GameAnalysis { .features .iter() .flatten() - .filter(|f| f.candidate()) + .filter(|f| f.candidate(self.hardness.bans)) .count(); self.positions() + candidates / 2 } @@ -220,6 +248,25 @@ impl GameAnalysis { } } + /// Counts the difficulty of a move as `hardness` says from the next + /// [`Self::refresh`] on; when it asks for it, [`Self::begin`] wants the shallow + /// searches. + pub fn set_hardness(&mut self, hardness: Hardness) { + if self.hardness != hardness { + self.hardness = hardness; + self.dirty = true; + } + } + + /// Shallow searches of `nodes` instead of [`SHALLOW_NODES`]: only for an experiment + /// (choosing the nodes); those of other nodes are made again. + pub fn set_shallow_nodes(&mut self, nodes: u64) { + if self.shallow_nodes != nodes { + self.shallow_nodes = nodes; + self.dirty = true; + } + } + /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. pub fn refresh(&mut self, game: &Game) { if self.dirty || self.built_rev != Some(game.revision()) { @@ -251,8 +298,8 @@ impl GameAnalysis { (0..self.line.len()) .filter_map(|i| { let known = self.evals.get(&self.keys[i]).cloned(); - // Already evaluated: only a missing second search can be left. - if known.is_some() && !self.second_missing(i) + // Already evaluated: only the second or shallow search can be left. + if known.is_some() && !self.extra_missing(i) || known.is_none() && self.values[i].is_some() { return None; @@ -264,7 +311,7 @@ impl GameAnalysis { .get(i) .copied() .flatten() - .filter(|f| f.candidate()) + .filter(|f| f.candidate(self.hardness.bans)) .and_then(|_| self.played.get(i).cloned().flatten()); let others = match &played { Some(p) => here @@ -287,6 +334,7 @@ impl GameAnalysis { played, others, known, + shallow: self.hardness.uses_shallow().then_some(self.shallow_nodes), }) }) .collect() @@ -294,8 +342,8 @@ impl GameAnalysis { /// Position `i` is evaluated, its move could be brilliant or great and was the /// engine's best, but the best other move was never searched for (an analysis from - /// before !! and !). - fn second_missing(&self, i: usize) -> bool { + /// before !! and !), or the shallow search the rules ask for was not made. + fn extra_missing(&self, i: usize) -> bool { let (Some(e), Some(Some(played)), Some(Some(f))) = ( self.evals.get(&self.keys[i]), self.played.get(i), @@ -303,15 +351,22 @@ impl GameAnalysis { ) else { return false; }; - f.candidate() + let shallow_missing = || { + self.hardness.uses_shallow() + && !e + .shallow + .as_ref() + .is_some_and(|s| &s.played == played && s.nodes == self.shallow_nodes) + }; + f.candidate(self.hardness.bans) && e.pv.first() == Some(played) && report::worth_second(e.eval, self.movers[i]) - && e.second.as_ref().map(|s| &s.without) != Some(played) + && (e.second.as_ref().map(|s| &s.without) != Some(played) || shallow_missing()) } - /// Positions whose evaluation is there but which still want the second search of - /// !! and ! ("Update" fills them in without evaluating anything again). None for - /// evaluations from the PGN, which have no engine lines. + /// Positions whose evaluation is there but which still want the second (or shallow) + /// search of !! 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 @@ -321,7 +376,7 @@ impl GameAnalysis { return 0; } (0..self.played.len()) - .filter(|i| self.second_missing(*i)) + .filter(|i| self.extra_missing(*i)) .count() } @@ -398,11 +453,27 @@ impl GameAnalysis { .and_then(|e| e.second.as_ref()) .filter(|s| Some(&s.without) == played.as_ref()) .map(|s| s.eval), + difficulty: e + .and_then(|e| Some((e.eval, e.shallow.as_ref()?))) + .filter(|(_, s)| { + Some(&s.played) == played.as_ref() && s.nodes == self.shallow_nodes + }) + .zip(positions.get(i - 1)) + .map(|((deep, s), p)| { + self.hardness + .measure + .difficulty(deep, s.best_eval, s.played_eval, p.turn()) + }), }); } self.movers = plies.iter().map(|p| p.mover).collect(); - self.report = - Report::build_with(&self.values, &plies, Phases::divide(&positions), self.rules); + self.report = Report::build_tuned( + &self.values, + &plies, + Phases::divide(&positions), + self.rules, + self.hardness, + ); self.marks.clear(); for (i, j) in self.report.judgements.iter().enumerate() { let Some(judgement) = *j else { continue }; @@ -577,6 +648,7 @@ impl GameAnalysis { pv: Vec::new(), depth: 0, second: None, + shallow: None, }, ); } @@ -693,6 +765,7 @@ mod tests { pv: vec!["e2e4".into()], depth: 10, second: None, + shallow: None, }, nps: 0, }); diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs index 938a7fb..01619a9 100644 --- a/crates/game-review/src/report.rs +++ b/crates/game-review/src/report.rs @@ -166,6 +166,75 @@ mod good { pub const SECOND_FROM: f64 = GREAT_AFTER - NEAR_BEST; } +/// How hard a move is to find, in the mover's win %, from a shallow search +/// ([`crate::SHALLOW_NODES`]) of the engine's own best move. A move the strong search +/// plays and a weak one underrates is what people call brilliant (Zaidi & Guerzhoy 2024, +/// arXiv 2406.11895); an obvious only move (10.Be2 of an online game, 32.Kd2 of Tal — +/// Larsen) the shallow search finds too. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Measure { + /// How much worse than its own best move the shallow search finds the move played + /// (0 when it finds this move best). + #[default] + Choice, + /// How much worse the shallow search finds the move played than the deep one. + Depth, +} + +impl Measure { + /// The difficulty of a move the deep search finds `deep`, the shallow search + /// `played` and its own best move `best`. + pub fn difficulty(self, deep: Eval, best: Eval, played: Eval, mover: Color) -> f64 { + let top = match self { + Measure::Choice => best, + Measure::Depth => deep, + }; + (top.win_percent(mover) - played.win_percent(mover)).max(0.0) + } +} + +/// The say of a move's difficulty ([`Measure`]) in !! and ! ([`Rules::ChessCom`] only), +/// being tried out (2026-10-29) and off by default: the default is the rules without it, +/// and no shallow search is made for them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hardness { + /// !: only a move at least this hard to find (win %). + pub great: Option, + /// !: every other move loses at least this much (win %). + pub gap: f64, + /// !: never a capture nor an attacked piece stepping quietly away (the rules of + /// 2026-10-28 and 2026-10-29 against obvious !). + pub bans: bool, + /// !!: also the only good move (as for !, with [`Self::brilliant_gap`]) at least this + /// hard to find, sacrifice or not (in the check set at 5 000 nodes: 17…Be6!! of + /// Byrne — Fischer, 33.c3+!! of Kasparov — Topalov). + pub brilliant: Option, + /// !! of a hard move: every other move loses at least this much (win %). + pub brilliant_gap: f64, + /// How the difficulty is measured. + pub measure: Measure, +} + +impl Default for Hardness { + fn default() -> Hardness { + Hardness { + great: None, + gap: good::GAP_CHESSCOM, + bans: true, + brilliant: None, + brilliant_gap: good::GAP_CHESSCOM, + measure: Measure::Choice, + } + } +} + +impl Hardness { + /// The rules ask how hard a move was to find: the shallow search is wanted. + pub fn uses_shallow(&self) -> bool { + self.great.is_some() || self.brilliant.is_some() + } +} + /// Whether the best other move is worth searching for: the move played was the engine's /// best (`eval` the position's evaluation), and the position is good enough for !! or !. pub fn worth_second(eval: Eval, mover: Color) -> bool { @@ -185,7 +254,7 @@ fn outcome(win: f64) -> u8 { /// Brilliant or great, from the evaluations around the move (before the combination rule /// of [`Rules::Strict`]). -fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules) -> Option { +fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules, hard: Hardness) -> Option { let f = ply.features?; let (wb, wa) = (before.win_percent(ply.mover), after.win_percent(ply.mover)); let loss = wb - wa; @@ -220,33 +289,46 @@ fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules) -> Option return Some(Judgement::Brilliant); } let w2 = second?; + let bans = rules == Rules::Strict || hard.bans; // [`Rules::ChessCom`]: a capture is the natural move, never great (12…Nxc3, 13…Nxe4 of // Byrne — Fischer, 22…Nbxd5, 26.Qxd4+ of Kasparov — Topalov are not chess.com's !; the // few captures it marks — 20.Rxe7+, 18.fxe6 — are given up for fewer wrong ones). - if rules == Rules::ChessCom && f.capture { + if rules == Rules::ChessCom && bans && f.capture { return None; } // The engine's own best move loses nothing: a drop to the next position is the noise // of two searches (9.Nf5! of the Immortal game, −0.51 then −0.82 at 3M nodes); the // first rules still count it. - let only_move = ply.best - && (rules == Rules::ChessCom || loss <= good::NEAR_BEST) - && wb - w2 - >= match rules { - Rules::Strict => good::GAP, - Rules::ChessCom => good::GAP_CHESSCOM, - } - && (rules == Rules::ChessCom || outcome(wa) > outcome(w2)) - && wa >= good::GREAT_AFTER - && w2 - < match rules { - Rules::Strict => good::GREAT_ALT, - Rules::ChessCom => good::GREAT_ALT_CHESSCOM, - }; + let only_move = |gap: f64| { + ply.best + && (rules == Rules::ChessCom || loss <= good::NEAR_BEST) + && wb - w2 >= gap + && (rules == Rules::ChessCom || outcome(wa) > outcome(w2)) + && wa >= good::GREAT_AFTER + && w2 + < match rules { + Rules::Strict => good::GREAT_ALT, + Rules::ChessCom => good::GREAT_ALT_CHESSCOM, + } + }; // Tried and dropped (2026-10-28): a pawn offered as the only good move brilliant too — // finds 33.c3+!! of Kasparov — Topalov, but also marks 17.d5 of Steinitz — von // Bardeleben, which chess.com leaves unmarked. - (only_move && f.great_shape(rules)).then_some(Judgement::Great) + if !f.great_shape(rules, bans) { + return None; + } + if rules == Rules::Strict { + return only_move(good::GAP).then_some(Judgement::Great); + } + // How hard the move was to find: unknown (no shallow search) is not hard. + let at_least = |t: Option| t.is_some_and(|t| ply.difficulty.is_some_and(|d| d >= t)); + if at_least(hard.brilliant) && only_move(hard.brilliant_gap) { + Some(Judgement::Brilliant) + } else if only_move(hard.gap) && (hard.great.is_none() || at_least(hard.great)) { + Some(Judgement::Great) + } else { + None + } } /// `after` (the move played) mates `mover`'s opponent in fewer moves than `other` (the @@ -371,6 +453,9 @@ pub struct Ply { pub features: Option, /// The best other move's evaluation, when the move played was the best. pub second: Option, + /// How hard the move was to find ([`Hardness::measure`]), when a shallow search was + /// made. + pub difficulty: Option, } #[derive(Clone, Debug, Default, PartialEq)] @@ -417,6 +502,17 @@ impl Report { plies: &[Ply], phases: Phases, rules: Rules, + ) -> Report { + Self::build_tuned(evals, plies, phases, rules, Hardness::default()) + } + + /// [`Report::build_with`] where the difficulty of a move counts as `hard` says. + pub fn build_tuned( + evals: &[Option], + plies: &[Ply], + phases: Phases, + rules: Rules, + hard: Hardness, ) -> Report { let n = plies.len().min(evals.len().saturating_sub(1)); let mut report = Report { @@ -454,7 +550,7 @@ impl Report { judge(before, after, ply.mover) }; let good = if error.is_none() { - note(before, after, &ply, rules) + note(before, after, &ply, rules, hard) } else { None }; @@ -596,6 +692,7 @@ mod tests { best: false, features: None, second: None, + difficulty: None, } } @@ -776,6 +873,7 @@ mod tests { ..Default::default() }), second, + difficulty: None, } } diff --git a/crates/prep/src/lib.rs b/crates/prep/src/lib.rs index ec4b5b8..04cdcac 100644 --- a/crates/prep/src/lib.rs +++ b/crates/prep/src/lib.rs @@ -480,6 +480,7 @@ impl PrepReport { played: None, others: Vec::new(), known: None, + shallow: None, }) .collect() } @@ -987,6 +988,7 @@ mod tests { pv, depth: 12, second: None, + shallow: None, }, nps: 0, }; diff --git a/crates/uci/src/bin/fake_uci.rs b/crates/uci/src/bin/fake_uci.rs index cb94eca..9c504b9 100644 --- a/crates/uci/src/bin/fake_uci.rs +++ b/crates/uci/src/bin/fake_uci.rs @@ -26,6 +26,10 @@ //! --ignore-quit ignore `quit` (must be killed) //! --hash-memory scores depend on the position and on the searches made //! since the last `ucinewgame` (as a hash kept between them) +//! --searchmoves honour `go ... searchmoves M...`: M's first move is the +//! best move, scored 30 cp lower (a worse move) +//! --shallow N MOVE `go nodes n` with n < N (no `searchmoves`): MOVE is the +//! best move (a shallow search choosing another move) //! //! Protocol violations by the GUI (`position`/`go`/`setoption`/`ucinewgame` //! during a search) are reported as `info string ERROR ...`. @@ -54,6 +58,8 @@ struct Cfg { mate: bool, ignore_quit: bool, hash_memory: bool, + searchmoves: bool, + shallow: Option<(u64, String)>, } fn parse_args() -> Cfg { @@ -83,6 +89,11 @@ fn parse_args() -> Cfg { "--mate" => c.mate = true, "--ignore-quit" => c.ignore_quit = true, "--hash-memory" => c.hash_memory = true, + "--searchmoves" => c.searchmoves = true, + "--shallow" => { + let n = num(args.next()); + c.shallow = args.next().map(|m| (n, m)); + } other => { eprintln!("fake_uci: unknown flag {other}"); std::process::exit(2); @@ -281,14 +292,34 @@ fn main() { // `go nodes N`: a short search that ends by itself, like a real one. .or_else(|| toks.contains(&"nodes").then_some(3)); since_new_game += 1; - let bias = if cfg.hash_memory { + let mut bias = if cfg.hash_memory { let of_position = marker.bytes().map(i32::from).sum::() % 97; of_position + 1000 * since_new_game } else { 0 }; + let among = toks + .iter() + .position(|&t| t == "searchmoves") + .and_then(|p| toks.get(p + 1)); + let nodes: Option = toks + .iter() + .position(|&t| t == "nodes") + .and_then(|p| toks.get(p + 1)) + .and_then(|v| v.parse().ok()); + let mut shown = marker.clone(); + match (among, &cfg.shallow) { + (Some(m), _) if cfg.searchmoves => { + shown = (*m).to_owned(); + bias -= 30; + } + (None, Some((below, best))) if nodes.is_some_and(|n| n < *below) => { + shown = best.clone(); + } + _ => {} + } search = Some(Search { - marker: marker.clone(), + marker: shown, depth: 0, max_depth, bias,