Review: brilliant (!!) and great (!) moves; Android board shows move marks
A sound piece sacrifice is !!, the only good move that turns the game is !, by the rules of docs/research/brilliant-moves.md. Sacrifices come from a static exchange count over the board (features.rs); the best other move comes from a second engine search (searchmoves) only where the move played was the engine's best and could be either. The marks go wherever errors go: report, notation, graph, board badge, and into the PGN as $3/$1 unless the author's sign is there. An older analysis is filled in by Update without evaluating it again. The Android board now draws the move's mark in the corner of its square, as the desktop does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fb4e7ba330
commit
1aa85f59d3
26 changed files with 1398 additions and 119 deletions
249
crates/game-review/src/features.rs
Normal file
249
crates/game-review/src/features.rs
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
//! What a move does on the board, without an engine: a piece offered (a sacrifice), a
|
||||
//! piece taken back or saved, a mate (docs/research/brilliant-moves.md §3.1, §4). The
|
||||
//! engine's evaluations then say whether it was brilliant (!!) or great (!).
|
||||
|
||||
use chess_core::shakmaty::{Bitboard, Board, Chess, Color, Move, Position, Role, Square};
|
||||
|
||||
/// The move as the rules of !! and ! see it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct MoveFeatures {
|
||||
/// Legal moves in the position: one is a forced move, never marked.
|
||||
pub legal: usize,
|
||||
/// The mover was in check.
|
||||
pub check: bool,
|
||||
pub promotion: bool,
|
||||
/// The move mates.
|
||||
pub mates: bool,
|
||||
/// Takes back on the square where the opponent has just taken.
|
||||
pub recapture: bool,
|
||||
/// After the move the opponent can win a piece (a knight or more) for at least two
|
||||
/// points more than the move took; a piece that was lost anyway does not count.
|
||||
pub sacrifice: bool,
|
||||
/// A piece (not the king) under attack moves away without loss.
|
||||
pub escape: bool,
|
||||
/// A capture that wins two points or more.
|
||||
pub winning_capture: bool,
|
||||
}
|
||||
|
||||
impl MoveFeatures {
|
||||
/// `prev`: the opponent's move just before (for a recapture).
|
||||
pub fn of(before: &Chess, m: &Move, prev: Option<&Move>) -> MoveFeatures {
|
||||
let mover = before.turn();
|
||||
let mut after = before.clone();
|
||||
after.play_unchecked(*m);
|
||||
let taken = m.capture().map_or(0, value);
|
||||
// The opponent's best gain on each of the mover's pieces after the move.
|
||||
let threats = threats(&after);
|
||||
let threat = threats.iter().map(|t| t.0).max().unwrap_or(0);
|
||||
let offered = threats
|
||||
.iter()
|
||||
.filter(|t| t.0 == threat)
|
||||
.map(|t| t.1)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
// The moved piece was hanging where it stood: losing it is no sacrifice.
|
||||
let from_threat = m
|
||||
.from()
|
||||
.map_or(0, |f| pseudo_threat(before.board(), f, mover.other()));
|
||||
let lost_anyway = from_threat >= 2;
|
||||
let on_target = threats.iter().find(|t| t.2 == m.to()).map_or(0, |t| t.0);
|
||||
let gain = taken - on_target;
|
||||
MoveFeatures {
|
||||
legal: before.legal_moves().len(),
|
||||
check: before.is_check(),
|
||||
promotion: m.is_promotion(),
|
||||
mates: after.is_checkmate(),
|
||||
recapture: m.is_capture() && prev.is_some_and(|p| p.is_capture() && p.to() == m.to()),
|
||||
sacrifice: offered >= 3 && taken - threat <= -2 && !lost_anyway,
|
||||
escape: lost_anyway && from_threat < 900 && gain >= 0,
|
||||
winning_capture: m.is_capture() && gain >= 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Could be brilliant: a sacrifice by choice.
|
||||
pub fn brilliant_shape(&self) -> bool {
|
||||
self.sacrifice && self.legal > 1 && !self.check && !self.promotion
|
||||
}
|
||||
|
||||
/// Could be great: not a forced, obvious or finishing move.
|
||||
pub fn great_shape(&self) -> bool {
|
||||
self.legal > 1 && !self.mates && !self.escape && !self.recapture && !self.winning_capture
|
||||
}
|
||||
|
||||
/// Worth asking the engine for the best other move.
|
||||
pub fn candidate(&self) -> bool {
|
||||
self.brilliant_shape() || self.great_shape()
|
||||
}
|
||||
}
|
||||
|
||||
/// Exchange values; the king's makes taking into a defended square never pay.
|
||||
fn value(r: Role) -> i32 {
|
||||
match r {
|
||||
Role::Pawn => 1,
|
||||
Role::Knight | Role::Bishop => 3,
|
||||
Role::Rook => 5,
|
||||
Role::Queen => 9,
|
||||
Role::King => 1000,
|
||||
}
|
||||
}
|
||||
|
||||
/// Static exchange on `sq`: what `side` gains taking first with the piece on `first`,
|
||||
/// both sides then taking with their cheapest piece and free to stop (x-rays count).
|
||||
fn see(board: &Board, sq: Square, first: Square, side: Color) -> i32 {
|
||||
let (Some(target), Some(attacker)) = (board.role_at(sq), board.role_at(first)) else {
|
||||
return 0;
|
||||
};
|
||||
let mut gains = vec![value(target)];
|
||||
let mut occupied = board.occupied() ^ Bitboard::from_square(first);
|
||||
let mut on_square = value(attacker);
|
||||
let mut turn = side.other();
|
||||
loop {
|
||||
let cheapest = (board.attacks_to(sq, turn, occupied) & occupied)
|
||||
.into_iter()
|
||||
.filter_map(|a| Some((value(board.role_at(a)?), a)))
|
||||
.min();
|
||||
let Some((v, a)) = cheapest else { break };
|
||||
let last = gains[gains.len() - 1];
|
||||
gains.push(on_square - last);
|
||||
on_square = v;
|
||||
occupied ^= Bitboard::from_square(a);
|
||||
turn = turn.other();
|
||||
}
|
||||
for d in (1..gains.len()).rev() {
|
||||
gains[d - 1] = -(-gains[d - 1]).max(gains[d]);
|
||||
}
|
||||
gains[0]
|
||||
}
|
||||
|
||||
/// The pieces (a knight or more) the side to move can win, with legal first captures:
|
||||
/// (gain, value of the piece, its square).
|
||||
fn threats(pos: &Chess) -> Vec<(i32, i32, Square)> {
|
||||
let us = pos.turn();
|
||||
let board = pos.board();
|
||||
let legal = pos.legal_moves();
|
||||
let mut out = Vec::new();
|
||||
for sq in board.by_color(us.other()) {
|
||||
let Some(r) = board.role_at(sq) else { continue };
|
||||
if matches!(r, Role::King | Role::Pawn) {
|
||||
continue;
|
||||
}
|
||||
let first = legal
|
||||
.iter()
|
||||
.filter(|m| m.to() == sq && m.is_capture() && !m.is_en_passant())
|
||||
.filter_map(|m| Some((value(m.role()), m.from()?)))
|
||||
.min();
|
||||
if let Some((_, from)) = first {
|
||||
let g = see(board, sq, from, us);
|
||||
if g > 0 {
|
||||
out.push((g, value(r), sq));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What `by` would win taking on `sq`, whoever is to move (a piece already hanging).
|
||||
fn pseudo_threat(board: &Board, sq: Square, by: Color) -> i32 {
|
||||
let first = board
|
||||
.attacks_to(sq, by, board.occupied())
|
||||
.into_iter()
|
||||
.filter_map(|a| Some((value(board.role_at(a)?), a)))
|
||||
.min();
|
||||
first.map_or(0, |(_, a)| see(board, sq, a, by).max(0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chess_core::shakmaty::fen::Fen;
|
||||
use chess_core::shakmaty::san::San;
|
||||
use chess_core::shakmaty::{CastlingMode, Chess};
|
||||
|
||||
fn position(fen: &str) -> Chess {
|
||||
fen.parse::<Fen>()
|
||||
.unwrap()
|
||||
.into_position(CastlingMode::Standard)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The features of the last of `moves` (SAN) played from `start`.
|
||||
fn last(start: Chess, moves: &str) -> MoveFeatures {
|
||||
let mut pos = start;
|
||||
let mut prev = None;
|
||||
let sans: Vec<&str> = moves
|
||||
.split_whitespace()
|
||||
.filter(|t| !t.ends_with('.'))
|
||||
.collect();
|
||||
for (i, san) in sans.iter().enumerate() {
|
||||
let m = san.parse::<San>().unwrap().to_move(&pos).unwrap();
|
||||
if i + 1 == sans.len() {
|
||||
return MoveFeatures::of(&pos, &m, prev.as_ref());
|
||||
}
|
||||
pos.play_unchecked(m);
|
||||
prev = Some(m);
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn features(fen: &str, san: &str) -> MoveFeatures {
|
||||
last(position(fen), san)
|
||||
}
|
||||
|
||||
const OPERA: &str = "1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 \
|
||||
7. Qb3 Qe7 8. Nc3 c6 9. Bg5 b5 10. Nxb5 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 \
|
||||
13. Rxd7 Rxd7 14. Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+";
|
||||
|
||||
#[test]
|
||||
fn a_queen_offered_for_mate_is_a_sacrifice() {
|
||||
let f = last(Chess::default(), OPERA);
|
||||
assert!(f.sacrifice && f.brilliant_shape(), "{f:?}");
|
||||
assert!(!f.mates && f.candidate());
|
||||
// 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(), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trades_and_good_captures_are_not_sacrifices() {
|
||||
let f = last(
|
||||
Chess::default(),
|
||||
"1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nxd4",
|
||||
);
|
||||
assert!(!f.sacrifice && f.recapture, "{f:?}");
|
||||
// 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() && !f.sacrifice,
|
||||
"{f:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_saved_or_lost_anyway_is_no_move_of_note() {
|
||||
// The bishop on c4 attacked by the pawn on d5: Bb3 saves it.
|
||||
let f = features("4k3/8/8/3p4/2B5/8/8/4K3 w - - 0 1", "Bb3");
|
||||
assert!(f.escape && !f.great_shape() && !f.sacrifice, "{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:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_no_one_can_legally_take_is_not_offered() {
|
||||
// The rook on d7 is pinned by the bishop: the knight on d5 is no offer to it.
|
||||
let f = features("4k3/3r4/8/8/B7/2N5/8/4K3 w - - 0 1", "Nd5");
|
||||
assert!(!f.sacrifice, "{f:?}");
|
||||
let f = features("4k3/3r4/8/8/8/2N5/8/4K3 w - - 0 1", "Nd5");
|
||||
assert!(f.sacrifice && f.brilliant_shape(), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exchanges_follow_the_cheapest_piece_and_x_rays() {
|
||||
// Rook takes a pawn defended by a pawn: loses four.
|
||||
let b = position("4k3/8/2p5/3p4/8/8/8/3RK3 w - - 0 1");
|
||||
assert_eq!(see(b.board(), Square::D5, Square::D1, Color::White), -4);
|
||||
// Two rooks behind each other against one defender: the pawn is won.
|
||||
let b = position("3rk3/8/8/3p4/8/8/3R4/3RK3 w - - 0 1");
|
||||
assert_eq!(see(b.board(), Square::D5, Square::D2, Color::White), 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,7 @@ use std::time::{Duration, Instant};
|
|||
|
||||
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side};
|
||||
|
||||
use crate::{Eval, PosEval};
|
||||
use crate::{Eval, PosEval, Second};
|
||||
|
||||
/// A node-limited search should never take this long; stop it if it does.
|
||||
const SEARCH_GUARD: Duration = Duration::from_secs(300);
|
||||
|
|
@ -18,6 +18,13 @@ pub struct Target {
|
|||
pub key: String,
|
||||
pub pos: EnginePosition,
|
||||
pub turn: Side,
|
||||
/// The move played here (UCI), when it could be brilliant or great: if it is the
|
||||
/// engine's best, a second search among `others` finds the best of the rest.
|
||||
pub played: Option<String>,
|
||||
/// The other legal moves (UCI).
|
||||
pub others: Vec<String>,
|
||||
/// The evaluation already there: only the second search is left.
|
||||
pub known: Option<PosEval>,
|
||||
}
|
||||
|
||||
/// How the engine searches.
|
||||
|
|
@ -79,68 +86,132 @@ pub fn run(
|
|||
let _ = handle.set_hash_mb(settings.hash_mb.max(1));
|
||||
let _ = handle.set_multipv(1);
|
||||
let _ = handle.new_game();
|
||||
for (i, t) in targets.into_iter().enumerate() {
|
||||
let id = SearchId(i as u64 + 1);
|
||||
handle
|
||||
.search(t.pos.clone(), id, SearchLimits::Nodes(settings.nodes))
|
||||
.map_err(|e| JobFailure::Engine(e.to_string()))?;
|
||||
let started = Instant::now();
|
||||
let mut stopping = false;
|
||||
let mut last: Option<uci::SearchInfo> = None;
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
handle.quit();
|
||||
return Ok(());
|
||||
}
|
||||
if !stopping && started.elapsed() > SEARCH_GUARD {
|
||||
let _ = handle.stop();
|
||||
stopping = true;
|
||||
}
|
||||
match handle.recv_timeout(Duration::from_millis(100)) {
|
||||
Some(EngineEvent::Info { search_id, info }) if search_id == id => {
|
||||
if info.multipv_index() == 1 && info.score.is_some() {
|
||||
let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact);
|
||||
if exact || last.is_none() {
|
||||
last = Some(info);
|
||||
}
|
||||
let mut next_id = 0;
|
||||
let mut search = |pos: &EnginePosition, among: Vec<String>| {
|
||||
next_id += 1;
|
||||
search_once(
|
||||
&handle,
|
||||
pos,
|
||||
SearchId(next_id),
|
||||
among,
|
||||
settings.nodes,
|
||||
cancel,
|
||||
)
|
||||
};
|
||||
for t in targets {
|
||||
let (mut eval, nps) = match t.known {
|
||||
Some(e) => (e, 0),
|
||||
None => {
|
||||
let Some((info, best)) = search(&t.pos, Vec::new())? else {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
handle.quit();
|
||||
return Ok(());
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let Some(score) = info.score else { continue };
|
||||
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
|
||||
if let Some(b) = best
|
||||
&& pv.first() != Some(&b)
|
||||
{
|
||||
pv = vec![b];
|
||||
}
|
||||
Some(EngineEvent::BestMove {
|
||||
search_id, best, ..
|
||||
}) if search_id == id => {
|
||||
if let Some(info) = last.take()
|
||||
&& let Some(score) = info.score
|
||||
{
|
||||
let eval = Eval::from_white_eval(score.to_white(t.turn).eval);
|
||||
let mut pv: Vec<String> = info.pv.iter().take(12).cloned().collect();
|
||||
if let Some(b) = best
|
||||
&& pv.first() != Some(&b)
|
||||
{
|
||||
pv = vec![b];
|
||||
}
|
||||
on_event(JobEvent::Eval {
|
||||
key: t.key,
|
||||
eval: PosEval {
|
||||
eval,
|
||||
pv,
|
||||
depth: info.depth.unwrap_or(0),
|
||||
},
|
||||
nps: info.nps.unwrap_or(0),
|
||||
let eval = PosEval {
|
||||
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
|
||||
pv,
|
||||
depth: info.depth.unwrap_or(0),
|
||||
second: None,
|
||||
};
|
||||
(eval, info.nps.unwrap_or(0))
|
||||
}
|
||||
};
|
||||
// The move played is the engine's best: what the best of the others gives says
|
||||
// whether it was the only good move, or a sacrifice when nothing else won.
|
||||
let mover = match t.turn {
|
||||
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)
|
||||
{
|
||||
match search(&t.pos, t.others.clone())? {
|
||||
// An engine that ignores `searchmoves` answers with the move played:
|
||||
// no second move then.
|
||||
Some((info, best))
|
||||
if best.as_ref() != Some(played) && info.pv.first() != Some(played) =>
|
||||
{
|
||||
if let Some(score) = info.score {
|
||||
eval.second = Some(Second {
|
||||
without: played.clone(),
|
||||
eval: Eval::from_white_eval(score.to_white(t.turn).eval),
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
Some(EngineEvent::Terminated(reason)) => {
|
||||
return Err(JobFailure::Terminated(reason));
|
||||
None if cancel.load(Ordering::Relaxed) => {
|
||||
handle.quit();
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
on_event(JobEvent::Eval {
|
||||
key: t.key,
|
||||
eval,
|
||||
nps,
|
||||
});
|
||||
}
|
||||
handle.quit();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One node-limited search: its last full line and the best move. `None` when it gave
|
||||
/// no line or `cancel` was set.
|
||||
fn search_once(
|
||||
handle: &uci::EngineHandle,
|
||||
pos: &EnginePosition,
|
||||
id: SearchId,
|
||||
among: Vec<String>,
|
||||
nodes: u64,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<Option<(uci::SearchInfo, Option<String>)>, JobFailure> {
|
||||
handle
|
||||
.search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among)
|
||||
.map_err(|e| JobFailure::Engine(e.to_string()))?;
|
||||
let started = Instant::now();
|
||||
let mut stopping = false;
|
||||
let mut last: Option<uci::SearchInfo> = None;
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Ok(None);
|
||||
}
|
||||
if !stopping && started.elapsed() > SEARCH_GUARD {
|
||||
let _ = handle.stop();
|
||||
stopping = true;
|
||||
}
|
||||
match handle.recv_timeout(Duration::from_millis(100)) {
|
||||
Some(EngineEvent::Info { search_id, info }) if search_id == id => {
|
||||
if info.multipv_index() == 1 && info.score.is_some() {
|
||||
let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact);
|
||||
if exact || last.is_none() {
|
||||
last = Some(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(EngineEvent::BestMove {
|
||||
search_id, best, ..
|
||||
}) if search_id == id => {
|
||||
return Ok(last.map(|info| (info, best.map(|b| b.to_string()))));
|
||||
}
|
||||
Some(EngineEvent::Terminated(reason)) => {
|
||||
return Err(JobFailure::Terminated(reason));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -12,14 +12,16 @@ use std::path::{Path, PathBuf};
|
|||
|
||||
use chess_core::shakmaty::san::SanPlus;
|
||||
use chess_core::shakmaty::uci::UciMove;
|
||||
use chess_core::shakmaty::{Chess, Color, Move, Position};
|
||||
use chess_core::shakmaty::{CastlingMode, Chess, Color, Move, Position};
|
||||
use chess_core::{Annotation, CommentPart, Game, NodeId, parse_comment};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uci::{EnginePosition, Side};
|
||||
|
||||
mod features;
|
||||
mod job;
|
||||
pub mod report;
|
||||
|
||||
pub use features::MoveFeatures;
|
||||
pub use job::{JobEvent, JobFailure, JobSettings, Target, run};
|
||||
pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats};
|
||||
|
||||
|
|
@ -32,6 +34,18 @@ pub struct PosEval {
|
|||
pub pv: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub depth: u32,
|
||||
/// The best move but the one played, when that one was the engine's best and could
|
||||
/// be brilliant or great (older analyses have none).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub second: Option<Second>,
|
||||
}
|
||||
|
||||
/// The best of the other moves: how the position stood without the move played.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Second {
|
||||
/// The move left out (UCI).
|
||||
pub without: String,
|
||||
pub eval: Eval,
|
||||
}
|
||||
|
||||
/// Where the evaluations came from.
|
||||
|
|
@ -51,7 +65,7 @@ struct CacheFile {
|
|||
|
||||
const CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// An engine assessment of a main-line move.
|
||||
/// An engine assessment of a main-line move: an error, or a move of note (!!, !).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Mark {
|
||||
pub judgement: Judgement,
|
||||
|
|
@ -79,6 +93,11 @@ pub struct GameAnalysis {
|
|||
values: Vec<Option<Eval>>,
|
||||
/// Positions without legal moves (mate, stalemate): no engine needed.
|
||||
terminal: Vec<bool>,
|
||||
/// What each move of the line does on the board (`features[i]`: the move from
|
||||
/// position `i`); `None` for a null move.
|
||||
features: Vec<Option<MoveFeatures>>,
|
||||
/// The move played from each position of the line (UCI; `None` for a null move).
|
||||
played: Vec<Option<String>>,
|
||||
pub report: Report,
|
||||
pub marks: HashMap<NodeId, Mark>,
|
||||
}
|
||||
|
|
@ -98,6 +117,8 @@ impl GameAnalysis {
|
|||
movers: Vec::new(),
|
||||
values: Vec::new(),
|
||||
terminal: Vec::new(),
|
||||
features: Vec::new(),
|
||||
played: Vec::new(),
|
||||
report: Report::default(),
|
||||
marks: HashMap::new(),
|
||||
};
|
||||
|
|
@ -143,6 +164,19 @@ impl GameAnalysis {
|
|||
self.terminal.iter().filter(|t| !**t).count()
|
||||
}
|
||||
|
||||
/// Engine searches a full analysis is expected to make, for its time: one per
|
||||
/// position, and a second one for about half of the moves that could be brilliant or
|
||||
/// great (those the engine finds best too).
|
||||
pub fn searches(&self) -> usize {
|
||||
let candidates = self
|
||||
.features
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|f| f.candidate())
|
||||
.count();
|
||||
self.positions() + candidates / 2
|
||||
}
|
||||
|
||||
/// 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()) {
|
||||
|
|
@ -165,18 +199,78 @@ impl GameAnalysis {
|
|||
self.meta = Some(ReviewMeta { nodes, ..meta });
|
||||
self.rebuild(game);
|
||||
(0..self.line.len())
|
||||
.filter(|i| self.values[*i].is_none())
|
||||
.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)
|
||||
|| known.is_none() && self.values[i].is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let here = game.position(self.line[i])?;
|
||||
// The move played, when it could be brilliant or great.
|
||||
let played = self
|
||||
.features
|
||||
.get(i)
|
||||
.copied()
|
||||
.flatten()
|
||||
.filter(|f| f.candidate())
|
||||
.and_then(|_| self.played.get(i).cloned().flatten());
|
||||
let others = match &played {
|
||||
Some(p) => here
|
||||
.legal_moves()
|
||||
.iter()
|
||||
.map(|m| m.to_uci(CastlingMode::Standard).to_string())
|
||||
.filter(|u| u != p)
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let (key, pos) = position_key(game, self.line[i])?;
|
||||
let turn = match game.position(self.line[i])?.turn() {
|
||||
let turn = match here.turn() {
|
||||
Color::White => Side::White,
|
||||
Color::Black => Side::Black,
|
||||
};
|
||||
Some(Target { key, pos, turn })
|
||||
Some(Target {
|
||||
key,
|
||||
pos,
|
||||
turn,
|
||||
played,
|
||||
others,
|
||||
known,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let (Some(e), Some(Some(played)), Some(Some(f))) = (
|
||||
self.evals.get(&self.keys[i]),
|
||||
self.played.get(i),
|
||||
self.features.get(i),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
f.candidate()
|
||||
&& e.pv.first() == Some(played)
|
||||
&& report::worth_second(e.eval, self.movers[i])
|
||||
&& e.second.as_ref().map(|s| &s.without) != Some(played)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn seconds_missing(&self) -> usize {
|
||||
if self.meta.as_ref().is_none_or(|m| m.nodes == 0) {
|
||||
return 0;
|
||||
}
|
||||
(0..self.played.len())
|
||||
.filter(|i| self.second_missing(*i))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Takes in what the engine job reported.
|
||||
pub fn apply(&mut self, event: JobEvent) {
|
||||
match event {
|
||||
|
|
@ -217,14 +311,38 @@ impl GameAnalysis {
|
|||
.or_else(|| positions.get(i).and_then(terminal_eval))
|
||||
})
|
||||
.collect();
|
||||
let moves: Vec<Option<Move>> = (1..self.line.len())
|
||||
.map(|i| match game.game_move(self.line[i]).map(|m| m.kind) {
|
||||
Some(chess_core::MoveKind::Normal(m)) => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
self.features = (0..moves.len())
|
||||
.map(|i| {
|
||||
let (m, before) = (moves[i].as_ref()?, positions.get(i)?);
|
||||
let prev = i.checked_sub(1).and_then(|p| moves[p].as_ref());
|
||||
Some(MoveFeatures::of(before, m, prev))
|
||||
})
|
||||
.collect();
|
||||
self.played = (1..self.line.len())
|
||||
.map(|i| game.game_move(self.line[i]).and_then(|m| m.uci()))
|
||||
.collect();
|
||||
let mut plies = Vec::with_capacity(self.line.len().saturating_sub(1));
|
||||
for i in 1..self.line.len() {
|
||||
let mv = game.game_move(self.line[i]);
|
||||
let best = self.evals.get(&self.keys[i - 1]).and_then(|e| e.pv.first());
|
||||
let e = self.evals.get(&self.keys[i - 1]);
|
||||
let best = e.and_then(|e| e.pv.first());
|
||||
let played = mv.and_then(|m| m.uci());
|
||||
plies.push(Ply {
|
||||
mover: positions.get(i - 1).map_or(Color::White, |p| p.turn()),
|
||||
null: mv.is_none_or(|m| m.is_null()),
|
||||
best: best.is_some() && mv.and_then(|m| m.uci()).as_ref() == best,
|
||||
best: best.is_some() && played.as_ref() == best,
|
||||
features: self.features[i - 1],
|
||||
// Only for the move played now (the line may have changed since).
|
||||
second: e
|
||||
.and_then(|e| e.second.as_ref())
|
||||
.filter(|s| Some(&s.without) == played.as_ref())
|
||||
.map(|s| s.eval),
|
||||
});
|
||||
}
|
||||
self.movers = plies.iter().map(|p| p.mover).collect();
|
||||
|
|
@ -233,8 +351,9 @@ impl GameAnalysis {
|
|||
for (i, j) in self.report.judgements.iter().enumerate() {
|
||||
let Some(judgement) = *j else { continue };
|
||||
let (base, node) = (self.line[i], self.line[i + 1]);
|
||||
// A better line only for an error: a good move was the best one.
|
||||
let (best, best_san) = match (self.evals.get(&self.keys[i]), positions.get(i)) {
|
||||
(Some(e), Some(root)) => parse_pv(root, &e.pv),
|
||||
(Some(e), Some(root)) if judgement.is_error() => parse_pv(root, &e.pv),
|
||||
_ => (Vec::new(), Vec::new()),
|
||||
};
|
||||
let best_label = best_san.first().and_then(|san| {
|
||||
|
|
@ -263,7 +382,11 @@ impl GameAnalysis {
|
|||
/// the player best answers, the first two moves of the engine line from the position
|
||||
/// after the move (shown as arrows, as on Lichess).
|
||||
pub fn refutation(&self, node: NodeId, game: &Game) -> Vec<Move> {
|
||||
if !self.marks.contains_key(&node) {
|
||||
if !self
|
||||
.marks
|
||||
.get(&node)
|
||||
.is_some_and(|m| m.judgement.is_error())
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let (Some(i), Some(pos)) = (
|
||||
|
|
@ -397,6 +520,7 @@ impl GameAnalysis {
|
|||
eval,
|
||||
pv: Vec::new(),
|
||||
depth: 0,
|
||||
second: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
|
@ -521,6 +645,7 @@ mod tests {
|
|||
eval: Eval::Cp(20 - i as i32 * 300),
|
||||
pv: vec!["e2e4".into()],
|
||||
depth: 10,
|
||||
second: None,
|
||||
},
|
||||
nps: 0,
|
||||
});
|
||||
|
|
@ -541,7 +666,13 @@ mod tests {
|
|||
engine: "Fake".into(),
|
||||
nodes: 250,
|
||||
};
|
||||
assert!(c.begin(&g, fast.clone(), false).is_empty());
|
||||
// Nothing left to evaluate; 1.e4, the engine's best, still wants the best other
|
||||
// move (an analysis from before !! and !).
|
||||
assert_eq!(c.seconds_missing(), 1);
|
||||
let left = c.begin(&g, fast.clone(), false);
|
||||
assert_eq!(left.len(), 1);
|
||||
assert!(left[0].known.is_some() && left[0].played.as_deref() == Some("e2e4"));
|
||||
assert!(!left[0].others.is_empty() && !left[0].others.contains(&"e2e4".to_string()));
|
||||
assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(1000));
|
||||
c.begin(&g, fast, true);
|
||||
assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(250));
|
||||
|
|
@ -563,6 +694,7 @@ mod tests {
|
|||
eval: Eval::Cp(20),
|
||||
pv: vec![],
|
||||
depth: 1,
|
||||
second: None,
|
||||
},
|
||||
nps: 0,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -117,6 +117,87 @@ pub enum Judgement {
|
|||
Inaccuracy,
|
||||
Mistake,
|
||||
Blunder,
|
||||
/// The only good move, or one that turned the game (!).
|
||||
Great,
|
||||
/// A sound sacrifice of a piece (!!).
|
||||
Brilliant,
|
||||
}
|
||||
|
||||
impl Judgement {
|
||||
/// An error (?!, ?, ??), not a move of note.
|
||||
pub fn is_error(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Judgement::Inaccuracy | Judgement::Mistake | Judgement::Blunder
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The thresholds of !! and ! in the mover's win % (docs/research/brilliant-moves.md §10).
|
||||
mod good {
|
||||
/// At most this behind the engine's best move.
|
||||
pub const NEAR_BEST: f64 = 2.0;
|
||||
/// !!: the position after the sacrifice is at least this good.
|
||||
pub const SOUND_AFTER: f64 = 45.0;
|
||||
/// !!: without the move the game was not won anyway.
|
||||
pub const WON_ANYWAY: f64 = 90.0;
|
||||
/// !: every other move loses at least this much.
|
||||
pub const GAP: f64 = 10.0;
|
||||
/// !: lost below, won above (the move changes which).
|
||||
pub const LOST: f64 = 33.0;
|
||||
pub const WON: f64 = 67.0;
|
||||
/// !: the position after the move is not lost, and the best other move did not win.
|
||||
pub const GREAT_AFTER: f64 = 40.0;
|
||||
pub const GREAT_ALT: f64 = 75.0;
|
||||
/// An opponent's move losing this much (or judged a mistake or a blunder: near a mate
|
||||
/// the win % hardly moves) starts a new combination.
|
||||
pub const OPPONENT_ERROR: f64 = 10.0;
|
||||
/// Below this the mover's position is too bad for either mark: no second search.
|
||||
/// (The lower of the two floors after the move, !'s, less the step from the best.)
|
||||
pub const SECOND_FROM: f64 = GREAT_AFTER - NEAR_BEST;
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
eval.win_percent(mover) >= good::SECOND_FROM
|
||||
}
|
||||
|
||||
/// Lost, equal, won (0, 1, 2).
|
||||
fn outcome(win: f64) -> u8 {
|
||||
if win < good::LOST {
|
||||
0
|
||||
} else if win > good::WON {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
/// Brilliant or great, from the evaluations around the move (before the combination rule).
|
||||
fn note(before: Eval, after: Eval, ply: &Ply) -> Option<Judgement> {
|
||||
let f = ply.features?;
|
||||
let (wb, wa) = (before.win_percent(ply.mover), after.win_percent(ply.mover));
|
||||
let loss = wb - wa;
|
||||
let second = ply.second.map(|e| e.win_percent(ply.mover));
|
||||
// Without the move: the best other move, or the best move when another was played.
|
||||
let without = if ply.best { second } else { Some(wb) };
|
||||
if f.brilliant_shape()
|
||||
&& (ply.best || loss <= good::NEAR_BEST)
|
||||
&& wa >= good::SOUND_AFTER
|
||||
&& without.is_some_and(|w| w < good::WON_ANYWAY)
|
||||
{
|
||||
return Some(Judgement::Brilliant);
|
||||
}
|
||||
let w2 = second?;
|
||||
(f.great_shape()
|
||||
&& ply.best
|
||||
&& loss <= good::NEAR_BEST
|
||||
&& wb - w2 >= good::GAP
|
||||
&& outcome(wa) > outcome(w2)
|
||||
&& wa >= good::GREAT_AFTER
|
||||
&& w2 < good::GREAT_ALT)
|
||||
.then_some(Judgement::Great)
|
||||
}
|
||||
|
||||
/// Judgement of a move from the evaluations before and after it.
|
||||
|
|
@ -221,6 +302,10 @@ pub struct Ply {
|
|||
pub null: bool,
|
||||
/// The move played equals the engine's best move (never judged as an error).
|
||||
pub best: bool,
|
||||
/// What the move does on the board (`None`: not known, never !! or !).
|
||||
pub features: Option<crate::MoveFeatures>,
|
||||
/// The best other move's evaluation, when the move played was the best.
|
||||
pub second: Option<Eval>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
|
|
@ -228,6 +313,8 @@ pub struct SideStats {
|
|||
pub inaccuracies: u32,
|
||||
pub mistakes: u32,
|
||||
pub blunders: u32,
|
||||
pub great: u32,
|
||||
pub brilliant: u32,
|
||||
/// Average centipawn loss.
|
||||
pub acpl: Option<u32>,
|
||||
pub accuracy: Option<f64>,
|
||||
|
|
@ -264,6 +351,9 @@ impl Report {
|
|||
..Report::default()
|
||||
};
|
||||
let mut losses: [Vec<i32>; 2] = [Vec::new(), Vec::new()];
|
||||
// Moves that passed !! or ! before the combination rule, and each move's loss.
|
||||
let mut noted = vec![false; n];
|
||||
let mut lost = vec![0.0; n];
|
||||
for i in 0..n {
|
||||
let ply = plies[i];
|
||||
let (Some(before), Some(after)) = (evals[i], evals[i + 1]) else {
|
||||
|
|
@ -272,11 +362,29 @@ impl Report {
|
|||
if ply.null {
|
||||
continue;
|
||||
}
|
||||
let j = if ply.best {
|
||||
lost[i] = before.win_percent(ply.mover) - after.win_percent(ply.mover);
|
||||
let error = if ply.best {
|
||||
None
|
||||
} else {
|
||||
judge(before, after, ply.mover)
|
||||
};
|
||||
let good = if error.is_none() {
|
||||
note(before, after, &ply)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
noted[i] = good.is_some();
|
||||
// One mark a combination: the moves that go on with it after a mark are not
|
||||
// marked again, unless the opponent erred in between.
|
||||
let erred = |k: usize| {
|
||||
lost[k] >= good::OPPONENT_ERROR
|
||||
|| matches!(
|
||||
report.judgements[k],
|
||||
Some(Judgement::Mistake | Judgement::Blunder)
|
||||
)
|
||||
};
|
||||
let goes_on = i >= 2 && noted[i - 2] && !erred(i - 1);
|
||||
let j = error.or(good.filter(|_| !goes_on));
|
||||
report.judgements[i] = j;
|
||||
let stats = match ply.mover {
|
||||
Color::White => &mut report.white,
|
||||
|
|
@ -286,6 +394,8 @@ impl Report {
|
|||
Some(Judgement::Inaccuracy) => stats.inaccuracies += 1,
|
||||
Some(Judgement::Mistake) => stats.mistakes += 1,
|
||||
Some(Judgement::Blunder) => stats.blunders += 1,
|
||||
Some(Judgement::Great) => stats.great += 1,
|
||||
Some(Judgement::Brilliant) => stats.brilliant += 1,
|
||||
None => {}
|
||||
}
|
||||
let loss = (before.cp_for(ply.mover) - after.cp_for(ply.mover)).max(0);
|
||||
|
|
@ -398,6 +508,8 @@ mod tests {
|
|||
mover,
|
||||
null: false,
|
||||
best: false,
|
||||
features: None,
|
||||
second: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -566,4 +678,114 @@ mod tests {
|
|||
assert_eq!(p.of(0), Phase::Opening);
|
||||
assert_eq!(p.of(mid), Phase::Middlegame);
|
||||
}
|
||||
|
||||
fn noted(mover: Color, sacrifice: bool, second: Option<Eval>) -> Ply {
|
||||
Ply {
|
||||
mover,
|
||||
null: false,
|
||||
best: true,
|
||||
features: Some(crate::MoveFeatures {
|
||||
legal: 30,
|
||||
sacrifice,
|
||||
..Default::default()
|
||||
}),
|
||||
second,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sound_sacrifice_is_brilliant_unless_the_game_was_won_anyway() {
|
||||
let w = Color::White;
|
||||
let evals = [Some(Eval::Cp(100)), Some(Eval::Cp(100))];
|
||||
let r = Report::build(
|
||||
&evals,
|
||||
&[noted(w, true, Some(Eval::Cp(-100)))],
|
||||
Phases::default(),
|
||||
);
|
||||
assert_eq!(r.judgements[0], Some(Judgement::Brilliant));
|
||||
assert_eq!(r.white.brilliant, 1);
|
||||
// Another move won as well: no !!.
|
||||
let r = Report::build(
|
||||
&evals,
|
||||
&[noted(w, true, Some(Eval::Cp(800)))],
|
||||
Phases::default(),
|
||||
);
|
||||
assert_eq!(r.judgements[0], None);
|
||||
// No best other move known (an older analysis): nothing said.
|
||||
let r = Report::build(&evals, &[noted(w, true, None)], Phases::default());
|
||||
assert_eq!(r.judgements[0], None);
|
||||
// Unsound: the position after it is bad.
|
||||
let bad = [Some(Eval::Cp(-200)), Some(Eval::Cp(-200))];
|
||||
let r = Report::build(
|
||||
&bad,
|
||||
&[noted(w, true, Some(Eval::Cp(-400)))],
|
||||
Phases::default(),
|
||||
);
|
||||
assert_eq!(r.judgements[0], None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_only_move_that_turns_the_game_is_great() {
|
||||
let w = Color::White;
|
||||
let evals = [Some(Eval::Cp(300)), Some(Eval::Cp(300))];
|
||||
let r = Report::build(
|
||||
&evals,
|
||||
&[noted(w, false, Some(Eval::Cp(-300)))],
|
||||
Phases::default(),
|
||||
);
|
||||
assert_eq!(r.judgements[0], Some(Judgement::Great));
|
||||
assert_eq!(r.white.great, 1);
|
||||
// Others are worse but still win: not great.
|
||||
let r = Report::build(
|
||||
&evals,
|
||||
&[noted(w, false, Some(Eval::Cp(250)))],
|
||||
Phases::default(),
|
||||
);
|
||||
assert_eq!(r.judgements[0], None);
|
||||
// Not the engine's move: never great.
|
||||
let mut p = noted(w, false, Some(Eval::Cp(-300)));
|
||||
p.best = false;
|
||||
assert_eq!(
|
||||
Report::build(&evals, &[p], Phases::default()).judgements[0],
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_combination_is_marked_once_unless_the_opponent_errs() {
|
||||
let (w, b) = (Color::White, Color::Black);
|
||||
let quiet = ply(b);
|
||||
let great = || noted(w, false, Some(Eval::Cp(-300)));
|
||||
let evals = [Some(Eval::Cp(300)); 4];
|
||||
let r = Report::build(&evals, &[great(), quiet, great()], Phases::default());
|
||||
assert_eq!(r.judgements, vec![Some(Judgement::Great), None, None]);
|
||||
// Black blunders in between: a new mark.
|
||||
let evals = [
|
||||
Some(Eval::Cp(300)),
|
||||
Some(Eval::Cp(300)),
|
||||
Some(Eval::Cp(900)),
|
||||
Some(Eval::Cp(900)),
|
||||
];
|
||||
let mut strong = great();
|
||||
strong.second = Some(Eval::Cp(-300));
|
||||
let r = Report::build(&evals, &[great(), quiet, strong], Phases::default());
|
||||
assert_eq!(r.judgements[1], Some(Judgement::Blunder));
|
||||
assert_eq!(r.judgements[0], Some(Judgement::Great));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opponent_letting_a_mate_in_starts_a_new_combination() {
|
||||
// Near a mate the win % hardly moves: Black's move loses little of it but lets a
|
||||
// forced mate in, a mistake; White's next move of note is marked again.
|
||||
let (w, b) = (Color::White, Color::Black);
|
||||
let mate = Some(Eval::Mate {
|
||||
white: true,
|
||||
moves: 3,
|
||||
});
|
||||
let evals = [Some(Eval::Cp(900)), Some(Eval::Cp(900)), mate, mate];
|
||||
let great = || noted(w, false, Some(Eval::Cp(-300)));
|
||||
let r = Report::build(&evals, &[great(), ply(b), great()], Phases::default());
|
||||
assert_eq!(r.judgements[1], Some(Judgement::Mistake));
|
||||
assert_eq!(r.judgements[2], Some(Judgement::Great));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,12 +22,16 @@ use shakmaty::Color;
|
|||
use crate::EngineLine;
|
||||
use crate::engine::{line_with, pawns};
|
||||
|
||||
/// How bad a move was.
|
||||
/// How bad a move was, or that it was of note.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
|
||||
pub enum MoveJudgement {
|
||||
Inaccuracy,
|
||||
Mistake,
|
||||
Blunder,
|
||||
/// The only good move, or one that turned the game (!).
|
||||
Great,
|
||||
/// A sound sacrifice of a piece (!!).
|
||||
Brilliant,
|
||||
}
|
||||
|
||||
impl From<Judgement> for MoveJudgement {
|
||||
|
|
@ -36,6 +40,8 @@ impl From<Judgement> for MoveJudgement {
|
|||
Judgement::Inaccuracy => MoveJudgement::Inaccuracy,
|
||||
Judgement::Mistake => MoveJudgement::Mistake,
|
||||
Judgement::Blunder => MoveJudgement::Blunder,
|
||||
Judgement::Great => MoveJudgement::Great,
|
||||
Judgement::Brilliant => MoveJudgement::Brilliant,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -59,6 +65,8 @@ pub struct SideReview {
|
|||
pub inaccuracies: u32,
|
||||
pub mistakes: u32,
|
||||
pub blunders: u32,
|
||||
pub great: u32,
|
||||
pub brilliant: u32,
|
||||
/// Average centipawn loss.
|
||||
pub acpl: Option<u32>,
|
||||
/// Accuracy 0..100 (only when every position is evaluated).
|
||||
|
|
@ -68,7 +76,8 @@ pub struct SideReview {
|
|||
pub endgame: Option<f64>,
|
||||
}
|
||||
|
||||
/// An inaccuracy, mistake or blunder of the main line.
|
||||
/// A marked move of the main line: an inaccuracy, mistake or blunder, or a great or
|
||||
/// brilliant move (these have no better line and no reply).
|
||||
#[derive(Debug, Clone, PartialEq, uniffi::Record)]
|
||||
pub struct ReviewMove {
|
||||
/// The node of the move.
|
||||
|
|
@ -104,8 +113,14 @@ pub struct ReviewState {
|
|||
pub nodes: u64,
|
||||
/// Positions of the main line without an evaluation.
|
||||
pub missing: u32,
|
||||
/// Evaluated positions still waiting for the second search of !! and ! (an analysis
|
||||
/// from before them): "fill in" does it.
|
||||
pub seconds_missing: u32,
|
||||
/// Positions a full analysis looks at (for the time estimate).
|
||||
pub positions: u32,
|
||||
/// Engine searches a full analysis is expected to make (for the time estimate: a
|
||||
/// second search for moves that could be brilliant or great).
|
||||
pub searches: u32,
|
||||
/// The engine's speed in the last run, per thread (0 when unknown).
|
||||
pub nps_per_thread: u64,
|
||||
/// The start position and the position after every main-line move.
|
||||
|
|
@ -115,7 +130,7 @@ pub struct ReviewState {
|
|||
pub endgame: Option<u32>,
|
||||
pub white: SideReview,
|
||||
pub black: SideReview,
|
||||
/// The errors, in the order of the game.
|
||||
/// The marked moves, in the order of the game.
|
||||
pub moves: Vec<ReviewMove>,
|
||||
}
|
||||
|
||||
|
|
@ -347,6 +362,8 @@ fn side(s: &SideStats) -> SideReview {
|
|||
inaccuracies: s.inaccuracies,
|
||||
mistakes: s.mistakes,
|
||||
blunders: s.blunders,
|
||||
great: s.great,
|
||||
brilliant: s.brilliant,
|
||||
acpl: s.acpl,
|
||||
accuracy: s.accuracy,
|
||||
opening: s.phase_accuracy[0],
|
||||
|
|
@ -380,17 +397,20 @@ fn snapshot(st: &Inner) -> ReviewState {
|
|||
let Some(mark) = a.marks.get(id) else {
|
||||
continue;
|
||||
};
|
||||
let best = a.eval_at(i - 1).filter(|e| !e.pv.is_empty()).and_then(|e| {
|
||||
let root = st.game.position(mark.base)?;
|
||||
let (cp, mate) = match e.eval {
|
||||
Eval::Cp(cp) => (Some(cp), None),
|
||||
Eval::Mate { white, moves } => (
|
||||
None,
|
||||
Some(if white { moves as i32 } else { -(moves as i32) }),
|
||||
),
|
||||
};
|
||||
Some(line_with(root, 1, cp, mate, &e.pv))
|
||||
});
|
||||
let best = a
|
||||
.eval_at(i - 1)
|
||||
.filter(|e| !e.pv.is_empty() && mark.judgement.is_error())
|
||||
.and_then(|e| {
|
||||
let root = st.game.position(mark.base)?;
|
||||
let (cp, mate) = match e.eval {
|
||||
Eval::Cp(cp) => (Some(cp), None),
|
||||
Eval::Mate { white, moves } => (
|
||||
None,
|
||||
Some(if white { moves as i32 } else { -(moves as i32) }),
|
||||
),
|
||||
};
|
||||
Some(line_with(root, 1, cp, mate, &e.pv))
|
||||
});
|
||||
// The reply is the first move of the engine line after the bad move.
|
||||
let reply = a
|
||||
.eval_at(i)
|
||||
|
|
@ -418,7 +438,9 @@ fn snapshot(st: &Inner) -> ReviewState {
|
|||
engine: meta.engine,
|
||||
nodes: meta.nodes,
|
||||
missing: a.missing() as u32,
|
||||
seconds_missing: a.seconds_missing() as u32,
|
||||
positions: a.positions() as u32,
|
||||
searches: a.searches() as u32,
|
||||
nps_per_thread: st.nps_per_thread,
|
||||
points,
|
||||
middlegame: a.report.phases.middlegame.map(|i| i as u32),
|
||||
|
|
|
|||
|
|
@ -137,6 +137,7 @@ enum Cmd {
|
|||
position: EnginePosition,
|
||||
id: SearchId,
|
||||
limits: SearchLimits,
|
||||
among: Vec<String>,
|
||||
},
|
||||
Stop,
|
||||
/// A complete `setoption ...` / `ucinewgame` line, applied while idle.
|
||||
|
|
@ -219,12 +220,28 @@ impl EngineHandle {
|
|||
position: EnginePosition,
|
||||
search_id: SearchId,
|
||||
limits: SearchLimits,
|
||||
) -> Result<(), EngineError> {
|
||||
self.search_among(position, search_id, limits, Vec::new())
|
||||
}
|
||||
|
||||
/// A search among these moves only (`go … searchmoves`, UCI moves of `position`);
|
||||
/// empty: all of them. A move that is not a UCI move is refused.
|
||||
pub fn search_among(
|
||||
&self,
|
||||
position: EnginePosition,
|
||||
search_id: SearchId,
|
||||
limits: SearchLimits,
|
||||
among: Vec<String>,
|
||||
) -> Result<(), EngineError> {
|
||||
position.validate()?;
|
||||
if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) {
|
||||
return Err(EngineError::InvalidInput(format!("not a move: {bad:?}")));
|
||||
}
|
||||
self.send(Cmd::Search {
|
||||
position,
|
||||
id: search_id,
|
||||
limits,
|
||||
among,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -707,6 +724,7 @@ struct PendingSearch {
|
|||
position: EnginePosition,
|
||||
id: SearchId,
|
||||
limits: SearchLimits,
|
||||
among: Vec<String>,
|
||||
}
|
||||
|
||||
struct Supervisor {
|
||||
|
|
@ -828,11 +846,13 @@ impl Supervisor {
|
|||
position,
|
||||
id,
|
||||
limits,
|
||||
among,
|
||||
} => {
|
||||
if let Some(old) = self.pending.replace(PendingSearch {
|
||||
position,
|
||||
id,
|
||||
limits,
|
||||
among,
|
||||
}) {
|
||||
self.emit(EngineEvent::Superseded { search_id: old.id });
|
||||
}
|
||||
|
|
@ -934,7 +954,12 @@ impl Supervisor {
|
|||
match self.pending.take() {
|
||||
Some(p) => {
|
||||
self.write(&p.position.to_command())?;
|
||||
self.write(&p.limits.to_command())?;
|
||||
let mut go = p.limits.to_command();
|
||||
if !p.among.is_empty() {
|
||||
go += " searchmoves ";
|
||||
go += &p.among.join(" ");
|
||||
}
|
||||
self.write(&go)?;
|
||||
self.state = State::Searching { id: p.id };
|
||||
self.emit(EngineEvent::SearchStarted { search_id: p.id });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -269,7 +269,7 @@ impl EnginePosition {
|
|||
}
|
||||
}
|
||||
|
||||
fn is_uci_move(m: &str) -> bool {
|
||||
pub(crate) fn is_uci_move(m: &str) -> bool {
|
||||
let b = m.as_bytes();
|
||||
let sq = |f: u8, r: u8| (b'a'..=b'h').contains(&f) && (b'1'..=b'8').contains(&r);
|
||||
match b.len() {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue