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-2010 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
71 score = prevScore = -VALUE_INFINITE;
73 pv.push_back(MOVE_NONE);
76 bool operator<(const RootMove& m) const { return score < m.score; }
77 bool operator==(const Move& m) const { return pv[0] == m; }
79 void extract_pv_from_tt(Position& pos);
80 void insert_pv_in_tt(Position& pos);
91 // Lookup table to check if a Piece is a slider and its access function
92 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
93 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
95 // Maximum depth for razoring
96 const Depth RazorDepth = 4 * ONE_PLY;
98 // Dynamic razoring margin based on depth
99 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
101 // Maximum depth for use of dynamic threat detection when null move fails low
102 const Depth ThreatDepth = 5 * ONE_PLY;
104 // Minimum depth for use of internal iterative deepening
105 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
107 // At Non-PV nodes we do an internal iterative deepening search
108 // when the static evaluation is bigger then beta - IIDMargin.
109 const Value IIDMargin = Value(0x100);
111 // Minimum depth for use of singular extension
112 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
114 // Futility margin for quiescence search
115 const Value FutilityMarginQS = Value(0x80);
117 // Futility lookup tables (initialized at startup) and their access functions
118 Value FutilityMargins[16][64]; // [depth][moveNumber]
119 int FutilityMoveCounts[32]; // [depth]
121 inline Value futility_margin(Depth d, int mn) {
123 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
124 : 2 * VALUE_INFINITE;
127 inline int futility_move_count(Depth d) {
129 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
132 // Reduction lookup tables (initialized at startup) and their access function
133 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
135 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
137 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
140 // Easy move margin. An easy move candidate must be at least this much
141 // better than the second best move.
142 const Value EasyMoveMargin = Value(0x150);
145 /// Namespace variables
147 std::vector<RootMove> RootMoves;
148 size_t MultiPV, UCIMultiPV, PVIdx;
152 bool SkillLevelEnabled, Chess960;
158 template <NodeType NT>
159 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
161 template <NodeType NT>
162 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
164 void id_loop(Position& pos);
165 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
166 bool connected_moves(const Position& pos, Move m1, Move m2);
167 Value value_to_tt(Value v, int ply);
168 Value value_from_tt(Value v, int ply);
169 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
170 bool connected_threat(const Position& pos, Move m, Move threat);
171 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
172 Move do_skill_level();
173 int elapsed_time(bool reset = false);
174 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
175 void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
176 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
178 // MovePickerExt class template extends MovePicker and allows to choose at
179 // compile time the proper moves source according to the type of node. In the
180 // default case we simply create and use a standard MovePicker object.
181 template<bool SpNode> struct MovePickerExt : public MovePicker {
183 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
184 : MovePicker(p, ttm, d, h, ss, b) {}
187 // In case of a SpNode we use split point's shared MovePicker object as moves source
188 template<> struct MovePickerExt<true> : public MovePicker {
190 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
191 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
193 Move next_move() { return mp->next_move(); }
197 // is_dangerous() checks whether a move belongs to some classes of known
198 // 'dangerous' moves so that we avoid to prune it.
199 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
201 // Test for a pawn pushed to 7th or a passed pawn move
202 if (type_of(pos.piece_on(move_from(m))) == PAWN)
204 Color c = pos.side_to_move();
205 if ( relative_rank(c, move_to(m)) == RANK_7
206 || pos.pawn_is_passed(c, move_to(m)))
210 // Test for a capture that triggers a pawn endgame
211 if ( captureOrPromotion
212 && type_of(pos.piece_on(move_to(m))) != PAWN
213 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
214 - PieceValueMidgame[pos.piece_on(move_to(m))] == VALUE_ZERO)
224 /// Search::init() is called during startup to initialize various lookup tables
226 void Search::init() {
228 int d; // depth (ONE_PLY == 2)
229 int hd; // half depth (ONE_PLY == 1)
232 // Init reductions array
233 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
235 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
236 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
237 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
238 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
241 // Init futility margins array
242 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
243 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
245 // Init futility move count array
246 for (d = 0; d < 32; d++)
247 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
251 /// Search::perft() is our utility to verify move generation. All the leaf nodes
252 /// up to the given depth are generated and counted and the sum returned.
254 int64_t Search::perft(Position& pos, Depth depth) {
259 MoveList<MV_LEGAL> ml(pos);
261 // At the last ply just return the number of moves (leaf nodes)
262 if (depth <= ONE_PLY)
266 for ( ; !ml.end(); ++ml)
268 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
269 sum += perft(pos, depth - ONE_PLY);
270 pos.undo_move(ml.move());
276 /// Search::think() is the external interface to Stockfish's search, and is
277 /// called by the main thread when the program receives the UCI 'go' command. It
278 /// searches from RootPosition and at the end prints the "bestmove" to output.
280 void Search::think() {
282 static Book book; // Defined static to initialize the PRNG only once
284 Position& pos = RootPosition;
285 Chess960 = pos.is_chess960();
287 TimeMgr.init(Limits, pos.startpos_ply_counter());
292 // Populate RootMoves with all the legal moves (default) or, if a SearchMoves
293 // is given, with the subset of legal moves to search.
294 for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
295 if ( SearchMoves.empty()
296 || count(SearchMoves.begin(), SearchMoves.end(), ml.move()))
297 RootMoves.push_back(RootMove(ml.move()));
299 if (Options["OwnBook"].value<bool>())
301 if (Options["Book File"].value<string>() != book.name())
302 book.open(Options["Book File"].value<string>());
304 Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
306 if ( bookMove != MOVE_NONE
307 && count(RootMoves.begin(), RootMoves.end(), bookMove))
309 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
314 // Read UCI options: GUI could change UCI parameters during the game
315 read_evaluation_uci_options(pos.side_to_move());
316 Threads.read_uci_options();
318 TT.set_size(Options["Hash"].value<int>());
319 if (Options["Clear Hash"].value<bool>())
321 Options["Clear Hash"].set_value("false");
325 UCIMultiPV = Options["MultiPV"].value<size_t>();
326 SkillLevel = Options["Skill Level"].value<int>();
328 // Do we have to play with skill handicap? In this case enable MultiPV that
329 // we will use behind the scenes to retrieve a set of possible moves.
330 SkillLevelEnabled = (SkillLevel < 20);
331 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
333 if (Options["Use Search Log"].value<bool>())
335 Log log(Options["Search Log Filename"].value<string>());
336 log << "\nSearching: " << pos.to_fen()
337 << "\ninfinite: " << Limits.infinite
338 << " ponder: " << Limits.ponder
339 << " time: " << Limits.time
340 << " increment: " << Limits.increment
341 << " moves to go: " << Limits.movesToGo
345 for (int i = 0; i < Threads.size(); i++)
347 Threads[i].maxPly = 0;
348 Threads[i].wake_up();
351 // Set best timer interval to avoid lagging under time pressure. Timer is
352 // used to check for remaining available thinking time.
353 if (TimeMgr.available_time())
354 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
356 Threads.set_timer(100);
358 // We're ready to start searching. Call the iterative deepening loop function
361 // Stop timer and send all the slaves to sleep, if not already sleeping
362 Threads.set_timer(0);
365 if (Options["Use Search Log"].value<bool>())
367 int e = elapsed_time();
369 Log log(Options["Search Log Filename"].value<string>());
370 log << "Nodes: " << pos.nodes_searched()
371 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
372 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
375 pos.do_move(RootMoves[0].pv[0], st);
376 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
377 pos.undo_move(RootMoves[0].pv[0]);
382 // When we reach max depth we arrive here even without a StopRequest, but if
383 // we are pondering or in infinite search, we shouldn't print the best move
384 // before we are told to do so.
385 if (!Signals.stop && (Limits.ponder || Limits.infinite))
386 Threads.wait_for_stop_or_ponderhit();
388 // Best move could be MOVE_NONE when searching on a stalemate position
389 cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
390 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
396 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
397 // with increasing depth until the allocated thinking time has been consumed,
398 // user stops the search, or the maximum search depth is reached.
400 void id_loop(Position& pos) {
402 Stack ss[PLY_MAX_PLUS_2];
403 int depth, prevBestMoveChanges;
404 Value bestValue, alpha, beta, delta;
405 bool bestMoveNeverChanged = true;
406 Move skillBest = MOVE_NONE;
408 memset(ss, 0, 4 * sizeof(Stack));
409 depth = BestMoveChanges = 0;
410 bestValue = delta = -VALUE_INFINITE;
411 ss->currentMove = MOVE_NULL; // Hack to skip update gains
413 // Handle the special case of a mate/stalemate position
414 if (RootMoves.empty())
416 cout << "info depth 0"
417 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
419 RootMoves.push_back(MOVE_NONE);
423 // Iterative deepening loop until requested to stop or target depth reached
424 while (!Signals.stop && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
426 // Save last iteration's scores before first PV line is searched and all
427 // the move scores but the (new) PV are set to -VALUE_INFINITE.
428 for (size_t i = 0; i < RootMoves.size(); i++)
429 RootMoves[i].prevScore = RootMoves[i].score;
431 prevBestMoveChanges = BestMoveChanges;
434 // MultiPV loop. We perform a full root search for each PV line
435 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
437 // Set aspiration window default width
438 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
441 alpha = RootMoves[PVIdx].prevScore - delta;
442 beta = RootMoves[PVIdx].prevScore + delta;
446 alpha = -VALUE_INFINITE;
447 beta = VALUE_INFINITE;
450 // Start with a small aspiration window and, in case of fail high/low,
451 // research with bigger window until not failing high/low anymore.
453 // Search starts from ss+1 to allow referencing (ss-1). This is
454 // needed by update gains and ss copy when splitting at Root.
455 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
457 // Bring to front the best move. It is critical that sorting is
458 // done with a stable algorithm because all the values but the first
459 // and eventually the new best one are set to -VALUE_INFINITE and
460 // we want to keep the same order for all the moves but the new
461 // PV that goes to the front. Note that in case of MultiPV search
462 // the already searched PV lines are preserved.
463 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
465 // In case we have found an exact score and we are going to leave
466 // the fail high/low loop then reorder the PV moves, otherwise
467 // leave the last PV move in its position so to be searched again.
468 // Of course this is needed only in MultiPV search.
469 if (PVIdx && bestValue > alpha && bestValue < beta)
470 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
472 // Write PV back to transposition table in case the relevant
473 // entries have been overwritten during the search.
474 for (size_t i = 0; i <= PVIdx; i++)
475 RootMoves[i].insert_pv_in_tt(pos);
477 // If search has been stopped exit the aspiration window loop.
478 // Sorting and writing PV back to TT is safe becuase RootMoves
479 // is still valid, although refers to previous iteration.
483 // Send full PV info to GUI if we are going to leave the loop or
484 // if we have a fail high/low and we are deep in the search.
485 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
486 pv_info_to_uci(pos, depth, alpha, beta);
488 // In case of failing high/low increase aspiration window and
489 // research, otherwise exit the fail high/low loop.
490 if (bestValue >= beta)
495 else if (bestValue <= alpha)
497 Signals.failedLowAtRoot = true;
498 Signals.stopOnPonderhit = false;
506 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
508 } while (abs(bestValue) < VALUE_KNOWN_WIN);
511 // Skills: Do we need to pick now the best move ?
512 if (SkillLevelEnabled && depth == 1 + SkillLevel)
513 skillBest = do_skill_level();
515 if (Options["Use Search Log"].value<bool>())
516 pv_info_to_log(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]);
518 // Filter out startup noise when monitoring best move stability
519 if (depth > 2 && BestMoveChanges)
520 bestMoveNeverChanged = false;
522 // Do we have time for the next iteration? Can we stop searching now?
523 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
525 bool stop = false; // Local variable, not the volatile Signals.stop
527 // Take in account some extra time if the best move has changed
528 if (depth > 4 && depth < 50)
529 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
531 // Stop search if most of available time is already consumed. We
532 // probably don't have enough time to search the first move at the
533 // next iteration anyway.
534 if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
537 // Stop search early if one move seems to be much better than others
540 && ( bestMoveNeverChanged
541 || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
543 Value rBeta = bestValue - EasyMoveMargin;
544 (ss+1)->excludedMove = RootMoves[0].pv[0];
545 (ss+1)->skipNullMove = true;
546 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
547 (ss+1)->skipNullMove = false;
548 (ss+1)->excludedMove = MOVE_NONE;
556 // If we are allowed to ponder do not stop the search now but
557 // keep pondering until GUI sends "ponderhit" or "stop".
559 Signals.stopOnPonderhit = true;
566 // When using skills swap best PV line with the sub-optimal one
567 if (SkillLevelEnabled)
569 if (skillBest == MOVE_NONE) // Still unassigned ?
570 skillBest = do_skill_level();
572 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
577 // search<>() is the main search function for both PV and non-PV nodes and for
578 // normal and SplitPoint nodes. When called just after a split point the search
579 // is simpler because we have already probed the hash table, done a null move
580 // search, and searched the first move before splitting, we don't have to repeat
581 // all this work again. We also don't need to store anything to the hash table
582 // here: This is taken care of after we return from the split point.
584 template <NodeType NT>
585 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
587 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
588 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
589 const bool RootNode = (NT == Root || NT == SplitPointRoot);
591 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
592 assert(beta > alpha && beta <= VALUE_INFINITE);
593 assert(PvNode || alpha == beta - 1);
594 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
596 Move movesSearched[MAX_MOVES];
601 Move ttMove, move, excludedMove, threatMove;
604 Value bestValue, value, oldAlpha;
605 Value refinedValue, nullValue, futilityBase, futilityValue;
606 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
607 bool captureOrPromotion, dangerous, doFullDepthSearch;
608 int moveCount = 0, playedMoveCount = 0;
609 Thread& thread = Threads[pos.thread()];
610 SplitPoint* sp = NULL;
612 refinedValue = bestValue = value = -VALUE_INFINITE;
614 inCheck = pos.in_check();
615 ss->ply = (ss-1)->ply + 1;
617 // Used to send selDepth info to GUI
618 if (PvNode && thread.maxPly < ss->ply)
619 thread.maxPly = ss->ply;
621 // Step 1. Initialize node
624 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
625 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
626 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
632 ttMove = excludedMove = MOVE_NONE;
633 threatMove = sp->threatMove;
634 goto split_point_start;
637 // Step 2. Check for aborted search and immediate draw
639 || pos.is_draw<false>()
640 || ss->ply > PLY_MAX) && !RootNode)
643 // Step 3. Mate distance pruning
646 alpha = std::max(value_mated_in(ss->ply), alpha);
647 beta = std::min(value_mate_in(ss->ply+1), beta);
652 // Step 4. Transposition table lookup
653 // We don't want the score of a partial search to overwrite a previous full search
654 // TT value, so we use a different position key in case of an excluded move.
655 excludedMove = ss->excludedMove;
656 posKey = excludedMove ? pos.exclusion_key() : pos.key();
657 tte = TT.probe(posKey);
658 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
660 // At PV nodes we check for exact scores, while at non-PV nodes we check for
661 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
662 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
663 // we should also update RootMoveList to avoid bogus output.
664 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
665 : can_return_tt(tte, depth, beta, ss->ply)))
668 ss->bestMove = move = ttMove; // Can be MOVE_NONE
669 value = value_from_tt(tte->value(), ss->ply);
673 && !pos.is_capture_or_promotion(move)
674 && move != ss->killers[0])
676 ss->killers[1] = ss->killers[0];
677 ss->killers[0] = move;
682 // Step 5. Evaluate the position statically and update parent's gain statistics
684 ss->eval = ss->evalMargin = VALUE_NONE;
687 assert(tte->static_value() != VALUE_NONE);
689 ss->eval = tte->static_value();
690 ss->evalMargin = tte->static_value_margin();
691 refinedValue = refine_eval(tte, ss->eval, ss->ply);
695 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
696 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
699 // Update gain for the parent non-capture move given the static position
700 // evaluation before and after the move.
701 if ( (move = (ss-1)->currentMove) != MOVE_NULL
702 && (ss-1)->eval != VALUE_NONE
703 && ss->eval != VALUE_NONE
704 && pos.captured_piece_type() == PIECE_TYPE_NONE
705 && !is_special(move))
707 Square to = move_to(move);
708 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
711 // Step 6. Razoring (is omitted in PV nodes)
713 && depth < RazorDepth
715 && refinedValue + razor_margin(depth) < beta
716 && ttMove == MOVE_NONE
717 && abs(beta) < VALUE_MATE_IN_PLY_MAX
718 && !pos.has_pawn_on_7th(pos.side_to_move()))
720 Value rbeta = beta - razor_margin(depth);
721 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
723 // Logically we should return (v + razor_margin(depth)), but
724 // surprisingly this did slightly weaker in tests.
728 // Step 7. Static null move pruning (is omitted in PV nodes)
729 // We're betting that the opponent doesn't have a move that will reduce
730 // the score by more than futility_margin(depth) if we do a null move.
733 && depth < RazorDepth
735 && refinedValue - futility_margin(depth, 0) >= beta
736 && abs(beta) < VALUE_MATE_IN_PLY_MAX
737 && pos.non_pawn_material(pos.side_to_move()))
738 return refinedValue - futility_margin(depth, 0);
740 // Step 8. Null move search with verification search (is omitted in PV nodes)
745 && refinedValue >= beta
746 && abs(beta) < VALUE_MATE_IN_PLY_MAX
747 && pos.non_pawn_material(pos.side_to_move()))
749 ss->currentMove = MOVE_NULL;
751 // Null move dynamic reduction based on depth
752 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
754 // Null move dynamic reduction based on value
755 if (refinedValue - PawnValueMidgame > beta)
758 pos.do_null_move<true>(st);
759 (ss+1)->skipNullMove = true;
760 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
761 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
762 (ss+1)->skipNullMove = false;
763 pos.do_null_move<false>(st);
765 if (nullValue >= beta)
767 // Do not return unproven mate scores
768 if (nullValue >= VALUE_MATE_IN_PLY_MAX)
771 if (depth < 6 * ONE_PLY)
774 // Do verification search at high depths
775 ss->skipNullMove = true;
776 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
777 ss->skipNullMove = false;
784 // The null move failed low, which means that we may be faced with
785 // some kind of threat. If the previous move was reduced, check if
786 // the move that refuted the null move was somehow connected to the
787 // move which was reduced. If a connection is found, return a fail
788 // low score (which will cause the reduced move to fail high in the
789 // parent node, which will trigger a re-search with full depth).
790 threatMove = (ss+1)->bestMove;
792 if ( depth < ThreatDepth
794 && threatMove != MOVE_NONE
795 && connected_moves(pos, (ss-1)->currentMove, threatMove))
800 // Step 9. ProbCut (is omitted in PV nodes)
801 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
802 // and a reduced search returns a value much above beta, we can (almost) safely
803 // prune the previous move.
805 && depth >= RazorDepth + ONE_PLY
808 && excludedMove == MOVE_NONE
809 && abs(beta) < VALUE_MATE_IN_PLY_MAX)
811 Value rbeta = beta + 200;
812 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
814 assert(rdepth >= ONE_PLY);
816 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
819 while ((move = mp.next_move()) != MOVE_NONE)
820 if (pos.pl_move_is_legal(move, ci.pinned))
822 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
823 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
830 // Step 10. Internal iterative deepening
831 if ( depth >= IIDDepth[PvNode]
832 && ttMove == MOVE_NONE
833 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
835 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
837 ss->skipNullMove = true;
838 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
839 ss->skipNullMove = false;
841 tte = TT.probe(posKey);
842 ttMove = tte ? tte->move() : MOVE_NONE;
845 split_point_start: // At split points actual search starts from here
847 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
849 ss->bestMove = MOVE_NONE;
850 futilityBase = ss->eval + ss->evalMargin;
851 singularExtensionNode = !RootNode
853 && depth >= SingularExtensionDepth[PvNode]
854 && ttMove != MOVE_NONE
855 && !excludedMove // Recursive singular search is not allowed
856 && (tte->type() & VALUE_TYPE_LOWER)
857 && tte->depth() >= depth - 3 * ONE_PLY;
860 lock_grab(&(sp->lock));
861 bestValue = sp->bestValue;
862 moveCount = sp->moveCount;
864 assert(bestValue > -VALUE_INFINITE && moveCount > 0);
867 // Step 11. Loop through moves
868 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
869 while ( bestValue < beta
870 && (move = mp.next_move()) != MOVE_NONE
871 && !thread.cutoff_occurred())
875 if (move == excludedMove)
878 // At root obey the "searchmoves" option and skip moves not listed in Root
879 // Move List, as a consequence any illegal move is also skipped. In MultiPV
880 // mode we also skip PV moves which have been already searched.
881 if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
884 // At PV and SpNode nodes we want all moves to be legal since the beginning
885 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
890 moveCount = ++sp->moveCount;
891 lock_release(&(sp->lock));
898 Signals.firstRootMove = (moveCount == 1);
899 nodes = pos.nodes_searched();
901 if (pos.thread() == 0 && elapsed_time() > 2000)
902 cout << "info depth " << depth / ONE_PLY
903 << " currmove " << move_to_uci(move, Chess960)
904 << " currmovenumber " << moveCount + PVIdx << endl;
907 isPvMove = (PvNode && moveCount <= 1);
908 captureOrPromotion = pos.is_capture_or_promotion(move);
909 givesCheck = pos.move_gives_check(move, ci);
910 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
913 // Step 12. Extend checks and, in PV nodes, also dangerous moves
914 if (PvNode && dangerous)
917 else if (givesCheck && pos.see_sign(move) >= 0)
918 ext = PvNode ? ONE_PLY : ONE_PLY / 2;
920 // Singular extension search. If all moves but one fail low on a search of
921 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
922 // is singular and should be extended. To verify this we do a reduced search
923 // on all the other moves but the ttMove, if result is lower than ttValue minus
924 // a margin then we extend ttMove.
925 if ( singularExtensionNode
928 && pos.pl_move_is_legal(move, ci.pinned))
930 Value ttValue = value_from_tt(tte->value(), ss->ply);
932 if (abs(ttValue) < VALUE_KNOWN_WIN)
934 Value rBeta = ttValue - int(depth);
935 ss->excludedMove = move;
936 ss->skipNullMove = true;
937 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
938 ss->skipNullMove = false;
939 ss->excludedMove = MOVE_NONE;
940 ss->bestMove = MOVE_NONE;
946 // Update current move (this must be done after singular extension search)
947 newDepth = depth - ONE_PLY + ext;
949 // Step 13. Futility pruning (is omitted in PV nodes)
951 && !captureOrPromotion
956 && (bestValue > VALUE_MATED_IN_PLY_MAX || bestValue == -VALUE_INFINITE))
958 // Move count based pruning
959 if ( moveCount >= futility_move_count(depth)
960 && (!threatMove || !connected_threat(pos, move, threatMove)))
963 lock_grab(&(sp->lock));
968 // Value based pruning
969 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
970 // but fixing this made program slightly weaker.
971 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
972 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
973 + H.gain(pos.piece_on(move_from(move)), move_to(move));
975 if (futilityValue < beta)
978 lock_grab(&(sp->lock));
983 // Prune moves with negative SEE at low depths
984 if ( predictedDepth < 2 * ONE_PLY
985 && pos.see_sign(move) < 0)
988 lock_grab(&(sp->lock));
994 // Check for legality only before to do the move
995 if (!pos.pl_move_is_legal(move, ci.pinned))
1001 ss->currentMove = move;
1002 if (!SpNode && !captureOrPromotion)
1003 movesSearched[playedMoveCount++] = move;
1005 // Step 14. Make the move
1006 pos.do_move(move, st, ci, givesCheck);
1008 // Step 15. Reduced depth search (LMR). If the move fails high will be
1009 // re-searched at full depth.
1010 if ( depth > 3 * ONE_PLY
1012 && !captureOrPromotion
1015 && ss->killers[0] != move
1016 && ss->killers[1] != move)
1018 ss->reduction = reduction<PvNode>(depth, moveCount);
1019 Depth d = newDepth - ss->reduction;
1020 alpha = SpNode ? sp->alpha : alpha;
1022 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1023 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1025 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1026 ss->reduction = DEPTH_ZERO;
1029 doFullDepthSearch = !isPvMove;
1031 // Step 16. Full depth search, when LMR is skipped or fails high
1032 if (doFullDepthSearch)
1034 alpha = SpNode ? sp->alpha : alpha;
1035 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1036 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1039 // Only for PV nodes do a full PV search on the first move or after a fail
1040 // high, in the latter case search only if value < beta, otherwise let the
1041 // parent node to fail low with value <= alpha and to try another move.
1042 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1043 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1044 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1046 // Step 17. Undo move
1047 pos.undo_move(move);
1049 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1051 // Step 18. Check for new best move
1054 lock_grab(&(sp->lock));
1055 bestValue = sp->bestValue;
1059 // Finished searching the move. If StopRequest is true, the search
1060 // was aborted because the user interrupted the search or because we
1061 // ran out of time. In this case, the return value of the search cannot
1062 // be trusted, and we don't update the best move and/or PV.
1063 if (RootNode && !Signals.stop)
1065 RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1066 rm.nodes += pos.nodes_searched() - nodes;
1068 // PV move or new best move ?
1069 if (isPvMove || value > alpha)
1072 rm.extract_pv_from_tt(pos);
1074 // We record how often the best move has been changed in each
1075 // iteration. This information is used for time management: When
1076 // the best move changes frequently, we allocate some more time.
1077 if (!isPvMove && MultiPV == 1)
1081 // All other moves but the PV are set to the lowest value, this
1082 // is not a problem when sorting becuase sort is stable and move
1083 // position in the list is preserved, just the PV is pushed up.
1084 rm.score = -VALUE_INFINITE;
1088 if (value > bestValue)
1091 ss->bestMove = move;
1095 && value < beta) // We want always alpha < beta
1098 if (SpNode && !thread.cutoff_occurred())
1100 sp->bestValue = value;
1101 sp->ss->bestMove = move;
1103 sp->is_betaCutoff = (value >= beta);
1107 // Step 19. Check for split
1109 && depth >= Threads.min_split_depth()
1111 && Threads.available_slave_exists(pos.thread())
1113 && !thread.cutoff_occurred())
1114 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1115 threatMove, moveCount, &mp, NT);
1118 // Step 20. Check for mate and stalemate
1119 // All legal moves have been searched and if there are no legal moves, it
1120 // must be mate or stalemate. Note that we can have a false positive in
1121 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1122 // harmless because return value is discarded anyhow in the parent nodes.
1123 // If we are in a singular extension search then return a fail low score.
1125 return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1127 // If we have pruned all the moves without searching return a fail-low score
1128 if (bestValue == -VALUE_INFINITE)
1130 assert(!playedMoveCount);
1135 // Step 21. Update tables
1136 // Update transposition table entry, killers and history
1137 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1139 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1140 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1141 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1143 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1145 // Update killers and history for non capture cut-off moves
1146 if ( bestValue >= beta
1147 && !pos.is_capture_or_promotion(move)
1150 if (move != ss->killers[0])
1152 ss->killers[1] = ss->killers[0];
1153 ss->killers[0] = move;
1156 // Increase history value of the cut-off move
1157 Value bonus = Value(int(depth) * int(depth));
1158 H.add(pos.piece_on(move_from(move)), move_to(move), bonus);
1160 // Decrease history of all the other played non-capture moves
1161 for (int i = 0; i < playedMoveCount - 1; i++)
1163 Move m = movesSearched[i];
1164 H.add(pos.piece_on(move_from(m)), move_to(m), -bonus);
1171 // Here we have the lock still grabbed
1172 sp->is_slave[pos.thread()] = false;
1173 sp->nodes += pos.nodes_searched();
1174 lock_release(&(sp->lock));
1177 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1183 // qsearch() is the quiescence search function, which is called by the main
1184 // search function when the remaining depth is zero (or, to be more precise,
1185 // less than ONE_PLY).
1187 template <NodeType NT>
1188 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1190 const bool PvNode = (NT == PV);
1192 assert(NT == PV || NT == NonPV);
1193 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1194 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1195 assert(PvNode || alpha == beta - 1);
1197 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1201 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1202 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1206 Value oldAlpha = alpha;
1208 ss->bestMove = ss->currentMove = MOVE_NONE;
1209 ss->ply = (ss-1)->ply + 1;
1211 // Check for an instant draw or maximum ply reached
1212 if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1215 // Decide whether or not to include checks, this fixes also the type of
1216 // TT entry depth that we are going to use. Note that in qsearch we use
1217 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1218 inCheck = pos.in_check();
1219 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1221 // Transposition table lookup. At PV nodes, we don't use the TT for
1222 // pruning, but only for move ordering.
1223 tte = TT.probe(pos.key());
1224 ttMove = (tte ? tte->move() : MOVE_NONE);
1226 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1228 ss->bestMove = ttMove; // Can be MOVE_NONE
1229 return value_from_tt(tte->value(), ss->ply);
1232 // Evaluate the position statically
1235 bestValue = futilityBase = -VALUE_INFINITE;
1236 ss->eval = evalMargin = VALUE_NONE;
1237 enoughMaterial = false;
1243 assert(tte->static_value() != VALUE_NONE);
1245 evalMargin = tte->static_value_margin();
1246 ss->eval = bestValue = tte->static_value();
1249 ss->eval = bestValue = evaluate(pos, evalMargin);
1251 // Stand pat. Return immediately if static value is at least beta
1252 if (bestValue >= beta)
1255 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1260 if (PvNode && bestValue > alpha)
1263 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1264 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1267 // Initialize a MovePicker object for the current position, and prepare
1268 // to search the moves. Because the depth is <= 0 here, only captures,
1269 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1271 MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1274 // Loop through the moves until no moves remain or a beta cutoff occurs
1275 while ( bestValue < beta
1276 && (move = mp.next_move()) != MOVE_NONE)
1278 assert(is_ok(move));
1280 givesCheck = pos.move_gives_check(move, ci);
1288 && !is_promotion(move)
1289 && !pos.is_passed_pawn_push(move))
1291 futilityValue = futilityBase
1292 + PieceValueEndgame[pos.piece_on(move_to(move))]
1293 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1295 if (futilityValue < beta)
1297 if (futilityValue > bestValue)
1298 bestValue = futilityValue;
1303 // Prune moves with negative or equal SEE
1304 if ( futilityBase < beta
1305 && depth < DEPTH_ZERO
1306 && pos.see(move) <= 0)
1310 // Detect non-capture evasions that are candidate to be pruned
1311 evasionPrunable = !PvNode
1313 && bestValue > VALUE_MATED_IN_PLY_MAX
1314 && !pos.is_capture(move)
1315 && !pos.can_castle(pos.side_to_move());
1317 // Don't search moves with negative SEE values
1319 && (!inCheck || evasionPrunable)
1321 && !is_promotion(move)
1322 && pos.see_sign(move) < 0)
1325 // Don't search useless checks
1330 && !pos.is_capture_or_promotion(move)
1331 && ss->eval + PawnValueMidgame / 4 < beta
1332 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1334 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1335 bestValue = ss->eval + PawnValueMidgame / 4;
1340 // Check for legality only before to do the move
1341 if (!pos.pl_move_is_legal(move, ci.pinned))
1344 ss->currentMove = move;
1346 // Make and search the move
1347 pos.do_move(move, st, ci, givesCheck);
1348 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1349 pos.undo_move(move);
1351 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1354 if (value > bestValue)
1357 ss->bestMove = move;
1361 && value < beta) // We want always alpha < beta
1366 // All legal moves have been searched. A special case: If we're in check
1367 // and no legal moves were found, it is checkmate.
1368 if (inCheck && bestValue == -VALUE_INFINITE)
1369 return value_mated_in(ss->ply);
1371 // Update transposition table
1372 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1373 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1374 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1376 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1378 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1384 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1385 // bestValue is updated only when returning false because in that case move
1388 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1390 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1391 Square from, to, ksq, victimSq;
1394 Value futilityValue, bv = *bestValue;
1396 from = move_from(move);
1398 them = flip(pos.side_to_move());
1399 ksq = pos.king_square(them);
1400 kingAtt = pos.attacks_from<KING>(ksq);
1401 pc = pos.piece_on(from);
1403 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1404 oldAtt = pos.attacks_from(pc, from, occ);
1405 newAtt = pos.attacks_from(pc, to, occ);
1407 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1408 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1410 if (!(b && (b & (b - 1))))
1413 // Rule 2. Queen contact check is very dangerous
1414 if ( type_of(pc) == QUEEN
1415 && bit_is_set(kingAtt, to))
1418 // Rule 3. Creating new double threats with checks
1419 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1423 victimSq = pop_1st_bit(&b);
1424 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1426 // Note that here we generate illegal "double move"!
1427 if ( futilityValue >= beta
1428 && pos.see_sign(make_move(from, victimSq)) >= 0)
1431 if (futilityValue > bv)
1435 // Update bestValue only if check is not dangerous (because we will prune the move)
1441 // connected_moves() tests whether two moves are 'connected' in the sense
1442 // that the first move somehow made the second move possible (for instance
1443 // if the moving piece is the same in both moves). The first move is assumed
1444 // to be the move that was made to reach the current position, while the
1445 // second move is assumed to be a move from the current position.
1447 bool connected_moves(const Position& pos, Move m1, Move m2) {
1449 Square f1, t1, f2, t2;
1456 // Case 1: The moving piece is the same in both moves
1462 // Case 2: The destination square for m2 was vacated by m1
1468 // Case 3: Moving through the vacated square
1469 p2 = pos.piece_on(f2);
1470 if ( piece_is_slider(p2)
1471 && bit_is_set(squares_between(f2, t2), f1))
1474 // Case 4: The destination square for m2 is defended by the moving piece in m1
1475 p1 = pos.piece_on(t1);
1476 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1479 // Case 5: Discovered check, checking piece is the piece moved in m1
1480 ksq = pos.king_square(pos.side_to_move());
1481 if ( piece_is_slider(p1)
1482 && bit_is_set(squares_between(t1, ksq), f2))
1484 Bitboard occ = pos.occupied_squares();
1485 clear_bit(&occ, f2);
1486 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1493 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1494 // "plies to mate from the current ply". Non-mate scores are unchanged. The
1495 // function is called before storing a value to the transposition table.
1497 Value value_to_tt(Value v, int ply) {
1499 if (v >= VALUE_MATE_IN_PLY_MAX)
1502 if (v <= VALUE_MATED_IN_PLY_MAX)
1509 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1510 // the transposition table to a mate score corrected for the current ply.
1512 Value value_from_tt(Value v, int ply) {
1514 if (v >= VALUE_MATE_IN_PLY_MAX)
1517 if (v <= VALUE_MATED_IN_PLY_MAX)
1524 // connected_threat() tests whether it is safe to forward prune a move or if
1525 // is somehow connected to the threat move returned by null search.
1527 bool connected_threat(const Position& pos, Move m, Move threat) {
1530 assert(is_ok(threat));
1531 assert(!pos.is_capture_or_promotion(m));
1532 assert(!pos.is_passed_pawn_push(m));
1534 Square mfrom, mto, tfrom, tto;
1536 mfrom = move_from(m);
1538 tfrom = move_from(threat);
1539 tto = move_to(threat);
1541 // Case 1: Don't prune moves which move the threatened piece
1545 // Case 2: If the threatened piece has value less than or equal to the
1546 // value of the threatening piece, don't prune moves which defend it.
1547 if ( pos.is_capture(threat)
1548 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1549 || type_of(pos.piece_on(tfrom)) == KING)
1550 && pos.move_attacks_square(m, tto))
1553 // Case 3: If the moving piece in the threatened move is a slider, don't
1554 // prune safe moves which block its ray.
1555 if ( piece_is_slider(pos.piece_on(tfrom))
1556 && bit_is_set(squares_between(tfrom, tto), mto)
1557 && pos.see_sign(m) >= 0)
1564 // can_return_tt() returns true if a transposition table score can be used to
1565 // cut-off at a given point in search.
1567 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1569 Value v = value_from_tt(tte->value(), ply);
1571 return ( tte->depth() >= depth
1572 || v >= std::max(VALUE_MATE_IN_PLY_MAX, beta)
1573 || v < std::min(VALUE_MATED_IN_PLY_MAX, beta))
1575 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1576 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1580 // refine_eval() returns the transposition table score if possible, otherwise
1581 // falls back on static position evaluation.
1583 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1587 Value v = value_from_tt(tte->value(), ply);
1589 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1590 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1597 // current_search_time() returns the number of milliseconds which have passed
1598 // since the beginning of the current search.
1600 int elapsed_time(bool reset) {
1602 static int searchStartTime;
1605 searchStartTime = system_time();
1607 return system_time() - searchStartTime;
1611 // score_to_uci() converts a value to a string suitable for use with the UCI
1612 // protocol specifications:
1614 // cp <x> The score from the engine's point of view in centipawns.
1615 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1616 // use negative values for y.
1618 string score_to_uci(Value v, Value alpha, Value beta) {
1620 std::stringstream s;
1622 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1623 s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1625 s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1627 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1633 // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1634 // the PV lines also if are still to be searched and so refer to the previous
1637 void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1639 int t = elapsed_time();
1642 for (int i = 0; i < Threads.size(); i++)
1643 if (Threads[i].maxPly > selDepth)
1644 selDepth = Threads[i].maxPly;
1646 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1648 bool updated = (i <= PVIdx);
1650 if (depth == 1 && !updated)
1653 int d = (updated ? depth : depth - 1);
1654 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1655 std::stringstream s;
1657 for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1658 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1660 cout << "info depth " << d
1661 << " seldepth " << selDepth
1662 << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1663 << " nodes " << pos.nodes_searched()
1664 << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1666 << " multipv " << i + 1
1667 << " pv" << s.str() << endl;
1672 // pv_info_to_log() writes human-readable search information to the log file
1673 // (which is created when the UCI parameter "Use Search Log" is "true"). It
1674 // uses the two below helpers to pretty format time and score respectively.
1676 string time_to_string(int millisecs) {
1678 const int MSecMinute = 1000 * 60;
1679 const int MSecHour = 1000 * 60 * 60;
1681 int hours = millisecs / MSecHour;
1682 int minutes = (millisecs % MSecHour) / MSecMinute;
1683 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1685 std::stringstream s;
1690 s << std::setfill('0') << std::setw(2) << minutes << ':'
1691 << std::setw(2) << seconds;
1695 string score_to_string(Value v) {
1697 std::stringstream s;
1699 if (v >= VALUE_MATE_IN_PLY_MAX)
1700 s << "#" << (VALUE_MATE - v + 1) / 2;
1701 else if (v <= VALUE_MATED_IN_PLY_MAX)
1702 s << "-#" << (VALUE_MATE + v) / 2;
1704 s << std::setprecision(2) << std::fixed << std::showpos
1705 << float(v) / PawnValueMidgame;
1710 void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1712 const int64_t K = 1000;
1713 const int64_t M = 1000000;
1715 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1717 string san, padding;
1719 std::stringstream s;
1721 s << std::setw(2) << depth
1722 << std::setw(8) << score_to_string(value)
1723 << std::setw(8) << time_to_string(time);
1725 if (pos.nodes_searched() < M)
1726 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1728 else if (pos.nodes_searched() < K * M)
1729 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1732 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1734 padding = string(s.str().length(), ' ');
1735 length = padding.length();
1737 while (*m != MOVE_NONE)
1739 san = move_to_san(pos, *m);
1741 if (length + san.length() > 80)
1743 s << "\n" + padding;
1744 length = padding.length();
1748 length += san.length() + 1;
1750 pos.do_move(*m++, *st++);
1754 pos.undo_move(*--m);
1756 Log l(Options["Search Log Filename"].value<string>());
1757 l << s.str() << endl;
1761 // When playing with strength handicap choose best move among the MultiPV set
1762 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1764 Move do_skill_level() {
1766 assert(MultiPV > 1);
1770 // PRNG sequence should be not deterministic
1771 for (int i = abs(system_time() % 50); i > 0; i--)
1772 rk.rand<unsigned>();
1774 // RootMoves are already sorted by score in descending order
1775 size_t size = std::min(MultiPV, RootMoves.size());
1776 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1777 int weakness = 120 - 2 * SkillLevel;
1778 int max_s = -VALUE_INFINITE;
1779 Move best = MOVE_NONE;
1781 // Choose best move. For each move score we add two terms both dependent on
1782 // weakness, one deterministic and bigger for weaker moves, and one random,
1783 // then we choose the move with the resulting highest score.
1784 for (size_t i = 0; i < size; i++)
1786 int s = RootMoves[i].score;
1788 // Don't allow crazy blunders even at very low skills
1789 if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1792 // This is our magic formula
1793 s += ( weakness * int(RootMoves[0].score - s)
1794 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1799 best = RootMoves[i].pv[0];
1806 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1807 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1808 // allow to always have a ponder move even when we fail high at root and also a
1809 // long PV to print that is important for position analysis.
1811 void RootMove::extract_pv_from_tt(Position& pos) {
1813 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1818 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1822 pos.do_move(m, *st++);
1824 while ( (tte = TT.probe(pos.key())) != NULL
1825 && tte->move() != MOVE_NONE
1826 && pos.is_pseudo_legal(tte->move())
1827 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1829 && (!pos.is_draw<false>() || ply < 2))
1831 pv.push_back(tte->move());
1832 pos.do_move(tte->move(), *st++);
1835 pv.push_back(MOVE_NONE);
1837 do pos.undo_move(pv[--ply]); while (ply);
1841 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
1842 // the PV back into the TT. This makes sure the old PV moves are searched
1843 // first, even if the old TT entries have been overwritten.
1845 void RootMove::insert_pv_in_tt(Position& pos) {
1847 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1850 Value v, m = VALUE_NONE;
1853 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1859 // Don't overwrite existing correct entries
1860 if (!tte || tte->move() != pv[ply])
1862 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1863 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
1865 pos.do_move(pv[ply], *st++);
1867 } while (pv[++ply] != MOVE_NONE);
1869 do pos.undo_move(pv[--ply]); while (ply);
1875 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1876 /// The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
1877 /// for which the thread is the master.
1879 void Thread::idle_loop(SplitPoint* sp) {
1883 // If we are not searching, wait for a condition to be signaled
1884 // instead of wasting CPU time polling for work.
1887 || (Threads.use_sleeping_threads() && !is_searching))
1889 assert((!sp && threadID) || Threads.use_sleeping_threads());
1897 // Grab the lock to avoid races with Thread::wake_up()
1898 lock_grab(&sleepLock);
1900 // If we are master and all slaves have finished don't go to sleep
1901 if (sp && Threads.split_point_finished(sp))
1903 lock_release(&sleepLock);
1907 // Do sleep after retesting sleep conditions under lock protection, in
1908 // particular we need to avoid a deadlock in case a master thread has,
1909 // in the meanwhile, allocated us and sent the wake_up() call before we
1910 // had the chance to grab the lock.
1911 if (do_sleep || !is_searching)
1912 cond_wait(&sleepCond, &sleepLock);
1914 lock_release(&sleepLock);
1917 // If this thread has been assigned work, launch a search
1920 assert(!do_terminate);
1922 // Copy split point position and search stack and call search()
1923 Stack ss[PLY_MAX_PLUS_2];
1924 SplitPoint* tsp = splitPoint;
1925 Position pos(*tsp->pos, threadID);
1927 memcpy(ss, tsp->ss - 1, 4 * sizeof(Stack));
1930 if (tsp->nodeType == Root)
1931 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1932 else if (tsp->nodeType == PV)
1933 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1934 else if (tsp->nodeType == NonPV)
1935 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1939 assert(is_searching);
1941 is_searching = false;
1943 // Wake up master thread so to allow it to return from the idle loop in
1944 // case we are the last slave of the split point.
1945 if ( Threads.use_sleeping_threads()
1946 && threadID != tsp->master
1947 && !Threads[tsp->master].is_searching)
1948 Threads[tsp->master].wake_up();
1951 // If this thread is the master of a split point and all slaves have
1952 // finished their work at this split point, return from the idle loop.
1953 if (sp && Threads.split_point_finished(sp))
1955 // Because sp->is_slave[] is reset under lock protection,
1956 // be sure sp->lock has been released before to return.
1957 lock_grab(&(sp->lock));
1958 lock_release(&(sp->lock));
1965 /// do_timer_event() is called by the timer thread when the timer triggers. It
1966 /// is used to print debug info and, more important, to detect when we are out of
1967 /// available time and so stop the search.
1969 void do_timer_event() {
1971 static int lastInfoTime;
1972 int e = elapsed_time();
1974 if (system_time() - lastInfoTime >= 1000 || !lastInfoTime)
1976 lastInfoTime = system_time();
1979 dbg_print_hit_rate();
1985 bool stillAtFirstMove = Signals.firstRootMove
1986 && !Signals.failedLowAtRoot
1987 && e > TimeMgr.available_time();
1989 bool noMoreTime = e > TimeMgr.maximum_time()
1990 || stillAtFirstMove;
1992 if ( (Limits.useTimeManagement() && noMoreTime)
1993 || (Limits.maxTime && e >= Limits.maxTime)
1994 /* missing nodes limit */ ) // FIXME
1995 Signals.stop = true;