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 // Different node types, used as template parameter
59 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
61 // Lookup table to check if a Piece is a slider and its access function
62 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
63 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
65 // Dynamic razoring margin based on depth
66 inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
68 // Futility lookup tables (initialized at startup) and their access functions
69 Value FutilityMargins[16][64]; // [depth][moveNumber]
70 int FutilityMoveCounts[32]; // [depth]
72 inline Value futility_margin(Depth d, int mn) {
74 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
78 inline int futility_move_count(Depth d) {
80 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
83 // Reduction lookup tables (initialized at startup) and their access function
84 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
86 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
88 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
91 // Easy move margin. An easy move candidate must be at least this much better
92 // than the second best move.
93 const Value EasyMoveMargin = Value(0x150);
95 // This is the minimum interval in msec between two check_time() calls
96 const int TimerResolution = 5;
99 size_t MultiPV, UCIMultiPV, PVIdx;
103 bool SkillLevelEnabled, Chess960;
107 template <NodeType NT>
108 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
110 template <NodeType NT>
111 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
113 void id_loop(Position& pos);
114 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
115 bool connected_moves(const Position& pos, Move m1, Move m2);
116 Value value_to_tt(Value v, int ply);
117 Value value_from_tt(Value v, int ply);
118 bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
119 bool connected_threat(const Position& pos, Move m, Move threat);
120 Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
121 Move do_skill_level();
122 string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
124 // is_dangerous() checks whether a move belongs to some classes of known
125 // 'dangerous' moves so that we avoid to prune it.
126 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
129 if (type_of(m) == CASTLE)
133 if ( type_of(pos.piece_moved(m)) == PAWN
134 && pos.pawn_is_passed(pos.side_to_move(), to_sq(m)))
137 // Entering a pawn endgame?
138 if ( captureOrPromotion
139 && type_of(pos.piece_on(to_sq(m))) != PAWN
140 && type_of(m) == NORMAL
141 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
142 - PieceValue[Mg][pos.piece_on(to_sq(m))] == VALUE_ZERO))
151 /// Search::init() is called during startup to initialize various lookup tables
153 void Search::init() {
155 int d; // depth (ONE_PLY == 2)
156 int hd; // half depth (ONE_PLY == 1)
159 // Init reductions array
160 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
162 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
163 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
164 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
165 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
168 // Init futility margins array
169 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
170 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
172 // Init futility move count array
173 for (d = 0; d < 32; d++)
174 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
178 /// Search::perft() is our utility to verify move generation. All the leaf nodes
179 /// up to the given depth are generated and counted and the sum returned.
181 size_t Search::perft(Position& pos, Depth depth) {
183 // At the last ply just return the number of legal moves (leaf nodes)
184 if (depth == ONE_PLY)
185 return MoveList<LEGAL>(pos).size();
191 for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
193 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
194 cnt += perft(pos, depth - ONE_PLY);
195 pos.undo_move(ml.move());
202 /// Search::think() is the external interface to Stockfish's search, and is
203 /// called by the main thread when the program receives the UCI 'go' command. It
204 /// searches from RootPosition and at the end prints the "bestmove" to output.
206 void Search::think() {
208 static PolyglotBook book; // Defined static to initialize the PRNG only once
210 Position& pos = RootPosition;
211 Chess960 = pos.is_chess960();
212 Eval::RootColor = pos.side_to_move();
213 TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
217 if (RootMoves.empty())
219 sync_cout << "info depth 0 score "
220 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << sync_endl;
222 RootMoves.push_back(MOVE_NONE);
226 if (Options["OwnBook"] && !Limits.infinite)
228 Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
230 if (bookMove && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
232 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
237 UCIMultiPV = Options["MultiPV"];
238 SkillLevel = Options["Skill Level"];
240 // Do we have to play with skill handicap? In this case enable MultiPV that
241 // we will use behind the scenes to retrieve a set of possible moves.
242 SkillLevelEnabled = (SkillLevel < 20);
243 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
245 if (Options["Use Search Log"])
247 Log log(Options["Search Log Filename"]);
248 log << "\nSearching: " << pos.to_fen()
249 << "\ninfinite: " << Limits.infinite
250 << " ponder: " << Limits.ponder
251 << " time: " << Limits.time[pos.side_to_move()]
252 << " increment: " << Limits.inc[pos.side_to_move()]
253 << " moves to go: " << Limits.movestogo
259 // Set best timer interval to avoid lagging under time pressure. Timer is
260 // used to check for remaining available thinking time.
261 if (Limits.use_time_management())
262 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
263 else if (Limits.nodes)
264 Threads.set_timer(2 * TimerResolution);
266 Threads.set_timer(100);
268 // We're ready to start searching. Call the iterative deepening loop function
271 Threads.set_timer(0); // Stop timer
274 if (Options["Use Search Log"])
276 Time::point elapsed = Time::now() - SearchTime + 1;
278 Log log(Options["Search Log Filename"]);
279 log << "Nodes: " << pos.nodes_searched()
280 << "\nNodes/second: " << pos.nodes_searched() * 1000 / elapsed
281 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
284 pos.do_move(RootMoves[0].pv[0], st);
285 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << std::endl;
286 pos.undo_move(RootMoves[0].pv[0]);
291 // When we reach max depth we arrive here even without Signals.stop is raised,
292 // but if we are pondering or in infinite search, we shouldn't print the best
293 // move before we are told to do so.
294 if (!Signals.stop && (Limits.ponder || Limits.infinite))
295 pos.this_thread()->wait_for_stop_or_ponderhit();
297 // Best move could be MOVE_NONE when searching on a stalemate position
298 sync_cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
299 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << sync_endl;
305 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
306 // with increasing depth until the allocated thinking time has been consumed,
307 // user stops the search, or the maximum search depth is reached.
309 void id_loop(Position& pos) {
311 Stack ss[MAX_PLY_PLUS_2];
312 int depth, prevBestMoveChanges;
313 Value bestValue, alpha, beta, delta;
314 bool bestMoveNeverChanged = true;
315 Move skillBest = MOVE_NONE;
317 memset(ss, 0, 4 * sizeof(Stack));
318 depth = BestMoveChanges = 0;
319 bestValue = delta = -VALUE_INFINITE;
320 ss->currentMove = MOVE_NULL; // Hack to skip update gains
322 // Iterative deepening loop until requested to stop or target depth reached
323 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
325 // Save last iteration's scores before first PV line is searched and all
326 // the move scores but the (new) PV are set to -VALUE_INFINITE.
327 for (size_t i = 0; i < RootMoves.size(); i++)
328 RootMoves[i].prevScore = RootMoves[i].score;
330 prevBestMoveChanges = BestMoveChanges;
333 // MultiPV loop. We perform a full root search for each PV line
334 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
336 // Set aspiration window default width
337 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
340 alpha = RootMoves[PVIdx].prevScore - delta;
341 beta = RootMoves[PVIdx].prevScore + delta;
345 alpha = -VALUE_INFINITE;
346 beta = VALUE_INFINITE;
349 // Start with a small aspiration window and, in case of fail high/low,
350 // research with bigger window until not failing high/low anymore.
353 // Search starts from ss+1 to allow referencing (ss-1). This is
354 // needed by update gains and ss copy when splitting at Root.
355 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
357 // Bring to front the best move. It is critical that sorting is
358 // done with a stable algorithm because all the values but the first
359 // and eventually the new best one are set to -VALUE_INFINITE and
360 // we want to keep the same order for all the moves but the new
361 // PV that goes to the front. Note that in case of MultiPV search
362 // the already searched PV lines are preserved.
363 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
365 // In case we have found an exact score and we are going to leave
366 // the fail high/low loop then reorder the PV moves, otherwise
367 // leave the last PV move in its position so to be searched again.
368 // Of course this is needed only in MultiPV search.
369 if (PVIdx && bestValue > alpha && bestValue < beta)
370 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
372 // Write PV back to transposition table in case the relevant
373 // entries have been overwritten during the search.
374 for (size_t i = 0; i <= PVIdx; i++)
375 RootMoves[i].insert_pv_in_tt(pos);
377 // If search has been stopped exit the aspiration window loop.
378 // Sorting and writing PV back to TT is safe becuase RootMoves
379 // is still valid, although refers to previous iteration.
383 // Send full PV info to GUI if we are going to leave the loop or
384 // if we have a fail high/low and we are deep in the search.
385 if ((bestValue > alpha && bestValue < beta) || Time::now() - SearchTime > 2000)
386 sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
388 // In case of failing high/low increase aspiration window and
389 // research, otherwise exit the fail high/low loop.
390 if (bestValue >= beta)
395 else if (bestValue <= alpha)
397 Signals.failedLowAtRoot = true;
398 Signals.stopOnPonderhit = false;
406 // Search with full window in case we have a win/mate score
407 if (abs(bestValue) >= VALUE_KNOWN_WIN)
409 alpha = -VALUE_INFINITE;
410 beta = VALUE_INFINITE;
413 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
417 // Skills: Do we need to pick now the best move ?
418 if (SkillLevelEnabled && depth == 1 + SkillLevel)
419 skillBest = do_skill_level();
421 if (!Signals.stop && Options["Use Search Log"])
423 Log log(Options["Search Log Filename"]);
424 log << pretty_pv(pos, depth, bestValue, Time::now() - SearchTime, &RootMoves[0].pv[0])
428 // Filter out startup noise when monitoring best move stability
429 if (depth > 2 && BestMoveChanges)
430 bestMoveNeverChanged = false;
432 // Do we have time for the next iteration? Can we stop searching now?
433 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
435 bool stop = false; // Local variable, not the volatile Signals.stop
437 // Take in account some extra time if the best move has changed
438 if (depth > 4 && depth < 50)
439 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
441 // Stop search if most of available time is already consumed. We
442 // probably don't have enough time to search the first move at the
443 // next iteration anyway.
444 if (Time::now() - SearchTime > (TimeMgr.available_time() * 62) / 100)
447 // Stop search early if one move seems to be much better than others
450 && ( (bestMoveNeverChanged && pos.captured_piece_type())
451 || Time::now() - SearchTime > (TimeMgr.available_time() * 40) / 100))
453 Value rBeta = bestValue - EasyMoveMargin;
454 (ss+1)->excludedMove = RootMoves[0].pv[0];
455 (ss+1)->skipNullMove = true;
456 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
457 (ss+1)->skipNullMove = false;
458 (ss+1)->excludedMove = MOVE_NONE;
466 // If we are allowed to ponder do not stop the search now but
467 // keep pondering until GUI sends "ponderhit" or "stop".
469 Signals.stopOnPonderhit = true;
476 // When using skills swap best PV line with the sub-optimal one
477 if (SkillLevelEnabled)
479 if (skillBest == MOVE_NONE) // Still unassigned ?
480 skillBest = do_skill_level();
482 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), skillBest));
487 // search<>() is the main search function for both PV and non-PV nodes and for
488 // normal and SplitPoint nodes. When called just after a split point the search
489 // is simpler because we have already probed the hash table, done a null move
490 // search, and searched the first move before splitting, we don't have to repeat
491 // all this work again. We also don't need to store anything to the hash table
492 // here: This is taken care of after we return from the split point.
494 template <NodeType NT>
495 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
497 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
498 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
499 const bool RootNode = (NT == Root || NT == SplitPointRoot);
501 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
502 assert(PvNode || (alpha == beta - 1));
503 assert(depth > DEPTH_ZERO);
505 Move movesSearched[64];
510 Move ttMove, move, excludedMove, bestMove, threatMove;
512 Value bestValue, value, oldAlpha, ttValue;
513 Value refinedValue, nullValue, futilityValue;
514 bool pvMove, inCheck, singularExtensionNode, givesCheck;
515 bool captureOrPromotion, dangerous, doFullDepthSearch;
516 int moveCount, playedMoveCount;
518 // Step 1. Initialize node
519 Thread* thisThread = pos.this_thread();
520 moveCount = playedMoveCount = 0;
522 inCheck = pos.in_check();
527 bestMove = sp->bestMove;
528 threatMove = sp->threatMove;
529 bestValue = sp->bestValue;
531 ttMove = excludedMove = MOVE_NONE;
532 ttValue = VALUE_NONE;
534 assert(sp->bestValue > -VALUE_INFINITE && sp->moveCount > 0);
536 goto split_point_start;
539 bestValue = -VALUE_INFINITE;
540 ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
541 ss->ply = (ss-1)->ply + 1;
542 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
543 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
545 // Used to send selDepth info to GUI
546 if (PvNode && thisThread->maxPly < ss->ply)
547 thisThread->maxPly = ss->ply;
551 // Step 2. Check for aborted search and immediate draw
552 if (Signals.stop || pos.is_draw<false>() || ss->ply > MAX_PLY)
555 // Step 3. Mate distance pruning. Even if we mate at the next move our score
556 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
557 // a shorter mate was found upward in the tree then there is no need to search
558 // further, we will never beat current alpha. Same logic but with reversed signs
559 // applies also in the opposite condition of being mated instead of giving mate,
560 // in this case return a fail-high score.
561 alpha = std::max(mated_in(ss->ply), alpha);
562 beta = std::min(mate_in(ss->ply+1), beta);
567 // Step 4. Transposition table lookup
568 // We don't want the score of a partial search to overwrite a previous full search
569 // TT value, so we use a different position key in case of an excluded move.
570 excludedMove = ss->excludedMove;
571 posKey = excludedMove ? pos.exclusion_key() : pos.key();
572 tte = TT.probe(posKey);
573 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
574 ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
576 // At PV nodes we check for exact scores, while at non-PV nodes we check for
577 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
578 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
579 // we should also update RootMoveList to avoid bogus output.
580 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
581 : can_return_tt(tte, depth, ttValue, beta)))
584 ss->currentMove = ttMove; // Can be MOVE_NONE
588 && !pos.is_capture_or_promotion(ttMove)
589 && ttMove != ss->killers[0])
591 ss->killers[1] = ss->killers[0];
592 ss->killers[0] = ttMove;
597 // Step 5. Evaluate the position statically and update parent's gain statistics
599 ss->eval = ss->evalMargin = refinedValue = VALUE_NONE;
602 assert(tte->static_value() != VALUE_NONE);
604 ss->eval = tte->static_value();
605 ss->evalMargin = tte->static_value_margin();
606 refinedValue = refine_eval(tte, ttValue, ss->eval);
610 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
611 TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
614 // Update gain for the parent non-capture move given the static position
615 // evaluation before and after the move.
616 if ( (move = (ss-1)->currentMove) != MOVE_NULL
617 && (ss-1)->eval != VALUE_NONE
618 && ss->eval != VALUE_NONE
619 && !pos.captured_piece_type()
620 && type_of(move) == NORMAL)
622 Square to = to_sq(move);
623 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
626 // Step 6. Razoring (is omitted in PV nodes)
628 && depth < 4 * ONE_PLY
630 && refinedValue + razor_margin(depth) < beta
631 && ttMove == MOVE_NONE
632 && abs(beta) < VALUE_MATE_IN_MAX_PLY
633 && !pos.pawn_on_7th(pos.side_to_move()))
635 Value rbeta = beta - razor_margin(depth);
636 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
638 // Logically we should return (v + razor_margin(depth)), but
639 // surprisingly this did slightly weaker in tests.
643 // Step 7. Static null move pruning (is omitted in PV nodes)
644 // We're betting that the opponent doesn't have a move that will reduce
645 // the score by more than futility_margin(depth) if we do a null move.
648 && depth < 4 * ONE_PLY
650 && refinedValue - futility_margin(depth, 0) >= beta
651 && abs(beta) < VALUE_MATE_IN_MAX_PLY
652 && pos.non_pawn_material(pos.side_to_move()))
653 return refinedValue - futility_margin(depth, 0);
655 // Step 8. Null move search with verification search (is omitted in PV nodes)
660 && refinedValue >= beta
661 && abs(beta) < VALUE_MATE_IN_MAX_PLY
662 && pos.non_pawn_material(pos.side_to_move()))
664 ss->currentMove = MOVE_NULL;
666 // Null move dynamic reduction based on depth
667 Depth R = 3 * ONE_PLY + depth / 4;
669 // Null move dynamic reduction based on value
670 if (refinedValue - PawnValueMg > beta)
673 pos.do_null_move<true>(st);
674 (ss+1)->skipNullMove = true;
675 nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
676 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
677 (ss+1)->skipNullMove = false;
678 pos.do_null_move<false>(st);
680 if (nullValue >= beta)
682 // Do not return unproven mate scores
683 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
686 if (depth < 6 * ONE_PLY)
689 // Do verification search at high depths
690 ss->skipNullMove = true;
691 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
692 ss->skipNullMove = false;
699 // The null move failed low, which means that we may be faced with
700 // some kind of threat. If the previous move was reduced, check if
701 // the move that refuted the null move was somehow connected to the
702 // move which was reduced. If a connection is found, return a fail
703 // low score (which will cause the reduced move to fail high in the
704 // parent node, which will trigger a re-search with full depth).
705 threatMove = (ss+1)->currentMove;
707 if ( depth < 5 * ONE_PLY
709 && threatMove != MOVE_NONE
710 && connected_moves(pos, (ss-1)->currentMove, threatMove))
715 // Step 9. ProbCut (is omitted in PV nodes)
716 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
717 // and a reduced search returns a value much above beta, we can (almost) safely
718 // prune the previous move.
720 && depth >= 5 * ONE_PLY
723 && excludedMove == MOVE_NONE
724 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
726 Value rbeta = beta + 200;
727 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
729 assert(rdepth >= ONE_PLY);
730 assert((ss-1)->currentMove != MOVE_NONE);
731 assert((ss-1)->currentMove != MOVE_NULL);
733 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
736 while ((move = mp.next_move<false>()) != MOVE_NONE)
737 if (pos.pl_move_is_legal(move, ci.pinned))
739 ss->currentMove = move;
740 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
741 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
748 // Step 10. Internal iterative deepening
749 if ( depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
750 && ttMove == MOVE_NONE
751 && (PvNode || (!inCheck && ss->eval + Value(256) >= beta)))
753 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
755 ss->skipNullMove = true;
756 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
757 ss->skipNullMove = false;
759 tte = TT.probe(posKey);
760 ttMove = tte ? tte->move() : MOVE_NONE;
763 split_point_start: // At split points actual search starts from here
765 MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
767 value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
768 singularExtensionNode = !RootNode
770 && depth >= (PvNode ? 6 * ONE_PLY : 8 * ONE_PLY)
771 && ttMove != MOVE_NONE
772 && !excludedMove // Recursive singular search is not allowed
773 && (tte->type() & BOUND_LOWER)
774 && tte->depth() >= depth - 3 * ONE_PLY;
776 // Step 11. Loop through moves
777 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
778 while ( bestValue < beta
779 && (move = mp.next_move<SpNode>()) != MOVE_NONE
780 && !thisThread->cutoff_occurred()
785 if (move == excludedMove)
788 // At root obey the "searchmoves" option and skip moves not listed in Root
789 // Move List, as a consequence any illegal move is also skipped. In MultiPV
790 // mode we also skip PV moves which have been already searched.
791 if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
796 // Shared counter cannot be decremented later if move turns out to be illegal
797 if (!pos.pl_move_is_legal(move, ci.pinned))
800 moveCount = ++sp->moveCount;
808 Signals.firstRootMove = (moveCount == 1);
810 if (thisThread == Threads.main_thread() && Time::now() - SearchTime > 2000)
811 sync_cout << "info depth " << depth / ONE_PLY
812 << " currmove " << move_to_uci(move, Chess960)
813 << " currmovenumber " << moveCount + PVIdx << sync_endl;
816 captureOrPromotion = pos.is_capture_or_promotion(move);
817 givesCheck = pos.move_gives_check(move, ci);
818 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
821 // Step 12. Extend checks and, in PV nodes, also dangerous moves
822 if (PvNode && dangerous)
825 else if (givesCheck && pos.see_sign(move) >= 0)
828 // Singular extension search. If all moves but one fail low on a search of
829 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
830 // is singular and should be extended. To verify this we do a reduced search
831 // on all the other moves but the ttMove, if result is lower than ttValue minus
832 // a margin then we extend ttMove.
833 if ( singularExtensionNode
836 && pos.pl_move_is_legal(move, ci.pinned)
837 && abs(ttValue) < VALUE_KNOWN_WIN)
839 Value rBeta = ttValue - int(depth);
840 ss->excludedMove = move;
841 ss->skipNullMove = true;
842 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
843 ss->skipNullMove = false;
844 ss->excludedMove = MOVE_NONE;
847 ext = rBeta >= beta ? ONE_PLY + ONE_PLY / 2 : ONE_PLY;
850 // Update current move (this must be done after singular extension search)
851 newDepth = depth - ONE_PLY + ext;
853 // Step 13. Futility pruning (is omitted in PV nodes)
855 && !captureOrPromotion
859 && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
861 // Move count based pruning
862 if ( moveCount >= futility_move_count(depth)
863 && (!threatMove || !connected_threat(pos, move, threatMove)))
871 // Value based pruning
872 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
873 // but fixing this made program slightly weaker.
874 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
875 futilityValue = ss->eval + ss->evalMargin + futility_margin(predictedDepth, moveCount)
876 + H.gain(pos.piece_moved(move), to_sq(move));
878 if (futilityValue < beta)
886 // Prune moves with negative SEE at low depths
887 if ( predictedDepth < 2 * ONE_PLY
888 && pos.see_sign(move) < 0)
897 // Check for legality only before to do the move
898 if (!pos.pl_move_is_legal(move, ci.pinned))
904 pvMove = PvNode ? moveCount == 1 : false;
905 ss->currentMove = move;
906 if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
907 movesSearched[playedMoveCount++] = move;
909 // Step 14. Make the move
910 pos.do_move(move, st, ci, givesCheck);
912 // Step 15. Reduced depth search (LMR). If the move fails high will be
913 // re-searched at full depth.
914 if ( depth > 3 * ONE_PLY
916 && !captureOrPromotion
918 && ss->killers[0] != move
919 && ss->killers[1] != move)
921 ss->reduction = reduction<PvNode>(depth, moveCount);
922 Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
923 alpha = SpNode ? sp->alpha : alpha;
925 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
927 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
928 ss->reduction = DEPTH_ZERO;
931 doFullDepthSearch = !pvMove;
933 // Step 16. Full depth search, when LMR is skipped or fails high
934 if (doFullDepthSearch)
936 alpha = SpNode ? sp->alpha : alpha;
937 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
938 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
941 // Only for PV nodes do a full PV search on the first move or after a fail
942 // high, in the latter case search only if value < beta, otherwise let the
943 // parent node to fail low with value <= alpha and to try another move.
944 if (PvNode && (pvMove || (value > alpha && (RootNode || value < beta))))
945 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
946 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
948 // Step 17. Undo move
951 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
953 // Step 18. Check for new best move
957 bestValue = sp->bestValue;
961 // Finished searching the move. If Signals.stop is true, the search
962 // was aborted because the user interrupted the search or because we
963 // ran out of time. In this case, the return value of the search cannot
964 // be trusted, and we don't update the best move and/or PV.
965 if (RootNode && !Signals.stop)
967 RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
969 // PV move or new best move ?
970 if (pvMove || value > alpha)
973 rm.extract_pv_from_tt(pos);
975 // We record how often the best move has been changed in each
976 // iteration. This information is used for time management: When
977 // the best move changes frequently, we allocate some more time.
978 if (!pvMove && MultiPV == 1)
982 // All other moves but the PV are set to the lowest value, this
983 // is not a problem when sorting becuase sort is stable and move
984 // position in the list is preserved, just the PV is pushed up.
985 rm.score = -VALUE_INFINITE;
988 if (value > bestValue)
995 && value < beta) // We want always alpha < beta
997 alpha = bestValue; // Update alpha here!
1000 if (SpNode && !thisThread->cutoff_occurred())
1002 sp->bestValue = bestValue;
1003 sp->bestMove = bestMove;
1006 if (bestValue >= beta)
1011 // Step 19. Check for split
1013 && depth >= Threads.min_split_depth()
1015 && Threads.available_slave_exists(thisThread)
1017 && !thisThread->cutoff_occurred())
1018 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1019 depth, threatMove, moveCount, mp, NT);
1022 // Step 20. Check for mate and stalemate
1023 // All legal moves have been searched and if there are no legal moves, it
1024 // must be mate or stalemate. Note that we can have a false positive in
1025 // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1026 // harmless because return value is discarded anyhow in the parent nodes.
1027 // If we are in a singular extension search then return a fail low score.
1028 // A split node has at least one move, the one tried before to be splitted.
1029 if (!SpNode && !moveCount)
1030 return excludedMove ? alpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1032 // If we have pruned all the moves without searching return a fail-low score
1033 if (bestValue == -VALUE_INFINITE)
1035 assert(!playedMoveCount);
1040 // Step 21. Update tables
1041 // Update transposition table entry, killers and history
1042 if (!SpNode && !Signals.stop && !thisThread->cutoff_occurred())
1044 Move ttm = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1045 Bound bt = bestValue <= oldAlpha ? BOUND_UPPER
1046 : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1048 TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, ttm, ss->eval, ss->evalMargin);
1050 // Update killers and history for non capture cut-off moves
1051 if ( bestValue >= beta
1052 && !pos.is_capture_or_promotion(bestMove)
1055 if (bestMove != ss->killers[0])
1057 ss->killers[1] = ss->killers[0];
1058 ss->killers[0] = bestMove;
1061 // Increase history value of the cut-off move
1062 Value bonus = Value(int(depth) * int(depth));
1063 H.add(pos.piece_moved(bestMove), to_sq(bestMove), bonus);
1065 // Decrease history of all the other played non-capture moves
1066 for (int i = 0; i < playedMoveCount - 1; i++)
1068 Move m = movesSearched[i];
1069 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1074 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1080 // qsearch() is the quiescence search function, which is called by the main
1081 // search function when the remaining depth is zero (or, to be more precise,
1082 // less than ONE_PLY).
1084 template <NodeType NT>
1085 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1087 const bool PvNode = (NT == PV);
1089 assert(NT == PV || NT == NonPV);
1090 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1091 assert((alpha == beta - 1) || PvNode);
1092 assert(depth <= DEPTH_ZERO);
1095 Move ttMove, move, bestMove;
1096 Value ttValue, bestValue, value, evalMargin, futilityValue, futilityBase;
1097 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1101 Value oldAlpha = alpha;
1103 ss->currentMove = bestMove = MOVE_NONE;
1104 ss->ply = (ss-1)->ply + 1;
1106 // Check for an instant draw or maximum ply reached
1107 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1110 // Decide whether or not to include checks, this fixes also the type of
1111 // TT entry depth that we are going to use. Note that in qsearch we use
1112 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1113 inCheck = pos.in_check();
1114 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1116 // Transposition table lookup. At PV nodes, we don't use the TT for
1117 // pruning, but only for move ordering.
1118 tte = TT.probe(pos.key());
1119 ttMove = (tte ? tte->move() : MOVE_NONE);
1120 ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_ZERO;
1122 if (!PvNode && tte && can_return_tt(tte, ttDepth, ttValue, beta))
1124 ss->currentMove = ttMove; // Can be MOVE_NONE
1128 // Evaluate the position statically
1131 bestValue = futilityBase = -VALUE_INFINITE;
1132 ss->eval = evalMargin = VALUE_NONE;
1133 enoughMaterial = false;
1139 assert(tte->static_value() != VALUE_NONE);
1141 evalMargin = tte->static_value_margin();
1142 ss->eval = bestValue = tte->static_value();
1145 ss->eval = bestValue = evaluate(pos, evalMargin);
1147 // Stand pat. Return immediately if static value is at least beta
1148 if (bestValue >= beta)
1151 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1156 if (PvNode && bestValue > alpha)
1159 futilityBase = ss->eval + evalMargin + Value(128);
1160 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1163 // Initialize a MovePicker object for the current position, and prepare
1164 // to search the moves. Because the depth is <= 0 here, only captures,
1165 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1167 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1170 // Loop through the moves until no moves remain or a beta cutoff occurs
1171 while ( bestValue < beta
1172 && (move = mp.next_move<false>()) != MOVE_NONE)
1174 assert(is_ok(move));
1176 givesCheck = pos.move_gives_check(move, ci);
1184 && type_of(move) != PROMOTION
1185 && !pos.is_passed_pawn_push(move))
1187 futilityValue = futilityBase
1188 + PieceValue[Eg][pos.piece_on(to_sq(move))]
1189 + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1191 if (futilityValue < beta)
1193 if (futilityValue > bestValue)
1194 bestValue = futilityValue;
1199 // Prune moves with negative or equal SEE
1200 if ( futilityBase < beta
1201 && depth < DEPTH_ZERO
1202 && pos.see(move) <= 0)
1206 // Detect non-capture evasions that are candidate to be pruned
1207 evasionPrunable = !PvNode
1209 && bestValue > VALUE_MATED_IN_MAX_PLY
1210 && !pos.is_capture(move)
1211 && !pos.can_castle(pos.side_to_move());
1213 // Don't search moves with negative SEE values
1215 && (!inCheck || evasionPrunable)
1217 && type_of(move) != PROMOTION
1218 && pos.see_sign(move) < 0)
1221 // Don't search useless checks
1226 && !pos.is_capture_or_promotion(move)
1227 && ss->eval + PawnValueMg / 4 < beta
1228 && !check_is_dangerous(pos, move, futilityBase, beta))
1231 // Check for legality only before to do the move
1232 if (!pos.pl_move_is_legal(move, ci.pinned))
1235 ss->currentMove = move;
1237 // Make and search the move
1238 pos.do_move(move, st, ci, givesCheck);
1239 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1240 pos.undo_move(move);
1242 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1245 if (value > bestValue)
1252 && value < beta) // We want always alpha < beta
1257 // All legal moves have been searched. A special case: If we're in check
1258 // and no legal moves were found, it is checkmate.
1259 if (inCheck && bestValue == -VALUE_INFINITE)
1260 return mated_in(ss->ply); // Plies to mate from the root
1262 // Update transposition table
1263 move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1264 bt = bestValue <= oldAlpha ? BOUND_UPPER
1265 : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1267 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1269 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1275 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1276 // bestValue is updated only when returning false because in that case move
1279 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1281 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1282 Square from, to, ksq;
1286 from = from_sq(move);
1288 them = ~pos.side_to_move();
1289 ksq = pos.king_square(them);
1290 kingAtt = pos.attacks_from<KING>(ksq);
1291 pc = pos.piece_moved(move);
1293 occ = pos.pieces() ^ from ^ ksq;
1294 oldAtt = pos.attacks_from(pc, from, occ);
1295 newAtt = pos.attacks_from(pc, to, occ);
1297 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1298 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1300 if (!more_than_one(b))
1303 // Rule 2. Queen contact check is very dangerous
1304 if (type_of(pc) == QUEEN && (kingAtt & to))
1307 // Rule 3. Creating new double threats with checks
1308 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1311 // Note that here we generate illegal "double move"!
1312 if (futilityBase + PieceValue[Eg][pos.piece_on(pop_lsb(&b))] >= beta)
1320 // connected_moves() tests whether two moves are 'connected' in the sense
1321 // that the first move somehow made the second move possible (for instance
1322 // if the moving piece is the same in both moves). The first move is assumed
1323 // to be the move that was made to reach the current position, while the
1324 // second move is assumed to be a move from the current position.
1326 bool connected_moves(const Position& pos, Move m1, Move m2) {
1328 Square f1, t1, f2, t2;
1335 // Case 1: The moving piece is the same in both moves
1341 // Case 2: The destination square for m2 was vacated by m1
1347 // Case 3: Moving through the vacated square
1348 p2 = pos.piece_on(f2);
1349 if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1352 // Case 4: The destination square for m2 is defended by the moving piece in m1
1353 p1 = pos.piece_on(t1);
1354 if (pos.attacks_from(p1, t1) & t2)
1357 // Case 5: Discovered check, checking piece is the piece moved in m1
1358 ksq = pos.king_square(pos.side_to_move());
1359 if ( piece_is_slider(p1)
1360 && (between_bb(t1, ksq) & f2)
1361 && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1368 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1369 // "plies to mate from the current position". Non-mate scores are unchanged.
1370 // The function is called before storing a value to the transposition table.
1372 Value value_to_tt(Value v, int ply) {
1374 if (v >= VALUE_MATE_IN_MAX_PLY)
1377 if (v <= VALUE_MATED_IN_MAX_PLY)
1384 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1385 // from the transposition table (where refers to the plies to mate/be mated
1386 // from current position) to "plies to mate/be mated from the root".
1388 Value value_from_tt(Value v, int ply) {
1390 if (v >= VALUE_MATE_IN_MAX_PLY)
1393 if (v <= VALUE_MATED_IN_MAX_PLY)
1400 // connected_threat() tests whether it is safe to forward prune a move or if
1401 // is somehow connected to the threat move returned by null search.
1403 bool connected_threat(const Position& pos, Move m, Move threat) {
1406 assert(is_ok(threat));
1407 assert(!pos.is_capture_or_promotion(m));
1408 assert(!pos.is_passed_pawn_push(m));
1410 Square mfrom, mto, tfrom, tto;
1414 tfrom = from_sq(threat);
1415 tto = to_sq(threat);
1417 // Case 1: Don't prune moves which move the threatened piece
1421 // Case 2: If the threatened piece has value less than or equal to the
1422 // value of the threatening piece, don't prune moves which defend it.
1423 if ( pos.is_capture(threat)
1424 && ( PieceValue[Mg][pos.piece_on(tfrom)] >= PieceValue[Mg][pos.piece_on(tto)]
1425 || type_of(pos.piece_on(tfrom)) == KING)
1426 && pos.move_attacks_square(m, tto))
1429 // Case 3: If the moving piece in the threatened move is a slider, don't
1430 // prune safe moves which block its ray.
1431 if ( piece_is_slider(pos.piece_on(tfrom))
1432 && (between_bb(tfrom, tto) & mto)
1433 && pos.see_sign(m) >= 0)
1440 // can_return_tt() returns true if a transposition table score can be used to
1441 // cut-off at a given point in search.
1443 bool can_return_tt(const TTEntry* tte, Depth depth, Value v, Value beta) {
1445 return ( tte->depth() >= depth
1446 || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1447 || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1449 && ( ((tte->type() & BOUND_LOWER) && v >= beta)
1450 || ((tte->type() & BOUND_UPPER) && v < beta));
1454 // refine_eval() returns the transposition table score if possible, otherwise
1455 // falls back on static position evaluation.
1457 Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1461 if ( ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1462 || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1469 // When playing with strength handicap choose best move among the MultiPV set
1470 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1472 Move do_skill_level() {
1474 assert(MultiPV > 1);
1478 // PRNG sequence should be not deterministic
1479 for (int i = Time::now() % 50; i > 0; i--)
1480 rk.rand<unsigned>();
1482 // RootMoves are already sorted by score in descending order
1483 size_t size = std::min(MultiPV, RootMoves.size());
1484 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1485 int weakness = 120 - 2 * SkillLevel;
1486 int max_s = -VALUE_INFINITE;
1487 Move best = MOVE_NONE;
1489 // Choose best move. For each move score we add two terms both dependent on
1490 // weakness, one deterministic and bigger for weaker moves, and one random,
1491 // then we choose the move with the resulting highest score.
1492 for (size_t i = 0; i < size; i++)
1494 int s = RootMoves[i].score;
1496 // Don't allow crazy blunders even at very low skills
1497 if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1500 // This is our magic formula
1501 s += ( weakness * int(RootMoves[0].score - s)
1502 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1507 best = RootMoves[i].pv[0];
1514 // uci_pv() formats PV information according to UCI protocol. UCI requires
1515 // to send all the PV lines also if are still to be searched and so refer to
1516 // the previous search score.
1518 string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1520 std::stringstream s;
1521 Time::point elaspsed = Time::now() - SearchTime + 1;
1524 for (size_t i = 0; i < Threads.size(); i++)
1525 if (Threads[i].maxPly > selDepth)
1526 selDepth = Threads[i].maxPly;
1528 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1530 bool updated = (i <= PVIdx);
1532 if (depth == 1 && !updated)
1535 int d = (updated ? depth : depth - 1);
1536 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1538 if (s.rdbuf()->in_avail())
1541 s << "info depth " << d
1542 << " seldepth " << selDepth
1543 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1544 << " nodes " << pos.nodes_searched()
1545 << " nps " << pos.nodes_searched() * 1000 / elaspsed
1546 << " time " << elaspsed
1547 << " multipv " << i + 1
1550 for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1551 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1560 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1561 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1562 /// allow to always have a ponder move even when we fail high at root, and a
1563 /// long PV to print that is important for position analysis.
1565 void RootMove::extract_pv_from_tt(Position& pos) {
1567 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1572 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1576 pos.do_move(m, *st++);
1578 while ( (tte = TT.probe(pos.key())) != NULL
1579 && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1580 && pos.is_pseudo_legal(m)
1581 && pos.pl_move_is_legal(m, pos.pinned_pieces())
1583 && (!pos.is_draw<false>() || ply < 2))
1586 pos.do_move(m, *st++);
1589 pv.push_back(MOVE_NONE);
1591 do pos.undo_move(pv[--ply]); while (ply);
1595 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1596 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1597 /// first, even if the old TT entries have been overwritten.
1599 void RootMove::insert_pv_in_tt(Position& pos) {
1601 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1604 Value v, m = VALUE_NONE;
1607 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1613 // Don't overwrite existing correct entries
1614 if (!tte || tte->move() != pv[ply])
1616 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1617 TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1619 pos.do_move(pv[ply], *st++);
1621 } while (pv[++ply] != MOVE_NONE);
1623 do pos.undo_move(pv[--ply]); while (ply);
1627 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1629 void Thread::idle_loop() {
1631 // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1632 // object for which the thread is the master.
1633 const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1635 assert(!sp_master || (sp_master->master == this && is_searching));
1637 // If this thread is the master of a split point and all slaves have
1638 // finished their work at this split point, return from the idle loop.
1639 while (!sp_master || sp_master->slavesMask)
1641 // If we are not searching, wait for a condition to be signaled
1642 // instead of wasting CPU time polling for work.
1645 || (!is_searching && Threads.use_sleeping_threads()))
1653 // Grab the lock to avoid races with Thread::wake_up()
1656 // If we are master and all slaves have finished don't go to sleep
1657 if (sp_master && !sp_master->slavesMask)
1663 // Do sleep after retesting sleep conditions under lock protection, in
1664 // particular we need to avoid a deadlock in case a master thread has,
1665 // in the meanwhile, allocated us and sent the wake_up() call before we
1666 // had the chance to grab the lock.
1667 if (do_sleep || !is_searching)
1668 sleepCondition.wait(mutex);
1673 // If this thread has been assigned work, launch a search
1676 assert(!do_sleep && !do_exit);
1678 Threads.mutex.lock();
1680 assert(is_searching);
1681 SplitPoint* sp = curSplitPoint;
1683 Threads.mutex.unlock();
1685 Stack ss[MAX_PLY_PLUS_2];
1686 Position pos(*sp->pos, this);
1688 memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1693 assert(sp->activePositions[idx] == NULL);
1695 sp->activePositions[idx] = &pos;
1697 if (sp->nodeType == Root)
1698 search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1699 else if (sp->nodeType == PV)
1700 search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1701 else if (sp->nodeType == NonPV)
1702 search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1706 assert(is_searching);
1708 is_searching = false;
1709 sp->activePositions[idx] = NULL;
1710 sp->slavesMask &= ~(1ULL << idx);
1711 sp->nodes += pos.nodes_searched();
1713 // Wake up master thread so to allow it to return from the idle loop in
1714 // case we are the last slave of the split point.
1715 if ( Threads.use_sleeping_threads()
1716 && this != sp->master
1719 assert(!sp->master->is_searching);
1720 sp->master->wake_up();
1723 // After releasing the lock we cannot access anymore any SplitPoint
1724 // related data in a safe way becuase it could have been released under
1725 // our feet by the sp master. Also accessing other Thread objects is
1726 // unsafe because if we are exiting there is a chance are already freed.
1733 /// check_time() is called by the timer thread when the timer triggers. It is
1734 /// used to print debug info and, more important, to detect when we are out of
1735 /// available time and so stop the search.
1739 static Time::point lastInfoTime = Time::now();
1740 int64_t nodes = 0; // Workaround silly 'uninitialized' gcc warning
1742 if (Time::now() - lastInfoTime >= 1000)
1744 lastInfoTime = Time::now();
1753 Threads.mutex.lock();
1755 nodes = RootPosition.nodes_searched();
1757 // Loop across all split points and sum accumulated SplitPoint nodes plus
1758 // all the currently active slaves positions.
1759 for (size_t i = 0; i < Threads.size(); i++)
1760 for (int j = 0; j < Threads[i].splitPointsCnt; j++)
1762 SplitPoint& sp = Threads[i].splitPoints[j];
1767 Bitboard sm = sp.slavesMask;
1770 Position* pos = sp.activePositions[pop_lsb(&sm)];
1771 nodes += pos ? pos->nodes_searched() : 0;
1777 Threads.mutex.unlock();
1780 Time::point elapsed = Time::now() - SearchTime;
1781 bool stillAtFirstMove = Signals.firstRootMove
1782 && !Signals.failedLowAtRoot
1783 && elapsed > TimeMgr.available_time();
1785 bool noMoreTime = elapsed > TimeMgr.maximum_time() - 2 * TimerResolution
1786 || stillAtFirstMove;
1788 if ( (Limits.use_time_management() && noMoreTime)
1789 || (Limits.movetime && elapsed >= Limits.movetime)
1790 || (Limits.nodes && nodes >= Limits.nodes))
1791 Signals.stop = true;