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-2012 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/>.
37 #include "ucioption.h"
41 volatile SignalsType Signals;
43 std::vector<RootMove> RootMoves;
44 Position RootPosition;
52 using namespace Search;
54 // For some reason argument-dependent lookup (ADL) doesn't work for Android's
55 // STLPort, so explicitly qualify following functions.
61 // Set to true to force running with one thread. Used for debugging
62 const bool FakeSplit = false;
64 // Different node types, used as template parameter
65 enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
67 // Lookup table to check if a Piece is a slider and its access function
68 const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
69 inline bool piece_is_slider(Piece p) { return Slidings[p]; }
71 // Maximum depth for razoring
72 const Depth RazorDepth = 4 * ONE_PLY;
74 // Dynamic razoring margin based on depth
75 inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
77 // Maximum depth for use of dynamic threat detection when null move fails low
78 const Depth ThreatDepth = 5 * ONE_PLY;
80 // Minimum depth for use of internal iterative deepening
81 const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
83 // At Non-PV nodes we do an internal iterative deepening search
84 // when the static evaluation is bigger then beta - IIDMargin.
85 const Value IIDMargin = Value(256);
87 // Minimum depth for use of singular extension
88 const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
90 // Futility margin for quiescence search
91 const Value FutilityMarginQS = Value(128);
93 // Futility lookup tables (initialized at startup) and their access functions
94 Value FutilityMargins[16][64]; // [depth][moveNumber]
95 int FutilityMoveCounts[32]; // [depth]
97 inline Value futility_margin(Depth d, int mn) {
99 return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
100 : 2 * VALUE_INFINITE;
103 inline int futility_move_count(Depth d) {
105 return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
108 // Reduction lookup tables (initialized at startup) and their access function
109 int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
111 template <bool PvNode> inline Depth reduction(Depth d, int mn) {
113 return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
116 // Easy move margin. An easy move candidate must be at least this much better
117 // than the second best move.
118 const Value EasyMoveMargin = Value(0x150);
120 // This is the minimum interval in msec between two check_time() calls
121 const int TimerResolution = 5;
124 size_t MultiPV, UCIMultiPV, PVIdx;
128 bool SkillLevelEnabled, Chess960;
132 template <NodeType NT>
133 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
135 template <NodeType NT>
136 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
138 void id_loop(Position& pos);
139 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
140 bool connected_moves(const Position& pos, Move m1, Move m2);
141 Value value_to_tt(Value v, int ply);
142 Value value_from_tt(Value v, int ply);
143 bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
144 bool connected_threat(const Position& pos, Move m, Move threat);
145 Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
146 Move do_skill_level();
147 string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
149 // MovePickerExt class template extends MovePicker and allows to choose at
150 // compile time the proper moves source according to the type of node. In the
151 // default case we simply create and use a standard MovePicker object.
152 template<bool SpNode> struct MovePickerExt : public MovePicker {
154 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
155 : MovePicker(p, ttm, d, h, ss, b) {}
158 // In case of a SpNode we use split point's shared MovePicker object as moves source
159 template<> struct MovePickerExt<true> : public MovePicker {
161 MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
162 : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
164 Move next_move() { return mp->next_move(); }
168 // is_dangerous() checks whether a move belongs to some classes of known
169 // 'dangerous' moves so that we avoid to prune it.
170 FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
173 if (type_of(m) == CASTLE)
177 if ( type_of(pos.piece_moved(m)) == PAWN
178 && pos.pawn_is_passed(pos.side_to_move(), to_sq(m)))
181 // Entering a pawn endgame?
182 if ( captureOrPromotion
183 && type_of(pos.piece_on(to_sq(m))) != PAWN
184 && type_of(m) == NORMAL
185 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
186 - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO))
195 /// Search::init() is called during startup to initialize various lookup tables
197 void Search::init() {
199 int d; // depth (ONE_PLY == 2)
200 int hd; // half depth (ONE_PLY == 1)
203 // Init reductions array
204 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
206 double pvRed = log(double(hd)) * log(double(mc)) / 3.0;
207 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
208 Reductions[1][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
209 Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
212 // Init futility margins array
213 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
214 FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
216 // Init futility move count array
217 for (d = 0; d < 32; d++)
218 FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
222 /// Search::perft() is our utility to verify move generation. All the leaf nodes
223 /// up to the given depth are generated and counted and the sum returned.
225 int64_t Search::perft(Position& pos, Depth depth) {
230 MoveList<LEGAL> ml(pos);
232 // At the last ply just return the number of moves (leaf nodes)
233 if (depth == ONE_PLY)
237 for ( ; !ml.end(); ++ml)
239 pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
240 cnt += perft(pos, depth - ONE_PLY);
241 pos.undo_move(ml.move());
247 /// Search::think() is the external interface to Stockfish's search, and is
248 /// called by the main thread when the program receives the UCI 'go' command. It
249 /// searches from RootPosition and at the end prints the "bestmove" to output.
251 void Search::think() {
253 static Book book; // Defined static to initialize the PRNG only once
255 Position& pos = RootPosition;
256 Chess960 = pos.is_chess960();
257 Eval::RootColor = pos.side_to_move();
258 TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
262 if (RootMoves.empty())
264 cout << "info depth 0 score "
265 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
267 RootMoves.push_back(MOVE_NONE);
271 if (Options["OwnBook"] && !Limits.infinite)
273 Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
275 if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
277 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
282 UCIMultiPV = Options["MultiPV"];
283 SkillLevel = Options["Skill Level"];
285 // Do we have to play with skill handicap? In this case enable MultiPV that
286 // we will use behind the scenes to retrieve a set of possible moves.
287 SkillLevelEnabled = (SkillLevel < 20);
288 MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
290 if (Options["Use Search Log"])
292 Log log(Options["Search Log Filename"]);
293 log << "\nSearching: " << pos.to_fen()
294 << "\ninfinite: " << Limits.infinite
295 << " ponder: " << Limits.ponder
296 << " time: " << Limits.time[pos.side_to_move()]
297 << " increment: " << Limits.inc[pos.side_to_move()]
298 << " moves to go: " << Limits.movestogo
304 // Set best timer interval to avoid lagging under time pressure. Timer is
305 // used to check for remaining available thinking time.
306 if (Limits.use_time_management())
307 Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
309 Threads.set_timer(100);
311 // We're ready to start searching. Call the iterative deepening loop function
314 Threads.set_timer(0); // Stop timer
317 if (Options["Use Search Log"])
319 int e = SearchTime.elapsed();
321 Log log(Options["Search Log Filename"]);
322 log << "Nodes: " << pos.nodes_searched()
323 << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
324 << "\nBest move: " << move_to_san(pos, RootMoves[0].pv[0]);
327 pos.do_move(RootMoves[0].pv[0], st);
328 log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
329 pos.undo_move(RootMoves[0].pv[0]);
334 // When we reach max depth we arrive here even without Signals.stop is raised,
335 // but if we are pondering or in infinite search, we shouldn't print the best
336 // move before we are told to do so.
337 if (!Signals.stop && (Limits.ponder || Limits.infinite))
338 pos.this_thread()->wait_for_stop_or_ponderhit();
340 // Best move could be MOVE_NONE when searching on a stalemate position
341 cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
342 << " ponder " << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
348 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
349 // with increasing depth until the allocated thinking time has been consumed,
350 // user stops the search, or the maximum search depth is reached.
352 void id_loop(Position& pos) {
354 Stack ss[MAX_PLY_PLUS_2];
355 int depth, prevBestMoveChanges;
356 Value bestValue, alpha, beta, delta;
357 bool bestMoveNeverChanged = true;
358 Move skillBest = MOVE_NONE;
360 memset(ss, 0, 4 * sizeof(Stack));
361 depth = BestMoveChanges = 0;
362 bestValue = delta = -VALUE_INFINITE;
363 ss->currentMove = MOVE_NULL; // Hack to skip update gains
365 // Iterative deepening loop until requested to stop or target depth reached
366 while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
368 // Save last iteration's scores before first PV line is searched and all
369 // the move scores but the (new) PV are set to -VALUE_INFINITE.
370 for (size_t i = 0; i < RootMoves.size(); i++)
371 RootMoves[i].prevScore = RootMoves[i].score;
373 prevBestMoveChanges = BestMoveChanges;
376 // MultiPV loop. We perform a full root search for each PV line
377 for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
379 // Set aspiration window default width
380 if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
383 alpha = RootMoves[PVIdx].prevScore - delta;
384 beta = RootMoves[PVIdx].prevScore + delta;
388 alpha = -VALUE_INFINITE;
389 beta = VALUE_INFINITE;
392 // Start with a small aspiration window and, in case of fail high/low,
393 // research with bigger window until not failing high/low anymore.
395 // Search starts from ss+1 to allow referencing (ss-1). This is
396 // needed by update gains and ss copy when splitting at Root.
397 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
399 // Bring to front the best move. It is critical that sorting is
400 // done with a stable algorithm because all the values but the first
401 // and eventually the new best one are set to -VALUE_INFINITE and
402 // we want to keep the same order for all the moves but the new
403 // PV that goes to the front. Note that in case of MultiPV search
404 // the already searched PV lines are preserved.
405 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
407 // In case we have found an exact score and we are going to leave
408 // the fail high/low loop then reorder the PV moves, otherwise
409 // leave the last PV move in its position so to be searched again.
410 // Of course this is needed only in MultiPV search.
411 if (PVIdx && bestValue > alpha && bestValue < beta)
412 sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
414 // Write PV back to transposition table in case the relevant
415 // entries have been overwritten during the search.
416 for (size_t i = 0; i <= PVIdx; i++)
417 RootMoves[i].insert_pv_in_tt(pos);
419 // If search has been stopped exit the aspiration window loop.
420 // Sorting and writing PV back to TT is safe becuase RootMoves
421 // is still valid, although refers to previous iteration.
425 // Send full PV info to GUI if we are going to leave the loop or
426 // if we have a fail high/low and we are deep in the search.
427 if ((bestValue > alpha && bestValue < beta) || SearchTime.elapsed() > 2000)
428 cout << uci_pv(pos, depth, alpha, beta) << endl;
430 // In case of failing high/low increase aspiration window and
431 // research, otherwise exit the fail high/low loop.
432 if (bestValue >= beta)
437 else if (bestValue <= alpha)
439 Signals.failedLowAtRoot = true;
440 Signals.stopOnPonderhit = false;
448 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
450 } while (abs(bestValue) < VALUE_KNOWN_WIN);
453 // Skills: Do we need to pick now the best move ?
454 if (SkillLevelEnabled && depth == 1 + SkillLevel)
455 skillBest = do_skill_level();
457 if (!Signals.stop && Options["Use Search Log"])
459 Log log(Options["Search Log Filename"]);
460 log << pretty_pv(pos, depth, bestValue, SearchTime.elapsed(), &RootMoves[0].pv[0])
464 // Filter out startup noise when monitoring best move stability
465 if (depth > 2 && BestMoveChanges)
466 bestMoveNeverChanged = false;
468 // Do we have time for the next iteration? Can we stop searching now?
469 if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
471 bool stop = false; // Local variable, not the volatile Signals.stop
473 // Take in account some extra time if the best move has changed
474 if (depth > 4 && depth < 50)
475 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
477 // Stop search if most of available time is already consumed. We
478 // probably don't have enough time to search the first move at the
479 // next iteration anyway.
480 if (SearchTime.elapsed() > (TimeMgr.available_time() * 62) / 100)
483 // Stop search early if one move seems to be much better than others
486 && ( (bestMoveNeverChanged && pos.captured_piece_type())
487 || SearchTime.elapsed() > (TimeMgr.available_time() * 40) / 100))
489 Value rBeta = bestValue - EasyMoveMargin;
490 (ss+1)->excludedMove = RootMoves[0].pv[0];
491 (ss+1)->skipNullMove = true;
492 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
493 (ss+1)->skipNullMove = false;
494 (ss+1)->excludedMove = MOVE_NONE;
502 // If we are allowed to ponder do not stop the search now but
503 // keep pondering until GUI sends "ponderhit" or "stop".
505 Signals.stopOnPonderhit = true;
512 // When using skills swap best PV line with the sub-optimal one
513 if (SkillLevelEnabled)
515 if (skillBest == MOVE_NONE) // Still unassigned ?
516 skillBest = do_skill_level();
518 std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
523 // search<>() is the main search function for both PV and non-PV nodes and for
524 // normal and SplitPoint nodes. When called just after a split point the search
525 // is simpler because we have already probed the hash table, done a null move
526 // search, and searched the first move before splitting, we don't have to repeat
527 // all this work again. We also don't need to store anything to the hash table
528 // here: This is taken care of after we return from the split point.
530 template <NodeType NT>
531 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
533 const bool PvNode = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
534 const bool SpNode = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
535 const bool RootNode = (NT == Root || NT == SplitPointRoot);
537 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
538 assert((alpha == beta - 1) || PvNode);
539 assert(depth > DEPTH_ZERO);
541 Move movesSearched[64];
545 Move ttMove, move, excludedMove, bestMove, threatMove;
548 Value bestValue, value, oldAlpha, ttValue;
549 Value refinedValue, nullValue, futilityBase, futilityValue;
550 bool isPvMove, inCheck, singularExtensionNode, givesCheck;
551 bool captureOrPromotion, dangerous, doFullDepthSearch;
552 int moveCount = 0, playedMoveCount = 0;
553 Thread* thisThread = pos.this_thread();
554 SplitPoint* sp = NULL;
556 refinedValue = bestValue = value = -VALUE_INFINITE;
558 inCheck = pos.in_check();
559 ss->ply = (ss-1)->ply + 1;
561 // Used to send selDepth info to GUI
562 if (PvNode && thisThread->maxPly < ss->ply)
563 thisThread->maxPly = ss->ply;
565 // Step 1. Initialize node
569 ttMove = excludedMove = MOVE_NONE;
570 ttValue = VALUE_ZERO;
572 bestMove = sp->bestMove;
573 threatMove = sp->threatMove;
574 bestValue = sp->bestValue;
575 moveCount = sp->moveCount; // Lock must be held here
577 assert(bestValue > -VALUE_INFINITE && moveCount > 0);
579 goto split_point_start;
583 ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
584 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
585 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
589 // Step 2. Check for aborted search and immediate draw
590 // Enforce node limit here. FIXME: This only works with 1 search thread.
591 if (Limits.nodes && pos.nodes_searched() >= Limits.nodes)
595 || pos.is_draw<false>()
596 || ss->ply > MAX_PLY) && !RootNode)
599 // Step 3. Mate distance pruning. Even if we mate at the next move our score
600 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
601 // a shorter mate was found upward in the tree then there is no need to search
602 // further, we will never beat current alpha. Same logic but with reversed signs
603 // applies also in the opposite condition of being mated instead of giving mate,
604 // in this case return a fail-high score.
607 alpha = std::max(mated_in(ss->ply), alpha);
608 beta = std::min(mate_in(ss->ply+1), beta);
613 // Step 4. Transposition table lookup
614 // We don't want the score of a partial search to overwrite a previous full search
615 // TT value, so we use a different position key in case of an excluded move.
616 excludedMove = ss->excludedMove;
617 posKey = excludedMove ? pos.exclusion_key() : pos.key();
618 tte = TT.probe(posKey);
619 ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
620 ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_ZERO;
622 // At PV nodes we check for exact scores, while at non-PV nodes we check for
623 // a fail high/low. Biggest advantage at probing at PV nodes is to have a
624 // smooth experience in analysis mode. We don't probe at Root nodes otherwise
625 // we should also update RootMoveList to avoid bogus output.
626 if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
627 : can_return_tt(tte, depth, ttValue, beta)))
630 ss->currentMove = ttMove; // Can be MOVE_NONE
634 && !pos.is_capture_or_promotion(ttMove)
635 && ttMove != ss->killers[0])
637 ss->killers[1] = ss->killers[0];
638 ss->killers[0] = ttMove;
643 // Step 5. Evaluate the position statically and update parent's gain statistics
645 ss->eval = ss->evalMargin = VALUE_NONE;
648 assert(tte->static_value() != VALUE_NONE);
650 ss->eval = tte->static_value();
651 ss->evalMargin = tte->static_value_margin();
652 refinedValue = refine_eval(tte, ttValue, ss->eval);
656 refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
657 TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
660 // Update gain for the parent non-capture move given the static position
661 // evaluation before and after the move.
662 if ( (move = (ss-1)->currentMove) != MOVE_NULL
663 && (ss-1)->eval != VALUE_NONE
664 && ss->eval != VALUE_NONE
665 && !pos.captured_piece_type()
666 && type_of(move) == NORMAL)
668 Square to = to_sq(move);
669 H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
672 // Step 6. Razoring (is omitted in PV nodes)
674 && depth < RazorDepth
676 && refinedValue + razor_margin(depth) < beta
677 && ttMove == MOVE_NONE
678 && abs(beta) < VALUE_MATE_IN_MAX_PLY
679 && !pos.pawn_on_7th(pos.side_to_move()))
681 Value rbeta = beta - razor_margin(depth);
682 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
684 // Logically we should return (v + razor_margin(depth)), but
685 // surprisingly this did slightly weaker in tests.
689 // Step 7. Static null move pruning (is omitted in PV nodes)
690 // We're betting that the opponent doesn't have a move that will reduce
691 // the score by more than futility_margin(depth) if we do a null move.
694 && depth < RazorDepth
696 && refinedValue - futility_margin(depth, 0) >= beta
697 && abs(beta) < VALUE_MATE_IN_MAX_PLY
698 && pos.non_pawn_material(pos.side_to_move()))
699 return refinedValue - futility_margin(depth, 0);
701 // Step 8. Null move search with verification search (is omitted in PV nodes)
706 && refinedValue >= beta
707 && abs(beta) < VALUE_MATE_IN_MAX_PLY
708 && pos.non_pawn_material(pos.side_to_move()))
710 ss->currentMove = MOVE_NULL;
712 // Null move dynamic reduction based on depth
713 Depth R = 3 * ONE_PLY + depth / 4;
715 // Null move dynamic reduction based on value
716 if (refinedValue - PawnValueMidgame > beta)
719 pos.do_null_move<true>(st);
720 (ss+1)->skipNullMove = true;
721 nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
722 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
723 (ss+1)->skipNullMove = false;
724 pos.do_null_move<false>(st);
726 if (nullValue >= beta)
728 // Do not return unproven mate scores
729 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
732 if (depth < 6 * ONE_PLY)
735 // Do verification search at high depths
736 ss->skipNullMove = true;
737 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
738 ss->skipNullMove = false;
745 // The null move failed low, which means that we may be faced with
746 // some kind of threat. If the previous move was reduced, check if
747 // the move that refuted the null move was somehow connected to the
748 // move which was reduced. If a connection is found, return a fail
749 // low score (which will cause the reduced move to fail high in the
750 // parent node, which will trigger a re-search with full depth).
751 threatMove = (ss+1)->currentMove;
753 if ( depth < ThreatDepth
755 && threatMove != MOVE_NONE
756 && connected_moves(pos, (ss-1)->currentMove, threatMove))
761 // Step 9. ProbCut (is omitted in PV nodes)
762 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
763 // and a reduced search returns a value much above beta, we can (almost) safely
764 // prune the previous move.
766 && depth >= RazorDepth + ONE_PLY
769 && excludedMove == MOVE_NONE
770 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
772 Value rbeta = beta + 200;
773 Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
775 assert(rdepth >= ONE_PLY);
776 assert((ss-1)->currentMove != MOVE_NONE);
777 assert((ss-1)->currentMove != MOVE_NULL);
779 MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
782 while ((move = mp.next_move()) != MOVE_NONE)
783 if (pos.pl_move_is_legal(move, ci.pinned))
785 ss->currentMove = move;
786 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
787 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
794 // Step 10. Internal iterative deepening
795 if ( depth >= IIDDepth[PvNode]
796 && ttMove == MOVE_NONE
797 && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
799 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
801 ss->skipNullMove = true;
802 search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
803 ss->skipNullMove = false;
805 tte = TT.probe(posKey);
806 ttMove = tte ? tte->move() : MOVE_NONE;
809 split_point_start: // At split points actual search starts from here
811 MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
813 futilityBase = ss->eval + ss->evalMargin;
814 singularExtensionNode = !RootNode
816 && depth >= SingularExtensionDepth[PvNode]
817 && ttMove != MOVE_NONE
818 && !excludedMove // Recursive singular search is not allowed
819 && (tte->type() & BOUND_LOWER)
820 && tte->depth() >= depth - 3 * ONE_PLY;
822 // Step 11. Loop through moves
823 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
824 while ( bestValue < beta
825 && (move = mp.next_move()) != MOVE_NONE
826 && !thisThread->cutoff_occurred()
831 if (move == excludedMove)
834 // At root obey the "searchmoves" option and skip moves not listed in Root
835 // Move List, as a consequence any illegal move is also skipped. In MultiPV
836 // mode we also skip PV moves which have been already searched.
837 if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
840 // At PV and SpNode nodes we want all moves to be legal since the beginning
841 if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
846 moveCount = ++sp->moveCount;
847 lock_release(sp->lock);
854 Signals.firstRootMove = (moveCount == 1);
856 if (thisThread == Threads.main_thread() && SearchTime.elapsed() > 2000)
857 cout << "info depth " << depth / ONE_PLY
858 << " currmove " << move_to_uci(move, Chess960)
859 << " currmovenumber " << moveCount + PVIdx << endl;
862 isPvMove = (PvNode && moveCount <= 1);
863 captureOrPromotion = pos.is_capture_or_promotion(move);
864 givesCheck = pos.move_gives_check(move, ci);
865 dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
868 // Step 12. Extend checks and, in PV nodes, also dangerous moves
869 if (PvNode && dangerous)
872 else if (givesCheck && pos.see_sign(move) >= 0)
875 // Singular extension search. If all moves but one fail low on a search of
876 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
877 // is singular and should be extended. To verify this we do a reduced search
878 // on all the other moves but the ttMove, if result is lower than ttValue minus
879 // a margin then we extend ttMove.
880 if ( singularExtensionNode
883 && pos.pl_move_is_legal(move, ci.pinned)
884 && abs(ttValue) < VALUE_KNOWN_WIN)
886 Value rBeta = ttValue - int(depth);
887 ss->excludedMove = move;
888 ss->skipNullMove = true;
889 value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
890 ss->skipNullMove = false;
891 ss->excludedMove = MOVE_NONE;
897 // Update current move (this must be done after singular extension search)
898 newDepth = depth - ONE_PLY + ext;
900 // Step 13. Futility pruning (is omitted in PV nodes)
902 && !captureOrPromotion
906 && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
908 // Move count based pruning
909 if ( moveCount >= futility_move_count(depth)
910 && (!threatMove || !connected_threat(pos, move, threatMove)))
918 // Value based pruning
919 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
920 // but fixing this made program slightly weaker.
921 Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
922 futilityValue = futilityBase + futility_margin(predictedDepth, moveCount)
923 + H.gain(pos.piece_moved(move), to_sq(move));
925 if (futilityValue < beta)
933 // Prune moves with negative SEE at low depths
934 if ( predictedDepth < 2 * ONE_PLY
935 && pos.see_sign(move) < 0)
944 // Check for legality only before to do the move
945 if (!pos.pl_move_is_legal(move, ci.pinned))
951 ss->currentMove = move;
952 if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
953 movesSearched[playedMoveCount++] = move;
955 // Step 14. Make the move
956 pos.do_move(move, st, ci, givesCheck);
958 // Step 15. Reduced depth search (LMR). If the move fails high will be
959 // re-searched at full depth.
960 if ( depth > 3 * ONE_PLY
962 && !captureOrPromotion
964 && ss->killers[0] != move
965 && ss->killers[1] != move)
967 ss->reduction = reduction<PvNode>(depth, moveCount);
968 Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
969 alpha = SpNode ? sp->alpha : alpha;
971 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
973 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
974 ss->reduction = DEPTH_ZERO;
977 doFullDepthSearch = !isPvMove;
979 // Step 16. Full depth search, when LMR is skipped or fails high
980 if (doFullDepthSearch)
982 alpha = SpNode ? sp->alpha : alpha;
983 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
984 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
987 // Only for PV nodes do a full PV search on the first move or after a fail
988 // high, in the latter case search only if value < beta, otherwise let the
989 // parent node to fail low with value <= alpha and to try another move.
990 if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
991 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
992 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
994 // Step 17. Undo move
997 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
999 // Step 18. Check for new best move
1002 lock_grab(sp->lock);
1003 bestValue = sp->bestValue;
1007 // Finished searching the move. If Signals.stop is true, the search
1008 // was aborted because the user interrupted the search or because we
1009 // ran out of time. In this case, the return value of the search cannot
1010 // be trusted, and we don't update the best move and/or PV.
1011 if (RootNode && !Signals.stop)
1013 RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1015 // PV move or new best move ?
1016 if (isPvMove || value > alpha)
1019 rm.extract_pv_from_tt(pos);
1021 // We record how often the best move has been changed in each
1022 // iteration. This information is used for time management: When
1023 // the best move changes frequently, we allocate some more time.
1024 if (!isPvMove && MultiPV == 1)
1028 // All other moves but the PV are set to the lowest value, this
1029 // is not a problem when sorting becuase sort is stable and move
1030 // position in the list is preserved, just the PV is pushed up.
1031 rm.score = -VALUE_INFINITE;
1035 if (value > bestValue)
1042 && value < beta) // We want always alpha < beta
1045 if (SpNode && !thisThread->cutoff_occurred())
1047 sp->bestValue = value;
1048 sp->bestMove = move;
1056 // Step 19. Check for split
1058 && depth >= Threads.min_split_depth()
1060 && Threads.available_slave_exists(thisThread)
1062 && !thisThread->cutoff_occurred())
1063 bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1064 depth, threatMove, moveCount, &mp, NT);
1067 // Step 20. Check for mate and stalemate
1068 // All legal moves have been searched and if there are no legal moves, it
1069 // must be mate or stalemate. Note that we can have a false positive in
1070 // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1071 // harmless because return value is discarded anyhow in the parent nodes.
1072 // If we are in a singular extension search then return a fail low score.
1074 return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1076 // If we have pruned all the moves without searching return a fail-low score
1077 if (bestValue == -VALUE_INFINITE)
1079 assert(!playedMoveCount);
1081 bestValue = oldAlpha;
1084 // Step 21. Update tables
1085 // Update transposition table entry, killers and history
1086 if (!SpNode && !Signals.stop && !thisThread->cutoff_occurred())
1088 move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1089 bt = bestValue <= oldAlpha ? BOUND_UPPER
1090 : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1092 TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);
1094 // Update killers and history for non capture cut-off moves
1095 if ( bestValue >= beta
1096 && !pos.is_capture_or_promotion(move)
1099 if (move != ss->killers[0])
1101 ss->killers[1] = ss->killers[0];
1102 ss->killers[0] = move;
1105 // Increase history value of the cut-off move
1106 Value bonus = Value(int(depth) * int(depth));
1107 H.add(pos.piece_moved(move), to_sq(move), bonus);
1109 // Decrease history of all the other played non-capture moves
1110 for (int i = 0; i < playedMoveCount - 1; i++)
1112 Move m = movesSearched[i];
1113 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1118 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1124 // qsearch() is the quiescence search function, which is called by the main
1125 // search function when the remaining depth is zero (or, to be more precise,
1126 // less than ONE_PLY).
1128 template <NodeType NT>
1129 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1131 const bool PvNode = (NT == PV);
1133 assert(NT == PV || NT == NonPV);
1134 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1135 assert((alpha == beta - 1) || PvNode);
1136 assert(depth <= DEPTH_ZERO);
1139 Move ttMove, move, bestMove;
1140 Value ttValue, bestValue, value, evalMargin, futilityValue, futilityBase;
1141 bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1145 Value oldAlpha = alpha;
1147 ss->currentMove = bestMove = MOVE_NONE;
1148 ss->ply = (ss-1)->ply + 1;
1150 // Check for an instant draw or maximum ply reached
1151 if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1154 // Decide whether or not to include checks, this fixes also the type of
1155 // TT entry depth that we are going to use. Note that in qsearch we use
1156 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1157 inCheck = pos.in_check();
1158 ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1160 // Transposition table lookup. At PV nodes, we don't use the TT for
1161 // pruning, but only for move ordering.
1162 tte = TT.probe(pos.key());
1163 ttMove = (tte ? tte->move() : MOVE_NONE);
1164 ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_ZERO;
1166 if (!PvNode && tte && can_return_tt(tte, ttDepth, ttValue, beta))
1168 ss->currentMove = ttMove; // Can be MOVE_NONE
1172 // Evaluate the position statically
1175 bestValue = futilityBase = -VALUE_INFINITE;
1176 ss->eval = evalMargin = VALUE_NONE;
1177 enoughMaterial = false;
1183 assert(tte->static_value() != VALUE_NONE);
1185 evalMargin = tte->static_value_margin();
1186 ss->eval = bestValue = tte->static_value();
1189 ss->eval = bestValue = evaluate(pos, evalMargin);
1191 // Stand pat. Return immediately if static value is at least beta
1192 if (bestValue >= beta)
1195 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1200 if (PvNode && bestValue > alpha)
1203 futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1204 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1207 // Initialize a MovePicker object for the current position, and prepare
1208 // to search the moves. Because the depth is <= 0 here, only captures,
1209 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1211 MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1214 // Loop through the moves until no moves remain or a beta cutoff occurs
1215 while ( bestValue < beta
1216 && (move = mp.next_move()) != MOVE_NONE)
1218 assert(is_ok(move));
1220 givesCheck = pos.move_gives_check(move, ci);
1228 && type_of(move) != PROMOTION
1229 && !pos.is_passed_pawn_push(move))
1231 futilityValue = futilityBase
1232 + PieceValueEndgame[pos.piece_on(to_sq(move))]
1233 + (type_of(move) == ENPASSANT ? PawnValueEndgame : VALUE_ZERO);
1235 if (futilityValue < beta)
1237 if (futilityValue > bestValue)
1238 bestValue = futilityValue;
1243 // Prune moves with negative or equal SEE
1244 if ( futilityBase < beta
1245 && depth < DEPTH_ZERO
1246 && pos.see(move) <= 0)
1250 // Detect non-capture evasions that are candidate to be pruned
1251 evasionPrunable = !PvNode
1253 && bestValue > VALUE_MATED_IN_MAX_PLY
1254 && !pos.is_capture(move)
1255 && !pos.can_castle(pos.side_to_move());
1257 // Don't search moves with negative SEE values
1259 && (!inCheck || evasionPrunable)
1261 && type_of(move) != PROMOTION
1262 && pos.see_sign(move) < 0)
1265 // Don't search useless checks
1270 && !pos.is_capture_or_promotion(move)
1271 && ss->eval + PawnValueMidgame / 4 < beta
1272 && !check_is_dangerous(pos, move, futilityBase, beta))
1275 // Check for legality only before to do the move
1276 if (!pos.pl_move_is_legal(move, ci.pinned))
1279 ss->currentMove = move;
1281 // Make and search the move
1282 pos.do_move(move, st, ci, givesCheck);
1283 value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1284 pos.undo_move(move);
1286 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1289 if (value > bestValue)
1296 && value < beta) // We want always alpha < beta
1301 // All legal moves have been searched. A special case: If we're in check
1302 // and no legal moves were found, it is checkmate.
1303 if (inCheck && bestValue == -VALUE_INFINITE)
1304 return mated_in(ss->ply); // Plies to mate from the root
1306 // Update transposition table
1307 move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1308 bt = bestValue <= oldAlpha ? BOUND_UPPER
1309 : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1311 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1313 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1319 // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1320 // bestValue is updated only when returning false because in that case move
1323 bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1325 Bitboard b, occ, oldAtt, newAtt, kingAtt;
1326 Square from, to, ksq;
1330 from = from_sq(move);
1332 them = ~pos.side_to_move();
1333 ksq = pos.king_square(them);
1334 kingAtt = pos.attacks_from<KING>(ksq);
1335 pc = pos.piece_moved(move);
1337 occ = pos.pieces() ^ from ^ ksq;
1338 oldAtt = pos.attacks_from(pc, from, occ);
1339 newAtt = pos.attacks_from(pc, to, occ);
1341 // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1342 b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1344 if (!more_than_one(b))
1347 // Rule 2. Queen contact check is very dangerous
1348 if (type_of(pc) == QUEEN && (kingAtt & to))
1351 // Rule 3. Creating new double threats with checks
1352 b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1355 // Note that here we generate illegal "double move"!
1356 if (futilityBase + PieceValueEndgame[pos.piece_on(pop_lsb(&b))] >= beta)
1364 // connected_moves() tests whether two moves are 'connected' in the sense
1365 // that the first move somehow made the second move possible (for instance
1366 // if the moving piece is the same in both moves). The first move is assumed
1367 // to be the move that was made to reach the current position, while the
1368 // second move is assumed to be a move from the current position.
1370 bool connected_moves(const Position& pos, Move m1, Move m2) {
1372 Square f1, t1, f2, t2;
1379 // Case 1: The moving piece is the same in both moves
1385 // Case 2: The destination square for m2 was vacated by m1
1391 // Case 3: Moving through the vacated square
1392 p2 = pos.piece_on(f2);
1393 if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1396 // Case 4: The destination square for m2 is defended by the moving piece in m1
1397 p1 = pos.piece_on(t1);
1398 if (pos.attacks_from(p1, t1) & t2)
1401 // Case 5: Discovered check, checking piece is the piece moved in m1
1402 ksq = pos.king_square(pos.side_to_move());
1403 if ( piece_is_slider(p1)
1404 && (between_bb(t1, ksq) & f2)
1405 && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1412 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1413 // "plies to mate from the current position". Non-mate scores are unchanged.
1414 // The function is called before storing a value to the transposition table.
1416 Value value_to_tt(Value v, int ply) {
1418 if (v >= VALUE_MATE_IN_MAX_PLY)
1421 if (v <= VALUE_MATED_IN_MAX_PLY)
1428 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1429 // from the transposition table (where refers to the plies to mate/be mated
1430 // from current position) to "plies to mate/be mated from the root".
1432 Value value_from_tt(Value v, int ply) {
1434 if (v >= VALUE_MATE_IN_MAX_PLY)
1437 if (v <= VALUE_MATED_IN_MAX_PLY)
1444 // connected_threat() tests whether it is safe to forward prune a move or if
1445 // is somehow connected to the threat move returned by null search.
1447 bool connected_threat(const Position& pos, Move m, Move threat) {
1450 assert(is_ok(threat));
1451 assert(!pos.is_capture_or_promotion(m));
1452 assert(!pos.is_passed_pawn_push(m));
1454 Square mfrom, mto, tfrom, tto;
1458 tfrom = from_sq(threat);
1459 tto = to_sq(threat);
1461 // Case 1: Don't prune moves which move the threatened piece
1465 // Case 2: If the threatened piece has value less than or equal to the
1466 // value of the threatening piece, don't prune moves which defend it.
1467 if ( pos.is_capture(threat)
1468 && ( PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1469 || type_of(pos.piece_on(tfrom)) == KING)
1470 && pos.move_attacks_square(m, tto))
1473 // Case 3: If the moving piece in the threatened move is a slider, don't
1474 // prune safe moves which block its ray.
1475 if ( piece_is_slider(pos.piece_on(tfrom))
1476 && (between_bb(tfrom, tto) & mto)
1477 && pos.see_sign(m) >= 0)
1484 // can_return_tt() returns true if a transposition table score can be used to
1485 // cut-off at a given point in search.
1487 bool can_return_tt(const TTEntry* tte, Depth depth, Value v, Value beta) {
1489 return ( tte->depth() >= depth
1490 || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1491 || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1493 && ( ((tte->type() & BOUND_LOWER) && v >= beta)
1494 || ((tte->type() & BOUND_UPPER) && v < beta));
1498 // refine_eval() returns the transposition table score if possible, otherwise
1499 // falls back on static position evaluation.
1501 Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1505 if ( ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1506 || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1513 // When playing with strength handicap choose best move among the MultiPV set
1514 // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1516 Move do_skill_level() {
1518 assert(MultiPV > 1);
1522 // PRNG sequence should be not deterministic
1523 for (int i = Time::current_time().msec() % 50; i > 0; i--)
1524 rk.rand<unsigned>();
1526 // RootMoves are already sorted by score in descending order
1527 size_t size = std::min(MultiPV, RootMoves.size());
1528 int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1529 int weakness = 120 - 2 * SkillLevel;
1530 int max_s = -VALUE_INFINITE;
1531 Move best = MOVE_NONE;
1533 // Choose best move. For each move score we add two terms both dependent on
1534 // weakness, one deterministic and bigger for weaker moves, and one random,
1535 // then we choose the move with the resulting highest score.
1536 for (size_t i = 0; i < size; i++)
1538 int s = RootMoves[i].score;
1540 // Don't allow crazy blunders even at very low skills
1541 if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1544 // This is our magic formula
1545 s += ( weakness * int(RootMoves[0].score - s)
1546 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1551 best = RootMoves[i].pv[0];
1558 // uci_pv() formats PV information according to UCI protocol. UCI requires
1559 // to send all the PV lines also if are still to be searched and so refer to
1560 // the previous search score.
1562 string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1564 std::stringstream s;
1565 int t = SearchTime.elapsed();
1568 for (int i = 0; i < Threads.size(); i++)
1569 if (Threads[i].maxPly > selDepth)
1570 selDepth = Threads[i].maxPly;
1572 for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1574 bool updated = (i <= PVIdx);
1576 if (depth == 1 && !updated)
1579 int d = (updated ? depth : depth - 1);
1580 Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1582 if (s.rdbuf()->in_avail())
1585 s << "info depth " << d
1586 << " seldepth " << selDepth
1587 << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1588 << " nodes " << pos.nodes_searched()
1589 << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1591 << " multipv " << i + 1
1594 for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1595 s << " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1604 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1605 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1606 /// allow to always have a ponder move even when we fail high at root, and a
1607 /// long PV to print that is important for position analysis.
1609 void RootMove::extract_pv_from_tt(Position& pos) {
1611 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1616 assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1620 pos.do_move(m, *st++);
1622 while ( (tte = TT.probe(pos.key())) != NULL
1623 && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1624 && pos.is_pseudo_legal(m)
1625 && pos.pl_move_is_legal(m, pos.pinned_pieces())
1627 && (!pos.is_draw<false>() || ply < 2))
1630 pos.do_move(m, *st++);
1633 pv.push_back(MOVE_NONE);
1635 do pos.undo_move(pv[--ply]); while (ply);
1639 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1640 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1641 /// first, even if the old TT entries have been overwritten.
1643 void RootMove::insert_pv_in_tt(Position& pos) {
1645 StateInfo state[MAX_PLY_PLUS_2], *st = state;
1648 Value v, m = VALUE_NONE;
1651 assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1657 // Don't overwrite existing correct entries
1658 if (!tte || tte->move() != pv[ply])
1660 v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1661 TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1663 pos.do_move(pv[ply], *st++);
1665 } while (pv[++ply] != MOVE_NONE);
1667 do pos.undo_move(pv[--ply]); while (ply);
1671 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1672 /// The parameter 'master_sp', if non-NULL, is a pointer to an active SplitPoint
1673 /// object for which the thread is the master.
1675 void Thread::idle_loop(SplitPoint* sp_master) {
1677 // If this thread is the master of a split point and all slaves have
1678 // finished their work at this split point, return from the idle loop.
1679 while (!sp_master || sp_master->slavesMask)
1681 // If we are not searching, wait for a condition to be signaled
1682 // instead of wasting CPU time polling for work.
1685 || (!is_searching && Threads.use_sleeping_threads()))
1693 // Grab the lock to avoid races with Thread::wake_up()
1694 lock_grab(sleepLock);
1696 // If we are master and all slaves have finished don't go to sleep
1697 if (sp_master && !sp_master->slavesMask)
1699 lock_release(sleepLock);
1703 // Do sleep after retesting sleep conditions under lock protection, in
1704 // particular we need to avoid a deadlock in case a master thread has,
1705 // in the meanwhile, allocated us and sent the wake_up() call before we
1706 // had the chance to grab the lock.
1707 if (do_sleep || !is_searching)
1708 cond_wait(sleepCond, sleepLock);
1710 lock_release(sleepLock);
1713 // If this thread has been assigned work, launch a search
1716 assert(!do_sleep && !do_exit);
1718 lock_grab(Threads.splitLock);
1720 assert(is_searching);
1721 SplitPoint* sp = curSplitPoint;
1723 lock_release(Threads.splitLock);
1725 Stack ss[MAX_PLY_PLUS_2];
1726 Position pos(*sp->pos, this);
1728 memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1731 lock_grab(sp->lock);
1733 if (sp->nodeType == Root)
1734 search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1735 else if (sp->nodeType == PV)
1736 search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1737 else if (sp->nodeType == NonPV)
1738 search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1742 assert(is_searching);
1744 is_searching = false;
1745 sp->slavesMask &= ~(1ULL << idx);
1746 sp->nodes += pos.nodes_searched();
1748 // Wake up master thread so to allow it to return from the idle loop in
1749 // case we are the last slave of the split point.
1750 if ( Threads.use_sleeping_threads()
1751 && this != sp->master
1752 && !sp->master->is_searching)
1753 sp->master->wake_up();
1755 // After releasing the lock we cannot access anymore any SplitPoint
1756 // related data in a safe way becuase it could have been released under
1757 // our feet by the sp master. Also accessing other Thread objects is
1758 // unsafe because if we are exiting there is a chance are already freed.
1759 lock_release(sp->lock);
1765 /// check_time() is called by the timer thread when the timer triggers. It is
1766 /// used to print debug info and, more important, to detect when we are out of
1767 /// available time and so stop the search.
1771 static Time lastInfoTime = Time::current_time();
1773 if (lastInfoTime.elapsed() >= 1000)
1775 lastInfoTime.restart();
1782 int e = SearchTime.elapsed();
1783 bool stillAtFirstMove = Signals.firstRootMove
1784 && !Signals.failedLowAtRoot
1785 && e > TimeMgr.available_time();
1787 bool noMoreTime = e > TimeMgr.maximum_time() - 2 * TimerResolution
1788 || stillAtFirstMove;
1790 if ( (Limits.use_time_management() && noMoreTime)
1791 || (Limits.movetime && e >= Limits.movetime))
1792 Signals.stop = true;