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/>.
39 #include "ucioption.h"
43 volatile SignalsType Signals;
45 std::vector<Move> SearchMoves;
46 Position RootPosition;
52 using namespace Search;
56 // Set to true to force running with one thread. Used for debugging
57 const bool FakeSplit = false;
59 // Different node types, used as template parameter
60 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
62 // RootMove struct is used for moves at the root of the tree. For each root
63 // move we store a score, a node count, and a PV (really a refutation in the
64 // case of moves which fail low). Score is normally set at -VALUE_INFINITE for
70 score = prevScore = -VALUE_INFINITE;
72 pv.push_back(MOVE_NONE);
75 bool operator<(const RootMove& m) const { return score < m.score; }
76 bool operator==(const Move& m) const { return pv[0] == m; }
78 void extract_pv_from_tt(Position& pos);
79 void insert_pv_in_tt(Position& pos);
89 // Lookup table to check if a Piece is a slider and its access function
90 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
91 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
93 // Maximum depth for razoring
94 const Depth RazorDepth = 4 * ONE_PLY;
96 // Dynamic razoring margin based on depth
97 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
99 // Maximum depth for use of dynamic threat detection when null move fails low
100 const Depth ThreatDepth = 5 * ONE_PLY;
102 // Minimum depth for use of internal iterative deepening
103 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
105 // At Non-PV nodes we do an internal iterative deepening search
106 // when the static evaluation is bigger then beta - IIDMargin.
107 const Value IIDMargin = Value(0x100);
109 // Minimum depth for use of singular extension
110 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
112 // Futility margin for quiescence search
113 const Value FutilityMarginQS = Value(0x80);
115 // Futility lookup tables (initialized at startup) and their access functions
116 Value FutilityMargins[16][64]; // [depth][moveNumber]
117 int FutilityMoveCounts[32]; // [depth]
119 inline Value futility_margin(Depth d, int mn) {
121 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
122 : 2 * VALUE_INFINITE;
125 inline int futility_move_count(Depth d) {
127 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
130 // Reduction lookup tables (initialized at startup) and their access function
131 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
133 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
135 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
138 // Easy move margin. An easy move candidate must be at least this much
139 // better than the second best move.
140 const Value EasyMoveMargin = Value(0x150);
143 /// Namespace variables
145 std::vector<RootMove> RootMoves;
146 size_t MultiPV, UCIMultiPV, PVIdx;
150 bool SkillLevelEnabled, Chess960;
156 template <NodeType NT>
157 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
159 template <NodeType NT>
160 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
162 void id_loop(Position& pos);
163 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
164 bool connected_moves(const Position& pos, Move m1, Move m2);
165 Value value_to_tt(Value v, int ply);
166 Value value_from_tt(Value v, int ply);
167 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
168 bool connected_threat(const Position& pos, Move m, Move threat);
169 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
170 Move do_skill_level();
171 int elapsed_time(bool reset = false);
172 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
173 void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
174 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
176 // MovePickerExt class template extends MovePicker and allows to choose at
177 // compile time the proper moves source according to the type of node. In the
178 // default case we simply create and use a standard MovePicker object.
179 template<bool SpNode> struct MovePickerExt : public MovePicker {
181 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
182 : MovePicker(p, ttm, d, h, ss, b) {}
185 // In case of a SpNode we use split point's shared MovePicker object as moves source
186 template<> struct MovePickerExt<true> : public MovePicker {
188 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
189 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
191 Move next_move() { return mp->next_move(); }
195 // is_dangerous() checks whether a move belongs to some classes of known
196 // 'dangerous' moves so that we avoid to prune it.
197 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
199 // Test for a pawn pushed to 7th or a passed pawn move
200 if (type_of(pos.piece_on(from_sq(m))) == PAWN)
202 Color c = pos.side_to_move();
203 if ( relative_rank(c, to_sq(m)) == RANK_7
204 || pos.pawn_is_passed(c, to_sq(m)))
208 // Test for a capture that triggers a pawn endgame
209 if ( captureOrPromotion
210 && type_of(pos.piece_on(to_sq(m))) != PAWN
211 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
212 - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO)
222 /// Search::init() is called during startup to initialize various lookup tables
224 void Search::init() {
226 int d; // depth (ONE_PLY == 2)
227 int hd; // half depth (ONE_PLY == 1)
230 // Init reductions array
231 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
233 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
234 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
235 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
236 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
239 // Init futility margins array
240 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
241 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
243 // Init futility move count array
244 for (d = 0; d < 32; d++)
245 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
249 /// Search::perft() is our utility to verify move generation. All the leaf nodes
250 /// up to the given depth are generated and counted and the sum returned.
252 int64_t Search::perft(Position& pos, Depth depth) {
257 MoveList<MV_LEGAL> ml(pos);
259 // At the last ply just return the number of moves (leaf nodes)
260 if (depth == ONE_PLY)
264 for ( ; !ml.end(); ++ml)
266 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
267 cnt += perft(pos, depth - ONE_PLY);
268 pos.undo_move(ml.move());
274 /// Search::think() is the external interface to Stockfish's search, and is
275 /// called by the main thread when the program receives the UCI 'go' command. It
276 /// searches from RootPosition and at the end prints the "bestmove" to output.
278 void Search::think() {
280 static Book book; // Defined static to initialize the PRNG only once
282 Position& pos = RootPosition;
283 Chess960 = pos.is_chess960();
285 TimeMgr.init(Limits, pos.startpos_ply_counter());
290 // Populate RootMoves with all the legal moves (default) or, if a SearchMoves
291 // is given, with the subset of legal moves to search.
292 for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
293 if (SearchMoves.empty() || count(SearchMoves.begin(), SearchMoves.end(), ml.move()))
294 RootMoves.push_back(RootMove(ml.move()));
296 if (Options["OwnBook"])
298 Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
300 if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
302 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
307 // Read UCI options: GUI could change UCI parameters during the game
308 read_evaluation_uci_options(pos.side_to_move());
309 Threads.read_uci_options();
311 TT.set_size(Options["Hash"]);
312 if (Options["Clear Hash"])
314 Options["Clear Hash"] = false;
318 UCIMultiPV = Options["MultiPV"];
319 SkillLevel = Options["Skill Level"];
321 // Do we have to play with skill handicap? In this case enable MultiPV that
322 // we will use behind the scenes to retrieve a set of possible moves.
323 SkillLevelEnabled = (SkillLevel < 20);
324 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
326 if (Options["Use Search Log"])
328 Log log(Options["Search Log Filename"]);
329 log << "\nSearching: " << pos.to_fen()
330 << "\ninfinite: " << Limits.infinite
331 << " ponder: " << Limits.ponder
332 << " time: " << Limits.time
333 << " increment: " << Limits.increment
334 << " moves to go: " << Limits.movesToGo
338 for (int i = 0; i < Threads.size(); i++)
340 Threads[i].maxPly = 0;
341 Threads[i].wake_up();
344 // Set best timer interval to avoid lagging under time pressure. Timer is
345 // used to check for remaining available thinking time.
346 if (TimeMgr.available_time())
347 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
349 Threads.set_timer(100);
351 // We're ready to start searching. Call the iterative deepening loop function
354 // Stop timer and send all the slaves to sleep, if not already sleeping
355 Threads.set_timer(0);
358 if (Options["Use Search Log"])
360 int e = elapsed_time();
362 Log log(Options["Search Log Filename"]);
363 log << "Nodes: " << pos.nodes_searched()
364 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
365 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
368 pos.do_move(RootMoves[0].pv[0], st);
369 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
370 pos.undo_move(RootMoves[0].pv[0]);
375 // When we reach max depth we arrive here even without a StopRequest, but if
376 // we are pondering or in infinite search, we shouldn't print the best move
377 // before we are told to do so.
378 if (!Signals.stop && (Limits.ponder || Limits.infinite))
379 Threads.wait_for_stop_or_ponderhit();
381 // Best move could be MOVE_NONE when searching on a stalemate position
382 cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
383 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
389 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
390 // with increasing depth until the allocated thinking time has been consumed,
391 // user stops the search, or the maximum search depth is reached.
393 void id_loop(Position& pos) {
395 Stack ss[MAX_PLY_PLUS_2];
396 int depth, prevBestMoveChanges;
397 Value bestValue, alpha, beta, delta;
398 bool bestMoveNeverChanged = true;
399 Move skillBest = MOVE_NONE;
401 memset(ss, 0, 4 * sizeof(Stack));
402 depth = BestMoveChanges = 0;
403 bestValue = delta = -VALUE_INFINITE;
404 ss->currentMove = MOVE_NULL; // Hack to skip update gains
406 // Handle the special case of a mated/stalemate position
407 if (RootMoves.empty())
409 cout << "info depth 0 score "
410 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
412 RootMoves.push_back(MOVE_NONE);
416 // Iterative deepening loop until requested to stop or target depth reached
417 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.maxDepth || depth <= Limits.maxDepth))
419 // Save last iteration's scores before first PV line is searched and all
420 // the move scores but the (new) PV are set to -VALUE_INFINITE.
421 for (size_t i = 0; i < RootMoves.size(); i++)
422 RootMoves[i].prevScore = RootMoves[i].score;
424 prevBestMoveChanges = BestMoveChanges;
427 // MultiPV loop. We perform a full root search for each PV line
428 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
430 // Set aspiration window default width
431 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
434 alpha = RootMoves[PVIdx].prevScore - delta;
435 beta = RootMoves[PVIdx].prevScore + delta;
439 alpha = -VALUE_INFINITE;
440 beta = VALUE_INFINITE;
443 // Start with a small aspiration window and, in case of fail high/low,
444 // research with bigger window until not failing high/low anymore.
446 // Search starts from ss+1 to allow referencing (ss-1). This is
447 // needed by update gains and ss copy when splitting at Root.
448 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
450 // Bring to front the best move. It is critical that sorting is
451 // done with a stable algorithm because all the values but the first
452 // and eventually the new best one are set to -VALUE_INFINITE and
453 // we want to keep the same order for all the moves but the new
454 // PV that goes to the front. Note that in case of MultiPV search
455 // the already searched PV lines are preserved.
456 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
458 // In case we have found an exact score and we are going to leave
459 // the fail high/low loop then reorder the PV moves, otherwise
460 // leave the last PV move in its position so to be searched again.
461 // Of course this is needed only in MultiPV search.
462 if (PVIdx && bestValue > alpha && bestValue < beta)
463 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
465 // Write PV back to transposition table in case the relevant
466 // entries have been overwritten during the search.
467 for (size_t i = 0; i <= PVIdx; i++)
468 RootMoves[i].insert_pv_in_tt(pos);
470 // If search has been stopped exit the aspiration window loop.
471 // Sorting and writing PV back to TT is safe becuase RootMoves
472 // is still valid, although refers to previous iteration.
476 // Send full PV info to GUI if we are going to leave the loop or
477 // if we have a fail high/low and we are deep in the search.
478 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
479 pv_info_to_uci(pos, depth, alpha, beta);
481 // In case of failing high/low increase aspiration window and
482 // research, otherwise exit the fail high/low loop.
483 if (bestValue >= beta)
488 else if (bestValue <= alpha)
490 Signals.failedLowAtRoot = true;
491 Signals.stopOnPonderhit = false;
499 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
501 } while (abs(bestValue) < VALUE_KNOWN_WIN);
504 // Skills: Do we need to pick now the best move ?
505 if (SkillLevelEnabled && depth == 1 + SkillLevel)
506 skillBest = do_skill_level();
508 if (Options["Use Search Log"])
509 pv_info_to_log(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]);
511 // Filter out startup noise when monitoring best move stability
512 if (depth > 2 && BestMoveChanges)
513 bestMoveNeverChanged = false;
515 // Do we have time for the next iteration? Can we stop searching now?
516 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
518 bool stop = false; // Local variable, not the volatile Signals.stop
520 // Take in account some extra time if the best move has changed
521 if (depth > 4 && depth < 50)
522 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
524 // Stop search if most of available time is already consumed. We
525 // probably don't have enough time to search the first move at the
526 // next iteration anyway.
527 if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
530 // Stop search early if one move seems to be much better than others
533 && ( bestMoveNeverChanged
534 || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
536 Value rBeta = bestValue - EasyMoveMargin;
537 (ss+1)->excludedMove = RootMoves[0].pv[0];
538 (ss+1)->skipNullMove = true;
539 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
540 (ss+1)->skipNullMove = false;
541 (ss+1)->excludedMove = MOVE_NONE;
549 // If we are allowed to ponder do not stop the search now but
550 // keep pondering until GUI sends "ponderhit" or "stop".
552 Signals.stopOnPonderhit = true;
559 // When using skills swap best PV line with the sub-optimal one
560 if (SkillLevelEnabled)
562 if (skillBest == MOVE_NONE) // Still unassigned ?
563 skillBest = do_skill_level();
565 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
570 // search<>() is the main search function for both PV and non-PV nodes and for
571 // normal and SplitPoint nodes. When called just after a split point the search
572 // is simpler because we have already probed the hash table, done a null move
573 // search, and searched the first move before splitting, we don't have to repeat
574 // all this work again. We also don't need to store anything to the hash table
575 // here: This is taken care of after we return from the split point.
577 template <NodeType NT>
578 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
580 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
581 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
582 const bool RootNode = (NT == Root || NT == SplitPointRoot);
584 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
585 assert(PvNode == (alpha != beta - 1));
586 assert(depth > DEPTH_ZERO);
587 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
589 Move movesSearched[MAX_MOVES];
593 Move ttMove, move, excludedMove, threatMove;
596 Value bestValue, value, oldAlpha;
597 Value refinedValue, nullValue, futilityBase, futilityValue;
598 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
599 bool captureOrPromotion, dangerous, doFullDepthSearch;
600 int moveCount = 0, playedMoveCount = 0;
601 Thread& thread = Threads[pos.thread()];
602 SplitPoint* sp = NULL;
604 refinedValue = bestValue = value = -VALUE_INFINITE;
606 inCheck = pos.in_check();
607 ss->ply = (ss-1)->ply + 1;
609 // Used to send selDepth info to GUI
610 if (PvNode && thread.maxPly < ss->ply)
611 thread.maxPly = ss->ply;
613 // Step 1. Initialize node
616 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
617 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
618 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
624 ttMove = excludedMove = MOVE_NONE;
625 threatMove = sp->threatMove;
626 goto split_point_start;
629 // Step 2. Check for aborted search and immediate draw
631 || pos.is_draw<false>()
632 || ss->ply > MAX_PLY) && !RootNode)
635 // Step 3. Mate distance pruning. Even if we mate at the next move our score
636 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
637 // a shorter mate was found upward in the tree then there is no need to search
638 // further, we will never beat current alpha. Same logic but with reversed signs
639 // applies also in the opposite condition of being mated instead of giving mate,
640 // in this case return a fail-high score.
643 alpha = std::max(mated_in(ss->ply), alpha);
644 beta = std::min(mate_in(ss->ply+1), beta);
649 // Step 4. Transposition table lookup
650 // We don't want the score of a partial search to overwrite a previous full search
651 // TT value, so we use a different position key in case of an excluded move.
652 excludedMove = ss->excludedMove;
653 posKey = excludedMove ? pos.exclusion_key() : pos.key();
654 tte = TT.probe(posKey);
655 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
657 // At PV nodes we check for exact scores, while at non-PV nodes we check for
658 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
659 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
660 // we should also update RootMoveList to avoid bogus output.
661 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
662 : can_return_tt(tte, depth, beta, ss->ply)))
665 ss->bestMove = move = ttMove; // Can be MOVE_NONE
666 value = value_from_tt(tte->value(), ss->ply);
670 && !pos.is_capture_or_promotion(move)
671 && move != ss->killers[0])
673 ss->killers[1] = ss->killers[0];
674 ss->killers[0] = move;
679 // Step 5. Evaluate the position statically and update parent's gain statistics
681 ss->eval = ss->evalMargin = VALUE_NONE;
684 assert(tte->static_value() != VALUE_NONE);
686 ss->eval = tte->static_value();
687 ss->evalMargin = tte->static_value_margin();
688 refinedValue = refine_eval(tte, ss->eval, ss->ply);
692 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
693 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
696 // Update gain for the parent non-capture move given the static position
697 // evaluation before and after the move.
698 if ( (move = (ss-1)->currentMove) != MOVE_NULL
699 && (ss-1)->eval != VALUE_NONE
700 && ss->eval != VALUE_NONE
701 && pos.captured_piece_type() == NO_PIECE_TYPE
702 && !is_special(move))
704 Square to = to_sq(move);
705 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
708 // Step 6. Razoring (is omitted in PV nodes)
710 && depth < RazorDepth
712 && refinedValue + razor_margin(depth) < beta
713 && ttMove == MOVE_NONE
714 && abs(beta) < VALUE_MATE_IN_MAX_PLY
715 && !pos.has_pawn_on_7th(pos.side_to_move()))
717 Value rbeta = beta - razor_margin(depth);
718 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
720 // Logically we should return (v + razor_margin(depth)), but
721 // surprisingly this did slightly weaker in tests.
725 // Step 7. Static null move pruning (is omitted in PV nodes)
726 // We're betting that the opponent doesn't have a move that will reduce
727 // the score by more than futility_margin(depth) if we do a null move.
730 && depth < RazorDepth
732 && refinedValue - futility_margin(depth, 0) >= beta
733 && abs(beta) < VALUE_MATE_IN_MAX_PLY
734 && pos.non_pawn_material(pos.side_to_move()))
735 return refinedValue - futility_margin(depth, 0);
737 // Step 8. Null move search with verification search (is omitted in PV nodes)
742 && refinedValue >= beta
743 && abs(beta) < VALUE_MATE_IN_MAX_PLY
744 && pos.non_pawn_material(pos.side_to_move()))
746 ss->currentMove = MOVE_NULL;
748 // Null move dynamic reduction based on depth
749 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
751 // Null move dynamic reduction based on value
752 if (refinedValue - PawnValueMidgame > beta)
755 pos.do_null_move<true>(st);
756 (ss+1)->skipNullMove = true;
757 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
758 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
759 (ss+1)->skipNullMove = false;
760 pos.do_null_move<false>(st);
762 if (nullValue >= beta)
764 // Do not return unproven mate scores
765 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
768 if (depth < 6 * ONE_PLY)
771 // Do verification search at high depths
772 ss->skipNullMove = true;
773 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
774 ss->skipNullMove = false;
781 // The null move failed low, which means that we may be faced with
782 // some kind of threat. If the previous move was reduced, check if
783 // the move that refuted the null move was somehow connected to the
784 // move which was reduced. If a connection is found, return a fail
785 // low score (which will cause the reduced move to fail high in the
786 // parent node, which will trigger a re-search with full depth).
787 threatMove = (ss+1)->bestMove;
789 if ( depth < ThreatDepth
791 && threatMove != MOVE_NONE
792 && connected_moves(pos, (ss-1)->currentMove, threatMove))
797 // Step 9. ProbCut (is omitted in PV nodes)
798 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
799 // and a reduced search returns a value much above beta, we can (almost) safely
800 // prune the previous move.
802 && depth >= RazorDepth + ONE_PLY
805 && excludedMove == MOVE_NONE
806 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
808 Value rbeta = beta + 200;
809 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
811 assert(rdepth >= ONE_PLY);
813 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
816 while ((move = mp.next_move()) != MOVE_NONE)
817 if (pos.pl_move_is_legal(move, ci.pinned))
819 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
820 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
827 // Step 10. Internal iterative deepening
828 if ( depth >= IIDDepth[PvNode]
829 && ttMove == MOVE_NONE
830 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
832 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
834 ss->skipNullMove = true;
835 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
836 ss->skipNullMove = false;
838 tte = TT.probe(posKey);
839 ttMove = tte ? tte->move() : MOVE_NONE;
842 split_point_start: // At split points actual search starts from here
844 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
846 ss->bestMove = MOVE_NONE;
847 futilityBase = ss->eval + ss->evalMargin;
848 singularExtensionNode = !RootNode
850 && depth >= SingularExtensionDepth[PvNode]
851 && ttMove != MOVE_NONE
852 && !excludedMove // Recursive singular search is not allowed
853 && (tte->type() & VALUE_TYPE_LOWER)
854 && tte->depth() >= depth - 3 * ONE_PLY;
857 lock_grab(&(sp->lock));
858 bestValue = sp->bestValue;
859 moveCount = sp->moveCount;
861 assert(bestValue > -VALUE_INFINITE && moveCount > 0);
864 // Step 11. Loop through moves
865 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
866 while ( bestValue < beta
867 && (move = mp.next_move()) != MOVE_NONE
868 && !thread.cutoff_occurred())
872 if (move == excludedMove)
875 // At root obey the "searchmoves" option and skip moves not listed in Root
876 // Move List, as a consequence any illegal move is also skipped. In MultiPV
877 // mode we also skip PV moves which have been already searched.
878 if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
881 // At PV and SpNode nodes we want all moves to be legal since the beginning
882 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
887 moveCount = ++sp->moveCount;
888 lock_release(&(sp->lock));
895 Signals.firstRootMove = (moveCount == 1);
897 if (pos.thread() == 0 && elapsed_time() > 2000)
898 cout << "info depth " << depth / ONE_PLY
899 << " currmove " << move_to_uci(move, Chess960)
900 << " currmovenumber " << moveCount + PVIdx << endl;
903 isPvMove = (PvNode && moveCount <= 1);
904 captureOrPromotion = pos.is_capture_or_promotion(move);
905 givesCheck = pos.move_gives_check(move, ci);
906 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
909 // Step 12. Extend checks and, in PV nodes, also dangerous moves
910 if (PvNode && dangerous)
913 else if (givesCheck && pos.see_sign(move) >= 0)
914 ext = PvNode ? ONE_PLY : ONE_PLY / 2;
916 // Singular extension search. If all moves but one fail low on a search of
917 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
918 // is singular and should be extended. To verify this we do a reduced search
919 // on all the other moves but the ttMove, if result is lower than ttValue minus
920 // a margin then we extend ttMove.
921 if ( singularExtensionNode
924 && pos.pl_move_is_legal(move, ci.pinned))
926 Value ttValue = value_from_tt(tte->value(), ss->ply);
928 if (abs(ttValue) < VALUE_KNOWN_WIN)
930 Value rBeta = ttValue - int(depth);
931 ss->excludedMove = move;
932 ss->skipNullMove = true;
933 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
934 ss->skipNullMove = false;
935 ss->excludedMove = MOVE_NONE;
936 ss->bestMove = MOVE_NONE;
942 // Update current move (this must be done after singular extension search)
943 newDepth = depth - ONE_PLY + ext;
945 // Step 13. Futility pruning (is omitted in PV nodes)
947 && !captureOrPromotion
952 && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
954 // Move count based pruning
955 if ( moveCount >= futility_move_count(depth)
956 && (!threatMove || !connected_threat(pos, move, threatMove)))
959 lock_grab(&(sp->lock));
964 // Value based pruning
965 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
966 // but fixing this made program slightly weaker.
967 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
968 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
969 + H.gain(pos.piece_on(from_sq(move)), to_sq(move));
971 if (futilityValue < beta)
974 lock_grab(&(sp->lock));
979 // Prune moves with negative SEE at low depths
980 if ( predictedDepth < 2 * ONE_PLY
981 && pos.see_sign(move) < 0)
984 lock_grab(&(sp->lock));
990 // Check for legality only before to do the move
991 if (!pos.pl_move_is_legal(move, ci.pinned))
997 ss->currentMove = move;
998 if (!SpNode && !captureOrPromotion)
999 movesSearched[playedMoveCount++] = move;
1001 // Step 14. Make the move
1002 pos.do_move(move, st, ci, givesCheck);
1004 // Step 15. Reduced depth search (LMR). If the move fails high will be
1005 // re-searched at full depth.
1006 if ( depth > 3 * ONE_PLY
1008 && !captureOrPromotion
1011 && ss->killers[0] != move
1012 && ss->killers[1] != move)
1014 ss->reduction = reduction<PvNode>(depth, moveCount);
1015 Depth d = newDepth - ss->reduction;
1016 alpha = SpNode ? sp->alpha : alpha;
1018 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1019 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1021 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1022 ss->reduction = DEPTH_ZERO;
1025 doFullDepthSearch = !isPvMove;
1027 // Step 16. Full depth search, when LMR is skipped or fails high
1028 if (doFullDepthSearch)
1030 alpha = SpNode ? sp->alpha : alpha;
1031 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1032 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1035 // Only for PV nodes do a full PV search on the first move or after a fail
1036 // high, in the latter case search only if value < beta, otherwise let the
1037 // parent node to fail low with value <= alpha and to try another move.
1038 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1039 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1040 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1042 // Step 17. Undo move
1043 pos.undo_move(move);
1045 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1047 // Step 18. Check for new best move
1050 lock_grab(&(sp->lock));
1051 bestValue = sp->bestValue;
1055 // Finished searching the move. If StopRequest is true, the search
1056 // was aborted because the user interrupted the search or because we
1057 // ran out of time. In this case, the return value of the search cannot
1058 // be trusted, and we don't update the best move and/or PV.
1059 if (RootNode && !Signals.stop)
1061 RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1063 // PV move or new best move ?
1064 if (isPvMove || value > alpha)
1067 rm.extract_pv_from_tt(pos);
1069 // We record how often the best move has been changed in each
1070 // iteration. This information is used for time management: When
1071 // the best move changes frequently, we allocate some more time.
1072 if (!isPvMove && MultiPV == 1)
1076 // All other moves but the PV are set to the lowest value, this
1077 // is not a problem when sorting becuase sort is stable and move
1078 // position in the list is preserved, just the PV is pushed up.
1079 rm.score = -VALUE_INFINITE;
1083 if (value > bestValue)
1086 ss->bestMove = move;
1090 && value < beta) // We want always alpha < beta
1093 if (SpNode && !thread.cutoff_occurred())
1095 sp->bestValue = value;
1096 sp->ss->bestMove = move;
1098 sp->is_betaCutoff = (value >= beta);
1102 // Step 19. Check for split
1104 && depth >= Threads.min_split_depth()
1106 && Threads.available_slave_exists(pos.thread())
1108 && !thread.cutoff_occurred())
1109 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1110 threatMove, moveCount, &mp, NT);
1113 // Step 20. Check for mate and stalemate
1114 // All legal moves have been searched and if there are no legal moves, it
1115 // must be mate or stalemate. Note that we can have a false positive in
1116 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1117 // harmless because return value is discarded anyhow in the parent nodes.
1118 // If we are in a singular extension search then return a fail low score.
1120 return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1122 // If we have pruned all the moves without searching return a fail-low score
1123 if (bestValue == -VALUE_INFINITE)
1125 assert(!playedMoveCount);
1130 // Step 21. Update tables
1131 // Update transposition table entry, killers and history
1132 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1134 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1135 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1136 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1138 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1140 // Update killers and history for non capture cut-off moves
1141 if ( bestValue >= beta
1142 && !pos.is_capture_or_promotion(move)
1145 if (move != ss->killers[0])
1147 ss->killers[1] = ss->killers[0];
1148 ss->killers[0] = move;
1151 // Increase history value of the cut-off move
1152 Value bonus = Value(int(depth) * int(depth));
1153 H.add(pos.piece_on(from_sq(move)), to_sq(move), bonus);
1155 // Decrease history of all the other played non-capture moves
1156 for (int i = 0; i < playedMoveCount - 1; i++)
1158 Move m = movesSearched[i];
1159 H.add(pos.piece_on(from_sq(m)), to_sq(m), -bonus);
1166 // Here we have the lock still grabbed
1167 sp->is_slave[pos.thread()] = false;
1168 sp->nodes += pos.nodes_searched();
1169 lock_release(&(sp->lock));
1172 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1178 // qsearch() is the quiescence search function, which is called by the main
1179 // search function when the remaining depth is zero (or, to be more precise,
1180 // less than ONE_PLY).
1182 template <NodeType NT>
1183 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1185 const bool PvNode = (NT == PV);
1187 assert(NT == PV || NT == NonPV);
1188 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1189 assert(PvNode == (alpha != beta - 1));
1190 assert(depth <= DEPTH_ZERO);
1191 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1195 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1196 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1200 Value oldAlpha = alpha;
1202 ss->bestMove = ss->currentMove = MOVE_NONE;
1203 ss->ply = (ss-1)->ply + 1;
1205 // Check for an instant draw or maximum ply reached
1206 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1209 // Decide whether or not to include checks, this fixes also the type of
1210 // TT entry depth that we are going to use. Note that in qsearch we use
1211 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1212 inCheck = pos.in_check();
1213 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1215 // Transposition table lookup. At PV nodes, we don't use the TT for
1216 // pruning, but only for move ordering.
1217 tte = TT.probe(pos.key());
1218 ttMove = (tte ? tte->move() : MOVE_NONE);
1220 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1222 ss->bestMove = ttMove; // Can be MOVE_NONE
1223 return value_from_tt(tte->value(), ss->ply);
1226 // Evaluate the position statically
1229 bestValue = futilityBase = -VALUE_INFINITE;
1230 ss->eval = evalMargin = VALUE_NONE;
1231 enoughMaterial = false;
1237 assert(tte->static_value() != VALUE_NONE);
1239 evalMargin = tte->static_value_margin();
1240 ss->eval = bestValue = tte->static_value();
1243 ss->eval = bestValue = evaluate(pos, evalMargin);
1245 // Stand pat. Return immediately if static value is at least beta
1246 if (bestValue >= beta)
1249 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1254 if (PvNode && bestValue > alpha)
1257 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1258 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1261 // Initialize a MovePicker object for the current position, and prepare
1262 // to search the moves. Because the depth is <= 0 here, only captures,
1263 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1265 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1268 // Loop through the moves until no moves remain or a beta cutoff occurs
1269 while ( bestValue < beta
1270 && (move = mp.next_move()) != MOVE_NONE)
1272 assert(is_ok(move));
1274 givesCheck = pos.move_gives_check(move, ci);
1282 && !is_promotion(move)
1283 && !pos.is_passed_pawn_push(move))
1285 futilityValue = futilityBase
1286 + PieceValueEndgame[pos.piece_on(to_sq(move))]
1287 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1289 if (futilityValue < beta)
1291 if (futilityValue > bestValue)
1292 bestValue = futilityValue;
1297 // Prune moves with negative or equal SEE
1298 if ( futilityBase < beta
1299 && depth < DEPTH_ZERO
1300 && pos.see(move) <= 0)
1304 // Detect non-capture evasions that are candidate to be pruned
1305 evasionPrunable = !PvNode
1307 && bestValue > VALUE_MATED_IN_MAX_PLY
1308 && !pos.is_capture(move)
1309 && !pos.can_castle(pos.side_to_move());
1311 // Don't search moves with negative SEE values
1313 && (!inCheck || evasionPrunable)
1315 && !is_promotion(move)
1316 && pos.see_sign(move) < 0)
1319 // Don't search useless checks
1324 && !pos.is_capture_or_promotion(move)
1325 && ss->eval + PawnValueMidgame / 4 < beta
1326 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1328 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1329 bestValue = ss->eval + PawnValueMidgame / 4;
1334 // Check for legality only before to do the move
1335 if (!pos.pl_move_is_legal(move, ci.pinned))
1338 ss->currentMove = move;
1340 // Make and search the move
1341 pos.do_move(move, st, ci, givesCheck);
1342 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1343 pos.undo_move(move);
1345 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1348 if (value > bestValue)
1351 ss->bestMove = move;
1355 && value < beta) // We want always alpha < beta
1360 // All legal moves have been searched. A special case: If we're in check
1361 // and no legal moves were found, it is checkmate.
1362 if (inCheck && bestValue == -VALUE_INFINITE)
1363 return mated_in(ss->ply); // Plies to mate from the root
1365 // Update transposition table
1366 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1367 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1368 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1370 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1372 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1378 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1379 // bestValue is updated only when returning false because in that case move
1382 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1384 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1385 Square from, to, ksq, victimSq;
1388 Value futilityValue, bv = *bestValue;
1390 from = from_sq(move);
1392 them = flip(pos.side_to_move());
1393 ksq = pos.king_square(them);
1394 kingAtt = pos.attacks_from<KING>(ksq);
1395 pc = pos.piece_on(from);
1397 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1398 oldAtt = pos.attacks_from(pc, from, occ);
1399 newAtt = pos.attacks_from(pc, to, occ);
1401 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1402 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1404 if (!(b && (b & (b - 1))))
1407 // Rule 2. Queen contact check is very dangerous
1408 if ( type_of(pc) == QUEEN
1409 && bit_is_set(kingAtt, to))
1412 // Rule 3. Creating new double threats with checks
1413 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1417 victimSq = pop_1st_bit(&b);
1418 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1420 // Note that here we generate illegal "double move"!
1421 if ( futilityValue >= beta
1422 && pos.see_sign(make_move(from, victimSq)) >= 0)
1425 if (futilityValue > bv)
1429 // Update bestValue only if check is not dangerous (because we will prune the move)
1435 // connected_moves() tests whether two moves are 'connected' in the sense
1436 // that the first move somehow made the second move possible (for instance
1437 // if the moving piece is the same in both moves). The first move is assumed
1438 // to be the move that was made to reach the current position, while the
1439 // second move is assumed to be a move from the current position.
1441 bool connected_moves(const Position& pos, Move m1, Move m2) {
1443 Square f1, t1, f2, t2;
1450 // Case 1: The moving piece is the same in both moves
1456 // Case 2: The destination square for m2 was vacated by m1
1462 // Case 3: Moving through the vacated square
1463 p2 = pos.piece_on(f2);
1464 if ( piece_is_slider(p2)
1465 && bit_is_set(squares_between(f2, t2), f1))
1468 // Case 4: The destination square for m2 is defended by the moving piece in m1
1469 p1 = pos.piece_on(t1);
1470 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1473 // Case 5: Discovered check, checking piece is the piece moved in m1
1474 ksq = pos.king_square(pos.side_to_move());
1475 if ( piece_is_slider(p1)
1476 && bit_is_set(squares_between(t1, ksq), f2))
1478 Bitboard occ = pos.occupied_squares();
1479 clear_bit(&occ, f2);
1480 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1487 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1488 // "plies to mate from the current position". Non-mate scores are unchanged.
1489 // The function is called before storing a value to the transposition table.
1491 Value value_to_tt(Value v, int ply) {
1493 if (v >= VALUE_MATE_IN_MAX_PLY)
1496 if (v <= VALUE_MATED_IN_MAX_PLY)
1503 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1504 // from the transposition table (where refers to the plies to mate/be mated
1505 // from current position) to "plies to mate/be mated from the root".
1507 Value value_from_tt(Value v, int ply) {
1509 if (v >= VALUE_MATE_IN_MAX_PLY)
1512 if (v <= VALUE_MATED_IN_MAX_PLY)
1519 // connected_threat() tests whether it is safe to forward prune a move or if
1520 // is somehow connected to the threat move returned by null search.
1522 bool connected_threat(const Position& pos, Move m, Move threat) {
1525 assert(is_ok(threat));
1526 assert(!pos.is_capture_or_promotion(m));
1527 assert(!pos.is_passed_pawn_push(m));
1529 Square mfrom, mto, tfrom, tto;
1533 tfrom = from_sq(threat);
1534 tto = to_sq(threat);
1536 // Case 1: Don't prune moves which move the threatened piece
1540 // Case 2: If the threatened piece has value less than or equal to the
1541 // value of the threatening piece, don't prune moves which defend it.
1542 if ( pos.is_capture(threat)
1543 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1544 || type_of(pos.piece_on(tfrom)) == KING)
1545 && pos.move_attacks_square(m, tto))
1548 // Case 3: If the moving piece in the threatened move is a slider, don't
1549 // prune safe moves which block its ray.
1550 if ( piece_is_slider(pos.piece_on(tfrom))
1551 && bit_is_set(squares_between(tfrom, tto), mto)
1552 && pos.see_sign(m) >= 0)
1559 // can_return_tt() returns true if a transposition table score can be used to
1560 // cut-off at a given point in search.
1562 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1564 Value v = value_from_tt(tte->value(), ply);
1566 return ( tte->depth() >= depth
1567 || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1568 || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1570 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1571 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1575 // refine_eval() returns the transposition table score if possible, otherwise
1576 // falls back on static position evaluation.
1578 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1582 Value v = value_from_tt(tte->value(), ply);
1584 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1585 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1592 // current_search_time() returns the number of milliseconds which have passed
1593 // since the beginning of the current search.
1595 int elapsed_time(bool reset) {
1597 static int searchStartTime;
1600 searchStartTime = system_time();
1602 return system_time() - searchStartTime;
1606 // score_to_uci() converts a value to a string suitable for use with the UCI
1607 // protocol specifications:
1609 // cp <x> The score from the engine's point of view in centipawns.
1610 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1611 // use negative values for y.
1613 string score_to_uci(Value v, Value alpha, Value beta) {
1615 std::stringstream s;
1617 if (abs(v) < VALUE_MATE_IN_MAX_PLY)
1618 s << "cp " << v * 100 / int(PawnValueMidgame);
1620 s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1622 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1628 // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1629 // the PV lines also if are still to be searched and so refer to the previous
1632 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1634 int t = elapsed_time();
1637 for (int i = 0; i < Threads.size(); i++)
1638 if (Threads[i].maxPly > selDepth)
1639 selDepth = Threads[i].maxPly;
1641 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1643 bool updated = (i <= PVIdx);
1645 if (depth == 1 && !updated)
1648 int d = (updated ? depth : depth - 1);
1649 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1650 std::stringstream s;
1652 for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1653 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1655 cout << "info depth " << d
1656 << " seldepth " << selDepth
1657 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1658 << " nodes " << pos.nodes_searched()
1659 << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1661 << " multipv " << i + 1
1662 << " pv" << s.str() << endl;
1667 // pv_info_to_log() writes human-readable search information to the log file
1668 // (which is created when the UCI parameter "Use Search Log" is "true"). It
1669 // uses the two below helpers to pretty format time and score respectively.
1671 string time_to_string(int millisecs) {
1673 const int MSecMinute = 1000 * 60;
1674 const int MSecHour = 1000 * 60 * 60;
1676 int hours = millisecs / MSecHour;
1677 int minutes = (millisecs % MSecHour) / MSecMinute;
1678 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1680 std::stringstream s;
1685 s << std::setfill('0') << std::setw(2) << minutes << ':'
1686 << std::setw(2) << seconds;
1690 string score_to_string(Value v) {
1692 std::stringstream s;
1694 if (v >= VALUE_MATE_IN_MAX_PLY)
1695 s << "#" << (VALUE_MATE - v + 1) / 2;
1696 else if (v <= VALUE_MATED_IN_MAX_PLY)
1697 s << "-#" << (VALUE_MATE + v) / 2;
1699 s << std::setprecision(2) << std::fixed << std::showpos
1700 << float(v) / PawnValueMidgame;
1705 void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1707 const int64_t K = 1000;
1708 const int64_t M = 1000000;
1710 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1712 string san, padding;
1714 std::stringstream s;
1716 s << std::setw(2) << depth
1717 << std::setw(8) << score_to_string(value)
1718 << std::setw(8) << time_to_string(time);
1720 if (pos.nodes_searched() < M)
1721 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1723 else if (pos.nodes_searched() < K * M)
1724 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1727 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1729 padding = string(s.str().length(), ' ');
1730 length = padding.length();
1732 while (*m != MOVE_NONE)
1734 san = move_to_san(pos, *m);
1736 if (length + san.length() > 80)
1738 s << "\n" + padding;
1739 length = padding.length();
1743 length += san.length() + 1;
1745 pos.do_move(*m++, *st++);
1749 pos.undo_move(*--m);
1751 Log l(Options["Search Log Filename"]);
1752 l << s.str() << endl;
1756 // When playing with strength handicap choose best move among the MultiPV set
1757 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1759 Move do_skill_level() {
1761 assert(MultiPV > 1);
1765 // PRNG sequence should be not deterministic
1766 for (int i = abs(system_time() % 50); i > 0; i--)
1767 rk.rand<unsigned>();
1769 // RootMoves are already sorted by score in descending order
1770 size_t size = std::min(MultiPV, RootMoves.size());
1771 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1772 int weakness = 120 - 2 * SkillLevel;
1773 int max_s = -VALUE_INFINITE;
1774 Move best = MOVE_NONE;
1776 // Choose best move. For each move score we add two terms both dependent on
1777 // weakness, one deterministic and bigger for weaker moves, and one random,
1778 // then we choose the move with the resulting highest score.
1779 for (size_t i = 0; i < size; i++)
1781 int s = RootMoves[i].score;
1783 // Don't allow crazy blunders even at very low skills
1784 if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1787 // This is our magic formula
1788 s += ( weakness * int(RootMoves[0].score - s)
1789 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1794 best = RootMoves[i].pv[0];
1801 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1802 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1803 // allow to always have a ponder move even when we fail high at root and also a
1804 // long PV to print that is important for position analysis.
1806 void RootMove::extract_pv_from_tt(Position& pos) {
1808 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1813 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1817 pos.do_move(m, *st++);
1819 while ( (tte = TT.probe(pos.key())) != NULL
1820 && tte->move() != MOVE_NONE
1821 && pos.is_pseudo_legal(tte->move())
1822 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1824 && (!pos.is_draw<false>() || ply < 2))
1826 pv.push_back(tte->move());
1827 pos.do_move(tte->move(), *st++);
1830 pv.push_back(MOVE_NONE);
1832 do pos.undo_move(pv[--ply]); while (ply);
1836 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
1837 // the PV back into the TT. This makes sure the old PV moves are searched
1838 // first, even if the old TT entries have been overwritten.
1840 void RootMove::insert_pv_in_tt(Position& pos) {
1842 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1845 Value v, m = VALUE_NONE;
1848 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1854 // Don't overwrite existing correct entries
1855 if (!tte || tte->move() != pv[ply])
1857 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1858 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
1860 pos.do_move(pv[ply], *st++);
1862 } while (pv[++ply] != MOVE_NONE);
1864 do pos.undo_move(pv[--ply]); while (ply);
1870 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1871 /// The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
1872 /// for which the thread is the master.
1874 void Thread::idle_loop(SplitPoint* sp) {
1878 // If we are not searching, wait for a condition to be signaled
1879 // instead of wasting CPU time polling for work.
1882 || (Threads.use_sleeping_threads() && !is_searching))
1884 assert((!sp && threadID) || Threads.use_sleeping_threads());
1892 // Grab the lock to avoid races with Thread::wake_up()
1893 lock_grab(&sleepLock);
1895 // If we are master and all slaves have finished don't go to sleep
1896 if (sp && Threads.split_point_finished(sp))
1898 lock_release(&sleepLock);
1902 // Do sleep after retesting sleep conditions under lock protection, in
1903 // particular we need to avoid a deadlock in case a master thread has,
1904 // in the meanwhile, allocated us and sent the wake_up() call before we
1905 // had the chance to grab the lock.
1906 if (do_sleep || !is_searching)
1907 cond_wait(&sleepCond, &sleepLock);
1909 lock_release(&sleepLock);
1912 // If this thread has been assigned work, launch a search
1915 assert(!do_terminate);
1917 // Copy split point position and search stack and call search()
1918 Stack ss[MAX_PLY_PLUS_2];
1919 SplitPoint* tsp = splitPoint;
1920 Position pos(*tsp->pos, threadID);
1922 memcpy(ss, tsp->ss - 1, 4 * sizeof(Stack));
1925 if (tsp->nodeType == Root)
1926 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1927 else if (tsp->nodeType == PV)
1928 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1929 else if (tsp->nodeType == NonPV)
1930 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1934 assert(is_searching);
1936 is_searching = false;
1938 // Wake up master thread so to allow it to return from the idle loop in
1939 // case we are the last slave of the split point.
1940 if ( Threads.use_sleeping_threads()
1941 && threadID != tsp->master
1942 && !Threads[tsp->master].is_searching)
1943 Threads[tsp->master].wake_up();
1946 // If this thread is the master of a split point and all slaves have
1947 // finished their work at this split point, return from the idle loop.
1948 if (sp && Threads.split_point_finished(sp))
1950 // Because sp->is_slave[] is reset under lock protection,
1951 // be sure sp->lock has been released before to return.
1952 lock_grab(&(sp->lock));
1953 lock_release(&(sp->lock));
1960 /// do_timer_event() is called by the timer thread when the timer triggers. It
1961 /// is used to print debug info and, more important, to detect when we are out of
1962 /// available time and so stop the search.
1964 void do_timer_event() {
1966 static int lastInfoTime;
1967 int e = elapsed_time();
1969 if (system_time() - lastInfoTime >= 1000 || !lastInfoTime)
1971 lastInfoTime = system_time();
1978 bool stillAtFirstMove = Signals.firstRootMove
1979 && !Signals.failedLowAtRoot
1980 && e > TimeMgr.available_time();
1982 bool noMoreTime = e > TimeMgr.maximum_time()
1983 || stillAtFirstMove;
1985 if ( (Limits.useTimeManagement() && noMoreTime)
1986 || (Limits.maxTime && e >= Limits.maxTime)
1987 /* missing nodes limit */ ) // FIXME
1988 Signals.stop = true;