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 IIDDepth[2] = { 8 * OnePly /* non-PV */, 5 * OnePly /* PV */};
184 // At Non-PV nodes we do an internal iterative deepening search
185 // when the static evaluation is at most IIDMargin below beta.
186 const Value IIDMargin = Value(0x100);
188 // Step 11. Decide the new search depth
190 // Extensions. Configurable UCI options
191 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
192 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
193 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
195 // Minimum depth for use of singular extension
196 const Depth SingularExtensionDepth[2] = { 8 * OnePly /* non-PV */, 6 * OnePly /* PV */};
198 // If the TT move is at least SingularExtensionMargin better then the
199 // remaining ones we will extend it.
200 const Value SingularExtensionMargin = Value(0x20);
202 // Step 12. Futility pruning
204 // Futility margin for quiescence search
205 const Value FutilityMarginQS = Value(0x80);
207 // Futility lookup tables (initialized at startup) and their getter functions
208 int32_t FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
209 int FutilityMoveCountArray[32]; // [depth]
211 inline Value futility_margin(Depth d, int mn) { return Value(d < 7 * OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
212 inline int futility_move_count(Depth d) { return d < 16 * OnePly ? FutilityMoveCountArray[d] : 512; }
214 // Step 14. Reduced search
216 // Reduction lookup tables (initialized at startup) and their getter functions
217 int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
219 template <NodeType PV>
220 inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / 2, 63)][Min(mn, 63)]; }
222 // Common adjustments
224 // Search depth at iteration 1
225 const Depth InitialDepth = OnePly;
227 // Easy move margin. An easy move candidate must be at least this much
228 // better than the second best move.
229 const Value EasyMoveMargin = Value(0x200);
231 // Last seconds noise filtering (LSN)
232 const bool UseLSNFiltering = true;
233 const int LSNTime = 4000; // In milliseconds
234 const Value LSNValue = value_from_centipawns(200);
235 bool loseOnTime = false;
243 // Scores and number of times the best move changed for each iteration
244 Value ValueByIteration[PLY_MAX_PLUS_2];
245 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
247 // Search window management
253 // Time managment variables
254 int SearchStartTime, MaxNodes, MaxDepth, MaxSearchTime;
255 int AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
256 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
257 bool FirstRootMove, AbortSearch, Quit, AspirationFailLow;
261 std::ofstream LogFile;
263 // Multi-threads related variables
264 Depth MinimumSplitDepth;
265 int MaxThreadsPerSplitPoint;
268 // Node counters, used only by thread[0] but try to keep in different cache
269 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
271 int NodesBetweenPolls = 30000;
278 Value id_loop(const Position& pos, Move searchMoves[]);
279 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr);
281 template <NodeType PvNode>
282 Value search(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
284 template <NodeType PvNode>
285 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
287 template <NodeType PvNode>
288 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous);
290 void sp_search(SplitPoint* sp, int threadID);
291 void sp_search_pv(SplitPoint* sp, int threadID);
292 void init_node(SearchStack ss[], int ply, int threadID);
293 void update_pv(SearchStack ss[], int ply);
294 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
295 bool connected_moves(const Position& pos, Move m1, Move m2);
296 bool value_is_mate(Value value);
297 bool move_is_killer(Move m, const SearchStack& ss);
298 bool ok_to_do_nullmove(const Position& pos);
299 bool ok_to_prune(const Position& pos, Move m, Move threat);
300 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
301 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
302 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
303 void update_killers(Move m, SearchStack& ss);
304 void update_gains(const Position& pos, Move move, Value before, Value after);
306 int current_search_time();
310 void wait_for_stop_or_ponderhit();
311 void init_ss_array(SearchStack ss[]);
312 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value);
314 #if !defined(_MSC_VER)
315 void *init_thread(void *threadID);
317 DWORD WINAPI init_thread(LPVOID threadID);
327 /// init_threads(), exit_threads() and nodes_searched() are helpers to
328 /// give accessibility to some TM methods from outside of current file.
330 void init_threads() { TM.init_threads(); }
331 void exit_threads() { TM.exit_threads(); }
332 int64_t nodes_searched() { return TM.nodes_searched(); }
335 /// perft() is our utility to verify move generation is bug free. All the legal
336 /// moves up to given depth are generated and counted and the sum returned.
338 int perft(Position& pos, Depth depth)
343 MovePicker mp(pos, MOVE_NONE, depth, H);
345 // If we are at the last ply we don't need to do and undo
346 // the moves, just to count them.
347 if (depth <= OnePly) // Replace with '<' to test also qsearch
349 while (mp.get_next_move()) sum++;
353 // Loop through all legal moves
355 while ((move = mp.get_next_move()) != MOVE_NONE)
357 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
358 sum += perft(pos, depth - OnePly);
365 /// think() is the external interface to Stockfish's search, and is called when
366 /// the program receives the UCI 'go' command. It initializes various
367 /// search-related global variables, and calls root_search(). It returns false
368 /// when a quit command is received during the search.
370 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
371 int time[], int increment[], int movesToGo, int maxDepth,
372 int maxNodes, int maxTime, Move searchMoves[]) {
374 // Initialize global search variables
375 StopOnPonderhit = AbortSearch = Quit = AspirationFailLow = false;
376 MaxSearchTime = AbsoluteMaxSearchTime = ExtraSearchTime = 0;
378 TM.resetNodeCounters();
379 SearchStartTime = get_system_time();
380 ExactMaxTime = maxTime;
383 InfiniteSearch = infinite;
384 PonderSearch = ponder;
385 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
387 // Look for a book move, only during games, not tests
388 if (UseTimeManagement && get_option_value_bool("OwnBook"))
390 if (get_option_value_string("Book File") != OpeningBook.file_name())
391 OpeningBook.open(get_option_value_string("Book File"));
393 Move bookMove = OpeningBook.get_move(pos, get_option_value_bool("Best Book Move"));
394 if (bookMove != MOVE_NONE)
397 wait_for_stop_or_ponderhit();
399 cout << "bestmove " << bookMove << endl;
404 // Reset loseOnTime flag at the beginning of a new game
405 if (button_was_pressed("New Game"))
408 // Read UCI option values
409 TT.set_size(get_option_value_int("Hash"));
410 if (button_was_pressed("Clear Hash"))
413 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
414 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
415 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
416 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
417 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
418 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
419 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
420 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
421 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
422 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
423 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
424 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
426 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
427 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
428 MultiPV = get_option_value_int("MultiPV");
429 Chess960 = get_option_value_bool("UCI_Chess960");
430 UseLogFile = get_option_value_bool("Use Search Log");
433 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
435 read_weights(pos.side_to_move());
437 // Set the number of active threads
438 int newActiveThreads = get_option_value_int("Threads");
439 if (newActiveThreads != TM.active_threads())
441 TM.set_active_threads(newActiveThreads);
442 init_eval(TM.active_threads());
445 // Wake up sleeping threads
446 TM.wake_sleeping_threads();
449 int myTime = time[side_to_move];
450 int myIncrement = increment[side_to_move];
451 if (UseTimeManagement)
453 if (!movesToGo) // Sudden death time control
457 MaxSearchTime = myTime / 30 + myIncrement;
458 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
460 else // Blitz game without increment
462 MaxSearchTime = myTime / 30;
463 AbsoluteMaxSearchTime = myTime / 8;
466 else // (x moves) / (y minutes)
470 MaxSearchTime = myTime / 2;
471 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
475 MaxSearchTime = myTime / Min(movesToGo, 20);
476 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
480 if (get_option_value_bool("Ponder"))
482 MaxSearchTime += MaxSearchTime / 4;
483 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
487 // Set best NodesBetweenPolls interval to avoid lagging under
488 // heavy time pressure.
490 NodesBetweenPolls = Min(MaxNodes, 30000);
491 else if (myTime && myTime < 1000)
492 NodesBetweenPolls = 1000;
493 else if (myTime && myTime < 5000)
494 NodesBetweenPolls = 5000;
496 NodesBetweenPolls = 30000;
498 // Write search information to log file
500 LogFile << "Searching: " << pos.to_fen() << endl
501 << "infinite: " << infinite
502 << " ponder: " << ponder
503 << " time: " << myTime
504 << " increment: " << myIncrement
505 << " moves to go: " << movesToGo << endl;
507 // LSN filtering. Used only for developing purposes, disabled by default
511 // Step 2. If after last move we decided to lose on time, do it now!
512 while (SearchStartTime + myTime + 1000 > get_system_time())
516 // We're ready to start thinking. Call the iterative deepening loop function
517 Value v = id_loop(pos, searchMoves);
521 // Step 1. If this is sudden death game and our position is hopeless,
522 // decide to lose on time.
523 if ( !loseOnTime // If we already lost on time, go to step 3.
533 // Step 3. Now after stepping over the time limit, reset flag for next match.
541 TM.put_threads_to_sleep();
547 /// init_search() is called during startup. It initializes various lookup tables
551 // Init our reduction lookup tables
552 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
553 for (int j = 1; j < 64; j++) // j == moveNumber
555 double pvRed = log(double(i)) * log(double(j)) / 3.0;
556 double nonPVRed = log(double(i)) * log(double(j)) / 1.5;
557 ReductionMatrix[PV][i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
558 ReductionMatrix[NonPV][i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
561 // Init futility margins array
562 for (int i = 0; i < 16; i++) // i == depth (OnePly = 2)
563 for (int j = 0; j < 64; j++) // j == moveNumber
565 // FIXME: test using log instead of BSR
566 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j + 45;
569 // Init futility move count array
570 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
571 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
575 // SearchStack::init() initializes a search stack. Used at the beginning of a
576 // new search from the root.
577 void SearchStack::init(int ply) {
579 pv[ply] = pv[ply + 1] = MOVE_NONE;
580 currentMove = threatMove = MOVE_NONE;
581 reduction = Depth(0);
585 void SearchStack::initKillers() {
587 mateKiller = MOVE_NONE;
588 for (int i = 0; i < KILLER_MAX; i++)
589 killers[i] = MOVE_NONE;
594 // id_loop() is the main iterative deepening loop. It calls root_search
595 // repeatedly with increasing depth until the allocated thinking time has
596 // been consumed, the user stops the search, or the maximum search depth is
599 Value id_loop(const Position& pos, Move searchMoves[]) {
602 SearchStack ss[PLY_MAX_PLUS_2];
603 Move EasyMove = MOVE_NONE;
604 Value value, alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
606 // Moves to search are verified, copied, scored and sorted
607 RootMoveList rml(p, searchMoves);
609 // Handle special case of searching on a mate/stale position
610 if (rml.move_count() == 0)
613 wait_for_stop_or_ponderhit();
615 return pos.is_check() ? -VALUE_MATE : VALUE_DRAW;
618 // Print RootMoveList startup scoring to the standard output,
619 // so to output information also for iteration 1.
620 cout << "info depth " << 1
621 << "\ninfo depth " << 1
622 << " score " << value_to_string(rml.get_move_score(0))
623 << " time " << current_search_time()
624 << " nodes " << TM.nodes_searched()
626 << " pv " << rml.get_move(0) << "\n";
632 ValueByIteration[1] = rml.get_move_score(0);
635 // Is one move significantly better than others after initial scoring ?
636 if ( rml.move_count() == 1
637 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
638 EasyMove = rml.get_move(0);
640 // Iterative deepening loop
641 while (Iteration < PLY_MAX)
643 // Initialize iteration
645 BestMoveChangesByIteration[Iteration] = 0;
647 cout << "info depth " << Iteration << endl;
649 // Calculate dynamic aspiration window based on previous iterations
650 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
652 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
653 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
655 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
656 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
658 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
659 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
662 // Search to the current depth, rml is updated and sorted, alpha and beta could change
663 value = root_search(p, ss, rml, &alpha, &beta);
665 // Write PV to transposition table, in case the relevant entries have
666 // been overwritten during the search.
667 TT.insert_pv(p, ss[0].pv);
670 break; // Value cannot be trusted. Break out immediately!
672 //Save info about search result
673 ValueByIteration[Iteration] = value;
675 // Drop the easy move if differs from the new best move
676 if (ss[0].pv[0] != EasyMove)
677 EasyMove = MOVE_NONE;
679 if (UseTimeManagement)
682 bool stopSearch = false;
684 // Stop search early if there is only a single legal move,
685 // we search up to Iteration 6 anyway to get a proper score.
686 if (Iteration >= 6 && rml.move_count() == 1)
689 // Stop search early when the last two iterations returned a mate score
691 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
692 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
695 // Stop search early if one move seems to be much better than the others
696 int64_t nodes = TM.nodes_searched();
698 && EasyMove == ss[0].pv[0]
699 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
700 && current_search_time() > MaxSearchTime / 16)
701 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
702 && current_search_time() > MaxSearchTime / 32)))
705 // Add some extra time if the best move has changed during the last two iterations
706 if (Iteration > 5 && Iteration <= 50)
707 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
708 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
710 // Stop search if most of MaxSearchTime is consumed at the end of the
711 // iteration. We probably don't have enough time to search the first
712 // move at the next iteration anyway.
713 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
719 StopOnPonderhit = true;
725 if (MaxDepth && Iteration >= MaxDepth)
729 // If we are pondering or in infinite search, we shouldn't print the
730 // best move before we are told to do so.
731 if (!AbortSearch && (PonderSearch || InfiniteSearch))
732 wait_for_stop_or_ponderhit();
734 // Print final search statistics
735 cout << "info nodes " << TM.nodes_searched()
737 << " time " << current_search_time()
738 << " hashfull " << TT.full() << endl;
740 // Print the best move and the ponder move to the standard output
741 if (ss[0].pv[0] == MOVE_NONE)
743 ss[0].pv[0] = rml.get_move(0);
744 ss[0].pv[1] = MOVE_NONE;
747 assert(ss[0].pv[0] != MOVE_NONE);
749 cout << "bestmove " << ss[0].pv[0];
751 if (ss[0].pv[1] != MOVE_NONE)
752 cout << " ponder " << ss[0].pv[1];
759 dbg_print_mean(LogFile);
761 if (dbg_show_hit_rate)
762 dbg_print_hit_rate(LogFile);
764 LogFile << "\nNodes: " << TM.nodes_searched()
765 << "\nNodes/second: " << nps()
766 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
769 p.do_move(ss[0].pv[0], st);
770 LogFile << "\nPonder move: "
771 << move_to_san(p, ss[0].pv[1]) // Works also with MOVE_NONE
774 return rml.get_move_score(0);
778 // root_search() is the function which searches the root node. It is
779 // similar to search_pv except that it uses a different move ordering
780 // scheme, prints some information to the standard output and handles
781 // the fail low/high loops.
783 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr) {
790 Depth depth, ext, newDepth;
791 Value value, alpha, beta;
792 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
793 int researchCountFH, researchCountFL;
795 researchCountFH = researchCountFL = 0;
798 isCheck = pos.is_check();
800 // Step 1. Initialize node and poll (omitted at root, but I can see no good reason for this, FIXME)
801 // Step 2. Check for aborted search (omitted at root, because we do not initialize root node)
802 // Step 3. Mate distance pruning (omitted at root)
803 // Step 4. Transposition table lookup (omitted at root)
805 // Step 5. Evaluate the position statically
806 // At root we do this only to get reference value for child nodes
808 ss[0].eval = evaluate(pos, ei, 0);
810 ss[0].eval = VALUE_NONE; // HACK because we do not initialize root node
812 // Step 6. Razoring (omitted at root)
813 // Step 7. Static null move pruning (omitted at root)
814 // Step 8. Null move search with verification search (omitted at root)
815 // Step 9. Internal iterative deepening (omitted at root)
817 // Step extra. Fail low loop
818 // We start with small aspiration window and in case of fail low, we research
819 // with bigger window until we are not failing low anymore.
822 // Sort the moves before to (re)search
825 // Step 10. Loop through all moves in the root move list
826 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
828 // This is used by time management
829 FirstRootMove = (i == 0);
831 // Save the current node count before the move is searched
832 nodes = TM.nodes_searched();
834 // Reset beta cut-off counters
835 TM.resetBetaCounters();
837 // Pick the next root move, and print the move and the move number to
838 // the standard output.
839 move = ss[0].currentMove = rml.get_move(i);
841 if (current_search_time() >= 1000)
842 cout << "info currmove " << move
843 << " currmovenumber " << i + 1 << endl;
845 moveIsCheck = pos.move_is_check(move);
846 captureOrPromotion = pos.move_is_capture_or_promotion(move);
848 // Step 11. Decide the new search depth
849 depth = (Iteration - 2) * OnePly + InitialDepth;
850 ext = extension<PV>(pos, move, captureOrPromotion, moveIsCheck, false, false, &dangerous);
851 newDepth = depth + ext;
853 // Step 12. Futility pruning (omitted at root)
855 // Step extra. Fail high loop
856 // If move fails high, we research with bigger window until we are not failing
858 value = - VALUE_INFINITE;
862 // Step 13. Make the move
863 pos.do_move(move, st, ci, moveIsCheck);
865 // Step extra. pv search
866 // We do pv search for first moves (i < MultiPV)
867 // and for fail high research (value > alpha)
868 if (i < MultiPV || value > alpha)
870 // Aspiration window is disabled in multi-pv case
872 alpha = -VALUE_INFINITE;
874 // Full depth PV search, done on first move or after a fail high
875 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, 1, false, 0);
879 // Step 14. Reduced search
880 // if the move fails high will be re-searched at full depth
881 bool doFullDepthSearch = true;
883 if ( depth >= 3 * OnePly
885 && !captureOrPromotion
886 && !move_is_castle(move))
888 ss[0].reduction = reduction<PV>(depth, i - MultiPV + 2);
891 // Reduced depth non-pv search using alpha as upperbound
892 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth-ss[0].reduction, 1, true, 0);
893 doFullDepthSearch = (value > alpha);
897 // Step 15. Full depth search
898 if (doFullDepthSearch)
900 // Full depth non-pv search using alpha as upperbound
901 ss[0].reduction = Depth(0);
902 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth, 1, true, 0);
904 // If we are above alpha then research at same depth but as PV
905 // to get a correct score or eventually a fail high above beta.
907 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, 1, false, 0);
911 // Step 16. Undo move
914 // Can we exit fail high loop ?
915 if (AbortSearch || value < beta)
918 // We are failing high and going to do a research. It's important to update
919 // the score before research in case we run out of time while researching.
920 rml.set_move_score(i, value);
922 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
923 rml.set_move_pv(i, ss[0].pv);
925 // Print information to the standard output
926 print_pv_info(pos, ss, alpha, beta, value);
928 // Prepare for a research after a fail high, each time with a wider window
929 *betaPtr = beta = Min(beta + AspirationDelta * (1 << researchCountFH), VALUE_INFINITE);
932 } // End of fail high loop
934 // Finished searching the move. If AbortSearch is true, the search
935 // was aborted because the user interrupted the search or because we
936 // ran out of time. In this case, the return value of the search cannot
937 // be trusted, and we break out of the loop without updating the best
942 // Remember beta-cutoff and searched nodes counts for this move. The
943 // info is used to sort the root moves for the next iteration.
945 TM.get_beta_counters(pos.side_to_move(), our, their);
946 rml.set_beta_counters(i, our, their);
947 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
949 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
950 assert(value < beta);
952 // Step 17. Check for new best move
953 if (value <= alpha && i >= MultiPV)
954 rml.set_move_score(i, -VALUE_INFINITE);
957 // PV move or new best move!
960 rml.set_move_score(i, value);
962 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
963 rml.set_move_pv(i, ss[0].pv);
967 // We record how often the best move has been changed in each
968 // iteration. This information is used for time managment: When
969 // the best move changes frequently, we allocate some more time.
971 BestMoveChangesByIteration[Iteration]++;
973 // Print information to the standard output
974 print_pv_info(pos, ss, alpha, beta, value);
976 // Raise alpha to setup proper non-pv search upper bound
983 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
985 cout << "info multipv " << j + 1
986 << " score " << value_to_string(rml.get_move_score(j))
987 << " depth " << (j <= i ? Iteration : Iteration - 1)
988 << " time " << current_search_time()
989 << " nodes " << TM.nodes_searched()
993 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
994 cout << rml.get_move_pv(j, k) << " ";
998 alpha = rml.get_move_score(Min(i, MultiPV - 1));
1000 } // PV move or new best move
1002 assert(alpha >= *alphaPtr);
1004 AspirationFailLow = (alpha == *alphaPtr);
1006 if (AspirationFailLow && StopOnPonderhit)
1007 StopOnPonderhit = false;
1010 // Can we exit fail low loop ?
1011 if (AbortSearch || !AspirationFailLow)
1014 // Prepare for a research after a fail low, each time with a wider window
1015 *alphaPtr = alpha = Max(alpha - AspirationDelta * (1 << researchCountFL), -VALUE_INFINITE);
1020 // Sort the moves before to return
1027 // search<>() is the main search function for both PV and non-PV nodes
1029 template <NodeType PvNode>
1030 Value search(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth,
1031 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1033 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1034 assert(beta > alpha && beta <= VALUE_INFINITE);
1035 assert(PvNode || alpha == beta - 1);
1036 assert(ply >= 0 && ply < PLY_MAX);
1037 assert(threadID >= 0 && threadID < TM.active_threads());
1039 Move movesSearched[256];
1044 Depth ext, newDepth;
1045 Value bestValue, value, oldAlpha;
1046 Value refinedValue, nullValue, futilityValueScaled; // Non-PV specific
1047 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1048 bool mateThreat = false;
1050 refinedValue = bestValue = value = -VALUE_INFINITE;
1054 return qsearch<PvNode>(pos, ss, alpha, beta, Depth(0), ply, threadID);
1056 // Step 1. Initialize node and poll
1057 // Polling can abort search.
1058 init_node(ss, ply, threadID);
1060 // Step 2. Check for aborted search and immediate draw
1061 if (AbortSearch || TM.thread_should_stop(threadID))
1064 if (pos.is_draw() || ply >= PLY_MAX - 1)
1067 // Step 3. Mate distance pruning
1068 alpha = Max(value_mated_in(ply), alpha);
1069 beta = Min(value_mate_in(ply+1), beta);
1073 // Step 4. Transposition table lookup
1075 // We don't want the score of a partial search to overwrite a previous full search
1076 // TT value, so we use a different position key in case of an excluded move exists.
1077 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1079 tte = TT.retrieve(posKey);
1080 ttMove = (tte ? tte->move() : MOVE_NONE);
1082 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1083 // This is to avoid problems in the following areas:
1085 // * Repetition draw detection
1086 // * Fifty move rule detection
1087 // * Searching for a mate
1088 // * Printing of full PV line
1090 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1092 // Refresh tte entry to avoid aging
1093 TT.store(posKey, tte->value(), tte->type(), tte->depth(), ttMove);
1095 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1096 return value_from_tt(tte->value(), ply);
1099 // Step 5. Evaluate the position statically
1100 // At PV nodes we do this only to update gain statistics
1101 isCheck = pos.is_check();
1104 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1105 ss[ply].eval = value_from_tt(tte->value(), ply);
1107 ss[ply].eval = evaluate(pos, ei, threadID);
1109 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1110 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1113 // Step 6. Razoring (is omitted in PV nodes)
1115 && refinedValue < beta - razor_margin(depth)
1116 && ttMove == MOVE_NONE
1117 && ss[ply - 1].currentMove != MOVE_NULL
1118 && depth < RazorDepth
1120 && !value_is_mate(beta)
1121 && !pos.has_pawn_on_7th(pos.side_to_move()))
1123 Value rbeta = beta - razor_margin(depth);
1124 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1126 // Logically we should return (v + razor_margin(depth)), but
1127 // surprisingly this did slightly weaker in tests.
1131 // Step 7. Static null move pruning (is omitted in PV nodes)
1132 // We're betting that the opponent doesn't have a move that will reduce
1133 // the score by more than futility_margin(depth) if we do a null move.
1136 && depth < RazorDepth
1138 && !value_is_mate(beta)
1139 && ok_to_do_nullmove(pos)
1140 && refinedValue >= beta + futility_margin(depth, 0))
1141 return refinedValue - futility_margin(depth, 0);
1143 // Step 8. Null move search with verification search (is omitted in PV nodes)
1144 // When we jump directly to qsearch() we do a null move only if static value is
1145 // at least beta. Otherwise we do a null move if static value is not more than
1146 // NullMoveMargin under beta.
1151 && !value_is_mate(beta)
1152 && ok_to_do_nullmove(pos)
1153 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1155 ss[ply].currentMove = MOVE_NULL;
1157 // Null move dynamic reduction based on depth
1158 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1160 // Null move dynamic reduction based on value
1161 if (refinedValue - beta > PawnValueMidgame)
1164 pos.do_null_move(st);
1166 nullValue = -search<NonPV>(pos, ss, -beta, -alpha, depth-R*OnePly, ply+1, false, threadID);
1168 pos.undo_null_move();
1170 if (nullValue >= beta)
1172 // Do not return unproven mate scores
1173 if (nullValue >= value_mate_in(PLY_MAX))
1176 if (depth < 6 * OnePly)
1179 // Do zugzwang verification search
1180 Value v = search<NonPV>(pos, ss, alpha, beta, depth-5*OnePly, ply, false, threadID);
1184 // The null move failed low, which means that we may be faced with
1185 // some kind of threat. If the previous move was reduced, check if
1186 // the move that refuted the null move was somehow connected to the
1187 // move which was reduced. If a connection is found, return a fail
1188 // low score (which will cause the reduced move to fail high in the
1189 // parent node, which will trigger a re-search with full depth).
1190 if (nullValue == value_mated_in(ply + 2))
1193 ss[ply].threatMove = ss[ply + 1].currentMove;
1194 if ( depth < ThreatDepth
1195 && ss[ply - 1].reduction
1196 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1201 // Step 9. Internal iterative deepening
1202 if ( depth >= IIDDepth[PvNode]
1203 && ttMove == MOVE_NONE
1204 && (PvNode || (!isCheck && ss[ply].eval >= beta - IIDMargin)))
1206 Depth d = (PvNode ? depth - 2 * OnePly : depth / 2);
1207 search<PvNode>(pos, ss, alpha, beta, d, ply, false, threadID);
1208 ttMove = ss[ply].pv[ply];
1209 tte = TT.retrieve(posKey);
1212 // Expensive mate threat detection (only for PV nodes)
1214 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1216 // Initialize a MovePicker object for the current position
1217 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply], (PvNode ? -VALUE_INFINITE : beta));
1220 // Step 10. Loop through moves
1221 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1222 while ( bestValue < beta
1223 && (move = mp.get_next_move()) != MOVE_NONE
1224 && !TM.thread_should_stop(threadID))
1226 assert(move_is_ok(move));
1228 if (move == excludedMove)
1231 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1232 moveIsCheck = pos.move_is_check(move, ci);
1233 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1235 // Step 11. Decide the new search depth
1236 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1238 // Singular extension search. We extend the TT move if its value is much better than
1239 // its siblings. To verify this we do a reduced search on all the other moves but the
1240 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1241 if ( depth >= SingularExtensionDepth[PvNode]
1243 && move == tte->move()
1244 && !excludedMove // Do not allow recursive singular extension search
1246 && is_lower_bound(tte->type())
1247 && tte->depth() >= depth - 3 * OnePly)
1249 Value ttValue = value_from_tt(tte->value(), ply);
1251 if (abs(ttValue) < VALUE_KNOWN_WIN)
1253 Value b = ttValue - SingularExtensionMargin;
1254 Value v = search<NonPV>(pos, ss, b - 1, b, depth / 2, ply, false, threadID, move);
1256 if (v < ttValue - SingularExtensionMargin)
1261 newDepth = depth - OnePly + ext;
1263 // Update current move (this must be done after singular extension search)
1264 movesSearched[moveCount++] = ss[ply].currentMove = move;
1266 // Step 12. Futility pruning (is omitted in PV nodes)
1270 && !captureOrPromotion
1271 && !move_is_castle(move)
1274 // Move count based pruning
1275 if ( moveCount >= futility_move_count(depth)
1276 && ok_to_prune(pos, move, ss[ply].threatMove)
1277 && bestValue > value_mated_in(PLY_MAX))
1280 // Value based pruning
1281 Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount); // FIXME We illogically ignore reduction condition depth >= 3*OnePly
1282 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1283 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1285 if (futilityValueScaled < beta)
1287 if (futilityValueScaled > bestValue)
1288 bestValue = futilityValueScaled;
1293 // Step 13. Make the move
1294 pos.do_move(move, st, ci, moveIsCheck);
1296 // Step extra. pv search (only in PV nodes)
1297 // The first move in list is the expected PV
1298 if (PvNode && moveCount == 1)
1299 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, ply+1, false, threadID);
1302 // Step 14. Reduced search
1303 // if the move fails high will be re-searched at full depth.
1304 bool doFullDepthSearch = true;
1306 if ( depth >= 3 * OnePly
1308 && !captureOrPromotion
1309 && !move_is_castle(move)
1310 && !move_is_killer(move, ss[ply]))
1312 ss[ply].reduction = reduction<PvNode>(depth, moveCount);
1313 if (ss[ply].reduction)
1315 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1316 doFullDepthSearch = (value > alpha);
1320 // Step 15. Full depth search
1321 if (doFullDepthSearch)
1323 ss[ply].reduction = Depth(0);
1324 value = -search<NonPV>(pos, ss, -(alpha+1), -alpha, newDepth, ply+1, true, threadID);
1326 // Step extra. pv search (only in PV nodes)
1327 // Search only for possible new PV nodes, if instead value >= beta then
1328 // parent node fails low with value <= alpha and tries another move.
1329 if (PvNode && value > alpha && value < beta)
1330 value = -search<PV>(pos, ss, -beta, -alpha, newDepth, ply+1, false, threadID);
1334 // Step 16. Undo move
1335 pos.undo_move(move);
1337 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1339 // Step 17. Check for new best move
1340 if (value > bestValue)
1347 if (value == value_mate_in(ply + 1))
1348 ss[ply].mateKiller = move;
1352 // Step 18. Check for split
1353 if ( TM.active_threads() > 1
1355 && depth >= MinimumSplitDepth
1357 && TM.available_thread_exists(threadID)
1359 && !TM.thread_should_stop(threadID)
1360 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1361 depth, mateThreat, &moveCount, &mp, threadID, PvNode))
1365 // Step 19. Check for mate and stalemate
1366 // All legal moves have been searched and if there are
1367 // no legal moves, it must be mate or stalemate.
1368 // If one move was excluded return fail low score.
1370 return excludedMove ? oldAlpha : (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1372 // Step 20. Update tables
1373 // If the search is not aborted, update the transposition table,
1374 // history counters, and killer moves.
1375 if (AbortSearch || TM.thread_should_stop(threadID))
1378 if (bestValue <= oldAlpha)
1379 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1381 else if (bestValue >= beta)
1383 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1384 move = ss[ply].pv[ply];
1385 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1386 if (!pos.move_is_capture_or_promotion(move))
1388 update_history(pos, move, depth, movesSearched, moveCount);
1389 update_killers(move, ss[ply]);
1393 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1395 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1401 // qsearch() is the quiescence search function, which is called by the main
1402 // search function when the remaining depth is zero (or, to be more precise,
1403 // less than OnePly).
1405 template <NodeType PvNode>
1406 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1407 Depth depth, int ply, int threadID) {
1409 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1410 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1411 assert(PvNode || alpha == beta - 1);
1413 assert(ply >= 0 && ply < PLY_MAX);
1414 assert(threadID >= 0 && threadID < TM.active_threads());
1419 Value staticValue, bestValue, value, futilityBase, futilityValue;
1420 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1421 const TTEntry* tte = NULL;
1423 Value oldAlpha = alpha;
1425 // Initialize, and make an early exit in case of an aborted search,
1426 // an instant draw, maximum ply reached, etc.
1427 init_node(ss, ply, threadID);
1429 // After init_node() that calls poll()
1430 if (AbortSearch || TM.thread_should_stop(threadID))
1433 if (pos.is_draw() || ply >= PLY_MAX - 1)
1436 // Transposition table lookup. At PV nodes, we don't use the TT for
1437 // pruning, but only for move ordering.
1438 tte = TT.retrieve(pos.get_key());
1439 ttMove = (tte ? tte->move() : MOVE_NONE);
1441 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1443 assert(tte->type() != VALUE_TYPE_EVAL);
1445 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1446 return value_from_tt(tte->value(), ply);
1449 isCheck = pos.is_check();
1451 // Evaluate the position statically
1453 staticValue = -VALUE_INFINITE;
1454 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1455 staticValue = value_from_tt(tte->value(), ply);
1457 staticValue = evaluate(pos, ei, threadID);
1461 ss[ply].eval = staticValue;
1462 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1465 // Initialize "stand pat score", and return it immediately if it is
1467 bestValue = staticValue;
1469 if (bestValue >= beta)
1471 // Store the score to avoid a future costly evaluation() call
1472 if (!isCheck && !tte && ei.kingDanger[pos.side_to_move()] == 0)
1473 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1478 if (bestValue > alpha)
1481 // If we are near beta then try to get a cutoff pushing checks a bit further
1482 bool deepChecks = (depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8);
1484 // Initialize a MovePicker object for the current position, and prepare
1485 // to search the moves. Because the depth is <= 0 here, only captures,
1486 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1487 // and we are near beta) will be generated.
1488 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1490 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1491 futilityBase = staticValue + FutilityMarginQS + ei.kingDanger[pos.side_to_move()];
1493 // Loop through the moves until no moves remain or a beta cutoff occurs
1494 while ( alpha < beta
1495 && (move = mp.get_next_move()) != MOVE_NONE)
1497 assert(move_is_ok(move));
1499 moveIsCheck = pos.move_is_check(move, ci);
1501 // Update current move
1503 ss[ply].currentMove = move;
1511 && !move_is_promotion(move)
1512 && !pos.move_is_passed_pawn_push(move))
1514 futilityValue = futilityBase
1515 + pos.endgame_value_of_piece_on(move_to(move))
1516 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1518 if (futilityValue < alpha)
1520 if (futilityValue > bestValue)
1521 bestValue = futilityValue;
1526 // Detect blocking evasions that are candidate to be pruned
1527 evasionPrunable = isCheck
1528 && bestValue > value_mated_in(PLY_MAX)
1529 && !pos.move_is_capture(move)
1530 && pos.type_of_piece_on(move_from(move)) != KING
1531 && !pos.can_castle(pos.side_to_move());
1533 // Don't search moves with negative SEE values
1535 && (!isCheck || evasionPrunable)
1537 && !move_is_promotion(move)
1538 && pos.see_sign(move) < 0)
1541 // Make and search the move
1542 pos.do_move(move, st, ci, moveIsCheck);
1543 value = -qsearch<PvNode>(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1544 pos.undo_move(move);
1546 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1549 if (value > bestValue)
1560 // All legal moves have been searched. A special case: If we're in check
1561 // and no legal moves were found, it is checkmate.
1562 if (!moveCount && isCheck) // Mate!
1563 return value_mated_in(ply);
1565 // Update transposition table
1566 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1567 if (bestValue <= oldAlpha)
1569 // If bestValue isn't changed it means it is still the static evaluation
1570 // of the node, so keep this info to avoid a future evaluation() call.
1571 ValueType type = (bestValue == staticValue && !ei.kingDanger[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1572 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1574 else if (bestValue >= beta)
1576 move = ss[ply].pv[ply];
1577 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1579 // Update killers only for good checking moves
1580 if (!pos.move_is_capture_or_promotion(move))
1581 update_killers(move, ss[ply]);
1584 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1586 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1592 // sp_search() is used to search from a split point. This function is called
1593 // by each thread working at the split point. It is similar to the normal
1594 // search() function, but simpler. Because we have already probed the hash
1595 // table, done a null move search, and searched the first move before
1596 // splitting, we don't have to repeat all this work in sp_search(). We
1597 // also don't need to store anything to the hash table here: This is taken
1598 // care of after we return from the split point.
1600 void sp_search(SplitPoint* sp, int threadID) {
1602 assert(threadID >= 0 && threadID < TM.active_threads());
1603 assert(TM.active_threads() > 1);
1607 Depth ext, newDepth;
1608 Value value, futilityValueScaled;
1609 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1611 value = -VALUE_INFINITE;
1613 Position pos(*sp->pos);
1615 SearchStack* ss = sp->sstack[threadID];
1616 isCheck = pos.is_check();
1618 // Step 10. Loop through moves
1619 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1620 lock_grab(&(sp->lock));
1622 while ( sp->bestValue < sp->beta
1623 && !TM.thread_should_stop(threadID)
1624 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1626 moveCount = ++sp->moves;
1627 lock_release(&(sp->lock));
1629 assert(move_is_ok(move));
1631 moveIsCheck = pos.move_is_check(move, ci);
1632 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1634 // Step 11. Decide the new search depth
1635 ext = extension<NonPV>(pos, move, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1636 newDepth = sp->depth - OnePly + ext;
1638 // Update current move
1639 ss[sp->ply].currentMove = move;
1641 // Step 12. Futility pruning
1644 && !captureOrPromotion
1645 && !move_is_castle(move))
1647 // Move count based pruning
1648 if ( moveCount >= futility_move_count(sp->depth)
1649 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1650 && sp->bestValue > value_mated_in(PLY_MAX))
1652 lock_grab(&(sp->lock));
1656 // Value based pruning
1657 Depth predictedDepth = newDepth - reduction<NonPV>(sp->depth, moveCount);
1658 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1659 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1661 if (futilityValueScaled < sp->beta)
1663 lock_grab(&(sp->lock));
1665 if (futilityValueScaled > sp->bestValue)
1666 sp->bestValue = futilityValueScaled;
1671 // Step 13. Make the move
1672 pos.do_move(move, st, ci, moveIsCheck);
1674 // Step 14. Reduced search
1675 // if the move fails high will be re-searched at full depth.
1676 bool doFullDepthSearch = true;
1679 && !captureOrPromotion
1680 && !move_is_castle(move)
1681 && !move_is_killer(move, ss[sp->ply]))
1683 ss[sp->ply].reduction = reduction<NonPV>(sp->depth, moveCount);
1684 if (ss[sp->ply].reduction)
1686 value = -search<NonPV>(pos, ss, -(sp->alpha+1), -(sp->alpha), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1687 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1691 // Step 15. Full depth search
1692 if (doFullDepthSearch)
1694 ss[sp->ply].reduction = Depth(0);
1695 value = -search<NonPV>(pos, ss, -(sp->alpha+1), -(sp->alpha), newDepth, sp->ply+1, true, threadID);
1698 // Step 16. Undo move
1699 pos.undo_move(move);
1701 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1703 // Step 17. Check for new best move
1704 lock_grab(&(sp->lock));
1706 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1708 sp->bestValue = value;
1709 if (sp->bestValue >= sp->beta)
1711 sp->stopRequest = true;
1712 sp_update_pv(sp->parentSstack, ss, sp->ply);
1717 /* Here we have the lock still grabbed */
1719 sp->slaves[threadID] = 0;
1722 lock_release(&(sp->lock));
1726 // sp_search_pv() is used to search from a PV split point. This function
1727 // is called by each thread working at the split point. It is similar to
1728 // the normal search_pv() function, but simpler. Because we have already
1729 // probed the hash table and searched the first move before splitting, we
1730 // don't have to repeat all this work in sp_search_pv(). We also don't
1731 // need to store anything to the hash table here: This is taken care of
1732 // after we return from the split point.
1734 void sp_search_pv(SplitPoint* sp, int threadID) {
1736 assert(threadID >= 0 && threadID < TM.active_threads());
1737 assert(TM.active_threads() > 1);
1741 Depth ext, newDepth;
1743 bool moveIsCheck, captureOrPromotion, dangerous;
1745 value = -VALUE_INFINITE;
1747 Position pos(*sp->pos);
1749 SearchStack* ss = sp->sstack[threadID];
1751 // Step 10. Loop through moves
1752 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1753 lock_grab(&(sp->lock));
1755 while ( sp->alpha < sp->beta
1756 && !TM.thread_should_stop(threadID)
1757 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1759 moveCount = ++sp->moves;
1760 lock_release(&(sp->lock));
1762 assert(move_is_ok(move));
1764 moveIsCheck = pos.move_is_check(move, ci);
1765 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1767 // Step 11. Decide the new search depth
1768 ext = extension<PV>(pos, move, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1769 newDepth = sp->depth - OnePly + ext;
1771 // Update current move
1772 ss[sp->ply].currentMove = move;
1774 // Step 12. Futility pruning (is omitted in PV nodes)
1776 // Step 13. Make the move
1777 pos.do_move(move, st, ci, moveIsCheck);
1779 // Step 14. Reduced search
1780 // if the move fails high will be re-searched at full depth.
1781 bool doFullDepthSearch = true;
1784 && !captureOrPromotion
1785 && !move_is_castle(move)
1786 && !move_is_killer(move, ss[sp->ply]))
1788 ss[sp->ply].reduction = reduction<PV>(sp->depth, moveCount);
1789 if (ss[sp->ply].reduction)
1791 Value localAlpha = sp->alpha;
1792 value = -search<NonPV>(pos, ss, -(localAlpha+1), -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1793 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
1797 // Step 15. Full depth search
1798 if (doFullDepthSearch)
1800 Value localAlpha = sp->alpha;
1801 ss[sp->ply].reduction = Depth(0);
1802 value = -search<NonPV>(pos, ss, -(localAlpha+1), -localAlpha, newDepth, sp->ply+1, true, threadID);
1804 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
1806 // If another thread has failed high then sp->alpha has been increased
1807 // to be higher or equal then beta, if so, avoid to start a PV search.
1808 localAlpha = sp->alpha;
1809 if (localAlpha < sp->beta)
1810 value = -search<PV>(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, false, threadID);
1814 // Step 16. Undo move
1815 pos.undo_move(move);
1817 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1819 // Step 17. Check for new best move
1820 lock_grab(&(sp->lock));
1822 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1824 sp->bestValue = value;
1825 if (value > sp->alpha)
1827 // Ask threads to stop before to modify sp->alpha
1828 if (value >= sp->beta)
1829 sp->stopRequest = true;
1833 sp_update_pv(sp->parentSstack, ss, sp->ply);
1834 if (value == value_mate_in(sp->ply + 1))
1835 ss[sp->ply].mateKiller = move;
1840 /* Here we have the lock still grabbed */
1842 sp->slaves[threadID] = 0;
1845 lock_release(&(sp->lock));
1849 // init_node() is called at the beginning of all the search functions
1850 // (search() qsearch(), and so on) and initializes the
1851 // search stack object corresponding to the current node. Once every
1852 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1853 // for user input and checks whether it is time to stop the search.
1855 void init_node(SearchStack ss[], int ply, int threadID) {
1857 assert(ply >= 0 && ply < PLY_MAX);
1858 assert(threadID >= 0 && threadID < TM.active_threads());
1860 TM.incrementNodeCounter(threadID);
1865 if (NodesSincePoll >= NodesBetweenPolls)
1872 ss[ply + 2].initKillers();
1876 // update_pv() is called whenever a search returns a value > alpha.
1877 // It updates the PV in the SearchStack object corresponding to the
1880 void update_pv(SearchStack ss[], int ply) {
1882 assert(ply >= 0 && ply < PLY_MAX);
1886 ss[ply].pv[ply] = ss[ply].currentMove;
1888 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
1889 ss[ply].pv[p] = ss[ply + 1].pv[p];
1891 ss[ply].pv[p] = MOVE_NONE;
1895 // sp_update_pv() is a variant of update_pv for use at split points. The
1896 // difference between the two functions is that sp_update_pv also updates
1897 // the PV at the parent node.
1899 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
1901 assert(ply >= 0 && ply < PLY_MAX);
1905 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1907 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
1908 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
1910 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1914 // connected_moves() tests whether two moves are 'connected' in the sense
1915 // that the first move somehow made the second move possible (for instance
1916 // if the moving piece is the same in both moves). The first move is assumed
1917 // to be the move that was made to reach the current position, while the
1918 // second move is assumed to be a move from the current position.
1920 bool connected_moves(const Position& pos, Move m1, Move m2) {
1922 Square f1, t1, f2, t2;
1925 assert(move_is_ok(m1));
1926 assert(move_is_ok(m2));
1928 if (m2 == MOVE_NONE)
1931 // Case 1: The moving piece is the same in both moves
1937 // Case 2: The destination square for m2 was vacated by m1
1943 // Case 3: Moving through the vacated square
1944 if ( piece_is_slider(pos.piece_on(f2))
1945 && bit_is_set(squares_between(f2, t2), f1))
1948 // Case 4: The destination square for m2 is defended by the moving piece in m1
1949 p = pos.piece_on(t1);
1950 if (bit_is_set(pos.attacks_from(p, t1), t2))
1953 // Case 5: Discovered check, checking piece is the piece moved in m1
1954 if ( piece_is_slider(p)
1955 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1956 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1958 // discovered_check_candidates() works also if the Position's side to
1959 // move is the opposite of the checking piece.
1960 Color them = opposite_color(pos.side_to_move());
1961 Bitboard dcCandidates = pos.discovered_check_candidates(them);
1963 if (bit_is_set(dcCandidates, f2))
1970 // value_is_mate() checks if the given value is a mate one
1971 // eventually compensated for the ply.
1973 bool value_is_mate(Value value) {
1975 assert(abs(value) <= VALUE_INFINITE);
1977 return value <= value_mated_in(PLY_MAX)
1978 || value >= value_mate_in(PLY_MAX);
1982 // move_is_killer() checks if the given move is among the
1983 // killer moves of that ply.
1985 bool move_is_killer(Move m, const SearchStack& ss) {
1987 const Move* k = ss.killers;
1988 for (int i = 0; i < KILLER_MAX; i++, k++)
1996 // extension() decides whether a move should be searched with normal depth,
1997 // or with extended depth. Certain classes of moves (checking moves, in
1998 // particular) are searched with bigger depth than ordinary moves and in
1999 // any case are marked as 'dangerous'. Note that also if a move is not
2000 // extended, as example because the corresponding UCI option is set to zero,
2001 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2002 template <NodeType PvNode>
2003 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck,
2004 bool singleEvasion, bool mateThreat, bool* dangerous) {
2006 assert(m != MOVE_NONE);
2008 Depth result = Depth(0);
2009 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2014 result += CheckExtension[PvNode];
2017 result += SingleEvasionExtension[PvNode];
2020 result += MateThreatExtension[PvNode];
2023 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2025 Color c = pos.side_to_move();
2026 if (relative_rank(c, move_to(m)) == RANK_7)
2028 result += PawnPushTo7thExtension[PvNode];
2031 if (pos.pawn_is_passed(c, move_to(m)))
2033 result += PassedPawnExtension[PvNode];
2038 if ( captureOrPromotion
2039 && pos.type_of_piece_on(move_to(m)) != PAWN
2040 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2041 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2042 && !move_is_promotion(m)
2045 result += PawnEndgameExtension[PvNode];
2050 && captureOrPromotion
2051 && pos.type_of_piece_on(move_to(m)) != PAWN
2052 && pos.see_sign(m) >= 0)
2058 return Min(result, OnePly);
2062 // ok_to_do_nullmove() looks at the current position and decides whether
2063 // doing a 'null move' should be allowed. In order to avoid zugzwang
2064 // problems, null moves are not allowed when the side to move has very
2065 // little material left. Currently, the test is a bit too simple: Null
2066 // moves are avoided only when the side to move has only pawns left.
2067 // It's probably a good idea to avoid null moves in at least some more
2068 // complicated endgames, e.g. KQ vs KR. FIXME
2070 bool ok_to_do_nullmove(const Position& pos) {
2072 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2076 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2077 // non-tactical moves late in the move list close to the leaves are
2078 // candidates for pruning.
2080 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2082 assert(move_is_ok(m));
2083 assert(threat == MOVE_NONE || move_is_ok(threat));
2084 assert(!pos.move_is_check(m));
2085 assert(!pos.move_is_capture_or_promotion(m));
2086 assert(!pos.move_is_passed_pawn_push(m));
2088 Square mfrom, mto, tfrom, tto;
2090 // Prune if there isn't any threat move
2091 if (threat == MOVE_NONE)
2094 mfrom = move_from(m);
2096 tfrom = move_from(threat);
2097 tto = move_to(threat);
2099 // Case 1: Don't prune moves which move the threatened piece
2103 // Case 2: If the threatened piece has value less than or equal to the
2104 // value of the threatening piece, don't prune move which defend it.
2105 if ( pos.move_is_capture(threat)
2106 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2107 || pos.type_of_piece_on(tfrom) == KING)
2108 && pos.move_attacks_square(m, tto))
2111 // Case 3: If the moving piece in the threatened move is a slider, don't
2112 // prune safe moves which block its ray.
2113 if ( piece_is_slider(pos.piece_on(tfrom))
2114 && bit_is_set(squares_between(tfrom, tto), mto)
2115 && pos.see_sign(m) >= 0)
2122 // ok_to_use_TT() returns true if a transposition table score
2123 // can be used at a given point in search.
2125 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2127 Value v = value_from_tt(tte->value(), ply);
2129 return ( tte->depth() >= depth
2130 || v >= Max(value_mate_in(PLY_MAX), beta)
2131 || v < Min(value_mated_in(PLY_MAX), beta))
2133 && ( (is_lower_bound(tte->type()) && v >= beta)
2134 || (is_upper_bound(tte->type()) && v < beta));
2138 // refine_eval() returns the transposition table score if
2139 // possible otherwise falls back on static position evaluation.
2141 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2146 Value v = value_from_tt(tte->value(), ply);
2148 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2149 || (is_upper_bound(tte->type()) && v < defaultEval))
2156 // update_history() registers a good move that produced a beta-cutoff
2157 // in history and marks as failures all the other moves of that ply.
2159 void update_history(const Position& pos, Move move, Depth depth,
2160 Move movesSearched[], int moveCount) {
2164 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2166 for (int i = 0; i < moveCount - 1; i++)
2168 m = movesSearched[i];
2172 if (!pos.move_is_capture_or_promotion(m))
2173 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2178 // update_killers() add a good move that produced a beta-cutoff
2179 // among the killer moves of that ply.
2181 void update_killers(Move m, SearchStack& ss) {
2183 if (m == ss.killers[0])
2186 for (int i = KILLER_MAX - 1; i > 0; i--)
2187 ss.killers[i] = ss.killers[i - 1];
2193 // update_gains() updates the gains table of a non-capture move given
2194 // the static position evaluation before and after the move.
2196 void update_gains(const Position& pos, Move m, Value before, Value after) {
2199 && before != VALUE_NONE
2200 && after != VALUE_NONE
2201 && pos.captured_piece() == NO_PIECE_TYPE
2202 && !move_is_castle(m)
2203 && !move_is_promotion(m))
2204 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2208 // current_search_time() returns the number of milliseconds which have passed
2209 // since the beginning of the current search.
2211 int current_search_time() {
2213 return get_system_time() - SearchStartTime;
2217 // nps() computes the current nodes/second count.
2221 int t = current_search_time();
2222 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2226 // poll() performs two different functions: It polls for user input, and it
2227 // looks at the time consumed so far and decides if it's time to abort the
2232 static int lastInfoTime;
2233 int t = current_search_time();
2238 // We are line oriented, don't read single chars
2239 std::string command;
2241 if (!std::getline(std::cin, command))
2244 if (command == "quit")
2247 PonderSearch = false;
2251 else if (command == "stop")
2254 PonderSearch = false;
2256 else if (command == "ponderhit")
2260 // Print search information
2264 else if (lastInfoTime > t)
2265 // HACK: Must be a new search where we searched less than
2266 // NodesBetweenPolls nodes during the first second of search.
2269 else if (t - lastInfoTime >= 1000)
2276 if (dbg_show_hit_rate)
2277 dbg_print_hit_rate();
2279 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2280 << " time " << t << " hashfull " << TT.full() << endl;
2283 // Should we stop the search?
2287 bool stillAtFirstMove = FirstRootMove
2288 && !AspirationFailLow
2289 && t > MaxSearchTime + ExtraSearchTime;
2291 bool noMoreTime = t > AbsoluteMaxSearchTime
2292 || stillAtFirstMove;
2294 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2295 || (ExactMaxTime && t >= ExactMaxTime)
2296 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2301 // ponderhit() is called when the program is pondering (i.e. thinking while
2302 // it's the opponent's turn to move) in order to let the engine know that
2303 // it correctly predicted the opponent's move.
2307 int t = current_search_time();
2308 PonderSearch = false;
2310 bool stillAtFirstMove = FirstRootMove
2311 && !AspirationFailLow
2312 && t > MaxSearchTime + ExtraSearchTime;
2314 bool noMoreTime = t > AbsoluteMaxSearchTime
2315 || stillAtFirstMove;
2317 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2322 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2324 void init_ss_array(SearchStack ss[]) {
2326 for (int i = 0; i < 3; i++)
2329 ss[i].initKillers();
2334 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2335 // while the program is pondering. The point is to work around a wrinkle in
2336 // the UCI protocol: When pondering, the engine is not allowed to give a
2337 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2338 // We simply wait here until one of these commands is sent, and return,
2339 // after which the bestmove and pondermove will be printed (in id_loop()).
2341 void wait_for_stop_or_ponderhit() {
2343 std::string command;
2347 if (!std::getline(std::cin, command))
2350 if (command == "quit")
2355 else if (command == "ponderhit" || command == "stop")
2361 // print_pv_info() prints to standard output and eventually to log file information on
2362 // the current PV line. It is called at each iteration or after a new pv is found.
2364 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value) {
2366 cout << "info depth " << Iteration
2367 << " score " << value_to_string(value)
2368 << ((value >= beta) ? " lowerbound" :
2369 ((value <= alpha)? " upperbound" : ""))
2370 << " time " << current_search_time()
2371 << " nodes " << TM.nodes_searched()
2375 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
2376 cout << ss[0].pv[j] << " ";
2382 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
2383 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
2385 LogFile << pretty_pv(pos, current_search_time(), Iteration,
2386 TM.nodes_searched(), value, type, ss[0].pv) << endl;
2391 // init_thread() is the function which is called when a new thread is
2392 // launched. It simply calls the idle_loop() function with the supplied
2393 // threadID. There are two versions of this function; one for POSIX
2394 // threads and one for Windows threads.
2396 #if !defined(_MSC_VER)
2398 void* init_thread(void *threadID) {
2400 TM.idle_loop(*(int*)threadID, NULL);
2406 DWORD WINAPI init_thread(LPVOID threadID) {
2408 TM.idle_loop(*(int*)threadID, NULL);
2415 /// The ThreadsManager class
2417 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2418 // get_beta_counters() are getters/setters for the per thread
2419 // counters used to sort the moves at root.
2421 void ThreadsManager::resetNodeCounters() {
2423 for (int i = 0; i < MAX_THREADS; i++)
2424 threads[i].nodes = 0ULL;
2427 void ThreadsManager::resetBetaCounters() {
2429 for (int i = 0; i < MAX_THREADS; i++)
2430 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2433 int64_t ThreadsManager::nodes_searched() const {
2435 int64_t result = 0ULL;
2436 for (int i = 0; i < ActiveThreads; i++)
2437 result += threads[i].nodes;
2442 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2445 for (int i = 0; i < MAX_THREADS; i++)
2447 our += threads[i].betaCutOffs[us];
2448 their += threads[i].betaCutOffs[opposite_color(us)];
2453 // idle_loop() is where the threads are parked when they have no work to do.
2454 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2455 // object for which the current thread is the master.
2457 void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2459 assert(threadID >= 0 && threadID < MAX_THREADS);
2463 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2464 // master should exit as last one.
2465 if (AllThreadsShouldExit)
2468 threads[threadID].state = THREAD_TERMINATED;
2472 // If we are not thinking, wait for a condition to be signaled
2473 // instead of wasting CPU time polling for work.
2474 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2477 assert(threadID != 0);
2478 threads[threadID].state = THREAD_SLEEPING;
2480 #if !defined(_MSC_VER)
2481 lock_grab(&WaitLock);
2482 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2483 pthread_cond_wait(&WaitCond, &WaitLock);
2484 lock_release(&WaitLock);
2486 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2490 // If thread has just woken up, mark it as available
2491 if (threads[threadID].state == THREAD_SLEEPING)
2492 threads[threadID].state = THREAD_AVAILABLE;
2494 // If this thread has been assigned work, launch a search
2495 if (threads[threadID].state == THREAD_WORKISWAITING)
2497 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2499 threads[threadID].state = THREAD_SEARCHING;
2501 if (threads[threadID].splitPoint->pvNode)
2502 sp_search_pv(threads[threadID].splitPoint, threadID);
2504 sp_search(threads[threadID].splitPoint, threadID);
2506 assert(threads[threadID].state == THREAD_SEARCHING);
2508 threads[threadID].state = THREAD_AVAILABLE;
2511 // If this thread is the master of a split point and all threads have
2512 // finished their work at this split point, return from the idle loop.
2513 if (sp && sp->cpus == 0)
2515 // Because sp->cpus is decremented under lock protection,
2516 // be sure sp->lock has been released before to proceed.
2517 lock_grab(&(sp->lock));
2518 lock_release(&(sp->lock));
2520 assert(threads[threadID].state == THREAD_AVAILABLE);
2522 threads[threadID].state = THREAD_SEARCHING;
2529 // init_threads() is called during startup. It launches all helper threads,
2530 // and initializes the split point stack and the global locks and condition
2533 void ThreadsManager::init_threads() {
2538 #if !defined(_MSC_VER)
2539 pthread_t pthread[1];
2542 // Initialize global locks
2543 lock_init(&MPLock, NULL);
2544 lock_init(&WaitLock, NULL);
2546 #if !defined(_MSC_VER)
2547 pthread_cond_init(&WaitCond, NULL);
2549 for (i = 0; i < MAX_THREADS; i++)
2550 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2553 // Initialize SplitPointStack locks
2554 for (i = 0; i < MAX_THREADS; i++)
2555 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2557 SplitPointStack[i][j].parent = NULL;
2558 lock_init(&(SplitPointStack[i][j].lock), NULL);
2561 // Will be set just before program exits to properly end the threads
2562 AllThreadsShouldExit = false;
2564 // Threads will be put to sleep as soon as created
2565 AllThreadsShouldSleep = true;
2567 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2569 threads[0].state = THREAD_SEARCHING;
2570 for (i = 1; i < MAX_THREADS; i++)
2571 threads[i].state = THREAD_AVAILABLE;
2573 // Launch the helper threads
2574 for (i = 1; i < MAX_THREADS; i++)
2577 #if !defined(_MSC_VER)
2578 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2580 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, NULL) != NULL);
2585 cout << "Failed to create thread number " << i << endl;
2586 Application::exit_with_failure();
2589 // Wait until the thread has finished launching and is gone to sleep
2590 while (threads[i].state != THREAD_SLEEPING) {}
2595 // exit_threads() is called when the program exits. It makes all the
2596 // helper threads exit cleanly.
2598 void ThreadsManager::exit_threads() {
2600 ActiveThreads = MAX_THREADS; // HACK
2601 AllThreadsShouldSleep = true; // HACK
2602 wake_sleeping_threads();
2604 // This makes the threads to exit idle_loop()
2605 AllThreadsShouldExit = true;
2607 // Wait for thread termination
2608 for (int i = 1; i < MAX_THREADS; i++)
2609 while (threads[i].state != THREAD_TERMINATED);
2611 // Now we can safely destroy the locks
2612 for (int i = 0; i < MAX_THREADS; i++)
2613 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2614 lock_destroy(&(SplitPointStack[i][j].lock));
2616 lock_destroy(&WaitLock);
2617 lock_destroy(&MPLock);
2621 // thread_should_stop() checks whether the thread should stop its search.
2622 // This can happen if a beta cutoff has occurred in the thread's currently
2623 // active split point, or in some ancestor of the current split point.
2625 bool ThreadsManager::thread_should_stop(int threadID) const {
2627 assert(threadID >= 0 && threadID < ActiveThreads);
2631 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent) {}
2636 // thread_is_available() checks whether the thread with threadID "slave" is
2637 // available to help the thread with threadID "master" at a split point. An
2638 // obvious requirement is that "slave" must be idle. With more than two
2639 // threads, this is not by itself sufficient: If "slave" is the master of
2640 // some active split point, it is only available as a slave to the other
2641 // threads which are busy searching the split point at the top of "slave"'s
2642 // split point stack (the "helpful master concept" in YBWC terminology).
2644 bool ThreadsManager::thread_is_available(int slave, int master) const {
2646 assert(slave >= 0 && slave < ActiveThreads);
2647 assert(master >= 0 && master < ActiveThreads);
2648 assert(ActiveThreads > 1);
2650 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2653 // Make a local copy to be sure doesn't change under our feet
2654 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2656 if (localActiveSplitPoints == 0)
2657 // No active split points means that the thread is available as
2658 // a slave for any other thread.
2661 if (ActiveThreads == 2)
2664 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2665 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2666 // could have been set to 0 by another thread leading to an out of bound access.
2667 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2674 // available_thread_exists() tries to find an idle thread which is available as
2675 // a slave for the thread with threadID "master".
2677 bool ThreadsManager::available_thread_exists(int master) const {
2679 assert(master >= 0 && master < ActiveThreads);
2680 assert(ActiveThreads > 1);
2682 for (int i = 0; i < ActiveThreads; i++)
2683 if (thread_is_available(i, master))
2690 // split() does the actual work of distributing the work at a node between
2691 // several threads at PV nodes. If it does not succeed in splitting the
2692 // node (because no idle threads are available, or because we have no unused
2693 // split point objects), the function immediately returns false. If
2694 // splitting is possible, a SplitPoint object is initialized with all the
2695 // data that must be copied to the helper threads (the current position and
2696 // search stack, alpha, beta, the search depth, etc.), and we tell our
2697 // helper threads that they have been assigned work. This will cause them
2698 // to instantly leave their idle loops and call sp_search_pv(). When all
2699 // threads have returned from sp_search_pv (or, equivalently, when
2700 // splitPoint->cpus becomes 0), split() returns true.
2702 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2703 Value* alpha, const Value beta, Value* bestValue,
2704 Depth depth, bool mateThreat, int* moves, MovePicker* mp, int master, bool pvNode) {
2707 assert(sstck != NULL);
2708 assert(ply >= 0 && ply < PLY_MAX);
2709 assert(*bestValue >= -VALUE_INFINITE);
2710 assert( ( pvNode && *bestValue <= *alpha)
2711 || (!pvNode && *bestValue < beta ));
2712 assert(!pvNode || *alpha < beta);
2713 assert(beta <= VALUE_INFINITE);
2714 assert(depth > Depth(0));
2715 assert(master >= 0 && master < ActiveThreads);
2716 assert(ActiveThreads > 1);
2718 SplitPoint* splitPoint;
2722 // If no other thread is available to help us, or if we have too many
2723 // active split points, don't split.
2724 if ( !available_thread_exists(master)
2725 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2727 lock_release(&MPLock);
2731 // Pick the next available split point object from the split point stack
2732 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2734 // Initialize the split point object
2735 splitPoint->parent = threads[master].splitPoint;
2736 splitPoint->stopRequest = false;
2737 splitPoint->ply = ply;
2738 splitPoint->depth = depth;
2739 splitPoint->mateThreat = mateThreat;
2740 splitPoint->alpha = *alpha;
2741 splitPoint->beta = beta;
2742 splitPoint->pvNode = pvNode;
2743 splitPoint->bestValue = *bestValue;
2744 splitPoint->master = master;
2745 splitPoint->mp = mp;
2746 splitPoint->moves = *moves;
2747 splitPoint->cpus = 1;
2748 splitPoint->pos = &p;
2749 splitPoint->parentSstack = sstck;
2750 for (int i = 0; i < ActiveThreads; i++)
2751 splitPoint->slaves[i] = 0;
2753 threads[master].splitPoint = splitPoint;
2754 threads[master].activeSplitPoints++;
2756 // If we are here it means we are not available
2757 assert(threads[master].state != THREAD_AVAILABLE);
2759 // Allocate available threads setting state to THREAD_BOOKED
2760 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2761 if (thread_is_available(i, master))
2763 threads[i].state = THREAD_BOOKED;
2764 threads[i].splitPoint = splitPoint;
2765 splitPoint->slaves[i] = 1;
2769 assert(splitPoint->cpus > 1);
2771 // We can release the lock because slave threads are already booked and master is not available
2772 lock_release(&MPLock);
2774 // Tell the threads that they have work to do. This will make them leave
2775 // their idle loop. But before copy search stack tail for each thread.
2776 for (int i = 0; i < ActiveThreads; i++)
2777 if (i == master || splitPoint->slaves[i])
2779 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2781 assert(i == master || threads[i].state == THREAD_BOOKED);
2783 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2786 // Everything is set up. The master thread enters the idle loop, from
2787 // which it will instantly launch a search, because its state is
2788 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2789 // idle loop, which means that the main thread will return from the idle
2790 // loop when all threads have finished their work at this split point
2791 // (i.e. when splitPoint->cpus == 0).
2792 idle_loop(master, splitPoint);
2794 // We have returned from the idle loop, which means that all threads are
2795 // finished. Update alpha and bestValue, and return.
2798 *alpha = splitPoint->alpha;
2799 *bestValue = splitPoint->bestValue;
2800 threads[master].activeSplitPoints--;
2801 threads[master].splitPoint = splitPoint->parent;
2803 lock_release(&MPLock);
2808 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2809 // to start a new search from the root.
2811 void ThreadsManager::wake_sleeping_threads() {
2813 assert(AllThreadsShouldSleep);
2814 assert(ActiveThreads > 0);
2816 AllThreadsShouldSleep = false;
2818 if (ActiveThreads == 1)
2821 #if !defined(_MSC_VER)
2822 pthread_mutex_lock(&WaitLock);
2823 pthread_cond_broadcast(&WaitCond);
2824 pthread_mutex_unlock(&WaitLock);
2826 for (int i = 1; i < MAX_THREADS; i++)
2827 SetEvent(SitIdleEvent[i]);
2833 // put_threads_to_sleep() makes all the threads go to sleep just before
2834 // to leave think(), at the end of the search. Threads should have already
2835 // finished the job and should be idle.
2837 void ThreadsManager::put_threads_to_sleep() {
2839 assert(!AllThreadsShouldSleep);
2841 // This makes the threads to go to sleep
2842 AllThreadsShouldSleep = true;
2845 /// The RootMoveList class
2847 // RootMoveList c'tor
2849 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2851 SearchStack ss[PLY_MAX_PLUS_2];
2852 MoveStack mlist[MaxRootMoves];
2854 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2856 // Generate all legal moves
2857 MoveStack* last = generate_moves(pos, mlist);
2859 // Add each move to the moves[] array
2860 for (MoveStack* cur = mlist; cur != last; cur++)
2862 bool includeMove = includeAllMoves;
2864 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2865 includeMove = (searchMoves[k] == cur->move);
2870 // Find a quick score for the move
2872 pos.do_move(cur->move, st);
2873 moves[count].move = cur->move;
2874 moves[count].score = -qsearch<PV>(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2875 moves[count].pv[0] = cur->move;
2876 moves[count].pv[1] = MOVE_NONE;
2877 pos.undo_move(cur->move);
2884 // RootMoveList simple methods definitions
2886 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2888 moves[moveNum].nodes = nodes;
2889 moves[moveNum].cumulativeNodes += nodes;
2892 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2894 moves[moveNum].ourBeta = our;
2895 moves[moveNum].theirBeta = their;
2898 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2902 for (j = 0; pv[j] != MOVE_NONE; j++)
2903 moves[moveNum].pv[j] = pv[j];
2905 moves[moveNum].pv[j] = MOVE_NONE;
2909 // RootMoveList::sort() sorts the root move list at the beginning of a new
2912 void RootMoveList::sort() {
2914 sort_multipv(count - 1); // Sort all items
2918 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2919 // list by their scores and depths. It is used to order the different PVs
2920 // correctly in MultiPV mode.
2922 void RootMoveList::sort_multipv(int n) {
2926 for (i = 1; i <= n; i++)
2928 RootMove rm = moves[i];
2929 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2930 moves[j] = moves[j - 1];