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 const Depth RazorDepth = 4 * OnePly;
166 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * d); }
168 // Step 8. Null move search with verification search
170 // Null move margin. A null move search will not be done if the static
171 // evaluation of the position is more than NullMoveMargin below beta.
172 const Value NullMoveMargin = Value(0x200);
174 // Step 9. Internal iterative deepening
176 const Depth IIDDepthAtPVNodes = 5 * OnePly;
177 const Depth IIDDepthAtNonPVNodes = 8 * OnePly;
179 // Internal iterative deepening margin. At Non-PV nodes
180 // we do an internal iterative deepening
181 // search when the static evaluation is at most IIDMargin below beta.
182 const Value IIDMargin = Value(0x100);
184 // Step 11. Decide the new search depth
186 // Extensions. Configurable UCI options.
187 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
188 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
189 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
191 const Depth SingularExtensionDepthAtPVNodes = 6 * OnePly;
192 const Depth SingularExtensionDepthAtNonPVNodes = 8 * OnePly;
194 // If the TT move is at least SingularExtensionMargin better then the
195 // remaining ones we will extend it.
196 const Value SingularExtensionMargin = Value(0x20);
198 // Step 12. Futility pruning
200 const Value FutilityMarginQS = Value(0x80);
202 // Futility lookup tables (initialized at startup) and their getter functions
203 int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
204 int FutilityMoveCountArray[32]; // [depth]
206 inline Value futility_margin(Depth d, int mn) { return Value(d < 7*OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
207 inline int futility_move_count(Depth d) { return d < 16*OnePly ? FutilityMoveCountArray[d] : 512; }
209 // Step 14. Reduced search
211 // Reduction lookup tables (initialized at startup) and their getter functions
212 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
213 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
215 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
216 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
220 // Search depth at iteration 1
221 const Depth InitialDepth = OnePly;
223 // Easy move margin. An easy move candidate must be at least this much
224 // better than the second best move.
225 const Value EasyMoveMargin = Value(0x200);
227 /// Variables initialized by UCI options
229 // Depth limit for use of dynamic threat detection
232 // Last seconds noise filtering (LSN)
233 const bool UseLSNFiltering = true;
234 const int LSNTime = 4000; // In milliseconds
235 const Value LSNValue = value_from_centipawns(200);
236 bool loseOnTime = false;
238 // Iteration counters
241 // Scores and number of times the best move changed for each iteration
242 Value ValueByIteration[PLY_MAX_PLUS_2];
243 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
245 // Search window management
251 // Time managment variables
254 int MaxNodes, MaxDepth;
255 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
256 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
257 bool AbortSearch, Quit;
258 bool AspirationFailLow;
260 // Show current line?
261 bool ShowCurrentLine;
265 std::ofstream LogFile;
267 // MP related variables
268 Depth MinimumSplitDepth;
269 int MaxThreadsPerSplitPoint;
272 // Node counters, used only by thread[0] but try to keep in different
273 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
275 int NodesBetweenPolls = 30000;
282 Value id_loop(const Position& pos, Move searchMoves[]);
283 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
284 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
285 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
286 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
287 void sp_search(SplitPoint* sp, int threadID);
288 void sp_search_pv(SplitPoint* sp, int threadID);
289 void init_node(SearchStack ss[], int ply, int threadID);
290 void update_pv(SearchStack ss[], int ply);
291 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
292 bool connected_moves(const Position& pos, Move m1, Move m2);
293 bool value_is_mate(Value value);
294 bool move_is_killer(Move m, const SearchStack& ss);
295 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
296 bool ok_to_do_nullmove(const Position& pos);
297 bool ok_to_prune(const Position& pos, Move m, Move threat);
298 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
299 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
300 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
301 void update_killers(Move m, SearchStack& ss);
302 void update_gains(const Position& pos, Move move, Value before, Value after);
304 int current_search_time();
306 void poll(SearchStack ss[], int ply);
308 void wait_for_stop_or_ponderhit();
309 void init_ss_array(SearchStack ss[]);
311 #if !defined(_MSC_VER)
312 void *init_thread(void *threadID);
314 DWORD WINAPI init_thread(LPVOID threadID);
324 /// init_threads(), exit_threads() and nodes_searched() are helpers to
325 /// give accessibility to some TM methods from outside of current file.
327 void init_threads() { TM.init_threads(); }
328 void exit_threads() { TM.exit_threads(); }
329 int64_t nodes_searched() { return TM.nodes_searched(); }
332 /// perft() is our utility to verify move generation is bug free. All the legal
333 /// moves up to given depth are generated and counted and the sum returned.
335 int perft(Position& pos, Depth depth)
339 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
341 // If we are at the last ply we don't need to do and undo
342 // the moves, just to count them.
343 if (depth <= OnePly) // Replace with '<' to test also qsearch
345 while (mp.get_next_move()) sum++;
349 // Loop through all legal moves
351 while ((move = mp.get_next_move()) != MOVE_NONE)
354 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
355 sum += perft(pos, depth - OnePly);
362 /// think() is the external interface to Stockfish's search, and is called when
363 /// the program receives the UCI 'go' command. It initializes various
364 /// search-related global variables, and calls root_search(). It returns false
365 /// when a quit command is received during the search.
367 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
368 int time[], int increment[], int movesToGo, int maxDepth,
369 int maxNodes, int maxTime, Move searchMoves[]) {
371 // Initialize global search variables
372 StopOnPonderhit = AbortSearch = Quit = false;
373 AspirationFailLow = false;
375 SearchStartTime = get_system_time();
376 ExactMaxTime = maxTime;
379 InfiniteSearch = infinite;
380 PonderSearch = ponder;
381 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
383 // Look for a book move, only during games, not tests
384 if (UseTimeManagement && get_option_value_bool("OwnBook"))
387 if (get_option_value_string("Book File") != OpeningBook.file_name())
388 OpeningBook.open(get_option_value_string("Book File"));
390 bookMove = OpeningBook.get_move(pos);
391 if (bookMove != MOVE_NONE)
394 wait_for_stop_or_ponderhit();
396 cout << "bestmove " << bookMove << endl;
401 TM.resetNodeCounters();
403 if (button_was_pressed("New Game"))
404 loseOnTime = false; // Reset at the beginning of a new game
406 // Read UCI option values
407 TT.set_size(get_option_value_int("Hash"));
408 if (button_was_pressed("Clear Hash"))
411 bool PonderingEnabled = get_option_value_bool("Ponder");
412 MultiPV = get_option_value_int("MultiPV");
414 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
415 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
417 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
418 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
420 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
421 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
423 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
424 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
426 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
427 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
429 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
430 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
432 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
434 Chess960 = get_option_value_bool("UCI_Chess960");
435 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
436 UseLogFile = get_option_value_bool("Use Search Log");
438 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
440 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
441 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
443 read_weights(pos.side_to_move());
445 // Set the number of active threads
446 int newActiveThreads = get_option_value_int("Threads");
447 if (newActiveThreads != TM.active_threads())
449 TM.set_active_threads(newActiveThreads);
450 init_eval(TM.active_threads());
451 // HACK: init_eval() destroys the static castleRightsMask[] array in the
452 // Position class. The below line repairs the damage.
453 Position p(pos.to_fen());
457 // Wake up sleeping threads
458 TM.wake_sleeping_threads();
461 int myTime = time[side_to_move];
462 int myIncrement = increment[side_to_move];
463 if (UseTimeManagement)
465 if (!movesToGo) // Sudden death time control
469 MaxSearchTime = myTime / 30 + myIncrement;
470 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
472 else // Blitz game without increment
474 MaxSearchTime = myTime / 30;
475 AbsoluteMaxSearchTime = myTime / 8;
478 else // (x moves) / (y minutes)
482 MaxSearchTime = myTime / 2;
483 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
487 MaxSearchTime = myTime / Min(movesToGo, 20);
488 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
492 if (PonderingEnabled)
494 MaxSearchTime += MaxSearchTime / 4;
495 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
499 // Set best NodesBetweenPolls interval
501 NodesBetweenPolls = Min(MaxNodes, 30000);
502 else if (myTime && myTime < 1000)
503 NodesBetweenPolls = 1000;
504 else if (myTime && myTime < 5000)
505 NodesBetweenPolls = 5000;
507 NodesBetweenPolls = 30000;
509 // Write information to search log file
511 LogFile << "Searching: " << pos.to_fen() << endl
512 << "infinite: " << infinite
513 << " ponder: " << ponder
514 << " time: " << myTime
515 << " increment: " << myIncrement
516 << " moves to go: " << movesToGo << endl;
518 // LSN filtering. Used only for developing purpose. Disabled by default.
522 // Step 2. If after last move we decided to lose on time, do it now!
523 while (SearchStartTime + myTime + 1000 > get_system_time())
527 // We're ready to start thinking. Call the iterative deepening loop function
528 Value v = id_loop(pos, searchMoves);
532 // Step 1. If this is sudden death game and our position is hopeless,
533 // decide to lose on time.
534 if ( !loseOnTime // If we already lost on time, go to step 3.
544 // Step 3. Now after stepping over the time limit, reset flag for next match.
552 TM.put_threads_to_sleep();
558 /// init_search() is called during startup. It initializes various lookup tables
562 // Init our reduction lookup tables
563 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
564 for (int j = 1; j < 64; j++) // j == moveNumber
566 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
567 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
568 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
569 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
572 // Init futility margins array
573 for (int i = 0; i < 14; i++) // i == depth (OnePly = 2)
574 for (int j = 0; j < 64; j++) // j == moveNumber
576 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
579 // Init futility move count array
580 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
581 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
585 // SearchStack::init() initializes a search stack. Used at the beginning of a
586 // new search from the root.
587 void SearchStack::init(int ply) {
589 pv[ply] = pv[ply + 1] = MOVE_NONE;
590 currentMove = threatMove = MOVE_NONE;
591 reduction = Depth(0);
595 void SearchStack::initKillers() {
597 mateKiller = MOVE_NONE;
598 for (int i = 0; i < KILLER_MAX; i++)
599 killers[i] = MOVE_NONE;
604 // id_loop() is the main iterative deepening loop. It calls root_search
605 // repeatedly with increasing depth until the allocated thinking time has
606 // been consumed, the user stops the search, or the maximum search depth is
609 Value id_loop(const Position& pos, Move searchMoves[]) {
612 SearchStack ss[PLY_MAX_PLUS_2];
614 // searchMoves are verified, copied, scored and sorted
615 RootMoveList rml(p, searchMoves);
617 // Handle special case of searching on a mate/stale position
618 if (rml.move_count() == 0)
621 wait_for_stop_or_ponderhit();
623 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
626 // Print RootMoveList c'tor startup scoring to the standard output,
627 // so that we print information also for iteration 1.
628 cout << "info depth " << 1 << "\ninfo depth " << 1
629 << " score " << value_to_string(rml.get_move_score(0))
630 << " time " << current_search_time()
631 << " nodes " << TM.nodes_searched()
633 << " pv " << rml.get_move(0) << "\n";
639 ValueByIteration[1] = rml.get_move_score(0);
642 // Is one move significantly better than others after initial scoring ?
643 Move EasyMove = MOVE_NONE;
644 if ( rml.move_count() == 1
645 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
646 EasyMove = rml.get_move(0);
648 // Iterative deepening loop
649 while (Iteration < PLY_MAX)
651 // Initialize iteration
654 BestMoveChangesByIteration[Iteration] = 0;
658 cout << "info depth " << Iteration << endl;
660 // Calculate dynamic search window based on previous iterations
663 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
665 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
666 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
668 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
669 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
671 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
672 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
676 alpha = - VALUE_INFINITE;
677 beta = VALUE_INFINITE;
680 // Search to the current depth
681 Value value = root_search(p, ss, rml, alpha, beta);
683 // Write PV to transposition table, in case the relevant entries have
684 // been overwritten during the search.
685 TT.insert_pv(p, ss[0].pv);
688 break; // Value cannot be trusted. Break out immediately!
690 //Save info about search result
691 ValueByIteration[Iteration] = value;
693 // Drop the easy move if it differs from the new best move
694 if (ss[0].pv[0] != EasyMove)
695 EasyMove = MOVE_NONE;
697 if (UseTimeManagement)
700 bool stopSearch = false;
702 // Stop search early if there is only a single legal move,
703 // we search up to Iteration 6 anyway to get a proper score.
704 if (Iteration >= 6 && rml.move_count() == 1)
707 // Stop search early when the last two iterations returned a mate score
709 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
710 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
713 // Stop search early if one move seems to be much better than the rest
714 int64_t nodes = TM.nodes_searched();
716 && EasyMove == ss[0].pv[0]
717 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
718 && current_search_time() > MaxSearchTime / 16)
719 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
720 && current_search_time() > MaxSearchTime / 32)))
723 // Add some extra time if the best move has changed during the last two iterations
724 if (Iteration > 5 && Iteration <= 50)
725 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
726 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
728 // Stop search if most of MaxSearchTime is consumed at the end of the
729 // iteration. We probably don't have enough time to search the first
730 // move at the next iteration anyway.
731 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
739 StopOnPonderhit = true;
743 if (MaxDepth && Iteration >= MaxDepth)
749 // If we are pondering or in infinite search, we shouldn't print the
750 // best move before we are told to do so.
751 if (!AbortSearch && (PonderSearch || InfiniteSearch))
752 wait_for_stop_or_ponderhit();
754 // Print final search statistics
755 cout << "info nodes " << TM.nodes_searched()
757 << " time " << current_search_time()
758 << " hashfull " << TT.full() << endl;
760 // Print the best move and the ponder move to the standard output
761 if (ss[0].pv[0] == MOVE_NONE)
763 ss[0].pv[0] = rml.get_move(0);
764 ss[0].pv[1] = MOVE_NONE;
766 cout << "bestmove " << ss[0].pv[0];
767 if (ss[0].pv[1] != MOVE_NONE)
768 cout << " ponder " << ss[0].pv[1];
775 dbg_print_mean(LogFile);
777 if (dbg_show_hit_rate)
778 dbg_print_hit_rate(LogFile);
780 LogFile << "\nNodes: " << TM.nodes_searched()
781 << "\nNodes/second: " << nps()
782 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
785 p.do_move(ss[0].pv[0], st);
786 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
788 return rml.get_move_score(0);
792 // root_search() is the function which searches the root node. It is
793 // similar to search_pv except that it uses a different move ordering
794 // scheme and prints some information to the standard output.
796 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
801 Depth depth, ext, newDepth;
804 int researchCount = 0;
805 bool moveIsCheck, captureOrPromotion, dangerous;
806 Value alpha = oldAlpha;
807 bool isCheck = pos.is_check();
809 // Evaluate the position statically
811 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
813 while (1) // Fail low loop
816 // Loop through all the moves in the root move list
817 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
821 // We failed high, invalidate and skip next moves, leave node-counters
822 // and beta-counters as they are and quickly return, we will try to do
823 // a research at the next iteration with a bigger aspiration window.
824 rml.set_move_score(i, -VALUE_INFINITE);
828 RootMoveNumber = i + 1;
830 // Save the current node count before the move is searched
831 nodes = TM.nodes_searched();
833 // Reset beta cut-off counters
834 TM.resetBetaCounters();
836 // Pick the next root move, and print the move and the move number to
837 // the standard output.
838 move = ss[0].currentMove = rml.get_move(i);
840 if (current_search_time() >= 1000)
841 cout << "info currmove " << move
842 << " currmovenumber " << RootMoveNumber << endl;
844 // Decide search depth for this move
845 moveIsCheck = pos.move_is_check(move);
846 captureOrPromotion = pos.move_is_capture_or_promotion(move);
847 depth = (Iteration - 2) * OnePly + InitialDepth;
848 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
849 newDepth = depth + ext;
851 value = - VALUE_INFINITE;
853 while (1) // Fail high loop
856 // Make the move, and search it
857 pos.do_move(move, st, ci, moveIsCheck);
859 if (i < MultiPV || value > alpha)
861 // Aspiration window is disabled in multi-pv case
863 alpha = -VALUE_INFINITE;
865 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
869 // Try to reduce non-pv search depth by one ply if move seems not problematic,
870 // if the move fails high will be re-searched at full depth.
871 bool doFullDepthSearch = true;
873 if ( depth >= 3*OnePly // FIXME was newDepth
875 && !captureOrPromotion
876 && !move_is_castle(move))
878 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
881 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
882 doFullDepthSearch = (value > alpha);
886 if (doFullDepthSearch)
888 ss[0].reduction = Depth(0);
889 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
892 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
898 // Can we exit fail high loop ?
899 if (AbortSearch || value < beta)
902 // We are failing high and going to do a research. It's important to update score
903 // before research in case we run out of time while researching.
904 rml.set_move_score(i, value);
906 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
907 rml.set_move_pv(i, ss[0].pv);
909 // Print search information to the standard output
910 cout << "info depth " << Iteration
911 << " score " << value_to_string(value)
912 << ((value >= beta) ? " lowerbound" :
913 ((value <= alpha)? " upperbound" : ""))
914 << " time " << current_search_time()
915 << " nodes " << TM.nodes_searched()
919 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
920 cout << ss[0].pv[j] << " ";
926 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
927 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
929 LogFile << pretty_pv(pos, current_search_time(), Iteration,
930 TM.nodes_searched(), value, type, ss[0].pv) << endl;
933 // Prepare for a research after a fail high, each time with a wider window
935 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
937 } // End of fail high loop
939 // Finished searching the move. If AbortSearch is true, the search
940 // was aborted because the user interrupted the search or because we
941 // ran out of time. In this case, the return value of the search cannot
942 // be trusted, and we break out of the loop without updating the best
947 // Remember beta-cutoff and searched nodes counts for this move. The
948 // info is used to sort the root moves at the next iteration.
950 TM.get_beta_counters(pos.side_to_move(), our, their);
951 rml.set_beta_counters(i, our, their);
952 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
954 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
956 if (value <= alpha && i >= MultiPV)
957 rml.set_move_score(i, -VALUE_INFINITE);
960 // PV move or new best move!
963 rml.set_move_score(i, value);
965 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
966 rml.set_move_pv(i, ss[0].pv);
970 // We record how often the best move has been changed in each
971 // iteration. This information is used for time managment: When
972 // the best move changes frequently, we allocate some more time.
974 BestMoveChangesByIteration[Iteration]++;
976 // Print search information to the standard output
977 cout << "info depth " << Iteration
978 << " score " << value_to_string(value)
979 << ((value >= beta) ? " lowerbound" :
980 ((value <= alpha)? " upperbound" : ""))
981 << " time " << current_search_time()
982 << " nodes " << TM.nodes_searched()
986 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
987 cout << ss[0].pv[j] << " ";
993 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
994 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
996 LogFile << pretty_pv(pos, current_search_time(), Iteration,
997 TM.nodes_searched(), value, type, ss[0].pv) << endl;
1004 rml.sort_multipv(i);
1005 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1007 cout << "info multipv " << j + 1
1008 << " score " << value_to_string(rml.get_move_score(j))
1009 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1010 << " time " << current_search_time()
1011 << " nodes " << TM.nodes_searched()
1015 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1016 cout << rml.get_move_pv(j, k) << " ";
1020 alpha = rml.get_move_score(Min(i, MultiPV-1));
1022 } // PV move or new best move
1024 assert(alpha >= oldAlpha);
1026 AspirationFailLow = (alpha == oldAlpha);
1028 if (AspirationFailLow && StopOnPonderhit)
1029 StopOnPonderhit = false;
1032 // Can we exit fail low loop ?
1033 if (AbortSearch || alpha > oldAlpha)
1036 // Prepare for a research after a fail low, each time with a wider window
1038 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1047 // search_pv() is the main search function for PV nodes.
1049 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1050 Depth depth, int ply, int threadID) {
1052 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1053 assert(beta > alpha && beta <= VALUE_INFINITE);
1054 assert(ply >= 0 && ply < PLY_MAX);
1055 assert(threadID >= 0 && threadID < TM.active_threads());
1057 Move movesSearched[256];
1062 Depth ext, newDepth;
1063 Value bestValue, value, oldAlpha;
1064 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1065 bool mateThreat = false;
1067 bestValue = value = -VALUE_INFINITE;
1070 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1072 // Step 1. Initialize node and poll
1073 // Polling can abort search.
1074 init_node(ss, ply, threadID);
1076 // Step 2. Check for aborted search and immediate draw
1077 if (AbortSearch || TM.thread_should_stop(threadID))
1080 if (pos.is_draw() || ply >= PLY_MAX - 1)
1083 // Step 3. Mate distance pruning
1085 alpha = Max(value_mated_in(ply), alpha);
1086 beta = Min(value_mate_in(ply+1), beta);
1090 // Step 4. Transposition table lookup
1091 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1092 // This is to avoid problems in the following areas:
1094 // * Repetition draw detection
1095 // * Fifty move rule detection
1096 // * Searching for a mate
1097 // * Printing of full PV line
1098 tte = TT.retrieve(pos.get_key());
1099 ttMove = (tte ? tte->move() : MOVE_NONE);
1101 // Step 5. Evaluate the position statically
1102 // At PV nodes we do this only to update gain statistics
1103 isCheck = pos.is_check();
1106 ss[ply].eval = evaluate(pos, ei, threadID);
1107 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1110 // Step 6. Razoring (is omitted in PV nodes)
1111 // Step 7. Static null move pruning (is omitted in PV nodes)
1112 // Step 8. Null move search with verification search (is omitted in PV nodes)
1114 // Step 9. Internal iterative deepening
1115 if ( depth >= IIDDepthAtPVNodes
1116 && ttMove == MOVE_NONE)
1118 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1119 ttMove = ss[ply].pv[ply];
1120 tte = TT.retrieve(pos.get_key());
1123 // Step 10. Loop through moves
1124 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1126 // Initialize a MovePicker object for the current position
1127 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1128 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1131 while ( alpha < beta
1132 && (move = mp.get_next_move()) != MOVE_NONE
1133 && !TM.thread_should_stop(threadID))
1135 assert(move_is_ok(move));
1137 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1138 moveIsCheck = pos.move_is_check(move, ci);
1139 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1141 // Step 11. Decide the new search depth
1142 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1144 // Singular extension search. We extend the TT move if its value is much better than
1145 // its siblings. To verify this we do a reduced search on all the other moves but the
1146 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1147 if ( depth >= SingularExtensionDepthAtPVNodes
1149 && move == tte->move()
1151 && is_lower_bound(tte->type())
1152 && tte->depth() >= depth - 3 * OnePly)
1154 Value ttValue = value_from_tt(tte->value(), ply);
1156 if (abs(ttValue) < VALUE_KNOWN_WIN)
1158 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1160 if (excValue < ttValue - SingularExtensionMargin)
1165 newDepth = depth - OnePly + ext;
1167 // Update current move (this must be done after singular extension search)
1168 movesSearched[moveCount++] = ss[ply].currentMove = move;
1170 // Step 12. Futility pruning (is omitted in PV nodes)
1172 // Step 13. Make the move
1173 pos.do_move(move, st, ci, moveIsCheck);
1175 // Step extra. pv search (only in PV nodes)
1176 // The first move in list is the expected PV
1178 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1181 // Step 14. Reduced search
1182 // if the move fails high will be re-searched at full depth.
1183 bool doFullDepthSearch = true;
1185 if ( depth >= 3*OnePly
1187 && !captureOrPromotion
1188 && !move_is_castle(move)
1189 && !move_is_killer(move, ss[ply]))
1191 ss[ply].reduction = pv_reduction(depth, moveCount);
1192 if (ss[ply].reduction)
1194 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1195 doFullDepthSearch = (value > alpha);
1199 // Step 15. Full depth search
1200 if (doFullDepthSearch)
1202 ss[ply].reduction = Depth(0);
1203 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1205 // Step extra. pv search (only in PV nodes)
1206 if (value > alpha && value < beta)
1207 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1211 // Step 16. Undo move
1212 pos.undo_move(move);
1214 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1216 // Step 17. Check for new best move
1217 if (value > bestValue)
1224 if (value == value_mate_in(ply + 1))
1225 ss[ply].mateKiller = move;
1229 // Step 18. Check for split
1230 if ( TM.active_threads() > 1
1232 && depth >= MinimumSplitDepth
1234 && TM.available_thread_exists(threadID)
1236 && !TM.thread_should_stop(threadID)
1237 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1238 depth, &moveCount, &mp, threadID, true))
1242 // Step 19. Check for mate and stalemate
1243 // All legal moves have been searched and if there were
1244 // no legal moves, it must be mate or stalemate.
1246 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1248 // Step 20. Update tables
1249 // If the search is not aborted, update the transposition table,
1250 // history counters, and killer moves.
1251 if (AbortSearch || TM.thread_should_stop(threadID))
1254 if (bestValue <= oldAlpha)
1255 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1257 else if (bestValue >= beta)
1259 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1260 move = ss[ply].pv[ply];
1261 if (!pos.move_is_capture_or_promotion(move))
1263 update_history(pos, move, depth, movesSearched, moveCount);
1264 update_killers(move, ss[ply]);
1266 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1269 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1275 // search() is the search function for zero-width nodes.
1277 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1278 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1280 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1281 assert(ply >= 0 && ply < PLY_MAX);
1282 assert(threadID >= 0 && threadID < TM.active_threads());
1284 Move movesSearched[256];
1289 Depth ext, newDepth;
1290 Value bestValue, refinedValue, nullValue, value, futilityValueScaled;
1291 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1292 bool mateThreat = false;
1294 refinedValue = bestValue = value = -VALUE_INFINITE;
1297 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1299 // Step 1. Initialize node and poll
1300 // Polling can abort search.
1301 init_node(ss, ply, threadID);
1303 // Step 2. Check for aborted search and immediate draw
1304 if (AbortSearch || TM.thread_should_stop(threadID))
1307 if (pos.is_draw() || ply >= PLY_MAX - 1)
1310 // Step 3. Mate distance pruning
1311 if (value_mated_in(ply) >= beta)
1314 if (value_mate_in(ply + 1) < beta)
1317 // Step 4. Transposition table lookup
1319 // We don't want the score of a partial search to overwrite a previous full search
1320 // TT value, so we use a different position key in case of an excluded move exists.
1321 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1323 tte = TT.retrieve(posKey);
1324 ttMove = (tte ? tte->move() : MOVE_NONE);
1326 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1328 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1329 return value_from_tt(tte->value(), ply);
1332 // Step 5. Evaluate the position statically
1333 isCheck = pos.is_check();
1337 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1338 ss[ply].eval = value_from_tt(tte->value(), ply);
1340 ss[ply].eval = evaluate(pos, ei, threadID);
1342 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1343 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1347 if ( !value_is_mate(beta)
1349 && depth < RazorDepth
1350 && refinedValue < beta - razor_margin(depth)
1351 && ss[ply - 1].currentMove != MOVE_NULL
1352 && ttMove == MOVE_NONE
1353 && !pos.has_pawn_on_7th(pos.side_to_move()))
1355 Value rbeta = beta - razor_margin(depth);
1356 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1358 return v; //FIXME: Logically should be: return (v + razor_margin(depth));
1361 // Step 7. Static null move pruning
1362 // We're betting that the opponent doesn't have a move that will reduce
1363 // the score by more than fuility_margin(depth) if we do a null move.
1366 && depth < RazorDepth
1367 && refinedValue - futility_margin(depth, 0) >= beta)
1368 return refinedValue - futility_margin(depth, 0);
1370 // Step 8. Null move search with verification search
1371 // When we jump directly to qsearch() we do a null move only if static value is
1372 // at least beta. Otherwise we do a null move if static value is not more than
1373 // NullMoveMargin under beta.
1377 && !value_is_mate(beta)
1378 && ok_to_do_nullmove(pos)
1379 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1381 ss[ply].currentMove = MOVE_NULL;
1383 pos.do_null_move(st);
1385 // Null move dynamic reduction based on depth
1386 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1388 // Null move dynamic reduction based on value
1389 if (refinedValue - beta > PawnValueMidgame)
1392 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1394 pos.undo_null_move();
1396 if (nullValue >= beta)
1398 if (depth < 6 * OnePly)
1401 // Do zugzwang verification search
1402 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1406 // The null move failed low, which means that we may be faced with
1407 // some kind of threat. If the previous move was reduced, check if
1408 // the move that refuted the null move was somehow connected to the
1409 // move which was reduced. If a connection is found, return a fail
1410 // low score (which will cause the reduced move to fail high in the
1411 // parent node, which will trigger a re-search with full depth).
1412 if (nullValue == value_mated_in(ply + 2))
1415 ss[ply].threatMove = ss[ply + 1].currentMove;
1416 if ( depth < ThreatDepth
1417 && ss[ply - 1].reduction
1418 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1423 // Step 9. Internal iterative deepening
1424 if ( depth >= IIDDepthAtNonPVNodes
1425 && ttMove == MOVE_NONE
1427 && ss[ply].eval >= beta - IIDMargin)
1429 search(pos, ss, beta, depth/2, ply, false, threadID);
1430 ttMove = ss[ply].pv[ply];
1431 tte = TT.retrieve(posKey);
1434 // Step 10. Loop through moves
1435 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1437 // Initialize a MovePicker object for the current position
1438 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1441 while ( bestValue < beta
1442 && (move = mp.get_next_move()) != MOVE_NONE
1443 && !TM.thread_should_stop(threadID))
1445 assert(move_is_ok(move));
1447 if (move == excludedMove)
1450 moveIsCheck = pos.move_is_check(move, ci);
1451 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1452 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1454 // Step 11. Decide the new search depth
1455 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1457 // Singular extension search. We extend the TT move if its value is much better than
1458 // its siblings. To verify this we do a reduced search on all the other moves but the
1459 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1460 if ( depth >= SingularExtensionDepthAtNonPVNodes
1462 && move == tte->move()
1463 && !excludedMove // Do not allow recursive single-reply search
1465 && is_lower_bound(tte->type())
1466 && tte->depth() >= depth - 3 * OnePly)
1468 Value ttValue = value_from_tt(tte->value(), ply);
1470 if (abs(ttValue) < VALUE_KNOWN_WIN)
1472 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1474 if (excValue < ttValue - SingularExtensionMargin)
1479 newDepth = depth - OnePly + ext;
1481 // Update current move (this must be done after singular extension search)
1482 movesSearched[moveCount++] = ss[ply].currentMove = move;
1484 // Step 12. Futility pruning
1487 && !captureOrPromotion
1488 && !move_is_castle(move)
1491 // Move count based pruning
1492 if ( moveCount >= futility_move_count(depth)
1493 && ok_to_prune(pos, move, ss[ply].threatMove)
1494 && bestValue > value_mated_in(PLY_MAX))
1497 // Value based pruning
1498 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); // We illogically ignore reduction condition depth >= 3*OnePly
1499 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1500 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1502 if (futilityValueScaled < beta)
1504 if (futilityValueScaled > bestValue)
1505 bestValue = futilityValueScaled;
1510 // Step 13. Make the move
1511 pos.do_move(move, st, ci, moveIsCheck);
1513 // Step 14. Reduced search
1514 // if the move fails high will be re-searched at full depth.
1515 bool doFullDepthSearch = true;
1517 if ( depth >= 3*OnePly
1519 && !captureOrPromotion
1520 && !move_is_castle(move)
1521 && !move_is_killer(move, ss[ply]))
1523 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1524 if (ss[ply].reduction)
1526 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1527 doFullDepthSearch = (value >= beta);
1531 // Step 15. Full depth search
1532 if (doFullDepthSearch)
1534 ss[ply].reduction = Depth(0);
1535 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1538 // Step 16. Undo move
1539 pos.undo_move(move);
1541 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1543 // Step 17. Check for new best move
1544 if (value > bestValue)
1550 if (value == value_mate_in(ply + 1))
1551 ss[ply].mateKiller = move;
1554 // Step 18. Check for split
1555 if ( TM.active_threads() > 1
1557 && depth >= MinimumSplitDepth
1559 && TM.available_thread_exists(threadID)
1561 && !TM.thread_should_stop(threadID)
1562 && TM.split(pos, ss, ply, NULL, beta, &bestValue,
1563 depth, &moveCount, &mp, threadID, false))
1567 // Step 19. Check for mate and stalemate
1568 // All legal moves have been searched and if there were
1569 // no legal moves, it must be mate or stalemate.
1570 // If one move was excluded return fail low.
1572 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1574 // Step 20. Update tables
1575 // If the search is not aborted, update the transposition table,
1576 // history counters, and killer moves.
1577 if (AbortSearch || TM.thread_should_stop(threadID))
1580 if (bestValue < beta)
1581 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1584 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1585 move = ss[ply].pv[ply];
1586 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1587 if (!pos.move_is_capture_or_promotion(move))
1589 update_history(pos, move, depth, movesSearched, moveCount);
1590 update_killers(move, ss[ply]);
1595 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1601 // qsearch() is the quiescence search function, which is called by the main
1602 // search function when the remaining depth is zero (or, to be more precise,
1603 // less than OnePly).
1605 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1606 Depth depth, int ply, int threadID) {
1608 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1609 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1611 assert(ply >= 0 && ply < PLY_MAX);
1612 assert(threadID >= 0 && threadID < TM.active_threads());
1617 Value staticValue, bestValue, value, futilityBase, futilityValue;
1618 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1619 const TTEntry* tte = NULL;
1621 bool pvNode = (beta - alpha != 1);
1622 Value oldAlpha = alpha;
1624 // Initialize, and make an early exit in case of an aborted search,
1625 // an instant draw, maximum ply reached, etc.
1626 init_node(ss, ply, threadID);
1628 // After init_node() that calls poll()
1629 if (AbortSearch || TM.thread_should_stop(threadID))
1632 if (pos.is_draw() || ply >= PLY_MAX - 1)
1635 // Transposition table lookup. At PV nodes, we don't use the TT for
1636 // pruning, but only for move ordering.
1637 tte = TT.retrieve(pos.get_key());
1638 ttMove = (tte ? tte->move() : MOVE_NONE);
1640 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1642 assert(tte->type() != VALUE_TYPE_EVAL);
1644 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1645 return value_from_tt(tte->value(), ply);
1648 isCheck = pos.is_check();
1650 // Evaluate the position statically
1652 staticValue = -VALUE_INFINITE;
1653 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1654 staticValue = value_from_tt(tte->value(), ply);
1656 staticValue = evaluate(pos, ei, threadID);
1660 ss[ply].eval = staticValue;
1661 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1664 // Initialize "stand pat score", and return it immediately if it is
1666 bestValue = staticValue;
1668 if (bestValue >= beta)
1670 // Store the score to avoid a future costly evaluation() call
1671 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1672 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1677 if (bestValue > alpha)
1680 // If we are near beta then try to get a cutoff pushing checks a bit further
1681 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1683 // Initialize a MovePicker object for the current position, and prepare
1684 // to search the moves. Because the depth is <= 0 here, only captures,
1685 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1686 // and we are near beta) will be generated.
1687 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1689 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1690 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1692 // Loop through the moves until no moves remain or a beta cutoff
1694 while ( alpha < beta
1695 && (move = mp.get_next_move()) != MOVE_NONE)
1697 assert(move_is_ok(move));
1699 moveIsCheck = pos.move_is_check(move, ci);
1701 // Update current move
1703 ss[ply].currentMove = move;
1711 && !move_is_promotion(move)
1712 && !pos.move_is_passed_pawn_push(move))
1714 futilityValue = futilityBase
1715 + pos.endgame_value_of_piece_on(move_to(move))
1716 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1718 if (futilityValue < alpha)
1720 if (futilityValue > bestValue)
1721 bestValue = futilityValue;
1726 // Detect blocking evasions that are candidate to be pruned
1727 evasionPrunable = isCheck
1728 && bestValue != -VALUE_INFINITE
1729 && !pos.move_is_capture(move)
1730 && pos.type_of_piece_on(move_from(move)) != KING
1731 && !pos.can_castle(pos.side_to_move());
1733 // Don't search moves with negative SEE values
1734 if ( (!isCheck || evasionPrunable)
1737 && !move_is_promotion(move)
1738 && pos.see_sign(move) < 0)
1741 // Make and search the move
1742 pos.do_move(move, st, ci, moveIsCheck);
1743 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1744 pos.undo_move(move);
1746 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1749 if (value > bestValue)
1760 // All legal moves have been searched. A special case: If we're in check
1761 // and no legal moves were found, it is checkmate.
1762 if (!moveCount && pos.is_check()) // Mate!
1763 return value_mated_in(ply);
1765 // Update transposition table
1766 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1767 if (bestValue <= oldAlpha)
1769 // If bestValue isn't changed it means it is still the static evaluation
1770 // of the node, so keep this info to avoid a future evaluation() call.
1771 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1772 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1774 else if (bestValue >= beta)
1776 move = ss[ply].pv[ply];
1777 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1779 // Update killers only for good checking moves
1780 if (!pos.move_is_capture_or_promotion(move))
1781 update_killers(move, ss[ply]);
1784 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1786 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1792 // sp_search() is used to search from a split point. This function is called
1793 // by each thread working at the split point. It is similar to the normal
1794 // search() function, but simpler. Because we have already probed the hash
1795 // table, done a null move search, and searched the first move before
1796 // splitting, we don't have to repeat all this work in sp_search(). We
1797 // also don't need to store anything to the hash table here: This is taken
1798 // care of after we return from the split point.
1799 // FIXME: We are currently ignoring mateThreat flag here
1801 void sp_search(SplitPoint* sp, int threadID) {
1803 assert(threadID >= 0 && threadID < TM.active_threads());
1804 assert(TM.active_threads() > 1);
1808 Depth ext, newDepth;
1809 Value value, futilityValueScaled;
1810 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1812 value = -VALUE_INFINITE;
1814 Position pos(*sp->pos);
1816 SearchStack* ss = sp->sstack[threadID];
1817 isCheck = pos.is_check();
1819 // Step 10. Loop through moves
1820 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1821 lock_grab(&(sp->lock));
1823 while ( sp->bestValue < sp->beta
1824 && !TM.thread_should_stop(threadID)
1825 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1827 moveCount = ++sp->moves;
1828 lock_release(&(sp->lock));
1830 assert(move_is_ok(move));
1832 moveIsCheck = pos.move_is_check(move, ci);
1833 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1835 // Step 11. Decide the new search depth
1836 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1837 newDepth = sp->depth - OnePly + ext;
1839 // Update current move
1840 ss[sp->ply].currentMove = move;
1842 // Step 12. Futility pruning
1845 && !captureOrPromotion
1846 && !move_is_castle(move))
1848 // Move count based pruning
1849 if ( moveCount >= futility_move_count(sp->depth)
1850 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1851 && sp->bestValue > value_mated_in(PLY_MAX))
1853 lock_grab(&(sp->lock));
1857 // Value based pruning
1858 Depth predictedDepth = newDepth - nonpv_reduction(sp->depth, moveCount);
1859 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1860 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1862 if (futilityValueScaled < sp->beta)
1864 lock_grab(&(sp->lock));
1866 if (futilityValueScaled > sp->bestValue)
1867 sp->bestValue = futilityValueScaled;
1872 // Step 13. Make the move
1873 pos.do_move(move, st, ci, moveIsCheck);
1875 // Step 14. Reduced search
1876 // if the move fails high will be re-searched at full depth.
1877 bool doFullDepthSearch = true;
1880 && !captureOrPromotion
1881 && !move_is_castle(move)
1882 && !move_is_killer(move, ss[sp->ply]))
1884 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1885 if (ss[sp->ply].reduction)
1887 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1888 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1892 // Step 15. Full depth search
1893 if (doFullDepthSearch)
1895 ss[sp->ply].reduction = Depth(0);
1896 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1899 // Step 16. Undo move
1900 pos.undo_move(move);
1902 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1904 // Step 17. Check for new best move
1905 lock_grab(&(sp->lock));
1907 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1909 sp->bestValue = value;
1910 if (sp->bestValue >= sp->beta)
1912 sp->stopRequest = true;
1913 sp_update_pv(sp->parentSstack, ss, sp->ply);
1918 /* Here we have the lock still grabbed */
1920 sp->slaves[threadID] = 0;
1923 lock_release(&(sp->lock));
1927 // sp_search_pv() is used to search from a PV split point. This function
1928 // is called by each thread working at the split point. It is similar to
1929 // the normal search_pv() function, but simpler. Because we have already
1930 // probed the hash table and searched the first move before splitting, we
1931 // don't have to repeat all this work in sp_search_pv(). We also don't
1932 // need to store anything to the hash table here: This is taken care of
1933 // after we return from the split point.
1934 // FIXME: We are ignoring mateThreat flag!
1936 void sp_search_pv(SplitPoint* sp, int threadID) {
1938 assert(threadID >= 0 && threadID < TM.active_threads());
1939 assert(TM.active_threads() > 1);
1943 Depth ext, newDepth;
1945 bool moveIsCheck, captureOrPromotion, dangerous;
1947 value = -VALUE_INFINITE;
1949 Position pos(*sp->pos);
1951 SearchStack* ss = sp->sstack[threadID];
1953 // Step 10. Loop through moves
1954 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1955 lock_grab(&(sp->lock));
1957 while ( sp->alpha < sp->beta
1958 && !TM.thread_should_stop(threadID)
1959 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1961 moveCount = ++sp->moves;
1962 lock_release(&(sp->lock));
1964 assert(move_is_ok(move));
1966 moveIsCheck = pos.move_is_check(move, ci);
1967 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1969 // Step 11. Decide the new search depth
1970 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1971 newDepth = sp->depth - OnePly + ext;
1973 // Update current move
1974 ss[sp->ply].currentMove = move;
1976 // Step 12. Futility pruning (is omitted in PV nodes)
1978 // Step 13. Make the move
1979 pos.do_move(move, st, ci, moveIsCheck);
1981 // Step 14. Reduced search
1982 // if the move fails high will be re-searched at full depth.
1983 bool doFullDepthSearch = true;
1986 && !captureOrPromotion
1987 && !move_is_castle(move)
1988 && !move_is_killer(move, ss[sp->ply]))
1990 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
1991 if (ss[sp->ply].reduction)
1993 Value localAlpha = sp->alpha;
1994 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1995 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
1999 // Step 15. Full depth search
2000 if (doFullDepthSearch)
2002 Value localAlpha = sp->alpha;
2003 ss[sp->ply].reduction = Depth(0);
2004 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2006 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
2008 // If another thread has failed high then sp->alpha has been increased
2009 // to be higher or equal then beta, if so, avoid to start a PV search.
2010 localAlpha = sp->alpha;
2011 if (localAlpha < sp->beta)
2012 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2016 // Step 16. Undo move
2017 pos.undo_move(move);
2019 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2021 // Step 17. Check for new best move
2022 lock_grab(&(sp->lock));
2024 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
2026 sp->bestValue = value;
2027 if (value > sp->alpha)
2029 // Ask threads to stop before to modify sp->alpha
2030 if (value >= sp->beta)
2031 sp->stopRequest = true;
2035 sp_update_pv(sp->parentSstack, ss, sp->ply);
2036 if (value == value_mate_in(sp->ply + 1))
2037 ss[sp->ply].mateKiller = move;
2042 /* Here we have the lock still grabbed */
2044 sp->slaves[threadID] = 0;
2047 lock_release(&(sp->lock));
2051 // init_node() is called at the beginning of all the search functions
2052 // (search(), search_pv(), qsearch(), and so on) and initializes the
2053 // search stack object corresponding to the current node. Once every
2054 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2055 // for user input and checks whether it is time to stop the search.
2057 void init_node(SearchStack ss[], int ply, int threadID) {
2059 assert(ply >= 0 && ply < PLY_MAX);
2060 assert(threadID >= 0 && threadID < TM.active_threads());
2062 TM.incrementNodeCounter(threadID);
2067 if (NodesSincePoll >= NodesBetweenPolls)
2074 ss[ply + 2].initKillers();
2078 // update_pv() is called whenever a search returns a value > alpha.
2079 // It updates the PV in the SearchStack object corresponding to the
2082 void update_pv(SearchStack ss[], int ply) {
2084 assert(ply >= 0 && ply < PLY_MAX);
2088 ss[ply].pv[ply] = ss[ply].currentMove;
2090 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2091 ss[ply].pv[p] = ss[ply + 1].pv[p];
2093 ss[ply].pv[p] = MOVE_NONE;
2097 // sp_update_pv() is a variant of update_pv for use at split points. The
2098 // difference between the two functions is that sp_update_pv also updates
2099 // the PV at the parent node.
2101 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2103 assert(ply >= 0 && ply < PLY_MAX);
2107 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2109 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2110 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2112 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2116 // connected_moves() tests whether two moves are 'connected' in the sense
2117 // that the first move somehow made the second move possible (for instance
2118 // if the moving piece is the same in both moves). The first move is assumed
2119 // to be the move that was made to reach the current position, while the
2120 // second move is assumed to be a move from the current position.
2122 bool connected_moves(const Position& pos, Move m1, Move m2) {
2124 Square f1, t1, f2, t2;
2127 assert(move_is_ok(m1));
2128 assert(move_is_ok(m2));
2130 if (m2 == MOVE_NONE)
2133 // Case 1: The moving piece is the same in both moves
2139 // Case 2: The destination square for m2 was vacated by m1
2145 // Case 3: Moving through the vacated square
2146 if ( piece_is_slider(pos.piece_on(f2))
2147 && bit_is_set(squares_between(f2, t2), f1))
2150 // Case 4: The destination square for m2 is defended by the moving piece in m1
2151 p = pos.piece_on(t1);
2152 if (bit_is_set(pos.attacks_from(p, t1), t2))
2155 // Case 5: Discovered check, checking piece is the piece moved in m1
2156 if ( piece_is_slider(p)
2157 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2158 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2160 // discovered_check_candidates() works also if the Position's side to
2161 // move is the opposite of the checking piece.
2162 Color them = opposite_color(pos.side_to_move());
2163 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2165 if (bit_is_set(dcCandidates, f2))
2172 // value_is_mate() checks if the given value is a mate one
2173 // eventually compensated for the ply.
2175 bool value_is_mate(Value value) {
2177 assert(abs(value) <= VALUE_INFINITE);
2179 return value <= value_mated_in(PLY_MAX)
2180 || value >= value_mate_in(PLY_MAX);
2184 // move_is_killer() checks if the given move is among the
2185 // killer moves of that ply.
2187 bool move_is_killer(Move m, const SearchStack& ss) {
2189 const Move* k = ss.killers;
2190 for (int i = 0; i < KILLER_MAX; i++, k++)
2198 // extension() decides whether a move should be searched with normal depth,
2199 // or with extended depth. Certain classes of moves (checking moves, in
2200 // particular) are searched with bigger depth than ordinary moves and in
2201 // any case are marked as 'dangerous'. Note that also if a move is not
2202 // extended, as example because the corresponding UCI option is set to zero,
2203 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2205 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2206 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2208 assert(m != MOVE_NONE);
2210 Depth result = Depth(0);
2211 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2216 result += CheckExtension[pvNode];
2219 result += SingleEvasionExtension[pvNode];
2222 result += MateThreatExtension[pvNode];
2225 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2227 Color c = pos.side_to_move();
2228 if (relative_rank(c, move_to(m)) == RANK_7)
2230 result += PawnPushTo7thExtension[pvNode];
2233 if (pos.pawn_is_passed(c, move_to(m)))
2235 result += PassedPawnExtension[pvNode];
2240 if ( captureOrPromotion
2241 && pos.type_of_piece_on(move_to(m)) != PAWN
2242 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2243 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2244 && !move_is_promotion(m)
2247 result += PawnEndgameExtension[pvNode];
2252 && captureOrPromotion
2253 && pos.type_of_piece_on(move_to(m)) != PAWN
2254 && pos.see_sign(m) >= 0)
2260 return Min(result, OnePly);
2264 // ok_to_do_nullmove() looks at the current position and decides whether
2265 // doing a 'null move' should be allowed. In order to avoid zugzwang
2266 // problems, null moves are not allowed when the side to move has very
2267 // little material left. Currently, the test is a bit too simple: Null
2268 // moves are avoided only when the side to move has only pawns left.
2269 // It's probably a good idea to avoid null moves in at least some more
2270 // complicated endgames, e.g. KQ vs KR. FIXME
2272 bool ok_to_do_nullmove(const Position& pos) {
2274 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2278 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2279 // non-tactical moves late in the move list close to the leaves are
2280 // candidates for pruning.
2282 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2284 assert(move_is_ok(m));
2285 assert(threat == MOVE_NONE || move_is_ok(threat));
2286 assert(!pos.move_is_check(m));
2287 assert(!pos.move_is_capture_or_promotion(m));
2288 assert(!pos.move_is_passed_pawn_push(m));
2290 Square mfrom, mto, tfrom, tto;
2292 // Prune if there isn't any threat move
2293 if (threat == MOVE_NONE)
2296 mfrom = move_from(m);
2298 tfrom = move_from(threat);
2299 tto = move_to(threat);
2301 // Case 1: Don't prune moves which move the threatened piece
2305 // Case 2: If the threatened piece has value less than or equal to the
2306 // value of the threatening piece, don't prune move which defend it.
2307 if ( pos.move_is_capture(threat)
2308 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2309 || pos.type_of_piece_on(tfrom) == KING)
2310 && pos.move_attacks_square(m, tto))
2313 // Case 3: If the moving piece in the threatened move is a slider, don't
2314 // prune safe moves which block its ray.
2315 if ( piece_is_slider(pos.piece_on(tfrom))
2316 && bit_is_set(squares_between(tfrom, tto), mto)
2317 && pos.see_sign(m) >= 0)
2324 // ok_to_use_TT() returns true if a transposition table score
2325 // can be used at a given point in search.
2327 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2329 Value v = value_from_tt(tte->value(), ply);
2331 return ( tte->depth() >= depth
2332 || v >= Max(value_mate_in(PLY_MAX), beta)
2333 || v < Min(value_mated_in(PLY_MAX), beta))
2335 && ( (is_lower_bound(tte->type()) && v >= beta)
2336 || (is_upper_bound(tte->type()) && v < beta));
2340 // refine_eval() returns the transposition table score if
2341 // possible otherwise falls back on static position evaluation.
2343 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2348 Value v = value_from_tt(tte->value(), ply);
2350 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2351 || (is_upper_bound(tte->type()) && v < defaultEval))
2358 // update_history() registers a good move that produced a beta-cutoff
2359 // in history and marks as failures all the other moves of that ply.
2361 void update_history(const Position& pos, Move move, Depth depth,
2362 Move movesSearched[], int moveCount) {
2366 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2368 for (int i = 0; i < moveCount - 1; i++)
2370 m = movesSearched[i];
2374 if (!pos.move_is_capture_or_promotion(m))
2375 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2380 // update_killers() add a good move that produced a beta-cutoff
2381 // among the killer moves of that ply.
2383 void update_killers(Move m, SearchStack& ss) {
2385 if (m == ss.killers[0])
2388 for (int i = KILLER_MAX - 1; i > 0; i--)
2389 ss.killers[i] = ss.killers[i - 1];
2395 // update_gains() updates the gains table of a non-capture move given
2396 // the static position evaluation before and after the move.
2398 void update_gains(const Position& pos, Move m, Value before, Value after) {
2401 && before != VALUE_NONE
2402 && after != VALUE_NONE
2403 && pos.captured_piece() == NO_PIECE_TYPE
2404 && !move_is_castle(m)
2405 && !move_is_promotion(m))
2406 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2410 // current_search_time() returns the number of milliseconds which have passed
2411 // since the beginning of the current search.
2413 int current_search_time() {
2415 return get_system_time() - SearchStartTime;
2419 // nps() computes the current nodes/second count.
2423 int t = current_search_time();
2424 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2428 // poll() performs two different functions: It polls for user input, and it
2429 // looks at the time consumed so far and decides if it's time to abort the
2432 void poll(SearchStack ss[], int ply) {
2434 static int lastInfoTime;
2435 int t = current_search_time();
2440 // We are line oriented, don't read single chars
2441 std::string command;
2443 if (!std::getline(std::cin, command))
2446 if (command == "quit")
2449 PonderSearch = false;
2453 else if (command == "stop")
2456 PonderSearch = false;
2458 else if (command == "ponderhit")
2462 // Print search information
2466 else if (lastInfoTime > t)
2467 // HACK: Must be a new search where we searched less than
2468 // NodesBetweenPolls nodes during the first second of search.
2471 else if (t - lastInfoTime >= 1000)
2478 if (dbg_show_hit_rate)
2479 dbg_print_hit_rate();
2481 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2482 << " time " << t << " hashfull " << TT.full() << endl;
2484 // We only support current line printing in single thread mode
2485 if (ShowCurrentLine && TM.active_threads() == 1)
2487 cout << "info currline";
2488 for (int p = 0; p < ply; p++)
2489 cout << " " << ss[p].currentMove;
2495 // Should we stop the search?
2499 bool stillAtFirstMove = RootMoveNumber == 1
2500 && !AspirationFailLow
2501 && t > MaxSearchTime + ExtraSearchTime;
2503 bool noMoreTime = t > AbsoluteMaxSearchTime
2504 || stillAtFirstMove;
2506 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2507 || (ExactMaxTime && t >= ExactMaxTime)
2508 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2513 // ponderhit() is called when the program is pondering (i.e. thinking while
2514 // it's the opponent's turn to move) in order to let the engine know that
2515 // it correctly predicted the opponent's move.
2519 int t = current_search_time();
2520 PonderSearch = false;
2522 bool stillAtFirstMove = RootMoveNumber == 1
2523 && !AspirationFailLow
2524 && t > MaxSearchTime + ExtraSearchTime;
2526 bool noMoreTime = t > AbsoluteMaxSearchTime
2527 || stillAtFirstMove;
2529 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2534 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2536 void init_ss_array(SearchStack ss[]) {
2538 for (int i = 0; i < 3; i++)
2541 ss[i].initKillers();
2546 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2547 // while the program is pondering. The point is to work around a wrinkle in
2548 // the UCI protocol: When pondering, the engine is not allowed to give a
2549 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2550 // We simply wait here until one of these commands is sent, and return,
2551 // after which the bestmove and pondermove will be printed (in id_loop()).
2553 void wait_for_stop_or_ponderhit() {
2555 std::string command;
2559 if (!std::getline(std::cin, command))
2562 if (command == "quit")
2567 else if (command == "ponderhit" || command == "stop")
2573 // init_thread() is the function which is called when a new thread is
2574 // launched. It simply calls the idle_loop() function with the supplied
2575 // threadID. There are two versions of this function; one for POSIX
2576 // threads and one for Windows threads.
2578 #if !defined(_MSC_VER)
2580 void* init_thread(void *threadID) {
2582 TM.idle_loop(*(int*)threadID, NULL);
2588 DWORD WINAPI init_thread(LPVOID threadID) {
2590 TM.idle_loop(*(int*)threadID, NULL);
2597 /// The ThreadsManager class
2599 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2600 // get_beta_counters() are getters/setters for the per thread
2601 // counters used to sort the moves at root.
2603 void ThreadsManager::resetNodeCounters() {
2605 for (int i = 0; i < MAX_THREADS; i++)
2606 threads[i].nodes = 0ULL;
2609 void ThreadsManager::resetBetaCounters() {
2611 for (int i = 0; i < MAX_THREADS; i++)
2612 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2615 int64_t ThreadsManager::nodes_searched() const {
2617 int64_t result = 0ULL;
2618 for (int i = 0; i < ActiveThreads; i++)
2619 result += threads[i].nodes;
2624 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2627 for (int i = 0; i < MAX_THREADS; i++)
2629 our += threads[i].betaCutOffs[us];
2630 their += threads[i].betaCutOffs[opposite_color(us)];
2635 // idle_loop() is where the threads are parked when they have no work to do.
2636 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2637 // object for which the current thread is the master.
2639 void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2641 assert(threadID >= 0 && threadID < MAX_THREADS);
2645 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2646 // master should exit as last one.
2647 if (AllThreadsShouldExit)
2650 threads[threadID].state = THREAD_TERMINATED;
2654 // If we are not thinking, wait for a condition to be signaled
2655 // instead of wasting CPU time polling for work.
2656 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2659 assert(threadID != 0);
2660 threads[threadID].state = THREAD_SLEEPING;
2662 #if !defined(_MSC_VER)
2663 pthread_mutex_lock(&WaitLock);
2664 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2665 pthread_cond_wait(&WaitCond, &WaitLock);
2666 pthread_mutex_unlock(&WaitLock);
2668 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2672 // If thread has just woken up, mark it as available
2673 if (threads[threadID].state == THREAD_SLEEPING)
2674 threads[threadID].state = THREAD_AVAILABLE;
2676 // If this thread has been assigned work, launch a search
2677 if (threads[threadID].state == THREAD_WORKISWAITING)
2679 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2681 threads[threadID].state = THREAD_SEARCHING;
2683 if (threads[threadID].splitPoint->pvNode)
2684 sp_search_pv(threads[threadID].splitPoint, threadID);
2686 sp_search(threads[threadID].splitPoint, threadID);
2688 assert(threads[threadID].state == THREAD_SEARCHING);
2690 threads[threadID].state = THREAD_AVAILABLE;
2693 // If this thread is the master of a split point and all threads have
2694 // finished their work at this split point, return from the idle loop.
2695 if (waitSp != NULL && waitSp->cpus == 0)
2697 assert(threads[threadID].state == THREAD_AVAILABLE);
2699 threads[threadID].state = THREAD_SEARCHING;
2706 // init_threads() is called during startup. It launches all helper threads,
2707 // and initializes the split point stack and the global locks and condition
2710 void ThreadsManager::init_threads() {
2715 #if !defined(_MSC_VER)
2716 pthread_t pthread[1];
2719 // Initialize global locks
2720 lock_init(&MPLock, NULL);
2722 // Initialize SplitPointStack locks
2723 for (i = 0; i < MAX_THREADS; i++)
2724 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2726 SplitPointStack[i][j].parent = NULL;
2727 lock_init(&(SplitPointStack[i][j].lock), NULL);
2730 #if !defined(_MSC_VER)
2731 pthread_mutex_init(&WaitLock, NULL);
2732 pthread_cond_init(&WaitCond, NULL);
2734 for (i = 0; i < MAX_THREADS; i++)
2735 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2738 // Will be set just before program exits to properly end the threads
2739 AllThreadsShouldExit = false;
2741 // Threads will be put to sleep as soon as created
2742 AllThreadsShouldSleep = true;
2744 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2746 threads[0].state = THREAD_SEARCHING;
2747 for (i = 1; i < MAX_THREADS; i++)
2748 threads[i].state = THREAD_AVAILABLE;
2750 // Launch the helper threads
2751 for (i = 1; i < MAX_THREADS; i++)
2754 #if !defined(_MSC_VER)
2755 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2758 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
2763 cout << "Failed to create thread number " << i << endl;
2764 Application::exit_with_failure();
2767 // Wait until the thread has finished launching and is gone to sleep
2768 while (threads[i].state != THREAD_SLEEPING);
2773 // exit_threads() is called when the program exits. It makes all the
2774 // helper threads exit cleanly.
2776 void ThreadsManager::exit_threads() {
2778 ActiveThreads = MAX_THREADS; // HACK
2779 AllThreadsShouldSleep = true; // HACK
2780 wake_sleeping_threads();
2782 // This makes the threads to exit idle_loop()
2783 AllThreadsShouldExit = true;
2785 // Wait for thread termination
2786 for (int i = 1; i < MAX_THREADS; i++)
2787 while (threads[i].state != THREAD_TERMINATED);
2789 // Now we can safely destroy the locks
2790 for (int i = 0; i < MAX_THREADS; i++)
2791 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2792 lock_destroy(&(SplitPointStack[i][j].lock));
2796 // thread_should_stop() checks whether the thread should stop its search.
2797 // This can happen if a beta cutoff has occurred in the thread's currently
2798 // active split point, or in some ancestor of the current split point.
2800 bool ThreadsManager::thread_should_stop(int threadID) const {
2802 assert(threadID >= 0 && threadID < ActiveThreads);
2806 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent);
2811 // thread_is_available() checks whether the thread with threadID "slave" is
2812 // available to help the thread with threadID "master" at a split point. An
2813 // obvious requirement is that "slave" must be idle. With more than two
2814 // threads, this is not by itself sufficient: If "slave" is the master of
2815 // some active split point, it is only available as a slave to the other
2816 // threads which are busy searching the split point at the top of "slave"'s
2817 // split point stack (the "helpful master concept" in YBWC terminology).
2819 bool ThreadsManager::thread_is_available(int slave, int master) const {
2821 assert(slave >= 0 && slave < ActiveThreads);
2822 assert(master >= 0 && master < ActiveThreads);
2823 assert(ActiveThreads > 1);
2825 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2828 // Make a local copy to be sure doesn't change under our feet
2829 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2831 if (localActiveSplitPoints == 0)
2832 // No active split points means that the thread is available as
2833 // a slave for any other thread.
2836 if (ActiveThreads == 2)
2839 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2840 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2841 // could have been set to 0 by another thread leading to an out of bound access.
2842 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2849 // available_thread_exists() tries to find an idle thread which is available as
2850 // a slave for the thread with threadID "master".
2852 bool ThreadsManager::available_thread_exists(int master) const {
2854 assert(master >= 0 && master < ActiveThreads);
2855 assert(ActiveThreads > 1);
2857 for (int i = 0; i < ActiveThreads; i++)
2858 if (thread_is_available(i, master))
2865 // split() does the actual work of distributing the work at a node between
2866 // several threads at PV nodes. If it does not succeed in splitting the
2867 // node (because no idle threads are available, or because we have no unused
2868 // split point objects), the function immediately returns false. If
2869 // splitting is possible, a SplitPoint object is initialized with all the
2870 // data that must be copied to the helper threads (the current position and
2871 // search stack, alpha, beta, the search depth, etc.), and we tell our
2872 // helper threads that they have been assigned work. This will cause them
2873 // to instantly leave their idle loops and call sp_search_pv(). When all
2874 // threads have returned from sp_search_pv (or, equivalently, when
2875 // splitPoint->cpus becomes 0), split() returns true.
2877 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2878 Value* alpha, const Value beta, Value* bestValue,
2879 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2882 assert(sstck != NULL);
2883 assert(ply >= 0 && ply < PLY_MAX);
2884 assert(*bestValue >= -VALUE_INFINITE);
2885 assert( ( pvNode && *bestValue <= *alpha)
2886 || (!pvNode && *bestValue < beta ));
2887 assert(!pvNode || *alpha < beta);
2888 assert(beta <= VALUE_INFINITE);
2889 assert(depth > Depth(0));
2890 assert(master >= 0 && master < ActiveThreads);
2891 assert(ActiveThreads > 1);
2893 SplitPoint* splitPoint;
2897 // If no other thread is available to help us, or if we have too many
2898 // active split points, don't split.
2899 if ( !available_thread_exists(master)
2900 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2902 lock_release(&MPLock);
2906 // Pick the next available split point object from the split point stack
2907 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2909 // Initialize the split point object
2910 splitPoint->parent = threads[master].splitPoint;
2911 splitPoint->stopRequest = false;
2912 splitPoint->ply = ply;
2913 splitPoint->depth = depth;
2914 splitPoint->alpha = pvNode ? *alpha : beta - 1;
2915 splitPoint->beta = beta;
2916 splitPoint->pvNode = pvNode;
2917 splitPoint->bestValue = *bestValue;
2918 splitPoint->master = master;
2919 splitPoint->mp = mp;
2920 splitPoint->moves = *moves;
2921 splitPoint->cpus = 1;
2922 splitPoint->pos = &p;
2923 splitPoint->parentSstack = sstck;
2924 for (int i = 0; i < ActiveThreads; i++)
2925 splitPoint->slaves[i] = 0;
2927 threads[master].splitPoint = splitPoint;
2928 threads[master].activeSplitPoints++;
2930 // If we are here it means we are not available
2931 assert(threads[master].state != THREAD_AVAILABLE);
2933 // Allocate available threads setting state to THREAD_BOOKED
2934 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2935 if (thread_is_available(i, master))
2937 threads[i].state = THREAD_BOOKED;
2938 threads[i].splitPoint = splitPoint;
2939 splitPoint->slaves[i] = 1;
2943 assert(splitPoint->cpus > 1);
2945 // We can release the lock because slave threads are already booked and master is not available
2946 lock_release(&MPLock);
2948 // Tell the threads that they have work to do. This will make them leave
2949 // their idle loop. But before copy search stack tail for each thread.
2950 for (int i = 0; i < ActiveThreads; i++)
2951 if (i == master || splitPoint->slaves[i])
2953 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2955 assert(i == master || threads[i].state == THREAD_BOOKED);
2957 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2960 // Everything is set up. The master thread enters the idle loop, from
2961 // which it will instantly launch a search, because its state is
2962 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2963 // idle loop, which means that the main thread will return from the idle
2964 // loop when all threads have finished their work at this split point
2965 // (i.e. when splitPoint->cpus == 0).
2966 idle_loop(master, splitPoint);
2968 // We have returned from the idle loop, which means that all threads are
2969 // finished. Update alpha, beta and bestValue, and return.
2973 *alpha = splitPoint->alpha;
2975 *bestValue = splitPoint->bestValue;
2976 threads[master].activeSplitPoints--;
2977 threads[master].splitPoint = splitPoint->parent;
2979 lock_release(&MPLock);
2984 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2985 // to start a new search from the root.
2987 void ThreadsManager::wake_sleeping_threads() {
2989 assert(AllThreadsShouldSleep);
2990 assert(ActiveThreads > 0);
2992 AllThreadsShouldSleep = false;
2994 if (ActiveThreads == 1)
2997 for (int i = 1; i < ActiveThreads; i++)
2998 assert(threads[i].state == THREAD_SLEEPING);
3000 #if !defined(_MSC_VER)
3001 pthread_mutex_lock(&WaitLock);
3002 pthread_cond_broadcast(&WaitCond);
3003 pthread_mutex_unlock(&WaitLock);
3005 for (int i = 1; i < MAX_THREADS; i++)
3006 SetEvent(SitIdleEvent[i]);
3012 // put_threads_to_sleep() makes all the threads go to sleep just before
3013 // to leave think(), at the end of the search. Threads should have already
3014 // finished the job and should be idle.
3016 void ThreadsManager::put_threads_to_sleep() {
3018 assert(!AllThreadsShouldSleep);
3020 // This makes the threads to go to sleep
3021 AllThreadsShouldSleep = true;
3024 /// The RootMoveList class
3026 // RootMoveList c'tor
3028 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3030 SearchStack ss[PLY_MAX_PLUS_2];
3031 MoveStack mlist[MaxRootMoves];
3033 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3035 // Generate all legal moves
3036 MoveStack* last = generate_moves(pos, mlist);
3038 // Add each move to the moves[] array
3039 for (MoveStack* cur = mlist; cur != last; cur++)
3041 bool includeMove = includeAllMoves;
3043 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3044 includeMove = (searchMoves[k] == cur->move);
3049 // Find a quick score for the move
3051 pos.do_move(cur->move, st);
3052 moves[count].move = cur->move;
3053 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3054 moves[count].pv[0] = cur->move;
3055 moves[count].pv[1] = MOVE_NONE;
3056 pos.undo_move(cur->move);
3063 // RootMoveList simple methods definitions
3065 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3067 moves[moveNum].nodes = nodes;
3068 moves[moveNum].cumulativeNodes += nodes;
3071 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3073 moves[moveNum].ourBeta = our;
3074 moves[moveNum].theirBeta = their;
3077 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3081 for (j = 0; pv[j] != MOVE_NONE; j++)
3082 moves[moveNum].pv[j] = pv[j];
3084 moves[moveNum].pv[j] = MOVE_NONE;
3088 // RootMoveList::sort() sorts the root move list at the beginning of a new
3091 void RootMoveList::sort() {
3093 sort_multipv(count - 1); // Sort all items
3097 // RootMoveList::sort_multipv() sorts the first few moves in the root move
3098 // list by their scores and depths. It is used to order the different PVs
3099 // correctly in MultiPV mode.
3101 void RootMoveList::sort_multipv(int n) {
3105 for (i = 1; i <= n; i++)
3107 RootMove rm = moves[i];
3108 for (j = i; j > 0 && moves[j - 1] < rm; j--)
3109 moves[j] = moves[j - 1];