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/>.
40 #include "ucioption.h"
44 //// Local definitions
51 // IterationInfoType stores search results for each 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 a "speculated value" and then move on. Speculated values are
59 // used just to calculate aspiration window width, so also if are
60 // not exact is not big a problem.
62 struct IterationInfoType {
64 IterationInfoType(Value v = Value(0), Value sv = Value(0))
65 : value(v), speculatedValue(sv) {}
67 Value value, speculatedValue;
71 // The BetaCounterType class is used to order moves at ply one.
72 // Apart for the first one that has its score, following moves
73 // normally have score -VALUE_INFINITE, so are ordered according
74 // to the number of beta cutoffs occurred under their subtree during
75 // the last iteration.
77 struct BetaCounterType {
81 void add(Color us, Depth d, int threadID);
82 void read(Color us, int64_t& our, int64_t& their);
84 int64_t hits[THREAD_MAX][2];
88 // The RootMove class is used for moves at the root at the tree. For each
89 // root move, we store a score, a node count, and a PV (really a refutation
90 // in the case of moves which fail low).
95 bool operator<(const RootMove&); // used to sort
99 int64_t nodes, cumulativeNodes;
100 Move pv[PLY_MAX_PLUS_2];
101 int64_t ourBeta, theirBeta;
105 // The RootMoveList class is essentially an array of RootMove objects, with
106 // a handful of methods for accessing the data in the individual moves.
111 RootMoveList(Position &pos, Move searchMoves[]);
112 inline Move get_move(int moveNum) const;
113 inline Value get_move_score(int moveNum) const;
114 inline void set_move_score(int moveNum, Value score);
115 inline void set_move_nodes(int moveNum, int64_t nodes);
116 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
117 void set_move_pv(int moveNum, const Move pv[]);
118 inline Move get_move_pv(int moveNum, int i) const;
119 inline int64_t get_move_cumulative_nodes(int moveNum) const;
120 inline int move_count() const;
121 Move scan_for_easy_move() const;
123 void sort_multipv(int n);
126 static const int MaxRootMoves = 500;
127 RootMove moves[MaxRootMoves];
132 /// Constants and variables
134 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
137 int LMRNonPVMoves = 4;
139 // Depth limit for use of dynamic threat detection:
140 Depth ThreatDepth = 5*OnePly;
142 // Depth limit for selective search:
143 Depth SelectiveDepth = 7*OnePly;
145 // Use internal iterative deepening?
146 const bool UseIIDAtPVNodes = true;
147 const bool UseIIDAtNonPVNodes = false;
149 // Internal iterative deepening margin. At Non-PV moves, when
150 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
151 // when the static evaluation is at most IIDMargin below beta.
152 const Value IIDMargin = Value(0x100);
154 // Easy move margin. An easy move candidate must be at least this much
155 // better than the second best move.
156 const Value EasyMoveMargin = Value(0x200);
158 // Problem margin. If the score of the first move at iteration N+1 has
159 // dropped by more than this since iteration N, the boolean variable
160 // "Problem" is set to true, which will make the program spend some extra
161 // time looking for a better move.
162 const Value ProblemMargin = Value(0x28);
164 // No problem margin. If the boolean "Problem" is true, and a new move
165 // is found at the root which is less than NoProblemMargin worse than the
166 // best move from the previous iteration, Problem is set back to false.
167 const Value NoProblemMargin = Value(0x14);
169 // Null move margin. A null move search will not be done if the approximate
170 // evaluation of the position is more than NullMoveMargin below beta.
171 const Value NullMoveMargin = Value(0x300);
173 // Pruning criterions. See the code and comments in ok_to_prune() to
174 // understand their precise meaning.
175 const bool PruneEscapeMoves = false;
176 const bool PruneDefendingMoves = false;
177 const bool PruneBlockingMoves = false;
179 // Use futility pruning?
180 bool UseQSearchFutilityPruning = true;
181 bool UseFutilityPruning = true;
183 // Margins for futility pruning in the quiescence search, and at frontier
184 // and near frontier nodes
185 Value FutilityMarginQS = Value(0x80);
186 Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
187 Value(0x2A0), Value(0x340), Value(0x3A0) };
190 const bool RazorAtDepthOne = false;
191 Depth RazorDepth = 4*OnePly;
192 Value RazorMargin = Value(0x300);
194 // Last seconds noise filtering (LSN)
195 bool UseLSNFiltering = false;
196 bool looseOnTime = false;
197 int LSNTime = 4 * 1000; // In milliseconds
198 Value LSNValue = Value(0x200);
200 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
201 Depth CheckExtension[2] = {OnePly, OnePly};
202 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
203 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
204 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
205 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
206 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
208 // Search depth at iteration 1
209 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
213 int NodesBetweenPolls = 30000;
215 // Iteration counters
217 BetaCounterType BetaCounter;
219 // Scores and number of times the best move changed for each iteration:
220 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
221 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
226 // Time managment variables
228 int MaxNodes, MaxDepth;
229 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
234 bool StopOnPonderhit;
240 bool PonderingEnabled;
243 // Show current line?
244 bool ShowCurrentLine = false;
247 bool UseLogFile = false;
248 std::ofstream LogFile;
250 // MP related variables
251 Depth MinimumSplitDepth = 4*OnePly;
252 int MaxThreadsPerSplitPoint = 4;
253 Thread Threads[THREAD_MAX];
255 bool AllThreadsShouldExit = false;
256 const int MaxActiveSplitPoints = 8;
257 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
260 #if !defined(_MSC_VER)
261 pthread_cond_t WaitCond;
262 pthread_mutex_t WaitLock;
264 HANDLE SitIdleEvent[THREAD_MAX];
270 Value id_loop(const Position &pos, Move searchMoves[]);
271 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta);
272 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
273 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
274 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
275 void sp_search(SplitPoint *sp, int threadID);
276 void sp_search_pv(SplitPoint *sp, int threadID);
277 void init_node(SearchStack ss[], int ply, int threadID);
278 void update_pv(SearchStack ss[], int ply);
279 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
280 bool connected_moves(const Position &pos, Move m1, Move m2);
281 bool value_is_mate(Value value);
282 bool move_is_killer(Move m, const SearchStack& ss);
283 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
284 bool ok_to_do_nullmove(const Position &pos);
285 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
286 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
287 bool ok_to_history(const Position &pos, Move m);
288 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
289 void update_killers(Move m, SearchStack& ss);
291 bool fail_high_ply_1();
292 int current_search_time();
296 void print_current_line(SearchStack ss[], int ply, int threadID);
297 void wait_for_stop_or_ponderhit();
299 void idle_loop(int threadID, SplitPoint *waitSp);
300 void init_split_point_stack();
301 void destroy_split_point_stack();
302 bool thread_should_stop(int threadID);
303 bool thread_is_available(int slave, int master);
304 bool idle_thread_exists(int master);
305 bool split(const Position &pos, SearchStack *ss, int ply,
306 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
307 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
308 void wake_sleeping_threads();
310 #if !defined(_MSC_VER)
311 void *init_thread(void *threadID);
313 DWORD WINAPI init_thread(LPVOID threadID);
320 //// Global variables
323 // The main transposition table
324 TranspositionTable TT = TranspositionTable(TTDefaultSize);
327 // Number of active threads:
328 int ActiveThreads = 1;
330 // Locks. In principle, there is no need for IOLock to be a global variable,
331 // but it could turn out to be useful for debugging.
334 History H; // Should be made local?
336 // The empty search stack
337 SearchStack EmptySearchStack;
340 // SearchStack::init() initializes a search stack. Used at the beginning of a
341 // new search from the root.
342 void SearchStack::init(int ply) {
344 pv[ply] = pv[ply + 1] = MOVE_NONE;
345 currentMove = threatMove = MOVE_NONE;
346 reduction = Depth(0);
349 void SearchStack::initKillers() {
351 mateKiller = MOVE_NONE;
352 for (int i = 0; i < KILLER_MAX; i++)
353 killers[i] = MOVE_NONE;
361 /// think() is the external interface to Stockfish's search, and is called when
362 /// the program receives the UCI 'go' command. It initializes various
363 /// search-related global variables, and calls root_search()
365 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
366 int time[], int increment[], int movesToGo, int maxDepth,
367 int maxNodes, int maxTime, Move searchMoves[]) {
369 // Look for a book move
370 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
373 if (get_option_value_string("Book File") != OpeningBook.file_name())
376 OpeningBook.open("book.bin");
378 bookMove = OpeningBook.get_move(pos);
379 if (bookMove != MOVE_NONE)
381 std::cout << "bestmove " << bookMove << std::endl;
386 // Initialize global search variables
388 SearchStartTime = get_system_time();
389 EasyMove = MOVE_NONE;
390 for (int i = 0; i < THREAD_MAX; i++)
392 Threads[i].nodes = 0ULL;
393 Threads[i].failHighPly1 = false;
396 InfiniteSearch = infinite;
397 PonderSearch = ponder;
398 StopOnPonderhit = false;
404 ExactMaxTime = maxTime;
406 // Read UCI option values
407 TT.set_size(get_option_value_int("Hash"));
408 if (button_was_pressed("Clear Hash"))
411 PonderingEnabled = get_option_value_bool("Ponder");
412 MultiPV = get_option_value_int("MultiPV");
414 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
415 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
417 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
418 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
420 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
421 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
423 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
424 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
426 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
427 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
429 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
430 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
432 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
433 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
434 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
435 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
437 Chess960 = get_option_value_bool("UCI_Chess960");
438 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
439 UseLogFile = get_option_value_bool("Use Search Log");
441 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
443 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
444 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
446 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
447 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
448 for (int i = 0; i < 6; i++)
449 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
451 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
452 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
454 UseLSNFiltering = get_option_value_bool("LSN filtering");
455 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
456 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
458 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
459 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
461 read_weights(pos.side_to_move());
463 int newActiveThreads = get_option_value_int("Threads");
464 if (newActiveThreads != ActiveThreads)
466 ActiveThreads = newActiveThreads;
467 init_eval(ActiveThreads);
470 // Wake up sleeping threads:
471 wake_sleeping_threads();
473 for (int i = 1; i < ActiveThreads; i++)
474 assert(thread_is_available(i, 0));
476 // Set thinking time:
477 int myTime = time[side_to_move];
478 int myIncrement = increment[side_to_move];
480 if (!movesToGo) // Sudden death time control
484 MaxSearchTime = myTime / 30 + myIncrement;
485 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
486 } else { // Blitz game without increment
487 MaxSearchTime = myTime / 30;
488 AbsoluteMaxSearchTime = myTime / 8;
491 else // (x moves) / (y minutes)
495 MaxSearchTime = myTime / 2;
496 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
498 MaxSearchTime = myTime / Min(movesToGo, 20);
499 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
503 if (PonderingEnabled)
505 MaxSearchTime += MaxSearchTime / 4;
506 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
509 // Fixed depth or fixed number of nodes?
512 InfiniteSearch = true; // HACK
517 NodesBetweenPolls = Min(MaxNodes, 30000);
518 InfiniteSearch = true; // HACK
521 NodesBetweenPolls = 30000;
524 // Write information to search log file:
526 LogFile << "Searching: " << pos.to_fen() << std::endl
527 << "infinite: " << infinite
528 << " ponder: " << ponder
529 << " time: " << myTime
530 << " increment: " << myIncrement
531 << " moves to go: " << movesToGo << std::endl;
534 // We're ready to start thinking. Call the iterative deepening loop
538 Value v = id_loop(pos, searchMoves);
539 looseOnTime = ( UseLSNFiltering
546 looseOnTime = false; // reset for next match
547 while (SearchStartTime + myTime + 1000 > get_system_time())
549 id_loop(pos, searchMoves); // to fail gracefully
566 /// init_threads() is called during startup. It launches all helper threads,
567 /// and initializes the split point stack and the global locks and condition
570 void init_threads() {
574 #if !defined(_MSC_VER)
575 pthread_t pthread[1];
578 for (i = 0; i < THREAD_MAX; i++)
579 Threads[i].activeSplitPoints = 0;
581 // Initialize global locks:
582 lock_init(&MPLock, NULL);
583 lock_init(&IOLock, NULL);
585 init_split_point_stack();
587 #if !defined(_MSC_VER)
588 pthread_mutex_init(&WaitLock, NULL);
589 pthread_cond_init(&WaitCond, NULL);
591 for (i = 0; i < THREAD_MAX; i++)
592 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
595 // All threads except the main thread should be initialized to idle state
596 for (i = 1; i < THREAD_MAX; i++)
598 Threads[i].stop = false;
599 Threads[i].workIsWaiting = false;
600 Threads[i].idle = true;
601 Threads[i].running = false;
604 // Launch the helper threads
605 for(i = 1; i < THREAD_MAX; i++)
607 #if !defined(_MSC_VER)
608 pthread_create(pthread, NULL, init_thread, (void*)(&i));
611 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
614 // Wait until the thread has finished launching:
615 while (!Threads[i].running);
618 // Init also the empty search stack
619 EmptySearchStack.init(0);
620 EmptySearchStack.initKillers();
624 /// stop_threads() is called when the program exits. It makes all the
625 /// helper threads exit cleanly.
627 void stop_threads() {
629 ActiveThreads = THREAD_MAX; // HACK
630 Idle = false; // HACK
631 wake_sleeping_threads();
632 AllThreadsShouldExit = true;
633 for (int i = 1; i < THREAD_MAX; i++)
635 Threads[i].stop = true;
636 while(Threads[i].running);
638 destroy_split_point_stack();
642 /// nodes_searched() returns the total number of nodes searched so far in
643 /// the current search.
645 int64_t nodes_searched() {
647 int64_t result = 0ULL;
648 for (int i = 0; i < ActiveThreads; i++)
649 result += Threads[i].nodes;
656 // id_loop() is the main iterative deepening loop. It calls root_search
657 // repeatedly with increasing depth until the allocated thinking time has
658 // been consumed, the user stops the search, or the maximum search depth is
661 Value id_loop(const Position &pos, Move searchMoves[]) {
664 SearchStack ss[PLY_MAX_PLUS_2];
666 // searchMoves are verified, copied, scored and sorted
667 RootMoveList rml(p, searchMoves);
672 for (int i = 0; i < 3; i++)
677 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
680 EasyMove = rml.scan_for_easy_move();
682 // Iterative deepening loop
683 while (Iteration < PLY_MAX)
685 // Initialize iteration
688 BestMoveChangesByIteration[Iteration] = 0;
692 std::cout << "info depth " << Iteration << std::endl;
694 // Calculate dynamic search window based on previous iterations
697 if (MultiPV == 1 && Iteration >= 6)
699 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
700 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
702 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
704 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
705 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
709 alpha = - VALUE_INFINITE;
710 beta = VALUE_INFINITE;
713 // Search to the current depth
714 Value value = root_search(p, ss, rml, alpha, beta);
716 // Write PV to transposition table, in case the relevant entries have
717 // been overwritten during the search.
718 TT.insert_pv(p, ss[0].pv);
721 break; // Value cannot be trusted. Break out immediately!
723 //Save info about search result
724 Value speculatedValue;
727 Value delta = value - IterationInfo[Iteration - 1].value;
734 speculatedValue = value + delta;
735 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
737 else if (value <= alpha)
739 assert(value == alpha);
743 speculatedValue = value + delta;
744 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
746 speculatedValue = value;
748 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
749 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
751 // Erase the easy move if it differs from the new best move
752 if (ss[0].pv[0] != EasyMove)
753 EasyMove = MOVE_NONE;
760 bool stopSearch = false;
762 // Stop search early if there is only a single legal move:
763 if (Iteration >= 6 && rml.move_count() == 1)
766 // Stop search early when the last two iterations returned a mate score
768 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
769 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
772 // Stop search early if one move seems to be much better than the rest
773 int64_t nodes = nodes_searched();
777 && EasyMove == ss[0].pv[0]
778 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
779 && current_search_time() > MaxSearchTime / 16)
780 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
781 && current_search_time() > MaxSearchTime / 32)))
784 // Add some extra time if the best move has changed during the last two iterations
785 if (Iteration > 5 && Iteration <= 50)
786 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
787 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
789 // Stop search if most of MaxSearchTime is consumed at the end of the
790 // iteration. We probably don't have enough time to search the first
791 // move at the next iteration anyway.
792 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
797 //FIXME: Implement fail-low emergency measures
801 StopOnPonderhit = true;
805 if (MaxDepth && Iteration >= MaxDepth)
811 // If we are pondering, we shouldn't print the best move before we
814 wait_for_stop_or_ponderhit();
816 // Print final search statistics
817 std::cout << "info nodes " << nodes_searched()
819 << " time " << current_search_time()
820 << " hashfull " << TT.full() << std::endl;
822 // Print the best move and the ponder move to the standard output
823 if (ss[0].pv[0] == MOVE_NONE)
825 ss[0].pv[0] = rml.get_move(0);
826 ss[0].pv[1] = MOVE_NONE;
828 std::cout << "bestmove " << ss[0].pv[0];
829 if (ss[0].pv[1] != MOVE_NONE)
830 std::cout << " ponder " << ss[0].pv[1];
832 std::cout << std::endl;
837 dbg_print_mean(LogFile);
839 if (dbg_show_hit_rate)
840 dbg_print_hit_rate(LogFile);
843 LogFile << "Nodes: " << nodes_searched() << std::endl
844 << "Nodes/second: " << nps() << std::endl
845 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
847 p.do_move(ss[0].pv[0], st);
848 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
849 << std::endl << std::endl;
851 return rml.get_move_score(0);
855 // root_search() is the function which searches the root node. It is
856 // similar to search_pv except that it uses a different move ordering
857 // scheme (perhaps we should try to use this at internal PV nodes, too?)
858 // and prints some information to the standard output.
860 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
862 Value oldAlpha = alpha;
864 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
866 // Loop through all the moves in the root move list
867 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
871 // We failed high, invalidate and skip next moves, leave node-counters
872 // and beta-counters as they are and quickly return, we will try to do
873 // a research at the next iteration with a bigger aspiration window.
874 rml.set_move_score(i, -VALUE_INFINITE);
882 RootMoveNumber = i + 1;
885 // Remember the node count before the move is searched. The node counts
886 // are used to sort the root moves at the next iteration.
887 nodes = nodes_searched();
889 // Reset beta cut-off counters
892 // Pick the next root move, and print the move and the move number to
893 // the standard output.
894 move = ss[0].currentMove = rml.get_move(i);
895 if (current_search_time() >= 1000)
896 std::cout << "info currmove " << move
897 << " currmovenumber " << i + 1 << std::endl;
899 // Decide search depth for this move
901 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
902 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
904 // Make the move, and search it
905 pos.do_move(move, st, dcCandidates);
909 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
910 // If the value has dropped a lot compared to the last iteration,
911 // set the boolean variable Problem to true. This variable is used
912 // for time managment: When Problem is true, we try to complete the
913 // current iteration before playing a move.
914 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
916 if (Problem && StopOnPonderhit)
917 StopOnPonderhit = false;
921 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
924 // Fail high! Set the boolean variable FailHigh to true, and
925 // re-search the move with a big window. The variable FailHigh is
926 // used for time managment: We try to avoid aborting the search
927 // prematurely during a fail high research.
929 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
935 // Finished searching the move. If AbortSearch is true, the search
936 // was aborted because the user interrupted the search or because we
937 // ran out of time. In this case, the return value of the search cannot
938 // be trusted, and we break out of the loop without updating the best
943 // Remember the node count for this move. The node counts are used to
944 // sort the root moves at the next iteration.
945 rml.set_move_nodes(i, nodes_searched() - nodes);
947 // Remember the beta-cutoff statistics
949 BetaCounter.read(pos.side_to_move(), our, their);
950 rml.set_beta_counters(i, our, their);
952 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
954 if (value <= alpha && i >= MultiPV)
955 rml.set_move_score(i, -VALUE_INFINITE);
958 // PV move or new best move!
961 rml.set_move_score(i, value);
963 rml.set_move_pv(i, ss[0].pv);
967 // We record how often the best move has been changed in each
968 // iteration. This information is used for time managment: When
969 // the best move changes frequently, we allocate some more time.
971 BestMoveChangesByIteration[Iteration]++;
973 // Print search information to the standard output:
974 std::cout << "info depth " << Iteration
975 << " score " << value_to_string(value)
976 << " time " << current_search_time()
977 << " nodes " << nodes_searched()
981 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
982 std::cout << ss[0].pv[j] << " ";
984 std::cout << std::endl;
987 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
993 // Reset the global variable Problem to false if the value isn't too
994 // far below the final value from the last iteration.
995 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1000 rml.sort_multipv(i);
1001 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1004 std::cout << "info multipv " << j + 1
1005 << " score " << value_to_string(rml.get_move_score(j))
1006 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1007 << " time " << current_search_time()
1008 << " nodes " << nodes_searched()
1012 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1013 std::cout << rml.get_move_pv(j, k) << " ";
1015 std::cout << std::endl;
1017 alpha = rml.get_move_score(Min(i, MultiPV-1));
1019 } // New best move case
1021 assert(alpha >= oldAlpha);
1023 FailLow = (alpha == oldAlpha);
1029 // search_pv() is the main search function for PV nodes.
1031 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1032 Depth depth, int ply, int threadID) {
1034 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1035 assert(beta > alpha && beta <= VALUE_INFINITE);
1036 assert(ply >= 0 && ply < PLY_MAX);
1037 assert(threadID >= 0 && threadID < ActiveThreads);
1040 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1042 // Initialize, and make an early exit in case of an aborted search,
1043 // an instant draw, maximum ply reached, etc.
1044 init_node(ss, ply, threadID);
1046 // After init_node() that calls poll()
1047 if (AbortSearch || thread_should_stop(threadID))
1055 if (ply >= PLY_MAX - 1)
1056 return evaluate(pos, ei, threadID);
1058 // Mate distance pruning
1059 Value oldAlpha = alpha;
1060 alpha = Max(value_mated_in(ply), alpha);
1061 beta = Min(value_mate_in(ply+1), beta);
1065 // Transposition table lookup. At PV nodes, we don't use the TT for
1066 // pruning, but only for move ordering.
1067 const TTEntry* tte = TT.retrieve(pos);
1068 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1070 // Go with internal iterative deepening if we don't have a TT move
1071 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1073 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1074 ttMove = ss[ply].pv[ply];
1077 // Initialize a MovePicker object for the current position, and prepare
1078 // to search all moves
1079 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1081 Move move, movesSearched[256];
1083 Value value, bestValue = -VALUE_INFINITE;
1084 Bitboard dcCandidates = mp.discovered_check_candidates();
1085 Color us = pos.side_to_move();
1086 bool isCheck = pos.is_check();
1087 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1089 // Loop through all legal moves until no moves remain or a beta cutoff
1091 while ( alpha < beta
1092 && (move = mp.get_next_move()) != MOVE_NONE
1093 && !thread_should_stop(threadID))
1095 assert(move_is_ok(move));
1097 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1098 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1099 bool moveIsCapture = pos.move_is_capture(move);
1101 movesSearched[moveCount++] = ss[ply].currentMove = move;
1103 // Decide the new search depth
1105 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1106 Depth newDepth = depth - OnePly + ext;
1108 // Make and search the move
1110 pos.do_move(move, st, dcCandidates);
1112 if (moveCount == 1) // The first move in list is the PV
1113 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1116 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1117 // if the move fails high will be re-searched at full depth.
1118 if ( depth >= 2*OnePly
1119 && moveCount >= LMRPVMoves
1122 && !move_promotion(move)
1123 && !move_is_castle(move)
1124 && !move_is_killer(move, ss[ply]))
1126 ss[ply].reduction = OnePly;
1127 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1130 value = alpha + 1; // Just to trigger next condition
1132 if (value > alpha) // Go with full depth non-pv search
1134 ss[ply].reduction = Depth(0);
1135 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1136 if (value > alpha && value < beta)
1138 // When the search fails high at ply 1 while searching the first
1139 // move at the root, set the flag failHighPly1. This is used for
1140 // time managment: We don't want to stop the search early in
1141 // such cases, because resolving the fail high at ply 1 could
1142 // result in a big drop in score at the root.
1143 if (ply == 1 && RootMoveNumber == 1)
1144 Threads[threadID].failHighPly1 = true;
1146 // A fail high occurred. Re-search at full window (pv search)
1147 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1148 Threads[threadID].failHighPly1 = false;
1152 pos.undo_move(move);
1154 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1157 if (value > bestValue)
1164 if (value == value_mate_in(ply + 1))
1165 ss[ply].mateKiller = move;
1167 // If we are at ply 1, and we are searching the first root move at
1168 // ply 0, set the 'Problem' variable if the score has dropped a lot
1169 // (from the computer's point of view) since the previous iteration:
1172 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1177 if ( ActiveThreads > 1
1179 && depth >= MinimumSplitDepth
1181 && idle_thread_exists(threadID)
1183 && !thread_should_stop(threadID)
1184 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1185 &moveCount, &mp, dcCandidates, threadID, true))
1189 // All legal moves have been searched. A special case: If there were
1190 // no legal moves, it must be mate or stalemate:
1192 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1194 // If the search is not aborted, update the transposition table,
1195 // history counters, and killer moves.
1196 if (AbortSearch || thread_should_stop(threadID))
1199 if (bestValue <= oldAlpha)
1200 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1202 else if (bestValue >= beta)
1204 BetaCounter.add(pos.side_to_move(), depth, threadID);
1205 Move m = ss[ply].pv[ply];
1206 if (ok_to_history(pos, m)) // Only non capture moves are considered
1208 update_history(pos, m, depth, movesSearched, moveCount);
1209 update_killers(m, ss[ply]);
1211 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1214 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1220 // search() is the search function for zero-width nodes.
1222 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1223 int ply, bool allowNullmove, int threadID) {
1225 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1226 assert(ply >= 0 && ply < PLY_MAX);
1227 assert(threadID >= 0 && threadID < ActiveThreads);
1230 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1232 // Initialize, and make an early exit in case of an aborted search,
1233 // an instant draw, maximum ply reached, etc.
1234 init_node(ss, ply, threadID);
1236 // After init_node() that calls poll()
1237 if (AbortSearch || thread_should_stop(threadID))
1245 if (ply >= PLY_MAX - 1)
1246 return evaluate(pos, ei, threadID);
1248 // Mate distance pruning
1249 if (value_mated_in(ply) >= beta)
1252 if (value_mate_in(ply + 1) < beta)
1255 // Transposition table lookup
1256 const TTEntry* tte = TT.retrieve(pos);
1257 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1259 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1261 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1262 return value_from_tt(tte->value(), ply);
1265 Value approximateEval = quick_evaluate(pos);
1266 bool mateThreat = false;
1267 bool isCheck = pos.is_check();
1273 && !value_is_mate(beta)
1274 && ok_to_do_nullmove(pos)
1275 && approximateEval >= beta - NullMoveMargin)
1277 ss[ply].currentMove = MOVE_NULL;
1280 pos.do_null_move(st);
1281 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1283 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1285 pos.undo_null_move();
1287 if (value_is_mate(nullValue))
1289 /* Do not return unproven mates */
1291 else if (nullValue >= beta)
1293 if (depth < 6 * OnePly)
1296 // Do zugzwang verification search
1297 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1301 // The null move failed low, which means that we may be faced with
1302 // some kind of threat. If the previous move was reduced, check if
1303 // the move that refuted the null move was somehow connected to the
1304 // move which was reduced. If a connection is found, return a fail
1305 // low score (which will cause the reduced move to fail high in the
1306 // parent node, which will trigger a re-search with full depth).
1307 if (nullValue == value_mated_in(ply + 2))
1310 ss[ply].threatMove = ss[ply + 1].currentMove;
1311 if ( depth < ThreatDepth
1312 && ss[ply - 1].reduction
1313 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1317 // Null move search not allowed, try razoring
1318 else if ( !value_is_mate(beta)
1319 && approximateEval < beta - RazorMargin
1320 && depth < RazorDepth
1321 && (RazorAtDepthOne || depth > OnePly)
1322 && ttMove == MOVE_NONE
1323 && !pos.has_pawn_on_7th(pos.side_to_move()))
1325 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1326 if ( (v < beta - RazorMargin - RazorMargin / 4)
1327 || (depth <= 2*OnePly && v < beta - RazorMargin)
1328 || (depth <= OnePly && v < beta - RazorMargin / 2))
1332 // Go with internal iterative deepening if we don't have a TT move
1333 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1334 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1336 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1337 ttMove = ss[ply].pv[ply];
1340 // Initialize a MovePicker object for the current position, and prepare
1341 // to search all moves:
1342 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1344 Move move, movesSearched[256];
1346 Value value, bestValue = -VALUE_INFINITE;
1347 Bitboard dcCandidates = mp.discovered_check_candidates();
1348 Value futilityValue = VALUE_NONE;
1349 bool useFutilityPruning = UseFutilityPruning
1350 && depth < SelectiveDepth
1353 // Loop through all legal moves until no moves remain or a beta cutoff
1355 while ( bestValue < beta
1356 && (move = mp.get_next_move()) != MOVE_NONE
1357 && !thread_should_stop(threadID))
1359 assert(move_is_ok(move));
1361 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1362 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1363 bool moveIsCapture = pos.move_is_capture(move);
1365 movesSearched[moveCount++] = ss[ply].currentMove = move;
1367 // Decide the new search depth
1369 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1370 Depth newDepth = depth - OnePly + ext;
1373 if ( useFutilityPruning
1376 && !move_promotion(move))
1378 // History pruning. See ok_to_prune() definition
1379 if ( moveCount >= 2 + int(depth)
1380 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1383 // Value based pruning
1384 if (depth < 7 * OnePly && approximateEval < beta)
1386 if (futilityValue == VALUE_NONE)
1387 futilityValue = evaluate(pos, ei, threadID)
1388 + FutilityMargins[int(depth)/2 - 1]
1391 if (futilityValue < beta)
1393 if (futilityValue > bestValue)
1394 bestValue = futilityValue;
1400 // Make and search the move
1402 pos.do_move(move, st, dcCandidates);
1404 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1405 // if the move fails high will be re-searched at full depth.
1406 if ( depth >= 2*OnePly
1407 && moveCount >= LMRNonPVMoves
1410 && !move_promotion(move)
1411 && !move_is_castle(move)
1412 && !move_is_killer(move, ss[ply]))
1414 ss[ply].reduction = OnePly;
1415 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1418 value = beta; // Just to trigger next condition
1420 if (value >= beta) // Go with full depth non-pv search
1422 ss[ply].reduction = Depth(0);
1423 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1425 pos.undo_move(move);
1427 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1430 if (value > bestValue)
1436 if (value == value_mate_in(ply + 1))
1437 ss[ply].mateKiller = move;
1441 if ( ActiveThreads > 1
1443 && depth >= MinimumSplitDepth
1445 && idle_thread_exists(threadID)
1447 && !thread_should_stop(threadID)
1448 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1449 &mp, dcCandidates, threadID, false))
1453 // All legal moves have been searched. A special case: If there were
1454 // no legal moves, it must be mate or stalemate.
1456 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1458 // If the search is not aborted, update the transposition table,
1459 // history counters, and killer moves.
1460 if (AbortSearch || thread_should_stop(threadID))
1463 if (bestValue < beta)
1464 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1467 BetaCounter.add(pos.side_to_move(), depth, threadID);
1468 Move m = ss[ply].pv[ply];
1469 if (ok_to_history(pos, m)) // Only non capture moves are considered
1471 update_history(pos, m, depth, movesSearched, moveCount);
1472 update_killers(m, ss[ply]);
1474 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1477 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1483 // qsearch() is the quiescence search function, which is called by the main
1484 // search function when the remaining depth is zero (or, to be more precise,
1485 // less than OnePly).
1487 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1488 Depth depth, int ply, int threadID) {
1490 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1491 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1493 assert(ply >= 0 && ply < PLY_MAX);
1494 assert(threadID >= 0 && threadID < ActiveThreads);
1496 // Initialize, and make an early exit in case of an aborted search,
1497 // an instant draw, maximum ply reached, etc.
1498 init_node(ss, ply, threadID);
1500 // After init_node() that calls poll()
1501 if (AbortSearch || thread_should_stop(threadID))
1507 // Transposition table lookup, only when not in PV
1508 TTEntry* tte = NULL;
1509 bool pvNode = (beta - alpha != 1);
1512 tte = TT.retrieve(pos);
1513 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1515 assert(tte->type() != VALUE_TYPE_EVAL);
1517 return value_from_tt(tte->value(), ply);
1520 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1522 // Evaluate the position statically
1525 bool isCheck = pos.is_check();
1526 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1529 staticValue = -VALUE_INFINITE;
1531 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1533 // Use the cached evaluation score if possible
1534 assert(tte->value() == evaluate(pos, ei, threadID));
1535 assert(ei.futilityMargin == Value(0));
1537 staticValue = tte->value();
1540 staticValue = evaluate(pos, ei, threadID);
1542 if (ply == PLY_MAX - 1)
1543 return evaluate(pos, ei, threadID);
1545 // Initialize "stand pat score", and return it immediately if it is
1547 Value bestValue = staticValue;
1549 if (bestValue >= beta)
1551 // Store the score to avoid a future costly evaluation() call
1552 if (!isCheck && !tte && ei.futilityMargin == 0)
1553 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1558 if (bestValue > alpha)
1561 // Initialize a MovePicker object for the current position, and prepare
1562 // to search the moves. Because the depth is <= 0 here, only captures,
1563 // queen promotions and checks (only if depth == 0) will be generated.
1564 MovePicker mp = MovePicker(pos, pvNode, ttMove, EmptySearchStack, depth);
1567 Bitboard dcCandidates = mp.discovered_check_candidates();
1568 Color us = pos.side_to_move();
1569 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1571 // Loop through the moves until no moves remain or a beta cutoff
1573 while ( alpha < beta
1574 && (move = mp.get_next_move()) != MOVE_NONE)
1576 assert(move_is_ok(move));
1579 ss[ply].currentMove = move;
1582 if ( UseQSearchFutilityPruning
1586 && !move_promotion(move)
1587 && !pos.move_is_check(move, dcCandidates)
1588 && !pos.move_is_passed_pawn_push(move))
1590 Value futilityValue = staticValue
1591 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1592 pos.endgame_value_of_piece_on(move_to(move)))
1593 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1595 + ei.futilityMargin;
1597 if (futilityValue < alpha)
1599 if (futilityValue > bestValue)
1600 bestValue = futilityValue;
1605 // Don't search captures and checks with negative SEE values
1607 && !move_promotion(move)
1608 && (pos.midgame_value_of_piece_on(move_from(move)) >
1609 pos.midgame_value_of_piece_on(move_to(move)))
1610 && pos.see(move) < 0)
1613 // Make and search the move.
1615 pos.do_move(move, st, dcCandidates);
1616 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1617 pos.undo_move(move);
1619 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1622 if (value > bestValue)
1633 // All legal moves have been searched. A special case: If we're in check
1634 // and no legal moves were found, it is checkmate:
1635 if (pos.is_check() && moveCount == 0) // Mate!
1636 return value_mated_in(ply);
1638 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1640 // Update transposition table
1641 Move m = ss[ply].pv[ply];
1644 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1645 if (bestValue < beta)
1646 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_UPPER);
1648 TT.store(pos, value_to_tt(bestValue, ply), d, m, VALUE_TYPE_LOWER);
1651 // Update killers only for good check moves
1652 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1653 update_killers(m, ss[ply]);
1659 // sp_search() is used to search from a split point. This function is called
1660 // by each thread working at the split point. It is similar to the normal
1661 // search() function, but simpler. Because we have already probed the hash
1662 // table, done a null move search, and searched the first move before
1663 // splitting, we don't have to repeat all this work in sp_search(). We
1664 // also don't need to store anything to the hash table here: This is taken
1665 // care of after we return from the split point.
1667 void sp_search(SplitPoint *sp, int threadID) {
1669 assert(threadID >= 0 && threadID < ActiveThreads);
1670 assert(ActiveThreads > 1);
1672 Position pos = Position(sp->pos);
1673 SearchStack *ss = sp->sstack[threadID];
1676 bool isCheck = pos.is_check();
1677 bool useFutilityPruning = UseFutilityPruning
1678 && sp->depth < SelectiveDepth
1681 while ( sp->bestValue < sp->beta
1682 && !thread_should_stop(threadID)
1683 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1685 assert(move_is_ok(move));
1687 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1688 bool moveIsCapture = pos.move_is_capture(move);
1690 lock_grab(&(sp->lock));
1691 int moveCount = ++sp->moves;
1692 lock_release(&(sp->lock));
1694 ss[sp->ply].currentMove = move;
1696 // Decide the new search depth.
1698 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1699 Depth newDepth = sp->depth - OnePly + ext;
1702 if ( useFutilityPruning
1705 && !move_promotion(move)
1706 && moveCount >= 2 + int(sp->depth)
1707 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1710 // Make and search the move.
1712 pos.do_move(move, st, sp->dcCandidates);
1714 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1715 // if the move fails high will be re-searched at full depth.
1717 && moveCount >= LMRNonPVMoves
1719 && !move_promotion(move)
1720 && !move_is_castle(move)
1721 && !move_is_killer(move, ss[sp->ply]))
1723 ss[sp->ply].reduction = OnePly;
1724 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1727 value = sp->beta; // Just to trigger next condition
1729 if (value >= sp->beta) // Go with full depth non-pv search
1731 ss[sp->ply].reduction = Depth(0);
1732 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1734 pos.undo_move(move);
1736 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1738 if (thread_should_stop(threadID))
1742 lock_grab(&(sp->lock));
1743 if (value > sp->bestValue && !thread_should_stop(threadID))
1745 sp->bestValue = value;
1746 if (sp->bestValue >= sp->beta)
1748 sp_update_pv(sp->parentSstack, ss, sp->ply);
1749 for (int i = 0; i < ActiveThreads; i++)
1750 if (i != threadID && (i == sp->master || sp->slaves[i]))
1751 Threads[i].stop = true;
1753 sp->finished = true;
1756 lock_release(&(sp->lock));
1759 lock_grab(&(sp->lock));
1761 // If this is the master thread and we have been asked to stop because of
1762 // a beta cutoff higher up in the tree, stop all slave threads:
1763 if (sp->master == threadID && thread_should_stop(threadID))
1764 for (int i = 0; i < ActiveThreads; i++)
1766 Threads[i].stop = true;
1769 sp->slaves[threadID] = 0;
1771 lock_release(&(sp->lock));
1775 // sp_search_pv() is used to search from a PV split point. This function
1776 // is called by each thread working at the split point. It is similar to
1777 // the normal search_pv() function, but simpler. Because we have already
1778 // probed the hash table and searched the first move before splitting, we
1779 // don't have to repeat all this work in sp_search_pv(). We also don't
1780 // need to store anything to the hash table here: This is taken care of
1781 // after we return from the split point.
1783 void sp_search_pv(SplitPoint *sp, int threadID) {
1785 assert(threadID >= 0 && threadID < ActiveThreads);
1786 assert(ActiveThreads > 1);
1788 Position pos = Position(sp->pos);
1789 SearchStack *ss = sp->sstack[threadID];
1793 while ( sp->alpha < sp->beta
1794 && !thread_should_stop(threadID)
1795 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1797 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1798 bool moveIsCapture = pos.move_is_capture(move);
1800 assert(move_is_ok(move));
1802 lock_grab(&(sp->lock));
1803 int moveCount = ++sp->moves;
1804 lock_release(&(sp->lock));
1806 ss[sp->ply].currentMove = move;
1808 // Decide the new search depth.
1810 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1811 Depth newDepth = sp->depth - OnePly + ext;
1813 // Make and search the move.
1815 pos.do_move(move, st, sp->dcCandidates);
1817 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1818 // if the move fails high will be re-searched at full depth.
1820 && moveCount >= LMRPVMoves
1822 && !move_promotion(move)
1823 && !move_is_castle(move)
1824 && !move_is_killer(move, ss[sp->ply]))
1826 ss[sp->ply].reduction = OnePly;
1827 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1830 value = sp->alpha + 1; // Just to trigger next condition
1832 if (value > sp->alpha) // Go with full depth non-pv search
1834 ss[sp->ply].reduction = Depth(0);
1835 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1837 if (value > sp->alpha && value < sp->beta)
1839 // When the search fails high at ply 1 while searching the first
1840 // move at the root, set the flag failHighPly1. This is used for
1841 // time managment: We don't want to stop the search early in
1842 // such cases, because resolving the fail high at ply 1 could
1843 // result in a big drop in score at the root.
1844 if (sp->ply == 1 && RootMoveNumber == 1)
1845 Threads[threadID].failHighPly1 = true;
1847 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1848 Threads[threadID].failHighPly1 = false;
1851 pos.undo_move(move);
1853 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1855 if (thread_should_stop(threadID))
1859 lock_grab(&(sp->lock));
1860 if (value > sp->bestValue && !thread_should_stop(threadID))
1862 sp->bestValue = value;
1863 if (value > sp->alpha)
1866 sp_update_pv(sp->parentSstack, ss, sp->ply);
1867 if (value == value_mate_in(sp->ply + 1))
1868 ss[sp->ply].mateKiller = move;
1870 if(value >= sp->beta)
1872 for(int i = 0; i < ActiveThreads; i++)
1873 if(i != threadID && (i == sp->master || sp->slaves[i]))
1874 Threads[i].stop = true;
1876 sp->finished = true;
1879 // If we are at ply 1, and we are searching the first root move at
1880 // ply 0, set the 'Problem' variable if the score has dropped a lot
1881 // (from the computer's point of view) since the previous iteration.
1884 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1887 lock_release(&(sp->lock));
1890 lock_grab(&(sp->lock));
1892 // If this is the master thread and we have been asked to stop because of
1893 // a beta cutoff higher up in the tree, stop all slave threads.
1894 if (sp->master == threadID && thread_should_stop(threadID))
1895 for (int i = 0; i < ActiveThreads; i++)
1897 Threads[i].stop = true;
1900 sp->slaves[threadID] = 0;
1902 lock_release(&(sp->lock));
1905 /// The BetaCounterType class
1907 BetaCounterType::BetaCounterType() { clear(); }
1909 void BetaCounterType::clear() {
1911 for (int i = 0; i < THREAD_MAX; i++)
1912 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1915 void BetaCounterType::add(Color us, Depth d, int threadID) {
1917 // Weighted count based on depth
1918 hits[threadID][us] += int(d);
1921 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1924 for (int i = 0; i < THREAD_MAX; i++)
1927 their += hits[i][opposite_color(us)];
1932 /// The RootMove class
1936 RootMove::RootMove() {
1937 nodes = cumulativeNodes = 0ULL;
1940 // RootMove::operator<() is the comparison function used when
1941 // sorting the moves. A move m1 is considered to be better
1942 // than a move m2 if it has a higher score, or if the moves
1943 // have equal score but m1 has the higher node count.
1945 bool RootMove::operator<(const RootMove& m) {
1947 if (score != m.score)
1948 return (score < m.score);
1950 return theirBeta <= m.theirBeta;
1953 /// The RootMoveList class
1957 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1959 MoveStack mlist[MaxRootMoves];
1960 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1962 // Generate all legal moves
1963 int lm_count = generate_legal_moves(pos, mlist);
1965 // Add each move to the moves[] array
1966 for (int i = 0; i < lm_count; i++)
1968 bool includeMove = includeAllMoves;
1970 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1971 includeMove = (searchMoves[k] == mlist[i].move);
1975 // Find a quick score for the move
1977 SearchStack ss[PLY_MAX_PLUS_2];
1979 moves[count].move = mlist[i].move;
1980 moves[count].nodes = 0ULL;
1981 pos.do_move(moves[count].move, st);
1982 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1984 pos.undo_move(moves[count].move);
1985 moves[count].pv[0] = moves[i].move;
1986 moves[count].pv[1] = MOVE_NONE; // FIXME
1994 // Simple accessor methods for the RootMoveList class
1996 inline Move RootMoveList::get_move(int moveNum) const {
1997 return moves[moveNum].move;
2000 inline Value RootMoveList::get_move_score(int moveNum) const {
2001 return moves[moveNum].score;
2004 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2005 moves[moveNum].score = score;
2008 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2009 moves[moveNum].nodes = nodes;
2010 moves[moveNum].cumulativeNodes += nodes;
2013 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2014 moves[moveNum].ourBeta = our;
2015 moves[moveNum].theirBeta = their;
2018 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2020 for(j = 0; pv[j] != MOVE_NONE; j++)
2021 moves[moveNum].pv[j] = pv[j];
2022 moves[moveNum].pv[j] = MOVE_NONE;
2025 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2026 return moves[moveNum].pv[i];
2029 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2030 return moves[moveNum].cumulativeNodes;
2033 inline int RootMoveList::move_count() const {
2038 // RootMoveList::scan_for_easy_move() is called at the end of the first
2039 // iteration, and is used to detect an "easy move", i.e. a move which appears
2040 // to be much bester than all the rest. If an easy move is found, the move
2041 // is returned, otherwise the function returns MOVE_NONE. It is very
2042 // important that this function is called at the right moment: The code
2043 // assumes that the first iteration has been completed and the moves have
2044 // been sorted. This is done in RootMoveList c'tor.
2046 Move RootMoveList::scan_for_easy_move() const {
2053 // moves are sorted so just consider the best and the second one
2054 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2060 // RootMoveList::sort() sorts the root move list at the beginning of a new
2063 inline void RootMoveList::sort() {
2065 sort_multipv(count - 1); // all items
2069 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2070 // list by their scores and depths. It is used to order the different PVs
2071 // correctly in MultiPV mode.
2073 void RootMoveList::sort_multipv(int n) {
2075 for (int i = 1; i <= n; i++)
2077 RootMove rm = moves[i];
2079 for (j = i; j > 0 && moves[j-1] < rm; j--)
2080 moves[j] = moves[j-1];
2086 // init_node() is called at the beginning of all the search functions
2087 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2088 // stack object corresponding to the current node. Once every
2089 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2090 // for user input and checks whether it is time to stop the search.
2092 void init_node(SearchStack ss[], int ply, int threadID) {
2093 assert(ply >= 0 && ply < PLY_MAX);
2094 assert(threadID >= 0 && threadID < ActiveThreads);
2096 Threads[threadID].nodes++;
2100 if(NodesSincePoll >= NodesBetweenPolls) {
2107 ss[ply+2].initKillers();
2109 if(Threads[threadID].printCurrentLine)
2110 print_current_line(ss, ply, threadID);
2114 // update_pv() is called whenever a search returns a value > alpha. It
2115 // updates the PV in the SearchStack object corresponding to the current
2118 void update_pv(SearchStack ss[], int ply) {
2119 assert(ply >= 0 && ply < PLY_MAX);
2121 ss[ply].pv[ply] = ss[ply].currentMove;
2123 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2124 ss[ply].pv[p] = ss[ply+1].pv[p];
2125 ss[ply].pv[p] = MOVE_NONE;
2129 // sp_update_pv() is a variant of update_pv for use at split points. The
2130 // difference between the two functions is that sp_update_pv also updates
2131 // the PV at the parent node.
2133 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2134 assert(ply >= 0 && ply < PLY_MAX);
2136 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2138 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2139 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2140 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2144 // connected_moves() tests whether two moves are 'connected' in the sense
2145 // that the first move somehow made the second move possible (for instance
2146 // if the moving piece is the same in both moves). The first move is
2147 // assumed to be the move that was made to reach the current position, while
2148 // the second move is assumed to be a move from the current position.
2150 bool connected_moves(const Position &pos, Move m1, Move m2) {
2151 Square f1, t1, f2, t2;
2153 assert(move_is_ok(m1));
2154 assert(move_is_ok(m2));
2159 // Case 1: The moving piece is the same in both moves.
2165 // Case 2: The destination square for m2 was vacated by m1.
2171 // Case 3: Moving through the vacated square:
2172 if(piece_is_slider(pos.piece_on(f2)) &&
2173 bit_is_set(squares_between(f2, t2), f1))
2176 // Case 4: The destination square for m2 is attacked by the moving piece
2178 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2181 // Case 5: Discovered check, checking piece is the piece moved in m1:
2182 if(piece_is_slider(pos.piece_on(t1)) &&
2183 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2185 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2187 Bitboard occ = pos.occupied_squares();
2188 Color us = pos.side_to_move();
2189 Square ksq = pos.king_square(us);
2190 clear_bit(&occ, f2);
2191 if(pos.type_of_piece_on(t1) == BISHOP) {
2192 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2195 else if(pos.type_of_piece_on(t1) == ROOK) {
2196 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2200 assert(pos.type_of_piece_on(t1) == QUEEN);
2201 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2210 // value_is_mate() checks if the given value is a mate one
2211 // eventually compensated for the ply.
2213 bool value_is_mate(Value value) {
2215 assert(abs(value) <= VALUE_INFINITE);
2217 return value <= value_mated_in(PLY_MAX)
2218 || value >= value_mate_in(PLY_MAX);
2222 // move_is_killer() checks if the given move is among the
2223 // killer moves of that ply.
2225 bool move_is_killer(Move m, const SearchStack& ss) {
2227 const Move* k = ss.killers;
2228 for (int i = 0; i < KILLER_MAX; i++, k++)
2236 // extension() decides whether a move should be searched with normal depth,
2237 // or with extended depth. Certain classes of moves (checking moves, in
2238 // particular) are searched with bigger depth than ordinary moves and in
2239 // any case are marked as 'dangerous'. Note that also if a move is not
2240 // extended, as example because the corresponding UCI option is set to zero,
2241 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2243 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2244 bool singleReply, bool mateThreat, bool* dangerous) {
2246 assert(m != MOVE_NONE);
2248 Depth result = Depth(0);
2249 *dangerous = check || singleReply || mateThreat;
2252 result += CheckExtension[pvNode];
2255 result += SingleReplyExtension[pvNode];
2258 result += MateThreatExtension[pvNode];
2260 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2262 if (pos.move_is_pawn_push_to_7th(m))
2264 result += PawnPushTo7thExtension[pvNode];
2267 if (pos.move_is_passed_pawn_push(m))
2269 result += PassedPawnExtension[pvNode];
2275 && pos.type_of_piece_on(move_to(m)) != PAWN
2276 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2277 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2278 && !move_promotion(m)
2281 result += PawnEndgameExtension[pvNode];
2287 && pos.type_of_piece_on(move_to(m)) != PAWN
2294 return Min(result, OnePly);
2298 // ok_to_do_nullmove() looks at the current position and decides whether
2299 // doing a 'null move' should be allowed. In order to avoid zugzwang
2300 // problems, null moves are not allowed when the side to move has very
2301 // little material left. Currently, the test is a bit too simple: Null
2302 // moves are avoided only when the side to move has only pawns left. It's
2303 // probably a good idea to avoid null moves in at least some more
2304 // complicated endgames, e.g. KQ vs KR. FIXME
2306 bool ok_to_do_nullmove(const Position &pos) {
2307 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2313 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2314 // non-tactical moves late in the move list close to the leaves are
2315 // candidates for pruning.
2317 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2318 Square mfrom, mto, tfrom, tto;
2320 assert(move_is_ok(m));
2321 assert(threat == MOVE_NONE || move_is_ok(threat));
2322 assert(!move_promotion(m));
2323 assert(!pos.move_is_check(m));
2324 assert(!pos.move_is_capture(m));
2325 assert(!pos.move_is_passed_pawn_push(m));
2326 assert(d >= OnePly);
2328 mfrom = move_from(m);
2330 tfrom = move_from(threat);
2331 tto = move_to(threat);
2333 // Case 1: Castling moves are never pruned.
2334 if (move_is_castle(m))
2337 // Case 2: Don't prune moves which move the threatened piece
2338 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2341 // Case 3: If the threatened piece has value less than or equal to the
2342 // value of the threatening piece, don't prune move which defend it.
2343 if ( !PruneDefendingMoves
2344 && threat != MOVE_NONE
2345 && pos.move_is_capture(threat)
2346 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2347 || pos.type_of_piece_on(tfrom) == KING)
2348 && pos.move_attacks_square(m, tto))
2351 // Case 4: Don't prune moves with good history.
2352 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2355 // Case 5: If the moving piece in the threatened move is a slider, don't
2356 // prune safe moves which block its ray.
2357 if ( !PruneBlockingMoves
2358 && threat != MOVE_NONE
2359 && piece_is_slider(pos.piece_on(tfrom))
2360 && bit_is_set(squares_between(tfrom, tto), mto)
2368 // ok_to_use_TT() returns true if a transposition table score
2369 // can be used at a given point in search.
2371 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2373 Value v = value_from_tt(tte->value(), ply);
2375 return ( tte->depth() >= depth
2376 || v >= Max(value_mate_in(100), beta)
2377 || v < Min(value_mated_in(100), beta))
2379 && ( (is_lower_bound(tte->type()) && v >= beta)
2380 || (is_upper_bound(tte->type()) && v < beta));
2384 // ok_to_history() returns true if a move m can be stored
2385 // in history. Should be a non capturing move nor a promotion.
2387 bool ok_to_history(const Position& pos, Move m) {
2389 return !pos.move_is_capture(m) && !move_promotion(m);
2393 // update_history() registers a good move that produced a beta-cutoff
2394 // in history and marks as failures all the other moves of that ply.
2396 void update_history(const Position& pos, Move m, Depth depth,
2397 Move movesSearched[], int moveCount) {
2399 H.success(pos.piece_on(move_from(m)), m, depth);
2401 for (int i = 0; i < moveCount - 1; i++)
2403 assert(m != movesSearched[i]);
2404 if (ok_to_history(pos, movesSearched[i]))
2405 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2410 // update_killers() add a good move that produced a beta-cutoff
2411 // among the killer moves of that ply.
2413 void update_killers(Move m, SearchStack& ss) {
2415 if (m == ss.killers[0])
2418 for (int i = KILLER_MAX - 1; i > 0; i--)
2419 ss.killers[i] = ss.killers[i - 1];
2424 // fail_high_ply_1() checks if some thread is currently resolving a fail
2425 // high at ply 1 at the node below the first root node. This information
2426 // is used for time managment.
2428 bool fail_high_ply_1() {
2429 for(int i = 0; i < ActiveThreads; i++)
2430 if(Threads[i].failHighPly1)
2436 // current_search_time() returns the number of milliseconds which have passed
2437 // since the beginning of the current search.
2439 int current_search_time() {
2440 return get_system_time() - SearchStartTime;
2444 // nps() computes the current nodes/second count.
2447 int t = current_search_time();
2448 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2452 // poll() performs two different functions: It polls for user input, and it
2453 // looks at the time consumed so far and decides if it's time to abort the
2458 static int lastInfoTime;
2459 int t = current_search_time();
2464 // We are line oriented, don't read single chars
2465 std::string command;
2466 if (!std::getline(std::cin, command))
2469 if (command == "quit")
2472 PonderSearch = false;
2475 else if(command == "stop")
2478 PonderSearch = false;
2480 else if(command == "ponderhit")
2483 // Print search information
2487 else if (lastInfoTime > t)
2488 // HACK: Must be a new search where we searched less than
2489 // NodesBetweenPolls nodes during the first second of search.
2492 else if (t - lastInfoTime >= 1000)
2499 if (dbg_show_hit_rate)
2500 dbg_print_hit_rate();
2502 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2503 << " time " << t << " hashfull " << TT.full() << std::endl;
2504 lock_release(&IOLock);
2505 if (ShowCurrentLine)
2506 Threads[0].printCurrentLine = true;
2508 // Should we stop the search?
2512 bool overTime = t > AbsoluteMaxSearchTime
2513 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2514 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2515 && t > 6*(MaxSearchTime + ExtraSearchTime));
2517 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2518 || (ExactMaxTime && t >= ExactMaxTime)
2519 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2524 // ponderhit() is called when the program is pondering (i.e. thinking while
2525 // it's the opponent's turn to move) in order to let the engine know that
2526 // it correctly predicted the opponent's move.
2529 int t = current_search_time();
2530 PonderSearch = false;
2531 if(Iteration >= 3 &&
2532 (!InfiniteSearch && (StopOnPonderhit ||
2533 t > AbsoluteMaxSearchTime ||
2534 (RootMoveNumber == 1 &&
2535 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2536 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2537 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2542 // print_current_line() prints the current line of search for a given
2543 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2545 void print_current_line(SearchStack ss[], int ply, int threadID) {
2546 assert(ply >= 0 && ply < PLY_MAX);
2547 assert(threadID >= 0 && threadID < ActiveThreads);
2549 if(!Threads[threadID].idle) {
2551 std::cout << "info currline " << (threadID + 1);
2552 for(int p = 0; p < ply; p++)
2553 std::cout << " " << ss[p].currentMove;
2554 std::cout << std::endl;
2555 lock_release(&IOLock);
2557 Threads[threadID].printCurrentLine = false;
2558 if(threadID + 1 < ActiveThreads)
2559 Threads[threadID + 1].printCurrentLine = true;
2563 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2564 // while the program is pondering. The point is to work around a wrinkle in
2565 // the UCI protocol: When pondering, the engine is not allowed to give a
2566 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2567 // We simply wait here until one of these commands is sent, and return,
2568 // after which the bestmove and pondermove will be printed (in id_loop()).
2570 void wait_for_stop_or_ponderhit() {
2571 std::string command;
2574 if(!std::getline(std::cin, command))
2577 if(command == "quit") {
2578 OpeningBook.close();
2583 else if(command == "ponderhit" || command == "stop")
2589 // idle_loop() is where the threads are parked when they have no work to do.
2590 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2591 // object for which the current thread is the master.
2593 void idle_loop(int threadID, SplitPoint *waitSp) {
2594 assert(threadID >= 0 && threadID < THREAD_MAX);
2596 Threads[threadID].running = true;
2599 if(AllThreadsShouldExit && threadID != 0)
2602 // If we are not thinking, wait for a condition to be signaled instead
2603 // of wasting CPU time polling for work:
2604 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2605 #if !defined(_MSC_VER)
2606 pthread_mutex_lock(&WaitLock);
2607 if(Idle || threadID >= ActiveThreads)
2608 pthread_cond_wait(&WaitCond, &WaitLock);
2609 pthread_mutex_unlock(&WaitLock);
2611 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2615 // If this thread has been assigned work, launch a search:
2616 if(Threads[threadID].workIsWaiting) {
2617 Threads[threadID].workIsWaiting = false;
2618 if(Threads[threadID].splitPoint->pvNode)
2619 sp_search_pv(Threads[threadID].splitPoint, threadID);
2621 sp_search(Threads[threadID].splitPoint, threadID);
2622 Threads[threadID].idle = true;
2625 // If this thread is the master of a split point and all threads have
2626 // finished their work at this split point, return from the idle loop:
2627 if(waitSp != NULL && waitSp->cpus == 0)
2631 Threads[threadID].running = false;
2635 // init_split_point_stack() is called during program initialization, and
2636 // initializes all split point objects.
2638 void init_split_point_stack() {
2639 for(int i = 0; i < THREAD_MAX; i++)
2640 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2641 SplitPointStack[i][j].parent = NULL;
2642 lock_init(&(SplitPointStack[i][j].lock), NULL);
2647 // destroy_split_point_stack() is called when the program exits, and
2648 // destroys all locks in the precomputed split point objects.
2650 void destroy_split_point_stack() {
2651 for(int i = 0; i < THREAD_MAX; i++)
2652 for(int j = 0; j < MaxActiveSplitPoints; j++)
2653 lock_destroy(&(SplitPointStack[i][j].lock));
2657 // thread_should_stop() checks whether the thread with a given threadID has
2658 // been asked to stop, directly or indirectly. This can happen if a beta
2659 // cutoff has occured in thre thread's currently active split point, or in
2660 // some ancestor of the current split point.
2662 bool thread_should_stop(int threadID) {
2663 assert(threadID >= 0 && threadID < ActiveThreads);
2667 if(Threads[threadID].stop)
2669 if(ActiveThreads <= 2)
2671 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2673 Threads[threadID].stop = true;
2680 // thread_is_available() checks whether the thread with threadID "slave" is
2681 // available to help the thread with threadID "master" at a split point. An
2682 // obvious requirement is that "slave" must be idle. With more than two
2683 // threads, this is not by itself sufficient: If "slave" is the master of
2684 // some active split point, it is only available as a slave to the other
2685 // threads which are busy searching the split point at the top of "slave"'s
2686 // split point stack (the "helpful master concept" in YBWC terminology).
2688 bool thread_is_available(int slave, int master) {
2689 assert(slave >= 0 && slave < ActiveThreads);
2690 assert(master >= 0 && master < ActiveThreads);
2691 assert(ActiveThreads > 1);
2693 if(!Threads[slave].idle || slave == master)
2696 if(Threads[slave].activeSplitPoints == 0)
2697 // No active split points means that the thread is available as a slave
2698 // for any other thread.
2701 if(ActiveThreads == 2)
2704 // Apply the "helpful master" concept if possible.
2705 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2712 // idle_thread_exists() tries to find an idle thread which is available as
2713 // a slave for the thread with threadID "master".
2715 bool idle_thread_exists(int master) {
2716 assert(master >= 0 && master < ActiveThreads);
2717 assert(ActiveThreads > 1);
2719 for(int i = 0; i < ActiveThreads; i++)
2720 if(thread_is_available(i, master))
2726 // split() does the actual work of distributing the work at a node between
2727 // several threads at PV nodes. If it does not succeed in splitting the
2728 // node (because no idle threads are available, or because we have no unused
2729 // split point objects), the function immediately returns false. If
2730 // splitting is possible, a SplitPoint object is initialized with all the
2731 // data that must be copied to the helper threads (the current position and
2732 // search stack, alpha, beta, the search depth, etc.), and we tell our
2733 // helper threads that they have been assigned work. This will cause them
2734 // to instantly leave their idle loops and call sp_search_pv(). When all
2735 // threads have returned from sp_search_pv (or, equivalently, when
2736 // splitPoint->cpus becomes 0), split() returns true.
2738 bool split(const Position &p, SearchStack *sstck, int ply,
2739 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2740 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2743 assert(sstck != NULL);
2744 assert(ply >= 0 && ply < PLY_MAX);
2745 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2746 assert(!pvNode || *alpha < *beta);
2747 assert(*beta <= VALUE_INFINITE);
2748 assert(depth > Depth(0));
2749 assert(master >= 0 && master < ActiveThreads);
2750 assert(ActiveThreads > 1);
2752 SplitPoint *splitPoint;
2757 // If no other thread is available to help us, or if we have too many
2758 // active split points, don't split:
2759 if(!idle_thread_exists(master) ||
2760 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2761 lock_release(&MPLock);
2765 // Pick the next available split point object from the split point stack:
2766 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2767 Threads[master].activeSplitPoints++;
2769 // Initialize the split point object:
2770 splitPoint->parent = Threads[master].splitPoint;
2771 splitPoint->finished = false;
2772 splitPoint->ply = ply;
2773 splitPoint->depth = depth;
2774 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2775 splitPoint->beta = *beta;
2776 splitPoint->pvNode = pvNode;
2777 splitPoint->dcCandidates = dcCandidates;
2778 splitPoint->bestValue = *bestValue;
2779 splitPoint->master = master;
2780 splitPoint->mp = mp;
2781 splitPoint->moves = *moves;
2782 splitPoint->cpus = 1;
2783 splitPoint->pos.copy(p);
2784 splitPoint->parentSstack = sstck;
2785 for(i = 0; i < ActiveThreads; i++)
2786 splitPoint->slaves[i] = 0;
2788 // Copy the current position and the search stack to the master thread:
2789 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2790 Threads[master].splitPoint = splitPoint;
2792 // Make copies of the current position and search stack for each thread:
2793 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2795 if(thread_is_available(i, master)) {
2796 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2797 Threads[i].splitPoint = splitPoint;
2798 splitPoint->slaves[i] = 1;
2802 // Tell the threads that they have work to do. This will make them leave
2804 for(i = 0; i < ActiveThreads; i++)
2805 if(i == master || splitPoint->slaves[i]) {
2806 Threads[i].workIsWaiting = true;
2807 Threads[i].idle = false;
2808 Threads[i].stop = false;
2811 lock_release(&MPLock);
2813 // Everything is set up. The master thread enters the idle loop, from
2814 // which it will instantly launch a search, because its workIsWaiting
2815 // slot is 'true'. We send the split point as a second parameter to the
2816 // idle loop, which means that the main thread will return from the idle
2817 // loop when all threads have finished their work at this split point
2818 // (i.e. when // splitPoint->cpus == 0).
2819 idle_loop(master, splitPoint);
2821 // We have returned from the idle loop, which means that all threads are
2822 // finished. Update alpha, beta and bestvalue, and return:
2824 if(pvNode) *alpha = splitPoint->alpha;
2825 *beta = splitPoint->beta;
2826 *bestValue = splitPoint->bestValue;
2827 Threads[master].stop = false;
2828 Threads[master].idle = false;
2829 Threads[master].activeSplitPoints--;
2830 Threads[master].splitPoint = splitPoint->parent;
2831 lock_release(&MPLock);
2837 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2838 // to start a new search from the root.
2840 void wake_sleeping_threads() {
2841 if(ActiveThreads > 1) {
2842 for(int i = 1; i < ActiveThreads; i++) {
2843 Threads[i].idle = true;
2844 Threads[i].workIsWaiting = false;
2846 #if !defined(_MSC_VER)
2847 pthread_mutex_lock(&WaitLock);
2848 pthread_cond_broadcast(&WaitCond);
2849 pthread_mutex_unlock(&WaitLock);
2851 for(int i = 1; i < THREAD_MAX; i++)
2852 SetEvent(SitIdleEvent[i]);
2858 // init_thread() is the function which is called when a new thread is
2859 // launched. It simply calls the idle_loop() function with the supplied
2860 // threadID. There are two versions of this function; one for POSIX threads
2861 // and one for Windows threads.
2863 #if !defined(_MSC_VER)
2865 void *init_thread(void *threadID) {
2866 idle_loop(*(int *)threadID, NULL);
2872 DWORD WINAPI init_thread(LPVOID threadID) {
2873 idle_loop(*(int *)threadID, NULL);