Review: one fixed engine search everywhere, in parallel engine processes
Every position of a game analysis (and of the opening errors) is searched by ChessPenguin's Stockfish 19 to 1M nodes with one thread, a 32 MB hash and ucinewgame before each search, so the evaluations depend on the position alone: the same marks on every computer and phone, whatever the number of engine processes (one per CPU, at most 8 on a computer and 4 on a phone, and what the free memory holds) or the order of the positions. - ReviewMeta.search: analyses of another search are stale; shown, but Update makes them all again. The prep caches drop such evaluations. - Desktop: no launch dialog (engine, quality, threads, memory are gone); Analyse starts at once, its tooltip gives the time; the prep dialog keeps the colour. Without the own Stockfish the download is offered. - settings.review and prep.quality removed; old settings files still read. - fake_uci --hash-memory; tests of determinism on processes and order. - chesscom_check in the fixed search (CP_REVIEW_NODES for experiments); review_bench example for times and determinism on a real engine. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8c9c2d38c2
commit
968ab221cf
16 changed files with 923 additions and 902 deletions
|
|
@ -741,10 +741,9 @@ impl App {
|
||||||
if let Some(k) = std::env::var("CP_BEST").ok().and_then(|v| v.parse().ok()) {
|
if let Some(k) = std::env::var("CP_BEST").ok().and_then(|v| v.parse().ok()) {
|
||||||
g.debug_best_line(k);
|
g.debug_best_line(k);
|
||||||
}
|
}
|
||||||
// CP_REVIEW=dialog opens the game-analysis dialog, =ask presses «Analyse», any
|
// CP_REVIEW=ask presses «Analyse», any other value starts the analysis.
|
||||||
// other value starts the analysis.
|
|
||||||
if let Ok(v) = std::env::var("CP_REVIEW") {
|
if let Ok(v) = std::env::var("CP_REVIEW") {
|
||||||
g.debug_review(&self.settings, ctx, &v);
|
g.debug_review(ctx, &v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(start) = self.debug.play_from.take() {
|
if let Some(start) = self.debug.play_from.take() {
|
||||||
|
|
@ -907,11 +906,7 @@ impl App {
|
||||||
PrepAction::NeedEngine => self
|
PrepAction::NeedEngine => self
|
||||||
.engine_offer
|
.engine_offer
|
||||||
.ask(crate::engine_offer::Pending::OpeningErrors, &self.settings),
|
.ask(crate::engine_offer::Pending::OpeningErrors, &self.settings),
|
||||||
PrepAction::EngineSwitch | PrepAction::SettingsChanged => self.settings_dirty = true,
|
PrepAction::SettingsChanged => self.settings_dirty = true,
|
||||||
PrepAction::OpenEngines => {
|
|
||||||
self.settings_ui.open = true;
|
|
||||||
self.settings_ui.tab = Tab::Engines;
|
|
||||||
}
|
|
||||||
PrepAction::Toast(m) => self.toast(ctx, m),
|
PrepAction::Toast(m) => self.toast(ctx, m),
|
||||||
PrepAction::CopyText(text, msg) => {
|
PrepAction::CopyText(text, msg) => {
|
||||||
ctx.copy_text(text);
|
ctx.copy_text(text);
|
||||||
|
|
@ -2626,7 +2621,9 @@ impl App {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Makes ChessPenguin's Stockfish (just downloaded) or a found engine the active
|
/// Makes ChessPenguin's Stockfish (just downloaded) or a found engine the active
|
||||||
/// one, then runs what the user was doing.
|
/// one, then runs what the user was doing. The game analysis and the opening errors
|
||||||
|
/// use ChessPenguin's Stockfish whatever the active engine: downloaded for them, it
|
||||||
|
/// becomes the active one only when there was none.
|
||||||
fn engine_arrived(
|
fn engine_arrived(
|
||||||
&mut self,
|
&mut self,
|
||||||
ctx: &egui::Context,
|
ctx: &egui::Context,
|
||||||
|
|
@ -2640,7 +2637,16 @@ impl App {
|
||||||
self.settings.engines.push(cfg);
|
self.settings.engines.push(cfg);
|
||||||
self.settings.engines.len() - 1
|
self.settings.engines.len() - 1
|
||||||
});
|
});
|
||||||
self.settings.active_engine = Some(index);
|
let own_search = matches!(
|
||||||
|
pending,
|
||||||
|
Some(
|
||||||
|
crate::engine_offer::Pending::GameAnalysis
|
||||||
|
| crate::engine_offer::Pending::OpeningErrors
|
||||||
|
)
|
||||||
|
);
|
||||||
|
if !own_search || self.settings.active_engine().is_none() {
|
||||||
|
self.settings.active_engine = Some(index);
|
||||||
|
}
|
||||||
self.settings_dirty = true;
|
self.settings_dirty = true;
|
||||||
match pending {
|
match pending {
|
||||||
Some(crate::engine_offer::Pending::LiveAnalysis) => {
|
Some(crate::engine_offer::Pending::LiveAnalysis) => {
|
||||||
|
|
@ -2650,7 +2656,7 @@ impl App {
|
||||||
}
|
}
|
||||||
Some(crate::engine_offer::Pending::GameAnalysis) => {
|
Some(crate::engine_offer::Pending::GameAnalysis) => {
|
||||||
let actions = match self.game.as_mut() {
|
let actions = match self.game.as_mut() {
|
||||||
Some(g) => g.start_review_now(&self.settings, ctx),
|
Some(g) => g.start_review_now(ctx),
|
||||||
None => Vec::new(),
|
None => Vec::new(),
|
||||||
};
|
};
|
||||||
for a in actions {
|
for a in actions {
|
||||||
|
|
@ -2666,7 +2672,7 @@ impl App {
|
||||||
}
|
}
|
||||||
Some(crate::engine_offer::Pending::OpeningErrors) => {
|
Some(crate::engine_offer::Pending::OpeningErrors) => {
|
||||||
let actions = match self.prep.as_mut() {
|
let actions = match self.prep.as_mut() {
|
||||||
Some(p) => p.start_after_engine(&self.settings, ctx),
|
Some(p) => p.start_after_engine(ctx),
|
||||||
None => Vec::new(),
|
None => Vec::new(),
|
||||||
};
|
};
|
||||||
self.prep_actions(ctx, actions);
|
self.prep_actions(ctx, actions);
|
||||||
|
|
@ -2966,7 +2972,6 @@ impl eframe::App for App {
|
||||||
if let Some(p) = self.prep.as_mut() {
|
if let Some(p) = self.prep.as_mut() {
|
||||||
p.poll_quietly(&ctx, &self.settings);
|
p.poll_quietly(&ctx, &self.settings);
|
||||||
}
|
}
|
||||||
let review = self.settings.review.clone();
|
|
||||||
let actions = game.show(
|
let actions = game.show(
|
||||||
ui,
|
ui,
|
||||||
&mut self.settings,
|
&mut self.settings,
|
||||||
|
|
@ -2975,8 +2980,6 @@ impl eframe::App for App {
|
||||||
&mut self.translation,
|
&mut self.translation,
|
||||||
input_enabled,
|
input_enabled,
|
||||||
);
|
);
|
||||||
// The analysis options (its dialog) are kept.
|
|
||||||
self.settings_dirty |= self.settings.review != review;
|
|
||||||
self.reference_tab = game.reference_tab();
|
self.reference_tab = game.reference_tab();
|
||||||
let game_back_previous = game.previous_prep && game.previous.is_some();
|
let game_back_previous = game.previous_prep && game.previous.is_some();
|
||||||
// Before the actions: leaving may take the game away.
|
// Before the actions: leaving may take the game away.
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,9 @@ enum Mode {
|
||||||
System(PathBuf),
|
System(PathBuf),
|
||||||
/// The downloaded engine was deleted from the disk.
|
/// The downloaded engine was deleted from the disk.
|
||||||
Missing,
|
Missing,
|
||||||
|
/// The game analysis or the opening errors, which need ChessPenguin's Stockfish 19
|
||||||
|
/// itself (their search is the same on every computer): only its download helps.
|
||||||
|
Own,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct EngineOffer {
|
pub struct EngineOffer {
|
||||||
|
|
@ -79,7 +82,9 @@ impl EngineOffer {
|
||||||
pub fn ask(&mut self, pending: Pending, settings: &Settings) {
|
pub fn ask(&mut self, pending: Pending, settings: &Settings) {
|
||||||
self.pending = Some(pending);
|
self.pending = Some(pending);
|
||||||
self.failure = None;
|
self.failure = None;
|
||||||
self.mode = if settings.active_engine().is_some_and(|e| e.builtin) {
|
self.mode = if pending != Pending::LiveAnalysis {
|
||||||
|
Mode::Own
|
||||||
|
} else if settings.active_engine().is_some_and(|e| e.builtin) {
|
||||||
Mode::Missing
|
Mode::Missing
|
||||||
} else if settings.engines.is_empty()
|
} else if settings.engines.is_empty()
|
||||||
&& let Some(p) = crate::engines::system_stockfish()
|
&& let Some(p) = crate::engines::system_stockfish()
|
||||||
|
|
@ -222,6 +227,12 @@ impl EngineOffer {
|
||||||
tr("Stockfish not found"),
|
tr("Stockfish not found"),
|
||||||
tr("The Stockfish file is missing from the disk. Download it again?"),
|
tr("The Stockfish file is missing from the disk. Download it again?"),
|
||||||
),
|
),
|
||||||
|
Mode::Own => (
|
||||||
|
tr("Analysis needs Stockfish 19"),
|
||||||
|
tr(
|
||||||
|
"Game analysis and the search for opening errors always use ChessPenguin's Stockfish 19, so that their marks are the same on every computer. Download it? The analysis will start as soon as the download finishes.",
|
||||||
|
),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
ui.heading(title);
|
ui.heading(title);
|
||||||
ui.add_space(6.0);
|
ui.add_space(6.0);
|
||||||
|
|
@ -283,13 +294,16 @@ impl EngineOffer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
// Another engine does not do for the game analysis.
|
||||||
if ui.button(tr("Choose engine file…")).clicked() {
|
if self.mode != Mode::Own {
|
||||||
events.push(OfferEvent::ChooseFile);
|
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||||
self.open = false;
|
if ui.button(tr("Choose engine file…")).clicked() {
|
||||||
self.pending = None;
|
events.push(OfferEvent::ChooseFile);
|
||||||
}
|
self.open = false;
|
||||||
});
|
self.pending = None;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -366,7 +380,7 @@ impl EngineOffer {
|
||||||
ui.label(RichText::new(d).small().weak());
|
ui.label(RichText::new(d).small().weak());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if matches!(f, Failure::Network(_)) && cfg!(target_os = "linux") {
|
if matches!(f, Failure::Network(_)) && cfg!(target_os = "linux") && self.mode != Mode::Own {
|
||||||
ui.label(
|
ui.label(
|
||||||
RichText::new(tr(
|
RichText::new(tr(
|
||||||
"A stockfish package of your distribution is found by ChessPenguin too.",
|
"A stockfish package of your distribution is found by ChessPenguin too.",
|
||||||
|
|
@ -388,14 +402,16 @@ impl EngineOffer {
|
||||||
self.failure = None;
|
self.failure = None;
|
||||||
self.pending = None;
|
self.pending = None;
|
||||||
}
|
}
|
||||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
if self.mode != Mode::Own {
|
||||||
if ui.button(tr("Choose engine file…")).clicked() {
|
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||||
events.push(OfferEvent::ChooseFile);
|
if ui.button(tr("Choose engine file…")).clicked() {
|
||||||
self.open = false;
|
events.push(OfferEvent::ChooseFile);
|
||||||
self.failure = None;
|
self.open = false;
|
||||||
self.pending = None;
|
self.failure = None;
|
||||||
}
|
self.pending = None;
|
||||||
});
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ use crate::board::{self, Arrow, BoardState, BoardView};
|
||||||
use crate::notation::{
|
use crate::notation::{
|
||||||
CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, Slot, toggle_nag,
|
CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, Slot, toggle_nag,
|
||||||
};
|
};
|
||||||
use crate::review::{DialogAction, ReportAction, Review};
|
use crate::review::{ReportAction, Review};
|
||||||
use crate::settings::Settings;
|
use crate::settings::Settings;
|
||||||
|
|
||||||
/// Where an opened game came from (to return to the same library row, to save into).
|
/// Where an opened game came from (to return to the same library row, to save into).
|
||||||
|
|
@ -706,7 +706,7 @@ impl GameView {
|
||||||
self.review.note_live_speed(analysis.nps, e.threads);
|
self.review.note_live_speed(analysis.nps, e.threads);
|
||||||
}
|
}
|
||||||
self.play_tick(ui.ctx(), &mut actions);
|
self.play_tick(ui.ctx(), &mut actions);
|
||||||
if input_enabled && !self.review.dialog_open && self.play_leave.is_none() {
|
if input_enabled && self.play_leave.is_none() {
|
||||||
self.editor_keys(ui, &mut actions);
|
self.editor_keys(ui, &mut actions);
|
||||||
self.keyboard(ui, &mut actions);
|
self.keyboard(ui, &mut actions);
|
||||||
}
|
}
|
||||||
|
|
@ -783,27 +783,16 @@ impl GameView {
|
||||||
});
|
});
|
||||||
self.sync_analysis(analysis);
|
self.sync_analysis(analysis);
|
||||||
|
|
||||||
// «Analyse»: at once with the options chosen before, else the dialog first.
|
// «Analyse»: at once — the search is the same for everyone, nothing to choose.
|
||||||
if std::mem::take(&mut self.review_asked) {
|
if std::mem::take(&mut self.review_asked) {
|
||||||
if self.engine_busy {
|
if self.engine_busy {
|
||||||
actions.push(GameAction::Toast(
|
actions.push(GameAction::Toast(
|
||||||
tr("Opening errors are being searched — wait or stop it in the report").to_owned(),
|
tr("Opening errors are being searched — wait or stop it in the report").to_owned(),
|
||||||
));
|
));
|
||||||
} else if settings.review.chosen {
|
|
||||||
self.start_review(settings, true, ui.ctx(), &mut actions);
|
|
||||||
} else {
|
} else {
|
||||||
self.review.dialog_open = true;
|
self.start_review(false, ui.ctx(), &mut actions);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match self.review.dialog(ui.ctx(), settings) {
|
|
||||||
Some(DialogAction::Start) => {
|
|
||||||
settings.review.chosen = true;
|
|
||||||
self.start_review(settings, true, ui.ctx(), &mut actions);
|
|
||||||
}
|
|
||||||
Some(DialogAction::EngineSwitch) => actions.push(GameAction::EngineSwitch),
|
|
||||||
Some(DialogAction::OpenEngines) => actions.push(GameAction::OpenEngineSettings),
|
|
||||||
None => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A line from the clipboard: pasted, or asked about.
|
// A line from the clipboard: pasted, or asked about.
|
||||||
if let Some(text) = self.paste_request.take() {
|
if let Some(text) = self.paste_request.take() {
|
||||||
|
|
@ -848,26 +837,14 @@ impl GameView {
|
||||||
actions
|
actions
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_review(
|
/// Starts the game analysis with ChessPenguin's Stockfish; without it, the offer to
|
||||||
&mut self,
|
/// download it comes first.
|
||||||
settings: &Settings,
|
fn start_review(&mut self, full: bool, ctx: &egui::Context, actions: &mut Vec<GameAction>) {
|
||||||
full: bool,
|
let Some(path) = crate::engines::own_stockfish() else {
|
||||||
ctx: &egui::Context,
|
|
||||||
actions: &mut Vec<GameAction>,
|
|
||||||
) {
|
|
||||||
if !crate::engine_offer::EngineOffer::engine_ready(settings) {
|
|
||||||
self.review.dialog_open = false;
|
|
||||||
actions.push(GameAction::NeedEngine);
|
actions.push(GameAction::NeedEngine);
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
let Some(engine) = settings.active_engine().cloned() else {
|
|
||||||
self.review.dialog_open = true;
|
|
||||||
return;
|
|
||||||
};
|
};
|
||||||
if self
|
if self.review.start(&self.game, &path, full, ctx) {
|
||||||
.review
|
|
||||||
.start(&self.game, &engine, &settings.review, full, ctx)
|
|
||||||
{
|
|
||||||
actions.push(GameAction::PauseLive);
|
actions.push(GameAction::PauseLive);
|
||||||
self.side_tab = SideTab::Report;
|
self.side_tab = SideTab::Report;
|
||||||
} else if let Some(e) = &self.review.error {
|
} else if let Some(e) = &self.review.error {
|
||||||
|
|
@ -903,8 +880,10 @@ impl GameView {
|
||||||
));
|
));
|
||||||
} else if ui
|
} else if ui
|
||||||
.add_enabled(!self.engine_busy, egui::Button::new(big("📈")))
|
.add_enabled(!self.engine_busy, egui::Button::new(big("📈")))
|
||||||
.on_hover_text(tr(
|
.on_hover_text(format!(
|
||||||
"Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)",
|
"{}\n{}",
|
||||||
|
tr("Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)"),
|
||||||
|
self.review.estimate()
|
||||||
))
|
))
|
||||||
.on_disabled_hover_text(tr(
|
.on_disabled_hover_text(tr(
|
||||||
"Opening errors are being searched — wait or stop it in the report",
|
"Opening errors are being searched — wait or stop it in the report",
|
||||||
|
|
@ -1481,10 +1460,8 @@ impl GameView {
|
||||||
&[("n", &n)],
|
&[("n", &n)],
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
Some(ReportAction::Update) => {
|
Some(ReportAction::Update) => self.start_review(false, ui.ctx(), actions),
|
||||||
self.start_review(settings, false, ui.ctx(), actions)
|
Some(ReportAction::Analyse) => self.start_review(true, ui.ctx(), actions),
|
||||||
}
|
|
||||||
Some(ReportAction::Reanalyse) => self.review.dialog_open = true,
|
|
||||||
None => {}
|
None => {}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
|
@ -2083,23 +2060,18 @@ impl GameView {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `how`: "dialog" opens the dialog, "ask" presses «Analyse», else the analysis starts.
|
/// `how`: "ask" presses «Analyse», else the analysis starts.
|
||||||
pub fn debug_review(&mut self, settings: &Settings, ctx: &egui::Context, how: &str) {
|
pub fn debug_review(&mut self, ctx: &egui::Context, how: &str) {
|
||||||
match how {
|
match how {
|
||||||
"dialog" => self.review.dialog_open = true,
|
|
||||||
"ask" => self.review_asked = true,
|
"ask" => self.review_asked = true,
|
||||||
_ => self.start_review(settings, false, ctx, &mut Vec::new()),
|
_ => self.start_review(false, ctx, &mut Vec::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the game analysis right away (after an engine was installed for it).
|
/// Starts the game analysis right away (after an engine was installed for it).
|
||||||
pub fn start_review_now(
|
pub fn start_review_now(&mut self, ctx: &egui::Context) -> Vec<GameAction> {
|
||||||
&mut self,
|
|
||||||
settings: &Settings,
|
|
||||||
ctx: &egui::Context,
|
|
||||||
) -> Vec<GameAction> {
|
|
||||||
let mut actions = Vec::new();
|
let mut actions = Vec::new();
|
||||||
self.start_review(settings, true, ctx, &mut actions);
|
self.start_review(false, ctx, &mut actions);
|
||||||
actions
|
actions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7925,17 +7925,6 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"Partiyaga baholar, !!/!/?!/?/?? belgilari, izohlar va yaxshiroq liniyalarni qo‘shadi (bekor qilish: Ctrl+Z)",
|
"Partiyaga baholar, !!/!/?!/?/?? belgilari, izohlar va yaxshiroq liniyalarni qo‘shadi (bekor qilish: Ctrl+Z)",
|
||||||
"Партияға бағаларды, !!/!/?!/?/?? белгілерін, түсініктемелер мен жақсырақ варианттарды қосады (болдырмау — Ctrl+Z)",
|
"Партияға бағаларды, !!/!/?!/?/?? белгілерін, түсініктемелер мен жақсырақ варианттарды қосады (болдырмау — Ctrl+Z)",
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"Analyse again…",
|
|
||||||
"Проанализировать заново…",
|
|
||||||
"Analyser de nouveau…",
|
|
||||||
"Erneut analysieren…",
|
|
||||||
"Analizar de nuevo…",
|
|
||||||
"Analizza di nuovo…",
|
|
||||||
"Analisar de novo…",
|
|
||||||
"Qayta tahlil qilish…",
|
|
||||||
"Қайта талдау…",
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Go to the next one",
|
"Go to the next one",
|
||||||
"Перейти к следующей",
|
"Перейти к следующей",
|
||||||
|
|
@ -7969,50 +7958,6 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"Aniqlik",
|
"Aniqlik",
|
||||||
"Дәлдік",
|
"Дәлдік",
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"The engine evaluates every position of the main line. The game itself is not changed.",
|
|
||||||
"Движок оценит каждую позицию основной линии. Сама партия не изменится.",
|
|
||||||
"Le moteur évalue chaque position de la ligne principale. La partie elle-même n'est pas modifiée.",
|
|
||||||
"Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert.",
|
|
||||||
"El motor evalúa cada posición de la línea principal. La partida en sí no cambia.",
|
|
||||||
"Il motore valuta ogni posizione della linea principale. La partita non viene modificata.",
|
|
||||||
"O motor avalia cada posição da linha principal. A partida em si não é alterada.",
|
|
||||||
"Dvigatel asosiy liniyaning har bir pozitsiyasini baholaydi. Partiyaning o‘zi o‘zgarmaydi.",
|
|
||||||
"Қозғалтқыш негізгі варианттың әр позициясын бағалайды. Партияның өзі өзгермейді.",
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Quality",
|
|
||||||
"Качество",
|
|
||||||
"Qualité",
|
|
||||||
"Qualität",
|
|
||||||
"Calidad",
|
|
||||||
"Qualità",
|
|
||||||
"Qualidade",
|
|
||||||
"Sifat",
|
|
||||||
"Сапа",
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Analyse",
|
|
||||||
"Анализировать",
|
|
||||||
"Analyser",
|
|
||||||
"Analysieren",
|
|
||||||
"Analizar",
|
|
||||||
"Analizza",
|
|
||||||
"Analisar",
|
|
||||||
"Tahlil qilish",
|
|
||||||
"Талдау",
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Add an engine first",
|
|
||||||
"Сначала добавьте движок",
|
|
||||||
"Ajoutez d'abord un moteur",
|
|
||||||
"Zuerst eine Engine hinzufügen",
|
|
||||||
"Primero añade un motor",
|
|
||||||
"Aggiungi prima un motore",
|
|
||||||
"Adicione um motor primeiro",
|
|
||||||
"Avval dvigatel qo‘shing",
|
|
||||||
"Алдымен қозғалтқыш қосыңыз",
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Inaccuracy",
|
"Inaccuracy",
|
||||||
"Неточность",
|
"Неточность",
|
||||||
|
|
@ -8112,17 +8057,6 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"Bahosiz pozitsiyalar: {n}",
|
"Bahosiz pozitsiyalar: {n}",
|
||||||
"Бағасыз позициялар: {n}",
|
"Бағасыз позициялар: {n}",
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"{quality} · {nodes} nodes",
|
|
||||||
"{quality} · {nodes} узлов",
|
|
||||||
"{quality} · {nodes} nœuds",
|
|
||||||
"{quality} · {nodes} Knoten",
|
|
||||||
"{quality} · {nodes} nodos",
|
|
||||||
"{quality} · {nodes} nodi",
|
|
||||||
"{quality} · {nodes} nós",
|
|
||||||
"{quality} · {nodes} tugun",
|
|
||||||
"{quality} · {nodes} түйін",
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"{n} positions, about {time}",
|
"{n} positions, about {time}",
|
||||||
"Позиций: {n}, примерно {time}",
|
"Позиций: {n}, примерно {time}",
|
||||||
|
|
@ -8167,17 +8101,6 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"Oddiy",
|
"Oddiy",
|
||||||
"Қалыпты",
|
"Қалыпты",
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"Deep",
|
|
||||||
"Глубоко",
|
|
||||||
"Approfondi",
|
|
||||||
"Gründlich",
|
|
||||||
"Profundo",
|
|
||||||
"Approfondito",
|
|
||||||
"Profunda",
|
|
||||||
"Chuqur",
|
|
||||||
"Терең",
|
|
||||||
],
|
|
||||||
// Engines
|
// Engines
|
||||||
[
|
[
|
||||||
"The built-in engine is not part of this build",
|
"The built-in engine is not part of this build",
|
||||||
|
|
@ -14005,17 +13928,6 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"Debyut xatolari",
|
"Debyut xatolari",
|
||||||
"Дебют қателері",
|
"Дебют қателері",
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"For opening errors “Fast” is usually enough. “Normal” is for adult databases and takes 4 times longer.",
|
|
||||||
"Для поиска ошибок в дебюте обычно достаточно «Быстро». «Обычно» — для взрослых баз, в 4 раза дольше.",
|
|
||||||
"Pour les erreurs d'ouverture, « Rapide » suffit en général. « Normal » est pour les bases d'adultes et prend 4 fois plus de temps.",
|
|
||||||
"Für Eröffnungsfehler reicht meist „Schnell“. „Normal“ ist für Datenbanken Erwachsener und dauert 4-mal länger.",
|
|
||||||
"Para errores de apertura suele bastar «Rápido». «Normal» es para bases de adultos y tarda 4 veces más.",
|
|
||||||
"Per gli errori di apertura di solito basta «Veloce». «Normale» è per database di adulti e richiede 4 volte più tempo.",
|
|
||||||
"Para erros de abertura, «Rápido» costuma bastar. «Normal» é para bases de adultos e leva 4 vezes mais.",
|
|
||||||
"Debyut xatolari uchun odatda «Tez» yetarli. «Oddiy» — kattalar bazalari uchun, 4 barobar uzoq.",
|
|
||||||
"Дебют қателері үшін әдетте «Жылдам» жеткілікті. «Қалыпты» — ересектер базалары үшін, 4 есе ұзақ.",
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"identical positions are counted once",
|
"identical positions are counted once",
|
||||||
"одинаковые позиции считаются один раз",
|
"одинаковые позиции считаются один раз",
|
||||||
|
|
@ -14379,28 +14291,6 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"▶ Debyut xatolarini topish",
|
"▶ Debyut xatolarini topish",
|
||||||
"▶ Дебют қателерін табу",
|
"▶ Дебют қателерін табу",
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"More precisely…",
|
|
||||||
"Точнее…",
|
|
||||||
"Plus précisément…",
|
|
||||||
"Genauer…",
|
|
||||||
"Con más precisión…",
|
|
||||||
"Più precisamente…",
|
|
||||||
"Com mais precisão…",
|
|
||||||
"Aniqroq…",
|
|
||||||
"Дәлірек…",
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"The same positions at «Normal» quality",
|
|
||||||
"Те же позиции с качеством «Обычно»",
|
|
||||||
"Les mêmes positions en qualité « Normal »",
|
|
||||||
"Dieselben Stellungen in Qualität „Normal“",
|
|
||||||
"Las mismas posiciones con calidad «Normal»",
|
|
||||||
"Le stesse posizioni con qualità «Normale»",
|
|
||||||
"As mesmas posições com qualidade «Normal»",
|
|
||||||
"O‘sha pozitsiyalar «Oddiy» sifatda",
|
|
||||||
"Сол позициялар «Қалыпты» сапада",
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Repeated errors — the same position, the same move",
|
"Repeated errors — the same position, the same move",
|
||||||
"Повторяющиеся ошибки — одна и та же позиция, тот же ход",
|
"Повторяющиеся ошибки — одна и та же позиция, тот же ход",
|
||||||
|
|
@ -14633,15 +14523,15 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"▶ Дебют қателерін табу ≈ {time}",
|
"▶ Дебют қателерін табу ≈ {time}",
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"Errors found · {engine} · {quality} · {n} positions",
|
"Errors found · {engine} · {n} positions",
|
||||||
"Ошибки найдены · {engine} · {quality} · {n} позиций",
|
"Ошибки найдены · {engine} · {n} позиций",
|
||||||
"Erreurs trouvées · {engine} · {quality} · {n} positions",
|
"Erreurs trouvées · {engine} · {n} positions",
|
||||||
"Fehler gefunden · {engine} · {quality} · {n} Stellungen",
|
"Fehler gefunden · {engine} · {n} Stellungen",
|
||||||
"Errores encontrados · {engine} · {quality} · {n} posiciones",
|
"Errores encontrados · {engine} · {n} posiciones",
|
||||||
"Errori trovati · {engine} · {quality} · {n} posizioni",
|
"Errori trovati · {engine} · {n} posizioni",
|
||||||
"Erros encontrados · {engine} · {quality} · {n} posições",
|
"Erros encontrados · {engine} · {n} posições",
|
||||||
"Xatolar topildi · {engine} · {quality} · {n} pozitsiya",
|
"Xatolar topildi · {engine} · {n} pozitsiya",
|
||||||
"Қателер табылды · {engine} · {quality} · {n} позиция",
|
"Қателер табылды · {engine} · {n} позиция",
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"opponents ≈ {elo}",
|
"opponents ≈ {elo}",
|
||||||
|
|
@ -15029,15 +14919,15 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"Жалғастыру ≈ {time}",
|
"Жалғастыру ≈ {time}",
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"Errors found · {quality} · {n} positions",
|
"Errors found · {n} positions",
|
||||||
"Ошибки найдены · {quality} · {n} позиций",
|
"Ошибки найдены · {n} позиций",
|
||||||
"Erreurs trouvées · {quality} · {n} positions",
|
"Erreurs trouvées · {n} positions",
|
||||||
"Fehler gefunden · {quality} · {n} Stellungen",
|
"Fehler gefunden · {n} Stellungen",
|
||||||
"Errores encontrados · {quality} · {n} posiciones",
|
"Errores encontrados · {n} posiciones",
|
||||||
"Errori trovati · {quality} · {n} posizioni",
|
"Errori trovati · {n} posizioni",
|
||||||
"Erros encontrados · {quality} · {n} posições",
|
"Erros encontrados · {n} posições",
|
||||||
"Xatolar topildi · {quality} · {n} pozitsiya",
|
"Xatolar topildi · {n} pozitsiya",
|
||||||
"Қателер табылды · {quality} · {n} позиция",
|
"Қателер табылды · {n} позиция",
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"in {p} % of games",
|
"in {p} % of games",
|
||||||
|
|
@ -15072,6 +14962,61 @@ const ROWS: &[[&str; 9]] = &[
|
||||||
"{judgement}: yaxshisi {best} ({before} → {after}) · {n} partiyada",
|
"{judgement}: yaxshisi {best} ({before} → {after}) · {n} partiyada",
|
||||||
"{judgement}: жақсысы {best} ({before} → {after}) · {n} партияда",
|
"{judgement}: жақсысы {best} ({before} → {after}) · {n} партияда",
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
"Analysis needs Stockfish 19",
|
||||||
|
"Для анализа нужен Stockfish 19",
|
||||||
|
"L’analyse nécessite Stockfish 19",
|
||||||
|
"Die Analyse braucht Stockfish 19",
|
||||||
|
"El análisis necesita Stockfish 19",
|
||||||
|
"L’analisi richiede Stockfish 19",
|
||||||
|
"A análise precisa do Stockfish 19",
|
||||||
|
"Tahlil uchun Stockfish 19 kerak",
|
||||||
|
"Талдау үшін Stockfish 19 керек",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Game analysis and the search for opening errors always use ChessPenguin's Stockfish 19, so that their marks are the same on every computer. Download it? The analysis will start as soon as the download finishes.",
|
||||||
|
"Анализ партии и поиск ошибок в дебютах всегда идут на Stockfish 19 из ChessPenguin — так отметки одинаковы на любом компьютере. Скачать его? Анализ начнётся, как только загрузка закончится.",
|
||||||
|
"L’analyse de partie et la recherche d’erreurs d’ouverture utilisent toujours le Stockfish 19 de ChessPenguin, pour que leurs signes soient les mêmes sur tous les ordinateurs. Le télécharger ? L’analyse commencera dès la fin du téléchargement.",
|
||||||
|
"Die Partieanalyse und die Suche nach Eröffnungsfehlern verwenden immer das Stockfish 19 von ChessPenguin, damit ihre Zeichen auf jedem Computer gleich sind. Herunterladen? Die Analyse beginnt, sobald der Download fertig ist.",
|
||||||
|
"El análisis de partidas y la búsqueda de errores de apertura usan siempre el Stockfish 19 de ChessPenguin, para que sus signos sean iguales en cualquier ordenador. ¿Descargarlo? El análisis empezará en cuanto termine la descarga.",
|
||||||
|
"L’analisi della partita e la ricerca degli errori d’apertura usano sempre lo Stockfish 19 di ChessPenguin, perché i segni siano uguali su ogni computer. Scaricarlo? L’analisi partirà appena finito il download.",
|
||||||
|
"A análise de partidas e a procura de erros de abertura usam sempre o Stockfish 19 do ChessPenguin, para que as marcas sejam iguais em qualquer computador. Descarregá-lo? A análise começa assim que o download terminar.",
|
||||||
|
"Partiya tahlili va debyut xatolarini qidirish doim ChessPenguin’ning Stockfish 19 dvigatelida bo‘ladi — belgilar har qanday kompyuterda bir xil chiqadi. Yuklab olinsinmi? Yuklash tugashi bilan tahlil boshlanadi.",
|
||||||
|
"Партияны талдау мен дебют қателерін іздеу әрқашан ChessPenguin-нің Stockfish 19 қозғалтқышында жүреді — белгілер кез келген компьютерде бірдей болады. Жүктеп алу керек пе? Жүктеу біткен соң талдау басталады.",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"This analysis was made with other engine settings",
|
||||||
|
"Этот анализ сделан с прежними настройками движка",
|
||||||
|
"Cette analyse a été faite avec d’autres réglages du moteur",
|
||||||
|
"Diese Analyse wurde mit anderen Engine-Einstellungen gemacht",
|
||||||
|
"Este análisis se hizo con otros ajustes del motor",
|
||||||
|
"Questa analisi è stata fatta con altre impostazioni del motore",
|
||||||
|
"Esta análise foi feita com outras definições do motor",
|
||||||
|
"Bu tahlil dvigatelning boshqa sozlamalari bilan qilingan",
|
||||||
|
"Бұл талдау қозғалтқыштың басқа баптауларымен жасалған",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Every position is analysed again, the same way on every computer",
|
||||||
|
"Все позиции анализируются заново — одинаково на любом компьютере",
|
||||||
|
"Toutes les positions sont analysées de nouveau, de la même façon sur tous les ordinateurs",
|
||||||
|
"Alle Stellungen werden neu analysiert, auf jedem Computer gleich",
|
||||||
|
"Todas las posiciones se analizan de nuevo, igual en cualquier ordenador",
|
||||||
|
"Tutte le posizioni vengono analizzate di nuovo, allo stesso modo su ogni computer",
|
||||||
|
"Todas as posições são analisadas de novo, da mesma forma em qualquer computador",
|
||||||
|
"Barcha pozitsiyalar qayta tahlil qilinadi — har qanday kompyuterda bir xil",
|
||||||
|
"Барлық позиция қайта талданады — кез келген компьютерде бірдей",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Analyse with the engine",
|
||||||
|
"Проанализировать движком",
|
||||||
|
"Analyser avec le moteur",
|
||||||
|
"Mit der Engine analysieren",
|
||||||
|
"Analizar con el motor",
|
||||||
|
"Analizza con il motore",
|
||||||
|
"Analisar com o motor",
|
||||||
|
"Dvigatel bilan tahlil qilish",
|
||||||
|
"Қозғалтқышпен талдау",
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
|
||||||
|
|
@ -29,8 +29,8 @@ use crate::board_search::{Background, PREVIEW_ARROW};
|
||||||
use crate::i18n::{tr, trf};
|
use crate::i18n::{tr, trf};
|
||||||
use crate::large_db::grouped;
|
use crate::large_db::grouped;
|
||||||
use crate::reference::RefDb;
|
use crate::reference::RefDb;
|
||||||
use crate::review::{self, DialogAction};
|
use crate::review;
|
||||||
use crate::settings::{REVIEW_QUALITY, Settings};
|
use crate::settings::Settings;
|
||||||
|
|
||||||
/// «Prepare against…» as the library asks it: the name typed or picked and the colour
|
/// «Prepare against…» as the library asks it: the name typed or picked and the colour
|
||||||
/// of the filter (§2.1).
|
/// of the filter (§2.1).
|
||||||
|
|
@ -863,8 +863,6 @@ pub enum PrepAction {
|
||||||
EngineStarted,
|
EngineStarted,
|
||||||
EngineEnded,
|
EngineEnded,
|
||||||
NeedEngine,
|
NeedEngine,
|
||||||
EngineSwitch,
|
|
||||||
OpenEngines,
|
|
||||||
Toast(String),
|
Toast(String),
|
||||||
CopyText(String, &'static str),
|
CopyText(String, &'static str),
|
||||||
/// The line as a new game (no database).
|
/// The line as a new game (no database).
|
||||||
|
|
@ -928,8 +926,8 @@ struct EngineJob {
|
||||||
cancel: Arc<AtomicBool>,
|
cancel: Arc<AtomicBool>,
|
||||||
total: usize,
|
total: usize,
|
||||||
done: usize,
|
done: usize,
|
||||||
threads: u32,
|
/// Engine processes of the run.
|
||||||
nodes: u64,
|
processes: usize,
|
||||||
/// Evaluations since the cache was saved.
|
/// Evaluations since the cache was saved.
|
||||||
unsaved: usize,
|
unsaved: usize,
|
||||||
}
|
}
|
||||||
|
|
@ -1393,7 +1391,7 @@ impl PrepScreen {
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.and_then(|d| PrepReport::load(d, &screen.db, &screen.player, &options));
|
.and_then(|d| PrepReport::load(d, &screen.db, &screen.player, &options));
|
||||||
match cached {
|
match cached {
|
||||||
Some(r) => screen.take_report(r, settings),
|
Some(r) => screen.take_report(r),
|
||||||
None => screen.rebuild(ctx),
|
None => screen.rebuild(ctx),
|
||||||
}
|
}
|
||||||
screen
|
screen
|
||||||
|
|
@ -1416,9 +1414,9 @@ impl PrepScreen {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The engine run after an engine was installed for it.
|
/// The engine run after an engine was installed for it.
|
||||||
pub fn start_after_engine(&mut self, settings: &Settings, ctx: &egui::Context) -> Vec<PrepAction> {
|
pub fn start_after_engine(&mut self, ctx: &egui::Context) -> Vec<PrepAction> {
|
||||||
let mut actions = Vec::new();
|
let mut actions = Vec::new();
|
||||||
self.start_engine(settings, ctx, &mut actions);
|
self.start_engine(ctx, &mut actions);
|
||||||
actions
|
actions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1445,8 +1443,8 @@ impl PrepScreen {
|
||||||
|
|
||||||
/// A report arrived (built or from the cache): the rows of the games list, the
|
/// A report arrived (built or from the cache): the rows of the games list, the
|
||||||
/// cached evaluations, the default expansion.
|
/// cached evaluations, the default expansion.
|
||||||
fn take_report(&mut self, mut report: PrepReport, settings: &Settings) {
|
fn take_report(&mut self, mut report: PrepReport) {
|
||||||
let taken = report.take_cached(&self.cache, settings.prep.nodes());
|
let taken = report.take_cached(&self.cache);
|
||||||
self.dirty |= taken > 0;
|
self.dirty |= taken > 0;
|
||||||
self.rows = report
|
self.rows = report
|
||||||
.games
|
.games
|
||||||
|
|
@ -1523,7 +1521,7 @@ impl PrepScreen {
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.and_then(|d| PrepReport::load(d, &self.db, &self.player, &options));
|
.and_then(|d| PrepReport::load(d, &self.db, &self.player, &options));
|
||||||
match cached {
|
match cached {
|
||||||
Some(r) => self.take_report(r, settings),
|
Some(r) => self.take_report(r),
|
||||||
None => self.rebuild(ctx),
|
None => self.rebuild(ctx),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1552,7 +1550,7 @@ impl PrepScreen {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The engine run for the colour(s) shown.
|
/// The engine run for the colour(s) shown.
|
||||||
fn engine_state(&self, settings: &Settings) -> EngineState {
|
fn engine_state(&self) -> EngineState {
|
||||||
if self.job.is_some() {
|
if self.job.is_some() {
|
||||||
return EngineState::Running;
|
return EngineState::Running;
|
||||||
}
|
}
|
||||||
|
|
@ -1564,7 +1562,7 @@ impl PrepScreen {
|
||||||
}
|
}
|
||||||
let side = self.color.side();
|
let side = self.color.side();
|
||||||
let total = report.distinct_positions_for(side);
|
let total = report.distinct_positions_for(side);
|
||||||
let missing = report.missing_for(settings.prep.nodes(), side);
|
let missing = report.missing_for(side);
|
||||||
if missing == 0 {
|
if missing == 0 {
|
||||||
EngineState::Complete { total }
|
EngineState::Complete { total }
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -1670,7 +1668,7 @@ impl PrepScreen {
|
||||||
{
|
{
|
||||||
self.build = None;
|
self.build = None;
|
||||||
match r {
|
match r {
|
||||||
Some(report) => self.take_report(report, settings),
|
Some(report) => self.take_report(report),
|
||||||
None => self.error = Some(tr("The games could not be read").to_owned()),
|
None => self.error = Some(tr("The games could not be read").to_owned()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1704,7 +1702,7 @@ impl PrepScreen {
|
||||||
self.start_book(ctx, actions);
|
self.start_book(ctx, actions);
|
||||||
if self.auto_engine && self.report.is_some() && self.build.is_none() {
|
if self.auto_engine && self.report.is_some() && self.build.is_none() {
|
||||||
self.auto_engine = false;
|
self.auto_engine = false;
|
||||||
self.start_engine(settings, ctx, actions);
|
self.start_engine(ctx, actions);
|
||||||
}
|
}
|
||||||
if self.build.is_some() || self.book_job.is_some() || self.job.is_some() {
|
if self.build.is_some() || self.book_job.is_some() || self.job.is_some() {
|
||||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||||
|
|
@ -1777,47 +1775,48 @@ impl PrepScreen {
|
||||||
// ----- the engine ----------------------------------------------------------------
|
// ----- the engine ----------------------------------------------------------------
|
||||||
|
|
||||||
/// Positions the next run has to evaluate, and how long it takes.
|
/// Positions the next run has to evaluate, and how long it takes.
|
||||||
fn estimate(&self, settings: &Settings) -> (usize, f64) {
|
fn estimate(&self) -> (usize, f64) {
|
||||||
let Some(report) = &self.report else {
|
let Some(report) = &self.report else {
|
||||||
return (0, 0.0);
|
return (0, 0.0);
|
||||||
};
|
};
|
||||||
let nodes = settings.prep.nodes();
|
let missing = report.missing_for(self.color.side());
|
||||||
let missing = report.missing_for(nodes, self.color.side());
|
(missing, self.secs_for(missing, review::processes()))
|
||||||
let per_thread = self.nps_per_thread.unwrap_or(review::DEFAULT_NPS);
|
|
||||||
(missing, review::estimate_secs(missing, nodes, per_thread, settings.review.threads))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The button: the dialog the first time, at once with the options chosen before.
|
/// Seconds `positions` take in `processes` engine processes.
|
||||||
|
fn secs_for(&self, positions: usize, processes: usize) -> f64 {
|
||||||
|
let nps = self.nps_per_thread.unwrap_or(review::DEFAULT_NPS);
|
||||||
|
game_review::estimate_secs(positions, nps, processes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The button: the dialog the first time, at once with the colour chosen before.
|
||||||
fn engine_asked(&mut self, settings: &Settings, ctx: &egui::Context, actions: &mut Vec<PrepAction>) {
|
fn engine_asked(&mut self, settings: &Settings, ctx: &egui::Context, actions: &mut Vec<PrepAction>) {
|
||||||
if !crate::engine_offer::EngineOffer::engine_ready(settings) {
|
if crate::engines::own_stockfish().is_none() {
|
||||||
actions.push(PrepAction::NeedEngine);
|
actions.push(PrepAction::NeedEngine);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if settings.prep.chosen {
|
if settings.prep.chosen {
|
||||||
self.start_engine(settings, ctx, actions);
|
self.start_engine(ctx, actions);
|
||||||
} else {
|
} else {
|
||||||
self.dialog_open = true;
|
self.dialog_open = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_engine(&mut self, settings: &Settings, ctx: &egui::Context, actions: &mut Vec<PrepAction>) {
|
/// Starts the search for opening errors: ChessPenguin's Stockfish with the fixed
|
||||||
|
/// search of the game analysis (`game_review::run`), the same on every computer.
|
||||||
|
fn start_engine(&mut self, ctx: &egui::Context, actions: &mut Vec<PrepAction>) {
|
||||||
self.error = None;
|
self.error = None;
|
||||||
let Some(engine) = settings.active_engine().cloned() else {
|
let Some(path) = crate::engines::own_stockfish() else {
|
||||||
self.dialog_open = true;
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let Some(path) = engine.executable() else {
|
|
||||||
actions.push(PrepAction::NeedEngine);
|
actions.push(PrepAction::NeedEngine);
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let nodes = settings.prep.nodes();
|
|
||||||
let cache = std::mem::take(&mut self.cache);
|
let cache = std::mem::take(&mut self.cache);
|
||||||
let mut taken = 0;
|
let mut taken = 0;
|
||||||
self.rejudge(|r| taken = r.take_cached(&cache, nodes));
|
self.rejudge(|r| taken = r.take_cached(&cache));
|
||||||
self.cache = cache;
|
self.cache = cache;
|
||||||
self.dirty |= taken > 0;
|
self.dirty |= taken > 0;
|
||||||
let Some(report) = self.report.as_ref() else { return };
|
let Some(report) = self.report.as_ref() else { return };
|
||||||
let targets = report.targets_for(nodes, self.color.side());
|
let targets = report.targets_for(self.color.side());
|
||||||
if targets.is_empty() {
|
if targets.is_empty() {
|
||||||
actions.push(PrepAction::Toast(tr("Every position is already evaluated").to_owned()));
|
actions.push(PrepAction::Toast(tr("Every position is already evaluated").to_owned()));
|
||||||
self.tab = Tab::Errors;
|
self.tab = Tab::Errors;
|
||||||
|
|
@ -1826,19 +1825,14 @@ impl PrepScreen {
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
let cancel = Arc::new(AtomicBool::new(false));
|
let cancel = Arc::new(AtomicBool::new(false));
|
||||||
let total = targets.len();
|
let total = targets.len();
|
||||||
let job_settings = JobSettings {
|
let job_settings = JobSettings::new(review::processes(), None);
|
||||||
threads: settings.review.threads.max(1),
|
let processes = job_settings.processes;
|
||||||
hash_mb: settings.review.hash_mb,
|
|
||||||
nodes,
|
|
||||||
eval_file: None,
|
|
||||||
};
|
|
||||||
let threads = job_settings.threads;
|
|
||||||
let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone());
|
let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone());
|
||||||
let spawned = std::thread::Builder::new()
|
let spawned = std::thread::Builder::new()
|
||||||
.name("prep-engine".into())
|
.name("prep-engine".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
let result = game_review::run(
|
let result = game_review::run(
|
||||||
uci::EngineConfig::new(&path),
|
review::engine_config(&path),
|
||||||
&job_settings,
|
&job_settings,
|
||||||
targets,
|
targets,
|
||||||
&cancel_w,
|
&cancel_w,
|
||||||
|
|
@ -1866,8 +1860,7 @@ impl PrepScreen {
|
||||||
cancel,
|
cancel,
|
||||||
total,
|
total,
|
||||||
done: 0,
|
done: 0,
|
||||||
threads,
|
processes,
|
||||||
nodes,
|
|
||||||
unsaved: 0,
|
unsaved: 0,
|
||||||
});
|
});
|
||||||
self.tab = Tab::Errors;
|
self.tab = Tab::Errors;
|
||||||
|
|
@ -1884,11 +1877,12 @@ impl PrepScreen {
|
||||||
JobMsg::Event(e) => {
|
JobMsg::Event(e) => {
|
||||||
if let JobEvent::Eval { nps, .. } = &e {
|
if let JobEvent::Eval { nps, .. } = &e {
|
||||||
job.done += 1;
|
job.done += 1;
|
||||||
|
// One engine thread per process.
|
||||||
if *nps > 0 {
|
if *nps > 0 {
|
||||||
self.nps_per_thread = Some(*nps as f64 / f64::from(job.threads));
|
self.nps_per_thread = Some(*nps as f64);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some((k, eval)) = report.apply(&e, job.nodes) {
|
if let Some((k, eval)) = report.apply(&e) {
|
||||||
self.cache.insert(k, eval);
|
self.cache.insert(k, eval);
|
||||||
job.unsaved += 1;
|
job.unsaved += 1;
|
||||||
got = true;
|
got = true;
|
||||||
|
|
@ -1960,7 +1954,7 @@ impl PrepScreen {
|
||||||
if !self.dialog_open {
|
if !self.dialog_open {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let mut action = None;
|
let mut start = false;
|
||||||
let moves = self.plies.div_ceil(2);
|
let moves = self.plies.div_ceil(2);
|
||||||
let (white_n, black_n) = self
|
let (white_n, black_n) = self
|
||||||
.report
|
.report
|
||||||
|
|
@ -1982,10 +1976,6 @@ impl PrepScreen {
|
||||||
.max_height((screen.height() - 160.0).max(100.0))
|
.max_height((screen.height() - 160.0).max(100.0))
|
||||||
.auto_shrink([false, true])
|
.auto_shrink([false, true])
|
||||||
.show(ui, |ui| {
|
.show(ui, |ui| {
|
||||||
if let Some(a) = review::engine_picker(ui, settings, "prep_engine") {
|
|
||||||
action = Some(a);
|
|
||||||
}
|
|
||||||
ui.add_space(4.0);
|
|
||||||
ui.horizontal_wrapped(|ui| {
|
ui.horizontal_wrapped(|ui| {
|
||||||
ui.label(tr("Colour"));
|
ui.label(tr("Colour"));
|
||||||
for (choice, n) in [
|
for (choice, n) in [
|
||||||
|
|
@ -1997,24 +1987,8 @@ impl PrepScreen {
|
||||||
ui.radio_value(&mut self.color, choice, label);
|
ui.radio_value(&mut self.color, choice, label);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
ui.add_space(4.0);
|
|
||||||
let mut quality = settings.prep.quality;
|
|
||||||
let (mut threads, mut hash) = (settings.review.threads, settings.review.hash_mb);
|
|
||||||
review::options_grid(
|
|
||||||
ui,
|
|
||||||
"prep_grid",
|
|
||||||
&mut quality,
|
|
||||||
&mut threads,
|
|
||||||
&mut hash,
|
|
||||||
Some(tr(
|
|
||||||
"For opening errors “Fast” is usually enough. “Normal” is for adult databases and takes 4 times longer.",
|
|
||||||
)),
|
|
||||||
);
|
|
||||||
settings.prep.quality = quality;
|
|
||||||
settings.review.threads = threads;
|
|
||||||
settings.review.hash_mb = hash;
|
|
||||||
ui.add_space(6.0);
|
ui.add_space(6.0);
|
||||||
let (missing, secs) = self.estimate(settings);
|
let (missing, secs) = self.estimate();
|
||||||
let all = self
|
let all = self
|
||||||
.report
|
.report
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|
@ -2036,46 +2010,28 @@ impl PrepScreen {
|
||||||
});
|
});
|
||||||
ui.add_space(10.0);
|
ui.add_space(10.0);
|
||||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||||
let ready = settings.active_engine().is_some();
|
|
||||||
if ui
|
if ui
|
||||||
.add_enabled(
|
.button(RichText::new(tr("Find errors")).strong().size(16.0))
|
||||||
ready,
|
|
||||||
egui::Button::new(RichText::new(tr("Find errors")).strong().size(16.0)),
|
|
||||||
)
|
|
||||||
.clicked()
|
.clicked()
|
||||||
{
|
{
|
||||||
action = Some(DialogAction::Start);
|
start = true;
|
||||||
}
|
}
|
||||||
if ui.button(tr("Cancel")).clicked() {
|
if ui.button(tr("Cancel")).clicked() {
|
||||||
self.dialog_open = false;
|
self.dialog_open = false;
|
||||||
}
|
}
|
||||||
if !ready {
|
|
||||||
ui.label(RichText::new(tr("Add an engine first")).color(ui.visuals().warn_fg_color));
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
if modal.should_close() {
|
if modal.should_close() {
|
||||||
self.dialog_open = false;
|
self.dialog_open = false;
|
||||||
}
|
}
|
||||||
if action.is_none()
|
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {
|
||||||
&& settings.active_engine().is_some()
|
start = true;
|
||||||
&& ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter))
|
|
||||||
{
|
|
||||||
action = Some(DialogAction::Start);
|
|
||||||
}
|
}
|
||||||
match action {
|
if start {
|
||||||
Some(DialogAction::Start) => {
|
self.dialog_open = false;
|
||||||
self.dialog_open = false;
|
settings.prep.chosen = true;
|
||||||
settings.prep.chosen = true;
|
actions.push(PrepAction::SettingsChanged);
|
||||||
actions.push(PrepAction::SettingsChanged);
|
self.engine_asked(settings, ctx, actions);
|
||||||
self.start_engine(settings, ctx, actions);
|
|
||||||
}
|
|
||||||
Some(DialogAction::EngineSwitch) => actions.push(PrepAction::EngineSwitch),
|
|
||||||
Some(DialogAction::OpenEngines) => {
|
|
||||||
self.dialog_open = false;
|
|
||||||
actions.push(PrepAction::OpenEngines);
|
|
||||||
}
|
|
||||||
None => {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2450,9 +2406,9 @@ impl PrepScreen {
|
||||||
let width = ui.available_width();
|
let width = ui.available_width();
|
||||||
let gap = ui.spacing().item_spacing.x;
|
let gap = ui.spacing().item_spacing.x;
|
||||||
let pad = 2.0 * ui.spacing().button_padding.x;
|
let pad = 2.0 * ui.spacing().button_padding.x;
|
||||||
let state = self.engine_state(settings);
|
let state = self.engine_state();
|
||||||
// The engine part on the right is measured first: the rest gets what it leaves.
|
// The engine part on the right is measured first: the rest gets what it leaves.
|
||||||
let engine = self.engine_texts(settings, state, width);
|
let engine = self.engine_texts(state, width);
|
||||||
let engine_w = match &engine {
|
let engine_w = match &engine {
|
||||||
EngineTexts::Running => (width * 0.35).clamp(90.0, 360.0) + text_width(ui, tr("Stop"), egui::TextStyle::Button) + pad + 2.0 * gap,
|
EngineTexts::Running => (width * 0.35).clamp(90.0, 360.0) + text_width(ui, tr("Stop"), egui::TextStyle::Button) + pad + 2.0 * gap,
|
||||||
EngineTexts::Button { label, note } | EngineTexts::Done { label, note } => {
|
EngineTexts::Button { label, note } | EngineTexts::Done { label, note } => {
|
||||||
|
|
@ -2534,8 +2490,8 @@ impl PrepScreen {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the engine part of the controls says, by the room there is.
|
/// What the engine part of the controls says, by the room there is.
|
||||||
fn engine_texts(&self, settings: &Settings, state: EngineState, width: f32) -> EngineTexts {
|
fn engine_texts(&self, state: EngineState, width: f32) -> EngineTexts {
|
||||||
let (missing, secs) = self.estimate(settings);
|
let (missing, secs) = self.estimate();
|
||||||
let time = review::format_duration(secs);
|
let time = review::format_duration(secs);
|
||||||
match state {
|
match state {
|
||||||
EngineState::Running => EngineTexts::Running,
|
EngineState::Running => EngineTexts::Running,
|
||||||
|
|
@ -2591,9 +2547,7 @@ impl PrepScreen {
|
||||||
self.stop_engine(actions);
|
self.stop_engine(actions);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let left = total.saturating_sub(done);
|
let secs = self.secs_for(total.saturating_sub(done), job.processes);
|
||||||
let per_thread = self.nps_per_thread.unwrap_or(review::DEFAULT_NPS);
|
|
||||||
let secs = review::estimate_secs(left, job.nodes, per_thread, job.threads);
|
|
||||||
let text = if width < 760.0 {
|
let text = if width < 760.0 {
|
||||||
format!("{}/{}", grouped(done), grouped(total))
|
format!("{}/{}", grouped(done), grouped(total))
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -2610,7 +2564,7 @@ impl PrepScreen {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let Some(report) = &self.report else { return };
|
let Some(report) = &self.report else { return };
|
||||||
let hint = self.engine_status(settings).unwrap_or_else(|| {
|
let hint = self.engine_status().unwrap_or_else(|| {
|
||||||
tr("The engine finds the opening errors in his games (Shift+A)").to_owned()
|
tr("The engine finds the opening errors in his games (Shift+A)").to_owned()
|
||||||
});
|
});
|
||||||
let _ = report;
|
let _ = report;
|
||||||
|
|
@ -2634,27 +2588,19 @@ impl PrepScreen {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// «Errors found · Stockfish 19 · Fast · 2 947 positions», once evaluated.
|
/// «Errors found · Stockfish 19 · 2 947 positions», once evaluated.
|
||||||
fn engine_status(&self, settings: &Settings) -> Option<String> {
|
fn engine_status(&self) -> Option<String> {
|
||||||
let report = self.report.as_ref()?;
|
let report = self.report.as_ref()?;
|
||||||
if !report.evaluated() {
|
if !report.evaluated() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let nodes = report.engine.as_ref().map_or(settings.prep.nodes(), |e| e.nodes);
|
|
||||||
let quality = REVIEW_QUALITY
|
|
||||||
.iter()
|
|
||||||
.find(|q| q.1 == nodes)
|
|
||||||
.map_or_else(|| review::format_count(nodes), |q| tr(q.0).to_owned());
|
|
||||||
let n = grouped(report.distinct_positions_for(self.color.side()));
|
let n = grouped(report.distinct_positions_for(self.color.side()));
|
||||||
Some(match report.engine.as_ref().filter(|e| !e.name.is_empty()) {
|
Some(match report.engine.as_ref().filter(|e| !e.name.is_empty()) {
|
||||||
Some(e) => trf(
|
Some(e) => trf(
|
||||||
"Errors found · {engine} · {quality} · {n} positions",
|
"Errors found · {engine} · {n} positions",
|
||||||
&[("engine", &e.name), ("quality", &quality), ("n", &n)],
|
&[("engine", &e.name), ("n", &n)],
|
||||||
),
|
|
||||||
None => trf(
|
|
||||||
"Errors found · {quality} · {n} positions",
|
|
||||||
&[("quality", &quality), ("n", &n)],
|
|
||||||
),
|
),
|
||||||
|
None => trf("Errors found · {n} positions", &[("n", &n)]),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -3882,10 +3828,10 @@ impl PrepScreen {
|
||||||
fn errors_tab(&mut self, ui: &mut Ui, settings: &mut Settings, actions: &mut Vec<PrepAction>) {
|
fn errors_tab(&mut self, ui: &mut Ui, settings: &mut Settings, actions: &mut Vec<PrepAction>) {
|
||||||
let Some(report) = self.report.as_ref() else { return };
|
let Some(report) = self.report.as_ref() else { return };
|
||||||
let moves = self.plies.div_ceil(2);
|
let moves = self.plies.div_ceil(2);
|
||||||
let state = self.engine_state(settings);
|
let state = self.engine_state();
|
||||||
if state == EngineState::NotRun {
|
if state == EngineState::NotRun {
|
||||||
// The invitation (§5).
|
// The invitation (§5).
|
||||||
let (positions, secs) = self.estimate(settings);
|
let (positions, secs) = self.estimate();
|
||||||
let games: usize = self.color.colours().iter().map(|&w| report.color(w).games.len()).sum();
|
let games: usize = self.color.colours().iter().map(|&w| report.color(w).games.len()).sum();
|
||||||
let colour = match self.color {
|
let colour = match self.color {
|
||||||
ColorChoice::White => tr("as White"),
|
ColorChoice::White => tr("as White"),
|
||||||
|
|
@ -3912,16 +3858,14 @@ impl PrepScreen {
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let (mut ask_engine, mut open_dialog) = (false, false);
|
let mut ask_engine = false;
|
||||||
let mut inaccuracies = settings.prep.inaccuracies;
|
let mut inaccuracies = settings.prep.inaccuracies;
|
||||||
// The state line: how far the engine got; the switch of the inaccuracies.
|
// The state line: how far the engine got; the switch of the inaccuracies.
|
||||||
ui.horizontal_wrapped(|ui| {
|
ui.horizontal_wrapped(|ui| {
|
||||||
match state {
|
match state {
|
||||||
EngineState::Running => {
|
EngineState::Running => {
|
||||||
if let Some(job) = &self.job {
|
if let Some(job) = &self.job {
|
||||||
let left = job.total.saturating_sub(job.done);
|
let secs = self.secs_for(job.total.saturating_sub(job.done), job.processes);
|
||||||
let per_thread = self.nps_per_thread.unwrap_or(review::DEFAULT_NPS);
|
|
||||||
let secs = review::estimate_secs(left, job.nodes, per_thread, job.threads);
|
|
||||||
ui.label(
|
ui.label(
|
||||||
RichText::new(trf(
|
RichText::new(trf(
|
||||||
"Checked {done} of {total} positions",
|
"Checked {done} of {total} positions",
|
||||||
|
|
@ -3933,7 +3877,7 @@ impl PrepScreen {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EngineState::Partial { done, total } => {
|
EngineState::Partial { done, total } => {
|
||||||
let (_, secs) = self.estimate(settings);
|
let (_, secs) = self.estimate();
|
||||||
ui.label(
|
ui.label(
|
||||||
RichText::new(trf(
|
RichText::new(trf(
|
||||||
"Checked {done} of {total} positions",
|
"Checked {done} of {total} positions",
|
||||||
|
|
@ -3951,19 +3895,9 @@ impl PrepScreen {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EngineState::Complete { .. } => {
|
EngineState::Complete { .. } => {
|
||||||
if let Some(status) = self.engine_status(settings) {
|
if let Some(status) = self.engine_status() {
|
||||||
ui.label(RichText::new(status).weak());
|
ui.label(RichText::new(status).weak());
|
||||||
}
|
}
|
||||||
if settings.prep.quality == 0 {
|
|
||||||
ui.label(RichText::new("·").weak());
|
|
||||||
if ui
|
|
||||||
.link(tr("More precisely…"))
|
|
||||||
.on_hover_text(tr("The same positions at «Normal» quality"))
|
|
||||||
.clicked()
|
|
||||||
{
|
|
||||||
open_dialog = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
EngineState::NotRun => {}
|
EngineState::NotRun => {}
|
||||||
}
|
}
|
||||||
|
|
@ -3982,9 +3916,6 @@ impl PrepScreen {
|
||||||
self.engine_asked(settings, ui.ctx(), actions);
|
self.engine_asked(settings, ui.ctx(), actions);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if open_dialog {
|
|
||||||
self.dialog_open = true;
|
|
||||||
}
|
|
||||||
let Some(report) = self.report.as_ref() else { return };
|
let Some(report) = self.report.as_ref() else { return };
|
||||||
// The lines per colour: in the stack only (beside the board the summary has them).
|
// The lines per colour: in the stack only (beside the board the summary has them).
|
||||||
if self.stacked {
|
if self.stacked {
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,15 @@
|
||||||
//! Whole-game analysis on the desktop: the background engine job over the main line,
|
//! Whole-game analysis on the desktop: the background engine job over the main line,
|
||||||
//! the evaluation graph under the board, the report tab and the launch dialog. The
|
//! the evaluation graph under the board and the report tab. The
|
||||||
//! evaluations, judgements, cache and the job itself are the `game-review` crate's,
|
//! evaluations, judgements, cache and the job itself are the `game-review` crate's,
|
||||||
//! shared with the Android app.
|
//! shared with the Android app.
|
||||||
//!
|
//!
|
||||||
//! The job uses its own engine process and never touches the game; writing the results
|
//! The job uses engine processes of its own — ChessPenguin's Stockfish 19 with the fixed
|
||||||
//! into the game is a separate, undoable action ([`Review::write_to_game`]).
|
//! search of `game_review::run`, the same on every computer, not the user's engine — and
|
||||||
|
//! never touches the game; writing the results into the game is a separate, undoable
|
||||||
|
//! action ([`Review::write_to_game`]).
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::PathBuf;
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::mpsc::{Receiver, channel};
|
use std::sync::mpsc::{Receiver, channel};
|
||||||
|
|
@ -15,24 +17,20 @@ use std::sync::mpsc::{Receiver, channel};
|
||||||
use chess_core::shakmaty::{Color, Move};
|
use chess_core::shakmaty::{Color, Move};
|
||||||
use chess_core::{Game, Nag, NodeId};
|
use chess_core::{Game, Nag, NodeId};
|
||||||
use egui::{Color32, RichText, Sense, Stroke, Ui, pos2, vec2};
|
use egui::{Color32, RichText, Sense, Stroke, Ui, pos2, vec2};
|
||||||
use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, ReviewMeta};
|
use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement};
|
||||||
|
|
||||||
pub use game_review::Mark;
|
pub use game_review::Mark;
|
||||||
|
|
||||||
use crate::i18n::{tr, trf};
|
use crate::i18n::{tr, trf};
|
||||||
use crate::settings::{EngineConfig, REVIEW_QUALITY, ReviewSettings, Settings};
|
use crate::settings::Settings;
|
||||||
|
|
||||||
pub enum ReportAction {
|
pub enum ReportAction {
|
||||||
Goto(NodeId),
|
Goto(NodeId),
|
||||||
Write,
|
Write,
|
||||||
|
/// Evaluate what is missing (all of it for a stale analysis).
|
||||||
Update,
|
Update,
|
||||||
Reanalyse,
|
/// The engine over evaluations read from the PGN.
|
||||||
}
|
Analyse,
|
||||||
|
|
||||||
pub enum DialogAction {
|
|
||||||
Start,
|
|
||||||
EngineSwitch,
|
|
||||||
OpenEngines,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum JobMsg {
|
enum JobMsg {
|
||||||
|
|
@ -46,7 +44,6 @@ struct Job {
|
||||||
cancel: Arc<AtomicBool>,
|
cancel: Arc<AtomicBool>,
|
||||||
total: usize,
|
total: usize,
|
||||||
done: usize,
|
done: usize,
|
||||||
threads: u32,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Job {
|
impl Drop for Job {
|
||||||
|
|
@ -62,8 +59,7 @@ pub struct Review {
|
||||||
pub error: Option<String>,
|
pub error: Option<String>,
|
||||||
/// Graph and report tab are shown.
|
/// Graph and report tab are shown.
|
||||||
pub visible: bool,
|
pub visible: bool,
|
||||||
pub dialog_open: bool,
|
/// Measured speed of one engine thread, for time estimates.
|
||||||
/// Measured engine speed per thread, for time estimates.
|
|
||||||
nps_per_thread: Option<f64>,
|
nps_per_thread: Option<f64>,
|
||||||
/// Report tab: index of the last visited error per side and kind.
|
/// Report tab: index of the last visited error per side and kind.
|
||||||
cycle: HashMap<(Color, Judgement), usize>,
|
cycle: HashMap<(Color, Judgement), usize>,
|
||||||
|
|
@ -82,7 +78,6 @@ impl Review {
|
||||||
analysis,
|
analysis,
|
||||||
job: None,
|
job: None,
|
||||||
error: None,
|
error: None,
|
||||||
dialog_open: false,
|
|
||||||
nps_per_thread: None,
|
nps_per_thread: None,
|
||||||
cycle: HashMap::new(),
|
cycle: HashMap::new(),
|
||||||
}
|
}
|
||||||
|
|
@ -110,48 +105,27 @@ impl Review {
|
||||||
self.analysis.refresh(game);
|
self.analysis.refresh(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the engine job. `full` discards earlier results; otherwise only positions
|
/// Starts the engine job with the engine at `path` (ChessPenguin's Stockfish). `full`
|
||||||
/// without an evaluation are analysed. Returns false if there is nothing to do.
|
/// discards earlier results; otherwise only positions without an evaluation are
|
||||||
pub fn start(
|
/// analysed (all of them for a stale analysis). Returns false if there is nothing to do.
|
||||||
&mut self,
|
pub fn start(&mut self, game: &Game, path: &Path, full: bool, ctx: &egui::Context) -> bool {
|
||||||
game: &Game,
|
|
||||||
engine: &EngineConfig,
|
|
||||||
rs: &ReviewSettings,
|
|
||||||
full: bool,
|
|
||||||
ctx: &egui::Context,
|
|
||||||
) -> bool {
|
|
||||||
self.job = None;
|
self.job = None;
|
||||||
self.error = None;
|
self.error = None;
|
||||||
let Some(path) = engine.executable() else {
|
let targets = self.analysis.begin(game, full);
|
||||||
self.error = Some(tr("The built-in engine is not part of this build").into());
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let meta = ReviewMeta {
|
|
||||||
engine: engine.name.clone(),
|
|
||||||
nodes: rs.nodes(),
|
|
||||||
};
|
|
||||||
let targets = self.analysis.begin(game, meta, full);
|
|
||||||
if targets.is_empty() {
|
if targets.is_empty() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
let cancel = Arc::new(AtomicBool::new(false));
|
let cancel = Arc::new(AtomicBool::new(false));
|
||||||
let total = targets.len();
|
let total = targets.len();
|
||||||
// Filling in keeps the quality of the earlier run (see `GameAnalysis::begin`).
|
let settings = JobSettings::new(processes(), None);
|
||||||
let nodes = self.analysis.meta.as_ref().map_or(rs.nodes(), |m| m.nodes);
|
let config = engine_config(path);
|
||||||
let settings = JobSettings {
|
|
||||||
threads: rs.threads.max(1),
|
|
||||||
hash_mb: rs.hash_mb,
|
|
||||||
nodes,
|
|
||||||
eval_file: None,
|
|
||||||
};
|
|
||||||
let threads = settings.threads;
|
|
||||||
let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone());
|
let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone());
|
||||||
let spawned = std::thread::Builder::new()
|
let spawned = std::thread::Builder::new()
|
||||||
.name("game-review".into())
|
.name("game-review".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
let result = game_review::run(
|
let result = game_review::run(
|
||||||
uci::EngineConfig::new(&path),
|
config,
|
||||||
&settings,
|
&settings,
|
||||||
targets,
|
targets,
|
||||||
&cancel_w,
|
&cancel_w,
|
||||||
|
|
@ -179,7 +153,6 @@ impl Review {
|
||||||
cancel,
|
cancel,
|
||||||
total,
|
total,
|
||||||
done: 0,
|
done: 0,
|
||||||
threads,
|
|
||||||
});
|
});
|
||||||
self.visible = true;
|
self.visible = true;
|
||||||
true
|
true
|
||||||
|
|
@ -202,8 +175,9 @@ impl Review {
|
||||||
JobMsg::Event(e) => {
|
JobMsg::Event(e) => {
|
||||||
if let JobEvent::Eval { nps, .. } = &e {
|
if let JobEvent::Eval { nps, .. } = &e {
|
||||||
job.done += 1;
|
job.done += 1;
|
||||||
|
// One engine thread per process.
|
||||||
if *nps > 0 {
|
if *nps > 0 {
|
||||||
self.nps_per_thread = Some(*nps as f64 / f64::from(job.threads));
|
self.nps_per_thread = Some(*nps as f64);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.analysis.apply(e);
|
self.analysis.apply(e);
|
||||||
|
|
@ -229,6 +203,22 @@ impl Review {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// "64 positions, about 20 s": what a full analysis of the game takes.
|
||||||
|
pub fn estimate(&self) -> String {
|
||||||
|
let secs = game_review::estimate_secs(
|
||||||
|
self.analysis.searches(),
|
||||||
|
self.nps_per_thread.unwrap_or(DEFAULT_NPS),
|
||||||
|
processes(),
|
||||||
|
);
|
||||||
|
trf(
|
||||||
|
"{n} positions, about {time}",
|
||||||
|
&[
|
||||||
|
("n", &self.analysis.positions()),
|
||||||
|
("time", &format_duration(secs)),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// After an inaccuracy, mistake or blunder: how the opponent punishes it and how
|
/// After an inaccuracy, mistake or blunder: how the opponent punishes it and how
|
||||||
/// the player best answers (shown as arrows, as on Lichess).
|
/// the player best answers (shown as arrows, as on Lichess).
|
||||||
pub fn refutation(&self, node: NodeId, game: &Game) -> Vec<Move> {
|
pub fn refutation(&self, node: NodeId, game: &Game) -> Vec<Move> {
|
||||||
|
|
@ -536,17 +526,29 @@ impl Review {
|
||||||
let missing = self.missing();
|
let missing = self.missing();
|
||||||
// An analysis from before !! and !: "Update" looks for them, nothing else.
|
// An analysis from before !! and !: "Update" looks for them, nothing else.
|
||||||
let seconds = self.analysis.seconds_missing();
|
let seconds = self.analysis.seconds_missing();
|
||||||
if (missing > 0 || seconds > 0) && !self.running() {
|
// An analysis of another search: "Update" makes it again.
|
||||||
|
let stale = self.analysis.stale();
|
||||||
|
if (stale || missing > 0 || seconds > 0) && !self.running() {
|
||||||
ui.horizontal_wrapped(|ui| {
|
ui.horizontal_wrapped(|ui| {
|
||||||
let text = if missing > 0 {
|
let text = if stale {
|
||||||
|
tr("This analysis was made with other engine settings").to_string()
|
||||||
|
} else if missing > 0 {
|
||||||
trf("Positions without evaluation: {n}", &[("n", &missing)])
|
trf("Positions without evaluation: {n}", &[("n", &missing)])
|
||||||
} else {
|
} else {
|
||||||
tr("!! and ! were not looked for in this analysis").to_string()
|
tr("!! and ! were not looked for in this analysis").to_string()
|
||||||
};
|
};
|
||||||
ui.label(RichText::new(text).color(ui.visuals().warn_fg_color));
|
ui.label(RichText::new(text).color(ui.visuals().warn_fg_color));
|
||||||
let can_update = self.analysis.meta.as_ref().is_some_and(|m| m.nodes > 0);
|
let can_update = self.analysis.meta.as_ref().is_some_and(|m| m.nodes > 0);
|
||||||
if can_update && ui.button(tr("Update")).clicked() {
|
if can_update {
|
||||||
action = Some(ReportAction::Update);
|
let mut button = ui.button(tr("Update"));
|
||||||
|
if stale {
|
||||||
|
button = button.on_hover_text(tr(
|
||||||
|
"Every position is analysed again, the same way on every computer",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if button.clicked() {
|
||||||
|
action = Some(ReportAction::Update);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -564,11 +566,16 @@ impl Review {
|
||||||
{
|
{
|
||||||
action = Some(ReportAction::Write);
|
action = Some(ReportAction::Write);
|
||||||
}
|
}
|
||||||
if ui
|
// Evaluations of the PGN: the engine can make its own (an engine analysis
|
||||||
.add_enabled(!self.running(), egui::Button::new(tr("Analyse again…")))
|
// made again would only repeat itself).
|
||||||
.clicked()
|
let pgn_only = self.analysis.meta.as_ref().is_some_and(|m| m.nodes == 0);
|
||||||
|
if pgn_only
|
||||||
|
&& ui
|
||||||
|
.add_enabled(!self.running(), egui::Button::new(tr("Analyse with the engine")))
|
||||||
|
.on_hover_text(self.estimate())
|
||||||
|
.clicked()
|
||||||
{
|
{
|
||||||
action = Some(ReportAction::Reanalyse);
|
action = Some(ReportAction::Analyse);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
action
|
action
|
||||||
|
|
@ -702,83 +709,6 @@ impl Review {
|
||||||
*k = k.wrapping_add(1) % hits.len();
|
*k = k.wrapping_add(1) % hits.len();
|
||||||
Some(hits[*k])
|
Some(hits[*k])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Launch dialog (engine, quality, threads, memory, time estimate).
|
|
||||||
pub fn dialog(&mut self, ctx: &egui::Context, settings: &mut Settings) -> Option<DialogAction> {
|
|
||||||
if !self.dialog_open {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let mut action = None;
|
|
||||||
let modal = egui::Modal::new(egui::Id::new("review_dialog")).show(ctx, |ui| {
|
|
||||||
ui.set_width(440.0);
|
|
||||||
ui.heading(tr("Game analysis"));
|
|
||||||
ui.label(
|
|
||||||
RichText::new(tr(
|
|
||||||
"The engine evaluates every position of the main line. The game itself is not changed.",
|
|
||||||
))
|
|
||||||
.weak(),
|
|
||||||
);
|
|
||||||
ui.add_space(8.0);
|
|
||||||
if let Some(a) = engine_picker(ui, settings, "review_engine") {
|
|
||||||
action = Some(a);
|
|
||||||
}
|
|
||||||
ui.add_space(4.0);
|
|
||||||
let rs = &mut settings.review;
|
|
||||||
let mut quality = rs.quality;
|
|
||||||
options_grid(
|
|
||||||
ui,
|
|
||||||
"review_grid",
|
|
||||||
&mut quality,
|
|
||||||
&mut rs.threads,
|
|
||||||
&mut rs.hash_mb,
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
rs.quality = quality;
|
|
||||||
ui.add_space(6.0);
|
|
||||||
let positions = self.analysis.positions();
|
|
||||||
let per_thread = self.nps_per_thread.unwrap_or(DEFAULT_NPS);
|
|
||||||
let searches = self.analysis.searches();
|
|
||||||
let secs = estimate_secs(searches, rs.nodes(), per_thread, rs.threads);
|
|
||||||
ui.label(trf(
|
|
||||||
"{n} positions, about {time}",
|
|
||||||
&[("n", &positions), ("time", &format_duration(secs))],
|
|
||||||
));
|
|
||||||
ui.add_space(10.0);
|
|
||||||
ui.horizontal(|ui| {
|
|
||||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
|
||||||
let ready = settings.active_engine().is_some();
|
|
||||||
if ui
|
|
||||||
.add_enabled(
|
|
||||||
ready,
|
|
||||||
egui::Button::new(RichText::new(tr("Analyse")).strong().size(16.0)),
|
|
||||||
)
|
|
||||||
.clicked()
|
|
||||||
{
|
|
||||||
action = Some(DialogAction::Start);
|
|
||||||
}
|
|
||||||
if ui.button(tr("Cancel")).clicked() {
|
|
||||||
self.dialog_open = false;
|
|
||||||
}
|
|
||||||
if !ready {
|
|
||||||
ui.label(
|
|
||||||
RichText::new(tr("Add an engine first"))
|
|
||||||
.color(ui.visuals().warn_fg_color),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
if modal.should_close() {
|
|
||||||
self.dialog_open = false;
|
|
||||||
}
|
|
||||||
if matches!(
|
|
||||||
action,
|
|
||||||
Some(DialogAction::Start | DialogAction::OpenEngines)
|
|
||||||
) {
|
|
||||||
self.dialog_open = false;
|
|
||||||
}
|
|
||||||
action
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Review {
|
impl Drop for Review {
|
||||||
|
|
@ -788,100 +718,22 @@ impl Drop for Review {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Nodes per second and thread assumed until an engine was measured.
|
/// Nodes per second of one engine thread assumed until an engine was measured.
|
||||||
pub const DEFAULT_NPS: f64 = 700_000.0;
|
pub const DEFAULT_NPS: f64 = 700_000.0;
|
||||||
|
|
||||||
/// Seconds `searches` of `nodes` take at `per_thread` nodes per second on `threads`.
|
/// Engine processes of a game analysis on this computer: one per logical CPU, at most
|
||||||
pub fn estimate_secs(searches: usize, nodes: u64, per_thread: f64, threads: u32) -> f64 {
|
/// `game_review::MAX_PROCESSES` and what the free memory holds.
|
||||||
searches as f64 * nodes as f64 / (per_thread * f64::from(threads.max(1)))
|
pub fn processes() -> usize {
|
||||||
|
game_review::processes(game_review::MAX_PROCESSES)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The «Engine» row of a launch dialog: the active engine, the others to switch to,
|
/// ChessPenguin's Stockfish at `path` for an analysis job: below the program (nice 10),
|
||||||
/// «Add or edit engines…».
|
/// so that the program stays smooth while every CPU works.
|
||||||
pub fn engine_picker(ui: &mut Ui, settings: &mut Settings, id: &str) -> Option<DialogAction> {
|
pub fn engine_config(path: &Path) -> uci::EngineConfig {
|
||||||
let mut action = None;
|
uci::EngineConfig {
|
||||||
ui.horizontal(|ui| {
|
nice: 10,
|
||||||
ui.label(tr("Engine"));
|
..uci::EngineConfig::new(path)
|
||||||
let current = settings
|
}
|
||||||
.active_engine()
|
|
||||||
.map(|e| e.name.clone())
|
|
||||||
.unwrap_or_else(|| tr("not selected").into());
|
|
||||||
egui::ComboBox::from_id_salt(id)
|
|
||||||
.selected_text(current)
|
|
||||||
.width(ui.available_width() - 8.0)
|
|
||||||
.show_ui(ui, |ui| {
|
|
||||||
for i in 0..settings.engines.len() {
|
|
||||||
let selected = settings.active_engine == Some(i);
|
|
||||||
if ui
|
|
||||||
.selectable_label(selected, &settings.engines[i].name)
|
|
||||||
.clicked()
|
|
||||||
&& !selected
|
|
||||||
{
|
|
||||||
settings.active_engine = Some(i);
|
|
||||||
action = Some(DialogAction::EngineSwitch);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ui.separator();
|
|
||||||
if ui.button(tr("Add or edit engines…")).clicked() {
|
|
||||||
action = Some(DialogAction::OpenEngines);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
action
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The «Quality · Threads · Memory» grid of a launch dialog; `quality` indexes
|
|
||||||
/// [`REVIEW_QUALITY`]. `quality_hint`: a tooltip on the quality slider.
|
|
||||||
pub fn options_grid(
|
|
||||||
ui: &mut Ui,
|
|
||||||
id: &str,
|
|
||||||
quality: &mut usize,
|
|
||||||
threads: &mut u32,
|
|
||||||
hash_mb: &mut u32,
|
|
||||||
quality_hint: Option<&str>,
|
|
||||||
) {
|
|
||||||
let cores = std::thread::available_parallelism()
|
|
||||||
.map(|n| n.get() as u32)
|
|
||||||
.unwrap_or(1);
|
|
||||||
let hash_steps = crate::game_view::hash_steps();
|
|
||||||
ui.spacing_mut().slider_width = 200.0;
|
|
||||||
egui::Grid::new(id)
|
|
||||||
.num_columns(3)
|
|
||||||
.spacing(vec2(12.0, 8.0))
|
|
||||||
.show(ui, |ui| {
|
|
||||||
ui.label(tr("Quality"));
|
|
||||||
let mut q = (*quality).min(REVIEW_QUALITY.len() - 1);
|
|
||||||
crate::game_view::index_slider(ui, &mut q, REVIEW_QUALITY.len());
|
|
||||||
*quality = q;
|
|
||||||
let label = ui.label(trf(
|
|
||||||
"{quality} · {nodes} nodes",
|
|
||||||
&[
|
|
||||||
("quality", &tr(REVIEW_QUALITY[q].0)),
|
|
||||||
("nodes", &format_count(REVIEW_QUALITY[q].1)),
|
|
||||||
],
|
|
||||||
));
|
|
||||||
if let Some(hint) = quality_hint {
|
|
||||||
label.on_hover_text(hint);
|
|
||||||
}
|
|
||||||
ui.end_row();
|
|
||||||
|
|
||||||
ui.label(tr("Threads"));
|
|
||||||
let mut th = (*threads).clamp(1, cores) as usize - 1;
|
|
||||||
crate::game_view::index_slider(ui, &mut th, cores as usize);
|
|
||||||
*threads = th as u32 + 1;
|
|
||||||
ui.label(format!("{} / {cores}", *threads));
|
|
||||||
ui.end_row();
|
|
||||||
|
|
||||||
ui.label(tr("Memory"));
|
|
||||||
let mut h = hash_steps
|
|
||||||
.iter()
|
|
||||||
.position(|m| *m >= *hash_mb)
|
|
||||||
.unwrap_or(hash_steps.len() - 1);
|
|
||||||
crate::game_view::index_slider(ui, &mut h, hash_steps.len());
|
|
||||||
*hash_mb = hash_steps[h];
|
|
||||||
ui.label(crate::game_view::format_mb(*hash_mb));
|
|
||||||
ui.end_row();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes `[%eval …]` commands from a comment.
|
/// Removes `[%eval …]` commands from a comment.
|
||||||
|
|
|
||||||
|
|
@ -118,8 +118,6 @@ pub struct Settings {
|
||||||
pub show_best_arrow: bool,
|
pub show_best_arrow: bool,
|
||||||
/// Recently opened PGN files, most recent first.
|
/// Recently opened PGN files, most recent first.
|
||||||
pub databases: Vec<PathBuf>,
|
pub databases: Vec<PathBuf>,
|
||||||
/// Whole-game analysis options.
|
|
||||||
pub review: ReviewSettings,
|
|
||||||
/// The first-start engine discovery has run (see `engines::first_run_setup`).
|
/// The first-start engine discovery has run (see `engines::first_run_setup`).
|
||||||
pub engines_discovered: bool,
|
pub engines_discovered: bool,
|
||||||
/// The sample databases were put on the shelf (see `examples::first_run_setup`).
|
/// The sample databases were put on the shelf (see `examples::first_run_setup`).
|
||||||
|
|
@ -153,19 +151,17 @@ pub struct Settings {
|
||||||
pub prep: PrepSettings,
|
pub prep: PrepSettings,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Options of the opponent preparation; threads and memory are the game analysis's.
|
/// Options of the opponent preparation; its engine search is the game analysis's.
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub struct PrepSettings {
|
pub struct PrepSettings {
|
||||||
/// Index into [`REVIEW_QUALITY`]; «Fast» is enough for opening errors.
|
|
||||||
pub quality: usize,
|
|
||||||
/// The book (`None`: the largest database on the shelf; `Some("")`: no book).
|
/// The book (`None`: the largest database on the shelf; `Some("")`: no book).
|
||||||
pub book: Option<PathBuf>,
|
pub book: Option<PathBuf>,
|
||||||
/// Plies of the opening the report looks at.
|
/// Plies of the opening the report looks at.
|
||||||
pub plies: usize,
|
pub plies: usize,
|
||||||
/// Moves with fewer games fold into «other moves».
|
/// Moves with fewer games fold into «other moves».
|
||||||
pub branches_from: u32,
|
pub branches_from: u32,
|
||||||
/// The engine was started from the dialog once: the button starts it at once.
|
/// The colour was chosen in the dialog once: the button starts the engine at once.
|
||||||
pub chosen: bool,
|
pub chosen: bool,
|
||||||
/// Inaccuracies (?!) are shown with the mistakes and blunders.
|
/// Inaccuracies (?!) are shown with the mistakes and blunders.
|
||||||
pub inaccuracies: bool,
|
pub inaccuracies: bool,
|
||||||
|
|
@ -176,7 +172,6 @@ pub struct PrepSettings {
|
||||||
impl Default for PrepSettings {
|
impl Default for PrepSettings {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
quality: 0,
|
|
||||||
book: None,
|
book: None,
|
||||||
plies: 20,
|
plies: 20,
|
||||||
branches_from: 3,
|
branches_from: 3,
|
||||||
|
|
@ -187,60 +182,6 @@ impl Default for PrepSettings {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PrepSettings {
|
|
||||||
pub fn nodes(&self) -> u64 {
|
|
||||||
REVIEW_QUALITY[self.quality.min(REVIEW_QUALITY.len() - 1)].1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Options of the whole-game analysis (the engine is the active one).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
||||||
#[serde(default)]
|
|
||||||
pub struct ReviewSettings {
|
|
||||||
/// Index into [`REVIEW_QUALITY`].
|
|
||||||
pub quality: usize,
|
|
||||||
pub threads: u32,
|
|
||||||
pub hash_mb: u32,
|
|
||||||
/// An analysis was started from the dialog once: «Analyse» starts the next one with
|
|
||||||
/// these options at once (the dialog stays for «Analyse again…»).
|
|
||||||
pub chosen: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ReviewSettings {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
quality: 1,
|
|
||||||
threads: default_threads(),
|
|
||||||
hash_mb: default_hash(),
|
|
||||||
chosen: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Search effort per position: (label, nodes).
|
|
||||||
pub const REVIEW_QUALITY: [(&str, u64); 3] = [
|
|
||||||
("Fast", 250_000),
|
|
||||||
("Normal", 1_000_000),
|
|
||||||
("Deep", 3_000_000),
|
|
||||||
];
|
|
||||||
|
|
||||||
impl ReviewSettings {
|
|
||||||
/// Options other than the defaults were chosen in the dialog (before `chosen` was
|
|
||||||
/// kept, 1.5): they count as chosen.
|
|
||||||
pub fn note_earlier_choice(&mut self) {
|
|
||||||
let default = ReviewSettings::default();
|
|
||||||
if (self.quality, self.threads, self.hash_mb)
|
|
||||||
!= (default.quality, default.threads, default.hash_mb)
|
|
||||||
{
|
|
||||||
self.chosen = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn nodes(&self) -> u64 {
|
|
||||||
REVIEW_QUALITY[self.quality.min(REVIEW_QUALITY.len() - 1)].1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for Settings {
|
impl Default for Settings {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
|
@ -260,7 +201,6 @@ impl Default for Settings {
|
||||||
active_engine: None,
|
active_engine: None,
|
||||||
show_best_arrow: true,
|
show_best_arrow: true,
|
||||||
databases: Vec::new(),
|
databases: Vec::new(),
|
||||||
review: ReviewSettings::default(),
|
|
||||||
engines_discovered: false,
|
engines_discovered: false,
|
||||||
examples_added: false,
|
examples_added: false,
|
||||||
check_updates: true,
|
check_updates: true,
|
||||||
|
|
@ -303,15 +243,13 @@ impl Settings {
|
||||||
migrate_legacy_config(&path);
|
migrate_legacy_config(&path);
|
||||||
match std::fs::read(&path) {
|
match std::fs::read(&path) {
|
||||||
Ok(bytes) => {
|
Ok(bytes) => {
|
||||||
let mut s: Settings = serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"settings: cannot parse {}: {e}; using defaults",
|
"settings: cannot parse {}: {e}; using defaults",
|
||||||
path.display()
|
path.display()
|
||||||
);
|
);
|
||||||
Self::default()
|
Self::default()
|
||||||
});
|
})
|
||||||
s.review.note_earlier_choice();
|
|
||||||
s
|
|
||||||
}
|
}
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::first_start(),
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::first_start(),
|
||||||
Err(_) => Self::default(),
|
Err(_) => Self::default(),
|
||||||
|
|
@ -375,13 +313,20 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
/// The settings of 1.x kept the engine options of the game analysis and the
|
||||||
|
/// quality of the preparation: they are read without them now.
|
||||||
#[test]
|
#[test]
|
||||||
fn options_chosen_before_count_as_chosen() {
|
fn settings_with_the_old_analysis_options_are_read() {
|
||||||
let mut r = ReviewSettings::default();
|
let old = r#"{
|
||||||
r.note_earlier_choice();
|
"language": "Ru",
|
||||||
assert!(!r.chosen, "the defaults: never chosen");
|
"review": {"quality": 2, "threads": 12, "hash_mb": 1024, "chosen": true},
|
||||||
r.quality = 2;
|
"prep": {"quality": 1, "plies": 16, "chosen": true}
|
||||||
r.note_earlier_choice();
|
}"#;
|
||||||
assert!(r.chosen);
|
let s: Settings = serde_json::from_str(old).expect("read");
|
||||||
|
assert_eq!(s.language, Lang::Ru);
|
||||||
|
assert_eq!(s.prep.plies, 16);
|
||||||
|
assert!(s.prep.chosen);
|
||||||
|
let json = serde_json::to_string(&s).expect("written");
|
||||||
|
assert!(!json.contains("\"review\"") && !json.contains("quality"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,40 @@
|
||||||
//! Our !! and ! against chess.com's on every game of `chesscom/` (see its README): run it
|
//! Our !! and ! against chess.com's on every game of `chesscom/` (see its README): run it
|
||||||
//! after each change of the rules, to see that a fix for one game broke no other.
|
//! after each change of the rules, to see that a fix for one game broke no other.
|
||||||
//!
|
//!
|
||||||
//! `cargo run --release -p game-review --example chesscom_check -- <engine> [nodes] [threads]`
|
//! `cargo run --release -p game-review --example chesscom_check -- <engine>`
|
||||||
|
//!
|
||||||
|
//! The engine searches as in the program: the fixed search of the game analysis
|
||||||
|
//! (`game_review::SEARCH_NODES` nodes, one thread, a clear hash), in one engine process
|
||||||
|
//! per CPU. `<engine>` is ChessPenguin's Stockfish 19.
|
||||||
|
//!
|
||||||
|
//! `CP_REVIEW_NODES=N` searches N nodes instead, for choosing the program's nodes (the
|
||||||
|
//! program itself never does): its evaluations are cached apart.
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::AtomicBool;
|
use std::sync::atomic::AtomicBool;
|
||||||
|
|
||||||
use chess_core::shakmaty::Color;
|
use chess_core::shakmaty::Color;
|
||||||
use chess_core::{Game, Nag};
|
use chess_core::{Game, Nag};
|
||||||
use game_review::{GameAnalysis, JobSettings, Judgement, ReviewMeta};
|
use game_review::{GameAnalysis, JobSettings, Judgement, SEARCH_NODES, SEARCH_VERSION};
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let args: Vec<String> = std::env::args().collect();
|
let args: Vec<String> = std::env::args().collect();
|
||||||
let Some(engine) = args.get(1) else {
|
let (Some(engine), 2) = (args.get(1), args.len()) else {
|
||||||
eprintln!("usage: chesscom_check <engine> [nodes = 3000000] [threads = 8]");
|
eprintln!("usage: chesscom_check <engine>");
|
||||||
std::process::exit(2);
|
std::process::exit(2);
|
||||||
};
|
};
|
||||||
let nodes: u64 = args.get(2).map_or(3_000_000, |n| n.parse().expect("nodes"));
|
let nodes: u64 = std::env::var("CP_REVIEW_NODES")
|
||||||
let threads: u32 = args.get(3).map_or(8, |n| n.parse().expect("threads"));
|
.map_or(SEARCH_NODES, |n| n.parse().expect("CP_REVIEW_NODES: a number"));
|
||||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||||
let cache = root
|
// Evaluations of one version of the fixed search are the same on every machine;
|
||||||
.join("../../target/chesscom-check")
|
// those of other nodes go apart.
|
||||||
.join(nodes.to_string());
|
let folder = if nodes == SEARCH_NODES {
|
||||||
|
format!("v{SEARCH_VERSION}")
|
||||||
|
} else {
|
||||||
|
format!("v{SEARCH_VERSION}-{nodes}")
|
||||||
|
};
|
||||||
|
let cache = root.join("../../target/chesscom-check").join(folder);
|
||||||
|
println!("{nodes} nodes per search");
|
||||||
std::fs::create_dir_all(&cache).expect("cache folder");
|
std::fs::create_dir_all(&cache).expect("cache folder");
|
||||||
|
|
||||||
let mut files: Vec<PathBuf> = std::fs::read_dir(root.join("chesscom"))
|
let mut files: Vec<PathBuf> = std::fs::read_dir(root.join("chesscom"))
|
||||||
|
|
@ -38,7 +51,7 @@ fn main() {
|
||||||
let text = std::fs::read_to_string(&file).expect("pgn");
|
let text = std::fs::read_to_string(&file).expect("pgn");
|
||||||
let game = chess_core::parse_str(&text).game;
|
let game = chess_core::parse_str(&text).game;
|
||||||
let mut a = GameAnalysis::new(&game, Some(&cache));
|
let mut a = GameAnalysis::new(&game, Some(&cache));
|
||||||
review(&mut a, &game, engine, nodes, threads);
|
review(&mut a, &game, engine, nodes);
|
||||||
a.save_cache(&cache).expect("cache");
|
a.save_cache(&cache).expect("cache");
|
||||||
let compared = game.tag("ChessComMarks").unwrap_or("!! !").to_owned();
|
let compared = game.tag("ChessComMarks").unwrap_or("!! !").to_owned();
|
||||||
println!(
|
println!(
|
||||||
|
|
@ -131,18 +144,15 @@ fn main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fills in what the cache lacks (all of it the first time) at `nodes`.
|
/// Fills in what the cache lacks (all of it the first time) at `nodes`.
|
||||||
fn review(a: &mut GameAnalysis, game: &Game, engine: &str, nodes: u64, threads: u32) {
|
fn review(a: &mut GameAnalysis, game: &Game, engine: &str, nodes: u64) {
|
||||||
let meta = ReviewMeta {
|
let targets = a.begin(game, false);
|
||||||
engine: "check".into(),
|
if let Some(m) = &mut a.meta {
|
||||||
nodes,
|
m.nodes = nodes;
|
||||||
};
|
}
|
||||||
let targets = a.begin(game, meta, false);
|
|
||||||
if !targets.is_empty() {
|
if !targets.is_empty() {
|
||||||
let settings = JobSettings {
|
let settings = JobSettings {
|
||||||
threads,
|
|
||||||
hash_mb: 256,
|
|
||||||
nodes,
|
nodes,
|
||||||
eval_file: None,
|
..JobSettings::new(game_review::processes(game_review::MAX_PROCESSES), None)
|
||||||
};
|
};
|
||||||
let cancel = AtomicBool::new(false);
|
let cancel = AtomicBool::new(false);
|
||||||
game_review::run(
|
game_review::run(
|
||||||
|
|
|
||||||
57
crates/game-review/examples/review_bench.rs
Normal file
57
crates/game-review/examples/review_bench.rs
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
//! Time of the fixed game analysis of one game, and a check that it is the same at any
|
||||||
|
//! number of engine processes: prints the time and a digest of every evaluation.
|
||||||
|
//!
|
||||||
|
//! `cargo run --release -p game-review --example review_bench -- <engine> <pgn> <processes>...`
|
||||||
|
|
||||||
|
use std::sync::atomic::AtomicBool;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use game_review::{GameAnalysis, JobSettings};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args: Vec<String> = std::env::args().collect();
|
||||||
|
if args.len() < 4 {
|
||||||
|
eprintln!("usage: review_bench <engine> <pgn> <processes>...");
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
let text = std::fs::read_to_string(&args[2]).expect("pgn");
|
||||||
|
let game = chess_core::parse_str(&text).game;
|
||||||
|
let mut digests = Vec::new();
|
||||||
|
for p in &args[3..] {
|
||||||
|
let processes: usize = p.parse().expect("processes");
|
||||||
|
let mut a = GameAnalysis::new(&game, None);
|
||||||
|
let targets = a.begin(&game, true);
|
||||||
|
let positions = targets.len();
|
||||||
|
let mut searches = 0;
|
||||||
|
let started = Instant::now();
|
||||||
|
game_review::run(
|
||||||
|
uci::EngineConfig::new(&args[1]),
|
||||||
|
&JobSettings::new(processes, None),
|
||||||
|
targets,
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
&mut |e| {
|
||||||
|
if let game_review::JobEvent::Eval { eval, .. } = &e {
|
||||||
|
searches += 1 + usize::from(eval.second.is_some());
|
||||||
|
}
|
||||||
|
a.apply(e);
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("engine");
|
||||||
|
let secs = started.elapsed().as_secs_f64();
|
||||||
|
// Every evaluation, line and second search, in the order of the game.
|
||||||
|
let all: Vec<_> = (0..a.line().len()).map(|i| a.eval_at(i).cloned()).collect();
|
||||||
|
let bytes = serde_json::to_vec(&all).expect("json");
|
||||||
|
let digest = bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
|
||||||
|
(h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)
|
||||||
|
});
|
||||||
|
println!(
|
||||||
|
"processes {processes:>2}: {positions} positions, {searches} searches, {secs:.1} s, \
|
||||||
|
evaluations {digest:016x}"
|
||||||
|
);
|
||||||
|
digests.push(digest);
|
||||||
|
}
|
||||||
|
if digests.windows(2).any(|w| w[0] != w[1]) {
|
||||||
|
println!("DIFFERENT evaluations");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,17 +1,80 @@
|
||||||
//! The engine job of a game analysis: its own engine process, one node-limited search
|
//! The engine job of a game analysis: one node-limited search per position, in engine
|
||||||
//! per position, results reported as they come. Runs on the caller's thread until it
|
//! processes of its own, results reported as they come. Runs on the caller's thread
|
||||||
//! is done or cancelled; the game is never touched.
|
//! until it is done or cancelled; the game is never touched.
|
||||||
|
//!
|
||||||
|
//! The search is the same everywhere (decision of 2026-10-28): every position is
|
||||||
|
//! searched to [`SEARCH_NODES`] nodes by an engine with one thread and a hash of
|
||||||
|
//! [`SEARCH_HASH_MB`], cleared (`ucinewgame`) before each search. One thread and a
|
||||||
|
//! clear hash make a search depend on its position alone — not on the machine, the
|
||||||
|
//! order of the positions or what was searched before — so every computer and phone
|
||||||
|
//! gets the same evaluations, and the same marks. Speed comes from several engine
|
||||||
|
//! processes, each taking the next position; their number changes nothing but the time.
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::collections::HashSet;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
use std::sync::mpsc::channel;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side};
|
use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side};
|
||||||
|
|
||||||
use crate::{Eval, PosEval, Second};
|
use crate::{Eval, PosEval, Second};
|
||||||
|
|
||||||
|
/// 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;
|
||||||
|
|
||||||
|
/// 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;
|
||||||
|
|
||||||
|
/// The version of the fixed search: [`SEARCH_NODES`], [`SEARCH_HASH_MB`], one thread, a
|
||||||
|
/// clear hash, and the engine (ChessPenguin's Stockfish 19). Raised when any of them
|
||||||
|
/// changes: evaluations of another version are stale and are made again, never mixed.
|
||||||
|
pub const SEARCH_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
/// Engine processes of a job on a computer at most.
|
||||||
|
pub const MAX_PROCESSES: usize = 8;
|
||||||
|
|
||||||
|
/// Engine processes of a job on a phone at most.
|
||||||
|
pub const PHONE_PROCESSES: usize = 4;
|
||||||
|
|
||||||
|
/// Memory of the engine's network, shared by all its processes (Stockfish 19 keeps it
|
||||||
|
/// in shared memory), in MB.
|
||||||
|
const SHARED_MB: u64 = 200;
|
||||||
|
|
||||||
|
/// Memory of one engine process of its own (the hash of [`SEARCH_HASH_MB`] included),
|
||||||
|
/// in MB.
|
||||||
|
const PROCESS_MB: u64 = 70;
|
||||||
|
|
||||||
/// A node-limited search should never take this long; stop it if it does.
|
/// A node-limited search should never take this long; stop it if it does.
|
||||||
const SEARCH_GUARD: Duration = Duration::from_secs(300);
|
const SEARCH_GUARD: Duration = Duration::from_secs(300);
|
||||||
|
|
||||||
|
/// Engine processes for a job on this machine: one per logical CPU, at most `limit`
|
||||||
|
/// (and [`MAX_PROCESSES`]), and no more than the free memory holds.
|
||||||
|
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)
|
||||||
|
});
|
||||||
|
cpus.min(limit).min(memory).clamp(1, MAX_PROCESSES)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Memory available to new processes (`MemAvailable` of Linux and Android), in MB;
|
||||||
|
/// `None` where it is not known.
|
||||||
|
fn available_mb() -> Option<u64> {
|
||||||
|
let info = std::fs::read_to_string("/proc/meminfo").ok()?;
|
||||||
|
let line = info.lines().find(|l| l.starts_with("MemAvailable:"))?;
|
||||||
|
let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
|
||||||
|
Some(kb / 1024)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds `searches` take at `nps` nodes per second of one engine process (one
|
||||||
|
/// thread), in `processes` of them: the time estimate of a run.
|
||||||
|
pub fn estimate_secs(searches: usize, nps: f64, processes: usize) -> f64 {
|
||||||
|
let rate = nps.max(1.0) * processes.clamp(1, MAX_PROCESSES) as f64;
|
||||||
|
searches as f64 * SEARCH_NODES as f64 / rate
|
||||||
|
}
|
||||||
|
|
||||||
/// A position to evaluate (from [`crate::GameAnalysis::begin`]).
|
/// A position to evaluate (from [`crate::GameAnalysis::begin`]).
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Target {
|
pub struct Target {
|
||||||
|
|
@ -27,15 +90,28 @@ pub struct Target {
|
||||||
pub known: Option<PosEval>,
|
pub known: Option<PosEval>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How the engine searches.
|
/// How the job runs; the search itself is fixed (see the module).
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct JobSettings {
|
pub struct JobSettings {
|
||||||
pub threads: u32,
|
/// Engine processes working at once (see [`processes`]).
|
||||||
pub hash_mb: u32,
|
pub processes: usize,
|
||||||
/// Nodes per position.
|
|
||||||
pub nodes: u64,
|
|
||||||
/// The network file of the engine (Stockfish `EvalFile`), when it is not beside it.
|
/// The network file of the engine (Stockfish `EvalFile`), when it is not beside it.
|
||||||
pub eval_file: Option<String>,
|
pub eval_file: Option<String>,
|
||||||
|
/// Nodes per search: [`SEARCH_NODES`] in the programs. Only an experiment (the
|
||||||
|
/// chess.com check, choosing the nodes) searches otherwise, never mixing its
|
||||||
|
/// evaluations with the programs'.
|
||||||
|
pub nodes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JobSettings {
|
||||||
|
/// The fixed search in `processes` engine processes.
|
||||||
|
pub fn new(processes: usize, eval_file: Option<String>) -> JobSettings {
|
||||||
|
JobSettings {
|
||||||
|
processes,
|
||||||
|
eval_file,
|
||||||
|
nodes: SEARCH_NODES,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the job reports, for [`crate::GameAnalysis::apply`].
|
/// What the job reports, for [`crate::GameAnalysis::apply`].
|
||||||
|
|
@ -46,7 +122,8 @@ pub enum JobEvent {
|
||||||
Eval {
|
Eval {
|
||||||
key: String,
|
key: String,
|
||||||
eval: PosEval,
|
eval: PosEval,
|
||||||
/// The engine's speed in this search (0 if it did not say).
|
/// The speed of the engine process in this search (one thread; 0 if it did
|
||||||
|
/// not say).
|
||||||
nps: u64,
|
nps: u64,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
@ -62,14 +139,75 @@ pub enum JobFailure {
|
||||||
Terminated(uci::TerminationReason),
|
Terminated(uci::TerminationReason),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluates `targets` one by one; `on_event` gets every result. Returns when all are
|
enum WorkerMsg {
|
||||||
/// done, or soon after `cancel` is set (then with `Ok`).
|
Event(JobEvent),
|
||||||
|
Failed(JobFailure),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates `targets` in `settings.processes` engine processes; `on_event` gets every
|
||||||
|
/// result, on the caller's thread, in the order they come. Returns when all are done,
|
||||||
|
/// or soon after `cancel` is set (then with `Ok`). When an engine fails, the others
|
||||||
|
/// stop too and the first failure is returned; what came before it was reported.
|
||||||
pub fn run(
|
pub fn run(
|
||||||
config: uci::EngineConfig,
|
config: uci::EngineConfig,
|
||||||
settings: &JobSettings,
|
settings: &JobSettings,
|
||||||
targets: Vec<Target>,
|
targets: Vec<Target>,
|
||||||
cancel: &AtomicBool,
|
cancel: &AtomicBool,
|
||||||
on_event: &mut dyn FnMut(JobEvent),
|
on_event: &mut dyn FnMut(JobEvent),
|
||||||
|
) -> Result<(), JobFailure> {
|
||||||
|
if targets.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let mut failure = None;
|
||||||
|
std::thread::scope(|s| {
|
||||||
|
for _ in 0..workers {
|
||||||
|
let tx = tx.clone();
|
||||||
|
let (config, targets, next, halted) = (config.clone(), &targets, &next, &halted);
|
||||||
|
s.spawn(move || {
|
||||||
|
let mut send = |e| {
|
||||||
|
let _ = tx.send(WorkerMsg::Event(e));
|
||||||
|
};
|
||||||
|
if let Err(e) = worker(config, settings, targets, next, halted, &mut send) {
|
||||||
|
let _ = tx.send(WorkerMsg::Failed(e));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
drop(tx);
|
||||||
|
let mut names = HashSet::new();
|
||||||
|
for msg in rx {
|
||||||
|
match msg {
|
||||||
|
WorkerMsg::Event(JobEvent::Engine(name)) => {
|
||||||
|
if names.insert(name.clone()) {
|
||||||
|
on_event(JobEvent::Engine(name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WorkerMsg::Event(e) => on_event(e),
|
||||||
|
WorkerMsg::Failed(e) => {
|
||||||
|
failed.store(true, Ordering::Relaxed);
|
||||||
|
failure.get_or_insert(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
match failure {
|
||||||
|
Some(e) if !cancel.load(Ordering::Relaxed) => Err(e),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One engine process: takes the next target until there is none or `halted`.
|
||||||
|
fn worker(
|
||||||
|
config: uci::EngineConfig,
|
||||||
|
settings: &JobSettings,
|
||||||
|
targets: &[Target],
|
||||||
|
next: &AtomicUsize,
|
||||||
|
halted: &dyn Fn() -> bool,
|
||||||
|
on_event: &mut dyn FnMut(JobEvent),
|
||||||
) -> Result<(), JobFailure> {
|
) -> Result<(), JobFailure> {
|
||||||
let handle = uci::Engine::spawn_with(config, Box::new(|| {}))
|
let handle = uci::Engine::spawn_with(config, Box::new(|| {}))
|
||||||
.map_err(|e| JobFailure::Start(e.to_string()))?;
|
.map_err(|e| JobFailure::Start(e.to_string()))?;
|
||||||
|
|
@ -82,31 +220,24 @@ pub fn run(
|
||||||
.map_err(|e| JobFailure::Start(e.to_string()))?;
|
.map_err(|e| JobFailure::Start(e.to_string()))?;
|
||||||
}
|
}
|
||||||
// Unknown options are not fatal: some engines lack Threads/Hash/MultiPV.
|
// Unknown options are not fatal: some engines lack Threads/Hash/MultiPV.
|
||||||
let _ = handle.set_threads(settings.threads.max(1));
|
let _ = handle.set_threads(1);
|
||||||
let _ = handle.set_hash_mb(settings.hash_mb.max(1));
|
let _ = handle.set_hash_mb(SEARCH_HASH_MB);
|
||||||
let _ = handle.set_multipv(1);
|
let _ = handle.set_multipv(1);
|
||||||
let _ = handle.new_game();
|
|
||||||
let mut next_id = 0;
|
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<String>| {
|
let mut search = |pos: &EnginePosition, among: Vec<String>| {
|
||||||
next_id += 1;
|
next_id += 1;
|
||||||
search_once(
|
let _ = handle.new_game();
|
||||||
&handle,
|
search_once(&handle, pos, SearchId(next_id), among, settings.nodes, halted)
|
||||||
pos,
|
|
||||||
SearchId(next_id),
|
|
||||||
among,
|
|
||||||
settings.nodes,
|
|
||||||
cancel,
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
for t in targets {
|
while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||||
let (mut eval, nps) = match t.known {
|
if halted() {
|
||||||
Some(e) => (e, 0),
|
break;
|
||||||
|
}
|
||||||
|
let (mut eval, nps) = match &t.known {
|
||||||
|
Some(e) => (e.clone(), 0),
|
||||||
None => {
|
None => {
|
||||||
let Some((info, best)) = search(&t.pos, Vec::new())? else {
|
let Some((info, best)) = search(&t.pos, Vec::new())? else {
|
||||||
if cancel.load(Ordering::Relaxed) {
|
|
||||||
handle.quit();
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let Some(score) = info.score else { continue };
|
let Some(score) = info.score else { continue };
|
||||||
|
|
@ -149,15 +280,12 @@ pub fn run(
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None if cancel.load(Ordering::Relaxed) => {
|
None if halted() => break,
|
||||||
handle.quit();
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
on_event(JobEvent::Eval {
|
on_event(JobEvent::Eval {
|
||||||
key: t.key,
|
key: t.key.clone(),
|
||||||
eval,
|
eval,
|
||||||
nps,
|
nps,
|
||||||
});
|
});
|
||||||
|
|
@ -167,14 +295,14 @@ pub fn run(
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One node-limited search: its last full line and the best move. `None` when it gave
|
/// One node-limited search: its last full line and the best move. `None` when it gave
|
||||||
/// no line or `cancel` was set.
|
/// no line or the job was halted.
|
||||||
fn search_once(
|
fn search_once(
|
||||||
handle: &uci::EngineHandle,
|
handle: &uci::EngineHandle,
|
||||||
pos: &EnginePosition,
|
pos: &EnginePosition,
|
||||||
id: SearchId,
|
id: SearchId,
|
||||||
among: Vec<String>,
|
among: Vec<String>,
|
||||||
nodes: u64,
|
nodes: u64,
|
||||||
cancel: &AtomicBool,
|
halted: &dyn Fn() -> bool,
|
||||||
) -> Result<Option<(uci::SearchInfo, Option<String>)>, JobFailure> {
|
) -> Result<Option<(uci::SearchInfo, Option<String>)>, JobFailure> {
|
||||||
handle
|
handle
|
||||||
.search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among)
|
.search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among)
|
||||||
|
|
@ -183,7 +311,7 @@ fn search_once(
|
||||||
let mut stopping = false;
|
let mut stopping = false;
|
||||||
let mut last: Option<uci::SearchInfo> = None;
|
let mut last: Option<uci::SearchInfo> = None;
|
||||||
loop {
|
loop {
|
||||||
if cancel.load(Ordering::Relaxed) {
|
if halted() {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
if !stopping && started.elapsed() > SEARCH_GUARD {
|
if !stopping && started.elapsed() > SEARCH_GUARD {
|
||||||
|
|
@ -215,36 +343,34 @@ fn search_once(
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::{GameAnalysis, ReviewMeta};
|
use crate::GameAnalysis;
|
||||||
|
|
||||||
/// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`) answers
|
/// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`).
|
||||||
/// like Stockfish: every position gets an evaluation, in order.
|
fn fake() -> &'static str {
|
||||||
#[test]
|
|
||||||
fn the_job_evaluates_every_position() {
|
|
||||||
let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci");
|
let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci");
|
||||||
assert!(
|
assert!(
|
||||||
std::path::Path::new(fake).exists(),
|
std::path::Path::new(fake).exists(),
|
||||||
"build the fake engine first: cargo build -p uci --bin fake_uci"
|
"build the fake engine first: cargo build -p uci --bin fake_uci"
|
||||||
);
|
);
|
||||||
|
fake
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settings(processes: usize) -> JobSettings {
|
||||||
|
JobSettings::new(processes, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fake engine answers like Stockfish: every position gets an evaluation.
|
||||||
|
#[test]
|
||||||
|
fn the_job_evaluates_every_position() {
|
||||||
let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game;
|
let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game;
|
||||||
let mut a = GameAnalysis::new(&game, None);
|
let mut a = GameAnalysis::new(&game, None);
|
||||||
let meta = ReviewMeta {
|
let targets = a.begin(&game, false);
|
||||||
engine: String::new(),
|
|
||||||
nodes: 1000,
|
|
||||||
};
|
|
||||||
let targets = a.begin(&game, meta, false);
|
|
||||||
let n = targets.len();
|
let n = targets.len();
|
||||||
let settings = JobSettings {
|
|
||||||
threads: 1,
|
|
||||||
hash_mb: 16,
|
|
||||||
nodes: 1000,
|
|
||||||
eval_file: None,
|
|
||||||
};
|
|
||||||
let mut evals = 0;
|
let mut evals = 0;
|
||||||
let cancel = AtomicBool::new(false);
|
let cancel = AtomicBool::new(false);
|
||||||
run(
|
run(
|
||||||
uci::EngineConfig::new(fake),
|
uci::EngineConfig::new(fake()),
|
||||||
&settings,
|
&settings(2),
|
||||||
targets,
|
targets,
|
||||||
&cancel,
|
&cancel,
|
||||||
&mut |e| {
|
&mut |e| {
|
||||||
|
|
@ -259,15 +385,16 @@ mod tests {
|
||||||
a.refresh(&game);
|
a.refresh(&game);
|
||||||
assert_eq!(a.missing(), 0);
|
assert_eq!(a.missing(), 0);
|
||||||
assert!(a.report.complete);
|
assert!(a.report.complete);
|
||||||
|
assert_eq!(a.meta.as_ref().map(|m| m.engine.as_str()), Some("Fake UCI"));
|
||||||
|
|
||||||
// A cancelled job ends at once, without results.
|
// A cancelled job ends at once, without results.
|
||||||
let mut b = GameAnalysis::new(&game, None);
|
let mut b = GameAnalysis::new(&game, None);
|
||||||
let targets = b.begin(&game, ReviewMeta::default(), false);
|
let targets = b.begin(&game, false);
|
||||||
cancel.store(true, Ordering::Relaxed);
|
cancel.store(true, Ordering::Relaxed);
|
||||||
let mut got = 0;
|
let mut got = 0;
|
||||||
run(
|
run(
|
||||||
uci::EngineConfig::new(fake),
|
uci::EngineConfig::new(fake()),
|
||||||
&settings,
|
&settings(3),
|
||||||
targets,
|
targets,
|
||||||
&cancel,
|
&cancel,
|
||||||
&mut |e| {
|
&mut |e| {
|
||||||
|
|
@ -279,4 +406,70 @@ mod tests {
|
||||||
.expect("cancelled cleanly");
|
.expect("cancelled cleanly");
|
||||||
assert_eq!(got, 0);
|
assert_eq!(got, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The evaluations depend on the positions alone: not on the number of engine
|
||||||
|
/// processes, nor on the order of the positions. The fake engine with `--hash-memory`
|
||||||
|
/// lets earlier searches change a score, as a hash kept between searches does: only
|
||||||
|
/// a clear hash before every search gives the same results.
|
||||||
|
#[test]
|
||||||
|
fn the_evaluations_do_not_depend_on_processes_or_order() {
|
||||||
|
let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 *").game;
|
||||||
|
let evaluate = |processes: usize, reverse: bool| {
|
||||||
|
let mut a = GameAnalysis::new(&game, None);
|
||||||
|
let mut targets = a.begin(&game, false);
|
||||||
|
if reverse {
|
||||||
|
targets.reverse();
|
||||||
|
}
|
||||||
|
let mut config = uci::EngineConfig::new(fake());
|
||||||
|
config.args = vec!["--hash-memory".into()];
|
||||||
|
run(
|
||||||
|
config,
|
||||||
|
&settings(processes),
|
||||||
|
targets,
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
&mut |e| a.apply(e),
|
||||||
|
)
|
||||||
|
.expect("the job runs");
|
||||||
|
a.refresh(&game);
|
||||||
|
(0..a.line().len())
|
||||||
|
.map(|i| a.eval_at(i).cloned())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
let one = evaluate(1, false);
|
||||||
|
assert!(one.iter().all(Option::is_some));
|
||||||
|
// The fake scores differ by position: the comparison means something.
|
||||||
|
assert!(one.windows(2).any(|w| w[0] != w[1]));
|
||||||
|
assert_eq!(evaluate(1, true), one);
|
||||||
|
assert_eq!(evaluate(3, false), one);
|
||||||
|
assert_eq!(evaluate(8, true), one);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failing_engine_fails_the_job() {
|
||||||
|
let game = chess_core::parse_str("1. e4 e5 *").game;
|
||||||
|
let mut a = GameAnalysis::new(&game, None);
|
||||||
|
let targets = a.begin(&game, false);
|
||||||
|
let result = run(
|
||||||
|
uci::EngineConfig::new("/nonexistent/engine"),
|
||||||
|
&settings(2),
|
||||||
|
targets,
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
&mut |_| {},
|
||||||
|
);
|
||||||
|
assert!(matches!(result, Err(JobFailure::Start(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn processes_are_bounded() {
|
||||||
|
assert_eq!(processes(1), 1);
|
||||||
|
assert!((1..=MAX_PROCESSES).contains(&processes(usize::MAX)));
|
||||||
|
assert_eq!(processes(0), 1);
|
||||||
|
assert!(processes(PHONE_PROCESSES) <= PHONE_PROCESSES);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_estimate_counts_every_process() {
|
||||||
|
assert_eq!(estimate_secs(10, 1_000_000.0, 1), 10.0);
|
||||||
|
assert_eq!(estimate_secs(10, 1_000_000.0, 4), 2.5);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,10 @@ mod job;
|
||||||
pub mod report;
|
pub mod report;
|
||||||
|
|
||||||
pub use features::{MoveFeatures, Rules};
|
pub use features::{MoveFeatures, Rules};
|
||||||
pub use job::{JobEvent, JobFailure, JobSettings, Target, run};
|
pub use job::{
|
||||||
|
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};
|
pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats, judge};
|
||||||
|
|
||||||
/// Engine result for one position of the main line.
|
/// Engine result for one position of the main line.
|
||||||
|
|
@ -54,6 +57,28 @@ pub struct ReviewMeta {
|
||||||
pub engine: String,
|
pub engine: String,
|
||||||
/// Nodes per position; 0 = read from `[%eval]` comments of the PGN.
|
/// Nodes per position; 0 = read from `[%eval]` comments of the PGN.
|
||||||
pub nodes: u64,
|
pub nodes: u64,
|
||||||
|
/// The version of the fixed search the engine made ([`SEARCH_VERSION`]); 0 for an
|
||||||
|
/// analysis from before it, whose user-chosen engine settings gave other results.
|
||||||
|
#[serde(default)]
|
||||||
|
pub search: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReviewMeta {
|
||||||
|
/// Evaluations of the fixed search of today (see [`run`]); the engine's name comes
|
||||||
|
/// with the job's [`JobEvent::Engine`].
|
||||||
|
pub fn fixed_search() -> ReviewMeta {
|
||||||
|
ReviewMeta {
|
||||||
|
engine: String::new(),
|
||||||
|
nodes: SEARCH_NODES,
|
||||||
|
search: SEARCH_VERSION,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Engine evaluations of another search than today's: shown, but never completed
|
||||||
|
/// with new ones — an update makes them all again.
|
||||||
|
pub fn is_stale(&self) -> bool {
|
||||||
|
self.nodes > 0 && self.search != SEARCH_VERSION
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
|
|
@ -136,6 +161,12 @@ impl GameAnalysis {
|
||||||
!self.evals.is_empty()
|
!self.evals.is_empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The evaluations come from another engine search than today's fixed one (an
|
||||||
|
/// analysis made before it): shown as they are until an update makes them again.
|
||||||
|
pub fn stale(&self) -> bool {
|
||||||
|
self.has_data() && self.meta.as_ref().is_some_and(ReviewMeta::is_stale)
|
||||||
|
}
|
||||||
|
|
||||||
/// Root and main-line nodes, in order: index `i` of [`Self::values`] belongs here.
|
/// Root and main-line nodes, in order: index `i` of [`Self::values`] belongs here.
|
||||||
pub fn line(&self) -> &[NodeId] {
|
pub fn line(&self) -> &[NodeId] {
|
||||||
&self.line
|
&self.line
|
||||||
|
|
@ -196,19 +227,23 @@ impl GameAnalysis {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Prepares an engine run: `full` drops the earlier results. Returns the positions
|
/// Prepares an engine run of the fixed search: `full` drops the earlier results, and
|
||||||
/// without an evaluation, for [`run`]. Filling in an engine analysis keeps its
|
/// so does an analysis of another search ([`Self::stale`]), so that one report never
|
||||||
/// nodes per position, so that one report never mixes two qualities: the run must use
|
/// mixes two. Returns the positions without an evaluation, for [`run`].
|
||||||
/// `self.meta`'s nodes, not the asked ones.
|
pub fn begin(&mut self, game: &Game, full: bool) -> Vec<Target> {
|
||||||
pub fn begin(&mut self, game: &Game, meta: ReviewMeta, full: bool) -> Vec<Target> {
|
if full || self.stale() {
|
||||||
if full {
|
|
||||||
self.evals.clear();
|
self.evals.clear();
|
||||||
}
|
}
|
||||||
let nodes = match &self.meta {
|
let engine = self
|
||||||
Some(old) if !full && old.nodes > 0 && self.has_data() => old.nodes,
|
.meta
|
||||||
_ => meta.nodes,
|
.take()
|
||||||
};
|
.filter(|m| !m.is_stale() && m.nodes > 0)
|
||||||
self.meta = Some(ReviewMeta { nodes, ..meta });
|
.map(|m| m.engine)
|
||||||
|
.unwrap_or_default();
|
||||||
|
self.meta = Some(ReviewMeta {
|
||||||
|
engine,
|
||||||
|
..ReviewMeta::fixed_search()
|
||||||
|
});
|
||||||
self.rebuild(game);
|
self.rebuild(game);
|
||||||
(0..self.line.len())
|
(0..self.line.len())
|
||||||
.filter_map(|i| {
|
.filter_map(|i| {
|
||||||
|
|
@ -275,7 +310,7 @@ impl GameAnalysis {
|
||||||
/// !! and ! ("Update" fills them in without evaluating anything again). None for
|
/// !! and ! ("Update" fills them in without evaluating anything again). None for
|
||||||
/// evaluations from the PGN, which have no engine lines.
|
/// evaluations from the PGN, which have no engine lines.
|
||||||
pub fn seconds_missing(&self) -> usize {
|
pub fn seconds_missing(&self) -> usize {
|
||||||
if self.meta.as_ref().is_none_or(|m| m.nodes == 0) {
|
if self.meta.as_ref().is_none_or(|m| m.nodes == 0 || m.is_stale()) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
(0..self.played.len())
|
(0..self.played.len())
|
||||||
|
|
@ -541,6 +576,7 @@ impl GameAnalysis {
|
||||||
self.meta = Some(ReviewMeta {
|
self.meta = Some(ReviewMeta {
|
||||||
engine: "PGN".into(),
|
engine: "PGN".into(),
|
||||||
nodes: 0,
|
nodes: 0,
|
||||||
|
search: 0,
|
||||||
});
|
});
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
@ -640,19 +676,8 @@ mod tests {
|
||||||
assert_eq!(s.values()[1], Some(Eval::Cp(0)));
|
assert_eq!(s.values()[1], Some(Eval::Cp(0)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
/// Fake engine results for `targets`: the evaluations fall by 3 pawns a move.
|
||||||
fn engine_results_are_cached_per_main_line() {
|
fn fake_results(a: &mut GameAnalysis, targets: Vec<Target>) {
|
||||||
let dir = std::env::temp_dir().join(format!("game-review-test-{}", std::process::id()));
|
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
|
||||||
let g = game("1. e4 e5 2. Nf3 *");
|
|
||||||
let mut a = GameAnalysis::new(&g, Some(&dir));
|
|
||||||
assert!(!a.has_data());
|
|
||||||
let meta = ReviewMeta {
|
|
||||||
engine: "Fake".into(),
|
|
||||||
nodes: 1000,
|
|
||||||
};
|
|
||||||
let targets = a.begin(&g, meta.clone(), false);
|
|
||||||
assert_eq!(targets.len(), 4);
|
|
||||||
for (i, t) in targets.into_iter().enumerate() {
|
for (i, t) in targets.into_iter().enumerate() {
|
||||||
a.apply(JobEvent::Eval {
|
a.apply(JobEvent::Eval {
|
||||||
key: t.key,
|
key: t.key,
|
||||||
|
|
@ -665,55 +690,48 @@ mod tests {
|
||||||
nps: 0,
|
nps: 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn engine_results_are_cached_per_main_line() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("game-review-test-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let g = game("1. e4 e5 2. Nf3 *");
|
||||||
|
let mut a = GameAnalysis::new(&g, Some(&dir));
|
||||||
|
assert!(!a.has_data());
|
||||||
|
let targets = a.begin(&g, false);
|
||||||
|
assert_eq!(targets.len(), 4);
|
||||||
|
a.apply(JobEvent::Engine("Fake".into()));
|
||||||
|
fake_results(&mut a, targets);
|
||||||
a.refresh(&g);
|
a.refresh(&g);
|
||||||
assert_eq!(a.missing(), 0);
|
assert_eq!(a.missing(), 0);
|
||||||
a.save_cache(&dir).expect("saved");
|
a.save_cache(&dir).expect("saved");
|
||||||
let b = GameAnalysis::new(&g, Some(&dir));
|
let b = GameAnalysis::new(&g, Some(&dir));
|
||||||
assert_eq!(b.meta, Some(meta));
|
let fixed = ReviewMeta {
|
||||||
|
engine: "Fake".into(),
|
||||||
|
..ReviewMeta::fixed_search()
|
||||||
|
};
|
||||||
|
assert_eq!(b.meta, Some(fixed.clone()));
|
||||||
|
assert!(!b.stale());
|
||||||
assert_eq!(b.values(), a.values());
|
assert_eq!(b.values(), a.values());
|
||||||
// 1.e4 was the engine's own move: never an error, whatever the evaluations say.
|
// 1.e4 was the engine's own move: never an error, whatever the evaluations say.
|
||||||
assert!(!b.marks.contains_key(&g.mainline()[0]));
|
assert!(!b.marks.contains_key(&g.mainline()[0]));
|
||||||
// Another main line has its own file.
|
// Another main line has its own file.
|
||||||
assert!(!GameAnalysis::new(&game("1. d4 *"), Some(&dir)).has_data());
|
assert!(!GameAnalysis::new(&game("1. d4 *"), Some(&dir)).has_data());
|
||||||
// Filling in keeps the quality of the first run.
|
|
||||||
let mut c = GameAnalysis::new(&g, Some(&dir));
|
|
||||||
let fast = ReviewMeta {
|
|
||||||
engine: "Fake".into(),
|
|
||||||
nodes: 250,
|
|
||||||
};
|
|
||||||
// Nothing left to evaluate; 1.e4, the engine's best, still wants the best other
|
// Nothing left to evaluate; 1.e4, the engine's best, still wants the best other
|
||||||
// move (an analysis from before !! and !).
|
// move (an analysis from before !! and !): filling in searches only that.
|
||||||
|
let mut c = GameAnalysis::new(&g, Some(&dir));
|
||||||
assert_eq!(c.seconds_missing(), 1);
|
assert_eq!(c.seconds_missing(), 1);
|
||||||
let left = c.begin(&g, fast.clone(), false);
|
let left = c.begin(&g, false);
|
||||||
assert_eq!(left.len(), 1);
|
assert_eq!(left.len(), 1);
|
||||||
assert!(left[0].known.is_some() && left[0].played.as_deref() == Some("e2e4"));
|
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!(!left[0].others.is_empty() && !left[0].others.contains(&"e2e4".to_string()));
|
||||||
assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(1000));
|
assert_eq!(c.meta, Some(fixed));
|
||||||
c.begin(&g, fast, true);
|
|
||||||
assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(250));
|
|
||||||
// A game without moves is never cached.
|
// A game without moves is never cached.
|
||||||
let empty = game("*");
|
let empty = game("*");
|
||||||
let mut e = GameAnalysis::new(&empty, Some(&dir));
|
let mut e = GameAnalysis::new(&empty, Some(&dir));
|
||||||
let t = e.begin(
|
let t = e.begin(&empty, false);
|
||||||
&empty,
|
fake_results(&mut e, t);
|
||||||
ReviewMeta {
|
|
||||||
engine: "Fake".into(),
|
|
||||||
nodes: 1000,
|
|
||||||
},
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
for t in t {
|
|
||||||
e.apply(JobEvent::Eval {
|
|
||||||
key: t.key,
|
|
||||||
eval: PosEval {
|
|
||||||
eval: Eval::Cp(20),
|
|
||||||
pv: vec![],
|
|
||||||
depth: 1,
|
|
||||||
second: None,
|
|
||||||
},
|
|
||||||
nps: 0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
e.save_cache(&dir).expect("nothing to save is fine");
|
e.save_cache(&dir).expect("nothing to save is fine");
|
||||||
assert!(
|
assert!(
|
||||||
!GameAnalysis::new(
|
!GameAnalysis::new(
|
||||||
|
|
@ -725,4 +743,43 @@ mod tests {
|
||||||
assert!(!GameAnalysis::new(&empty, Some(&dir)).has_data());
|
assert!(!GameAnalysis::new(&empty, Some(&dir)).has_data());
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An analysis cached before the fixed search (its meta without `search`, the nodes
|
||||||
|
/// the user chose) is shown, but stale: an update makes every evaluation again.
|
||||||
|
#[test]
|
||||||
|
fn an_analysis_of_another_search_is_stale() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("game-review-stale-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
let g = game("1. e4 e5 2. Nf3 *");
|
||||||
|
let mut a = GameAnalysis::new(&g, None);
|
||||||
|
let targets = a.begin(&g, false);
|
||||||
|
fake_results(&mut a, targets);
|
||||||
|
a.refresh(&g);
|
||||||
|
let path = a.cache_path(&dir);
|
||||||
|
a.save_cache(&dir).expect("saved");
|
||||||
|
// The file as 1.x wrote it: no `search` in the meta, 3M nodes.
|
||||||
|
let mut json: serde_json::Value =
|
||||||
|
serde_json::from_slice(&std::fs::read(&path).expect("cache")).expect("json");
|
||||||
|
let meta = json["meta"].as_object_mut().expect("meta");
|
||||||
|
meta.remove("search");
|
||||||
|
meta.insert("nodes".into(), 3_000_000.into());
|
||||||
|
meta.insert("engine".into(), "Stockfish 17".into());
|
||||||
|
std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written");
|
||||||
|
|
||||||
|
let mut old = GameAnalysis::new(&g, Some(&dir));
|
||||||
|
assert!(old.has_data() && old.stale());
|
||||||
|
assert_eq!(old.meta.as_ref().map(|m| m.search), Some(0));
|
||||||
|
assert_eq!(old.missing(), 0);
|
||||||
|
assert!(old.report.complete, "the old report is still shown");
|
||||||
|
assert_eq!(old.seconds_missing(), 0, "not filled in: made again");
|
||||||
|
let targets = old.begin(&g, false);
|
||||||
|
assert_eq!(targets.len(), 4, "every position again");
|
||||||
|
assert!(targets.iter().all(|t| t.known.is_none()));
|
||||||
|
assert!(!old.has_data() && !old.stale());
|
||||||
|
assert_eq!(old.meta, Some(ReviewMeta::fixed_search()));
|
||||||
|
// Evaluations of the PGN are not an engine search: never stale.
|
||||||
|
let pgn = game("1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} *");
|
||||||
|
assert!(!GameAnalysis::new(&pgn, None).stale());
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,9 +14,7 @@ use std::sync::{Arc, Mutex};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use chess_core::{Game, NodeId};
|
use chess_core::{Game, NodeId};
|
||||||
use game_review::{
|
use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, SideStats};
|
||||||
Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, ReviewMeta, SideStats,
|
|
||||||
};
|
|
||||||
use shakmaty::Color;
|
use shakmaty::Color;
|
||||||
|
|
||||||
use crate::EngineLine;
|
use crate::EngineLine;
|
||||||
|
|
@ -111,6 +109,9 @@ pub struct ReviewState {
|
||||||
pub engine: String,
|
pub engine: String,
|
||||||
/// Nodes per position; 0 for evaluations from the PGN.
|
/// Nodes per position; 0 for evaluations from the PGN.
|
||||||
pub nodes: u64,
|
pub nodes: u64,
|
||||||
|
/// The evaluations come from another engine search than today's fixed one (an
|
||||||
|
/// analysis made before it): shown, but "update" makes them all again.
|
||||||
|
pub stale: bool,
|
||||||
/// Positions of the main line without an evaluation.
|
/// Positions of the main line without an evaluation.
|
||||||
pub missing: u32,
|
pub missing: u32,
|
||||||
/// Evaluated positions still waiting for the second search of !! and ! (an analysis
|
/// Evaluated positions still waiting for the second search of !! and ! (an analysis
|
||||||
|
|
@ -121,8 +122,10 @@ pub struct ReviewState {
|
||||||
/// Engine searches a full analysis is expected to make (for the time estimate: a
|
/// Engine searches a full analysis is expected to make (for the time estimate: a
|
||||||
/// second search for moves that could be brilliant or great).
|
/// second search for moves that could be brilliant or great).
|
||||||
pub searches: u32,
|
pub searches: u32,
|
||||||
/// The engine's speed in the last run, per thread (0 when unknown).
|
/// The speed of one engine process in the last run (0 when unknown).
|
||||||
pub nps_per_thread: u64,
|
pub nps_per_process: u64,
|
||||||
|
/// Engine processes a run uses on this phone (for the time estimate).
|
||||||
|
pub processes: u32,
|
||||||
/// The start position and the position after every main-line move.
|
/// The start position and the position after every main-line move.
|
||||||
pub points: Vec<ReviewPoint>,
|
pub points: Vec<ReviewPoint>,
|
||||||
/// Where the middlegame and the endgame begin, as indices of `points`.
|
/// Where the middlegame and the endgame begin, as indices of `points`.
|
||||||
|
|
@ -143,7 +146,6 @@ enum Msg {
|
||||||
struct Job {
|
struct Job {
|
||||||
rx: Receiver<Msg>,
|
rx: Receiver<Msg>,
|
||||||
cancel: Arc<AtomicBool>,
|
cancel: Arc<AtomicBool>,
|
||||||
threads: u32,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Job {
|
impl Drop for Job {
|
||||||
|
|
@ -162,7 +164,7 @@ struct Inner {
|
||||||
done: u32,
|
done: u32,
|
||||||
total: u32,
|
total: u32,
|
||||||
failure: Option<String>,
|
failure: Option<String>,
|
||||||
nps_per_thread: u64,
|
nps_per_process: u64,
|
||||||
/// When the cache was last written: a long run is kept now and then, so that a
|
/// When the cache was last written: a long run is kept now and then, so that a
|
||||||
/// crash or a killed app loses little of it.
|
/// crash or a killed app loses little of it.
|
||||||
saved: Instant,
|
saved: Instant,
|
||||||
|
|
@ -196,7 +198,7 @@ impl GameReview {
|
||||||
done: 0,
|
done: 0,
|
||||||
total: 0,
|
total: 0,
|
||||||
failure: None,
|
failure: None,
|
||||||
nps_per_thread: 0,
|
nps_per_process: 0,
|
||||||
saved: Instant::now(),
|
saved: Instant::now(),
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
@ -206,37 +208,23 @@ impl GameReview {
|
||||||
#[uniffi::export]
|
#[uniffi::export]
|
||||||
impl GameReview {
|
impl GameReview {
|
||||||
/// Starts the engine at `path` (with its network `eval_file`, if not empty) on the
|
/// Starts the engine at `path` (with its network `eval_file`, if not empty) on the
|
||||||
/// positions without an evaluation, or on all of them when `full`. Returns false when
|
/// positions without an evaluation, or on all of them when `full` (or when the
|
||||||
/// there is nothing to analyse. Returns at once: the engine starts on its own thread.
|
/// analysis is stale). The search is the fixed one of every game analysis, the same
|
||||||
pub fn start(
|
/// as on the desktop. Returns false when there is nothing to analyse. Returns at
|
||||||
&self,
|
/// once: the engine starts on its own thread.
|
||||||
path: String,
|
pub fn start(&self, path: String, eval_file: String, full: bool) -> bool {
|
||||||
eval_file: String,
|
|
||||||
threads: u32,
|
|
||||||
hash_mb: u32,
|
|
||||||
nodes: u64,
|
|
||||||
full: bool,
|
|
||||||
) -> bool {
|
|
||||||
let mut st = lock(&self.inner);
|
let mut st = lock(&self.inner);
|
||||||
stop(&mut st);
|
stop(&mut st);
|
||||||
st.failure = None;
|
st.failure = None;
|
||||||
let meta = ReviewMeta {
|
|
||||||
engine: "Stockfish".into(),
|
|
||||||
nodes,
|
|
||||||
};
|
|
||||||
let Inner { game, analysis, .. } = &mut *st;
|
let Inner { game, analysis, .. } = &mut *st;
|
||||||
let targets = analysis.begin(game, meta, full);
|
let targets = analysis.begin(game, full);
|
||||||
if targets.is_empty() {
|
if targets.is_empty() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// Filling in keeps the quality of the earlier run (see `GameAnalysis::begin`).
|
let settings = JobSettings::new(
|
||||||
let nodes = analysis.meta.as_ref().map_or(nodes, |m| m.nodes);
|
phone_processes(),
|
||||||
let settings = JobSettings {
|
(!eval_file.is_empty()).then_some(eval_file),
|
||||||
threads: threads.max(1),
|
);
|
||||||
hash_mb: hash_mb.max(1),
|
|
||||||
nodes,
|
|
||||||
eval_file: (!eval_file.is_empty()).then_some(eval_file),
|
|
||||||
};
|
|
||||||
// Below the app (nice 10), as the live engine: the phone stays smooth.
|
// Below the app (nice 10), as the live engine: the phone stays smooth.
|
||||||
let config = uci::EngineConfig {
|
let config = uci::EngineConfig {
|
||||||
nice: 10,
|
nice: 10,
|
||||||
|
|
@ -247,7 +235,6 @@ impl GameReview {
|
||||||
let stop = cancel.clone();
|
let stop = cancel.clone();
|
||||||
st.total = targets.len() as u32;
|
st.total = targets.len() as u32;
|
||||||
st.done = 0;
|
st.done = 0;
|
||||||
let threads = settings.threads;
|
|
||||||
let spawned = std::thread::Builder::new()
|
let spawned = std::thread::Builder::new()
|
||||||
.name("game-review".into())
|
.name("game-review".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
|
|
@ -264,11 +251,7 @@ impl GameReview {
|
||||||
st.failure = Some(e.to_string());
|
st.failure = Some(e.to_string());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
st.job = Some(Job {
|
st.job = Some(Job { rx, cancel });
|
||||||
rx,
|
|
||||||
cancel,
|
|
||||||
threads,
|
|
||||||
});
|
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -285,6 +268,18 @@ impl GameReview {
|
||||||
analysis.refresh(game);
|
analysis.refresh(game);
|
||||||
snapshot(&st)
|
snapshot(&st)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Seconds a full analysis takes at `nps_per_process` nodes per second of one
|
||||||
|
/// engine process (measured before, or a guess), in this phone's processes.
|
||||||
|
pub fn estimate_secs(&self, nps_per_process: u64) -> u32 {
|
||||||
|
let st = lock(&self.inner);
|
||||||
|
game_review::estimate_secs(
|
||||||
|
st.analysis.searches(),
|
||||||
|
nps_per_process as f64,
|
||||||
|
phone_processes(),
|
||||||
|
)
|
||||||
|
.ceil() as u32
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for GameReview {
|
impl Drop for GameReview {
|
||||||
|
|
@ -316,13 +311,12 @@ fn drain(st: &mut Inner) {
|
||||||
Msg::Failed(e) => ended = Some(Some(e)),
|
Msg::Failed(e) => ended = Some(Some(e)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let threads = u64::from(job.threads.max(1));
|
|
||||||
let got = !events.is_empty();
|
let got = !events.is_empty();
|
||||||
for e in events {
|
for e in events {
|
||||||
if let JobEvent::Eval { nps, .. } = &e {
|
if let JobEvent::Eval { nps, .. } = &e {
|
||||||
st.done += 1;
|
st.done += 1;
|
||||||
if *nps > 0 {
|
if *nps > 0 {
|
||||||
st.nps_per_thread = nps / threads;
|
st.nps_per_process = *nps;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
st.analysis.apply(e);
|
st.analysis.apply(e);
|
||||||
|
|
@ -336,6 +330,13 @@ fn drain(st: &mut Inner) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Engine processes of a game analysis on a phone: one per core, at most
|
||||||
|
/// [`game_review::PHONE_PROCESSES`] and what the free memory holds; all below the app
|
||||||
|
/// (nice 10).
|
||||||
|
fn phone_processes() -> usize {
|
||||||
|
game_review::processes(game_review::PHONE_PROCESSES)
|
||||||
|
}
|
||||||
|
|
||||||
fn save(st: &mut Inner) {
|
fn save(st: &mut Inner) {
|
||||||
st.saved = Instant::now();
|
st.saved = Instant::now();
|
||||||
if let Some(dir) = &st.cache_dir {
|
if let Some(dir) = &st.cache_dir {
|
||||||
|
|
@ -437,11 +438,13 @@ fn snapshot(st: &Inner) -> ReviewState {
|
||||||
has_data: a.has_data(),
|
has_data: a.has_data(),
|
||||||
engine: meta.engine,
|
engine: meta.engine,
|
||||||
nodes: meta.nodes,
|
nodes: meta.nodes,
|
||||||
|
stale: a.stale(),
|
||||||
missing: a.missing() as u32,
|
missing: a.missing() as u32,
|
||||||
seconds_missing: a.seconds_missing() as u32,
|
seconds_missing: a.seconds_missing() as u32,
|
||||||
positions: a.positions() as u32,
|
positions: a.positions() as u32,
|
||||||
searches: a.searches() as u32,
|
searches: a.searches() as u32,
|
||||||
nps_per_thread: st.nps_per_thread,
|
nps_per_process: st.nps_per_process,
|
||||||
|
processes: phone_processes() as u32,
|
||||||
points,
|
points,
|
||||||
middlegame: a.report.phases.middlegame.map(|i| i as u32),
|
middlegame: a.report.phases.middlegame.map(|i| i as u32),
|
||||||
endgame: a.report.phases.endgame.map(|i| i as u32),
|
endgame: a.report.phases.endgame.map(|i| i as u32),
|
||||||
|
|
@ -478,7 +481,7 @@ mod tests {
|
||||||
assert!(ke7.best.is_none() && ke7.reply_from.is_none());
|
assert!(ke7.best.is_none() && ke7.reply_from.is_none());
|
||||||
assert!(s.white.accuracy.is_some());
|
assert!(s.white.accuracy.is_some());
|
||||||
// Nothing to analyse: every position has an evaluation.
|
// Nothing to analyse: every position has an evaluation.
|
||||||
assert!(!review.start("/nonexistent".into(), String::new(), 1, 16, 1000, false));
|
assert!(!review.start("/nonexistent".into(), String::new(), false));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// With the fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`).
|
/// With the fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`).
|
||||||
|
|
@ -495,7 +498,7 @@ mod tests {
|
||||||
let db = open_bytes("t.pgn".into(), b"1. e4 e5 2. Nf3 Nc6 *\n".to_vec()).unwrap();
|
let db = open_bytes("t.pgn".into(), b"1. e4 e5 2. Nf3 Nc6 *\n".to_vec()).unwrap();
|
||||||
let review = db.review(0, cache.clone()).unwrap();
|
let review = db.review(0, cache.clone()).unwrap();
|
||||||
assert!(!review.state().has_data);
|
assert!(!review.state().has_data);
|
||||||
assert!(review.start(fake.into(), String::new(), 1, 16, 1000, false));
|
assert!(review.start(fake.into(), String::new(), false));
|
||||||
let mut s = review.state();
|
let mut s = review.state();
|
||||||
for _ in 0..200 {
|
for _ in 0..200 {
|
||||||
if !s.running {
|
if !s.running {
|
||||||
|
|
@ -511,7 +514,8 @@ mod tests {
|
||||||
drop(review);
|
drop(review);
|
||||||
// The next time the game opens, the results are there without the engine.
|
// The next time the game opens, the results are there without the engine.
|
||||||
let again = db.review(0, cache).unwrap().state();
|
let again = db.review(0, cache).unwrap().state();
|
||||||
assert!(again.has_data && again.missing == 0 && again.nodes == 1000);
|
assert!(again.has_data && again.missing == 0 && !again.stale);
|
||||||
|
assert_eq!(again.nodes, game_review::SEARCH_NODES);
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -519,14 +523,7 @@ mod tests {
|
||||||
fn a_failing_engine_is_reported() {
|
fn a_failing_engine_is_reported() {
|
||||||
let db = open_bytes("t.pgn".into(), b"1. e4 e5 *\n".to_vec()).unwrap();
|
let db = open_bytes("t.pgn".into(), b"1. e4 e5 *\n".to_vec()).unwrap();
|
||||||
let review = db.review(0, String::new()).unwrap();
|
let review = db.review(0, String::new()).unwrap();
|
||||||
assert!(review.start(
|
assert!(review.start("/nonexistent/engine".into(), String::new(), false));
|
||||||
"/nonexistent/engine".into(),
|
|
||||||
String::new(),
|
|
||||||
1,
|
|
||||||
16,
|
|
||||||
1000,
|
|
||||||
false
|
|
||||||
));
|
|
||||||
let mut s = review.state();
|
let mut s = review.state();
|
||||||
for _ in 0..200 {
|
for _ in 0..200 {
|
||||||
if !s.running {
|
if !s.running {
|
||||||
|
|
|
||||||
|
|
@ -5,8 +5,8 @@
|
||||||
//!
|
//!
|
||||||
//! ```text
|
//! ```text
|
||||||
//! cargo run --release -p prep --example prep_report -- <database> "<player>" \
|
//! cargo run --release -p prep --example prep_report -- <database> "<player>" \
|
||||||
//! [--engine <path>] [--book <path>] [--plies 20] [--nodes 250000] \
|
//! [--engine <path>] [--book <path>] [--plies 20] [--processes N] \
|
||||||
//! [--threads N] [--min-games 3] [--no-cache]
|
//! [--min-games 3] [--no-cache]
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! The report and the evaluations are cached under `~/.cache/chesspenguin/prep/`
|
//! The report and the evaluations are cached under `~/.cache/chesspenguin/prep/`
|
||||||
|
|
@ -26,8 +26,7 @@ struct Args {
|
||||||
engine: Option<PathBuf>,
|
engine: Option<PathBuf>,
|
||||||
book: Option<PathBuf>,
|
book: Option<PathBuf>,
|
||||||
plies: usize,
|
plies: usize,
|
||||||
nodes: u64,
|
processes: usize,
|
||||||
threads: u32,
|
|
||||||
min_games: u32,
|
min_games: u32,
|
||||||
cache: bool,
|
cache: bool,
|
||||||
}
|
}
|
||||||
|
|
@ -40,10 +39,7 @@ fn args() -> Args {
|
||||||
engine: None,
|
engine: None,
|
||||||
book: None,
|
book: None,
|
||||||
plies: prep::DEFAULT_PLIES,
|
plies: prep::DEFAULT_PLIES,
|
||||||
nodes: 250_000,
|
processes: game_review::processes(game_review::MAX_PROCESSES),
|
||||||
threads: std::thread::available_parallelism()
|
|
||||||
.map(|n| (n.get() as u32 / 2).max(1))
|
|
||||||
.unwrap_or(1),
|
|
||||||
min_games: 3,
|
min_games: 3,
|
||||||
cache: true,
|
cache: true,
|
||||||
};
|
};
|
||||||
|
|
@ -53,8 +49,9 @@ fn args() -> Args {
|
||||||
"--engine" => a.engine = it.next().map(PathBuf::from),
|
"--engine" => a.engine = it.next().map(PathBuf::from),
|
||||||
"--book" => a.book = it.next().map(PathBuf::from),
|
"--book" => a.book = it.next().map(PathBuf::from),
|
||||||
"--plies" => a.plies = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.plies),
|
"--plies" => a.plies = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.plies),
|
||||||
"--nodes" => a.nodes = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.nodes),
|
"--processes" => {
|
||||||
"--threads" => a.threads = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.threads),
|
a.processes = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.processes)
|
||||||
|
}
|
||||||
"--min-games" => {
|
"--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)
|
||||||
}
|
}
|
||||||
|
|
@ -324,12 +321,7 @@ fn main() {
|
||||||
report.distinct_positions(),
|
report.distinct_positions(),
|
||||||
cache.len()
|
cache.len()
|
||||||
);
|
);
|
||||||
let settings = game_review::JobSettings {
|
let settings = game_review::JobSettings::new(a.processes, None);
|
||||||
threads: a.threads,
|
|
||||||
hash_mb: 256,
|
|
||||||
nodes: a.nodes,
|
|
||||||
eval_file: None,
|
|
||||||
};
|
|
||||||
let t = Instant::now();
|
let t = Instant::now();
|
||||||
let mut last_shown = Instant::now();
|
let mut last_shown = Instant::now();
|
||||||
let mut first = true;
|
let mut first = true;
|
||||||
|
|
@ -342,7 +334,10 @@ fn main() {
|
||||||
&never,
|
&never,
|
||||||
&mut |p| {
|
&mut |p| {
|
||||||
if first {
|
if first {
|
||||||
println!("[engine] {} positions to evaluate at {} nodes, {} threads", p.total, a.nodes, a.threads);
|
println!(
|
||||||
|
"[engine] {} positions to evaluate, {} engine processes",
|
||||||
|
p.total, a.processes
|
||||||
|
);
|
||||||
first = false;
|
first = false;
|
||||||
}
|
}
|
||||||
if last_shown.elapsed().as_secs_f64() >= 5.0 {
|
if last_shown.elapsed().as_secs_f64() >= 5.0 {
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ use std::path::{Path, PathBuf};
|
||||||
use chess_core::shakmaty::san::SanPlus;
|
use chess_core::shakmaty::san::SanPlus;
|
||||||
use chess_core::shakmaty::uci::UciMove;
|
use chess_core::shakmaty::uci::UciMove;
|
||||||
use chess_core::shakmaty::{Chess, Color, Position};
|
use chess_core::shakmaty::{Chess, Color, Position};
|
||||||
use game_review::{Eval, Judgement, PosEval};
|
use game_review::{Eval, Judgement, PosEval, SEARCH_VERSION};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::games::{GameInfo, Tally};
|
use crate::games::{GameInfo, Tally};
|
||||||
|
|
@ -220,6 +220,10 @@ const CACHE_LIMIT: usize = 1_000_000;
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
struct CacheFile {
|
struct CacheFile {
|
||||||
version: u32,
|
version: u32,
|
||||||
|
/// The version of the fixed search the evaluations come from ([`SEARCH_VERSION`];
|
||||||
|
/// 0: from before it). Those of another one are not used.
|
||||||
|
#[serde(default)]
|
||||||
|
search: u32,
|
||||||
positions: Vec<(u64, PositionEval)>,
|
positions: Vec<(u64, PositionEval)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -241,7 +245,7 @@ impl PositionCache {
|
||||||
let entries = std::fs::read(Self::path(dir))
|
let entries = std::fs::read(Self::path(dir))
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|bytes| serde_json::from_slice::<CacheFile>(&bytes).ok())
|
.and_then(|bytes| serde_json::from_slice::<CacheFile>(&bytes).ok())
|
||||||
.filter(|f| f.version == CACHE_VERSION)
|
.filter(|f| f.version == CACHE_VERSION && f.search == SEARCH_VERSION)
|
||||||
.map(|f| f.positions.into_iter().collect())
|
.map(|f| f.positions.into_iter().collect())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
PositionCache {
|
PositionCache {
|
||||||
|
|
@ -292,6 +296,7 @@ impl PositionCache {
|
||||||
}
|
}
|
||||||
let file = CacheFile {
|
let file = CacheFile {
|
||||||
version: CACHE_VERSION,
|
version: CACHE_VERSION,
|
||||||
|
search: SEARCH_VERSION,
|
||||||
positions,
|
positions,
|
||||||
};
|
};
|
||||||
let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?;
|
let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?;
|
||||||
|
|
@ -386,6 +391,13 @@ mod tests {
|
||||||
assert_eq!(d.get(1), c.get(1));
|
assert_eq!(d.get(1), c.get(1));
|
||||||
assert_eq!(d.get(2).map(|e| e.nodes), Some(EXACT));
|
assert_eq!(d.get(2).map(|e| e.nodes), Some(EXACT));
|
||||||
assert_eq!(d.get(3), None);
|
assert_eq!(d.get(3), None);
|
||||||
|
// A cache from before the fixed search of the game analysis is not used.
|
||||||
|
let path = PositionCache::path(&dir);
|
||||||
|
let mut json: serde_json::Value =
|
||||||
|
serde_json::from_slice(&std::fs::read(&path).expect("cache")).expect("json");
|
||||||
|
json.as_object_mut().expect("cache").remove("search");
|
||||||
|
std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written");
|
||||||
|
assert!(PositionCache::load(&dir).is_empty());
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
|
|
||||||
use chess_import::Database;
|
use chess_import::Database;
|
||||||
use game_review::{JobEvent, JobFailure, JobSettings, Target};
|
use game_review::{JobEvent, JobFailure, JobSettings, SEARCH_NODES, SEARCH_VERSION, Target};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use uci::EnginePosition;
|
use uci::EnginePosition;
|
||||||
|
|
||||||
|
|
@ -125,7 +125,7 @@ impl ColorReport {
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct EngineInfo {
|
pub struct EngineInfo {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// Nodes per position asked for (an evaluation from the cache may have more).
|
/// Nodes per position.
|
||||||
pub nodes: u64,
|
pub nodes: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -167,6 +167,10 @@ pub struct PrepReport {
|
||||||
pub engine: Option<EngineInfo>,
|
pub engine: Option<EngineInfo>,
|
||||||
/// Engine evaluations by position key.
|
/// Engine evaluations by position key.
|
||||||
pub evals: HashMap<u64, PositionEval>,
|
pub evals: HashMap<u64, PositionEval>,
|
||||||
|
/// The version of the fixed search of the game analysis the evaluations come from
|
||||||
|
/// ([`SEARCH_VERSION`]; 0: from before it, made with the user's engine settings).
|
||||||
|
#[serde(default)]
|
||||||
|
pub search: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Identity of a database for the report cache: the content of a PGN file, the
|
/// Identity of a database for the report cache: the content of a PGN file, the
|
||||||
|
|
@ -270,6 +274,7 @@ pub fn build(
|
||||||
book_counts: HashMap::new(),
|
book_counts: HashMap::new(),
|
||||||
engine: None,
|
engine: None,
|
||||||
evals,
|
evals,
|
||||||
|
search: SEARCH_VERSION,
|
||||||
};
|
};
|
||||||
report.refresh();
|
report.refresh();
|
||||||
Some(report)
|
Some(report)
|
||||||
|
|
@ -416,29 +421,28 @@ impl PrepReport {
|
||||||
self.positions_for(side).len()
|
self.positions_for(side).len()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Positions without an evaluation of at least `nodes`.
|
/// Positions without an evaluation.
|
||||||
pub fn missing(&self, nodes: u64) -> usize {
|
pub fn missing(&self) -> usize {
|
||||||
self.missing_for(nodes, Side::Any)
|
self.missing_for(Side::Any)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [`PrepReport::missing`] among the games the player had `side` in.
|
/// [`PrepReport::missing`] among the games the player had `side` in.
|
||||||
pub fn missing_for(&self, nodes: u64, side: Side) -> usize {
|
pub fn missing_for(&self, side: Side) -> usize {
|
||||||
self.positions_for(side)
|
self.positions_for(side)
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(k, _, _)| !self.evals.get(k).is_some_and(|e| e.nodes >= nodes))
|
.filter(|(k, _, _)| !self.evals.contains_key(k))
|
||||||
.count()
|
.count()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Takes from `cache` the evaluations of at least `nodes` the report lacks;
|
/// Takes from `cache` the evaluations the report lacks; returns how many.
|
||||||
/// returns how many.
|
pub fn take_cached(&mut self, cache: &PositionCache) -> usize {
|
||||||
pub fn take_cached(&mut self, cache: &PositionCache, nodes: u64) -> usize {
|
|
||||||
let keys: Vec<u64> = self.positions().iter().map(|(k, _, _)| *k).collect();
|
let keys: Vec<u64> = self.positions().iter().map(|(k, _, _)| *k).collect();
|
||||||
let mut taken = 0;
|
let mut taken = 0;
|
||||||
for k in keys {
|
for k in keys {
|
||||||
if self.evals.get(&k).is_some_and(|e| e.nodes >= nodes) {
|
if self.evals.contains_key(&k) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Some(e) = cache.get(k).filter(|e| e.nodes >= nodes) {
|
if let Some(e) = cache.get(k) {
|
||||||
self.evals.insert(k, e.clone());
|
self.evals.insert(k, e.clone());
|
||||||
taken += 1;
|
taken += 1;
|
||||||
}
|
}
|
||||||
|
|
@ -449,19 +453,19 @@ impl PrepReport {
|
||||||
taken
|
taken
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The positions still to evaluate at `nodes`, for [`game_review::run`] (one
|
/// The positions still to evaluate, for [`game_review::run`] (one search each, no
|
||||||
/// search each, no second search for !! and !). Their keys are the position keys
|
/// second search for !! and !). Their keys are the position keys in hexadecimal, as
|
||||||
/// in hexadecimal, as [`PrepReport::apply`] reads them.
|
/// [`PrepReport::apply`] reads them.
|
||||||
pub fn targets(&self, nodes: u64) -> Vec<Target> {
|
pub fn targets(&self) -> Vec<Target> {
|
||||||
self.targets_for(nodes, Side::Any)
|
self.targets_for(Side::Any)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [`PrepReport::targets`] of the games the player had `side` in (the dialog's
|
/// [`PrepReport::targets`] of the games the player had `side` in (the dialog's
|
||||||
/// «Black — 133 games» halves the work).
|
/// «Black — 133 games» halves the work).
|
||||||
pub fn targets_for(&self, nodes: u64, side: Side) -> Vec<Target> {
|
pub fn targets_for(&self, side: Side) -> Vec<Target> {
|
||||||
self.positions_for(side)
|
self.positions_for(side)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|(k, _, _)| !self.evals.get(k).is_some_and(|e| e.nodes >= nodes))
|
.filter(|(k, _, _)| !self.evals.contains_key(k))
|
||||||
.map(|(k, g, i)| Target {
|
.map(|(k, g, i)| Target {
|
||||||
key: format!("{k:016x}"),
|
key: format!("{k:016x}"),
|
||||||
pos: EnginePosition::startpos(g.ucis[..i].iter().cloned()),
|
pos: EnginePosition::startpos(g.ucis[..i].iter().cloned()),
|
||||||
|
|
@ -477,10 +481,10 @@ impl PrepReport {
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Takes in what the engine job reported for a run at `nodes`; the evaluation
|
/// Takes in what the engine job reported; the evaluation it carried (to cache), if
|
||||||
/// it carried (to cache), if any. The errors are re-judged on the next
|
/// any. The errors are re-judged on the next [`PrepReport::refresh`].
|
||||||
/// [`PrepReport::refresh`].
|
pub fn apply(&mut self, event: &JobEvent) -> Option<(u64, PositionEval)> {
|
||||||
pub fn apply(&mut self, event: &JobEvent, nodes: u64) -> Option<(u64, PositionEval)> {
|
let nodes = SEARCH_NODES;
|
||||||
match event {
|
match event {
|
||||||
JobEvent::Engine(name) => {
|
JobEvent::Engine(name) => {
|
||||||
self.engine = Some(EngineInfo {
|
self.engine = Some(EngineInfo {
|
||||||
|
|
@ -561,13 +565,24 @@ impl PrepReport {
|
||||||
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 fp = fingerprint(db);
|
||||||
let bytes = std::fs::read(Self::cache_path(dir, fp, player, options)).ok()?;
|
let bytes = std::fs::read(Self::cache_path(dir, fp, player, options)).ok()?;
|
||||||
let report: PrepReport = serde_json::from_slice(&bytes).ok()?;
|
let mut report: PrepReport = serde_json::from_slice(&bytes).ok()?;
|
||||||
(report.version == REPORT_VERSION
|
let same = report.version == REPORT_VERSION
|
||||||
&& report.fingerprint == fp
|
&& report.fingerprint == fp
|
||||||
&& report.player == *player
|
&& report.player == *player
|
||||||
&& report.plies == options.plies
|
&& report.plies == options.plies
|
||||||
&& report.side() == options.side)
|
&& report.side() == options.side;
|
||||||
.then_some(report)
|
if !same {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// Evaluations of another search are not mixed with today's: the errors are
|
||||||
|
// found again.
|
||||||
|
if report.search != SEARCH_VERSION {
|
||||||
|
report.evals.retain(|_, e| e.nodes == EXACT);
|
||||||
|
report.engine = None;
|
||||||
|
report.search = SEARCH_VERSION;
|
||||||
|
report.refresh();
|
||||||
|
}
|
||||||
|
Some(report)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Keeps the report in `dir` (atomically).
|
/// Keeps the report in `dir` (atomically).
|
||||||
|
|
@ -593,7 +608,7 @@ pub struct Progress {
|
||||||
pub nps: u64,
|
pub nps: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the engine over the positions `report` lacks at `settings.nodes` (the cache
|
/// Runs the engine over the positions `report` lacks (the cache
|
||||||
/// is consulted first and fed as results come; `cache_dir` saves it every few
|
/// is consulted first and fed as results come; `cache_dir` saves it every few
|
||||||
/// hundred positions and at the end), updating the report as results come in.
|
/// hundred positions and at the end), updating the report as results come in.
|
||||||
/// Returns when done, or soon after `cancel` is set (what was evaluated stays).
|
/// Returns when done, or soon after `cancel` is set (what was evaluated stays).
|
||||||
|
|
@ -606,9 +621,8 @@ pub fn analyse(
|
||||||
cancel: &AtomicBool,
|
cancel: &AtomicBool,
|
||||||
on_progress: &mut dyn FnMut(Progress),
|
on_progress: &mut dyn FnMut(Progress),
|
||||||
) -> Result<(), JobFailure> {
|
) -> Result<(), JobFailure> {
|
||||||
let nodes = settings.nodes;
|
report.take_cached(cache);
|
||||||
report.take_cached(cache, nodes);
|
let targets = report.targets();
|
||||||
let targets = report.targets(nodes);
|
|
||||||
let total = targets.len();
|
let total = targets.len();
|
||||||
let mut progress = Progress {
|
let mut progress = Progress {
|
||||||
done: 0,
|
done: 0,
|
||||||
|
|
@ -625,7 +639,7 @@ pub fn analyse(
|
||||||
progress.done += 1;
|
progress.done += 1;
|
||||||
progress.nps = *nps;
|
progress.nps = *nps;
|
||||||
}
|
}
|
||||||
if let Some((key, eval)) = report.apply(&event, nodes) {
|
if let Some((key, eval)) = report.apply(&event) {
|
||||||
cache.insert(key, eval);
|
cache.insert(key, eval);
|
||||||
since_save += 1;
|
since_save += 1;
|
||||||
if since_save >= 200
|
if since_save >= 200
|
||||||
|
|
@ -860,14 +874,14 @@ mod tests {
|
||||||
// 9 + 11 + 7 positions; the start and 1.e4 c5 2.Nf3 shared by three games,
|
// 9 + 11 + 7 positions; the start and 1.e4 c5 2.Nf3 shared by three games,
|
||||||
// 2...Nc6 3.Bb5 by two.
|
// 2...Nc6 3.Bb5 by two.
|
||||||
assert_eq!(total, 27 - 10);
|
assert_eq!(total, 27 - 10);
|
||||||
let targets = report.targets(1000);
|
let targets = report.targets();
|
||||||
assert_eq!(targets.len(), total);
|
assert_eq!(targets.len(), total);
|
||||||
// One colour: the positions of its games only (the start position is in both).
|
// One colour: the positions of its games only (the start position is in both).
|
||||||
let black = report.targets_for(1000, Side::Black);
|
let black = report.targets_for(Side::Black);
|
||||||
assert_eq!(black.len(), report.games[1].keys.len());
|
assert_eq!(black.len(), report.games[1].keys.len());
|
||||||
assert_eq!(report.distinct_positions_for(Side::Black), black.len());
|
assert_eq!(report.distinct_positions_for(Side::Black), black.len());
|
||||||
assert!(report.distinct_positions_for(Side::White) < total);
|
assert!(report.distinct_positions_for(Side::White) < total);
|
||||||
assert_eq!(report.missing_for(1000, Side::Black), black.len());
|
assert_eq!(report.missing_for(Side::Black), black.len());
|
||||||
assert_eq!(targets[0].key, format!("{:016x}", report.games[0].keys[0]));
|
assert_eq!(targets[0].key, format!("{:016x}", report.games[0].keys[0]));
|
||||||
assert!(targets[0].pos.moves.is_empty());
|
assert!(targets[0].pos.moves.is_empty());
|
||||||
assert_eq!(targets[3].pos.moves, vec!["e2e4", "c7c5", "g1f3"]);
|
assert_eq!(targets[3].pos.moves, vec!["e2e4", "c7c5", "g1f3"]);
|
||||||
|
|
@ -891,14 +905,13 @@ mod tests {
|
||||||
},
|
},
|
||||||
nps: 0,
|
nps: 0,
|
||||||
};
|
};
|
||||||
let (k, e) = report.apply(&event, 1000).expect("an evaluation");
|
let (k, e) = report.apply(&event).expect("an evaluation");
|
||||||
cache.insert(k, e);
|
cache.insert(k, e);
|
||||||
}
|
}
|
||||||
assert_eq!(report.missing(1000), 0);
|
assert_eq!(report.missing(), 0);
|
||||||
assert_eq!(report.missing(2000), total);
|
|
||||||
assert!(report.evaluated());
|
assert!(report.evaluated());
|
||||||
report.refresh();
|
report.refresh();
|
||||||
assert_eq!(report.engine.as_ref().map(|e| e.nodes), Some(1000));
|
assert_eq!(report.engine.as_ref().map(|e| e.nodes), Some(SEARCH_NODES));
|
||||||
let w = &report.white;
|
let w = &report.white;
|
||||||
assert_eq!(w.counts.blunders, 2);
|
assert_eq!(w.counts.blunders, 2);
|
||||||
assert_eq!(w.errors.len(), 2);
|
assert_eq!(w.errors.len(), 2);
|
||||||
|
|
@ -929,10 +942,21 @@ mod tests {
|
||||||
let mut fresh = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
|
let mut fresh = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
|
||||||
.expect("report");
|
.expect("report");
|
||||||
assert!(!fresh.evaluated());
|
assert!(!fresh.evaluated());
|
||||||
assert_eq!(fresh.take_cached(&cache, 1000), total);
|
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.white.repeated, report.white.repeated);
|
||||||
assert_eq!(fresh.take_cached(&cache, 1000), 0);
|
assert_eq!(fresh.take_cached(&cache), 0);
|
||||||
|
// A report of another search (from before the fixed one) keeps its games but
|
||||||
|
// not its evaluations.
|
||||||
|
let path = PrepReport::cache_path(&dir, report.fingerprint, &player, &Options::default());
|
||||||
|
let mut json: serde_json::Value =
|
||||||
|
serde_json::from_slice(&std::fs::read(&path).expect("report")).expect("json");
|
||||||
|
json.as_object_mut().expect("report").remove("search");
|
||||||
|
std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written");
|
||||||
|
let old = PrepReport::load(&dir, &db, &player, &Options::default()).expect("still read");
|
||||||
|
assert!(!old.evaluated() && old.white.errors.is_empty());
|
||||||
|
assert_eq!(old.missing(), total);
|
||||||
|
assert_eq!(old.search, SEARCH_VERSION);
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -951,12 +975,7 @@ mod tests {
|
||||||
let mut report = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
|
let mut report = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
|
||||||
.expect("report");
|
.expect("report");
|
||||||
let total = report.distinct_positions();
|
let total = report.distinct_positions();
|
||||||
let settings = JobSettings {
|
let settings = JobSettings::new(2, None);
|
||||||
threads: 1,
|
|
||||||
hash_mb: 16,
|
|
||||||
nodes: 1000,
|
|
||||||
eval_file: None,
|
|
||||||
};
|
|
||||||
let mut cache = PositionCache::default();
|
let mut cache = PositionCache::default();
|
||||||
let mut last = Progress::default();
|
let mut last = Progress::default();
|
||||||
analyse(
|
analyse(
|
||||||
|
|
@ -970,7 +989,7 @@ mod tests {
|
||||||
)
|
)
|
||||||
.expect("the job runs");
|
.expect("the job runs");
|
||||||
assert_eq!((last.done, last.total), (total, total));
|
assert_eq!((last.done, last.total), (total, total));
|
||||||
assert_eq!(report.missing(1000), 0);
|
assert_eq!(report.missing(), 0);
|
||||||
assert_eq!(cache.len(), total);
|
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.
|
// A second run has nothing to do; a cancelled one ends at once.
|
||||||
|
|
@ -988,7 +1007,7 @@ mod tests {
|
||||||
&mut |_| calls += 1,
|
&mut |_| calls += 1,
|
||||||
)
|
)
|
||||||
.expect("nothing to do");
|
.expect("nothing to do");
|
||||||
assert_eq!(again.missing(1000), 0, "all from the cache");
|
assert_eq!(again.missing(), 0, "all from the cache");
|
||||||
assert_eq!(calls, 1);
|
assert_eq!(calls, 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,8 @@
|
||||||
//! --exit-after-go N on the N-th `go`, print one info and exit(1)
|
//! --exit-after-go N on the N-th `go`, print one info and exit(1)
|
||||||
//! --mate multipv 1 = mate 3, multipv 2 = mate -2
|
//! --mate multipv 1 = mate 3, multipv 2 = mate -2
|
||||||
//! --ignore-quit ignore `quit` (must be killed)
|
//! --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)
|
||||||
//!
|
//!
|
||||||
//! Protocol violations by the GUI (`position`/`go`/`setoption`/`ucinewgame`
|
//! Protocol violations by the GUI (`position`/`go`/`setoption`/`ucinewgame`
|
||||||
//! during a search) are reported as `info string ERROR ...`.
|
//! during a search) are reported as `info string ERROR ...`.
|
||||||
|
|
@ -51,6 +53,7 @@ struct Cfg {
|
||||||
exit_after_go: Option<u32>,
|
exit_after_go: Option<u32>,
|
||||||
mate: bool,
|
mate: bool,
|
||||||
ignore_quit: bool,
|
ignore_quit: bool,
|
||||||
|
hash_memory: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_args() -> Cfg {
|
fn parse_args() -> Cfg {
|
||||||
|
|
@ -79,6 +82,7 @@ fn parse_args() -> Cfg {
|
||||||
"--exit-after-go" => c.exit_after_go = Some(num(args.next()) as u32),
|
"--exit-after-go" => c.exit_after_go = Some(num(args.next()) as u32),
|
||||||
"--mate" => c.mate = true,
|
"--mate" => c.mate = true,
|
||||||
"--ignore-quit" => c.ignore_quit = true,
|
"--ignore-quit" => c.ignore_quit = true,
|
||||||
|
"--hash-memory" => c.hash_memory = true,
|
||||||
other => {
|
other => {
|
||||||
eprintln!("fake_uci: unknown flag {other}");
|
eprintln!("fake_uci: unknown flag {other}");
|
||||||
std::process::exit(2);
|
std::process::exit(2);
|
||||||
|
|
@ -92,6 +96,8 @@ struct Search {
|
||||||
marker: String,
|
marker: String,
|
||||||
depth: u32,
|
depth: u32,
|
||||||
max_depth: Option<u32>,
|
max_depth: Option<u32>,
|
||||||
|
/// Added to every score (`--hash-memory`).
|
||||||
|
bias: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn out(line: &str) {
|
fn out(line: &str) {
|
||||||
|
|
@ -100,14 +106,14 @@ fn out(line: &str) {
|
||||||
let _ = o.flush();
|
let _ = o.flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn info_lines(cfg: &Cfg, marker: &str, depth: u32, multipv: u32) {
|
fn info_lines(cfg: &Cfg, marker: &str, depth: u32, multipv: u32, bias: i32) {
|
||||||
for k in 1..=multipv {
|
for k in 1..=multipv {
|
||||||
let score = if cfg.mate && k == 1 {
|
let score = if cfg.mate && k == 1 {
|
||||||
"mate 3".to_string()
|
"mate 3".to_string()
|
||||||
} else if cfg.mate && k == 2 {
|
} else if cfg.mate && k == 2 {
|
||||||
"mate -2".to_string()
|
"mate -2".to_string()
|
||||||
} else {
|
} else {
|
||||||
format!("cp {}", 50 - 10 * k as i32)
|
format!("cp {}", 50 - 10 * k as i32 + bias)
|
||||||
};
|
};
|
||||||
out(&format!(
|
out(&format!(
|
||||||
"info depth {depth} seldepth {} multipv {k} score {score} nodes {} nps 100000 \
|
"info depth {depth} seldepth {} multipv {k} score {score} nodes {} nps 100000 \
|
||||||
|
|
@ -159,6 +165,8 @@ fn main() {
|
||||||
let mut marker = "startpos".to_string();
|
let mut marker = "startpos".to_string();
|
||||||
let mut search: Option<Search> = None;
|
let mut search: Option<Search> = None;
|
||||||
let mut gos = 0u32;
|
let mut gos = 0u32;
|
||||||
|
// Searches since the last `ucinewgame` (`--hash-memory`).
|
||||||
|
let mut since_new_game = 0i32;
|
||||||
let mut hung = false;
|
let mut hung = false;
|
||||||
let interval = Duration::from_millis(cfg.info_interval.max(1));
|
let interval = Duration::from_millis(cfg.info_interval.max(1));
|
||||||
|
|
||||||
|
|
@ -179,7 +187,7 @@ fn main() {
|
||||||
// Search tick.
|
// Search tick.
|
||||||
if let Some(s) = search.as_mut() {
|
if let Some(s) = search.as_mut() {
|
||||||
s.depth += 1;
|
s.depth += 1;
|
||||||
info_lines(&cfg, &s.marker, s.depth, multipv);
|
info_lines(&cfg, &s.marker, s.depth, multipv, s.bias);
|
||||||
if s.max_depth.is_some_and(|m| s.depth >= m) {
|
if s.max_depth.is_some_and(|m| s.depth >= m) {
|
||||||
out(&format!("bestmove {} ponder e7e5", bm(&s.marker)));
|
out(&format!("bestmove {} ponder e7e5", bm(&s.marker)));
|
||||||
search = None;
|
search = None;
|
||||||
|
|
@ -242,6 +250,7 @@ fn main() {
|
||||||
if search.is_some() {
|
if search.is_some() {
|
||||||
out("info string ERROR ucinewgame during search");
|
out("info string ERROR ucinewgame during search");
|
||||||
}
|
}
|
||||||
|
since_new_game = 0;
|
||||||
}
|
}
|
||||||
Some("position") => {
|
Some("position") => {
|
||||||
if search.is_some() {
|
if search.is_some() {
|
||||||
|
|
@ -261,7 +270,7 @@ fn main() {
|
||||||
}
|
}
|
||||||
gos += 1;
|
gos += 1;
|
||||||
if cfg.exit_after_go == Some(gos) {
|
if cfg.exit_after_go == Some(gos) {
|
||||||
info_lines(&cfg, &marker, 1, multipv);
|
info_lines(&cfg, &marker, 1, multipv, 0);
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
let max_depth = toks
|
let max_depth = toks
|
||||||
|
|
@ -271,10 +280,18 @@ fn main() {
|
||||||
.and_then(|v| v.parse().ok())
|
.and_then(|v| v.parse().ok())
|
||||||
// `go nodes N`: a short search that ends by itself, like a real one.
|
// `go nodes N`: a short search that ends by itself, like a real one.
|
||||||
.or_else(|| toks.contains(&"nodes").then_some(3));
|
.or_else(|| toks.contains(&"nodes").then_some(3));
|
||||||
|
since_new_game += 1;
|
||||||
|
let bias = if cfg.hash_memory {
|
||||||
|
let of_position = marker.bytes().map(i32::from).sum::<i32>() % 97;
|
||||||
|
of_position + 1000 * since_new_game
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
search = Some(Search {
|
search = Some(Search {
|
||||||
marker: marker.clone(),
|
marker: marker.clone(),
|
||||||
depth: 0,
|
depth: 0,
|
||||||
max_depth,
|
max_depth,
|
||||||
|
bias,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Some("stop") => {
|
Some("stop") => {
|
||||||
|
|
@ -284,12 +301,12 @@ fn main() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for i in 0..cfg.stale_after_stop {
|
for i in 0..cfg.stale_after_stop {
|
||||||
info_lines(&cfg, &s.marker, s.depth + 1 + i, multipv);
|
info_lines(&cfg, &s.marker, s.depth + 1 + i, multipv, s.bias);
|
||||||
}
|
}
|
||||||
std::thread::sleep(Duration::from_millis(cfg.bestmove_delay));
|
std::thread::sleep(Duration::from_millis(cfg.bestmove_delay));
|
||||||
out(&format!("bestmove {} ponder e7e5", bm(&s.marker)));
|
out(&format!("bestmove {} ponder e7e5", bm(&s.marker)));
|
||||||
for i in 0..cfg.info_after_bestmove {
|
for i in 0..cfg.info_after_bestmove {
|
||||||
info_lines(&cfg, &s.marker, s.depth + 100 + i, multipv);
|
info_lines(&cfg, &s.marker, s.depth + 100 + i, multipv, s.bias);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some("quit") if !cfg.ignore_quit => return,
|
Some("quit") if !cfg.ignore_quit => return,
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue