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 int current_search_time();
333 void print_current_line(SearchStack ss[], int ply, int threadID);
334 void wait_for_stop_or_ponderhit();
336 void idle_loop(int threadID, SplitPoint *waitSp);
337 void init_split_point_stack();
338 void destroy_split_point_stack();
339 bool thread_should_stop(int threadID);
340 bool thread_is_available(int slave, int master);
341 bool idle_thread_exists(int master);
342 bool split(const Position &pos, SearchStack *ss, int ply,
343 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
344 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
345 void wake_sleeping_threads();
347 #if !defined(_MSC_VER)
348 void *init_thread(void *threadID);
350 DWORD WINAPI init_thread(LPVOID threadID);
357 //// Global variables
360 // The main transposition table
361 TranspositionTable TT = TranspositionTable(TTDefaultSize);
364 // Number of active threads:
365 int ActiveThreads = 1;
367 // Locks. In principle, there is no need for IOLock to be a global variable,
368 // but it could turn out to be useful for debugging.
371 History H; // Should be made local?
373 // The empty search stack
374 SearchStack EmptySearchStack;
377 // SearchStack::init() initializes a search stack. Used at the beginning of a
378 // new search from the root.
379 void SearchStack::init(int ply) {
381 pv[ply] = pv[ply + 1] = MOVE_NONE;
382 currentMove = threatMove = MOVE_NONE;
383 reduction = Depth(0);
386 void SearchStack::initKillers() {
388 mateKiller = MOVE_NONE;
389 for (int i = 0; i < KILLER_MAX; i++)
390 killers[i] = MOVE_NONE;
398 /// think() is the external interface to Stockfish's search, and is called when
399 /// the program receives the UCI 'go' command. It initializes various
400 /// search-related global variables, and calls root_search()
402 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
403 int time[], int increment[], int movesToGo, int maxDepth,
404 int maxNodes, int maxTime, Move searchMoves[]) {
406 // Look for a book move
407 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
410 if (get_option_value_string("Book File") != OpeningBook.file_name())
413 OpeningBook.open("book.bin");
415 bookMove = OpeningBook.get_move(pos);
416 if (bookMove != MOVE_NONE)
418 std::cout << "bestmove " << bookMove << std::endl;
423 // Initialize global search variables
425 SearchStartTime = get_system_time();
426 EasyMove = MOVE_NONE;
427 for (int i = 0; i < THREAD_MAX; i++)
429 Threads[i].nodes = 0ULL;
430 Threads[i].failHighPly1 = false;
433 InfiniteSearch = infinite;
434 PonderSearch = ponder;
435 StopOnPonderhit = false;
441 ExactMaxTime = maxTime;
443 // Read UCI option values
444 TT.set_size(get_option_value_int("Hash"));
445 if (button_was_pressed("Clear Hash"))
448 PonderingEnabled = get_option_value_bool("Ponder");
449 MultiPV = get_option_value_int("MultiPV");
451 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
452 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
454 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
455 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
457 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
458 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
460 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
461 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
463 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
464 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
466 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
467 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
469 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
470 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
471 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
472 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
474 Chess960 = get_option_value_bool("UCI_Chess960");
475 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
476 UseLogFile = get_option_value_bool("Use Search Log");
478 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
480 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
481 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
483 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
484 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
485 for (int i = 0; i < 6; i++)
486 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
488 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
489 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
491 UseLSNFiltering = get_option_value_bool("LSN filtering");
492 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
493 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
495 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
496 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
498 read_weights(pos.side_to_move());
500 int newActiveThreads = get_option_value_int("Threads");
501 if (newActiveThreads != ActiveThreads)
503 ActiveThreads = newActiveThreads;
504 init_eval(ActiveThreads);
507 // Wake up sleeping threads:
508 wake_sleeping_threads();
510 for (int i = 1; i < ActiveThreads; i++)
511 assert(thread_is_available(i, 0));
513 // Set thinking time:
514 int myTime = time[side_to_move];
515 int myIncrement = increment[side_to_move];
517 if (!movesToGo) // Sudden death time control
521 MaxSearchTime = myTime / 30 + myIncrement;
522 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
523 } else { // Blitz game without increment
524 MaxSearchTime = myTime / 30;
525 AbsoluteMaxSearchTime = myTime / 8;
528 else // (x moves) / (y minutes)
532 MaxSearchTime = myTime / 2;
533 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
535 MaxSearchTime = myTime / Min(movesToGo, 20);
536 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
540 if (PonderingEnabled)
542 MaxSearchTime += MaxSearchTime / 4;
543 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
546 // Fixed depth or fixed number of nodes?
549 InfiniteSearch = true; // HACK
554 NodesBetweenPolls = Min(MaxNodes, 30000);
555 InfiniteSearch = true; // HACK
558 NodesBetweenPolls = 30000;
561 // Write information to search log file:
563 LogFile << "Searching: " << pos.to_fen() << std::endl
564 << "infinite: " << infinite
565 << " ponder: " << ponder
566 << " time: " << myTime
567 << " increment: " << myIncrement
568 << " moves to go: " << movesToGo << std::endl;
571 // We're ready to start thinking. Call the iterative deepening loop
575 Value v = id_loop(pos, searchMoves);
576 looseOnTime = ( UseLSNFiltering
583 looseOnTime = false; // reset for next match
584 while (SearchStartTime + myTime + 1000 > get_system_time())
586 id_loop(pos, searchMoves); // to fail gracefully
603 /// init_threads() is called during startup. It launches all helper threads,
604 /// and initializes the split point stack and the global locks and condition
607 void init_threads() {
611 #if !defined(_MSC_VER)
612 pthread_t pthread[1];
615 for (i = 0; i < THREAD_MAX; i++)
616 Threads[i].activeSplitPoints = 0;
618 // Initialize global locks:
619 lock_init(&MPLock, NULL);
620 lock_init(&IOLock, NULL);
622 init_split_point_stack();
624 #if !defined(_MSC_VER)
625 pthread_mutex_init(&WaitLock, NULL);
626 pthread_cond_init(&WaitCond, NULL);
628 for (i = 0; i < THREAD_MAX; i++)
629 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
632 // All threads except the main thread should be initialized to idle state
633 for (i = 1; i < THREAD_MAX; i++)
635 Threads[i].stop = false;
636 Threads[i].workIsWaiting = false;
637 Threads[i].idle = true;
638 Threads[i].running = false;
641 // Launch the helper threads
642 for(i = 1; i < THREAD_MAX; i++)
644 #if !defined(_MSC_VER)
645 pthread_create(pthread, NULL, init_thread, (void*)(&i));
648 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
651 // Wait until the thread has finished launching:
652 while (!Threads[i].running);
655 // Init also the empty search stack
656 EmptySearchStack.init(0);
657 EmptySearchStack.initKillers();
661 /// stop_threads() is called when the program exits. It makes all the
662 /// helper threads exit cleanly.
664 void stop_threads() {
666 ActiveThreads = THREAD_MAX; // HACK
667 Idle = false; // HACK
668 wake_sleeping_threads();
669 AllThreadsShouldExit = true;
670 for (int i = 1; i < THREAD_MAX; i++)
672 Threads[i].stop = true;
673 while(Threads[i].running);
675 destroy_split_point_stack();
679 /// nodes_searched() returns the total number of nodes searched so far in
680 /// the current search.
682 int64_t nodes_searched() {
684 int64_t result = 0ULL;
685 for (int i = 0; i < ActiveThreads; i++)
686 result += Threads[i].nodes;
693 // id_loop() is the main iterative deepening loop. It calls root_search
694 // repeatedly with increasing depth until the allocated thinking time has
695 // been consumed, the user stops the search, or the maximum search depth is
698 Value id_loop(const Position &pos, Move searchMoves[]) {
701 SearchStack ss[PLY_MAX_PLUS_2];
703 // searchMoves are verified, copied, scored and sorted
704 RootMoveList rml(p, searchMoves);
709 for (int i = 0; i < 3; i++)
714 IterationInfo[1].set(rml.get_move_score(0));
717 EasyMove = rml.scan_for_easy_move();
719 // Iterative deepening loop
720 while (Iteration < PLY_MAX)
722 // Initialize iteration
725 BestMoveChangesByIteration[Iteration] = 0;
729 std::cout << "info depth " << Iteration << std::endl;
731 //Calculate dynamic search window based on previous iterations.
735 if (MultiPV == 1 && Iteration >= 6) {
736 Value prevDelta1 = IterationInfo[Iteration - 1].speculated_value() - IterationInfo[Iteration - 2].speculated_value();
737 Value prevDelta2 = IterationInfo[Iteration - 2].speculated_value() - IterationInfo[Iteration - 3].speculated_value();
739 Value delta = Max((2 * Abs(prevDelta1) + Abs(prevDelta2)) , ProblemMargin);
741 alpha = IterationInfo[Iteration - 1].value() - delta;
742 beta = IterationInfo[Iteration - 1].value() + delta;
743 if (alpha < - VALUE_INFINITE) alpha = - VALUE_INFINITE;
744 if (beta > VALUE_INFINITE) beta = VALUE_INFINITE;
747 alpha = - VALUE_INFINITE;
748 beta = VALUE_INFINITE;
751 // Search to the current depth
752 Value value = root_search(p, ss, rml, alpha, beta);
754 break; //Value cannot be trusted. Break out immediately!
756 // Write PV to transposition table, in case the relevant entries have
757 // been overwritten during the search:
758 TT.insert_pv(p, ss[0].pv);
760 //Save info about search result
761 Value speculated_value = value;
765 Value prev_value = IterationInfo[Iteration - 1].value();
766 Value delta = value - prev_value;
770 speculated_value = prev_value + 2 * delta;
771 BestMoveChangesByIteration[Iteration] += 2; //This is used to tell time management to allocate more time
772 } else if (value <= alpha) {
774 speculated_value = prev_value + 2 * delta;
775 BestMoveChangesByIteration[Iteration] += 3; //This is used to tell time management to allocate more time
780 if (speculated_value < - VALUE_INFINITE) speculated_value = - VALUE_INFINITE;
781 if (speculated_value > VALUE_INFINITE) speculated_value = VALUE_INFINITE;
783 IterationInfo[Iteration].set(value, speculated_value, fHigh, fLow);
785 // Erase the easy move if it differs from the new best move
786 if (ss[0].pv[0] != EasyMove)
787 EasyMove = MOVE_NONE;
794 bool stopSearch = false;
796 // Stop search early if there is only a single legal move:
797 if (Iteration >= 6 && rml.move_count() == 1)
800 // Stop search early when the last two iterations returned a mate score
802 && abs(IterationInfo[Iteration].value()) >= abs(VALUE_MATE) - 100
803 && abs(IterationInfo[Iteration-1].value()) >= abs(VALUE_MATE) - 100)
806 // Stop search early if one move seems to be much better than the rest
807 int64_t nodes = nodes_searched();
808 if ( Iteration >= 8 && !fLow && !fHigh
809 && EasyMove == ss[0].pv[0]
810 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
811 && current_search_time() > MaxSearchTime / 16)
812 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
813 && current_search_time() > MaxSearchTime / 32)))
816 // Add some extra time if the best move has changed during the last two iterations
817 if (Iteration > 5 && Iteration <= 50)
818 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
819 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
821 // Stop search if most of MaxSearchTime is consumed at the end of the
822 // iteration. We probably don't have enough time to search the first
823 // move at the next iteration anyway.
824 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
829 //FIXME: Implement fail-low emergency measures
833 StopOnPonderhit = true;
837 if (MaxDepth && Iteration >= MaxDepth)
843 // If we are pondering, we shouldn't print the best move before we
846 wait_for_stop_or_ponderhit();
848 // Print final search statistics
849 std::cout << "info nodes " << nodes_searched()
851 << " time " << current_search_time()
852 << " hashfull " << TT.full() << std::endl;
854 // Print the best move and the ponder move to the standard output
855 if (ss[0].pv[0] == MOVE_NONE)
857 ss[0].pv[0] = rml.get_move(0);
858 ss[0].pv[1] = MOVE_NONE;
860 std::cout << "bestmove " << ss[0].pv[0];
861 if (ss[0].pv[1] != MOVE_NONE)
862 std::cout << " ponder " << ss[0].pv[1];
864 std::cout << std::endl;
869 dbg_print_mean(LogFile);
871 if (dbg_show_hit_rate)
872 dbg_print_hit_rate(LogFile);
875 LogFile << "Nodes: " << nodes_searched() << std::endl
876 << "Nodes/second: " << nps() << std::endl
877 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
879 p.do_move(ss[0].pv[0], st);
880 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
881 << std::endl << std::endl;
883 return rml.get_move_score(0);
887 // root_search() is the function which searches the root node. It is
888 // similar to search_pv except that it uses a different move ordering
889 // scheme (perhaps we should try to use this at internal PV nodes, too?)
890 // and prints some information to the standard output.
892 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
894 //FIXME: Implement bestValue
895 Value oldAlpha = alpha;
897 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
899 // Loop through all the moves in the root move list
900 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
903 rml.set_move_score(i, -VALUE_INFINITE);
904 //Leave node-counters and beta-counters as they are.
913 RootMoveNumber = i + 1;
916 // Remember the node count before the move is searched. The node counts
917 // are used to sort the root moves at the next iteration.
918 nodes = nodes_searched();
920 // Reset beta cut-off counters
923 // Pick the next root move, and print the move and the move number to
924 // the standard output.
925 move = ss[0].currentMove = rml.get_move(i);
926 if (current_search_time() >= 1000)
927 std::cout << "info currmove " << move
928 << " currmovenumber " << i + 1 << std::endl;
930 // Decide search depth for this move
932 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
933 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
935 // Make the move, and search it
936 pos.do_move(move, st, dcCandidates);
940 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
941 // If the value has dropped a lot compared to the last iteration,
942 // set the boolean variable Problem to true. This variable is used
943 // for time managment: When Problem is true, we try to complete the
944 // current iteration before playing a move.
945 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value() - ProblemMargin);
947 if (Problem && StopOnPonderhit)
948 StopOnPonderhit = false;
952 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
955 // Fail high! Set the boolean variable FailHigh to true, and
956 // re-search the move with a big window. The variable FailHigh is
957 // used for time managment: We try to avoid aborting the search
958 // prematurely during a fail high research.
960 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
966 // Finished searching the move. If AbortSearch is true, the search
967 // was aborted because the user interrupted the search or because we
968 // ran out of time. In this case, the return value of the search cannot
969 // be trusted, and we break out of the loop without updating the best
974 // Remember the node count for this move. The node counts are used to
975 // sort the root moves at the next iteration.
976 rml.set_move_nodes(i, nodes_searched() - nodes);
978 // Remember the beta-cutoff statistics
980 BetaCounter.read(pos.side_to_move(), our, their);
981 rml.set_beta_counters(i, our, their);
983 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
985 if (value <= alpha && i >= MultiPV)
986 rml.set_move_score(i, -VALUE_INFINITE);
992 rml.set_move_score(i, value);
994 rml.set_move_pv(i, ss[0].pv);
998 // We record how often the best move has been changed in each
999 // iteration. This information is used for time managment: When
1000 // the best move changes frequently, we allocate some more time.
1002 BestMoveChangesByIteration[Iteration]++;
1004 // Print search information to the standard output:
1005 std::cout << "info depth " << Iteration
1006 << " score " << value_to_string(value)
1007 << " time " << current_search_time()
1008 << " nodes " << nodes_searched()
1012 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1013 std::cout << ss[0].pv[j] << " ";
1015 std::cout << std::endl;
1018 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
1024 // Reset the global variable Problem to false if the value isn't too
1025 // far below the final value from the last iteration.
1026 if (value > IterationInfo[Iteration - 1].value() - NoProblemMargin)
1031 rml.sort_multipv(i);
1032 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1035 std::cout << "info multipv " << j + 1
1036 << " score " << value_to_string(rml.get_move_score(j))
1037 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1038 << " time " << current_search_time()
1039 << " nodes " << nodes_searched()
1043 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1044 std::cout << rml.get_move_pv(j, k) << " ";
1046 std::cout << std::endl;
1048 alpha = rml.get_move_score(Min(i, MultiPV-1));
1052 if (alpha <= oldAlpha)
1062 // search_pv() is the main search function for PV nodes.
1064 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1065 Depth depth, int ply, int threadID) {
1067 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1068 assert(beta > alpha && beta <= VALUE_INFINITE);
1069 assert(ply >= 0 && ply < PLY_MAX);
1070 assert(threadID >= 0 && threadID < ActiveThreads);
1073 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1075 // Initialize, and make an early exit in case of an aborted search,
1076 // an instant draw, maximum ply reached, etc.
1077 init_node(ss, ply, threadID);
1079 // After init_node() that calls poll()
1080 if (AbortSearch || thread_should_stop(threadID))
1088 if (ply >= PLY_MAX - 1)
1089 return evaluate(pos, ei, threadID);
1091 // Mate distance pruning
1092 Value oldAlpha = alpha;
1093 alpha = Max(value_mated_in(ply), alpha);
1094 beta = Min(value_mate_in(ply+1), beta);
1098 // Transposition table lookup. At PV nodes, we don't use the TT for
1099 // pruning, but only for move ordering.
1100 const TTEntry* tte = TT.retrieve(pos);
1101 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1103 // Go with internal iterative deepening if we don't have a TT move
1104 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1106 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1107 ttMove = ss[ply].pv[ply];
1110 // Initialize a MovePicker object for the current position, and prepare
1111 // to search all moves
1112 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1114 Move move, movesSearched[256];
1116 Value value, bestValue = -VALUE_INFINITE;
1117 Bitboard dcCandidates = mp.discovered_check_candidates();
1118 Color us = pos.side_to_move();
1119 bool isCheck = pos.is_check();
1120 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1122 // Loop through all legal moves until no moves remain or a beta cutoff
1124 while ( alpha < beta
1125 && (move = mp.get_next_move()) != MOVE_NONE
1126 && !thread_should_stop(threadID))
1128 assert(move_is_ok(move));
1130 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1131 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1132 bool moveIsCapture = pos.move_is_capture(move);
1134 movesSearched[moveCount++] = ss[ply].currentMove = move;
1136 // Decide the new search depth
1138 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1139 Depth newDepth = depth - OnePly + ext;
1141 // Make and search the move
1143 pos.do_move(move, st, dcCandidates);
1145 if (moveCount == 1) // The first move in list is the PV
1146 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1149 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1150 // if the move fails high will be re-searched at full depth.
1151 if ( depth >= 2*OnePly
1152 && moveCount >= LMRPVMoves
1155 && !move_promotion(move)
1156 && !move_is_castle(move)
1157 && !move_is_killer(move, ss[ply]))
1159 ss[ply].reduction = OnePly;
1160 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1163 value = alpha + 1; // Just to trigger next condition
1165 if (value > alpha) // Go with full depth non-pv search
1167 ss[ply].reduction = Depth(0);
1168 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1169 if (value > alpha && value < beta)
1171 // When the search fails high at ply 1 while searching the first
1172 // move at the root, set the flag failHighPly1. This is used for
1173 // time managment: We don't want to stop the search early in
1174 // such cases, because resolving the fail high at ply 1 could
1175 // result in a big drop in score at the root.
1176 if (ply == 1 && RootMoveNumber == 1)
1177 Threads[threadID].failHighPly1 = true;
1179 // A fail high occurred. Re-search at full window (pv search)
1180 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1181 Threads[threadID].failHighPly1 = false;
1185 pos.undo_move(move);
1187 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1190 if (value > bestValue)
1197 if (value == value_mate_in(ply + 1))
1198 ss[ply].mateKiller = move;
1200 // If we are at ply 1, and we are searching the first root move at
1201 // ply 0, set the 'Problem' variable if the score has dropped a lot
1202 // (from the computer's point of view) since the previous iteration:
1205 && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1210 if ( ActiveThreads > 1
1212 && depth >= MinimumSplitDepth
1214 && idle_thread_exists(threadID)
1216 && !thread_should_stop(threadID)
1217 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1218 &moveCount, &mp, dcCandidates, threadID, true))
1222 // All legal moves have been searched. A special case: If there were
1223 // no legal moves, it must be mate or stalemate:
1225 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1227 // If the search is not aborted, update the transposition table,
1228 // history counters, and killer moves.
1229 if (AbortSearch || thread_should_stop(threadID))
1232 if (bestValue <= oldAlpha)
1233 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1235 else if (bestValue >= beta)
1237 BetaCounter.add(pos.side_to_move(), depth, threadID);
1238 Move m = ss[ply].pv[ply];
1239 if (ok_to_history(pos, m)) // Only non capture moves are considered
1241 update_history(pos, m, depth, movesSearched, moveCount);
1242 update_killers(m, ss[ply]);
1244 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1247 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1253 // search() is the search function for zero-width nodes.
1255 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1256 int ply, bool allowNullmove, int threadID) {
1258 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1259 assert(ply >= 0 && ply < PLY_MAX);
1260 assert(threadID >= 0 && threadID < ActiveThreads);
1263 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1265 // Initialize, and make an early exit in case of an aborted search,
1266 // an instant draw, maximum ply reached, etc.
1267 init_node(ss, ply, threadID);
1269 // After init_node() that calls poll()
1270 if (AbortSearch || thread_should_stop(threadID))
1278 if (ply >= PLY_MAX - 1)
1279 return evaluate(pos, ei, threadID);
1281 // Mate distance pruning
1282 if (value_mated_in(ply) >= beta)
1285 if (value_mate_in(ply + 1) < beta)
1288 // Transposition table lookup
1289 const TTEntry* tte = TT.retrieve(pos);
1290 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1292 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1294 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1295 return value_from_tt(tte->value(), ply);
1298 Value approximateEval = quick_evaluate(pos);
1299 bool mateThreat = false;
1300 bool isCheck = pos.is_check();
1306 && !value_is_mate(beta)
1307 && ok_to_do_nullmove(pos)
1308 && approximateEval >= beta - NullMoveMargin)
1310 ss[ply].currentMove = MOVE_NULL;
1313 pos.do_null_move(st);
1314 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1316 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1318 pos.undo_null_move();
1320 if (value_is_mate(nullValue))
1322 /* Do not return unproven mates */
1324 else if (nullValue >= beta)
1326 if (depth < 6 * OnePly)
1329 // Do zugzwang verification search
1330 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1334 // The null move failed low, which means that we may be faced with
1335 // some kind of threat. If the previous move was reduced, check if
1336 // the move that refuted the null move was somehow connected to the
1337 // move which was reduced. If a connection is found, return a fail
1338 // low score (which will cause the reduced move to fail high in the
1339 // parent node, which will trigger a re-search with full depth).
1340 if (nullValue == value_mated_in(ply + 2))
1343 ss[ply].threatMove = ss[ply + 1].currentMove;
1344 if ( depth < ThreatDepth
1345 && ss[ply - 1].reduction
1346 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1350 // Null move search not allowed, try razoring
1351 else if ( !value_is_mate(beta)
1352 && approximateEval < beta - RazorMargin
1353 && depth < RazorDepth
1354 && (RazorAtDepthOne || depth > OnePly)
1355 && ttMove == MOVE_NONE
1356 && !pos.has_pawn_on_7th(pos.side_to_move()))
1358 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1359 if ( (v < beta - RazorMargin - RazorMargin / 4)
1360 || (depth <= 2*OnePly && v < beta - RazorMargin)
1361 || (depth <= OnePly && v < beta - RazorMargin / 2))
1365 // Go with internal iterative deepening if we don't have a TT move
1366 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1367 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1369 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1370 ttMove = ss[ply].pv[ply];
1373 // Initialize a MovePicker object for the current position, and prepare
1374 // to search all moves:
1375 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1377 Move move, movesSearched[256];
1379 Value value, bestValue = -VALUE_INFINITE;
1380 Bitboard dcCandidates = mp.discovered_check_candidates();
1381 Value futilityValue = VALUE_NONE;
1382 bool useFutilityPruning = UseFutilityPruning
1383 && depth < SelectiveDepth
1386 // Loop through all legal moves until no moves remain or a beta cutoff
1388 while ( bestValue < beta
1389 && (move = mp.get_next_move()) != MOVE_NONE
1390 && !thread_should_stop(threadID))
1392 assert(move_is_ok(move));
1394 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1395 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1396 bool moveIsCapture = pos.move_is_capture(move);
1398 movesSearched[moveCount++] = ss[ply].currentMove = move;
1400 // Decide the new search depth
1402 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1403 Depth newDepth = depth - OnePly + ext;
1406 if ( useFutilityPruning
1409 && !move_promotion(move))
1411 // History pruning. See ok_to_prune() definition
1412 if ( moveCount >= 2 + int(depth)
1413 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1416 // Value based pruning
1417 if (depth < 7 * OnePly && approximateEval < beta)
1419 if (futilityValue == VALUE_NONE)
1420 futilityValue = evaluate(pos, ei, threadID)
1421 + FutilityMargins[int(depth)/2 - 1]
1424 if (futilityValue < beta)
1426 if (futilityValue > bestValue)
1427 bestValue = futilityValue;
1433 // Make and search the move
1435 pos.do_move(move, st, dcCandidates);
1437 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1438 // if the move fails high will be re-searched at full depth.
1439 if ( depth >= 2*OnePly
1440 && moveCount >= LMRNonPVMoves
1443 && !move_promotion(move)
1444 && !move_is_castle(move)
1445 && !move_is_killer(move, ss[ply]))
1447 ss[ply].reduction = OnePly;
1448 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1451 value = beta; // Just to trigger next condition
1453 if (value >= beta) // Go with full depth non-pv search
1455 ss[ply].reduction = Depth(0);
1456 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1458 pos.undo_move(move);
1460 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1463 if (value > bestValue)
1469 if (value == value_mate_in(ply + 1))
1470 ss[ply].mateKiller = move;
1474 if ( ActiveThreads > 1
1476 && depth >= MinimumSplitDepth
1478 && idle_thread_exists(threadID)
1480 && !thread_should_stop(threadID)
1481 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1482 &mp, dcCandidates, threadID, false))
1486 // All legal moves have been searched. A special case: If there were
1487 // no legal moves, it must be mate or stalemate.
1489 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1491 // If the search is not aborted, update the transposition table,
1492 // history counters, and killer moves.
1493 if (AbortSearch || thread_should_stop(threadID))
1496 if (bestValue < beta)
1497 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1500 BetaCounter.add(pos.side_to_move(), depth, threadID);
1501 Move m = ss[ply].pv[ply];
1502 if (ok_to_history(pos, m)) // Only non capture moves are considered
1504 update_history(pos, m, depth, movesSearched, moveCount);
1505 update_killers(m, ss[ply]);
1507 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1510 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1516 // qsearch() is the quiescence search function, which is called by the main
1517 // search function when the remaining depth is zero (or, to be more precise,
1518 // less than OnePly).
1520 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1521 Depth depth, int ply, int threadID) {
1523 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1524 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1526 assert(ply >= 0 && ply < PLY_MAX);
1527 assert(threadID >= 0 && threadID < ActiveThreads);
1529 // Initialize, and make an early exit in case of an aborted search,
1530 // an instant draw, maximum ply reached, etc.
1531 init_node(ss, ply, threadID);
1533 // After init_node() that calls poll()
1534 if (AbortSearch || thread_should_stop(threadID))
1540 // Transposition table lookup, only when not in PV
1541 TTEntry* tte = NULL;
1542 bool pvNode = (beta - alpha != 1);
1545 tte = TT.retrieve(pos);
1546 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1548 assert(tte->type() != VALUE_TYPE_EVAL);
1550 return value_from_tt(tte->value(), ply);
1554 // Evaluate the position statically
1557 bool isCheck = pos.is_check();
1558 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1561 staticValue = -VALUE_INFINITE;
1563 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1565 // Use the cached evaluation score if possible
1566 assert(tte->value() == evaluate(pos, ei, threadID));
1567 assert(ei.futilityMargin == Value(0));
1569 staticValue = tte->value();
1572 staticValue = evaluate(pos, ei, threadID);
1574 if (ply == PLY_MAX - 1)
1575 return evaluate(pos, ei, threadID);
1577 // Initialize "stand pat score", and return it immediately if it is
1579 Value bestValue = staticValue;
1581 if (bestValue >= beta)
1583 // Store the score to avoid a future costly evaluation() call
1584 if (!isCheck && !tte && ei.futilityMargin == 0)
1585 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1590 if (bestValue > alpha)
1593 // Initialize a MovePicker object for the current position, and prepare
1594 // to search the moves. Because the depth is <= 0 here, only captures,
1595 // queen promotions and checks (only if depth == 0) will be generated.
1596 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth);
1599 Bitboard dcCandidates = mp.discovered_check_candidates();
1600 Color us = pos.side_to_move();
1601 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1603 // Loop through the moves until no moves remain or a beta cutoff
1605 while ( alpha < beta
1606 && (move = mp.get_next_move()) != MOVE_NONE)
1608 assert(move_is_ok(move));
1611 ss[ply].currentMove = move;
1614 if ( UseQSearchFutilityPruning
1618 && !move_promotion(move)
1619 && !pos.move_is_check(move, dcCandidates)
1620 && !pos.move_is_passed_pawn_push(move))
1622 Value futilityValue = staticValue
1623 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1624 pos.endgame_value_of_piece_on(move_to(move)))
1625 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1627 + ei.futilityMargin;
1629 if (futilityValue < alpha)
1631 if (futilityValue > bestValue)
1632 bestValue = futilityValue;
1637 // Don't search captures and checks with negative SEE values
1639 && !move_promotion(move)
1640 && (pos.midgame_value_of_piece_on(move_from(move)) >
1641 pos.midgame_value_of_piece_on(move_to(move)))
1642 && pos.see(move) < 0)
1645 // Make and search the move.
1647 pos.do_move(move, st, dcCandidates);
1648 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1649 pos.undo_move(move);
1651 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1654 if (value > bestValue)
1665 // All legal moves have been searched. A special case: If we're in check
1666 // and no legal moves were found, it is checkmate:
1667 if (pos.is_check() && moveCount == 0) // Mate!
1668 return value_mated_in(ply);
1670 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1672 // Update transposition table
1675 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1676 if (bestValue < beta)
1677 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_UPPER);
1679 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_LOWER);
1682 // Update killers only for good check moves
1683 Move m = ss[ply].currentMove;
1684 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1686 // Wrong to update history when depth is <= 0
1687 update_killers(m, ss[ply]);
1693 // sp_search() is used to search from a split point. This function is called
1694 // by each thread working at the split point. It is similar to the normal
1695 // search() function, but simpler. Because we have already probed the hash
1696 // table, done a null move search, and searched the first move before
1697 // splitting, we don't have to repeat all this work in sp_search(). We
1698 // also don't need to store anything to the hash table here: This is taken
1699 // care of after we return from the split point.
1701 void sp_search(SplitPoint *sp, int threadID) {
1703 assert(threadID >= 0 && threadID < ActiveThreads);
1704 assert(ActiveThreads > 1);
1706 Position pos = Position(sp->pos);
1707 SearchStack *ss = sp->sstack[threadID];
1710 bool isCheck = pos.is_check();
1711 bool useFutilityPruning = UseFutilityPruning
1712 && sp->depth < SelectiveDepth
1715 while ( sp->bestValue < sp->beta
1716 && !thread_should_stop(threadID)
1717 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1719 assert(move_is_ok(move));
1721 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1722 bool moveIsCapture = pos.move_is_capture(move);
1724 lock_grab(&(sp->lock));
1725 int moveCount = ++sp->moves;
1726 lock_release(&(sp->lock));
1728 ss[sp->ply].currentMove = move;
1730 // Decide the new search depth.
1732 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1733 Depth newDepth = sp->depth - OnePly + ext;
1736 if ( useFutilityPruning
1739 && !move_promotion(move)
1740 && moveCount >= 2 + int(sp->depth)
1741 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1744 // Make and search the move.
1746 pos.do_move(move, st, sp->dcCandidates);
1748 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1749 // if the move fails high will be re-searched at full depth.
1751 && moveCount >= LMRNonPVMoves
1753 && !move_promotion(move)
1754 && !move_is_castle(move)
1755 && !move_is_killer(move, ss[sp->ply]))
1757 ss[sp->ply].reduction = OnePly;
1758 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1761 value = sp->beta; // Just to trigger next condition
1763 if (value >= sp->beta) // Go with full depth non-pv search
1765 ss[sp->ply].reduction = Depth(0);
1766 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1768 pos.undo_move(move);
1770 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1772 if (thread_should_stop(threadID))
1776 lock_grab(&(sp->lock));
1777 if (value > sp->bestValue && !thread_should_stop(threadID))
1779 sp->bestValue = value;
1780 if (sp->bestValue >= sp->beta)
1782 sp_update_pv(sp->parentSstack, ss, sp->ply);
1783 for (int i = 0; i < ActiveThreads; i++)
1784 if (i != threadID && (i == sp->master || sp->slaves[i]))
1785 Threads[i].stop = true;
1787 sp->finished = true;
1790 lock_release(&(sp->lock));
1793 lock_grab(&(sp->lock));
1795 // If this is the master thread and we have been asked to stop because of
1796 // a beta cutoff higher up in the tree, stop all slave threads:
1797 if (sp->master == threadID && thread_should_stop(threadID))
1798 for (int i = 0; i < ActiveThreads; i++)
1800 Threads[i].stop = true;
1803 sp->slaves[threadID] = 0;
1805 lock_release(&(sp->lock));
1809 // sp_search_pv() is used to search from a PV split point. This function
1810 // is called by each thread working at the split point. It is similar to
1811 // the normal search_pv() function, but simpler. Because we have already
1812 // probed the hash table and searched the first move before splitting, we
1813 // don't have to repeat all this work in sp_search_pv(). We also don't
1814 // need to store anything to the hash table here: This is taken care of
1815 // after we return from the split point.
1817 void sp_search_pv(SplitPoint *sp, int threadID) {
1819 assert(threadID >= 0 && threadID < ActiveThreads);
1820 assert(ActiveThreads > 1);
1822 Position pos = Position(sp->pos);
1823 SearchStack *ss = sp->sstack[threadID];
1827 while ( sp->alpha < sp->beta
1828 && !thread_should_stop(threadID)
1829 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1831 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1832 bool moveIsCapture = pos.move_is_capture(move);
1834 assert(move_is_ok(move));
1836 lock_grab(&(sp->lock));
1837 int moveCount = ++sp->moves;
1838 lock_release(&(sp->lock));
1840 ss[sp->ply].currentMove = move;
1842 // Decide the new search depth.
1844 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1845 Depth newDepth = sp->depth - OnePly + ext;
1847 // Make and search the move.
1849 pos.do_move(move, st, sp->dcCandidates);
1851 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1852 // if the move fails high will be re-searched at full depth.
1854 && moveCount >= LMRPVMoves
1856 && !move_promotion(move)
1857 && !move_is_castle(move)
1858 && !move_is_killer(move, ss[sp->ply]))
1860 ss[sp->ply].reduction = OnePly;
1861 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1864 value = sp->alpha + 1; // Just to trigger next condition
1866 if (value > sp->alpha) // Go with full depth non-pv search
1868 ss[sp->ply].reduction = Depth(0);
1869 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1871 if (value > sp->alpha && value < sp->beta)
1873 // When the search fails high at ply 1 while searching the first
1874 // move at the root, set the flag failHighPly1. This is used for
1875 // time managment: We don't want to stop the search early in
1876 // such cases, because resolving the fail high at ply 1 could
1877 // result in a big drop in score at the root.
1878 if (sp->ply == 1 && RootMoveNumber == 1)
1879 Threads[threadID].failHighPly1 = true;
1881 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1882 Threads[threadID].failHighPly1 = false;
1885 pos.undo_move(move);
1887 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1889 if (thread_should_stop(threadID))
1893 lock_grab(&(sp->lock));
1894 if (value > sp->bestValue && !thread_should_stop(threadID))
1896 sp->bestValue = value;
1897 if (value > sp->alpha)
1900 sp_update_pv(sp->parentSstack, ss, sp->ply);
1901 if (value == value_mate_in(sp->ply + 1))
1902 ss[sp->ply].mateKiller = move;
1904 if(value >= sp->beta)
1906 for(int i = 0; i < ActiveThreads; i++)
1907 if(i != threadID && (i == sp->master || sp->slaves[i]))
1908 Threads[i].stop = true;
1910 sp->finished = true;
1913 // If we are at ply 1, and we are searching the first root move at
1914 // ply 0, set the 'Problem' variable if the score has dropped a lot
1915 // (from the computer's point of view) since the previous iteration.
1918 && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1921 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));
1939 /// The BetaCounterType class
1941 BetaCounterType::BetaCounterType() { clear(); }
1943 void BetaCounterType::clear() {
1945 for (int i = 0; i < THREAD_MAX; i++)
1946 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1949 void BetaCounterType::add(Color us, Depth d, int threadID) {
1951 // Weighted count based on depth
1952 hits[threadID][us] += int(d);
1955 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1958 for (int i = 0; i < THREAD_MAX; i++)
1961 their += hits[i][opposite_color(us)];
1966 /// The RootMove class
1970 RootMove::RootMove() {
1971 nodes = cumulativeNodes = 0ULL;
1974 // RootMove::operator<() is the comparison function used when
1975 // sorting the moves. A move m1 is considered to be better
1976 // than a move m2 if it has a higher score, or if the moves
1977 // have equal score but m1 has the higher node count.
1979 bool RootMove::operator<(const RootMove& m) {
1981 if (score != m.score)
1982 return (score < m.score);
1984 return theirBeta <= m.theirBeta;
1987 /// The RootMoveList class
1991 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1993 MoveStack mlist[MaxRootMoves];
1994 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1996 // Generate all legal moves
1997 int lm_count = generate_legal_moves(pos, mlist);
1999 // Add each move to the moves[] array
2000 for (int i = 0; i < lm_count; i++)
2002 bool includeMove = includeAllMoves;
2004 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2005 includeMove = (searchMoves[k] == mlist[i].move);
2009 // Find a quick score for the move
2011 SearchStack ss[PLY_MAX_PLUS_2];
2013 moves[count].move = mlist[i].move;
2014 moves[count].nodes = 0ULL;
2015 pos.do_move(moves[count].move, st);
2016 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
2018 pos.undo_move(moves[count].move);
2019 moves[count].pv[0] = moves[i].move;
2020 moves[count].pv[1] = MOVE_NONE; // FIXME
2028 // Simple accessor methods for the RootMoveList class
2030 inline Move RootMoveList::get_move(int moveNum) const {
2031 return moves[moveNum].move;
2034 inline Value RootMoveList::get_move_score(int moveNum) const {
2035 return moves[moveNum].score;
2038 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2039 moves[moveNum].score = score;
2042 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2043 moves[moveNum].nodes = nodes;
2044 moves[moveNum].cumulativeNodes += nodes;
2047 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2048 moves[moveNum].ourBeta = our;
2049 moves[moveNum].theirBeta = their;
2052 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2054 for(j = 0; pv[j] != MOVE_NONE; j++)
2055 moves[moveNum].pv[j] = pv[j];
2056 moves[moveNum].pv[j] = MOVE_NONE;
2059 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2060 return moves[moveNum].pv[i];
2063 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2064 return moves[moveNum].cumulativeNodes;
2067 inline int RootMoveList::move_count() const {
2072 // RootMoveList::scan_for_easy_move() is called at the end of the first
2073 // iteration, and is used to detect an "easy move", i.e. a move which appears
2074 // to be much bester than all the rest. If an easy move is found, the move
2075 // is returned, otherwise the function returns MOVE_NONE. It is very
2076 // important that this function is called at the right moment: The code
2077 // assumes that the first iteration has been completed and the moves have
2078 // been sorted. This is done in RootMoveList c'tor.
2080 Move RootMoveList::scan_for_easy_move() const {
2087 // moves are sorted so just consider the best and the second one
2088 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2094 // RootMoveList::sort() sorts the root move list at the beginning of a new
2097 inline void RootMoveList::sort() {
2099 sort_multipv(count - 1); // all items
2103 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2104 // list by their scores and depths. It is used to order the different PVs
2105 // correctly in MultiPV mode.
2107 void RootMoveList::sort_multipv(int n) {
2109 for (int i = 1; i <= n; i++)
2111 RootMove rm = moves[i];
2113 for (j = i; j > 0 && moves[j-1] < rm; j--)
2114 moves[j] = moves[j-1];
2120 // init_node() is called at the beginning of all the search functions
2121 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2122 // stack object corresponding to the current node. Once every
2123 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2124 // for user input and checks whether it is time to stop the search.
2126 void init_node(SearchStack ss[], int ply, int threadID) {
2127 assert(ply >= 0 && ply < PLY_MAX);
2128 assert(threadID >= 0 && threadID < ActiveThreads);
2130 Threads[threadID].nodes++;
2134 if(NodesSincePoll >= NodesBetweenPolls) {
2141 ss[ply+2].initKillers();
2143 if(Threads[threadID].printCurrentLine)
2144 print_current_line(ss, ply, threadID);
2148 // update_pv() is called whenever a search returns a value > alpha. It
2149 // updates the PV in the SearchStack object corresponding to the current
2152 void update_pv(SearchStack ss[], int ply) {
2153 assert(ply >= 0 && ply < PLY_MAX);
2155 ss[ply].pv[ply] = ss[ply].currentMove;
2157 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2158 ss[ply].pv[p] = ss[ply+1].pv[p];
2159 ss[ply].pv[p] = MOVE_NONE;
2163 // sp_update_pv() is a variant of update_pv for use at split points. The
2164 // difference between the two functions is that sp_update_pv also updates
2165 // the PV at the parent node.
2167 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2168 assert(ply >= 0 && ply < PLY_MAX);
2170 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2172 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2173 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2174 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2178 // connected_moves() tests whether two moves are 'connected' in the sense
2179 // that the first move somehow made the second move possible (for instance
2180 // if the moving piece is the same in both moves). The first move is
2181 // assumed to be the move that was made to reach the current position, while
2182 // the second move is assumed to be a move from the current position.
2184 bool connected_moves(const Position &pos, Move m1, Move m2) {
2185 Square f1, t1, f2, t2;
2187 assert(move_is_ok(m1));
2188 assert(move_is_ok(m2));
2193 // Case 1: The moving piece is the same in both moves.
2199 // Case 2: The destination square for m2 was vacated by m1.
2205 // Case 3: Moving through the vacated square:
2206 if(piece_is_slider(pos.piece_on(f2)) &&
2207 bit_is_set(squares_between(f2, t2), f1))
2210 // Case 4: The destination square for m2 is attacked by the moving piece
2212 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2215 // Case 5: Discovered check, checking piece is the piece moved in m1:
2216 if(piece_is_slider(pos.piece_on(t1)) &&
2217 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2219 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2221 Bitboard occ = pos.occupied_squares();
2222 Color us = pos.side_to_move();
2223 Square ksq = pos.king_square(us);
2224 clear_bit(&occ, f2);
2225 if(pos.type_of_piece_on(t1) == BISHOP) {
2226 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2229 else if(pos.type_of_piece_on(t1) == ROOK) {
2230 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2234 assert(pos.type_of_piece_on(t1) == QUEEN);
2235 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2244 // value_is_mate() checks if the given value is a mate one
2245 // eventually compensated for the ply.
2247 bool value_is_mate(Value value) {
2249 assert(abs(value) <= VALUE_INFINITE);
2251 return value <= value_mated_in(PLY_MAX)
2252 || value >= value_mate_in(PLY_MAX);
2256 // move_is_killer() checks if the given move is among the
2257 // killer moves of that ply.
2259 bool move_is_killer(Move m, const SearchStack& ss) {
2261 const Move* k = ss.killers;
2262 for (int i = 0; i < KILLER_MAX; i++, k++)
2270 // extension() decides whether a move should be searched with normal depth,
2271 // or with extended depth. Certain classes of moves (checking moves, in
2272 // particular) are searched with bigger depth than ordinary moves and in
2273 // any case are marked as 'dangerous'. Note that also if a move is not
2274 // extended, as example because the corresponding UCI option is set to zero,
2275 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2277 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2278 bool singleReply, bool mateThreat, bool* dangerous) {
2280 assert(m != MOVE_NONE);
2282 Depth result = Depth(0);
2283 *dangerous = check || singleReply || mateThreat;
2286 result += CheckExtension[pvNode];
2289 result += SingleReplyExtension[pvNode];
2292 result += MateThreatExtension[pvNode];
2294 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2296 if (pos.move_is_pawn_push_to_7th(m))
2298 result += PawnPushTo7thExtension[pvNode];
2301 if (pos.move_is_passed_pawn_push(m))
2303 result += PassedPawnExtension[pvNode];
2309 && pos.type_of_piece_on(move_to(m)) != PAWN
2310 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2311 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2312 && !move_promotion(m)
2315 result += PawnEndgameExtension[pvNode];
2321 && pos.type_of_piece_on(move_to(m)) != PAWN
2328 return Min(result, OnePly);
2332 // ok_to_do_nullmove() looks at the current position and decides whether
2333 // doing a 'null move' should be allowed. In order to avoid zugzwang
2334 // problems, null moves are not allowed when the side to move has very
2335 // little material left. Currently, the test is a bit too simple: Null
2336 // moves are avoided only when the side to move has only pawns left. It's
2337 // probably a good idea to avoid null moves in at least some more
2338 // complicated endgames, e.g. KQ vs KR. FIXME
2340 bool ok_to_do_nullmove(const Position &pos) {
2341 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2347 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2348 // non-tactical moves late in the move list close to the leaves are
2349 // candidates for pruning.
2351 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2352 Square mfrom, mto, tfrom, tto;
2354 assert(move_is_ok(m));
2355 assert(threat == MOVE_NONE || move_is_ok(threat));
2356 assert(!move_promotion(m));
2357 assert(!pos.move_is_check(m));
2358 assert(!pos.move_is_capture(m));
2359 assert(!pos.move_is_passed_pawn_push(m));
2360 assert(d >= OnePly);
2362 mfrom = move_from(m);
2364 tfrom = move_from(threat);
2365 tto = move_to(threat);
2367 // Case 1: Castling moves are never pruned.
2368 if (move_is_castle(m))
2371 // Case 2: Don't prune moves which move the threatened piece
2372 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2375 // Case 3: If the threatened piece has value less than or equal to the
2376 // value of the threatening piece, don't prune move which defend it.
2377 if ( !PruneDefendingMoves
2378 && threat != MOVE_NONE
2379 && pos.move_is_capture(threat)
2380 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2381 || pos.type_of_piece_on(tfrom) == KING)
2382 && pos.move_attacks_square(m, tto))
2385 // Case 4: Don't prune moves with good history.
2386 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2389 // Case 5: If the moving piece in the threatened move is a slider, don't
2390 // prune safe moves which block its ray.
2391 if ( !PruneBlockingMoves
2392 && threat != MOVE_NONE
2393 && piece_is_slider(pos.piece_on(tfrom))
2394 && bit_is_set(squares_between(tfrom, tto), mto)
2402 // ok_to_use_TT() returns true if a transposition table score
2403 // can be used at a given point in search.
2405 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2407 Value v = value_from_tt(tte->value(), ply);
2409 return ( tte->depth() >= depth
2410 || v >= Max(value_mate_in(100), beta)
2411 || v < Min(value_mated_in(100), beta))
2413 && ( (is_lower_bound(tte->type()) && v >= beta)
2414 || (is_upper_bound(tte->type()) && v < beta));
2418 // ok_to_history() returns true if a move m can be stored
2419 // in history. Should be a non capturing move nor a promotion.
2421 bool ok_to_history(const Position& pos, Move m) {
2423 return !pos.move_is_capture(m) && !move_promotion(m);
2427 // update_history() registers a good move that produced a beta-cutoff
2428 // in history and marks as failures all the other moves of that ply.
2430 void update_history(const Position& pos, Move m, Depth depth,
2431 Move movesSearched[], int moveCount) {
2433 H.success(pos.piece_on(move_from(m)), m, depth);
2435 for (int i = 0; i < moveCount - 1; i++)
2437 assert(m != movesSearched[i]);
2438 if (ok_to_history(pos, movesSearched[i]))
2439 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2444 // update_killers() add a good move that produced a beta-cutoff
2445 // among the killer moves of that ply.
2447 void update_killers(Move m, SearchStack& ss) {
2449 if (m == ss.killers[0])
2452 for (int i = KILLER_MAX - 1; i > 0; i--)
2453 ss.killers[i] = ss.killers[i - 1];
2458 // fail_high_ply_1() checks if some thread is currently resolving a fail
2459 // high at ply 1 at the node below the first root node. This information
2460 // is used for time managment.
2462 bool fail_high_ply_1() {
2463 for(int i = 0; i < ActiveThreads; i++)
2464 if(Threads[i].failHighPly1)
2470 // current_search_time() returns the number of milliseconds which have passed
2471 // since the beginning of the current search.
2473 int current_search_time() {
2474 return get_system_time() - SearchStartTime;
2478 // nps() computes the current nodes/second count.
2481 int t = current_search_time();
2482 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2486 // poll() performs two different functions: It polls for user input, and it
2487 // looks at the time consumed so far and decides if it's time to abort the
2492 static int lastInfoTime;
2493 int t = current_search_time();
2498 // We are line oriented, don't read single chars
2499 std::string command;
2500 if (!std::getline(std::cin, command))
2503 if (command == "quit")
2506 PonderSearch = false;
2509 else if(command == "stop")
2512 PonderSearch = false;
2514 else if(command == "ponderhit")
2517 // Print search information
2521 else if (lastInfoTime > t)
2522 // HACK: Must be a new search where we searched less than
2523 // NodesBetweenPolls nodes during the first second of search.
2526 else if (t - lastInfoTime >= 1000)
2533 if (dbg_show_hit_rate)
2534 dbg_print_hit_rate();
2536 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2537 << " time " << t << " hashfull " << TT.full() << std::endl;
2538 lock_release(&IOLock);
2539 if (ShowCurrentLine)
2540 Threads[0].printCurrentLine = true;
2542 // Should we stop the search?
2546 bool overTime = t > AbsoluteMaxSearchTime
2547 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: BUG??
2548 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2549 && t > 6*(MaxSearchTime + ExtraSearchTime));
2551 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2552 || (ExactMaxTime && t >= ExactMaxTime)
2553 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2558 // ponderhit() is called when the program is pondering (i.e. thinking while
2559 // it's the opponent's turn to move) in order to let the engine know that
2560 // it correctly predicted the opponent's move.
2563 int t = current_search_time();
2564 PonderSearch = false;
2565 if(Iteration >= 3 &&
2566 (!InfiniteSearch && (StopOnPonderhit ||
2567 t > AbsoluteMaxSearchTime ||
2568 (RootMoveNumber == 1 &&
2569 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2570 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2571 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2576 // print_current_line() prints the current line of search for a given
2577 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2579 void print_current_line(SearchStack ss[], int ply, int threadID) {
2580 assert(ply >= 0 && ply < PLY_MAX);
2581 assert(threadID >= 0 && threadID < ActiveThreads);
2583 if(!Threads[threadID].idle) {
2585 std::cout << "info currline " << (threadID + 1);
2586 for(int p = 0; p < ply; p++)
2587 std::cout << " " << ss[p].currentMove;
2588 std::cout << std::endl;
2589 lock_release(&IOLock);
2591 Threads[threadID].printCurrentLine = false;
2592 if(threadID + 1 < ActiveThreads)
2593 Threads[threadID + 1].printCurrentLine = true;
2597 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2598 // while the program is pondering. The point is to work around a wrinkle in
2599 // the UCI protocol: When pondering, the engine is not allowed to give a
2600 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2601 // We simply wait here until one of these commands is sent, and return,
2602 // after which the bestmove and pondermove will be printed (in id_loop()).
2604 void wait_for_stop_or_ponderhit() {
2605 std::string command;
2608 if(!std::getline(std::cin, command))
2611 if(command == "quit") {
2612 OpeningBook.close();
2617 else if(command == "ponderhit" || command == "stop")
2623 // idle_loop() is where the threads are parked when they have no work to do.
2624 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2625 // object for which the current thread is the master.
2627 void idle_loop(int threadID, SplitPoint *waitSp) {
2628 assert(threadID >= 0 && threadID < THREAD_MAX);
2630 Threads[threadID].running = true;
2633 if(AllThreadsShouldExit && threadID != 0)
2636 // If we are not thinking, wait for a condition to be signaled instead
2637 // of wasting CPU time polling for work:
2638 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2639 #if !defined(_MSC_VER)
2640 pthread_mutex_lock(&WaitLock);
2641 if(Idle || threadID >= ActiveThreads)
2642 pthread_cond_wait(&WaitCond, &WaitLock);
2643 pthread_mutex_unlock(&WaitLock);
2645 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2649 // If this thread has been assigned work, launch a search:
2650 if(Threads[threadID].workIsWaiting) {
2651 Threads[threadID].workIsWaiting = false;
2652 if(Threads[threadID].splitPoint->pvNode)
2653 sp_search_pv(Threads[threadID].splitPoint, threadID);
2655 sp_search(Threads[threadID].splitPoint, threadID);
2656 Threads[threadID].idle = true;
2659 // If this thread is the master of a split point and all threads have
2660 // finished their work at this split point, return from the idle loop:
2661 if(waitSp != NULL && waitSp->cpus == 0)
2665 Threads[threadID].running = false;
2669 // init_split_point_stack() is called during program initialization, and
2670 // initializes all split point objects.
2672 void init_split_point_stack() {
2673 for(int i = 0; i < THREAD_MAX; i++)
2674 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2675 SplitPointStack[i][j].parent = NULL;
2676 lock_init(&(SplitPointStack[i][j].lock), NULL);
2681 // destroy_split_point_stack() is called when the program exits, and
2682 // destroys all locks in the precomputed split point objects.
2684 void destroy_split_point_stack() {
2685 for(int i = 0; i < THREAD_MAX; i++)
2686 for(int j = 0; j < MaxActiveSplitPoints; j++)
2687 lock_destroy(&(SplitPointStack[i][j].lock));
2691 // thread_should_stop() checks whether the thread with a given threadID has
2692 // been asked to stop, directly or indirectly. This can happen if a beta
2693 // cutoff has occured in thre thread's currently active split point, or in
2694 // some ancestor of the current split point.
2696 bool thread_should_stop(int threadID) {
2697 assert(threadID >= 0 && threadID < ActiveThreads);
2701 if(Threads[threadID].stop)
2703 if(ActiveThreads <= 2)
2705 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2707 Threads[threadID].stop = true;
2714 // thread_is_available() checks whether the thread with threadID "slave" is
2715 // available to help the thread with threadID "master" at a split point. An
2716 // obvious requirement is that "slave" must be idle. With more than two
2717 // threads, this is not by itself sufficient: If "slave" is the master of
2718 // some active split point, it is only available as a slave to the other
2719 // threads which are busy searching the split point at the top of "slave"'s
2720 // split point stack (the "helpful master concept" in YBWC terminology).
2722 bool thread_is_available(int slave, int master) {
2723 assert(slave >= 0 && slave < ActiveThreads);
2724 assert(master >= 0 && master < ActiveThreads);
2725 assert(ActiveThreads > 1);
2727 if(!Threads[slave].idle || slave == master)
2730 if(Threads[slave].activeSplitPoints == 0)
2731 // No active split points means that the thread is available as a slave
2732 // for any other thread.
2735 if(ActiveThreads == 2)
2738 // Apply the "helpful master" concept if possible.
2739 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2746 // idle_thread_exists() tries to find an idle thread which is available as
2747 // a slave for the thread with threadID "master".
2749 bool idle_thread_exists(int master) {
2750 assert(master >= 0 && master < ActiveThreads);
2751 assert(ActiveThreads > 1);
2753 for(int i = 0; i < ActiveThreads; i++)
2754 if(thread_is_available(i, master))
2760 // split() does the actual work of distributing the work at a node between
2761 // several threads at PV nodes. If it does not succeed in splitting the
2762 // node (because no idle threads are available, or because we have no unused
2763 // split point objects), the function immediately returns false. If
2764 // splitting is possible, a SplitPoint object is initialized with all the
2765 // data that must be copied to the helper threads (the current position and
2766 // search stack, alpha, beta, the search depth, etc.), and we tell our
2767 // helper threads that they have been assigned work. This will cause them
2768 // to instantly leave their idle loops and call sp_search_pv(). When all
2769 // threads have returned from sp_search_pv (or, equivalently, when
2770 // splitPoint->cpus becomes 0), split() returns true.
2772 bool split(const Position &p, SearchStack *sstck, int ply,
2773 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2774 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2777 assert(sstck != NULL);
2778 assert(ply >= 0 && ply < PLY_MAX);
2779 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2780 assert(!pvNode || *alpha < *beta);
2781 assert(*beta <= VALUE_INFINITE);
2782 assert(depth > Depth(0));
2783 assert(master >= 0 && master < ActiveThreads);
2784 assert(ActiveThreads > 1);
2786 SplitPoint *splitPoint;
2791 // If no other thread is available to help us, or if we have too many
2792 // active split points, don't split:
2793 if(!idle_thread_exists(master) ||
2794 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2795 lock_release(&MPLock);
2799 // Pick the next available split point object from the split point stack:
2800 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2801 Threads[master].activeSplitPoints++;
2803 // Initialize the split point object:
2804 splitPoint->parent = Threads[master].splitPoint;
2805 splitPoint->finished = false;
2806 splitPoint->ply = ply;
2807 splitPoint->depth = depth;
2808 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2809 splitPoint->beta = *beta;
2810 splitPoint->pvNode = pvNode;
2811 splitPoint->dcCandidates = dcCandidates;
2812 splitPoint->bestValue = *bestValue;
2813 splitPoint->master = master;
2814 splitPoint->mp = mp;
2815 splitPoint->moves = *moves;
2816 splitPoint->cpus = 1;
2817 splitPoint->pos.copy(p);
2818 splitPoint->parentSstack = sstck;
2819 for(i = 0; i < ActiveThreads; i++)
2820 splitPoint->slaves[i] = 0;
2822 // Copy the current position and the search stack to the master thread:
2823 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2824 Threads[master].splitPoint = splitPoint;
2826 // Make copies of the current position and search stack for each thread:
2827 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2829 if(thread_is_available(i, master)) {
2830 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2831 Threads[i].splitPoint = splitPoint;
2832 splitPoint->slaves[i] = 1;
2836 // Tell the threads that they have work to do. This will make them leave
2838 for(i = 0; i < ActiveThreads; i++)
2839 if(i == master || splitPoint->slaves[i]) {
2840 Threads[i].workIsWaiting = true;
2841 Threads[i].idle = false;
2842 Threads[i].stop = false;
2845 lock_release(&MPLock);
2847 // Everything is set up. The master thread enters the idle loop, from
2848 // which it will instantly launch a search, because its workIsWaiting
2849 // slot is 'true'. We send the split point as a second parameter to the
2850 // idle loop, which means that the main thread will return from the idle
2851 // loop when all threads have finished their work at this split point
2852 // (i.e. when // splitPoint->cpus == 0).
2853 idle_loop(master, splitPoint);
2855 // We have returned from the idle loop, which means that all threads are
2856 // finished. Update alpha, beta and bestvalue, and return:
2858 if(pvNode) *alpha = splitPoint->alpha;
2859 *beta = splitPoint->beta;
2860 *bestValue = splitPoint->bestValue;
2861 Threads[master].stop = false;
2862 Threads[master].idle = false;
2863 Threads[master].activeSplitPoints--;
2864 Threads[master].splitPoint = splitPoint->parent;
2865 lock_release(&MPLock);
2871 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2872 // to start a new search from the root.
2874 void wake_sleeping_threads() {
2875 if(ActiveThreads > 1) {
2876 for(int i = 1; i < ActiveThreads; i++) {
2877 Threads[i].idle = true;
2878 Threads[i].workIsWaiting = false;
2880 #if !defined(_MSC_VER)
2881 pthread_mutex_lock(&WaitLock);
2882 pthread_cond_broadcast(&WaitCond);
2883 pthread_mutex_unlock(&WaitLock);
2885 for(int i = 1; i < THREAD_MAX; i++)
2886 SetEvent(SitIdleEvent[i]);
2892 // init_thread() is the function which is called when a new thread is
2893 // launched. It simply calls the idle_loop() function with the supplied
2894 // threadID. There are two versions of this function; one for POSIX threads
2895 // and one for Windows threads.
2897 #if !defined(_MSC_VER)
2899 void *init_thread(void *threadID) {
2900 idle_loop(*(int *)threadID, NULL);
2906 DWORD WINAPI init_thread(LPVOID threadID) {
2907 idle_loop(*(int *)threadID, NULL);