2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2009 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
42 #include "ucioption.h"
48 //// Local definitions
55 // IterationInfoType stores search results for each iteration
57 // Because we use relatively small (dynamic) aspiration window,
58 // there happens many fail highs and fail lows in root. And
59 // because we don't do researches in those cases, "value" stored
60 // here is not necessarily exact. Instead in case of fail high/low
61 // we guess what the right value might be and store our guess
62 // as a "speculated value" and then move on. Speculated values are
63 // used just to calculate aspiration window width, so also if are
64 // not exact is not big a problem.
66 struct IterationInfoType {
68 IterationInfoType(Value v = Value(0), Value sv = Value(0))
69 : value(v), speculatedValue(sv) {}
71 Value value, speculatedValue;
75 // The BetaCounterType class is used to order moves at ply one.
76 // Apart for the first one that has its score, following moves
77 // normally have score -VALUE_INFINITE, so are ordered according
78 // to the number of beta cutoffs occurred under their subtree during
79 // the last iteration. The counters are per thread variables to avoid
80 // concurrent accessing under SMP case.
82 struct BetaCounterType {
86 void add(Color us, Depth d, int threadID);
87 void read(Color us, int64_t& our, int64_t& their);
91 // The RootMove class is used for moves at the root at the tree. For each
92 // root move, we store a score, a node count, and a PV (really a refutation
93 // in the case of moves which fail low).
97 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
99 // RootMove::operator<() is the comparison function used when
100 // sorting the moves. A move m1 is considered to be better
101 // than a move m2 if it has a higher score, or if the moves
102 // have equal score but m1 has the higher node count.
103 bool operator<(const RootMove& m) const {
105 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
110 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
111 Move pv[PLY_MAX_PLUS_2];
115 // The RootMoveList class is essentially an array of RootMove objects, with
116 // a handful of methods for accessing the data in the individual moves.
121 RootMoveList(Position& pos, Move searchMoves[]);
123 int move_count() const { return count; }
124 Move get_move(int moveNum) const { return moves[moveNum].move; }
125 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
126 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
127 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
128 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
130 void set_move_nodes(int moveNum, int64_t nodes);
131 void set_beta_counters(int moveNum, int64_t our, int64_t their);
132 void set_move_pv(int moveNum, const Move pv[]);
134 void sort_multipv(int n);
137 static const int MaxRootMoves = 500;
138 RootMove moves[MaxRootMoves];
145 // Search depth at iteration 1
146 const Depth InitialDepth = OnePly;
148 // Depth limit for selective search
149 const Depth SelectiveDepth = 7 * OnePly;
151 // Use internal iterative deepening?
152 const bool UseIIDAtPVNodes = true;
153 const bool UseIIDAtNonPVNodes = true;
155 // Internal iterative deepening margin. At Non-PV moves, when
156 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
157 // search when the static evaluation is at most IIDMargin below beta.
158 const Value IIDMargin = Value(0x100);
160 // Easy move margin. An easy move candidate must be at least this much
161 // better than the second best move.
162 const Value EasyMoveMargin = Value(0x200);
164 // Problem margin. If the score of the first move at iteration N+1 has
165 // dropped by more than this since iteration N, the boolean variable
166 // "Problem" is set to true, which will make the program spend some extra
167 // time looking for a better move.
168 const Value ProblemMargin = Value(0x28);
170 // No problem margin. If the boolean "Problem" is true, and a new move
171 // is found at the root which is less than NoProblemMargin worse than the
172 // best move from the previous iteration, Problem is set back to false.
173 const Value NoProblemMargin = Value(0x14);
175 // Null move margin. A null move search will not be done if the static
176 // evaluation of the position is more than NullMoveMargin below beta.
177 const Value NullMoveMargin = Value(0x200);
179 // If the TT move is at least SingleReplyMargin better then the
180 // remaining ones we will extend it.
181 const Value SingleReplyMargin = Value(0x20);
183 // Margins for futility pruning in the quiescence search, and at frontier
184 // and near frontier nodes.
185 const Value FutilityMarginQS = Value(0x80);
187 // Each move futility margin is decreased
188 const Value IncrementalFutilityMargin = Value(0x8);
190 // Depth limit for razoring
191 const Depth RazorDepth = 4 * OnePly;
193 /// Variables initialized by UCI options
195 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
196 int LMRPVMoves, LMRNonPVMoves;
198 // Depth limit for use of dynamic threat detection
201 // Last seconds noise filtering (LSN)
202 const bool UseLSNFiltering = true;
203 const int LSNTime = 4000; // In milliseconds
204 const Value LSNValue = value_from_centipawns(200);
205 bool loseOnTime = false;
207 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
208 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
209 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
211 // Iteration counters
213 BetaCounterType BetaCounter;
215 // Scores and number of times the best move changed for each iteration
216 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
217 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
222 // Time managment variables
225 int MaxNodes, MaxDepth;
226 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
227 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
228 bool AbortSearch, Quit;
229 bool FailHigh, FailLow, Problem;
231 // Show current line?
232 bool ShowCurrentLine;
236 std::ofstream LogFile;
238 // MP related variables
239 int ActiveThreads = 1;
240 Depth MinimumSplitDepth;
241 int MaxThreadsPerSplitPoint;
242 Thread Threads[THREAD_MAX];
245 bool AllThreadsShouldExit = false;
246 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
249 #if !defined(_MSC_VER)
250 pthread_cond_t WaitCond;
251 pthread_mutex_t WaitLock;
253 HANDLE SitIdleEvent[THREAD_MAX];
256 // Node counters, used only by thread[0] but try to keep in different
257 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
259 int NodesBetweenPolls = 30000;
267 Value id_loop(const Position& pos, Move searchMoves[]);
268 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
269 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
270 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
271 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
272 void sp_search(SplitPoint* sp, int threadID);
273 void sp_search_pv(SplitPoint* sp, int threadID);
274 void init_node(SearchStack ss[], int ply, int threadID);
275 void update_pv(SearchStack ss[], int ply);
276 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
277 bool connected_moves(const Position& pos, Move m1, Move m2);
278 bool value_is_mate(Value value);
279 bool move_is_killer(Move m, const SearchStack& ss);
280 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
281 bool ok_to_do_nullmove(const Position& pos);
282 bool ok_to_prune(const Position& pos, Move m, Move threat);
283 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
284 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
285 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
286 void update_killers(Move m, SearchStack& ss);
288 bool fail_high_ply_1();
289 int current_search_time();
293 void print_current_line(SearchStack ss[], int ply, int threadID);
294 void wait_for_stop_or_ponderhit();
295 void init_ss_array(SearchStack ss[]);
297 void idle_loop(int threadID, SplitPoint* waitSp);
298 void init_split_point_stack();
299 void destroy_split_point_stack();
300 bool thread_should_stop(int threadID);
301 bool thread_is_available(int slave, int master);
302 bool idle_thread_exists(int master);
303 bool split(const Position& pos, SearchStack* ss, int ply,
304 Value *alpha, Value *beta, Value *bestValue,
305 const Value futilityValue, Depth depth, int *moves,
306 MovePicker *mp, int master, bool pvNode);
307 void wake_sleeping_threads();
309 #if !defined(_MSC_VER)
310 void *init_thread(void *threadID);
312 DWORD WINAPI init_thread(LPVOID threadID);
323 static double lnArray[512];
325 inline double ln(int i)
330 /// perft() is our utility to verify move generation is bug free. All the legal
331 /// moves up to given depth are generated and counted and the sum returned.
333 int perft(Position& pos, Depth depth)
337 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
339 // If we are at the last ply we don't need to do and undo
340 // the moves, just to count them.
341 if (depth <= OnePly) // Replace with '<' to test also qsearch
343 while (mp.get_next_move()) sum++;
347 // Loop through all legal moves
349 while ((move = mp.get_next_move()) != MOVE_NONE)
352 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
353 sum += perft(pos, depth - OnePly);
360 /// think() is the external interface to Stockfish's search, and is called when
361 /// the program receives the UCI 'go' command. It initializes various
362 /// search-related global variables, and calls root_search(). It returns false
363 /// when a quit command is received during the search.
365 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
366 int time[], int increment[], int movesToGo, int maxDepth,
367 int maxNodes, int maxTime, Move searchMoves[]) {
369 // Initialize global search variables
370 Idle = StopOnPonderhit = AbortSearch = Quit = false;
371 FailHigh = FailLow = Problem = false;
373 SearchStartTime = get_system_time();
374 ExactMaxTime = maxTime;
377 InfiniteSearch = infinite;
378 PonderSearch = ponder;
379 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
381 // Look for a book move, only during games, not tests
382 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
385 if (get_option_value_string("Book File") != OpeningBook.file_name())
386 OpeningBook.open(get_option_value_string("Book File"));
388 bookMove = OpeningBook.get_move(pos);
389 if (bookMove != MOVE_NONE)
391 cout << "bestmove " << bookMove << endl;
396 for (int i = 0; i < THREAD_MAX; i++)
398 Threads[i].nodes = 0ULL;
399 Threads[i].failHighPly1 = false;
402 if (button_was_pressed("New Game"))
403 loseOnTime = false; // Reset at the beginning of a new game
405 // Read UCI option values
406 TT.set_size(get_option_value_int("Hash"));
407 if (button_was_pressed("Clear Hash"))
410 bool PonderingEnabled = get_option_value_bool("Ponder");
411 MultiPV = get_option_value_int("MultiPV");
413 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
414 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
416 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
417 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
419 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
420 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
422 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
423 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
425 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
426 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
428 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
429 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
431 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
432 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
433 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
435 Chess960 = get_option_value_bool("UCI_Chess960");
436 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
437 UseLogFile = get_option_value_bool("Use Search Log");
439 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
441 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
442 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
444 read_weights(pos.side_to_move());
446 // Set the number of active threads
447 int newActiveThreads = get_option_value_int("Threads");
448 if (newActiveThreads != ActiveThreads)
450 ActiveThreads = newActiveThreads;
451 init_eval(ActiveThreads);
454 // Wake up sleeping threads
455 wake_sleeping_threads();
457 for (int i = 1; i < ActiveThreads; i++)
458 assert(thread_is_available(i, 0));
461 int myTime = time[side_to_move];
462 int myIncrement = increment[side_to_move];
463 if (UseTimeManagement)
465 if (!movesToGo) // Sudden death time control
469 MaxSearchTime = myTime / 30 + myIncrement;
470 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
472 else // Blitz game without increment
474 MaxSearchTime = myTime / 30;
475 AbsoluteMaxSearchTime = myTime / 8;
478 else // (x moves) / (y minutes)
482 MaxSearchTime = myTime / 2;
483 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
487 MaxSearchTime = myTime / Min(movesToGo, 20);
488 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
492 if (PonderingEnabled)
494 MaxSearchTime += MaxSearchTime / 4;
495 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
499 // Set best NodesBetweenPolls interval
501 NodesBetweenPolls = Min(MaxNodes, 30000);
502 else if (myTime && myTime < 1000)
503 NodesBetweenPolls = 1000;
504 else if (myTime && myTime < 5000)
505 NodesBetweenPolls = 5000;
507 NodesBetweenPolls = 30000;
509 // Write information to search log file
511 LogFile << "Searching: " << pos.to_fen() << endl
512 << "infinite: " << infinite
513 << " ponder: " << ponder
514 << " time: " << myTime
515 << " increment: " << myIncrement
516 << " moves to go: " << movesToGo << endl;
518 // LSN filtering. Used only for developing purpose. Disabled by default.
522 // Step 2. If after last move we decided to lose on time, do it now!
523 while (SearchStartTime + myTime + 1000 > get_system_time())
527 // We're ready to start thinking. Call the iterative deepening loop function
528 Value v = id_loop(pos, searchMoves);
533 // Step 1. If this is sudden death game and our position is hopeless,
534 // decide to lose on time.
535 if ( !loseOnTime // If we already lost on time, go to step 3.
545 // Step 3. Now after stepping over the time limit, reset flag for next match.
558 /// init_threads() is called during startup. It launches all helper threads,
559 /// and initializes the split point stack and the global locks and condition
562 #include <cmath> //FIXME: HACK
564 void init_threads() {
567 for (int i = 0; i < 512; i++)
568 lnArray[i] = log(double(i));
572 #if !defined(_MSC_VER)
573 pthread_t pthread[1];
576 for (i = 0; i < THREAD_MAX; i++)
577 Threads[i].activeSplitPoints = 0;
579 // Initialize global locks
580 lock_init(&MPLock, NULL);
581 lock_init(&IOLock, NULL);
583 init_split_point_stack();
585 #if !defined(_MSC_VER)
586 pthread_mutex_init(&WaitLock, NULL);
587 pthread_cond_init(&WaitCond, NULL);
589 for (i = 0; i < THREAD_MAX; i++)
590 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
593 // All threads except the main thread should be initialized to idle state
594 for (i = 1; i < THREAD_MAX; i++)
596 Threads[i].stop = false;
597 Threads[i].workIsWaiting = false;
598 Threads[i].idle = true;
599 Threads[i].running = false;
602 // Launch the helper threads
603 for (i = 1; i < THREAD_MAX; i++)
605 #if !defined(_MSC_VER)
606 pthread_create(pthread, NULL, init_thread, (void*)(&i));
609 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
612 // Wait until the thread has finished launching
613 while (!Threads[i].running);
618 /// stop_threads() is called when the program exits. It makes all the
619 /// helper threads exit cleanly.
621 void stop_threads() {
623 ActiveThreads = THREAD_MAX; // HACK
624 Idle = false; // HACK
625 wake_sleeping_threads();
626 AllThreadsShouldExit = true;
627 for (int i = 1; i < THREAD_MAX; i++)
629 Threads[i].stop = true;
630 while (Threads[i].running);
632 destroy_split_point_stack();
636 /// nodes_searched() returns the total number of nodes searched so far in
637 /// the current search.
639 int64_t nodes_searched() {
641 int64_t result = 0ULL;
642 for (int i = 0; i < ActiveThreads; i++)
643 result += Threads[i].nodes;
648 // SearchStack::init() initializes a search stack. Used at the beginning of a
649 // new search from the root.
650 void SearchStack::init(int ply) {
652 pv[ply] = pv[ply + 1] = MOVE_NONE;
653 currentMove = threatMove = MOVE_NONE;
654 reduction = Depth(0);
658 void SearchStack::initKillers() {
660 mateKiller = MOVE_NONE;
661 for (int i = 0; i < KILLER_MAX; i++)
662 killers[i] = MOVE_NONE;
667 // id_loop() is the main iterative deepening loop. It calls root_search
668 // repeatedly with increasing depth until the allocated thinking time has
669 // been consumed, the user stops the search, or the maximum search depth is
672 Value id_loop(const Position& pos, Move searchMoves[]) {
675 SearchStack ss[PLY_MAX_PLUS_2];
677 // searchMoves are verified, copied, scored and sorted
678 RootMoveList rml(p, searchMoves);
680 if (rml.move_count() == 0)
683 wait_for_stop_or_ponderhit();
685 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
688 // Print RootMoveList c'tor startup scoring to the standard output,
689 // so that we print information also for iteration 1.
690 cout << "info depth " << 1 << "\ninfo depth " << 1
691 << " score " << value_to_string(rml.get_move_score(0))
692 << " time " << current_search_time()
693 << " nodes " << nodes_searched()
695 << " pv " << rml.get_move(0) << "\n";
701 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
704 // Is one move significantly better than others after initial scoring ?
705 Move EasyMove = MOVE_NONE;
706 if ( rml.move_count() == 1
707 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
708 EasyMove = rml.get_move(0);
710 // Iterative deepening loop
711 while (Iteration < PLY_MAX)
713 // Initialize iteration
716 BestMoveChangesByIteration[Iteration] = 0;
720 cout << "info depth " << Iteration << endl;
722 // Calculate dynamic search window based on previous iterations
725 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
727 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
728 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
730 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
732 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
733 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
737 alpha = - VALUE_INFINITE;
738 beta = VALUE_INFINITE;
741 // Search to the current depth
742 Value value = root_search(p, ss, rml, alpha, beta);
744 // Write PV to transposition table, in case the relevant entries have
745 // been overwritten during the search.
746 TT.insert_pv(p, ss[0].pv);
749 break; // Value cannot be trusted. Break out immediately!
751 //Save info about search result
752 Value speculatedValue;
755 Value delta = value - IterationInfo[Iteration - 1].value;
762 speculatedValue = value + delta;
763 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
765 else if (value <= alpha)
767 assert(value == alpha);
771 speculatedValue = value + delta;
772 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
774 speculatedValue = value;
776 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
777 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
779 // Drop the easy move if it differs from the new best move
780 if (ss[0].pv[0] != EasyMove)
781 EasyMove = MOVE_NONE;
785 if (UseTimeManagement)
788 bool stopSearch = false;
790 // Stop search early if there is only a single legal move,
791 // we search up to Iteration 6 anyway to get a proper score.
792 if (Iteration >= 6 && rml.move_count() == 1)
795 // Stop search early when the last two iterations returned a mate score
797 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
798 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
801 // Stop search early if one move seems to be much better than the rest
802 int64_t nodes = nodes_searched();
806 && EasyMove == ss[0].pv[0]
807 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
808 && current_search_time() > MaxSearchTime / 16)
809 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
810 && current_search_time() > MaxSearchTime / 32)))
813 // Add some extra time if the best move has changed during the last two iterations
814 if (Iteration > 5 && Iteration <= 50)
815 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
816 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
818 // Stop search if most of MaxSearchTime is consumed at the end of the
819 // iteration. We probably don't have enough time to search the first
820 // move at the next iteration anyway.
821 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
829 StopOnPonderhit = true;
833 if (MaxDepth && Iteration >= MaxDepth)
839 // If we are pondering or in infinite search, we shouldn't print the
840 // best move before we are told to do so.
841 if (!AbortSearch && (PonderSearch || InfiniteSearch))
842 wait_for_stop_or_ponderhit();
844 // Print final search statistics
845 cout << "info nodes " << nodes_searched()
847 << " time " << current_search_time()
848 << " hashfull " << TT.full() << endl;
850 // Print the best move and the ponder move to the standard output
851 if (ss[0].pv[0] == MOVE_NONE)
853 ss[0].pv[0] = rml.get_move(0);
854 ss[0].pv[1] = MOVE_NONE;
856 cout << "bestmove " << ss[0].pv[0];
857 if (ss[0].pv[1] != MOVE_NONE)
858 cout << " ponder " << ss[0].pv[1];
865 dbg_print_mean(LogFile);
867 if (dbg_show_hit_rate)
868 dbg_print_hit_rate(LogFile);
870 LogFile << "\nNodes: " << nodes_searched()
871 << "\nNodes/second: " << nps()
872 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
875 p.do_move(ss[0].pv[0], st);
876 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
878 return rml.get_move_score(0);
882 // root_search() is the function which searches the root node. It is
883 // similar to search_pv except that it uses a different move ordering
884 // scheme and prints some information to the standard output.
886 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta) {
888 Value oldAlpha = alpha;
892 // Loop through all the moves in the root move list
893 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
897 // We failed high, invalidate and skip next moves, leave node-counters
898 // and beta-counters as they are and quickly return, we will try to do
899 // a research at the next iteration with a bigger aspiration window.
900 rml.set_move_score(i, -VALUE_INFINITE);
906 Depth depth, ext, newDepth;
908 RootMoveNumber = i + 1;
911 // Save the current node count before the move is searched
912 nodes = nodes_searched();
914 // Reset beta cut-off counters
917 // Pick the next root move, and print the move and the move number to
918 // the standard output.
919 move = ss[0].currentMove = rml.get_move(i);
921 if (current_search_time() >= 1000)
922 cout << "info currmove " << move
923 << " currmovenumber " << RootMoveNumber << endl;
925 // Decide search depth for this move
926 bool moveIsCheck = pos.move_is_check(move);
927 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
929 depth = (Iteration - 2) * OnePly + InitialDepth;
930 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
931 newDepth = depth + ext;
933 // Make the move, and search it
934 pos.do_move(move, st, ci, moveIsCheck);
938 // Aspiration window is disabled in multi-pv case
940 alpha = -VALUE_INFINITE;
942 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
944 // If the value has dropped a lot compared to the last iteration,
945 // set the boolean variable Problem to true. This variable is used
946 // for time managment: When Problem is true, we try to complete the
947 // current iteration before playing a move.
948 Problem = ( Iteration >= 2
949 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
951 if (Problem && StopOnPonderhit)
952 StopOnPonderhit = false;
956 // Try to reduce non-pv search depth by one ply if move seems not problematic,
957 // if the move fails high will be re-searched at full depth.
958 if ( depth >= 3*OnePly // FIXME was newDepth
960 && !captureOrPromotion
961 && !move_is_castle(move))
963 double red = 0.5 + ln(RootMoveNumber - MultiPV + 1) * ln(depth / 2) / 6.0;
966 ss[0].reduction = Depth(int(floor(red * int(OnePly))));
967 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
970 value = alpha + 1; // Just to trigger next condition
972 value = alpha + 1; // Just to trigger next condition
976 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
980 // Fail high! Set the boolean variable FailHigh to true, and
981 // re-search the move using a PV search. The variable FailHigh
982 // is used for time managment: We try to avoid aborting the
983 // search prematurely during a fail high research.
985 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
992 // Finished searching the move. If AbortSearch is true, the search
993 // was aborted because the user interrupted the search or because we
994 // ran out of time. In this case, the return value of the search cannot
995 // be trusted, and we break out of the loop without updating the best
1000 // Remember beta-cutoff and searched nodes counts for this move. The
1001 // info is used to sort the root moves at the next iteration.
1003 BetaCounter.read(pos.side_to_move(), our, their);
1004 rml.set_beta_counters(i, our, their);
1005 rml.set_move_nodes(i, nodes_searched() - nodes);
1007 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1009 if (value <= alpha && i >= MultiPV)
1010 rml.set_move_score(i, -VALUE_INFINITE);
1013 // PV move or new best move!
1016 rml.set_move_score(i, value);
1018 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1019 rml.set_move_pv(i, ss[0].pv);
1023 // We record how often the best move has been changed in each
1024 // iteration. This information is used for time managment: When
1025 // the best move changes frequently, we allocate some more time.
1027 BestMoveChangesByIteration[Iteration]++;
1029 // Print search information to the standard output
1030 cout << "info depth " << Iteration
1031 << " score " << value_to_string(value)
1032 << ((value >= beta) ? " lowerbound" :
1033 ((value <= alpha)? " upperbound" : ""))
1034 << " time " << current_search_time()
1035 << " nodes " << nodes_searched()
1039 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1040 cout << ss[0].pv[j] << " ";
1046 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1047 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1049 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1050 nodes_searched(), value, type, ss[0].pv) << endl;
1055 // Reset the global variable Problem to false if the value isn't too
1056 // far below the final value from the last iteration.
1057 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1062 rml.sort_multipv(i);
1063 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1065 cout << "info multipv " << j + 1
1066 << " score " << value_to_string(rml.get_move_score(j))
1067 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1068 << " time " << current_search_time()
1069 << " nodes " << nodes_searched()
1073 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1074 cout << rml.get_move_pv(j, k) << " ";
1078 alpha = rml.get_move_score(Min(i, MultiPV-1));
1080 } // PV move or new best move
1082 assert(alpha >= oldAlpha);
1084 FailLow = (alpha == oldAlpha);
1090 // search_pv() is the main search function for PV nodes.
1092 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1093 Depth depth, int ply, int threadID) {
1095 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1096 assert(beta > alpha && beta <= VALUE_INFINITE);
1097 assert(ply >= 0 && ply < PLY_MAX);
1098 assert(threadID >= 0 && threadID < ActiveThreads);
1100 Move movesSearched[256];
1104 Depth ext, newDepth;
1105 Value oldAlpha, value;
1106 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1108 Value bestValue = -VALUE_INFINITE;
1111 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1113 // Initialize, and make an early exit in case of an aborted search,
1114 // an instant draw, maximum ply reached, etc.
1115 init_node(ss, ply, threadID);
1117 // After init_node() that calls poll()
1118 if (AbortSearch || thread_should_stop(threadID))
1121 if (pos.is_draw() || ply >= PLY_MAX - 1)
1124 // Mate distance pruning
1126 alpha = Max(value_mated_in(ply), alpha);
1127 beta = Min(value_mate_in(ply+1), beta);
1131 // Transposition table lookup. At PV nodes, we don't use the TT for
1132 // pruning, but only for move ordering. This is to avoid problems in
1133 // the following areas:
1135 // * Repetition draw detection
1136 // * Fifty move rule detection
1137 // * Searching for a mate
1138 // * Printing of full PV line
1140 tte = TT.retrieve(pos.get_key());
1141 ttMove = (tte ? tte->move() : MOVE_NONE);
1143 // Go with internal iterative deepening if we don't have a TT move
1144 if ( UseIIDAtPVNodes
1145 && depth >= 5*OnePly
1146 && ttMove == MOVE_NONE)
1148 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1149 ttMove = ss[ply].pv[ply];
1150 tte = TT.retrieve(pos.get_key());
1153 // Initialize a MovePicker object for the current position, and prepare
1154 // to search all moves
1155 isCheck = pos.is_check();
1156 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1158 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1160 // Loop through all legal moves until no moves remain or a beta cutoff
1162 while ( alpha < beta
1163 && (move = mp.get_next_move()) != MOVE_NONE
1164 && !thread_should_stop(threadID))
1166 assert(move_is_ok(move));
1168 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1169 moveIsCheck = pos.move_is_check(move, ci);
1170 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1172 // Decide the new search depth
1173 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1175 // Singular extension search. We extend the TT move if its value is much better than
1176 // its siblings. To verify this we do a reduced search on all the other moves but the
1177 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1178 if ( depth >= 6 * OnePly
1180 && move == tte->move()
1182 && is_lower_bound(tte->type())
1183 && tte->depth() >= depth - 3 * OnePly)
1185 Value ttValue = value_from_tt(tte->value(), ply);
1187 if (abs(ttValue) < VALUE_KNOWN_WIN)
1189 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1191 if (excValue < ttValue - SingleReplyMargin)
1196 newDepth = depth - OnePly + ext;
1198 // Update current move
1199 movesSearched[moveCount++] = ss[ply].currentMove = move;
1201 // Make and search the move
1202 pos.do_move(move, st, ci, moveIsCheck);
1204 if (moveCount == 1) // The first move in list is the PV
1205 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1208 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1209 // if the move fails high will be re-searched at full depth.
1210 if ( depth >= 3*OnePly
1212 && !captureOrPromotion
1213 && !move_is_castle(move)
1214 && !move_is_killer(move, ss[ply]))
1216 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 6.0;
1219 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1220 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1223 value = alpha + 1; // Just to trigger next condition
1226 value = alpha + 1; // Just to trigger next condition
1228 if (value > alpha) // Go with full depth non-pv search
1230 ss[ply].reduction = Depth(0);
1231 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1232 if (value > alpha && value < beta)
1234 // When the search fails high at ply 1 while searching the first
1235 // move at the root, set the flag failHighPly1. This is used for
1236 // time managment: We don't want to stop the search early in
1237 // such cases, because resolving the fail high at ply 1 could
1238 // result in a big drop in score at the root.
1239 if (ply == 1 && RootMoveNumber == 1)
1240 Threads[threadID].failHighPly1 = true;
1242 // A fail high occurred. Re-search at full window (pv search)
1243 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1244 Threads[threadID].failHighPly1 = false;
1248 pos.undo_move(move);
1250 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1253 if (value > bestValue)
1260 if (value == value_mate_in(ply + 1))
1261 ss[ply].mateKiller = move;
1263 // If we are at ply 1, and we are searching the first root move at
1264 // ply 0, set the 'Problem' variable if the score has dropped a lot
1265 // (from the computer's point of view) since the previous iteration.
1268 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1273 if ( ActiveThreads > 1
1275 && depth >= MinimumSplitDepth
1277 && idle_thread_exists(threadID)
1279 && !thread_should_stop(threadID)
1280 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1281 depth, &moveCount, &mp, threadID, true))
1285 // All legal moves have been searched. A special case: If there were
1286 // no legal moves, it must be mate or stalemate.
1288 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1290 // If the search is not aborted, update the transposition table,
1291 // history counters, and killer moves.
1292 if (AbortSearch || thread_should_stop(threadID))
1295 if (bestValue <= oldAlpha)
1296 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1298 else if (bestValue >= beta)
1300 BetaCounter.add(pos.side_to_move(), depth, threadID);
1301 move = ss[ply].pv[ply];
1302 if (!pos.move_is_capture_or_promotion(move))
1304 update_history(pos, move, depth, movesSearched, moveCount);
1305 update_killers(move, ss[ply]);
1307 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1310 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1316 // search() is the search function for zero-width nodes.
1318 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1319 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1321 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1322 assert(ply >= 0 && ply < PLY_MAX);
1323 assert(threadID >= 0 && threadID < ActiveThreads);
1325 Move movesSearched[256];
1330 Depth ext, newDepth;
1331 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1332 bool isCheck, useFutilityPruning, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1333 bool mateThreat = false;
1335 futilityValue = staticValue = bestValue = -VALUE_INFINITE;
1338 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1340 // Initialize, and make an early exit in case of an aborted search,
1341 // an instant draw, maximum ply reached, etc.
1342 init_node(ss, ply, threadID);
1344 // After init_node() that calls poll()
1345 if (AbortSearch || thread_should_stop(threadID))
1348 if (pos.is_draw() || ply >= PLY_MAX - 1)
1351 // Mate distance pruning
1352 if (value_mated_in(ply) >= beta)
1355 if (value_mate_in(ply + 1) < beta)
1358 // We don't want the score of a partial search to overwrite a previous full search
1359 // TT value, so we use a different position key in case of an excluded move exsists.
1360 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1362 // Transposition table lookup
1363 tte = TT.retrieve(posKey);
1364 ttMove = (tte ? tte->move() : MOVE_NONE);
1366 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1368 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1369 return value_from_tt(tte->value(), ply);
1372 isCheck = pos.is_check();
1374 // Calculate depth dependant futility pruning parameters
1375 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1376 const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1378 // Evaluate the position statically
1380 ss[ply].eval = VALUE_NONE;
1383 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1384 staticValue = value_from_tt(tte->value(), ply);
1386 staticValue = evaluate(pos, ei, threadID);
1388 ss[ply].eval = staticValue;
1389 futilityValue = staticValue + FutilityValueMargin;
1390 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1397 && !value_is_mate(beta)
1398 && ok_to_do_nullmove(pos)
1399 && staticValue >= beta - NullMoveMargin)
1401 ss[ply].currentMove = MOVE_NULL;
1403 pos.do_null_move(st);
1405 // Null move dynamic reduction based on depth
1406 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1408 // Null move dynamic reduction based on value
1409 if (staticValue - beta > PawnValueMidgame)
1412 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1414 pos.undo_null_move();
1416 if (nullValue >= beta)
1418 if (depth < 6 * OnePly)
1421 // Do zugzwang verification search
1422 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1426 // The null move failed low, which means that we may be faced with
1427 // some kind of threat. If the previous move was reduced, check if
1428 // the move that refuted the null move was somehow connected to the
1429 // move which was reduced. If a connection is found, return a fail
1430 // low score (which will cause the reduced move to fail high in the
1431 // parent node, which will trigger a re-search with full depth).
1432 if (nullValue == value_mated_in(ply + 2))
1435 ss[ply].threatMove = ss[ply + 1].currentMove;
1436 if ( depth < ThreatDepth
1437 && ss[ply - 1].reduction
1438 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1442 // Null move search not allowed, try razoring
1443 else if ( !value_is_mate(beta)
1445 && depth < RazorDepth
1446 && staticValue < beta - (NullMoveMargin + 16 * depth)
1447 && ss[ply - 1].currentMove != MOVE_NULL
1448 && ttMove == MOVE_NONE
1449 && !pos.has_pawn_on_7th(pos.side_to_move()))
1451 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1452 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1457 // Go with internal iterative deepening if we don't have a TT move
1458 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1459 !isCheck && evaluate(pos, ei, threadID) >= beta - IIDMargin)
1461 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1462 ttMove = ss[ply].pv[ply];
1463 tte = TT.retrieve(pos.get_key());
1466 // Initialize a MovePicker object for the current position, and prepare
1467 // to search all moves.
1468 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1470 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1472 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1473 while ( bestValue < beta
1474 && (move = mp.get_next_move()) != MOVE_NONE
1475 && !thread_should_stop(threadID))
1477 assert(move_is_ok(move));
1479 if (move == excludedMove)
1482 moveIsCheck = pos.move_is_check(move, ci);
1483 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1484 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1486 // Decide the new search depth
1487 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1489 // Singular extension search. We extend the TT move if its value is much better than
1490 // its siblings. To verify this we do a reduced search on all the other moves but the
1491 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1492 if ( depth >= 8 * OnePly
1494 && move == tte->move()
1495 && !excludedMove // Do not allow recursive single-reply search
1497 && is_lower_bound(tte->type())
1498 && tte->depth() >= depth - 3 * OnePly)
1500 Value ttValue = value_from_tt(tte->value(), ply);
1502 if (abs(ttValue) < VALUE_KNOWN_WIN)
1504 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1506 if (excValue < ttValue - SingleReplyMargin)
1511 newDepth = depth - OnePly + ext;
1513 // Update current move
1514 movesSearched[moveCount++] = ss[ply].currentMove = move;
1517 if ( useFutilityPruning
1519 && !captureOrPromotion
1522 // Move count based pruning
1523 if ( moveCount >= FutilityMoveCountMargin
1524 && ok_to_prune(pos, move, ss[ply].threatMove)
1525 && bestValue > value_mated_in(PLY_MAX))
1528 // Value based pruning
1529 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1531 if (futilityValueScaled < beta)
1533 if (futilityValueScaled > bestValue)
1534 bestValue = futilityValueScaled;
1539 // Make and search the move
1540 pos.do_move(move, st, ci, moveIsCheck);
1542 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1543 // if the move fails high will be re-searched at full depth.
1544 if ( depth >= 3*OnePly
1546 && !captureOrPromotion
1547 && !move_is_castle(move)
1548 && !move_is_killer(move, ss[ply])
1549 /* && move != ttMove*/)
1551 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1554 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1555 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1558 value = beta; // Just to trigger next condition
1561 value = beta; // Just to trigger next condition
1563 if (value >= beta) // Go with full depth non-pv search
1565 ss[ply].reduction = Depth(0);
1566 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1568 pos.undo_move(move);
1570 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1573 if (value > bestValue)
1579 if (value == value_mate_in(ply + 1))
1580 ss[ply].mateKiller = move;
1584 if ( ActiveThreads > 1
1586 && depth >= MinimumSplitDepth
1588 && idle_thread_exists(threadID)
1590 && !thread_should_stop(threadID)
1591 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue,
1592 depth, &moveCount, &mp, threadID, false))
1596 // All legal moves have been searched. A special case: If there were
1597 // no legal moves, it must be mate or stalemate.
1599 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1601 // If the search is not aborted, update the transposition table,
1602 // history counters, and killer moves.
1603 if (AbortSearch || thread_should_stop(threadID))
1606 if (bestValue < beta)
1607 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1610 BetaCounter.add(pos.side_to_move(), depth, threadID);
1611 move = ss[ply].pv[ply];
1612 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1613 if (!pos.move_is_capture_or_promotion(move))
1615 update_history(pos, move, depth, movesSearched, moveCount);
1616 update_killers(move, ss[ply]);
1621 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1627 // qsearch() is the quiescence search function, which is called by the main
1628 // search function when the remaining depth is zero (or, to be more precise,
1629 // less than OnePly).
1631 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1632 Depth depth, int ply, int threadID) {
1634 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1635 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1637 assert(ply >= 0 && ply < PLY_MAX);
1638 assert(threadID >= 0 && threadID < ActiveThreads);
1643 Value staticValue, bestValue, value, futilityBase, futilityValue;
1644 bool isCheck, enoughMaterial, moveIsCheck;
1645 const TTEntry* tte = NULL;
1647 bool pvNode = (beta - alpha != 1);
1649 // Initialize, and make an early exit in case of an aborted search,
1650 // an instant draw, maximum ply reached, etc.
1651 init_node(ss, ply, threadID);
1653 // After init_node() that calls poll()
1654 if (AbortSearch || thread_should_stop(threadID))
1657 if (pos.is_draw() || ply >= PLY_MAX - 1)
1660 // Transposition table lookup. At PV nodes, we don't use the TT for
1661 // pruning, but only for move ordering.
1662 tte = TT.retrieve(pos.get_key());
1663 ttMove = (tte ? tte->move() : MOVE_NONE);
1665 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1667 assert(tte->type() != VALUE_TYPE_EVAL);
1669 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1670 return value_from_tt(tte->value(), ply);
1673 isCheck = pos.is_check();
1675 // Evaluate the position statically
1677 staticValue = -VALUE_INFINITE;
1678 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1679 staticValue = value_from_tt(tte->value(), ply);
1681 staticValue = evaluate(pos, ei, threadID);
1683 // Initialize "stand pat score", and return it immediately if it is
1685 bestValue = staticValue;
1687 if (bestValue >= beta)
1689 // Store the score to avoid a future costly evaluation() call
1690 if (!isCheck && !tte && ei.futilityMargin == 0)
1691 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1696 if (bestValue > alpha)
1699 // Initialize a MovePicker object for the current position, and prepare
1700 // to search the moves. Because the depth is <= 0 here, only captures,
1701 // queen promotions and checks (only if depth == 0) will be generated.
1702 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1704 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1705 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1707 // Loop through the moves until no moves remain or a beta cutoff
1709 while ( alpha < beta
1710 && (move = mp.get_next_move()) != MOVE_NONE)
1712 assert(move_is_ok(move));
1714 moveIsCheck = pos.move_is_check(move, ci);
1716 // Update current move
1718 ss[ply].currentMove = move;
1726 && !move_is_promotion(move)
1727 && !pos.move_is_passed_pawn_push(move))
1729 futilityValue = futilityBase
1730 + pos.endgame_value_of_piece_on(move_to(move))
1731 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1733 if (futilityValue < alpha)
1735 if (futilityValue > bestValue)
1736 bestValue = futilityValue;
1741 // Don't search captures and checks with negative SEE values
1744 && !move_is_promotion(move)
1745 && pos.see_sign(move) < 0)
1748 // Make and search the move
1749 pos.do_move(move, st, ci, moveIsCheck);
1750 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1751 pos.undo_move(move);
1753 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1756 if (value > bestValue)
1767 // All legal moves have been searched. A special case: If we're in check
1768 // and no legal moves were found, it is checkmate.
1769 if (!moveCount && pos.is_check()) // Mate!
1770 return value_mated_in(ply);
1772 // Update transposition table
1773 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1774 if (bestValue < beta)
1776 // If bestValue isn't changed it means it is still the static evaluation
1777 // of the node, so keep this info to avoid a future evaluation() call.
1778 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1779 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1783 move = ss[ply].pv[ply];
1784 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1786 // Update killers only for good checking moves
1787 if (!pos.move_is_capture_or_promotion(move))
1788 update_killers(move, ss[ply]);
1791 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1797 // sp_search() is used to search from a split point. This function is called
1798 // by each thread working at the split point. It is similar to the normal
1799 // search() function, but simpler. Because we have already probed the hash
1800 // table, done a null move search, and searched the first move before
1801 // splitting, we don't have to repeat all this work in sp_search(). We
1802 // also don't need to store anything to the hash table here: This is taken
1803 // care of after we return from the split point.
1805 void sp_search(SplitPoint* sp, int threadID) {
1807 assert(threadID >= 0 && threadID < ActiveThreads);
1808 assert(ActiveThreads > 1);
1810 Position pos = Position(sp->pos);
1812 SearchStack* ss = sp->sstack[threadID];
1815 bool isCheck = pos.is_check();
1816 bool useFutilityPruning = sp->depth < SelectiveDepth
1819 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1821 while ( sp->bestValue < sp->beta
1822 && !thread_should_stop(threadID)
1823 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1825 assert(move_is_ok(move));
1827 bool moveIsCheck = pos.move_is_check(move, ci);
1828 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1830 lock_grab(&(sp->lock));
1831 int moveCount = ++sp->moves;
1832 lock_release(&(sp->lock));
1834 ss[sp->ply].currentMove = move;
1836 // Decide the new search depth.
1838 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1839 Depth newDepth = sp->depth - OnePly + ext;
1842 if ( useFutilityPruning
1844 && !captureOrPromotion)
1846 // Move count based pruning
1847 if ( moveCount >= FutilityMoveCountMargin
1848 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1849 && sp->bestValue > value_mated_in(PLY_MAX))
1852 // Value based pruning
1853 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1855 if (futilityValueScaled < sp->beta)
1857 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1859 lock_grab(&(sp->lock));
1860 if (futilityValueScaled > sp->bestValue)
1861 sp->bestValue = futilityValueScaled;
1862 lock_release(&(sp->lock));
1868 // Make and search the move.
1870 pos.do_move(move, st, ci, moveIsCheck);
1872 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1873 // if the move fails high will be re-searched at full depth.
1875 && !captureOrPromotion
1876 && !move_is_castle(move)
1877 && !move_is_killer(move, ss[sp->ply]))
1879 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 3.0;
1882 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1883 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1886 value = sp->beta; // Just to trigger next condition
1889 value = sp->beta; // Just to trigger next condition
1891 if (value >= sp->beta) // Go with full depth non-pv search
1893 ss[sp->ply].reduction = Depth(0);
1894 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1896 pos.undo_move(move);
1898 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1900 if (thread_should_stop(threadID))
1904 if (value > sp->bestValue) // Less then 2% of cases
1906 lock_grab(&(sp->lock));
1907 if (value > sp->bestValue && !thread_should_stop(threadID))
1909 sp->bestValue = value;
1910 if (sp->bestValue >= sp->beta)
1912 sp_update_pv(sp->parentSstack, ss, sp->ply);
1913 for (int i = 0; i < ActiveThreads; i++)
1914 if (i != threadID && (i == sp->master || sp->slaves[i]))
1915 Threads[i].stop = true;
1917 sp->finished = true;
1920 lock_release(&(sp->lock));
1924 lock_grab(&(sp->lock));
1926 // If this is the master thread and we have been asked to stop because of
1927 // a beta cutoff higher up in the tree, stop all slave threads.
1928 if (sp->master == threadID && thread_should_stop(threadID))
1929 for (int i = 0; i < ActiveThreads; i++)
1931 Threads[i].stop = true;
1934 sp->slaves[threadID] = 0;
1936 lock_release(&(sp->lock));
1940 // sp_search_pv() is used to search from a PV split point. This function
1941 // is called by each thread working at the split point. It is similar to
1942 // the normal search_pv() function, but simpler. Because we have already
1943 // probed the hash table and searched the first move before splitting, we
1944 // don't have to repeat all this work in sp_search_pv(). We also don't
1945 // need to store anything to the hash table here: This is taken care of
1946 // after we return from the split point.
1948 void sp_search_pv(SplitPoint* sp, int threadID) {
1950 assert(threadID >= 0 && threadID < ActiveThreads);
1951 assert(ActiveThreads > 1);
1953 Position pos = Position(sp->pos);
1955 SearchStack* ss = sp->sstack[threadID];
1959 while ( sp->alpha < sp->beta
1960 && !thread_should_stop(threadID)
1961 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1963 bool moveIsCheck = pos.move_is_check(move, ci);
1964 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1966 assert(move_is_ok(move));
1968 lock_grab(&(sp->lock));
1969 int moveCount = ++sp->moves;
1970 lock_release(&(sp->lock));
1972 ss[sp->ply].currentMove = move;
1974 // Decide the new search depth.
1976 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1977 Depth newDepth = sp->depth - OnePly + ext;
1979 // Make and search the move.
1981 pos.do_move(move, st, ci, moveIsCheck);
1983 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1984 // if the move fails high will be re-searched at full depth.
1986 && !captureOrPromotion
1987 && !move_is_castle(move)
1988 && !move_is_killer(move, ss[sp->ply]))
1990 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 6.0;
1993 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1994 value = -search(pos, ss, -sp->alpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1997 value = sp->alpha + 1; // Just to trigger next condition
2000 value = sp->alpha + 1; // Just to trigger next condition
2002 if (value > sp->alpha) // Go with full depth non-pv search
2004 ss[sp->ply].reduction = Depth(0);
2005 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
2007 if (value > sp->alpha && value < sp->beta)
2009 // When the search fails high at ply 1 while searching the first
2010 // move at the root, set the flag failHighPly1. This is used for
2011 // time managment: We don't want to stop the search early in
2012 // such cases, because resolving the fail high at ply 1 could
2013 // result in a big drop in score at the root.
2014 if (sp->ply == 1 && RootMoveNumber == 1)
2015 Threads[threadID].failHighPly1 = true;
2017 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2018 Threads[threadID].failHighPly1 = false;
2021 pos.undo_move(move);
2023 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2025 if (thread_should_stop(threadID))
2029 lock_grab(&(sp->lock));
2030 if (value > sp->bestValue && !thread_should_stop(threadID))
2032 sp->bestValue = value;
2033 if (value > sp->alpha)
2036 sp_update_pv(sp->parentSstack, ss, sp->ply);
2037 if (value == value_mate_in(sp->ply + 1))
2038 ss[sp->ply].mateKiller = move;
2040 if (value >= sp->beta)
2042 for (int i = 0; i < ActiveThreads; i++)
2043 if (i != threadID && (i == sp->master || sp->slaves[i]))
2044 Threads[i].stop = true;
2046 sp->finished = true;
2049 // If we are at ply 1, and we are searching the first root move at
2050 // ply 0, set the 'Problem' variable if the score has dropped a lot
2051 // (from the computer's point of view) since the previous iteration.
2054 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2057 lock_release(&(sp->lock));
2060 lock_grab(&(sp->lock));
2062 // If this is the master thread and we have been asked to stop because of
2063 // a beta cutoff higher up in the tree, stop all slave threads.
2064 if (sp->master == threadID && thread_should_stop(threadID))
2065 for (int i = 0; i < ActiveThreads; i++)
2067 Threads[i].stop = true;
2070 sp->slaves[threadID] = 0;
2072 lock_release(&(sp->lock));
2075 /// The BetaCounterType class
2077 BetaCounterType::BetaCounterType() { clear(); }
2079 void BetaCounterType::clear() {
2081 for (int i = 0; i < THREAD_MAX; i++)
2082 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2085 void BetaCounterType::add(Color us, Depth d, int threadID) {
2087 // Weighted count based on depth
2088 Threads[threadID].betaCutOffs[us] += unsigned(d);
2091 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2094 for (int i = 0; i < THREAD_MAX; i++)
2096 our += Threads[i].betaCutOffs[us];
2097 their += Threads[i].betaCutOffs[opposite_color(us)];
2102 /// The RootMoveList class
2104 // RootMoveList c'tor
2106 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2108 MoveStack mlist[MaxRootMoves];
2109 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2111 // Generate all legal moves
2112 MoveStack* last = generate_moves(pos, mlist);
2114 // Add each move to the moves[] array
2115 for (MoveStack* cur = mlist; cur != last; cur++)
2117 bool includeMove = includeAllMoves;
2119 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2120 includeMove = (searchMoves[k] == cur->move);
2125 // Find a quick score for the move
2127 SearchStack ss[PLY_MAX_PLUS_2];
2130 moves[count].move = cur->move;
2131 pos.do_move(moves[count].move, st);
2132 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2133 pos.undo_move(moves[count].move);
2134 moves[count].pv[0] = moves[count].move;
2135 moves[count].pv[1] = MOVE_NONE;
2142 // RootMoveList simple methods definitions
2144 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2146 moves[moveNum].nodes = nodes;
2147 moves[moveNum].cumulativeNodes += nodes;
2150 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2152 moves[moveNum].ourBeta = our;
2153 moves[moveNum].theirBeta = their;
2156 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2160 for (j = 0; pv[j] != MOVE_NONE; j++)
2161 moves[moveNum].pv[j] = pv[j];
2163 moves[moveNum].pv[j] = MOVE_NONE;
2167 // RootMoveList::sort() sorts the root move list at the beginning of a new
2170 void RootMoveList::sort() {
2172 sort_multipv(count - 1); // Sort all items
2176 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2177 // list by their scores and depths. It is used to order the different PVs
2178 // correctly in MultiPV mode.
2180 void RootMoveList::sort_multipv(int n) {
2184 for (i = 1; i <= n; i++)
2186 RootMove rm = moves[i];
2187 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2188 moves[j] = moves[j - 1];
2195 // init_node() is called at the beginning of all the search functions
2196 // (search(), search_pv(), qsearch(), and so on) and initializes the
2197 // search stack object corresponding to the current node. Once every
2198 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2199 // for user input and checks whether it is time to stop the search.
2201 void init_node(SearchStack ss[], int ply, int threadID) {
2203 assert(ply >= 0 && ply < PLY_MAX);
2204 assert(threadID >= 0 && threadID < ActiveThreads);
2206 Threads[threadID].nodes++;
2211 if (NodesSincePoll >= NodesBetweenPolls)
2218 ss[ply + 2].initKillers();
2220 if (Threads[threadID].printCurrentLine)
2221 print_current_line(ss, ply, threadID);
2225 // update_pv() is called whenever a search returns a value > alpha.
2226 // It updates the PV in the SearchStack object corresponding to the
2229 void update_pv(SearchStack ss[], int ply) {
2231 assert(ply >= 0 && ply < PLY_MAX);
2235 ss[ply].pv[ply] = ss[ply].currentMove;
2237 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2238 ss[ply].pv[p] = ss[ply + 1].pv[p];
2240 ss[ply].pv[p] = MOVE_NONE;
2244 // sp_update_pv() is a variant of update_pv for use at split points. The
2245 // difference between the two functions is that sp_update_pv also updates
2246 // the PV at the parent node.
2248 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2250 assert(ply >= 0 && ply < PLY_MAX);
2254 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2256 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2257 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2259 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2263 // connected_moves() tests whether two moves are 'connected' in the sense
2264 // that the first move somehow made the second move possible (for instance
2265 // if the moving piece is the same in both moves). The first move is assumed
2266 // to be the move that was made to reach the current position, while the
2267 // second move is assumed to be a move from the current position.
2269 bool connected_moves(const Position& pos, Move m1, Move m2) {
2271 Square f1, t1, f2, t2;
2274 assert(move_is_ok(m1));
2275 assert(move_is_ok(m2));
2277 if (m2 == MOVE_NONE)
2280 // Case 1: The moving piece is the same in both moves
2286 // Case 2: The destination square for m2 was vacated by m1
2292 // Case 3: Moving through the vacated square
2293 if ( piece_is_slider(pos.piece_on(f2))
2294 && bit_is_set(squares_between(f2, t2), f1))
2297 // Case 4: The destination square for m2 is defended by the moving piece in m1
2298 p = pos.piece_on(t1);
2299 if (bit_is_set(pos.attacks_from(p, t1), t2))
2302 // Case 5: Discovered check, checking piece is the piece moved in m1
2303 if ( piece_is_slider(p)
2304 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2305 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2307 // discovered_check_candidates() works also if the Position's side to
2308 // move is the opposite of the checking piece.
2309 Color them = opposite_color(pos.side_to_move());
2310 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2312 if (bit_is_set(dcCandidates, f2))
2319 // value_is_mate() checks if the given value is a mate one
2320 // eventually compensated for the ply.
2322 bool value_is_mate(Value value) {
2324 assert(abs(value) <= VALUE_INFINITE);
2326 return value <= value_mated_in(PLY_MAX)
2327 || value >= value_mate_in(PLY_MAX);
2331 // move_is_killer() checks if the given move is among the
2332 // killer moves of that ply.
2334 bool move_is_killer(Move m, const SearchStack& ss) {
2336 const Move* k = ss.killers;
2337 for (int i = 0; i < KILLER_MAX; i++, k++)
2345 // extension() decides whether a move should be searched with normal depth,
2346 // or with extended depth. Certain classes of moves (checking moves, in
2347 // particular) are searched with bigger depth than ordinary moves and in
2348 // any case are marked as 'dangerous'. Note that also if a move is not
2349 // extended, as example because the corresponding UCI option is set to zero,
2350 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2352 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2353 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2355 assert(m != MOVE_NONE);
2357 Depth result = Depth(0);
2358 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2363 result += CheckExtension[pvNode];
2366 result += SingleEvasionExtension[pvNode];
2369 result += MateThreatExtension[pvNode];
2372 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2374 Color c = pos.side_to_move();
2375 if (relative_rank(c, move_to(m)) == RANK_7)
2377 result += PawnPushTo7thExtension[pvNode];
2380 if (pos.pawn_is_passed(c, move_to(m)))
2382 result += PassedPawnExtension[pvNode];
2387 if ( captureOrPromotion
2388 && pos.type_of_piece_on(move_to(m)) != PAWN
2389 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2390 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2391 && !move_is_promotion(m)
2394 result += PawnEndgameExtension[pvNode];
2399 && captureOrPromotion
2400 && pos.type_of_piece_on(move_to(m)) != PAWN
2401 && pos.see_sign(m) >= 0)
2407 return Min(result, OnePly);
2411 // ok_to_do_nullmove() looks at the current position and decides whether
2412 // doing a 'null move' should be allowed. In order to avoid zugzwang
2413 // problems, null moves are not allowed when the side to move has very
2414 // little material left. Currently, the test is a bit too simple: Null
2415 // moves are avoided only when the side to move has only pawns left.
2416 // It's probably a good idea to avoid null moves in at least some more
2417 // complicated endgames, e.g. KQ vs KR. FIXME
2419 bool ok_to_do_nullmove(const Position& pos) {
2421 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2425 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2426 // non-tactical moves late in the move list close to the leaves are
2427 // candidates for pruning.
2429 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2431 assert(move_is_ok(m));
2432 assert(threat == MOVE_NONE || move_is_ok(threat));
2433 assert(!pos.move_is_check(m));
2434 assert(!pos.move_is_capture_or_promotion(m));
2435 assert(!pos.move_is_passed_pawn_push(m));
2437 Square mfrom, mto, tfrom, tto;
2439 // Prune if there isn't any threat move and
2440 // is not a castling move (common case).
2441 if (threat == MOVE_NONE && !move_is_castle(m))
2444 mfrom = move_from(m);
2446 tfrom = move_from(threat);
2447 tto = move_to(threat);
2449 // Case 1: Castling moves are never pruned
2450 if (move_is_castle(m))
2453 // Case 2: Don't prune moves which move the threatened piece
2457 // Case 3: If the threatened piece has value less than or equal to the
2458 // value of the threatening piece, don't prune move which defend it.
2459 if ( pos.move_is_capture(threat)
2460 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2461 || pos.type_of_piece_on(tfrom) == KING)
2462 && pos.move_attacks_square(m, tto))
2465 // Case 4: If the moving piece in the threatened move is a slider, don't
2466 // prune safe moves which block its ray.
2467 if ( piece_is_slider(pos.piece_on(tfrom))
2468 && bit_is_set(squares_between(tfrom, tto), mto)
2469 && pos.see_sign(m) >= 0)
2476 // ok_to_use_TT() returns true if a transposition table score
2477 // can be used at a given point in search.
2479 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2481 Value v = value_from_tt(tte->value(), ply);
2483 return ( tte->depth() >= depth
2484 || v >= Max(value_mate_in(PLY_MAX), beta)
2485 || v < Min(value_mated_in(PLY_MAX), beta))
2487 && ( (is_lower_bound(tte->type()) && v >= beta)
2488 || (is_upper_bound(tte->type()) && v < beta));
2492 // refine_eval() returns the transposition table score if
2493 // possible otherwise falls back on static position evaluation.
2495 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2500 Value v = value_from_tt(tte->value(), ply);
2502 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2503 || (is_upper_bound(tte->type()) && v < defaultEval))
2509 // update_history() registers a good move that produced a beta-cutoff
2510 // in history and marks as failures all the other moves of that ply.
2512 void update_history(const Position& pos, Move move, Depth depth,
2513 Move movesSearched[], int moveCount) {
2517 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2519 for (int i = 0; i < moveCount - 1; i++)
2521 m = movesSearched[i];
2525 if (!pos.move_is_capture_or_promotion(m))
2526 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2531 // update_killers() add a good move that produced a beta-cutoff
2532 // among the killer moves of that ply.
2534 void update_killers(Move m, SearchStack& ss) {
2536 if (m == ss.killers[0])
2539 for (int i = KILLER_MAX - 1; i > 0; i--)
2540 ss.killers[i] = ss.killers[i - 1];
2546 // fail_high_ply_1() checks if some thread is currently resolving a fail
2547 // high at ply 1 at the node below the first root node. This information
2548 // is used for time management.
2550 bool fail_high_ply_1() {
2552 for (int i = 0; i < ActiveThreads; i++)
2553 if (Threads[i].failHighPly1)
2560 // current_search_time() returns the number of milliseconds which have passed
2561 // since the beginning of the current search.
2563 int current_search_time() {
2565 return get_system_time() - SearchStartTime;
2569 // nps() computes the current nodes/second count.
2573 int t = current_search_time();
2574 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2578 // poll() performs two different functions: It polls for user input, and it
2579 // looks at the time consumed so far and decides if it's time to abort the
2584 static int lastInfoTime;
2585 int t = current_search_time();
2590 // We are line oriented, don't read single chars
2591 std::string command;
2593 if (!std::getline(std::cin, command))
2596 if (command == "quit")
2599 PonderSearch = false;
2603 else if (command == "stop")
2606 PonderSearch = false;
2608 else if (command == "ponderhit")
2612 // Print search information
2616 else if (lastInfoTime > t)
2617 // HACK: Must be a new search where we searched less than
2618 // NodesBetweenPolls nodes during the first second of search.
2621 else if (t - lastInfoTime >= 1000)
2629 if (dbg_show_hit_rate)
2630 dbg_print_hit_rate();
2632 cout << "info nodes " << nodes_searched() << " nps " << nps()
2633 << " time " << t << " hashfull " << TT.full() << endl;
2635 lock_release(&IOLock);
2637 if (ShowCurrentLine)
2638 Threads[0].printCurrentLine = true;
2641 // Should we stop the search?
2645 bool stillAtFirstMove = RootMoveNumber == 1
2647 && t > MaxSearchTime + ExtraSearchTime;
2649 bool noProblemFound = !FailHigh
2651 && !fail_high_ply_1()
2653 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2655 bool noMoreTime = t > AbsoluteMaxSearchTime
2656 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2659 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2660 || (ExactMaxTime && t >= ExactMaxTime)
2661 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2666 // ponderhit() is called when the program is pondering (i.e. thinking while
2667 // it's the opponent's turn to move) in order to let the engine know that
2668 // it correctly predicted the opponent's move.
2672 int t = current_search_time();
2673 PonderSearch = false;
2675 bool stillAtFirstMove = RootMoveNumber == 1
2677 && t > MaxSearchTime + ExtraSearchTime;
2679 bool noProblemFound = !FailHigh
2681 && !fail_high_ply_1()
2683 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2685 bool noMoreTime = t > AbsoluteMaxSearchTime
2689 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2694 // print_current_line() prints the current line of search for a given
2695 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2697 void print_current_line(SearchStack ss[], int ply, int threadID) {
2699 assert(ply >= 0 && ply < PLY_MAX);
2700 assert(threadID >= 0 && threadID < ActiveThreads);
2702 if (!Threads[threadID].idle)
2705 cout << "info currline " << (threadID + 1);
2706 for (int p = 0; p < ply; p++)
2707 cout << " " << ss[p].currentMove;
2710 lock_release(&IOLock);
2712 Threads[threadID].printCurrentLine = false;
2713 if (threadID + 1 < ActiveThreads)
2714 Threads[threadID + 1].printCurrentLine = true;
2718 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2720 void init_ss_array(SearchStack ss[]) {
2722 for (int i = 0; i < 3; i++)
2725 ss[i].initKillers();
2730 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2731 // while the program is pondering. The point is to work around a wrinkle in
2732 // the UCI protocol: When pondering, the engine is not allowed to give a
2733 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2734 // We simply wait here until one of these commands is sent, and return,
2735 // after which the bestmove and pondermove will be printed (in id_loop()).
2737 void wait_for_stop_or_ponderhit() {
2739 std::string command;
2743 if (!std::getline(std::cin, command))
2746 if (command == "quit")
2751 else if (command == "ponderhit" || command == "stop")
2757 // idle_loop() is where the threads are parked when they have no work to do.
2758 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2759 // object for which the current thread is the master.
2761 void idle_loop(int threadID, SplitPoint* waitSp) {
2763 assert(threadID >= 0 && threadID < THREAD_MAX);
2765 Threads[threadID].running = true;
2769 if (AllThreadsShouldExit && threadID != 0)
2772 // If we are not thinking, wait for a condition to be signaled
2773 // instead of wasting CPU time polling for work.
2774 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2777 #if !defined(_MSC_VER)
2778 pthread_mutex_lock(&WaitLock);
2779 if (Idle || threadID >= ActiveThreads)
2780 pthread_cond_wait(&WaitCond, &WaitLock);
2782 pthread_mutex_unlock(&WaitLock);
2784 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2788 // If this thread has been assigned work, launch a search
2789 if (Threads[threadID].workIsWaiting)
2791 Threads[threadID].workIsWaiting = false;
2792 if (Threads[threadID].splitPoint->pvNode)
2793 sp_search_pv(Threads[threadID].splitPoint, threadID);
2795 sp_search(Threads[threadID].splitPoint, threadID);
2797 Threads[threadID].idle = true;
2800 // If this thread is the master of a split point and all threads have
2801 // finished their work at this split point, return from the idle loop.
2802 if (waitSp != NULL && waitSp->cpus == 0)
2806 Threads[threadID].running = false;
2810 // init_split_point_stack() is called during program initialization, and
2811 // initializes all split point objects.
2813 void init_split_point_stack() {
2815 for (int i = 0; i < THREAD_MAX; i++)
2816 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2818 SplitPointStack[i][j].parent = NULL;
2819 lock_init(&(SplitPointStack[i][j].lock), NULL);
2824 // destroy_split_point_stack() is called when the program exits, and
2825 // destroys all locks in the precomputed split point objects.
2827 void destroy_split_point_stack() {
2829 for (int i = 0; i < THREAD_MAX; i++)
2830 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2831 lock_destroy(&(SplitPointStack[i][j].lock));
2835 // thread_should_stop() checks whether the thread with a given threadID has
2836 // been asked to stop, directly or indirectly. This can happen if a beta
2837 // cutoff has occurred in the thread's currently active split point, or in
2838 // some ancestor of the current split point.
2840 bool thread_should_stop(int threadID) {
2842 assert(threadID >= 0 && threadID < ActiveThreads);
2846 if (Threads[threadID].stop)
2848 if (ActiveThreads <= 2)
2850 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2853 Threads[threadID].stop = true;
2860 // thread_is_available() checks whether the thread with threadID "slave" is
2861 // available to help the thread with threadID "master" at a split point. An
2862 // obvious requirement is that "slave" must be idle. With more than two
2863 // threads, this is not by itself sufficient: If "slave" is the master of
2864 // some active split point, it is only available as a slave to the other
2865 // threads which are busy searching the split point at the top of "slave"'s
2866 // split point stack (the "helpful master concept" in YBWC terminology).
2868 bool thread_is_available(int slave, int master) {
2870 assert(slave >= 0 && slave < ActiveThreads);
2871 assert(master >= 0 && master < ActiveThreads);
2872 assert(ActiveThreads > 1);
2874 if (!Threads[slave].idle || slave == master)
2877 if (Threads[slave].activeSplitPoints == 0)
2878 // No active split points means that the thread is available as
2879 // a slave for any other thread.
2882 if (ActiveThreads == 2)
2885 // Apply the "helpful master" concept if possible
2886 if (SplitPointStack[slave][Threads[slave].activeSplitPoints - 1].slaves[master])
2893 // idle_thread_exists() tries to find an idle thread which is available as
2894 // a slave for the thread with threadID "master".
2896 bool idle_thread_exists(int master) {
2898 assert(master >= 0 && master < ActiveThreads);
2899 assert(ActiveThreads > 1);
2901 for (int i = 0; i < ActiveThreads; i++)
2902 if (thread_is_available(i, master))
2909 // split() does the actual work of distributing the work at a node between
2910 // several threads at PV nodes. If it does not succeed in splitting the
2911 // node (because no idle threads are available, or because we have no unused
2912 // split point objects), the function immediately returns false. If
2913 // splitting is possible, a SplitPoint object is initialized with all the
2914 // data that must be copied to the helper threads (the current position and
2915 // search stack, alpha, beta, the search depth, etc.), and we tell our
2916 // helper threads that they have been assigned work. This will cause them
2917 // to instantly leave their idle loops and call sp_search_pv(). When all
2918 // threads have returned from sp_search_pv (or, equivalently, when
2919 // splitPoint->cpus becomes 0), split() returns true.
2921 bool split(const Position& p, SearchStack* sstck, int ply,
2922 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2923 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2926 assert(sstck != NULL);
2927 assert(ply >= 0 && ply < PLY_MAX);
2928 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2929 assert(!pvNode || *alpha < *beta);
2930 assert(*beta <= VALUE_INFINITE);
2931 assert(depth > Depth(0));
2932 assert(master >= 0 && master < ActiveThreads);
2933 assert(ActiveThreads > 1);
2935 SplitPoint* splitPoint;
2940 // If no other thread is available to help us, or if we have too many
2941 // active split points, don't split.
2942 if ( !idle_thread_exists(master)
2943 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2945 lock_release(&MPLock);
2949 // Pick the next available split point object from the split point stack
2950 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2951 Threads[master].activeSplitPoints++;
2953 // Initialize the split point object and copy current position
2954 splitPoint->parent = Threads[master].splitPoint;
2955 splitPoint->finished = false;
2956 splitPoint->ply = ply;
2957 splitPoint->depth = depth;
2958 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2959 splitPoint->beta = *beta;
2960 splitPoint->pvNode = pvNode;
2961 splitPoint->bestValue = *bestValue;
2962 splitPoint->futilityValue = futilityValue;
2963 splitPoint->master = master;
2964 splitPoint->mp = mp;
2965 splitPoint->moves = *moves;
2966 splitPoint->cpus = 1;
2967 splitPoint->pos.copy(p);
2968 splitPoint->parentSstack = sstck;
2969 for (i = 0; i < ActiveThreads; i++)
2970 splitPoint->slaves[i] = 0;
2972 // Copy the current search stack to the master thread
2973 memcpy(splitPoint->sstack[master], sstck, (ply+1) * sizeof(SearchStack));
2974 Threads[master].splitPoint = splitPoint;
2976 // Make copies of the current position and search stack for each thread
2977 for (i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2978 if (thread_is_available(i, master))
2980 memcpy(splitPoint->sstack[i], sstck, (ply+1) * sizeof(SearchStack));
2981 Threads[i].splitPoint = splitPoint;
2982 splitPoint->slaves[i] = 1;
2986 // Tell the threads that they have work to do. This will make them leave
2988 for (i = 0; i < ActiveThreads; i++)
2989 if (i == master || splitPoint->slaves[i])
2991 Threads[i].workIsWaiting = true;
2992 Threads[i].idle = false;
2993 Threads[i].stop = false;
2996 lock_release(&MPLock);
2998 // Everything is set up. The master thread enters the idle loop, from
2999 // which it will instantly launch a search, because its workIsWaiting
3000 // slot is 'true'. We send the split point as a second parameter to the
3001 // idle loop, which means that the main thread will return from the idle
3002 // loop when all threads have finished their work at this split point
3003 // (i.e. when splitPoint->cpus == 0).
3004 idle_loop(master, splitPoint);
3006 // We have returned from the idle loop, which means that all threads are
3007 // finished. Update alpha, beta and bestValue, and return.
3011 *alpha = splitPoint->alpha;
3013 *beta = splitPoint->beta;
3014 *bestValue = splitPoint->bestValue;
3015 Threads[master].stop = false;
3016 Threads[master].idle = false;
3017 Threads[master].activeSplitPoints--;
3018 Threads[master].splitPoint = splitPoint->parent;
3020 lock_release(&MPLock);
3025 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3026 // to start a new search from the root.
3028 void wake_sleeping_threads() {
3030 if (ActiveThreads > 1)
3032 for (int i = 1; i < ActiveThreads; i++)
3034 Threads[i].idle = true;
3035 Threads[i].workIsWaiting = false;
3038 #if !defined(_MSC_VER)
3039 pthread_mutex_lock(&WaitLock);
3040 pthread_cond_broadcast(&WaitCond);
3041 pthread_mutex_unlock(&WaitLock);
3043 for (int i = 1; i < THREAD_MAX; i++)
3044 SetEvent(SitIdleEvent[i]);
3050 // init_thread() is the function which is called when a new thread is
3051 // launched. It simply calls the idle_loop() function with the supplied
3052 // threadID. There are two versions of this function; one for POSIX
3053 // threads and one for Windows threads.
3055 #if !defined(_MSC_VER)
3057 void* init_thread(void *threadID) {
3059 idle_loop(*(int*)threadID, NULL);
3065 DWORD WINAPI init_thread(LPVOID threadID) {
3067 idle_loop(*(int*)threadID, NULL);