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/>.
43 #include "ucioption.h"
49 //// Local definitions
55 enum NodeType { NonPV, PV };
57 // ThreadsManager class is used to handle all the threads related stuff in search,
58 // init, starting, parking and, the most important, launching a slave thread at a
59 // split point are what this class does. All the access to shared thread data is
60 // done through this class, so that we avoid using global variables instead.
62 class ThreadsManager {
63 /* As long as the single ThreadsManager object is defined as a global we don't
64 need to explicitly initialize to zero its data members because variables with
65 static storage duration are automatically set to zero before enter main()
71 int active_threads() const { return ActiveThreads; }
72 void set_active_threads(int newActiveThreads) { ActiveThreads = newActiveThreads; }
73 void incrementNodeCounter(int threadID) { threads[threadID].nodes++; }
74 void incrementBetaCounter(Color us, Depth d, int threadID) { threads[threadID].betaCutOffs[us] += unsigned(d); }
76 void resetNodeCounters();
77 void resetBetaCounters();
78 int64_t nodes_searched() const;
79 void get_beta_counters(Color us, int64_t& our, int64_t& their) const;
80 bool available_thread_exists(int master) const;
81 bool thread_is_available(int slave, int master) const;
82 bool thread_should_stop(int threadID) const;
83 void wake_sleeping_threads();
84 void put_threads_to_sleep();
85 void idle_loop(int threadID, SplitPoint* sp);
86 bool split(const Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
87 Depth depth, bool mateThreat, int* moves, MovePicker* mp, int master, bool pvNode);
93 volatile bool AllThreadsShouldExit, AllThreadsShouldSleep;
94 Thread threads[MAX_THREADS];
95 SplitPoint SplitPointStack[MAX_THREADS][ACTIVE_SPLIT_POINTS_MAX];
97 Lock MPLock, WaitLock;
99 #if !defined(_MSC_VER)
100 pthread_cond_t WaitCond;
102 HANDLE SitIdleEvent[MAX_THREADS];
108 // RootMove struct is used for moves at the root at the tree. For each
109 // root move, we store a score, a node count, and a PV (really a refutation
110 // in the case of moves which fail low).
114 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
116 // RootMove::operator<() is the comparison function used when
117 // sorting the moves. A move m1 is considered to be better
118 // than a move m2 if it has a higher score, or if the moves
119 // have equal score but m1 has the higher node count.
120 bool operator<(const RootMove& m) const {
122 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
127 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
128 Move pv[PLY_MAX_PLUS_2];
132 // The RootMoveList class is essentially an array of RootMove objects, with
133 // a handful of methods for accessing the data in the individual moves.
138 RootMoveList(Position& pos, Move searchMoves[]);
140 int move_count() const { return count; }
141 Move get_move(int moveNum) const { return moves[moveNum].move; }
142 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
143 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
144 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
145 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
147 void set_move_nodes(int moveNum, int64_t nodes);
148 void set_beta_counters(int moveNum, int64_t our, int64_t their);
149 void set_move_pv(int moveNum, const Move pv[]);
151 void sort_multipv(int n);
154 static const int MaxRootMoves = 500;
155 RootMove moves[MaxRootMoves];
164 // Maximum depth for razoring
165 const Depth RazorDepth = 4 * OnePly;
167 // Dynamic razoring margin based on depth
168 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
170 // Step 8. Null move search with verification search
172 // Null move margin. A null move search will not be done if the static
173 // evaluation of the position is more than NullMoveMargin below beta.
174 const Value NullMoveMargin = Value(0x200);
176 // Maximum depth for use of dynamic threat detection when null move fails low
177 const Depth ThreatDepth = 5 * OnePly;
179 // Step 9. Internal iterative deepening
181 // Minimum depth for use of internal iterative deepening
182 const Depth IIDDepthAtPVNodes = 5 * OnePly;
183 const Depth IIDDepthAtNonPVNodes = 8 * OnePly;
185 // At Non-PV nodes we do an internal iterative deepening search
186 // when the static evaluation is at most IIDMargin below beta.
187 const Value IIDMargin = Value(0x100);
189 // Step 11. Decide the new search depth
191 // Extensions. Configurable UCI options
192 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
193 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
194 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
196 // Minimum depth for use of singular extension
197 const Depth SingularExtensionDepth[2] = { 8 * OnePly /* non-PV */, 6 * OnePly /* PV */};
199 // If the TT move is at least SingularExtensionMargin better then the
200 // remaining ones we will extend it.
201 const Value SingularExtensionMargin = Value(0x20);
203 // Step 12. Futility pruning
205 // Futility margin for quiescence search
206 const Value FutilityMarginQS = Value(0x80);
208 // Futility lookup tables (initialized at startup) and their getter functions
209 int32_t FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
210 int FutilityMoveCountArray[32]; // [depth]
212 inline Value futility_margin(Depth d, int mn) { return Value(d < 7 * OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
213 inline int futility_move_count(Depth d) { return d < 16 * OnePly ? FutilityMoveCountArray[d] : 512; }
215 // Step 14. Reduced search
217 // Reduction lookup tables (initialized at startup) and their getter functions
218 int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
220 template <NodeType PV>
221 inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / 2, 63)][Min(mn, 63)]; }
223 // Common adjustments
225 // Search depth at iteration 1
226 const Depth InitialDepth = OnePly;
228 // Easy move margin. An easy move candidate must be at least this much
229 // better than the second best move.
230 const Value EasyMoveMargin = Value(0x200);
232 // Last seconds noise filtering (LSN)
233 const bool UseLSNFiltering = true;
234 const int LSNTime = 4000; // In milliseconds
235 const Value LSNValue = value_from_centipawns(200);
236 bool loseOnTime = false;
244 // Scores and number of times the best move changed for each iteration
245 Value ValueByIteration[PLY_MAX_PLUS_2];
246 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
248 // Search window management
254 // Time managment variables
255 int SearchStartTime, MaxNodes, MaxDepth, MaxSearchTime;
256 int AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
257 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
258 bool FirstRootMove, AbortSearch, Quit, AspirationFailLow;
262 std::ofstream LogFile;
264 // Multi-threads related variables
265 Depth MinimumSplitDepth;
266 int MaxThreadsPerSplitPoint;
269 // Node counters, used only by thread[0] but try to keep in different cache
270 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
272 int NodesBetweenPolls = 30000;
279 Value id_loop(const Position& pos, Move searchMoves[]);
280 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr);
282 template <NodeType PvNode>
283 Value search(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
285 template <NodeType PvNode>
286 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous);
288 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
289 void sp_search(SplitPoint* sp, int threadID);
290 void sp_search_pv(SplitPoint* sp, int threadID);
291 void init_node(SearchStack ss[], int ply, int threadID);
292 void update_pv(SearchStack ss[], int ply);
293 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
294 bool connected_moves(const Position& pos, Move m1, Move m2);
295 bool value_is_mate(Value value);
296 bool move_is_killer(Move m, const SearchStack& ss);
297 bool ok_to_do_nullmove(const Position& pos);
298 bool ok_to_prune(const Position& pos, Move m, Move threat);
299 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
300 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
301 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
302 void update_killers(Move m, SearchStack& ss);
303 void update_gains(const Position& pos, Move move, Value before, Value after);
305 int current_search_time();
309 void wait_for_stop_or_ponderhit();
310 void init_ss_array(SearchStack ss[]);
311 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value);
313 #if !defined(_MSC_VER)
314 void *init_thread(void *threadID);
316 DWORD WINAPI init_thread(LPVOID threadID);
326 /// init_threads(), exit_threads() and nodes_searched() are helpers to
327 /// give accessibility to some TM methods from outside of current file.
329 void init_threads() { TM.init_threads(); }
330 void exit_threads() { TM.exit_threads(); }
331 int64_t nodes_searched() { return TM.nodes_searched(); }
334 /// perft() is our utility to verify move generation is bug free. All the legal
335 /// moves up to given depth are generated and counted and the sum returned.
337 int perft(Position& pos, Depth depth)
342 MovePicker mp(pos, MOVE_NONE, depth, H);
344 // If we are at the last ply we don't need to do and undo
345 // the moves, just to count them.
346 if (depth <= OnePly) // Replace with '<' to test also qsearch
348 while (mp.get_next_move()) sum++;
352 // Loop through all legal moves
354 while ((move = mp.get_next_move()) != MOVE_NONE)
356 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
357 sum += perft(pos, depth - OnePly);
364 /// think() is the external interface to Stockfish's search, and is called when
365 /// the program receives the UCI 'go' command. It initializes various
366 /// search-related global variables, and calls root_search(). It returns false
367 /// when a quit command is received during the search.
369 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
370 int time[], int increment[], int movesToGo, int maxDepth,
371 int maxNodes, int maxTime, Move searchMoves[]) {
373 // Initialize global search variables
374 StopOnPonderhit = AbortSearch = Quit = AspirationFailLow = false;
375 MaxSearchTime = AbsoluteMaxSearchTime = ExtraSearchTime = 0;
377 TM.resetNodeCounters();
378 SearchStartTime = get_system_time();
379 ExactMaxTime = maxTime;
382 InfiniteSearch = infinite;
383 PonderSearch = ponder;
384 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
386 // Look for a book move, only during games, not tests
387 if (UseTimeManagement && get_option_value_bool("OwnBook"))
389 if (get_option_value_string("Book File") != OpeningBook.file_name())
390 OpeningBook.open(get_option_value_string("Book File"));
392 Move bookMove = OpeningBook.get_move(pos, get_option_value_bool("Best Book Move"));
393 if (bookMove != MOVE_NONE)
396 wait_for_stop_or_ponderhit();
398 cout << "bestmove " << bookMove << endl;
403 // Reset loseOnTime flag at the beginning of a new game
404 if (button_was_pressed("New Game"))
407 // Read UCI option values
408 TT.set_size(get_option_value_int("Hash"));
409 if (button_was_pressed("Clear Hash"))
412 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
413 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
414 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
415 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
416 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
417 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
418 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
419 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
420 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
421 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
422 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
423 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
425 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
426 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
427 MultiPV = get_option_value_int("MultiPV");
428 Chess960 = get_option_value_bool("UCI_Chess960");
429 UseLogFile = get_option_value_bool("Use Search Log");
432 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
434 read_weights(pos.side_to_move());
436 // Set the number of active threads
437 int newActiveThreads = get_option_value_int("Threads");
438 if (newActiveThreads != TM.active_threads())
440 TM.set_active_threads(newActiveThreads);
441 init_eval(TM.active_threads());
444 // Wake up sleeping threads
445 TM.wake_sleeping_threads();
448 int myTime = time[side_to_move];
449 int myIncrement = increment[side_to_move];
450 if (UseTimeManagement)
452 if (!movesToGo) // Sudden death time control
456 MaxSearchTime = myTime / 30 + myIncrement;
457 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
459 else // Blitz game without increment
461 MaxSearchTime = myTime / 30;
462 AbsoluteMaxSearchTime = myTime / 8;
465 else // (x moves) / (y minutes)
469 MaxSearchTime = myTime / 2;
470 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
474 MaxSearchTime = myTime / Min(movesToGo, 20);
475 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
479 if (get_option_value_bool("Ponder"))
481 MaxSearchTime += MaxSearchTime / 4;
482 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
486 // Set best NodesBetweenPolls interval to avoid lagging under
487 // heavy time pressure.
489 NodesBetweenPolls = Min(MaxNodes, 30000);
490 else if (myTime && myTime < 1000)
491 NodesBetweenPolls = 1000;
492 else if (myTime && myTime < 5000)
493 NodesBetweenPolls = 5000;
495 NodesBetweenPolls = 30000;
497 // Write search information to log file
499 LogFile << "Searching: " << pos.to_fen() << endl
500 << "infinite: " << infinite
501 << " ponder: " << ponder
502 << " time: " << myTime
503 << " increment: " << myIncrement
504 << " moves to go: " << movesToGo << endl;
506 // LSN filtering. Used only for developing purposes, disabled by default
510 // Step 2. If after last move we decided to lose on time, do it now!
511 while (SearchStartTime + myTime + 1000 > get_system_time())
515 // We're ready to start thinking. Call the iterative deepening loop function
516 Value v = id_loop(pos, searchMoves);
520 // Step 1. If this is sudden death game and our position is hopeless,
521 // decide to lose on time.
522 if ( !loseOnTime // If we already lost on time, go to step 3.
532 // Step 3. Now after stepping over the time limit, reset flag for next match.
540 TM.put_threads_to_sleep();
546 /// init_search() is called during startup. It initializes various lookup tables
550 // Init our reduction lookup tables
551 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
552 for (int j = 1; j < 64; j++) // j == moveNumber
554 double pvRed = log(double(i)) * log(double(j)) / 3.0;
555 double nonPVRed = log(double(i)) * log(double(j)) / 1.5;
556 ReductionMatrix[PV][i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
557 ReductionMatrix[NonPV][i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
560 // Init futility margins array
561 for (int i = 0; i < 16; i++) // i == depth (OnePly = 2)
562 for (int j = 0; j < 64; j++) // j == moveNumber
564 // FIXME: test using log instead of BSR
565 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j + 45;
568 // Init futility move count array
569 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
570 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
574 // SearchStack::init() initializes a search stack. Used at the beginning of a
575 // new search from the root.
576 void SearchStack::init(int ply) {
578 pv[ply] = pv[ply + 1] = MOVE_NONE;
579 currentMove = threatMove = MOVE_NONE;
580 reduction = Depth(0);
584 void SearchStack::initKillers() {
586 mateKiller = MOVE_NONE;
587 for (int i = 0; i < KILLER_MAX; i++)
588 killers[i] = MOVE_NONE;
593 // id_loop() is the main iterative deepening loop. It calls root_search
594 // repeatedly with increasing depth until the allocated thinking time has
595 // been consumed, the user stops the search, or the maximum search depth is
598 Value id_loop(const Position& pos, Move searchMoves[]) {
601 SearchStack ss[PLY_MAX_PLUS_2];
602 Move EasyMove = MOVE_NONE;
603 Value value, alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
605 // Moves to search are verified, copied, scored and sorted
606 RootMoveList rml(p, searchMoves);
608 // Handle special case of searching on a mate/stale position
609 if (rml.move_count() == 0)
612 wait_for_stop_or_ponderhit();
614 return pos.is_check() ? -VALUE_MATE : VALUE_DRAW;
617 // Print RootMoveList startup scoring to the standard output,
618 // so to output information also for iteration 1.
619 cout << "info depth " << 1
620 << "\ninfo depth " << 1
621 << " score " << value_to_string(rml.get_move_score(0))
622 << " time " << current_search_time()
623 << " nodes " << TM.nodes_searched()
625 << " pv " << rml.get_move(0) << "\n";
631 ValueByIteration[1] = rml.get_move_score(0);
634 // Is one move significantly better than others after initial scoring ?
635 if ( rml.move_count() == 1
636 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
637 EasyMove = rml.get_move(0);
639 // Iterative deepening loop
640 while (Iteration < PLY_MAX)
642 // Initialize iteration
644 BestMoveChangesByIteration[Iteration] = 0;
646 cout << "info depth " << Iteration << endl;
648 // Calculate dynamic aspiration window based on previous iterations
649 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
651 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
652 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
654 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
655 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
657 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
658 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
661 // Search to the current depth, rml is updated and sorted, alpha and beta could change
662 value = root_search(p, ss, rml, &alpha, &beta);
664 // Write PV to transposition table, in case the relevant entries have
665 // been overwritten during the search.
666 TT.insert_pv(p, ss[0].pv);
669 break; // Value cannot be trusted. Break out immediately!
671 //Save info about search result
672 ValueByIteration[Iteration] = value;
674 // Drop the easy move if differs from the new best move
675 if (ss[0].pv[0] != EasyMove)
676 EasyMove = MOVE_NONE;
678 if (UseTimeManagement)
681 bool stopSearch = false;
683 // Stop search early if there is only a single legal move,
684 // we search up to Iteration 6 anyway to get a proper score.
685 if (Iteration >= 6 && rml.move_count() == 1)
688 // Stop search early when the last two iterations returned a mate score
690 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
691 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
694 // Stop search early if one move seems to be much better than the others
695 int64_t nodes = TM.nodes_searched();
697 && EasyMove == ss[0].pv[0]
698 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
699 && current_search_time() > MaxSearchTime / 16)
700 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
701 && current_search_time() > MaxSearchTime / 32)))
704 // Add some extra time if the best move has changed during the last two iterations
705 if (Iteration > 5 && Iteration <= 50)
706 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
707 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
709 // Stop search if most of MaxSearchTime is consumed at the end of the
710 // iteration. We probably don't have enough time to search the first
711 // move at the next iteration anyway.
712 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
718 StopOnPonderhit = true;
724 if (MaxDepth && Iteration >= MaxDepth)
728 // If we are pondering or in infinite search, we shouldn't print the
729 // best move before we are told to do so.
730 if (!AbortSearch && (PonderSearch || InfiniteSearch))
731 wait_for_stop_or_ponderhit();
733 // Print final search statistics
734 cout << "info nodes " << TM.nodes_searched()
736 << " time " << current_search_time()
737 << " hashfull " << TT.full() << endl;
739 // Print the best move and the ponder move to the standard output
740 if (ss[0].pv[0] == MOVE_NONE)
742 ss[0].pv[0] = rml.get_move(0);
743 ss[0].pv[1] = MOVE_NONE;
746 assert(ss[0].pv[0] != MOVE_NONE);
748 cout << "bestmove " << ss[0].pv[0];
750 if (ss[0].pv[1] != MOVE_NONE)
751 cout << " ponder " << ss[0].pv[1];
758 dbg_print_mean(LogFile);
760 if (dbg_show_hit_rate)
761 dbg_print_hit_rate(LogFile);
763 LogFile << "\nNodes: " << TM.nodes_searched()
764 << "\nNodes/second: " << nps()
765 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
768 p.do_move(ss[0].pv[0], st);
769 LogFile << "\nPonder move: "
770 << move_to_san(p, ss[0].pv[1]) // Works also with MOVE_NONE
773 return rml.get_move_score(0);
777 // root_search() is the function which searches the root node. It is
778 // similar to search_pv except that it uses a different move ordering
779 // scheme, prints some information to the standard output and handles
780 // the fail low/high loops.
782 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr) {
789 Depth depth, ext, newDepth;
790 Value value, alpha, beta;
791 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
792 int researchCountFH, researchCountFL;
794 researchCountFH = researchCountFL = 0;
797 isCheck = pos.is_check();
799 // Step 1. Initialize node and poll (omitted at root, but I can see no good reason for this, FIXME)
800 // Step 2. Check for aborted search (omitted at root, because we do not initialize root node)
801 // Step 3. Mate distance pruning (omitted at root)
802 // Step 4. Transposition table lookup (omitted at root)
804 // Step 5. Evaluate the position statically
805 // At root we do this only to get reference value for child nodes
807 ss[0].eval = evaluate(pos, ei, 0);
809 ss[0].eval = VALUE_NONE; // HACK because we do not initialize root node
811 // Step 6. Razoring (omitted at root)
812 // Step 7. Static null move pruning (omitted at root)
813 // Step 8. Null move search with verification search (omitted at root)
814 // Step 9. Internal iterative deepening (omitted at root)
816 // Step extra. Fail low loop
817 // We start with small aspiration window and in case of fail low, we research
818 // with bigger window until we are not failing low anymore.
821 // Sort the moves before to (re)search
824 // Step 10. Loop through all moves in the root move list
825 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
827 // This is used by time management
828 FirstRootMove = (i == 0);
830 // Save the current node count before the move is searched
831 nodes = TM.nodes_searched();
833 // Reset beta cut-off counters
834 TM.resetBetaCounters();
836 // Pick the next root move, and print the move and the move number to
837 // the standard output.
838 move = ss[0].currentMove = rml.get_move(i);
840 if (current_search_time() >= 1000)
841 cout << "info currmove " << move
842 << " currmovenumber " << i + 1 << endl;
844 moveIsCheck = pos.move_is_check(move);
845 captureOrPromotion = pos.move_is_capture_or_promotion(move);
847 // Step 11. Decide the new search depth
848 depth = (Iteration - 2) * OnePly + InitialDepth;
849 ext = extension<PV>(pos, move, captureOrPromotion, moveIsCheck, false, false, &dangerous);
850 newDepth = depth + ext;
852 // Step 12. Futility pruning (omitted at root)
854 // Step extra. Fail high loop
855 // If move fails high, we research with bigger window until we are not failing
857 value = - VALUE_INFINITE;
861 // Step 13. Make the move
862 pos.do_move(move, st, ci, moveIsCheck);
864 // Step extra. pv search
865 // We do pv search for first moves (i < MultiPV)
866 // and for fail high research (value > alpha)
867 if (i < MultiPV || value > alpha)
869 // Aspiration window is disabled in multi-pv case
871 alpha = -VALUE_INFINITE;
873 // Full depth PV search, done on first move or after a fail high
874 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, 1, false, 0);
878 // Step 14. Reduced search
879 // if the move fails high will be re-searched at full depth
880 bool doFullDepthSearch = true;
882 if ( depth >= 3 * OnePly
884 && !captureOrPromotion
885 && !move_is_castle(move))
887 ss[0].reduction = reduction<PV>(depth, i - MultiPV + 2);
890 // Reduced depth non-pv search using alpha as upperbound
891 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth-ss[0].reduction, 1, true, 0);
892 doFullDepthSearch = (value > alpha);
896 // Step 15. Full depth search
897 if (doFullDepthSearch)
899 // Full depth non-pv search using alpha as upperbound
900 ss[0].reduction = Depth(0);
901 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth, 1, true, 0);
903 // If we are above alpha then research at same depth but as PV
904 // to get a correct score or eventually a fail high above beta.
906 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, 1, false, 0);
910 // Step 16. Undo move
913 // Can we exit fail high loop ?
914 if (AbortSearch || value < beta)
917 // We are failing high and going to do a research. It's important to update
918 // the score before research in case we run out of time while researching.
919 rml.set_move_score(i, value);
921 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
922 rml.set_move_pv(i, ss[0].pv);
924 // Print information to the standard output
925 print_pv_info(pos, ss, alpha, beta, value);
927 // Prepare for a research after a fail high, each time with a wider window
928 *betaPtr = beta = Min(beta + AspirationDelta * (1 << researchCountFH), VALUE_INFINITE);
931 } // End of fail high loop
933 // Finished searching the move. If AbortSearch is true, the search
934 // was aborted because the user interrupted the search or because we
935 // ran out of time. In this case, the return value of the search cannot
936 // be trusted, and we break out of the loop without updating the best
941 // Remember beta-cutoff and searched nodes counts for this move. The
942 // info is used to sort the root moves for the next iteration.
944 TM.get_beta_counters(pos.side_to_move(), our, their);
945 rml.set_beta_counters(i, our, their);
946 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
948 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
949 assert(value < beta);
951 // Step 17. Check for new best move
952 if (value <= alpha && i >= MultiPV)
953 rml.set_move_score(i, -VALUE_INFINITE);
956 // PV move or new best move!
959 rml.set_move_score(i, value);
961 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
962 rml.set_move_pv(i, ss[0].pv);
966 // We record how often the best move has been changed in each
967 // iteration. This information is used for time managment: When
968 // the best move changes frequently, we allocate some more time.
970 BestMoveChangesByIteration[Iteration]++;
972 // Print information to the standard output
973 print_pv_info(pos, ss, alpha, beta, value);
975 // Raise alpha to setup proper non-pv search upper bound
982 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
984 cout << "info multipv " << j + 1
985 << " score " << value_to_string(rml.get_move_score(j))
986 << " depth " << (j <= i ? Iteration : Iteration - 1)
987 << " time " << current_search_time()
988 << " nodes " << TM.nodes_searched()
992 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
993 cout << rml.get_move_pv(j, k) << " ";
997 alpha = rml.get_move_score(Min(i, MultiPV - 1));
999 } // PV move or new best move
1001 assert(alpha >= *alphaPtr);
1003 AspirationFailLow = (alpha == *alphaPtr);
1005 if (AspirationFailLow && StopOnPonderhit)
1006 StopOnPonderhit = false;
1009 // Can we exit fail low loop ?
1010 if (AbortSearch || !AspirationFailLow)
1013 // Prepare for a research after a fail low, each time with a wider window
1014 *alphaPtr = alpha = Max(alpha - AspirationDelta * (1 << researchCountFL), -VALUE_INFINITE);
1019 // Sort the moves before to return
1026 // search_pv() is the main search function for PV nodes.
1028 template <NodeType PvNode>
1029 Value search(Position& pos, SearchStack ss[], Value alpha, Value beta,
1030 Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove) {
1032 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1033 assert(beta > alpha && beta <= VALUE_INFINITE);
1034 assert(ply >= 0 && ply < PLY_MAX);
1035 assert(threadID >= 0 && threadID < TM.active_threads());
1037 Move movesSearched[256];
1042 Depth ext, newDepth;
1043 Value bestValue, value, oldAlpha;
1044 Value refinedValue, nullValue, futilityValueScaled; // Non-PV specific
1045 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1046 bool mateThreat = false;
1048 refinedValue = bestValue = value = -VALUE_INFINITE;
1052 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1054 // Step 1. Initialize node and poll
1055 // Polling can abort search.
1056 init_node(ss, ply, threadID);
1058 // Step 2. Check for aborted search and immediate draw
1059 if (AbortSearch || TM.thread_should_stop(threadID))
1062 if (pos.is_draw() || ply >= PLY_MAX - 1)
1065 // Step 3. Mate distance pruning
1066 alpha = Max(value_mated_in(ply), alpha);
1067 beta = Min(value_mate_in(ply+1), beta);
1071 // Step 4. Transposition table lookup
1073 // We don't want the score of a partial search to overwrite a previous full search
1074 // TT value, so we use a different position key in case of an excluded move exists.
1075 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1077 tte = TT.retrieve(posKey);
1078 ttMove = (tte ? tte->move() : MOVE_NONE);
1080 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1081 // This is to avoid problems in the following areas:
1083 // * Repetition draw detection
1084 // * Fifty move rule detection
1085 // * Searching for a mate
1086 // * Printing of full PV line
1088 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1090 // Refresh tte entry to avoid aging
1091 TT.store(posKey, tte->value(), tte->type(), tte->depth(), ttMove);
1093 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1094 return value_from_tt(tte->value(), ply);
1097 // Step 5. Evaluate the position statically
1098 // At PV nodes we do this only to update gain statistics
1099 isCheck = pos.is_check();
1102 if (!PvNode && tte && (tte->type() & VALUE_TYPE_EVAL))
1103 ss[ply].eval = value_from_tt(tte->value(), ply);
1105 ss[ply].eval = evaluate(pos, ei, threadID);
1107 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1108 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1111 // Step 6. Razoring (is omitted in PV nodes)
1113 && refinedValue < beta - razor_margin(depth)
1114 && ttMove == MOVE_NONE
1115 && ss[ply - 1].currentMove != MOVE_NULL
1116 && depth < RazorDepth
1118 && !value_is_mate(beta)
1119 && !pos.has_pawn_on_7th(pos.side_to_move()))
1121 Value rbeta = beta - razor_margin(depth);
1122 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1124 // Logically we should return (v + razor_margin(depth)), but
1125 // surprisingly this did slightly weaker in tests.
1129 // Step 7. Static null move pruning (is omitted in PV nodes)
1130 // We're betting that the opponent doesn't have a move that will reduce
1131 // the score by more than futility_margin(depth) if we do a null move.
1134 && depth < RazorDepth
1136 && !value_is_mate(beta)
1137 && ok_to_do_nullmove(pos)
1138 && refinedValue >= beta + futility_margin(depth, 0))
1139 return refinedValue - futility_margin(depth, 0);
1141 // Step 8. Null move search with verification search (is omitted in PV nodes)
1142 // When we jump directly to qsearch() we do a null move only if static value is
1143 // at least beta. Otherwise we do a null move if static value is not more than
1144 // NullMoveMargin under beta.
1149 && !value_is_mate(beta)
1150 && ok_to_do_nullmove(pos)
1151 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1153 ss[ply].currentMove = MOVE_NULL;
1155 // Null move dynamic reduction based on depth
1156 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1158 // Null move dynamic reduction based on value
1159 if (refinedValue - beta > PawnValueMidgame)
1162 pos.do_null_move(st);
1164 nullValue = -search<NonPV>(pos, ss, -beta, -alpha, depth-R*OnePly, ply+1, false, threadID);
1166 pos.undo_null_move();
1168 if (nullValue >= beta)
1170 // Do not return unproven mate scores
1171 if (nullValue >= value_mate_in(PLY_MAX))
1174 if (depth < 6 * OnePly)
1177 // Do zugzwang verification search
1178 Value v = search<NonPV>(pos, ss, alpha, beta, depth-5*OnePly, ply, false, threadID);
1182 // The null move failed low, which means that we may be faced with
1183 // some kind of threat. If the previous move was reduced, check if
1184 // the move that refuted the null move was somehow connected to the
1185 // move which was reduced. If a connection is found, return a fail
1186 // low score (which will cause the reduced move to fail high in the
1187 // parent node, which will trigger a re-search with full depth).
1188 if (nullValue == value_mated_in(ply + 2))
1191 ss[ply].threatMove = ss[ply + 1].currentMove;
1192 if ( depth < ThreatDepth
1193 && ss[ply - 1].reduction
1194 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1199 // Step 9. Internal iterative deepening
1200 // We have different rules for PV nodes and non-pv nodes
1202 && depth >= IIDDepthAtPVNodes
1203 && ttMove == MOVE_NONE)
1205 search<PV>(pos, ss, alpha, beta, depth-2*OnePly, ply, false, threadID);
1206 ttMove = ss[ply].pv[ply];
1207 tte = TT.retrieve(posKey);
1211 && depth >= IIDDepthAtNonPVNodes
1212 && ttMove == MOVE_NONE
1214 && ss[ply].eval >= beta - IIDMargin)
1216 search<NonPV>(pos, ss, alpha, beta, depth/2, ply, false, threadID);
1217 ttMove = ss[ply].pv[ply];
1218 tte = TT.retrieve(posKey);
1221 // Expensive mate threat detection (only for PV nodes)
1223 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1225 // Initialize a MovePicker object for the current position
1226 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply], (PvNode ? -VALUE_INFINITE : beta));
1229 // Step 10. Loop through moves
1230 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1231 while ( bestValue < beta
1232 && (move = mp.get_next_move()) != MOVE_NONE
1233 && !TM.thread_should_stop(threadID))
1235 assert(move_is_ok(move));
1237 if (move == excludedMove)
1240 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1241 moveIsCheck = pos.move_is_check(move, ci);
1242 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1244 // Step 11. Decide the new search depth
1245 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1247 // Singular extension search. We extend the TT move if its value is much better than
1248 // its siblings. To verify this we do a reduced search on all the other moves but the
1249 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1250 if ( depth >= SingularExtensionDepth[PvNode]
1252 && move == tte->move()
1253 && !excludedMove // Do not allow recursive singular extension search
1255 && is_lower_bound(tte->type())
1256 && tte->depth() >= depth - 3 * OnePly)
1258 Value ttValue = value_from_tt(tte->value(), ply);
1260 if (abs(ttValue) < VALUE_KNOWN_WIN)
1262 Value excValue = search<NonPV>(pos, ss, ttValue - SingularExtensionMargin - 1, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1264 if (excValue < ttValue - SingularExtensionMargin)
1269 newDepth = depth - OnePly + ext;
1271 // Update current move (this must be done after singular extension search)
1272 movesSearched[moveCount++] = ss[ply].currentMove = move;
1274 // Step 12. Futility pruning (is omitted in PV nodes)
1278 && !captureOrPromotion
1279 && !move_is_castle(move)
1282 // Move count based pruning
1283 if ( moveCount >= futility_move_count(depth)
1284 && ok_to_prune(pos, move, ss[ply].threatMove)
1285 && bestValue > value_mated_in(PLY_MAX))
1288 // Value based pruning
1289 Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount); // We illogically ignore reduction condition depth >= 3*OnePly
1290 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1291 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1293 if (futilityValueScaled < beta)
1295 if (futilityValueScaled > bestValue)
1296 bestValue = futilityValueScaled;
1301 // Step 13. Make the move
1302 pos.do_move(move, st, ci, moveIsCheck);
1304 // Step extra. pv search (only in PV nodes)
1305 // The first move in list is the expected PV
1306 if (PvNode && moveCount == 1)
1307 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, ply+1, false, threadID);
1310 // Step 14. Reduced search
1311 // if the move fails high will be re-searched at full depth.
1312 bool doFullDepthSearch = true;
1314 if ( depth >= 3 * OnePly
1316 && !captureOrPromotion
1317 && !move_is_castle(move)
1318 && !move_is_killer(move, ss[ply]))
1320 ss[ply].reduction = reduction<PvNode>(depth, moveCount);
1321 if (ss[ply].reduction)
1323 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1324 doFullDepthSearch = (value > alpha);
1328 // Step 15. Full depth search
1329 if (doFullDepthSearch)
1331 ss[ply].reduction = Depth(0);
1332 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth, ply+1, true, threadID);
1334 // Step extra. pv search (only in PV nodes)
1335 if (PvNode && value > alpha && value < beta)
1336 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, ply+1, false, threadID);
1340 // Step 16. Undo move
1341 pos.undo_move(move);
1343 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1345 // Step 17. Check for new best move
1346 if (value > bestValue)
1353 if (value == value_mate_in(ply + 1))
1354 ss[ply].mateKiller = move;
1358 // Step 18. Check for split
1359 if ( TM.active_threads() > 1
1361 && depth >= MinimumSplitDepth
1363 && TM.available_thread_exists(threadID)
1365 && !TM.thread_should_stop(threadID)
1366 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1367 depth, mateThreat, &moveCount, &mp, threadID, PvNode))
1371 // Step 19. Check for mate and stalemate
1372 // All legal moves have been searched and if there are
1373 // no legal moves, it must be mate or stalemate.
1374 // If one move was excluded return fail low score.
1376 return excludedMove ? oldAlpha : (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1378 // Step 20. Update tables
1379 // If the search is not aborted, update the transposition table,
1380 // history counters, and killer moves.
1381 if (AbortSearch || TM.thread_should_stop(threadID))
1384 if (bestValue <= oldAlpha)
1385 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1387 else if (bestValue >= beta)
1389 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1390 move = ss[ply].pv[ply];
1391 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1392 if (!pos.move_is_capture_or_promotion(move))
1394 update_history(pos, move, depth, movesSearched, moveCount);
1395 update_killers(move, ss[ply]);
1399 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1401 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1407 // qsearch() is the quiescence search function, which is called by the main
1408 // search function when the remaining depth is zero (or, to be more precise,
1409 // less than OnePly).
1411 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1412 Depth depth, int ply, int threadID) {
1414 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1415 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1417 assert(ply >= 0 && ply < PLY_MAX);
1418 assert(threadID >= 0 && threadID < TM.active_threads());
1423 Value staticValue, bestValue, value, futilityBase, futilityValue;
1424 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1425 const TTEntry* tte = NULL;
1427 bool pvNode = (beta - alpha != 1);
1428 Value oldAlpha = alpha;
1430 // Initialize, and make an early exit in case of an aborted search,
1431 // an instant draw, maximum ply reached, etc.
1432 init_node(ss, ply, threadID);
1434 // After init_node() that calls poll()
1435 if (AbortSearch || TM.thread_should_stop(threadID))
1438 if (pos.is_draw() || ply >= PLY_MAX - 1)
1441 // Transposition table lookup. At PV nodes, we don't use the TT for
1442 // pruning, but only for move ordering.
1443 tte = TT.retrieve(pos.get_key());
1444 ttMove = (tte ? tte->move() : MOVE_NONE);
1446 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1448 assert(tte->type() != VALUE_TYPE_EVAL);
1450 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1451 return value_from_tt(tte->value(), ply);
1454 isCheck = pos.is_check();
1456 // Evaluate the position statically
1458 staticValue = -VALUE_INFINITE;
1459 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1460 staticValue = value_from_tt(tte->value(), ply);
1462 staticValue = evaluate(pos, ei, threadID);
1466 ss[ply].eval = staticValue;
1467 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1470 // Initialize "stand pat score", and return it immediately if it is
1472 bestValue = staticValue;
1474 if (bestValue >= beta)
1476 // Store the score to avoid a future costly evaluation() call
1477 if (!isCheck && !tte && ei.kingDanger[pos.side_to_move()] == 0)
1478 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1483 if (bestValue > alpha)
1486 // If we are near beta then try to get a cutoff pushing checks a bit further
1487 bool deepChecks = (depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8);
1489 // Initialize a MovePicker object for the current position, and prepare
1490 // to search the moves. Because the depth is <= 0 here, only captures,
1491 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1492 // and we are near beta) will be generated.
1493 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1495 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1496 futilityBase = staticValue + FutilityMarginQS + ei.kingDanger[pos.side_to_move()];
1498 // Loop through the moves until no moves remain or a beta cutoff occurs
1499 while ( alpha < beta
1500 && (move = mp.get_next_move()) != MOVE_NONE)
1502 assert(move_is_ok(move));
1504 moveIsCheck = pos.move_is_check(move, ci);
1506 // Update current move
1508 ss[ply].currentMove = move;
1516 && !move_is_promotion(move)
1517 && !pos.move_is_passed_pawn_push(move))
1519 futilityValue = futilityBase
1520 + pos.endgame_value_of_piece_on(move_to(move))
1521 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1523 if (futilityValue < alpha)
1525 if (futilityValue > bestValue)
1526 bestValue = futilityValue;
1531 // Detect blocking evasions that are candidate to be pruned
1532 evasionPrunable = isCheck
1533 && bestValue > value_mated_in(PLY_MAX)
1534 && !pos.move_is_capture(move)
1535 && pos.type_of_piece_on(move_from(move)) != KING
1536 && !pos.can_castle(pos.side_to_move());
1538 // Don't search moves with negative SEE values
1539 if ( (!isCheck || evasionPrunable)
1542 && !move_is_promotion(move)
1543 && pos.see_sign(move) < 0)
1546 // Make and search the move
1547 pos.do_move(move, st, ci, moveIsCheck);
1548 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1549 pos.undo_move(move);
1551 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1554 if (value > bestValue)
1565 // All legal moves have been searched. A special case: If we're in check
1566 // and no legal moves were found, it is checkmate.
1567 if (!moveCount && isCheck) // Mate!
1568 return value_mated_in(ply);
1570 // Update transposition table
1571 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1572 if (bestValue <= oldAlpha)
1574 // If bestValue isn't changed it means it is still the static evaluation
1575 // of the node, so keep this info to avoid a future evaluation() call.
1576 ValueType type = (bestValue == staticValue && !ei.kingDanger[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1577 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1579 else if (bestValue >= beta)
1581 move = ss[ply].pv[ply];
1582 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1584 // Update killers only for good checking moves
1585 if (!pos.move_is_capture_or_promotion(move))
1586 update_killers(move, ss[ply]);
1589 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1591 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1597 // sp_search() is used to search from a split point. This function is called
1598 // by each thread working at the split point. It is similar to the normal
1599 // search() function, but simpler. Because we have already probed the hash
1600 // table, done a null move search, and searched the first move before
1601 // splitting, we don't have to repeat all this work in sp_search(). We
1602 // also don't need to store anything to the hash table here: This is taken
1603 // care of after we return from the split point.
1605 void sp_search(SplitPoint* sp, int threadID) {
1607 assert(threadID >= 0 && threadID < TM.active_threads());
1608 assert(TM.active_threads() > 1);
1612 Depth ext, newDepth;
1613 Value value, futilityValueScaled;
1614 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1616 value = -VALUE_INFINITE;
1618 Position pos(*sp->pos);
1620 SearchStack* ss = sp->sstack[threadID];
1621 isCheck = pos.is_check();
1623 // Step 10. Loop through moves
1624 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1625 lock_grab(&(sp->lock));
1627 while ( sp->bestValue < sp->beta
1628 && !TM.thread_should_stop(threadID)
1629 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1631 moveCount = ++sp->moves;
1632 lock_release(&(sp->lock));
1634 assert(move_is_ok(move));
1636 moveIsCheck = pos.move_is_check(move, ci);
1637 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1639 // Step 11. Decide the new search depth
1640 ext = extension<NonPV>(pos, move, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1641 newDepth = sp->depth - OnePly + ext;
1643 // Update current move
1644 ss[sp->ply].currentMove = move;
1646 // Step 12. Futility pruning
1649 && !captureOrPromotion
1650 && !move_is_castle(move))
1652 // Move count based pruning
1653 if ( moveCount >= futility_move_count(sp->depth)
1654 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1655 && sp->bestValue > value_mated_in(PLY_MAX))
1657 lock_grab(&(sp->lock));
1661 // Value based pruning
1662 Depth predictedDepth = newDepth - reduction<NonPV>(sp->depth, moveCount);
1663 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1664 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1666 if (futilityValueScaled < sp->beta)
1668 lock_grab(&(sp->lock));
1670 if (futilityValueScaled > sp->bestValue)
1671 sp->bestValue = futilityValueScaled;
1676 // Step 13. Make the move
1677 pos.do_move(move, st, ci, moveIsCheck);
1679 // Step 14. Reduced search
1680 // if the move fails high will be re-searched at full depth.
1681 bool doFullDepthSearch = true;
1684 && !captureOrPromotion
1685 && !move_is_castle(move)
1686 && !move_is_killer(move, ss[sp->ply]))
1688 ss[sp->ply].reduction = reduction<NonPV>(sp->depth, moveCount);
1689 if (ss[sp->ply].reduction)
1691 value = -search<NonPV>(pos, ss, -(sp->alpha+1), -(sp->alpha), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1692 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1696 // Step 15. Full depth search
1697 if (doFullDepthSearch)
1699 ss[sp->ply].reduction = Depth(0);
1700 value = -search<NonPV>(pos, ss, -(sp->alpha+1), -(sp->alpha), newDepth, sp->ply+1, true, threadID);
1703 // Step 16. Undo move
1704 pos.undo_move(move);
1706 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1708 // Step 17. Check for new best move
1709 lock_grab(&(sp->lock));
1711 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1713 sp->bestValue = value;
1714 if (sp->bestValue >= sp->beta)
1716 sp->stopRequest = true;
1717 sp_update_pv(sp->parentSstack, ss, sp->ply);
1722 /* Here we have the lock still grabbed */
1724 sp->slaves[threadID] = 0;
1727 lock_release(&(sp->lock));
1731 // sp_search_pv() is used to search from a PV split point. This function
1732 // is called by each thread working at the split point. It is similar to
1733 // the normal search_pv() function, but simpler. Because we have already
1734 // probed the hash table and searched the first move before splitting, we
1735 // don't have to repeat all this work in sp_search_pv(). We also don't
1736 // need to store anything to the hash table here: This is taken care of
1737 // after we return from the split point.
1739 void sp_search_pv(SplitPoint* sp, int threadID) {
1741 assert(threadID >= 0 && threadID < TM.active_threads());
1742 assert(TM.active_threads() > 1);
1746 Depth ext, newDepth;
1748 bool moveIsCheck, captureOrPromotion, dangerous;
1750 value = -VALUE_INFINITE;
1752 Position pos(*sp->pos);
1754 SearchStack* ss = sp->sstack[threadID];
1756 // Step 10. Loop through moves
1757 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1758 lock_grab(&(sp->lock));
1760 while ( sp->alpha < sp->beta
1761 && !TM.thread_should_stop(threadID)
1762 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1764 moveCount = ++sp->moves;
1765 lock_release(&(sp->lock));
1767 assert(move_is_ok(move));
1769 moveIsCheck = pos.move_is_check(move, ci);
1770 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1772 // Step 11. Decide the new search depth
1773 ext = extension<PV>(pos, move, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1774 newDepth = sp->depth - OnePly + ext;
1776 // Update current move
1777 ss[sp->ply].currentMove = move;
1779 // Step 12. Futility pruning (is omitted in PV nodes)
1781 // Step 13. Make the move
1782 pos.do_move(move, st, ci, moveIsCheck);
1784 // Step 14. Reduced search
1785 // if the move fails high will be re-searched at full depth.
1786 bool doFullDepthSearch = true;
1789 && !captureOrPromotion
1790 && !move_is_castle(move)
1791 && !move_is_killer(move, ss[sp->ply]))
1793 ss[sp->ply].reduction = reduction<PV>(sp->depth, moveCount);
1794 if (ss[sp->ply].reduction)
1796 Value localAlpha = sp->alpha;
1797 value = -search<NonPV>(pos, ss, -(localAlpha+1), -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1798 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
1802 // Step 15. Full depth search
1803 if (doFullDepthSearch)
1805 Value localAlpha = sp->alpha;
1806 ss[sp->ply].reduction = Depth(0);
1807 value = -search<NonPV>(pos, ss, -(localAlpha+1), -localAlpha, newDepth, sp->ply+1, true, threadID);
1809 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
1811 // If another thread has failed high then sp->alpha has been increased
1812 // to be higher or equal then beta, if so, avoid to start a PV search.
1813 localAlpha = sp->alpha;
1814 if (localAlpha < sp->beta)
1815 value = -search<PV>(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, false, threadID);
1819 // Step 16. Undo move
1820 pos.undo_move(move);
1822 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1824 // Step 17. Check for new best move
1825 lock_grab(&(sp->lock));
1827 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1829 sp->bestValue = value;
1830 if (value > sp->alpha)
1832 // Ask threads to stop before to modify sp->alpha
1833 if (value >= sp->beta)
1834 sp->stopRequest = true;
1838 sp_update_pv(sp->parentSstack, ss, sp->ply);
1839 if (value == value_mate_in(sp->ply + 1))
1840 ss[sp->ply].mateKiller = move;
1845 /* Here we have the lock still grabbed */
1847 sp->slaves[threadID] = 0;
1850 lock_release(&(sp->lock));
1854 // init_node() is called at the beginning of all the search functions
1855 // (search() qsearch(), and so on) and initializes the
1856 // search stack object corresponding to the current node. Once every
1857 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1858 // for user input and checks whether it is time to stop the search.
1860 void init_node(SearchStack ss[], int ply, int threadID) {
1862 assert(ply >= 0 && ply < PLY_MAX);
1863 assert(threadID >= 0 && threadID < TM.active_threads());
1865 TM.incrementNodeCounter(threadID);
1870 if (NodesSincePoll >= NodesBetweenPolls)
1877 ss[ply + 2].initKillers();
1881 // update_pv() is called whenever a search returns a value > alpha.
1882 // It updates the PV in the SearchStack object corresponding to the
1885 void update_pv(SearchStack ss[], int ply) {
1887 assert(ply >= 0 && ply < PLY_MAX);
1891 ss[ply].pv[ply] = ss[ply].currentMove;
1893 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
1894 ss[ply].pv[p] = ss[ply + 1].pv[p];
1896 ss[ply].pv[p] = MOVE_NONE;
1900 // sp_update_pv() is a variant of update_pv for use at split points. The
1901 // difference between the two functions is that sp_update_pv also updates
1902 // the PV at the parent node.
1904 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
1906 assert(ply >= 0 && ply < PLY_MAX);
1910 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1912 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
1913 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
1915 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1919 // connected_moves() tests whether two moves are 'connected' in the sense
1920 // that the first move somehow made the second move possible (for instance
1921 // if the moving piece is the same in both moves). The first move is assumed
1922 // to be the move that was made to reach the current position, while the
1923 // second move is assumed to be a move from the current position.
1925 bool connected_moves(const Position& pos, Move m1, Move m2) {
1927 Square f1, t1, f2, t2;
1930 assert(move_is_ok(m1));
1931 assert(move_is_ok(m2));
1933 if (m2 == MOVE_NONE)
1936 // Case 1: The moving piece is the same in both moves
1942 // Case 2: The destination square for m2 was vacated by m1
1948 // Case 3: Moving through the vacated square
1949 if ( piece_is_slider(pos.piece_on(f2))
1950 && bit_is_set(squares_between(f2, t2), f1))
1953 // Case 4: The destination square for m2 is defended by the moving piece in m1
1954 p = pos.piece_on(t1);
1955 if (bit_is_set(pos.attacks_from(p, t1), t2))
1958 // Case 5: Discovered check, checking piece is the piece moved in m1
1959 if ( piece_is_slider(p)
1960 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1961 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1963 // discovered_check_candidates() works also if the Position's side to
1964 // move is the opposite of the checking piece.
1965 Color them = opposite_color(pos.side_to_move());
1966 Bitboard dcCandidates = pos.discovered_check_candidates(them);
1968 if (bit_is_set(dcCandidates, f2))
1975 // value_is_mate() checks if the given value is a mate one
1976 // eventually compensated for the ply.
1978 bool value_is_mate(Value value) {
1980 assert(abs(value) <= VALUE_INFINITE);
1982 return value <= value_mated_in(PLY_MAX)
1983 || value >= value_mate_in(PLY_MAX);
1987 // move_is_killer() checks if the given move is among the
1988 // killer moves of that ply.
1990 bool move_is_killer(Move m, const SearchStack& ss) {
1992 const Move* k = ss.killers;
1993 for (int i = 0; i < KILLER_MAX; i++, k++)
2001 // extension() decides whether a move should be searched with normal depth,
2002 // or with extended depth. Certain classes of moves (checking moves, in
2003 // particular) are searched with bigger depth than ordinary moves and in
2004 // any case are marked as 'dangerous'. Note that also if a move is not
2005 // extended, as example because the corresponding UCI option is set to zero,
2006 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2007 template <NodeType PvNode>
2008 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck,
2009 bool singleEvasion, bool mateThreat, bool* dangerous) {
2011 assert(m != MOVE_NONE);
2013 Depth result = Depth(0);
2014 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2019 result += CheckExtension[PvNode];
2022 result += SingleEvasionExtension[PvNode];
2025 result += MateThreatExtension[PvNode];
2028 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2030 Color c = pos.side_to_move();
2031 if (relative_rank(c, move_to(m)) == RANK_7)
2033 result += PawnPushTo7thExtension[PvNode];
2036 if (pos.pawn_is_passed(c, move_to(m)))
2038 result += PassedPawnExtension[PvNode];
2043 if ( captureOrPromotion
2044 && pos.type_of_piece_on(move_to(m)) != PAWN
2045 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2046 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2047 && !move_is_promotion(m)
2050 result += PawnEndgameExtension[PvNode];
2055 && captureOrPromotion
2056 && pos.type_of_piece_on(move_to(m)) != PAWN
2057 && pos.see_sign(m) >= 0)
2063 return Min(result, OnePly);
2067 // ok_to_do_nullmove() looks at the current position and decides whether
2068 // doing a 'null move' should be allowed. In order to avoid zugzwang
2069 // problems, null moves are not allowed when the side to move has very
2070 // little material left. Currently, the test is a bit too simple: Null
2071 // moves are avoided only when the side to move has only pawns left.
2072 // It's probably a good idea to avoid null moves in at least some more
2073 // complicated endgames, e.g. KQ vs KR. FIXME
2075 bool ok_to_do_nullmove(const Position& pos) {
2077 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2081 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2082 // non-tactical moves late in the move list close to the leaves are
2083 // candidates for pruning.
2085 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2087 assert(move_is_ok(m));
2088 assert(threat == MOVE_NONE || move_is_ok(threat));
2089 assert(!pos.move_is_check(m));
2090 assert(!pos.move_is_capture_or_promotion(m));
2091 assert(!pos.move_is_passed_pawn_push(m));
2093 Square mfrom, mto, tfrom, tto;
2095 // Prune if there isn't any threat move
2096 if (threat == MOVE_NONE)
2099 mfrom = move_from(m);
2101 tfrom = move_from(threat);
2102 tto = move_to(threat);
2104 // Case 1: Don't prune moves which move the threatened piece
2108 // Case 2: If the threatened piece has value less than or equal to the
2109 // value of the threatening piece, don't prune move which defend it.
2110 if ( pos.move_is_capture(threat)
2111 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2112 || pos.type_of_piece_on(tfrom) == KING)
2113 && pos.move_attacks_square(m, tto))
2116 // Case 3: If the moving piece in the threatened move is a slider, don't
2117 // prune safe moves which block its ray.
2118 if ( piece_is_slider(pos.piece_on(tfrom))
2119 && bit_is_set(squares_between(tfrom, tto), mto)
2120 && pos.see_sign(m) >= 0)
2127 // ok_to_use_TT() returns true if a transposition table score
2128 // can be used at a given point in search.
2130 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2132 Value v = value_from_tt(tte->value(), ply);
2134 return ( tte->depth() >= depth
2135 || v >= Max(value_mate_in(PLY_MAX), beta)
2136 || v < Min(value_mated_in(PLY_MAX), beta))
2138 && ( (is_lower_bound(tte->type()) && v >= beta)
2139 || (is_upper_bound(tte->type()) && v < beta));
2143 // refine_eval() returns the transposition table score if
2144 // possible otherwise falls back on static position evaluation.
2146 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2151 Value v = value_from_tt(tte->value(), ply);
2153 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2154 || (is_upper_bound(tte->type()) && v < defaultEval))
2161 // update_history() registers a good move that produced a beta-cutoff
2162 // in history and marks as failures all the other moves of that ply.
2164 void update_history(const Position& pos, Move move, Depth depth,
2165 Move movesSearched[], int moveCount) {
2169 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2171 for (int i = 0; i < moveCount - 1; i++)
2173 m = movesSearched[i];
2177 if (!pos.move_is_capture_or_promotion(m))
2178 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2183 // update_killers() add a good move that produced a beta-cutoff
2184 // among the killer moves of that ply.
2186 void update_killers(Move m, SearchStack& ss) {
2188 if (m == ss.killers[0])
2191 for (int i = KILLER_MAX - 1; i > 0; i--)
2192 ss.killers[i] = ss.killers[i - 1];
2198 // update_gains() updates the gains table of a non-capture move given
2199 // the static position evaluation before and after the move.
2201 void update_gains(const Position& pos, Move m, Value before, Value after) {
2204 && before != VALUE_NONE
2205 && after != VALUE_NONE
2206 && pos.captured_piece() == NO_PIECE_TYPE
2207 && !move_is_castle(m)
2208 && !move_is_promotion(m))
2209 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2213 // current_search_time() returns the number of milliseconds which have passed
2214 // since the beginning of the current search.
2216 int current_search_time() {
2218 return get_system_time() - SearchStartTime;
2222 // nps() computes the current nodes/second count.
2226 int t = current_search_time();
2227 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2231 // poll() performs two different functions: It polls for user input, and it
2232 // looks at the time consumed so far and decides if it's time to abort the
2237 static int lastInfoTime;
2238 int t = current_search_time();
2243 // We are line oriented, don't read single chars
2244 std::string command;
2246 if (!std::getline(std::cin, command))
2249 if (command == "quit")
2252 PonderSearch = false;
2256 else if (command == "stop")
2259 PonderSearch = false;
2261 else if (command == "ponderhit")
2265 // Print search information
2269 else if (lastInfoTime > t)
2270 // HACK: Must be a new search where we searched less than
2271 // NodesBetweenPolls nodes during the first second of search.
2274 else if (t - lastInfoTime >= 1000)
2281 if (dbg_show_hit_rate)
2282 dbg_print_hit_rate();
2284 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2285 << " time " << t << " hashfull " << TT.full() << endl;
2288 // Should we stop the search?
2292 bool stillAtFirstMove = FirstRootMove
2293 && !AspirationFailLow
2294 && t > MaxSearchTime + ExtraSearchTime;
2296 bool noMoreTime = t > AbsoluteMaxSearchTime
2297 || stillAtFirstMove;
2299 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2300 || (ExactMaxTime && t >= ExactMaxTime)
2301 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2306 // ponderhit() is called when the program is pondering (i.e. thinking while
2307 // it's the opponent's turn to move) in order to let the engine know that
2308 // it correctly predicted the opponent's move.
2312 int t = current_search_time();
2313 PonderSearch = false;
2315 bool stillAtFirstMove = FirstRootMove
2316 && !AspirationFailLow
2317 && t > MaxSearchTime + ExtraSearchTime;
2319 bool noMoreTime = t > AbsoluteMaxSearchTime
2320 || stillAtFirstMove;
2322 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2327 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2329 void init_ss_array(SearchStack ss[]) {
2331 for (int i = 0; i < 3; i++)
2334 ss[i].initKillers();
2339 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2340 // while the program is pondering. The point is to work around a wrinkle in
2341 // the UCI protocol: When pondering, the engine is not allowed to give a
2342 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2343 // We simply wait here until one of these commands is sent, and return,
2344 // after which the bestmove and pondermove will be printed (in id_loop()).
2346 void wait_for_stop_or_ponderhit() {
2348 std::string command;
2352 if (!std::getline(std::cin, command))
2355 if (command == "quit")
2360 else if (command == "ponderhit" || command == "stop")
2366 // print_pv_info() prints to standard output and eventually to log file information on
2367 // the current PV line. It is called at each iteration or after a new pv is found.
2369 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value) {
2371 cout << "info depth " << Iteration
2372 << " score " << value_to_string(value)
2373 << ((value >= beta) ? " lowerbound" :
2374 ((value <= alpha)? " upperbound" : ""))
2375 << " time " << current_search_time()
2376 << " nodes " << TM.nodes_searched()
2380 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
2381 cout << ss[0].pv[j] << " ";
2387 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
2388 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
2390 LogFile << pretty_pv(pos, current_search_time(), Iteration,
2391 TM.nodes_searched(), value, type, ss[0].pv) << endl;
2396 // init_thread() is the function which is called when a new thread is
2397 // launched. It simply calls the idle_loop() function with the supplied
2398 // threadID. There are two versions of this function; one for POSIX
2399 // threads and one for Windows threads.
2401 #if !defined(_MSC_VER)
2403 void* init_thread(void *threadID) {
2405 TM.idle_loop(*(int*)threadID, NULL);
2411 DWORD WINAPI init_thread(LPVOID threadID) {
2413 TM.idle_loop(*(int*)threadID, NULL);
2420 /// The ThreadsManager class
2422 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2423 // get_beta_counters() are getters/setters for the per thread
2424 // counters used to sort the moves at root.
2426 void ThreadsManager::resetNodeCounters() {
2428 for (int i = 0; i < MAX_THREADS; i++)
2429 threads[i].nodes = 0ULL;
2432 void ThreadsManager::resetBetaCounters() {
2434 for (int i = 0; i < MAX_THREADS; i++)
2435 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2438 int64_t ThreadsManager::nodes_searched() const {
2440 int64_t result = 0ULL;
2441 for (int i = 0; i < ActiveThreads; i++)
2442 result += threads[i].nodes;
2447 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2450 for (int i = 0; i < MAX_THREADS; i++)
2452 our += threads[i].betaCutOffs[us];
2453 their += threads[i].betaCutOffs[opposite_color(us)];
2458 // idle_loop() is where the threads are parked when they have no work to do.
2459 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2460 // object for which the current thread is the master.
2462 void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2464 assert(threadID >= 0 && threadID < MAX_THREADS);
2468 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2469 // master should exit as last one.
2470 if (AllThreadsShouldExit)
2473 threads[threadID].state = THREAD_TERMINATED;
2477 // If we are not thinking, wait for a condition to be signaled
2478 // instead of wasting CPU time polling for work.
2479 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2482 assert(threadID != 0);
2483 threads[threadID].state = THREAD_SLEEPING;
2485 #if !defined(_MSC_VER)
2486 lock_grab(&WaitLock);
2487 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2488 pthread_cond_wait(&WaitCond, &WaitLock);
2489 lock_release(&WaitLock);
2491 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2495 // If thread has just woken up, mark it as available
2496 if (threads[threadID].state == THREAD_SLEEPING)
2497 threads[threadID].state = THREAD_AVAILABLE;
2499 // If this thread has been assigned work, launch a search
2500 if (threads[threadID].state == THREAD_WORKISWAITING)
2502 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2504 threads[threadID].state = THREAD_SEARCHING;
2506 if (threads[threadID].splitPoint->pvNode)
2507 sp_search_pv(threads[threadID].splitPoint, threadID);
2509 sp_search(threads[threadID].splitPoint, threadID);
2511 assert(threads[threadID].state == THREAD_SEARCHING);
2513 threads[threadID].state = THREAD_AVAILABLE;
2516 // If this thread is the master of a split point and all threads have
2517 // finished their work at this split point, return from the idle loop.
2518 if (sp && sp->cpus == 0)
2520 // Because sp->cpus is decremented under lock protection,
2521 // be sure sp->lock has been released before to proceed.
2522 lock_grab(&(sp->lock));
2523 lock_release(&(sp->lock));
2525 assert(threads[threadID].state == THREAD_AVAILABLE);
2527 threads[threadID].state = THREAD_SEARCHING;
2534 // init_threads() is called during startup. It launches all helper threads,
2535 // and initializes the split point stack and the global locks and condition
2538 void ThreadsManager::init_threads() {
2543 #if !defined(_MSC_VER)
2544 pthread_t pthread[1];
2547 // Initialize global locks
2548 lock_init(&MPLock, NULL);
2549 lock_init(&WaitLock, NULL);
2551 #if !defined(_MSC_VER)
2552 pthread_cond_init(&WaitCond, NULL);
2554 for (i = 0; i < MAX_THREADS; i++)
2555 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2558 // Initialize SplitPointStack locks
2559 for (i = 0; i < MAX_THREADS; i++)
2560 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2562 SplitPointStack[i][j].parent = NULL;
2563 lock_init(&(SplitPointStack[i][j].lock), NULL);
2566 // Will be set just before program exits to properly end the threads
2567 AllThreadsShouldExit = false;
2569 // Threads will be put to sleep as soon as created
2570 AllThreadsShouldSleep = true;
2572 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2574 threads[0].state = THREAD_SEARCHING;
2575 for (i = 1; i < MAX_THREADS; i++)
2576 threads[i].state = THREAD_AVAILABLE;
2578 // Launch the helper threads
2579 for (i = 1; i < MAX_THREADS; i++)
2582 #if !defined(_MSC_VER)
2583 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2585 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, NULL) != NULL);
2590 cout << "Failed to create thread number " << i << endl;
2591 Application::exit_with_failure();
2594 // Wait until the thread has finished launching and is gone to sleep
2595 while (threads[i].state != THREAD_SLEEPING) {}
2600 // exit_threads() is called when the program exits. It makes all the
2601 // helper threads exit cleanly.
2603 void ThreadsManager::exit_threads() {
2605 ActiveThreads = MAX_THREADS; // HACK
2606 AllThreadsShouldSleep = true; // HACK
2607 wake_sleeping_threads();
2609 // This makes the threads to exit idle_loop()
2610 AllThreadsShouldExit = true;
2612 // Wait for thread termination
2613 for (int i = 1; i < MAX_THREADS; i++)
2614 while (threads[i].state != THREAD_TERMINATED);
2616 // Now we can safely destroy the locks
2617 for (int i = 0; i < MAX_THREADS; i++)
2618 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2619 lock_destroy(&(SplitPointStack[i][j].lock));
2621 lock_destroy(&WaitLock);
2622 lock_destroy(&MPLock);
2626 // thread_should_stop() checks whether the thread should stop its search.
2627 // This can happen if a beta cutoff has occurred in the thread's currently
2628 // active split point, or in some ancestor of the current split point.
2630 bool ThreadsManager::thread_should_stop(int threadID) const {
2632 assert(threadID >= 0 && threadID < ActiveThreads);
2636 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent) {}
2641 // thread_is_available() checks whether the thread with threadID "slave" is
2642 // available to help the thread with threadID "master" at a split point. An
2643 // obvious requirement is that "slave" must be idle. With more than two
2644 // threads, this is not by itself sufficient: If "slave" is the master of
2645 // some active split point, it is only available as a slave to the other
2646 // threads which are busy searching the split point at the top of "slave"'s
2647 // split point stack (the "helpful master concept" in YBWC terminology).
2649 bool ThreadsManager::thread_is_available(int slave, int master) const {
2651 assert(slave >= 0 && slave < ActiveThreads);
2652 assert(master >= 0 && master < ActiveThreads);
2653 assert(ActiveThreads > 1);
2655 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2658 // Make a local copy to be sure doesn't change under our feet
2659 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2661 if (localActiveSplitPoints == 0)
2662 // No active split points means that the thread is available as
2663 // a slave for any other thread.
2666 if (ActiveThreads == 2)
2669 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2670 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2671 // could have been set to 0 by another thread leading to an out of bound access.
2672 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2679 // available_thread_exists() tries to find an idle thread which is available as
2680 // a slave for the thread with threadID "master".
2682 bool ThreadsManager::available_thread_exists(int master) const {
2684 assert(master >= 0 && master < ActiveThreads);
2685 assert(ActiveThreads > 1);
2687 for (int i = 0; i < ActiveThreads; i++)
2688 if (thread_is_available(i, master))
2695 // split() does the actual work of distributing the work at a node between
2696 // several threads at PV nodes. If it does not succeed in splitting the
2697 // node (because no idle threads are available, or because we have no unused
2698 // split point objects), the function immediately returns false. If
2699 // splitting is possible, a SplitPoint object is initialized with all the
2700 // data that must be copied to the helper threads (the current position and
2701 // search stack, alpha, beta, the search depth, etc.), and we tell our
2702 // helper threads that they have been assigned work. This will cause them
2703 // to instantly leave their idle loops and call sp_search_pv(). When all
2704 // threads have returned from sp_search_pv (or, equivalently, when
2705 // splitPoint->cpus becomes 0), split() returns true.
2707 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2708 Value* alpha, const Value beta, Value* bestValue,
2709 Depth depth, bool mateThreat, int* moves, MovePicker* mp, int master, bool pvNode) {
2712 assert(sstck != NULL);
2713 assert(ply >= 0 && ply < PLY_MAX);
2714 assert(*bestValue >= -VALUE_INFINITE);
2715 assert( ( pvNode && *bestValue <= *alpha)
2716 || (!pvNode && *bestValue < beta ));
2717 assert(!pvNode || *alpha < beta);
2718 assert(beta <= VALUE_INFINITE);
2719 assert(depth > Depth(0));
2720 assert(master >= 0 && master < ActiveThreads);
2721 assert(ActiveThreads > 1);
2723 SplitPoint* splitPoint;
2727 // If no other thread is available to help us, or if we have too many
2728 // active split points, don't split.
2729 if ( !available_thread_exists(master)
2730 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2732 lock_release(&MPLock);
2736 // Pick the next available split point object from the split point stack
2737 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2739 // Initialize the split point object
2740 splitPoint->parent = threads[master].splitPoint;
2741 splitPoint->stopRequest = false;
2742 splitPoint->ply = ply;
2743 splitPoint->depth = depth;
2744 splitPoint->mateThreat = mateThreat;
2745 splitPoint->alpha = *alpha;
2746 splitPoint->beta = beta;
2747 splitPoint->pvNode = pvNode;
2748 splitPoint->bestValue = *bestValue;
2749 splitPoint->master = master;
2750 splitPoint->mp = mp;
2751 splitPoint->moves = *moves;
2752 splitPoint->cpus = 1;
2753 splitPoint->pos = &p;
2754 splitPoint->parentSstack = sstck;
2755 for (int i = 0; i < ActiveThreads; i++)
2756 splitPoint->slaves[i] = 0;
2758 threads[master].splitPoint = splitPoint;
2759 threads[master].activeSplitPoints++;
2761 // If we are here it means we are not available
2762 assert(threads[master].state != THREAD_AVAILABLE);
2764 // Allocate available threads setting state to THREAD_BOOKED
2765 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2766 if (thread_is_available(i, master))
2768 threads[i].state = THREAD_BOOKED;
2769 threads[i].splitPoint = splitPoint;
2770 splitPoint->slaves[i] = 1;
2774 assert(splitPoint->cpus > 1);
2776 // We can release the lock because slave threads are already booked and master is not available
2777 lock_release(&MPLock);
2779 // Tell the threads that they have work to do. This will make them leave
2780 // their idle loop. But before copy search stack tail for each thread.
2781 for (int i = 0; i < ActiveThreads; i++)
2782 if (i == master || splitPoint->slaves[i])
2784 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2786 assert(i == master || threads[i].state == THREAD_BOOKED);
2788 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2791 // Everything is set up. The master thread enters the idle loop, from
2792 // which it will instantly launch a search, because its state is
2793 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2794 // idle loop, which means that the main thread will return from the idle
2795 // loop when all threads have finished their work at this split point
2796 // (i.e. when splitPoint->cpus == 0).
2797 idle_loop(master, splitPoint);
2799 // We have returned from the idle loop, which means that all threads are
2800 // finished. Update alpha and bestValue, and return.
2803 *alpha = splitPoint->alpha;
2804 *bestValue = splitPoint->bestValue;
2805 threads[master].activeSplitPoints--;
2806 threads[master].splitPoint = splitPoint->parent;
2808 lock_release(&MPLock);
2813 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2814 // to start a new search from the root.
2816 void ThreadsManager::wake_sleeping_threads() {
2818 assert(AllThreadsShouldSleep);
2819 assert(ActiveThreads > 0);
2821 AllThreadsShouldSleep = false;
2823 if (ActiveThreads == 1)
2826 #if !defined(_MSC_VER)
2827 pthread_mutex_lock(&WaitLock);
2828 pthread_cond_broadcast(&WaitCond);
2829 pthread_mutex_unlock(&WaitLock);
2831 for (int i = 1; i < MAX_THREADS; i++)
2832 SetEvent(SitIdleEvent[i]);
2838 // put_threads_to_sleep() makes all the threads go to sleep just before
2839 // to leave think(), at the end of the search. Threads should have already
2840 // finished the job and should be idle.
2842 void ThreadsManager::put_threads_to_sleep() {
2844 assert(!AllThreadsShouldSleep);
2846 // This makes the threads to go to sleep
2847 AllThreadsShouldSleep = true;
2850 /// The RootMoveList class
2852 // RootMoveList c'tor
2854 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2856 SearchStack ss[PLY_MAX_PLUS_2];
2857 MoveStack mlist[MaxRootMoves];
2859 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2861 // Generate all legal moves
2862 MoveStack* last = generate_moves(pos, mlist);
2864 // Add each move to the moves[] array
2865 for (MoveStack* cur = mlist; cur != last; cur++)
2867 bool includeMove = includeAllMoves;
2869 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2870 includeMove = (searchMoves[k] == cur->move);
2875 // Find a quick score for the move
2877 pos.do_move(cur->move, st);
2878 moves[count].move = cur->move;
2879 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2880 moves[count].pv[0] = cur->move;
2881 moves[count].pv[1] = MOVE_NONE;
2882 pos.undo_move(cur->move);
2889 // RootMoveList simple methods definitions
2891 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2893 moves[moveNum].nodes = nodes;
2894 moves[moveNum].cumulativeNodes += nodes;
2897 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2899 moves[moveNum].ourBeta = our;
2900 moves[moveNum].theirBeta = their;
2903 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2907 for (j = 0; pv[j] != MOVE_NONE; j++)
2908 moves[moveNum].pv[j] = pv[j];
2910 moves[moveNum].pv[j] = MOVE_NONE;
2914 // RootMoveList::sort() sorts the root move list at the beginning of a new
2917 void RootMoveList::sort() {
2919 sort_multipv(count - 1); // Sort all items
2923 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2924 // list by their scores and depths. It is used to order the different PVs
2925 // correctly in MultiPV mode.
2927 void RootMoveList::sort_multipv(int n) {
2931 for (i = 1; i <= n; i++)
2933 RootMove rm = moves[i];
2934 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2935 moves[j] = moves[j - 1];