use alloc::vec::Vec;
use core::mem;
use search_core::Budget;
use crate::minimax::improves;
use crate::table::{Entry, Memory};
use crate::{Algorithm, Bound, Game, Score, ScoredMove, SearchResult, Searcher, Side, Stats};
#[must_use]
pub fn alpha_beta<G: Game>(
game: &G,
position: &G::Position,
depth: u32,
) -> SearchResult<G::Move, G::Score> {
Searcher::new().search(game, position, depth)
}
impl<G: Game, T: Memory<G>> Searcher<G, T> {
#[must_use]
pub fn search(
&mut self,
game: &G,
position: &G::Position,
depth: u32,
) -> SearchResult<G::Move, G::Score> {
self.stats = Stats::ZERO;
self.hint.clear();
self.guess = None;
let mut unlimited = |_: &Stats| false;
let mut run = Run {
game,
budget: &mut unlimited,
};
let node = self.iterate(&mut run, position, depth, Window::FULL);
self.result(&node, depth)
}
pub(crate) fn iterate<B: Budget<Stats>>(
&mut self,
run: &mut Run<'_, G, B>,
position: &G::Position,
depth: u32,
window: Window<G::Score>,
) -> Node<G::Score> {
self.aborted = false;
if self.algorithm == Algorithm::Mtdf {
return self.mtdf(run, position, depth);
}
self.root(run, position, depth, window)
}
pub(crate) fn root<B: Budget<Stats>>(
&mut self,
run: &mut Run<'_, G, B>,
position: &G::Position,
depth: u32,
window: Window<G::Score>,
) -> Node<G::Score> {
let mut root_moves = mem::take(&mut self.root_moves);
root_moves.clear();
let frame = Frame {
ply: 0,
depth,
window,
on_hint: true,
};
let node = self.visit(run, position, frame, Some(&mut root_moves));
self.root_moves = root_moves;
node
}
pub(crate) fn result(
&self,
node: &Node<G::Score>,
depth: u32,
) -> SearchResult<G::Move, G::Score> {
SearchResult {
score: node.score,
bound: node.bound,
pv: self.line(0).to_vec(),
root_moves: self.root_moves.clone(),
unexamined: node.skipped,
depth,
proven: node.proven,
stats: self.stats,
}
}
fn visit<B: Budget<Stats>>(
&mut self,
run: &mut Run<'_, G, B>,
position: &G::Position,
frame: Frame<G::Score>,
root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
) -> Node<G::Score> {
let game = run.game;
if run.budget.exhausted(&self.stats) {
self.aborted = true;
return Node::horizon(game.evaluate(position));
}
self.stats
.visit(u32::try_from(frame.ply).expect("a ply never exceeds the u32 search depth"));
let mut moves = self.enter(frame.ply);
if frame.depth == 0 {
return self.quiesce(run, position, frame, moves, root_moves);
}
game.moves(position, &mut moves);
if moves.is_empty() {
self.leave(frame.ply, moves);
return Node::leaf(game.evaluate(position));
}
game.order_moves(position, &mut moves);
let key = self.table.key(game, position);
let stored = self.table.recall(&key);
if let Some(node) = stored.as_ref().and_then(|entry| answer(entry, frame)) {
self.stats.table_hits += 1;
self.leave(frame.ply, moves);
return node;
}
if let Some(best) = stored.and_then(|entry| entry.best) {
promote(&mut moves, &best);
}
let hint = self.promote_hint(&mut moves, frame);
let expansion = Expansion {
moves,
hint,
stand: None,
};
let node = self.expand(run, position, frame, expansion, root_moves);
if !self.aborted {
let entry = self.entry(&node, frame);
self.table.remember(key, entry);
}
node
}
fn entry(&self, node: &Node<G::Score>, frame: Frame<G::Score>) -> Entry<G::Move, G::Score> {
Entry {
depth: frame.depth,
score: node.score,
bound: node.bound,
best: self.line(frame.ply).first().map(|step| step.mv.clone()),
proven: node.proven,
reach: node.reach,
}
}
fn quiesce<B: Budget<Stats>>(
&mut self,
run: &mut Run<'_, G, B>,
position: &G::Position,
frame: Frame<G::Score>,
mut moves: Vec<G::Move>,
root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
) -> Node<G::Score> {
let game = run.game;
self.stats.horizon += 1;
let stand = Node::horizon(game.evaluate(position));
game.noisy_moves(position, &mut moves);
if moves.is_empty() {
self.leave(frame.ply, moves);
return stand;
}
game.order_moves(position, &mut moves);
let hint = self.promote_hint(&mut moves, frame);
let expansion = Expansion {
moves,
hint,
stand: Some(stand),
};
self.expand(run, position, frame, expansion, root_moves)
}
fn promote_hint(&self, moves: &mut [G::Move], frame: Frame<G::Score>) -> Option<G::Move> {
let hint = self.hint.get(frame.ply).filter(|_| frame.on_hint)?;
promote(moves, hint).then(|| hint.clone())
}
fn expand<B: Budget<Stats>>(
&mut self,
run: &mut Run<'_, G, B>,
position: &G::Position,
frame: Frame<G::Score>,
expansion: Expansion<G::Move, G::Score>,
mut root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
) -> Node<G::Score> {
let Expansion {
mut moves,
hint,
stand,
} = expansion;
let game = run.game;
let side = game.side_to_move(position);
let total = moves.len();
let mut window = frame.window;
if let Some(stand) = stand {
window.tighten(side, stand.score);
}
let mut best = stand;
let (mut widened, mut proven, mut searched, mut reach) = (false, stand.is_none(), 0, 0);
for mv in moves.drain(..) {
if best.is_some_and(|best| stops(game, side, best.score, &window)) {
break;
}
searched += 1;
let child_frame = frame.child(window, hint.as_ref() == Some(&mv));
let child = self.child(
run,
&game.play(position, &mv),
child_frame,
(side, best.is_some()),
);
if self.aborted {
break;
}
let step = ScoredMove {
mv,
score: child.score,
bound: child.bound,
};
if let Some(root_moves) = root_moves.as_deref_mut() {
root_moves.push(step.clone());
}
widened |= child.bound.widens(side);
proven &= child.proven;
reach = reach.max(child.reach + 1);
window.tighten(side, child.score);
if best.is_none_or(|best| improves(side, child.score, best.score)) {
best = Some(child);
self.adopt(frame.ply, step);
}
}
self.leave(frame.ply, moves);
let Some(best) = best else {
return Node::horizon(game.evaluate(position));
};
let node = Node {
proven,
reach,
..best
};
self.finish(side, node, total - searched, widened)
}
fn child<B: Budget<Stats>>(
&mut self,
run: &mut Run<'_, G, B>,
position: &G::Position,
frame: Frame<G::Score>,
(side, later): (Side, bool),
) -> Node<G::Score> {
let scout = frame
.window
.null(side)
.filter(|_| later && self.algorithm == Algorithm::Pvs);
if let Some(window) = scout {
let node = self.visit(run, position, Frame { window, ..frame }, None);
if self.aborted || !frame.window.needs_research(&node) {
return node;
}
self.stats.researches += 1;
}
self.visit(run, position, frame, None)
}
fn finish(
&mut self,
side: Side,
best: Node<G::Score>,
skipped: usize,
widened: bool,
) -> Node<G::Score> {
let cut = skipped > 0;
if cut && !self.aborted {
self.stats.cuts += 1;
}
Node {
bound: Bound::combine(side, cut, best.bound, widened),
skipped,
..best
}
}
}
fn promote<M: PartialEq>(moves: &mut [M], mv: &M) -> bool {
let Some(index) = moves.iter().position(|candidate| candidate == mv) else {
return false;
};
moves[..=index].rotate_right(1);
true
}
fn answer<M, S: Ord + Copy>(entry: &Entry<M, S>, frame: Frame<S>) -> Option<Node<S>> {
if frame.ply == 0 || !entry.serves(frame.depth) {
return None;
}
let answers = match entry.bound {
Bound::Exact => true,
Bound::Lower => frame.window.closes(Side::Max, entry.score),
Bound::Upper => frame.window.closes(Side::Min, entry.score),
Bound::Approximate => false,
};
answers.then(|| Node::stored(entry))
}
fn stops<G: Game>(game: &G, side: Side, score: G::Score, window: &Window<G::Score>) -> bool {
window.closes(side, score) || game.satisfices(side, score)
}
struct Expansion<M, S> {
moves: Vec<M>,
hint: Option<M>,
stand: Option<Node<S>>,
}
pub(crate) struct Run<'a, G, B> {
pub(crate) game: &'a G,
pub(crate) budget: &'a mut B,
}
#[derive(Debug, Clone, Copy)]
struct Frame<S> {
ply: usize,
depth: u32,
window: Window<S>,
on_hint: bool,
}
impl<S> Frame<S> {
const fn child(&self, window: Window<S>, hinted: bool) -> Self {
Self {
ply: self.ply + 1,
depth: self.depth.saturating_sub(1),
window,
on_hint: self.on_hint && hinted,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Window<S> {
pub alpha: Option<S>,
pub beta: Option<S>,
}
impl<S> Window<S> {
pub const FULL: Self = Self {
alpha: None,
beta: None,
};
}
impl<S: Ord + Copy> Window<S> {
pub(crate) const fn is_full(&self) -> bool {
self.alpha.is_none() && self.beta.is_none()
}
fn closes(&self, side: Side, score: S) -> bool {
match side {
Side::Max => self.beta.is_some_and(|beta| score >= beta),
Side::Min => self.alpha.is_some_and(|alpha| score <= alpha),
}
}
fn null(&self, side: Side) -> Option<Self>
where
S: Score,
{
let (alpha, beta) = match side {
Side::Max => {
let alpha = self.alpha?;
(alpha, alpha.next_up())
}
Side::Min => {
let beta = self.beta?;
(beta.next_down(), beta)
}
};
(alpha < beta).then_some(Self {
alpha: Some(alpha),
beta: Some(beta),
})
}
fn needs_research(&self, node: &Node<S>) -> bool {
let above = self.alpha.is_none_or(|alpha| node.score > alpha);
let below = self.beta.is_none_or(|beta| node.score < beta);
node.bound != Bound::Exact && above && below
}
fn tighten(&mut self, side: Side, score: S) {
match side {
Side::Max => self.alpha = Some(self.alpha.map_or(score, |alpha| alpha.max(score))),
Side::Min => self.beta = Some(self.beta.map_or(score, |beta| beta.min(score))),
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Node<S> {
pub(crate) score: S,
pub(crate) bound: Bound,
skipped: usize,
proven: bool,
reach: u32,
}
impl<S> Node<S> {
const fn leaf(score: S) -> Self {
Self {
score,
bound: Bound::Exact,
skipped: 0,
proven: true,
reach: 1,
}
}
const fn horizon(score: S) -> Self {
Self {
score,
bound: Bound::Exact,
skipped: 0,
proven: false,
reach: 0,
}
}
fn stored<M>(entry: &Entry<M, S>) -> Self
where
S: Copy,
{
Self {
score: entry.score,
bound: entry.bound,
skipped: 0,
proven: entry.proven,
reach: entry.reach,
}
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use alloc::vec::Vec;
use super::{Frame, Run, Window, answer};
use crate::table::Entry;
use crate::{Bound, Game, Searcher, Side, Stats};
struct TwoMoves;
impl Game for TwoMoves {
type Position = bool;
type Move = u8;
type Score = i32;
fn side_to_move(&self, _: &bool) -> Side {
Side::Max
}
fn moves(&self, &root: &bool, moves: &mut Vec<u8>) {
if root {
moves.extend([1, 2]);
}
}
fn play(&self, _: &bool, _: &u8) -> bool {
false
}
fn evaluate(&self, _: &bool) -> i32 {
0
}
}
fn search_with_hint(hint: Vec<u8>) -> Option<u8> {
let mut searcher = Searcher::<TwoMoves>::new();
searcher.hint = hint;
let mut unlimited = |_: &Stats| false;
let mut run = Run {
game: &TwoMoves,
budget: &mut unlimited,
};
let node = searcher.iterate(&mut run, &true, 2, Window::FULL);
searcher.result(&node, 2).best().copied()
}
#[test]
fn unusable_entries_answer_nothing() {
let entry = |bound, depth| Entry::<u8, i32> {
depth,
score: 3,
bound,
best: None,
proven: false,
reach: 0,
};
let frame = Frame {
ply: 1,
depth: 2,
window: Window {
alpha: Some(0),
beta: Some(5),
},
on_hint: false,
};
assert!(answer(&entry(Bound::Approximate, 2), frame).is_none());
assert!(answer(&entry(Bound::Exact, 3), frame).is_none());
assert!(answer(&entry(Bound::Lower, 2), frame).is_none());
assert!(answer(&entry(Bound::Upper, 2), frame).is_none());
let beyond = Frame {
window: Window {
alpha: Some(3),
beta: Some(3),
},
..frame
};
assert!(answer(&entry(Bound::Lower, 2), beyond).is_some());
assert!(answer(&entry(Bound::Upper, 2), beyond).is_some());
}
#[test]
fn pvs_scouts_only_later_children() {
let mut searcher = Searcher::<TwoMoves>::new().with_algorithm(crate::Algorithm::Pvs);
let mut unlimited = |_: &Stats| false;
let mut run = Run {
game: &TwoMoves,
budget: &mut unlimited,
};
let frame = Frame {
ply: 1,
depth: 1,
window: Window {
alpha: Some(-1),
beta: Some(1),
},
on_hint: false,
};
let first = searcher.child(&mut run, &true, frame, (Side::Max, false));
assert_eq!(
(first.score, first.bound, searcher.stats.researches),
(0, Bound::Exact, 0)
);
let later = searcher.child(&mut run, &true, frame, (Side::Max, true));
assert_eq!(
(later.score, later.bound, searcher.stats.researches),
(0, Bound::Exact, 1)
);
}
#[test]
fn only_legal_hints_are_tried_first() {
assert_eq!(search_with_hint(vec![2]), Some(2));
assert_eq!(search_with_hint(vec![9]), Some(1));
assert_eq!(search_with_hint(Vec::new()), Some(1));
}
}