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/>.
38 #include "ucioption.h"
42 volatile SignalsType Signals;
44 std::vector<RootMove> RootMoves;
45 Position RootPosition;
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 // Maximum depth for razoring
66 const Depth RazorDepth = 4 * ONE_PLY;
68 // Dynamic razoring margin based on depth
69 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
71 // Maximum depth for use of dynamic threat detection when null move fails low
72 const Depth ThreatDepth = 5 * ONE_PLY;
74 // Minimum depth for use of internal iterative deepening
75 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
77 // At Non-PV nodes we do an internal iterative deepening search
78 // when the static evaluation is bigger then beta - IIDMargin.
79 const Value IIDMargin = Value(0x100);
81 // Minimum depth for use of singular extension
82 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
84 // Futility margin for quiescence search
85 const Value FutilityMarginQS = Value(0x80);
87 // Futility lookup tables (initialized at startup) and their access functions
88 Value FutilityMargins[16][64]; // [depth][moveNumber]
89 int FutilityMoveCounts[32]; // [depth]
91 inline Value futility_margin(Depth d, int mn) {
93 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
97 inline int futility_move_count(Depth d) {
99 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
102 // Reduction lookup tables (initialized at startup) and their access function
103 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
105 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
107 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
110 // Easy move margin. An easy move candidate must be at least this much better
111 // than the second best move.
112 const Value EasyMoveMargin = Value(0x150);
114 // This is the minimum interval in msec between two check_time() calls
115 const int TimerResolution = 5;
118 size_t MultiPV, UCIMultiPV, PVIdx;
122 bool SkillLevelEnabled, Chess960;
126 template <NodeType NT>
127 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
129 template <NodeType NT>
130 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
132 void id_loop(Position& pos);
133 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
134 bool connected_moves(const Position& pos, Move m1, Move m2);
135 Value value_to_tt(Value v, int ply);
136 Value value_from_tt(Value v, int ply);
137 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
138 bool connected_threat(const Position& pos, Move m, Move threat);
139 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
140 Move do_skill_level();
141 int elapsed_time(bool reset = false);
142 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
143 void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
144 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
146 // MovePickerExt class template extends MovePicker and allows to choose at
147 // compile time the proper moves source according to the type of node. In the
148 // default case we simply create and use a standard MovePicker object.
149 template<bool SpNode> struct MovePickerExt : public MovePicker {
151 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
152 : MovePicker(p, ttm, d, h, ss, b) {}
155 // In case of a SpNode we use split point's shared MovePicker object as moves source
156 template<> struct MovePickerExt<true> : public MovePicker {
158 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
159 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
161 Move next_move() { return mp->next_move(); }
165 // is_dangerous() checks whether a move belongs to some classes of known
166 // 'dangerous' moves so that we avoid to prune it.
167 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
169 // Test for a pawn pushed to 7th or a passed pawn move
170 if (type_of(pos.piece_moved(m)) == PAWN)
172 Color c = pos.side_to_move();
173 if ( relative_rank(c, to_sq(m)) == RANK_7
174 || pos.pawn_is_passed(c, to_sq(m)))
178 // Test for a capture that triggers a pawn endgame
179 if ( captureOrPromotion
180 && type_of(pos.piece_on(to_sq(m))) != PAWN
181 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
182 - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO)
192 /// Search::init() is called during startup to initialize various lookup tables
194 void Search::init() {
196 int d; // depth (ONE_PLY == 2)
197 int hd; // half depth (ONE_PLY == 1)
200 // Init reductions array
201 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
203 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
204 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
205 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
206 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
209 // Init futility margins array
210 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
211 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
213 // Init futility move count array
214 for (d = 0; d < 32; d++)
215 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
219 /// Search::perft() is our utility to verify move generation. All the leaf nodes
220 /// up to the given depth are generated and counted and the sum returned.
222 int64_t Search::perft(Position& pos, Depth depth) {
227 MoveList<MV_LEGAL> ml(pos);
229 // At the last ply just return the number of moves (leaf nodes)
230 if (depth == ONE_PLY)
234 for ( ; !ml.end(); ++ml)
236 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
237 cnt += perft(pos, depth - ONE_PLY);
238 pos.undo_move(ml.move());
244 /// Search::think() is the external interface to Stockfish's search, and is
245 /// called by the main thread when the program receives the UCI 'go' command. It
246 /// searches from RootPosition and at the end prints the "bestmove" to output.
248 void Search::think() {
250 static Book book; // Defined static to initialize the PRNG only once
252 Position& pos = RootPosition;
253 Chess960 = pos.is_chess960();
255 TimeMgr.init(Limits, pos.startpos_ply_counter());
259 if (RootMoves.empty())
261 cout << "info depth 0 score "
262 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
264 RootMoves.push_back(MOVE_NONE);
268 if (Options["OwnBook"])
270 Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
272 if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
274 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
279 // Read UCI options: GUI could change UCI parameters during the game
280 read_evaluation_uci_options(pos.side_to_move());
281 Threads.read_uci_options();
283 TT.set_size(Options["Hash"]);
284 if (Options["Clear Hash"])
286 Options["Clear Hash"] = false;
290 UCIMultiPV = Options["MultiPV"];
291 SkillLevel = Options["Skill Level"];
293 // Do we have to play with skill handicap? In this case enable MultiPV that
294 // we will use behind the scenes to retrieve a set of possible moves.
295 SkillLevelEnabled = (SkillLevel < 20);
296 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
298 if (Options["Use Search Log"])
300 Log log(Options["Search Log Filename"]);
301 log << "\nSearching: " << pos.to_fen()
302 << "\ninfinite: " << Limits.infinite
303 << " ponder: " << Limits.ponder
304 << " time: " << Limits.time
305 << " increment: " << Limits.increment
306 << " moves to go: " << Limits.movesToGo
310 for (int i = 0; i < Threads.size(); i++)
312 Threads[i].maxPly = 0;
313 Threads[i].wake_up();
316 // Set best timer interval to avoid lagging under time pressure. Timer is
317 // used to check for remaining available thinking time.
318 if (Limits.use_time_management())
319 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
321 Threads.set_timer(100);
323 // We're ready to start searching. Call the iterative deepening loop function
326 // Stop timer and send all the slaves to sleep, if not already sleeping
327 Threads.set_timer(0);
330 if (Options["Use Search Log"])
332 int e = elapsed_time();
334 Log log(Options["Search Log Filename"]);
335 log << "Nodes: " << pos.nodes_searched()
336 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
337 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
340 pos.do_move(RootMoves[0].pv[0], st);
341 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
342 pos.undo_move(RootMoves[0].pv[0]);
347 // When we reach max depth we arrive here even without Signals.stop is raised,
348 // but if we are pondering or in infinite search, we shouldn't print the best
349 // move before we are told to do so.
350 if (!Signals.stop && (Limits.ponder || Limits.infinite))
351 Threads.wait_for_stop_or_ponderhit();
353 // Best move could be MOVE_NONE when searching on a stalemate position
354 cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
355 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
361 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
362 // with increasing depth until the allocated thinking time has been consumed,
363 // user stops the search, or the maximum search depth is reached.
365 void id_loop(Position& pos) {
367 Stack ss[MAX_PLY_PLUS_2];
368 int depth, prevBestMoveChanges;
369 Value bestValue, alpha, beta, delta;
370 bool bestMoveNeverChanged = true;
371 Move skillBest = MOVE_NONE;
373 memset(ss, 0, 4 * sizeof(Stack));
374 depth = BestMoveChanges = 0;
375 bestValue = delta = -VALUE_INFINITE;
376 ss->currentMove = MOVE_NULL; // Hack to skip update gains
378 // Iterative deepening loop until requested to stop or target depth reached
379 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.maxDepth || depth <= Limits.maxDepth))
381 // Save last iteration's scores before first PV line is searched and all
382 // the move scores but the (new) PV are set to -VALUE_INFINITE.
383 for (size_t i = 0; i < RootMoves.size(); i++)
384 RootMoves[i].prevScore = RootMoves[i].score;
386 prevBestMoveChanges = BestMoveChanges;
389 // MultiPV loop. We perform a full root search for each PV line
390 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
392 // Set aspiration window default width
393 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
396 alpha = RootMoves[PVIdx].prevScore - delta;
397 beta = RootMoves[PVIdx].prevScore + delta;
401 alpha = -VALUE_INFINITE;
402 beta = VALUE_INFINITE;
405 // Start with a small aspiration window and, in case of fail high/low,
406 // research with bigger window until not failing high/low anymore.
408 // Search starts from ss+1 to allow referencing (ss-1). This is
409 // needed by update gains and ss copy when splitting at Root.
410 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
412 // Bring to front the best move. It is critical that sorting is
413 // done with a stable algorithm because all the values but the first
414 // and eventually the new best one are set to -VALUE_INFINITE and
415 // we want to keep the same order for all the moves but the new
416 // PV that goes to the front. Note that in case of MultiPV search
417 // the already searched PV lines are preserved.
418 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
420 // In case we have found an exact score and we are going to leave
421 // the fail high/low loop then reorder the PV moves, otherwise
422 // leave the last PV move in its position so to be searched again.
423 // Of course this is needed only in MultiPV search.
424 if (PVIdx && bestValue > alpha && bestValue < beta)
425 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
427 // Write PV back to transposition table in case the relevant
428 // entries have been overwritten during the search.
429 for (size_t i = 0; i <= PVIdx; i++)
430 RootMoves[i].insert_pv_in_tt(pos);
432 // If search has been stopped exit the aspiration window loop.
433 // Sorting and writing PV back to TT is safe becuase RootMoves
434 // is still valid, although refers to previous iteration.
438 // Send full PV info to GUI if we are going to leave the loop or
439 // if we have a fail high/low and we are deep in the search.
440 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
441 pv_info_to_uci(pos, depth, alpha, beta);
443 // In case of failing high/low increase aspiration window and
444 // research, otherwise exit the fail high/low loop.
445 if (bestValue >= beta)
450 else if (bestValue <= alpha)
452 Signals.failedLowAtRoot = true;
453 Signals.stopOnPonderhit = false;
461 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
463 } while (abs(bestValue) < VALUE_KNOWN_WIN);
466 // Skills: Do we need to pick now the best move ?
467 if (SkillLevelEnabled && depth == 1 + SkillLevel)
468 skillBest = do_skill_level();
470 if (Options["Use Search Log"])
471 pv_info_to_log(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]);
473 // Filter out startup noise when monitoring best move stability
474 if (depth > 2 && BestMoveChanges)
475 bestMoveNeverChanged = false;
477 // Do we have time for the next iteration? Can we stop searching now?
478 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
480 bool stop = false; // Local variable, not the volatile Signals.stop
482 // Take in account some extra time if the best move has changed
483 if (depth > 4 && depth < 50)
484 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
486 // Stop search if most of available time is already consumed. We
487 // probably don't have enough time to search the first move at the
488 // next iteration anyway.
489 if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
492 // Stop search early if one move seems to be much better than others
495 && ( (bestMoveNeverChanged && pos.captured_piece_type())
496 || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
498 Value rBeta = bestValue - EasyMoveMargin;
499 (ss+1)->excludedMove = RootMoves[0].pv[0];
500 (ss+1)->skipNullMove = true;
501 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
502 (ss+1)->skipNullMove = false;
503 (ss+1)->excludedMove = MOVE_NONE;
511 // If we are allowed to ponder do not stop the search now but
512 // keep pondering until GUI sends "ponderhit" or "stop".
514 Signals.stopOnPonderhit = true;
521 // When using skills swap best PV line with the sub-optimal one
522 if (SkillLevelEnabled)
524 if (skillBest == MOVE_NONE) // Still unassigned ?
525 skillBest = do_skill_level();
527 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
532 // search<>() is the main search function for both PV and non-PV nodes and for
533 // normal and SplitPoint nodes. When called just after a split point the search
534 // is simpler because we have already probed the hash table, done a null move
535 // search, and searched the first move before splitting, we don't have to repeat
536 // all this work again. We also don't need to store anything to the hash table
537 // here: This is taken care of after we return from the split point.
539 template <NodeType NT>
540 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
542 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
543 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
544 const bool RootNode = (NT == Root || NT == SplitPointRoot);
546 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
547 assert((alpha == beta - 1) || PvNode);
548 assert(depth > DEPTH_ZERO);
549 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
551 Move movesSearched[MAX_MOVES];
555 Move ttMove, move, excludedMove, threatMove;
558 Value bestValue, value, oldAlpha;
559 Value refinedValue, nullValue, futilityBase, futilityValue;
560 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
561 bool captureOrPromotion, dangerous, doFullDepthSearch;
562 int moveCount = 0, playedMoveCount = 0;
563 Thread& thread = Threads[pos.thread()];
564 SplitPoint* sp = NULL;
566 refinedValue = bestValue = value = -VALUE_INFINITE;
568 inCheck = pos.in_check();
569 ss->ply = (ss-1)->ply + 1;
571 // Used to send selDepth info to GUI
572 if (PvNode && thread.maxPly < ss->ply)
573 thread.maxPly = ss->ply;
575 // Step 1. Initialize node
579 ttMove = excludedMove = MOVE_NONE;
581 threatMove = sp->threatMove;
582 bestValue = sp->bestValue;
583 moveCount = sp->moveCount; // Lock must be held here
585 assert(bestValue > -VALUE_INFINITE && moveCount > 0);
587 goto split_point_start;
591 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
592 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
593 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
597 // Step 2. Check for aborted search and immediate draw
598 // Enforce node limit here. FIXME: This only works with 1 search thread.
599 if (Limits.maxNodes && pos.nodes_searched() >= Limits.maxNodes)
603 || pos.is_draw<false>()
604 || ss->ply > MAX_PLY) && !RootNode)
607 // Step 3. Mate distance pruning. Even if we mate at the next move our score
608 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
609 // a shorter mate was found upward in the tree then there is no need to search
610 // further, we will never beat current alpha. Same logic but with reversed signs
611 // applies also in the opposite condition of being mated instead of giving mate,
612 // in this case return a fail-high score.
615 alpha = std::max(mated_in(ss->ply), alpha);
616 beta = std::min(mate_in(ss->ply+1), beta);
621 // Step 4. Transposition table lookup
622 // We don't want the score of a partial search to overwrite a previous full search
623 // TT value, so we use a different position key in case of an excluded move.
624 excludedMove = ss->excludedMove;
625 posKey = excludedMove ? pos.exclusion_key() : pos.key();
626 tte = TT.probe(posKey);
627 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
629 // At PV nodes we check for exact scores, while at non-PV nodes we check for
630 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
631 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
632 // we should also update RootMoveList to avoid bogus output.
633 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
634 : can_return_tt(tte, depth, beta, ss->ply)))
637 ss->bestMove = move = ttMove; // Can be MOVE_NONE
638 value = value_from_tt(tte->value(), ss->ply);
642 && !pos.is_capture_or_promotion(move)
643 && move != ss->killers[0])
645 ss->killers[1] = ss->killers[0];
646 ss->killers[0] = move;
651 // Step 5. Evaluate the position statically and update parent's gain statistics
653 ss->eval = ss->evalMargin = VALUE_NONE;
656 assert(tte->static_value() != VALUE_NONE);
658 ss->eval = tte->static_value();
659 ss->evalMargin = tte->static_value_margin();
660 refinedValue = refine_eval(tte, ss->eval, ss->ply);
664 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
665 TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
668 // Update gain for the parent non-capture move given the static position
669 // evaluation before and after the move.
670 if ( (move = (ss-1)->currentMove) != MOVE_NULL
671 && (ss-1)->eval != VALUE_NONE
672 && ss->eval != VALUE_NONE
673 && !pos.captured_piece_type()
674 && !is_special(move))
676 Square to = to_sq(move);
677 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
680 // Step 6. Razoring (is omitted in PV nodes)
682 && depth < RazorDepth
684 && refinedValue + razor_margin(depth) < beta
685 && ttMove == MOVE_NONE
686 && abs(beta) < VALUE_MATE_IN_MAX_PLY
687 && !pos.has_pawn_on_7th(pos.side_to_move()))
689 Value rbeta = beta - razor_margin(depth);
690 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
692 // Logically we should return (v + razor_margin(depth)), but
693 // surprisingly this did slightly weaker in tests.
697 // Step 7. Static null move pruning (is omitted in PV nodes)
698 // We're betting that the opponent doesn't have a move that will reduce
699 // the score by more than futility_margin(depth) if we do a null move.
702 && depth < RazorDepth
704 && refinedValue - futility_margin(depth, 0) >= beta
705 && abs(beta) < VALUE_MATE_IN_MAX_PLY
706 && pos.non_pawn_material(pos.side_to_move()))
707 return refinedValue - futility_margin(depth, 0);
709 // Step 8. Null move search with verification search (is omitted in PV nodes)
714 && refinedValue >= beta
715 && abs(beta) < VALUE_MATE_IN_MAX_PLY
716 && pos.non_pawn_material(pos.side_to_move()))
718 ss->currentMove = MOVE_NULL;
720 // Null move dynamic reduction based on depth
721 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
723 // Null move dynamic reduction based on value
724 if (refinedValue - PawnValueMidgame > beta)
727 pos.do_null_move<true>(st);
728 (ss+1)->skipNullMove = true;
729 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
730 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
731 (ss+1)->skipNullMove = false;
732 pos.do_null_move<false>(st);
734 if (nullValue >= beta)
736 // Do not return unproven mate scores
737 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
740 if (depth < 6 * ONE_PLY)
743 // Do verification search at high depths
744 ss->skipNullMove = true;
745 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
746 ss->skipNullMove = false;
753 // The null move failed low, which means that we may be faced with
754 // some kind of threat. If the previous move was reduced, check if
755 // the move that refuted the null move was somehow connected to the
756 // move which was reduced. If a connection is found, return a fail
757 // low score (which will cause the reduced move to fail high in the
758 // parent node, which will trigger a re-search with full depth).
759 threatMove = (ss+1)->bestMove;
761 if ( depth < ThreatDepth
763 && threatMove != MOVE_NONE
764 && connected_moves(pos, (ss-1)->currentMove, threatMove))
769 // Step 9. ProbCut (is omitted in PV nodes)
770 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
771 // and a reduced search returns a value much above beta, we can (almost) safely
772 // prune the previous move.
774 && depth >= RazorDepth + ONE_PLY
777 && excludedMove == MOVE_NONE
778 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
780 Value rbeta = beta + 200;
781 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
783 assert(rdepth >= ONE_PLY);
784 assert((ss-1)->currentMove != MOVE_NONE);
786 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
789 while ((move = mp.next_move()) != MOVE_NONE)
790 if (pos.pl_move_is_legal(move, ci.pinned))
792 ss->currentMove = move;
793 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
794 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
801 // Step 10. Internal iterative deepening
802 if ( depth >= IIDDepth[PvNode]
803 && ttMove == MOVE_NONE
804 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
806 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
808 ss->skipNullMove = true;
809 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
810 ss->skipNullMove = false;
812 tte = TT.probe(posKey);
813 ttMove = tte ? tte->move() : MOVE_NONE;
816 split_point_start: // At split points actual search starts from here
818 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
820 ss->bestMove = MOVE_NONE;
821 futilityBase = ss->eval + ss->evalMargin;
822 singularExtensionNode = !RootNode
824 && depth >= SingularExtensionDepth[PvNode]
825 && ttMove != MOVE_NONE
826 && !excludedMove // Recursive singular search is not allowed
827 && (tte->type() & BOUND_LOWER)
828 && tte->depth() >= depth - 3 * ONE_PLY;
830 // Step 11. Loop through moves
831 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
832 while ( bestValue < beta
833 && (move = mp.next_move()) != MOVE_NONE
834 && !thread.cutoff_occurred()
839 if (move == excludedMove)
842 // At root obey the "searchmoves" option and skip moves not listed in Root
843 // Move List, as a consequence any illegal move is also skipped. In MultiPV
844 // mode we also skip PV moves which have been already searched.
845 if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
848 // At PV and SpNode nodes we want all moves to be legal since the beginning
849 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
854 moveCount = ++sp->moveCount;
855 lock_release(sp->lock);
862 Signals.firstRootMove = (moveCount == 1);
864 if (pos.thread() == 0 && elapsed_time() > 2000)
865 cout << "info depth " << depth / ONE_PLY
866 << " currmove " << move_to_uci(move, Chess960)
867 << " currmovenumber " << moveCount + PVIdx << endl;
870 isPvMove = (PvNode && moveCount <= 1);
871 captureOrPromotion = pos.is_capture_or_promotion(move);
872 givesCheck = pos.move_gives_check(move, ci);
873 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
876 // Step 12. Extend checks and, in PV nodes, also dangerous moves
877 if (PvNode && dangerous)
880 else if (givesCheck && pos.see_sign(move) >= 0)
881 ext = PvNode ? ONE_PLY : ONE_PLY / 2;
883 // Singular extension search. If all moves but one fail low on a search of
884 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
885 // is singular and should be extended. To verify this we do a reduced search
886 // on all the other moves but the ttMove, if result is lower than ttValue minus
887 // a margin then we extend ttMove.
888 if ( singularExtensionNode
891 && pos.pl_move_is_legal(move, ci.pinned))
893 Value ttValue = value_from_tt(tte->value(), ss->ply);
895 if (abs(ttValue) < VALUE_KNOWN_WIN)
897 Value rBeta = ttValue - int(depth);
898 ss->excludedMove = move;
899 ss->skipNullMove = true;
900 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
901 ss->skipNullMove = false;
902 ss->excludedMove = MOVE_NONE;
903 ss->bestMove = MOVE_NONE;
909 // Update current move (this must be done after singular extension search)
910 newDepth = depth - ONE_PLY + ext;
912 // Step 13. Futility pruning (is omitted in PV nodes)
914 && !captureOrPromotion
919 && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
921 // Move count based pruning
922 if ( moveCount >= futility_move_count(depth)
923 && (!threatMove || !connected_threat(pos, move, threatMove)))
931 // Value based pruning
932 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
933 // but fixing this made program slightly weaker.
934 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
935 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
936 + H.gain(pos.piece_moved(move), to_sq(move));
938 if (futilityValue < beta)
946 // Prune moves with negative SEE at low depths
947 if ( predictedDepth < 2 * ONE_PLY
948 && pos.see_sign(move) < 0)
957 // Check for legality only before to do the move
958 if (!pos.pl_move_is_legal(move, ci.pinned))
964 ss->currentMove = move;
965 if (!SpNode && !captureOrPromotion)
966 movesSearched[playedMoveCount++] = move;
968 // Step 14. Make the move
969 pos.do_move(move, st, ci, givesCheck);
971 // Step 15. Reduced depth search (LMR). If the move fails high will be
972 // re-searched at full depth.
973 if ( depth > 3 * ONE_PLY
975 && !captureOrPromotion
978 && ss->killers[0] != move
979 && ss->killers[1] != move)
981 ss->reduction = reduction<PvNode>(depth, moveCount);
982 Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
983 alpha = SpNode ? sp->alpha : alpha;
985 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
987 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
988 ss->reduction = DEPTH_ZERO;
991 doFullDepthSearch = !isPvMove;
993 // Step 16. Full depth search, when LMR is skipped or fails high
994 if (doFullDepthSearch)
996 alpha = SpNode ? sp->alpha : alpha;
997 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
998 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1001 // Only for PV nodes do a full PV search on the first move or after a fail
1002 // high, in the latter case search only if value < beta, otherwise let the
1003 // parent node to fail low with value <= alpha and to try another move.
1004 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1005 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1006 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1008 // Step 17. Undo move
1009 pos.undo_move(move);
1011 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1013 // Step 18. Check for new best move
1016 lock_grab(sp->lock);
1017 bestValue = sp->bestValue;
1021 // Finished searching the move. If Signals.stop is true, the search
1022 // was aborted because the user interrupted the search or because we
1023 // ran out of time. In this case, the return value of the search cannot
1024 // be trusted, and we don't update the best move and/or PV.
1025 if (RootNode && !Signals.stop)
1027 RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1029 // PV move or new best move ?
1030 if (isPvMove || value > alpha)
1033 rm.extract_pv_from_tt(pos);
1035 // We record how often the best move has been changed in each
1036 // iteration. This information is used for time management: When
1037 // the best move changes frequently, we allocate some more time.
1038 if (!isPvMove && MultiPV == 1)
1042 // All other moves but the PV are set to the lowest value, this
1043 // is not a problem when sorting becuase sort is stable and move
1044 // position in the list is preserved, just the PV is pushed up.
1045 rm.score = -VALUE_INFINITE;
1049 if (value > bestValue)
1052 ss->bestMove = move;
1056 && value < beta) // We want always alpha < beta
1059 if (SpNode && !thread.cutoff_occurred())
1061 sp->bestValue = value;
1062 sp->ss->bestMove = move;
1064 sp->is_betaCutoff = (value >= beta);
1068 // Step 19. Check for split
1070 && depth >= Threads.min_split_depth()
1072 && Threads.available_slave_exists(pos.thread())
1074 && !thread.cutoff_occurred())
1075 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1076 threatMove, moveCount, &mp, NT);
1079 // Step 20. Check for mate and stalemate
1080 // All legal moves have been searched and if there are no legal moves, it
1081 // must be mate or stalemate. Note that we can have a false positive in
1082 // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1083 // harmless because return value is discarded anyhow in the parent nodes.
1084 // If we are in a singular extension search then return a fail low score.
1086 return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1088 // If we have pruned all the moves without searching return a fail-low score
1089 if (bestValue == -VALUE_INFINITE)
1091 assert(!playedMoveCount);
1096 // Step 21. Update tables
1097 // Update transposition table entry, killers and history
1098 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1100 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1101 bt = bestValue <= oldAlpha ? BOUND_UPPER
1102 : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1104 TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);
1106 // Update killers and history for non capture cut-off moves
1107 if ( bestValue >= beta
1108 && !pos.is_capture_or_promotion(move)
1111 if (move != ss->killers[0])
1113 ss->killers[1] = ss->killers[0];
1114 ss->killers[0] = move;
1117 // Increase history value of the cut-off move
1118 Value bonus = Value(int(depth) * int(depth));
1119 H.add(pos.piece_moved(move), to_sq(move), bonus);
1121 // Decrease history of all the other played non-capture moves
1122 for (int i = 0; i < playedMoveCount - 1; i++)
1124 Move m = movesSearched[i];
1125 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1130 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1136 // qsearch() is the quiescence search function, which is called by the main
1137 // search function when the remaining depth is zero (or, to be more precise,
1138 // less than ONE_PLY).
1140 template <NodeType NT>
1141 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1143 const bool PvNode = (NT == PV);
1145 assert(NT == PV || NT == NonPV);
1146 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1147 assert((alpha == beta - 1) || PvNode);
1148 assert(depth <= DEPTH_ZERO);
1149 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1153 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1154 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1158 Value oldAlpha = alpha;
1160 ss->bestMove = ss->currentMove = MOVE_NONE;
1161 ss->ply = (ss-1)->ply + 1;
1163 // Check for an instant draw or maximum ply reached
1164 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1167 // Decide whether or not to include checks, this fixes also the type of
1168 // TT entry depth that we are going to use. Note that in qsearch we use
1169 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1170 inCheck = pos.in_check();
1171 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1173 // Transposition table lookup. At PV nodes, we don't use the TT for
1174 // pruning, but only for move ordering.
1175 tte = TT.probe(pos.key());
1176 ttMove = (tte ? tte->move() : MOVE_NONE);
1178 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1180 ss->bestMove = ttMove; // Can be MOVE_NONE
1181 return value_from_tt(tte->value(), ss->ply);
1184 // Evaluate the position statically
1187 bestValue = futilityBase = -VALUE_INFINITE;
1188 ss->eval = evalMargin = VALUE_NONE;
1189 enoughMaterial = false;
1195 assert(tte->static_value() != VALUE_NONE);
1197 evalMargin = tte->static_value_margin();
1198 ss->eval = bestValue = tte->static_value();
1201 ss->eval = bestValue = evaluate(pos, evalMargin);
1203 // Stand pat. Return immediately if static value is at least beta
1204 if (bestValue >= beta)
1207 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1212 if (PvNode && bestValue > alpha)
1215 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1216 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1219 // Initialize a MovePicker object for the current position, and prepare
1220 // to search the moves. Because the depth is <= 0 here, only captures,
1221 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1223 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1226 // Loop through the moves until no moves remain or a beta cutoff occurs
1227 while ( bestValue < beta
1228 && (move = mp.next_move()) != MOVE_NONE)
1230 assert(is_ok(move));
1232 givesCheck = pos.move_gives_check(move, ci);
1240 && !is_promotion(move)
1241 && !pos.is_passed_pawn_push(move))
1243 futilityValue = futilityBase
1244 + PieceValueEndgame[pos.piece_on(to_sq(move))]
1245 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1247 if (futilityValue < beta)
1249 if (futilityValue > bestValue)
1250 bestValue = futilityValue;
1255 // Prune moves with negative or equal SEE
1256 if ( futilityBase < beta
1257 && depth < DEPTH_ZERO
1258 && pos.see(move) <= 0)
1262 // Detect non-capture evasions that are candidate to be pruned
1263 evasionPrunable = !PvNode
1265 && bestValue > VALUE_MATED_IN_MAX_PLY
1266 && !pos.is_capture(move)
1267 && !pos.can_castle(pos.side_to_move());
1269 // Don't search moves with negative SEE values
1271 && (!inCheck || evasionPrunable)
1273 && !is_promotion(move)
1274 && pos.see_sign(move) < 0)
1277 // Don't search useless checks
1282 && !pos.is_capture_or_promotion(move)
1283 && ss->eval + PawnValueMidgame / 4 < beta
1284 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1286 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1287 bestValue = ss->eval + PawnValueMidgame / 4;
1292 // Check for legality only before to do the move
1293 if (!pos.pl_move_is_legal(move, ci.pinned))
1296 ss->currentMove = move;
1298 // Make and search the move
1299 pos.do_move(move, st, ci, givesCheck);
1300 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1301 pos.undo_move(move);
1303 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1306 if (value > bestValue)
1309 ss->bestMove = move;
1313 && value < beta) // We want always alpha < beta
1318 // All legal moves have been searched. A special case: If we're in check
1319 // and no legal moves were found, it is checkmate.
1320 if (inCheck && bestValue == -VALUE_INFINITE)
1321 return mated_in(ss->ply); // Plies to mate from the root
1323 // Update transposition table
1324 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1325 bt = bestValue <= oldAlpha ? BOUND_UPPER
1326 : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1328 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1330 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1336 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1337 // bestValue is updated only when returning false because in that case move
1340 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1342 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1343 Square from, to, ksq, victimSq;
1346 Value futilityValue, bv = *bestValue;
1348 from = from_sq(move);
1350 them = ~pos.side_to_move();
1351 ksq = pos.king_square(them);
1352 kingAtt = pos.attacks_from<KING>(ksq);
1353 pc = pos.piece_on(from);
1355 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1356 oldAtt = pos.attacks_from(pc, from, occ);
1357 newAtt = pos.attacks_from(pc, to, occ);
1359 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1360 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1362 if (!(b && (b & (b - 1))))
1365 // Rule 2. Queen contact check is very dangerous
1366 if ( type_of(pc) == QUEEN
1367 && bit_is_set(kingAtt, to))
1370 // Rule 3. Creating new double threats with checks
1371 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1375 victimSq = pop_1st_bit(&b);
1376 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1378 // Note that here we generate illegal "double move"!
1379 if ( futilityValue >= beta
1380 && pos.see_sign(make_move(from, victimSq)) >= 0)
1383 if (futilityValue > bv)
1387 // Update bestValue only if check is not dangerous (because we will prune the move)
1393 // connected_moves() tests whether two moves are 'connected' in the sense
1394 // that the first move somehow made the second move possible (for instance
1395 // if the moving piece is the same in both moves). The first move is assumed
1396 // to be the move that was made to reach the current position, while the
1397 // second move is assumed to be a move from the current position.
1399 bool connected_moves(const Position& pos, Move m1, Move m2) {
1401 Square f1, t1, f2, t2;
1408 // Case 1: The moving piece is the same in both moves
1414 // Case 2: The destination square for m2 was vacated by m1
1420 // Case 3: Moving through the vacated square
1421 p2 = pos.piece_on(f2);
1422 if ( piece_is_slider(p2)
1423 && bit_is_set(squares_between(f2, t2), f1))
1426 // Case 4: The destination square for m2 is defended by the moving piece in m1
1427 p1 = pos.piece_on(t1);
1428 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1431 // Case 5: Discovered check, checking piece is the piece moved in m1
1432 ksq = pos.king_square(pos.side_to_move());
1433 if ( piece_is_slider(p1)
1434 && bit_is_set(squares_between(t1, ksq), f2))
1436 Bitboard occ = pos.occupied_squares();
1437 clear_bit(&occ, f2);
1438 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1445 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1446 // "plies to mate from the current position". Non-mate scores are unchanged.
1447 // The function is called before storing a value to the transposition table.
1449 Value value_to_tt(Value v, int ply) {
1451 if (v >= VALUE_MATE_IN_MAX_PLY)
1454 if (v <= VALUE_MATED_IN_MAX_PLY)
1461 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1462 // from the transposition table (where refers to the plies to mate/be mated
1463 // from current position) to "plies to mate/be mated from the root".
1465 Value value_from_tt(Value v, int ply) {
1467 if (v >= VALUE_MATE_IN_MAX_PLY)
1470 if (v <= VALUE_MATED_IN_MAX_PLY)
1477 // connected_threat() tests whether it is safe to forward prune a move or if
1478 // is somehow connected to the threat move returned by null search.
1480 bool connected_threat(const Position& pos, Move m, Move threat) {
1483 assert(is_ok(threat));
1484 assert(!pos.is_capture_or_promotion(m));
1485 assert(!pos.is_passed_pawn_push(m));
1487 Square mfrom, mto, tfrom, tto;
1491 tfrom = from_sq(threat);
1492 tto = to_sq(threat);
1494 // Case 1: Don't prune moves which move the threatened piece
1498 // Case 2: If the threatened piece has value less than or equal to the
1499 // value of the threatening piece, don't prune moves which defend it.
1500 if ( pos.is_capture(threat)
1501 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1502 || type_of(pos.piece_on(tfrom)) == KING)
1503 && pos.move_attacks_square(m, tto))
1506 // Case 3: If the moving piece in the threatened move is a slider, don't
1507 // prune safe moves which block its ray.
1508 if ( piece_is_slider(pos.piece_on(tfrom))
1509 && bit_is_set(squares_between(tfrom, tto), mto)
1510 && pos.see_sign(m) >= 0)
1517 // can_return_tt() returns true if a transposition table score can be used to
1518 // cut-off at a given point in search.
1520 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1522 Value v = value_from_tt(tte->value(), ply);
1524 return ( tte->depth() >= depth
1525 || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1526 || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1528 && ( ((tte->type() & BOUND_LOWER) && v >= beta)
1529 || ((tte->type() & BOUND_UPPER) && v < beta));
1533 // refine_eval() returns the transposition table score if possible, otherwise
1534 // falls back on static position evaluation.
1536 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1540 Value v = value_from_tt(tte->value(), ply);
1542 if ( ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1543 || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1550 // current_search_time() returns the number of milliseconds which have passed
1551 // since the beginning of the current search.
1553 int elapsed_time(bool reset) {
1555 static int searchStartTime;
1558 searchStartTime = system_time();
1560 return system_time() - searchStartTime;
1564 // score_to_uci() converts a value to a string suitable for use with the UCI
1565 // protocol specifications:
1567 // cp <x> The score from the engine's point of view in centipawns.
1568 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1569 // use negative values for y.
1571 string score_to_uci(Value v, Value alpha, Value beta) {
1573 std::stringstream s;
1575 if (abs(v) < VALUE_MATE_IN_MAX_PLY)
1576 s << "cp " << v * 100 / int(PawnValueMidgame);
1578 s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1580 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1586 // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1587 // the PV lines also if are still to be searched and so refer to the previous
1590 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1592 int t = elapsed_time();
1595 for (int i = 0; i < Threads.size(); i++)
1596 if (Threads[i].maxPly > selDepth)
1597 selDepth = Threads[i].maxPly;
1599 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1601 bool updated = (i <= PVIdx);
1603 if (depth == 1 && !updated)
1606 int d = (updated ? depth : depth - 1);
1607 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1608 std::stringstream s;
1610 for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1611 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1613 cout << "info depth " << d
1614 << " seldepth " << selDepth
1615 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1616 << " nodes " << pos.nodes_searched()
1617 << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1619 << " multipv " << i + 1
1620 << " pv" << s.str() << endl;
1625 // pv_info_to_log() writes human-readable search information to the log file
1626 // (which is created when the UCI parameter "Use Search Log" is "true"). It
1627 // uses the two below helpers to pretty format time and score respectively.
1629 string time_to_string(int millisecs) {
1631 const int MSecMinute = 1000 * 60;
1632 const int MSecHour = 1000 * 60 * 60;
1634 int hours = millisecs / MSecHour;
1635 int minutes = (millisecs % MSecHour) / MSecMinute;
1636 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1638 std::stringstream s;
1643 s << std::setfill('0') << std::setw(2) << minutes << ':'
1644 << std::setw(2) << seconds;
1648 string score_to_string(Value v) {
1650 std::stringstream s;
1652 if (v >= VALUE_MATE_IN_MAX_PLY)
1653 s << "#" << (VALUE_MATE - v + 1) / 2;
1654 else if (v <= VALUE_MATED_IN_MAX_PLY)
1655 s << "-#" << (VALUE_MATE + v) / 2;
1657 s << std::setprecision(2) << std::fixed << std::showpos
1658 << float(v) / PawnValueMidgame;
1663 void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1665 const int64_t K = 1000;
1666 const int64_t M = 1000000;
1668 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1670 string san, padding;
1672 std::stringstream s;
1674 s << std::setw(2) << depth
1675 << std::setw(8) << score_to_string(value)
1676 << std::setw(8) << time_to_string(time);
1678 if (pos.nodes_searched() < M)
1679 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1681 else if (pos.nodes_searched() < K * M)
1682 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1685 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1687 padding = string(s.str().length(), ' ');
1688 length = padding.length();
1690 while (*m != MOVE_NONE)
1692 san = move_to_san(pos, *m);
1694 if (length + san.length() > 80)
1696 s << "\n" + padding;
1697 length = padding.length();
1701 length += san.length() + 1;
1703 pos.do_move(*m++, *st++);
1707 pos.undo_move(*--m);
1709 Log l(Options["Search Log Filename"]);
1710 l << s.str() << endl;
1714 // When playing with strength handicap choose best move among the MultiPV set
1715 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1717 Move do_skill_level() {
1719 assert(MultiPV > 1);
1723 // PRNG sequence should be not deterministic
1724 for (int i = abs(system_time() % 50); i > 0; i--)
1725 rk.rand<unsigned>();
1727 // RootMoves are already sorted by score in descending order
1728 size_t size = std::min(MultiPV, RootMoves.size());
1729 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1730 int weakness = 120 - 2 * SkillLevel;
1731 int max_s = -VALUE_INFINITE;
1732 Move best = MOVE_NONE;
1734 // Choose best move. For each move score we add two terms both dependent on
1735 // weakness, one deterministic and bigger for weaker moves, and one random,
1736 // then we choose the move with the resulting highest score.
1737 for (size_t i = 0; i < size; i++)
1739 int s = RootMoves[i].score;
1741 // Don't allow crazy blunders even at very low skills
1742 if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1745 // This is our magic formula
1746 s += ( weakness * int(RootMoves[0].score - s)
1747 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1752 best = RootMoves[i].pv[0];
1761 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1762 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1763 /// allow to always have a ponder move even when we fail high at root, and a
1764 /// long PV to print that is important for position analysis.
1766 void RootMove::extract_pv_from_tt(Position& pos) {
1768 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1773 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1777 pos.do_move(m, *st++);
1779 while ( (tte = TT.probe(pos.key())) != NULL
1780 && tte->move() != MOVE_NONE
1781 && pos.is_pseudo_legal(tte->move())
1782 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1784 && (!pos.is_draw<false>() || ply < 2))
1786 pv.push_back(tte->move());
1787 pos.do_move(tte->move(), *st++);
1790 pv.push_back(MOVE_NONE);
1792 do pos.undo_move(pv[--ply]); while (ply);
1796 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1797 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1798 /// first, even if the old TT entries have been overwritten.
1800 void RootMove::insert_pv_in_tt(Position& pos) {
1802 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1805 Value v, m = VALUE_NONE;
1808 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1814 // Don't overwrite existing correct entries
1815 if (!tte || tte->move() != pv[ply])
1817 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1818 TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1820 pos.do_move(pv[ply], *st++);
1822 } while (pv[++ply] != MOVE_NONE);
1824 do pos.undo_move(pv[--ply]); while (ply);
1828 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1829 /// The parameter 'master_sp', if non-NULL, is a pointer to an active SplitPoint
1830 /// object for which the thread is the master.
1832 void Thread::idle_loop(SplitPoint* sp_master) {
1834 // If this thread is the master of a split point and all slaves have
1835 // finished their work at this split point, return from the idle loop.
1836 while (!sp_master || sp_master->slavesMask)
1838 // If we are not searching, wait for a condition to be signaled
1839 // instead of wasting CPU time polling for work.
1842 || (!is_searching && Threads.use_sleeping_threads()))
1850 // Grab the lock to avoid races with Thread::wake_up()
1851 lock_grab(sleepLock);
1853 // If we are master and all slaves have finished don't go to sleep
1854 if (sp_master && !sp_master->slavesMask)
1856 lock_release(sleepLock);
1860 // Do sleep after retesting sleep conditions under lock protection, in
1861 // particular we need to avoid a deadlock in case a master thread has,
1862 // in the meanwhile, allocated us and sent the wake_up() call before we
1863 // had the chance to grab the lock.
1864 if (do_sleep || !is_searching)
1865 cond_wait(sleepCond, sleepLock);
1867 lock_release(sleepLock);
1870 // If this thread has been assigned work, launch a search
1873 assert(!do_sleep && !do_exit);
1875 // Copy split point position and search stack and call search()
1876 Stack ss[MAX_PLY_PLUS_2];
1877 SplitPoint* sp = splitPoint;
1878 Position pos(*sp->pos, threadID);
1880 memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1883 lock_grab(sp->lock);
1885 if (sp->nodeType == Root)
1886 search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1887 else if (sp->nodeType == PV)
1888 search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1889 else if (sp->nodeType == NonPV)
1890 search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1894 assert(is_searching);
1896 // We return from search with lock held
1897 sp->slavesMask &= ~(1ULL << threadID);
1898 sp->nodes += pos.nodes_searched();
1899 lock_release(sp->lock);
1901 is_searching = false;
1903 // Wake up master thread so to allow it to return from the idle loop in
1904 // case we are the last slave of the split point.
1905 if ( Threads.use_sleeping_threads()
1906 && threadID != sp->master
1907 && !Threads[sp->master].is_searching)
1908 Threads[sp->master].wake_up();
1914 /// check_time() is called by the timer thread when the timer triggers. It is
1915 /// used to print debug info and, more important, to detect when we are out of
1916 /// available time and so stop the search.
1920 static int lastInfoTime;
1921 int e = elapsed_time();
1923 if (system_time() - lastInfoTime >= 1000 || !lastInfoTime)
1925 lastInfoTime = system_time();
1932 bool stillAtFirstMove = Signals.firstRootMove
1933 && !Signals.failedLowAtRoot
1934 && e > TimeMgr.available_time();
1936 bool noMoreTime = e > TimeMgr.maximum_time() - 2 * TimerResolution
1937 || stillAtFirstMove;
1939 if ( (Limits.use_time_management() && noMoreTime)
1940 || (Limits.maxTime && e >= Limits.maxTime))
1941 Signals.stop = true;