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 Value bestValue = -VALUE_INFINITE;
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++)
902 if (alpha >= beta) { //Aspiration window failed high, ignore rest of the moves!
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 <= bestValue && 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)
1021 if (value > bestValue)
1028 // Reset the global variable Problem to false if the value isn't too
1029 // far below the final value from the last iteration.
1030 if (value > IterationInfo[Iteration - 1].value() - NoProblemMargin)
1035 rml.sort_multipv(i);
1036 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1039 std::cout << "info multipv " << j + 1
1040 << " score " << value_to_string(rml.get_move_score(j))
1041 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1042 << " time " << current_search_time()
1043 << " nodes " << nodes_searched()
1047 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1048 std::cout << rml.get_move_pv(j, k) << " ";
1050 std::cout << std::endl;
1052 alpha = rml.get_move_score(Min(i, MultiPV-1));
1053 bestValue = alpha; //In MultiPV-mode bestValue and alpha are always same thing.
1057 if (bestValue <= oldAlpha)
1067 // search_pv() is the main search function for PV nodes.
1069 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1070 Depth depth, int ply, int threadID) {
1072 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1073 assert(beta > alpha && beta <= VALUE_INFINITE);
1074 assert(ply >= 0 && ply < PLY_MAX);
1075 assert(threadID >= 0 && threadID < ActiveThreads);
1078 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1080 // Initialize, and make an early exit in case of an aborted search,
1081 // an instant draw, maximum ply reached, etc.
1082 init_node(ss, ply, threadID);
1084 // After init_node() that calls poll()
1085 if (AbortSearch || thread_should_stop(threadID))
1093 if (ply >= PLY_MAX - 1)
1094 return evaluate(pos, ei, threadID);
1096 // Mate distance pruning
1097 Value oldAlpha = alpha;
1098 alpha = Max(value_mated_in(ply), alpha);
1099 beta = Min(value_mate_in(ply+1), beta);
1103 // Transposition table lookup. At PV nodes, we don't use the TT for
1104 // pruning, but only for move ordering.
1105 const TTEntry* tte = TT.retrieve(pos);
1106 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1108 // Go with internal iterative deepening if we don't have a TT move
1109 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1111 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1112 ttMove = ss[ply].pv[ply];
1115 // Initialize a MovePicker object for the current position, and prepare
1116 // to search all moves
1117 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1119 Move move, movesSearched[256];
1121 Value value, bestValue = -VALUE_INFINITE;
1122 Bitboard dcCandidates = mp.discovered_check_candidates();
1123 Color us = pos.side_to_move();
1124 bool isCheck = pos.is_check();
1125 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1127 // Loop through all legal moves until no moves remain or a beta cutoff
1129 while ( alpha < beta
1130 && (move = mp.get_next_move()) != MOVE_NONE
1131 && !thread_should_stop(threadID))
1133 assert(move_is_ok(move));
1135 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1136 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1137 bool moveIsCapture = pos.move_is_capture(move);
1139 movesSearched[moveCount++] = ss[ply].currentMove = move;
1141 // Decide the new search depth
1143 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1144 Depth newDepth = depth - OnePly + ext;
1146 // Make and search the move
1148 pos.do_move(move, st, dcCandidates);
1150 if (moveCount == 1) // The first move in list is the PV
1151 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1154 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1155 // if the move fails high will be re-searched at full depth.
1156 if ( depth >= 2*OnePly
1157 && moveCount >= LMRPVMoves
1160 && !move_promotion(move)
1161 && !move_is_castle(move)
1162 && !move_is_killer(move, ss[ply]))
1164 ss[ply].reduction = OnePly;
1165 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1168 value = alpha + 1; // Just to trigger next condition
1170 if (value > alpha) // Go with full depth non-pv search
1172 ss[ply].reduction = Depth(0);
1173 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1174 if (value > alpha && value < beta)
1176 // When the search fails high at ply 1 while searching the first
1177 // move at the root, set the flag failHighPly1. This is used for
1178 // time managment: We don't want to stop the search early in
1179 // such cases, because resolving the fail high at ply 1 could
1180 // result in a big drop in score at the root.
1181 if (ply == 1 && RootMoveNumber == 1)
1182 Threads[threadID].failHighPly1 = 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;
1190 pos.undo_move(move);
1192 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1195 if (value > bestValue)
1202 if (value == value_mate_in(ply + 1))
1203 ss[ply].mateKiller = move;
1205 // If we are at ply 1, and we are searching the first root move at
1206 // ply 0, set the 'Problem' variable if the score has dropped a lot
1207 // (from the computer's point of view) since the previous iteration:
1210 && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1215 if ( ActiveThreads > 1
1217 && depth >= MinimumSplitDepth
1219 && idle_thread_exists(threadID)
1221 && !thread_should_stop(threadID)
1222 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1223 &moveCount, &mp, dcCandidates, threadID, true))
1227 // All legal moves have been searched. A special case: If there were
1228 // no legal moves, it must be mate or stalemate:
1230 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1232 // If the search is not aborted, update the transposition table,
1233 // history counters, and killer moves.
1234 if (AbortSearch || thread_should_stop(threadID))
1237 if (bestValue <= oldAlpha)
1238 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1240 else if (bestValue >= beta)
1242 BetaCounter.add(pos.side_to_move(), depth, threadID);
1243 Move m = ss[ply].pv[ply];
1244 if (ok_to_history(pos, m)) // Only non capture moves are considered
1246 update_history(pos, m, depth, movesSearched, moveCount);
1247 update_killers(m, ss[ply]);
1249 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1252 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1258 // search() is the search function for zero-width nodes.
1260 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1261 int ply, bool allowNullmove, int threadID) {
1263 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1264 assert(ply >= 0 && ply < PLY_MAX);
1265 assert(threadID >= 0 && threadID < ActiveThreads);
1268 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1270 // Initialize, and make an early exit in case of an aborted search,
1271 // an instant draw, maximum ply reached, etc.
1272 init_node(ss, ply, threadID);
1274 // After init_node() that calls poll()
1275 if (AbortSearch || thread_should_stop(threadID))
1283 if (ply >= PLY_MAX - 1)
1284 return evaluate(pos, ei, threadID);
1286 // Mate distance pruning
1287 if (value_mated_in(ply) >= beta)
1290 if (value_mate_in(ply + 1) < beta)
1293 // Transposition table lookup
1294 const TTEntry* tte = TT.retrieve(pos);
1295 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1297 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1299 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1300 return value_from_tt(tte->value(), ply);
1303 Value approximateEval = quick_evaluate(pos);
1304 bool mateThreat = false;
1305 bool isCheck = pos.is_check();
1311 && !value_is_mate(beta)
1312 && ok_to_do_nullmove(pos)
1313 && approximateEval >= beta - NullMoveMargin)
1315 ss[ply].currentMove = MOVE_NULL;
1318 pos.do_null_move(st);
1319 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1321 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1323 pos.undo_null_move();
1325 if (value_is_mate(nullValue))
1327 /* Do not return unproven mates */
1329 else if (nullValue >= beta)
1331 if (depth < 6 * OnePly)
1334 // Do zugzwang verification search
1335 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1339 // The null move failed low, which means that we may be faced with
1340 // some kind of threat. If the previous move was reduced, check if
1341 // the move that refuted the null move was somehow connected to the
1342 // move which was reduced. If a connection is found, return a fail
1343 // low score (which will cause the reduced move to fail high in the
1344 // parent node, which will trigger a re-search with full depth).
1345 if (nullValue == value_mated_in(ply + 2))
1348 ss[ply].threatMove = ss[ply + 1].currentMove;
1349 if ( depth < ThreatDepth
1350 && ss[ply - 1].reduction
1351 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1355 // Null move search not allowed, try razoring
1356 else if ( !value_is_mate(beta)
1357 && approximateEval < beta - RazorMargin
1358 && depth < RazorDepth
1359 && (RazorAtDepthOne || depth > OnePly)
1360 && ttMove == MOVE_NONE
1361 && !pos.has_pawn_on_7th(pos.side_to_move()))
1363 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1364 if ( (v < beta - RazorMargin - RazorMargin / 4)
1365 || (depth <= 2*OnePly && v < beta - RazorMargin)
1366 || (depth <= OnePly && v < beta - RazorMargin / 2))
1370 // Go with internal iterative deepening if we don't have a TT move
1371 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1372 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1374 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1375 ttMove = ss[ply].pv[ply];
1378 // Initialize a MovePicker object for the current position, and prepare
1379 // to search all moves:
1380 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1382 Move move, movesSearched[256];
1384 Value value, bestValue = -VALUE_INFINITE;
1385 Bitboard dcCandidates = mp.discovered_check_candidates();
1386 Value futilityValue = VALUE_NONE;
1387 bool useFutilityPruning = UseFutilityPruning
1388 && depth < SelectiveDepth
1391 // Loop through all legal moves until no moves remain or a beta cutoff
1393 while ( bestValue < beta
1394 && (move = mp.get_next_move()) != MOVE_NONE
1395 && !thread_should_stop(threadID))
1397 assert(move_is_ok(move));
1399 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1400 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1401 bool moveIsCapture = pos.move_is_capture(move);
1403 movesSearched[moveCount++] = ss[ply].currentMove = move;
1405 // Decide the new search depth
1407 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1408 Depth newDepth = depth - OnePly + ext;
1411 if ( useFutilityPruning
1414 && !move_promotion(move))
1416 // History pruning. See ok_to_prune() definition
1417 if ( moveCount >= 2 + int(depth)
1418 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1421 // Value based pruning
1422 if (depth < 7 * OnePly && approximateEval < beta)
1424 if (futilityValue == VALUE_NONE)
1425 futilityValue = evaluate(pos, ei, threadID)
1426 + FutilityMargins[int(depth)/2 - 1]
1429 if (futilityValue < beta)
1431 if (futilityValue > bestValue)
1432 bestValue = futilityValue;
1438 // Make and search the move
1440 pos.do_move(move, st, dcCandidates);
1442 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1443 // if the move fails high will be re-searched at full depth.
1444 if ( depth >= 2*OnePly
1445 && moveCount >= LMRNonPVMoves
1448 && !move_promotion(move)
1449 && !move_is_castle(move)
1450 && !move_is_killer(move, ss[ply]))
1452 ss[ply].reduction = OnePly;
1453 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1456 value = beta; // Just to trigger next condition
1458 if (value >= beta) // Go with full depth non-pv search
1460 ss[ply].reduction = Depth(0);
1461 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1463 pos.undo_move(move);
1465 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1468 if (value > bestValue)
1474 if (value == value_mate_in(ply + 1))
1475 ss[ply].mateKiller = move;
1479 if ( ActiveThreads > 1
1481 && depth >= MinimumSplitDepth
1483 && idle_thread_exists(threadID)
1485 && !thread_should_stop(threadID)
1486 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1487 &mp, dcCandidates, threadID, false))
1491 // All legal moves have been searched. A special case: If there were
1492 // no legal moves, it must be mate or stalemate.
1494 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1496 // If the search is not aborted, update the transposition table,
1497 // history counters, and killer moves.
1498 if (AbortSearch || thread_should_stop(threadID))
1501 if (bestValue < beta)
1502 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1505 BetaCounter.add(pos.side_to_move(), depth, threadID);
1506 Move m = ss[ply].pv[ply];
1507 if (ok_to_history(pos, m)) // Only non capture moves are considered
1509 update_history(pos, m, depth, movesSearched, moveCount);
1510 update_killers(m, ss[ply]);
1512 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1515 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1521 // qsearch() is the quiescence search function, which is called by the main
1522 // search function when the remaining depth is zero (or, to be more precise,
1523 // less than OnePly).
1525 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1526 Depth depth, int ply, int threadID) {
1528 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1529 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1531 assert(ply >= 0 && ply < PLY_MAX);
1532 assert(threadID >= 0 && threadID < ActiveThreads);
1534 // Initialize, and make an early exit in case of an aborted search,
1535 // an instant draw, maximum ply reached, etc.
1536 init_node(ss, ply, threadID);
1538 // After init_node() that calls poll()
1539 if (AbortSearch || thread_should_stop(threadID))
1545 // Transposition table lookup, only when not in PV
1546 TTEntry* tte = NULL;
1547 bool pvNode = (beta - alpha != 1);
1550 tte = TT.retrieve(pos);
1551 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1553 assert(tte->type() != VALUE_TYPE_EVAL);
1555 return value_from_tt(tte->value(), ply);
1559 // Evaluate the position statically
1562 bool isCheck = pos.is_check();
1563 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1566 staticValue = -VALUE_INFINITE;
1568 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1570 // Use the cached evaluation score if possible
1571 assert(tte->value() == evaluate(pos, ei, threadID));
1572 assert(ei.futilityMargin == Value(0));
1574 staticValue = tte->value();
1577 staticValue = evaluate(pos, ei, threadID);
1579 if (ply == PLY_MAX - 1)
1580 return evaluate(pos, ei, threadID);
1582 // Initialize "stand pat score", and return it immediately if it is
1584 Value bestValue = staticValue;
1586 if (bestValue >= beta)
1588 // Store the score to avoid a future costly evaluation() call
1589 if (!isCheck && !tte && ei.futilityMargin == 0)
1590 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1595 if (bestValue > alpha)
1598 // Initialize a MovePicker object for the current position, and prepare
1599 // to search the moves. Because the depth is <= 0 here, only captures,
1600 // queen promotions and checks (only if depth == 0) will be generated.
1601 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth);
1604 Bitboard dcCandidates = mp.discovered_check_candidates();
1605 Color us = pos.side_to_move();
1606 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1608 // Loop through the moves until no moves remain or a beta cutoff
1610 while ( alpha < beta
1611 && (move = mp.get_next_move()) != MOVE_NONE)
1613 assert(move_is_ok(move));
1616 ss[ply].currentMove = move;
1619 if ( UseQSearchFutilityPruning
1623 && !move_promotion(move)
1624 && !pos.move_is_check(move, dcCandidates)
1625 && !pos.move_is_passed_pawn_push(move))
1627 Value futilityValue = staticValue
1628 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1629 pos.endgame_value_of_piece_on(move_to(move)))
1630 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1632 + ei.futilityMargin;
1634 if (futilityValue < alpha)
1636 if (futilityValue > bestValue)
1637 bestValue = futilityValue;
1642 // Don't search captures and checks with negative SEE values
1644 && !move_promotion(move)
1645 && (pos.midgame_value_of_piece_on(move_from(move)) >
1646 pos.midgame_value_of_piece_on(move_to(move)))
1647 && pos.see(move) < 0)
1650 // Make and search the move.
1652 pos.do_move(move, st, dcCandidates);
1653 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1654 pos.undo_move(move);
1656 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1659 if (value > bestValue)
1670 // All legal moves have been searched. A special case: If we're in check
1671 // and no legal moves were found, it is checkmate:
1672 if (pos.is_check() && moveCount == 0) // Mate!
1673 return value_mated_in(ply);
1675 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1677 // Update transposition table
1680 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1681 if (bestValue < beta)
1682 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_UPPER);
1684 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_LOWER);
1687 // Update killers only for good check moves
1688 Move m = ss[ply].currentMove;
1689 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1691 // Wrong to update history when depth is <= 0
1692 update_killers(m, ss[ply]);
1698 // sp_search() is used to search from a split point. This function is called
1699 // by each thread working at the split point. It is similar to the normal
1700 // search() function, but simpler. Because we have already probed the hash
1701 // table, done a null move search, and searched the first move before
1702 // splitting, we don't have to repeat all this work in sp_search(). We
1703 // also don't need to store anything to the hash table here: This is taken
1704 // care of after we return from the split point.
1706 void sp_search(SplitPoint *sp, int threadID) {
1708 assert(threadID >= 0 && threadID < ActiveThreads);
1709 assert(ActiveThreads > 1);
1711 Position pos = Position(sp->pos);
1712 SearchStack *ss = sp->sstack[threadID];
1715 bool isCheck = pos.is_check();
1716 bool useFutilityPruning = UseFutilityPruning
1717 && sp->depth < SelectiveDepth
1720 while ( sp->bestValue < sp->beta
1721 && !thread_should_stop(threadID)
1722 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1724 assert(move_is_ok(move));
1726 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1727 bool moveIsCapture = pos.move_is_capture(move);
1729 lock_grab(&(sp->lock));
1730 int moveCount = ++sp->moves;
1731 lock_release(&(sp->lock));
1733 ss[sp->ply].currentMove = move;
1735 // Decide the new search depth.
1737 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1738 Depth newDepth = sp->depth - OnePly + ext;
1741 if ( useFutilityPruning
1744 && !move_promotion(move)
1745 && moveCount >= 2 + int(sp->depth)
1746 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1749 // Make and search the move.
1751 pos.do_move(move, st, sp->dcCandidates);
1753 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1754 // if the move fails high will be re-searched at full depth.
1756 && moveCount >= LMRNonPVMoves
1758 && !move_promotion(move)
1759 && !move_is_castle(move)
1760 && !move_is_killer(move, ss[sp->ply]))
1762 ss[sp->ply].reduction = OnePly;
1763 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1766 value = sp->beta; // Just to trigger next condition
1768 if (value >= sp->beta) // Go with full depth non-pv search
1770 ss[sp->ply].reduction = Depth(0);
1771 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1773 pos.undo_move(move);
1775 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1777 if (thread_should_stop(threadID))
1781 lock_grab(&(sp->lock));
1782 if (value > sp->bestValue && !thread_should_stop(threadID))
1784 sp->bestValue = value;
1785 if (sp->bestValue >= sp->beta)
1787 sp_update_pv(sp->parentSstack, ss, sp->ply);
1788 for (int i = 0; i < ActiveThreads; i++)
1789 if (i != threadID && (i == sp->master || sp->slaves[i]))
1790 Threads[i].stop = true;
1792 sp->finished = true;
1795 lock_release(&(sp->lock));
1798 lock_grab(&(sp->lock));
1800 // If this is the master thread and we have been asked to stop because of
1801 // a beta cutoff higher up in the tree, stop all slave threads:
1802 if (sp->master == threadID && thread_should_stop(threadID))
1803 for (int i = 0; i < ActiveThreads; i++)
1805 Threads[i].stop = true;
1808 sp->slaves[threadID] = 0;
1810 lock_release(&(sp->lock));
1814 // sp_search_pv() is used to search from a PV split point. This function
1815 // is called by each thread working at the split point. It is similar to
1816 // the normal search_pv() function, but simpler. Because we have already
1817 // probed the hash table and searched the first move before splitting, we
1818 // don't have to repeat all this work in sp_search_pv(). We also don't
1819 // need to store anything to the hash table here: This is taken care of
1820 // after we return from the split point.
1822 void sp_search_pv(SplitPoint *sp, int threadID) {
1824 assert(threadID >= 0 && threadID < ActiveThreads);
1825 assert(ActiveThreads > 1);
1827 Position pos = Position(sp->pos);
1828 SearchStack *ss = sp->sstack[threadID];
1832 while ( sp->alpha < sp->beta
1833 && !thread_should_stop(threadID)
1834 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1836 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1837 bool moveIsCapture = pos.move_is_capture(move);
1839 assert(move_is_ok(move));
1841 lock_grab(&(sp->lock));
1842 int moveCount = ++sp->moves;
1843 lock_release(&(sp->lock));
1845 ss[sp->ply].currentMove = move;
1847 // Decide the new search depth.
1849 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1850 Depth newDepth = sp->depth - OnePly + ext;
1852 // Make and search the move.
1854 pos.do_move(move, st, sp->dcCandidates);
1856 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1857 // if the move fails high will be re-searched at full depth.
1859 && moveCount >= LMRPVMoves
1861 && !move_promotion(move)
1862 && !move_is_castle(move)
1863 && !move_is_killer(move, ss[sp->ply]))
1865 ss[sp->ply].reduction = OnePly;
1866 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1869 value = sp->alpha + 1; // Just to trigger next condition
1871 if (value > sp->alpha) // Go with full depth non-pv search
1873 ss[sp->ply].reduction = Depth(0);
1874 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1876 if (value > sp->alpha && value < sp->beta)
1878 // When the search fails high at ply 1 while searching the first
1879 // move at the root, set the flag failHighPly1. This is used for
1880 // time managment: We don't want to stop the search early in
1881 // such cases, because resolving the fail high at ply 1 could
1882 // result in a big drop in score at the root.
1883 if (sp->ply == 1 && RootMoveNumber == 1)
1884 Threads[threadID].failHighPly1 = true;
1886 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1887 Threads[threadID].failHighPly1 = false;
1890 pos.undo_move(move);
1892 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1894 if (thread_should_stop(threadID))
1898 lock_grab(&(sp->lock));
1899 if (value > sp->bestValue && !thread_should_stop(threadID))
1901 sp->bestValue = value;
1902 if (value > sp->alpha)
1905 sp_update_pv(sp->parentSstack, ss, sp->ply);
1906 if (value == value_mate_in(sp->ply + 1))
1907 ss[sp->ply].mateKiller = move;
1909 if(value >= sp->beta)
1911 for(int i = 0; i < ActiveThreads; i++)
1912 if(i != threadID && (i == sp->master || sp->slaves[i]))
1913 Threads[i].stop = true;
1915 sp->finished = true;
1918 // If we are at ply 1, and we are searching the first root move at
1919 // ply 0, set the 'Problem' variable if the score has dropped a lot
1920 // (from the computer's point of view) since the previous iteration.
1923 && -value <= IterationInfo[Iteration-1].value() - ProblemMargin)
1926 lock_release(&(sp->lock));
1929 lock_grab(&(sp->lock));
1931 // If this is the master thread and we have been asked to stop because of
1932 // a beta cutoff higher up in the tree, stop all slave threads.
1933 if (sp->master == threadID && thread_should_stop(threadID))
1934 for (int i = 0; i < ActiveThreads; i++)
1936 Threads[i].stop = true;
1939 sp->slaves[threadID] = 0;
1941 lock_release(&(sp->lock));
1944 /// The BetaCounterType class
1946 BetaCounterType::BetaCounterType() { clear(); }
1948 void BetaCounterType::clear() {
1950 for (int i = 0; i < THREAD_MAX; i++)
1951 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1954 void BetaCounterType::add(Color us, Depth d, int threadID) {
1956 // Weighted count based on depth
1957 hits[threadID][us] += int(d);
1960 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1963 for (int i = 0; i < THREAD_MAX; i++)
1966 their += hits[i][opposite_color(us)];
1971 /// The RootMove class
1975 RootMove::RootMove() {
1976 nodes = cumulativeNodes = 0ULL;
1979 // RootMove::operator<() is the comparison function used when
1980 // sorting the moves. A move m1 is considered to be better
1981 // than a move m2 if it has a higher score, or if the moves
1982 // have equal score but m1 has the higher node count.
1984 bool RootMove::operator<(const RootMove& m) {
1986 if (score != m.score)
1987 return (score < m.score);
1989 return theirBeta <= m.theirBeta;
1992 /// The RootMoveList class
1996 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1998 MoveStack mlist[MaxRootMoves];
1999 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2001 // Generate all legal moves
2002 int lm_count = generate_legal_moves(pos, mlist);
2004 // Add each move to the moves[] array
2005 for (int i = 0; i < lm_count; i++)
2007 bool includeMove = includeAllMoves;
2009 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2010 includeMove = (searchMoves[k] == mlist[i].move);
2014 // Find a quick score for the move
2016 SearchStack ss[PLY_MAX_PLUS_2];
2018 moves[count].move = mlist[i].move;
2019 moves[count].nodes = 0ULL;
2020 pos.do_move(moves[count].move, st);
2021 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
2023 pos.undo_move(moves[count].move);
2024 moves[count].pv[0] = moves[i].move;
2025 moves[count].pv[1] = MOVE_NONE; // FIXME
2033 // Simple accessor methods for the RootMoveList class
2035 inline Move RootMoveList::get_move(int moveNum) const {
2036 return moves[moveNum].move;
2039 inline Value RootMoveList::get_move_score(int moveNum) const {
2040 return moves[moveNum].score;
2043 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2044 moves[moveNum].score = score;
2047 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2048 moves[moveNum].nodes = nodes;
2049 moves[moveNum].cumulativeNodes += nodes;
2052 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2053 moves[moveNum].ourBeta = our;
2054 moves[moveNum].theirBeta = their;
2057 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2059 for(j = 0; pv[j] != MOVE_NONE; j++)
2060 moves[moveNum].pv[j] = pv[j];
2061 moves[moveNum].pv[j] = MOVE_NONE;
2064 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2065 return moves[moveNum].pv[i];
2068 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2069 return moves[moveNum].cumulativeNodes;
2072 inline int RootMoveList::move_count() const {
2077 // RootMoveList::scan_for_easy_move() is called at the end of the first
2078 // iteration, and is used to detect an "easy move", i.e. a move which appears
2079 // to be much bester than all the rest. If an easy move is found, the move
2080 // is returned, otherwise the function returns MOVE_NONE. It is very
2081 // important that this function is called at the right moment: The code
2082 // assumes that the first iteration has been completed and the moves have
2083 // been sorted. This is done in RootMoveList c'tor.
2085 Move RootMoveList::scan_for_easy_move() const {
2092 // moves are sorted so just consider the best and the second one
2093 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2099 // RootMoveList::sort() sorts the root move list at the beginning of a new
2102 inline void RootMoveList::sort() {
2104 sort_multipv(count - 1); // all items
2108 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2109 // list by their scores and depths. It is used to order the different PVs
2110 // correctly in MultiPV mode.
2112 void RootMoveList::sort_multipv(int n) {
2114 for (int i = 1; i <= n; i++)
2116 RootMove rm = moves[i];
2118 for (j = i; j > 0 && moves[j-1] < rm; j--)
2119 moves[j] = moves[j-1];
2125 // init_node() is called at the beginning of all the search functions
2126 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2127 // stack object corresponding to the current node. Once every
2128 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2129 // for user input and checks whether it is time to stop the search.
2131 void init_node(SearchStack ss[], int ply, int threadID) {
2132 assert(ply >= 0 && ply < PLY_MAX);
2133 assert(threadID >= 0 && threadID < ActiveThreads);
2135 Threads[threadID].nodes++;
2139 if(NodesSincePoll >= NodesBetweenPolls) {
2146 ss[ply+2].initKillers();
2148 if(Threads[threadID].printCurrentLine)
2149 print_current_line(ss, ply, threadID);
2153 // update_pv() is called whenever a search returns a value > alpha. It
2154 // updates the PV in the SearchStack object corresponding to the current
2157 void update_pv(SearchStack ss[], int ply) {
2158 assert(ply >= 0 && ply < PLY_MAX);
2160 ss[ply].pv[ply] = ss[ply].currentMove;
2162 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2163 ss[ply].pv[p] = ss[ply+1].pv[p];
2164 ss[ply].pv[p] = MOVE_NONE;
2168 // sp_update_pv() is a variant of update_pv for use at split points. The
2169 // difference between the two functions is that sp_update_pv also updates
2170 // the PV at the parent node.
2172 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2173 assert(ply >= 0 && ply < PLY_MAX);
2175 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2177 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2178 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2179 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2183 // connected_moves() tests whether two moves are 'connected' in the sense
2184 // that the first move somehow made the second move possible (for instance
2185 // if the moving piece is the same in both moves). The first move is
2186 // assumed to be the move that was made to reach the current position, while
2187 // the second move is assumed to be a move from the current position.
2189 bool connected_moves(const Position &pos, Move m1, Move m2) {
2190 Square f1, t1, f2, t2;
2192 assert(move_is_ok(m1));
2193 assert(move_is_ok(m2));
2198 // Case 1: The moving piece is the same in both moves.
2204 // Case 2: The destination square for m2 was vacated by m1.
2210 // Case 3: Moving through the vacated square:
2211 if(piece_is_slider(pos.piece_on(f2)) &&
2212 bit_is_set(squares_between(f2, t2), f1))
2215 // Case 4: The destination square for m2 is attacked by the moving piece
2217 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2220 // Case 5: Discovered check, checking piece is the piece moved in m1:
2221 if(piece_is_slider(pos.piece_on(t1)) &&
2222 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2224 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2226 Bitboard occ = pos.occupied_squares();
2227 Color us = pos.side_to_move();
2228 Square ksq = pos.king_square(us);
2229 clear_bit(&occ, f2);
2230 if(pos.type_of_piece_on(t1) == BISHOP) {
2231 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2234 else if(pos.type_of_piece_on(t1) == ROOK) {
2235 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2239 assert(pos.type_of_piece_on(t1) == QUEEN);
2240 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2249 // value_is_mate() checks if the given value is a mate one
2250 // eventually compensated for the ply.
2252 bool value_is_mate(Value value) {
2254 assert(abs(value) <= VALUE_INFINITE);
2256 return value <= value_mated_in(PLY_MAX)
2257 || value >= value_mate_in(PLY_MAX);
2261 // move_is_killer() checks if the given move is among the
2262 // killer moves of that ply.
2264 bool move_is_killer(Move m, const SearchStack& ss) {
2266 const Move* k = ss.killers;
2267 for (int i = 0; i < KILLER_MAX; i++, k++)
2275 // extension() decides whether a move should be searched with normal depth,
2276 // or with extended depth. Certain classes of moves (checking moves, in
2277 // particular) are searched with bigger depth than ordinary moves and in
2278 // any case are marked as 'dangerous'. Note that also if a move is not
2279 // extended, as example because the corresponding UCI option is set to zero,
2280 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2282 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2283 bool singleReply, bool mateThreat, bool* dangerous) {
2285 assert(m != MOVE_NONE);
2287 Depth result = Depth(0);
2288 *dangerous = check || singleReply || mateThreat;
2291 result += CheckExtension[pvNode];
2294 result += SingleReplyExtension[pvNode];
2297 result += MateThreatExtension[pvNode];
2299 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2301 if (pos.move_is_pawn_push_to_7th(m))
2303 result += PawnPushTo7thExtension[pvNode];
2306 if (pos.move_is_passed_pawn_push(m))
2308 result += PassedPawnExtension[pvNode];
2314 && pos.type_of_piece_on(move_to(m)) != PAWN
2315 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2316 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2317 && !move_promotion(m)
2320 result += PawnEndgameExtension[pvNode];
2326 && pos.type_of_piece_on(move_to(m)) != PAWN
2333 return Min(result, OnePly);
2337 // ok_to_do_nullmove() looks at the current position and decides whether
2338 // doing a 'null move' should be allowed. In order to avoid zugzwang
2339 // problems, null moves are not allowed when the side to move has very
2340 // little material left. Currently, the test is a bit too simple: Null
2341 // moves are avoided only when the side to move has only pawns left. It's
2342 // probably a good idea to avoid null moves in at least some more
2343 // complicated endgames, e.g. KQ vs KR. FIXME
2345 bool ok_to_do_nullmove(const Position &pos) {
2346 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2352 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2353 // non-tactical moves late in the move list close to the leaves are
2354 // candidates for pruning.
2356 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2357 Square mfrom, mto, tfrom, tto;
2359 assert(move_is_ok(m));
2360 assert(threat == MOVE_NONE || move_is_ok(threat));
2361 assert(!move_promotion(m));
2362 assert(!pos.move_is_check(m));
2363 assert(!pos.move_is_capture(m));
2364 assert(!pos.move_is_passed_pawn_push(m));
2365 assert(d >= OnePly);
2367 mfrom = move_from(m);
2369 tfrom = move_from(threat);
2370 tto = move_to(threat);
2372 // Case 1: Castling moves are never pruned.
2373 if (move_is_castle(m))
2376 // Case 2: Don't prune moves which move the threatened piece
2377 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2380 // Case 3: If the threatened piece has value less than or equal to the
2381 // value of the threatening piece, don't prune move which defend it.
2382 if ( !PruneDefendingMoves
2383 && threat != MOVE_NONE
2384 && pos.move_is_capture(threat)
2385 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2386 || pos.type_of_piece_on(tfrom) == KING)
2387 && pos.move_attacks_square(m, tto))
2390 // Case 4: Don't prune moves with good history.
2391 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2394 // Case 5: If the moving piece in the threatened move is a slider, don't
2395 // prune safe moves which block its ray.
2396 if ( !PruneBlockingMoves
2397 && threat != MOVE_NONE
2398 && piece_is_slider(pos.piece_on(tfrom))
2399 && bit_is_set(squares_between(tfrom, tto), mto)
2407 // ok_to_use_TT() returns true if a transposition table score
2408 // can be used at a given point in search.
2410 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2412 Value v = value_from_tt(tte->value(), ply);
2414 return ( tte->depth() >= depth
2415 || v >= Max(value_mate_in(100), beta)
2416 || v < Min(value_mated_in(100), beta))
2418 && ( (is_lower_bound(tte->type()) && v >= beta)
2419 || (is_upper_bound(tte->type()) && v < beta));
2423 // ok_to_history() returns true if a move m can be stored
2424 // in history. Should be a non capturing move nor a promotion.
2426 bool ok_to_history(const Position& pos, Move m) {
2428 return !pos.move_is_capture(m) && !move_promotion(m);
2432 // update_history() registers a good move that produced a beta-cutoff
2433 // in history and marks as failures all the other moves of that ply.
2435 void update_history(const Position& pos, Move m, Depth depth,
2436 Move movesSearched[], int moveCount) {
2438 H.success(pos.piece_on(move_from(m)), m, depth);
2440 for (int i = 0; i < moveCount - 1; i++)
2442 assert(m != movesSearched[i]);
2443 if (ok_to_history(pos, movesSearched[i]))
2444 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2449 // update_killers() add a good move that produced a beta-cutoff
2450 // among the killer moves of that ply.
2452 void update_killers(Move m, SearchStack& ss) {
2454 if (m == ss.killers[0])
2457 for (int i = KILLER_MAX - 1; i > 0; i--)
2458 ss.killers[i] = ss.killers[i - 1];
2463 // fail_high_ply_1() checks if some thread is currently resolving a fail
2464 // high at ply 1 at the node below the first root node. This information
2465 // is used for time managment.
2467 bool fail_high_ply_1() {
2468 for(int i = 0; i < ActiveThreads; i++)
2469 if(Threads[i].failHighPly1)
2475 // current_search_time() returns the number of milliseconds which have passed
2476 // since the beginning of the current search.
2478 int current_search_time() {
2479 return get_system_time() - SearchStartTime;
2483 // nps() computes the current nodes/second count.
2486 int t = current_search_time();
2487 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2491 // poll() performs two different functions: It polls for user input, and it
2492 // looks at the time consumed so far and decides if it's time to abort the
2497 static int lastInfoTime;
2498 int t = current_search_time();
2503 // We are line oriented, don't read single chars
2504 std::string command;
2505 if (!std::getline(std::cin, command))
2508 if (command == "quit")
2511 PonderSearch = false;
2514 else if(command == "stop")
2517 PonderSearch = false;
2519 else if(command == "ponderhit")
2522 // Print search information
2526 else if (lastInfoTime > t)
2527 // HACK: Must be a new search where we searched less than
2528 // NodesBetweenPolls nodes during the first second of search.
2531 else if (t - lastInfoTime >= 1000)
2538 if (dbg_show_hit_rate)
2539 dbg_print_hit_rate();
2541 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2542 << " time " << t << " hashfull " << TT.full() << std::endl;
2543 lock_release(&IOLock);
2544 if (ShowCurrentLine)
2545 Threads[0].printCurrentLine = true;
2547 // Should we stop the search?
2551 bool overTime = t > AbsoluteMaxSearchTime
2552 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: BUG??
2553 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2554 && t > 6*(MaxSearchTime + ExtraSearchTime));
2556 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2557 || (ExactMaxTime && t >= ExactMaxTime)
2558 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2563 // ponderhit() is called when the program is pondering (i.e. thinking while
2564 // it's the opponent's turn to move) in order to let the engine know that
2565 // it correctly predicted the opponent's move.
2568 int t = current_search_time();
2569 PonderSearch = false;
2570 if(Iteration >= 3 &&
2571 (!InfiniteSearch && (StopOnPonderhit ||
2572 t > AbsoluteMaxSearchTime ||
2573 (RootMoveNumber == 1 &&
2574 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2575 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2576 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2581 // print_current_line() prints the current line of search for a given
2582 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2584 void print_current_line(SearchStack ss[], int ply, int threadID) {
2585 assert(ply >= 0 && ply < PLY_MAX);
2586 assert(threadID >= 0 && threadID < ActiveThreads);
2588 if(!Threads[threadID].idle) {
2590 std::cout << "info currline " << (threadID + 1);
2591 for(int p = 0; p < ply; p++)
2592 std::cout << " " << ss[p].currentMove;
2593 std::cout << std::endl;
2594 lock_release(&IOLock);
2596 Threads[threadID].printCurrentLine = false;
2597 if(threadID + 1 < ActiveThreads)
2598 Threads[threadID + 1].printCurrentLine = true;
2602 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2603 // while the program is pondering. The point is to work around a wrinkle in
2604 // the UCI protocol: When pondering, the engine is not allowed to give a
2605 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2606 // We simply wait here until one of these commands is sent, and return,
2607 // after which the bestmove and pondermove will be printed (in id_loop()).
2609 void wait_for_stop_or_ponderhit() {
2610 std::string command;
2613 if(!std::getline(std::cin, command))
2616 if(command == "quit") {
2617 OpeningBook.close();
2622 else if(command == "ponderhit" || command == "stop")
2628 // idle_loop() is where the threads are parked when they have no work to do.
2629 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2630 // object for which the current thread is the master.
2632 void idle_loop(int threadID, SplitPoint *waitSp) {
2633 assert(threadID >= 0 && threadID < THREAD_MAX);
2635 Threads[threadID].running = true;
2638 if(AllThreadsShouldExit && threadID != 0)
2641 // If we are not thinking, wait for a condition to be signaled instead
2642 // of wasting CPU time polling for work:
2643 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2644 #if !defined(_MSC_VER)
2645 pthread_mutex_lock(&WaitLock);
2646 if(Idle || threadID >= ActiveThreads)
2647 pthread_cond_wait(&WaitCond, &WaitLock);
2648 pthread_mutex_unlock(&WaitLock);
2650 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2654 // If this thread has been assigned work, launch a search:
2655 if(Threads[threadID].workIsWaiting) {
2656 Threads[threadID].workIsWaiting = false;
2657 if(Threads[threadID].splitPoint->pvNode)
2658 sp_search_pv(Threads[threadID].splitPoint, threadID);
2660 sp_search(Threads[threadID].splitPoint, threadID);
2661 Threads[threadID].idle = true;
2664 // If this thread is the master of a split point and all threads have
2665 // finished their work at this split point, return from the idle loop:
2666 if(waitSp != NULL && waitSp->cpus == 0)
2670 Threads[threadID].running = false;
2674 // init_split_point_stack() is called during program initialization, and
2675 // initializes all split point objects.
2677 void init_split_point_stack() {
2678 for(int i = 0; i < THREAD_MAX; i++)
2679 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2680 SplitPointStack[i][j].parent = NULL;
2681 lock_init(&(SplitPointStack[i][j].lock), NULL);
2686 // destroy_split_point_stack() is called when the program exits, and
2687 // destroys all locks in the precomputed split point objects.
2689 void destroy_split_point_stack() {
2690 for(int i = 0; i < THREAD_MAX; i++)
2691 for(int j = 0; j < MaxActiveSplitPoints; j++)
2692 lock_destroy(&(SplitPointStack[i][j].lock));
2696 // thread_should_stop() checks whether the thread with a given threadID has
2697 // been asked to stop, directly or indirectly. This can happen if a beta
2698 // cutoff has occured in thre thread's currently active split point, or in
2699 // some ancestor of the current split point.
2701 bool thread_should_stop(int threadID) {
2702 assert(threadID >= 0 && threadID < ActiveThreads);
2706 if(Threads[threadID].stop)
2708 if(ActiveThreads <= 2)
2710 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2712 Threads[threadID].stop = true;
2719 // thread_is_available() checks whether the thread with threadID "slave" is
2720 // available to help the thread with threadID "master" at a split point. An
2721 // obvious requirement is that "slave" must be idle. With more than two
2722 // threads, this is not by itself sufficient: If "slave" is the master of
2723 // some active split point, it is only available as a slave to the other
2724 // threads which are busy searching the split point at the top of "slave"'s
2725 // split point stack (the "helpful master concept" in YBWC terminology).
2727 bool thread_is_available(int slave, int master) {
2728 assert(slave >= 0 && slave < ActiveThreads);
2729 assert(master >= 0 && master < ActiveThreads);
2730 assert(ActiveThreads > 1);
2732 if(!Threads[slave].idle || slave == master)
2735 if(Threads[slave].activeSplitPoints == 0)
2736 // No active split points means that the thread is available as a slave
2737 // for any other thread.
2740 if(ActiveThreads == 2)
2743 // Apply the "helpful master" concept if possible.
2744 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2751 // idle_thread_exists() tries to find an idle thread which is available as
2752 // a slave for the thread with threadID "master".
2754 bool idle_thread_exists(int master) {
2755 assert(master >= 0 && master < ActiveThreads);
2756 assert(ActiveThreads > 1);
2758 for(int i = 0; i < ActiveThreads; i++)
2759 if(thread_is_available(i, master))
2765 // split() does the actual work of distributing the work at a node between
2766 // several threads at PV nodes. If it does not succeed in splitting the
2767 // node (because no idle threads are available, or because we have no unused
2768 // split point objects), the function immediately returns false. If
2769 // splitting is possible, a SplitPoint object is initialized with all the
2770 // data that must be copied to the helper threads (the current position and
2771 // search stack, alpha, beta, the search depth, etc.), and we tell our
2772 // helper threads that they have been assigned work. This will cause them
2773 // to instantly leave their idle loops and call sp_search_pv(). When all
2774 // threads have returned from sp_search_pv (or, equivalently, when
2775 // splitPoint->cpus becomes 0), split() returns true.
2777 bool split(const Position &p, SearchStack *sstck, int ply,
2778 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2779 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2782 assert(sstck != NULL);
2783 assert(ply >= 0 && ply < PLY_MAX);
2784 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2785 assert(!pvNode || *alpha < *beta);
2786 assert(*beta <= VALUE_INFINITE);
2787 assert(depth > Depth(0));
2788 assert(master >= 0 && master < ActiveThreads);
2789 assert(ActiveThreads > 1);
2791 SplitPoint *splitPoint;
2796 // If no other thread is available to help us, or if we have too many
2797 // active split points, don't split:
2798 if(!idle_thread_exists(master) ||
2799 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2800 lock_release(&MPLock);
2804 // Pick the next available split point object from the split point stack:
2805 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2806 Threads[master].activeSplitPoints++;
2808 // Initialize the split point object:
2809 splitPoint->parent = Threads[master].splitPoint;
2810 splitPoint->finished = false;
2811 splitPoint->ply = ply;
2812 splitPoint->depth = depth;
2813 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2814 splitPoint->beta = *beta;
2815 splitPoint->pvNode = pvNode;
2816 splitPoint->dcCandidates = dcCandidates;
2817 splitPoint->bestValue = *bestValue;
2818 splitPoint->master = master;
2819 splitPoint->mp = mp;
2820 splitPoint->moves = *moves;
2821 splitPoint->cpus = 1;
2822 splitPoint->pos.copy(p);
2823 splitPoint->parentSstack = sstck;
2824 for(i = 0; i < ActiveThreads; i++)
2825 splitPoint->slaves[i] = 0;
2827 // Copy the current position and the search stack to the master thread:
2828 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2829 Threads[master].splitPoint = splitPoint;
2831 // Make copies of the current position and search stack for each thread:
2832 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2834 if(thread_is_available(i, master)) {
2835 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2836 Threads[i].splitPoint = splitPoint;
2837 splitPoint->slaves[i] = 1;
2841 // Tell the threads that they have work to do. This will make them leave
2843 for(i = 0; i < ActiveThreads; i++)
2844 if(i == master || splitPoint->slaves[i]) {
2845 Threads[i].workIsWaiting = true;
2846 Threads[i].idle = false;
2847 Threads[i].stop = false;
2850 lock_release(&MPLock);
2852 // Everything is set up. The master thread enters the idle loop, from
2853 // which it will instantly launch a search, because its workIsWaiting
2854 // slot is 'true'. We send the split point as a second parameter to the
2855 // idle loop, which means that the main thread will return from the idle
2856 // loop when all threads have finished their work at this split point
2857 // (i.e. when // splitPoint->cpus == 0).
2858 idle_loop(master, splitPoint);
2860 // We have returned from the idle loop, which means that all threads are
2861 // finished. Update alpha, beta and bestvalue, and return:
2863 if(pvNode) *alpha = splitPoint->alpha;
2864 *beta = splitPoint->beta;
2865 *bestValue = splitPoint->bestValue;
2866 Threads[master].stop = false;
2867 Threads[master].idle = false;
2868 Threads[master].activeSplitPoints--;
2869 Threads[master].splitPoint = splitPoint->parent;
2870 lock_release(&MPLock);
2876 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2877 // to start a new search from the root.
2879 void wake_sleeping_threads() {
2880 if(ActiveThreads > 1) {
2881 for(int i = 1; i < ActiveThreads; i++) {
2882 Threads[i].idle = true;
2883 Threads[i].workIsWaiting = false;
2885 #if !defined(_MSC_VER)
2886 pthread_mutex_lock(&WaitLock);
2887 pthread_cond_broadcast(&WaitCond);
2888 pthread_mutex_unlock(&WaitLock);
2890 for(int i = 1; i < THREAD_MAX; i++)
2891 SetEvent(SitIdleEvent[i]);
2897 // init_thread() is the function which is called when a new thread is
2898 // launched. It simply calls the idle_loop() function with the supplied
2899 // threadID. There are two versions of this function; one for POSIX threads
2900 // and one for Windows threads.
2902 #if !defined(_MSC_VER)
2904 void *init_thread(void *threadID) {
2905 idle_loop(*(int *)threadID, NULL);
2911 DWORD WINAPI init_thread(LPVOID threadID) {
2912 idle_loop(*(int *)threadID, NULL);