2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
39 #include "ucioption.h"
47 // Set to true to force running with one thread. Used for debugging
48 const bool FakeSplit = false;
50 // Different node types, used as template parameter
51 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
53 // RootMove struct is used for moves at the root of the tree. For each root
54 // move, we store a score, a node count, and a PV (really a refutation
55 // in the case of moves which fail low). Score is normally set at
56 // -VALUE_INFINITE for all non-pv moves.
59 // RootMove::operator<() is the comparison function used when
60 // sorting the moves. A move m1 is considered to be better
61 // than a move m2 if it has an higher score
62 bool operator<(const RootMove& m) const { return score < m.score; }
64 void extract_pv_from_tt(Position& pos);
65 void insert_pv_in_tt(Position& pos);
73 // RootMoveList struct is mainly a std::vector of RootMove objects
74 struct RootMoveList : public std::vector<RootMove> {
76 void init(Position& pos, Move searchMoves[]);
77 RootMove* find(const Move& m, int startIndex = 0);
85 // Lookup table to check if a Piece is a slider and its access function
86 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
87 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
91 // Maximum depth for razoring
92 const Depth RazorDepth = 4 * ONE_PLY;
94 // Dynamic razoring margin based on depth
95 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
97 // Maximum depth for use of dynamic threat detection when null move fails low
98 const Depth ThreatDepth = 5 * ONE_PLY;
100 // Step 9. Internal iterative deepening
102 // Minimum depth for use of internal iterative deepening
103 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
105 // At Non-PV nodes we do an internal iterative deepening search
106 // when the static evaluation is bigger then beta - IIDMargin.
107 const Value IIDMargin = Value(0x100);
109 // Step 11. Decide the new search depth
111 // Extensions. Array index 0 is used for non-PV nodes, index 1 for PV nodes
112 const Depth CheckExtension[] = { ONE_PLY / 2, ONE_PLY / 1 };
113 const Depth PawnEndgameExtension[] = { ONE_PLY / 1, ONE_PLY / 1 };
114 const Depth PawnPushTo7thExtension[] = { ONE_PLY / 2, ONE_PLY / 2 };
115 const Depth PassedPawnExtension[] = { DEPTH_ZERO, ONE_PLY / 2 };
117 // Minimum depth for use of singular extension
118 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
120 // Step 12. Futility pruning
122 // Futility margin for quiescence search
123 const Value FutilityMarginQS = Value(0x80);
125 // Futility lookup tables (initialized at startup) and their access functions
126 Value FutilityMargins[16][64]; // [depth][moveNumber]
127 int FutilityMoveCounts[32]; // [depth]
129 inline Value futility_margin(Depth d, int mn) {
131 return d < 7 * ONE_PLY ? FutilityMargins[Max(d, 1)][Min(mn, 63)]
132 : 2 * VALUE_INFINITE;
135 inline int futility_move_count(Depth d) {
137 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
140 // Step 14. Reduced search
142 // Reduction lookup tables (initialized at startup) and their access function
143 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
145 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
147 return (Depth) Reductions[PvNode][Min(d / ONE_PLY, 63)][Min(mn, 63)];
150 // Easy move margin. An easy move candidate must be at least this much
151 // better than the second best move.
152 const Value EasyMoveMargin = Value(0x200);
155 /// Namespace variables
161 int MultiPV, UCIMultiPV, MultiPVIdx;
163 // Time management variables
164 bool StopOnPonderhit, FirstRootMove, StopRequest, QuitRequest, AspirationFailLow;
168 // Skill level adjustment
170 bool SkillLevelEnabled;
172 // Node counters, used only by thread[0] but try to keep in different cache
173 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
175 int NodesBetweenPolls = 30000;
183 Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove);
185 template <NodeType NT>
186 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
188 template <NodeType NT>
189 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
191 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
192 bool connected_moves(const Position& pos, Move m1, Move m2);
193 Value value_to_tt(Value v, int ply);
194 Value value_from_tt(Value v, int ply);
195 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
196 bool connected_threat(const Position& pos, Move m, Move threat);
197 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
198 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
199 void do_skill_level(Move* best, Move* ponder);
201 int current_search_time(int set = 0);
202 string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
203 string speed_to_uci(int64_t nodes);
204 string pv_to_uci(const Move pv[], int pvNum, bool chess960);
205 string pretty_pv(Position& pos, int depth, Value score, int time, Move pv[]);
206 string depth_to_uci(Depth depth);
207 void poll(const Position& pos);
208 void wait_for_stop_or_ponderhit();
210 // MovePickerExt template class extends MovePicker and allows to choose at compile
211 // time the proper moves source according to the type of node. In the default case
212 // we simply create and use a standard MovePicker object.
213 template<bool SpNode> struct MovePickerExt : public MovePicker {
215 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
216 : MovePicker(p, ttm, d, h, ss, b) {}
219 // In case of a SpNode we use split point's shared MovePicker object as moves source
220 template<> struct MovePickerExt<true> : public MovePicker {
222 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
223 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
225 Move get_next_move() { return mp->get_next_move(); }
229 // Overload operator<<() to make it easier to print moves in a coordinate
230 // notation compatible with UCI protocol.
231 std::ostream& operator<<(std::ostream& os, Move m) {
233 bool chess960 = (os.iword(0) != 0); // See set960()
234 return os << move_to_uci(m, chess960);
237 // When formatting a move for std::cout we must know if we are in Chess960
238 // or not. To keep using the handy operator<<() on the move the trick is to
239 // embed this flag in the stream itself. Function-like named enum set960 is
240 // used as a custom manipulator and the stream internal general-purpose array,
241 // accessed through ios_base::iword(), is used to pass the flag to the move's
242 // operator<<() that will read it to properly format castling moves.
245 std::ostream& operator<< (std::ostream& os, const set960& f) {
247 os.iword(0) = int(f);
251 // extension() decides whether a move should be searched with normal depth,
252 // or with extended depth. Certain classes of moves (checking moves, in
253 // particular) are searched with bigger depth than ordinary moves and in
254 // any case are marked as 'dangerous'. Note that also if a move is not
255 // extended, as example because the corresponding UCI option is set to zero,
256 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
257 template <bool PvNode>
258 FORCE_INLINE Depth extension(const Position& pos, Move m, bool captureOrPromotion,
259 bool moveIsCheck, bool* dangerous) {
260 assert(m != MOVE_NONE);
262 Depth result = DEPTH_ZERO;
263 *dangerous = moveIsCheck;
265 if (moveIsCheck && pos.see_sign(m) >= 0)
266 result += CheckExtension[PvNode];
268 if (type_of(pos.piece_on(move_from(m))) == PAWN)
270 Color c = pos.side_to_move();
271 if (relative_rank(c, move_to(m)) == RANK_7)
273 result += PawnPushTo7thExtension[PvNode];
276 if (pos.pawn_is_passed(c, move_to(m)))
278 result += PassedPawnExtension[PvNode];
283 if ( captureOrPromotion
284 && type_of(pos.piece_on(move_to(m))) != PAWN
285 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
286 - PieceValueMidgame[pos.piece_on(move_to(m))] == VALUE_ZERO)
289 result += PawnEndgameExtension[PvNode];
293 return Min(result, ONE_PLY);
299 /// init_search() is called during startup to initialize various lookup tables
303 int d; // depth (ONE_PLY == 2)
304 int hd; // half depth (ONE_PLY == 1)
307 // Init reductions array
308 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
310 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
311 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
312 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
313 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
316 // Init futility margins array
317 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
318 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
320 // Init futility move count array
321 for (d = 0; d < 32; d++)
322 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
326 /// perft() is our utility to verify move generation. All the leaf nodes up to
327 /// the given depth are generated and counted and the sum returned.
329 int64_t perft(Position& pos, Depth depth) {
334 // Generate all legal moves
335 MoveList<MV_LEGAL> ml(pos);
337 // If we are at the last ply we don't need to do and undo
338 // the moves, just to count them.
339 if (depth <= ONE_PLY)
342 // Loop through all legal moves
344 for ( ; !ml.end(); ++ml)
346 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
347 sum += perft(pos, depth - ONE_PLY);
348 pos.undo_move(ml.move());
354 /// think() is the external interface to Stockfish's search, and is called when
355 /// the program receives the UCI 'go' command. It initializes various global
356 /// variables, and calls id_loop(). It returns false when a "quit" command is
357 /// received during the search.
359 bool think(Position& pos, const SearchLimits& limits, Move searchMoves[]) {
361 static Book book; // Define static to initialize the PRNG only once
363 // Initialize global search-related variables
364 StopOnPonderhit = StopRequest = QuitRequest = AspirationFailLow = false;
366 current_search_time(get_system_time());
368 TimeMgr.init(Limits, pos.startpos_ply_counter());
370 // Set output steram in normal or chess960 mode
371 cout << set960(pos.is_chess960());
373 // Set best NodesBetweenPolls interval to avoid lagging under time pressure
375 NodesBetweenPolls = Min(Limits.maxNodes, 30000);
376 else if (Limits.time && Limits.time < 1000)
377 NodesBetweenPolls = 1000;
378 else if (Limits.time && Limits.time < 5000)
379 NodesBetweenPolls = 5000;
381 NodesBetweenPolls = 30000;
383 // Look for a book move
384 if (Options["OwnBook"].value<bool>())
386 if (Options["Book File"].value<string>() != book.name())
387 book.open(Options["Book File"].value<string>());
389 Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
390 if (bookMove != MOVE_NONE)
393 wait_for_stop_or_ponderhit();
395 cout << "bestmove " << bookMove << endl;
401 UCIMultiPV = Options["MultiPV"].value<int>();
402 SkillLevel = Options["Skill Level"].value<int>();
404 read_evaluation_uci_options(pos.side_to_move());
405 Threads.read_uci_options();
407 // Set a new TT size if changed
408 TT.set_size(Options["Hash"].value<int>());
410 if (Options["Clear Hash"].value<bool>())
412 Options["Clear Hash"].set_value("false");
416 // Do we have to play with skill handicap? In this case enable MultiPV that
417 // we will use behind the scenes to retrieve a set of possible moves.
418 SkillLevelEnabled = (SkillLevel < 20);
419 MultiPV = (SkillLevelEnabled ? Max(UCIMultiPV, 4) : UCIMultiPV);
421 // Wake up needed threads and reset maxPly counter
422 for (int i = 0; i < Threads.size(); i++)
424 Threads[i].wake_up();
425 Threads[i].maxPly = 0;
428 // Write to log file and keep it open to be accessed during the search
429 if (Options["Use Search Log"].value<bool>())
431 Log log(Options["Search Log Filename"].value<string>());
432 log << "\nSearching: " << pos.to_fen()
433 << "\ninfinite: " << Limits.infinite
434 << " ponder: " << Limits.ponder
435 << " time: " << Limits.time
436 << " increment: " << Limits.increment
437 << " moves to go: " << Limits.movesToGo
441 // We're ready to start thinking. Call the iterative deepening loop function
442 Move ponderMove = MOVE_NONE;
443 Move bestMove = id_loop(pos, searchMoves, &ponderMove);
445 // Write final search statistics and close log file
446 if (Options["Use Search Log"].value<bool>())
448 int t = current_search_time();
450 Log log(Options["Search Log Filename"].value<string>());
451 log << "Nodes: " << pos.nodes_searched()
452 << "\nNodes/second: " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
453 << "\nBest move: " << move_to_san(pos, bestMove);
456 pos.do_move(bestMove, st);
457 log << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
458 pos.undo_move(bestMove); // Return from think() with unchanged position
461 // This makes all the threads to go to sleep
464 // If we are pondering or in infinite search, we shouldn't print the
465 // best move before we are told to do so.
466 if (!StopRequest && (Limits.ponder || Limits.infinite))
467 wait_for_stop_or_ponderhit();
469 // Could be MOVE_NONE when searching on a stalemate position
470 cout << "bestmove " << bestMove;
472 // UCI protol is not clear on allowing sending an empty ponder move, instead
473 // it is clear that ponder move is optional. So skip it if empty.
474 if (ponderMove != MOVE_NONE)
475 cout << " ponder " << ponderMove;
485 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
486 // with increasing depth until the allocated thinking time has been consumed,
487 // user stops the search, or the maximum search depth is reached.
489 Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove) {
491 SearchStack ss[PLY_MAX_PLUS_2];
492 Value bestValues[PLY_MAX_PLUS_2];
493 int bestMoveChanges[PLY_MAX_PLUS_2];
494 int depth, aspirationDelta;
495 Value value, alpha, beta;
496 Move bestMove, easyMove, skillBest, skillPonder;
498 // Initialize stuff before a new search
499 memset(ss, 0, 4 * sizeof(SearchStack));
502 *ponderMove = bestMove = easyMove = skillBest = skillPonder = MOVE_NONE;
503 depth = aspirationDelta = 0;
504 value = alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
505 ss->currentMove = MOVE_NULL; // Hack to skip update gains
507 // Moves to search are verified and copied
508 Rml.init(pos, searchMoves);
510 // Handle special case of searching on a mate/stalemate position
513 cout << "info" << depth_to_uci(DEPTH_ZERO)
514 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW, alpha, beta) << endl;
519 // Iterative deepening loop until requested to stop or target depth reached
520 while (!StopRequest && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
522 // Save now last iteration's scores, before Rml moves are reordered
523 for (size_t i = 0; i < Rml.size(); i++)
524 Rml[i].prevScore = Rml[i].score;
526 Rml.bestMoveChanges = 0;
528 // MultiPV loop. We perform a full root search for each PV line
529 for (MultiPVIdx = 0; MultiPVIdx < Min(MultiPV, (int)Rml.size()); MultiPVIdx++)
531 // Calculate dynamic aspiration window based on previous iterations
532 if (depth >= 5 && abs(Rml[MultiPVIdx].prevScore) < VALUE_KNOWN_WIN)
534 int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
535 int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
537 aspirationDelta = Min(Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
538 aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
540 alpha = Max(Rml[MultiPVIdx].prevScore - aspirationDelta, -VALUE_INFINITE);
541 beta = Min(Rml[MultiPVIdx].prevScore + aspirationDelta, VALUE_INFINITE);
545 alpha = -VALUE_INFINITE;
546 beta = VALUE_INFINITE;
549 // Start with a small aspiration window and, in case of fail high/low,
550 // research with bigger window until not failing high/low anymore.
552 // Search starts from ss+1 to allow referencing (ss-1). This is
553 // needed by update gains and ss copy when splitting at Root.
554 value = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
556 // Bring to front the best move. It is critical that sorting is
557 // done with a stable algorithm because all the values but the first
558 // and eventually the new best one are set to -VALUE_INFINITE and
559 // we want to keep the same order for all the moves but the new
560 // PV that goes to the front. Note that in case of MultiPV search
561 // the already searched PV lines are preserved.
562 sort<RootMove>(Rml.begin() + MultiPVIdx, Rml.end());
564 // In case we have found an exact score and we are going to leave
565 // the fail high/low loop then reorder the PV moves, otherwise
566 // leave the last PV move in its position so to be searched again.
567 // Of course this is needed only in MultiPV search.
568 if (MultiPVIdx && value > alpha && value < beta)
569 sort<RootMove>(Rml.begin(), Rml.begin() + MultiPVIdx);
571 // Write PV back to transposition table in case the relevant entries
572 // have been overwritten during the search.
573 for (int i = 0; i <= MultiPVIdx; i++)
574 Rml[i].insert_pv_in_tt(pos);
576 // If search has been stopped exit the aspiration window loop,
577 // note that sorting and writing PV back to TT is safe becuase
578 // Rml is still valid, although refers to the previous iteration.
582 // Send full PV info to GUI if we are going to leave the loop or
583 // if we have a fail high/low and we are deep in the search. UCI
584 // protocol requires to send all the PV lines also if are still
585 // to be searched and so refer to the previous search's score.
586 if ((value > alpha && value < beta) || current_search_time() > 2000)
587 for (int i = 0; i < Min(UCIMultiPV, (int)Rml.size()); i++)
589 bool updated = (i <= MultiPVIdx);
591 if (depth == 1 && !updated)
594 Depth d = (updated ? depth : depth - 1) * ONE_PLY;
595 Value s = (updated ? Rml[i].score : Rml[i].prevScore);
599 << (i == MultiPVIdx ? score_to_uci(s, alpha, beta) : score_to_uci(s))
600 << speed_to_uci(pos.nodes_searched())
601 << pv_to_uci(&Rml[i].pv[0], i + 1, pos.is_chess960())
605 // In case of failing high/low increase aspiration window and
606 // research, otherwise exit the fail high/low loop.
609 beta = Min(beta + aspirationDelta, VALUE_INFINITE);
610 aspirationDelta += aspirationDelta / 2;
612 else if (value <= alpha)
614 AspirationFailLow = true;
615 StopOnPonderhit = false;
617 alpha = Max(alpha - aspirationDelta, -VALUE_INFINITE);
618 aspirationDelta += aspirationDelta / 2;
623 } while (abs(value) < VALUE_KNOWN_WIN);
626 // Collect info about search result
627 bestMove = Rml[0].pv[0];
628 *ponderMove = Rml[0].pv[1];
629 bestValues[depth] = value;
630 bestMoveChanges[depth] = Rml.bestMoveChanges;
632 // Skills: Do we need to pick now the best and the ponder moves ?
633 if (SkillLevelEnabled && depth == 1 + SkillLevel)
634 do_skill_level(&skillBest, &skillPonder);
636 if (Options["Use Search Log"].value<bool>())
638 Log log(Options["Search Log Filename"].value<string>());
639 log << pretty_pv(pos, depth, value, current_search_time(), &Rml[0].pv[0]) << endl;
642 // Init easyMove at first iteration or drop it if differs from the best move
643 if (depth == 1 && (Rml.size() == 1 || Rml[0].score > Rml[1].score + EasyMoveMargin))
645 else if (bestMove != easyMove)
646 easyMove = MOVE_NONE;
648 // Check for some early stop condition
649 if (!StopRequest && Limits.useTimeManagement())
651 // Easy move: Stop search early if one move seems to be much better
652 // than the others or if there is only a single legal move. Also in
653 // the latter case search to some depth anyway to get a proper score.
655 && easyMove == bestMove
657 ||( Rml[0].nodes > (pos.nodes_searched() * 85) / 100
658 && current_search_time() > TimeMgr.available_time() / 16)
659 ||( Rml[0].nodes > (pos.nodes_searched() * 98) / 100
660 && current_search_time() > TimeMgr.available_time() / 32)))
663 // Take in account some extra time if the best move has changed
664 if (depth > 4 && depth < 50)
665 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
667 // Stop search if most of available time is already consumed. We probably don't
668 // have enough time to search the first move at the next iteration anyway.
669 if (current_search_time() > (TimeMgr.available_time() * 62) / 100)
672 // If we are allowed to ponder do not stop the search now but keep pondering
673 if (StopRequest && Limits.ponder)
676 StopOnPonderhit = true;
681 // When using skills overwrite best and ponder moves with the sub-optimal ones
682 if (SkillLevelEnabled)
684 if (skillBest == MOVE_NONE) // Still unassigned ?
685 do_skill_level(&skillBest, &skillPonder);
687 bestMove = skillBest;
688 *ponderMove = skillPonder;
695 // search<>() is the main search function for both PV and non-PV nodes and for
696 // normal and SplitPoint nodes. When called just after a split point the search
697 // is simpler because we have already probed the hash table, done a null move
698 // search, and searched the first move before splitting, we don't have to repeat
699 // all this work again. We also don't need to store anything to the hash table
700 // here: This is taken care of after we return from the split point.
702 template <NodeType NT>
703 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
705 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
706 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
707 const bool RootNode = (NT == Root || NT == SplitPointRoot);
709 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
710 assert(beta > alpha && beta <= VALUE_INFINITE);
711 assert(PvNode || alpha == beta - 1);
712 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
714 Move movesSearched[MAX_MOVES];
719 Move ttMove, move, excludedMove, threatMove;
722 Value bestValue, value, oldAlpha;
723 Value refinedValue, nullValue, futilityBase, futilityValue;
724 bool isPvMove, inCheck, singularExtensionNode, givesCheck, captureOrPromotion, dangerous;
725 int moveCount = 0, playedMoveCount = 0;
726 Thread& thread = Threads[pos.thread()];
727 SplitPoint* sp = NULL;
729 refinedValue = bestValue = value = -VALUE_INFINITE;
731 inCheck = pos.in_check();
732 ss->ply = (ss-1)->ply + 1;
734 // Used to send selDepth info to GUI
735 if (PvNode && thread.maxPly < ss->ply)
736 thread.maxPly = ss->ply;
738 // Step 1. Initialize node and poll. Polling can abort search
741 ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
742 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
743 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
749 ttMove = excludedMove = MOVE_NONE;
750 threatMove = sp->threatMove;
751 goto split_point_start;
754 if (pos.thread() == 0 && ++NodesSincePoll > NodesBetweenPolls)
760 // Step 2. Check for aborted search and immediate draw
762 || pos.is_draw<false>()
763 || ss->ply > PLY_MAX) && !RootNode)
766 // Step 3. Mate distance pruning
769 alpha = Max(value_mated_in(ss->ply), alpha);
770 beta = Min(value_mate_in(ss->ply+1), beta);
775 // Step 4. Transposition table lookup
776 // We don't want the score of a partial search to overwrite a previous full search
777 // TT value, so we use a different position key in case of an excluded move.
778 excludedMove = ss->excludedMove;
779 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
780 tte = TT.probe(posKey);
781 ttMove = RootNode ? Rml[MultiPVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
783 // At PV nodes we check for exact scores, while at non-PV nodes we check for
784 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
785 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
786 // we should also update RootMoveList to avoid bogus output.
787 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
788 : can_return_tt(tte, depth, beta, ss->ply)))
791 ss->bestMove = move = ttMove; // Can be MOVE_NONE
792 value = value_from_tt(tte->value(), ss->ply);
796 && !pos.is_capture_or_promotion(move)
797 && move != ss->killers[0])
799 ss->killers[1] = ss->killers[0];
800 ss->killers[0] = move;
805 // Step 5. Evaluate the position statically and update parent's gain statistics
807 ss->eval = ss->evalMargin = VALUE_NONE;
810 assert(tte->static_value() != VALUE_NONE);
812 ss->eval = tte->static_value();
813 ss->evalMargin = tte->static_value_margin();
814 refinedValue = refine_eval(tte, ss->eval, ss->ply);
818 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
819 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
822 // Update gain for the parent non-capture move given the static position
823 // evaluation before and after the move.
824 if ( (move = (ss-1)->currentMove) != MOVE_NULL
825 && (ss-1)->eval != VALUE_NONE
826 && ss->eval != VALUE_NONE
827 && pos.captured_piece_type() == PIECE_TYPE_NONE
828 && !is_special(move))
830 Square to = move_to(move);
831 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
834 // Step 6. Razoring (is omitted in PV nodes)
836 && depth < RazorDepth
838 && refinedValue + razor_margin(depth) < beta
839 && ttMove == MOVE_NONE
840 && abs(beta) < VALUE_MATE_IN_PLY_MAX
841 && !pos.has_pawn_on_7th(pos.side_to_move()))
843 Value rbeta = beta - razor_margin(depth);
844 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
846 // Logically we should return (v + razor_margin(depth)), but
847 // surprisingly this did slightly weaker in tests.
851 // Step 7. Static null move pruning (is omitted in PV nodes)
852 // We're betting that the opponent doesn't have a move that will reduce
853 // the score by more than futility_margin(depth) if we do a null move.
856 && depth < RazorDepth
858 && refinedValue - futility_margin(depth, 0) >= beta
859 && abs(beta) < VALUE_MATE_IN_PLY_MAX
860 && pos.non_pawn_material(pos.side_to_move()))
861 return refinedValue - futility_margin(depth, 0);
863 // Step 8. Null move search with verification search (is omitted in PV nodes)
868 && refinedValue >= beta
869 && abs(beta) < VALUE_MATE_IN_PLY_MAX
870 && pos.non_pawn_material(pos.side_to_move()))
872 ss->currentMove = MOVE_NULL;
874 // Null move dynamic reduction based on depth
875 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
877 // Null move dynamic reduction based on value
878 if (refinedValue - PawnValueMidgame > beta)
881 pos.do_null_move<true>(st);
882 (ss+1)->skipNullMove = true;
883 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
884 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
885 (ss+1)->skipNullMove = false;
886 pos.do_null_move<false>(st);
888 if (nullValue >= beta)
890 // Do not return unproven mate scores
891 if (nullValue >= VALUE_MATE_IN_PLY_MAX)
894 if (depth < 6 * ONE_PLY)
897 // Do verification search at high depths
898 ss->skipNullMove = true;
899 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
900 ss->skipNullMove = false;
907 // The null move failed low, which means that we may be faced with
908 // some kind of threat. If the previous move was reduced, check if
909 // the move that refuted the null move was somehow connected to the
910 // move which was reduced. If a connection is found, return a fail
911 // low score (which will cause the reduced move to fail high in the
912 // parent node, which will trigger a re-search with full depth).
913 threatMove = (ss+1)->bestMove;
915 if ( depth < ThreatDepth
917 && threatMove != MOVE_NONE
918 && connected_moves(pos, (ss-1)->currentMove, threatMove))
923 // Step 9. ProbCut (is omitted in PV nodes)
924 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
925 // and a reduced search returns a value much above beta, we can (almost) safely
926 // prune the previous move.
928 && depth >= RazorDepth + ONE_PLY
931 && excludedMove == MOVE_NONE
932 && abs(beta) < VALUE_MATE_IN_PLY_MAX)
934 Value rbeta = beta + 200;
935 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
937 assert(rdepth >= ONE_PLY);
939 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
942 while ((move = mp.get_next_move()) != MOVE_NONE)
943 if (pos.pl_move_is_legal(move, ci.pinned))
945 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
946 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
953 // Step 10. Internal iterative deepening
954 if ( depth >= IIDDepth[PvNode]
955 && ttMove == MOVE_NONE
956 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
958 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
960 ss->skipNullMove = true;
961 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
962 ss->skipNullMove = false;
964 tte = TT.probe(posKey);
965 ttMove = tte ? tte->move() : MOVE_NONE;
968 split_point_start: // At split points actual search starts from here
970 // Initialize a MovePicker object for the current position
971 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
973 ss->bestMove = MOVE_NONE;
974 futilityBase = ss->eval + ss->evalMargin;
975 singularExtensionNode = !RootNode
977 && depth >= SingularExtensionDepth[PvNode]
978 && ttMove != MOVE_NONE
979 && !excludedMove // Do not allow recursive singular extension search
980 && (tte->type() & VALUE_TYPE_LOWER)
981 && tte->depth() >= depth - 3 * ONE_PLY;
984 lock_grab(&(sp->lock));
985 bestValue = sp->bestValue;
988 // Step 11. Loop through moves
989 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
990 while ( bestValue < beta
991 && (move = mp.get_next_move()) != MOVE_NONE
992 && !thread.cutoff_occurred())
996 if (move == excludedMove)
999 // At root obey the "searchmoves" option and skip moves not listed in Root
1000 // Move List, as a consequence any illegal move is also skipped. In MultiPV
1001 // mode we also skip PV moves which have been already searched.
1002 if (RootNode && !Rml.find(move, MultiPVIdx))
1005 // At PV and SpNode nodes we want all moves to be legal since the beginning
1006 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
1011 moveCount = ++sp->moveCount;
1012 lock_release(&(sp->lock));
1019 // This is used by time management
1020 FirstRootMove = (moveCount == 1);
1022 // Save the current node count before the move is searched
1023 nodes = pos.nodes_searched();
1025 // For long searches send current move info to GUI
1026 if (pos.thread() == 0 && current_search_time() > 2000)
1027 cout << "info" << depth_to_uci(depth)
1028 << " currmove " << move
1029 << " currmovenumber " << moveCount + MultiPVIdx << endl;
1032 // At Root and at first iteration do a PV search on all the moves to score root moves
1033 isPvMove = (PvNode && moveCount <= (RootNode && depth <= ONE_PLY ? MAX_MOVES : 1));
1034 givesCheck = pos.move_gives_check(move, ci);
1035 captureOrPromotion = pos.is_capture_or_promotion(move);
1037 // Step 12. Decide the new search depth
1038 ext = extension<PvNode>(pos, move, captureOrPromotion, givesCheck, &dangerous);
1040 // Singular extension search. If all moves but one fail low on a search of
1041 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
1042 // is singular and should be extended. To verify this we do a reduced search
1043 // on all the other moves but the ttMove, if result is lower than ttValue minus
1044 // a margin then we extend ttMove.
1045 if ( singularExtensionNode
1047 && pos.pl_move_is_legal(move, ci.pinned)
1050 Value ttValue = value_from_tt(tte->value(), ss->ply);
1052 if (abs(ttValue) < VALUE_KNOWN_WIN)
1054 Value rBeta = ttValue - int(depth);
1055 ss->excludedMove = move;
1056 ss->skipNullMove = true;
1057 Value v = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1058 ss->skipNullMove = false;
1059 ss->excludedMove = MOVE_NONE;
1060 ss->bestMove = MOVE_NONE;
1066 // Update current move (this must be done after singular extension search)
1067 newDepth = depth - ONE_PLY + ext;
1069 // Step 13. Futility pruning (is omitted in PV nodes)
1071 && !captureOrPromotion
1075 && !is_castle(move))
1077 // Move count based pruning
1078 if ( moveCount >= futility_move_count(depth)
1079 && (!threatMove || !connected_threat(pos, move, threatMove))
1080 && bestValue > VALUE_MATED_IN_PLY_MAX) // FIXME bestValue is racy
1083 lock_grab(&(sp->lock));
1088 // Value based pruning
1089 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1090 // but fixing this made program slightly weaker.
1091 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
1092 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
1093 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1095 if (futilityValue < beta)
1099 lock_grab(&(sp->lock));
1100 if (futilityValue > sp->bestValue)
1101 sp->bestValue = bestValue = futilityValue;
1103 else if (futilityValue > bestValue)
1104 bestValue = futilityValue;
1109 // Prune moves with negative SEE at low depths
1110 if ( predictedDepth < 2 * ONE_PLY
1111 && bestValue > VALUE_MATED_IN_PLY_MAX
1112 && pos.see_sign(move) < 0)
1115 lock_grab(&(sp->lock));
1121 // Check for legality only before to do the move
1122 if (!pos.pl_move_is_legal(move, ci.pinned))
1128 ss->currentMove = move;
1129 if (!SpNode && !captureOrPromotion)
1130 movesSearched[playedMoveCount++] = move;
1132 // Step 14. Make the move
1133 pos.do_move(move, st, ci, givesCheck);
1135 // Step extra. pv search (only in PV nodes)
1136 // The first move in list is the expected PV
1138 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1139 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1142 // Step 15. Reduced depth search
1143 // If the move fails high will be re-searched at full depth.
1144 bool doFullDepthSearch = true;
1146 if ( depth > 3 * ONE_PLY
1147 && !captureOrPromotion
1150 && ss->killers[0] != move
1151 && ss->killers[1] != move
1152 && (ss->reduction = reduction<PvNode>(depth, moveCount)) != DEPTH_ZERO)
1154 Depth d = newDepth - ss->reduction;
1155 alpha = SpNode ? sp->alpha : alpha;
1157 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1158 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1160 ss->reduction = DEPTH_ZERO;
1161 doFullDepthSearch = (value > alpha);
1164 // Step 16. Full depth search
1165 if (doFullDepthSearch)
1167 alpha = SpNode ? sp->alpha : alpha;
1168 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1169 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1171 // Step extra. pv search (only in PV nodes)
1172 // Search only for possible new PV nodes, if instead value >= beta then
1173 // parent node fails low with value <= alpha and tries another move.
1174 if (PvNode && value > alpha && (RootNode || value < beta))
1175 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1176 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1180 // Step 17. Undo move
1181 pos.undo_move(move);
1183 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1185 // Step 18. Check for new best move
1188 lock_grab(&(sp->lock));
1189 bestValue = sp->bestValue;
1193 // Finished searching the move. If StopRequest is true, the search
1194 // was aborted because the user interrupted the search or because we
1195 // ran out of time. In this case, the return value of the search cannot
1196 // be trusted, and we don't update the best move and/or PV.
1197 if (RootNode && !StopRequest)
1199 // Remember searched nodes counts for this move
1200 RootMove* rm = Rml.find(move);
1201 rm->nodes += pos.nodes_searched() - nodes;
1203 // PV move or new best move ?
1204 if (isPvMove || value > alpha)
1208 rm->extract_pv_from_tt(pos);
1210 // We record how often the best move has been changed in each
1211 // iteration. This information is used for time management: When
1212 // the best move changes frequently, we allocate some more time.
1213 if (!isPvMove && MultiPV == 1)
1214 Rml.bestMoveChanges++;
1217 // All other moves but the PV are set to the lowest value, this
1218 // is not a problem when sorting becuase sort is stable and move
1219 // position in the list is preserved, just the PV is pushed up.
1220 rm->score = -VALUE_INFINITE;
1224 if (value > bestValue)
1227 ss->bestMove = move;
1231 && value < beta) // We want always alpha < beta
1234 if (SpNode && !thread.cutoff_occurred())
1236 sp->bestValue = value;
1237 sp->ss->bestMove = move;
1239 sp->is_betaCutoff = (value >= beta);
1243 // Step 19. Check for split
1245 && depth >= Threads.min_split_depth()
1247 && Threads.available_slave_exists(pos.thread())
1249 && !thread.cutoff_occurred())
1250 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1251 threatMove, moveCount, &mp, NT);
1254 // Step 20. Check for mate and stalemate
1255 // All legal moves have been searched and if there are no legal moves, it
1256 // must be mate or stalemate. Note that we can have a false positive in
1257 // case of StopRequest or thread.cutoff_occurred() are set, but this is
1258 // harmless because return value is discarded anyhow in the parent nodes.
1259 // If we are in a singular extension search then return a fail low score.
1260 if (!SpNode && !moveCount)
1261 return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1263 // Step 21. Update tables
1264 // If the search is not aborted, update the transposition table,
1265 // history counters, and killer moves.
1266 if (!SpNode && !StopRequest && !thread.cutoff_occurred())
1268 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1269 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1270 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1272 TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1274 // Update killers and history only for non capture moves that fails high
1275 if ( bestValue >= beta
1276 && !pos.is_capture_or_promotion(move))
1278 if (move != ss->killers[0])
1280 ss->killers[1] = ss->killers[0];
1281 ss->killers[0] = move;
1283 update_history(pos, move, depth, movesSearched, playedMoveCount);
1289 // Here we have the lock still grabbed
1290 sp->is_slave[pos.thread()] = false;
1291 sp->nodes += pos.nodes_searched();
1292 lock_release(&(sp->lock));
1295 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1300 // qsearch() is the quiescence search function, which is called by the main
1301 // search function when the remaining depth is zero (or, to be more precise,
1302 // less than ONE_PLY).
1304 template <NodeType NT>
1305 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
1307 const bool PvNode = (NT == PV);
1309 assert(NT == PV || NT == NonPV);
1310 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1311 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1312 assert(PvNode || alpha == beta - 1);
1314 assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1318 Value bestValue, value, evalMargin, futilityValue, futilityBase;
1319 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1323 Value oldAlpha = alpha;
1325 ss->bestMove = ss->currentMove = MOVE_NONE;
1326 ss->ply = (ss-1)->ply + 1;
1328 // Check for an instant draw or maximum ply reached
1329 if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1332 // Decide whether or not to include checks, this fixes also the type of
1333 // TT entry depth that we are going to use. Note that in qsearch we use
1334 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1335 inCheck = pos.in_check();
1336 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1338 // Transposition table lookup. At PV nodes, we don't use the TT for
1339 // pruning, but only for move ordering.
1340 tte = TT.probe(pos.get_key());
1341 ttMove = (tte ? tte->move() : MOVE_NONE);
1343 if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1345 ss->bestMove = ttMove; // Can be MOVE_NONE
1346 return value_from_tt(tte->value(), ss->ply);
1349 // Evaluate the position statically
1352 bestValue = futilityBase = -VALUE_INFINITE;
1353 ss->eval = evalMargin = VALUE_NONE;
1354 enoughMaterial = false;
1360 assert(tte->static_value() != VALUE_NONE);
1362 evalMargin = tte->static_value_margin();
1363 ss->eval = bestValue = tte->static_value();
1366 ss->eval = bestValue = evaluate(pos, evalMargin);
1368 // Stand pat. Return immediately if static value is at least beta
1369 if (bestValue >= beta)
1372 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1377 if (PvNode && bestValue > alpha)
1380 // Futility pruning parameters, not needed when in check
1381 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1382 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1385 // Initialize a MovePicker object for the current position, and prepare
1386 // to search the moves. Because the depth is <= 0 here, only captures,
1387 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1389 MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1392 // Loop through the moves until no moves remain or a beta cutoff occurs
1393 while ( bestValue < beta
1394 && (move = mp.get_next_move()) != MOVE_NONE)
1396 assert(is_ok(move));
1398 givesCheck = pos.move_gives_check(move, ci);
1406 && !is_promotion(move)
1407 && !pos.is_passed_pawn_push(move))
1409 futilityValue = futilityBase
1410 + PieceValueEndgame[pos.piece_on(move_to(move))]
1411 + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1413 if (futilityValue < beta)
1415 if (futilityValue > bestValue)
1416 bestValue = futilityValue;
1421 // Prune moves with negative or equal SEE
1422 if ( futilityBase < beta
1423 && depth < DEPTH_ZERO
1424 && pos.see(move) <= 0)
1428 // Detect non-capture evasions that are candidate to be pruned
1429 evasionPrunable = !PvNode
1431 && bestValue > VALUE_MATED_IN_PLY_MAX
1432 && !pos.is_capture(move)
1433 && !pos.can_castle(pos.side_to_move());
1435 // Don't search moves with negative SEE values
1437 && (!inCheck || evasionPrunable)
1439 && !is_promotion(move)
1440 && pos.see_sign(move) < 0)
1443 // Don't search useless checks
1448 && !pos.is_capture_or_promotion(move)
1449 && ss->eval + PawnValueMidgame / 4 < beta
1450 && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1452 if (ss->eval + PawnValueMidgame / 4 > bestValue)
1453 bestValue = ss->eval + PawnValueMidgame / 4;
1458 // Check for legality only before to do the move
1459 if (!pos.pl_move_is_legal(move, ci.pinned))
1462 // Update current move
1463 ss->currentMove = move;
1465 // Make and search the move
1466 pos.do_move(move, st, ci, givesCheck);
1467 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1468 pos.undo_move(move);
1470 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1473 if (value > bestValue)
1476 ss->bestMove = move;
1480 && value < beta) // We want always alpha < beta
1485 // All legal moves have been searched. A special case: If we're in check
1486 // and no legal moves were found, it is checkmate.
1487 if (inCheck && bestValue == -VALUE_INFINITE)
1488 return value_mated_in(ss->ply);
1490 // Update transposition table
1491 move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1492 vt = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1493 : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1495 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1497 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1503 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1504 // bestValue is updated only when returning false because in that case move
1507 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1509 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1510 Square from, to, ksq, victimSq;
1513 Value futilityValue, bv = *bestValue;
1515 from = move_from(move);
1517 them = flip(pos.side_to_move());
1518 ksq = pos.king_square(them);
1519 kingAtt = pos.attacks_from<KING>(ksq);
1520 pc = pos.piece_on(from);
1522 occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1523 oldAtt = pos.attacks_from(pc, from, occ);
1524 newAtt = pos.attacks_from(pc, to, occ);
1526 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1527 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1529 if (!(b && (b & (b - 1))))
1532 // Rule 2. Queen contact check is very dangerous
1533 if ( type_of(pc) == QUEEN
1534 && bit_is_set(kingAtt, to))
1537 // Rule 3. Creating new double threats with checks
1538 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1542 victimSq = pop_1st_bit(&b);
1543 futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1545 // Note that here we generate illegal "double move"!
1546 if ( futilityValue >= beta
1547 && pos.see_sign(make_move(from, victimSq)) >= 0)
1550 if (futilityValue > bv)
1554 // Update bestValue only if check is not dangerous (because we will prune the move)
1560 // connected_moves() tests whether two moves are 'connected' in the sense
1561 // that the first move somehow made the second move possible (for instance
1562 // if the moving piece is the same in both moves). The first move is assumed
1563 // to be the move that was made to reach the current position, while the
1564 // second move is assumed to be a move from the current position.
1566 bool connected_moves(const Position& pos, Move m1, Move m2) {
1568 Square f1, t1, f2, t2;
1575 // Case 1: The moving piece is the same in both moves
1581 // Case 2: The destination square for m2 was vacated by m1
1587 // Case 3: Moving through the vacated square
1588 p2 = pos.piece_on(f2);
1589 if ( piece_is_slider(p2)
1590 && bit_is_set(squares_between(f2, t2), f1))
1593 // Case 4: The destination square for m2 is defended by the moving piece in m1
1594 p1 = pos.piece_on(t1);
1595 if (bit_is_set(pos.attacks_from(p1, t1), t2))
1598 // Case 5: Discovered check, checking piece is the piece moved in m1
1599 ksq = pos.king_square(pos.side_to_move());
1600 if ( piece_is_slider(p1)
1601 && bit_is_set(squares_between(t1, ksq), f2))
1603 Bitboard occ = pos.occupied_squares();
1604 clear_bit(&occ, f2);
1605 if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1612 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1613 // "plies to mate from the current ply". Non-mate scores are unchanged.
1614 // The function is called before storing a value to the transposition table.
1616 Value value_to_tt(Value v, int ply) {
1618 if (v >= VALUE_MATE_IN_PLY_MAX)
1621 if (v <= VALUE_MATED_IN_PLY_MAX)
1628 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1629 // the transposition table to a mate score corrected for the current ply.
1631 Value value_from_tt(Value v, int ply) {
1633 if (v >= VALUE_MATE_IN_PLY_MAX)
1636 if (v <= VALUE_MATED_IN_PLY_MAX)
1643 // connected_threat() tests whether it is safe to forward prune a move or if
1644 // is somehow connected to the threat move returned by null search.
1646 bool connected_threat(const Position& pos, Move m, Move threat) {
1649 assert(is_ok(threat));
1650 assert(!pos.is_capture_or_promotion(m));
1651 assert(!pos.is_passed_pawn_push(m));
1653 Square mfrom, mto, tfrom, tto;
1655 mfrom = move_from(m);
1657 tfrom = move_from(threat);
1658 tto = move_to(threat);
1660 // Case 1: Don't prune moves which move the threatened piece
1664 // Case 2: If the threatened piece has value less than or equal to the
1665 // value of the threatening piece, don't prune moves which defend it.
1666 if ( pos.is_capture(threat)
1667 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1668 || type_of(pos.piece_on(tfrom)) == KING)
1669 && pos.move_attacks_square(m, tto))
1672 // Case 3: If the moving piece in the threatened move is a slider, don't
1673 // prune safe moves which block its ray.
1674 if ( piece_is_slider(pos.piece_on(tfrom))
1675 && bit_is_set(squares_between(tfrom, tto), mto)
1676 && pos.see_sign(m) >= 0)
1683 // can_return_tt() returns true if a transposition table score
1684 // can be used to cut-off at a given point in search.
1686 bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1688 Value v = value_from_tt(tte->value(), ply);
1690 return ( tte->depth() >= depth
1691 || v >= Max(VALUE_MATE_IN_PLY_MAX, beta)
1692 || v < Min(VALUE_MATED_IN_PLY_MAX, beta))
1694 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1695 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1699 // refine_eval() returns the transposition table score if
1700 // possible otherwise falls back on static position evaluation.
1702 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1706 Value v = value_from_tt(tte->value(), ply);
1708 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1709 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1716 // update_history() registers a good move that produced a beta-cutoff
1717 // in history and marks as failures all the other moves of that ply.
1719 void update_history(const Position& pos, Move move, Depth depth,
1720 Move movesSearched[], int moveCount) {
1722 Value bonus = Value(int(depth) * int(depth));
1724 H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1726 for (int i = 0; i < moveCount - 1; i++)
1728 m = movesSearched[i];
1732 H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1737 // current_search_time() returns the number of milliseconds which have passed
1738 // since the beginning of the current search.
1740 int current_search_time(int set) {
1742 static int searchStartTime;
1745 searchStartTime = set;
1747 return get_system_time() - searchStartTime;
1751 // score_to_uci() converts a value to a string suitable for use with the UCI
1752 // protocol specifications:
1754 // cp <x> The score from the engine's point of view in centipawns.
1755 // mate <y> Mate in y moves, not plies. If the engine is getting mated
1756 // use negative values for y.
1758 string score_to_uci(Value v, Value alpha, Value beta) {
1760 std::stringstream s;
1762 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1763 s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1765 s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1767 s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1773 // speed_to_uci() returns a string with time stats of current search suitable
1774 // to be sent to UCI gui.
1776 string speed_to_uci(int64_t nodes) {
1778 std::stringstream s;
1779 int t = current_search_time();
1781 s << " nodes " << nodes
1782 << " nps " << (t > 0 ? int(nodes * 1000 / t) : 0)
1788 // pv_to_uci() returns a string with information on the current PV line
1789 // formatted according to UCI specification.
1791 string pv_to_uci(const Move pv[], int pvNum, bool chess960) {
1793 std::stringstream s;
1795 s << " multipv " << pvNum << " pv " << set960(chess960);
1797 for ( ; *pv != MOVE_NONE; pv++)
1803 // depth_to_uci() returns a string with information on the current depth and
1804 // seldepth formatted according to UCI specification.
1806 string depth_to_uci(Depth depth) {
1808 std::stringstream s;
1810 // Retrieve max searched depth among threads
1812 for (int i = 0; i < Threads.size(); i++)
1813 if (Threads[i].maxPly > selDepth)
1814 selDepth = Threads[i].maxPly;
1816 s << " depth " << depth / ONE_PLY << " seldepth " << selDepth;
1821 string time_to_string(int millisecs) {
1823 const int MSecMinute = 1000 * 60;
1824 const int MSecHour = 1000 * 60 * 60;
1826 int hours = millisecs / MSecHour;
1827 int minutes = (millisecs % MSecHour) / MSecMinute;
1828 int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1830 std::stringstream s;
1835 s << std::setfill('0') << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
1839 string score_to_string(Value v) {
1841 std::stringstream s;
1843 if (v >= VALUE_MATE_IN_PLY_MAX)
1844 s << "#" << (VALUE_MATE - v + 1) / 2;
1845 else if (v <= VALUE_MATED_IN_PLY_MAX)
1846 s << "-#" << (VALUE_MATE + v) / 2;
1848 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);
1905 // poll() performs two different functions: It polls for user input, and it
1906 // looks at the time consumed so far and decides if it's time to abort the
1909 void poll(const Position& pos) {
1911 static int lastInfoTime;
1912 int t = current_search_time();
1915 if (input_available())
1917 // We are line oriented, don't read single chars
1920 if (!std::getline(std::cin, command) || command == "quit")
1922 // Quit the program as soon as possible
1923 Limits.ponder = false;
1924 QuitRequest = StopRequest = true;
1927 else if (command == "stop")
1929 // Stop calculating as soon as possible, but still send the "bestmove"
1930 // and possibly the "ponder" token when finishing the search.
1931 Limits.ponder = false;
1934 else if (command == "ponderhit")
1936 // The opponent has played the expected move. GUI sends "ponderhit" if
1937 // we were told to ponder on the same move the opponent has played. We
1938 // should continue searching but switching from pondering to normal search.
1939 Limits.ponder = false;
1941 if (StopOnPonderhit)
1946 // Print search information
1950 else if (lastInfoTime > t)
1951 // HACK: Must be a new search where we searched less than
1952 // NodesBetweenPolls nodes during the first second of search.
1955 else if (t - lastInfoTime >= 1000)
1960 dbg_print_hit_rate();
1963 // Should we stop the search?
1967 bool stillAtFirstMove = FirstRootMove
1968 && !AspirationFailLow
1969 && t > TimeMgr.available_time();
1971 bool noMoreTime = t > TimeMgr.maximum_time()
1972 || stillAtFirstMove;
1974 if ( (Limits.useTimeManagement() && noMoreTime)
1975 || (Limits.maxTime && t >= Limits.maxTime)
1976 || (Limits.maxNodes && pos.nodes_searched() >= Limits.maxNodes)) // FIXME
1981 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
1982 // while the program is pondering. The point is to work around a wrinkle in
1983 // the UCI protocol: When pondering, the engine is not allowed to give a
1984 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
1985 // We simply wait here until one of these commands is sent, and return,
1986 // after which the bestmove and pondermove will be printed.
1988 void wait_for_stop_or_ponderhit() {
1992 // Wait for a command from stdin
1993 while ( std::getline(std::cin, command)
1994 && command != "ponderhit" && command != "stop" && command != "quit") {};
1996 if (command != "ponderhit" && command != "stop")
1997 QuitRequest = true; // Must be "quit" or getline() returned false
2001 // When playing with strength handicap choose best move among the MultiPV set
2002 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
2003 void do_skill_level(Move* best, Move* ponder) {
2005 assert(MultiPV > 1);
2009 // Rml list is already sorted by score in descending order
2011 int max_s = -VALUE_INFINITE;
2012 int size = Min(MultiPV, (int)Rml.size());
2013 int max = Rml[0].score;
2014 int var = Min(max - Rml[size - 1].score, PawnValueMidgame);
2015 int wk = 120 - 2 * SkillLevel;
2017 // PRNG sequence should be non deterministic
2018 for (int i = abs(get_system_time() % 50); i > 0; i--)
2019 rk.rand<unsigned>();
2021 // Choose best move. For each move's score we add two terms both dependent
2022 // on wk, one deterministic and bigger for weaker moves, and one random,
2023 // then we choose the move with the resulting highest score.
2024 for (int i = 0; i < size; i++)
2028 // Don't allow crazy blunders even at very low skills
2029 if (i > 0 && Rml[i-1].score > s + EasyMoveMargin)
2032 // This is our magical formula
2033 s += ((max - s) * wk + var * (rk.rand<unsigned>() % wk)) / 128;
2038 *best = Rml[i].pv[0];
2039 *ponder = Rml[i].pv[1];
2045 /// RootMove and RootMoveList method's definitions
2047 void RootMoveList::init(Position& pos, Move searchMoves[]) {
2050 bestMoveChanges = 0;
2053 // Generate all legal moves and add them to RootMoveList
2054 for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
2056 // If we have a searchMoves[] list then verify the move
2057 // is in the list before to add it.
2058 for (sm = searchMoves; *sm && *sm != ml.move(); sm++) {}
2060 if (sm != searchMoves && *sm != ml.move())
2064 rm.pv.push_back(ml.move());
2065 rm.pv.push_back(MOVE_NONE);
2066 rm.score = rm.prevScore = -VALUE_INFINITE;
2072 RootMove* RootMoveList::find(const Move& m, int startIndex) {
2074 for (size_t i = startIndex; i < size(); i++)
2075 if ((*this)[i].pv[0] == m)
2081 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
2082 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
2083 // allow to always have a ponder move even when we fail high at root and also a
2084 // long PV to print that is important for position analysis.
2086 void RootMove::extract_pv_from_tt(Position& pos) {
2088 StateInfo state[PLY_MAX_PLUS_2], *st = state;
2093 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
2097 pos.do_move(m, *st++);
2099 while ( (tte = TT.probe(pos.get_key())) != NULL
2100 && tte->move() != MOVE_NONE
2101 && pos.is_pseudo_legal(tte->move())
2102 && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
2104 && (!pos.is_draw<false>() || ply < 2))
2106 pv.push_back(tte->move());
2107 pos.do_move(tte->move(), *st++);
2110 pv.push_back(MOVE_NONE);
2112 do pos.undo_move(pv[--ply]); while (ply);
2115 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2116 // the PV back into the TT. This makes sure the old PV moves are searched
2117 // first, even if the old TT entries have been overwritten.
2119 void RootMove::insert_pv_in_tt(Position& pos) {
2121 StateInfo state[PLY_MAX_PLUS_2], *st = state;
2124 Value v, m = VALUE_NONE;
2127 assert(pv[0] != MOVE_NONE && pos.is_pseudo_legal(pv[0]));
2133 // Don't overwrite existing correct entries
2134 if (!tte || tte->move() != pv[ply])
2136 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
2137 TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2139 pos.do_move(pv[ply], *st++);
2141 } while (pv[++ply] != MOVE_NONE);
2143 do pos.undo_move(pv[--ply]); while (ply);
2148 // Little helper used by idle_loop() to check that all the slave threads of a
2149 // split point have finished searching.
2151 static bool all_slaves_finished(SplitPoint* sp) {
2153 for (int i = 0; i < Threads.size(); i++)
2154 if (sp->is_slave[i])
2161 // Thread::idle_loop() is where the thread is parked when it has no work to do.
2162 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
2163 // for which the thread is the master.
2165 void Thread::idle_loop(SplitPoint* sp) {
2169 // If we are not searching, wait for a condition to be signaled
2170 // instead of wasting CPU time polling for work.
2173 || (Threads.use_sleeping_threads() && !is_searching))
2175 assert((!sp && threadID) || Threads.use_sleeping_threads());
2177 // Slave thread should exit as soon as do_terminate flag raises
2184 // Grab the lock to avoid races with Thread::wake_up()
2185 lock_grab(&sleepLock);
2187 // If we are master and all slaves have finished don't go to sleep
2188 if (sp && all_slaves_finished(sp))
2190 lock_release(&sleepLock);
2194 // Do sleep after retesting sleep conditions under lock protection, in
2195 // particular we need to avoid a deadlock in case a master thread has,
2196 // in the meanwhile, allocated us and sent the wake_up() call before we
2197 // had the chance to grab the lock.
2198 if (do_sleep || !is_searching)
2199 cond_wait(&sleepCond, &sleepLock);
2201 lock_release(&sleepLock);
2204 // If this thread has been assigned work, launch a search
2207 assert(!do_terminate);
2209 // Copy split point position and search stack and call search()
2210 SearchStack ss[PLY_MAX_PLUS_2];
2211 SplitPoint* tsp = splitPoint;
2212 Position pos(*tsp->pos, threadID);
2214 memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2217 if (tsp->nodeType == Root)
2218 search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2219 else if (tsp->nodeType == PV)
2220 search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2221 else if (tsp->nodeType == NonPV)
2222 search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2226 assert(is_searching);
2228 is_searching = false;
2230 // Wake up master thread so to allow it to return from the idle loop in
2231 // case we are the last slave of the split point.
2232 if ( Threads.use_sleeping_threads()
2233 && threadID != tsp->master
2234 && !Threads[tsp->master].is_searching)
2235 Threads[tsp->master].wake_up();
2238 // If this thread is the master of a split point and all slaves have
2239 // finished their work at this split point, return from the idle loop.
2240 if (sp && all_slaves_finished(sp))
2242 // Because sp->is_slave[] is reset under lock protection,
2243 // be sure sp->lock has been released before to return.
2244 lock_grab(&(sp->lock));
2245 lock_release(&(sp->lock));