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 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/>.
39 #include "ucioption.h"
43 //// Local definitions
50 //The IterationInfoType is used to store search history
51 //iteration by iteration.
53 //Because we use relatively small (dynamic) aspiration window,
54 //there happens many fail highs and fail lows in root. And
55 //because we don't do researches in those cases, "value" stored
56 //here is not necessarily exact. Instead in case of fail high/low
57 //we guess what the right value might be and store our guess
58 //as "speculated value" and then move on...
60 class IterationInfoType {
63 Value _speculatedValue;
75 inline void set(Value v) {
76 set(v, v, false, false);
79 inline void set(Value v, Value specV, bool fHigh, bool fLow) {
81 _speculatedValue = specV;
86 inline Value value() {
90 inline Value speculated_value() {
91 return _speculatedValue;
94 inline bool fail_high() {
98 inline bool fail_low() {
104 // The BetaCounterType class is used to order moves at ply one.
105 // Apart for the first one that has its score, following moves
106 // normally have score -VALUE_INFINITE, so are ordered according
107 // to the number of beta cutoffs occurred under their subtree during
108 // the last iteration.
110 struct BetaCounterType {
114 void add(Color us, Depth d, int threadID);
115 void read(Color us, int64_t& our, int64_t& their);
117 int64_t hits[THREAD_MAX][2];
121 // The RootMove class is used for moves at the root at the tree. For each
122 // root move, we store a score, a node count, and a PV (really a refutation
123 // in the case of moves which fail low).
128 bool operator<(const RootMove&); // used to sort
132 int64_t nodes, cumulativeNodes;
133 Move pv[PLY_MAX_PLUS_2];
134 int64_t ourBeta, theirBeta;
138 // The RootMoveList class is essentially an array of RootMove objects, with
139 // a handful of methods for accessing the data in the individual moves.
144 RootMoveList(Position &pos, Move searchMoves[]);
145 inline Move get_move(int moveNum) const;
146 inline Value get_move_score(int moveNum) const;
147 inline void set_move_score(int moveNum, Value score);
148 inline void set_move_nodes(int moveNum, int64_t nodes);
149 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
150 void set_move_pv(int moveNum, const Move pv[]);
151 inline Move get_move_pv(int moveNum, int i) const;
152 inline int64_t get_move_cumulative_nodes(int moveNum) const;
153 inline int move_count() const;
154 Move scan_for_easy_move() const;
156 void sort_multipv(int n);
159 static const int MaxRootMoves = 500;
160 RootMove moves[MaxRootMoves];
165 /// Constants and variables
167 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
170 int LMRNonPVMoves = 4;
172 // Depth limit for use of dynamic threat detection:
173 Depth ThreatDepth = 5*OnePly;
175 // Depth limit for selective search:
176 Depth SelectiveDepth = 7*OnePly;
178 // Use internal iterative deepening?
179 const bool UseIIDAtPVNodes = true;
180 const bool UseIIDAtNonPVNodes = false;
182 // Internal iterative deepening margin. At Non-PV moves, when
183 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
184 // when the static evaluation is at most IIDMargin below beta.
185 const Value IIDMargin = Value(0x100);
187 // Easy move margin. An easy move candidate must be at least this much
188 // better than the second best move.
189 const Value EasyMoveMargin = Value(0x200);
191 // Problem margin. If the score of the first move at iteration N+1 has
192 // dropped by more than this since iteration N, the boolean variable
193 // "Problem" is set to true, which will make the program spend some extra
194 // time looking for a better move.
195 const Value ProblemMargin = Value(0x28);
197 // No problem margin. If the boolean "Problem" is true, and a new move
198 // is found at the root which is less than NoProblemMargin worse than the
199 // best move from the previous iteration, Problem is set back to false.
200 const Value NoProblemMargin = Value(0x14);
202 // Null move margin. A null move search will not be done if the approximate
203 // evaluation of the position is more than NullMoveMargin below beta.
204 const Value NullMoveMargin = Value(0x300);
206 // Pruning criterions. See the code and comments in ok_to_prune() to
207 // understand their precise meaning.
208 const bool PruneEscapeMoves = false;
209 const bool PruneDefendingMoves = false;
210 const bool PruneBlockingMoves = false;
212 // Use futility pruning?
213 bool UseQSearchFutilityPruning = true;
214 bool UseFutilityPruning = true;
216 // Margins for futility pruning in the quiescence search, and at frontier
217 // and near frontier nodes
218 Value FutilityMarginQS = Value(0x80);
219 Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
220 Value(0x2A0), Value(0x340), Value(0x3A0) };
223 const bool RazorAtDepthOne = false;
224 Depth RazorDepth = 4*OnePly;
225 Value RazorMargin = Value(0x300);
227 // Last seconds noise filtering (LSN)
228 bool UseLSNFiltering = false;
229 bool looseOnTime = false;
230 int LSNTime = 4 * 1000; // In milliseconds
231 Value LSNValue = Value(0x200);
233 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
234 Depth CheckExtension[2] = {OnePly, OnePly};
235 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
236 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
237 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
238 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
239 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
241 // Search depth at iteration 1
242 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
246 int NodesBetweenPolls = 30000;
248 // Iteration counters
250 BetaCounterType BetaCounter;
252 // Scores and number of times the best move changed for each iteration:
253 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
254 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
259 // Time managment variables
261 int MaxNodes, MaxDepth;
262 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
267 bool StopOnPonderhit;
273 bool PonderingEnabled;
276 // Show current line?
277 bool ShowCurrentLine = false;
280 bool UseLogFile = false;
281 std::ofstream LogFile;
283 // MP related variables
284 Depth MinimumSplitDepth = 4*OnePly;
285 int MaxThreadsPerSplitPoint = 4;
286 Thread Threads[THREAD_MAX];
288 bool AllThreadsShouldExit = false;
289 const int MaxActiveSplitPoints = 8;
290 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
293 #if !defined(_MSC_VER)
294 pthread_cond_t WaitCond;
295 pthread_mutex_t WaitLock;
297 HANDLE SitIdleEvent[THREAD_MAX];
303 Value id_loop(const Position &pos, Move searchMoves[]);
304 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml,
305 Value alpha, Value beta);
306 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
307 Depth depth, int ply, int threadID);
308 Value search(Position &pos, SearchStack ss[], Value beta,
309 Depth depth, int ply, bool allowNullmove, int threadID);
310 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
311 Depth depth, int ply, int threadID);
312 void sp_search(SplitPoint *sp, int threadID);
313 void sp_search_pv(SplitPoint *sp, int threadID);
314 void init_node(SearchStack ss[], int ply, int threadID);
315 void update_pv(SearchStack ss[], int ply);
316 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
317 bool connected_moves(const Position &pos, Move m1, Move m2);
318 bool value_is_mate(Value value);
319 bool move_is_killer(Move m, const SearchStack& ss);
320 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
321 bool ok_to_do_nullmove(const Position &pos);
322 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
323 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
324 bool ok_to_history(const Position &pos, Move m);
325 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
326 void update_killers(Move m, SearchStack& ss);
328 bool fail_high_ply_1();
329 bool aspiration_fail_high_ply_1();
330 int current_search_time();
334 void print_current_line(SearchStack ss[], int ply, int threadID);
335 void wait_for_stop_or_ponderhit();
337 void idle_loop(int threadID, SplitPoint *waitSp);
338 void init_split_point_stack();
339 void destroy_split_point_stack();
340 bool thread_should_stop(int threadID);
341 bool thread_is_available(int slave, int master);
342 bool idle_thread_exists(int master);
343 bool split(const Position &pos, SearchStack *ss, int ply,
344 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
345 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
346 void wake_sleeping_threads();
348 #if !defined(_MSC_VER)
349 void *init_thread(void *threadID);
351 DWORD WINAPI init_thread(LPVOID threadID);
358 //// Global variables
361 // The main transposition table
362 TranspositionTable TT = TranspositionTable(TTDefaultSize);
365 // Number of active threads:
366 int ActiveThreads = 1;
368 // Locks. In principle, there is no need for IOLock to be a global variable,
369 // but it could turn out to be useful for debugging.
372 History H; // Should be made local?
374 // The empty search stack
375 SearchStack EmptySearchStack;
378 // SearchStack::init() initializes a search stack. Used at the beginning of a
379 // new search from the root.
380 void SearchStack::init(int ply) {
382 pv[ply] = pv[ply + 1] = MOVE_NONE;
383 currentMove = threatMove = MOVE_NONE;
384 reduction = Depth(0);
387 void SearchStack::initKillers() {
389 mateKiller = MOVE_NONE;
390 for (int i = 0; i < KILLER_MAX; i++)
391 killers[i] = MOVE_NONE;
399 /// think() is the external interface to Stockfish's search, and is called when
400 /// the program receives the UCI 'go' command. It initializes various
401 /// search-related global variables, and calls root_search()
403 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
404 int time[], int increment[], int movesToGo, int maxDepth,
405 int maxNodes, int maxTime, Move searchMoves[]) {
407 // Look for a book move
408 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
411 if (get_option_value_string("Book File") != OpeningBook.file_name())
414 OpeningBook.open("book.bin");
416 bookMove = OpeningBook.get_move(pos);
417 if (bookMove != MOVE_NONE)
419 std::cout << "bestmove " << bookMove << std::endl;
424 // Initialize global search variables
426 SearchStartTime = get_system_time();
427 EasyMove = MOVE_NONE;
428 for (int i = 0; i < THREAD_MAX; i++)
430 Threads[i].nodes = 0ULL;
431 Threads[i].failHighPly1 = false;
432 Threads[i].aspirationFailHighPly1 = false;
435 InfiniteSearch = infinite;
436 PonderSearch = ponder;
437 StopOnPonderhit = false;
443 ExactMaxTime = maxTime;
445 // Read UCI option values
446 TT.set_size(get_option_value_int("Hash"));
447 if (button_was_pressed("Clear Hash"))
450 PonderingEnabled = get_option_value_bool("Ponder");
451 MultiPV = get_option_value_int("MultiPV");
453 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
454 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
456 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
457 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
459 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
460 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
462 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
463 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
465 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
466 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
468 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
469 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
471 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
472 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
473 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
474 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
476 Chess960 = get_option_value_bool("UCI_Chess960");
477 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
478 UseLogFile = get_option_value_bool("Use Search Log");
480 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
482 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
483 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
485 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
486 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
487 for (int i = 0; i < 6; i++)
488 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
490 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
491 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
493 UseLSNFiltering = get_option_value_bool("LSN filtering");
494 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
495 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
497 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
498 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
500 read_weights(pos.side_to_move());
502 int newActiveThreads = get_option_value_int("Threads");
503 if (newActiveThreads != ActiveThreads)
505 ActiveThreads = newActiveThreads;
506 init_eval(ActiveThreads);
509 // Wake up sleeping threads:
510 wake_sleeping_threads();
512 for (int i = 1; i < ActiveThreads; i++)
513 assert(thread_is_available(i, 0));
515 // Set thinking time:
516 int myTime = time[side_to_move];
517 int myIncrement = increment[side_to_move];
519 if (!movesToGo) // Sudden death time control
523 MaxSearchTime = myTime / 30 + myIncrement;
524 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
525 } else { // Blitz game without increment
526 MaxSearchTime = myTime / 30;
527 AbsoluteMaxSearchTime = myTime / 8;
530 else // (x moves) / (y minutes)
534 MaxSearchTime = myTime / 2;
535 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
537 MaxSearchTime = myTime / Min(movesToGo, 20);
538 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
542 if (PonderingEnabled)
544 MaxSearchTime += MaxSearchTime / 4;
545 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
548 // Fixed depth or fixed number of nodes?
551 InfiniteSearch = true; // HACK
556 NodesBetweenPolls = Min(MaxNodes, 30000);
557 InfiniteSearch = true; // HACK
560 NodesBetweenPolls = 30000;
563 // Write information to search log file:
565 LogFile << "Searching: " << pos.to_fen() << std::endl
566 << "infinite: " << infinite
567 << " ponder: " << ponder
568 << " time: " << myTime
569 << " increment: " << myIncrement
570 << " moves to go: " << movesToGo << std::endl;
573 // We're ready to start thinking. Call the iterative deepening loop
577 Value v = id_loop(pos, searchMoves);
578 looseOnTime = ( UseLSNFiltering
585 looseOnTime = false; // reset for next match
586 while (SearchStartTime + myTime + 1000 > get_system_time())
588 id_loop(pos, searchMoves); // to fail gracefully
605 /// init_threads() is called during startup. It launches all helper threads,
606 /// and initializes the split point stack and the global locks and condition
609 void init_threads() {
613 #if !defined(_MSC_VER)
614 pthread_t pthread[1];
617 for (i = 0; i < THREAD_MAX; i++)
618 Threads[i].activeSplitPoints = 0;
620 // Initialize global locks:
621 lock_init(&MPLock, NULL);
622 lock_init(&IOLock, NULL);
624 init_split_point_stack();
626 #if !defined(_MSC_VER)
627 pthread_mutex_init(&WaitLock, NULL);
628 pthread_cond_init(&WaitCond, NULL);
630 for (i = 0; i < THREAD_MAX; i++)
631 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
634 // All threads except the main thread should be initialized to idle state
635 for (i = 1; i < THREAD_MAX; i++)
637 Threads[i].stop = false;
638 Threads[i].workIsWaiting = false;
639 Threads[i].idle = true;
640 Threads[i].running = false;
643 // Launch the helper threads
644 for(i = 1; i < THREAD_MAX; i++)
646 #if !defined(_MSC_VER)
647 pthread_create(pthread, NULL, init_thread, (void*)(&i));
650 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
653 // Wait until the thread has finished launching:
654 while (!Threads[i].running);
657 // Init also the empty search stack
658 EmptySearchStack.init(0);
659 EmptySearchStack.initKillers();
663 /// stop_threads() is called when the program exits. It makes all the
664 /// helper threads exit cleanly.
666 void stop_threads() {
668 ActiveThreads = THREAD_MAX; // HACK
669 Idle = false; // HACK
670 wake_sleeping_threads();
671 AllThreadsShouldExit = true;
672 for (int i = 1; i < THREAD_MAX; i++)
674 Threads[i].stop = true;
675 while(Threads[i].running);
677 destroy_split_point_stack();
681 /// nodes_searched() returns the total number of nodes searched so far in
682 /// the current search.
684 int64_t nodes_searched() {
686 int64_t result = 0ULL;
687 for (int i = 0; i < ActiveThreads; i++)
688 result += Threads[i].nodes;
695 // id_loop() is the main iterative deepening loop. It calls root_search
696 // repeatedly with increasing depth until the allocated thinking time has
697 // been consumed, the user stops the search, or the maximum search depth is
700 Value id_loop(const Position &pos, Move searchMoves[]) {
703 SearchStack ss[PLY_MAX_PLUS_2];
705 // searchMoves are verified, copied, scored and sorted
706 RootMoveList rml(p, searchMoves);
711 for (int i = 0; i < 3; i++)
716 IterationInfo[1].set(rml.get_move_score(0));
719 EasyMove = rml.scan_for_easy_move();
721 // Iterative deepening loop
722 while (Iteration < PLY_MAX)
724 // Initialize iteration
727 BestMoveChangesByIteration[Iteration] = 0;
731 std::cout << "info depth " << Iteration << std::endl;
733 //Calculate dynamic search window based on previous iterations.
737 if (MultiPV == 1 && Iteration >= 6) {
738 Value prevDelta1 = IterationInfo[Iteration - 1].speculated_value() - IterationInfo[Iteration - 2].speculated_value();
739 Value prevDelta2 = IterationInfo[Iteration - 2].speculated_value() - IterationInfo[Iteration - 3].speculated_value();
741 Value delta = Max((2 * Abs(prevDelta1) + Abs(prevDelta2)) , ProblemMargin);
743 alpha = IterationInfo[Iteration - 1].value() - delta;
744 beta = IterationInfo[Iteration - 1].value() + delta;
745 if (alpha < - VALUE_INFINITE) alpha = - VALUE_INFINITE;
746 if (beta > VALUE_INFINITE) beta = VALUE_INFINITE;
749 alpha = - VALUE_INFINITE;
750 beta = VALUE_INFINITE;
753 // Search to the current depth
754 Value value = root_search(p, ss, rml, alpha, beta);
756 break; //Value cannot be trusted. Break out immediately!
758 // Write PV to transposition table, in case the relevant entries have
759 // been overwritten during the search:
760 TT.insert_pv(p, ss[0].pv);
762 //Save info about search result
763 Value speculated_value = value;
767 Value prev_value = IterationInfo[Iteration - 1].value();
768 Value delta = value - prev_value;
772 speculated_value = prev_value + 2 * delta;
773 BestMoveChangesByIteration[Iteration] += 2; //This is used to tell time management to allocate more time
774 } else if (value <= alpha) {
776 speculated_value = prev_value + 2 * delta;
777 BestMoveChangesByIteration[Iteration] += 3; //This is used to tell time management to allocate more time
782 if (speculated_value < - VALUE_INFINITE) speculated_value = - VALUE_INFINITE;
783 if (speculated_value > VALUE_INFINITE) speculated_value = VALUE_INFINITE;
785 IterationInfo[Iteration].set(value, speculated_value, fHigh, fLow);
787 // Erase the easy move if it differs from the new best move
788 if (ss[0].pv[0] != EasyMove)
789 EasyMove = MOVE_NONE;
796 bool stopSearch = false;
798 // Stop search early if there is only a single legal move:
799 if (Iteration >= 6 && rml.move_count() == 1)
802 // Stop search early when the last two iterations returned a mate score
804 && abs(IterationInfo[Iteration].value()) >= abs(VALUE_MATE) - 100
805 && abs(IterationInfo[Iteration-1].value()) >= abs(VALUE_MATE) - 100)
808 // Stop search early if one move seems to be much better than the rest
809 int64_t nodes = nodes_searched();
810 if ( Iteration >= 8 && !fLow && !fHigh
811 && EasyMove == ss[0].pv[0]
812 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
813 && current_search_time() > MaxSearchTime / 16)
814 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
815 && current_search_time() > MaxSearchTime / 32)))
818 // Add some extra time if the best move has changed during the last two iterations
819 if (Iteration > 5 && Iteration <= 50)
820 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
821 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
823 // Stop search if most of MaxSearchTime is consumed at the end of the
824 // iteration. We probably don't have enough time to search the first
825 // move at the next iteration anyway.
826 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
831 //FIXME: Implement fail-low emergency measures
835 StopOnPonderhit = true;
839 if (MaxDepth && Iteration >= MaxDepth)
845 // If we are pondering, we shouldn't print the best move before we
848 wait_for_stop_or_ponderhit();
850 // Print final search statistics
851 std::cout << "info nodes " << nodes_searched()
853 << " time " << current_search_time()
854 << " hashfull " << TT.full() << std::endl;
856 // Print the best move and the ponder move to the standard output
857 if (ss[0].pv[0] == MOVE_NONE)
859 ss[0].pv[0] = rml.get_move(0);
860 ss[0].pv[1] = MOVE_NONE;
862 std::cout << "bestmove " << ss[0].pv[0];
863 if (ss[0].pv[1] != MOVE_NONE)
864 std::cout << " ponder " << ss[0].pv[1];
866 std::cout << std::endl;
871 dbg_print_mean(LogFile);
873 if (dbg_show_hit_rate)
874 dbg_print_hit_rate(LogFile);
877 LogFile << "Nodes: " << nodes_searched() << std::endl
878 << "Nodes/second: " << nps() << std::endl
879 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
881 p.do_move(ss[0].pv[0], st);
882 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
883 << std::endl << std::endl;
885 return rml.get_move_score(0);
889 // root_search() is the function which searches the root node. It is
890 // similar to search_pv except that it uses a different move ordering
891 // scheme (perhaps we should try to use this at internal PV nodes, too?)
892 // and prints some information to the standard output.
894 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
896 Value oldAlpha = alpha;
898 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
900 // Loop through all the moves in the root move list
901 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
904 rml.set_move_score(i, -VALUE_INFINITE);
905 //Leave node-counters and beta-counters as they are.
914 RootMoveNumber = i + 1;
917 // Remember the node count before the move is searched. The node counts
918 // are used to sort the root moves at the next iteration.
919 nodes = nodes_searched();
921 // Reset beta cut-off counters
924 // Pick the next root move, and print the move and the move number to
925 // the standard output.
926 move = ss[0].currentMove = rml.get_move(i);
927 if (current_search_time() >= 1000)
928 std::cout << "info currmove " << move
929 << " currmovenumber " << i + 1 << std::endl;
931 // Decide search depth for this move
933 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
934 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
936 // Make the move, and search it
937 pos.do_move(move, st, dcCandidates);
941 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
942 // If the value has dropped a lot compared to the last iteration,
943 // set the boolean variable Problem to true. This variable is used
944 // for time managment: When Problem is true, we try to complete the
945 // current iteration before playing a move.
946 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value() - ProblemMargin);
948 if (Problem && StopOnPonderhit)
949 StopOnPonderhit = false;
953 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
956 // Fail high! Set the boolean variable FailHigh to true, and
957 // re-search the move with a big window. The variable FailHigh is
958 // used for time managment: We try to avoid aborting the search
959 // prematurely during a fail high research.
961 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
967 // Finished searching the move. If AbortSearch is true, the search
968 // was aborted because the user interrupted the search or because we
969 // ran out of time. In this case, the return value of the search cannot
970 // be trusted, and we break out of the loop without updating the best
975 // Remember the node count for this move. The node counts are used to
976 // sort the root moves at the next iteration.
977 rml.set_move_nodes(i, nodes_searched() - nodes);
979 // Remember the beta-cutoff statistics
981 BetaCounter.read(pos.side_to_move(), our, their);
982 rml.set_beta_counters(i, our, their);
984 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
986 if (value <= alpha && i >= MultiPV)
987 rml.set_move_score(i, -VALUE_INFINITE);
993 rml.set_move_score(i, value);
995 rml.set_move_pv(i, ss[0].pv);
999 // We record how often the best move has been changed in each
1000 // iteration. This information is used for time managment: When
1001 // the best move changes frequently, we allocate some more time.
1003 BestMoveChangesByIteration[Iteration]++;
1005 // Print search information to the standard output:
1006 std::cout << "info depth " << Iteration
1007 << " score " << value_to_string(value)
1008 << " time " << current_search_time()
1009 << " nodes " << nodes_searched()
1013 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1014 std::cout << ss[0].pv[j] << " ";
1016 std::cout << std::endl;
1019 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
1025 // Reset the global variable Problem to false if the value isn't too
1026 // far below the final value from the last iteration.
1027 if (value > IterationInfo[Iteration - 1].value() - NoProblemMargin)
1032 rml.sort_multipv(i);
1033 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1036 std::cout << "info multipv " << j + 1
1037 << " score " << value_to_string(rml.get_move_score(j))
1038 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1039 << " time " << current_search_time()
1040 << " nodes " << nodes_searched()
1044 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1045 std::cout << rml.get_move_pv(j, k) << " ";
1047 std::cout << std::endl;
1049 alpha = rml.get_move_score(Min(i, MultiPV-1));
1053 if (alpha <= oldAlpha)
1063 // search_pv() is the main search function for PV nodes.
1065 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1066 Depth depth, int ply, int threadID) {
1068 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1069 assert(beta > alpha && beta <= VALUE_INFINITE);
1070 assert(ply >= 0 && ply < PLY_MAX);
1071 assert(threadID >= 0 && threadID < ActiveThreads);
1074 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1076 // Initialize, and make an early exit in case of an aborted search,
1077 // an instant draw, maximum ply reached, etc.
1078 init_node(ss, ply, threadID);
1080 // After init_node() that calls poll()
1081 if (AbortSearch || thread_should_stop(threadID))
1089 if (ply >= PLY_MAX - 1)
1090 return evaluate(pos, ei, threadID);
1092 // Mate distance pruning
1093 Value oldAlpha = alpha;
1094 alpha = Max(value_mated_in(ply), alpha);
1095 beta = Min(value_mate_in(ply+1), beta);
1099 // Transposition table lookup. At PV nodes, we don't use the TT for
1100 // pruning, but only for move ordering.
1101 const TTEntry* tte = TT.retrieve(pos);
1102 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1104 // Go with internal iterative deepening if we don't have a TT move
1105 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1107 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1108 ttMove = ss[ply].pv[ply];
1111 // Initialize a MovePicker object for the current position, and prepare
1112 // to search all moves
1113 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1115 Move move, movesSearched[256];
1117 Value value, bestValue = -VALUE_INFINITE;
1118 Bitboard dcCandidates = mp.discovered_check_candidates();
1119 Color us = pos.side_to_move();
1120 bool isCheck = pos.is_check();
1121 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1123 // Loop through all legal moves until no moves remain or a beta cutoff
1125 while ( alpha < beta
1126 && (move = mp.get_next_move()) != MOVE_NONE
1127 && !thread_should_stop(threadID))
1129 assert(move_is_ok(move));
1131 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1132 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1133 bool moveIsCapture = pos.move_is_capture(move);
1135 movesSearched[moveCount++] = ss[ply].currentMove = move;
1137 // Decide the new search depth
1139 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1140 Depth newDepth = depth - OnePly + ext;
1142 // Make and search the move
1144 pos.do_move(move, st, dcCandidates);
1146 if (moveCount == 1) // The first move in list is the PV
1147 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1150 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1151 // if the move fails high will be re-searched at full depth.
1152 if ( depth >= 2*OnePly
1153 && moveCount >= LMRPVMoves
1156 && !move_promotion(move)
1157 && !move_is_castle(move)
1158 && !move_is_killer(move, ss[ply]))
1160 ss[ply].reduction = OnePly;
1161 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1164 value = alpha + 1; // Just to trigger next condition
1166 if (value > alpha) // Go with full depth non-pv search
1168 ss[ply].reduction = Depth(0);
1169 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1170 if (value > alpha /*&& value < beta*/)
1172 // When the search fails high at ply 1 while searching the first
1173 // move at the root, set the flag failHighPly1. This is used for
1174 // time managment: We don't want to stop the search early in
1175 // such cases, because resolving the fail high at ply 1 could
1176 // result in a big drop in score at the root.
1177 if (ply == 1 && RootMoveNumber == 1) {
1178 Threads[threadID].failHighPly1 = true;
1179 if (value >= beta) {
1180 Threads[threadID].aspirationFailHighPly1 = true;
1184 // A fail high occurred. Re-search at full window (pv search)
1185 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1186 Threads[threadID].failHighPly1 = false;
1187 //FIXME: Current implementation of Problem code is not completely thread-safe.
1188 //If poll is called before pv is updated, we lose this move.
1189 //(failHighPly1 also suffers from same kind of problems though. There is also a small
1190 //fraction of time when failHighPly1 and Problem are _both_ false, though we
1191 //are facing bad problems. If we are very unlucky search is terminated).
1192 Threads[threadID].aspirationFailHighPly1 = false;
1196 pos.undo_move(move);
1198 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1201 if (value > bestValue)
1208 if (value == value_mate_in(ply + 1))
1209 ss[ply].mateKiller = move;
1211 // If we are at ply 1, and we are searching the first root move at
1212 // ply 0, set the 'Problem' variable if the score has dropped a lot
1213 // (from the computer's point of view) since the previous iteration:
1216 && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1221 if ( ActiveThreads > 1
1223 && depth >= MinimumSplitDepth
1225 && idle_thread_exists(threadID)
1227 && !thread_should_stop(threadID)
1228 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1229 &moveCount, &mp, dcCandidates, threadID, true))
1233 // All legal moves have been searched. A special case: If there were
1234 // no legal moves, it must be mate or stalemate:
1236 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1238 // If the search is not aborted, update the transposition table,
1239 // history counters, and killer moves.
1240 if (AbortSearch || thread_should_stop(threadID))
1243 if (bestValue <= oldAlpha)
1244 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1246 else if (bestValue >= beta)
1248 BetaCounter.add(pos.side_to_move(), depth, threadID);
1249 Move m = ss[ply].pv[ply];
1250 if (ok_to_history(pos, m)) // Only non capture moves are considered
1252 update_history(pos, m, depth, movesSearched, moveCount);
1253 update_killers(m, ss[ply]);
1255 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1258 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1264 // search() is the search function for zero-width nodes.
1266 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1267 int ply, bool allowNullmove, int threadID) {
1269 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1270 assert(ply >= 0 && ply < PLY_MAX);
1271 assert(threadID >= 0 && threadID < ActiveThreads);
1274 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1276 // Initialize, and make an early exit in case of an aborted search,
1277 // an instant draw, maximum ply reached, etc.
1278 init_node(ss, ply, threadID);
1280 // After init_node() that calls poll()
1281 if (AbortSearch || thread_should_stop(threadID))
1289 if (ply >= PLY_MAX - 1)
1290 return evaluate(pos, ei, threadID);
1292 // Mate distance pruning
1293 if (value_mated_in(ply) >= beta)
1296 if (value_mate_in(ply + 1) < beta)
1299 // Transposition table lookup
1300 const TTEntry* tte = TT.retrieve(pos);
1301 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1303 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1305 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1306 return value_from_tt(tte->value(), ply);
1309 Value approximateEval = quick_evaluate(pos);
1310 bool mateThreat = false;
1311 bool isCheck = pos.is_check();
1317 && !value_is_mate(beta)
1318 && ok_to_do_nullmove(pos)
1319 && approximateEval >= beta - NullMoveMargin)
1321 ss[ply].currentMove = MOVE_NULL;
1324 pos.do_null_move(st);
1325 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1327 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1329 pos.undo_null_move();
1331 if (value_is_mate(nullValue))
1333 /* Do not return unproven mates */
1335 else if (nullValue >= beta)
1337 if (depth < 6 * OnePly)
1340 // Do zugzwang verification search
1341 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1345 // The null move failed low, which means that we may be faced with
1346 // some kind of threat. If the previous move was reduced, check if
1347 // the move that refuted the null move was somehow connected to the
1348 // move which was reduced. If a connection is found, return a fail
1349 // low score (which will cause the reduced move to fail high in the
1350 // parent node, which will trigger a re-search with full depth).
1351 if (nullValue == value_mated_in(ply + 2))
1354 ss[ply].threatMove = ss[ply + 1].currentMove;
1355 if ( depth < ThreatDepth
1356 && ss[ply - 1].reduction
1357 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1361 // Null move search not allowed, try razoring
1362 else if ( !value_is_mate(beta)
1363 && approximateEval < beta - RazorMargin
1364 && depth < RazorDepth
1365 && (RazorAtDepthOne || depth > OnePly)
1366 && ttMove == MOVE_NONE
1367 && !pos.has_pawn_on_7th(pos.side_to_move()))
1369 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1370 if ( (v < beta - RazorMargin - RazorMargin / 4)
1371 || (depth <= 2*OnePly && v < beta - RazorMargin)
1372 || (depth <= OnePly && v < beta - RazorMargin / 2))
1376 // Go with internal iterative deepening if we don't have a TT move
1377 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1378 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1380 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1381 ttMove = ss[ply].pv[ply];
1384 // Initialize a MovePicker object for the current position, and prepare
1385 // to search all moves:
1386 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1388 Move move, movesSearched[256];
1390 Value value, bestValue = -VALUE_INFINITE;
1391 Bitboard dcCandidates = mp.discovered_check_candidates();
1392 Value futilityValue = VALUE_NONE;
1393 bool useFutilityPruning = UseFutilityPruning
1394 && depth < SelectiveDepth
1397 // Loop through all legal moves until no moves remain or a beta cutoff
1399 while ( bestValue < beta
1400 && (move = mp.get_next_move()) != MOVE_NONE
1401 && !thread_should_stop(threadID))
1403 assert(move_is_ok(move));
1405 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1406 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1407 bool moveIsCapture = pos.move_is_capture(move);
1409 movesSearched[moveCount++] = ss[ply].currentMove = move;
1411 // Decide the new search depth
1413 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1414 Depth newDepth = depth - OnePly + ext;
1417 if ( useFutilityPruning
1420 && !move_promotion(move))
1422 // History pruning. See ok_to_prune() definition
1423 if ( moveCount >= 2 + int(depth)
1424 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1427 // Value based pruning
1428 if (depth < 7 * OnePly && approximateEval < beta)
1430 if (futilityValue == VALUE_NONE)
1431 futilityValue = evaluate(pos, ei, threadID)
1432 + FutilityMargins[int(depth)/2 - 1]
1435 if (futilityValue < beta)
1437 if (futilityValue > bestValue)
1438 bestValue = futilityValue;
1444 // Make and search the move
1446 pos.do_move(move, st, dcCandidates);
1448 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1449 // if the move fails high will be re-searched at full depth.
1450 if ( depth >= 2*OnePly
1451 && moveCount >= LMRNonPVMoves
1454 && !move_promotion(move)
1455 && !move_is_castle(move)
1456 && !move_is_killer(move, ss[ply]))
1458 ss[ply].reduction = OnePly;
1459 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1462 value = beta; // Just to trigger next condition
1464 if (value >= beta) // Go with full depth non-pv search
1466 ss[ply].reduction = Depth(0);
1467 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1469 pos.undo_move(move);
1471 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1474 if (value > bestValue)
1480 if (value == value_mate_in(ply + 1))
1481 ss[ply].mateKiller = move;
1485 if ( ActiveThreads > 1
1487 && depth >= MinimumSplitDepth
1489 && idle_thread_exists(threadID)
1491 && !thread_should_stop(threadID)
1492 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1493 &mp, dcCandidates, threadID, false))
1497 // All legal moves have been searched. A special case: If there were
1498 // no legal moves, it must be mate or stalemate.
1500 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1502 // If the search is not aborted, update the transposition table,
1503 // history counters, and killer moves.
1504 if (AbortSearch || thread_should_stop(threadID))
1507 if (bestValue < beta)
1508 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1511 BetaCounter.add(pos.side_to_move(), depth, threadID);
1512 Move m = ss[ply].pv[ply];
1513 if (ok_to_history(pos, m)) // Only non capture moves are considered
1515 update_history(pos, m, depth, movesSearched, moveCount);
1516 update_killers(m, ss[ply]);
1518 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1521 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1527 // qsearch() is the quiescence search function, which is called by the main
1528 // search function when the remaining depth is zero (or, to be more precise,
1529 // less than OnePly).
1531 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1532 Depth depth, int ply, int threadID) {
1534 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1535 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1537 assert(ply >= 0 && ply < PLY_MAX);
1538 assert(threadID >= 0 && threadID < ActiveThreads);
1540 // Initialize, and make an early exit in case of an aborted search,
1541 // an instant draw, maximum ply reached, etc.
1542 init_node(ss, ply, threadID);
1544 // After init_node() that calls poll()
1545 if (AbortSearch || thread_should_stop(threadID))
1551 // Transposition table lookup, only when not in PV
1552 TTEntry* tte = NULL;
1553 bool pvNode = (beta - alpha != 1);
1556 tte = TT.retrieve(pos);
1557 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1559 assert(tte->type() != VALUE_TYPE_EVAL);
1561 return value_from_tt(tte->value(), ply);
1565 // Evaluate the position statically
1568 bool isCheck = pos.is_check();
1569 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1572 staticValue = -VALUE_INFINITE;
1574 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1576 // Use the cached evaluation score if possible
1577 assert(tte->value() == evaluate(pos, ei, threadID));
1578 assert(ei.futilityMargin == Value(0));
1580 staticValue = tte->value();
1583 staticValue = evaluate(pos, ei, threadID);
1585 if (ply == PLY_MAX - 1)
1586 return evaluate(pos, ei, threadID);
1588 // Initialize "stand pat score", and return it immediately if it is
1590 Value bestValue = staticValue;
1592 if (bestValue >= beta)
1594 // Store the score to avoid a future costly evaluation() call
1595 if (!isCheck && !tte && ei.futilityMargin == 0)
1596 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1601 if (bestValue > alpha)
1604 // Initialize a MovePicker object for the current position, and prepare
1605 // to search the moves. Because the depth is <= 0 here, only captures,
1606 // queen promotions and checks (only if depth == 0) will be generated.
1607 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth);
1610 Bitboard dcCandidates = mp.discovered_check_candidates();
1611 Color us = pos.side_to_move();
1612 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1614 // Loop through the moves until no moves remain or a beta cutoff
1616 while ( alpha < beta
1617 && (move = mp.get_next_move()) != MOVE_NONE)
1619 assert(move_is_ok(move));
1622 ss[ply].currentMove = move;
1625 if ( UseQSearchFutilityPruning
1629 && !move_promotion(move)
1630 && !pos.move_is_check(move, dcCandidates)
1631 && !pos.move_is_passed_pawn_push(move))
1633 Value futilityValue = staticValue
1634 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1635 pos.endgame_value_of_piece_on(move_to(move)))
1636 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1638 + ei.futilityMargin;
1640 if (futilityValue < alpha)
1642 if (futilityValue > bestValue)
1643 bestValue = futilityValue;
1648 // Don't search captures and checks with negative SEE values
1650 && !move_promotion(move)
1651 && (pos.midgame_value_of_piece_on(move_from(move)) >
1652 pos.midgame_value_of_piece_on(move_to(move)))
1653 && pos.see(move) < 0)
1656 // Make and search the move.
1658 pos.do_move(move, st, dcCandidates);
1659 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1660 pos.undo_move(move);
1662 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1665 if (value > bestValue)
1676 // All legal moves have been searched. A special case: If we're in check
1677 // and no legal moves were found, it is checkmate:
1678 if (pos.is_check() && moveCount == 0) // Mate!
1679 return value_mated_in(ply);
1681 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1683 // Update transposition table
1686 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1687 if (bestValue < beta)
1688 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_UPPER);
1690 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_LOWER);
1693 // Update killers only for good check moves
1694 Move m = ss[ply].currentMove;
1695 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1697 // Wrong to update history when depth is <= 0
1698 update_killers(m, ss[ply]);
1704 // sp_search() is used to search from a split point. This function is called
1705 // by each thread working at the split point. It is similar to the normal
1706 // search() function, but simpler. Because we have already probed the hash
1707 // table, done a null move search, and searched the first move before
1708 // splitting, we don't have to repeat all this work in sp_search(). We
1709 // also don't need to store anything to the hash table here: This is taken
1710 // care of after we return from the split point.
1712 void sp_search(SplitPoint *sp, int threadID) {
1714 assert(threadID >= 0 && threadID < ActiveThreads);
1715 assert(ActiveThreads > 1);
1717 Position pos = Position(sp->pos);
1718 SearchStack *ss = sp->sstack[threadID];
1721 bool isCheck = pos.is_check();
1722 bool useFutilityPruning = UseFutilityPruning
1723 && sp->depth < SelectiveDepth
1726 while ( sp->bestValue < sp->beta
1727 && !thread_should_stop(threadID)
1728 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1730 assert(move_is_ok(move));
1732 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1733 bool moveIsCapture = pos.move_is_capture(move);
1735 lock_grab(&(sp->lock));
1736 int moveCount = ++sp->moves;
1737 lock_release(&(sp->lock));
1739 ss[sp->ply].currentMove = move;
1741 // Decide the new search depth.
1743 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1744 Depth newDepth = sp->depth - OnePly + ext;
1747 if ( useFutilityPruning
1750 && !move_promotion(move)
1751 && moveCount >= 2 + int(sp->depth)
1752 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1755 // Make and search the move.
1757 pos.do_move(move, st, sp->dcCandidates);
1759 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1760 // if the move fails high will be re-searched at full depth.
1762 && moveCount >= LMRNonPVMoves
1764 && !move_promotion(move)
1765 && !move_is_castle(move)
1766 && !move_is_killer(move, ss[sp->ply]))
1768 ss[sp->ply].reduction = OnePly;
1769 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1772 value = sp->beta; // Just to trigger next condition
1774 if (value >= sp->beta) // Go with full depth non-pv search
1776 ss[sp->ply].reduction = Depth(0);
1777 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1779 pos.undo_move(move);
1781 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1783 if (thread_should_stop(threadID))
1787 lock_grab(&(sp->lock));
1788 if (value > sp->bestValue && !thread_should_stop(threadID))
1790 sp->bestValue = value;
1791 if (sp->bestValue >= sp->beta)
1793 sp_update_pv(sp->parentSstack, ss, sp->ply);
1794 for (int i = 0; i < ActiveThreads; i++)
1795 if (i != threadID && (i == sp->master || sp->slaves[i]))
1796 Threads[i].stop = true;
1798 sp->finished = true;
1801 lock_release(&(sp->lock));
1804 lock_grab(&(sp->lock));
1806 // If this is the master thread and we have been asked to stop because of
1807 // a beta cutoff higher up in the tree, stop all slave threads:
1808 if (sp->master == threadID && thread_should_stop(threadID))
1809 for (int i = 0; i < ActiveThreads; i++)
1811 Threads[i].stop = true;
1814 sp->slaves[threadID] = 0;
1816 lock_release(&(sp->lock));
1820 // sp_search_pv() is used to search from a PV split point. This function
1821 // is called by each thread working at the split point. It is similar to
1822 // the normal search_pv() function, but simpler. Because we have already
1823 // probed the hash table and searched the first move before splitting, we
1824 // don't have to repeat all this work in sp_search_pv(). We also don't
1825 // need to store anything to the hash table here: This is taken care of
1826 // after we return from the split point.
1828 void sp_search_pv(SplitPoint *sp, int threadID) {
1830 assert(threadID >= 0 && threadID < ActiveThreads);
1831 assert(ActiveThreads > 1);
1833 Position pos = Position(sp->pos);
1834 SearchStack *ss = sp->sstack[threadID];
1838 while ( sp->alpha < sp->beta
1839 && !thread_should_stop(threadID)
1840 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1842 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1843 bool moveIsCapture = pos.move_is_capture(move);
1845 assert(move_is_ok(move));
1847 lock_grab(&(sp->lock));
1848 int moveCount = ++sp->moves;
1849 lock_release(&(sp->lock));
1851 ss[sp->ply].currentMove = move;
1853 // Decide the new search depth.
1855 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1856 Depth newDepth = sp->depth - OnePly + ext;
1858 // Make and search the move.
1860 pos.do_move(move, st, sp->dcCandidates);
1862 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1863 // if the move fails high will be re-searched at full depth.
1865 && moveCount >= LMRPVMoves
1867 && !move_promotion(move)
1868 && !move_is_castle(move)
1869 && !move_is_killer(move, ss[sp->ply]))
1871 ss[sp->ply].reduction = OnePly;
1872 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1875 value = sp->alpha + 1; // Just to trigger next condition
1877 if (value > sp->alpha) // Go with full depth non-pv search
1879 ss[sp->ply].reduction = Depth(0);
1880 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1882 if (value > sp->alpha /*&& value < sp->beta*/)
1884 // When the search fails high at ply 1 while searching the first
1885 // move at the root, set the flag failHighPly1. This is used for
1886 // time managment: We don't want to stop the search early in
1887 // such cases, because resolving the fail high at ply 1 could
1888 // result in a big drop in score at the root.
1889 if (sp->ply == 1 && RootMoveNumber == 1) {
1890 Threads[threadID].failHighPly1 = true;
1891 if (value >= sp->beta) {
1892 Threads[threadID].aspirationFailHighPly1 = true;
1896 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1897 Threads[threadID].failHighPly1 = false;
1898 Threads[threadID].aspirationFailHighPly1 = false;
1901 pos.undo_move(move);
1903 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1905 if (thread_should_stop(threadID))
1909 lock_grab(&(sp->lock));
1910 if (value > sp->bestValue && !thread_should_stop(threadID))
1912 sp->bestValue = value;
1913 if (value > sp->alpha)
1916 sp_update_pv(sp->parentSstack, ss, sp->ply);
1917 if (value == value_mate_in(sp->ply + 1))
1918 ss[sp->ply].mateKiller = move;
1920 if(value >= sp->beta)
1922 for(int i = 0; i < ActiveThreads; i++)
1923 if(i != threadID && (i == sp->master || sp->slaves[i]))
1924 Threads[i].stop = true;
1926 sp->finished = true;
1929 // If we are at ply 1, and we are searching the first root move at
1930 // ply 0, set the 'Problem' variable if the score has dropped a lot
1931 // (from the computer's point of view) since the previous iteration.
1934 && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1937 lock_release(&(sp->lock));
1940 lock_grab(&(sp->lock));
1942 // If this is the master thread and we have been asked to stop because of
1943 // a beta cutoff higher up in the tree, stop all slave threads.
1944 if (sp->master == threadID && thread_should_stop(threadID))
1945 for (int i = 0; i < ActiveThreads; i++)
1947 Threads[i].stop = true;
1950 sp->slaves[threadID] = 0;
1952 lock_release(&(sp->lock));
1955 /// The BetaCounterType class
1957 BetaCounterType::BetaCounterType() { clear(); }
1959 void BetaCounterType::clear() {
1961 for (int i = 0; i < THREAD_MAX; i++)
1962 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1965 void BetaCounterType::add(Color us, Depth d, int threadID) {
1967 // Weighted count based on depth
1968 hits[threadID][us] += int(d);
1971 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1974 for (int i = 0; i < THREAD_MAX; i++)
1977 their += hits[i][opposite_color(us)];
1982 /// The RootMove class
1986 RootMove::RootMove() {
1987 nodes = cumulativeNodes = 0ULL;
1990 // RootMove::operator<() is the comparison function used when
1991 // sorting the moves. A move m1 is considered to be better
1992 // than a move m2 if it has a higher score, or if the moves
1993 // have equal score but m1 has the higher node count.
1995 bool RootMove::operator<(const RootMove& m) {
1997 if (score != m.score)
1998 return (score < m.score);
2000 return theirBeta <= m.theirBeta;
2003 /// The RootMoveList class
2007 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2009 MoveStack mlist[MaxRootMoves];
2010 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2012 // Generate all legal moves
2013 int lm_count = generate_legal_moves(pos, mlist);
2015 // Add each move to the moves[] array
2016 for (int i = 0; i < lm_count; i++)
2018 bool includeMove = includeAllMoves;
2020 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2021 includeMove = (searchMoves[k] == mlist[i].move);
2025 // Find a quick score for the move
2027 SearchStack ss[PLY_MAX_PLUS_2];
2029 moves[count].move = mlist[i].move;
2030 moves[count].nodes = 0ULL;
2031 pos.do_move(moves[count].move, st);
2032 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
2034 pos.undo_move(moves[count].move);
2035 moves[count].pv[0] = moves[i].move;
2036 moves[count].pv[1] = MOVE_NONE; // FIXME
2044 // Simple accessor methods for the RootMoveList class
2046 inline Move RootMoveList::get_move(int moveNum) const {
2047 return moves[moveNum].move;
2050 inline Value RootMoveList::get_move_score(int moveNum) const {
2051 return moves[moveNum].score;
2054 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2055 moves[moveNum].score = score;
2058 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2059 moves[moveNum].nodes = nodes;
2060 moves[moveNum].cumulativeNodes += nodes;
2063 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2064 moves[moveNum].ourBeta = our;
2065 moves[moveNum].theirBeta = their;
2068 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2070 for(j = 0; pv[j] != MOVE_NONE; j++)
2071 moves[moveNum].pv[j] = pv[j];
2072 moves[moveNum].pv[j] = MOVE_NONE;
2075 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2076 return moves[moveNum].pv[i];
2079 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2080 return moves[moveNum].cumulativeNodes;
2083 inline int RootMoveList::move_count() const {
2088 // RootMoveList::scan_for_easy_move() is called at the end of the first
2089 // iteration, and is used to detect an "easy move", i.e. a move which appears
2090 // to be much bester than all the rest. If an easy move is found, the move
2091 // is returned, otherwise the function returns MOVE_NONE. It is very
2092 // important that this function is called at the right moment: The code
2093 // assumes that the first iteration has been completed and the moves have
2094 // been sorted. This is done in RootMoveList c'tor.
2096 Move RootMoveList::scan_for_easy_move() const {
2103 // moves are sorted so just consider the best and the second one
2104 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2110 // RootMoveList::sort() sorts the root move list at the beginning of a new
2113 inline void RootMoveList::sort() {
2115 sort_multipv(count - 1); // all items
2119 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2120 // list by their scores and depths. It is used to order the different PVs
2121 // correctly in MultiPV mode.
2123 void RootMoveList::sort_multipv(int n) {
2125 for (int i = 1; i <= n; i++)
2127 RootMove rm = moves[i];
2129 for (j = i; j > 0 && moves[j-1] < rm; j--)
2130 moves[j] = moves[j-1];
2136 // init_node() is called at the beginning of all the search functions
2137 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2138 // stack object corresponding to the current node. Once every
2139 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2140 // for user input and checks whether it is time to stop the search.
2142 void init_node(SearchStack ss[], int ply, int threadID) {
2143 assert(ply >= 0 && ply < PLY_MAX);
2144 assert(threadID >= 0 && threadID < ActiveThreads);
2146 Threads[threadID].nodes++;
2150 if(NodesSincePoll >= NodesBetweenPolls) {
2157 ss[ply+2].initKillers();
2159 if(Threads[threadID].printCurrentLine)
2160 print_current_line(ss, ply, threadID);
2164 // update_pv() is called whenever a search returns a value > alpha. It
2165 // updates the PV in the SearchStack object corresponding to the current
2168 void update_pv(SearchStack ss[], int ply) {
2169 assert(ply >= 0 && ply < PLY_MAX);
2171 ss[ply].pv[ply] = ss[ply].currentMove;
2173 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2174 ss[ply].pv[p] = ss[ply+1].pv[p];
2175 ss[ply].pv[p] = MOVE_NONE;
2179 // sp_update_pv() is a variant of update_pv for use at split points. The
2180 // difference between the two functions is that sp_update_pv also updates
2181 // the PV at the parent node.
2183 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2184 assert(ply >= 0 && ply < PLY_MAX);
2186 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2188 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2189 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2190 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2194 // connected_moves() tests whether two moves are 'connected' in the sense
2195 // that the first move somehow made the second move possible (for instance
2196 // if the moving piece is the same in both moves). The first move is
2197 // assumed to be the move that was made to reach the current position, while
2198 // the second move is assumed to be a move from the current position.
2200 bool connected_moves(const Position &pos, Move m1, Move m2) {
2201 Square f1, t1, f2, t2;
2203 assert(move_is_ok(m1));
2204 assert(move_is_ok(m2));
2209 // Case 1: The moving piece is the same in both moves.
2215 // Case 2: The destination square for m2 was vacated by m1.
2221 // Case 3: Moving through the vacated square:
2222 if(piece_is_slider(pos.piece_on(f2)) &&
2223 bit_is_set(squares_between(f2, t2), f1))
2226 // Case 4: The destination square for m2 is attacked by the moving piece
2228 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2231 // Case 5: Discovered check, checking piece is the piece moved in m1:
2232 if(piece_is_slider(pos.piece_on(t1)) &&
2233 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2235 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2237 Bitboard occ = pos.occupied_squares();
2238 Color us = pos.side_to_move();
2239 Square ksq = pos.king_square(us);
2240 clear_bit(&occ, f2);
2241 if(pos.type_of_piece_on(t1) == BISHOP) {
2242 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2245 else if(pos.type_of_piece_on(t1) == ROOK) {
2246 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2250 assert(pos.type_of_piece_on(t1) == QUEEN);
2251 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2260 // value_is_mate() checks if the given value is a mate one
2261 // eventually compensated for the ply.
2263 bool value_is_mate(Value value) {
2265 assert(abs(value) <= VALUE_INFINITE);
2267 return value <= value_mated_in(PLY_MAX)
2268 || value >= value_mate_in(PLY_MAX);
2272 // move_is_killer() checks if the given move is among the
2273 // killer moves of that ply.
2275 bool move_is_killer(Move m, const SearchStack& ss) {
2277 const Move* k = ss.killers;
2278 for (int i = 0; i < KILLER_MAX; i++, k++)
2286 // extension() decides whether a move should be searched with normal depth,
2287 // or with extended depth. Certain classes of moves (checking moves, in
2288 // particular) are searched with bigger depth than ordinary moves and in
2289 // any case are marked as 'dangerous'. Note that also if a move is not
2290 // extended, as example because the corresponding UCI option is set to zero,
2291 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2293 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2294 bool singleReply, bool mateThreat, bool* dangerous) {
2296 assert(m != MOVE_NONE);
2298 Depth result = Depth(0);
2299 *dangerous = check || singleReply || mateThreat;
2302 result += CheckExtension[pvNode];
2305 result += SingleReplyExtension[pvNode];
2308 result += MateThreatExtension[pvNode];
2310 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2312 if (pos.move_is_pawn_push_to_7th(m))
2314 result += PawnPushTo7thExtension[pvNode];
2317 if (pos.move_is_passed_pawn_push(m))
2319 result += PassedPawnExtension[pvNode];
2325 && pos.type_of_piece_on(move_to(m)) != PAWN
2326 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2327 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2328 && !move_promotion(m)
2331 result += PawnEndgameExtension[pvNode];
2337 && pos.type_of_piece_on(move_to(m)) != PAWN
2344 return Min(result, OnePly);
2348 // ok_to_do_nullmove() looks at the current position and decides whether
2349 // doing a 'null move' should be allowed. In order to avoid zugzwang
2350 // problems, null moves are not allowed when the side to move has very
2351 // little material left. Currently, the test is a bit too simple: Null
2352 // moves are avoided only when the side to move has only pawns left. It's
2353 // probably a good idea to avoid null moves in at least some more
2354 // complicated endgames, e.g. KQ vs KR. FIXME
2356 bool ok_to_do_nullmove(const Position &pos) {
2357 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2363 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2364 // non-tactical moves late in the move list close to the leaves are
2365 // candidates for pruning.
2367 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2368 Square mfrom, mto, tfrom, tto;
2370 assert(move_is_ok(m));
2371 assert(threat == MOVE_NONE || move_is_ok(threat));
2372 assert(!move_promotion(m));
2373 assert(!pos.move_is_check(m));
2374 assert(!pos.move_is_capture(m));
2375 assert(!pos.move_is_passed_pawn_push(m));
2376 assert(d >= OnePly);
2378 mfrom = move_from(m);
2380 tfrom = move_from(threat);
2381 tto = move_to(threat);
2383 // Case 1: Castling moves are never pruned.
2384 if (move_is_castle(m))
2387 // Case 2: Don't prune moves which move the threatened piece
2388 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2391 // Case 3: If the threatened piece has value less than or equal to the
2392 // value of the threatening piece, don't prune move which defend it.
2393 if ( !PruneDefendingMoves
2394 && threat != MOVE_NONE
2395 && pos.move_is_capture(threat)
2396 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2397 || pos.type_of_piece_on(tfrom) == KING)
2398 && pos.move_attacks_square(m, tto))
2401 // Case 4: Don't prune moves with good history.
2402 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2405 // Case 5: If the moving piece in the threatened move is a slider, don't
2406 // prune safe moves which block its ray.
2407 if ( !PruneBlockingMoves
2408 && threat != MOVE_NONE
2409 && piece_is_slider(pos.piece_on(tfrom))
2410 && bit_is_set(squares_between(tfrom, tto), mto)
2418 // ok_to_use_TT() returns true if a transposition table score
2419 // can be used at a given point in search.
2421 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2423 Value v = value_from_tt(tte->value(), ply);
2425 return ( tte->depth() >= depth
2426 || v >= Max(value_mate_in(100), beta)
2427 || v < Min(value_mated_in(100), beta))
2429 && ( (is_lower_bound(tte->type()) && v >= beta)
2430 || (is_upper_bound(tte->type()) && v < beta));
2434 // ok_to_history() returns true if a move m can be stored
2435 // in history. Should be a non capturing move nor a promotion.
2437 bool ok_to_history(const Position& pos, Move m) {
2439 return !pos.move_is_capture(m) && !move_promotion(m);
2443 // update_history() registers a good move that produced a beta-cutoff
2444 // in history and marks as failures all the other moves of that ply.
2446 void update_history(const Position& pos, Move m, Depth depth,
2447 Move movesSearched[], int moveCount) {
2449 H.success(pos.piece_on(move_from(m)), m, depth);
2451 for (int i = 0; i < moveCount - 1; i++)
2453 assert(m != movesSearched[i]);
2454 if (ok_to_history(pos, movesSearched[i]))
2455 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2460 // update_killers() add a good move that produced a beta-cutoff
2461 // among the killer moves of that ply.
2463 void update_killers(Move m, SearchStack& ss) {
2465 if (m == ss.killers[0])
2468 for (int i = KILLER_MAX - 1; i > 0; i--)
2469 ss.killers[i] = ss.killers[i - 1];
2474 // fail_high_ply_1() checks if some thread is currently resolving a fail
2475 // high at ply 1 at the node below the first root node. This information
2476 // is used for time managment.
2478 bool fail_high_ply_1() {
2479 for(int i = 0; i < ActiveThreads; i++)
2480 if(Threads[i].failHighPly1)
2485 bool aspiration_fail_high_ply_1() {
2486 for(int i = 0; i < ActiveThreads; i++)
2487 if(Threads[i].aspirationFailHighPly1)
2493 // current_search_time() returns the number of milliseconds which have passed
2494 // since the beginning of the current search.
2496 int current_search_time() {
2497 return get_system_time() - SearchStartTime;
2501 // nps() computes the current nodes/second count.
2504 int t = current_search_time();
2505 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2509 // poll() performs two different functions: It polls for user input, and it
2510 // looks at the time consumed so far and decides if it's time to abort the
2515 static int lastInfoTime;
2516 int t = current_search_time();
2521 // We are line oriented, don't read single chars
2522 std::string command;
2523 if (!std::getline(std::cin, command))
2526 if (command == "quit")
2529 PonderSearch = false;
2532 else if(command == "stop")
2535 PonderSearch = false;
2537 else if(command == "ponderhit")
2540 // Print search information
2544 else if (lastInfoTime > t)
2545 // HACK: Must be a new search where we searched less than
2546 // NodesBetweenPolls nodes during the first second of search.
2549 else if (t - lastInfoTime >= 1000)
2556 if (dbg_show_hit_rate)
2557 dbg_print_hit_rate();
2559 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2560 << " time " << t << " hashfull " << TT.full() << std::endl;
2561 lock_release(&IOLock);
2562 if (ShowCurrentLine)
2563 Threads[0].printCurrentLine = true;
2565 // Should we stop the search?
2569 bool overTime = t > AbsoluteMaxSearchTime
2570 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow && !aspiration_fail_high_ply_1())
2571 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !aspiration_fail_high_ply_1() && !Problem
2572 && t > 6*(MaxSearchTime + ExtraSearchTime));
2574 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2575 || (ExactMaxTime && t >= ExactMaxTime)
2576 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2581 // ponderhit() is called when the program is pondering (i.e. thinking while
2582 // it's the opponent's turn to move) in order to let the engine know that
2583 // it correctly predicted the opponent's move.
2586 int t = current_search_time();
2587 PonderSearch = false;
2588 if(Iteration >= 3 &&
2589 (!InfiniteSearch && (StopOnPonderhit ||
2590 t > AbsoluteMaxSearchTime ||
2591 (RootMoveNumber == 1 &&
2592 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2593 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2594 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2599 // print_current_line() prints the current line of search for a given
2600 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2602 void print_current_line(SearchStack ss[], int ply, int threadID) {
2603 assert(ply >= 0 && ply < PLY_MAX);
2604 assert(threadID >= 0 && threadID < ActiveThreads);
2606 if(!Threads[threadID].idle) {
2608 std::cout << "info currline " << (threadID + 1);
2609 for(int p = 0; p < ply; p++)
2610 std::cout << " " << ss[p].currentMove;
2611 std::cout << std::endl;
2612 lock_release(&IOLock);
2614 Threads[threadID].printCurrentLine = false;
2615 if(threadID + 1 < ActiveThreads)
2616 Threads[threadID + 1].printCurrentLine = true;
2620 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2621 // while the program is pondering. The point is to work around a wrinkle in
2622 // the UCI protocol: When pondering, the engine is not allowed to give a
2623 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2624 // We simply wait here until one of these commands is sent, and return,
2625 // after which the bestmove and pondermove will be printed (in id_loop()).
2627 void wait_for_stop_or_ponderhit() {
2628 std::string command;
2631 if(!std::getline(std::cin, command))
2634 if(command == "quit") {
2635 OpeningBook.close();
2640 else if(command == "ponderhit" || command == "stop")
2646 // idle_loop() is where the threads are parked when they have no work to do.
2647 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2648 // object for which the current thread is the master.
2650 void idle_loop(int threadID, SplitPoint *waitSp) {
2651 assert(threadID >= 0 && threadID < THREAD_MAX);
2653 Threads[threadID].running = true;
2656 if(AllThreadsShouldExit && threadID != 0)
2659 // If we are not thinking, wait for a condition to be signaled instead
2660 // of wasting CPU time polling for work:
2661 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2662 #if !defined(_MSC_VER)
2663 pthread_mutex_lock(&WaitLock);
2664 if(Idle || threadID >= ActiveThreads)
2665 pthread_cond_wait(&WaitCond, &WaitLock);
2666 pthread_mutex_unlock(&WaitLock);
2668 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2672 // If this thread has been assigned work, launch a search:
2673 if(Threads[threadID].workIsWaiting) {
2674 Threads[threadID].workIsWaiting = false;
2675 if(Threads[threadID].splitPoint->pvNode)
2676 sp_search_pv(Threads[threadID].splitPoint, threadID);
2678 sp_search(Threads[threadID].splitPoint, threadID);
2679 Threads[threadID].idle = true;
2682 // If this thread is the master of a split point and all threads have
2683 // finished their work at this split point, return from the idle loop:
2684 if(waitSp != NULL && waitSp->cpus == 0)
2688 Threads[threadID].running = false;
2692 // init_split_point_stack() is called during program initialization, and
2693 // initializes all split point objects.
2695 void init_split_point_stack() {
2696 for(int i = 0; i < THREAD_MAX; i++)
2697 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2698 SplitPointStack[i][j].parent = NULL;
2699 lock_init(&(SplitPointStack[i][j].lock), NULL);
2704 // destroy_split_point_stack() is called when the program exits, and
2705 // destroys all locks in the precomputed split point objects.
2707 void destroy_split_point_stack() {
2708 for(int i = 0; i < THREAD_MAX; i++)
2709 for(int j = 0; j < MaxActiveSplitPoints; j++)
2710 lock_destroy(&(SplitPointStack[i][j].lock));
2714 // thread_should_stop() checks whether the thread with a given threadID has
2715 // been asked to stop, directly or indirectly. This can happen if a beta
2716 // cutoff has occured in thre thread's currently active split point, or in
2717 // some ancestor of the current split point.
2719 bool thread_should_stop(int threadID) {
2720 assert(threadID >= 0 && threadID < ActiveThreads);
2724 if(Threads[threadID].stop)
2726 if(ActiveThreads <= 2)
2728 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2730 Threads[threadID].stop = true;
2737 // thread_is_available() checks whether the thread with threadID "slave" is
2738 // available to help the thread with threadID "master" at a split point. An
2739 // obvious requirement is that "slave" must be idle. With more than two
2740 // threads, this is not by itself sufficient: If "slave" is the master of
2741 // some active split point, it is only available as a slave to the other
2742 // threads which are busy searching the split point at the top of "slave"'s
2743 // split point stack (the "helpful master concept" in YBWC terminology).
2745 bool thread_is_available(int slave, int master) {
2746 assert(slave >= 0 && slave < ActiveThreads);
2747 assert(master >= 0 && master < ActiveThreads);
2748 assert(ActiveThreads > 1);
2750 if(!Threads[slave].idle || slave == master)
2753 if(Threads[slave].activeSplitPoints == 0)
2754 // No active split points means that the thread is available as a slave
2755 // for any other thread.
2758 if(ActiveThreads == 2)
2761 // Apply the "helpful master" concept if possible.
2762 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2769 // idle_thread_exists() tries to find an idle thread which is available as
2770 // a slave for the thread with threadID "master".
2772 bool idle_thread_exists(int master) {
2773 assert(master >= 0 && master < ActiveThreads);
2774 assert(ActiveThreads > 1);
2776 for(int i = 0; i < ActiveThreads; i++)
2777 if(thread_is_available(i, master))
2783 // split() does the actual work of distributing the work at a node between
2784 // several threads at PV nodes. If it does not succeed in splitting the
2785 // node (because no idle threads are available, or because we have no unused
2786 // split point objects), the function immediately returns false. If
2787 // splitting is possible, a SplitPoint object is initialized with all the
2788 // data that must be copied to the helper threads (the current position and
2789 // search stack, alpha, beta, the search depth, etc.), and we tell our
2790 // helper threads that they have been assigned work. This will cause them
2791 // to instantly leave their idle loops and call sp_search_pv(). When all
2792 // threads have returned from sp_search_pv (or, equivalently, when
2793 // splitPoint->cpus becomes 0), split() returns true.
2795 bool split(const Position &p, SearchStack *sstck, int ply,
2796 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2797 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2800 assert(sstck != NULL);
2801 assert(ply >= 0 && ply < PLY_MAX);
2802 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2803 assert(!pvNode || *alpha < *beta);
2804 assert(*beta <= VALUE_INFINITE);
2805 assert(depth > Depth(0));
2806 assert(master >= 0 && master < ActiveThreads);
2807 assert(ActiveThreads > 1);
2809 SplitPoint *splitPoint;
2814 // If no other thread is available to help us, or if we have too many
2815 // active split points, don't split:
2816 if(!idle_thread_exists(master) ||
2817 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2818 lock_release(&MPLock);
2822 // Pick the next available split point object from the split point stack:
2823 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2824 Threads[master].activeSplitPoints++;
2826 // Initialize the split point object:
2827 splitPoint->parent = Threads[master].splitPoint;
2828 splitPoint->finished = false;
2829 splitPoint->ply = ply;
2830 splitPoint->depth = depth;
2831 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2832 splitPoint->beta = *beta;
2833 splitPoint->pvNode = pvNode;
2834 splitPoint->dcCandidates = dcCandidates;
2835 splitPoint->bestValue = *bestValue;
2836 splitPoint->master = master;
2837 splitPoint->mp = mp;
2838 splitPoint->moves = *moves;
2839 splitPoint->cpus = 1;
2840 splitPoint->pos.copy(p);
2841 splitPoint->parentSstack = sstck;
2842 for(i = 0; i < ActiveThreads; i++)
2843 splitPoint->slaves[i] = 0;
2845 // Copy the current position and the search stack to the master thread:
2846 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2847 Threads[master].splitPoint = splitPoint;
2849 // Make copies of the current position and search stack for each thread:
2850 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2852 if(thread_is_available(i, master)) {
2853 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2854 Threads[i].splitPoint = splitPoint;
2855 splitPoint->slaves[i] = 1;
2859 // Tell the threads that they have work to do. This will make them leave
2861 for(i = 0; i < ActiveThreads; i++)
2862 if(i == master || splitPoint->slaves[i]) {
2863 Threads[i].workIsWaiting = true;
2864 Threads[i].idle = false;
2865 Threads[i].stop = false;
2868 lock_release(&MPLock);
2870 // Everything is set up. The master thread enters the idle loop, from
2871 // which it will instantly launch a search, because its workIsWaiting
2872 // slot is 'true'. We send the split point as a second parameter to the
2873 // idle loop, which means that the main thread will return from the idle
2874 // loop when all threads have finished their work at this split point
2875 // (i.e. when // splitPoint->cpus == 0).
2876 idle_loop(master, splitPoint);
2878 // We have returned from the idle loop, which means that all threads are
2879 // finished. Update alpha, beta and bestvalue, and return:
2881 if(pvNode) *alpha = splitPoint->alpha;
2882 *beta = splitPoint->beta;
2883 *bestValue = splitPoint->bestValue;
2884 Threads[master].stop = false;
2885 Threads[master].idle = false;
2886 Threads[master].activeSplitPoints--;
2887 Threads[master].splitPoint = splitPoint->parent;
2888 lock_release(&MPLock);
2894 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2895 // to start a new search from the root.
2897 void wake_sleeping_threads() {
2898 if(ActiveThreads > 1) {
2899 for(int i = 1; i < ActiveThreads; i++) {
2900 Threads[i].idle = true;
2901 Threads[i].workIsWaiting = false;
2903 #if !defined(_MSC_VER)
2904 pthread_mutex_lock(&WaitLock);
2905 pthread_cond_broadcast(&WaitCond);
2906 pthread_mutex_unlock(&WaitLock);
2908 for(int i = 1; i < THREAD_MAX; i++)
2909 SetEvent(SitIdleEvent[i]);
2915 // init_thread() is the function which is called when a new thread is
2916 // launched. It simply calls the idle_loop() function with the supplied
2917 // threadID. There are two versions of this function; one for POSIX threads
2918 // and one for Windows threads.
2920 #if !defined(_MSC_VER)
2922 void *init_thread(void *threadID) {
2923 idle_loop(*(int *)threadID, NULL);
2929 DWORD WINAPI init_thread(LPVOID threadID) {
2930 idle_loop(*(int *)threadID, NULL);