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 initialized from UCI options
134 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
136 int LMRPVMoves, LMRNonPVMoves;
138 // Depth limit for use of dynamic threat detection
141 // Depth limit for selective search
142 Depth SelectiveDepth;
144 // Use internal iterative deepening?
145 const bool UseIIDAtPVNodes = true;
146 const bool UseIIDAtNonPVNodes = false;
148 // Internal iterative deepening margin. At Non-PV moves, when
149 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
150 // when the static evaluation is at most IIDMargin below beta.
151 const Value IIDMargin = Value(0x100);
153 // Easy move margin. An easy move candidate must be at least this much
154 // better than the second best move.
155 const Value EasyMoveMargin = Value(0x200);
157 // Problem margin. If the score of the first move at iteration N+1 has
158 // dropped by more than this since iteration N, the boolean variable
159 // "Problem" is set to true, which will make the program spend some extra
160 // time looking for a better move.
161 const Value ProblemMargin = Value(0x28);
163 // No problem margin. If the boolean "Problem" is true, and a new move
164 // is found at the root which is less than NoProblemMargin worse than the
165 // best move from the previous iteration, Problem is set back to false.
166 const Value NoProblemMargin = Value(0x14);
168 // Null move margin. A null move search will not be done if the approximate
169 // evaluation of the position is more than NullMoveMargin below beta.
170 const Value NullMoveMargin = Value(0x300);
172 // Pruning criterions. See the code and comments in ok_to_prune() to
173 // understand their precise meaning.
174 const bool PruneEscapeMoves = false;
175 const bool PruneDefendingMoves = false;
176 const bool PruneBlockingMoves = false;
178 // Use futility pruning?
179 bool UseQSearchFutilityPruning, UseFutilityPruning;
181 // Margins for futility pruning in the quiescence search, and at frontier
182 // and near frontier nodes
183 const Value FutilityMarginQS = Value(0x80);
185 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
186 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
187 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
188 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
190 const Depth RazorDepth = 4*OnePly;
192 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
193 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
195 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
196 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
198 // Last seconds noise filtering (LSN)
199 bool UseLSNFiltering;
200 bool looseOnTime = false;
201 int LSNTime; // In milliseconds
204 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
205 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
206 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
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;
248 std::ofstream LogFile;
250 // MP related variables
251 Depth MinimumSplitDepth;
252 int MaxThreadsPerSplitPoint;
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 UseLSNFiltering = get_option_value_bool("LSN filtering");
447 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
448 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
450 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
451 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
453 read_weights(pos.side_to_move());
455 int newActiveThreads = get_option_value_int("Threads");
456 if (newActiveThreads != ActiveThreads)
458 ActiveThreads = newActiveThreads;
459 init_eval(ActiveThreads);
462 // Wake up sleeping threads:
463 wake_sleeping_threads();
465 for (int i = 1; i < ActiveThreads; i++)
466 assert(thread_is_available(i, 0));
468 // Set thinking time:
469 int myTime = time[side_to_move];
470 int myIncrement = increment[side_to_move];
472 if (!movesToGo) // Sudden death time control
476 MaxSearchTime = myTime / 30 + myIncrement;
477 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
478 } else { // Blitz game without increment
479 MaxSearchTime = myTime / 30;
480 AbsoluteMaxSearchTime = myTime / 8;
483 else // (x moves) / (y minutes)
487 MaxSearchTime = myTime / 2;
488 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
490 MaxSearchTime = myTime / Min(movesToGo, 20);
491 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
495 if (PonderingEnabled)
497 MaxSearchTime += MaxSearchTime / 4;
498 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
501 // Fixed depth or fixed number of nodes?
504 InfiniteSearch = true; // HACK
509 NodesBetweenPolls = Min(MaxNodes, 30000);
510 InfiniteSearch = true; // HACK
513 NodesBetweenPolls = 30000;
516 // Write information to search log file:
518 LogFile << "Searching: " << pos.to_fen() << std::endl
519 << "infinite: " << infinite
520 << " ponder: " << ponder
521 << " time: " << myTime
522 << " increment: " << myIncrement
523 << " moves to go: " << movesToGo << std::endl;
526 // We're ready to start thinking. Call the iterative deepening loop
530 Value v = id_loop(pos, searchMoves);
531 looseOnTime = ( UseLSNFiltering
538 looseOnTime = false; // reset for next match
539 while (SearchStartTime + myTime + 1000 > get_system_time())
541 id_loop(pos, searchMoves); // to fail gracefully
558 /// init_threads() is called during startup. It launches all helper threads,
559 /// and initializes the split point stack and the global locks and condition
562 void init_threads() {
566 #if !defined(_MSC_VER)
567 pthread_t pthread[1];
570 for (i = 0; i < THREAD_MAX; i++)
571 Threads[i].activeSplitPoints = 0;
573 // Initialize global locks:
574 lock_init(&MPLock, NULL);
575 lock_init(&IOLock, NULL);
577 init_split_point_stack();
579 #if !defined(_MSC_VER)
580 pthread_mutex_init(&WaitLock, NULL);
581 pthread_cond_init(&WaitCond, NULL);
583 for (i = 0; i < THREAD_MAX; i++)
584 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
587 // All threads except the main thread should be initialized to idle state
588 for (i = 1; i < THREAD_MAX; i++)
590 Threads[i].stop = false;
591 Threads[i].workIsWaiting = false;
592 Threads[i].idle = true;
593 Threads[i].running = false;
596 // Launch the helper threads
597 for(i = 1; i < THREAD_MAX; i++)
599 #if !defined(_MSC_VER)
600 pthread_create(pthread, NULL, init_thread, (void*)(&i));
603 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
606 // Wait until the thread has finished launching:
607 while (!Threads[i].running);
610 // Init also the empty search stack
611 EmptySearchStack.init(0);
612 EmptySearchStack.initKillers();
616 /// stop_threads() is called when the program exits. It makes all the
617 /// helper threads exit cleanly.
619 void stop_threads() {
621 ActiveThreads = THREAD_MAX; // HACK
622 Idle = false; // HACK
623 wake_sleeping_threads();
624 AllThreadsShouldExit = true;
625 for (int i = 1; i < THREAD_MAX; i++)
627 Threads[i].stop = true;
628 while(Threads[i].running);
630 destroy_split_point_stack();
634 /// nodes_searched() returns the total number of nodes searched so far in
635 /// the current search.
637 int64_t nodes_searched() {
639 int64_t result = 0ULL;
640 for (int i = 0; i < ActiveThreads; i++)
641 result += Threads[i].nodes;
648 // id_loop() is the main iterative deepening loop. It calls root_search
649 // repeatedly with increasing depth until the allocated thinking time has
650 // been consumed, the user stops the search, or the maximum search depth is
653 Value id_loop(const Position &pos, Move searchMoves[]) {
656 SearchStack ss[PLY_MAX_PLUS_2];
658 // searchMoves are verified, copied, scored and sorted
659 RootMoveList rml(p, searchMoves);
664 for (int i = 0; i < 3; i++)
669 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
672 EasyMove = rml.scan_for_easy_move();
674 // Iterative deepening loop
675 while (Iteration < PLY_MAX)
677 // Initialize iteration
680 BestMoveChangesByIteration[Iteration] = 0;
684 std::cout << "info depth " << Iteration << std::endl;
686 // Calculate dynamic search window based on previous iterations
689 if (MultiPV == 1 && Iteration >= 6)
691 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
692 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
694 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
696 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
697 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
701 alpha = - VALUE_INFINITE;
702 beta = VALUE_INFINITE;
705 // Search to the current depth
706 Value value = root_search(p, ss, rml, alpha, beta);
708 // Write PV to transposition table, in case the relevant entries have
709 // been overwritten during the search.
710 TT.insert_pv(p, ss[0].pv);
713 break; // Value cannot be trusted. Break out immediately!
715 //Save info about search result
716 Value speculatedValue;
719 Value delta = value - IterationInfo[Iteration - 1].value;
726 speculatedValue = value + delta;
727 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
729 else if (value <= alpha)
731 assert(value == alpha);
735 speculatedValue = value + delta;
736 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
738 speculatedValue = value;
740 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
741 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
743 // Erase the easy move if it differs from the new best move
744 if (ss[0].pv[0] != EasyMove)
745 EasyMove = MOVE_NONE;
752 bool stopSearch = false;
754 // Stop search early if there is only a single legal move:
755 if (Iteration >= 6 && rml.move_count() == 1)
758 // Stop search early when the last two iterations returned a mate score
760 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
761 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
764 // Stop search early if one move seems to be much better than the rest
765 int64_t nodes = nodes_searched();
769 && EasyMove == ss[0].pv[0]
770 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
771 && current_search_time() > MaxSearchTime / 16)
772 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
773 && current_search_time() > MaxSearchTime / 32)))
776 // Add some extra time if the best move has changed during the last two iterations
777 if (Iteration > 5 && Iteration <= 50)
778 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
779 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
781 // Stop search if most of MaxSearchTime is consumed at the end of the
782 // iteration. We probably don't have enough time to search the first
783 // move at the next iteration anyway.
784 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
789 //FIXME: Implement fail-low emergency measures
793 StopOnPonderhit = true;
797 if (MaxDepth && Iteration >= MaxDepth)
803 // If we are pondering, we shouldn't print the best move before we
806 wait_for_stop_or_ponderhit();
808 // Print final search statistics
809 std::cout << "info nodes " << nodes_searched()
811 << " time " << current_search_time()
812 << " hashfull " << TT.full() << std::endl;
814 // Print the best move and the ponder move to the standard output
815 if (ss[0].pv[0] == MOVE_NONE)
817 ss[0].pv[0] = rml.get_move(0);
818 ss[0].pv[1] = MOVE_NONE;
820 std::cout << "bestmove " << ss[0].pv[0];
821 if (ss[0].pv[1] != MOVE_NONE)
822 std::cout << " ponder " << ss[0].pv[1];
824 std::cout << std::endl;
829 dbg_print_mean(LogFile);
831 if (dbg_show_hit_rate)
832 dbg_print_hit_rate(LogFile);
835 LogFile << "Nodes: " << nodes_searched() << std::endl
836 << "Nodes/second: " << nps() << std::endl
837 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
839 p.do_move(ss[0].pv[0], st);
840 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
841 << std::endl << std::endl;
843 return rml.get_move_score(0);
847 // root_search() is the function which searches the root node. It is
848 // similar to search_pv except that it uses a different move ordering
849 // scheme (perhaps we should try to use this at internal PV nodes, too?)
850 // and prints some information to the standard output.
852 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
854 Value oldAlpha = alpha;
856 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
858 // Loop through all the moves in the root move list
859 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
863 // We failed high, invalidate and skip next moves, leave node-counters
864 // and beta-counters as they are and quickly return, we will try to do
865 // a research at the next iteration with a bigger aspiration window.
866 rml.set_move_score(i, -VALUE_INFINITE);
874 RootMoveNumber = i + 1;
877 // Remember the node count before the move is searched. The node counts
878 // are used to sort the root moves at the next iteration.
879 nodes = nodes_searched();
881 // Reset beta cut-off counters
884 // Pick the next root move, and print the move and the move number to
885 // the standard output.
886 move = ss[0].currentMove = rml.get_move(i);
887 if (current_search_time() >= 1000)
888 std::cout << "info currmove " << move
889 << " currmovenumber " << i + 1 << std::endl;
891 // Decide search depth for this move
893 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
894 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
896 // Make the move, and search it
897 pos.do_move(move, st, dcCandidates);
901 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
902 // If the value has dropped a lot compared to the last iteration,
903 // set the boolean variable Problem to true. This variable is used
904 // for time managment: When Problem is true, we try to complete the
905 // current iteration before playing a move.
906 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
908 if (Problem && StopOnPonderhit)
909 StopOnPonderhit = false;
913 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
916 // Fail high! Set the boolean variable FailHigh to true, and
917 // re-search the move with a big window. The variable FailHigh is
918 // used for time managment: We try to avoid aborting the search
919 // prematurely during a fail high research.
921 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
927 // Finished searching the move. If AbortSearch is true, the search
928 // was aborted because the user interrupted the search or because we
929 // ran out of time. In this case, the return value of the search cannot
930 // be trusted, and we break out of the loop without updating the best
935 // Remember the node count for this move. The node counts are used to
936 // sort the root moves at the next iteration.
937 rml.set_move_nodes(i, nodes_searched() - nodes);
939 // Remember the beta-cutoff statistics
941 BetaCounter.read(pos.side_to_move(), our, their);
942 rml.set_beta_counters(i, our, their);
944 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
946 if (value <= alpha && i >= MultiPV)
947 rml.set_move_score(i, -VALUE_INFINITE);
950 // PV move or new best move!
953 rml.set_move_score(i, value);
955 rml.set_move_pv(i, ss[0].pv);
959 // We record how often the best move has been changed in each
960 // iteration. This information is used for time managment: When
961 // the best move changes frequently, we allocate some more time.
963 BestMoveChangesByIteration[Iteration]++;
965 // Print search information to the standard output:
966 std::cout << "info depth " << Iteration
967 << " score " << value_to_string(value)
968 << " time " << current_search_time()
969 << " nodes " << nodes_searched()
973 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
974 std::cout << ss[0].pv[j] << " ";
976 std::cout << std::endl;
979 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
985 // Reset the global variable Problem to false if the value isn't too
986 // far below the final value from the last iteration.
987 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
993 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
996 std::cout << "info multipv " << j + 1
997 << " score " << value_to_string(rml.get_move_score(j))
998 << " depth " << ((j <= i)? Iteration : Iteration - 1)
999 << " time " << current_search_time()
1000 << " nodes " << nodes_searched()
1004 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1005 std::cout << rml.get_move_pv(j, k) << " ";
1007 std::cout << std::endl;
1009 alpha = rml.get_move_score(Min(i, MultiPV-1));
1011 } // New best move case
1013 assert(alpha >= oldAlpha);
1015 FailLow = (alpha == oldAlpha);
1021 // search_pv() is the main search function for PV nodes.
1023 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1024 Depth depth, int ply, int threadID) {
1026 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1027 assert(beta > alpha && beta <= VALUE_INFINITE);
1028 assert(ply >= 0 && ply < PLY_MAX);
1029 assert(threadID >= 0 && threadID < ActiveThreads);
1032 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1034 // Initialize, and make an early exit in case of an aborted search,
1035 // an instant draw, maximum ply reached, etc.
1036 init_node(ss, ply, threadID);
1038 // After init_node() that calls poll()
1039 if (AbortSearch || thread_should_stop(threadID))
1047 if (ply >= PLY_MAX - 1)
1048 return evaluate(pos, ei, threadID);
1050 // Mate distance pruning
1051 Value oldAlpha = alpha;
1052 alpha = Max(value_mated_in(ply), alpha);
1053 beta = Min(value_mate_in(ply+1), beta);
1057 // Transposition table lookup. At PV nodes, we don't use the TT for
1058 // pruning, but only for move ordering.
1059 const TTEntry* tte = TT.retrieve(pos);
1060 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1062 // Go with internal iterative deepening if we don't have a TT move
1063 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1065 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1066 ttMove = ss[ply].pv[ply];
1069 // Initialize a MovePicker object for the current position, and prepare
1070 // to search all moves
1071 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1073 Move move, movesSearched[256];
1075 Value value, bestValue = -VALUE_INFINITE;
1076 Bitboard dcCandidates = mp.discovered_check_candidates();
1077 Color us = pos.side_to_move();
1078 bool isCheck = pos.is_check();
1079 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1081 // Loop through all legal moves until no moves remain or a beta cutoff
1083 while ( alpha < beta
1084 && (move = mp.get_next_move()) != MOVE_NONE
1085 && !thread_should_stop(threadID))
1087 assert(move_is_ok(move));
1089 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1090 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1091 bool moveIsCapture = pos.move_is_capture(move);
1093 movesSearched[moveCount++] = ss[ply].currentMove = move;
1095 // Decide the new search depth
1097 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1098 Depth newDepth = depth - OnePly + ext;
1100 // Make and search the move
1102 pos.do_move(move, st, dcCandidates);
1104 if (moveCount == 1) // The first move in list is the PV
1105 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1108 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1109 // if the move fails high will be re-searched at full depth.
1110 if ( depth >= 2*OnePly
1111 && moveCount >= LMRPVMoves
1114 && !move_promotion(move)
1115 && !move_is_castle(move)
1116 && !move_is_killer(move, ss[ply]))
1118 ss[ply].reduction = OnePly;
1119 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1122 value = alpha + 1; // Just to trigger next condition
1124 if (value > alpha) // Go with full depth non-pv search
1126 ss[ply].reduction = Depth(0);
1127 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1128 if (value > alpha && value < beta)
1130 // When the search fails high at ply 1 while searching the first
1131 // move at the root, set the flag failHighPly1. This is used for
1132 // time managment: We don't want to stop the search early in
1133 // such cases, because resolving the fail high at ply 1 could
1134 // result in a big drop in score at the root.
1135 if (ply == 1 && RootMoveNumber == 1)
1136 Threads[threadID].failHighPly1 = true;
1138 // A fail high occurred. Re-search at full window (pv search)
1139 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1140 Threads[threadID].failHighPly1 = false;
1144 pos.undo_move(move);
1146 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1149 if (value > bestValue)
1156 if (value == value_mate_in(ply + 1))
1157 ss[ply].mateKiller = move;
1159 // If we are at ply 1, and we are searching the first root move at
1160 // ply 0, set the 'Problem' variable if the score has dropped a lot
1161 // (from the computer's point of view) since the previous iteration:
1164 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1169 if ( ActiveThreads > 1
1171 && depth >= MinimumSplitDepth
1173 && idle_thread_exists(threadID)
1175 && !thread_should_stop(threadID)
1176 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1177 &moveCount, &mp, dcCandidates, threadID, true))
1181 // All legal moves have been searched. A special case: If there were
1182 // no legal moves, it must be mate or stalemate:
1184 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1186 // If the search is not aborted, update the transposition table,
1187 // history counters, and killer moves.
1188 if (AbortSearch || thread_should_stop(threadID))
1191 if (bestValue <= oldAlpha)
1192 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1194 else if (bestValue >= beta)
1196 BetaCounter.add(pos.side_to_move(), depth, threadID);
1197 Move m = ss[ply].pv[ply];
1198 if (ok_to_history(pos, m)) // Only non capture moves are considered
1200 update_history(pos, m, depth, movesSearched, moveCount);
1201 update_killers(m, ss[ply]);
1203 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1206 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1212 // search() is the search function for zero-width nodes.
1214 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1215 int ply, bool allowNullmove, int threadID) {
1217 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1218 assert(ply >= 0 && ply < PLY_MAX);
1219 assert(threadID >= 0 && threadID < ActiveThreads);
1222 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1224 // Initialize, and make an early exit in case of an aborted search,
1225 // an instant draw, maximum ply reached, etc.
1226 init_node(ss, ply, threadID);
1228 // After init_node() that calls poll()
1229 if (AbortSearch || thread_should_stop(threadID))
1237 if (ply >= PLY_MAX - 1)
1238 return evaluate(pos, ei, threadID);
1240 // Mate distance pruning
1241 if (value_mated_in(ply) >= beta)
1244 if (value_mate_in(ply + 1) < beta)
1247 // Transposition table lookup
1248 const TTEntry* tte = TT.retrieve(pos);
1249 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1251 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1253 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1254 return value_from_tt(tte->value(), ply);
1257 Value approximateEval = quick_evaluate(pos);
1258 bool mateThreat = false;
1259 bool isCheck = pos.is_check();
1265 && !value_is_mate(beta)
1266 && ok_to_do_nullmove(pos)
1267 && approximateEval >= beta - NullMoveMargin)
1269 ss[ply].currentMove = MOVE_NULL;
1272 pos.do_null_move(st);
1273 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1275 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1277 pos.undo_null_move();
1279 if (value_is_mate(nullValue))
1281 /* Do not return unproven mates */
1283 else if (nullValue >= beta)
1285 if (depth < 6 * OnePly)
1288 // Do zugzwang verification search
1289 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1293 // The null move failed low, which means that we may be faced with
1294 // some kind of threat. If the previous move was reduced, check if
1295 // the move that refuted the null move was somehow connected to the
1296 // move which was reduced. If a connection is found, return a fail
1297 // low score (which will cause the reduced move to fail high in the
1298 // parent node, which will trigger a re-search with full depth).
1299 if (nullValue == value_mated_in(ply + 2))
1302 ss[ply].threatMove = ss[ply + 1].currentMove;
1303 if ( depth < ThreatDepth
1304 && ss[ply - 1].reduction
1305 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1309 // Null move search not allowed, try razoring
1310 else if ( !value_is_mate(beta)
1311 && depth < RazorDepth
1312 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1313 && ttMove == MOVE_NONE
1314 && !pos.has_pawn_on_7th(pos.side_to_move()))
1316 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1317 if (v < beta - RazorMargins[int(depth) - 2])
1321 // Go with internal iterative deepening if we don't have a TT move
1322 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1323 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1325 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1326 ttMove = ss[ply].pv[ply];
1329 // Initialize a MovePicker object for the current position, and prepare
1330 // to search all moves:
1331 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1333 Move move, movesSearched[256];
1335 Value value, bestValue = -VALUE_INFINITE;
1336 Bitboard dcCandidates = mp.discovered_check_candidates();
1337 Value futilityValue = VALUE_NONE;
1338 bool useFutilityPruning = UseFutilityPruning
1339 && depth < SelectiveDepth
1342 // Loop through all legal moves until no moves remain or a beta cutoff
1344 while ( bestValue < beta
1345 && (move = mp.get_next_move()) != MOVE_NONE
1346 && !thread_should_stop(threadID))
1348 assert(move_is_ok(move));
1350 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1351 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1352 bool moveIsCapture = pos.move_is_capture(move);
1354 movesSearched[moveCount++] = ss[ply].currentMove = move;
1356 // Decide the new search depth
1358 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1359 Depth newDepth = depth - OnePly + ext;
1362 if ( useFutilityPruning
1365 && !move_promotion(move))
1367 // History pruning. See ok_to_prune() definition
1368 if ( moveCount >= 2 + int(depth)
1369 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1372 // Value based pruning
1373 if (depth < 7 * OnePly && approximateEval < beta)
1375 if (futilityValue == VALUE_NONE)
1376 futilityValue = evaluate(pos, ei, threadID)
1377 + FutilityMargins[int(depth) - 2];
1379 if (futilityValue < beta)
1381 if (futilityValue > bestValue)
1382 bestValue = futilityValue;
1388 // Make and search the move
1390 pos.do_move(move, st, dcCandidates);
1392 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1393 // if the move fails high will be re-searched at full depth.
1394 if ( depth >= 2*OnePly
1395 && moveCount >= LMRNonPVMoves
1398 && !move_promotion(move)
1399 && !move_is_castle(move)
1400 && !move_is_killer(move, ss[ply]))
1402 ss[ply].reduction = OnePly;
1403 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1406 value = beta; // Just to trigger next condition
1408 if (value >= beta) // Go with full depth non-pv search
1410 ss[ply].reduction = Depth(0);
1411 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1413 pos.undo_move(move);
1415 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1418 if (value > bestValue)
1424 if (value == value_mate_in(ply + 1))
1425 ss[ply].mateKiller = move;
1429 if ( ActiveThreads > 1
1431 && depth >= MinimumSplitDepth
1433 && idle_thread_exists(threadID)
1435 && !thread_should_stop(threadID)
1436 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1437 &mp, dcCandidates, threadID, false))
1441 // All legal moves have been searched. A special case: If there were
1442 // no legal moves, it must be mate or stalemate.
1444 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1446 // If the search is not aborted, update the transposition table,
1447 // history counters, and killer moves.
1448 if (AbortSearch || thread_should_stop(threadID))
1451 if (bestValue < beta)
1452 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1455 BetaCounter.add(pos.side_to_move(), depth, threadID);
1456 Move m = ss[ply].pv[ply];
1457 if (ok_to_history(pos, m)) // Only non capture moves are considered
1459 update_history(pos, m, depth, movesSearched, moveCount);
1460 update_killers(m, ss[ply]);
1462 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1465 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1471 // qsearch() is the quiescence search function, which is called by the main
1472 // search function when the remaining depth is zero (or, to be more precise,
1473 // less than OnePly).
1475 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1476 Depth depth, int ply, int threadID) {
1478 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1479 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1481 assert(ply >= 0 && ply < PLY_MAX);
1482 assert(threadID >= 0 && threadID < ActiveThreads);
1484 // Initialize, and make an early exit in case of an aborted search,
1485 // an instant draw, maximum ply reached, etc.
1486 init_node(ss, ply, threadID);
1488 // After init_node() that calls poll()
1489 if (AbortSearch || thread_should_stop(threadID))
1495 // Transposition table lookup, only when not in PV
1496 TTEntry* tte = NULL;
1497 bool pvNode = (beta - alpha != 1);
1500 tte = TT.retrieve(pos);
1501 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1503 assert(tte->type() != VALUE_TYPE_EVAL);
1505 return value_from_tt(tte->value(), ply);
1508 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1510 // Evaluate the position statically
1513 bool isCheck = pos.is_check();
1514 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1517 staticValue = -VALUE_INFINITE;
1519 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1521 // Use the cached evaluation score if possible
1522 assert(tte->value() == evaluate(pos, ei, threadID));
1523 assert(ei.futilityMargin == Value(0));
1525 staticValue = tte->value();
1528 staticValue = evaluate(pos, ei, threadID);
1530 if (ply == PLY_MAX - 1)
1531 return evaluate(pos, ei, threadID);
1533 // Initialize "stand pat score", and return it immediately if it is
1535 Value bestValue = staticValue;
1537 if (bestValue >= beta)
1539 // Store the score to avoid a future costly evaluation() call
1540 if (!isCheck && !tte && ei.futilityMargin == 0)
1541 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1546 if (bestValue > alpha)
1549 // Initialize a MovePicker object for the current position, and prepare
1550 // to search the moves. Because the depth is <= 0 here, only captures,
1551 // queen promotions and checks (only if depth == 0) will be generated.
1552 MovePicker mp = MovePicker(pos, pvNode, ttMove, EmptySearchStack, depth);
1555 Bitboard dcCandidates = mp.discovered_check_candidates();
1556 Color us = pos.side_to_move();
1557 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1559 // Loop through the moves until no moves remain or a beta cutoff
1561 while ( alpha < beta
1562 && (move = mp.get_next_move()) != MOVE_NONE)
1564 assert(move_is_ok(move));
1567 ss[ply].currentMove = move;
1570 if ( UseQSearchFutilityPruning
1574 && !move_promotion(move)
1575 && !pos.move_is_check(move, dcCandidates)
1576 && !pos.move_is_passed_pawn_push(move))
1578 Value futilityValue = staticValue
1579 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1580 pos.endgame_value_of_piece_on(move_to(move)))
1581 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1583 + ei.futilityMargin;
1585 if (futilityValue < alpha)
1587 if (futilityValue > bestValue)
1588 bestValue = futilityValue;
1593 // Don't search captures and checks with negative SEE values
1595 && !move_promotion(move)
1596 && (pos.midgame_value_of_piece_on(move_from(move)) >
1597 pos.midgame_value_of_piece_on(move_to(move)))
1598 && pos.see(move) < 0)
1601 // Make and search the move.
1603 pos.do_move(move, st, dcCandidates);
1604 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1605 pos.undo_move(move);
1607 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1610 if (value > bestValue)
1621 // All legal moves have been searched. A special case: If we're in check
1622 // and no legal moves were found, it is checkmate:
1623 if (pos.is_check() && moveCount == 0) // Mate!
1624 return value_mated_in(ply);
1626 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1628 // Update transposition table
1629 Move m = ss[ply].pv[ply];
1632 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1633 if (bestValue < beta)
1634 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_UPPER);
1636 TT.store(pos, value_to_tt(bestValue, ply), d, m, VALUE_TYPE_LOWER);
1639 // Update killers only for good check moves
1640 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1641 update_killers(m, ss[ply]);
1647 // sp_search() is used to search from a split point. This function is called
1648 // by each thread working at the split point. It is similar to the normal
1649 // search() function, but simpler. Because we have already probed the hash
1650 // table, done a null move search, and searched the first move before
1651 // splitting, we don't have to repeat all this work in sp_search(). We
1652 // also don't need to store anything to the hash table here: This is taken
1653 // care of after we return from the split point.
1655 void sp_search(SplitPoint *sp, int threadID) {
1657 assert(threadID >= 0 && threadID < ActiveThreads);
1658 assert(ActiveThreads > 1);
1660 Position pos = Position(sp->pos);
1661 SearchStack *ss = sp->sstack[threadID];
1664 bool isCheck = pos.is_check();
1665 bool useFutilityPruning = UseFutilityPruning
1666 && sp->depth < SelectiveDepth
1669 while ( sp->bestValue < sp->beta
1670 && !thread_should_stop(threadID)
1671 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1673 assert(move_is_ok(move));
1675 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1676 bool moveIsCapture = pos.move_is_capture(move);
1678 lock_grab(&(sp->lock));
1679 int moveCount = ++sp->moves;
1680 lock_release(&(sp->lock));
1682 ss[sp->ply].currentMove = move;
1684 // Decide the new search depth.
1686 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1687 Depth newDepth = sp->depth - OnePly + ext;
1690 if ( useFutilityPruning
1693 && !move_promotion(move)
1694 && moveCount >= 2 + int(sp->depth)
1695 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1698 // Make and search the move.
1700 pos.do_move(move, st, sp->dcCandidates);
1702 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1703 // if the move fails high will be re-searched at full depth.
1705 && moveCount >= LMRNonPVMoves
1707 && !move_promotion(move)
1708 && !move_is_castle(move)
1709 && !move_is_killer(move, ss[sp->ply]))
1711 ss[sp->ply].reduction = OnePly;
1712 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1715 value = sp->beta; // Just to trigger next condition
1717 if (value >= sp->beta) // Go with full depth non-pv search
1719 ss[sp->ply].reduction = Depth(0);
1720 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1722 pos.undo_move(move);
1724 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1726 if (thread_should_stop(threadID))
1730 lock_grab(&(sp->lock));
1731 if (value > sp->bestValue && !thread_should_stop(threadID))
1733 sp->bestValue = value;
1734 if (sp->bestValue >= sp->beta)
1736 sp_update_pv(sp->parentSstack, ss, sp->ply);
1737 for (int i = 0; i < ActiveThreads; i++)
1738 if (i != threadID && (i == sp->master || sp->slaves[i]))
1739 Threads[i].stop = true;
1741 sp->finished = true;
1744 lock_release(&(sp->lock));
1747 lock_grab(&(sp->lock));
1749 // If this is the master thread and we have been asked to stop because of
1750 // a beta cutoff higher up in the tree, stop all slave threads:
1751 if (sp->master == threadID && thread_should_stop(threadID))
1752 for (int i = 0; i < ActiveThreads; i++)
1754 Threads[i].stop = true;
1757 sp->slaves[threadID] = 0;
1759 lock_release(&(sp->lock));
1763 // sp_search_pv() is used to search from a PV split point. This function
1764 // is called by each thread working at the split point. It is similar to
1765 // the normal search_pv() function, but simpler. Because we have already
1766 // probed the hash table and searched the first move before splitting, we
1767 // don't have to repeat all this work in sp_search_pv(). We also don't
1768 // need to store anything to the hash table here: This is taken care of
1769 // after we return from the split point.
1771 void sp_search_pv(SplitPoint *sp, int threadID) {
1773 assert(threadID >= 0 && threadID < ActiveThreads);
1774 assert(ActiveThreads > 1);
1776 Position pos = Position(sp->pos);
1777 SearchStack *ss = sp->sstack[threadID];
1781 while ( sp->alpha < sp->beta
1782 && !thread_should_stop(threadID)
1783 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1785 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1786 bool moveIsCapture = pos.move_is_capture(move);
1788 assert(move_is_ok(move));
1790 lock_grab(&(sp->lock));
1791 int moveCount = ++sp->moves;
1792 lock_release(&(sp->lock));
1794 ss[sp->ply].currentMove = move;
1796 // Decide the new search depth.
1798 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1799 Depth newDepth = sp->depth - OnePly + ext;
1801 // Make and search the move.
1803 pos.do_move(move, st, sp->dcCandidates);
1805 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1806 // if the move fails high will be re-searched at full depth.
1808 && moveCount >= LMRPVMoves
1810 && !move_promotion(move)
1811 && !move_is_castle(move)
1812 && !move_is_killer(move, ss[sp->ply]))
1814 ss[sp->ply].reduction = OnePly;
1815 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1818 value = sp->alpha + 1; // Just to trigger next condition
1820 if (value > sp->alpha) // Go with full depth non-pv search
1822 ss[sp->ply].reduction = Depth(0);
1823 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1825 if (value > sp->alpha && value < sp->beta)
1827 // When the search fails high at ply 1 while searching the first
1828 // move at the root, set the flag failHighPly1. This is used for
1829 // time managment: We don't want to stop the search early in
1830 // such cases, because resolving the fail high at ply 1 could
1831 // result in a big drop in score at the root.
1832 if (sp->ply == 1 && RootMoveNumber == 1)
1833 Threads[threadID].failHighPly1 = true;
1835 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1836 Threads[threadID].failHighPly1 = false;
1839 pos.undo_move(move);
1841 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1843 if (thread_should_stop(threadID))
1847 lock_grab(&(sp->lock));
1848 if (value > sp->bestValue && !thread_should_stop(threadID))
1850 sp->bestValue = value;
1851 if (value > sp->alpha)
1854 sp_update_pv(sp->parentSstack, ss, sp->ply);
1855 if (value == value_mate_in(sp->ply + 1))
1856 ss[sp->ply].mateKiller = move;
1858 if(value >= sp->beta)
1860 for(int i = 0; i < ActiveThreads; i++)
1861 if(i != threadID && (i == sp->master || sp->slaves[i]))
1862 Threads[i].stop = true;
1864 sp->finished = true;
1867 // If we are at ply 1, and we are searching the first root move at
1868 // ply 0, set the 'Problem' variable if the score has dropped a lot
1869 // (from the computer's point of view) since the previous iteration.
1872 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1875 lock_release(&(sp->lock));
1878 lock_grab(&(sp->lock));
1880 // If this is the master thread and we have been asked to stop because of
1881 // a beta cutoff higher up in the tree, stop all slave threads.
1882 if (sp->master == threadID && thread_should_stop(threadID))
1883 for (int i = 0; i < ActiveThreads; i++)
1885 Threads[i].stop = true;
1888 sp->slaves[threadID] = 0;
1890 lock_release(&(sp->lock));
1893 /// The BetaCounterType class
1895 BetaCounterType::BetaCounterType() { clear(); }
1897 void BetaCounterType::clear() {
1899 for (int i = 0; i < THREAD_MAX; i++)
1900 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1903 void BetaCounterType::add(Color us, Depth d, int threadID) {
1905 // Weighted count based on depth
1906 hits[threadID][us] += int(d);
1909 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1912 for (int i = 0; i < THREAD_MAX; i++)
1915 their += hits[i][opposite_color(us)];
1920 /// The RootMove class
1924 RootMove::RootMove() {
1925 nodes = cumulativeNodes = 0ULL;
1928 // RootMove::operator<() is the comparison function used when
1929 // sorting the moves. A move m1 is considered to be better
1930 // than a move m2 if it has a higher score, or if the moves
1931 // have equal score but m1 has the higher node count.
1933 bool RootMove::operator<(const RootMove& m) {
1935 if (score != m.score)
1936 return (score < m.score);
1938 return theirBeta <= m.theirBeta;
1941 /// The RootMoveList class
1945 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1947 MoveStack mlist[MaxRootMoves];
1948 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1950 // Generate all legal moves
1951 int lm_count = generate_legal_moves(pos, mlist);
1953 // Add each move to the moves[] array
1954 for (int i = 0; i < lm_count; i++)
1956 bool includeMove = includeAllMoves;
1958 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1959 includeMove = (searchMoves[k] == mlist[i].move);
1963 // Find a quick score for the move
1965 SearchStack ss[PLY_MAX_PLUS_2];
1967 moves[count].move = mlist[i].move;
1968 moves[count].nodes = 0ULL;
1969 pos.do_move(moves[count].move, st);
1970 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1972 pos.undo_move(moves[count].move);
1973 moves[count].pv[0] = moves[i].move;
1974 moves[count].pv[1] = MOVE_NONE; // FIXME
1982 // Simple accessor methods for the RootMoveList class
1984 inline Move RootMoveList::get_move(int moveNum) const {
1985 return moves[moveNum].move;
1988 inline Value RootMoveList::get_move_score(int moveNum) const {
1989 return moves[moveNum].score;
1992 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1993 moves[moveNum].score = score;
1996 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1997 moves[moveNum].nodes = nodes;
1998 moves[moveNum].cumulativeNodes += nodes;
2001 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2002 moves[moveNum].ourBeta = our;
2003 moves[moveNum].theirBeta = their;
2006 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2008 for(j = 0; pv[j] != MOVE_NONE; j++)
2009 moves[moveNum].pv[j] = pv[j];
2010 moves[moveNum].pv[j] = MOVE_NONE;
2013 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2014 return moves[moveNum].pv[i];
2017 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2018 return moves[moveNum].cumulativeNodes;
2021 inline int RootMoveList::move_count() const {
2026 // RootMoveList::scan_for_easy_move() is called at the end of the first
2027 // iteration, and is used to detect an "easy move", i.e. a move which appears
2028 // to be much bester than all the rest. If an easy move is found, the move
2029 // is returned, otherwise the function returns MOVE_NONE. It is very
2030 // important that this function is called at the right moment: The code
2031 // assumes that the first iteration has been completed and the moves have
2032 // been sorted. This is done in RootMoveList c'tor.
2034 Move RootMoveList::scan_for_easy_move() const {
2041 // moves are sorted so just consider the best and the second one
2042 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2048 // RootMoveList::sort() sorts the root move list at the beginning of a new
2051 inline void RootMoveList::sort() {
2053 sort_multipv(count - 1); // all items
2057 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2058 // list by their scores and depths. It is used to order the different PVs
2059 // correctly in MultiPV mode.
2061 void RootMoveList::sort_multipv(int n) {
2063 for (int i = 1; i <= n; i++)
2065 RootMove rm = moves[i];
2067 for (j = i; j > 0 && moves[j-1] < rm; j--)
2068 moves[j] = moves[j-1];
2074 // init_node() is called at the beginning of all the search functions
2075 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2076 // stack object corresponding to the current node. Once every
2077 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2078 // for user input and checks whether it is time to stop the search.
2080 void init_node(SearchStack ss[], int ply, int threadID) {
2081 assert(ply >= 0 && ply < PLY_MAX);
2082 assert(threadID >= 0 && threadID < ActiveThreads);
2084 Threads[threadID].nodes++;
2088 if(NodesSincePoll >= NodesBetweenPolls) {
2095 ss[ply+2].initKillers();
2097 if(Threads[threadID].printCurrentLine)
2098 print_current_line(ss, ply, threadID);
2102 // update_pv() is called whenever a search returns a value > alpha. It
2103 // updates the PV in the SearchStack object corresponding to the current
2106 void update_pv(SearchStack ss[], int ply) {
2107 assert(ply >= 0 && ply < PLY_MAX);
2109 ss[ply].pv[ply] = ss[ply].currentMove;
2111 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2112 ss[ply].pv[p] = ss[ply+1].pv[p];
2113 ss[ply].pv[p] = MOVE_NONE;
2117 // sp_update_pv() is a variant of update_pv for use at split points. The
2118 // difference between the two functions is that sp_update_pv also updates
2119 // the PV at the parent node.
2121 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2122 assert(ply >= 0 && ply < PLY_MAX);
2124 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2126 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2127 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2128 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2132 // connected_moves() tests whether two moves are 'connected' in the sense
2133 // that the first move somehow made the second move possible (for instance
2134 // if the moving piece is the same in both moves). The first move is
2135 // assumed to be the move that was made to reach the current position, while
2136 // the second move is assumed to be a move from the current position.
2138 bool connected_moves(const Position &pos, Move m1, Move m2) {
2139 Square f1, t1, f2, t2;
2141 assert(move_is_ok(m1));
2142 assert(move_is_ok(m2));
2147 // Case 1: The moving piece is the same in both moves.
2153 // Case 2: The destination square for m2 was vacated by m1.
2159 // Case 3: Moving through the vacated square:
2160 if(piece_is_slider(pos.piece_on(f2)) &&
2161 bit_is_set(squares_between(f2, t2), f1))
2164 // Case 4: The destination square for m2 is attacked by the moving piece
2166 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2169 // Case 5: Discovered check, checking piece is the piece moved in m1:
2170 if(piece_is_slider(pos.piece_on(t1)) &&
2171 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2173 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2175 Bitboard occ = pos.occupied_squares();
2176 Color us = pos.side_to_move();
2177 Square ksq = pos.king_square(us);
2178 clear_bit(&occ, f2);
2179 if(pos.type_of_piece_on(t1) == BISHOP) {
2180 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2183 else if(pos.type_of_piece_on(t1) == ROOK) {
2184 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2188 assert(pos.type_of_piece_on(t1) == QUEEN);
2189 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2198 // value_is_mate() checks if the given value is a mate one
2199 // eventually compensated for the ply.
2201 bool value_is_mate(Value value) {
2203 assert(abs(value) <= VALUE_INFINITE);
2205 return value <= value_mated_in(PLY_MAX)
2206 || value >= value_mate_in(PLY_MAX);
2210 // move_is_killer() checks if the given move is among the
2211 // killer moves of that ply.
2213 bool move_is_killer(Move m, const SearchStack& ss) {
2215 const Move* k = ss.killers;
2216 for (int i = 0; i < KILLER_MAX; i++, k++)
2224 // extension() decides whether a move should be searched with normal depth,
2225 // or with extended depth. Certain classes of moves (checking moves, in
2226 // particular) are searched with bigger depth than ordinary moves and in
2227 // any case are marked as 'dangerous'. Note that also if a move is not
2228 // extended, as example because the corresponding UCI option is set to zero,
2229 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2231 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2232 bool singleReply, bool mateThreat, bool* dangerous) {
2234 assert(m != MOVE_NONE);
2236 Depth result = Depth(0);
2237 *dangerous = check || singleReply || mateThreat;
2240 result += CheckExtension[pvNode];
2243 result += SingleReplyExtension[pvNode];
2246 result += MateThreatExtension[pvNode];
2248 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2250 if (pos.move_is_pawn_push_to_7th(m))
2252 result += PawnPushTo7thExtension[pvNode];
2255 if (pos.move_is_passed_pawn_push(m))
2257 result += PassedPawnExtension[pvNode];
2263 && pos.type_of_piece_on(move_to(m)) != PAWN
2264 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2265 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2266 && !move_promotion(m)
2269 result += PawnEndgameExtension[pvNode];
2275 && pos.type_of_piece_on(move_to(m)) != PAWN
2282 return Min(result, OnePly);
2286 // ok_to_do_nullmove() looks at the current position and decides whether
2287 // doing a 'null move' should be allowed. In order to avoid zugzwang
2288 // problems, null moves are not allowed when the side to move has very
2289 // little material left. Currently, the test is a bit too simple: Null
2290 // moves are avoided only when the side to move has only pawns left. It's
2291 // probably a good idea to avoid null moves in at least some more
2292 // complicated endgames, e.g. KQ vs KR. FIXME
2294 bool ok_to_do_nullmove(const Position &pos) {
2295 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2301 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2302 // non-tactical moves late in the move list close to the leaves are
2303 // candidates for pruning.
2305 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2306 Square mfrom, mto, tfrom, tto;
2308 assert(move_is_ok(m));
2309 assert(threat == MOVE_NONE || move_is_ok(threat));
2310 assert(!move_promotion(m));
2311 assert(!pos.move_is_check(m));
2312 assert(!pos.move_is_capture(m));
2313 assert(!pos.move_is_passed_pawn_push(m));
2314 assert(d >= OnePly);
2316 mfrom = move_from(m);
2318 tfrom = move_from(threat);
2319 tto = move_to(threat);
2321 // Case 1: Castling moves are never pruned.
2322 if (move_is_castle(m))
2325 // Case 2: Don't prune moves which move the threatened piece
2326 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2329 // Case 3: If the threatened piece has value less than or equal to the
2330 // value of the threatening piece, don't prune move which defend it.
2331 if ( !PruneDefendingMoves
2332 && threat != MOVE_NONE
2333 && pos.move_is_capture(threat)
2334 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2335 || pos.type_of_piece_on(tfrom) == KING)
2336 && pos.move_attacks_square(m, tto))
2339 // Case 4: Don't prune moves with good history.
2340 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2343 // Case 5: If the moving piece in the threatened move is a slider, don't
2344 // prune safe moves which block its ray.
2345 if ( !PruneBlockingMoves
2346 && threat != MOVE_NONE
2347 && piece_is_slider(pos.piece_on(tfrom))
2348 && bit_is_set(squares_between(tfrom, tto), mto)
2356 // ok_to_use_TT() returns true if a transposition table score
2357 // can be used at a given point in search.
2359 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2361 Value v = value_from_tt(tte->value(), ply);
2363 return ( tte->depth() >= depth
2364 || v >= Max(value_mate_in(100), beta)
2365 || v < Min(value_mated_in(100), beta))
2367 && ( (is_lower_bound(tte->type()) && v >= beta)
2368 || (is_upper_bound(tte->type()) && v < beta));
2372 // ok_to_history() returns true if a move m can be stored
2373 // in history. Should be a non capturing move nor a promotion.
2375 bool ok_to_history(const Position& pos, Move m) {
2377 return !pos.move_is_capture(m) && !move_promotion(m);
2381 // update_history() registers a good move that produced a beta-cutoff
2382 // in history and marks as failures all the other moves of that ply.
2384 void update_history(const Position& pos, Move m, Depth depth,
2385 Move movesSearched[], int moveCount) {
2387 H.success(pos.piece_on(move_from(m)), m, depth);
2389 for (int i = 0; i < moveCount - 1; i++)
2391 assert(m != movesSearched[i]);
2392 if (ok_to_history(pos, movesSearched[i]))
2393 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2398 // update_killers() add a good move that produced a beta-cutoff
2399 // among the killer moves of that ply.
2401 void update_killers(Move m, SearchStack& ss) {
2403 if (m == ss.killers[0])
2406 for (int i = KILLER_MAX - 1; i > 0; i--)
2407 ss.killers[i] = ss.killers[i - 1];
2412 // fail_high_ply_1() checks if some thread is currently resolving a fail
2413 // high at ply 1 at the node below the first root node. This information
2414 // is used for time managment.
2416 bool fail_high_ply_1() {
2417 for(int i = 0; i < ActiveThreads; i++)
2418 if(Threads[i].failHighPly1)
2424 // current_search_time() returns the number of milliseconds which have passed
2425 // since the beginning of the current search.
2427 int current_search_time() {
2428 return get_system_time() - SearchStartTime;
2432 // nps() computes the current nodes/second count.
2435 int t = current_search_time();
2436 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2440 // poll() performs two different functions: It polls for user input, and it
2441 // looks at the time consumed so far and decides if it's time to abort the
2446 static int lastInfoTime;
2447 int t = current_search_time();
2452 // We are line oriented, don't read single chars
2453 std::string command;
2454 if (!std::getline(std::cin, command))
2457 if (command == "quit")
2460 PonderSearch = false;
2463 else if(command == "stop")
2466 PonderSearch = false;
2468 else if(command == "ponderhit")
2471 // Print search information
2475 else if (lastInfoTime > t)
2476 // HACK: Must be a new search where we searched less than
2477 // NodesBetweenPolls nodes during the first second of search.
2480 else if (t - lastInfoTime >= 1000)
2487 if (dbg_show_hit_rate)
2488 dbg_print_hit_rate();
2490 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2491 << " time " << t << " hashfull " << TT.full() << std::endl;
2492 lock_release(&IOLock);
2493 if (ShowCurrentLine)
2494 Threads[0].printCurrentLine = true;
2496 // Should we stop the search?
2500 bool overTime = t > AbsoluteMaxSearchTime
2501 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2502 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2503 && t > 6*(MaxSearchTime + ExtraSearchTime));
2505 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2506 || (ExactMaxTime && t >= ExactMaxTime)
2507 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2512 // ponderhit() is called when the program is pondering (i.e. thinking while
2513 // it's the opponent's turn to move) in order to let the engine know that
2514 // it correctly predicted the opponent's move.
2517 int t = current_search_time();
2518 PonderSearch = false;
2519 if(Iteration >= 3 &&
2520 (!InfiniteSearch && (StopOnPonderhit ||
2521 t > AbsoluteMaxSearchTime ||
2522 (RootMoveNumber == 1 &&
2523 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2524 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2525 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2530 // print_current_line() prints the current line of search for a given
2531 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2533 void print_current_line(SearchStack ss[], int ply, int threadID) {
2534 assert(ply >= 0 && ply < PLY_MAX);
2535 assert(threadID >= 0 && threadID < ActiveThreads);
2537 if(!Threads[threadID].idle) {
2539 std::cout << "info currline " << (threadID + 1);
2540 for(int p = 0; p < ply; p++)
2541 std::cout << " " << ss[p].currentMove;
2542 std::cout << std::endl;
2543 lock_release(&IOLock);
2545 Threads[threadID].printCurrentLine = false;
2546 if(threadID + 1 < ActiveThreads)
2547 Threads[threadID + 1].printCurrentLine = true;
2551 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2552 // while the program is pondering. The point is to work around a wrinkle in
2553 // the UCI protocol: When pondering, the engine is not allowed to give a
2554 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2555 // We simply wait here until one of these commands is sent, and return,
2556 // after which the bestmove and pondermove will be printed (in id_loop()).
2558 void wait_for_stop_or_ponderhit() {
2559 std::string command;
2562 if(!std::getline(std::cin, command))
2565 if(command == "quit") {
2566 OpeningBook.close();
2571 else if(command == "ponderhit" || command == "stop")
2577 // idle_loop() is where the threads are parked when they have no work to do.
2578 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2579 // object for which the current thread is the master.
2581 void idle_loop(int threadID, SplitPoint *waitSp) {
2582 assert(threadID >= 0 && threadID < THREAD_MAX);
2584 Threads[threadID].running = true;
2587 if(AllThreadsShouldExit && threadID != 0)
2590 // If we are not thinking, wait for a condition to be signaled instead
2591 // of wasting CPU time polling for work:
2592 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2593 #if !defined(_MSC_VER)
2594 pthread_mutex_lock(&WaitLock);
2595 if(Idle || threadID >= ActiveThreads)
2596 pthread_cond_wait(&WaitCond, &WaitLock);
2597 pthread_mutex_unlock(&WaitLock);
2599 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2603 // If this thread has been assigned work, launch a search:
2604 if(Threads[threadID].workIsWaiting) {
2605 Threads[threadID].workIsWaiting = false;
2606 if(Threads[threadID].splitPoint->pvNode)
2607 sp_search_pv(Threads[threadID].splitPoint, threadID);
2609 sp_search(Threads[threadID].splitPoint, threadID);
2610 Threads[threadID].idle = true;
2613 // If this thread is the master of a split point and all threads have
2614 // finished their work at this split point, return from the idle loop:
2615 if(waitSp != NULL && waitSp->cpus == 0)
2619 Threads[threadID].running = false;
2623 // init_split_point_stack() is called during program initialization, and
2624 // initializes all split point objects.
2626 void init_split_point_stack() {
2627 for(int i = 0; i < THREAD_MAX; i++)
2628 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2629 SplitPointStack[i][j].parent = NULL;
2630 lock_init(&(SplitPointStack[i][j].lock), NULL);
2635 // destroy_split_point_stack() is called when the program exits, and
2636 // destroys all locks in the precomputed split point objects.
2638 void destroy_split_point_stack() {
2639 for(int i = 0; i < THREAD_MAX; i++)
2640 for(int j = 0; j < MaxActiveSplitPoints; j++)
2641 lock_destroy(&(SplitPointStack[i][j].lock));
2645 // thread_should_stop() checks whether the thread with a given threadID has
2646 // been asked to stop, directly or indirectly. This can happen if a beta
2647 // cutoff has occured in thre thread's currently active split point, or in
2648 // some ancestor of the current split point.
2650 bool thread_should_stop(int threadID) {
2651 assert(threadID >= 0 && threadID < ActiveThreads);
2655 if(Threads[threadID].stop)
2657 if(ActiveThreads <= 2)
2659 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2661 Threads[threadID].stop = true;
2668 // thread_is_available() checks whether the thread with threadID "slave" is
2669 // available to help the thread with threadID "master" at a split point. An
2670 // obvious requirement is that "slave" must be idle. With more than two
2671 // threads, this is not by itself sufficient: If "slave" is the master of
2672 // some active split point, it is only available as a slave to the other
2673 // threads which are busy searching the split point at the top of "slave"'s
2674 // split point stack (the "helpful master concept" in YBWC terminology).
2676 bool thread_is_available(int slave, int master) {
2677 assert(slave >= 0 && slave < ActiveThreads);
2678 assert(master >= 0 && master < ActiveThreads);
2679 assert(ActiveThreads > 1);
2681 if(!Threads[slave].idle || slave == master)
2684 if(Threads[slave].activeSplitPoints == 0)
2685 // No active split points means that the thread is available as a slave
2686 // for any other thread.
2689 if(ActiveThreads == 2)
2692 // Apply the "helpful master" concept if possible.
2693 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2700 // idle_thread_exists() tries to find an idle thread which is available as
2701 // a slave for the thread with threadID "master".
2703 bool idle_thread_exists(int master) {
2704 assert(master >= 0 && master < ActiveThreads);
2705 assert(ActiveThreads > 1);
2707 for(int i = 0; i < ActiveThreads; i++)
2708 if(thread_is_available(i, master))
2714 // split() does the actual work of distributing the work at a node between
2715 // several threads at PV nodes. If it does not succeed in splitting the
2716 // node (because no idle threads are available, or because we have no unused
2717 // split point objects), the function immediately returns false. If
2718 // splitting is possible, a SplitPoint object is initialized with all the
2719 // data that must be copied to the helper threads (the current position and
2720 // search stack, alpha, beta, the search depth, etc.), and we tell our
2721 // helper threads that they have been assigned work. This will cause them
2722 // to instantly leave their idle loops and call sp_search_pv(). When all
2723 // threads have returned from sp_search_pv (or, equivalently, when
2724 // splitPoint->cpus becomes 0), split() returns true.
2726 bool split(const Position &p, SearchStack *sstck, int ply,
2727 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2728 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2731 assert(sstck != NULL);
2732 assert(ply >= 0 && ply < PLY_MAX);
2733 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2734 assert(!pvNode || *alpha < *beta);
2735 assert(*beta <= VALUE_INFINITE);
2736 assert(depth > Depth(0));
2737 assert(master >= 0 && master < ActiveThreads);
2738 assert(ActiveThreads > 1);
2740 SplitPoint *splitPoint;
2745 // If no other thread is available to help us, or if we have too many
2746 // active split points, don't split:
2747 if(!idle_thread_exists(master) ||
2748 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2749 lock_release(&MPLock);
2753 // Pick the next available split point object from the split point stack:
2754 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2755 Threads[master].activeSplitPoints++;
2757 // Initialize the split point object:
2758 splitPoint->parent = Threads[master].splitPoint;
2759 splitPoint->finished = false;
2760 splitPoint->ply = ply;
2761 splitPoint->depth = depth;
2762 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2763 splitPoint->beta = *beta;
2764 splitPoint->pvNode = pvNode;
2765 splitPoint->dcCandidates = dcCandidates;
2766 splitPoint->bestValue = *bestValue;
2767 splitPoint->master = master;
2768 splitPoint->mp = mp;
2769 splitPoint->moves = *moves;
2770 splitPoint->cpus = 1;
2771 splitPoint->pos.copy(p);
2772 splitPoint->parentSstack = sstck;
2773 for(i = 0; i < ActiveThreads; i++)
2774 splitPoint->slaves[i] = 0;
2776 // Copy the current position and the search stack to the master thread:
2777 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2778 Threads[master].splitPoint = splitPoint;
2780 // Make copies of the current position and search stack for each thread:
2781 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2783 if(thread_is_available(i, master)) {
2784 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2785 Threads[i].splitPoint = splitPoint;
2786 splitPoint->slaves[i] = 1;
2790 // Tell the threads that they have work to do. This will make them leave
2792 for(i = 0; i < ActiveThreads; i++)
2793 if(i == master || splitPoint->slaves[i]) {
2794 Threads[i].workIsWaiting = true;
2795 Threads[i].idle = false;
2796 Threads[i].stop = false;
2799 lock_release(&MPLock);
2801 // Everything is set up. The master thread enters the idle loop, from
2802 // which it will instantly launch a search, because its workIsWaiting
2803 // slot is 'true'. We send the split point as a second parameter to the
2804 // idle loop, which means that the main thread will return from the idle
2805 // loop when all threads have finished their work at this split point
2806 // (i.e. when // splitPoint->cpus == 0).
2807 idle_loop(master, splitPoint);
2809 // We have returned from the idle loop, which means that all threads are
2810 // finished. Update alpha, beta and bestvalue, and return:
2812 if(pvNode) *alpha = splitPoint->alpha;
2813 *beta = splitPoint->beta;
2814 *bestValue = splitPoint->bestValue;
2815 Threads[master].stop = false;
2816 Threads[master].idle = false;
2817 Threads[master].activeSplitPoints--;
2818 Threads[master].splitPoint = splitPoint->parent;
2819 lock_release(&MPLock);
2825 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2826 // to start a new search from the root.
2828 void wake_sleeping_threads() {
2829 if(ActiveThreads > 1) {
2830 for(int i = 1; i < ActiveThreads; i++) {
2831 Threads[i].idle = true;
2832 Threads[i].workIsWaiting = false;
2834 #if !defined(_MSC_VER)
2835 pthread_mutex_lock(&WaitLock);
2836 pthread_cond_broadcast(&WaitCond);
2837 pthread_mutex_unlock(&WaitLock);
2839 for(int i = 1; i < THREAD_MAX; i++)
2840 SetEvent(SitIdleEvent[i]);
2846 // init_thread() is the function which is called when a new thread is
2847 // launched. It simply calls the idle_loop() function with the supplied
2848 // threadID. There are two versions of this function; one for POSIX threads
2849 // and one for Windows threads.
2851 #if !defined(_MSC_VER)
2853 void *init_thread(void *threadID) {
2854 idle_loop(*(int *)threadID, NULL);
2860 DWORD WINAPI init_thread(LPVOID threadID) {
2861 idle_loop(*(int *)threadID, NULL);