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 // Reduction lookup tables (initialized at startup) and their access function
82 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
84 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
86 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
89 size_t MultiPV, UCIMultiPV, PVIdx;
93 bool SkillLevelEnabled, Chess960;
96 template <NodeType NT>
97 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
99 template <NodeType NT>
100 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
102 void id_loop(Position& pos);
103 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
104 bool connected_moves(const Position& pos, Move m1, Move m2);
105 Value value_to_tt(Value v, int ply);
106 Value value_from_tt(Value v, int ply);
107 bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
108 bool connected_threat(const Position& pos, Move m, Move threat);
109 Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
110 Move do_skill_level();
111 string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
116 /// Search::init() is called during startup to initialize various lookup tables
118 void Search::init() {
120 int d; // depth (ONE_PLY == 2)
121 int hd; // half depth (ONE_PLY == 1)
124 // Init reductions array
125 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
127 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
128 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
129 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
130 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
133 // Init futility margins array
134 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
135 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
137 // Init futility move count array
138 for (d = 0; d < 32; d++)
139 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
143 /// Search::perft() is our utility to verify move generation. All the leaf nodes
144 /// up to the given depth are generated and counted and the sum returned.
146 size_t Search::perft(Position& pos, Depth depth) {
148 // At the last ply just return the number of legal moves (leaf nodes)
149 if (depth == ONE_PLY)
150 return MoveList<LEGAL>(pos).size();
156 for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
158 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
159 cnt += perft(pos, depth - ONE_PLY);
160 pos.undo_move(ml.move());
167 /// Search::think() is the external interface to Stockfish's search, and is
168 /// called by the main thread when the program receives the UCI 'go' command. It
169 /// searches from RootPosition and at the end prints the "bestmove" to output.
171 void Search::think() {
173 static PolyglotBook book; // Defined static to initialize the PRNG only once
175 Position& pos = RootPosition;
176 Chess960 = pos.is_chess960();
177 Eval::RootColor = pos.side_to_move();
178 Eval::ValueDraw[ Eval::RootColor] = VALUE_DRAW - Eval::ContemptFactor;
179 Eval::ValueDraw[~Eval::RootColor] = VALUE_DRAW + Eval::ContemptFactor;
180 TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
184 if (RootMoves.empty())
186 sync_cout << "info depth 0 score "
187 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << sync_endl;
189 RootMoves.push_back(MOVE_NONE);
193 if (Options["OwnBook"] && !Limits.infinite)
195 Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
197 if (bookMove && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
199 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
204 UCIMultiPV = Options["MultiPV"];
205 SkillLevel = Options["Skill Level"];
207 // Do we have to play with skill handicap? In this case enable MultiPV that
208 // we will use behind the scenes to retrieve a set of possible moves.
209 SkillLevelEnabled = (SkillLevel < 20);
210 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
212 if (Options["Use Search Log"])
214 Log log(Options["Search Log Filename"]);
215 log << "\nSearching: " << pos.to_fen()
216 << "\ninfinite: " << Limits.infinite
217 << " ponder: " << Limits.ponder
218 << " time: " << Limits.time[pos.side_to_move()]
219 << " increment: " << Limits.inc[pos.side_to_move()]
220 << " moves to go: " << Limits.movestogo
226 // Set best timer interval to avoid lagging under time pressure. Timer is
227 // used to check for remaining available thinking time.
228 if (Limits.use_time_management())
229 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
230 else if (Limits.nodes)
231 Threads.set_timer(2 * TimerResolution);
233 Threads.set_timer(100);
235 // We're ready to start searching. Call the iterative deepening loop function
238 Threads.set_timer(0); // Stop timer
241 if (Options["Use Search Log"])
243 Time::point elapsed = Time::now() - SearchTime + 1;
245 Log log(Options["Search Log Filename"]);
246 log << "Nodes: " << pos.nodes_searched()
247 << "\nNodes/second: " << pos.nodes_searched() * 1000 / elapsed
248 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
251 pos.do_move(RootMoves[0].pv[0], st);
252 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << std::endl;
253 pos.undo_move(RootMoves[0].pv[0]);
258 // When we reach max depth we arrive here even without Signals.stop is raised,
259 // but if we are pondering or in infinite search, we shouldn't print the best
260 // move before we are told to do so.
261 if (!Signals.stop && (Limits.ponder || Limits.infinite))
262 pos.this_thread()->wait_for_stop_or_ponderhit();
264 // Best move could be MOVE_NONE when searching on a stalemate position
265 sync_cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
266 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << sync_endl;
272 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
273 // with increasing depth until the allocated thinking time has been consumed,
274 // user stops the search, or the maximum search depth is reached.
276 void id_loop(Position& pos) {
278 Stack ss[MAX_PLY_PLUS_2];
279 int depth, prevBestMoveChanges;
280 Value bestValue, alpha, beta, delta;
281 bool bestMoveNeverChanged = true;
282 Move skillBest = MOVE_NONE;
284 memset(ss, 0, 4 * sizeof(Stack));
285 depth = BestMoveChanges = 0;
286 bestValue = delta = -VALUE_INFINITE;
287 ss->currentMove = MOVE_NULL; // Hack to skip update gains
289 // Iterative deepening loop until requested to stop or target depth reached
290 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
292 // Save last iteration's scores before first PV line is searched and all
293 // the move scores but the (new) PV are set to -VALUE_INFINITE.
294 for (size_t i = 0; i < RootMoves.size(); i++)
295 RootMoves[i].prevScore = RootMoves[i].score;
297 prevBestMoveChanges = BestMoveChanges;
300 // MultiPV loop. We perform a full root search for each PV line
301 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
303 // Set aspiration window default width
304 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
307 alpha = RootMoves[PVIdx].prevScore - delta;
308 beta = RootMoves[PVIdx].prevScore + delta;
312 alpha = -VALUE_INFINITE;
313 beta = VALUE_INFINITE;
316 // Start with a small aspiration window and, in case of fail high/low,
317 // research with bigger window until not failing high/low anymore.
320 // Search starts from ss+1 to allow referencing (ss-1). This is
321 // needed by update gains and ss copy when splitting at Root.
322 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
324 // Bring to front the best move. It is critical that sorting is
325 // done with a stable algorithm because all the values but the first
326 // and eventually the new best one are set to -VALUE_INFINITE and
327 // we want to keep the same order for all the moves but the new
328 // PV that goes to the front. Note that in case of MultiPV search
329 // the already searched PV lines are preserved.
330 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
332 // In case we have found an exact score and we are going to leave
333 // the fail high/low loop then reorder the PV moves, otherwise
334 // leave the last PV move in its position so to be searched again.
335 // Of course this is needed only in MultiPV search.
336 if (PVIdx && bestValue > alpha && bestValue < beta)
337 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
339 // Write PV back to transposition table in case the relevant
340 // entries have been overwritten during the search.
341 for (size_t i = 0; i <= PVIdx; i++)
342 RootMoves[i].insert_pv_in_tt(pos);
344 // If search has been stopped exit the aspiration window loop.
345 // Sorting and writing PV back to TT is safe becuase RootMoves
346 // is still valid, although refers to previous iteration.
350 // Send full PV info to GUI if we are going to leave the loop or
351 // if we have a fail high/low and we are deep in the search.
352 if ((bestValue > alpha && bestValue < beta) || Time::now() - SearchTime > 2000)
353 sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
355 // In case of failing high/low increase aspiration window and
356 // research, otherwise exit the fail high/low loop.
357 if (bestValue >= beta)
362 else if (bestValue <= alpha)
364 Signals.failedLowAtRoot = true;
365 Signals.stopOnPonderhit = false;
373 // Search with full window in case we have a win/mate score
374 if (abs(bestValue) >= VALUE_KNOWN_WIN)
376 alpha = -VALUE_INFINITE;
377 beta = VALUE_INFINITE;
380 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
384 // Skills: Do we need to pick now the best move ?
385 if (SkillLevelEnabled && depth == 1 + SkillLevel)
386 skillBest = do_skill_level();
388 if (!Signals.stop && Options["Use Search Log"])
390 Log log(Options["Search Log Filename"]);
391 log << pretty_pv(pos, depth, bestValue, Time::now() - SearchTime, &RootMoves[0].pv[0])
395 // Filter out startup noise when monitoring best move stability
396 if (depth > 2 && BestMoveChanges)
397 bestMoveNeverChanged = false;
399 // Do we have time for the next iteration? Can we stop searching now?
400 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
402 bool stop = false; // Local variable, not the volatile Signals.stop
404 // Take in account some extra time if the best move has changed
405 if (depth > 4 && depth < 50)
406 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
408 // Stop search if most of available time is already consumed. We
409 // probably don't have enough time to search the first move at the
410 // next iteration anyway.
411 if (Time::now() - SearchTime > (TimeMgr.available_time() * 62) / 100)
414 // Stop search early if one move seems to be much better than others
417 && ( (bestMoveNeverChanged && pos.captured_piece_type())
418 || Time::now() - SearchTime > (TimeMgr.available_time() * 40) / 100))
420 Value rBeta = bestValue - 2 * PawnValueMg;
421 (ss+1)->excludedMove = RootMoves[0].pv[0];
422 (ss+1)->skipNullMove = true;
423 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
424 (ss+1)->skipNullMove = false;
425 (ss+1)->excludedMove = MOVE_NONE;
433 // If we are allowed to ponder do not stop the search now but
434 // keep pondering until GUI sends "ponderhit" or "stop".
436 Signals.stopOnPonderhit = true;
443 // When using skills swap best PV line with the sub-optimal one
444 if (SkillLevelEnabled)
446 if (skillBest == MOVE_NONE) // Still unassigned ?
447 skillBest = do_skill_level();
449 std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), skillBest));
454 // search<>() is the main search function for both PV and non-PV nodes and for
455 // normal and SplitPoint nodes. When called just after a split point the search
456 // is simpler because we have already probed the hash table, done a null move
457 // search, and searched the first move before splitting, we don't have to repeat
458 // all this work again. We also don't need to store anything to the hash table
459 // here: This is taken care of after we return from the split point.
461 template <NodeType NT>
462 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
464 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
465 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
466 const bool RootNode = (NT == Root || NT == SplitPointRoot);
468 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
469 assert(PvNode || (alpha == beta - 1));
470 assert(depth > DEPTH_ZERO);
472 Move movesSearched[64];
477 Move ttMove, move, excludedMove, bestMove, threatMove;
479 Value bestValue, value, ttValue;
480 Value refinedValue, nullValue, futilityValue;
481 bool inCheck, givesCheck, pvMove, singularExtensionNode;
482 bool captureOrPromotion, dangerous, doFullDepthSearch;
483 int moveCount, playedMoveCount;
485 // Step 1. Initialize node
486 Thread* thisThread = pos.this_thread();
487 moveCount = playedMoveCount = 0;
488 inCheck = pos.in_check();
493 bestMove = sp->bestMove;
494 threatMove = sp->threatMove;
495 bestValue = sp->bestValue;
497 ttMove = excludedMove = MOVE_NONE;
498 ttValue = VALUE_NONE;
500 assert(sp->bestValue > -VALUE_INFINITE && sp->moveCount > 0);
502 goto split_point_start;
505 bestValue = -VALUE_INFINITE;
506 ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
507 ss->ply = (ss-1)->ply + 1;
508 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
509 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
511 // Used to send selDepth info to GUI
512 if (PvNode && thisThread->maxPly < ss->ply)
513 thisThread->maxPly = ss->ply;
517 // Step 2. Check for aborted search and immediate draw
518 if (Signals.stop || pos.is_draw<false>() || ss->ply > MAX_PLY)
519 return Eval::ValueDraw[pos.side_to_move()];
521 // Step 3. Mate distance pruning. Even if we mate at the next move our score
522 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
523 // a shorter mate was found upward in the tree then there is no need to search
524 // further, we will never beat current alpha. Same logic but with reversed signs
525 // applies also in the opposite condition of being mated instead of giving mate,
526 // in this case return a fail-high score.
527 alpha = std::max(mated_in(ss->ply), alpha);
528 beta = std::min(mate_in(ss->ply+1), beta);
533 // Step 4. Transposition table lookup
534 // We don't want the score of a partial search to overwrite a previous full search
535 // TT value, so we use a different position key in case of an excluded move.
536 excludedMove = ss->excludedMove;
537 posKey = excludedMove ? pos.exclusion_key() : pos.key();
538 tte = TT.probe(posKey);
539 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
540 ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
542 // At PV nodes we check for exact scores, while at non-PV nodes we check for
543 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
544 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
545 // we should also update RootMoveList to avoid bogus output.
546 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
547 : can_return_tt(tte, depth, ttValue, beta)))
550 ss->currentMove = ttMove; // Can be MOVE_NONE
554 && !pos.is_capture_or_promotion(ttMove)
555 && ttMove != ss->killers[0])
557 ss->killers[1] = ss->killers[0];
558 ss->killers[0] = ttMove;
563 // Step 5. Evaluate the position statically and update parent's gain statistics
565 ss->eval = ss->evalMargin = refinedValue = VALUE_NONE;
568 assert(tte->static_value() != VALUE_NONE);
570 ss->eval = tte->static_value();
571 ss->evalMargin = tte->static_value_margin();
572 refinedValue = refine_eval(tte, ttValue, ss->eval);
576 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
577 TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
580 // Update gain for the parent non-capture move given the static position
581 // evaluation before and after the move.
582 if ( (move = (ss-1)->currentMove) != MOVE_NULL
583 && (ss-1)->eval != VALUE_NONE
584 && ss->eval != VALUE_NONE
585 && !pos.captured_piece_type()
586 && type_of(move) == NORMAL)
588 Square to = to_sq(move);
589 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
592 // Step 6. Razoring (is omitted in PV nodes)
594 && depth < 4 * ONE_PLY
596 && refinedValue + razor_margin(depth) < beta
597 && ttMove == MOVE_NONE
598 && abs(beta) < VALUE_MATE_IN_MAX_PLY
599 && !pos.pawn_on_7th(pos.side_to_move()))
601 Value rbeta = beta - razor_margin(depth);
602 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
604 // Logically we should return (v + razor_margin(depth)), but
605 // surprisingly this did slightly weaker in tests.
609 // Step 7. Static null move pruning (is omitted in PV nodes)
610 // We're betting that the opponent doesn't have a move that will reduce
611 // the score by more than futility_margin(depth) if we do a null move.
614 && depth < 4 * ONE_PLY
616 && refinedValue - FutilityMargins[depth][0] >= beta
617 && abs(beta) < VALUE_MATE_IN_MAX_PLY
618 && pos.non_pawn_material(pos.side_to_move()))
619 return refinedValue - FutilityMargins[depth][0];
621 // Step 8. Null move search with verification search (is omitted in PV nodes)
626 && refinedValue >= beta
627 && abs(beta) < VALUE_MATE_IN_MAX_PLY
628 && pos.non_pawn_material(pos.side_to_move()))
630 ss->currentMove = MOVE_NULL;
632 // Null move dynamic reduction based on depth
633 Depth R = 3 * ONE_PLY + depth / 4;
635 // Null move dynamic reduction based on value
636 if (refinedValue - PawnValueMg > beta)
639 pos.do_null_move<true>(st);
640 (ss+1)->skipNullMove = true;
641 nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
642 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
643 (ss+1)->skipNullMove = false;
644 pos.do_null_move<false>(st);
646 if (nullValue >= beta)
648 // Do not return unproven mate scores
649 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
652 if (depth < 6 * ONE_PLY)
655 // Do verification search at high depths
656 ss->skipNullMove = true;
657 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
658 ss->skipNullMove = false;
665 // The null move failed low, which means that we may be faced with
666 // some kind of threat. If the previous move was reduced, check if
667 // the move that refuted the null move was somehow connected to the
668 // move which was reduced. If a connection is found, return a fail
669 // low score (which will cause the reduced move to fail high in the
670 // parent node, which will trigger a re-search with full depth).
671 threatMove = (ss+1)->currentMove;
673 if ( depth < 5 * ONE_PLY
675 && threatMove != MOVE_NONE
676 && connected_moves(pos, (ss-1)->currentMove, threatMove))
681 // Step 9. ProbCut (is omitted in PV nodes)
682 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
683 // and a reduced search returns a value much above beta, we can (almost) safely
684 // prune the previous move.
686 && depth >= 5 * ONE_PLY
689 && excludedMove == MOVE_NONE
690 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
692 Value rbeta = beta + 200;
693 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
695 assert(rdepth >= ONE_PLY);
696 assert((ss-1)->currentMove != MOVE_NONE);
697 assert((ss-1)->currentMove != MOVE_NULL);
699 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
702 while ((move = mp.next_move<false>()) != MOVE_NONE)
703 if (pos.pl_move_is_legal(move, ci.pinned))
705 ss->currentMove = move;
706 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
707 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
714 // Step 10. Internal iterative deepening
715 if ( depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
716 && ttMove == MOVE_NONE
717 && (PvNode || (!inCheck && ss->eval + Value(256) >= beta)))
719 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
721 ss->skipNullMove = true;
722 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
723 ss->skipNullMove = false;
725 tte = TT.probe(posKey);
726 ttMove = tte ? tte->move() : MOVE_NONE;
729 split_point_start: // At split points actual search starts from here
731 MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
733 value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
734 singularExtensionNode = !RootNode
736 && depth >= (PvNode ? 6 * ONE_PLY : 8 * ONE_PLY)
737 && ttMove != MOVE_NONE
738 && !excludedMove // Recursive singular search is not allowed
739 && (tte->type() & BOUND_LOWER)
740 && tte->depth() >= depth - 3 * ONE_PLY;
742 // Step 11. Loop through moves
743 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
744 while ((move = mp.next_move<SpNode>()) != MOVE_NONE)
748 if (move == excludedMove)
751 // At root obey the "searchmoves" option and skip moves not listed in Root
752 // Move List, as a consequence any illegal move is also skipped. In MultiPV
753 // mode we also skip PV moves which have been already searched.
754 if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
759 // Shared counter cannot be decremented later if move turns out to be illegal
760 if (!pos.pl_move_is_legal(move, ci.pinned))
763 moveCount = ++sp->moveCount;
771 Signals.firstRootMove = (moveCount == 1);
773 if (thisThread == Threads.main_thread() && Time::now() - SearchTime > 2000)
774 sync_cout << "info depth " << depth / ONE_PLY
775 << " currmove " << move_to_uci(move, Chess960)
776 << " currmovenumber " << moveCount + PVIdx << sync_endl;
780 captureOrPromotion = pos.is_capture_or_promotion(move);
781 givesCheck = pos.move_gives_check(move, ci);
782 dangerous = givesCheck
783 || pos.is_passed_pawn_push(move)
784 || type_of(move) == CASTLE
785 || ( captureOrPromotion // Entering a pawn endgame?
786 && type_of(pos.piece_on(to_sq(move))) != PAWN
787 && type_of(move) == NORMAL
788 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
789 - PieceValue[Mg][pos.piece_on(to_sq(move))] == VALUE_ZERO));
791 // Step 12. Extend checks and, in PV nodes, also dangerous moves
792 if (PvNode && dangerous)
795 else if (givesCheck && pos.see_sign(move) >= 0)
798 // Singular extension search. If all moves but one fail low on a search of
799 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
800 // is singular and should be extended. To verify this we do a reduced search
801 // on all the other moves but the ttMove, if result is lower than ttValue minus
802 // a margin then we extend ttMove.
803 if ( singularExtensionNode
806 && pos.pl_move_is_legal(move, ci.pinned)
807 && abs(ttValue) < VALUE_KNOWN_WIN)
809 Value rBeta = ttValue - int(depth);
810 ss->excludedMove = move;
811 ss->skipNullMove = true;
812 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
813 ss->skipNullMove = false;
814 ss->excludedMove = MOVE_NONE;
817 ext = rBeta >= beta ? ONE_PLY + ONE_PLY / 2 : ONE_PLY;
820 // Update current move (this must be done after singular extension search)
821 newDepth = depth - ONE_PLY + ext;
823 // Step 13. Futility pruning (is omitted in PV nodes)
825 && !captureOrPromotion
829 && (bestValue > VALUE_MATED_IN_MAX_PLY || ( bestValue == -VALUE_INFINITE
830 && alpha > VALUE_MATED_IN_MAX_PLY)))
832 // Move count based pruning
833 if ( depth < 16 * ONE_PLY
834 && moveCount >= FutilityMoveCounts[depth]
835 && (!threatMove || !connected_threat(pos, move, threatMove)))
843 // Value based pruning
844 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
845 // but fixing this made program slightly weaker.
846 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
847 futilityValue = ss->eval + ss->evalMargin + futility_margin(predictedDepth, moveCount)
848 + H.gain(pos.piece_moved(move), to_sq(move));
850 if (futilityValue < beta)
858 // Prune moves with negative SEE at low depths
859 if ( predictedDepth < 2 * ONE_PLY
860 && pos.see_sign(move) < 0)
869 // Check for legality only before to do the move
870 if (!pos.pl_move_is_legal(move, ci.pinned))
876 pvMove = PvNode ? moveCount == 1 : false;
877 ss->currentMove = move;
878 if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
879 movesSearched[playedMoveCount++] = move;
881 // Step 14. Make the move
882 pos.do_move(move, st, ci, givesCheck);
884 // Step 15. Reduced depth search (LMR). If the move fails high will be
885 // re-searched at full depth.
886 if ( depth > 3 * ONE_PLY
888 && !captureOrPromotion
890 && ss->killers[0] != move
891 && ss->killers[1] != move)
893 ss->reduction = reduction<PvNode>(depth, moveCount);
894 Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
895 alpha = SpNode ? sp->alpha : alpha;
897 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
899 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
900 ss->reduction = DEPTH_ZERO;
903 doFullDepthSearch = !pvMove;
905 // Step 16. Full depth search, when LMR is skipped or fails high
906 if (doFullDepthSearch)
908 alpha = SpNode ? sp->alpha : alpha;
909 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
910 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
913 // Only for PV nodes do a full PV search on the first move or after a fail
914 // high, in the latter case search only if value < beta, otherwise let the
915 // parent node to fail low with value <= alpha and to try another move.
916 if (PvNode && (pvMove || (value > alpha && (RootNode || value < beta))))
917 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
918 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
920 // Step 17. Undo move
923 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
925 // Step 18. Check for new best move
929 bestValue = sp->bestValue;
933 // Finished searching the move. If Signals.stop is true, the search
934 // was aborted because the user interrupted the search or because we
935 // ran out of time. In this case, the return value of the search cannot
936 // be trusted, and we don't update the best move and/or PV.
937 if (Signals.stop || thisThread->cutoff_occurred())
942 RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
944 // PV move or new best move ?
945 if (pvMove || value > alpha)
948 rm.extract_pv_from_tt(pos);
950 // We record how often the best move has been changed in each
951 // iteration. This information is used for time management: When
952 // the best move changes frequently, we allocate some more time.
953 if (!pvMove && MultiPV == 1)
957 // All other moves but the PV are set to the lowest value, this
958 // is not a problem when sorting becuase sort is stable and move
959 // position in the list is preserved, just the PV is pushed up.
960 rm.score = -VALUE_INFINITE;
963 if (value > bestValue)
966 if (SpNode) sp->bestValue = value;
971 if (SpNode) sp->bestMove = move;
973 if (PvNode && value < beta)
975 alpha = value; // Update alpha here! Always alpha < beta
976 if (SpNode) sp->alpha = value;
980 if (SpNode) sp->cutoff = true;
986 // Step 19. Check for splitting the search
988 && depth >= Threads.min_split_depth()
990 && Threads.available_slave_exists(thisThread))
992 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
993 depth, threatMove, moveCount, mp, NT);
1001 // Step 20. Check for mate and stalemate
1002 // All legal moves have been searched and if there are no legal moves, it
1003 // must be mate or stalemate. Note that we can have a false positive in
1004 // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1005 // harmless because return value is discarded anyhow in the parent nodes.
1006 // If we are in a singular extension search then return a fail low score.
1007 // A split node has at least one move, the one tried before to be splitted.
1009 return excludedMove ? alpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1011 // If we have pruned all the moves without searching return a fail-low score
1012 if (bestValue == -VALUE_INFINITE)
1014 assert(!playedMoveCount);
1019 if (bestValue >= beta) // Failed high
1021 TT.store(posKey, value_to_tt(bestValue, ss->ply), BOUND_LOWER, depth,
1022 bestMove, ss->eval, ss->evalMargin);
1024 if (!pos.is_capture_or_promotion(bestMove) && !inCheck)
1026 if (bestMove != ss->killers[0])
1028 ss->killers[1] = ss->killers[0];
1029 ss->killers[0] = bestMove;
1032 // Increase history value of the cut-off move
1033 Value bonus = Value(int(depth) * int(depth));
1034 H.add(pos.piece_moved(bestMove), to_sq(bestMove), bonus);
1036 // Decrease history of all the other played non-capture moves
1037 for (int i = 0; i < playedMoveCount - 1; i++)
1039 Move m = movesSearched[i];
1040 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1044 else // Failed low or PV search
1045 TT.store(posKey, value_to_tt(bestValue, ss->ply),
1046 PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1047 depth, bestMove, ss->eval, ss->evalMargin);
1049 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1055 // qsearch() is the quiescence search function, which is called by the main
1056 // search function when the remaining depth is zero (or, to be more precise,
1057 // less than ONE_PLY).
1059 template <NodeType NT>
1060 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1062 const bool PvNode = (NT == PV);
1064 assert(NT == PV || NT == NonPV);
1065 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1066 assert(PvNode || (alpha == beta - 1));
1067 assert(depth <= DEPTH_ZERO);
1072 Move ttMove, move, bestMove;
1073 Value bestValue, value, ttValue, futilityValue, futilityBase;
1074 bool inCheck, givesCheck, enoughMaterial, evasionPrunable;
1077 inCheck = pos.in_check();
1078 ss->currentMove = bestMove = MOVE_NONE;
1079 ss->ply = (ss-1)->ply + 1;
1081 // Check for an instant draw or maximum ply reached
1082 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1083 return Eval::ValueDraw[pos.side_to_move()];
1085 // Transposition table lookup. At PV nodes, we don't use the TT for
1086 // pruning, but only for move ordering.
1088 tte = TT.probe(posKey);
1089 ttMove = tte ? tte->move() : MOVE_NONE;
1090 ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_NONE;
1092 // Decide whether or not to include checks, this fixes also the type of
1093 // TT entry depth that we are going to use. Note that in qsearch we use
1094 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1095 ttDepth = inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS;
1097 if (!PvNode && tte && can_return_tt(tte, ttDepth, ttValue, beta))
1099 ss->currentMove = ttMove; // Can be MOVE_NONE
1103 // Evaluate the position statically
1106 ss->eval = ss->evalMargin = VALUE_NONE;
1107 bestValue = futilityBase = -VALUE_INFINITE;
1108 enoughMaterial = false;
1114 assert(tte->static_value() != VALUE_NONE);
1116 ss->eval = bestValue = tte->static_value();
1117 ss->evalMargin = tte->static_value_margin();
1120 ss->eval = bestValue = evaluate(pos, ss->evalMargin);
1122 // Stand pat. Return immediately if static value is at least beta
1123 if (bestValue >= beta)
1126 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
1131 if (PvNode && bestValue > alpha)
1134 futilityBase = ss->eval + ss->evalMargin + Value(128);
1135 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1138 // Initialize a MovePicker object for the current position, and prepare
1139 // to search the moves. Because the depth is <= 0 here, only captures,
1140 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1142 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1145 // Loop through the moves until no moves remain or a beta cutoff occurs
1146 while ((move = mp.next_move<false>()) != MOVE_NONE)
1148 assert(is_ok(move));
1150 givesCheck = pos.move_gives_check(move, ci);
1158 && type_of(move) != PROMOTION
1159 && !pos.is_passed_pawn_push(move))
1161 futilityValue = futilityBase
1162 + PieceValue[Eg][pos.piece_on(to_sq(move))]
1163 + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1165 if (futilityValue < beta)
1167 if (futilityValue > bestValue)
1168 bestValue = futilityValue;
1173 // Prune moves with negative or equal SEE
1174 if ( futilityBase < beta
1175 && depth < DEPTH_ZERO
1176 && pos.see(move) <= 0)
1180 // Detect non-capture evasions that are candidate to be pruned
1181 evasionPrunable = !PvNode
1183 && bestValue > VALUE_MATED_IN_MAX_PLY
1184 && !pos.is_capture(move)
1185 && !pos.can_castle(pos.side_to_move());
1187 // Don't search moves with negative SEE values
1189 && (!inCheck || evasionPrunable)
1191 && type_of(move) != PROMOTION
1192 && pos.see_sign(move) < 0)
1195 // Don't search useless checks
1200 && !pos.is_capture_or_promotion(move)
1201 && ss->eval + PawnValueMg / 4 < beta
1202 && !check_is_dangerous(pos, move, futilityBase, beta))
1205 // Check for legality only before to do the move
1206 if (!pos.pl_move_is_legal(move, ci.pinned))
1209 ss->currentMove = move;
1211 // Make and search the move
1212 pos.do_move(move, st, ci, givesCheck);
1213 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1214 pos.undo_move(move);
1216 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1218 // Check for new best move
1219 if (value > bestValue)
1225 if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1232 TT.store(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1233 ttDepth, move, ss->eval, ss->evalMargin);
1241 // All legal moves have been searched. A special case: If we're in check
1242 // and no legal moves were found, it is checkmate.
1243 if (inCheck && bestValue == -VALUE_INFINITE)
1244 return mated_in(ss->ply); // Plies to mate from the root
1246 TT.store(posKey, value_to_tt(bestValue, ss->ply),
1247 PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1248 ttDepth, bestMove, ss->eval, ss->evalMargin);
1250 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1256 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1257 // bestValue is updated only when returning false because in that case move
1260 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1262 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1263 Square from, to, ksq;
1267 from = from_sq(move);
1269 them = ~pos.side_to_move();
1270 ksq = pos.king_square(them);
1271 kingAtt = pos.attacks_from<KING>(ksq);
1272 pc = pos.piece_moved(move);
1274 occ = pos.pieces() ^ from ^ ksq;
1275 oldAtt = pos.attacks_from(pc, from, occ);
1276 newAtt = pos.attacks_from(pc, to, occ);
1278 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1279 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1281 if (!more_than_one(b))
1284 // Rule 2. Queen contact check is very dangerous
1285 if (type_of(pc) == QUEEN && (kingAtt & to))
1288 // Rule 3. Creating new double threats with checks
1289 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1292 // Note that here we generate illegal "double move"!
1293 if (futilityBase + PieceValue[Eg][pos.piece_on(pop_lsb(&b))] >= beta)
1301 // connected_moves() tests whether two moves are 'connected' in the sense
1302 // that the first move somehow made the second move possible (for instance
1303 // if the moving piece is the same in both moves). The first move is assumed
1304 // to be the move that was made to reach the current position, while the
1305 // second move is assumed to be a move from the current position.
1307 bool connected_moves(const Position& pos, Move m1, Move m2) {
1309 Square f1, t1, f2, t2;
1316 // Case 1: The moving piece is the same in both moves
1322 // Case 2: The destination square for m2 was vacated by m1
1328 // Case 3: Moving through the vacated square
1329 p2 = pos.piece_on(f2);
1330 if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1333 // Case 4: The destination square for m2 is defended by the moving piece in m1
1334 p1 = pos.piece_on(t1);
1335 if (pos.attacks_from(p1, t1) & t2)
1338 // Case 5: Discovered check, checking piece is the piece moved in m1
1339 ksq = pos.king_square(pos.side_to_move());
1340 if ( piece_is_slider(p1)
1341 && (between_bb(t1, ksq) & f2)
1342 && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1349 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1350 // "plies to mate from the current position". Non-mate scores are unchanged.
1351 // The function is called before storing a value to the transposition table.
1353 Value value_to_tt(Value v, int ply) {
1355 if (v >= VALUE_MATE_IN_MAX_PLY)
1358 if (v <= VALUE_MATED_IN_MAX_PLY)
1365 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1366 // from the transposition table (where refers to the plies to mate/be mated
1367 // from current position) to "plies to mate/be mated from the root".
1369 Value value_from_tt(Value v, int ply) {
1371 if (v >= VALUE_MATE_IN_MAX_PLY)
1374 if (v <= VALUE_MATED_IN_MAX_PLY)
1381 // connected_threat() tests whether it is safe to forward prune a move or if
1382 // is somehow connected to the threat move returned by null search.
1384 bool connected_threat(const Position& pos, Move m, Move threat) {
1387 assert(is_ok(threat));
1388 assert(!pos.is_capture_or_promotion(m));
1389 assert(!pos.is_passed_pawn_push(m));
1391 Square mfrom, mto, tfrom, tto;
1395 tfrom = from_sq(threat);
1396 tto = to_sq(threat);
1398 // Case 1: Don't prune moves which move the threatened piece
1402 // Case 2: If the threatened piece has value less than or equal to the
1403 // value of the threatening piece, don't prune moves which defend it.
1404 if ( pos.is_capture(threat)
1405 && ( PieceValue[Mg][pos.piece_on(tfrom)] >= PieceValue[Mg][pos.piece_on(tto)]
1406 || type_of(pos.piece_on(tfrom)) == KING)
1407 && pos.move_attacks_square(m, tto))
1410 // Case 3: If the moving piece in the threatened move is a slider, don't
1411 // prune safe moves which block its ray.
1412 if ( piece_is_slider(pos.piece_on(tfrom))
1413 && (between_bb(tfrom, tto) & mto)
1414 && pos.see_sign(m) >= 0)
1421 // can_return_tt() returns true if a transposition table score can be used to
1422 // cut-off at a given point in search.
1424 bool can_return_tt(const TTEntry* tte, Depth depth, Value v, Value beta) {
1426 return ( tte->depth() >= depth
1427 || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1428 || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1430 && ( ((tte->type() & BOUND_LOWER) && v >= beta)
1431 || ((tte->type() & BOUND_UPPER) && v < beta));
1435 // refine_eval() returns the transposition table score if possible, otherwise
1436 // falls back on static position evaluation.
1438 Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1442 if ( ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1443 || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1450 // When playing with strength handicap choose best move among the MultiPV set
1451 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1453 Move do_skill_level() {
1455 assert(MultiPV > 1);
1459 // PRNG sequence should be not deterministic
1460 for (int i = Time::now() % 50; i > 0; i--)
1461 rk.rand<unsigned>();
1463 // RootMoves are already sorted by score in descending order
1464 size_t size = std::min(MultiPV, RootMoves.size());
1465 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1466 int weakness = 120 - 2 * SkillLevel;
1467 int max_s = -VALUE_INFINITE;
1468 Move best = MOVE_NONE;
1470 // Choose best move. For each move score we add two terms both dependent on
1471 // weakness, one deterministic and bigger for weaker moves, and one random,
1472 // then we choose the move with the resulting highest score.
1473 for (size_t i = 0; i < size; i++)
1475 int s = RootMoves[i].score;
1477 // Don't allow crazy blunders even at very low skills
1478 if (i > 0 && RootMoves[i-1].score > s + 2 * PawnValueMg)
1481 // This is our magic formula
1482 s += ( weakness * int(RootMoves[0].score - s)
1483 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1488 best = RootMoves[i].pv[0];
1495 // uci_pv() formats PV information according to UCI protocol. UCI requires
1496 // to send all the PV lines also if are still to be searched and so refer to
1497 // the previous search score.
1499 string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1501 std::stringstream s;
1502 Time::point elaspsed = Time::now() - SearchTime + 1;
1505 for (size_t i = 0; i < Threads.size(); i++)
1506 if (Threads[i].maxPly > selDepth)
1507 selDepth = Threads[i].maxPly;
1509 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1511 bool updated = (i <= PVIdx);
1513 if (depth == 1 && !updated)
1516 int d = (updated ? depth : depth - 1);
1517 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1519 if (s.rdbuf()->in_avail())
1522 s << "info depth " << d
1523 << " seldepth " << selDepth
1524 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1525 << " nodes " << pos.nodes_searched()
1526 << " nps " << pos.nodes_searched() * 1000 / elaspsed
1527 << " time " << elaspsed
1528 << " multipv " << i + 1
1531 for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1532 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1541 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1542 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1543 /// allow to always have a ponder move even when we fail high at root, and a
1544 /// long PV to print that is important for position analysis.
1546 void RootMove::extract_pv_from_tt(Position& pos) {
1548 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1553 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1557 pos.do_move(m, *st++);
1559 while ( (tte = TT.probe(pos.key())) != NULL
1560 && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1561 && pos.is_pseudo_legal(m)
1562 && pos.pl_move_is_legal(m, pos.pinned_pieces())
1564 && (!pos.is_draw<false>() || ply < 2))
1567 pos.do_move(m, *st++);
1570 pv.push_back(MOVE_NONE);
1572 do pos.undo_move(pv[--ply]); while (ply);
1576 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1577 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1578 /// first, even if the old TT entries have been overwritten.
1580 void RootMove::insert_pv_in_tt(Position& pos) {
1582 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1585 Value v, m = VALUE_NONE;
1588 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1594 // Don't overwrite existing correct entries
1595 if (!tte || tte->move() != pv[ply])
1597 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1598 TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1600 pos.do_move(pv[ply], *st++);
1602 } while (pv[++ply] != MOVE_NONE);
1604 do pos.undo_move(pv[--ply]); while (ply);
1608 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1610 void Thread::idle_loop() {
1612 // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1613 // object for which the thread is the master.
1614 const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1616 assert(!sp_master || (sp_master->master == this && is_searching));
1618 // If this thread is the master of a split point and all slaves have
1619 // finished their work at this split point, return from the idle loop.
1620 while (!sp_master || sp_master->slavesMask)
1622 // If we are not searching, wait for a condition to be signaled
1623 // instead of wasting CPU time polling for work.
1626 || (!is_searching && Threads.use_sleeping_threads()))
1634 // Grab the lock to avoid races with Thread::wake_up()
1637 // If we are master and all slaves have finished don't go to sleep
1638 if (sp_master && !sp_master->slavesMask)
1644 // Do sleep after retesting sleep conditions under lock protection, in
1645 // particular we need to avoid a deadlock in case a master thread has,
1646 // in the meanwhile, allocated us and sent the wake_up() call before we
1647 // had the chance to grab the lock.
1648 if (do_sleep || !is_searching)
1649 sleepCondition.wait(mutex);
1654 // If this thread has been assigned work, launch a search
1657 assert(!do_sleep && !do_exit);
1659 Threads.mutex.lock();
1661 assert(is_searching);
1662 SplitPoint* sp = curSplitPoint;
1664 Threads.mutex.unlock();
1666 Stack ss[MAX_PLY_PLUS_2];
1667 Position pos(*sp->pos, this);
1669 memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1674 assert(sp->activePositions[idx] == NULL);
1676 sp->activePositions[idx] = &pos;
1678 if (sp->nodeType == Root)
1679 search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1680 else if (sp->nodeType == PV)
1681 search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1682 else if (sp->nodeType == NonPV)
1683 search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1687 assert(is_searching);
1689 is_searching = false;
1690 sp->activePositions[idx] = NULL;
1691 sp->slavesMask &= ~(1ULL << idx);
1692 sp->nodes += pos.nodes_searched();
1694 // Wake up master thread so to allow it to return from the idle loop in
1695 // case we are the last slave of the split point.
1696 if ( Threads.use_sleeping_threads()
1697 && this != sp->master
1700 assert(!sp->master->is_searching);
1701 sp->master->wake_up();
1704 // After releasing the lock we cannot access anymore any SplitPoint
1705 // related data in a safe way becuase it could have been released under
1706 // our feet by the sp master. Also accessing other Thread objects is
1707 // unsafe because if we are exiting there is a chance are already freed.
1714 /// check_time() is called by the timer thread when the timer triggers. It is
1715 /// used to print debug info and, more important, to detect when we are out of
1716 /// available time and so stop the search.
1720 static Time::point lastInfoTime = Time::now();
1721 int64_t nodes = 0; // Workaround silly 'uninitialized' gcc warning
1723 if (Time::now() - lastInfoTime >= 1000)
1725 lastInfoTime = Time::now();
1734 Threads.mutex.lock();
1736 nodes = RootPosition.nodes_searched();
1738 // Loop across all split points and sum accumulated SplitPoint nodes plus
1739 // all the currently active slaves positions.
1740 for (size_t i = 0; i < Threads.size(); i++)
1741 for (int j = 0; j < Threads[i].splitPointsCnt; j++)
1743 SplitPoint& sp = Threads[i].splitPoints[j];
1748 Bitboard sm = sp.slavesMask;
1751 Position* pos = sp.activePositions[pop_lsb(&sm)];
1752 nodes += pos ? pos->nodes_searched() : 0;
1758 Threads.mutex.unlock();
1761 Time::point elapsed = Time::now() - SearchTime;
1762 bool stillAtFirstMove = Signals.firstRootMove
1763 && !Signals.failedLowAtRoot
1764 && elapsed > TimeMgr.available_time();
1766 bool noMoreTime = elapsed > TimeMgr.maximum_time() - 2 * TimerResolution
1767 || stillAtFirstMove;
1769 if ( (Limits.use_time_management() && noMoreTime)
1770 || (Limits.movetime && elapsed >= Limits.movetime)
1771 || (Limits.nodes && nodes >= Limits.nodes))
1772 Signals.stop = true;