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> RootMoves;
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
64 // in the case of moves which fail low). Score is normally set at
65 // -VALUE_INFINITE for all non-pv moves.
68 // RootMove::operator<() is the comparison function used when
69 // sorting the moves. A move m1 is considered to be better
70 // than a move m2 if it has an higher score
71 bool operator<(const RootMove& m) const { return score < m.score; }
73 void extract_pv_from_tt(Position& pos);
74 void insert_pv_in_tt(Position& pos);
82 // RootMoveList struct is mainly a std::vector of RootMove objects
83 struct RootMoveList : public std::vector<RootMove> {
85 void init(Position& pos, Move rootMoves[]);
86 RootMove* find(const Move& m, int startIndex = 0);
94 // Lookup table to check if a Piece is a slider and its access function
95 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
96 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
98 // Maximum depth for razoring
99 const Depth RazorDepth = 4 * ONE_PLY;
101 // Dynamic razoring margin based on depth
102 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
104 // Maximum depth for use of dynamic threat detection when null move fails low
105 const Depth ThreatDepth = 5 * ONE_PLY;
107 // Minimum depth for use of internal iterative deepening
108 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
110 // At Non-PV nodes we do an internal iterative deepening search
111 // when the static evaluation is bigger then beta - IIDMargin.
112 const Value IIDMargin = Value(0x100);
114 // Minimum depth for use of singular extension
115 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
117 // Futility margin for quiescence search
118 const Value FutilityMarginQS = Value(0x80);
120 // Futility lookup tables (initialized at startup) and their access functions
121 Value FutilityMargins[16][64]; // [depth][moveNumber]
122 int FutilityMoveCounts[32]; // [depth]
124 inline Value futility_margin(Depth d, int mn) {
126 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
127 : 2 * VALUE_INFINITE;
130 inline int futility_move_count(Depth d) {
132 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
135 // Reduction lookup tables (initialized at startup) and their access function
136 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
138 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
140 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
143 // Easy move margin. An easy move candidate must be at least this much
144 // better than the second best move.
145 const Value EasyMoveMargin = Value(0x150);
148 /// Namespace variables
151 size_t MultiPV, UCIMultiPV, MultiPVIdx;
154 bool SkillLevelEnabled;
160 Move id_loop(Position& pos, Move rootMoves[], Move* ponderMove);
162 template <NodeType NT>
163 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
165 template <NodeType NT>
166 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
168 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
169 bool connected_moves(const Position& pos, Move m1, Move m2);
170 Value value_to_tt(Value v, int ply);
171 Value value_from_tt(Value v, int ply);
172 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
173 bool connected_threat(const Position& pos, Move m, Move threat);
174 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
175 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
176 void do_skill_level(Move* best, Move* ponder);
178 int elapsed_time(bool reset = false);
179 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
180 string speed_to_uci(int64_t nodes);
181 string pv_to_uci(const Move pv[], int pvNum, bool chess960);
182 string pretty_pv(Position& pos, int depth, Value score, int time, Move pv[]);
183 string depth_to_uci(Depth depth);
185 // MovePickerExt template class extends MovePicker and allows to choose at compile
186 // time the proper moves source according to the type of node. In the default case
187 // we simply create and use a standard MovePicker object.
188 template<bool SpNode> struct MovePickerExt : 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) {}
194 // In case of a SpNode we use split point's shared MovePicker object as moves source
195 template<> struct MovePickerExt<true> : public MovePicker {
197 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
198 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
200 Move get_next_move() { return mp->get_next_move(); }
204 // Overload operator<<() to make it easier to print moves in a coordinate
205 // notation compatible with UCI protocol.
206 std::ostream& operator<<(std::ostream& os, Move m) {
208 bool chess960 = (os.iword(0) != 0); // See set960()
209 return os << move_to_uci(m, chess960);
212 // When formatting a move for std::cout we must know if we are in Chess960
213 // or not. To keep using the handy operator<<() on the move the trick is to
214 // embed this flag in the stream itself. Function-like named enum set960 is
215 // used as a custom manipulator and the stream internal general-purpose array,
216 // accessed through ios_base::iword(), is used to pass the flag to the move's
217 // operator<<() that will read it to properly format castling moves.
220 std::ostream& operator<< (std::ostream& os, const set960& f) {
222 os.iword(0) = int(f);
226 // is_dangerous() checks whether a move belongs to some classes of known
227 // 'dangerous' moves so that we avoid to prune it.
228 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
230 // Test for a pawn pushed to 7th or a passed pawn move
231 if (type_of(pos.piece_on(move_from(m))) == PAWN)
233 Color c = pos.side_to_move();
234 if ( relative_rank(c, move_to(m)) == RANK_7
235 || pos.pawn_is_passed(c, move_to(m)))
239 // Test for a capture that triggers a pawn endgame
240 if ( captureOrPromotion
241 && type_of(pos.piece_on(move_to(m))) != PAWN
242 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
243 - PieceValueMidgame[pos.piece_on(move_to(m))] == VALUE_ZERO)
253 /// init_search() is called during startup to initialize various lookup tables
255 void Search::init() {
257 int d; // depth (ONE_PLY == 2)
258 int hd; // half depth (ONE_PLY == 1)
261 // Init reductions array
262 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
264 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
265 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
266 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
267 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
270 // Init futility margins array
271 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
272 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
274 // Init futility move count array
275 for (d = 0; d < 32; d++)
276 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
280 /// perft() is our utility to verify move generation. All the leaf nodes up to
281 /// the given depth are generated and counted and the sum returned.
283 int64_t Search::perft(Position& pos, Depth depth) {
288 MoveList<MV_LEGAL> ml(pos);
290 // At the last ply just return the number of moves (leaf nodes)
291 if (depth <= ONE_PLY)
295 for ( ; !ml.end(); ++ml)
297 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
298 sum += perft(pos, depth - ONE_PLY);
299 pos.undo_move(ml.move());
305 /// think() is the external interface to Stockfish's search, and is called by the
306 /// main thread when the program receives the UCI 'go' command. It searches from
307 /// RootPosition and at the end prints the "bestmove" to output.
309 void Search::think() {
311 static Book book; // Defined static to initialize the PRNG only once
313 Position& pos = RootPosition;
315 TimeMgr.init(Limits, pos.startpos_ply_counter());
317 // Set output stream mode: normal or chess960. Castling notation is different
318 cout << set960(pos.is_chess960());
320 if (Options["OwnBook"].value<bool>())
322 if (Options["Book File"].value<string>() != book.name())
323 book.open(Options["Book File"].value<string>());
325 Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
326 if (bookMove != MOVE_NONE)
328 if (!Signals.stop && (Limits.ponder || Limits.infinite))
329 Threads.wait_for_stop_or_ponderhit();
331 cout << "bestmove " << bookMove << endl;
336 // Read UCI options: GUI could change UCI parameters during the game
337 read_evaluation_uci_options(pos.side_to_move());
338 Threads.read_uci_options();
340 TT.set_size(Options["Hash"].value<int>());
341 if (Options["Clear Hash"].value<bool>())
343 Options["Clear Hash"].set_value("false");
347 UCIMultiPV = Options["MultiPV"].value<size_t>();
348 SkillLevel = Options["Skill Level"].value<size_t>();
350 // Do we have to play with skill handicap? In this case enable MultiPV that
351 // we will use behind the scenes to retrieve a set of possible moves.
352 SkillLevelEnabled = (SkillLevel < 20);
353 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
355 if (Options["Use Search Log"].value<bool>())
357 Log log(Options["Search Log Filename"].value<string>());
358 log << "\nSearching: " << pos.to_fen()
359 << "\ninfinite: " << Limits.infinite
360 << " ponder: " << Limits.ponder
361 << " time: " << Limits.time
362 << " increment: " << Limits.increment
363 << " moves to go: " << Limits.movesToGo
367 // Wake up needed threads and reset maxPly counter
368 for (int i = 0; i < Threads.size(); i++)
370 Threads[i].maxPly = 0;
371 Threads[i].wake_up();
374 // Set best timer interval to avoid lagging under time pressure. Timer is
375 // used to check for remaining available thinking time.
376 if (TimeMgr.available_time())
377 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
379 Threads.set_timer(100);
381 // We're ready to start thinking. Call the iterative deepening loop function
382 Move ponderMove = MOVE_NONE;
383 Move bestMove = id_loop(pos, &RootMoves[0], &ponderMove);
385 // Stop timer and send all the slaves to sleep, if not already sleeping
386 Threads.set_timer(0);
389 if (Options["Use Search Log"].value<bool>())
391 int e = elapsed_time();
393 Log log(Options["Search Log Filename"].value<string>());
394 log << "Nodes: " << pos.nodes_searched()
395 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
396 << "\nBest move: " << move_to_san(pos, bestMove);
399 pos.do_move(bestMove, st);
400 log << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
401 pos.undo_move(bestMove); // Return from think() with unchanged position
404 // When we reach max depth we arrive here even without a StopRequest, but if
405 // we are pondering or in infinite search, we shouldn't print the best move
406 // before we are told to do so.
407 if (!Signals.stop && (Limits.ponder || Limits.infinite))
408 Threads.wait_for_stop_or_ponderhit();
410 // Could be MOVE_NONE when searching on a stalemate position
411 cout << "bestmove " << bestMove;
413 // UCI protol is not clear on allowing sending an empty ponder move, instead
414 // it is clear that ponder move is optional. So skip it if empty.
415 if (ponderMove != MOVE_NONE)
416 cout << " ponder " << ponderMove;
424 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
425 // with increasing depth until the allocated thinking time has been consumed,
426 // user stops the search, or the maximum search depth is reached.
428 Move id_loop(Position& pos, Move rootMoves[], Move* ponderMove) {
430 Stack ss[PLY_MAX_PLUS_2];
431 Value bestValues[PLY_MAX_PLUS_2];
432 int bestMoveChanges[PLY_MAX_PLUS_2];
433 int depth, aspirationDelta;
434 Value bestValue, alpha, beta;
435 Move bestMove, skillBest, skillPonder;
436 bool bestMoveNeverChanged = true;
438 memset(ss, 0, 4 * sizeof(Stack));
441 *ponderMove = bestMove = skillBest = skillPonder = MOVE_NONE;
442 depth = aspirationDelta = 0;
443 bestValue = alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
444 ss->currentMove = MOVE_NULL; // Hack to skip update gains
445 Rml.init(pos, rootMoves);
447 // Handle special case of searching on a mate/stalemate position
450 cout << "info" << depth_to_uci(DEPTH_ZERO)
451 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW, alpha, beta) << endl;
456 // Iterative deepening loop until requested to stop or target depth reached
457 while (!Signals.stop && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
459 // Save now last iteration's scores, before Rml moves are reordered
460 for (size_t i = 0; i < Rml.size(); i++)
461 Rml[i].prevScore = Rml[i].score;
463 Rml.bestMoveChanges = 0;
465 // MultiPV loop. We perform a full root search for each PV line
466 for (MultiPVIdx = 0; MultiPVIdx < std::min(MultiPV, Rml.size()); MultiPVIdx++)
468 // Calculate dynamic aspiration window based on previous iterations
469 if (depth >= 5 && abs(Rml[MultiPVIdx].prevScore) < VALUE_KNOWN_WIN)
471 int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
472 int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
474 aspirationDelta = std::min(std::max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
475 aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
477 alpha = std::max(Rml[MultiPVIdx].prevScore - aspirationDelta, -VALUE_INFINITE);
478 beta = std::min(Rml[MultiPVIdx].prevScore + aspirationDelta, VALUE_INFINITE);
482 alpha = -VALUE_INFINITE;
483 beta = VALUE_INFINITE;
486 // Start with a small aspiration window and, in case of fail high/low,
487 // research with bigger window until not failing high/low anymore.
489 // Search starts from ss+1 to allow referencing (ss-1). This is
490 // needed by update gains and ss copy when splitting at Root.
491 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
493 // Bring to front the best move. It is critical that sorting is
494 // done with a stable algorithm because all the values but the first
495 // and eventually the new best one are set to -VALUE_INFINITE and
496 // we want to keep the same order for all the moves but the new
497 // PV that goes to the front. Note that in case of MultiPV search
498 // the already searched PV lines are preserved.
499 sort<RootMove>(Rml.begin() + MultiPVIdx, Rml.end());
501 // In case we have found an exact score and we are going to leave
502 // the fail high/low loop then reorder the PV moves, otherwise
503 // leave the last PV move in its position so to be searched again.
504 // Of course this is needed only in MultiPV search.
505 if (MultiPVIdx && bestValue > alpha && bestValue < beta)
506 sort<RootMove>(Rml.begin(), Rml.begin() + MultiPVIdx);
508 // Write PV back to transposition table in case the relevant entries
509 // have been overwritten during the search.
510 for (size_t i = 0; i <= MultiPVIdx; i++)
511 Rml[i].insert_pv_in_tt(pos);
513 // If search has been stopped exit the aspiration window loop,
514 // note that sorting and writing PV back to TT is safe becuase
515 // Rml is still valid, although refers to the previous iteration.
519 // Send full PV info to GUI if we are going to leave the loop or
520 // if we have a fail high/low and we are deep in the search. UCI
521 // protocol requires to send all the PV lines also if are still
522 // to be searched and so refer to the previous search's score.
523 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
524 for (size_t i = 0; i < std::min(UCIMultiPV, Rml.size()); i++)
526 bool updated = (i <= MultiPVIdx);
528 if (depth == 1 && !updated)
531 Depth d = (updated ? depth : depth - 1) * ONE_PLY;
532 Value s = (updated ? Rml[i].score : Rml[i].prevScore);
536 << (i == MultiPVIdx ? score_to_uci(s, alpha, beta) : score_to_uci(s))
537 << speed_to_uci(pos.nodes_searched())
538 << pv_to_uci(&Rml[i].pv[0], i + 1, pos.is_chess960())
542 // In case of failing high/low increase aspiration window and
543 // research, otherwise exit the fail high/low loop.
544 if (bestValue >= beta)
546 beta = std::min(beta + aspirationDelta, VALUE_INFINITE);
547 aspirationDelta += aspirationDelta / 2;
549 else if (bestValue <= alpha)
551 Signals.failedLowAtRoot = true;
552 Signals.stopOnPonderhit = false;
554 alpha = std::max(alpha - aspirationDelta, -VALUE_INFINITE);
555 aspirationDelta += aspirationDelta / 2;
560 } while (abs(bestValue) < VALUE_KNOWN_WIN);
563 bestMove = Rml[0].pv[0];
564 *ponderMove = Rml[0].pv[1];
565 bestValues[depth] = bestValue;
566 bestMoveChanges[depth] = Rml.bestMoveChanges;
568 // Skills: Do we need to pick now the best and the ponder moves ?
569 if (SkillLevelEnabled && depth == 1 + SkillLevel)
570 do_skill_level(&skillBest, &skillPonder);
572 if (Options["Use Search Log"].value<bool>())
574 Log log(Options["Search Log Filename"].value<string>());
575 log << pretty_pv(pos, depth, bestValue, elapsed_time(), &Rml[0].pv[0]) << endl;
578 // Filter out startup noise when monitoring best move stability
579 if (depth > 2 && bestMoveChanges[depth])
580 bestMoveNeverChanged = false;
582 // Do we have time for the next iteration? Can we stop searching now?
583 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
585 bool stop = false; // Local variable instead of the volatile Signals.stop
587 // Take in account some extra time if the best move has changed
588 if (depth > 4 && depth < 50)
589 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
591 // Stop search if most of available time is already consumed. We probably don't
592 // have enough time to search the first move at the next iteration anyway.
593 if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
596 // Stop search early if one move seems to be much better than others
599 && ( bestMoveNeverChanged
600 || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
602 Value rBeta = bestValue - EasyMoveMargin;
603 (ss+1)->excludedMove = bestMove;
604 (ss+1)->skipNullMove = true;
605 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
606 (ss+1)->skipNullMove = false;
607 (ss+1)->excludedMove = MOVE_NONE;
615 // If we are allowed to ponder do not stop the search now but
616 // keep pondering until GUI sends "ponderhit" or "stop".
618 Signals.stopOnPonderhit = true;
625 // When using skills overwrite best and ponder moves with the sub-optimal ones
626 if (SkillLevelEnabled)
628 if (skillBest == MOVE_NONE) // Still unassigned ?
629 do_skill_level(&skillBest, &skillPonder);
631 bestMove = skillBest;
632 *ponderMove = skillPonder;
639 // search<>() is the main search function for both PV and non-PV nodes and for
640 // normal and SplitPoint nodes. When called just after a split point the search
641 // is simpler because we have already probed the hash table, done a null move
642 // search, and searched the first move before splitting, we don't have to repeat
643 // all this work again. We also don't need to store anything to the hash table
644 // here: This is taken care of after we return from the split point.
646 template <NodeType NT>
647 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
649 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
650 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
651 const bool RootNode = (NT == Root || NT == SplitPointRoot);
653 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
654 assert(beta > alpha && beta <= VALUE_INFINITE);
655 assert(PvNode || alpha == beta - 1);
656 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
658 Move movesSearched[MAX_MOVES];
663 Move ttMove, move, excludedMove, threatMove;
666 Value bestValue, value, oldAlpha;
667 Value refinedValue, nullValue, futilityBase, futilityValue;
668 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
669 bool captureOrPromotion, dangerous, doFullDepthSearch;
670 int moveCount = 0, playedMoveCount = 0;
671 Thread& thread = Threads[pos.thread()];
672 SplitPoint* sp = NULL;
674 refinedValue = bestValue = value = -VALUE_INFINITE;
676 inCheck = pos.in_check();
677 ss->ply = (ss-1)->ply + 1;
679 // Used to send selDepth info to GUI
680 if (PvNode && thread.maxPly < ss->ply)
681 thread.maxPly = ss->ply;
683 // Step 1. Initialize node
686 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
687 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
688 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
694 ttMove = excludedMove = MOVE_NONE;
695 threatMove = sp->threatMove;
696 goto split_point_start;
699 // Step 2. Check for aborted search and immediate draw
701 || pos.is_draw<false>()
702 || ss->ply > PLY_MAX) && !RootNode)
705 // Step 3. Mate distance pruning
708 alpha = std::max(value_mated_in(ss->ply), alpha);
709 beta = std::min(value_mate_in(ss->ply+1), beta);
714 // Step 4. Transposition table lookup
715 // We don't want the score of a partial search to overwrite a previous full search
716 // TT value, so we use a different position key in case of an excluded move.
717 excludedMove = ss->excludedMove;
718 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
719 tte = TT.probe(posKey);
720 ttMove = RootNode ? Rml[MultiPVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
722 // At PV nodes we check for exact scores, while at non-PV nodes we check for
723 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
724 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
725 // we should also update RootMoveList to avoid bogus output.
726 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
727 : can_return_tt(tte, depth, beta, ss->ply)))
730 ss->bestMove = move = ttMove; // Can be MOVE_NONE
731 value = value_from_tt(tte->value(), ss->ply);
735 && !pos.is_capture_or_promotion(move)
736 && move != ss->killers[0])
738 ss->killers[1] = ss->killers[0];
739 ss->killers[0] = move;
744 // Step 5. Evaluate the position statically and update parent's gain statistics
746 ss->eval = ss->evalMargin = VALUE_NONE;
749 assert(tte->static_value() != VALUE_NONE);
751 ss->eval = tte->static_value();
752 ss->evalMargin = tte->static_value_margin();
753 refinedValue = refine_eval(tte, ss->eval, ss->ply);
757 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
758 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
761 // Update gain for the parent non-capture move given the static position
762 // evaluation before and after the move.
763 if ( (move = (ss-1)->currentMove) != MOVE_NULL
764 && (ss-1)->eval != VALUE_NONE
765 && ss->eval != VALUE_NONE
766 && pos.captured_piece_type() == PIECE_TYPE_NONE
767 && !is_special(move))
769 Square to = move_to(move);
770 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
773 // Step 6. Razoring (is omitted in PV nodes)
775 && depth < RazorDepth
777 && refinedValue + razor_margin(depth) < beta
778 && ttMove == MOVE_NONE
779 && abs(beta) < VALUE_MATE_IN_PLY_MAX
780 && !pos.has_pawn_on_7th(pos.side_to_move()))
782 Value rbeta = beta - razor_margin(depth);
783 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
785 // Logically we should return (v + razor_margin(depth)), but
786 // surprisingly this did slightly weaker in tests.
790 // Step 7. Static null move pruning (is omitted in PV nodes)
791 // We're betting that the opponent doesn't have a move that will reduce
792 // the score by more than futility_margin(depth) if we do a null move.
795 && depth < RazorDepth
797 && refinedValue - futility_margin(depth, 0) >= beta
798 && abs(beta) < VALUE_MATE_IN_PLY_MAX
799 && pos.non_pawn_material(pos.side_to_move()))
800 return refinedValue - futility_margin(depth, 0);
802 // Step 8. Null move search with verification search (is omitted in PV nodes)
807 && refinedValue >= beta
808 && abs(beta) < VALUE_MATE_IN_PLY_MAX
809 && pos.non_pawn_material(pos.side_to_move()))
811 ss->currentMove = MOVE_NULL;
813 // Null move dynamic reduction based on depth
814 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
816 // Null move dynamic reduction based on value
817 if (refinedValue - PawnValueMidgame > beta)
820 pos.do_null_move<true>(st);
821 (ss+1)->skipNullMove = true;
822 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
823 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
824 (ss+1)->skipNullMove = false;
825 pos.do_null_move<false>(st);
827 if (nullValue >= beta)
829 // Do not return unproven mate scores
830 if (nullValue >= VALUE_MATE_IN_PLY_MAX)
833 if (depth < 6 * ONE_PLY)
836 // Do verification search at high depths
837 ss->skipNullMove = true;
838 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
839 ss->skipNullMove = false;
846 // The null move failed low, which means that we may be faced with
847 // some kind of threat. If the previous move was reduced, check if
848 // the move that refuted the null move was somehow connected to the
849 // move which was reduced. If a connection is found, return a fail
850 // low score (which will cause the reduced move to fail high in the
851 // parent node, which will trigger a re-search with full depth).
852 threatMove = (ss+1)->bestMove;
854 if ( depth < ThreatDepth
856 && threatMove != MOVE_NONE
857 && connected_moves(pos, (ss-1)->currentMove, threatMove))
862 // Step 9. ProbCut (is omitted in PV nodes)
863 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
864 // and a reduced search returns a value much above beta, we can (almost) safely
865 // prune the previous move.
867 && depth >= RazorDepth + ONE_PLY
870 && excludedMove == MOVE_NONE
871 && abs(beta) < VALUE_MATE_IN_PLY_MAX)
873 Value rbeta = beta + 200;
874 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
876 assert(rdepth >= ONE_PLY);
878 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
881 while ((move = mp.get_next_move()) != MOVE_NONE)
882 if (pos.pl_move_is_legal(move, ci.pinned))
884 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
885 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
892 // Step 10. Internal iterative deepening
893 if ( depth >= IIDDepth[PvNode]
894 && ttMove == MOVE_NONE
895 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
897 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
899 ss->skipNullMove = true;
900 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
901 ss->skipNullMove = false;
903 tte = TT.probe(posKey);
904 ttMove = tte ? tte->move() : MOVE_NONE;
907 split_point_start: // At split points actual search starts from here
909 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
911 ss->bestMove = MOVE_NONE;
912 futilityBase = ss->eval + ss->evalMargin;
913 singularExtensionNode = !RootNode
915 && depth >= SingularExtensionDepth[PvNode]
916 && ttMove != MOVE_NONE
917 && !excludedMove // Recursive singular search is not allowed
918 && (tte->type() & VALUE_TYPE_LOWER)
919 && tte->depth() >= depth - 3 * ONE_PLY;
922 lock_grab(&(sp->lock));
923 bestValue = sp->bestValue;
924 moveCount = sp->moveCount;
926 assert(bestValue > -VALUE_INFINITE && moveCount > 0);
929 // Step 11. Loop through moves
930 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
931 while ( bestValue < beta
932 && (move = mp.get_next_move()) != MOVE_NONE
933 && !thread.cutoff_occurred())
937 if (move == excludedMove)
940 // At root obey the "searchmoves" option and skip moves not listed in Root
941 // Move List, as a consequence any illegal move is also skipped. In MultiPV
942 // mode we also skip PV moves which have been already searched.
943 if (RootNode && !Rml.find(move, MultiPVIdx))
946 // At PV and SpNode nodes we want all moves to be legal since the beginning
947 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
952 moveCount = ++sp->moveCount;
953 lock_release(&(sp->lock));
960 // This is used by time management
961 Signals.firstRootMove = (moveCount == 1);
963 nodes = pos.nodes_searched();
965 if (pos.thread() == 0 && elapsed_time() > 2000)
966 cout << "info" << depth_to_uci(depth)
967 << " currmove " << move
968 << " currmovenumber " << moveCount + MultiPVIdx << endl;
971 isPvMove = (PvNode && moveCount <= 1);
972 captureOrPromotion = pos.is_capture_or_promotion(move);
973 givesCheck = pos.move_gives_check(move, ci);
974 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
977 // Step 12. Extend checks and, in PV nodes, also dangerous moves
978 if (PvNode && dangerous)
981 else if (givesCheck && pos.see_sign(move) >= 0)
982 ext = PvNode ? ONE_PLY : ONE_PLY / 2;
984 // Singular extension search. If all moves but one fail low on a search of
985 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
986 // is singular and should be extended. To verify this we do a reduced search
987 // on all the other moves but the ttMove, if result is lower than ttValue minus
988 // a margin then we extend ttMove.
989 if ( singularExtensionNode
992 && pos.pl_move_is_legal(move, ci.pinned))
994 Value ttValue = value_from_tt(tte->value(), ss->ply);
996 if (abs(ttValue) < VALUE_KNOWN_WIN)
998 Value rBeta = ttValue - int(depth);
999 ss->excludedMove = move;
1000 ss->skipNullMove = true;
1001 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1002 ss->skipNullMove = false;
1003 ss->excludedMove = MOVE_NONE;
1004 ss->bestMove = MOVE_NONE;
1010 // Update current move (this must be done after singular extension search)
1011 newDepth = depth - ONE_PLY + ext;
1013 // Step 13. Futility pruning (is omitted in PV nodes)
1015 && !captureOrPromotion
1020 && (bestValue > VALUE_MATED_IN_PLY_MAX || bestValue == -VALUE_INFINITE))
1022 // Move count based pruning
1023 if ( moveCount >= futility_move_count(depth)
1024 && (!threatMove || !connected_threat(pos, move, threatMove)))
1027 lock_grab(&(sp->lock));
1032 // Value based pruning
1033 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1034 // but fixing this made program slightly weaker.
1035 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
1036 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
1037 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1039 if (futilityValue < beta)
1042 lock_grab(&(sp->lock));
1047 // Prune moves with negative SEE at low depths
1048 if ( predictedDepth < 2 * ONE_PLY
1049 && pos.see_sign(move) < 0)
1052 lock_grab(&(sp->lock));
1058 // Check for legality only before to do the move
1059 if (!pos.pl_move_is_legal(move, ci.pinned))
1065 ss->currentMove = move;
1066 if (!SpNode && !captureOrPromotion)
1067 movesSearched[playedMoveCount++] = move;
1069 // Step 14. Make the move
1070 pos.do_move(move, st, ci, givesCheck);
1072 // Step 15. Reduced depth search (LMR). If the move fails high will be
1073 // re-searched at full depth.
1074 if ( depth > 3 * ONE_PLY
1076 && !captureOrPromotion
1079 && ss->killers[0] != move
1080 && ss->killers[1] != move)
1082 ss->reduction = reduction<PvNode>(depth, moveCount);
1083 Depth d = newDepth - ss->reduction;
1084 alpha = SpNode ? sp->alpha : alpha;
1086 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1087 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1089 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1090 ss->reduction = DEPTH_ZERO;
1093 doFullDepthSearch = !isPvMove;
1095 // Step 16. Full depth search, when LMR is skipped or fails high
1096 if (doFullDepthSearch)
1098 alpha = SpNode ? sp->alpha : alpha;
1099 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1100 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1103 // Only for PV nodes do a full PV search on the first move or after a fail
1104 // high, in the latter case search only if value < beta, otherwise let the
1105 // parent node to fail low with value <= alpha and to try another move.
1106 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1107 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1108 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1110 // Step 17. Undo move
1111 pos.undo_move(move);
1113 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1115 // Step 18. Check for new best move
1118 lock_grab(&(sp->lock));
1119 bestValue = sp->bestValue;
1123 // Finished searching the move. If StopRequest is true, the search
1124 // was aborted because the user interrupted the search or because we
1125 // ran out of time. In this case, the return value of the search cannot
1126 // be trusted, and we don't update the best move and/or PV.
1127 if (RootNode && !Signals.stop)
1129 RootMove* rm = Rml.find(move);
1130 rm->nodes += pos.nodes_searched() - nodes;
1132 // PV move or new best move ?
1133 if (isPvMove || value > alpha)
1136 rm->extract_pv_from_tt(pos);
1138 // We record how often the best move has been changed in each
1139 // iteration. This information is used for time management: When
1140 // the best move changes frequently, we allocate some more time.
1141 if (!isPvMove && MultiPV == 1)
1142 Rml.bestMoveChanges++;
1145 // All other moves but the PV are set to the lowest value, this
1146 // is not a problem when sorting becuase sort is stable and move
1147 // position in the list is preserved, just the PV is pushed up.
1148 rm->score = -VALUE_INFINITE;
1152 if (value > bestValue)
1155 ss->bestMove = move;
1159 && value < beta) // We want always alpha < beta
1162 if (SpNode && !thread.cutoff_occurred())
1164 sp->bestValue = value;
1165 sp->ss->bestMove = move;
1167 sp->is_betaCutoff = (value >= beta);
1171 // Step 19. Check for split
1173 && depth >= Threads.min_split_depth()
1175 && Threads.available_slave_exists(pos.thread())
1177 && !thread.cutoff_occurred())
1178 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1179 threatMove, moveCount, &mp, NT);
1182 // Step 20. Check for mate and stalemate
1183 // All legal moves have been searched and if there are no legal moves, it
1184 // must be mate or stalemate. Note that we can have a false positive in
1185 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1186 // harmless because return value is discarded anyhow in the parent nodes.
1187 // If we are in a singular extension search then return a fail low score.
1189 return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1191 // If we have pruned all the moves without searching return a fail-low score
1192 if (bestValue == -VALUE_INFINITE)
1194 assert(!playedMoveCount);
1199 // Step 21. Update tables
1200 // Update transposition table entry, history and killers
1201 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1203 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1204 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1205 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1207 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1209 // Update killers and history only for non capture moves that fails high
1210 if ( bestValue >= beta
1211 && !pos.is_capture_or_promotion(move))
1213 if (move != ss->killers[0])
1215 ss->killers[1] = ss->killers[0];
1216 ss->killers[0] = move;
1218 update_history(pos, move, depth, movesSearched, playedMoveCount);
1224 // Here we have the lock still grabbed
1225 sp->is_slave[pos.thread()] = false;
1226 sp->nodes += pos.nodes_searched();
1227 lock_release(&(sp->lock));
1230 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1236 // qsearch() is the quiescence search function, which is called by the main
1237 // search function when the remaining depth is zero (or, to be more precise,
1238 // less than ONE_PLY).
1240 template <NodeType NT>
1241 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1243 const bool PvNode = (NT == PV);
1245 assert(NT == PV || NT == NonPV);
1246 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1247 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1248 assert(PvNode || alpha == beta - 1);
1250 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1254 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1255 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1259 Value oldAlpha = alpha;
1261 ss->bestMove = ss->currentMove = MOVE_NONE;
1262 ss->ply = (ss-1)->ply + 1;
1264 // Check for an instant draw or maximum ply reached
1265 if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1268 // Decide whether or not to include checks, this fixes also the type of
1269 // TT entry depth that we are going to use. Note that in qsearch we use
1270 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1271 inCheck = pos.in_check();
1272 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1274 // Transposition table lookup. At PV nodes, we don't use the TT for
1275 // pruning, but only for move ordering.
1276 tte = TT.probe(pos.get_key());
1277 ttMove = (tte ? tte->move() : MOVE_NONE);
1279 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1281 ss->bestMove = ttMove; // Can be MOVE_NONE
1282 return value_from_tt(tte->value(), ss->ply);
1285 // Evaluate the position statically
1288 bestValue = futilityBase = -VALUE_INFINITE;
1289 ss->eval = evalMargin = VALUE_NONE;
1290 enoughMaterial = false;
1296 assert(tte->static_value() != VALUE_NONE);
1298 evalMargin = tte->static_value_margin();
1299 ss->eval = bestValue = tte->static_value();
1302 ss->eval = bestValue = evaluate(pos, evalMargin);
1304 // Stand pat. Return immediately if static value is at least beta
1305 if (bestValue >= beta)
1308 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1313 if (PvNode && bestValue > alpha)
1316 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1317 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1320 // Initialize a MovePicker object for the current position, and prepare
1321 // to search the moves. Because the depth is <= 0 here, only captures,
1322 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1324 MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1327 // Loop through the moves until no moves remain or a beta cutoff occurs
1328 while ( bestValue < beta
1329 && (move = mp.get_next_move()) != MOVE_NONE)
1331 assert(is_ok(move));
1333 givesCheck = pos.move_gives_check(move, ci);
1341 && !is_promotion(move)
1342 && !pos.is_passed_pawn_push(move))
1344 futilityValue = futilityBase
1345 + PieceValueEndgame[pos.piece_on(move_to(move))]
1346 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1348 if (futilityValue < beta)
1350 if (futilityValue > bestValue)
1351 bestValue = futilityValue;
1356 // Prune moves with negative or equal SEE
1357 if ( futilityBase < beta
1358 && depth < DEPTH_ZERO
1359 && pos.see(move) <= 0)
1363 // Detect non-capture evasions that are candidate to be pruned
1364 evasionPrunable = !PvNode
1366 && bestValue > VALUE_MATED_IN_PLY_MAX
1367 && !pos.is_capture(move)
1368 && !pos.can_castle(pos.side_to_move());
1370 // Don't search moves with negative SEE values
1372 && (!inCheck || evasionPrunable)
1374 && !is_promotion(move)
1375 && pos.see_sign(move) < 0)
1378 // Don't search useless checks
1383 && !pos.is_capture_or_promotion(move)
1384 && ss->eval + PawnValueMidgame / 4 < beta
1385 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1387 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1388 bestValue = ss->eval + PawnValueMidgame / 4;
1393 // Check for legality only before to do the move
1394 if (!pos.pl_move_is_legal(move, ci.pinned))
1397 ss->currentMove = move;
1399 // Make and search the move
1400 pos.do_move(move, st, ci, givesCheck);
1401 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1402 pos.undo_move(move);
1404 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1407 if (value > bestValue)
1410 ss->bestMove = move;
1414 && value < beta) // We want always alpha < beta
1419 // All legal moves have been searched. A special case: If we're in check
1420 // and no legal moves were found, it is checkmate.
1421 if (inCheck && bestValue == -VALUE_INFINITE)
1422 return value_mated_in(ss->ply);
1424 // Update transposition table
1425 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1426 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1427 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1429 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1431 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1437 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1438 // bestValue is updated only when returning false because in that case move
1441 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1443 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1444 Square from, to, ksq, victimSq;
1447 Value futilityValue, bv = *bestValue;
1449 from = move_from(move);
1451 them = flip(pos.side_to_move());
1452 ksq = pos.king_square(them);
1453 kingAtt = pos.attacks_from<KING>(ksq);
1454 pc = pos.piece_on(from);
1456 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1457 oldAtt = pos.attacks_from(pc, from, occ);
1458 newAtt = pos.attacks_from(pc, to, occ);
1460 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1461 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1463 if (!(b && (b & (b - 1))))
1466 // Rule 2. Queen contact check is very dangerous
1467 if ( type_of(pc) == QUEEN
1468 && bit_is_set(kingAtt, to))
1471 // Rule 3. Creating new double threats with checks
1472 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1476 victimSq = pop_1st_bit(&b);
1477 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1479 // Note that here we generate illegal "double move"!
1480 if ( futilityValue >= beta
1481 && pos.see_sign(make_move(from, victimSq)) >= 0)
1484 if (futilityValue > bv)
1488 // Update bestValue only if check is not dangerous (because we will prune the move)
1494 // connected_moves() tests whether two moves are 'connected' in the sense
1495 // that the first move somehow made the second move possible (for instance
1496 // if the moving piece is the same in both moves). The first move is assumed
1497 // to be the move that was made to reach the current position, while the
1498 // second move is assumed to be a move from the current position.
1500 bool connected_moves(const Position& pos, Move m1, Move m2) {
1502 Square f1, t1, f2, t2;
1509 // Case 1: The moving piece is the same in both moves
1515 // Case 2: The destination square for m2 was vacated by m1
1521 // Case 3: Moving through the vacated square
1522 p2 = pos.piece_on(f2);
1523 if ( piece_is_slider(p2)
1524 && bit_is_set(squares_between(f2, t2), f1))
1527 // Case 4: The destination square for m2 is defended by the moving piece in m1
1528 p1 = pos.piece_on(t1);
1529 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1532 // Case 5: Discovered check, checking piece is the piece moved in m1
1533 ksq = pos.king_square(pos.side_to_move());
1534 if ( piece_is_slider(p1)
1535 && bit_is_set(squares_between(t1, ksq), f2))
1537 Bitboard occ = pos.occupied_squares();
1538 clear_bit(&occ, f2);
1539 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1546 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1547 // "plies to mate from the current ply". Non-mate scores are unchanged.
1548 // The function is called before storing a value to the transposition table.
1550 Value value_to_tt(Value v, int ply) {
1552 if (v >= VALUE_MATE_IN_PLY_MAX)
1555 if (v <= VALUE_MATED_IN_PLY_MAX)
1562 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1563 // the transposition table to a mate score corrected for the current ply.
1565 Value value_from_tt(Value v, int ply) {
1567 if (v >= VALUE_MATE_IN_PLY_MAX)
1570 if (v <= VALUE_MATED_IN_PLY_MAX)
1577 // connected_threat() tests whether it is safe to forward prune a move or if
1578 // is somehow connected to the threat move returned by null search.
1580 bool connected_threat(const Position& pos, Move m, Move threat) {
1583 assert(is_ok(threat));
1584 assert(!pos.is_capture_or_promotion(m));
1585 assert(!pos.is_passed_pawn_push(m));
1587 Square mfrom, mto, tfrom, tto;
1589 mfrom = move_from(m);
1591 tfrom = move_from(threat);
1592 tto = move_to(threat);
1594 // Case 1: Don't prune moves which move the threatened piece
1598 // Case 2: If the threatened piece has value less than or equal to the
1599 // value of the threatening piece, don't prune moves which defend it.
1600 if ( pos.is_capture(threat)
1601 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1602 || type_of(pos.piece_on(tfrom)) == KING)
1603 && pos.move_attacks_square(m, tto))
1606 // Case 3: If the moving piece in the threatened move is a slider, don't
1607 // prune safe moves which block its ray.
1608 if ( piece_is_slider(pos.piece_on(tfrom))
1609 && bit_is_set(squares_between(tfrom, tto), mto)
1610 && pos.see_sign(m) >= 0)
1617 // can_return_tt() returns true if a transposition table score can be used to
1618 // cut-off at a given point in search.
1620 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1622 Value v = value_from_tt(tte->value(), ply);
1624 return ( tte->depth() >= depth
1625 || v >= std::max(VALUE_MATE_IN_PLY_MAX, beta)
1626 || v < std::min(VALUE_MATED_IN_PLY_MAX, beta))
1628 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1629 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1633 // refine_eval() returns the transposition table score if possible, otherwise
1634 // falls back on static position evaluation.
1636 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1640 Value v = value_from_tt(tte->value(), ply);
1642 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1643 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1650 // update_history() registers a good move that produced a beta-cutoff in
1651 // history and marks as failures all the other moves of that ply.
1653 void update_history(const Position& pos, Move move, Depth depth,
1654 Move movesSearched[], int moveCount) {
1656 Value bonus = Value(int(depth) * int(depth));
1658 H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1660 for (int i = 0; i < moveCount - 1; i++)
1662 m = movesSearched[i];
1666 H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1671 // current_search_time() returns the number of milliseconds which have passed
1672 // since the beginning of the current search.
1674 int elapsed_time(bool reset) {
1676 static int searchStartTime;
1679 searchStartTime = get_system_time();
1681 return get_system_time() - searchStartTime;
1685 // score_to_uci() converts a value to a string suitable for use with the UCI
1686 // protocol specifications:
1688 // cp <x> The score from the engine's point of view in centipawns.
1689 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1690 // use negative values for y.
1692 string score_to_uci(Value v, Value alpha, Value beta) {
1694 std::stringstream s;
1696 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1697 s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1699 s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1701 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1707 // speed_to_uci() returns a string with time stats of current search suitable
1708 // to be sent to UCI gui.
1710 string speed_to_uci(int64_t nodes) {
1712 std::stringstream s;
1713 int t = elapsed_time();
1715 s << " nodes " << nodes
1716 << " nps " << (t > 0 ? int(nodes * 1000 / t) : 0)
1723 // pv_to_uci() returns a string with information on the current PV line
1724 // formatted according to UCI specification.
1726 string pv_to_uci(const Move pv[], int pvNum, bool chess960) {
1728 std::stringstream s;
1730 s << " multipv " << pvNum << " pv " << set960(chess960);
1732 for ( ; *pv != MOVE_NONE; pv++)
1739 // depth_to_uci() returns a string with information on the current depth and
1740 // seldepth formatted according to UCI specification.
1742 string depth_to_uci(Depth depth) {
1744 std::stringstream s;
1746 // Retrieve max searched depth among threads
1748 for (int i = 0; i < Threads.size(); i++)
1749 if (Threads[i].maxPly > selDepth)
1750 selDepth = Threads[i].maxPly;
1752 s << " depth " << depth / ONE_PLY << " seldepth " << selDepth;
1758 // pretty_pv() creates a human-readable string from a position and a PV.
1759 // It is used to write search information to the log file (which is created
1760 // when the UCI parameter "Use Search Log" is "true"). It uses the two helpers
1761 // time_to_string() and score_to_string() to format time and score respectively.
1763 string time_to_string(int millisecs) {
1765 const int MSecMinute = 1000 * 60;
1766 const int MSecHour = 1000 * 60 * 60;
1768 int hours = millisecs / MSecHour;
1769 int minutes = (millisecs % MSecHour) / MSecMinute;
1770 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1772 std::stringstream s;
1777 s << std::setfill('0') << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
1781 string score_to_string(Value v) {
1783 std::stringstream s;
1785 if (v >= VALUE_MATE_IN_PLY_MAX)
1786 s << "#" << (VALUE_MATE - v + 1) / 2;
1787 else if (v <= VALUE_MATED_IN_PLY_MAX)
1788 s << "-#" << (VALUE_MATE + v) / 2;
1790 s << std::setprecision(2) << std::fixed << std::showpos << float(v) / PawnValueMidgame;
1795 string pretty_pv(Position& pos, int depth, Value value, int time, Move pv[]) {
1797 const int64_t K = 1000;
1798 const int64_t M = 1000000;
1799 const int startColumn = 28;
1800 const size_t maxLength = 80 - startColumn;
1802 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1805 std::stringstream s;
1808 // First print depth, score, time and searched nodes...
1809 s << set960(pos.is_chess960())
1810 << std::setw(2) << depth
1811 << std::setw(8) << score_to_string(value)
1812 << std::setw(8) << time_to_string(time);
1814 if (pos.nodes_searched() < M)
1815 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1816 else if (pos.nodes_searched() < K * M)
1817 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1819 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1821 // ...then print the full PV line in short algebraic notation
1822 while (*m != MOVE_NONE)
1824 san = move_to_san(pos, *m);
1825 length += san.length() + 1;
1827 if (length > maxLength)
1829 length = san.length() + 1;
1830 s << "\n" + string(startColumn, ' ');
1834 pos.do_move(*m++, *st++);
1837 // Restore original position before to leave
1838 while (m != pv) pos.undo_move(*--m);
1844 // When playing with strength handicap choose best move among the MultiPV set
1845 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1847 void do_skill_level(Move* best, Move* ponder) {
1849 assert(MultiPV > 1);
1853 // Rml list is already sorted by score in descending order
1855 size_t size = std::min(MultiPV, Rml.size());
1856 int max_s = -VALUE_INFINITE;
1857 int max = Rml[0].score;
1858 int var = std::min(max - Rml[size - 1].score, int(PawnValueMidgame));
1859 int wk = 120 - 2 * SkillLevel;
1861 // PRNG sequence should be non deterministic
1862 for (int i = abs(get_system_time() % 50); i > 0; i--)
1863 rk.rand<unsigned>();
1865 // Choose best move. For each move's score we add two terms both dependent
1866 // on wk, one deterministic and bigger for weaker moves, and one random,
1867 // then we choose the move with the resulting highest score.
1868 for (size_t i = 0; i < size; i++)
1872 // Don't allow crazy blunders even at very low skills
1873 if (i > 0 && Rml[i-1].score > s + EasyMoveMargin)
1876 // This is our magical formula
1877 s += ((max - s) * wk + var * (rk.rand<unsigned>() % wk)) / 128;
1882 *best = Rml[i].pv[0];
1883 *ponder = Rml[i].pv[1];
1889 // RootMove and RootMoveList method's definitions
1891 void RootMoveList::init(Position& pos, Move rootMoves[]) {
1894 bestMoveChanges = 0;
1897 // Generate all legal moves and add them to RootMoveList
1898 for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
1900 // If we have a rootMoves[] list then verify the move
1901 // is in the list before to add it.
1902 for (sm = rootMoves; *sm && *sm != ml.move(); sm++) {}
1904 if (sm != rootMoves && *sm != ml.move())
1908 rm.pv.push_back(ml.move());
1909 rm.pv.push_back(MOVE_NONE);
1910 rm.score = rm.prevScore = -VALUE_INFINITE;
1916 RootMove* RootMoveList::find(const Move& m, int startIndex) {
1918 for (size_t i = startIndex; i < size(); i++)
1919 if ((*this)[i].pv[0] == m)
1926 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1927 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1928 // allow to always have a ponder move even when we fail high at root and also a
1929 // long PV to print that is important for position analysis.
1931 void RootMove::extract_pv_from_tt(Position& pos) {
1933 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1938 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1942 pos.do_move(m, *st++);
1944 while ( (tte = TT.probe(pos.get_key())) != NULL
1945 && tte->move() != MOVE_NONE
1946 && pos.is_pseudo_legal(tte->move())
1947 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1949 && (!pos.is_draw<false>() || ply < 2))
1951 pv.push_back(tte->move());
1952 pos.do_move(tte->move(), *st++);
1955 pv.push_back(MOVE_NONE);
1957 do pos.undo_move(pv[--ply]); while (ply);
1961 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
1962 // the PV back into the TT. This makes sure the old PV moves are searched
1963 // first, even if the old TT entries have been overwritten.
1965 void RootMove::insert_pv_in_tt(Position& pos) {
1967 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1970 Value v, m = VALUE_NONE;
1973 assert(pv[0] != MOVE_NONE && pos.is_pseudo_legal(pv[0]));
1979 // Don't overwrite existing correct entries
1980 if (!tte || tte->move() != pv[ply])
1982 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1983 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
1985 pos.do_move(pv[ply], *st++);
1987 } while (pv[++ply] != MOVE_NONE);
1989 do pos.undo_move(pv[--ply]); while (ply);
1995 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1996 /// The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
1997 /// for which the thread is the master.
1999 void Thread::idle_loop(SplitPoint* sp) {
2003 // If we are not searching, wait for a condition to be signaled
2004 // instead of wasting CPU time polling for work.
2007 || (Threads.use_sleeping_threads() && !is_searching))
2009 assert((!sp && threadID) || Threads.use_sleeping_threads());
2017 // Grab the lock to avoid races with Thread::wake_up()
2018 lock_grab(&sleepLock);
2020 // If we are master and all slaves have finished don't go to sleep
2021 if (sp && Threads.split_point_finished(sp))
2023 lock_release(&sleepLock);
2027 // Do sleep after retesting sleep conditions under lock protection, in
2028 // particular we need to avoid a deadlock in case a master thread has,
2029 // in the meanwhile, allocated us and sent the wake_up() call before we
2030 // had the chance to grab the lock.
2031 if (do_sleep || !is_searching)
2032 cond_wait(&sleepCond, &sleepLock);
2034 lock_release(&sleepLock);
2037 // If this thread has been assigned work, launch a search
2040 assert(!do_terminate);
2042 // Copy split point position and search stack and call search()
2043 Stack ss[PLY_MAX_PLUS_2];
2044 SplitPoint* tsp = splitPoint;
2045 Position pos(*tsp->pos, threadID);
2047 memcpy(ss, tsp->ss - 1, 4 * sizeof(Stack));
2050 if (tsp->nodeType == Root)
2051 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2052 else if (tsp->nodeType == PV)
2053 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2054 else if (tsp->nodeType == NonPV)
2055 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2059 assert(is_searching);
2061 is_searching = false;
2063 // Wake up master thread so to allow it to return from the idle loop in
2064 // case we are the last slave of the split point.
2065 if ( Threads.use_sleeping_threads()
2066 && threadID != tsp->master
2067 && !Threads[tsp->master].is_searching)
2068 Threads[tsp->master].wake_up();
2071 // If this thread is the master of a split point and all slaves have
2072 // finished their work at this split point, return from the idle loop.
2073 if (sp && Threads.split_point_finished(sp))
2075 // Because sp->is_slave[] is reset under lock protection,
2076 // be sure sp->lock has been released before to return.
2077 lock_grab(&(sp->lock));
2078 lock_release(&(sp->lock));
2085 /// do_timer_event() is called by the timer thread when the timer triggers. It
2086 /// is used to print debug info and, more important, to detect when we are out of
2087 /// available time and so stop the search.
2089 void do_timer_event() {
2091 static int lastInfoTime;
2092 int e = elapsed_time();
2094 if (get_system_time() - lastInfoTime >= 1000 || !lastInfoTime)
2096 lastInfoTime = get_system_time();
2099 dbg_print_hit_rate();
2105 bool stillAtFirstMove = Signals.firstRootMove
2106 && !Signals.failedLowAtRoot
2107 && e > TimeMgr.available_time();
2109 bool noMoreTime = e > TimeMgr.maximum_time()
2110 || stillAtFirstMove;
2112 if ( (Limits.useTimeManagement() && noMoreTime)
2113 || (Limits.maxTime && e >= Limits.maxTime)
2114 /* missing nodes limit */ ) // FIXME
2115 Signals.stop = true;