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-2009 Marco Costalba
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
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* waitSp);
86 bool split(const Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
87 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode);
90 friend void poll(SearchStack ss[], int ply);
93 volatile bool AllThreadsShouldExit, AllThreadsShouldSleep;
94 Thread threads[MAX_THREADS];
95 SplitPoint SplitPointStack[MAX_THREADS][ACTIVE_SPLIT_POINTS_MAX];
99 #if !defined(_MSC_VER)
100 pthread_cond_t WaitCond;
101 pthread_mutex_t WaitLock;
103 HANDLE SitIdleEvent[MAX_THREADS];
109 // RootMove struct is used for moves at the root at the tree. For each
110 // root move, we store a score, a node count, and a PV (really a refutation
111 // in the case of moves which fail low).
115 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
117 // RootMove::operator<() is the comparison function used when
118 // sorting the moves. A move m1 is considered to be better
119 // than a move m2 if it has a higher score, or if the moves
120 // have equal score but m1 has the higher node count.
121 bool operator<(const RootMove& m) const {
123 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
128 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
129 Move pv[PLY_MAX_PLUS_2];
133 // The RootMoveList class is essentially an array of RootMove objects, with
134 // a handful of methods for accessing the data in the individual moves.
139 RootMoveList(Position& pos, Move searchMoves[]);
141 int move_count() const { return count; }
142 Move get_move(int moveNum) const { return moves[moveNum].move; }
143 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
144 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
145 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
146 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
148 void set_move_nodes(int moveNum, int64_t nodes);
149 void set_beta_counters(int moveNum, int64_t our, int64_t their);
150 void set_move_pv(int moveNum, const Move pv[]);
152 void sort_multipv(int n);
155 static const int MaxRootMoves = 500;
156 RootMove moves[MaxRootMoves];
165 // Maximum depth for razoring
166 const Depth RazorDepth = 4 * OnePly;
168 // Dynamic razoring margin based on depth
169 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * d); }
171 // Step 8. Null move search with verification search
173 // Null move margin. A null move search will not be done if the static
174 // evaluation of the position is more than NullMoveMargin below beta.
175 const Value NullMoveMargin = Value(0x200);
177 // Maximum depth for use of dynamic threat detection when null move fails low
178 const Depth ThreatDepth = 5 * OnePly;
180 // Step 9. Internal iterative deepening
182 // Minimum depth for use of internal iterative deepening
183 const Depth IIDDepthAtPVNodes = 5 * OnePly;
184 const Depth IIDDepthAtNonPVNodes = 8 * OnePly;
186 // Internal iterative deepening margin. At Non-PV nodes
187 // we do an internal iterative deepening
188 // search when the static evaluation is at most IIDMargin below beta.
189 const Value IIDMargin = Value(0x100);
191 // Step 11. Decide the new search depth
193 // Extensions. Configurable UCI options.
194 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
195 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
196 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
198 // Minimum depth for use of singular extension
199 const Depth SingularExtensionDepthAtPVNodes = 6 * OnePly;
200 const Depth SingularExtensionDepthAtNonPVNodes = 8 * OnePly;
202 // If the TT move is at least SingularExtensionMargin better then the
203 // remaining ones we will extend it.
204 const Value SingularExtensionMargin = Value(0x20);
206 // Step 12. Futility pruning
208 // Futility margin for quiescence search
209 const Value FutilityMarginQS = Value(0x80);
211 // Futility lookup tables (initialized at startup) and their getter functions
212 int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
213 int FutilityMoveCountArray[32]; // [depth]
215 inline Value futility_margin(Depth d, int mn) { return Value(d < 7*OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
216 inline int futility_move_count(Depth d) { return d < 16*OnePly ? FutilityMoveCountArray[d] : 512; }
218 // Step 14. Reduced search
220 // Reduction lookup tables (initialized at startup) and their getter functions
221 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
222 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
224 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
225 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
227 // Step. Common adjustments
229 // Search depth at iteration 1
230 const Depth InitialDepth = OnePly;
232 // Easy move margin. An easy move candidate must be at least this much
233 // better than the second best move.
234 const Value EasyMoveMargin = Value(0x200);
236 // Last seconds noise filtering (LSN)
237 const bool UseLSNFiltering = true;
238 const int LSNTime = 4000; // In milliseconds
239 const Value LSNValue = value_from_centipawns(200);
240 bool loseOnTime = false;
245 // Iteration counters
248 // Scores and number of times the best move changed for each iteration
249 Value ValueByIteration[PLY_MAX_PLUS_2];
250 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
252 // Search window management
258 // Time managment variables
261 int MaxNodes, MaxDepth;
262 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
263 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
264 bool AbortSearch, Quit;
265 bool AspirationFailLow;
267 // Show current line?
268 bool ShowCurrentLine;
272 std::ofstream LogFile;
274 // MP related variables
275 Depth MinimumSplitDepth;
276 int MaxThreadsPerSplitPoint;
279 // Node counters, used only by thread[0] but try to keep in different
280 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
282 int NodesBetweenPolls = 30000;
289 Value id_loop(const Position& pos, Move searchMoves[]);
290 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
291 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
292 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
293 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
294 void sp_search(SplitPoint* sp, int threadID);
295 void sp_search_pv(SplitPoint* sp, int threadID);
296 void init_node(SearchStack ss[], int ply, int threadID);
297 void update_pv(SearchStack ss[], int ply);
298 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
299 bool connected_moves(const Position& pos, Move m1, Move m2);
300 bool value_is_mate(Value value);
301 bool move_is_killer(Move m, const SearchStack& ss);
302 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
303 bool ok_to_do_nullmove(const Position& pos);
304 bool ok_to_prune(const Position& pos, Move m, Move threat);
305 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
306 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
307 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
308 void update_killers(Move m, SearchStack& ss);
309 void update_gains(const Position& pos, Move move, Value before, Value after);
311 int current_search_time();
313 void poll(SearchStack ss[], int ply);
315 void wait_for_stop_or_ponderhit();
316 void init_ss_array(SearchStack ss[]);
318 #if !defined(_MSC_VER)
319 void *init_thread(void *threadID);
321 DWORD WINAPI init_thread(LPVOID threadID);
331 /// init_threads(), exit_threads() and nodes_searched() are helpers to
332 /// give accessibility to some TM methods from outside of current file.
334 void init_threads() { TM.init_threads(); }
335 void exit_threads() { TM.exit_threads(); }
336 int64_t nodes_searched() { return TM.nodes_searched(); }
339 /// perft() is our utility to verify move generation is bug free. All the legal
340 /// moves up to given depth are generated and counted and the sum returned.
342 int perft(Position& pos, Depth depth)
346 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
348 // If we are at the last ply we don't need to do and undo
349 // the moves, just to count them.
350 if (depth <= OnePly) // Replace with '<' to test also qsearch
352 while (mp.get_next_move()) sum++;
356 // Loop through all legal moves
358 while ((move = mp.get_next_move()) != MOVE_NONE)
361 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
362 sum += perft(pos, depth - OnePly);
369 /// think() is the external interface to Stockfish's search, and is called when
370 /// the program receives the UCI 'go' command. It initializes various
371 /// search-related global variables, and calls root_search(). It returns false
372 /// when a quit command is received during the search.
374 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
375 int time[], int increment[], int movesToGo, int maxDepth,
376 int maxNodes, int maxTime, Move searchMoves[]) {
378 // Initialize global search variables
379 StopOnPonderhit = AbortSearch = Quit = false;
380 AspirationFailLow = false;
382 SearchStartTime = get_system_time();
383 ExactMaxTime = maxTime;
386 InfiniteSearch = infinite;
387 PonderSearch = ponder;
388 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
390 // Look for a book move, only during games, not tests
391 if (UseTimeManagement && get_option_value_bool("OwnBook"))
394 if (get_option_value_string("Book File") != OpeningBook.file_name())
395 OpeningBook.open(get_option_value_string("Book File"));
397 bookMove = OpeningBook.get_move(pos);
398 if (bookMove != MOVE_NONE)
401 wait_for_stop_or_ponderhit();
403 cout << "bestmove " << bookMove << endl;
408 TM.resetNodeCounters();
410 if (button_was_pressed("New Game"))
411 loseOnTime = false; // Reset at the beginning of a new game
413 // Read UCI option values
414 TT.set_size(get_option_value_int("Hash"));
415 if (button_was_pressed("Clear Hash"))
418 bool PonderingEnabled = get_option_value_bool("Ponder");
419 MultiPV = get_option_value_int("MultiPV");
421 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
422 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
424 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
425 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
427 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
428 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
430 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
431 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
433 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
434 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
436 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
437 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
439 Chess960 = get_option_value_bool("UCI_Chess960");
440 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
441 UseLogFile = get_option_value_bool("Use Search Log");
443 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
445 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
446 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
448 read_weights(pos.side_to_move());
450 // Set the number of active threads
451 int newActiveThreads = get_option_value_int("Threads");
452 if (newActiveThreads != TM.active_threads())
454 TM.set_active_threads(newActiveThreads);
455 init_eval(TM.active_threads());
456 // HACK: init_eval() destroys the static castleRightsMask[] array in the
457 // Position class. The below line repairs the damage.
458 Position p(pos.to_fen());
462 // Wake up sleeping threads
463 TM.wake_sleeping_threads();
466 int myTime = time[side_to_move];
467 int myIncrement = increment[side_to_move];
468 if (UseTimeManagement)
470 if (!movesToGo) // Sudden death time control
474 MaxSearchTime = myTime / 30 + myIncrement;
475 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
477 else // Blitz game without increment
479 MaxSearchTime = myTime / 30;
480 AbsoluteMaxSearchTime = myTime / 8;
483 else // (x moves) / (y minutes)
487 MaxSearchTime = myTime / 2;
488 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
492 MaxSearchTime = myTime / Min(movesToGo, 20);
493 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
497 if (PonderingEnabled)
499 MaxSearchTime += MaxSearchTime / 4;
500 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
504 // Set best NodesBetweenPolls interval
506 NodesBetweenPolls = Min(MaxNodes, 30000);
507 else if (myTime && myTime < 1000)
508 NodesBetweenPolls = 1000;
509 else if (myTime && myTime < 5000)
510 NodesBetweenPolls = 5000;
512 NodesBetweenPolls = 30000;
514 // Write information to search log file
516 LogFile << "Searching: " << pos.to_fen() << endl
517 << "infinite: " << infinite
518 << " ponder: " << ponder
519 << " time: " << myTime
520 << " increment: " << myIncrement
521 << " moves to go: " << movesToGo << endl;
523 // LSN filtering. Used only for developing purpose. Disabled by default.
527 // Step 2. If after last move we decided to lose on time, do it now!
528 while (SearchStartTime + myTime + 1000 > get_system_time())
532 // We're ready to start thinking. Call the iterative deepening loop function
533 Value v = id_loop(pos, searchMoves);
537 // Step 1. If this is sudden death game and our position is hopeless,
538 // decide to lose on time.
539 if ( !loseOnTime // If we already lost on time, go to step 3.
549 // Step 3. Now after stepping over the time limit, reset flag for next match.
557 TM.put_threads_to_sleep();
563 /// init_search() is called during startup. It initializes various lookup tables
567 // Init our reduction lookup tables
568 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
569 for (int j = 1; j < 64; j++) // j == moveNumber
571 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
572 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
573 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
574 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
577 // Init futility margins array
578 for (int i = 0; i < 14; i++) // i == depth (OnePly = 2)
579 for (int j = 0; j < 64; j++) // j == moveNumber
581 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
584 // Init futility move count array
585 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
586 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
590 // SearchStack::init() initializes a search stack. Used at the beginning of a
591 // new search from the root.
592 void SearchStack::init(int ply) {
594 pv[ply] = pv[ply + 1] = MOVE_NONE;
595 currentMove = threatMove = MOVE_NONE;
596 reduction = Depth(0);
600 void SearchStack::initKillers() {
602 mateKiller = MOVE_NONE;
603 for (int i = 0; i < KILLER_MAX; i++)
604 killers[i] = MOVE_NONE;
609 // id_loop() is the main iterative deepening loop. It calls root_search
610 // repeatedly with increasing depth until the allocated thinking time has
611 // been consumed, the user stops the search, or the maximum search depth is
614 Value id_loop(const Position& pos, Move searchMoves[]) {
617 SearchStack ss[PLY_MAX_PLUS_2];
619 // searchMoves are verified, copied, scored and sorted
620 RootMoveList rml(p, searchMoves);
622 // Handle special case of searching on a mate/stale position
623 if (rml.move_count() == 0)
626 wait_for_stop_or_ponderhit();
628 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
631 // Print RootMoveList c'tor startup scoring to the standard output,
632 // so that we print information also for iteration 1.
633 cout << "info depth " << 1 << "\ninfo depth " << 1
634 << " score " << value_to_string(rml.get_move_score(0))
635 << " time " << current_search_time()
636 << " nodes " << TM.nodes_searched()
638 << " pv " << rml.get_move(0) << "\n";
644 ValueByIteration[1] = rml.get_move_score(0);
647 // Is one move significantly better than others after initial scoring ?
648 Move EasyMove = MOVE_NONE;
649 if ( rml.move_count() == 1
650 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
651 EasyMove = rml.get_move(0);
653 // Iterative deepening loop
654 while (Iteration < PLY_MAX)
656 // Initialize iteration
659 BestMoveChangesByIteration[Iteration] = 0;
663 cout << "info depth " << Iteration << endl;
665 // Calculate dynamic search window based on previous iterations
668 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
670 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
671 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
673 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
674 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
676 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
677 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
681 alpha = - VALUE_INFINITE;
682 beta = VALUE_INFINITE;
685 // Search to the current depth
686 Value value = root_search(p, ss, rml, alpha, beta);
688 // Write PV to transposition table, in case the relevant entries have
689 // been overwritten during the search.
690 TT.insert_pv(p, ss[0].pv);
693 break; // Value cannot be trusted. Break out immediately!
695 //Save info about search result
696 ValueByIteration[Iteration] = value;
698 // Drop the easy move if it differs from the new best move
699 if (ss[0].pv[0] != EasyMove)
700 EasyMove = MOVE_NONE;
702 if (UseTimeManagement)
705 bool stopSearch = false;
707 // Stop search early if there is only a single legal move,
708 // we search up to Iteration 6 anyway to get a proper score.
709 if (Iteration >= 6 && rml.move_count() == 1)
712 // Stop search early when the last two iterations returned a mate score
714 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
715 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
718 // Stop search early if one move seems to be much better than the rest
719 int64_t nodes = TM.nodes_searched();
721 && EasyMove == ss[0].pv[0]
722 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
723 && current_search_time() > MaxSearchTime / 16)
724 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
725 && current_search_time() > MaxSearchTime / 32)))
728 // Add some extra time if the best move has changed during the last two iterations
729 if (Iteration > 5 && Iteration <= 50)
730 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
731 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
733 // Stop search if most of MaxSearchTime is consumed at the end of the
734 // iteration. We probably don't have enough time to search the first
735 // move at the next iteration anyway.
736 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
744 StopOnPonderhit = true;
748 if (MaxDepth && Iteration >= MaxDepth)
754 // If we are pondering or in infinite search, we shouldn't print the
755 // best move before we are told to do so.
756 if (!AbortSearch && (PonderSearch || InfiniteSearch))
757 wait_for_stop_or_ponderhit();
759 // Print final search statistics
760 cout << "info nodes " << TM.nodes_searched()
762 << " time " << current_search_time()
763 << " hashfull " << TT.full() << endl;
765 // Print the best move and the ponder move to the standard output
766 if (ss[0].pv[0] == MOVE_NONE)
768 ss[0].pv[0] = rml.get_move(0);
769 ss[0].pv[1] = MOVE_NONE;
771 cout << "bestmove " << ss[0].pv[0];
772 if (ss[0].pv[1] != MOVE_NONE)
773 cout << " ponder " << ss[0].pv[1];
780 dbg_print_mean(LogFile);
782 if (dbg_show_hit_rate)
783 dbg_print_hit_rate(LogFile);
785 LogFile << "\nNodes: " << TM.nodes_searched()
786 << "\nNodes/second: " << nps()
787 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
790 p.do_move(ss[0].pv[0], st);
791 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
793 return rml.get_move_score(0);
797 // root_search() is the function which searches the root node. It is
798 // similar to search_pv except that it uses a different move ordering
799 // scheme and prints some information to the standard output.
801 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
806 Depth depth, ext, newDepth;
809 int researchCount = 0;
810 bool moveIsCheck, captureOrPromotion, dangerous;
811 Value alpha = oldAlpha;
812 bool isCheck = pos.is_check();
814 // Evaluate the position statically
816 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
818 while (1) // Fail low loop
821 // Loop through all the moves in the root move list
822 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
826 // We failed high, invalidate and skip next moves, leave node-counters
827 // and beta-counters as they are and quickly return, we will try to do
828 // a research at the next iteration with a bigger aspiration window.
829 rml.set_move_score(i, -VALUE_INFINITE);
833 RootMoveNumber = i + 1;
835 // Save the current node count before the move is searched
836 nodes = TM.nodes_searched();
838 // Reset beta cut-off counters
839 TM.resetBetaCounters();
841 // Pick the next root move, and print the move and the move number to
842 // the standard output.
843 move = ss[0].currentMove = rml.get_move(i);
845 if (current_search_time() >= 1000)
846 cout << "info currmove " << move
847 << " currmovenumber " << RootMoveNumber << endl;
849 // Decide search depth for this move
850 moveIsCheck = pos.move_is_check(move);
851 captureOrPromotion = pos.move_is_capture_or_promotion(move);
852 depth = (Iteration - 2) * OnePly + InitialDepth;
853 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
854 newDepth = depth + ext;
856 value = - VALUE_INFINITE;
858 while (1) // Fail high loop
861 // Make the move, and search it
862 pos.do_move(move, st, ci, moveIsCheck);
864 if (i < MultiPV || value > alpha)
866 // Aspiration window is disabled in multi-pv case
868 alpha = -VALUE_INFINITE;
870 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
874 // Try to reduce non-pv search depth by one ply if move seems not problematic,
875 // if the move fails high will be re-searched at full depth.
876 bool doFullDepthSearch = true;
878 if ( depth >= 3*OnePly // FIXME was newDepth
880 && !captureOrPromotion
881 && !move_is_castle(move))
883 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
886 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
887 doFullDepthSearch = (value > alpha);
891 if (doFullDepthSearch)
893 ss[0].reduction = Depth(0);
894 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
897 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
903 // Can we exit fail high loop ?
904 if (AbortSearch || value < beta)
907 // We are failing high and going to do a research. It's important to update score
908 // before research in case we run out of time while researching.
909 rml.set_move_score(i, value);
911 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
912 rml.set_move_pv(i, ss[0].pv);
914 // Print search information to the standard output
915 cout << "info depth " << Iteration
916 << " score " << value_to_string(value)
917 << ((value >= beta) ? " lowerbound" :
918 ((value <= alpha)? " upperbound" : ""))
919 << " time " << current_search_time()
920 << " nodes " << TM.nodes_searched()
924 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
925 cout << ss[0].pv[j] << " ";
931 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
932 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
934 LogFile << pretty_pv(pos, current_search_time(), Iteration,
935 TM.nodes_searched(), value, type, ss[0].pv) << endl;
938 // Prepare for a research after a fail high, each time with a wider window
940 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
942 } // End of fail high loop
944 // Finished searching the move. If AbortSearch is true, the search
945 // was aborted because the user interrupted the search or because we
946 // ran out of time. In this case, the return value of the search cannot
947 // be trusted, and we break out of the loop without updating the best
952 // Remember beta-cutoff and searched nodes counts for this move. The
953 // info is used to sort the root moves at the next iteration.
955 TM.get_beta_counters(pos.side_to_move(), our, their);
956 rml.set_beta_counters(i, our, their);
957 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
959 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
961 if (value <= alpha && i >= MultiPV)
962 rml.set_move_score(i, -VALUE_INFINITE);
965 // PV move or new best move!
968 rml.set_move_score(i, value);
970 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
971 rml.set_move_pv(i, ss[0].pv);
975 // We record how often the best move has been changed in each
976 // iteration. This information is used for time managment: When
977 // the best move changes frequently, we allocate some more time.
979 BestMoveChangesByIteration[Iteration]++;
981 // Print search information to the standard output
982 cout << "info depth " << Iteration
983 << " score " << value_to_string(value)
984 << ((value >= beta) ? " lowerbound" :
985 ((value <= alpha)? " upperbound" : ""))
986 << " time " << current_search_time()
987 << " nodes " << TM.nodes_searched()
991 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
992 cout << ss[0].pv[j] << " ";
998 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
999 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1001 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1002 TM.nodes_searched(), value, type, ss[0].pv) << endl;
1009 rml.sort_multipv(i);
1010 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1012 cout << "info multipv " << j + 1
1013 << " score " << value_to_string(rml.get_move_score(j))
1014 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1015 << " time " << current_search_time()
1016 << " nodes " << TM.nodes_searched()
1020 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1021 cout << rml.get_move_pv(j, k) << " ";
1025 alpha = rml.get_move_score(Min(i, MultiPV-1));
1027 } // PV move or new best move
1029 assert(alpha >= oldAlpha);
1031 AspirationFailLow = (alpha == oldAlpha);
1033 if (AspirationFailLow && StopOnPonderhit)
1034 StopOnPonderhit = false;
1037 // Can we exit fail low loop ?
1038 if (AbortSearch || alpha > oldAlpha)
1041 // Prepare for a research after a fail low, each time with a wider window
1043 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1052 // search_pv() is the main search function for PV nodes.
1054 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1055 Depth depth, int ply, int threadID) {
1057 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1058 assert(beta > alpha && beta <= VALUE_INFINITE);
1059 assert(ply >= 0 && ply < PLY_MAX);
1060 assert(threadID >= 0 && threadID < TM.active_threads());
1062 Move movesSearched[256];
1067 Depth ext, newDepth;
1068 Value bestValue, value, oldAlpha;
1069 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1070 bool mateThreat = false;
1072 bestValue = value = -VALUE_INFINITE;
1075 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1077 // Step 1. Initialize node and poll
1078 // Polling can abort search.
1079 init_node(ss, ply, threadID);
1081 // Step 2. Check for aborted search and immediate draw
1082 if (AbortSearch || TM.thread_should_stop(threadID))
1085 if (pos.is_draw() || ply >= PLY_MAX - 1)
1088 // Step 3. Mate distance pruning
1090 alpha = Max(value_mated_in(ply), alpha);
1091 beta = Min(value_mate_in(ply+1), beta);
1095 // Step 4. Transposition table lookup
1096 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1097 // This is to avoid problems in the following areas:
1099 // * Repetition draw detection
1100 // * Fifty move rule detection
1101 // * Searching for a mate
1102 // * Printing of full PV line
1103 tte = TT.retrieve(pos.get_key());
1104 ttMove = (tte ? tte->move() : MOVE_NONE);
1106 // Step 5. Evaluate the position statically
1107 // At PV nodes we do this only to update gain statistics
1108 isCheck = pos.is_check();
1111 ss[ply].eval = evaluate(pos, ei, threadID);
1112 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1115 // Step 6. Razoring (is omitted in PV nodes)
1116 // Step 7. Static null move pruning (is omitted in PV nodes)
1117 // Step 8. Null move search with verification search (is omitted in PV nodes)
1119 // Step 9. Internal iterative deepening
1120 if ( depth >= IIDDepthAtPVNodes
1121 && ttMove == MOVE_NONE)
1123 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1124 ttMove = ss[ply].pv[ply];
1125 tte = TT.retrieve(pos.get_key());
1128 // Step 10. Loop through moves
1129 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1131 // Initialize a MovePicker object for the current position
1132 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1133 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1136 while ( alpha < beta
1137 && (move = mp.get_next_move()) != MOVE_NONE
1138 && !TM.thread_should_stop(threadID))
1140 assert(move_is_ok(move));
1142 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1143 moveIsCheck = pos.move_is_check(move, ci);
1144 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1146 // Step 11. Decide the new search depth
1147 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1149 // Singular extension search. We extend the TT move if its value is much better than
1150 // its siblings. To verify this we do a reduced search on all the other moves but the
1151 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1152 if ( depth >= SingularExtensionDepthAtPVNodes
1154 && move == tte->move()
1156 && is_lower_bound(tte->type())
1157 && tte->depth() >= depth - 3 * OnePly)
1159 Value ttValue = value_from_tt(tte->value(), ply);
1161 if (abs(ttValue) < VALUE_KNOWN_WIN)
1163 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1165 if (excValue < ttValue - SingularExtensionMargin)
1170 newDepth = depth - OnePly + ext;
1172 // Update current move (this must be done after singular extension search)
1173 movesSearched[moveCount++] = ss[ply].currentMove = move;
1175 // Step 12. Futility pruning (is omitted in PV nodes)
1177 // Step 13. Make the move
1178 pos.do_move(move, st, ci, moveIsCheck);
1180 // Step extra. pv search (only in PV nodes)
1181 // The first move in list is the expected PV
1183 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1186 // Step 14. Reduced search
1187 // if the move fails high will be re-searched at full depth.
1188 bool doFullDepthSearch = true;
1190 if ( depth >= 3*OnePly
1192 && !captureOrPromotion
1193 && !move_is_castle(move)
1194 && !move_is_killer(move, ss[ply]))
1196 ss[ply].reduction = pv_reduction(depth, moveCount);
1197 if (ss[ply].reduction)
1199 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1200 doFullDepthSearch = (value > alpha);
1204 // Step 15. Full depth search
1205 if (doFullDepthSearch)
1207 ss[ply].reduction = Depth(0);
1208 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1210 // Step extra. pv search (only in PV nodes)
1211 if (value > alpha && value < beta)
1212 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1216 // Step 16. Undo move
1217 pos.undo_move(move);
1219 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1221 // Step 17. Check for new best move
1222 if (value > bestValue)
1229 if (value == value_mate_in(ply + 1))
1230 ss[ply].mateKiller = move;
1234 // Step 18. Check for split
1235 if ( TM.active_threads() > 1
1237 && depth >= MinimumSplitDepth
1239 && TM.available_thread_exists(threadID)
1241 && !TM.thread_should_stop(threadID)
1242 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1243 depth, &moveCount, &mp, threadID, true))
1247 // Step 19. Check for mate and stalemate
1248 // All legal moves have been searched and if there were
1249 // no legal moves, it must be mate or stalemate.
1251 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1253 // Step 20. Update tables
1254 // If the search is not aborted, update the transposition table,
1255 // history counters, and killer moves.
1256 if (AbortSearch || TM.thread_should_stop(threadID))
1259 if (bestValue <= oldAlpha)
1260 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1262 else if (bestValue >= beta)
1264 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1265 move = ss[ply].pv[ply];
1266 if (!pos.move_is_capture_or_promotion(move))
1268 update_history(pos, move, depth, movesSearched, moveCount);
1269 update_killers(move, ss[ply]);
1271 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1274 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1280 // search() is the search function for zero-width nodes.
1282 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1283 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1285 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1286 assert(ply >= 0 && ply < PLY_MAX);
1287 assert(threadID >= 0 && threadID < TM.active_threads());
1289 Move movesSearched[256];
1294 Depth ext, newDepth;
1295 Value bestValue, refinedValue, nullValue, value, futilityValueScaled;
1296 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1297 bool mateThreat = false;
1299 refinedValue = bestValue = value = -VALUE_INFINITE;
1302 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1304 // Step 1. Initialize node and poll
1305 // Polling can abort search.
1306 init_node(ss, ply, threadID);
1308 // Step 2. Check for aborted search and immediate draw
1309 if (AbortSearch || TM.thread_should_stop(threadID))
1312 if (pos.is_draw() || ply >= PLY_MAX - 1)
1315 // Step 3. Mate distance pruning
1316 if (value_mated_in(ply) >= beta)
1319 if (value_mate_in(ply + 1) < beta)
1322 // Step 4. Transposition table lookup
1324 // We don't want the score of a partial search to overwrite a previous full search
1325 // TT value, so we use a different position key in case of an excluded move exists.
1326 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1328 tte = TT.retrieve(posKey);
1329 ttMove = (tte ? tte->move() : MOVE_NONE);
1331 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1333 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1334 return value_from_tt(tte->value(), ply);
1337 // Step 5. Evaluate the position statically
1338 isCheck = pos.is_check();
1342 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1343 ss[ply].eval = value_from_tt(tte->value(), ply);
1345 ss[ply].eval = evaluate(pos, ei, threadID);
1347 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1348 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1352 if ( !value_is_mate(beta)
1354 && depth < RazorDepth
1355 && refinedValue < beta - razor_margin(depth)
1356 && ss[ply - 1].currentMove != MOVE_NULL
1357 && ttMove == MOVE_NONE
1358 && !pos.has_pawn_on_7th(pos.side_to_move()))
1360 Value rbeta = beta - razor_margin(depth);
1361 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1363 return v; //FIXME: Logically should be: return (v + razor_margin(depth));
1366 // Step 7. Static null move pruning
1367 // We're betting that the opponent doesn't have a move that will reduce
1368 // the score by more than fuility_margin(depth) if we do a null move.
1371 && depth < RazorDepth
1372 && refinedValue - futility_margin(depth, 0) >= beta)
1373 return refinedValue - futility_margin(depth, 0);
1375 // Step 8. Null move search with verification search
1376 // When we jump directly to qsearch() we do a null move only if static value is
1377 // at least beta. Otherwise we do a null move if static value is not more than
1378 // NullMoveMargin under beta.
1382 && !value_is_mate(beta)
1383 && ok_to_do_nullmove(pos)
1384 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1386 ss[ply].currentMove = MOVE_NULL;
1388 pos.do_null_move(st);
1390 // Null move dynamic reduction based on depth
1391 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1393 // Null move dynamic reduction based on value
1394 if (refinedValue - beta > PawnValueMidgame)
1397 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1399 pos.undo_null_move();
1401 if (nullValue >= beta)
1403 if (depth < 6 * OnePly)
1406 // Do zugzwang verification search
1407 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1411 // The null move failed low, which means that we may be faced with
1412 // some kind of threat. If the previous move was reduced, check if
1413 // the move that refuted the null move was somehow connected to the
1414 // move which was reduced. If a connection is found, return a fail
1415 // low score (which will cause the reduced move to fail high in the
1416 // parent node, which will trigger a re-search with full depth).
1417 if (nullValue == value_mated_in(ply + 2))
1420 ss[ply].threatMove = ss[ply + 1].currentMove;
1421 if ( depth < ThreatDepth
1422 && ss[ply - 1].reduction
1423 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1428 // Step 9. Internal iterative deepening
1429 if ( depth >= IIDDepthAtNonPVNodes
1430 && ttMove == MOVE_NONE
1432 && ss[ply].eval >= beta - IIDMargin)
1434 search(pos, ss, beta, depth/2, ply, false, threadID);
1435 ttMove = ss[ply].pv[ply];
1436 tte = TT.retrieve(posKey);
1439 // Step 10. Loop through moves
1440 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1442 // Initialize a MovePicker object for the current position
1443 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply], beta);
1446 while ( bestValue < beta
1447 && (move = mp.get_next_move()) != MOVE_NONE
1448 && !TM.thread_should_stop(threadID))
1450 assert(move_is_ok(move));
1452 if (move == excludedMove)
1455 moveIsCheck = pos.move_is_check(move, ci);
1456 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1457 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1459 // Step 11. Decide the new search depth
1460 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1462 // Singular extension search. We extend the TT move if its value is much better than
1463 // its siblings. To verify this we do a reduced search on all the other moves but the
1464 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1465 if ( depth >= SingularExtensionDepthAtNonPVNodes
1467 && move == tte->move()
1468 && !excludedMove // Do not allow recursive single-reply search
1470 && is_lower_bound(tte->type())
1471 && tte->depth() >= depth - 3 * OnePly)
1473 Value ttValue = value_from_tt(tte->value(), ply);
1475 if (abs(ttValue) < VALUE_KNOWN_WIN)
1477 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1479 if (excValue < ttValue - SingularExtensionMargin)
1484 newDepth = depth - OnePly + ext;
1486 // Update current move (this must be done after singular extension search)
1487 movesSearched[moveCount++] = ss[ply].currentMove = move;
1489 // Step 12. Futility pruning
1492 && !captureOrPromotion
1493 && !move_is_castle(move)
1496 // Move count based pruning
1497 if ( moveCount >= futility_move_count(depth)
1498 && ok_to_prune(pos, move, ss[ply].threatMove)
1499 && bestValue > value_mated_in(PLY_MAX))
1502 // Value based pruning
1503 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); // We illogically ignore reduction condition depth >= 3*OnePly
1504 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1505 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1507 if (futilityValueScaled < beta)
1509 if (futilityValueScaled > bestValue)
1510 bestValue = futilityValueScaled;
1515 // Step 13. Make the move
1516 pos.do_move(move, st, ci, moveIsCheck);
1518 // Step 14. Reduced search
1519 // if the move fails high will be re-searched at full depth.
1520 bool doFullDepthSearch = true;
1522 if ( depth >= 3*OnePly
1524 && !captureOrPromotion
1525 && !move_is_castle(move)
1526 && !move_is_killer(move, ss[ply]))
1528 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1529 if (ss[ply].reduction)
1531 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1532 doFullDepthSearch = (value >= beta);
1536 // Step 15. Full depth search
1537 if (doFullDepthSearch)
1539 ss[ply].reduction = Depth(0);
1540 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1543 // Step 16. Undo move
1544 pos.undo_move(move);
1546 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1548 // Step 17. Check for new best move
1549 if (value > bestValue)
1555 if (value == value_mate_in(ply + 1))
1556 ss[ply].mateKiller = move;
1559 // Step 18. Check for split
1560 if ( TM.active_threads() > 1
1562 && depth >= MinimumSplitDepth
1564 && TM.available_thread_exists(threadID)
1566 && !TM.thread_should_stop(threadID)
1567 && TM.split(pos, ss, ply, NULL, beta, &bestValue,
1568 depth, &moveCount, &mp, threadID, false))
1572 // Step 19. Check for mate and stalemate
1573 // All legal moves have been searched and if there were
1574 // no legal moves, it must be mate or stalemate.
1575 // If one move was excluded return fail low.
1577 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1579 // Step 20. Update tables
1580 // If the search is not aborted, update the transposition table,
1581 // history counters, and killer moves.
1582 if (AbortSearch || TM.thread_should_stop(threadID))
1585 if (bestValue < beta)
1586 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1589 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1590 move = ss[ply].pv[ply];
1591 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1592 if (!pos.move_is_capture_or_promotion(move))
1594 update_history(pos, move, depth, movesSearched, moveCount);
1595 update_killers(move, ss[ply]);
1600 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1606 // qsearch() is the quiescence search function, which is called by the main
1607 // search function when the remaining depth is zero (or, to be more precise,
1608 // less than OnePly).
1610 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1611 Depth depth, int ply, int threadID) {
1613 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1614 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1616 assert(ply >= 0 && ply < PLY_MAX);
1617 assert(threadID >= 0 && threadID < TM.active_threads());
1622 Value staticValue, bestValue, value, futilityBase, futilityValue;
1623 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1624 const TTEntry* tte = NULL;
1626 bool pvNode = (beta - alpha != 1);
1627 Value oldAlpha = alpha;
1629 // Initialize, and make an early exit in case of an aborted search,
1630 // an instant draw, maximum ply reached, etc.
1631 init_node(ss, ply, threadID);
1633 // After init_node() that calls poll()
1634 if (AbortSearch || TM.thread_should_stop(threadID))
1637 if (pos.is_draw() || ply >= PLY_MAX - 1)
1640 // Transposition table lookup. At PV nodes, we don't use the TT for
1641 // pruning, but only for move ordering.
1642 tte = TT.retrieve(pos.get_key());
1643 ttMove = (tte ? tte->move() : MOVE_NONE);
1645 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1647 assert(tte->type() != VALUE_TYPE_EVAL);
1649 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1650 return value_from_tt(tte->value(), ply);
1653 isCheck = pos.is_check();
1655 // Evaluate the position statically
1657 staticValue = -VALUE_INFINITE;
1658 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1659 staticValue = value_from_tt(tte->value(), ply);
1661 staticValue = evaluate(pos, ei, threadID);
1665 ss[ply].eval = staticValue;
1666 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1669 // Initialize "stand pat score", and return it immediately if it is
1671 bestValue = staticValue;
1673 if (bestValue >= beta)
1675 // Store the score to avoid a future costly evaluation() call
1676 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1677 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1682 if (bestValue > alpha)
1685 // If we are near beta then try to get a cutoff pushing checks a bit further
1686 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1688 // Initialize a MovePicker object for the current position, and prepare
1689 // to search the moves. Because the depth is <= 0 here, only captures,
1690 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1691 // and we are near beta) will be generated.
1692 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1694 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1695 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1697 // Loop through the moves until no moves remain or a beta cutoff
1699 while ( alpha < beta
1700 && (move = mp.get_next_move()) != MOVE_NONE)
1702 assert(move_is_ok(move));
1704 moveIsCheck = pos.move_is_check(move, ci);
1706 // Update current move
1708 ss[ply].currentMove = move;
1716 && !move_is_promotion(move)
1717 && !pos.move_is_passed_pawn_push(move))
1719 futilityValue = futilityBase
1720 + pos.endgame_value_of_piece_on(move_to(move))
1721 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1723 if (futilityValue < alpha)
1725 if (futilityValue > bestValue)
1726 bestValue = futilityValue;
1731 // Detect blocking evasions that are candidate to be pruned
1732 evasionPrunable = isCheck
1733 && bestValue != -VALUE_INFINITE
1734 && !pos.move_is_capture(move)
1735 && pos.type_of_piece_on(move_from(move)) != KING
1736 && !pos.can_castle(pos.side_to_move());
1738 // Don't search moves with negative SEE values
1739 if ( (!isCheck || evasionPrunable)
1742 && !move_is_promotion(move)
1743 && pos.see_sign(move) < 0)
1746 // Make and search the move
1747 pos.do_move(move, st, ci, moveIsCheck);
1748 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1749 pos.undo_move(move);
1751 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1754 if (value > bestValue)
1765 // All legal moves have been searched. A special case: If we're in check
1766 // and no legal moves were found, it is checkmate.
1767 if (!moveCount && pos.is_check()) // Mate!
1768 return value_mated_in(ply);
1770 // Update transposition table
1771 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1772 if (bestValue <= oldAlpha)
1774 // If bestValue isn't changed it means it is still the static evaluation
1775 // of the node, so keep this info to avoid a future evaluation() call.
1776 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1777 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1779 else if (bestValue >= beta)
1781 move = ss[ply].pv[ply];
1782 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1784 // Update killers only for good checking moves
1785 if (!pos.move_is_capture_or_promotion(move))
1786 update_killers(move, ss[ply]);
1789 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1791 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1797 // sp_search() is used to search from a split point. This function is called
1798 // by each thread working at the split point. It is similar to the normal
1799 // search() function, but simpler. Because we have already probed the hash
1800 // table, done a null move search, and searched the first move before
1801 // splitting, we don't have to repeat all this work in sp_search(). We
1802 // also don't need to store anything to the hash table here: This is taken
1803 // care of after we return from the split point.
1804 // FIXME: We are currently ignoring mateThreat flag here
1806 void sp_search(SplitPoint* sp, int threadID) {
1808 assert(threadID >= 0 && threadID < TM.active_threads());
1809 assert(TM.active_threads() > 1);
1813 Depth ext, newDepth;
1814 Value value, futilityValueScaled;
1815 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1817 value = -VALUE_INFINITE;
1819 Position pos(*sp->pos);
1821 SearchStack* ss = sp->sstack[threadID];
1822 isCheck = pos.is_check();
1824 // Step 10. Loop through moves
1825 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1826 lock_grab(&(sp->lock));
1828 while ( sp->bestValue < sp->beta
1829 && !TM.thread_should_stop(threadID)
1830 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1832 moveCount = ++sp->moves;
1833 lock_release(&(sp->lock));
1835 assert(move_is_ok(move));
1837 moveIsCheck = pos.move_is_check(move, ci);
1838 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1840 // Step 11. Decide the new search depth
1841 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1842 newDepth = sp->depth - OnePly + ext;
1844 // Update current move
1845 ss[sp->ply].currentMove = move;
1847 // Step 12. Futility pruning
1850 && !captureOrPromotion
1851 && !move_is_castle(move))
1853 // Move count based pruning
1854 if ( moveCount >= futility_move_count(sp->depth)
1855 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1856 && sp->bestValue > value_mated_in(PLY_MAX))
1858 lock_grab(&(sp->lock));
1862 // Value based pruning
1863 Depth predictedDepth = newDepth - nonpv_reduction(sp->depth, moveCount);
1864 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1865 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1867 if (futilityValueScaled < sp->beta)
1869 lock_grab(&(sp->lock));
1871 if (futilityValueScaled > sp->bestValue)
1872 sp->bestValue = futilityValueScaled;
1877 // Step 13. Make the move
1878 pos.do_move(move, st, ci, moveIsCheck);
1880 // Step 14. Reduced search
1881 // if the move fails high will be re-searched at full depth.
1882 bool doFullDepthSearch = true;
1885 && !captureOrPromotion
1886 && !move_is_castle(move)
1887 && !move_is_killer(move, ss[sp->ply]))
1889 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1890 if (ss[sp->ply].reduction)
1892 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1893 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1897 // Step 15. Full depth search
1898 if (doFullDepthSearch)
1900 ss[sp->ply].reduction = Depth(0);
1901 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1904 // Step 16. Undo move
1905 pos.undo_move(move);
1907 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1909 // Step 17. Check for new best move
1910 lock_grab(&(sp->lock));
1912 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1914 sp->bestValue = value;
1915 if (sp->bestValue >= sp->beta)
1917 sp->stopRequest = true;
1918 sp_update_pv(sp->parentSstack, ss, sp->ply);
1923 /* Here we have the lock still grabbed */
1925 sp->slaves[threadID] = 0;
1928 lock_release(&(sp->lock));
1932 // sp_search_pv() is used to search from a PV split point. This function
1933 // is called by each thread working at the split point. It is similar to
1934 // the normal search_pv() function, but simpler. Because we have already
1935 // probed the hash table and searched the first move before splitting, we
1936 // don't have to repeat all this work in sp_search_pv(). We also don't
1937 // need to store anything to the hash table here: This is taken care of
1938 // after we return from the split point.
1939 // FIXME: We are ignoring mateThreat flag!
1941 void sp_search_pv(SplitPoint* sp, int threadID) {
1943 assert(threadID >= 0 && threadID < TM.active_threads());
1944 assert(TM.active_threads() > 1);
1948 Depth ext, newDepth;
1950 bool moveIsCheck, captureOrPromotion, dangerous;
1952 value = -VALUE_INFINITE;
1954 Position pos(*sp->pos);
1956 SearchStack* ss = sp->sstack[threadID];
1958 // Step 10. Loop through moves
1959 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1960 lock_grab(&(sp->lock));
1962 while ( sp->alpha < sp->beta
1963 && !TM.thread_should_stop(threadID)
1964 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1966 moveCount = ++sp->moves;
1967 lock_release(&(sp->lock));
1969 assert(move_is_ok(move));
1971 moveIsCheck = pos.move_is_check(move, ci);
1972 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1974 // Step 11. Decide the new search depth
1975 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1976 newDepth = sp->depth - OnePly + ext;
1978 // Update current move
1979 ss[sp->ply].currentMove = move;
1981 // Step 12. Futility pruning (is omitted in PV nodes)
1983 // Step 13. Make the move
1984 pos.do_move(move, st, ci, moveIsCheck);
1986 // Step 14. Reduced search
1987 // if the move fails high will be re-searched at full depth.
1988 bool doFullDepthSearch = true;
1991 && !captureOrPromotion
1992 && !move_is_castle(move)
1993 && !move_is_killer(move, ss[sp->ply]))
1995 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
1996 if (ss[sp->ply].reduction)
1998 Value localAlpha = sp->alpha;
1999 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2000 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
2004 // Step 15. Full depth search
2005 if (doFullDepthSearch)
2007 Value localAlpha = sp->alpha;
2008 ss[sp->ply].reduction = Depth(0);
2009 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2011 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
2013 // If another thread has failed high then sp->alpha has been increased
2014 // to be higher or equal then beta, if so, avoid to start a PV search.
2015 localAlpha = sp->alpha;
2016 if (localAlpha < sp->beta)
2017 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2021 // Step 16. Undo move
2022 pos.undo_move(move);
2024 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2026 // Step 17. Check for new best move
2027 lock_grab(&(sp->lock));
2029 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
2031 sp->bestValue = value;
2032 if (value > sp->alpha)
2034 // Ask threads to stop before to modify sp->alpha
2035 if (value >= sp->beta)
2036 sp->stopRequest = true;
2040 sp_update_pv(sp->parentSstack, ss, sp->ply);
2041 if (value == value_mate_in(sp->ply + 1))
2042 ss[sp->ply].mateKiller = move;
2047 /* Here we have the lock still grabbed */
2049 sp->slaves[threadID] = 0;
2052 lock_release(&(sp->lock));
2056 // init_node() is called at the beginning of all the search functions
2057 // (search(), search_pv(), qsearch(), and so on) and initializes the
2058 // search stack object corresponding to the current node. Once every
2059 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2060 // for user input and checks whether it is time to stop the search.
2062 void init_node(SearchStack ss[], int ply, int threadID) {
2064 assert(ply >= 0 && ply < PLY_MAX);
2065 assert(threadID >= 0 && threadID < TM.active_threads());
2067 TM.incrementNodeCounter(threadID);
2072 if (NodesSincePoll >= NodesBetweenPolls)
2079 ss[ply + 2].initKillers();
2083 // update_pv() is called whenever a search returns a value > alpha.
2084 // It updates the PV in the SearchStack object corresponding to the
2087 void update_pv(SearchStack ss[], int ply) {
2089 assert(ply >= 0 && ply < PLY_MAX);
2093 ss[ply].pv[ply] = ss[ply].currentMove;
2095 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2096 ss[ply].pv[p] = ss[ply + 1].pv[p];
2098 ss[ply].pv[p] = MOVE_NONE;
2102 // sp_update_pv() is a variant of update_pv for use at split points. The
2103 // difference between the two functions is that sp_update_pv also updates
2104 // the PV at the parent node.
2106 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2108 assert(ply >= 0 && ply < PLY_MAX);
2112 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2114 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2115 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2117 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2121 // connected_moves() tests whether two moves are 'connected' in the sense
2122 // that the first move somehow made the second move possible (for instance
2123 // if the moving piece is the same in both moves). The first move is assumed
2124 // to be the move that was made to reach the current position, while the
2125 // second move is assumed to be a move from the current position.
2127 bool connected_moves(const Position& pos, Move m1, Move m2) {
2129 Square f1, t1, f2, t2;
2132 assert(move_is_ok(m1));
2133 assert(move_is_ok(m2));
2135 if (m2 == MOVE_NONE)
2138 // Case 1: The moving piece is the same in both moves
2144 // Case 2: The destination square for m2 was vacated by m1
2150 // Case 3: Moving through the vacated square
2151 if ( piece_is_slider(pos.piece_on(f2))
2152 && bit_is_set(squares_between(f2, t2), f1))
2155 // Case 4: The destination square for m2 is defended by the moving piece in m1
2156 p = pos.piece_on(t1);
2157 if (bit_is_set(pos.attacks_from(p, t1), t2))
2160 // Case 5: Discovered check, checking piece is the piece moved in m1
2161 if ( piece_is_slider(p)
2162 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2163 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2165 // discovered_check_candidates() works also if the Position's side to
2166 // move is the opposite of the checking piece.
2167 Color them = opposite_color(pos.side_to_move());
2168 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2170 if (bit_is_set(dcCandidates, f2))
2177 // value_is_mate() checks if the given value is a mate one
2178 // eventually compensated for the ply.
2180 bool value_is_mate(Value value) {
2182 assert(abs(value) <= VALUE_INFINITE);
2184 return value <= value_mated_in(PLY_MAX)
2185 || value >= value_mate_in(PLY_MAX);
2189 // move_is_killer() checks if the given move is among the
2190 // killer moves of that ply.
2192 bool move_is_killer(Move m, const SearchStack& ss) {
2194 const Move* k = ss.killers;
2195 for (int i = 0; i < KILLER_MAX; i++, k++)
2203 // extension() decides whether a move should be searched with normal depth,
2204 // or with extended depth. Certain classes of moves (checking moves, in
2205 // particular) are searched with bigger depth than ordinary moves and in
2206 // any case are marked as 'dangerous'. Note that also if a move is not
2207 // extended, as example because the corresponding UCI option is set to zero,
2208 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2210 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2211 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2213 assert(m != MOVE_NONE);
2215 Depth result = Depth(0);
2216 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2221 result += CheckExtension[pvNode];
2224 result += SingleEvasionExtension[pvNode];
2227 result += MateThreatExtension[pvNode];
2230 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2232 Color c = pos.side_to_move();
2233 if (relative_rank(c, move_to(m)) == RANK_7)
2235 result += PawnPushTo7thExtension[pvNode];
2238 if (pos.pawn_is_passed(c, move_to(m)))
2240 result += PassedPawnExtension[pvNode];
2245 if ( captureOrPromotion
2246 && pos.type_of_piece_on(move_to(m)) != PAWN
2247 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2248 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2249 && !move_is_promotion(m)
2252 result += PawnEndgameExtension[pvNode];
2257 && captureOrPromotion
2258 && pos.type_of_piece_on(move_to(m)) != PAWN
2259 && pos.see_sign(m) >= 0)
2265 return Min(result, OnePly);
2269 // ok_to_do_nullmove() looks at the current position and decides whether
2270 // doing a 'null move' should be allowed. In order to avoid zugzwang
2271 // problems, null moves are not allowed when the side to move has very
2272 // little material left. Currently, the test is a bit too simple: Null
2273 // moves are avoided only when the side to move has only pawns left.
2274 // It's probably a good idea to avoid null moves in at least some more
2275 // complicated endgames, e.g. KQ vs KR. FIXME
2277 bool ok_to_do_nullmove(const Position& pos) {
2279 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2283 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2284 // non-tactical moves late in the move list close to the leaves are
2285 // candidates for pruning.
2287 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2289 assert(move_is_ok(m));
2290 assert(threat == MOVE_NONE || move_is_ok(threat));
2291 assert(!pos.move_is_check(m));
2292 assert(!pos.move_is_capture_or_promotion(m));
2293 assert(!pos.move_is_passed_pawn_push(m));
2295 Square mfrom, mto, tfrom, tto;
2297 // Prune if there isn't any threat move
2298 if (threat == MOVE_NONE)
2301 mfrom = move_from(m);
2303 tfrom = move_from(threat);
2304 tto = move_to(threat);
2306 // Case 1: Don't prune moves which move the threatened piece
2310 // Case 2: If the threatened piece has value less than or equal to the
2311 // value of the threatening piece, don't prune move which defend it.
2312 if ( pos.move_is_capture(threat)
2313 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2314 || pos.type_of_piece_on(tfrom) == KING)
2315 && pos.move_attacks_square(m, tto))
2318 // Case 3: If the moving piece in the threatened move is a slider, don't
2319 // prune safe moves which block its ray.
2320 if ( piece_is_slider(pos.piece_on(tfrom))
2321 && bit_is_set(squares_between(tfrom, tto), mto)
2322 && pos.see_sign(m) >= 0)
2329 // ok_to_use_TT() returns true if a transposition table score
2330 // can be used at a given point in search.
2332 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2334 Value v = value_from_tt(tte->value(), ply);
2336 return ( tte->depth() >= depth
2337 || v >= Max(value_mate_in(PLY_MAX), beta)
2338 || v < Min(value_mated_in(PLY_MAX), beta))
2340 && ( (is_lower_bound(tte->type()) && v >= beta)
2341 || (is_upper_bound(tte->type()) && v < beta));
2345 // refine_eval() returns the transposition table score if
2346 // possible otherwise falls back on static position evaluation.
2348 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2353 Value v = value_from_tt(tte->value(), ply);
2355 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2356 || (is_upper_bound(tte->type()) && v < defaultEval))
2363 // update_history() registers a good move that produced a beta-cutoff
2364 // in history and marks as failures all the other moves of that ply.
2366 void update_history(const Position& pos, Move move, Depth depth,
2367 Move movesSearched[], int moveCount) {
2371 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2373 for (int i = 0; i < moveCount - 1; i++)
2375 m = movesSearched[i];
2379 if (!pos.move_is_capture_or_promotion(m))
2380 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2385 // update_killers() add a good move that produced a beta-cutoff
2386 // among the killer moves of that ply.
2388 void update_killers(Move m, SearchStack& ss) {
2390 if (m == ss.killers[0])
2393 for (int i = KILLER_MAX - 1; i > 0; i--)
2394 ss.killers[i] = ss.killers[i - 1];
2400 // update_gains() updates the gains table of a non-capture move given
2401 // the static position evaluation before and after the move.
2403 void update_gains(const Position& pos, Move m, Value before, Value after) {
2406 && before != VALUE_NONE
2407 && after != VALUE_NONE
2408 && pos.captured_piece() == NO_PIECE_TYPE
2409 && !move_is_castle(m)
2410 && !move_is_promotion(m))
2411 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2415 // current_search_time() returns the number of milliseconds which have passed
2416 // since the beginning of the current search.
2418 int current_search_time() {
2420 return get_system_time() - SearchStartTime;
2424 // nps() computes the current nodes/second count.
2428 int t = current_search_time();
2429 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2433 // poll() performs two different functions: It polls for user input, and it
2434 // looks at the time consumed so far and decides if it's time to abort the
2437 void poll(SearchStack ss[], int ply) {
2439 static int lastInfoTime;
2440 int t = current_search_time();
2445 // We are line oriented, don't read single chars
2446 std::string command;
2448 if (!std::getline(std::cin, command))
2451 if (command == "quit")
2454 PonderSearch = false;
2458 else if (command == "stop")
2461 PonderSearch = false;
2463 else if (command == "ponderhit")
2467 // Print search information
2471 else if (lastInfoTime > t)
2472 // HACK: Must be a new search where we searched less than
2473 // NodesBetweenPolls nodes during the first second of search.
2476 else if (t - lastInfoTime >= 1000)
2483 if (dbg_show_hit_rate)
2484 dbg_print_hit_rate();
2486 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2487 << " time " << t << " hashfull " << TT.full() << endl;
2489 // We only support current line printing in single thread mode
2490 if (ShowCurrentLine && TM.active_threads() == 1)
2492 cout << "info currline";
2493 for (int p = 0; p < ply; p++)
2494 cout << " " << ss[p].currentMove;
2500 // Should we stop the search?
2504 bool stillAtFirstMove = RootMoveNumber == 1
2505 && !AspirationFailLow
2506 && t > MaxSearchTime + ExtraSearchTime;
2508 bool noMoreTime = t > AbsoluteMaxSearchTime
2509 || stillAtFirstMove;
2511 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2512 || (ExactMaxTime && t >= ExactMaxTime)
2513 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2518 // ponderhit() is called when the program is pondering (i.e. thinking while
2519 // it's the opponent's turn to move) in order to let the engine know that
2520 // it correctly predicted the opponent's move.
2524 int t = current_search_time();
2525 PonderSearch = false;
2527 bool stillAtFirstMove = RootMoveNumber == 1
2528 && !AspirationFailLow
2529 && t > MaxSearchTime + ExtraSearchTime;
2531 bool noMoreTime = t > AbsoluteMaxSearchTime
2532 || stillAtFirstMove;
2534 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2539 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2541 void init_ss_array(SearchStack ss[]) {
2543 for (int i = 0; i < 3; i++)
2546 ss[i].initKillers();
2551 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2552 // while the program is pondering. The point is to work around a wrinkle in
2553 // the UCI protocol: When pondering, the engine is not allowed to give a
2554 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2555 // We simply wait here until one of these commands is sent, and return,
2556 // after which the bestmove and pondermove will be printed (in id_loop()).
2558 void wait_for_stop_or_ponderhit() {
2560 std::string command;
2564 if (!std::getline(std::cin, command))
2567 if (command == "quit")
2572 else if (command == "ponderhit" || command == "stop")
2578 // init_thread() is the function which is called when a new thread is
2579 // launched. It simply calls the idle_loop() function with the supplied
2580 // threadID. There are two versions of this function; one for POSIX
2581 // threads and one for Windows threads.
2583 #if !defined(_MSC_VER)
2585 void* init_thread(void *threadID) {
2587 TM.idle_loop(*(int*)threadID, NULL);
2593 DWORD WINAPI init_thread(LPVOID threadID) {
2595 TM.idle_loop(*(int*)threadID, NULL);
2602 /// The ThreadsManager class
2604 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2605 // get_beta_counters() are getters/setters for the per thread
2606 // counters used to sort the moves at root.
2608 void ThreadsManager::resetNodeCounters() {
2610 for (int i = 0; i < MAX_THREADS; i++)
2611 threads[i].nodes = 0ULL;
2614 void ThreadsManager::resetBetaCounters() {
2616 for (int i = 0; i < MAX_THREADS; i++)
2617 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2620 int64_t ThreadsManager::nodes_searched() const {
2622 int64_t result = 0ULL;
2623 for (int i = 0; i < ActiveThreads; i++)
2624 result += threads[i].nodes;
2629 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2632 for (int i = 0; i < MAX_THREADS; i++)
2634 our += threads[i].betaCutOffs[us];
2635 their += threads[i].betaCutOffs[opposite_color(us)];
2640 // idle_loop() is where the threads are parked when they have no work to do.
2641 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2642 // object for which the current thread is the master.
2644 void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2646 assert(threadID >= 0 && threadID < MAX_THREADS);
2650 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2651 // master should exit as last one.
2652 if (AllThreadsShouldExit)
2655 threads[threadID].state = THREAD_TERMINATED;
2659 // If we are not thinking, wait for a condition to be signaled
2660 // instead of wasting CPU time polling for work.
2661 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2664 assert(threadID != 0);
2665 threads[threadID].state = THREAD_SLEEPING;
2667 #if !defined(_MSC_VER)
2668 pthread_mutex_lock(&WaitLock);
2669 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2670 pthread_cond_wait(&WaitCond, &WaitLock);
2671 pthread_mutex_unlock(&WaitLock);
2673 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2677 // If thread has just woken up, mark it as available
2678 if (threads[threadID].state == THREAD_SLEEPING)
2679 threads[threadID].state = THREAD_AVAILABLE;
2681 // If this thread has been assigned work, launch a search
2682 if (threads[threadID].state == THREAD_WORKISWAITING)
2684 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2686 threads[threadID].state = THREAD_SEARCHING;
2688 if (threads[threadID].splitPoint->pvNode)
2689 sp_search_pv(threads[threadID].splitPoint, threadID);
2691 sp_search(threads[threadID].splitPoint, threadID);
2693 assert(threads[threadID].state == THREAD_SEARCHING);
2695 threads[threadID].state = THREAD_AVAILABLE;
2698 // If this thread is the master of a split point and all threads have
2699 // finished their work at this split point, return from the idle loop.
2700 if (waitSp != NULL && waitSp->cpus == 0)
2702 assert(threads[threadID].state == THREAD_AVAILABLE);
2704 threads[threadID].state = THREAD_SEARCHING;
2711 // init_threads() is called during startup. It launches all helper threads,
2712 // and initializes the split point stack and the global locks and condition
2715 void ThreadsManager::init_threads() {
2720 #if !defined(_MSC_VER)
2721 pthread_t pthread[1];
2724 // Initialize global locks
2725 lock_init(&MPLock, NULL);
2727 // Initialize SplitPointStack locks
2728 for (i = 0; i < MAX_THREADS; i++)
2729 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2731 SplitPointStack[i][j].parent = NULL;
2732 lock_init(&(SplitPointStack[i][j].lock), NULL);
2735 #if !defined(_MSC_VER)
2736 pthread_mutex_init(&WaitLock, NULL);
2737 pthread_cond_init(&WaitCond, NULL);
2739 for (i = 0; i < MAX_THREADS; i++)
2740 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2743 // Will be set just before program exits to properly end the threads
2744 AllThreadsShouldExit = false;
2746 // Threads will be put to sleep as soon as created
2747 AllThreadsShouldSleep = true;
2749 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2751 threads[0].state = THREAD_SEARCHING;
2752 for (i = 1; i < MAX_THREADS; i++)
2753 threads[i].state = THREAD_AVAILABLE;
2755 // Launch the helper threads
2756 for (i = 1; i < MAX_THREADS; i++)
2759 #if !defined(_MSC_VER)
2760 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2762 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, NULL) != NULL);
2767 cout << "Failed to create thread number " << i << endl;
2768 Application::exit_with_failure();
2771 // Wait until the thread has finished launching and is gone to sleep
2772 while (threads[i].state != THREAD_SLEEPING);
2777 // exit_threads() is called when the program exits. It makes all the
2778 // helper threads exit cleanly.
2780 void ThreadsManager::exit_threads() {
2782 ActiveThreads = MAX_THREADS; // HACK
2783 AllThreadsShouldSleep = true; // HACK
2784 wake_sleeping_threads();
2786 // This makes the threads to exit idle_loop()
2787 AllThreadsShouldExit = true;
2789 // Wait for thread termination
2790 for (int i = 1; i < MAX_THREADS; i++)
2791 while (threads[i].state != THREAD_TERMINATED);
2793 // Now we can safely destroy the locks
2794 for (int i = 0; i < MAX_THREADS; i++)
2795 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2796 lock_destroy(&(SplitPointStack[i][j].lock));
2800 // thread_should_stop() checks whether the thread should stop its search.
2801 // This can happen if a beta cutoff has occurred in the thread's currently
2802 // active split point, or in some ancestor of the current split point.
2804 bool ThreadsManager::thread_should_stop(int threadID) const {
2806 assert(threadID >= 0 && threadID < ActiveThreads);
2810 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent);
2815 // thread_is_available() checks whether the thread with threadID "slave" is
2816 // available to help the thread with threadID "master" at a split point. An
2817 // obvious requirement is that "slave" must be idle. With more than two
2818 // threads, this is not by itself sufficient: If "slave" is the master of
2819 // some active split point, it is only available as a slave to the other
2820 // threads which are busy searching the split point at the top of "slave"'s
2821 // split point stack (the "helpful master concept" in YBWC terminology).
2823 bool ThreadsManager::thread_is_available(int slave, int master) const {
2825 assert(slave >= 0 && slave < ActiveThreads);
2826 assert(master >= 0 && master < ActiveThreads);
2827 assert(ActiveThreads > 1);
2829 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2832 // Make a local copy to be sure doesn't change under our feet
2833 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2835 if (localActiveSplitPoints == 0)
2836 // No active split points means that the thread is available as
2837 // a slave for any other thread.
2840 if (ActiveThreads == 2)
2843 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2844 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2845 // could have been set to 0 by another thread leading to an out of bound access.
2846 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2853 // available_thread_exists() tries to find an idle thread which is available as
2854 // a slave for the thread with threadID "master".
2856 bool ThreadsManager::available_thread_exists(int master) const {
2858 assert(master >= 0 && master < ActiveThreads);
2859 assert(ActiveThreads > 1);
2861 for (int i = 0; i < ActiveThreads; i++)
2862 if (thread_is_available(i, master))
2869 // split() does the actual work of distributing the work at a node between
2870 // several threads at PV nodes. If it does not succeed in splitting the
2871 // node (because no idle threads are available, or because we have no unused
2872 // split point objects), the function immediately returns false. If
2873 // splitting is possible, a SplitPoint object is initialized with all the
2874 // data that must be copied to the helper threads (the current position and
2875 // search stack, alpha, beta, the search depth, etc.), and we tell our
2876 // helper threads that they have been assigned work. This will cause them
2877 // to instantly leave their idle loops and call sp_search_pv(). When all
2878 // threads have returned from sp_search_pv (or, equivalently, when
2879 // splitPoint->cpus becomes 0), split() returns true.
2881 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2882 Value* alpha, const Value beta, Value* bestValue,
2883 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2886 assert(sstck != NULL);
2887 assert(ply >= 0 && ply < PLY_MAX);
2888 assert(*bestValue >= -VALUE_INFINITE);
2889 assert( ( pvNode && *bestValue <= *alpha)
2890 || (!pvNode && *bestValue < beta ));
2891 assert(!pvNode || *alpha < beta);
2892 assert(beta <= VALUE_INFINITE);
2893 assert(depth > Depth(0));
2894 assert(master >= 0 && master < ActiveThreads);
2895 assert(ActiveThreads > 1);
2897 SplitPoint* splitPoint;
2901 // If no other thread is available to help us, or if we have too many
2902 // active split points, don't split.
2903 if ( !available_thread_exists(master)
2904 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2906 lock_release(&MPLock);
2910 // Pick the next available split point object from the split point stack
2911 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2913 // Initialize the split point object
2914 splitPoint->parent = threads[master].splitPoint;
2915 splitPoint->stopRequest = false;
2916 splitPoint->ply = ply;
2917 splitPoint->depth = depth;
2918 splitPoint->alpha = pvNode ? *alpha : beta - 1;
2919 splitPoint->beta = beta;
2920 splitPoint->pvNode = pvNode;
2921 splitPoint->bestValue = *bestValue;
2922 splitPoint->master = master;
2923 splitPoint->mp = mp;
2924 splitPoint->moves = *moves;
2925 splitPoint->cpus = 1;
2926 splitPoint->pos = &p;
2927 splitPoint->parentSstack = sstck;
2928 for (int i = 0; i < ActiveThreads; i++)
2929 splitPoint->slaves[i] = 0;
2931 threads[master].splitPoint = splitPoint;
2932 threads[master].activeSplitPoints++;
2934 // If we are here it means we are not available
2935 assert(threads[master].state != THREAD_AVAILABLE);
2937 // Allocate available threads setting state to THREAD_BOOKED
2938 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2939 if (thread_is_available(i, master))
2941 threads[i].state = THREAD_BOOKED;
2942 threads[i].splitPoint = splitPoint;
2943 splitPoint->slaves[i] = 1;
2947 assert(splitPoint->cpus > 1);
2949 // We can release the lock because slave threads are already booked and master is not available
2950 lock_release(&MPLock);
2952 // Tell the threads that they have work to do. This will make them leave
2953 // their idle loop. But before copy search stack tail for each thread.
2954 for (int i = 0; i < ActiveThreads; i++)
2955 if (i == master || splitPoint->slaves[i])
2957 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2959 assert(i == master || threads[i].state == THREAD_BOOKED);
2961 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2964 // Everything is set up. The master thread enters the idle loop, from
2965 // which it will instantly launch a search, because its state is
2966 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2967 // idle loop, which means that the main thread will return from the idle
2968 // loop when all threads have finished their work at this split point
2969 // (i.e. when splitPoint->cpus == 0).
2970 idle_loop(master, splitPoint);
2972 // We have returned from the idle loop, which means that all threads are
2973 // finished. Update alpha, beta and bestValue, and return.
2977 *alpha = splitPoint->alpha;
2979 *bestValue = splitPoint->bestValue;
2980 threads[master].activeSplitPoints--;
2981 threads[master].splitPoint = splitPoint->parent;
2983 lock_release(&MPLock);
2988 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2989 // to start a new search from the root.
2991 void ThreadsManager::wake_sleeping_threads() {
2993 assert(AllThreadsShouldSleep);
2994 assert(ActiveThreads > 0);
2996 AllThreadsShouldSleep = false;
2998 if (ActiveThreads == 1)
3001 #if !defined(_MSC_VER)
3002 pthread_mutex_lock(&WaitLock);
3003 pthread_cond_broadcast(&WaitCond);
3004 pthread_mutex_unlock(&WaitLock);
3006 for (int i = 1; i < MAX_THREADS; i++)
3007 SetEvent(SitIdleEvent[i]);
3013 // put_threads_to_sleep() makes all the threads go to sleep just before
3014 // to leave think(), at the end of the search. Threads should have already
3015 // finished the job and should be idle.
3017 void ThreadsManager::put_threads_to_sleep() {
3019 assert(!AllThreadsShouldSleep);
3021 // This makes the threads to go to sleep
3022 AllThreadsShouldSleep = true;
3025 /// The RootMoveList class
3027 // RootMoveList c'tor
3029 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3031 SearchStack ss[PLY_MAX_PLUS_2];
3032 MoveStack mlist[MaxRootMoves];
3034 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3036 // Generate all legal moves
3037 MoveStack* last = generate_moves(pos, mlist);
3039 // Add each move to the moves[] array
3040 for (MoveStack* cur = mlist; cur != last; cur++)
3042 bool includeMove = includeAllMoves;
3044 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3045 includeMove = (searchMoves[k] == cur->move);
3050 // Find a quick score for the move
3052 pos.do_move(cur->move, st);
3053 moves[count].move = cur->move;
3054 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3055 moves[count].pv[0] = cur->move;
3056 moves[count].pv[1] = MOVE_NONE;
3057 pos.undo_move(cur->move);
3064 // RootMoveList simple methods definitions
3066 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3068 moves[moveNum].nodes = nodes;
3069 moves[moveNum].cumulativeNodes += nodes;
3072 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3074 moves[moveNum].ourBeta = our;
3075 moves[moveNum].theirBeta = their;
3078 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3082 for (j = 0; pv[j] != MOVE_NONE; j++)
3083 moves[moveNum].pv[j] = pv[j];
3085 moves[moveNum].pv[j] = MOVE_NONE;
3089 // RootMoveList::sort() sorts the root move list at the beginning of a new
3092 void RootMoveList::sort() {
3094 sort_multipv(count - 1); // Sort all items
3098 // RootMoveList::sort_multipv() sorts the first few moves in the root move
3099 // list by their scores and depths. It is used to order the different PVs
3100 // correctly in MultiPV mode.
3102 void RootMoveList::sort_multipv(int n) {
3106 for (i = 1; i <= n; i++)
3108 RootMove rm = moves[i];
3109 for (j = i; j > 0 && moves[j - 1] < rm; j--)
3110 moves[j] = moves[j - 1];