-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlpha_Beta.H
More file actions
1165 lines (1039 loc) · 46.1 KB
/
Copy pathAlpha_Beta.H
File metadata and controls
1165 lines (1039 loc) · 46.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file Alpha_Beta.H
* @brief Alpha-Beta pruning over the adversarial-search contract.
*
* This module keeps the same game adapter required by @ref Negamax.H but adds
* Alpha-Beta cutoffs on top of the same depth-first recurrence and result
* vocabulary. Through @ref Aleph::ExplorationPolicy it also supports opt-in move
* ordering by shallow score estimate plus lightweight killer/history hooks.
*
* @author Leandro Rabindranath León
*/
# ifndef ALPHA_BETA_H
# define ALPHA_BETA_H
#include <limits>
#include <utility>
#include <ah-errors.H>
#include <Negamax.H>
namespace Aleph {
/** @brief Adversarial search engine with Alpha-Beta pruning.
*
* Alpha-Beta improves upon pure Negamax by pruning branches that are
* guaranteed to be worse than a previously discovered line of play.
*
* The domain contract and score semantics are identical to @ref Negamax:
* `evaluate(state)` must always be expressed from the side-to-move
* perspective, while `apply()` / `undo()` alternate turns through the state.
*
* If `policy.move_ordering == MoveOrderingMode::Estimated_Score`, the engine
* materializes each successor batch, scores children by a one-ply estimate,
* and reorders them before search. Optional killer/history hooks can further
* bias that ordering when explicitly enabled.
*
* @tparam Domain game adapter exposing adversarial-search hooks.
*/
template <AdversarialGameDomain Domain>
class Alpha_Beta
{
public:
/// Type of the problem domain.
using Domain_Type = Domain;
/// Concrete search state type.
using State = typename Domain::State;
/// Move type.
using Move = typename Domain::Move;
/// Score type used for board evaluation.
using Score = typename Domain::Score;
/// Outcome of an Alpha-Beta search execution.
using Result = AdversarialSearchResult<Move, Score>;
/// Two-slot killer heuristic table for this move type.
using Killer_Table = Killer_Move_Table<Move>;
/// History heuristic table type (sparse or no-op depending on domain).
using History_Table = typename adversarial_search_detail::History_Table_Selector<Domain>::Type;
/** @brief Compile-time marker: Alpha_Beta only supports Depth_First strategy.
*
* Passing `ExplorationPolicy::Strategy::Best_First` to this engine raises
* `std::invalid_argument` at runtime. Check this constant before
* constructing a policy to detect the mismatch at compile time.
*/
static constexpr bool supports_best_first = false;
/** @brief Return the default exploration policy for Alpha-Beta. */
[[nodiscard]] static ExplorationPolicy default_policy() noexcept
{
return Negamax<Domain>::default_policy();
}
/** @brief Build an Alpha-Beta engine bound to one game domain. */
explicit Alpha_Beta(Domain domain,
ExplorationPolicy policy = default_policy(),
const SearchLimits &limits = {})
: domain_(std::move(domain)), policy_(policy), limits_(limits)
{
// empty
}
/** @brief Read-only access to the bound game domain. */
[[nodiscard]] const Domain &domain() const noexcept
{
return domain_;
}
/** @brief Mutable access to the bound game domain. */
[[nodiscard]] Domain &domain() noexcept
{
return domain_;
}
/** @brief Current exploration policy. */
[[nodiscard]] const ExplorationPolicy &policy() const noexcept
{
return policy_;
}
/** @brief Current hard limits. */
[[nodiscard]] const SearchLimits &limits() const noexcept
{
return limits_;
}
/** @brief Replace the exploration policy for future runs. */
void set_policy(const ExplorationPolicy &policy) noexcept
{
policy_ = policy;
}
/** @brief Replace the hard limits for future runs. */
void set_limits(const SearchLimits &limits) noexcept
{
limits_ = limits;
}
/** @brief Execute Alpha-Beta from `initial_state`.
*
* @param[in] initial_state Root position.
* @return Root score and one principal variation.
*
* @throws std::invalid_argument if unsupported common-policy values are
* requested.
*/
[[nodiscard]] Result search(State initial_state)
{
Null_Adversarial_Search_Tracer tracer;
return search(std::move(initial_state), tracer);
}
/** @brief Execute Alpha-Beta from `initial_state` while emitting trace events. */
template <typename Tracer>
requires AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] Result search(State initial_state, Tracer &tracer)
{
adversarial_search_detail::Null_Transposition_Table<AdversarialTranspositionEntry<Move, Score>> table;
adversarial_search_detail::Dummy_State_Key keyer;
return search_impl(std::move(initial_state),
table,
keyer,
tracer,
adversarial_search_detail::score_floor<Score>(),
adversarial_search_detail::score_ceiling<Score>());
}
/** @brief Execute Alpha-Beta with an explicit root window. */
[[nodiscard]] Result search_with_window(State initial_state, const Score alpha, const Score beta)
{
Null_Adversarial_Search_Tracer tracer;
return search_with_window(std::move(initial_state), alpha, beta, tracer);
}
/** @brief Execute Alpha-Beta with an explicit root window and tracing. */
template <typename Tracer>
requires AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] Result search_with_window(State initial_state,
const Score alpha,
const Score beta,
Tracer &tracer)
{
adversarial_search_detail::Null_Transposition_Table<AdversarialTranspositionEntry<Move, Score>> table;
adversarial_search_detail::Dummy_State_Key keyer;
return search_impl(std::move(initial_state), table, keyer, tracer, alpha, beta);
}
/** @brief Execute Alpha-Beta with a transposition table and explicit keyer. */
template <typename Table, typename Keyer>
requires AdversarialSearchKeyer<Table, Keyer, State, Move, Score>
[[nodiscard]] Result search(State initial_state, Table &table, Keyer keyer)
{
Null_Adversarial_Search_Tracer tracer;
return search(std::move(initial_state), table, keyer, tracer);
}
/** @brief Execute Alpha-Beta with TT/keyer and tracing. */
template <typename Table, typename Keyer, typename Tracer>
requires AdversarialSearchKeyer<Table, Keyer, State, Move, Score>
and AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] Result search(State initial_state, Table &table, Keyer keyer, Tracer &tracer)
{
return search_impl(std::move(initial_state),
table,
keyer,
tracer,
adversarial_search_detail::score_floor<Score>(),
adversarial_search_detail::score_ceiling<Score>());
}
/** @brief Execute Alpha-Beta with TT/keyer and an explicit root window. */
template <typename Table, typename Keyer>
requires AdversarialSearchKeyer<Table, Keyer, State, Move, Score>
[[nodiscard]] Result search_with_window(
State initial_state, Table &table, Keyer keyer, const Score alpha, const Score beta)
{
Null_Adversarial_Search_Tracer tracer;
return search_with_window(std::move(initial_state), table, keyer, alpha, beta, tracer);
}
/** @brief Execute Alpha-Beta with TT/keyer, root window and tracing. */
template <typename Table, typename Keyer, typename Tracer>
requires AdversarialSearchKeyer<Table, Keyer, State, Move, Score>
and AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] Result search_with_window(State initial_state,
Table &table,
Keyer keyer,
const Score alpha,
const Score beta,
Tracer &tracer)
{
return search_impl(std::move(initial_state), table, keyer, tracer, alpha, beta);
}
/** @brief Execute Alpha-Beta with a transposition table using `domain().state_key()`. */
template <typename Table, typename D_ = Domain>
requires SearchStateKeyProvider<D_>
and AdversarialTranspositionMemo<Table, typename D_::State_Key, Move, Score>
[[nodiscard]] Result search(State initial_state, Table &table)
{
Null_Adversarial_Search_Tracer tracer;
auto keyer = [this](const State &state)
{
return domain_.state_key(state);
};
return search_impl(std::move(initial_state),
table,
keyer,
tracer,
adversarial_search_detail::score_floor<Score>(),
adversarial_search_detail::score_ceiling<Score>());
}
/** @brief Execute Alpha-Beta with domain-provided key and tracing. */
template <typename Table, typename Tracer, typename D_ = Domain>
requires SearchStateKeyProvider<D_>
and AdversarialTranspositionMemo<Table, typename D_::State_Key, Move, Score>
and AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] Result search(State initial_state, Table &table, Tracer &tracer)
{
auto keyer = [this](const State &state)
{
return domain_.state_key(state);
};
return search_impl(std::move(initial_state),
table,
keyer,
tracer,
adversarial_search_detail::score_floor<Score>(),
adversarial_search_detail::score_ceiling<Score>());
}
/** @brief Execute Alpha-Beta with domain-provided key and explicit root window. */
template <typename Table, typename D_ = Domain>
requires SearchStateKeyProvider<D_>
and AdversarialTranspositionMemo<Table, typename D_::State_Key, Move, Score>
[[nodiscard]] Result search_with_window(State initial_state,
Table &table,
const Score alpha,
const Score beta)
{
Null_Adversarial_Search_Tracer tracer;
auto keyer = [this](const State &state)
{
return domain_.state_key(state);
};
return search_impl(std::move(initial_state), table, keyer, tracer, alpha, beta);
}
/** @brief Execute Alpha-Beta with domain-provided key, root window and tracing. */
template <typename Table, typename Tracer, typename D_ = Domain>
requires SearchStateKeyProvider<D_>
and AdversarialTranspositionMemo<Table, typename D_::State_Key, Move, Score>
and AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] Result search_with_window(
State initial_state, Table &table, const Score alpha, const Score beta, Tracer &tracer)
{
auto keyer = [this](const State &state)
{
return domain_.state_key(state);
};
return search_impl(std::move(initial_state), table, keyer, tracer, alpha, beta);
}
private:
Domain domain_;
ExplorationPolicy policy_;
SearchLimits limits_;
bool stop_ = false;
Killer_Table killer_moves_;
History_Table history_moves_;
[[nodiscard]] bool ordering_active() const noexcept
{
return policy_.move_ordering != MoveOrderingMode::Domain or policy_.use_killer_moves
or policy_.use_history_heuristic;
}
void validate_ordering_configuration() const
{
ah_invalid_argument_if(policy_.move_ordering == MoveOrderingMode::Estimated_Bound)
<< "Alpha_Beta does not support MoveOrderingMode::Estimated_Bound";
if constexpr (not Killer_Table::supported)
ah_invalid_argument_if(policy_.use_killer_moves)
<< "Alpha_Beta killer heuristic requires equality-comparable Move";
if constexpr (not MoveKeyProvider<Domain>)
ah_invalid_argument_if(policy_.use_history_heuristic)
<< "Alpha_Beta history heuristic requires domain.move_key(move)";
}
void clear_ordering_heuristics()
{
killer_moves_.clear();
history_moves_.clear();
}
[[nodiscard]] static size_t history_bonus(const size_t depth, const size_t remaining) noexcept
{
const size_t base = remaining == Search_Unlimited ? depth + 1 : remaining + 1;
return base * base;
}
[[nodiscard]] size_t move_history_score(const Move &move) const noexcept
{
if constexpr (MoveKeyProvider<Domain>)
if (policy_.use_history_heuristic)
return history_moves_.score(domain_.move_key(move));
return 0;
}
void record_cutoff_move(const size_t depth, const size_t remaining, const Move &move)
{
if (policy_.use_killer_moves)
killer_moves_.record(depth, move);
if constexpr (MoveKeyProvider<Domain>)
if (policy_.use_history_heuristic)
history_moves_.record(domain_.move_key(move), history_bonus(depth, remaining));
}
[[nodiscard]] Array<RankedMove<Move, Score>> collect_ordered_moves(State &state,
const size_t depth,
Result &result)
{
Array<RankedMove<Move, Score>> moves;
size_t ordinal = 0;
(void) domain_.for_each_successor(state,
[&](const Move &move) -> bool
{
RankedMove<Move, Score> ranked;
ranked.move = move;
ranked.ordinal = ordinal++;
if (policy_.use_killer_moves)
{
ranked.killer = killer_moves_.is_killer(depth, move);
if (ranked.killer)
++result.stats.move_ordering.killer_hits;
}
if (policy_.use_history_heuristic)
{
ranked.history_score = move_history_score(move);
if (ranked.history_score > 0)
++result.stats.move_ordering.history_hits;
}
if (policy_.move_ordering == MoveOrderingMode::Estimated_Score)
{
if constexpr (IncrementalEvaluator<Domain>)
{
// Fast path: estimate score without apply/undo.
ranked.priority = -domain_.evaluate_after(state, move);
}
else
{
bool applied = false;
try
{
domain_.apply(state, move);
applied = true;
ranked.priority = -domain_.evaluate(state);
}
catch (...)
{
if (applied)
domain_.undo(state, move);
throw;
}
domain_.undo(state, move);
}
++result.stats.heuristic_evaluations;
++result.stats.move_ordering.priority_estimates;
}
moves.append(std::move(ranked));
return true;
});
if (not moves.is_empty())
{
++result.stats.move_ordering.ordered_batches;
result.stats.move_ordering.ordered_moves += moves.size();
}
sort_ranked_moves(moves,
[](const Score &lhs, const Score &rhs) noexcept
{
return lhs > rhs;
},
policy_.use_killer_moves,
policy_.use_history_heuristic);
return moves;
}
template <typename Table, typename Keyer, typename Tracer>
requires AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] Result search_impl(State initial_state,
Table &table,
Keyer &keyer,
Tracer &tracer,
const Score alpha,
const Score beta)
{
ah_invalid_argument_if(policy_.strategy != ExplorationPolicy::Strategy::Depth_First)
<< "Alpha_Beta only supports depth-first exploration";
ah_invalid_argument_if(limits_.max_solutions == 0)
<< "SearchLimits::max_solutions must be positive or Search_Unlimited";
ah_invalid_argument_unless(alpha < beta) << "Alpha_Beta root window requires alpha < beta";
validate_ordering_configuration();
Result result;
result.policy = policy_;
result.limits = limits_;
const auto start_time = SearchClock::now();
stop_ = false;
clear_ordering_heuristics();
auto root = search_node(initial_state, 0, result, table, keyer, tracer, alpha, beta);
result.value = root.value;
result.principal_variation = std::move(root.principal_variation);
if (result.status == SearchStatus::NotStarted)
result.status = SearchStatus::Exhausted;
result.stats.elapsed_ms = search_elapsed_ms(SearchClock::now() - start_time);
return result;
}
[[nodiscard]] bool expansion_limit_reached(Result &result)
{
if (search_engine_detail::expansion_limit_reached(result, limits_))
{
stop_ = true;
return true;
}
return false;
}
template <typename Table, typename Keyer>
void store_transposition(State &state,
const size_t remaining,
Result &result,
Table &table,
Keyer &keyer,
const adversarial_search_detail::NodeEvaluation<Move, Score> &value,
const TranspositionBound bound)
{
adversarial_search_detail::store_adversarial_transposition<Move, Score>(
state, remaining, result, table, keyer, value, bound, stop_);
}
template <typename Table, typename Keyer>
[[nodiscard]] bool probe_transposition(State &state,
const size_t remaining,
Result &result,
Table &table,
Keyer &keyer,
Score &alpha,
Score &beta,
adversarial_search_detail::NodeEvaluation<Move, Score> &out)
{
auto *entry = adversarial_search_detail::probe_and_count_transposition<Move, Score>(
state, remaining, result, table, keyer);
if (entry != nullptr)
{
switch (entry->bound)
{
case TranspositionBound::Exact:
++result.stats.transpositions.cutoffs;
out.value = entry->value;
out.principal_variation = entry->principal_variation;
return true;
case TranspositionBound::Lower_Bound:
if (entry->value > alpha)
alpha = entry->value;
break;
case TranspositionBound::Upper_Bound:
if (entry->value < beta)
beta = entry->value;
break;
}
if (alpha >= beta)
{
++result.stats.transpositions.cutoffs;
out.value = entry->value;
out.principal_variation = entry->principal_variation;
return true;
}
}
return false;
}
template <typename Table, typename Keyer, typename Tracer>
requires AdversarialSearchTracer<Tracer, Move, Score>
[[nodiscard]] adversarial_search_detail::NodeEvaluation<Move, Score> search_node(State &state,
const size_t depth,
Result &result,
Table &table,
Keyer &keyer,
Tracer &tracer,
const Score alpha,
const Score beta)
{
using adversarial_search_detail::emit_trace;
using adversarial_search_detail::evaluate_leaf;
using adversarial_search_detail::first_move_of;
using adversarial_search_detail::prepend_move;
using adversarial_search_detail::remaining_depth;
search_engine_detail::register_visit(depth, result);
const size_t remaining = remaining_depth(limits_, depth);
emit_trace<Move, Score>(
tracer, AdversarialTraceEventKind::Enter_Node, depth, remaining, 0, 0, 0, Score{}, alpha, beta);
Score local_alpha = alpha;
Score local_beta = beta;
const Score alpha_orig = alpha;
const Score beta_orig = beta;
adversarial_search_detail::NodeEvaluation<Move, Score> cached;
if (probe_transposition(state, remaining, result, table, keyer, local_alpha, local_beta, cached))
{
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Transposition_Hit,
depth,
remaining,
0,
0,
0,
cached.value,
local_alpha,
local_beta,
first_move_of(cached.principal_variation));
return cached;
}
if (domain_.is_terminal(state))
{
++result.stats.terminal_states;
auto leaf = evaluate_leaf(domain_, state, result);
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Terminal_Node,
depth,
remaining,
0,
0,
0,
leaf.value,
local_alpha,
local_beta);
store_transposition(state, remaining, result, table, keyer, leaf, TranspositionBound::Exact);
return leaf;
}
if (depth >= limits_.max_depth)
{
++result.stats.pruned_by_depth;
auto leaf = evaluate_leaf(domain_, state, result);
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Depth_Cutoff,
depth,
remaining,
0,
0,
0,
leaf.value,
local_alpha,
local_beta);
store_transposition(state, remaining, result, table, keyer, leaf, TranspositionBound::Exact);
return leaf;
}
if (search_engine_detail::should_prune_state(domain_, state, depth))
{
++result.stats.pruned_by_domain;
auto leaf = evaluate_leaf(domain_, state, result);
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Domain_Prune,
depth,
remaining,
0,
0,
0,
leaf.value,
local_alpha,
local_beta);
store_transposition(state, remaining, result, table, keyer, leaf, TranspositionBound::Exact);
return leaf;
}
if (expansion_limit_reached(result))
{
auto leaf = evaluate_leaf(domain_, state, result);
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Expansion_Limit,
depth,
remaining,
0,
0,
0,
leaf.value,
local_alpha,
local_beta);
return leaf;
}
adversarial_search_detail::NodeEvaluation<Move, Score> best;
bool has_move = false;
bool has_best = false;
bool counted_expansion = false;
auto explore_move = [&](const Move &move) -> bool
{
if (stop_)
return false;
if (not counted_expansion)
{
++result.stats.expanded_states;
counted_expansion = true;
}
has_move = true;
++result.stats.generated_successors;
adversarial_search_detail::NodeEvaluation<Move, Score> child;
bool applied = false;
try
{
domain_.apply(state, move);
applied = true;
child = search_node(
state, depth + 1, result, table, keyer, tracer, -local_beta, -local_alpha);
}
catch (...)
{
if (applied)
domain_.undo(state, move);
throw;
}
domain_.undo(state, move);
const Score candidate = (child.value == std::numeric_limits<Score>::lowest())
? std::numeric_limits<Score>::max()
: -child.value;
if (not has_best or candidate > best.value)
{
best.value = candidate;
best.principal_variation = prepend_move(move, child.principal_variation);
has_best = true;
}
if (candidate > local_alpha)
local_alpha = candidate;
if (local_alpha >= local_beta)
{
++result.stats.alpha_beta_cutoffs;
record_cutoff_move(depth, remaining, move);
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Alpha_Beta_Cutoff,
depth,
remaining,
0,
0,
0,
best.value,
local_alpha,
local_beta,
std::optional<Move>{move});
return false;
}
return not stop_;
};
if (ordering_active())
{
for (auto ordered_moves = collect_ordered_moves(state, depth, result);
const auto &ranked : ordered_moves)
if (not explore_move(ranked.move))
break;
}
else
(void) domain_.for_each_successor(state,
[&](const Move &move) -> bool
{
return explore_move(move);
});
if (not has_move)
{
++result.stats.terminal_states;
auto leaf = evaluate_leaf(domain_, state, result);
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Terminal_Node,
depth,
remaining,
0,
0,
0,
leaf.value,
local_alpha,
local_beta);
store_transposition(state, remaining, result, table, keyer, leaf, TranspositionBound::Exact);
return leaf;
}
auto bound = TranspositionBound::Exact;
if (best.value <= alpha_orig)
bound = TranspositionBound::Upper_Bound;
else if (best.value >= beta_orig)
bound = TranspositionBound::Lower_Bound;
emit_trace<Move, Score>(tracer,
AdversarialTraceEventKind::Exit_Node,
depth,
remaining,
0,
0,
0,
best.value,
local_alpha,
local_beta,
first_move_of(best.principal_variation));
store_transposition(state, remaining, result, table, keyer, best, bound);
return best;
}
};
/** @brief Convenience wrapper for one-shot Alpha-Beta search. */
template <AdversarialGameDomain Domain>
[[nodiscard]] auto alpha_beta_search(Domain domain,
typename Domain::State initial_state,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {})
{
Alpha_Beta<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state));
}
/** @brief Convenience wrapper for one-shot Alpha-Beta search with tracing. */
template <AdversarialGameDomain Domain, typename Tracer>
requires AdversarialSearchTracer<Tracer, typename Domain::Move, typename Domain::Score>
[[nodiscard]] auto alpha_beta_search(Domain domain,
typename Domain::State initial_state,
Tracer &tracer,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {})
{
Alpha_Beta<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state), tracer);
}
/** @brief Convenience wrapper for Alpha-Beta search with transposition table. */
template <AdversarialGameDomain Domain, typename Table, typename Keyer>
requires AdversarialSearchKeyer<Table, Keyer, typename Domain::State, typename Domain::Move, typename Domain::Score>
[[nodiscard]] auto alpha_beta_search(Domain domain,
typename Domain::State initial_state,
Table &table,
Keyer keyer,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {})
{
Alpha_Beta<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state), table, keyer);
}
/** @brief Convenience wrapper for Alpha-Beta search with TT/keyer and tracing. */
template <AdversarialGameDomain Domain, typename Table, typename Keyer, typename Tracer>
requires AdversarialSearchKeyer<Table, Keyer, typename Domain::State, typename Domain::Move, typename Domain::Score>
and AdversarialSearchTracer<Tracer, typename Domain::Move, typename Domain::Score>
[[nodiscard]] auto alpha_beta_search(Domain domain,
typename Domain::State initial_state,
Table &table,
Keyer keyer,
Tracer &tracer,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {})
{
Alpha_Beta<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state), table, keyer, tracer);
}
/** @brief Convenience wrapper for Alpha-Beta search with domain-provided state key. */
template <AdversarialGameDomain Domain, typename Table>
requires SearchStateKeyProvider<Domain>
and AdversarialTranspositionMemo<Table, typename Domain::State_Key, typename Domain::Move, typename Domain::Score>
[[nodiscard]] auto alpha_beta_search(Domain domain,
typename Domain::State initial_state,
Table &table,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {})
{
Alpha_Beta<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state), table);
}
/** @brief Convenience wrapper for Alpha-Beta search with domain-provided key and tracing. */
template <AdversarialGameDomain Domain, typename Table, typename Tracer>
requires SearchStateKeyProvider<Domain>
and AdversarialTranspositionMemo<Table, typename Domain::State_Key, typename Domain::Move, typename Domain::Score>
and AdversarialSearchTracer<Tracer, typename Domain::Move, typename Domain::Score>
[[nodiscard]] auto alpha_beta_search(Domain domain,
typename Domain::State initial_state,
Table &table,
Tracer &tracer,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {})
{
Alpha_Beta<Domain> engine(std::move(domain), policy, limits);
return engine.search(std::move(initial_state), table, tracer);
}
/** @brief Iterative deepening over Alpha-Beta with optional aspiration windows. */
template <AdversarialGameDomain Domain, typename Tracer>
requires AdversarialSearchTracer<Tracer, typename Domain::Move, typename Domain::Score>
[[nodiscard]] auto iterative_deepening_alpha_beta_search(
Domain domain,
typename Domain::State initial_state,
Tracer &tracer,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {},
AdversarialIterativeDeepeningOptions<typename Domain::Score> options = {})
{
using Move = typename Domain::Move;
using Score = typename Domain::Score;
ah_invalid_argument_if(limits.max_depth == Search_Unlimited)
<< "iterative_deepening_alpha_beta_search requires a finite SearchLimits::max_depth";
ah_invalid_argument_if(options.depth_step == 0)
<< "AdversarialIterativeDeepeningOptions::depth_step must be positive";
ah_invalid_argument_if(options.initial_depth > limits.max_depth)
<< "AdversarialIterativeDeepeningOptions::initial_depth exceeds SearchLimits::max_depth";
ah_invalid_argument_if(options.aspiration.half_window < Score{})
<< "AspirationWindow::half_window must be non-negative";
Alpha_Beta<Domain> engine(std::move(domain), policy, limits);
const Score full_alpha = adversarial_search_detail::score_floor<Score>();
const Score full_beta = adversarial_search_detail::score_ceiling<Score>();
return adversarial_search_detail::run_iterative_deepening<Move, Score>(
engine, policy, limits, options, tracer,
[&](AdversarialIterativeDeepeningResult<Move, Score> &out,
AdversarialIterativeDeepeningIteration<Move, Score> &iteration,
const size_t depth, const size_t iteration_index)
{
const bool use_aspiration = options.aspiration.enabled() and out.has_iterations();
iteration.used_aspiration_window = use_aspiration;
Score center = Score{};
Score half_window = options.aspiration.half_window;
if (use_aspiration)
center = out.result.value;
for (;;)
{
const Score alpha
= use_aspiration
? adversarial_search_detail::saturating_subtract(center, half_window)
: full_alpha;
const Score beta
= use_aspiration
? adversarial_search_detail::saturating_add(center, half_window)
: full_beta;
iteration.aspiration_alpha = alpha;
iteration.aspiration_beta = beta;
iteration.result = engine.search_with_window(initial_state, alpha, beta, tracer);
adversarial_search_detail::accumulate_adversarial_stats(iteration.total_stats,
iteration.result.stats);
if (not use_aspiration or iteration.result.limit_reached())
break;
if (iteration.result.value <= alpha and alpha != full_alpha)
{
++iteration.aspiration_researches;
++out.aspiration_researches;
half_window = adversarial_search_detail::grow_aspiration_half_window(
half_window, options.aspiration);
adversarial_search_detail::emit_trace<Move, Score>(
tracer,
AdversarialTraceEventKind::Aspiration_Retry,
0, depth, iteration_index, depth,
iteration.aspiration_researches,
iteration.result.value,
adversarial_search_detail::saturating_subtract(center, half_window),
adversarial_search_detail::saturating_add(center, half_window),
adversarial_search_detail::first_move_of(iteration.result.principal_variation));
continue;
}
if (iteration.result.value >= beta and beta != full_beta)
{
++iteration.aspiration_researches;
++out.aspiration_researches;
half_window = adversarial_search_detail::grow_aspiration_half_window(
half_window, options.aspiration);
adversarial_search_detail::emit_trace<Move, Score>(
tracer,
AdversarialTraceEventKind::Aspiration_Retry,
0, depth, iteration_index, depth,
iteration.aspiration_researches,
iteration.result.value,
adversarial_search_detail::saturating_subtract(center, half_window),
adversarial_search_detail::saturating_add(center, half_window),
adversarial_search_detail::first_move_of(iteration.result.principal_variation));
continue;
}
break;
}
});
}
/** @brief Iterative deepening over Alpha-Beta with TT/keyer reuse. */
template <AdversarialGameDomain Domain, typename Table, typename Keyer, typename Tracer>
requires AdversarialSearchKeyer<Table, Keyer, typename Domain::State, typename Domain::Move, typename Domain::Score>
and AdversarialSearchTracer<Tracer, typename Domain::Move, typename Domain::Score>
[[nodiscard]] auto iterative_deepening_alpha_beta_search(
Domain domain,
typename Domain::State initial_state,
Table &table,
Keyer keyer,
Tracer &tracer,
ExplorationPolicy policy = Alpha_Beta<Domain>::default_policy(),
SearchLimits limits = {},
AdversarialIterativeDeepeningOptions<typename Domain::Score> options = {})
{
using Move = typename Domain::Move;
using Score = typename Domain::Score;
ah_invalid_argument_if(limits.max_depth == Search_Unlimited)
<< "iterative_deepening_alpha_beta_search requires a finite SearchLimits::max_depth";
ah_invalid_argument_if(options.depth_step == 0)