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/>.
40 #include "ucioption.h"
45 using Search::Signals;
50 volatile SignalsType Signals;
52 std::vector<Move> RootMoves;
53 Position* RootPosition;
58 // Set to true to force running with one thread. Used for debugging
59 const bool FakeSplit = false;
61 // Different node types, used as template parameter
62 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
64 // RootMove struct is used for moves at the root of the tree. For each root
65 // move, we store a score, a node count, and a PV (really a refutation
66 // in the case of moves which fail low). Score is normally set at
67 // -VALUE_INFINITE for all non-pv moves.
70 // RootMove::operator<() is the comparison function used when
71 // sorting the moves. A move m1 is considered to be better
72 // than a move m2 if it has an higher score
73 bool operator<(const RootMove& m) const { return score < m.score; }
75 void extract_pv_from_tt(Position& pos);
76 void insert_pv_in_tt(Position& pos);
84 // RootMoveList struct is mainly a std::vector of RootMove objects
85 struct RootMoveList : public std::vector<RootMove> {
87 void init(Position& pos, Move rootMoves[]);
88 RootMove* find(const Move& m, int startIndex = 0);
96 // Lookup table to check if a Piece is a slider and its access function
97 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
98 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
102 // Maximum depth for razoring
103 const Depth RazorDepth = 4 * ONE_PLY;
105 // Dynamic razoring margin based on depth
106 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
108 // Maximum depth for use of dynamic threat detection when null move fails low
109 const Depth ThreatDepth = 5 * ONE_PLY;
111 // Step 9. Internal iterative deepening
113 // Minimum depth for use of internal iterative deepening
114 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
116 // At Non-PV nodes we do an internal iterative deepening search
117 // when the static evaluation is bigger then beta - IIDMargin.
118 const Value IIDMargin = Value(0x100);
120 // Step 11. Decide the new search depth
122 // Extensions. Array index 0 is used for non-PV nodes, index 1 for PV nodes
123 const Depth CheckExtension[] = { ONE_PLY / 2, ONE_PLY / 1 };
124 const Depth PawnEndgameExtension[] = { ONE_PLY / 1, ONE_PLY / 1 };
125 const Depth PawnPushTo7thExtension[] = { ONE_PLY / 2, ONE_PLY / 2 };
126 const Depth PassedPawnExtension[] = { DEPTH_ZERO, ONE_PLY / 2 };
128 // Minimum depth for use of singular extension
129 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
131 // Step 12. Futility pruning
133 // Futility margin for quiescence search
134 const Value FutilityMarginQS = Value(0x80);
136 // Futility lookup tables (initialized at startup) and their access functions
137 Value FutilityMargins[16][64]; // [depth][moveNumber]
138 int FutilityMoveCounts[32]; // [depth]
140 inline Value futility_margin(Depth d, int mn) {
142 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
143 : 2 * VALUE_INFINITE;
146 inline int futility_move_count(Depth d) {
148 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
151 // Step 14. Reduced search
153 // Reduction lookup tables (initialized at startup) and their access function
154 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
156 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
158 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
161 // Easy move margin. An easy move candidate must be at least this much
162 // better than the second best move.
163 const Value EasyMoveMargin = Value(0x150);
166 /// Namespace variables
172 int MultiPV, UCIMultiPV, MultiPVIdx;
174 // Time management variables
177 // Skill level adjustment
179 bool SkillLevelEnabled;
187 Move id_loop(Position& pos, Move rootMoves[], Move* ponderMove);
189 template <NodeType NT>
190 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
192 template <NodeType NT>
193 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
195 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
196 bool connected_moves(const Position& pos, Move m1, Move m2);
197 Value value_to_tt(Value v, int ply);
198 Value value_from_tt(Value v, int ply);
199 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
200 bool connected_threat(const Position& pos, Move m, Move threat);
201 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
202 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
203 void do_skill_level(Move* best, Move* ponder);
205 int elapsed_search_time(int set = 0);
206 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
207 string speed_to_uci(int64_t nodes);
208 string pv_to_uci(const Move pv[], int pvNum, bool chess960);
209 string pretty_pv(Position& pos, int depth, Value score, int time, Move pv[]);
210 string depth_to_uci(Depth depth);
212 // MovePickerExt template class extends MovePicker and allows to choose at compile
213 // time the proper moves source according to the type of node. In the default case
214 // we simply create and use a standard MovePicker object.
215 template<bool SpNode> struct MovePickerExt : public MovePicker {
217 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
218 : MovePicker(p, ttm, d, h, ss, b) {}
221 // In case of a SpNode we use split point's shared MovePicker object as moves source
222 template<> struct MovePickerExt<true> : public MovePicker {
224 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
225 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
227 Move get_next_move() { return mp->get_next_move(); }
231 // Overload operator<<() to make it easier to print moves in a coordinate
232 // notation compatible with UCI protocol.
233 std::ostream& operator<<(std::ostream& os, Move m) {
235 bool chess960 = (os.iword(0) != 0); // See set960()
236 return os << move_to_uci(m, chess960);
239 // When formatting a move for std::cout we must know if we are in Chess960
240 // or not. To keep using the handy operator<<() on the move the trick is to
241 // embed this flag in the stream itself. Function-like named enum set960 is
242 // used as a custom manipulator and the stream internal general-purpose array,
243 // accessed through ios_base::iword(), is used to pass the flag to the move's
244 // operator<<() that will read it to properly format castling moves.
247 std::ostream& operator<< (std::ostream& os, const set960& f) {
249 os.iword(0) = int(f);
253 // extension() decides whether a move should be searched with normal depth,
254 // or with extended depth. Certain classes of moves (checking moves, in
255 // particular) are searched with bigger depth than ordinary moves and in
256 // any case are marked as 'dangerous'. Note that also if a move is not
257 // extended, as example because the corresponding UCI option is set to zero,
258 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
259 template <bool PvNode>
260 FORCE_INLINE Depth extension(const Position& pos, Move m, bool captureOrPromotion,
261 bool moveIsCheck, bool* dangerous) {
262 assert(m != MOVE_NONE);
264 Depth result = DEPTH_ZERO;
265 *dangerous = moveIsCheck;
267 if (moveIsCheck && pos.see_sign(m) >= 0)
268 result += CheckExtension[PvNode];
270 if (type_of(pos.piece_on(move_from(m))) == PAWN)
272 Color c = pos.side_to_move();
273 if (relative_rank(c, move_to(m)) == RANK_7)
275 result += PawnPushTo7thExtension[PvNode];
278 if (pos.pawn_is_passed(c, move_to(m)))
280 result += PassedPawnExtension[PvNode];
285 if ( captureOrPromotion
286 && type_of(pos.piece_on(move_to(m))) != PAWN
287 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
288 - PieceValueMidgame[pos.piece_on(move_to(m))] == VALUE_ZERO)
291 result += PawnEndgameExtension[PvNode];
295 return std::min(result, ONE_PLY);
301 /// init_search() is called during startup to initialize various lookup tables
303 void Search::init() {
305 int d; // depth (ONE_PLY == 2)
306 int hd; // half depth (ONE_PLY == 1)
309 // Init reductions array
310 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
312 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
313 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
314 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
315 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
318 // Init futility margins array
319 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
320 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
322 // Init futility move count array
323 for (d = 0; d < 32; d++)
324 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
328 /// perft() is our utility to verify move generation. All the leaf nodes up to
329 /// the given depth are generated and counted and the sum returned.
331 int64_t Search::perft(Position& pos, Depth depth) {
336 // Generate all legal moves
337 MoveList<MV_LEGAL> ml(pos);
339 // If we are at the last ply we don't need to do and undo
340 // the moves, just to count them.
341 if (depth <= ONE_PLY)
344 // Loop through all legal moves
346 for ( ; !ml.end(); ++ml)
348 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
349 sum += perft(pos, depth - ONE_PLY);
350 pos.undo_move(ml.move());
356 /// think() is the external interface to Stockfish's search, and is called when
357 /// the program receives the UCI 'go' command. It initializes various global
358 /// variables, and calls id_loop(). It returns false when a "quit" command is
359 /// received during the search.
361 void Search::think() {
363 static Book book; // Defined static to initialize the PRNG only once
365 Position& pos = *RootPosition;
367 // Save "search start" time and reset elapsed time to zero
368 elapsed_search_time(get_system_time());
370 // Reset global search signals
371 memset((void*)&Signals, 0, sizeof(Signals));
373 // Set output stream mode: normal or chess960. Castling notation is different
374 cout << set960(pos.is_chess960());
376 // Look for a book move
377 if (Options["OwnBook"].value<bool>())
379 if (Options["Book File"].value<string>() != book.name())
380 book.open(Options["Book File"].value<string>());
382 Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
383 if (bookMove != MOVE_NONE)
385 if (!Signals.stop && (Limits.ponder || Limits.infinite))
386 Threads.wait_for_stop_or_ponderhit();
388 cout << "bestmove " << bookMove << endl;
393 // Read UCI options: GUI could change UCI parameters during the game
394 read_evaluation_uci_options(pos.side_to_move());
395 Threads.read_uci_options();
397 // Set a new TT size if changed
398 TT.set_size(Options["Hash"].value<int>());
400 if (Options["Clear Hash"].value<bool>())
402 Options["Clear Hash"].set_value("false");
406 UCIMultiPV = Options["MultiPV"].value<int>();
407 SkillLevel = Options["Skill Level"].value<int>();
409 // Do we have to play with skill handicap? In this case enable MultiPV that
410 // we will use behind the scenes to retrieve a set of possible moves.
411 SkillLevelEnabled = (SkillLevel < 20);
412 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, 4) : UCIMultiPV);
414 // Write current search header to log file
415 if (Options["Use Search Log"].value<bool>())
417 Log log(Options["Search Log Filename"].value<string>());
418 log << "\nSearching: " << pos.to_fen()
419 << "\ninfinite: " << Limits.infinite
420 << " ponder: " << Limits.ponder
421 << " time: " << Limits.time
422 << " increment: " << Limits.increment
423 << " moves to go: " << Limits.movesToGo
427 // Wake up needed threads and reset maxPly counter
428 for (int i = 0; i < Threads.size(); i++)
430 Threads[i].maxPly = 0;
431 Threads[i].wake_up();
434 // Set best timer interval to avoid lagging under time pressure. Timer is
435 // used to check for remaining available thinking time.
436 TimeMgr.init(Limits, pos.startpos_ply_counter());
438 if (TimeMgr.available_time())
439 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
441 Threads.set_timer(100);
443 // We're ready to start thinking. Call the iterative deepening loop function
444 Move ponderMove = MOVE_NONE;
445 Move bestMove = id_loop(pos, &RootMoves[0], &ponderMove);
447 // Stop timer, no need to check for available time any more
448 Threads.set_timer(0);
450 // This makes all the slave threads to go to sleep, if not already sleeping
453 // Write current search final statistics to log file
454 if (Options["Use Search Log"].value<bool>())
456 int e = elapsed_search_time();
458 Log log(Options["Search Log Filename"].value<string>());
459 log << "Nodes: " << pos.nodes_searched()
460 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
461 << "\nBest move: " << move_to_san(pos, bestMove);
464 pos.do_move(bestMove, st);
465 log << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
466 pos.undo_move(bestMove); // Return from think() with unchanged position
469 // When we reach max depth we arrive here even without a StopRequest, but if
470 // we are pondering or in infinite search, we shouldn't print the best move
471 // before we are told to do so.
472 if (!Signals.stop && (Limits.ponder || Limits.infinite))
473 Threads.wait_for_stop_or_ponderhit();
475 // Could be MOVE_NONE when searching on a stalemate position
476 cout << "bestmove " << bestMove;
478 // UCI protol is not clear on allowing sending an empty ponder move, instead
479 // it is clear that ponder move is optional. So skip it if empty.
480 if (ponderMove != MOVE_NONE)
481 cout << " ponder " << ponderMove;
489 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
490 // with increasing depth until the allocated thinking time has been consumed,
491 // user stops the search, or the maximum search depth is reached.
493 Move id_loop(Position& pos, Move rootMoves[], Move* ponderMove) {
495 SearchStack ss[PLY_MAX_PLUS_2];
496 Value bestValues[PLY_MAX_PLUS_2];
497 int bestMoveChanges[PLY_MAX_PLUS_2];
498 int depth, aspirationDelta;
499 Value bestValue, alpha, beta;
500 Move bestMove, skillBest, skillPonder;
501 bool bestMoveNeverChanged = true;
503 // Initialize stuff before a new search
504 memset(ss, 0, 4 * sizeof(SearchStack));
507 *ponderMove = bestMove = skillBest = skillPonder = MOVE_NONE;
508 depth = aspirationDelta = 0;
509 bestValue = alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
510 ss->currentMove = MOVE_NULL; // Hack to skip update gains
512 // Moves to search are verified and copied
513 Rml.init(pos, rootMoves);
515 // Handle special case of searching on a mate/stalemate position
518 cout << "info" << depth_to_uci(DEPTH_ZERO)
519 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW, alpha, beta) << endl;
524 // Iterative deepening loop until requested to stop or target depth reached
525 while (!Signals.stop && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
527 // Save now last iteration's scores, before Rml moves are reordered
528 for (size_t i = 0; i < Rml.size(); i++)
529 Rml[i].prevScore = Rml[i].score;
531 Rml.bestMoveChanges = 0;
533 // MultiPV loop. We perform a full root search for each PV line
534 for (MultiPVIdx = 0; MultiPVIdx < std::min(MultiPV, (int)Rml.size()); MultiPVIdx++)
536 // Calculate dynamic aspiration window based on previous iterations
537 if (depth >= 5 && abs(Rml[MultiPVIdx].prevScore) < VALUE_KNOWN_WIN)
539 int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
540 int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
542 aspirationDelta = std::min(std::max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
543 aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
545 alpha = std::max(Rml[MultiPVIdx].prevScore - aspirationDelta, -VALUE_INFINITE);
546 beta = std::min(Rml[MultiPVIdx].prevScore + aspirationDelta, VALUE_INFINITE);
550 alpha = -VALUE_INFINITE;
551 beta = VALUE_INFINITE;
554 // Start with a small aspiration window and, in case of fail high/low,
555 // research with bigger window until not failing high/low anymore.
557 // Search starts from ss+1 to allow referencing (ss-1). This is
558 // needed by update gains and ss copy when splitting at Root.
559 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
561 // Bring to front the best move. It is critical that sorting is
562 // done with a stable algorithm because all the values but the first
563 // and eventually the new best one are set to -VALUE_INFINITE and
564 // we want to keep the same order for all the moves but the new
565 // PV that goes to the front. Note that in case of MultiPV search
566 // the already searched PV lines are preserved.
567 sort<RootMove>(Rml.begin() + MultiPVIdx, Rml.end());
569 // In case we have found an exact score and we are going to leave
570 // the fail high/low loop then reorder the PV moves, otherwise
571 // leave the last PV move in its position so to be searched again.
572 // Of course this is needed only in MultiPV search.
573 if (MultiPVIdx && bestValue > alpha && bestValue < beta)
574 sort<RootMove>(Rml.begin(), Rml.begin() + MultiPVIdx);
576 // Write PV back to transposition table in case the relevant entries
577 // have been overwritten during the search.
578 for (int i = 0; i <= MultiPVIdx; i++)
579 Rml[i].insert_pv_in_tt(pos);
581 // If search has been stopped exit the aspiration window loop,
582 // note that sorting and writing PV back to TT is safe becuase
583 // Rml is still valid, although refers to the previous iteration.
587 // Send full PV info to GUI if we are going to leave the loop or
588 // if we have a fail high/low and we are deep in the search. UCI
589 // protocol requires to send all the PV lines also if are still
590 // to be searched and so refer to the previous search's score.
591 if ((bestValue > alpha && bestValue < beta) || elapsed_search_time() > 2000)
592 for (int i = 0; i < std::min(UCIMultiPV, (int)Rml.size()); i++)
594 bool updated = (i <= MultiPVIdx);
596 if (depth == 1 && !updated)
599 Depth d = (updated ? depth : depth - 1) * ONE_PLY;
600 Value s = (updated ? Rml[i].score : Rml[i].prevScore);
604 << (i == MultiPVIdx ? score_to_uci(s, alpha, beta) : score_to_uci(s))
605 << speed_to_uci(pos.nodes_searched())
606 << pv_to_uci(&Rml[i].pv[0], i + 1, pos.is_chess960())
610 // In case of failing high/low increase aspiration window and
611 // research, otherwise exit the fail high/low loop.
612 if (bestValue >= beta)
614 beta = std::min(beta + aspirationDelta, VALUE_INFINITE);
615 aspirationDelta += aspirationDelta / 2;
617 else if (bestValue <= alpha)
619 Signals.failedLowAtRoot = true;
620 Signals.stopOnPonderhit = false;
622 alpha = std::max(alpha - aspirationDelta, -VALUE_INFINITE);
623 aspirationDelta += aspirationDelta / 2;
628 } while (abs(bestValue) < VALUE_KNOWN_WIN);
631 // Collect info about search result
632 bestMove = Rml[0].pv[0];
633 *ponderMove = Rml[0].pv[1];
634 bestValues[depth] = bestValue;
635 bestMoveChanges[depth] = Rml.bestMoveChanges;
637 // Skills: Do we need to pick now the best and the ponder moves ?
638 if (SkillLevelEnabled && depth == 1 + SkillLevel)
639 do_skill_level(&skillBest, &skillPonder);
641 if (Options["Use Search Log"].value<bool>())
643 Log log(Options["Search Log Filename"].value<string>());
644 log << pretty_pv(pos, depth, bestValue, elapsed_search_time(), &Rml[0].pv[0]) << endl;
647 // Filter out startup noise when monitoring best move stability
648 if (depth > 2 && bestMoveChanges[depth])
649 bestMoveNeverChanged = false;
651 // Do we have time for the next iteration? Can we stop searching now?
652 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
654 // Take in account some extra time if the best move has changed
655 if (depth > 4 && depth < 50)
656 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
658 // Stop search if most of available time is already consumed. We probably don't
659 // have enough time to search the first move at the next iteration anyway.
660 if (elapsed_search_time() > (TimeMgr.available_time() * 62) / 100)
663 // Stop search early if one move seems to be much better than others
666 && ( bestMoveNeverChanged
667 || elapsed_search_time() > (TimeMgr.available_time() * 40) / 100))
669 Value rBeta = bestValue - EasyMoveMargin;
670 (ss+1)->excludedMove = bestMove;
671 (ss+1)->skipNullMove = true;
672 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
673 (ss+1)->skipNullMove = false;
674 (ss+1)->excludedMove = MOVE_NONE;
680 // If we are allowed to ponder do not stop the search now but keep pondering
681 if (Signals.stop && Limits.ponder) // FIXME Limits.ponder is racy
683 Signals.stop = false;
684 Signals.stopOnPonderhit = true;
689 // When using skills overwrite best and ponder moves with the sub-optimal ones
690 if (SkillLevelEnabled)
692 if (skillBest == MOVE_NONE) // Still unassigned ?
693 do_skill_level(&skillBest, &skillPonder);
695 bestMove = skillBest;
696 *ponderMove = skillPonder;
703 // search<>() is the main search function for both PV and non-PV nodes and for
704 // normal and SplitPoint nodes. When called just after a split point the search
705 // is simpler because we have already probed the hash table, done a null move
706 // search, and searched the first move before splitting, we don't have to repeat
707 // all this work again. We also don't need to store anything to the hash table
708 // here: This is taken care of after we return from the split point.
710 template <NodeType NT>
711 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
713 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
714 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
715 const bool RootNode = (NT == Root || NT == SplitPointRoot);
717 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
718 assert(beta > alpha && beta <= VALUE_INFINITE);
719 assert(PvNode || alpha == beta - 1);
720 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
722 Move movesSearched[MAX_MOVES];
727 Move ttMove, move, excludedMove, threatMove;
730 Value bestValue, value, oldAlpha;
731 Value refinedValue, nullValue, futilityBase, futilityValue;
732 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
733 bool captureOrPromotion, dangerous, doFullDepthSearch;
734 int moveCount = 0, playedMoveCount = 0;
735 Thread& thread = Threads[pos.thread()];
736 SplitPoint* sp = NULL;
738 refinedValue = bestValue = value = -VALUE_INFINITE;
740 inCheck = pos.in_check();
741 ss->ply = (ss-1)->ply + 1;
743 // Used to send selDepth info to GUI
744 if (PvNode && thread.maxPly < ss->ply)
745 thread.maxPly = ss->ply;
747 // Step 1. Initialize node
750 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
751 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
752 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
758 ttMove = excludedMove = MOVE_NONE;
759 threatMove = sp->threatMove;
760 goto split_point_start;
763 // Step 2. Check for aborted search and immediate draw
765 || pos.is_draw<false>()
766 || ss->ply > PLY_MAX) && !RootNode)
769 // Step 3. Mate distance pruning
772 alpha = std::max(value_mated_in(ss->ply), alpha);
773 beta = std::min(value_mate_in(ss->ply+1), beta);
778 // Step 4. Transposition table lookup
779 // We don't want the score of a partial search to overwrite a previous full search
780 // TT value, so we use a different position key in case of an excluded move.
781 excludedMove = ss->excludedMove;
782 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
783 tte = TT.probe(posKey);
784 ttMove = RootNode ? Rml[MultiPVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
786 // At PV nodes we check for exact scores, while at non-PV nodes we check for
787 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
788 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
789 // we should also update RootMoveList to avoid bogus output.
790 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
791 : can_return_tt(tte, depth, beta, ss->ply)))
794 ss->bestMove = move = ttMove; // Can be MOVE_NONE
795 value = value_from_tt(tte->value(), ss->ply);
799 && !pos.is_capture_or_promotion(move)
800 && move != ss->killers[0])
802 ss->killers[1] = ss->killers[0];
803 ss->killers[0] = move;
808 // Step 5. Evaluate the position statically and update parent's gain statistics
810 ss->eval = ss->evalMargin = VALUE_NONE;
813 assert(tte->static_value() != VALUE_NONE);
815 ss->eval = tte->static_value();
816 ss->evalMargin = tte->static_value_margin();
817 refinedValue = refine_eval(tte, ss->eval, ss->ply);
821 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
822 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
825 // Update gain for the parent non-capture move given the static position
826 // evaluation before and after the move.
827 if ( (move = (ss-1)->currentMove) != MOVE_NULL
828 && (ss-1)->eval != VALUE_NONE
829 && ss->eval != VALUE_NONE
830 && pos.captured_piece_type() == PIECE_TYPE_NONE
831 && !is_special(move))
833 Square to = move_to(move);
834 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
837 // Step 6. Razoring (is omitted in PV nodes)
839 && depth < RazorDepth
841 && refinedValue + razor_margin(depth) < beta
842 && ttMove == MOVE_NONE
843 && abs(beta) < VALUE_MATE_IN_PLY_MAX
844 && !pos.has_pawn_on_7th(pos.side_to_move()))
846 Value rbeta = beta - razor_margin(depth);
847 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
849 // Logically we should return (v + razor_margin(depth)), but
850 // surprisingly this did slightly weaker in tests.
854 // Step 7. Static null move pruning (is omitted in PV nodes)
855 // We're betting that the opponent doesn't have a move that will reduce
856 // the score by more than futility_margin(depth) if we do a null move.
859 && depth < RazorDepth
861 && refinedValue - futility_margin(depth, 0) >= beta
862 && abs(beta) < VALUE_MATE_IN_PLY_MAX
863 && pos.non_pawn_material(pos.side_to_move()))
864 return refinedValue - futility_margin(depth, 0);
866 // Step 8. Null move search with verification search (is omitted in PV nodes)
871 && refinedValue >= beta
872 && abs(beta) < VALUE_MATE_IN_PLY_MAX
873 && pos.non_pawn_material(pos.side_to_move()))
875 ss->currentMove = MOVE_NULL;
877 // Null move dynamic reduction based on depth
878 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
880 // Null move dynamic reduction based on value
881 if (refinedValue - PawnValueMidgame > beta)
884 pos.do_null_move<true>(st);
885 (ss+1)->skipNullMove = true;
886 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
887 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
888 (ss+1)->skipNullMove = false;
889 pos.do_null_move<false>(st);
891 if (nullValue >= beta)
893 // Do not return unproven mate scores
894 if (nullValue >= VALUE_MATE_IN_PLY_MAX)
897 if (depth < 6 * ONE_PLY)
900 // Do verification search at high depths
901 ss->skipNullMove = true;
902 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
903 ss->skipNullMove = false;
910 // The null move failed low, which means that we may be faced with
911 // some kind of threat. If the previous move was reduced, check if
912 // the move that refuted the null move was somehow connected to the
913 // move which was reduced. If a connection is found, return a fail
914 // low score (which will cause the reduced move to fail high in the
915 // parent node, which will trigger a re-search with full depth).
916 threatMove = (ss+1)->bestMove;
918 if ( depth < ThreatDepth
920 && threatMove != MOVE_NONE
921 && connected_moves(pos, (ss-1)->currentMove, threatMove))
926 // Step 9. ProbCut (is omitted in PV nodes)
927 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
928 // and a reduced search returns a value much above beta, we can (almost) safely
929 // prune the previous move.
931 && depth >= RazorDepth + ONE_PLY
934 && excludedMove == MOVE_NONE
935 && abs(beta) < VALUE_MATE_IN_PLY_MAX)
937 Value rbeta = beta + 200;
938 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
940 assert(rdepth >= ONE_PLY);
942 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
945 while ((move = mp.get_next_move()) != MOVE_NONE)
946 if (pos.pl_move_is_legal(move, ci.pinned))
948 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
949 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
956 // Step 10. Internal iterative deepening
957 if ( depth >= IIDDepth[PvNode]
958 && ttMove == MOVE_NONE
959 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
961 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
963 ss->skipNullMove = true;
964 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
965 ss->skipNullMove = false;
967 tte = TT.probe(posKey);
968 ttMove = tte ? tte->move() : MOVE_NONE;
971 split_point_start: // At split points actual search starts from here
973 // Initialize a MovePicker object for the current position
974 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
976 ss->bestMove = MOVE_NONE;
977 futilityBase = ss->eval + ss->evalMargin;
978 singularExtensionNode = !RootNode
980 && depth >= SingularExtensionDepth[PvNode]
981 && ttMove != MOVE_NONE
982 && !excludedMove // Do not allow recursive singular extension search
983 && (tte->type() & VALUE_TYPE_LOWER)
984 && tte->depth() >= depth - 3 * ONE_PLY;
987 lock_grab(&(sp->lock));
988 bestValue = sp->bestValue;
991 // Step 11. Loop through moves
992 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
993 while ( bestValue < beta
994 && (move = mp.get_next_move()) != MOVE_NONE
995 && !thread.cutoff_occurred())
999 if (move == excludedMove)
1002 // At root obey the "searchmoves" option and skip moves not listed in Root
1003 // Move List, as a consequence any illegal move is also skipped. In MultiPV
1004 // mode we also skip PV moves which have been already searched.
1005 if (RootNode && !Rml.find(move, MultiPVIdx))
1008 // At PV and SpNode nodes we want all moves to be legal since the beginning
1009 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
1014 moveCount = ++sp->moveCount;
1015 lock_release(&(sp->lock));
1022 // This is used by time management
1023 Signals.firstRootMove = (moveCount == 1);
1025 // Save the current node count before the move is searched
1026 nodes = pos.nodes_searched();
1028 // For long searches send current move info to GUI
1029 if (pos.thread() == 0 && elapsed_search_time() > 2000)
1030 cout << "info" << depth_to_uci(depth)
1031 << " currmove " << move
1032 << " currmovenumber " << moveCount + MultiPVIdx << endl;
1035 isPvMove = (PvNode && moveCount <= 1);
1036 givesCheck = pos.move_gives_check(move, ci);
1037 captureOrPromotion = pos.is_capture_or_promotion(move);
1039 // Step 12. Decide the new search depth
1040 ext = extension<PvNode>(pos, move, captureOrPromotion, givesCheck, &dangerous);
1042 // Singular extension search. If all moves but one fail low on a search of
1043 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
1044 // is singular and should be extended. To verify this we do a reduced search
1045 // on all the other moves but the ttMove, if result is lower than ttValue minus
1046 // a margin then we extend ttMove.
1047 if ( singularExtensionNode
1049 && pos.pl_move_is_legal(move, ci.pinned)
1052 Value ttValue = value_from_tt(tte->value(), ss->ply);
1054 if (abs(ttValue) < VALUE_KNOWN_WIN)
1056 Value rBeta = ttValue - int(depth);
1057 ss->excludedMove = move;
1058 ss->skipNullMove = true;
1059 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1060 ss->skipNullMove = false;
1061 ss->excludedMove = MOVE_NONE;
1062 ss->bestMove = MOVE_NONE;
1068 // Update current move (this must be done after singular extension search)
1069 newDepth = depth - ONE_PLY + ext;
1071 // Step 13. Futility pruning (is omitted in PV nodes)
1073 && !captureOrPromotion
1077 && !is_castle(move))
1079 // Move count based pruning
1080 if ( moveCount >= futility_move_count(depth)
1081 && (!threatMove || !connected_threat(pos, move, threatMove))
1082 && bestValue > VALUE_MATED_IN_PLY_MAX) // FIXME bestValue is racy
1085 lock_grab(&(sp->lock));
1090 // Value based pruning
1091 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1092 // but fixing this made program slightly weaker.
1093 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
1094 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
1095 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1097 if (futilityValue < beta)
1101 lock_grab(&(sp->lock));
1102 if (futilityValue > sp->bestValue)
1103 sp->bestValue = bestValue = futilityValue;
1105 else if (futilityValue > bestValue)
1106 bestValue = futilityValue;
1111 // Prune moves with negative SEE at low depths
1112 if ( predictedDepth < 2 * ONE_PLY
1113 && bestValue > VALUE_MATED_IN_PLY_MAX
1114 && pos.see_sign(move) < 0)
1117 lock_grab(&(sp->lock));
1123 // Check for legality only before to do the move
1124 if (!pos.pl_move_is_legal(move, ci.pinned))
1130 ss->currentMove = move;
1131 if (!SpNode && !captureOrPromotion)
1132 movesSearched[playedMoveCount++] = move;
1134 // Step 14. Make the move
1135 pos.do_move(move, st, ci, givesCheck);
1137 // Step 15. Reduced depth search (LMR). If the move fails high will be
1138 // re-searched at full depth.
1139 if ( depth > 3 * ONE_PLY
1141 && !captureOrPromotion
1144 && ss->killers[0] != move
1145 && ss->killers[1] != move)
1147 ss->reduction = reduction<PvNode>(depth, moveCount);
1148 Depth d = newDepth - ss->reduction;
1149 alpha = SpNode ? sp->alpha : alpha;
1151 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1152 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1154 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1155 ss->reduction = DEPTH_ZERO;
1158 doFullDepthSearch = !isPvMove;
1160 // Step 16. Full depth search, when LMR is skipped or fails high
1161 if (doFullDepthSearch)
1163 alpha = SpNode ? sp->alpha : alpha;
1164 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1165 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1168 // Only for PV nodes do a full PV search on the first move or after a fail
1169 // high, in the latter case search only if value < beta, otherwise let the
1170 // parent node to fail low with value <= alpha and to try another move.
1171 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1172 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1173 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1175 // Step 17. Undo move
1176 pos.undo_move(move);
1178 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1180 // Step 18. Check for new best move
1183 lock_grab(&(sp->lock));
1184 bestValue = sp->bestValue;
1188 // Finished searching the move. If StopRequest is true, the search
1189 // was aborted because the user interrupted the search or because we
1190 // ran out of time. In this case, the return value of the search cannot
1191 // be trusted, and we don't update the best move and/or PV.
1192 if (RootNode && !Signals.stop)
1194 // Remember searched nodes counts for this move
1195 RootMove* rm = Rml.find(move);
1196 rm->nodes += pos.nodes_searched() - nodes;
1198 // PV move or new best move ?
1199 if (isPvMove || value > alpha)
1203 rm->extract_pv_from_tt(pos);
1205 // We record how often the best move has been changed in each
1206 // iteration. This information is used for time management: When
1207 // the best move changes frequently, we allocate some more time.
1208 if (!isPvMove && MultiPV == 1)
1209 Rml.bestMoveChanges++;
1212 // All other moves but the PV are set to the lowest value, this
1213 // is not a problem when sorting becuase sort is stable and move
1214 // position in the list is preserved, just the PV is pushed up.
1215 rm->score = -VALUE_INFINITE;
1219 if (value > bestValue)
1222 ss->bestMove = move;
1226 && value < beta) // We want always alpha < beta
1229 if (SpNode && !thread.cutoff_occurred())
1231 sp->bestValue = value;
1232 sp->ss->bestMove = move;
1234 sp->is_betaCutoff = (value >= beta);
1238 // Step 19. Check for split
1240 && depth >= Threads.min_split_depth()
1242 && Threads.available_slave_exists(pos.thread())
1244 && !thread.cutoff_occurred())
1245 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1246 threatMove, moveCount, &mp, NT);
1249 // Step 20. Check for mate and stalemate
1250 // All legal moves have been searched and if there are no legal moves, it
1251 // must be mate or stalemate. Note that we can have a false positive in
1252 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1253 // harmless because return value is discarded anyhow in the parent nodes.
1254 // If we are in a singular extension search then return a fail low score.
1255 if (!SpNode && !moveCount)
1256 return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1258 // Step 21. Update tables
1259 // If the search is not aborted, update the transposition table,
1260 // history counters, and killer moves.
1261 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1263 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1264 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1265 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1267 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1269 // Update killers and history only for non capture moves that fails high
1270 if ( bestValue >= beta
1271 && !pos.is_capture_or_promotion(move))
1273 if (move != ss->killers[0])
1275 ss->killers[1] = ss->killers[0];
1276 ss->killers[0] = move;
1278 update_history(pos, move, depth, movesSearched, playedMoveCount);
1284 // Here we have the lock still grabbed
1285 sp->is_slave[pos.thread()] = false;
1286 sp->nodes += pos.nodes_searched();
1287 lock_release(&(sp->lock));
1290 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1295 // qsearch() is the quiescence search function, which is called by the main
1296 // search function when the remaining depth is zero (or, to be more precise,
1297 // less than ONE_PLY).
1299 template <NodeType NT>
1300 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
1302 const bool PvNode = (NT == PV);
1304 assert(NT == PV || NT == NonPV);
1305 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1306 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1307 assert(PvNode || alpha == beta - 1);
1309 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1313 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1314 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1318 Value oldAlpha = alpha;
1320 ss->bestMove = ss->currentMove = MOVE_NONE;
1321 ss->ply = (ss-1)->ply + 1;
1323 // Check for an instant draw or maximum ply reached
1324 if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1327 // Decide whether or not to include checks, this fixes also the type of
1328 // TT entry depth that we are going to use. Note that in qsearch we use
1329 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1330 inCheck = pos.in_check();
1331 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1333 // Transposition table lookup. At PV nodes, we don't use the TT for
1334 // pruning, but only for move ordering.
1335 tte = TT.probe(pos.get_key());
1336 ttMove = (tte ? tte->move() : MOVE_NONE);
1338 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1340 ss->bestMove = ttMove; // Can be MOVE_NONE
1341 return value_from_tt(tte->value(), ss->ply);
1344 // Evaluate the position statically
1347 bestValue = futilityBase = -VALUE_INFINITE;
1348 ss->eval = evalMargin = VALUE_NONE;
1349 enoughMaterial = false;
1355 assert(tte->static_value() != VALUE_NONE);
1357 evalMargin = tte->static_value_margin();
1358 ss->eval = bestValue = tte->static_value();
1361 ss->eval = bestValue = evaluate(pos, evalMargin);
1363 // Stand pat. Return immediately if static value is at least beta
1364 if (bestValue >= beta)
1367 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1372 if (PvNode && bestValue > alpha)
1375 // Futility pruning parameters, not needed when in check
1376 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1377 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1380 // Initialize a MovePicker object for the current position, and prepare
1381 // to search the moves. Because the depth is <= 0 here, only captures,
1382 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1384 MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1387 // Loop through the moves until no moves remain or a beta cutoff occurs
1388 while ( bestValue < beta
1389 && (move = mp.get_next_move()) != MOVE_NONE)
1391 assert(is_ok(move));
1393 givesCheck = pos.move_gives_check(move, ci);
1401 && !is_promotion(move)
1402 && !pos.is_passed_pawn_push(move))
1404 futilityValue = futilityBase
1405 + PieceValueEndgame[pos.piece_on(move_to(move))]
1406 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1408 if (futilityValue < beta)
1410 if (futilityValue > bestValue)
1411 bestValue = futilityValue;
1416 // Prune moves with negative or equal SEE
1417 if ( futilityBase < beta
1418 && depth < DEPTH_ZERO
1419 && pos.see(move) <= 0)
1423 // Detect non-capture evasions that are candidate to be pruned
1424 evasionPrunable = !PvNode
1426 && bestValue > VALUE_MATED_IN_PLY_MAX
1427 && !pos.is_capture(move)
1428 && !pos.can_castle(pos.side_to_move());
1430 // Don't search moves with negative SEE values
1432 && (!inCheck || evasionPrunable)
1434 && !is_promotion(move)
1435 && pos.see_sign(move) < 0)
1438 // Don't search useless checks
1443 && !pos.is_capture_or_promotion(move)
1444 && ss->eval + PawnValueMidgame / 4 < beta
1445 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1447 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1448 bestValue = ss->eval + PawnValueMidgame / 4;
1453 // Check for legality only before to do the move
1454 if (!pos.pl_move_is_legal(move, ci.pinned))
1457 // Update current move
1458 ss->currentMove = move;
1460 // Make and search the move
1461 pos.do_move(move, st, ci, givesCheck);
1462 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1463 pos.undo_move(move);
1465 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1468 if (value > bestValue)
1471 ss->bestMove = move;
1475 && value < beta) // We want always alpha < beta
1480 // All legal moves have been searched. A special case: If we're in check
1481 // and no legal moves were found, it is checkmate.
1482 if (inCheck && bestValue == -VALUE_INFINITE)
1483 return value_mated_in(ss->ply);
1485 // Update transposition table
1486 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1487 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1488 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1490 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1492 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1498 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1499 // bestValue is updated only when returning false because in that case move
1502 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1504 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1505 Square from, to, ksq, victimSq;
1508 Value futilityValue, bv = *bestValue;
1510 from = move_from(move);
1512 them = flip(pos.side_to_move());
1513 ksq = pos.king_square(them);
1514 kingAtt = pos.attacks_from<KING>(ksq);
1515 pc = pos.piece_on(from);
1517 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1518 oldAtt = pos.attacks_from(pc, from, occ);
1519 newAtt = pos.attacks_from(pc, to, occ);
1521 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1522 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1524 if (!(b && (b & (b - 1))))
1527 // Rule 2. Queen contact check is very dangerous
1528 if ( type_of(pc) == QUEEN
1529 && bit_is_set(kingAtt, to))
1532 // Rule 3. Creating new double threats with checks
1533 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1537 victimSq = pop_1st_bit(&b);
1538 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1540 // Note that here we generate illegal "double move"!
1541 if ( futilityValue >= beta
1542 && pos.see_sign(make_move(from, victimSq)) >= 0)
1545 if (futilityValue > bv)
1549 // Update bestValue only if check is not dangerous (because we will prune the move)
1555 // connected_moves() tests whether two moves are 'connected' in the sense
1556 // that the first move somehow made the second move possible (for instance
1557 // if the moving piece is the same in both moves). The first move is assumed
1558 // to be the move that was made to reach the current position, while the
1559 // second move is assumed to be a move from the current position.
1561 bool connected_moves(const Position& pos, Move m1, Move m2) {
1563 Square f1, t1, f2, t2;
1570 // Case 1: The moving piece is the same in both moves
1576 // Case 2: The destination square for m2 was vacated by m1
1582 // Case 3: Moving through the vacated square
1583 p2 = pos.piece_on(f2);
1584 if ( piece_is_slider(p2)
1585 && bit_is_set(squares_between(f2, t2), f1))
1588 // Case 4: The destination square for m2 is defended by the moving piece in m1
1589 p1 = pos.piece_on(t1);
1590 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1593 // Case 5: Discovered check, checking piece is the piece moved in m1
1594 ksq = pos.king_square(pos.side_to_move());
1595 if ( piece_is_slider(p1)
1596 && bit_is_set(squares_between(t1, ksq), f2))
1598 Bitboard occ = pos.occupied_squares();
1599 clear_bit(&occ, f2);
1600 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1607 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1608 // "plies to mate from the current ply". Non-mate scores are unchanged.
1609 // The function is called before storing a value to the transposition table.
1611 Value value_to_tt(Value v, int ply) {
1613 if (v >= VALUE_MATE_IN_PLY_MAX)
1616 if (v <= VALUE_MATED_IN_PLY_MAX)
1623 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1624 // the transposition table to a mate score corrected for the current ply.
1626 Value value_from_tt(Value v, int ply) {
1628 if (v >= VALUE_MATE_IN_PLY_MAX)
1631 if (v <= VALUE_MATED_IN_PLY_MAX)
1638 // connected_threat() tests whether it is safe to forward prune a move or if
1639 // is somehow connected to the threat move returned by null search.
1641 bool connected_threat(const Position& pos, Move m, Move threat) {
1644 assert(is_ok(threat));
1645 assert(!pos.is_capture_or_promotion(m));
1646 assert(!pos.is_passed_pawn_push(m));
1648 Square mfrom, mto, tfrom, tto;
1650 mfrom = move_from(m);
1652 tfrom = move_from(threat);
1653 tto = move_to(threat);
1655 // Case 1: Don't prune moves which move the threatened piece
1659 // Case 2: If the threatened piece has value less than or equal to the
1660 // value of the threatening piece, don't prune moves which defend it.
1661 if ( pos.is_capture(threat)
1662 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1663 || type_of(pos.piece_on(tfrom)) == KING)
1664 && pos.move_attacks_square(m, tto))
1667 // Case 3: If the moving piece in the threatened move is a slider, don't
1668 // prune safe moves which block its ray.
1669 if ( piece_is_slider(pos.piece_on(tfrom))
1670 && bit_is_set(squares_between(tfrom, tto), mto)
1671 && pos.see_sign(m) >= 0)
1678 // can_return_tt() returns true if a transposition table score
1679 // can be used to cut-off at a given point in search.
1681 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1683 Value v = value_from_tt(tte->value(), ply);
1685 return ( tte->depth() >= depth
1686 || v >= std::max(VALUE_MATE_IN_PLY_MAX, beta)
1687 || v < std::min(VALUE_MATED_IN_PLY_MAX, beta))
1689 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1690 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1694 // refine_eval() returns the transposition table score if
1695 // possible otherwise falls back on static position evaluation.
1697 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1701 Value v = value_from_tt(tte->value(), ply);
1703 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1704 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1711 // update_history() registers a good move that produced a beta-cutoff
1712 // in history and marks as failures all the other moves of that ply.
1714 void update_history(const Position& pos, Move move, Depth depth,
1715 Move movesSearched[], int moveCount) {
1717 Value bonus = Value(int(depth) * int(depth));
1719 H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1721 for (int i = 0; i < moveCount - 1; i++)
1723 m = movesSearched[i];
1727 H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1732 // current_search_time() returns the number of milliseconds which have passed
1733 // since the beginning of the current search.
1735 int elapsed_search_time(int set) {
1737 static int searchStartTime;
1740 searchStartTime = set;
1742 return get_system_time() - searchStartTime;
1746 // score_to_uci() converts a value to a string suitable for use with the UCI
1747 // protocol specifications:
1749 // cp <x> The score from the engine's point of view in centipawns.
1750 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1751 // use negative values for y.
1753 string score_to_uci(Value v, Value alpha, Value beta) {
1755 std::stringstream s;
1757 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1758 s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1760 s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1762 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1768 // speed_to_uci() returns a string with time stats of current search suitable
1769 // to be sent to UCI gui.
1771 string speed_to_uci(int64_t nodes) {
1773 std::stringstream s;
1774 int t = elapsed_search_time();
1776 s << " nodes " << nodes
1777 << " nps " << (t > 0 ? int(nodes * 1000 / t) : 0)
1784 // pv_to_uci() returns a string with information on the current PV line
1785 // formatted according to UCI specification.
1787 string pv_to_uci(const Move pv[], int pvNum, bool chess960) {
1789 std::stringstream s;
1791 s << " multipv " << pvNum << " pv " << set960(chess960);
1793 for ( ; *pv != MOVE_NONE; pv++)
1800 // depth_to_uci() returns a string with information on the current depth and
1801 // seldepth formatted according to UCI specification.
1803 string depth_to_uci(Depth depth) {
1805 std::stringstream s;
1807 // Retrieve max searched depth among threads
1809 for (int i = 0; i < Threads.size(); i++)
1810 if (Threads[i].maxPly > selDepth)
1811 selDepth = Threads[i].maxPly;
1813 s << " depth " << depth / ONE_PLY << " seldepth " << selDepth;
1818 string time_to_string(int millisecs) {
1820 const int MSecMinute = 1000 * 60;
1821 const int MSecHour = 1000 * 60 * 60;
1823 int hours = millisecs / MSecHour;
1824 int minutes = (millisecs % MSecHour) / MSecMinute;
1825 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1827 std::stringstream s;
1832 s << std::setfill('0') << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
1836 string score_to_string(Value v) {
1838 std::stringstream s;
1840 if (v >= VALUE_MATE_IN_PLY_MAX)
1841 s << "#" << (VALUE_MATE - v + 1) / 2;
1842 else if (v <= VALUE_MATED_IN_PLY_MAX)
1843 s << "-#" << (VALUE_MATE + v) / 2;
1845 s << std::setprecision(2) << std::fixed << std::showpos << float(v) / PawnValueMidgame;
1851 // pretty_pv() creates a human-readable string from a position and a PV.
1852 // It is used to write search information to the log file (which is created
1853 // when the UCI parameter "Use Search Log" is "true").
1855 string pretty_pv(Position& pos, int depth, Value value, int time, Move pv[]) {
1857 const int64_t K = 1000;
1858 const int64_t M = 1000000;
1859 const int startColumn = 28;
1860 const size_t maxLength = 80 - startColumn;
1862 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1865 std::stringstream s;
1868 // First print depth, score, time and searched nodes...
1869 s << set960(pos.is_chess960())
1870 << std::setw(2) << depth
1871 << std::setw(8) << score_to_string(value)
1872 << std::setw(8) << time_to_string(time);
1874 if (pos.nodes_searched() < M)
1875 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1876 else if (pos.nodes_searched() < K * M)
1877 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1879 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1881 // ...then print the full PV line in short algebraic notation
1882 while (*m != MOVE_NONE)
1884 san = move_to_san(pos, *m);
1885 length += san.length() + 1;
1887 if (length > maxLength)
1889 length = san.length() + 1;
1890 s << "\n" + string(startColumn, ' ');
1894 pos.do_move(*m++, *st++);
1897 // Restore original position before to leave
1898 while (m != pv) pos.undo_move(*--m);
1904 // When playing with strength handicap choose best move among the MultiPV set
1905 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1907 void do_skill_level(Move* best, Move* ponder) {
1909 assert(MultiPV > 1);
1913 // Rml list is already sorted by score in descending order
1915 int max_s = -VALUE_INFINITE;
1916 int size = std::min(MultiPV, (int)Rml.size());
1917 int max = Rml[0].score;
1918 int var = std::min(max - Rml[size - 1].score, int(PawnValueMidgame));
1919 int wk = 120 - 2 * SkillLevel;
1921 // PRNG sequence should be non deterministic
1922 for (int i = abs(get_system_time() % 50); i > 0; i--)
1923 rk.rand<unsigned>();
1925 // Choose best move. For each move's score we add two terms both dependent
1926 // on wk, one deterministic and bigger for weaker moves, and one random,
1927 // then we choose the move with the resulting highest score.
1928 for (int i = 0; i < size; i++)
1932 // Don't allow crazy blunders even at very low skills
1933 if (i > 0 && Rml[i-1].score > s + EasyMoveMargin)
1936 // This is our magical formula
1937 s += ((max - s) * wk + var * (rk.rand<unsigned>() % wk)) / 128;
1942 *best = Rml[i].pv[0];
1943 *ponder = Rml[i].pv[1];
1949 /// RootMove and RootMoveList method's definitions
1951 void RootMoveList::init(Position& pos, Move rootMoves[]) {
1954 bestMoveChanges = 0;
1957 // Generate all legal moves and add them to RootMoveList
1958 for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
1960 // If we have a rootMoves[] list then verify the move
1961 // is in the list before to add it.
1962 for (sm = rootMoves; *sm && *sm != ml.move(); sm++) {}
1964 if (sm != rootMoves && *sm != ml.move())
1968 rm.pv.push_back(ml.move());
1969 rm.pv.push_back(MOVE_NONE);
1970 rm.score = rm.prevScore = -VALUE_INFINITE;
1976 RootMove* RootMoveList::find(const Move& m, int startIndex) {
1978 for (size_t i = startIndex; i < size(); i++)
1979 if ((*this)[i].pv[0] == m)
1986 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1987 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1988 // allow to always have a ponder move even when we fail high at root and also a
1989 // long PV to print that is important for position analysis.
1991 void RootMove::extract_pv_from_tt(Position& pos) {
1993 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1998 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
2002 pos.do_move(m, *st++);
2004 while ( (tte = TT.probe(pos.get_key())) != NULL
2005 && tte->move() != MOVE_NONE
2006 && pos.is_pseudo_legal(tte->move())
2007 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
2009 && (!pos.is_draw<false>() || ply < 2))
2011 pv.push_back(tte->move());
2012 pos.do_move(tte->move(), *st++);
2015 pv.push_back(MOVE_NONE);
2017 do pos.undo_move(pv[--ply]); while (ply);
2021 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2022 // the PV back into the TT. This makes sure the old PV moves are searched
2023 // first, even if the old TT entries have been overwritten.
2025 void RootMove::insert_pv_in_tt(Position& pos) {
2027 StateInfo state[PLY_MAX_PLUS_2], *st = state;
2030 Value v, m = VALUE_NONE;
2033 assert(pv[0] != MOVE_NONE && pos.is_pseudo_legal(pv[0]));
2039 // Don't overwrite existing correct entries
2040 if (!tte || tte->move() != pv[ply])
2042 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
2043 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2045 pos.do_move(pv[ply], *st++);
2047 } while (pv[++ply] != MOVE_NONE);
2049 do pos.undo_move(pv[--ply]); while (ply);
2055 // Thread::idle_loop() is where the thread is parked when it has no work to do.
2056 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
2057 // for which the thread is the master.
2059 void Thread::idle_loop(SplitPoint* sp) {
2063 // If we are not searching, wait for a condition to be signaled
2064 // instead of wasting CPU time polling for work.
2067 || (Threads.use_sleeping_threads() && !is_searching))
2069 assert((!sp && threadID) || Threads.use_sleeping_threads());
2071 // Slave thread should exit as soon as do_terminate flag raises
2078 // Grab the lock to avoid races with Thread::wake_up()
2079 lock_grab(&sleepLock);
2081 // If we are master and all slaves have finished don't go to sleep
2082 if (sp && Threads.split_point_finished(sp))
2084 lock_release(&sleepLock);
2088 // Do sleep after retesting sleep conditions under lock protection, in
2089 // particular we need to avoid a deadlock in case a master thread has,
2090 // in the meanwhile, allocated us and sent the wake_up() call before we
2091 // had the chance to grab the lock.
2092 if (do_sleep || !is_searching)
2093 cond_wait(&sleepCond, &sleepLock);
2095 lock_release(&sleepLock);
2098 // If this thread has been assigned work, launch a search
2101 assert(!do_terminate);
2103 // Copy split point position and search stack and call search()
2104 SearchStack ss[PLY_MAX_PLUS_2];
2105 SplitPoint* tsp = splitPoint;
2106 Position pos(*tsp->pos, threadID);
2108 memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2111 if (tsp->nodeType == Root)
2112 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2113 else if (tsp->nodeType == PV)
2114 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2115 else if (tsp->nodeType == NonPV)
2116 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2120 assert(is_searching);
2122 is_searching = false;
2124 // Wake up master thread so to allow it to return from the idle loop in
2125 // case we are the last slave of the split point.
2126 if ( Threads.use_sleeping_threads()
2127 && threadID != tsp->master
2128 && !Threads[tsp->master].is_searching)
2129 Threads[tsp->master].wake_up();
2132 // If this thread is the master of a split point and all slaves have
2133 // finished their work at this split point, return from the idle loop.
2134 if (sp && Threads.split_point_finished(sp))
2136 // Because sp->is_slave[] is reset under lock protection,
2137 // be sure sp->lock has been released before to return.
2138 lock_grab(&(sp->lock));
2139 lock_release(&(sp->lock));
2146 // do_timer_event() is called by the timer thread when the timer triggers
2148 void do_timer_event() {
2150 static int lastInfoTime;
2151 int e = elapsed_search_time();
2153 // Print debug information every one second
2154 if (!lastInfoTime || get_system_time() - lastInfoTime >= 1000)
2156 lastInfoTime = get_system_time();
2159 dbg_print_hit_rate();
2162 // Should we stop the search?
2166 bool stillAtFirstMove = Signals.firstRootMove
2167 && !Signals.failedLowAtRoot
2168 && e > TimeMgr.available_time();
2170 bool noMoreTime = e > TimeMgr.maximum_time()
2171 || stillAtFirstMove;
2173 if ( (Limits.useTimeManagement() && noMoreTime)
2174 || (Limits.maxTime && e >= Limits.maxTime)
2175 /* missing nodes limit */ ) // FIXME
2176 Signals.stop = true;