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, MultiPVIdx;
152 bool SkillLevelEnabled;
158 Move id_loop(Position& pos, Move* ponderMove);
160 template <NodeType NT>
161 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
163 template <NodeType NT>
164 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
166 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
167 bool connected_moves(const Position& pos, Move m1, Move m2);
168 Value value_to_tt(Value v, int ply);
169 Value value_from_tt(Value v, int ply);
170 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
171 bool connected_threat(const Position& pos, Move m, Move threat);
172 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
173 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
174 void do_skill_level(Move* best, Move* ponder);
175 int elapsed_time(bool reset = false);
176 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
177 string speed_to_uci(int64_t nodes);
178 string pv_to_uci(const Move pv[], int pvNum, bool chess960);
179 string pretty_pv(Position& pos, int depth, Value score, int time, Move pv[]);
180 string depth_to_uci(Depth depth);
182 // MovePickerExt class template extends MovePicker and allows to choose at
183 // compile time the proper moves source according to the type of node. In the
184 // default case we simply create and use a standard MovePicker object.
185 template<bool SpNode> struct MovePickerExt : public MovePicker {
187 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
188 : MovePicker(p, ttm, d, h, ss, b) {}
191 // In case of a SpNode we use split point's shared MovePicker object as moves source
192 template<> struct MovePickerExt<true> : public MovePicker {
194 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
195 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
197 Move get_next_move() { return mp->get_next_move(); }
201 // Overload operator<<() to make it easier to print moves in a coordinate
202 // notation compatible with UCI protocol.
203 std::ostream& operator<<(std::ostream& os, Move m) {
205 bool chess960 = (os.iword(0) != 0); // See set960()
206 return os << move_to_uci(m, chess960);
209 // When formatting a move for std::cout we must know if we are in Chess960 or
210 // not. To keep using the handy operator<<() on the move the trick is to embed
211 // this flag in the stream itself. Function-like named enum set960 is used as
212 // a custom manipulator and the stream internal general-purpose array, accessed
213 // through ios_base::iword(), is used to pass the flag to the move's operator<<
214 // that will read it to properly format castling moves.
217 std::ostream& operator<<(std::ostream& os, const set960& f) {
223 // is_dangerous() checks whether a move belongs to some classes of known
224 // 'dangerous' moves so that we avoid to prune it.
225 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
227 // Test for a pawn pushed to 7th or a passed pawn move
228 if (type_of(pos.piece_on(move_from(m))) == PAWN)
230 Color c = pos.side_to_move();
231 if ( relative_rank(c, move_to(m)) == RANK_7
232 || pos.pawn_is_passed(c, move_to(m)))
236 // Test for a capture that triggers a pawn endgame
237 if ( captureOrPromotion
238 && type_of(pos.piece_on(move_to(m))) != PAWN
239 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
240 - PieceValueMidgame[pos.piece_on(move_to(m))] == VALUE_ZERO)
250 /// init_search() is called during startup to initialize various lookup tables
252 void Search::init() {
254 int d; // depth (ONE_PLY == 2)
255 int hd; // half depth (ONE_PLY == 1)
258 // Init reductions array
259 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
261 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
262 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
263 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
264 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
267 // Init futility margins array
268 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
269 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
271 // Init futility move count array
272 for (d = 0; d < 32; d++)
273 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
277 /// perft() is our utility to verify move generation. All the leaf nodes up to
278 /// the given depth are generated and counted and the sum returned.
280 int64_t Search::perft(Position& pos, Depth depth) {
285 MoveList<MV_LEGAL> ml(pos);
287 // At the last ply just return the number of moves (leaf nodes)
288 if (depth <= ONE_PLY)
292 for ( ; !ml.end(); ++ml)
294 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
295 sum += perft(pos, depth - ONE_PLY);
296 pos.undo_move(ml.move());
302 /// think() is the external interface to Stockfish's search, and is called by the
303 /// main thread when the program receives the UCI 'go' command. It searches from
304 /// RootPosition and at the end prints the "bestmove" to output.
306 void Search::think() {
308 static Book book; // Defined static to initialize the PRNG only once
310 Position& pos = RootPosition;
312 TimeMgr.init(Limits, pos.startpos_ply_counter());
314 // Set output stream mode: normal or chess960. Castling notation is different
315 cout << set960(pos.is_chess960());
317 if (Options["OwnBook"].value<bool>())
319 if (Options["Book File"].value<string>() != book.name())
320 book.open(Options["Book File"].value<string>());
322 Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
323 if (bookMove != MOVE_NONE)
325 if (!Signals.stop && (Limits.ponder || Limits.infinite))
326 Threads.wait_for_stop_or_ponderhit();
328 cout << "bestmove " << bookMove << endl;
333 // Read UCI options: GUI could change UCI parameters during the game
334 read_evaluation_uci_options(pos.side_to_move());
335 Threads.read_uci_options();
337 TT.set_size(Options["Hash"].value<int>());
338 if (Options["Clear Hash"].value<bool>())
340 Options["Clear Hash"].set_value("false");
344 UCIMultiPV = Options["MultiPV"].value<size_t>();
345 SkillLevel = Options["Skill Level"].value<int>();
347 // Do we have to play with skill handicap? In this case enable MultiPV that
348 // we will use behind the scenes to retrieve a set of possible moves.
349 SkillLevelEnabled = (SkillLevel < 20);
350 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
352 if (Options["Use Search Log"].value<bool>())
354 Log log(Options["Search Log Filename"].value<string>());
355 log << "\nSearching: " << pos.to_fen()
356 << "\ninfinite: " << Limits.infinite
357 << " ponder: " << Limits.ponder
358 << " time: " << Limits.time
359 << " increment: " << Limits.increment
360 << " moves to go: " << Limits.movesToGo
364 // Wake up needed threads and reset maxPly counter
365 for (int i = 0; i < Threads.size(); i++)
367 Threads[i].maxPly = 0;
368 Threads[i].wake_up();
371 // Set best timer interval to avoid lagging under time pressure. Timer is
372 // used to check for remaining available thinking time.
373 if (TimeMgr.available_time())
374 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
376 Threads.set_timer(100);
378 // We're ready to start thinking. Call the iterative deepening loop function
379 Move ponderMove = MOVE_NONE;
380 Move bestMove = id_loop(pos, &ponderMove);
382 // Stop timer and send all the slaves to sleep, if not already sleeping
383 Threads.set_timer(0);
386 if (Options["Use Search Log"].value<bool>())
388 int e = elapsed_time();
390 Log log(Options["Search Log Filename"].value<string>());
391 log << "Nodes: " << pos.nodes_searched()
392 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
393 << "\nBest move: " << move_to_san(pos, bestMove);
396 pos.do_move(bestMove, st);
397 log << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
398 pos.undo_move(bestMove); // Return from think() with unchanged position
401 // When we reach max depth we arrive here even without a StopRequest, but if
402 // we are pondering or in infinite search, we shouldn't print the best move
403 // before we are told to do so.
404 if (!Signals.stop && (Limits.ponder || Limits.infinite))
405 Threads.wait_for_stop_or_ponderhit();
407 // Could be MOVE_NONE when searching on a stalemate position
408 cout << "bestmove " << bestMove;
410 // UCI protol is not clear on allowing sending an empty ponder move, instead
411 // it is clear that ponder move is optional. So skip it if empty.
412 if (ponderMove != MOVE_NONE)
413 cout << " ponder " << ponderMove;
421 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
422 // with increasing depth until the allocated thinking time has been consumed,
423 // user stops the search, or the maximum search depth is reached.
425 Move id_loop(Position& pos, Move* ponderMove) {
427 Stack ss[PLY_MAX_PLUS_2];
428 Value bestValues[PLY_MAX_PLUS_2];
429 int bestMoveChanges[PLY_MAX_PLUS_2];
430 int depth, aspirationDelta;
431 Value bestValue, alpha, beta;
432 Move bestMove, skillBest, skillPonder;
433 bool bestMoveNeverChanged = true;
435 memset(ss, 0, 4 * sizeof(Stack));
439 *ponderMove = bestMove = skillBest = skillPonder = MOVE_NONE;
440 depth = aspirationDelta = 0;
441 bestValue = alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
442 ss->currentMove = MOVE_NULL; // Hack to skip update gains
444 for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
445 if ( SearchMoves.empty()
446 || std::count(SearchMoves.begin(), SearchMoves.end(), ml.move()))
447 RootMoves.push_back(RootMove(ml.move()));
449 // Handle special case of searching on a mate/stalemate position
450 if (RootMoves.empty())
452 cout << "info" << depth_to_uci(DEPTH_ZERO)
453 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW, alpha, beta) << endl;
458 // Iterative deepening loop until requested to stop or target depth reached
459 while (!Signals.stop && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
461 // Save now last iteration's scores, before Rml moves are reordered
462 for (size_t i = 0; i < RootMoves.size(); i++)
463 RootMoves[i].prevScore = RootMoves[i].score;
467 // MultiPV loop. We perform a full root search for each PV line
468 for (MultiPVIdx = 0; MultiPVIdx < std::min(MultiPV, RootMoves.size()); MultiPVIdx++)
470 // Calculate dynamic aspiration window based on previous iterations
471 if (depth >= 5 && abs(RootMoves[MultiPVIdx].prevScore) < VALUE_KNOWN_WIN)
473 int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
474 int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
476 aspirationDelta = std::min(std::max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
477 aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
479 alpha = std::max(RootMoves[MultiPVIdx].prevScore - aspirationDelta, -VALUE_INFINITE);
480 beta = std::min(RootMoves[MultiPVIdx].prevScore + aspirationDelta, VALUE_INFINITE);
484 alpha = -VALUE_INFINITE;
485 beta = VALUE_INFINITE;
488 // Start with a small aspiration window and, in case of fail high/low,
489 // research with bigger window until not failing high/low anymore.
491 // Search starts from ss+1 to allow referencing (ss-1). This is
492 // needed by update gains and ss copy when splitting at Root.
493 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
495 // Bring to front the best move. It is critical that sorting is
496 // done with a stable algorithm because all the values but the first
497 // and eventually the new best one are set to -VALUE_INFINITE and
498 // we want to keep the same order for all the moves but the new
499 // PV that goes to the front. Note that in case of MultiPV search
500 // the already searched PV lines are preserved.
501 sort<RootMove>(RootMoves.begin() + MultiPVIdx, RootMoves.end());
503 // In case we have found an exact score and we are going to leave
504 // the fail high/low loop then reorder the PV moves, otherwise
505 // leave the last PV move in its position so to be searched again.
506 // Of course this is needed only in MultiPV search.
507 if (MultiPVIdx && bestValue > alpha && bestValue < beta)
508 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + MultiPVIdx);
510 // Write PV back to transposition table in case the relevant entries
511 // have been overwritten during the search.
512 for (size_t i = 0; i <= MultiPVIdx; i++)
513 RootMoves[i].insert_pv_in_tt(pos);
515 // If search has been stopped exit the aspiration window loop,
516 // note that sorting and writing PV back to TT is safe becuase
517 // Rml is still valid, although refers to the previous iteration.
521 // Send full PV info to GUI if we are going to leave the loop or
522 // if we have a fail high/low and we are deep in the search. UCI
523 // protocol requires to send all the PV lines also if are still
524 // to be searched and so refer to the previous search's score.
525 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
526 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
528 bool updated = (i <= MultiPVIdx);
530 if (depth == 1 && !updated)
533 Depth d = (updated ? depth : depth - 1) * ONE_PLY;
534 Value s = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
538 << (i == MultiPVIdx ? score_to_uci(s, alpha, beta) : score_to_uci(s))
539 << speed_to_uci(pos.nodes_searched())
540 << pv_to_uci(&RootMoves[i].pv[0], i + 1, pos.is_chess960())
544 // In case of failing high/low increase aspiration window and
545 // research, otherwise exit the fail high/low loop.
546 if (bestValue >= beta)
548 beta = std::min(beta + aspirationDelta, VALUE_INFINITE);
549 aspirationDelta += aspirationDelta / 2;
551 else if (bestValue <= alpha)
553 Signals.failedLowAtRoot = true;
554 Signals.stopOnPonderhit = false;
556 alpha = std::max(alpha - aspirationDelta, -VALUE_INFINITE);
557 aspirationDelta += aspirationDelta / 2;
562 } while (abs(bestValue) < VALUE_KNOWN_WIN);
565 bestMove = RootMoves[0].pv[0];
566 *ponderMove = RootMoves[0].pv[1];
567 bestValues[depth] = bestValue;
568 bestMoveChanges[depth] = BestMoveChanges;
570 // Skills: Do we need to pick now the best and the ponder moves ?
571 if (SkillLevelEnabled && depth == 1 + SkillLevel)
572 do_skill_level(&skillBest, &skillPonder);
574 if (Options["Use Search Log"].value<bool>())
576 Log log(Options["Search Log Filename"].value<string>());
577 log << pretty_pv(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]) << endl;
580 // Filter out startup noise when monitoring best move stability
581 if (depth > 2 && bestMoveChanges[depth])
582 bestMoveNeverChanged = false;
584 // Do we have time for the next iteration? Can we stop searching now?
585 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
587 bool stop = false; // Local variable instead of the volatile Signals.stop
589 // Take in account some extra time if the best move has changed
590 if (depth > 4 && depth < 50)
591 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
593 // Stop search if most of available time is already consumed. We probably don't
594 // have enough time to search the first move at the next iteration anyway.
595 if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
598 // Stop search early if one move seems to be much better than others
601 && ( bestMoveNeverChanged
602 || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
604 Value rBeta = bestValue - EasyMoveMargin;
605 (ss+1)->excludedMove = bestMove;
606 (ss+1)->skipNullMove = true;
607 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
608 (ss+1)->skipNullMove = false;
609 (ss+1)->excludedMove = MOVE_NONE;
617 // If we are allowed to ponder do not stop the search now but
618 // keep pondering until GUI sends "ponderhit" or "stop".
620 Signals.stopOnPonderhit = true;
627 // When using skills overwrite best and ponder moves with the sub-optimal ones
628 if (SkillLevelEnabled)
630 if (skillBest == MOVE_NONE) // Still unassigned ?
631 do_skill_level(&skillBest, &skillPonder);
633 bestMove = skillBest;
634 *ponderMove = skillPonder;
641 // search<>() is the main search function for both PV and non-PV nodes and for
642 // normal and SplitPoint nodes. When called just after a split point the search
643 // is simpler because we have already probed the hash table, done a null move
644 // search, and searched the first move before splitting, we don't have to repeat
645 // all this work again. We also don't need to store anything to the hash table
646 // here: This is taken care of after we return from the split point.
648 template <NodeType NT>
649 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
651 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
652 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
653 const bool RootNode = (NT == Root || NT == SplitPointRoot);
655 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
656 assert(beta > alpha && beta <= VALUE_INFINITE);
657 assert(PvNode || alpha == beta - 1);
658 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
660 Move movesSearched[MAX_MOVES];
665 Move ttMove, move, excludedMove, threatMove;
668 Value bestValue, value, oldAlpha;
669 Value refinedValue, nullValue, futilityBase, futilityValue;
670 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
671 bool captureOrPromotion, dangerous, doFullDepthSearch;
672 int moveCount = 0, playedMoveCount = 0;
673 Thread& thread = Threads[pos.thread()];
674 SplitPoint* sp = NULL;
676 refinedValue = bestValue = value = -VALUE_INFINITE;
678 inCheck = pos.in_check();
679 ss->ply = (ss-1)->ply + 1;
681 // Used to send selDepth info to GUI
682 if (PvNode && thread.maxPly < ss->ply)
683 thread.maxPly = ss->ply;
685 // Step 1. Initialize node
688 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
689 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
690 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
696 ttMove = excludedMove = MOVE_NONE;
697 threatMove = sp->threatMove;
698 goto split_point_start;
701 // Step 2. Check for aborted search and immediate draw
703 || pos.is_draw<false>()
704 || ss->ply > PLY_MAX) && !RootNode)
707 // Step 3. Mate distance pruning
710 alpha = std::max(value_mated_in(ss->ply), alpha);
711 beta = std::min(value_mate_in(ss->ply+1), beta);
716 // Step 4. Transposition table lookup
717 // We don't want the score of a partial search to overwrite a previous full search
718 // TT value, so we use a different position key in case of an excluded move.
719 excludedMove = ss->excludedMove;
720 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
721 tte = TT.probe(posKey);
722 ttMove = RootNode ? RootMoves[MultiPVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
724 // At PV nodes we check for exact scores, while at non-PV nodes we check for
725 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
726 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
727 // we should also update RootMoveList to avoid bogus output.
728 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
729 : can_return_tt(tte, depth, beta, ss->ply)))
732 ss->bestMove = move = ttMove; // Can be MOVE_NONE
733 value = value_from_tt(tte->value(), ss->ply);
737 && !pos.is_capture_or_promotion(move)
738 && move != ss->killers[0])
740 ss->killers[1] = ss->killers[0];
741 ss->killers[0] = move;
746 // Step 5. Evaluate the position statically and update parent's gain statistics
748 ss->eval = ss->evalMargin = VALUE_NONE;
751 assert(tte->static_value() != VALUE_NONE);
753 ss->eval = tte->static_value();
754 ss->evalMargin = tte->static_value_margin();
755 refinedValue = refine_eval(tte, ss->eval, ss->ply);
759 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
760 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
763 // Update gain for the parent non-capture move given the static position
764 // evaluation before and after the move.
765 if ( (move = (ss-1)->currentMove) != MOVE_NULL
766 && (ss-1)->eval != VALUE_NONE
767 && ss->eval != VALUE_NONE
768 && pos.captured_piece_type() == PIECE_TYPE_NONE
769 && !is_special(move))
771 Square to = move_to(move);
772 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
775 // Step 6. Razoring (is omitted in PV nodes)
777 && depth < RazorDepth
779 && refinedValue + razor_margin(depth) < beta
780 && ttMove == MOVE_NONE
781 && abs(beta) < VALUE_MATE_IN_PLY_MAX
782 && !pos.has_pawn_on_7th(pos.side_to_move()))
784 Value rbeta = beta - razor_margin(depth);
785 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
787 // Logically we should return (v + razor_margin(depth)), but
788 // surprisingly this did slightly weaker in tests.
792 // Step 7. Static null move pruning (is omitted in PV nodes)
793 // We're betting that the opponent doesn't have a move that will reduce
794 // the score by more than futility_margin(depth) if we do a null move.
797 && depth < RazorDepth
799 && refinedValue - futility_margin(depth, 0) >= beta
800 && abs(beta) < VALUE_MATE_IN_PLY_MAX
801 && pos.non_pawn_material(pos.side_to_move()))
802 return refinedValue - futility_margin(depth, 0);
804 // Step 8. Null move search with verification search (is omitted in PV nodes)
809 && refinedValue >= beta
810 && abs(beta) < VALUE_MATE_IN_PLY_MAX
811 && pos.non_pawn_material(pos.side_to_move()))
813 ss->currentMove = MOVE_NULL;
815 // Null move dynamic reduction based on depth
816 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
818 // Null move dynamic reduction based on value
819 if (refinedValue - PawnValueMidgame > beta)
822 pos.do_null_move<true>(st);
823 (ss+1)->skipNullMove = true;
824 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
825 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
826 (ss+1)->skipNullMove = false;
827 pos.do_null_move<false>(st);
829 if (nullValue >= beta)
831 // Do not return unproven mate scores
832 if (nullValue >= VALUE_MATE_IN_PLY_MAX)
835 if (depth < 6 * ONE_PLY)
838 // Do verification search at high depths
839 ss->skipNullMove = true;
840 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
841 ss->skipNullMove = false;
848 // The null move failed low, which means that we may be faced with
849 // some kind of threat. If the previous move was reduced, check if
850 // the move that refuted the null move was somehow connected to the
851 // move which was reduced. If a connection is found, return a fail
852 // low score (which will cause the reduced move to fail high in the
853 // parent node, which will trigger a re-search with full depth).
854 threatMove = (ss+1)->bestMove;
856 if ( depth < ThreatDepth
858 && threatMove != MOVE_NONE
859 && connected_moves(pos, (ss-1)->currentMove, threatMove))
864 // Step 9. ProbCut (is omitted in PV nodes)
865 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
866 // and a reduced search returns a value much above beta, we can (almost) safely
867 // prune the previous move.
869 && depth >= RazorDepth + ONE_PLY
872 && excludedMove == MOVE_NONE
873 && abs(beta) < VALUE_MATE_IN_PLY_MAX)
875 Value rbeta = beta + 200;
876 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
878 assert(rdepth >= ONE_PLY);
880 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
883 while ((move = mp.get_next_move()) != MOVE_NONE)
884 if (pos.pl_move_is_legal(move, ci.pinned))
886 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
887 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
894 // Step 10. Internal iterative deepening
895 if ( depth >= IIDDepth[PvNode]
896 && ttMove == MOVE_NONE
897 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
899 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
901 ss->skipNullMove = true;
902 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
903 ss->skipNullMove = false;
905 tte = TT.probe(posKey);
906 ttMove = tte ? tte->move() : MOVE_NONE;
909 split_point_start: // At split points actual search starts from here
911 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
913 ss->bestMove = MOVE_NONE;
914 futilityBase = ss->eval + ss->evalMargin;
915 singularExtensionNode = !RootNode
917 && depth >= SingularExtensionDepth[PvNode]
918 && ttMove != MOVE_NONE
919 && !excludedMove // Recursive singular search is not allowed
920 && (tte->type() & VALUE_TYPE_LOWER)
921 && tte->depth() >= depth - 3 * ONE_PLY;
924 lock_grab(&(sp->lock));
925 bestValue = sp->bestValue;
926 moveCount = sp->moveCount;
928 assert(bestValue > -VALUE_INFINITE && moveCount > 0);
931 // Step 11. Loop through moves
932 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
933 while ( bestValue < beta
934 && (move = mp.get_next_move()) != MOVE_NONE
935 && !thread.cutoff_occurred())
939 if (move == excludedMove)
942 // At root obey the "searchmoves" option and skip moves not listed in Root
943 // Move List, as a consequence any illegal move is also skipped. In MultiPV
944 // mode we also skip PV moves which have been already searched.
945 if (RootNode && !std::count(RootMoves.begin() + MultiPVIdx, RootMoves.end(), move))
948 // At PV and SpNode nodes we want all moves to be legal since the beginning
949 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
954 moveCount = ++sp->moveCount;
955 lock_release(&(sp->lock));
962 // This is used by time management
963 Signals.firstRootMove = (moveCount == 1);
965 nodes = pos.nodes_searched();
967 if (pos.thread() == 0 && elapsed_time() > 2000)
968 cout << "info" << depth_to_uci(depth)
969 << " currmove " << move
970 << " currmovenumber " << moveCount + MultiPVIdx << endl;
973 isPvMove = (PvNode && moveCount <= 1);
974 captureOrPromotion = pos.is_capture_or_promotion(move);
975 givesCheck = pos.move_gives_check(move, ci);
976 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
979 // Step 12. Extend checks and, in PV nodes, also dangerous moves
980 if (PvNode && dangerous)
983 else if (givesCheck && pos.see_sign(move) >= 0)
984 ext = PvNode ? ONE_PLY : ONE_PLY / 2;
986 // Singular extension search. If all moves but one fail low on a search of
987 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
988 // is singular and should be extended. To verify this we do a reduced search
989 // on all the other moves but the ttMove, if result is lower than ttValue minus
990 // a margin then we extend ttMove.
991 if ( singularExtensionNode
994 && pos.pl_move_is_legal(move, ci.pinned))
996 Value ttValue = value_from_tt(tte->value(), ss->ply);
998 if (abs(ttValue) < VALUE_KNOWN_WIN)
1000 Value rBeta = ttValue - int(depth);
1001 ss->excludedMove = move;
1002 ss->skipNullMove = true;
1003 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1004 ss->skipNullMove = false;
1005 ss->excludedMove = MOVE_NONE;
1006 ss->bestMove = MOVE_NONE;
1012 // Update current move (this must be done after singular extension search)
1013 newDepth = depth - ONE_PLY + ext;
1015 // Step 13. Futility pruning (is omitted in PV nodes)
1017 && !captureOrPromotion
1022 && (bestValue > VALUE_MATED_IN_PLY_MAX || bestValue == -VALUE_INFINITE))
1024 // Move count based pruning
1025 if ( moveCount >= futility_move_count(depth)
1026 && (!threatMove || !connected_threat(pos, move, threatMove)))
1029 lock_grab(&(sp->lock));
1034 // Value based pruning
1035 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1036 // but fixing this made program slightly weaker.
1037 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
1038 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
1039 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1041 if (futilityValue < beta)
1044 lock_grab(&(sp->lock));
1049 // Prune moves with negative SEE at low depths
1050 if ( predictedDepth < 2 * ONE_PLY
1051 && pos.see_sign(move) < 0)
1054 lock_grab(&(sp->lock));
1060 // Check for legality only before to do the move
1061 if (!pos.pl_move_is_legal(move, ci.pinned))
1067 ss->currentMove = move;
1068 if (!SpNode && !captureOrPromotion)
1069 movesSearched[playedMoveCount++] = move;
1071 // Step 14. Make the move
1072 pos.do_move(move, st, ci, givesCheck);
1074 // Step 15. Reduced depth search (LMR). If the move fails high will be
1075 // re-searched at full depth.
1076 if ( depth > 3 * ONE_PLY
1078 && !captureOrPromotion
1081 && ss->killers[0] != move
1082 && ss->killers[1] != move)
1084 ss->reduction = reduction<PvNode>(depth, moveCount);
1085 Depth d = newDepth - ss->reduction;
1086 alpha = SpNode ? sp->alpha : alpha;
1088 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1089 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1091 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1092 ss->reduction = DEPTH_ZERO;
1095 doFullDepthSearch = !isPvMove;
1097 // Step 16. Full depth search, when LMR is skipped or fails high
1098 if (doFullDepthSearch)
1100 alpha = SpNode ? sp->alpha : alpha;
1101 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1102 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1105 // Only for PV nodes do a full PV search on the first move or after a fail
1106 // high, in the latter case search only if value < beta, otherwise let the
1107 // parent node to fail low with value <= alpha and to try another move.
1108 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1109 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1110 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1112 // Step 17. Undo move
1113 pos.undo_move(move);
1115 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1117 // Step 18. Check for new best move
1120 lock_grab(&(sp->lock));
1121 bestValue = sp->bestValue;
1125 // Finished searching the move. If StopRequest is true, the search
1126 // was aborted because the user interrupted the search or because we
1127 // ran out of time. In this case, the return value of the search cannot
1128 // be trusted, and we don't update the best move and/or PV.
1129 if (RootNode && !Signals.stop)
1131 RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
1132 rm.nodes += pos.nodes_searched() - nodes;
1134 // PV move or new best move ?
1135 if (isPvMove || value > alpha)
1138 rm.extract_pv_from_tt(pos);
1140 // We record how often the best move has been changed in each
1141 // iteration. This information is used for time management: When
1142 // the best move changes frequently, we allocate some more time.
1143 if (!isPvMove && MultiPV == 1)
1147 // All other moves but the PV are set to the lowest value, this
1148 // is not a problem when sorting becuase sort is stable and move
1149 // position in the list is preserved, just the PV is pushed up.
1150 rm.score = -VALUE_INFINITE;
1154 if (value > bestValue)
1157 ss->bestMove = move;
1161 && value < beta) // We want always alpha < beta
1164 if (SpNode && !thread.cutoff_occurred())
1166 sp->bestValue = value;
1167 sp->ss->bestMove = move;
1169 sp->is_betaCutoff = (value >= beta);
1173 // Step 19. Check for split
1175 && depth >= Threads.min_split_depth()
1177 && Threads.available_slave_exists(pos.thread())
1179 && !thread.cutoff_occurred())
1180 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1181 threatMove, moveCount, &mp, NT);
1184 // Step 20. Check for mate and stalemate
1185 // All legal moves have been searched and if there are no legal moves, it
1186 // must be mate or stalemate. Note that we can have a false positive in
1187 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1188 // harmless because return value is discarded anyhow in the parent nodes.
1189 // If we are in a singular extension search then return a fail low score.
1191 return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1193 // If we have pruned all the moves without searching return a fail-low score
1194 if (bestValue == -VALUE_INFINITE)
1196 assert(!playedMoveCount);
1201 // Step 21. Update tables
1202 // Update transposition table entry, history and killers
1203 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1205 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1206 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1207 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1209 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1211 // Update killers and history only for non capture moves that fails high
1212 if ( bestValue >= beta
1213 && !pos.is_capture_or_promotion(move))
1215 if (move != ss->killers[0])
1217 ss->killers[1] = ss->killers[0];
1218 ss->killers[0] = move;
1220 update_history(pos, move, depth, movesSearched, playedMoveCount);
1226 // Here we have the lock still grabbed
1227 sp->is_slave[pos.thread()] = false;
1228 sp->nodes += pos.nodes_searched();
1229 lock_release(&(sp->lock));
1232 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1238 // qsearch() is the quiescence search function, which is called by the main
1239 // search function when the remaining depth is zero (or, to be more precise,
1240 // less than ONE_PLY).
1242 template <NodeType NT>
1243 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1245 const bool PvNode = (NT == PV);
1247 assert(NT == PV || NT == NonPV);
1248 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1249 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1250 assert(PvNode || alpha == beta - 1);
1252 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1256 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1257 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1261 Value oldAlpha = alpha;
1263 ss->bestMove = ss->currentMove = MOVE_NONE;
1264 ss->ply = (ss-1)->ply + 1;
1266 // Check for an instant draw or maximum ply reached
1267 if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1270 // Decide whether or not to include checks, this fixes also the type of
1271 // TT entry depth that we are going to use. Note that in qsearch we use
1272 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1273 inCheck = pos.in_check();
1274 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1276 // Transposition table lookup. At PV nodes, we don't use the TT for
1277 // pruning, but only for move ordering.
1278 tte = TT.probe(pos.get_key());
1279 ttMove = (tte ? tte->move() : MOVE_NONE);
1281 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1283 ss->bestMove = ttMove; // Can be MOVE_NONE
1284 return value_from_tt(tte->value(), ss->ply);
1287 // Evaluate the position statically
1290 bestValue = futilityBase = -VALUE_INFINITE;
1291 ss->eval = evalMargin = VALUE_NONE;
1292 enoughMaterial = false;
1298 assert(tte->static_value() != VALUE_NONE);
1300 evalMargin = tte->static_value_margin();
1301 ss->eval = bestValue = tte->static_value();
1304 ss->eval = bestValue = evaluate(pos, evalMargin);
1306 // Stand pat. Return immediately if static value is at least beta
1307 if (bestValue >= beta)
1310 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1315 if (PvNode && bestValue > alpha)
1318 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1319 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1322 // Initialize a MovePicker object for the current position, and prepare
1323 // to search the moves. Because the depth is <= 0 here, only captures,
1324 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1326 MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1329 // Loop through the moves until no moves remain or a beta cutoff occurs
1330 while ( bestValue < beta
1331 && (move = mp.get_next_move()) != MOVE_NONE)
1333 assert(is_ok(move));
1335 givesCheck = pos.move_gives_check(move, ci);
1343 && !is_promotion(move)
1344 && !pos.is_passed_pawn_push(move))
1346 futilityValue = futilityBase
1347 + PieceValueEndgame[pos.piece_on(move_to(move))]
1348 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1350 if (futilityValue < beta)
1352 if (futilityValue > bestValue)
1353 bestValue = futilityValue;
1358 // Prune moves with negative or equal SEE
1359 if ( futilityBase < beta
1360 && depth < DEPTH_ZERO
1361 && pos.see(move) <= 0)
1365 // Detect non-capture evasions that are candidate to be pruned
1366 evasionPrunable = !PvNode
1368 && bestValue > VALUE_MATED_IN_PLY_MAX
1369 && !pos.is_capture(move)
1370 && !pos.can_castle(pos.side_to_move());
1372 // Don't search moves with negative SEE values
1374 && (!inCheck || evasionPrunable)
1376 && !is_promotion(move)
1377 && pos.see_sign(move) < 0)
1380 // Don't search useless checks
1385 && !pos.is_capture_or_promotion(move)
1386 && ss->eval + PawnValueMidgame / 4 < beta
1387 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1389 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1390 bestValue = ss->eval + PawnValueMidgame / 4;
1395 // Check for legality only before to do the move
1396 if (!pos.pl_move_is_legal(move, ci.pinned))
1399 ss->currentMove = move;
1401 // Make and search the move
1402 pos.do_move(move, st, ci, givesCheck);
1403 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1404 pos.undo_move(move);
1406 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1409 if (value > bestValue)
1412 ss->bestMove = move;
1416 && value < beta) // We want always alpha < beta
1421 // All legal moves have been searched. A special case: If we're in check
1422 // and no legal moves were found, it is checkmate.
1423 if (inCheck && bestValue == -VALUE_INFINITE)
1424 return value_mated_in(ss->ply);
1426 // Update transposition table
1427 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1428 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1429 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1431 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1433 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1439 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1440 // bestValue is updated only when returning false because in that case move
1443 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1445 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1446 Square from, to, ksq, victimSq;
1449 Value futilityValue, bv = *bestValue;
1451 from = move_from(move);
1453 them = flip(pos.side_to_move());
1454 ksq = pos.king_square(them);
1455 kingAtt = pos.attacks_from<KING>(ksq);
1456 pc = pos.piece_on(from);
1458 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1459 oldAtt = pos.attacks_from(pc, from, occ);
1460 newAtt = pos.attacks_from(pc, to, occ);
1462 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1463 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1465 if (!(b && (b & (b - 1))))
1468 // Rule 2. Queen contact check is very dangerous
1469 if ( type_of(pc) == QUEEN
1470 && bit_is_set(kingAtt, to))
1473 // Rule 3. Creating new double threats with checks
1474 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1478 victimSq = pop_1st_bit(&b);
1479 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1481 // Note that here we generate illegal "double move"!
1482 if ( futilityValue >= beta
1483 && pos.see_sign(make_move(from, victimSq)) >= 0)
1486 if (futilityValue > bv)
1490 // Update bestValue only if check is not dangerous (because we will prune the move)
1496 // connected_moves() tests whether two moves are 'connected' in the sense
1497 // that the first move somehow made the second move possible (for instance
1498 // if the moving piece is the same in both moves). The first move is assumed
1499 // to be the move that was made to reach the current position, while the
1500 // second move is assumed to be a move from the current position.
1502 bool connected_moves(const Position& pos, Move m1, Move m2) {
1504 Square f1, t1, f2, t2;
1511 // Case 1: The moving piece is the same in both moves
1517 // Case 2: The destination square for m2 was vacated by m1
1523 // Case 3: Moving through the vacated square
1524 p2 = pos.piece_on(f2);
1525 if ( piece_is_slider(p2)
1526 && bit_is_set(squares_between(f2, t2), f1))
1529 // Case 4: The destination square for m2 is defended by the moving piece in m1
1530 p1 = pos.piece_on(t1);
1531 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1534 // Case 5: Discovered check, checking piece is the piece moved in m1
1535 ksq = pos.king_square(pos.side_to_move());
1536 if ( piece_is_slider(p1)
1537 && bit_is_set(squares_between(t1, ksq), f2))
1539 Bitboard occ = pos.occupied_squares();
1540 clear_bit(&occ, f2);
1541 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1548 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1549 // "plies to mate from the current ply". Non-mate scores are unchanged.
1550 // The function is called before storing a value to the transposition table.
1552 Value value_to_tt(Value v, int ply) {
1554 if (v >= VALUE_MATE_IN_PLY_MAX)
1557 if (v <= VALUE_MATED_IN_PLY_MAX)
1564 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1565 // the transposition table to a mate score corrected for the current ply.
1567 Value value_from_tt(Value v, int ply) {
1569 if (v >= VALUE_MATE_IN_PLY_MAX)
1572 if (v <= VALUE_MATED_IN_PLY_MAX)
1579 // connected_threat() tests whether it is safe to forward prune a move or if
1580 // is somehow connected to the threat move returned by null search.
1582 bool connected_threat(const Position& pos, Move m, Move threat) {
1585 assert(is_ok(threat));
1586 assert(!pos.is_capture_or_promotion(m));
1587 assert(!pos.is_passed_pawn_push(m));
1589 Square mfrom, mto, tfrom, tto;
1591 mfrom = move_from(m);
1593 tfrom = move_from(threat);
1594 tto = move_to(threat);
1596 // Case 1: Don't prune moves which move the threatened piece
1600 // Case 2: If the threatened piece has value less than or equal to the
1601 // value of the threatening piece, don't prune moves which defend it.
1602 if ( pos.is_capture(threat)
1603 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1604 || type_of(pos.piece_on(tfrom)) == KING)
1605 && pos.move_attacks_square(m, tto))
1608 // Case 3: If the moving piece in the threatened move is a slider, don't
1609 // prune safe moves which block its ray.
1610 if ( piece_is_slider(pos.piece_on(tfrom))
1611 && bit_is_set(squares_between(tfrom, tto), mto)
1612 && pos.see_sign(m) >= 0)
1619 // can_return_tt() returns true if a transposition table score can be used to
1620 // cut-off at a given point in search.
1622 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1624 Value v = value_from_tt(tte->value(), ply);
1626 return ( tte->depth() >= depth
1627 || v >= std::max(VALUE_MATE_IN_PLY_MAX, beta)
1628 || v < std::min(VALUE_MATED_IN_PLY_MAX, beta))
1630 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1631 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1635 // refine_eval() returns the transposition table score if possible, otherwise
1636 // falls back on static position evaluation.
1638 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1642 Value v = value_from_tt(tte->value(), ply);
1644 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1645 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1652 // update_history() registers a good move that produced a beta-cutoff in
1653 // history and marks as failures all the other moves of that ply.
1655 void update_history(const Position& pos, Move move, Depth depth,
1656 Move movesSearched[], int moveCount) {
1658 Value bonus = Value(int(depth) * int(depth));
1660 H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1662 for (int i = 0; i < moveCount - 1; i++)
1664 m = movesSearched[i];
1668 H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1673 // current_search_time() returns the number of milliseconds which have passed
1674 // since the beginning of the current search.
1676 int elapsed_time(bool reset) {
1678 static int searchStartTime;
1681 searchStartTime = get_system_time();
1683 return get_system_time() - searchStartTime;
1687 // score_to_uci() converts a value to a string suitable for use with the UCI
1688 // protocol specifications:
1690 // cp <x> The score from the engine's point of view in centipawns.
1691 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1692 // use negative values for y.
1694 string score_to_uci(Value v, Value alpha, Value beta) {
1696 std::stringstream s;
1698 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1699 s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1701 s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1703 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1709 // speed_to_uci() returns a string with time stats of current search suitable
1710 // to be sent to UCI gui.
1712 string speed_to_uci(int64_t nodes) {
1714 std::stringstream s;
1715 int t = elapsed_time();
1717 s << " nodes " << nodes
1718 << " nps " << (t > 0 ? int(nodes * 1000 / t) : 0)
1725 // pv_to_uci() returns a string with information on the current PV line
1726 // formatted according to UCI specification.
1728 string pv_to_uci(const Move pv[], int pvNum, bool chess960) {
1730 std::stringstream s;
1732 s << " multipv " << pvNum << " pv " << set960(chess960);
1734 for ( ; *pv != MOVE_NONE; pv++)
1741 // depth_to_uci() returns a string with information on the current depth and
1742 // seldepth formatted according to UCI specification.
1744 string depth_to_uci(Depth depth) {
1746 std::stringstream s;
1749 // Retrieve max searched depth among threads
1750 for (int i = 0; i < Threads.size(); i++)
1751 if (Threads[i].maxPly > selDepth)
1752 selDepth = Threads[i].maxPly;
1754 s << " depth " << depth / ONE_PLY << " seldepth " << selDepth;
1760 // pretty_pv() creates a human-readable string from a position and a PV. It is
1761 // used to write search information to the log file (which is created when the
1762 // UCI parameter "Use Search Log" is "true"). It uses the two below helper to
1763 // pretty format time and score respectively.
1765 string time_to_string(int millisecs) {
1767 const int MSecMinute = 1000 * 60;
1768 const int MSecHour = 1000 * 60 * 60;
1770 int hours = millisecs / MSecHour;
1771 int minutes = (millisecs % MSecHour) / MSecMinute;
1772 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1774 std::stringstream s;
1779 s << std::setfill('0') << std::setw(2) << minutes << ':'
1780 << std::setw(2) << seconds;
1784 string score_to_string(Value v) {
1786 std::stringstream s;
1788 if (v >= VALUE_MATE_IN_PLY_MAX)
1789 s << "#" << (VALUE_MATE - v + 1) / 2;
1790 else if (v <= VALUE_MATED_IN_PLY_MAX)
1791 s << "-#" << (VALUE_MATE + v) / 2;
1793 s << std::setprecision(2) << std::fixed << std::showpos
1794 << float(v) / PawnValueMidgame;
1799 string pretty_pv(Position& pos, int depth, Value value, int time, Move pv[]) {
1801 const int64_t K = 1000;
1802 const int64_t M = 1000000;
1804 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1806 string san, padding;
1808 std::stringstream s;
1810 s << set960(pos.is_chess960())
1811 << std::setw(2) << depth
1812 << std::setw(8) << score_to_string(value)
1813 << std::setw(8) << time_to_string(time);
1815 if (pos.nodes_searched() < M)
1816 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1817 else if (pos.nodes_searched() < K * M)
1818 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1820 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1822 padding = string(s.str().length(), ' ');
1823 length = padding.length();
1825 while (*m != MOVE_NONE)
1827 san = move_to_san(pos, *m);
1829 if (length + san.length() > 80)
1831 s << "\n" + padding;
1832 length = padding.length();
1836 length += san.length() + 1;
1838 pos.do_move(*m++, *st++);
1841 // Restore original position before to leave
1843 pos.undo_move(*--m);
1849 // When playing with strength handicap choose best move among the MultiPV set
1850 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1852 void do_skill_level(Move* best, Move* ponder) {
1854 assert(MultiPV > 1);
1858 // PRNG sequence should be not deterministic
1859 for (int i = abs(get_system_time() % 50); i > 0; i--)
1860 rk.rand<unsigned>();
1862 // Rml list is already sorted by score in descending order
1863 size_t size = std::min(MultiPV, RootMoves.size());
1864 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1865 int weakness = 120 - 2 * SkillLevel;
1866 int max_s = -VALUE_INFINITE;
1868 // Choose best move. For each move score we add two terms both dependent on
1869 // weakness, one deterministic and bigger for weaker moves, and one random,
1870 // then we choose the move with the resulting highest score.
1871 for (size_t i = 0; i < size; i++)
1873 int s = RootMoves[i].score;
1875 // Don't allow crazy blunders even at very low skills
1876 if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1879 // This is our magic formula
1880 s += ( weakness * int(RootMoves[0].score - s)
1881 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1886 *best = RootMoves[i].pv[0];
1887 *ponder = RootMoves[i].pv[1];
1893 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1894 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1895 // allow to always have a ponder move even when we fail high at root and also a
1896 // long PV to print that is important for position analysis.
1898 void RootMove::extract_pv_from_tt(Position& pos) {
1900 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1905 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1909 pos.do_move(m, *st++);
1911 while ( (tte = TT.probe(pos.get_key())) != NULL
1912 && tte->move() != MOVE_NONE
1913 && pos.is_pseudo_legal(tte->move())
1914 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1916 && (!pos.is_draw<false>() || ply < 2))
1918 pv.push_back(tte->move());
1919 pos.do_move(tte->move(), *st++);
1922 pv.push_back(MOVE_NONE);
1924 do pos.undo_move(pv[--ply]); while (ply);
1928 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
1929 // the PV back into the TT. This makes sure the old PV moves are searched
1930 // first, even if the old TT entries have been overwritten.
1932 void RootMove::insert_pv_in_tt(Position& pos) {
1934 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1937 Value v, m = VALUE_NONE;
1940 assert(pv[0] != MOVE_NONE && pos.is_pseudo_legal(pv[0]));
1946 // Don't overwrite existing correct entries
1947 if (!tte || tte->move() != pv[ply])
1949 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1950 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
1952 pos.do_move(pv[ply], *st++);
1954 } while (pv[++ply] != MOVE_NONE);
1956 do pos.undo_move(pv[--ply]); while (ply);
1962 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1963 /// The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
1964 /// for which the thread is the master.
1966 void Thread::idle_loop(SplitPoint* sp) {
1970 // If we are not searching, wait for a condition to be signaled
1971 // instead of wasting CPU time polling for work.
1974 || (Threads.use_sleeping_threads() && !is_searching))
1976 assert((!sp && threadID) || Threads.use_sleeping_threads());
1984 // Grab the lock to avoid races with Thread::wake_up()
1985 lock_grab(&sleepLock);
1987 // If we are master and all slaves have finished don't go to sleep
1988 if (sp && Threads.split_point_finished(sp))
1990 lock_release(&sleepLock);
1994 // Do sleep after retesting sleep conditions under lock protection, in
1995 // particular we need to avoid a deadlock in case a master thread has,
1996 // in the meanwhile, allocated us and sent the wake_up() call before we
1997 // had the chance to grab the lock.
1998 if (do_sleep || !is_searching)
1999 cond_wait(&sleepCond, &sleepLock);
2001 lock_release(&sleepLock);
2004 // If this thread has been assigned work, launch a search
2007 assert(!do_terminate);
2009 // Copy split point position and search stack and call search()
2010 Stack ss[PLY_MAX_PLUS_2];
2011 SplitPoint* tsp = splitPoint;
2012 Position pos(*tsp->pos, threadID);
2014 memcpy(ss, tsp->ss - 1, 4 * sizeof(Stack));
2017 if (tsp->nodeType == Root)
2018 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2019 else if (tsp->nodeType == PV)
2020 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2021 else if (tsp->nodeType == NonPV)
2022 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2026 assert(is_searching);
2028 is_searching = false;
2030 // Wake up master thread so to allow it to return from the idle loop in
2031 // case we are the last slave of the split point.
2032 if ( Threads.use_sleeping_threads()
2033 && threadID != tsp->master
2034 && !Threads[tsp->master].is_searching)
2035 Threads[tsp->master].wake_up();
2038 // If this thread is the master of a split point and all slaves have
2039 // finished their work at this split point, return from the idle loop.
2040 if (sp && Threads.split_point_finished(sp))
2042 // Because sp->is_slave[] is reset under lock protection,
2043 // be sure sp->lock has been released before to return.
2044 lock_grab(&(sp->lock));
2045 lock_release(&(sp->lock));
2052 /// do_timer_event() is called by the timer thread when the timer triggers. It
2053 /// is used to print debug info and, more important, to detect when we are out of
2054 /// available time and so stop the search.
2056 void do_timer_event() {
2058 static int lastInfoTime;
2059 int e = elapsed_time();
2061 if (get_system_time() - lastInfoTime >= 1000 || !lastInfoTime)
2063 lastInfoTime = get_system_time();
2066 dbg_print_hit_rate();
2072 bool stillAtFirstMove = Signals.firstRootMove
2073 && !Signals.failedLowAtRoot
2074 && e > TimeMgr.available_time();
2076 bool noMoreTime = e > TimeMgr.maximum_time()
2077 || stillAtFirstMove;
2079 if ( (Limits.useTimeManagement() && noMoreTime)
2080 || (Limits.maxTime && e >= Limits.maxTime)
2081 /* missing nodes limit */ ) // FIXME
2082 Signals.stop = true;