Skip to main content

game_tree_search/
searcher.rs

1//! [`Searcher`]: the reusable working memory of the searches.
2
3use alloc::vec::Vec;
4use core::mem;
5
6use crate::table::{Memory, Transpositions};
7use crate::{Game, Hashed, NoTable, ScoredMove, Stats, Table};
8
9/// Working memory for repeated searches: move lists and principal variations per ply, and
10/// optionally a transposition table `T`.
11///
12/// Keep one per search thread or game agent and reuse it. Its buffers grow to the deepest search
13/// run so far and are kept between searches, so a warm searcher allocates only results: the one it
14/// returns, plus one per iteration while deepening. The free functions such as
15/// [`alpha_beta()`](crate::alpha_beta()) create a fresh one per call.
16///
17/// Built with [`Searcher::with_table`], it also remembers positions in a [`Table`]
18/// across searches, which needs a [`Hashed`] game. Entries are only valid for
19/// the game configuration that produced them: when the game passed to the searcher changes
20/// its rules, clear the table, for example with
21/// [`SlotTable::clear`](crate::SlotTable::clear) through [`Searcher::table_mut`].
22///
23/// # Examples
24///
25/// ```
26/// # use game_tree_search::{Game, Side};
27/// # struct Nim;
28/// # impl Game for Nim {
29/// #     type Position = (u32, Side);
30/// #     type Move = u32;
31/// #     type Score = i32;
32/// #     fn side_to_move(&self, &(_, side): &Self::Position) -> Side { side }
33/// #     fn moves(&self, &(stones, _): &Self::Position, moves: &mut Vec<u32>) {
34/// #         moves.extend((1..=2).filter(|&take| take <= stones));
35/// #     }
36/// #     fn play(&self, &(stones, side): &Self::Position, take: &u32) -> Self::Position {
37/// #         (stones - take, if side == Side::Max { Side::Min } else { Side::Max })
38/// #     }
39/// #     fn evaluate(&self, &(stones, side): &Self::Position) -> i32 {
40/// #         match (stones, side) { (0, Side::Max) => -1, (0, Side::Min) => 1, _ => 0 }
41/// #     }
42/// # }
43/// use game_tree_search::Searcher;
44///
45/// let mut searcher = Searcher::new();
46/// for stones in 1..=9 {
47///     let result = searcher.search(&Nim, &(stones, Side::Max), 9);
48///     assert_eq!(result.score, if stones % 3 == 0 { -1 } else { 1 });
49/// }
50/// ```
51#[derive(Debug)]
52pub struct Searcher<G: Game, T = NoTable> {
53    /// Move lists by ply, empty between searches; kept for their capacity.
54    moves: Vec<Vec<G::Move>>,
55    /// The principal variation found below each ply in the current search.
56    lines: Vec<Vec<ScoredMove<G::Move, G::Score>>>,
57    /// The previous iteration's principal variation, tried first while a search follows it.
58    pub(crate) hint: Vec<G::Move>,
59    /// Whether the budget stopped the current search; its result is then discarded.
60    pub(crate) aborted: bool,
61    /// The counters of the current or last search.
62    pub(crate) stats: Stats,
63    /// The transposition table, kept between searches.
64    pub(crate) table: T,
65    /// The search run at each depth.
66    pub(crate) algorithm: Algorithm,
67    /// The score MTD(f) starts from: the previous iteration's while deepening.
68    pub(crate) guess: Option<G::Score>,
69    /// The moves searched at the root in the last root search.
70    pub(crate) root_moves: Vec<ScoredMove<G::Move, G::Score>>,
71    /// Plies deepening starts ahead of depth 1; a Lazy SMP helper thread runs ahead so its
72    /// entries are ready when the main thread gets there.
73    pub(crate) lead: u32,
74    /// Whether deepening's first iteration also asks the budget; a Lazy SMP helper must stop
75    /// at once when the main thread is done.
76    pub(crate) budget_first: bool,
77    /// How far a Lazy SMP helper rotates every position's moves after the first, once the game
78    /// has ordered them and before the table's and the hint's moves go first, so helpers
79    /// search the alternatives in different orders instead of in lockstep with the main
80    /// thread, while still trying the game's best guess first; `0` for every other searcher.
81    pub(crate) skew: usize,
82    /// Whether the last deepening completed its first iteration; only a Lazy SMP helper,
83    /// whose first iteration asks the budget, can have a result that is not an answer.
84    pub(crate) answered: bool,
85}
86
87/// The search a [`Searcher`] runs at each depth, for one search and for every iteration of
88/// deepening.
89///
90/// With the default [`Game::satisfices`], every algorithm returns the same score; they differ
91/// in how many positions they visit. Under satisficing, each returns a sound result, not
92/// necessarily the same one.
93/// Non-exhaustive: more algorithms may follow.
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
95#[non_exhaustive]
96pub enum Algorithm {
97    /// Fail-soft alpha-beta: see [`alpha_beta()`](crate::alpha_beta()).
98    #[default]
99    AlphaBeta,
100    /// Principal variation search: see [`pvs()`](crate::pvs()).
101    Pvs,
102    /// MTD(f), null-window searches that close in on the score: see [`mtdf()`](crate::mtdf()).
103    Mtdf,
104}
105
106impl<G: Game> Searcher<G> {
107    /// A searcher with empty buffers and no transposition table; the buffers grow on first
108    /// use.
109    #[must_use]
110    pub const fn new() -> Self {
111        Self::with_memory(NoTable)
112    }
113}
114
115impl<G: Hashed, T: Table<G::Key, G::Move, G::Score>> Searcher<G, Transpositions<T>> {
116    /// A searcher with empty buffers that remembers positions in `table` across searches.
117    #[must_use]
118    pub const fn with_table(table: T) -> Self {
119        Self::with_memory(Transpositions(table))
120    }
121
122    /// The transposition table.
123    #[must_use]
124    pub const fn table(&self) -> &T {
125        &self.table.0
126    }
127
128    /// The transposition table, for example to clear it.
129    pub const fn table_mut(&mut self) -> &mut T {
130        &mut self.table.0
131    }
132}
133
134impl<G: Game, T: Memory<G>> Searcher<G, T> {
135    /// A searcher with empty buffers and the given memory.
136    const fn with_memory(table: T) -> Self {
137        Self {
138            moves: Vec::new(),
139            lines: Vec::new(),
140            hint: Vec::new(),
141            aborted: false,
142            stats: Stats::ZERO,
143            table,
144            algorithm: Algorithm::AlphaBeta,
145            guess: None,
146            root_moves: Vec::new(),
147            lead: 0,
148            budget_first: false,
149            skew: 0,
150            answered: false,
151        }
152    }
153
154    /// This searcher, running `algorithm` from now on.
155    #[must_use]
156    pub const fn with_algorithm(mut self, algorithm: Algorithm) -> Self {
157        self.algorithm = algorithm;
158        self
159    }
160
161    /// The algorithm this searcher runs.
162    #[must_use]
163    pub const fn algorithm(&self) -> Algorithm {
164        self.algorithm
165    }
166
167    /// Prepares the buffers of `ply` for a new position: clears its line and hands out its
168    /// move list, empty. Give the list back with [`Searcher::leave`].
169    pub(crate) fn enter(&mut self, ply: usize) -> Vec<G::Move> {
170        while self.lines.len() <= ply {
171            self.lines.push(Vec::new());
172            self.moves.push(Vec::new());
173        }
174
175        self.lines[ply].clear();
176        mem::take(&mut self.moves[ply])
177    }
178
179    /// Returns the move list of `ply`, emptied, so its capacity serves the next position.
180    pub(crate) fn leave(&mut self, ply: usize, mut moves: Vec<G::Move>) {
181        moves.clear();
182        self.moves[ply] = moves;
183    }
184
185    /// Makes `step` followed by the line found below it, at `ply + 1`, the line of `ply`.
186    pub(crate) fn adopt(&mut self, ply: usize, step: ScoredMove<G::Move, G::Score>) {
187        let (above, below) = self.lines.split_at_mut(ply + 1);
188        let line = &mut above[ply];
189        line.clear();
190        line.push(step);
191        line.extend_from_slice(&below[0]);
192    }
193
194    /// The principal variation found below `ply`; empty if no search reached `ply`, as when
195    /// a budget stops a search at the root.
196    pub(crate) fn line(&self, ply: usize) -> &[ScoredMove<G::Move, G::Score>] {
197        self.lines.get(ply).map_or(&[], Vec::as_slice)
198    }
199}
200
201impl<G: Game> Default for Searcher<G> {
202    fn default() -> Self {
203        Self::new()
204    }
205}