1use alloc::vec::Vec;
4
5use core::mem;
6
7use search_core::Budget;
8
9use crate::incremental::{Borrowed, Place};
10use crate::minimax::improves;
11use crate::table::{Entry, Memory};
12use crate::{Algorithm, Bound, Game, Score, ScoredMove, SearchResult, Searcher, Side, Stats};
13
14#[must_use]
57pub fn alpha_beta<G: Game>(
58 game: &G,
59 position: &G::Position,
60 depth: u32,
61) -> SearchResult<G::Move, G::Score> {
62 Searcher::new().search(game, position, depth)
63}
64
65impl<G: Game, T: Memory<G>> Searcher<G, T> {
66 #[must_use]
73 pub fn search(
74 &mut self,
75 game: &G,
76 position: &G::Position,
77 depth: u32,
78 ) -> SearchResult<G::Move, G::Score> {
79 self.search_from(game, &mut Borrowed(position), depth)
80 }
81
82 pub(crate) fn search_from(
84 &mut self,
85 game: &G,
86 here: &mut impl Place<G>,
87 depth: u32,
88 ) -> SearchResult<G::Move, G::Score> {
89 self.stats = Stats::ZERO;
90 self.hint.clear();
91 self.guess = None;
92 let mut unlimited = |_: &Stats| false;
93 let mut run = Run {
94 game,
95 budget: &mut unlimited,
96 };
97
98 let node = self.iterate(&mut run, here, depth, Window::FULL);
99 self.result(&node, depth)
100 }
101
102 pub(crate) fn iterate<B: Budget<Stats>, H: Place<G>>(
108 &mut self,
109 run: &mut Run<'_, G, B>,
110 here: &mut H,
111 depth: u32,
112 window: Window<G::Score>,
113 ) -> Node<G::Score> {
114 self.aborted = false;
115 if self.algorithm == Algorithm::Mtdf {
116 return self.mtdf(run, here, depth);
117 }
118
119 self.root(run, here, depth, window)
120 }
121
122 pub(crate) fn root<B: Budget<Stats>, H: Place<G>>(
125 &mut self,
126 run: &mut Run<'_, G, B>,
127 here: &mut H,
128 depth: u32,
129 window: Window<G::Score>,
130 ) -> Node<G::Score> {
131 let mut root_moves = mem::take(&mut self.root_moves);
132 root_moves.clear();
133 let frame = Frame {
134 ply: 0,
135 depth,
136 window,
137 on_hint: true,
138 };
139 let node = self.visit(run, here, frame, Some(&mut root_moves));
140 self.root_moves = root_moves;
141
142 node
143 }
144
145 pub(crate) fn result(
147 &self,
148 node: &Node<G::Score>,
149 depth: u32,
150 ) -> SearchResult<G::Move, G::Score> {
151 SearchResult {
152 score: node.score,
153 bound: node.bound,
154 pv: self.line(0).to_vec(),
155 root_moves: self.root_moves.clone(),
156 unexamined: node.skipped,
157 depth,
158 proven: node.proven,
159 stats: self.stats,
160 }
161 }
162
163 fn visit<B: Budget<Stats>, H: Place<G>>(
169 &mut self,
170 run: &mut Run<'_, G, B>,
171 here: &mut H,
172 frame: Frame<G::Score>,
173 root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
174 ) -> Node<G::Score> {
175 let game = run.game;
176 if run.budget.exhausted(&self.stats) {
177 self.aborted = true;
178 return Node::horizon(game.evaluate(here.position()));
179 }
180
181 self.stats
182 .visit(u32::try_from(frame.ply).expect("a ply never exceeds the u32 search depth"));
183 let mut moves = self.enter(frame.ply);
184 if frame.depth == 0 {
185 return self.quiesce(run, here, frame, moves, root_moves);
186 }
187
188 game.moves(here.position(), &mut moves);
189 if moves.is_empty() {
190 self.leave(frame.ply, moves);
191 return Node::leaf(game.evaluate(here.position()));
192 }
193
194 self.order(game, here.position(), &mut moves);
195
196 let key = self.table.key(game, here.position());
197 let stored = self.table.recall(&key);
198 if let Some(node) = stored.as_ref().and_then(|entry| answer(entry, frame)) {
199 self.stats.table_hits += 1;
200 self.leave(frame.ply, moves);
201 return node;
202 }
203
204 if let Some(best) = stored.and_then(|entry| entry.best) {
205 promote(&mut moves, &best);
206 }
207
208 let hint = self.promote_hint(&mut moves, frame);
209 let expansion = Expansion {
210 moves,
211 hint,
212 stand: None,
213 };
214 let node = self.expand(run, here, frame, expansion, root_moves);
215 if !self.aborted {
216 let entry = self.entry(&node, frame);
217 self.table.remember(key, entry);
218 }
219
220 node
221 }
222
223 fn entry(&self, node: &Node<G::Score>, frame: Frame<G::Score>) -> Entry<G::Move, G::Score> {
225 Entry {
226 depth: frame.depth,
227 score: node.score,
228 bound: node.bound,
229 best: self.line(frame.ply).first().map(|step| step.mv.clone()),
230 proven: node.proven,
231 reach: node.reach,
232 }
233 }
234
235 fn quiesce<B: Budget<Stats>, H: Place<G>>(
239 &mut self,
240 run: &mut Run<'_, G, B>,
241 here: &mut H,
242 frame: Frame<G::Score>,
243 mut moves: Vec<G::Move>,
244 root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
245 ) -> Node<G::Score> {
246 let game = run.game;
247 self.stats.horizon += 1;
248 let stand = Node::horizon(game.evaluate(here.position()));
249 game.noisy_moves(here.position(), &mut moves);
250 if moves.is_empty() {
251 self.leave(frame.ply, moves);
252 return stand;
253 }
254
255 self.order(game, here.position(), &mut moves);
256 let hint = self.promote_hint(&mut moves, frame);
257 let expansion = Expansion {
258 moves,
259 hint,
260 stand: Some(stand),
261 };
262 self.expand(run, here, frame, expansion, root_moves)
263 }
264
265 fn order(&self, game: &G, position: &G::Position, moves: &mut [G::Move]) {
269 game.order_moves(position, moves);
270 if let Some((_, rest)) = moves.split_first_mut().filter(|(_, rest)| !rest.is_empty()) {
271 let skew = self.skew % rest.len();
272 rest.rotate_left(skew);
273 }
274 }
275
276 fn promote_hint(&self, moves: &mut [G::Move], frame: Frame<G::Score>) -> Option<G::Move> {
279 let hint = self.hint.get(frame.ply).filter(|_| frame.on_hint)?;
280
281 promote(moves, hint).then(|| hint.clone())
282 }
283
284 fn expand<B: Budget<Stats>, H: Place<G>>(
287 &mut self,
288 run: &mut Run<'_, G, B>,
289 here: &mut H,
290 frame: Frame<G::Score>,
291 expansion: Expansion<G::Move, G::Score>,
292 mut root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
293 ) -> Node<G::Score> {
294 let Expansion {
295 mut moves,
296 hint,
297 stand,
298 } = expansion;
299 let game = run.game;
300 let side = game.side_to_move(here.position());
301 let total = moves.len();
302 let mut window = frame.window;
303 if let Some(stand) = stand {
304 window.tighten(side, stand.score);
305 }
306
307 let mut best = stand;
308 let (mut widened, mut proven, mut searched, mut reach) = (false, stand.is_none(), 0, 0);
309 for mv in moves.drain(..) {
310 if best.is_some_and(|best| stops(game, side, best.score, &window)) {
311 break;
312 }
313
314 searched += 1;
315 let child_frame = frame.child(window, hint.as_ref() == Some(&mv));
316 let later = best.is_some();
317 let child = here.descend(game, &mv, |child| {
318 self.child(run, child, child_frame, (side, later))
319 });
320 if self.aborted {
321 break;
322 }
323
324 let step = ScoredMove {
325 mv,
326 score: child.score,
327 bound: child.bound,
328 };
329 if let Some(root_moves) = root_moves.as_deref_mut() {
330 root_moves.push(step.clone());
331 }
332
333 widened |= child.bound.widens(side);
334 proven &= child.proven;
335 reach = reach.max(child.reach + 1);
336 window.tighten(side, child.score);
337 if best.is_none_or(|best| improves(side, child.score, best.score)) {
338 best = Some(child);
339 self.adopt(frame.ply, step);
340 }
341 }
342
343 self.leave(frame.ply, moves);
344 let Some(best) = best else {
345 return Node::horizon(game.evaluate(here.position()));
346 };
347
348 let node = Node {
349 proven,
350 reach,
351 ..best
352 };
353 self.finish(side, node, total - searched, widened)
354 }
355
356 #[inline]
363 fn child<B: Budget<Stats>, H: Place<G>>(
364 &mut self,
365 run: &mut Run<'_, G, B>,
366 here: &mut H,
367 frame: Frame<G::Score>,
368 (side, later): (Side, bool),
369 ) -> Node<G::Score> {
370 let scout = frame
371 .window
372 .null(side)
373 .filter(|_| later && self.algorithm == Algorithm::Pvs);
374 if let Some(window) = scout {
375 let node = self.visit(run, here, Frame { window, ..frame }, None);
376 if self.aborted || !frame.window.needs_research(&node) {
377 return node;
378 }
379
380 self.stats.researches += 1;
381 }
382
383 self.visit(run, here, frame, None)
384 }
385
386 fn finish(
389 &mut self,
390 side: Side,
391 best: Node<G::Score>,
392 skipped: usize,
393 widened: bool,
394 ) -> Node<G::Score> {
395 let cut = skipped > 0;
396 if cut && !self.aborted {
397 self.stats.cuts += 1;
398 }
399
400 Node {
401 bound: Bound::combine(side, cut, best.bound, widened),
402 skipped,
403 ..best
404 }
405 }
406}
407
408fn promote<M: PartialEq>(moves: &mut [M], mv: &M) -> bool {
410 let Some(index) = moves.iter().position(|candidate| candidate == mv) else {
411 return false;
412 };
413
414 moves[..=index].rotate_right(1);
415 true
416}
417
418fn answer<M, S: Ord + Copy>(entry: &Entry<M, S>, frame: Frame<S>) -> Option<Node<S>> {
426 if frame.ply == 0 || !entry.serves(frame.depth) {
427 return None;
428 }
429
430 let answers = match entry.bound {
431 Bound::Exact => true,
432 Bound::Lower => frame.window.closes(Side::Max, entry.score),
433 Bound::Upper => frame.window.closes(Side::Min, entry.score),
434 Bound::Approximate => false,
435 };
436
437 answers.then(|| Node::stored(entry))
438}
439
440fn stops<G: Game>(game: &G, side: Side, score: G::Score, window: &Window<G::Score>) -> bool {
443 window.closes(side, score) || game.satisfices(side, score)
444}
445
446struct Expansion<M, S> {
448 moves: Vec<M>,
450 hint: Option<M>,
452 stand: Option<Node<S>>,
454}
455
456pub(crate) struct Run<'a, G, B> {
458 pub(crate) game: &'a G,
460 pub(crate) budget: &'a mut B,
462}
463
464#[derive(Debug, Clone, Copy)]
467struct Frame<S> {
468 ply: usize,
470 depth: u32,
472 window: Window<S>,
474 on_hint: bool,
476}
477
478impl<S> Frame<S> {
479 const fn child(&self, window: Window<S>, hinted: bool) -> Self {
481 Self {
482 ply: self.ply + 1,
483 depth: self.depth.saturating_sub(1),
484 window,
485 on_hint: self.on_hint && hinted,
486 }
487 }
488}
489
490#[derive(Debug, Clone, Copy, PartialEq, Eq)]
497pub struct Window<S> {
498 pub alpha: Option<S>,
501 pub beta: Option<S>,
504}
505
506impl<S> Window<S> {
507 pub const FULL: Self = Self {
509 alpha: None,
510 beta: None,
511 };
512}
513
514impl<S: Ord + Copy> Window<S> {
515 pub(crate) const fn is_full(&self) -> bool {
517 self.alpha.is_none() && self.beta.is_none()
518 }
519
520 fn closes(&self, side: Side, score: S) -> bool {
522 match side {
523 Side::Max => self.beta.is_some_and(|beta| score >= beta),
524 Side::Min => self.alpha.is_some_and(|alpha| score <= alpha),
525 }
526 }
527
528 fn null(&self, side: Side) -> Option<Self>
532 where
533 S: Score,
534 {
535 let (alpha, beta) = match side {
536 Side::Max => {
537 let alpha = self.alpha?;
538 (alpha, alpha.next_up())
539 }
540 Side::Min => {
541 let beta = self.beta?;
542 (beta.next_down(), beta)
543 }
544 };
545
546 (alpha < beta).then_some(Self {
547 alpha: Some(alpha),
548 beta: Some(beta),
549 })
550 }
551
552 fn needs_research(&self, node: &Node<S>) -> bool {
555 let above = self.alpha.is_none_or(|alpha| node.score > alpha);
556 let below = self.beta.is_none_or(|beta| node.score < beta);
557
558 node.bound != Bound::Exact && above && below
559 }
560
561 fn tighten(&mut self, side: Side, score: S) {
563 match side {
564 Side::Max => self.alpha = Some(self.alpha.map_or(score, |alpha| alpha.max(score))),
565 Side::Min => self.beta = Some(self.beta.map_or(score, |beta| beta.min(score))),
566 }
567 }
568}
569
570#[derive(Debug, Clone, Copy)]
573pub(crate) struct Node<S> {
574 pub(crate) score: S,
576 pub(crate) bound: Bound,
578 skipped: usize,
580 proven: bool,
582 reach: u32,
584}
585
586impl<S> Node<S> {
587 const fn leaf(score: S) -> Self {
589 Self {
590 score,
591 bound: Bound::Exact,
592 skipped: 0,
593 proven: true,
594 reach: 1,
595 }
596 }
597
598 const fn horizon(score: S) -> Self {
600 Self {
601 score,
602 bound: Bound::Exact,
603 skipped: 0,
604 proven: false,
605 reach: 0,
606 }
607 }
608
609 fn stored<M>(entry: &Entry<M, S>) -> Self
611 where
612 S: Copy,
613 {
614 Self {
615 score: entry.score,
616 bound: entry.bound,
617 skipped: 0,
618 proven: entry.proven,
619 reach: entry.reach,
620 }
621 }
622}
623
624#[cfg(test)]
626mod tests {
627 use alloc::vec;
628 use alloc::vec::Vec;
629
630 use super::{Frame, Run, Window, answer};
631 use crate::incremental::Borrowed;
632 use crate::table::Entry;
633 use crate::{Bound, Game, Searcher, Side, Stats};
634
635 struct TwoMoves;
637
638 impl Game for TwoMoves {
639 type Position = bool;
641 type Move = u8;
643 type Score = i32;
645
646 fn side_to_move(&self, _: &bool) -> Side {
647 Side::Max
648 }
649
650 fn moves(&self, &root: &bool, moves: &mut Vec<u8>) {
651 if root {
652 moves.extend([1, 2]);
653 }
654 }
655
656 fn play(&self, _: &bool, _: &u8) -> bool {
657 false
658 }
659
660 fn evaluate(&self, _: &bool) -> i32 {
661 0
662 }
663 }
664
665 fn search_with_hint(hint: Vec<u8>) -> Option<u8> {
667 let mut searcher = Searcher::<TwoMoves>::new();
668 searcher.hint = hint;
669 let mut unlimited = |_: &Stats| false;
670 let mut run = Run {
671 game: &TwoMoves,
672 budget: &mut unlimited,
673 };
674
675 let node = searcher.iterate(&mut run, &mut Borrowed(&true), 2, Window::FULL);
676 searcher.result(&node, 2).best().copied()
677 }
678
679 #[test]
682 fn unusable_entries_answer_nothing() {
683 let entry = |bound, depth| Entry::<u8, i32> {
684 depth,
685 score: 3,
686 bound,
687 best: None,
688 proven: false,
689 reach: 0,
690 };
691 let frame = Frame {
692 ply: 1,
693 depth: 2,
694 window: Window {
695 alpha: Some(0),
696 beta: Some(5),
697 },
698 on_hint: false,
699 };
700
701 assert!(answer(&entry(Bound::Approximate, 2), frame).is_none());
702 assert!(answer(&entry(Bound::Exact, 3), frame).is_none());
703 assert!(answer(&entry(Bound::Lower, 2), frame).is_none());
704 assert!(answer(&entry(Bound::Upper, 2), frame).is_none());
705 let beyond = Frame {
706 window: Window {
707 alpha: Some(3),
708 beta: Some(3),
709 },
710 ..frame
711 };
712 assert!(answer(&entry(Bound::Lower, 2), beyond).is_some());
713 assert!(answer(&entry(Bound::Upper, 2), beyond).is_some());
714 }
715
716 #[test]
720 fn pvs_scouts_only_later_children() {
721 let mut searcher = Searcher::<TwoMoves>::new().with_algorithm(crate::Algorithm::Pvs);
722 let mut unlimited = |_: &Stats| false;
723 let mut run = Run {
724 game: &TwoMoves,
725 budget: &mut unlimited,
726 };
727 let frame = Frame {
728 ply: 1,
729 depth: 1,
730 window: Window {
731 alpha: Some(-1),
732 beta: Some(1),
733 },
734 on_hint: false,
735 };
736
737 let first = searcher.child(&mut run, &mut Borrowed(&true), frame, (Side::Max, false));
738 assert_eq!(
739 (first.score, first.bound, searcher.stats.researches),
740 (0, Bound::Exact, 0)
741 );
742
743 let later = searcher.child(&mut run, &mut Borrowed(&true), frame, (Side::Max, true));
744 assert_eq!(
745 (later.score, later.bound, searcher.stats.researches),
746 (0, Bound::Exact, 1)
747 );
748 }
749
750 #[test]
753 fn a_budgeted_first_iteration_stops_at_once() {
754 let mut searcher = Searcher::<TwoMoves>::new();
755 searcher.budget_first = true;
756 let result = searcher.deepen(&TwoMoves, &true, 5, |_: &Stats| true);
757 assert_eq!((result.stats.nodes, result.pv.len()), (0, 0));
758 }
759
760 #[test]
762 fn only_legal_hints_are_tried_first() {
763 assert_eq!(search_with_hint(vec![2]), Some(2));
764 assert_eq!(search_with_hint(vec![9]), Some(1));
765 assert_eq!(search_with_hint(Vec::new()), Some(1));
766 }
767}