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 // Set output stream mode: normal or chess960. Castling notation is different
371 cout << set960(pos.is_chess960());
373 // Look for a book move
374 if (Options["OwnBook"].value<bool>())
376 if (Options["Book File"].value<string>() != book.name())
377 book.open(Options["Book File"].value<string>());
379 Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
380 if (bookMove != MOVE_NONE)
382 if (!Signals.stop && (Limits.ponder || Limits.infinite))
383 Threads.wait_for_stop_or_ponderhit();
385 cout << "bestmove " << bookMove << endl;
390 // Read UCI options: GUI could change UCI parameters during the game
391 read_evaluation_uci_options(pos.side_to_move());
392 Threads.read_uci_options();
394 // Set a new TT size if changed
395 TT.set_size(Options["Hash"].value<int>());
397 if (Options["Clear Hash"].value<bool>())
399 Options["Clear Hash"].set_value("false");
403 UCIMultiPV = Options["MultiPV"].value<int>();
404 SkillLevel = Options["Skill Level"].value<int>();
406 // Do we have to play with skill handicap? In this case enable MultiPV that
407 // we will use behind the scenes to retrieve a set of possible moves.
408 SkillLevelEnabled = (SkillLevel < 20);
409 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, 4) : UCIMultiPV);
411 // Write current search header to log file
412 if (Options["Use Search Log"].value<bool>())
414 Log log(Options["Search Log Filename"].value<string>());
415 log << "\nSearching: " << pos.to_fen()
416 << "\ninfinite: " << Limits.infinite
417 << " ponder: " << Limits.ponder
418 << " time: " << Limits.time
419 << " increment: " << Limits.increment
420 << " moves to go: " << Limits.movesToGo
424 // Wake up needed threads and reset maxPly counter
425 for (int i = 0; i < Threads.size(); i++)
427 Threads[i].maxPly = 0;
428 Threads[i].wake_up();
431 // Set best timer interval to avoid lagging under time pressure. Timer is
432 // used to check for remaining available thinking time.
433 TimeMgr.init(Limits, pos.startpos_ply_counter());
435 if (TimeMgr.available_time())
436 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
438 Threads.set_timer(100);
440 // We're ready to start thinking. Call the iterative deepening loop function
441 Move ponderMove = MOVE_NONE;
442 Move bestMove = id_loop(pos, &RootMoves[0], &ponderMove);
444 // Stop timer, no need to check for available time any more
445 Threads.set_timer(0);
447 // This makes all the slave threads to go to sleep, if not already sleeping
450 // Write current search final statistics to log file
451 if (Options["Use Search Log"].value<bool>())
453 int e = elapsed_search_time();
455 Log log(Options["Search Log Filename"].value<string>());
456 log << "Nodes: " << pos.nodes_searched()
457 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
458 << "\nBest move: " << move_to_san(pos, bestMove);
461 pos.do_move(bestMove, st);
462 log << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
463 pos.undo_move(bestMove); // Return from think() with unchanged position
466 // When we reach max depth we arrive here even without a StopRequest, but if
467 // we are pondering or in infinite search, we shouldn't print the best move
468 // before we are told to do so.
469 if (!Signals.stop && (Limits.ponder || Limits.infinite))
470 Threads.wait_for_stop_or_ponderhit();
472 // Could be MOVE_NONE when searching on a stalemate position
473 cout << "bestmove " << bestMove;
475 // UCI protol is not clear on allowing sending an empty ponder move, instead
476 // it is clear that ponder move is optional. So skip it if empty.
477 if (ponderMove != MOVE_NONE)
478 cout << " ponder " << ponderMove;
486 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
487 // with increasing depth until the allocated thinking time has been consumed,
488 // user stops the search, or the maximum search depth is reached.
490 Move id_loop(Position& pos, Move rootMoves[], Move* ponderMove) {
492 SearchStack ss[PLY_MAX_PLUS_2];
493 Value bestValues[PLY_MAX_PLUS_2];
494 int bestMoveChanges[PLY_MAX_PLUS_2];
495 int depth, aspirationDelta;
496 Value bestValue, alpha, beta;
497 Move bestMove, skillBest, skillPonder;
498 bool bestMoveNeverChanged = true;
500 // Initialize stuff before a new search
501 memset(ss, 0, 4 * sizeof(SearchStack));
504 *ponderMove = bestMove = skillBest = skillPonder = MOVE_NONE;
505 depth = aspirationDelta = 0;
506 bestValue = alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
507 ss->currentMove = MOVE_NULL; // Hack to skip update gains
509 // Moves to search are verified and copied
510 Rml.init(pos, rootMoves);
512 // Handle special case of searching on a mate/stalemate position
515 cout << "info" << depth_to_uci(DEPTH_ZERO)
516 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW, alpha, beta) << endl;
521 // Iterative deepening loop until requested to stop or target depth reached
522 while (!Signals.stop && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
524 // Save now last iteration's scores, before Rml moves are reordered
525 for (size_t i = 0; i < Rml.size(); i++)
526 Rml[i].prevScore = Rml[i].score;
528 Rml.bestMoveChanges = 0;
530 // MultiPV loop. We perform a full root search for each PV line
531 for (MultiPVIdx = 0; MultiPVIdx < std::min(MultiPV, (int)Rml.size()); MultiPVIdx++)
533 // Calculate dynamic aspiration window based on previous iterations
534 if (depth >= 5 && abs(Rml[MultiPVIdx].prevScore) < VALUE_KNOWN_WIN)
536 int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
537 int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
539 aspirationDelta = std::min(std::max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
540 aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
542 alpha = std::max(Rml[MultiPVIdx].prevScore - aspirationDelta, -VALUE_INFINITE);
543 beta = std::min(Rml[MultiPVIdx].prevScore + aspirationDelta, VALUE_INFINITE);
547 alpha = -VALUE_INFINITE;
548 beta = VALUE_INFINITE;
551 // Start with a small aspiration window and, in case of fail high/low,
552 // research with bigger window until not failing high/low anymore.
554 // Search starts from ss+1 to allow referencing (ss-1). This is
555 // needed by update gains and ss copy when splitting at Root.
556 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
558 // Bring to front the best move. It is critical that sorting is
559 // done with a stable algorithm because all the values but the first
560 // and eventually the new best one are set to -VALUE_INFINITE and
561 // we want to keep the same order for all the moves but the new
562 // PV that goes to the front. Note that in case of MultiPV search
563 // the already searched PV lines are preserved.
564 sort<RootMove>(Rml.begin() + MultiPVIdx, Rml.end());
566 // In case we have found an exact score and we are going to leave
567 // the fail high/low loop then reorder the PV moves, otherwise
568 // leave the last PV move in its position so to be searched again.
569 // Of course this is needed only in MultiPV search.
570 if (MultiPVIdx && bestValue > alpha && bestValue < beta)
571 sort<RootMove>(Rml.begin(), Rml.begin() + MultiPVIdx);
573 // Write PV back to transposition table in case the relevant entries
574 // have been overwritten during the search.
575 for (int i = 0; i <= MultiPVIdx; i++)
576 Rml[i].insert_pv_in_tt(pos);
578 // If search has been stopped exit the aspiration window loop,
579 // note that sorting and writing PV back to TT is safe becuase
580 // Rml is still valid, although refers to the previous iteration.
584 // Send full PV info to GUI if we are going to leave the loop or
585 // if we have a fail high/low and we are deep in the search. UCI
586 // protocol requires to send all the PV lines also if are still
587 // to be searched and so refer to the previous search's score.
588 if ((bestValue > alpha && bestValue < beta) || elapsed_search_time() > 2000)
589 for (int i = 0; i < std::min(UCIMultiPV, (int)Rml.size()); i++)
591 bool updated = (i <= MultiPVIdx);
593 if (depth == 1 && !updated)
596 Depth d = (updated ? depth : depth - 1) * ONE_PLY;
597 Value s = (updated ? Rml[i].score : Rml[i].prevScore);
601 << (i == MultiPVIdx ? score_to_uci(s, alpha, beta) : score_to_uci(s))
602 << speed_to_uci(pos.nodes_searched())
603 << pv_to_uci(&Rml[i].pv[0], i + 1, pos.is_chess960())
607 // In case of failing high/low increase aspiration window and
608 // research, otherwise exit the fail high/low loop.
609 if (bestValue >= beta)
611 beta = std::min(beta + aspirationDelta, VALUE_INFINITE);
612 aspirationDelta += aspirationDelta / 2;
614 else if (bestValue <= alpha)
616 Signals.failedLowAtRoot = true;
617 Signals.stopOnPonderhit = false;
619 alpha = std::max(alpha - aspirationDelta, -VALUE_INFINITE);
620 aspirationDelta += aspirationDelta / 2;
625 } while (abs(bestValue) < VALUE_KNOWN_WIN);
628 // Collect info about search result
629 bestMove = Rml[0].pv[0];
630 *ponderMove = Rml[0].pv[1];
631 bestValues[depth] = bestValue;
632 bestMoveChanges[depth] = Rml.bestMoveChanges;
634 // Skills: Do we need to pick now the best and the ponder moves ?
635 if (SkillLevelEnabled && depth == 1 + SkillLevel)
636 do_skill_level(&skillBest, &skillPonder);
638 if (Options["Use Search Log"].value<bool>())
640 Log log(Options["Search Log Filename"].value<string>());
641 log << pretty_pv(pos, depth, bestValue, elapsed_search_time(), &Rml[0].pv[0]) << endl;
644 // Filter out startup noise when monitoring best move stability
645 if (depth > 2 && bestMoveChanges[depth])
646 bestMoveNeverChanged = false;
648 // Do we have time for the next iteration? Can we stop searching now?
649 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
651 bool stop = false; // Local variable instead of the volatile Signals.stop
653 // Take in account some extra time if the best move has changed
654 if (depth > 4 && depth < 50)
655 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
657 // Stop search if most of available time is already consumed. We probably don't
658 // have enough time to search the first move at the next iteration anyway.
659 if (elapsed_search_time() > (TimeMgr.available_time() * 62) / 100)
662 // Stop search early if one move seems to be much better than others
665 && ( bestMoveNeverChanged
666 || elapsed_search_time() > (TimeMgr.available_time() * 40) / 100))
668 Value rBeta = bestValue - EasyMoveMargin;
669 (ss+1)->excludedMove = bestMove;
670 (ss+1)->skipNullMove = true;
671 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
672 (ss+1)->skipNullMove = false;
673 (ss+1)->excludedMove = MOVE_NONE;
681 // If we are allowed to ponder do not stop the search now but
682 // keep pondering until GUI sends "ponderhit" or "stop".
683 if (Limits.ponder) // FIXME racing
684 Signals.stopOnPonderhit = true;
691 // When using skills overwrite best and ponder moves with the sub-optimal ones
692 if (SkillLevelEnabled)
694 if (skillBest == MOVE_NONE) // Still unassigned ?
695 do_skill_level(&skillBest, &skillPonder);
697 bestMove = skillBest;
698 *ponderMove = skillPonder;
705 // search<>() is the main search function for both PV and non-PV nodes and for
706 // normal and SplitPoint nodes. When called just after a split point the search
707 // is simpler because we have already probed the hash table, done a null move
708 // search, and searched the first move before splitting, we don't have to repeat
709 // all this work again. We also don't need to store anything to the hash table
710 // here: This is taken care of after we return from the split point.
712 template <NodeType NT>
713 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
715 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
716 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
717 const bool RootNode = (NT == Root || NT == SplitPointRoot);
719 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
720 assert(beta > alpha && beta <= VALUE_INFINITE);
721 assert(PvNode || alpha == beta - 1);
722 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
724 Move movesSearched[MAX_MOVES];
729 Move ttMove, move, excludedMove, threatMove;
732 Value bestValue, value, oldAlpha;
733 Value refinedValue, nullValue, futilityBase, futilityValue;
734 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
735 bool captureOrPromotion, dangerous, doFullDepthSearch;
736 int moveCount = 0, playedMoveCount = 0;
737 Thread& thread = Threads[pos.thread()];
738 SplitPoint* sp = NULL;
740 refinedValue = bestValue = value = -VALUE_INFINITE;
742 inCheck = pos.in_check();
743 ss->ply = (ss-1)->ply + 1;
745 // Used to send selDepth info to GUI
746 if (PvNode && thread.maxPly < ss->ply)
747 thread.maxPly = ss->ply;
749 // Step 1. Initialize node
752 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
753 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
754 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
760 ttMove = excludedMove = MOVE_NONE;
761 threatMove = sp->threatMove;
762 goto split_point_start;
765 // Step 2. Check for aborted search and immediate draw
767 || pos.is_draw<false>()
768 || ss->ply > PLY_MAX) && !RootNode)
771 // Step 3. Mate distance pruning
774 alpha = std::max(value_mated_in(ss->ply), alpha);
775 beta = std::min(value_mate_in(ss->ply+1), beta);
780 // Step 4. Transposition table lookup
781 // We don't want the score of a partial search to overwrite a previous full search
782 // TT value, so we use a different position key in case of an excluded move.
783 excludedMove = ss->excludedMove;
784 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
785 tte = TT.probe(posKey);
786 ttMove = RootNode ? Rml[MultiPVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
788 // At PV nodes we check for exact scores, while at non-PV nodes we check for
789 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
790 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
791 // we should also update RootMoveList to avoid bogus output.
792 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
793 : can_return_tt(tte, depth, beta, ss->ply)))
796 ss->bestMove = move = ttMove; // Can be MOVE_NONE
797 value = value_from_tt(tte->value(), ss->ply);
801 && !pos.is_capture_or_promotion(move)
802 && move != ss->killers[0])
804 ss->killers[1] = ss->killers[0];
805 ss->killers[0] = move;
810 // Step 5. Evaluate the position statically and update parent's gain statistics
812 ss->eval = ss->evalMargin = VALUE_NONE;
815 assert(tte->static_value() != VALUE_NONE);
817 ss->eval = tte->static_value();
818 ss->evalMargin = tte->static_value_margin();
819 refinedValue = refine_eval(tte, ss->eval, ss->ply);
823 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
824 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
827 // Update gain for the parent non-capture move given the static position
828 // evaluation before and after the move.
829 if ( (move = (ss-1)->currentMove) != MOVE_NULL
830 && (ss-1)->eval != VALUE_NONE
831 && ss->eval != VALUE_NONE
832 && pos.captured_piece_type() == PIECE_TYPE_NONE
833 && !is_special(move))
835 Square to = move_to(move);
836 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
839 // Step 6. Razoring (is omitted in PV nodes)
841 && depth < RazorDepth
843 && refinedValue + razor_margin(depth) < beta
844 && ttMove == MOVE_NONE
845 && abs(beta) < VALUE_MATE_IN_PLY_MAX
846 && !pos.has_pawn_on_7th(pos.side_to_move()))
848 Value rbeta = beta - razor_margin(depth);
849 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
851 // Logically we should return (v + razor_margin(depth)), but
852 // surprisingly this did slightly weaker in tests.
856 // Step 7. Static null move pruning (is omitted in PV nodes)
857 // We're betting that the opponent doesn't have a move that will reduce
858 // the score by more than futility_margin(depth) if we do a null move.
861 && depth < RazorDepth
863 && refinedValue - futility_margin(depth, 0) >= beta
864 && abs(beta) < VALUE_MATE_IN_PLY_MAX
865 && pos.non_pawn_material(pos.side_to_move()))
866 return refinedValue - futility_margin(depth, 0);
868 // Step 8. Null move search with verification search (is omitted in PV nodes)
873 && refinedValue >= beta
874 && abs(beta) < VALUE_MATE_IN_PLY_MAX
875 && pos.non_pawn_material(pos.side_to_move()))
877 ss->currentMove = MOVE_NULL;
879 // Null move dynamic reduction based on depth
880 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
882 // Null move dynamic reduction based on value
883 if (refinedValue - PawnValueMidgame > beta)
886 pos.do_null_move<true>(st);
887 (ss+1)->skipNullMove = true;
888 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
889 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
890 (ss+1)->skipNullMove = false;
891 pos.do_null_move<false>(st);
893 if (nullValue >= beta)
895 // Do not return unproven mate scores
896 if (nullValue >= VALUE_MATE_IN_PLY_MAX)
899 if (depth < 6 * ONE_PLY)
902 // Do verification search at high depths
903 ss->skipNullMove = true;
904 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
905 ss->skipNullMove = false;
912 // The null move failed low, which means that we may be faced with
913 // some kind of threat. If the previous move was reduced, check if
914 // the move that refuted the null move was somehow connected to the
915 // move which was reduced. If a connection is found, return a fail
916 // low score (which will cause the reduced move to fail high in the
917 // parent node, which will trigger a re-search with full depth).
918 threatMove = (ss+1)->bestMove;
920 if ( depth < ThreatDepth
922 && threatMove != MOVE_NONE
923 && connected_moves(pos, (ss-1)->currentMove, threatMove))
928 // Step 9. ProbCut (is omitted in PV nodes)
929 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
930 // and a reduced search returns a value much above beta, we can (almost) safely
931 // prune the previous move.
933 && depth >= RazorDepth + ONE_PLY
936 && excludedMove == MOVE_NONE
937 && abs(beta) < VALUE_MATE_IN_PLY_MAX)
939 Value rbeta = beta + 200;
940 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
942 assert(rdepth >= ONE_PLY);
944 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
947 while ((move = mp.get_next_move()) != MOVE_NONE)
948 if (pos.pl_move_is_legal(move, ci.pinned))
950 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
951 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
958 // Step 10. Internal iterative deepening
959 if ( depth >= IIDDepth[PvNode]
960 && ttMove == MOVE_NONE
961 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
963 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
965 ss->skipNullMove = true;
966 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
967 ss->skipNullMove = false;
969 tte = TT.probe(posKey);
970 ttMove = tte ? tte->move() : MOVE_NONE;
973 split_point_start: // At split points actual search starts from here
975 // Initialize a MovePicker object for the current position
976 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
978 ss->bestMove = MOVE_NONE;
979 futilityBase = ss->eval + ss->evalMargin;
980 singularExtensionNode = !RootNode
982 && depth >= SingularExtensionDepth[PvNode]
983 && ttMove != MOVE_NONE
984 && !excludedMove // Do not allow recursive singular extension search
985 && (tte->type() & VALUE_TYPE_LOWER)
986 && tte->depth() >= depth - 3 * ONE_PLY;
989 lock_grab(&(sp->lock));
990 bestValue = sp->bestValue;
993 // Step 11. Loop through moves
994 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
995 while ( bestValue < beta
996 && (move = mp.get_next_move()) != MOVE_NONE
997 && !thread.cutoff_occurred())
1001 if (move == excludedMove)
1004 // At root obey the "searchmoves" option and skip moves not listed in Root
1005 // Move List, as a consequence any illegal move is also skipped. In MultiPV
1006 // mode we also skip PV moves which have been already searched.
1007 if (RootNode && !Rml.find(move, MultiPVIdx))
1010 // At PV and SpNode nodes we want all moves to be legal since the beginning
1011 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
1016 moveCount = ++sp->moveCount;
1017 lock_release(&(sp->lock));
1024 // This is used by time management
1025 Signals.firstRootMove = (moveCount == 1);
1027 // Save the current node count before the move is searched
1028 nodes = pos.nodes_searched();
1030 // For long searches send current move info to GUI
1031 if (pos.thread() == 0 && elapsed_search_time() > 2000)
1032 cout << "info" << depth_to_uci(depth)
1033 << " currmove " << move
1034 << " currmovenumber " << moveCount + MultiPVIdx << endl;
1037 isPvMove = (PvNode && moveCount <= 1);
1038 givesCheck = pos.move_gives_check(move, ci);
1039 captureOrPromotion = pos.is_capture_or_promotion(move);
1041 // Step 12. Decide the new search depth
1042 ext = extension<PvNode>(pos, move, captureOrPromotion, givesCheck, &dangerous);
1044 // Singular extension search. If all moves but one fail low on a search of
1045 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
1046 // is singular and should be extended. To verify this we do a reduced search
1047 // on all the other moves but the ttMove, if result is lower than ttValue minus
1048 // a margin then we extend ttMove.
1049 if ( singularExtensionNode
1051 && pos.pl_move_is_legal(move, ci.pinned)
1054 Value ttValue = value_from_tt(tte->value(), ss->ply);
1056 if (abs(ttValue) < VALUE_KNOWN_WIN)
1058 Value rBeta = ttValue - int(depth);
1059 ss->excludedMove = move;
1060 ss->skipNullMove = true;
1061 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1062 ss->skipNullMove = false;
1063 ss->excludedMove = MOVE_NONE;
1064 ss->bestMove = MOVE_NONE;
1070 // Update current move (this must be done after singular extension search)
1071 newDepth = depth - ONE_PLY + ext;
1073 // Step 13. Futility pruning (is omitted in PV nodes)
1075 && !captureOrPromotion
1079 && !is_castle(move))
1081 // Move count based pruning
1082 if ( moveCount >= futility_move_count(depth)
1083 && (!threatMove || !connected_threat(pos, move, threatMove))
1084 && bestValue > VALUE_MATED_IN_PLY_MAX) // FIXME bestValue is racy
1087 lock_grab(&(sp->lock));
1092 // Value based pruning
1093 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1094 // but fixing this made program slightly weaker.
1095 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
1096 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
1097 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1099 if (futilityValue < beta)
1103 lock_grab(&(sp->lock));
1104 if (futilityValue > sp->bestValue)
1105 sp->bestValue = bestValue = futilityValue;
1107 else if (futilityValue > bestValue)
1108 bestValue = futilityValue;
1113 // Prune moves with negative SEE at low depths
1114 if ( predictedDepth < 2 * ONE_PLY
1115 && bestValue > VALUE_MATED_IN_PLY_MAX
1116 && pos.see_sign(move) < 0)
1119 lock_grab(&(sp->lock));
1125 // Check for legality only before to do the move
1126 if (!pos.pl_move_is_legal(move, ci.pinned))
1132 ss->currentMove = move;
1133 if (!SpNode && !captureOrPromotion)
1134 movesSearched[playedMoveCount++] = move;
1136 // Step 14. Make the move
1137 pos.do_move(move, st, ci, givesCheck);
1139 // Step 15. Reduced depth search (LMR). If the move fails high will be
1140 // re-searched at full depth.
1141 if ( depth > 3 * ONE_PLY
1143 && !captureOrPromotion
1146 && ss->killers[0] != move
1147 && ss->killers[1] != move)
1149 ss->reduction = reduction<PvNode>(depth, moveCount);
1150 Depth d = newDepth - ss->reduction;
1151 alpha = SpNode ? sp->alpha : alpha;
1153 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1154 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1156 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1157 ss->reduction = DEPTH_ZERO;
1160 doFullDepthSearch = !isPvMove;
1162 // Step 16. Full depth search, when LMR is skipped or fails high
1163 if (doFullDepthSearch)
1165 alpha = SpNode ? sp->alpha : alpha;
1166 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1167 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1170 // Only for PV nodes do a full PV search on the first move or after a fail
1171 // high, in the latter case search only if value < beta, otherwise let the
1172 // parent node to fail low with value <= alpha and to try another move.
1173 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1174 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1175 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1177 // Step 17. Undo move
1178 pos.undo_move(move);
1180 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1182 // Step 18. Check for new best move
1185 lock_grab(&(sp->lock));
1186 bestValue = sp->bestValue;
1190 // Finished searching the move. If StopRequest is true, the search
1191 // was aborted because the user interrupted the search or because we
1192 // ran out of time. In this case, the return value of the search cannot
1193 // be trusted, and we don't update the best move and/or PV.
1194 if (RootNode && !Signals.stop)
1196 // Remember searched nodes counts for this move
1197 RootMove* rm = Rml.find(move);
1198 rm->nodes += pos.nodes_searched() - nodes;
1200 // PV move or new best move ?
1201 if (isPvMove || value > alpha)
1205 rm->extract_pv_from_tt(pos);
1207 // We record how often the best move has been changed in each
1208 // iteration. This information is used for time management: When
1209 // the best move changes frequently, we allocate some more time.
1210 if (!isPvMove && MultiPV == 1)
1211 Rml.bestMoveChanges++;
1214 // All other moves but the PV are set to the lowest value, this
1215 // is not a problem when sorting becuase sort is stable and move
1216 // position in the list is preserved, just the PV is pushed up.
1217 rm->score = -VALUE_INFINITE;
1221 if (value > bestValue)
1224 ss->bestMove = move;
1228 && value < beta) // We want always alpha < beta
1231 if (SpNode && !thread.cutoff_occurred())
1233 sp->bestValue = value;
1234 sp->ss->bestMove = move;
1236 sp->is_betaCutoff = (value >= beta);
1240 // Step 19. Check for split
1242 && depth >= Threads.min_split_depth()
1244 && Threads.available_slave_exists(pos.thread())
1246 && !thread.cutoff_occurred())
1247 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1248 threatMove, moveCount, &mp, NT);
1251 // Step 20. Check for mate and stalemate
1252 // All legal moves have been searched and if there are no legal moves, it
1253 // must be mate or stalemate. Note that we can have a false positive in
1254 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1255 // harmless because return value is discarded anyhow in the parent nodes.
1256 // If we are in a singular extension search then return a fail low score.
1257 if (!SpNode && !moveCount)
1258 return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1260 // Step 21. Update tables
1261 // If the search is not aborted, update the transposition table,
1262 // history counters, and killer moves.
1263 if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1265 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1266 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1267 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1269 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1271 // Update killers and history only for non capture moves that fails high
1272 if ( bestValue >= beta
1273 && !pos.is_capture_or_promotion(move))
1275 if (move != ss->killers[0])
1277 ss->killers[1] = ss->killers[0];
1278 ss->killers[0] = move;
1280 update_history(pos, move, depth, movesSearched, playedMoveCount);
1286 // Here we have the lock still grabbed
1287 sp->is_slave[pos.thread()] = false;
1288 sp->nodes += pos.nodes_searched();
1289 lock_release(&(sp->lock));
1292 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1297 // qsearch() is the quiescence search function, which is called by the main
1298 // search function when the remaining depth is zero (or, to be more precise,
1299 // less than ONE_PLY).
1301 template <NodeType NT>
1302 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
1304 const bool PvNode = (NT == PV);
1306 assert(NT == PV || NT == NonPV);
1307 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1308 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1309 assert(PvNode || alpha == beta - 1);
1311 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1315 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1316 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1320 Value oldAlpha = alpha;
1322 ss->bestMove = ss->currentMove = MOVE_NONE;
1323 ss->ply = (ss-1)->ply + 1;
1325 // Check for an instant draw or maximum ply reached
1326 if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1329 // Decide whether or not to include checks, this fixes also the type of
1330 // TT entry depth that we are going to use. Note that in qsearch we use
1331 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1332 inCheck = pos.in_check();
1333 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1335 // Transposition table lookup. At PV nodes, we don't use the TT for
1336 // pruning, but only for move ordering.
1337 tte = TT.probe(pos.get_key());
1338 ttMove = (tte ? tte->move() : MOVE_NONE);
1340 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1342 ss->bestMove = ttMove; // Can be MOVE_NONE
1343 return value_from_tt(tte->value(), ss->ply);
1346 // Evaluate the position statically
1349 bestValue = futilityBase = -VALUE_INFINITE;
1350 ss->eval = evalMargin = VALUE_NONE;
1351 enoughMaterial = false;
1357 assert(tte->static_value() != VALUE_NONE);
1359 evalMargin = tte->static_value_margin();
1360 ss->eval = bestValue = tte->static_value();
1363 ss->eval = bestValue = evaluate(pos, evalMargin);
1365 // Stand pat. Return immediately if static value is at least beta
1366 if (bestValue >= beta)
1369 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1374 if (PvNode && bestValue > alpha)
1377 // Futility pruning parameters, not needed when in check
1378 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1379 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1382 // Initialize a MovePicker object for the current position, and prepare
1383 // to search the moves. Because the depth is <= 0 here, only captures,
1384 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1386 MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1389 // Loop through the moves until no moves remain or a beta cutoff occurs
1390 while ( bestValue < beta
1391 && (move = mp.get_next_move()) != MOVE_NONE)
1393 assert(is_ok(move));
1395 givesCheck = pos.move_gives_check(move, ci);
1403 && !is_promotion(move)
1404 && !pos.is_passed_pawn_push(move))
1406 futilityValue = futilityBase
1407 + PieceValueEndgame[pos.piece_on(move_to(move))]
1408 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1410 if (futilityValue < beta)
1412 if (futilityValue > bestValue)
1413 bestValue = futilityValue;
1418 // Prune moves with negative or equal SEE
1419 if ( futilityBase < beta
1420 && depth < DEPTH_ZERO
1421 && pos.see(move) <= 0)
1425 // Detect non-capture evasions that are candidate to be pruned
1426 evasionPrunable = !PvNode
1428 && bestValue > VALUE_MATED_IN_PLY_MAX
1429 && !pos.is_capture(move)
1430 && !pos.can_castle(pos.side_to_move());
1432 // Don't search moves with negative SEE values
1434 && (!inCheck || evasionPrunable)
1436 && !is_promotion(move)
1437 && pos.see_sign(move) < 0)
1440 // Don't search useless checks
1445 && !pos.is_capture_or_promotion(move)
1446 && ss->eval + PawnValueMidgame / 4 < beta
1447 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1449 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1450 bestValue = ss->eval + PawnValueMidgame / 4;
1455 // Check for legality only before to do the move
1456 if (!pos.pl_move_is_legal(move, ci.pinned))
1459 // Update current move
1460 ss->currentMove = move;
1462 // Make and search the move
1463 pos.do_move(move, st, ci, givesCheck);
1464 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1465 pos.undo_move(move);
1467 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1470 if (value > bestValue)
1473 ss->bestMove = move;
1477 && value < beta) // We want always alpha < beta
1482 // All legal moves have been searched. A special case: If we're in check
1483 // and no legal moves were found, it is checkmate.
1484 if (inCheck && bestValue == -VALUE_INFINITE)
1485 return value_mated_in(ss->ply);
1487 // Update transposition table
1488 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1489 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1490 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1492 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1494 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1500 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1501 // bestValue is updated only when returning false because in that case move
1504 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1506 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1507 Square from, to, ksq, victimSq;
1510 Value futilityValue, bv = *bestValue;
1512 from = move_from(move);
1514 them = flip(pos.side_to_move());
1515 ksq = pos.king_square(them);
1516 kingAtt = pos.attacks_from<KING>(ksq);
1517 pc = pos.piece_on(from);
1519 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1520 oldAtt = pos.attacks_from(pc, from, occ);
1521 newAtt = pos.attacks_from(pc, to, occ);
1523 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1524 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1526 if (!(b && (b & (b - 1))))
1529 // Rule 2. Queen contact check is very dangerous
1530 if ( type_of(pc) == QUEEN
1531 && bit_is_set(kingAtt, to))
1534 // Rule 3. Creating new double threats with checks
1535 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1539 victimSq = pop_1st_bit(&b);
1540 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1542 // Note that here we generate illegal "double move"!
1543 if ( futilityValue >= beta
1544 && pos.see_sign(make_move(from, victimSq)) >= 0)
1547 if (futilityValue > bv)
1551 // Update bestValue only if check is not dangerous (because we will prune the move)
1557 // connected_moves() tests whether two moves are 'connected' in the sense
1558 // that the first move somehow made the second move possible (for instance
1559 // if the moving piece is the same in both moves). The first move is assumed
1560 // to be the move that was made to reach the current position, while the
1561 // second move is assumed to be a move from the current position.
1563 bool connected_moves(const Position& pos, Move m1, Move m2) {
1565 Square f1, t1, f2, t2;
1572 // Case 1: The moving piece is the same in both moves
1578 // Case 2: The destination square for m2 was vacated by m1
1584 // Case 3: Moving through the vacated square
1585 p2 = pos.piece_on(f2);
1586 if ( piece_is_slider(p2)
1587 && bit_is_set(squares_between(f2, t2), f1))
1590 // Case 4: The destination square for m2 is defended by the moving piece in m1
1591 p1 = pos.piece_on(t1);
1592 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1595 // Case 5: Discovered check, checking piece is the piece moved in m1
1596 ksq = pos.king_square(pos.side_to_move());
1597 if ( piece_is_slider(p1)
1598 && bit_is_set(squares_between(t1, ksq), f2))
1600 Bitboard occ = pos.occupied_squares();
1601 clear_bit(&occ, f2);
1602 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1609 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1610 // "plies to mate from the current ply". Non-mate scores are unchanged.
1611 // The function is called before storing a value to the transposition table.
1613 Value value_to_tt(Value v, int ply) {
1615 if (v >= VALUE_MATE_IN_PLY_MAX)
1618 if (v <= VALUE_MATED_IN_PLY_MAX)
1625 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1626 // the transposition table to a mate score corrected for the current ply.
1628 Value value_from_tt(Value v, int ply) {
1630 if (v >= VALUE_MATE_IN_PLY_MAX)
1633 if (v <= VALUE_MATED_IN_PLY_MAX)
1640 // connected_threat() tests whether it is safe to forward prune a move or if
1641 // is somehow connected to the threat move returned by null search.
1643 bool connected_threat(const Position& pos, Move m, Move threat) {
1646 assert(is_ok(threat));
1647 assert(!pos.is_capture_or_promotion(m));
1648 assert(!pos.is_passed_pawn_push(m));
1650 Square mfrom, mto, tfrom, tto;
1652 mfrom = move_from(m);
1654 tfrom = move_from(threat);
1655 tto = move_to(threat);
1657 // Case 1: Don't prune moves which move the threatened piece
1661 // Case 2: If the threatened piece has value less than or equal to the
1662 // value of the threatening piece, don't prune moves which defend it.
1663 if ( pos.is_capture(threat)
1664 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1665 || type_of(pos.piece_on(tfrom)) == KING)
1666 && pos.move_attacks_square(m, tto))
1669 // Case 3: If the moving piece in the threatened move is a slider, don't
1670 // prune safe moves which block its ray.
1671 if ( piece_is_slider(pos.piece_on(tfrom))
1672 && bit_is_set(squares_between(tfrom, tto), mto)
1673 && pos.see_sign(m) >= 0)
1680 // can_return_tt() returns true if a transposition table score
1681 // can be used to cut-off at a given point in search.
1683 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1685 Value v = value_from_tt(tte->value(), ply);
1687 return ( tte->depth() >= depth
1688 || v >= std::max(VALUE_MATE_IN_PLY_MAX, beta)
1689 || v < std::min(VALUE_MATED_IN_PLY_MAX, beta))
1691 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1692 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1696 // refine_eval() returns the transposition table score if
1697 // possible otherwise falls back on static position evaluation.
1699 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1703 Value v = value_from_tt(tte->value(), ply);
1705 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1706 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1713 // update_history() registers a good move that produced a beta-cutoff
1714 // in history and marks as failures all the other moves of that ply.
1716 void update_history(const Position& pos, Move move, Depth depth,
1717 Move movesSearched[], int moveCount) {
1719 Value bonus = Value(int(depth) * int(depth));
1721 H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1723 for (int i = 0; i < moveCount - 1; i++)
1725 m = movesSearched[i];
1729 H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1734 // current_search_time() returns the number of milliseconds which have passed
1735 // since the beginning of the current search.
1737 int elapsed_search_time(int set) {
1739 static int searchStartTime;
1742 searchStartTime = set;
1744 return get_system_time() - searchStartTime;
1748 // score_to_uci() converts a value to a string suitable for use with the UCI
1749 // protocol specifications:
1751 // cp <x> The score from the engine's point of view in centipawns.
1752 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1753 // use negative values for y.
1755 string score_to_uci(Value v, Value alpha, Value beta) {
1757 std::stringstream s;
1759 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1760 s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1762 s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1764 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1770 // speed_to_uci() returns a string with time stats of current search suitable
1771 // to be sent to UCI gui.
1773 string speed_to_uci(int64_t nodes) {
1775 std::stringstream s;
1776 int t = elapsed_search_time();
1778 s << " nodes " << nodes
1779 << " nps " << (t > 0 ? int(nodes * 1000 / t) : 0)
1786 // pv_to_uci() returns a string with information on the current PV line
1787 // formatted according to UCI specification.
1789 string pv_to_uci(const Move pv[], int pvNum, bool chess960) {
1791 std::stringstream s;
1793 s << " multipv " << pvNum << " pv " << set960(chess960);
1795 for ( ; *pv != MOVE_NONE; pv++)
1802 // depth_to_uci() returns a string with information on the current depth and
1803 // seldepth formatted according to UCI specification.
1805 string depth_to_uci(Depth depth) {
1807 std::stringstream s;
1809 // Retrieve max searched depth among threads
1811 for (int i = 0; i < Threads.size(); i++)
1812 if (Threads[i].maxPly > selDepth)
1813 selDepth = Threads[i].maxPly;
1815 s << " depth " << depth / ONE_PLY << " seldepth " << selDepth;
1820 string time_to_string(int millisecs) {
1822 const int MSecMinute = 1000 * 60;
1823 const int MSecHour = 1000 * 60 * 60;
1825 int hours = millisecs / MSecHour;
1826 int minutes = (millisecs % MSecHour) / MSecMinute;
1827 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1829 std::stringstream s;
1834 s << std::setfill('0') << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
1838 string score_to_string(Value v) {
1840 std::stringstream s;
1842 if (v >= VALUE_MATE_IN_PLY_MAX)
1843 s << "#" << (VALUE_MATE - v + 1) / 2;
1844 else if (v <= VALUE_MATED_IN_PLY_MAX)
1845 s << "-#" << (VALUE_MATE + v) / 2;
1847 s << std::setprecision(2) << std::fixed << std::showpos << float(v) / PawnValueMidgame;
1853 // pretty_pv() creates a human-readable string from a position and a PV.
1854 // It is used to write search information to the log file (which is created
1855 // when the UCI parameter "Use Search Log" is "true").
1857 string pretty_pv(Position& pos, int depth, Value value, int time, Move pv[]) {
1859 const int64_t K = 1000;
1860 const int64_t M = 1000000;
1861 const int startColumn = 28;
1862 const size_t maxLength = 80 - startColumn;
1864 StateInfo state[PLY_MAX_PLUS_2], *st = state;
1867 std::stringstream s;
1870 // First print depth, score, time and searched nodes...
1871 s << set960(pos.is_chess960())
1872 << std::setw(2) << depth
1873 << std::setw(8) << score_to_string(value)
1874 << std::setw(8) << time_to_string(time);
1876 if (pos.nodes_searched() < M)
1877 s << std::setw(8) << pos.nodes_searched() / 1 << " ";
1878 else if (pos.nodes_searched() < K * M)
1879 s << std::setw(7) << pos.nodes_searched() / K << "K ";
1881 s << std::setw(7) << pos.nodes_searched() / M << "M ";
1883 // ...then print the full PV line in short algebraic notation
1884 while (*m != MOVE_NONE)
1886 san = move_to_san(pos, *m);
1887 length += san.length() + 1;
1889 if (length > maxLength)
1891 length = san.length() + 1;
1892 s << "\n" + string(startColumn, ' ');
1896 pos.do_move(*m++, *st++);
1899 // Restore original position before to leave
1900 while (m != pv) pos.undo_move(*--m);
1906 // When playing with strength handicap choose best move among the MultiPV set
1907 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1909 void do_skill_level(Move* best, Move* ponder) {
1911 assert(MultiPV > 1);
1915 // Rml list is already sorted by score in descending order
1917 int max_s = -VALUE_INFINITE;
1918 int size = std::min(MultiPV, (int)Rml.size());
1919 int max = Rml[0].score;
1920 int var = std::min(max - Rml[size - 1].score, int(PawnValueMidgame));
1921 int wk = 120 - 2 * SkillLevel;
1923 // PRNG sequence should be non deterministic
1924 for (int i = abs(get_system_time() % 50); i > 0; i--)
1925 rk.rand<unsigned>();
1927 // Choose best move. For each move's score we add two terms both dependent
1928 // on wk, one deterministic and bigger for weaker moves, and one random,
1929 // then we choose the move with the resulting highest score.
1930 for (int i = 0; i < size; i++)
1934 // Don't allow crazy blunders even at very low skills
1935 if (i > 0 && Rml[i-1].score > s + EasyMoveMargin)
1938 // This is our magical formula
1939 s += ((max - s) * wk + var * (rk.rand<unsigned>() % wk)) / 128;
1944 *best = Rml[i].pv[0];
1945 *ponder = Rml[i].pv[1];
1951 /// RootMove and RootMoveList method's definitions
1953 void RootMoveList::init(Position& pos, Move rootMoves[]) {
1956 bestMoveChanges = 0;
1959 // Generate all legal moves and add them to RootMoveList
1960 for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
1962 // If we have a rootMoves[] list then verify the move
1963 // is in the list before to add it.
1964 for (sm = rootMoves; *sm && *sm != ml.move(); sm++) {}
1966 if (sm != rootMoves && *sm != ml.move())
1970 rm.pv.push_back(ml.move());
1971 rm.pv.push_back(MOVE_NONE);
1972 rm.score = rm.prevScore = -VALUE_INFINITE;
1978 RootMove* RootMoveList::find(const Move& m, int startIndex) {
1980 for (size_t i = startIndex; i < size(); i++)
1981 if ((*this)[i].pv[0] == m)
1988 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1989 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1990 // allow to always have a ponder move even when we fail high at root and also a
1991 // long PV to print that is important for position analysis.
1993 void RootMove::extract_pv_from_tt(Position& pos) {
1995 StateInfo state[PLY_MAX_PLUS_2], *st = state;
2000 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
2004 pos.do_move(m, *st++);
2006 while ( (tte = TT.probe(pos.get_key())) != NULL
2007 && tte->move() != MOVE_NONE
2008 && pos.is_pseudo_legal(tte->move())
2009 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
2011 && (!pos.is_draw<false>() || ply < 2))
2013 pv.push_back(tte->move());
2014 pos.do_move(tte->move(), *st++);
2017 pv.push_back(MOVE_NONE);
2019 do pos.undo_move(pv[--ply]); while (ply);
2023 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2024 // the PV back into the TT. This makes sure the old PV moves are searched
2025 // first, even if the old TT entries have been overwritten.
2027 void RootMove::insert_pv_in_tt(Position& pos) {
2029 StateInfo state[PLY_MAX_PLUS_2], *st = state;
2032 Value v, m = VALUE_NONE;
2035 assert(pv[0] != MOVE_NONE && pos.is_pseudo_legal(pv[0]));
2041 // Don't overwrite existing correct entries
2042 if (!tte || tte->move() != pv[ply])
2044 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
2045 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2047 pos.do_move(pv[ply], *st++);
2049 } while (pv[++ply] != MOVE_NONE);
2051 do pos.undo_move(pv[--ply]); while (ply);
2057 // Thread::idle_loop() is where the thread is parked when it has no work to do.
2058 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
2059 // for which the thread is the master.
2061 void Thread::idle_loop(SplitPoint* sp) {
2065 // If we are not searching, wait for a condition to be signaled
2066 // instead of wasting CPU time polling for work.
2069 || (Threads.use_sleeping_threads() && !is_searching))
2071 assert((!sp && threadID) || Threads.use_sleeping_threads());
2073 // Slave thread should exit as soon as do_terminate flag raises
2080 // Grab the lock to avoid races with Thread::wake_up()
2081 lock_grab(&sleepLock);
2083 // If we are master and all slaves have finished don't go to sleep
2084 if (sp && Threads.split_point_finished(sp))
2086 lock_release(&sleepLock);
2090 // Do sleep after retesting sleep conditions under lock protection, in
2091 // particular we need to avoid a deadlock in case a master thread has,
2092 // in the meanwhile, allocated us and sent the wake_up() call before we
2093 // had the chance to grab the lock.
2094 if (do_sleep || !is_searching)
2095 cond_wait(&sleepCond, &sleepLock);
2097 lock_release(&sleepLock);
2100 // If this thread has been assigned work, launch a search
2103 assert(!do_terminate);
2105 // Copy split point position and search stack and call search()
2106 SearchStack ss[PLY_MAX_PLUS_2];
2107 SplitPoint* tsp = splitPoint;
2108 Position pos(*tsp->pos, threadID);
2110 memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2113 if (tsp->nodeType == Root)
2114 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2115 else if (tsp->nodeType == PV)
2116 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2117 else if (tsp->nodeType == NonPV)
2118 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2122 assert(is_searching);
2124 is_searching = false;
2126 // Wake up master thread so to allow it to return from the idle loop in
2127 // case we are the last slave of the split point.
2128 if ( Threads.use_sleeping_threads()
2129 && threadID != tsp->master
2130 && !Threads[tsp->master].is_searching)
2131 Threads[tsp->master].wake_up();
2134 // If this thread is the master of a split point and all slaves have
2135 // finished their work at this split point, return from the idle loop.
2136 if (sp && Threads.split_point_finished(sp))
2138 // Because sp->is_slave[] is reset under lock protection,
2139 // be sure sp->lock has been released before to return.
2140 lock_grab(&(sp->lock));
2141 lock_release(&(sp->lock));
2148 // do_timer_event() is called by the timer thread when the timer triggers
2150 void do_timer_event() {
2152 static int lastInfoTime;
2153 int e = elapsed_search_time();
2155 // Print debug information every one second
2156 if (!lastInfoTime || get_system_time() - lastInfoTime >= 1000)
2158 lastInfoTime = get_system_time();
2161 dbg_print_hit_rate();
2164 // Should we stop the search?
2168 bool stillAtFirstMove = Signals.firstRootMove
2169 && !Signals.failedLowAtRoot
2170 && e > TimeMgr.available_time();
2172 bool noMoreTime = e > TimeMgr.maximum_time()
2173 || stillAtFirstMove;
2175 if ( (Limits.useTimeManagement() && noMoreTime)
2176 || (Limits.maxTime && e >= Limits.maxTime)
2177 /* missing nodes limit */ ) // FIXME
2178 Signals.stop = true;