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-2012 Marco Costalba, Joona Kiiski, Tord Romstad
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/>.
37 #include "ucioption.h"
41 volatile SignalsType Signals;
43 std::vector<RootMove> RootMoves;
44 Position RootPosition;
45 Time::point SearchTime;
46 StateStackPtr SetupStates;
51 using namespace Search;
55 // Set to true to force running with one thread. Used for debugging
56 const bool FakeSplit = false;
58 // This is the minimum interval in msec between two check_time() calls
59 const int TimerResolution = 5;
61 // Different node types, used as template parameter
62 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
64 // Lookup table to check if a Piece is a slider and its access function
65 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
66 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
68 // Dynamic razoring margin based on depth
69 inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
71 // Futility lookup tables (initialized at startup) and their access functions
72 Value FutilityMargins[16][64]; // [depth][moveNumber]
73 int FutilityMoveCounts[32]; // [depth]
75 inline Value futility_margin(Depth d, int mn) {
77 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
81 inline int futility_move_count(Depth d) {
83 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
86 // Reduction lookup tables (initialized at startup) and their access function
87 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
89 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
91 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
94 size_t MultiPV, UCIMultiPV, PVIdx;
98 bool SkillLevelEnabled, Chess960;
101 template <NodeType NT>
102 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
104 template <NodeType NT>
105 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
107 void id_loop(Position& pos);
108 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
109 bool connected_moves(const Position& pos, Move m1, Move m2);
110 Value value_to_tt(Value v, int ply);
111 Value value_from_tt(Value v, int ply);
112 bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
113 bool connected_threat(const Position& pos, Move m, Move threat);
114 Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
115 Move do_skill_level();
116 string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
118 // is_dangerous() checks whether a move belongs to some classes of known
119 // 'dangerous' moves so that we avoid to prune it.
120 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
123 if (type_of(m) == CASTLE)
127 if ( type_of(pos.piece_moved(m)) == PAWN
128 && pos.pawn_is_passed(pos.side_to_move(), to_sq(m)))
131 // Entering a pawn endgame?
132 if ( captureOrPromotion
133 && type_of(pos.piece_on(to_sq(m))) != PAWN
134 && type_of(m) == NORMAL
135 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
136 - PieceValue[Mg][pos.piece_on(to_sq(m))] == VALUE_ZERO))
145 /// Search::init() is called during startup to initialize various lookup tables
147 void Search::init() {
149 int d; // depth (ONE_PLY == 2)
150 int hd; // half depth (ONE_PLY == 1)
153 // Init reductions array
154 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
156 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
157 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
158 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
159 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
162 // Init futility margins array
163 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
164 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
166 // Init futility move count array
167 for (d = 0; d < 32; d++)
168 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
172 /// Search::perft() is our utility to verify move generation. All the leaf nodes
173 /// up to the given depth are generated and counted and the sum returned.
175 size_t Search::perft(Position& pos, Depth depth) {
177 // At the last ply just return the number of legal moves (leaf nodes)
178 if (depth == ONE_PLY)
179 return MoveList<LEGAL>(pos).size();
185 for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
187 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
188 cnt += perft(pos, depth - ONE_PLY);
189 pos.undo_move(ml.move());
196 /// Search::think() is the external interface to Stockfish's search, and is
197 /// called by the main thread when the program receives the UCI 'go' command. It
198 /// searches from RootPosition and at the end prints the "bestmove" to output.
200 void Search::think() {
202 static PolyglotBook book; // Defined static to initialize the PRNG only once
204 Position& pos = RootPosition;
205 Chess960 = pos.is_chess960();
206 Eval::RootColor = pos.side_to_move();
207 TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
211 if (RootMoves.empty())
213 sync_cout << "info depth 0 score "
214 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << sync_endl;
216 RootMoves.push_back(MOVE_NONE);
220 if (Options["OwnBook"] && !Limits.infinite)
222 Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
224 if (bookMove && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
226 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
231 UCIMultiPV = Options["MultiPV"];
232 SkillLevel = Options["Skill Level"];
234 // Do we have to play with skill handicap? In this case enable MultiPV that
235 // we will use behind the scenes to retrieve a set of possible moves.
236 SkillLevelEnabled = (SkillLevel < 20);
237 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
239 if (Options["Use Search Log"])
241 Log log(Options["Search Log Filename"]);
242 log << "\nSearching: " << pos.to_fen()
243 << "\ninfinite: " << Limits.infinite
244 << " ponder: " << Limits.ponder
245 << " time: " << Limits.time[pos.side_to_move()]
246 << " increment: " << Limits.inc[pos.side_to_move()]
247 << " moves to go: " << Limits.movestogo
253 // Set best timer interval to avoid lagging under time pressure. Timer is
254 // used to check for remaining available thinking time.
255 if (Limits.use_time_management())
256 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
257 else if (Limits.nodes)
258 Threads.set_timer(2 * TimerResolution);
260 Threads.set_timer(100);
262 // We're ready to start searching. Call the iterative deepening loop function
265 Threads.set_timer(0); // Stop timer
268 if (Options["Use Search Log"])
270 Time::point elapsed = Time::now() - SearchTime + 1;
272 Log log(Options["Search Log Filename"]);
273 log << "Nodes: " << pos.nodes_searched()
274 << "\nNodes/second: " << pos.nodes_searched() * 1000 / elapsed
275 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
278 pos.do_move(RootMoves[0].pv[0], st);
279 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << std::endl;
280 pos.undo_move(RootMoves[0].pv[0]);
285 // When we reach max depth we arrive here even without Signals.stop is raised,
286 // but if we are pondering or in infinite search, we shouldn't print the best
287 // move before we are told to do so.
288 if (!Signals.stop && (Limits.ponder || Limits.infinite))
289 pos.this_thread()->wait_for_stop_or_ponderhit();
291 // Best move could be MOVE_NONE when searching on a stalemate position
292 sync_cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
293 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << sync_endl;
299 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
300 // with increasing depth until the allocated thinking time has been consumed,
301 // user stops the search, or the maximum search depth is reached.
303 void id_loop(Position& pos) {
305 Stack ss[MAX_PLY_PLUS_2];
306 int depth, prevBestMoveChanges;
307 Value bestValue, alpha, beta, delta;
308 bool bestMoveNeverChanged = true;
309 Move skillBest = MOVE_NONE;
311 memset(ss, 0, 4 * sizeof(Stack));
312 depth = BestMoveChanges = 0;
313 bestValue = delta = -VALUE_INFINITE;
314 ss->currentMove = MOVE_NULL; // Hack to skip update gains
316 // Iterative deepening loop until requested to stop or target depth reached
317 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
319 // Save last iteration's scores before first PV line is searched and all
320 // the move scores but the (new) PV are set to -VALUE_INFINITE.
321 for (size_t i = 0; i < RootMoves.size(); i++)
322 RootMoves[i].prevScore = RootMoves[i].score;
324 prevBestMoveChanges = BestMoveChanges;
327 // MultiPV loop. We perform a full root search for each PV line
328 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
330 // Set aspiration window default width
331 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
334 alpha = RootMoves[PVIdx].prevScore - delta;
335 beta = RootMoves[PVIdx].prevScore + delta;
339 alpha = -VALUE_INFINITE;
340 beta = VALUE_INFINITE;
343 // Start with a small aspiration window and, in case of fail high/low,
344 // research with bigger window until not failing high/low anymore.
347 // Search starts from ss+1 to allow referencing (ss-1). This is
348 // needed by update gains and ss copy when splitting at Root.
349 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
351 // Bring to front the best move. It is critical that sorting is
352 // done with a stable algorithm because all the values but the first
353 // and eventually the new best one are set to -VALUE_INFINITE and
354 // we want to keep the same order for all the moves but the new
355 // PV that goes to the front. Note that in case of MultiPV search
356 // the already searched PV lines are preserved.
357 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
359 // In case we have found an exact score and we are going to leave
360 // the fail high/low loop then reorder the PV moves, otherwise
361 // leave the last PV move in its position so to be searched again.
362 // Of course this is needed only in MultiPV search.
363 if (PVIdx && bestValue > alpha && bestValue < beta)
364 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
366 // Write PV back to transposition table in case the relevant
367 // entries have been overwritten during the search.
368 for (size_t i = 0; i <= PVIdx; i++)
369 RootMoves[i].insert_pv_in_tt(pos);
371 // If search has been stopped exit the aspiration window loop.
372 // Sorting and writing PV back to TT is safe becuase RootMoves
373 // is still valid, although refers to previous iteration.
377 // Send full PV info to GUI if we are going to leave the loop or
378 // if we have a fail high/low and we are deep in the search.
379 if ((bestValue > alpha && bestValue < beta) || Time::now() - SearchTime > 2000)
380 sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
382 // In case of failing high/low increase aspiration window and
383 // research, otherwise exit the fail high/low loop.
384 if (bestValue >= beta)
389 else if (bestValue <= alpha)
391 Signals.failedLowAtRoot = true;
392 Signals.stopOnPonderhit = false;
400 // Search with full window in case we have a win/mate score
401 if (abs(bestValue) >= VALUE_KNOWN_WIN)
403 alpha = -VALUE_INFINITE;
404 beta = VALUE_INFINITE;
407 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
411 // Skills: Do we need to pick now the best move ?
412 if (SkillLevelEnabled && depth == 1 + SkillLevel)
413 skillBest = do_skill_level();
415 if (!Signals.stop && Options["Use Search Log"])
417 Log log(Options["Search Log Filename"]);
418 log << pretty_pv(pos, depth, bestValue, Time::now() - SearchTime, &RootMoves[0].pv[0])
422 // Filter out startup noise when monitoring best move stability
423 if (depth > 2 && BestMoveChanges)
424 bestMoveNeverChanged = false;
426 // Do we have time for the next iteration? Can we stop searching now?
427 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
429 bool stop = false; // Local variable, not the volatile Signals.stop
431 // Take in account some extra time if the best move has changed
432 if (depth > 4 && depth < 50)
433 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
435 // Stop search if most of available time is already consumed. We
436 // probably don't have enough time to search the first move at the
437 // next iteration anyway.
438 if (Time::now() - SearchTime > (TimeMgr.available_time() * 62) / 100)
441 // Stop search early if one move seems to be much better than others
444 && ( (bestMoveNeverChanged && pos.captured_piece_type())
445 || Time::now() - SearchTime > (TimeMgr.available_time() * 40) / 100))
447 Value rBeta = bestValue - 2 * PawnValueMg;
448 (ss+1)->excludedMove = RootMoves[0].pv[0];
449 (ss+1)->skipNullMove = true;
450 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
451 (ss+1)->skipNullMove = false;
452 (ss+1)->excludedMove = MOVE_NONE;
460 // If we are allowed to ponder do not stop the search now but
461 // keep pondering until GUI sends "ponderhit" or "stop".
463 Signals.stopOnPonderhit = true;
470 // When using skills swap best PV line with the sub-optimal one
471 if (SkillLevelEnabled)
473 if (skillBest == MOVE_NONE) // Still unassigned ?
474 skillBest = do_skill_level();
476 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), skillBest));
481 // search<>() is the main search function for both PV and non-PV nodes and for
482 // normal and SplitPoint nodes. When called just after a split point the search
483 // is simpler because we have already probed the hash table, done a null move
484 // search, and searched the first move before splitting, we don't have to repeat
485 // all this work again. We also don't need to store anything to the hash table
486 // here: This is taken care of after we return from the split point.
488 template <NodeType NT>
489 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
491 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
492 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
493 const bool RootNode = (NT == Root || NT == SplitPointRoot);
495 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
496 assert(PvNode || (alpha == beta - 1));
497 assert(depth > DEPTH_ZERO);
499 Move movesSearched[64];
504 Move ttMove, move, excludedMove, bestMove, threatMove;
506 Value bestValue, value, ttValue;
507 Value refinedValue, nullValue, futilityValue;
508 bool pvMove, inCheck, singularExtensionNode, givesCheck;
509 bool captureOrPromotion, dangerous, doFullDepthSearch;
510 int moveCount, playedMoveCount;
512 // Step 1. Initialize node
513 Thread* thisThread = pos.this_thread();
514 moveCount = playedMoveCount = 0;
515 inCheck = pos.in_check();
520 bestMove = sp->bestMove;
521 threatMove = sp->threatMove;
522 bestValue = sp->bestValue;
524 ttMove = excludedMove = MOVE_NONE;
525 ttValue = VALUE_NONE;
527 assert(sp->bestValue > -VALUE_INFINITE && sp->moveCount > 0);
529 goto split_point_start;
532 bestValue = -VALUE_INFINITE;
533 ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
534 ss->ply = (ss-1)->ply + 1;
535 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
536 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
538 // Used to send selDepth info to GUI
539 if (PvNode && thisThread->maxPly < ss->ply)
540 thisThread->maxPly = ss->ply;
544 // Step 2. Check for aborted search and immediate draw
545 if (Signals.stop || pos.is_draw<false>() || ss->ply > MAX_PLY)
546 return Eval::ValueDrawContempt;
548 // Step 3. Mate distance pruning. Even if we mate at the next move our score
549 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
550 // a shorter mate was found upward in the tree then there is no need to search
551 // further, we will never beat current alpha. Same logic but with reversed signs
552 // applies also in the opposite condition of being mated instead of giving mate,
553 // in this case return a fail-high score.
554 alpha = std::max(mated_in(ss->ply), alpha);
555 beta = std::min(mate_in(ss->ply+1), beta);
560 // Step 4. Transposition table lookup
561 // We don't want the score of a partial search to overwrite a previous full search
562 // TT value, so we use a different position key in case of an excluded move.
563 excludedMove = ss->excludedMove;
564 posKey = excludedMove ? pos.exclusion_key() : pos.key();
565 tte = TT.probe(posKey);
566 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
567 ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
569 // At PV nodes we check for exact scores, while at non-PV nodes we check for
570 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
571 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
572 // we should also update RootMoveList to avoid bogus output.
573 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
574 : can_return_tt(tte, depth, ttValue, beta)))
577 ss->currentMove = ttMove; // Can be MOVE_NONE
581 && !pos.is_capture_or_promotion(ttMove)
582 && ttMove != ss->killers[0])
584 ss->killers[1] = ss->killers[0];
585 ss->killers[0] = ttMove;
590 // Step 5. Evaluate the position statically and update parent's gain statistics
592 ss->eval = ss->evalMargin = refinedValue = VALUE_NONE;
595 assert(tte->static_value() != VALUE_NONE);
597 ss->eval = tte->static_value();
598 ss->evalMargin = tte->static_value_margin();
599 refinedValue = refine_eval(tte, ttValue, ss->eval);
603 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
604 TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
607 // Update gain for the parent non-capture move given the static position
608 // evaluation before and after the move.
609 if ( (move = (ss-1)->currentMove) != MOVE_NULL
610 && (ss-1)->eval != VALUE_NONE
611 && ss->eval != VALUE_NONE
612 && !pos.captured_piece_type()
613 && type_of(move) == NORMAL)
615 Square to = to_sq(move);
616 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
619 // Step 6. Razoring (is omitted in PV nodes)
621 && depth < 4 * ONE_PLY
623 && refinedValue + razor_margin(depth) < beta
624 && ttMove == MOVE_NONE
625 && abs(beta) < VALUE_MATE_IN_MAX_PLY
626 && !pos.pawn_on_7th(pos.side_to_move()))
628 Value rbeta = beta - razor_margin(depth);
629 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
631 // Logically we should return (v + razor_margin(depth)), but
632 // surprisingly this did slightly weaker in tests.
636 // Step 7. Static null move pruning (is omitted in PV nodes)
637 // We're betting that the opponent doesn't have a move that will reduce
638 // the score by more than futility_margin(depth) if we do a null move.
641 && depth < 4 * ONE_PLY
643 && refinedValue - futility_margin(depth, 0) >= beta
644 && abs(beta) < VALUE_MATE_IN_MAX_PLY
645 && pos.non_pawn_material(pos.side_to_move()))
646 return refinedValue - futility_margin(depth, 0);
648 // Step 8. Null move search with verification search (is omitted in PV nodes)
653 && refinedValue >= beta
654 && abs(beta) < VALUE_MATE_IN_MAX_PLY
655 && pos.non_pawn_material(pos.side_to_move()))
657 ss->currentMove = MOVE_NULL;
659 // Null move dynamic reduction based on depth
660 Depth R = 3 * ONE_PLY + depth / 4;
662 // Null move dynamic reduction based on value
663 if (refinedValue - PawnValueMg > beta)
666 pos.do_null_move<true>(st);
667 (ss+1)->skipNullMove = true;
668 nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
669 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
670 (ss+1)->skipNullMove = false;
671 pos.do_null_move<false>(st);
673 if (nullValue >= beta)
675 // Do not return unproven mate scores
676 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
679 if (depth < 6 * ONE_PLY)
682 // Do verification search at high depths
683 ss->skipNullMove = true;
684 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
685 ss->skipNullMove = false;
692 // The null move failed low, which means that we may be faced with
693 // some kind of threat. If the previous move was reduced, check if
694 // the move that refuted the null move was somehow connected to the
695 // move which was reduced. If a connection is found, return a fail
696 // low score (which will cause the reduced move to fail high in the
697 // parent node, which will trigger a re-search with full depth).
698 threatMove = (ss+1)->currentMove;
700 if ( depth < 5 * ONE_PLY
702 && threatMove != MOVE_NONE
703 && connected_moves(pos, (ss-1)->currentMove, threatMove))
708 // Step 9. ProbCut (is omitted in PV nodes)
709 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
710 // and a reduced search returns a value much above beta, we can (almost) safely
711 // prune the previous move.
713 && depth >= 5 * ONE_PLY
716 && excludedMove == MOVE_NONE
717 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
719 Value rbeta = beta + 200;
720 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
722 assert(rdepth >= ONE_PLY);
723 assert((ss-1)->currentMove != MOVE_NONE);
724 assert((ss-1)->currentMove != MOVE_NULL);
726 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
729 while ((move = mp.next_move<false>()) != MOVE_NONE)
730 if (pos.pl_move_is_legal(move, ci.pinned))
732 ss->currentMove = move;
733 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
734 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
741 // Step 10. Internal iterative deepening
742 if ( depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
743 && ttMove == MOVE_NONE
744 && (PvNode || (!inCheck && ss->eval + Value(256) >= beta)))
746 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
748 ss->skipNullMove = true;
749 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
750 ss->skipNullMove = false;
752 tte = TT.probe(posKey);
753 ttMove = tte ? tte->move() : MOVE_NONE;
756 split_point_start: // At split points actual search starts from here
758 MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
760 value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
761 singularExtensionNode = !RootNode
763 && depth >= (PvNode ? 6 * ONE_PLY : 8 * ONE_PLY)
764 && ttMove != MOVE_NONE
765 && !excludedMove // Recursive singular search is not allowed
766 && (tte->type() & BOUND_LOWER)
767 && tte->depth() >= depth - 3 * ONE_PLY;
769 // Step 11. Loop through moves
770 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
771 while (bestValue < beta && (move = mp.next_move<SpNode>()) != MOVE_NONE)
775 if (move == excludedMove)
778 // At root obey the "searchmoves" option and skip moves not listed in Root
779 // Move List, as a consequence any illegal move is also skipped. In MultiPV
780 // mode we also skip PV moves which have been already searched.
781 if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
786 // Shared counter cannot be decremented later if move turns out to be illegal
787 if (!pos.pl_move_is_legal(move, ci.pinned))
790 moveCount = ++sp->moveCount;
798 Signals.firstRootMove = (moveCount == 1);
800 if (thisThread == Threads.main_thread() && Time::now() - SearchTime > 2000)
801 sync_cout << "info depth " << depth / ONE_PLY
802 << " currmove " << move_to_uci(move, Chess960)
803 << " currmovenumber " << moveCount + PVIdx << sync_endl;
806 captureOrPromotion = pos.is_capture_or_promotion(move);
807 givesCheck = pos.move_gives_check(move, ci);
808 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
811 // Step 12. Extend checks and, in PV nodes, also dangerous moves
812 if (PvNode && dangerous)
815 else if (givesCheck && pos.see_sign(move) >= 0)
818 // Singular extension search. If all moves but one fail low on a search of
819 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
820 // is singular and should be extended. To verify this we do a reduced search
821 // on all the other moves but the ttMove, if result is lower than ttValue minus
822 // a margin then we extend ttMove.
823 if ( singularExtensionNode
826 && pos.pl_move_is_legal(move, ci.pinned)
827 && abs(ttValue) < VALUE_KNOWN_WIN)
829 Value rBeta = ttValue - int(depth);
830 ss->excludedMove = move;
831 ss->skipNullMove = true;
832 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
833 ss->skipNullMove = false;
834 ss->excludedMove = MOVE_NONE;
837 ext = rBeta >= beta ? ONE_PLY + ONE_PLY / 2 : ONE_PLY;
840 // Update current move (this must be done after singular extension search)
841 newDepth = depth - ONE_PLY + ext;
843 // Step 13. Futility pruning (is omitted in PV nodes)
845 && !captureOrPromotion
849 && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
851 // Move count based pruning
852 if ( moveCount >= futility_move_count(depth)
853 && (!threatMove || !connected_threat(pos, move, threatMove)))
861 // Value based pruning
862 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
863 // but fixing this made program slightly weaker.
864 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
865 futilityValue = ss->eval + ss->evalMargin + futility_margin(predictedDepth, moveCount)
866 + H.gain(pos.piece_moved(move), to_sq(move));
868 if (futilityValue < beta)
876 // Prune moves with negative SEE at low depths
877 if ( predictedDepth < 2 * ONE_PLY
878 && pos.see_sign(move) < 0)
887 // Check for legality only before to do the move
888 if (!pos.pl_move_is_legal(move, ci.pinned))
894 pvMove = PvNode ? moveCount == 1 : false;
895 ss->currentMove = move;
896 if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
897 movesSearched[playedMoveCount++] = move;
899 // Step 14. Make the move
900 pos.do_move(move, st, ci, givesCheck);
902 // Step 15. Reduced depth search (LMR). If the move fails high will be
903 // re-searched at full depth.
904 if ( depth > 3 * ONE_PLY
906 && !captureOrPromotion
908 && ss->killers[0] != move
909 && ss->killers[1] != move)
911 ss->reduction = reduction<PvNode>(depth, moveCount);
912 Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
913 alpha = SpNode ? sp->alpha : alpha;
915 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
917 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
918 ss->reduction = DEPTH_ZERO;
921 doFullDepthSearch = !pvMove;
923 // Step 16. Full depth search, when LMR is skipped or fails high
924 if (doFullDepthSearch)
926 alpha = SpNode ? sp->alpha : alpha;
927 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
928 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
931 // Only for PV nodes do a full PV search on the first move or after a fail
932 // high, in the latter case search only if value < beta, otherwise let the
933 // parent node to fail low with value <= alpha and to try another move.
934 if (PvNode && (pvMove || (value > alpha && (RootNode || value < beta))))
935 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
936 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
938 // Step 17. Undo move
941 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
943 // Step 18. Check for new best move
947 bestValue = sp->bestValue;
951 // Finished searching the move. If Signals.stop is true, the search
952 // was aborted because the user interrupted the search or because we
953 // ran out of time. In this case, the return value of the search cannot
954 // be trusted, and we don't update the best move and/or PV.
955 if (Signals.stop || thisThread->cutoff_occurred())
960 RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
962 // PV move or new best move ?
963 if (pvMove || value > alpha)
966 rm.extract_pv_from_tt(pos);
968 // We record how often the best move has been changed in each
969 // iteration. This information is used for time management: When
970 // the best move changes frequently, we allocate some more time.
971 if (!pvMove && MultiPV == 1)
975 // All other moves but the PV are set to the lowest value, this
976 // is not a problem when sorting becuase sort is stable and move
977 // position in the list is preserved, just the PV is pushed up.
978 rm.score = -VALUE_INFINITE;
981 if (value > bestValue)
989 if (PvNode && value < beta)
990 alpha = bestValue; // Update alpha here! Always alpha < beta
995 sp->bestValue = bestValue;
996 sp->bestMove = bestMove;
999 if (bestValue >= beta)
1004 // Step 19. Check for splitting the search
1006 && depth >= Threads.min_split_depth()
1008 && Threads.available_slave_exists(thisThread))
1009 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1010 depth, threatMove, moveCount, mp, NT);
1016 // Step 20. Check for mate and stalemate
1017 // All legal moves have been searched and if there are no legal moves, it
1018 // must be mate or stalemate. Note that we can have a false positive in
1019 // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1020 // harmless because return value is discarded anyhow in the parent nodes.
1021 // If we are in a singular extension search then return a fail low score.
1022 // A split node has at least one move, the one tried before to be splitted.
1024 return excludedMove ? alpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1026 // If we have pruned all the moves without searching return a fail-low score
1027 if (bestValue == -VALUE_INFINITE)
1029 assert(!playedMoveCount);
1034 if (bestValue >= beta) // Failed high
1036 TT.store(posKey, value_to_tt(bestValue, ss->ply), BOUND_LOWER, depth,
1037 bestMove, ss->eval, ss->evalMargin);
1039 if (!pos.is_capture_or_promotion(bestMove) && !inCheck)
1041 if (bestMove != ss->killers[0])
1043 ss->killers[1] = ss->killers[0];
1044 ss->killers[0] = bestMove;
1047 // Increase history value of the cut-off move
1048 Value bonus = Value(int(depth) * int(depth));
1049 H.add(pos.piece_moved(bestMove), to_sq(bestMove), bonus);
1051 // Decrease history of all the other played non-capture moves
1052 for (int i = 0; i < playedMoveCount - 1; i++)
1054 Move m = movesSearched[i];
1055 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1059 else // Failed low or PV search
1060 TT.store(posKey, value_to_tt(bestValue, ss->ply),
1061 PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1062 depth, bestMove, ss->eval, ss->evalMargin);
1064 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1070 // qsearch() is the quiescence search function, which is called by the main
1071 // search function when the remaining depth is zero (or, to be more precise,
1072 // less than ONE_PLY).
1074 template <NodeType NT>
1075 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1077 const bool PvNode = (NT == PV);
1079 assert(NT == PV || NT == NonPV);
1080 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1081 assert((alpha == beta - 1) || PvNode);
1082 assert(depth <= DEPTH_ZERO);
1085 Move ttMove, move, bestMove;
1086 Value ttValue, bestValue, value, evalMargin, futilityValue, futilityBase;
1087 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1091 Value oldAlpha = alpha;
1093 ss->currentMove = bestMove = MOVE_NONE;
1094 ss->ply = (ss-1)->ply + 1;
1096 // Check for an instant draw or maximum ply reached
1097 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1098 return Eval::ValueDrawContempt;
1100 // Decide whether or not to include checks, this fixes also the type of
1101 // TT entry depth that we are going to use. Note that in qsearch we use
1102 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1103 inCheck = pos.in_check();
1104 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1106 // Transposition table lookup. At PV nodes, we don't use the TT for
1107 // pruning, but only for move ordering.
1108 tte = TT.probe(pos.key());
1109 ttMove = (tte ? tte->move() : MOVE_NONE);
1110 ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_ZERO;
1112 if (!PvNode && tte && can_return_tt(tte, ttDepth, ttValue, beta))
1114 ss->currentMove = ttMove; // Can be MOVE_NONE
1118 // Evaluate the position statically
1121 bestValue = futilityBase = -VALUE_INFINITE;
1122 ss->eval = evalMargin = VALUE_NONE;
1123 enoughMaterial = false;
1129 assert(tte->static_value() != VALUE_NONE);
1131 evalMargin = tte->static_value_margin();
1132 ss->eval = bestValue = tte->static_value();
1135 ss->eval = bestValue = evaluate(pos, evalMargin);
1137 // Stand pat. Return immediately if static value is at least beta
1138 if (bestValue >= beta)
1141 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1146 if (PvNode && bestValue > alpha)
1149 futilityBase = ss->eval + evalMargin + Value(128);
1150 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1153 // Initialize a MovePicker object for the current position, and prepare
1154 // to search the moves. Because the depth is <= 0 here, only captures,
1155 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1157 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1160 // Loop through the moves until no moves remain or a beta cutoff occurs
1161 while ( bestValue < beta
1162 && (move = mp.next_move<false>()) != MOVE_NONE)
1164 assert(is_ok(move));
1166 givesCheck = pos.move_gives_check(move, ci);
1174 && type_of(move) != PROMOTION
1175 && !pos.is_passed_pawn_push(move))
1177 futilityValue = futilityBase
1178 + PieceValue[Eg][pos.piece_on(to_sq(move))]
1179 + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1181 if (futilityValue < beta)
1183 if (futilityValue > bestValue)
1184 bestValue = futilityValue;
1189 // Prune moves with negative or equal SEE
1190 if ( futilityBase < beta
1191 && depth < DEPTH_ZERO
1192 && pos.see(move) <= 0)
1196 // Detect non-capture evasions that are candidate to be pruned
1197 evasionPrunable = !PvNode
1199 && bestValue > VALUE_MATED_IN_MAX_PLY
1200 && !pos.is_capture(move)
1201 && !pos.can_castle(pos.side_to_move());
1203 // Don't search moves with negative SEE values
1205 && (!inCheck || evasionPrunable)
1207 && type_of(move) != PROMOTION
1208 && pos.see_sign(move) < 0)
1211 // Don't search useless checks
1216 && !pos.is_capture_or_promotion(move)
1217 && ss->eval + PawnValueMg / 4 < beta
1218 && !check_is_dangerous(pos, move, futilityBase, beta))
1221 // Check for legality only before to do the move
1222 if (!pos.pl_move_is_legal(move, ci.pinned))
1225 ss->currentMove = move;
1227 // Make and search the move
1228 pos.do_move(move, st, ci, givesCheck);
1229 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1230 pos.undo_move(move);
1232 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1235 if (value > bestValue)
1242 && value < beta) // We want always alpha < beta
1247 // All legal moves have been searched. A special case: If we're in check
1248 // and no legal moves were found, it is checkmate.
1249 if (inCheck && bestValue == -VALUE_INFINITE)
1250 return mated_in(ss->ply); // Plies to mate from the root
1252 // Update transposition table
1253 move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1254 bt = bestValue <= oldAlpha ? BOUND_UPPER
1255 : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1257 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1259 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1265 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1266 // bestValue is updated only when returning false because in that case move
1269 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1271 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1272 Square from, to, ksq;
1276 from = from_sq(move);
1278 them = ~pos.side_to_move();
1279 ksq = pos.king_square(them);
1280 kingAtt = pos.attacks_from<KING>(ksq);
1281 pc = pos.piece_moved(move);
1283 occ = pos.pieces() ^ from ^ ksq;
1284 oldAtt = pos.attacks_from(pc, from, occ);
1285 newAtt = pos.attacks_from(pc, to, occ);
1287 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1288 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1290 if (!more_than_one(b))
1293 // Rule 2. Queen contact check is very dangerous
1294 if (type_of(pc) == QUEEN && (kingAtt & to))
1297 // Rule 3. Creating new double threats with checks
1298 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1301 // Note that here we generate illegal "double move"!
1302 if (futilityBase + PieceValue[Eg][pos.piece_on(pop_lsb(&b))] >= beta)
1310 // connected_moves() tests whether two moves are 'connected' in the sense
1311 // that the first move somehow made the second move possible (for instance
1312 // if the moving piece is the same in both moves). The first move is assumed
1313 // to be the move that was made to reach the current position, while the
1314 // second move is assumed to be a move from the current position.
1316 bool connected_moves(const Position& pos, Move m1, Move m2) {
1318 Square f1, t1, f2, t2;
1325 // Case 1: The moving piece is the same in both moves
1331 // Case 2: The destination square for m2 was vacated by m1
1337 // Case 3: Moving through the vacated square
1338 p2 = pos.piece_on(f2);
1339 if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1342 // Case 4: The destination square for m2 is defended by the moving piece in m1
1343 p1 = pos.piece_on(t1);
1344 if (pos.attacks_from(p1, t1) & t2)
1347 // Case 5: Discovered check, checking piece is the piece moved in m1
1348 ksq = pos.king_square(pos.side_to_move());
1349 if ( piece_is_slider(p1)
1350 && (between_bb(t1, ksq) & f2)
1351 && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1358 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1359 // "plies to mate from the current position". Non-mate scores are unchanged.
1360 // The function is called before storing a value to the transposition table.
1362 Value value_to_tt(Value v, int ply) {
1364 if (v >= VALUE_MATE_IN_MAX_PLY)
1367 if (v <= VALUE_MATED_IN_MAX_PLY)
1374 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1375 // from the transposition table (where refers to the plies to mate/be mated
1376 // from current position) to "plies to mate/be mated from the root".
1378 Value value_from_tt(Value v, int ply) {
1380 if (v >= VALUE_MATE_IN_MAX_PLY)
1383 if (v <= VALUE_MATED_IN_MAX_PLY)
1390 // connected_threat() tests whether it is safe to forward prune a move or if
1391 // is somehow connected to the threat move returned by null search.
1393 bool connected_threat(const Position& pos, Move m, Move threat) {
1396 assert(is_ok(threat));
1397 assert(!pos.is_capture_or_promotion(m));
1398 assert(!pos.is_passed_pawn_push(m));
1400 Square mfrom, mto, tfrom, tto;
1404 tfrom = from_sq(threat);
1405 tto = to_sq(threat);
1407 // Case 1: Don't prune moves which move the threatened piece
1411 // Case 2: If the threatened piece has value less than or equal to the
1412 // value of the threatening piece, don't prune moves which defend it.
1413 if ( pos.is_capture(threat)
1414 && ( PieceValue[Mg][pos.piece_on(tfrom)] >= PieceValue[Mg][pos.piece_on(tto)]
1415 || type_of(pos.piece_on(tfrom)) == KING)
1416 && pos.move_attacks_square(m, tto))
1419 // Case 3: If the moving piece in the threatened move is a slider, don't
1420 // prune safe moves which block its ray.
1421 if ( piece_is_slider(pos.piece_on(tfrom))
1422 && (between_bb(tfrom, tto) & mto)
1423 && pos.see_sign(m) >= 0)
1430 // can_return_tt() returns true if a transposition table score can be used to
1431 // cut-off at a given point in search.
1433 bool can_return_tt(const TTEntry* tte, Depth depth, Value v, Value beta) {
1435 return ( tte->depth() >= depth
1436 || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1437 || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1439 && ( ((tte->type() & BOUND_LOWER) && v >= beta)
1440 || ((tte->type() & BOUND_UPPER) && v < beta));
1444 // refine_eval() returns the transposition table score if possible, otherwise
1445 // falls back on static position evaluation.
1447 Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1451 if ( ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1452 || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1459 // When playing with strength handicap choose best move among the MultiPV set
1460 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1462 Move do_skill_level() {
1464 assert(MultiPV > 1);
1468 // PRNG sequence should be not deterministic
1469 for (int i = Time::now() % 50; i > 0; i--)
1470 rk.rand<unsigned>();
1472 // RootMoves are already sorted by score in descending order
1473 size_t size = std::min(MultiPV, RootMoves.size());
1474 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1475 int weakness = 120 - 2 * SkillLevel;
1476 int max_s = -VALUE_INFINITE;
1477 Move best = MOVE_NONE;
1479 // Choose best move. For each move score we add two terms both dependent on
1480 // weakness, one deterministic and bigger for weaker moves, and one random,
1481 // then we choose the move with the resulting highest score.
1482 for (size_t i = 0; i < size; i++)
1484 int s = RootMoves[i].score;
1486 // Don't allow crazy blunders even at very low skills
1487 if (i > 0 && RootMoves[i-1].score > s + 2 * PawnValueMg)
1490 // This is our magic formula
1491 s += ( weakness * int(RootMoves[0].score - s)
1492 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1497 best = RootMoves[i].pv[0];
1504 // uci_pv() formats PV information according to UCI protocol. UCI requires
1505 // to send all the PV lines also if are still to be searched and so refer to
1506 // the previous search score.
1508 string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1510 std::stringstream s;
1511 Time::point elaspsed = Time::now() - SearchTime + 1;
1514 for (size_t i = 0; i < Threads.size(); i++)
1515 if (Threads[i].maxPly > selDepth)
1516 selDepth = Threads[i].maxPly;
1518 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1520 bool updated = (i <= PVIdx);
1522 if (depth == 1 && !updated)
1525 int d = (updated ? depth : depth - 1);
1526 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1528 if (s.rdbuf()->in_avail())
1531 s << "info depth " << d
1532 << " seldepth " << selDepth
1533 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1534 << " nodes " << pos.nodes_searched()
1535 << " nps " << pos.nodes_searched() * 1000 / elaspsed
1536 << " time " << elaspsed
1537 << " multipv " << i + 1
1540 for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1541 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1550 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1551 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1552 /// allow to always have a ponder move even when we fail high at root, and a
1553 /// long PV to print that is important for position analysis.
1555 void RootMove::extract_pv_from_tt(Position& pos) {
1557 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1562 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1566 pos.do_move(m, *st++);
1568 while ( (tte = TT.probe(pos.key())) != NULL
1569 && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1570 && pos.is_pseudo_legal(m)
1571 && pos.pl_move_is_legal(m, pos.pinned_pieces())
1573 && (!pos.is_draw<false>() || ply < 2))
1576 pos.do_move(m, *st++);
1579 pv.push_back(MOVE_NONE);
1581 do pos.undo_move(pv[--ply]); while (ply);
1585 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1586 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1587 /// first, even if the old TT entries have been overwritten.
1589 void RootMove::insert_pv_in_tt(Position& pos) {
1591 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1594 Value v, m = VALUE_NONE;
1597 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1603 // Don't overwrite existing correct entries
1604 if (!tte || tte->move() != pv[ply])
1606 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1607 TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1609 pos.do_move(pv[ply], *st++);
1611 } while (pv[++ply] != MOVE_NONE);
1613 do pos.undo_move(pv[--ply]); while (ply);
1617 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1619 void Thread::idle_loop() {
1621 // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1622 // object for which the thread is the master.
1623 const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1625 assert(!sp_master || (sp_master->master == this && is_searching));
1627 // If this thread is the master of a split point and all slaves have
1628 // finished their work at this split point, return from the idle loop.
1629 while (!sp_master || sp_master->slavesMask)
1631 // If we are not searching, wait for a condition to be signaled
1632 // instead of wasting CPU time polling for work.
1635 || (!is_searching && Threads.use_sleeping_threads()))
1643 // Grab the lock to avoid races with Thread::wake_up()
1646 // If we are master and all slaves have finished don't go to sleep
1647 if (sp_master && !sp_master->slavesMask)
1653 // Do sleep after retesting sleep conditions under lock protection, in
1654 // particular we need to avoid a deadlock in case a master thread has,
1655 // in the meanwhile, allocated us and sent the wake_up() call before we
1656 // had the chance to grab the lock.
1657 if (do_sleep || !is_searching)
1658 sleepCondition.wait(mutex);
1663 // If this thread has been assigned work, launch a search
1666 assert(!do_sleep && !do_exit);
1668 Threads.mutex.lock();
1670 assert(is_searching);
1671 SplitPoint* sp = curSplitPoint;
1673 Threads.mutex.unlock();
1675 Stack ss[MAX_PLY_PLUS_2];
1676 Position pos(*sp->pos, this);
1678 memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1683 assert(sp->activePositions[idx] == NULL);
1685 sp->activePositions[idx] = &pos;
1687 if (sp->nodeType == Root)
1688 search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1689 else if (sp->nodeType == PV)
1690 search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1691 else if (sp->nodeType == NonPV)
1692 search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1696 assert(is_searching);
1698 is_searching = false;
1699 sp->activePositions[idx] = NULL;
1700 sp->slavesMask &= ~(1ULL << idx);
1701 sp->nodes += pos.nodes_searched();
1703 // Wake up master thread so to allow it to return from the idle loop in
1704 // case we are the last slave of the split point.
1705 if ( Threads.use_sleeping_threads()
1706 && this != sp->master
1709 assert(!sp->master->is_searching);
1710 sp->master->wake_up();
1713 // After releasing the lock we cannot access anymore any SplitPoint
1714 // related data in a safe way becuase it could have been released under
1715 // our feet by the sp master. Also accessing other Thread objects is
1716 // unsafe because if we are exiting there is a chance are already freed.
1723 /// check_time() is called by the timer thread when the timer triggers. It is
1724 /// used to print debug info and, more important, to detect when we are out of
1725 /// available time and so stop the search.
1729 static Time::point lastInfoTime = Time::now();
1730 int64_t nodes = 0; // Workaround silly 'uninitialized' gcc warning
1732 if (Time::now() - lastInfoTime >= 1000)
1734 lastInfoTime = Time::now();
1743 Threads.mutex.lock();
1745 nodes = RootPosition.nodes_searched();
1747 // Loop across all split points and sum accumulated SplitPoint nodes plus
1748 // all the currently active slaves positions.
1749 for (size_t i = 0; i < Threads.size(); i++)
1750 for (int j = 0; j < Threads[i].splitPointsCnt; j++)
1752 SplitPoint& sp = Threads[i].splitPoints[j];
1757 Bitboard sm = sp.slavesMask;
1760 Position* pos = sp.activePositions[pop_lsb(&sm)];
1761 nodes += pos ? pos->nodes_searched() : 0;
1767 Threads.mutex.unlock();
1770 Time::point elapsed = Time::now() - SearchTime;
1771 bool stillAtFirstMove = Signals.firstRootMove
1772 && !Signals.failedLowAtRoot
1773 && elapsed > TimeMgr.available_time();
1775 bool noMoreTime = elapsed > TimeMgr.maximum_time() - 2 * TimerResolution
1776 || stillAtFirstMove;
1778 if ( (Limits.use_time_management() && noMoreTime)
1779 || (Limits.movetime && elapsed >= Limits.movetime)
1780 || (Limits.nodes && nodes >= Limits.nodes))
1781 Signals.stop = true;