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 // Depth limit for use of dynamic threat detection when null move fails low
175 const Depth ThreatDepth = 5 * OnePly;
177 // Step 9. Internal iterative deepening
179 const Depth IIDDepthAtPVNodes = 5 * OnePly;
180 const Depth IIDDepthAtNonPVNodes = 8 * OnePly;
182 // Internal iterative deepening margin. At Non-PV nodes
183 // we do an internal iterative deepening
184 // search when the static evaluation is at most IIDMargin below beta.
185 const Value IIDMargin = Value(0x100);
187 // Step 11. Decide the new search depth
189 // Extensions. Configurable UCI options.
190 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
191 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
192 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
194 const Depth SingularExtensionDepthAtPVNodes = 6 * OnePly;
195 const Depth SingularExtensionDepthAtNonPVNodes = 8 * OnePly;
197 // If the TT move is at least SingularExtensionMargin better then the
198 // remaining ones we will extend it.
199 const Value SingularExtensionMargin = Value(0x20);
201 // Step 12. Futility pruning
203 const Value FutilityMarginQS = Value(0x80);
205 // Futility lookup tables (initialized at startup) and their getter functions
206 int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
207 int FutilityMoveCountArray[32]; // [depth]
209 inline Value futility_margin(Depth d, int mn) { return Value(d < 7*OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
210 inline int futility_move_count(Depth d) { return d < 16*OnePly ? FutilityMoveCountArray[d] : 512; }
212 // Step 14. Reduced search
214 // Reduction lookup tables (initialized at startup) and their getter functions
215 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
216 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
218 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
219 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
221 // Step. Common adjustments
223 // Search depth at iteration 1
224 const Depth InitialDepth = OnePly;
226 // Easy move margin. An easy move candidate must be at least this much
227 // better than the second best move.
228 const Value EasyMoveMargin = Value(0x200);
230 // Last seconds noise filtering (LSN)
231 const bool UseLSNFiltering = true;
232 const int LSNTime = 4000; // In milliseconds
233 const Value LSNValue = value_from_centipawns(200);
234 bool loseOnTime = false;
239 // Iteration counters
242 // Scores and number of times the best move changed for each iteration
243 Value ValueByIteration[PLY_MAX_PLUS_2];
244 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
246 // Search window management
252 // Time managment variables
255 int MaxNodes, MaxDepth;
256 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
257 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
258 bool AbortSearch, Quit;
259 bool AspirationFailLow;
261 // Show current line?
262 bool ShowCurrentLine;
266 std::ofstream LogFile;
268 // MP related variables
269 Depth MinimumSplitDepth;
270 int MaxThreadsPerSplitPoint;
273 // Node counters, used only by thread[0] but try to keep in different
274 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
276 int NodesBetweenPolls = 30000;
283 Value id_loop(const Position& pos, Move searchMoves[]);
284 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
285 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
286 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
287 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
288 void sp_search(SplitPoint* sp, int threadID);
289 void sp_search_pv(SplitPoint* sp, int threadID);
290 void init_node(SearchStack ss[], int ply, int threadID);
291 void update_pv(SearchStack ss[], int ply);
292 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
293 bool connected_moves(const Position& pos, Move m1, Move m2);
294 bool value_is_mate(Value value);
295 bool move_is_killer(Move m, const SearchStack& ss);
296 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
297 bool ok_to_do_nullmove(const Position& pos);
298 bool ok_to_prune(const Position& pos, Move m, Move threat);
299 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
300 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
301 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
302 void update_killers(Move m, SearchStack& ss);
303 void update_gains(const Position& pos, Move move, Value before, Value after);
305 int current_search_time();
307 void poll(SearchStack ss[], int ply);
309 void wait_for_stop_or_ponderhit();
310 void init_ss_array(SearchStack ss[]);
312 #if !defined(_MSC_VER)
313 void *init_thread(void *threadID);
315 DWORD WINAPI init_thread(LPVOID threadID);
325 /// init_threads(), exit_threads() and nodes_searched() are helpers to
326 /// give accessibility to some TM methods from outside of current file.
328 void init_threads() { TM.init_threads(); }
329 void exit_threads() { TM.exit_threads(); }
330 int64_t nodes_searched() { return TM.nodes_searched(); }
333 /// perft() is our utility to verify move generation is bug free. All the legal
334 /// moves up to given depth are generated and counted and the sum returned.
336 int perft(Position& pos, Depth depth)
340 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
342 // If we are at the last ply we don't need to do and undo
343 // the moves, just to count them.
344 if (depth <= OnePly) // Replace with '<' to test also qsearch
346 while (mp.get_next_move()) sum++;
350 // Loop through all legal moves
352 while ((move = mp.get_next_move()) != MOVE_NONE)
355 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
356 sum += perft(pos, depth - OnePly);
363 /// think() is the external interface to Stockfish's search, and is called when
364 /// the program receives the UCI 'go' command. It initializes various
365 /// search-related global variables, and calls root_search(). It returns false
366 /// when a quit command is received during the search.
368 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
369 int time[], int increment[], int movesToGo, int maxDepth,
370 int maxNodes, int maxTime, Move searchMoves[]) {
372 // Initialize global search variables
373 StopOnPonderhit = AbortSearch = Quit = false;
374 AspirationFailLow = false;
376 SearchStartTime = get_system_time();
377 ExactMaxTime = maxTime;
380 InfiniteSearch = infinite;
381 PonderSearch = ponder;
382 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
384 // Look for a book move, only during games, not tests
385 if (UseTimeManagement && get_option_value_bool("OwnBook"))
388 if (get_option_value_string("Book File") != OpeningBook.file_name())
389 OpeningBook.open(get_option_value_string("Book File"));
391 bookMove = OpeningBook.get_move(pos);
392 if (bookMove != MOVE_NONE)
395 wait_for_stop_or_ponderhit();
397 cout << "bestmove " << bookMove << endl;
402 TM.resetNodeCounters();
404 if (button_was_pressed("New Game"))
405 loseOnTime = false; // Reset at the beginning of a new game
407 // Read UCI option values
408 TT.set_size(get_option_value_int("Hash"));
409 if (button_was_pressed("Clear Hash"))
412 bool PonderingEnabled = get_option_value_bool("Ponder");
413 MultiPV = get_option_value_int("MultiPV");
415 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
416 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
418 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
419 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
421 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
422 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
424 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
425 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
427 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
428 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
430 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
431 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
433 Chess960 = get_option_value_bool("UCI_Chess960");
434 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
435 UseLogFile = get_option_value_bool("Use Search Log");
437 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
439 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
440 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
442 read_weights(pos.side_to_move());
444 // Set the number of active threads
445 int newActiveThreads = get_option_value_int("Threads");
446 if (newActiveThreads != TM.active_threads())
448 TM.set_active_threads(newActiveThreads);
449 init_eval(TM.active_threads());
450 // HACK: init_eval() destroys the static castleRightsMask[] array in the
451 // Position class. The below line repairs the damage.
452 Position p(pos.to_fen());
456 // Wake up sleeping threads
457 TM.wake_sleeping_threads();
460 int myTime = time[side_to_move];
461 int myIncrement = increment[side_to_move];
462 if (UseTimeManagement)
464 if (!movesToGo) // Sudden death time control
468 MaxSearchTime = myTime / 30 + myIncrement;
469 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
471 else // Blitz game without increment
473 MaxSearchTime = myTime / 30;
474 AbsoluteMaxSearchTime = myTime / 8;
477 else // (x moves) / (y minutes)
481 MaxSearchTime = myTime / 2;
482 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
486 MaxSearchTime = myTime / Min(movesToGo, 20);
487 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
491 if (PonderingEnabled)
493 MaxSearchTime += MaxSearchTime / 4;
494 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
498 // Set best NodesBetweenPolls interval
500 NodesBetweenPolls = Min(MaxNodes, 30000);
501 else if (myTime && myTime < 1000)
502 NodesBetweenPolls = 1000;
503 else if (myTime && myTime < 5000)
504 NodesBetweenPolls = 5000;
506 NodesBetweenPolls = 30000;
508 // Write information to search log file
510 LogFile << "Searching: " << pos.to_fen() << endl
511 << "infinite: " << infinite
512 << " ponder: " << ponder
513 << " time: " << myTime
514 << " increment: " << myIncrement
515 << " moves to go: " << movesToGo << endl;
517 // LSN filtering. Used only for developing purpose. Disabled by default.
521 // Step 2. If after last move we decided to lose on time, do it now!
522 while (SearchStartTime + myTime + 1000 > get_system_time())
526 // We're ready to start thinking. Call the iterative deepening loop function
527 Value v = id_loop(pos, searchMoves);
531 // Step 1. If this is sudden death game and our position is hopeless,
532 // decide to lose on time.
533 if ( !loseOnTime // If we already lost on time, go to step 3.
543 // Step 3. Now after stepping over the time limit, reset flag for next match.
551 TM.put_threads_to_sleep();
557 /// init_search() is called during startup. It initializes various lookup tables
561 // Init our reduction lookup tables
562 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
563 for (int j = 1; j < 64; j++) // j == moveNumber
565 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
566 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
567 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
568 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
571 // Init futility margins array
572 for (int i = 0; i < 14; i++) // i == depth (OnePly = 2)
573 for (int j = 0; j < 64; j++) // j == moveNumber
575 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
578 // Init futility move count array
579 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
580 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
584 // SearchStack::init() initializes a search stack. Used at the beginning of a
585 // new search from the root.
586 void SearchStack::init(int ply) {
588 pv[ply] = pv[ply + 1] = MOVE_NONE;
589 currentMove = threatMove = MOVE_NONE;
590 reduction = Depth(0);
594 void SearchStack::initKillers() {
596 mateKiller = MOVE_NONE;
597 for (int i = 0; i < KILLER_MAX; i++)
598 killers[i] = MOVE_NONE;
603 // id_loop() is the main iterative deepening loop. It calls root_search
604 // repeatedly with increasing depth until the allocated thinking time has
605 // been consumed, the user stops the search, or the maximum search depth is
608 Value id_loop(const Position& pos, Move searchMoves[]) {
611 SearchStack ss[PLY_MAX_PLUS_2];
613 // searchMoves are verified, copied, scored and sorted
614 RootMoveList rml(p, searchMoves);
616 // Handle special case of searching on a mate/stale position
617 if (rml.move_count() == 0)
620 wait_for_stop_or_ponderhit();
622 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
625 // Print RootMoveList c'tor startup scoring to the standard output,
626 // so that we print information also for iteration 1.
627 cout << "info depth " << 1 << "\ninfo depth " << 1
628 << " score " << value_to_string(rml.get_move_score(0))
629 << " time " << current_search_time()
630 << " nodes " << TM.nodes_searched()
632 << " pv " << rml.get_move(0) << "\n";
638 ValueByIteration[1] = rml.get_move_score(0);
641 // Is one move significantly better than others after initial scoring ?
642 Move EasyMove = MOVE_NONE;
643 if ( rml.move_count() == 1
644 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
645 EasyMove = rml.get_move(0);
647 // Iterative deepening loop
648 while (Iteration < PLY_MAX)
650 // Initialize iteration
653 BestMoveChangesByIteration[Iteration] = 0;
657 cout << "info depth " << Iteration << endl;
659 // Calculate dynamic search window based on previous iterations
662 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
664 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
665 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
667 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
668 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
670 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
671 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
675 alpha = - VALUE_INFINITE;
676 beta = VALUE_INFINITE;
679 // Search to the current depth
680 Value value = root_search(p, ss, rml, alpha, beta);
682 // Write PV to transposition table, in case the relevant entries have
683 // been overwritten during the search.
684 TT.insert_pv(p, ss[0].pv);
687 break; // Value cannot be trusted. Break out immediately!
689 //Save info about search result
690 ValueByIteration[Iteration] = value;
692 // Drop the easy move if it differs from the new best move
693 if (ss[0].pv[0] != EasyMove)
694 EasyMove = MOVE_NONE;
696 if (UseTimeManagement)
699 bool stopSearch = false;
701 // Stop search early if there is only a single legal move,
702 // we search up to Iteration 6 anyway to get a proper score.
703 if (Iteration >= 6 && rml.move_count() == 1)
706 // Stop search early when the last two iterations returned a mate score
708 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
709 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
712 // Stop search early if one move seems to be much better than the rest
713 int64_t nodes = TM.nodes_searched();
715 && EasyMove == ss[0].pv[0]
716 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
717 && current_search_time() > MaxSearchTime / 16)
718 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
719 && current_search_time() > MaxSearchTime / 32)))
722 // Add some extra time if the best move has changed during the last two iterations
723 if (Iteration > 5 && Iteration <= 50)
724 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
725 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
727 // Stop search if most of MaxSearchTime is consumed at the end of the
728 // iteration. We probably don't have enough time to search the first
729 // move at the next iteration anyway.
730 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
738 StopOnPonderhit = true;
742 if (MaxDepth && Iteration >= MaxDepth)
748 // If we are pondering or in infinite search, we shouldn't print the
749 // best move before we are told to do so.
750 if (!AbortSearch && (PonderSearch || InfiniteSearch))
751 wait_for_stop_or_ponderhit();
753 // Print final search statistics
754 cout << "info nodes " << TM.nodes_searched()
756 << " time " << current_search_time()
757 << " hashfull " << TT.full() << endl;
759 // Print the best move and the ponder move to the standard output
760 if (ss[0].pv[0] == MOVE_NONE)
762 ss[0].pv[0] = rml.get_move(0);
763 ss[0].pv[1] = MOVE_NONE;
765 cout << "bestmove " << ss[0].pv[0];
766 if (ss[0].pv[1] != MOVE_NONE)
767 cout << " ponder " << ss[0].pv[1];
774 dbg_print_mean(LogFile);
776 if (dbg_show_hit_rate)
777 dbg_print_hit_rate(LogFile);
779 LogFile << "\nNodes: " << TM.nodes_searched()
780 << "\nNodes/second: " << nps()
781 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
784 p.do_move(ss[0].pv[0], st);
785 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
787 return rml.get_move_score(0);
791 // root_search() is the function which searches the root node. It is
792 // similar to search_pv except that it uses a different move ordering
793 // scheme and prints some information to the standard output.
795 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
800 Depth depth, ext, newDepth;
803 int researchCount = 0;
804 bool moveIsCheck, captureOrPromotion, dangerous;
805 Value alpha = oldAlpha;
806 bool isCheck = pos.is_check();
808 // Evaluate the position statically
810 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
812 while (1) // Fail low loop
815 // Loop through all the moves in the root move list
816 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
820 // We failed high, invalidate and skip next moves, leave node-counters
821 // and beta-counters as they are and quickly return, we will try to do
822 // a research at the next iteration with a bigger aspiration window.
823 rml.set_move_score(i, -VALUE_INFINITE);
827 RootMoveNumber = i + 1;
829 // Save the current node count before the move is searched
830 nodes = TM.nodes_searched();
832 // Reset beta cut-off counters
833 TM.resetBetaCounters();
835 // Pick the next root move, and print the move and the move number to
836 // the standard output.
837 move = ss[0].currentMove = rml.get_move(i);
839 if (current_search_time() >= 1000)
840 cout << "info currmove " << move
841 << " currmovenumber " << RootMoveNumber << endl;
843 // Decide search depth for this move
844 moveIsCheck = pos.move_is_check(move);
845 captureOrPromotion = pos.move_is_capture_or_promotion(move);
846 depth = (Iteration - 2) * OnePly + InitialDepth;
847 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
848 newDepth = depth + ext;
850 value = - VALUE_INFINITE;
852 while (1) // Fail high loop
855 // Make the move, and search it
856 pos.do_move(move, st, ci, moveIsCheck);
858 if (i < MultiPV || value > alpha)
860 // Aspiration window is disabled in multi-pv case
862 alpha = -VALUE_INFINITE;
864 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
868 // Try to reduce non-pv search depth by one ply if move seems not problematic,
869 // if the move fails high will be re-searched at full depth.
870 bool doFullDepthSearch = true;
872 if ( depth >= 3*OnePly // FIXME was newDepth
874 && !captureOrPromotion
875 && !move_is_castle(move))
877 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
880 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
881 doFullDepthSearch = (value > alpha);
885 if (doFullDepthSearch)
887 ss[0].reduction = Depth(0);
888 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
891 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
897 // Can we exit fail high loop ?
898 if (AbortSearch || value < beta)
901 // We are failing high and going to do a research. It's important to update score
902 // before research in case we run out of time while researching.
903 rml.set_move_score(i, value);
905 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
906 rml.set_move_pv(i, ss[0].pv);
908 // Print search information to the standard output
909 cout << "info depth " << Iteration
910 << " score " << value_to_string(value)
911 << ((value >= beta) ? " lowerbound" :
912 ((value <= alpha)? " upperbound" : ""))
913 << " time " << current_search_time()
914 << " nodes " << TM.nodes_searched()
918 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
919 cout << ss[0].pv[j] << " ";
925 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
926 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
928 LogFile << pretty_pv(pos, current_search_time(), Iteration,
929 TM.nodes_searched(), value, type, ss[0].pv) << endl;
932 // Prepare for a research after a fail high, each time with a wider window
934 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
936 } // End of fail high loop
938 // Finished searching the move. If AbortSearch is true, the search
939 // was aborted because the user interrupted the search or because we
940 // ran out of time. In this case, the return value of the search cannot
941 // be trusted, and we break out of the loop without updating the best
946 // Remember beta-cutoff and searched nodes counts for this move. The
947 // info is used to sort the root moves at the next iteration.
949 TM.get_beta_counters(pos.side_to_move(), our, their);
950 rml.set_beta_counters(i, our, their);
951 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
953 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
955 if (value <= alpha && i >= MultiPV)
956 rml.set_move_score(i, -VALUE_INFINITE);
959 // PV move or new best move!
962 rml.set_move_score(i, value);
964 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
965 rml.set_move_pv(i, ss[0].pv);
969 // We record how often the best move has been changed in each
970 // iteration. This information is used for time managment: When
971 // the best move changes frequently, we allocate some more time.
973 BestMoveChangesByIteration[Iteration]++;
975 // Print search information to the standard output
976 cout << "info depth " << Iteration
977 << " score " << value_to_string(value)
978 << ((value >= beta) ? " lowerbound" :
979 ((value <= alpha)? " upperbound" : ""))
980 << " time " << current_search_time()
981 << " nodes " << TM.nodes_searched()
985 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
986 cout << ss[0].pv[j] << " ";
992 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
993 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
995 LogFile << pretty_pv(pos, current_search_time(), Iteration,
996 TM.nodes_searched(), value, type, ss[0].pv) << endl;
1003 rml.sort_multipv(i);
1004 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1006 cout << "info multipv " << j + 1
1007 << " score " << value_to_string(rml.get_move_score(j))
1008 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1009 << " time " << current_search_time()
1010 << " nodes " << TM.nodes_searched()
1014 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1015 cout << rml.get_move_pv(j, k) << " ";
1019 alpha = rml.get_move_score(Min(i, MultiPV-1));
1021 } // PV move or new best move
1023 assert(alpha >= oldAlpha);
1025 AspirationFailLow = (alpha == oldAlpha);
1027 if (AspirationFailLow && StopOnPonderhit)
1028 StopOnPonderhit = false;
1031 // Can we exit fail low loop ?
1032 if (AbortSearch || alpha > oldAlpha)
1035 // Prepare for a research after a fail low, each time with a wider window
1037 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1046 // search_pv() is the main search function for PV nodes.
1048 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1049 Depth depth, int ply, int threadID) {
1051 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1052 assert(beta > alpha && beta <= VALUE_INFINITE);
1053 assert(ply >= 0 && ply < PLY_MAX);
1054 assert(threadID >= 0 && threadID < TM.active_threads());
1056 Move movesSearched[256];
1061 Depth ext, newDepth;
1062 Value bestValue, value, oldAlpha;
1063 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1064 bool mateThreat = false;
1066 bestValue = value = -VALUE_INFINITE;
1069 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1071 // Step 1. Initialize node and poll
1072 // Polling can abort search.
1073 init_node(ss, ply, threadID);
1075 // Step 2. Check for aborted search and immediate draw
1076 if (AbortSearch || TM.thread_should_stop(threadID))
1079 if (pos.is_draw() || ply >= PLY_MAX - 1)
1082 // Step 3. Mate distance pruning
1084 alpha = Max(value_mated_in(ply), alpha);
1085 beta = Min(value_mate_in(ply+1), beta);
1089 // Step 4. Transposition table lookup
1090 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1091 // This is to avoid problems in the following areas:
1093 // * Repetition draw detection
1094 // * Fifty move rule detection
1095 // * Searching for a mate
1096 // * Printing of full PV line
1097 tte = TT.retrieve(pos.get_key());
1098 ttMove = (tte ? tte->move() : MOVE_NONE);
1100 // Step 5. Evaluate the position statically
1101 // At PV nodes we do this only to update gain statistics
1102 isCheck = pos.is_check();
1105 ss[ply].eval = evaluate(pos, ei, threadID);
1106 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1109 // Step 6. Razoring (is omitted in PV nodes)
1110 // Step 7. Static null move pruning (is omitted in PV nodes)
1111 // Step 8. Null move search with verification search (is omitted in PV nodes)
1113 // Step 9. Internal iterative deepening
1114 if ( depth >= IIDDepthAtPVNodes
1115 && ttMove == MOVE_NONE)
1117 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1118 ttMove = ss[ply].pv[ply];
1119 tte = TT.retrieve(pos.get_key());
1122 // Step 10. Loop through moves
1123 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1125 // Initialize a MovePicker object for the current position
1126 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1127 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1130 while ( alpha < beta
1131 && (move = mp.get_next_move()) != MOVE_NONE
1132 && !TM.thread_should_stop(threadID))
1134 assert(move_is_ok(move));
1136 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1137 moveIsCheck = pos.move_is_check(move, ci);
1138 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1140 // Step 11. Decide the new search depth
1141 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1143 // Singular extension search. We extend the TT move if its value is much better than
1144 // its siblings. To verify this we do a reduced search on all the other moves but the
1145 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1146 if ( depth >= SingularExtensionDepthAtPVNodes
1148 && move == tte->move()
1150 && is_lower_bound(tte->type())
1151 && tte->depth() >= depth - 3 * OnePly)
1153 Value ttValue = value_from_tt(tte->value(), ply);
1155 if (abs(ttValue) < VALUE_KNOWN_WIN)
1157 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1159 if (excValue < ttValue - SingularExtensionMargin)
1164 newDepth = depth - OnePly + ext;
1166 // Update current move (this must be done after singular extension search)
1167 movesSearched[moveCount++] = ss[ply].currentMove = move;
1169 // Step 12. Futility pruning (is omitted in PV nodes)
1171 // Step 13. Make the move
1172 pos.do_move(move, st, ci, moveIsCheck);
1174 // Step extra. pv search (only in PV nodes)
1175 // The first move in list is the expected PV
1177 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1180 // Step 14. Reduced search
1181 // if the move fails high will be re-searched at full depth.
1182 bool doFullDepthSearch = true;
1184 if ( depth >= 3*OnePly
1186 && !captureOrPromotion
1187 && !move_is_castle(move)
1188 && !move_is_killer(move, ss[ply]))
1190 ss[ply].reduction = pv_reduction(depth, moveCount);
1191 if (ss[ply].reduction)
1193 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1194 doFullDepthSearch = (value > alpha);
1198 // Step 15. Full depth search
1199 if (doFullDepthSearch)
1201 ss[ply].reduction = Depth(0);
1202 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1204 // Step extra. pv search (only in PV nodes)
1205 if (value > alpha && value < beta)
1206 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1210 // Step 16. Undo move
1211 pos.undo_move(move);
1213 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1215 // Step 17. Check for new best move
1216 if (value > bestValue)
1223 if (value == value_mate_in(ply + 1))
1224 ss[ply].mateKiller = move;
1228 // Step 18. Check for split
1229 if ( TM.active_threads() > 1
1231 && depth >= MinimumSplitDepth
1233 && TM.available_thread_exists(threadID)
1235 && !TM.thread_should_stop(threadID)
1236 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1237 depth, &moveCount, &mp, threadID, true))
1241 // Step 19. Check for mate and stalemate
1242 // All legal moves have been searched and if there were
1243 // no legal moves, it must be mate or stalemate.
1245 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1247 // Step 20. Update tables
1248 // If the search is not aborted, update the transposition table,
1249 // history counters, and killer moves.
1250 if (AbortSearch || TM.thread_should_stop(threadID))
1253 if (bestValue <= oldAlpha)
1254 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1256 else if (bestValue >= beta)
1258 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1259 move = ss[ply].pv[ply];
1260 if (!pos.move_is_capture_or_promotion(move))
1262 update_history(pos, move, depth, movesSearched, moveCount);
1263 update_killers(move, ss[ply]);
1265 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1268 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1274 // search() is the search function for zero-width nodes.
1276 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1277 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1279 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1280 assert(ply >= 0 && ply < PLY_MAX);
1281 assert(threadID >= 0 && threadID < TM.active_threads());
1283 Move movesSearched[256];
1288 Depth ext, newDepth;
1289 Value bestValue, refinedValue, nullValue, value, futilityValueScaled;
1290 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1291 bool mateThreat = false;
1293 refinedValue = bestValue = value = -VALUE_INFINITE;
1296 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1298 // Step 1. Initialize node and poll
1299 // Polling can abort search.
1300 init_node(ss, ply, threadID);
1302 // Step 2. Check for aborted search and immediate draw
1303 if (AbortSearch || TM.thread_should_stop(threadID))
1306 if (pos.is_draw() || ply >= PLY_MAX - 1)
1309 // Step 3. Mate distance pruning
1310 if (value_mated_in(ply) >= beta)
1313 if (value_mate_in(ply + 1) < beta)
1316 // Step 4. Transposition table lookup
1318 // We don't want the score of a partial search to overwrite a previous full search
1319 // TT value, so we use a different position key in case of an excluded move exists.
1320 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1322 tte = TT.retrieve(posKey);
1323 ttMove = (tte ? tte->move() : MOVE_NONE);
1325 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1327 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1328 return value_from_tt(tte->value(), ply);
1331 // Step 5. Evaluate the position statically
1332 isCheck = pos.is_check();
1336 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1337 ss[ply].eval = value_from_tt(tte->value(), ply);
1339 ss[ply].eval = evaluate(pos, ei, threadID);
1341 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1342 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1346 if ( !value_is_mate(beta)
1348 && depth < RazorDepth
1349 && refinedValue < beta - razor_margin(depth)
1350 && ss[ply - 1].currentMove != MOVE_NULL
1351 && ttMove == MOVE_NONE
1352 && !pos.has_pawn_on_7th(pos.side_to_move()))
1354 Value rbeta = beta - razor_margin(depth);
1355 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1357 return v; //FIXME: Logically should be: return (v + razor_margin(depth));
1360 // Step 7. Static null move pruning
1361 // We're betting that the opponent doesn't have a move that will reduce
1362 // the score by more than fuility_margin(depth) if we do a null move.
1365 && depth < RazorDepth
1366 && refinedValue - futility_margin(depth, 0) >= beta)
1367 return refinedValue - futility_margin(depth, 0);
1369 // Step 8. Null move search with verification search
1370 // When we jump directly to qsearch() we do a null move only if static value is
1371 // at least beta. Otherwise we do a null move if static value is not more than
1372 // NullMoveMargin under beta.
1376 && !value_is_mate(beta)
1377 && ok_to_do_nullmove(pos)
1378 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1380 ss[ply].currentMove = MOVE_NULL;
1382 pos.do_null_move(st);
1384 // Null move dynamic reduction based on depth
1385 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1387 // Null move dynamic reduction based on value
1388 if (refinedValue - beta > PawnValueMidgame)
1391 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1393 pos.undo_null_move();
1395 if (nullValue >= beta)
1397 if (depth < 6 * OnePly)
1400 // Do zugzwang verification search
1401 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1405 // The null move failed low, which means that we may be faced with
1406 // some kind of threat. If the previous move was reduced, check if
1407 // the move that refuted the null move was somehow connected to the
1408 // move which was reduced. If a connection is found, return a fail
1409 // low score (which will cause the reduced move to fail high in the
1410 // parent node, which will trigger a re-search with full depth).
1411 if (nullValue == value_mated_in(ply + 2))
1414 ss[ply].threatMove = ss[ply + 1].currentMove;
1415 if ( depth < ThreatDepth
1416 && ss[ply - 1].reduction
1417 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1422 // Step 9. Internal iterative deepening
1423 if ( depth >= IIDDepthAtNonPVNodes
1424 && ttMove == MOVE_NONE
1426 && ss[ply].eval >= beta - IIDMargin)
1428 search(pos, ss, beta, depth/2, ply, false, threadID);
1429 ttMove = ss[ply].pv[ply];
1430 tte = TT.retrieve(posKey);
1433 // Step 10. Loop through moves
1434 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1436 // Initialize a MovePicker object for the current position
1437 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1440 while ( bestValue < beta
1441 && (move = mp.get_next_move()) != MOVE_NONE
1442 && !TM.thread_should_stop(threadID))
1444 assert(move_is_ok(move));
1446 if (move == excludedMove)
1449 moveIsCheck = pos.move_is_check(move, ci);
1450 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1451 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1453 // Step 11. Decide the new search depth
1454 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1456 // Singular extension search. We extend the TT move if its value is much better than
1457 // its siblings. To verify this we do a reduced search on all the other moves but the
1458 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1459 if ( depth >= SingularExtensionDepthAtNonPVNodes
1461 && move == tte->move()
1462 && !excludedMove // Do not allow recursive single-reply search
1464 && is_lower_bound(tte->type())
1465 && tte->depth() >= depth - 3 * OnePly)
1467 Value ttValue = value_from_tt(tte->value(), ply);
1469 if (abs(ttValue) < VALUE_KNOWN_WIN)
1471 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1473 if (excValue < ttValue - SingularExtensionMargin)
1478 newDepth = depth - OnePly + ext;
1480 // Update current move (this must be done after singular extension search)
1481 movesSearched[moveCount++] = ss[ply].currentMove = move;
1483 // Step 12. Futility pruning
1486 && !captureOrPromotion
1487 && !move_is_castle(move)
1490 // Move count based pruning
1491 if ( moveCount >= futility_move_count(depth)
1492 && ok_to_prune(pos, move, ss[ply].threatMove)
1493 && bestValue > value_mated_in(PLY_MAX))
1496 // Value based pruning
1497 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); // We illogically ignore reduction condition depth >= 3*OnePly
1498 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1499 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1501 if (futilityValueScaled < beta)
1503 if (futilityValueScaled > bestValue)
1504 bestValue = futilityValueScaled;
1509 // Step 13. Make the move
1510 pos.do_move(move, st, ci, moveIsCheck);
1512 // Step 14. Reduced search
1513 // if the move fails high will be re-searched at full depth.
1514 bool doFullDepthSearch = true;
1516 if ( depth >= 3*OnePly
1518 && !captureOrPromotion
1519 && !move_is_castle(move)
1520 && !move_is_killer(move, ss[ply]))
1522 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1523 if (ss[ply].reduction)
1525 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1526 doFullDepthSearch = (value >= beta);
1530 // Step 15. Full depth search
1531 if (doFullDepthSearch)
1533 ss[ply].reduction = Depth(0);
1534 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1537 // Step 16. Undo move
1538 pos.undo_move(move);
1540 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1542 // Step 17. Check for new best move
1543 if (value > bestValue)
1549 if (value == value_mate_in(ply + 1))
1550 ss[ply].mateKiller = move;
1553 // Step 18. Check for split
1554 if ( TM.active_threads() > 1
1556 && depth >= MinimumSplitDepth
1558 && TM.available_thread_exists(threadID)
1560 && !TM.thread_should_stop(threadID)
1561 && TM.split(pos, ss, ply, NULL, beta, &bestValue,
1562 depth, &moveCount, &mp, threadID, false))
1566 // Step 19. Check for mate and stalemate
1567 // All legal moves have been searched and if there were
1568 // no legal moves, it must be mate or stalemate.
1569 // If one move was excluded return fail low.
1571 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1573 // Step 20. Update tables
1574 // If the search is not aborted, update the transposition table,
1575 // history counters, and killer moves.
1576 if (AbortSearch || TM.thread_should_stop(threadID))
1579 if (bestValue < beta)
1580 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1583 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1584 move = ss[ply].pv[ply];
1585 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1586 if (!pos.move_is_capture_or_promotion(move))
1588 update_history(pos, move, depth, movesSearched, moveCount);
1589 update_killers(move, ss[ply]);
1594 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1600 // qsearch() is the quiescence search function, which is called by the main
1601 // search function when the remaining depth is zero (or, to be more precise,
1602 // less than OnePly).
1604 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1605 Depth depth, int ply, int threadID) {
1607 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1608 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1610 assert(ply >= 0 && ply < PLY_MAX);
1611 assert(threadID >= 0 && threadID < TM.active_threads());
1616 Value staticValue, bestValue, value, futilityBase, futilityValue;
1617 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1618 const TTEntry* tte = NULL;
1620 bool pvNode = (beta - alpha != 1);
1621 Value oldAlpha = alpha;
1623 // Initialize, and make an early exit in case of an aborted search,
1624 // an instant draw, maximum ply reached, etc.
1625 init_node(ss, ply, threadID);
1627 // After init_node() that calls poll()
1628 if (AbortSearch || TM.thread_should_stop(threadID))
1631 if (pos.is_draw() || ply >= PLY_MAX - 1)
1634 // Transposition table lookup. At PV nodes, we don't use the TT for
1635 // pruning, but only for move ordering.
1636 tte = TT.retrieve(pos.get_key());
1637 ttMove = (tte ? tte->move() : MOVE_NONE);
1639 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1641 assert(tte->type() != VALUE_TYPE_EVAL);
1643 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1644 return value_from_tt(tte->value(), ply);
1647 isCheck = pos.is_check();
1649 // Evaluate the position statically
1651 staticValue = -VALUE_INFINITE;
1652 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1653 staticValue = value_from_tt(tte->value(), ply);
1655 staticValue = evaluate(pos, ei, threadID);
1659 ss[ply].eval = staticValue;
1660 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1663 // Initialize "stand pat score", and return it immediately if it is
1665 bestValue = staticValue;
1667 if (bestValue >= beta)
1669 // Store the score to avoid a future costly evaluation() call
1670 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1671 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1676 if (bestValue > alpha)
1679 // If we are near beta then try to get a cutoff pushing checks a bit further
1680 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1682 // Initialize a MovePicker object for the current position, and prepare
1683 // to search the moves. Because the depth is <= 0 here, only captures,
1684 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1685 // and we are near beta) will be generated.
1686 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1688 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1689 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1691 // Loop through the moves until no moves remain or a beta cutoff
1693 while ( alpha < beta
1694 && (move = mp.get_next_move()) != MOVE_NONE)
1696 assert(move_is_ok(move));
1698 moveIsCheck = pos.move_is_check(move, ci);
1700 // Update current move
1702 ss[ply].currentMove = move;
1710 && !move_is_promotion(move)
1711 && !pos.move_is_passed_pawn_push(move))
1713 futilityValue = futilityBase
1714 + pos.endgame_value_of_piece_on(move_to(move))
1715 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1717 if (futilityValue < alpha)
1719 if (futilityValue > bestValue)
1720 bestValue = futilityValue;
1725 // Detect blocking evasions that are candidate to be pruned
1726 evasionPrunable = isCheck
1727 && bestValue != -VALUE_INFINITE
1728 && !pos.move_is_capture(move)
1729 && pos.type_of_piece_on(move_from(move)) != KING
1730 && !pos.can_castle(pos.side_to_move());
1732 // Don't search moves with negative SEE values
1733 if ( (!isCheck || evasionPrunable)
1736 && !move_is_promotion(move)
1737 && pos.see_sign(move) < 0)
1740 // Make and search the move
1741 pos.do_move(move, st, ci, moveIsCheck);
1742 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1743 pos.undo_move(move);
1745 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1748 if (value > bestValue)
1759 // All legal moves have been searched. A special case: If we're in check
1760 // and no legal moves were found, it is checkmate.
1761 if (!moveCount && pos.is_check()) // Mate!
1762 return value_mated_in(ply);
1764 // Update transposition table
1765 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1766 if (bestValue <= oldAlpha)
1768 // If bestValue isn't changed it means it is still the static evaluation
1769 // of the node, so keep this info to avoid a future evaluation() call.
1770 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1771 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1773 else if (bestValue >= beta)
1775 move = ss[ply].pv[ply];
1776 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1778 // Update killers only for good checking moves
1779 if (!pos.move_is_capture_or_promotion(move))
1780 update_killers(move, ss[ply]);
1783 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1785 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1791 // sp_search() is used to search from a split point. This function is called
1792 // by each thread working at the split point. It is similar to the normal
1793 // search() function, but simpler. Because we have already probed the hash
1794 // table, done a null move search, and searched the first move before
1795 // splitting, we don't have to repeat all this work in sp_search(). We
1796 // also don't need to store anything to the hash table here: This is taken
1797 // care of after we return from the split point.
1798 // FIXME: We are currently ignoring mateThreat flag here
1800 void sp_search(SplitPoint* sp, int threadID) {
1802 assert(threadID >= 0 && threadID < TM.active_threads());
1803 assert(TM.active_threads() > 1);
1807 Depth ext, newDepth;
1808 Value value, futilityValueScaled;
1809 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1811 value = -VALUE_INFINITE;
1813 Position pos(*sp->pos);
1815 SearchStack* ss = sp->sstack[threadID];
1816 isCheck = pos.is_check();
1818 // Step 10. Loop through moves
1819 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1820 lock_grab(&(sp->lock));
1822 while ( sp->bestValue < sp->beta
1823 && !TM.thread_should_stop(threadID)
1824 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1826 moveCount = ++sp->moves;
1827 lock_release(&(sp->lock));
1829 assert(move_is_ok(move));
1831 moveIsCheck = pos.move_is_check(move, ci);
1832 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1834 // Step 11. Decide the new search depth
1835 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1836 newDepth = sp->depth - OnePly + ext;
1838 // Update current move
1839 ss[sp->ply].currentMove = move;
1841 // Step 12. Futility pruning
1844 && !captureOrPromotion
1845 && !move_is_castle(move))
1847 // Move count based pruning
1848 if ( moveCount >= futility_move_count(sp->depth)
1849 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1850 && sp->bestValue > value_mated_in(PLY_MAX))
1852 lock_grab(&(sp->lock));
1856 // Value based pruning
1857 Depth predictedDepth = newDepth - nonpv_reduction(sp->depth, moveCount);
1858 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1859 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1861 if (futilityValueScaled < sp->beta)
1863 lock_grab(&(sp->lock));
1865 if (futilityValueScaled > sp->bestValue)
1866 sp->bestValue = futilityValueScaled;
1871 // Step 13. Make the move
1872 pos.do_move(move, st, ci, moveIsCheck);
1874 // Step 14. Reduced search
1875 // if the move fails high will be re-searched at full depth.
1876 bool doFullDepthSearch = true;
1879 && !captureOrPromotion
1880 && !move_is_castle(move)
1881 && !move_is_killer(move, ss[sp->ply]))
1883 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1884 if (ss[sp->ply].reduction)
1886 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1887 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1891 // Step 15. Full depth search
1892 if (doFullDepthSearch)
1894 ss[sp->ply].reduction = Depth(0);
1895 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1898 // Step 16. Undo move
1899 pos.undo_move(move);
1901 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1903 // Step 17. Check for new best move
1904 lock_grab(&(sp->lock));
1906 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1908 sp->bestValue = value;
1909 if (sp->bestValue >= sp->beta)
1911 sp->stopRequest = true;
1912 sp_update_pv(sp->parentSstack, ss, sp->ply);
1917 /* Here we have the lock still grabbed */
1919 sp->slaves[threadID] = 0;
1922 lock_release(&(sp->lock));
1926 // sp_search_pv() is used to search from a PV split point. This function
1927 // is called by each thread working at the split point. It is similar to
1928 // the normal search_pv() function, but simpler. Because we have already
1929 // probed the hash table and searched the first move before splitting, we
1930 // don't have to repeat all this work in sp_search_pv(). We also don't
1931 // need to store anything to the hash table here: This is taken care of
1932 // after we return from the split point.
1933 // FIXME: We are ignoring mateThreat flag!
1935 void sp_search_pv(SplitPoint* sp, int threadID) {
1937 assert(threadID >= 0 && threadID < TM.active_threads());
1938 assert(TM.active_threads() > 1);
1942 Depth ext, newDepth;
1944 bool moveIsCheck, captureOrPromotion, dangerous;
1946 value = -VALUE_INFINITE;
1948 Position pos(*sp->pos);
1950 SearchStack* ss = sp->sstack[threadID];
1952 // Step 10. Loop through moves
1953 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1954 lock_grab(&(sp->lock));
1956 while ( sp->alpha < sp->beta
1957 && !TM.thread_should_stop(threadID)
1958 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1960 moveCount = ++sp->moves;
1961 lock_release(&(sp->lock));
1963 assert(move_is_ok(move));
1965 moveIsCheck = pos.move_is_check(move, ci);
1966 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1968 // Step 11. Decide the new search depth
1969 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1970 newDepth = sp->depth - OnePly + ext;
1972 // Update current move
1973 ss[sp->ply].currentMove = move;
1975 // Step 12. Futility pruning (is omitted in PV nodes)
1977 // Step 13. Make the move
1978 pos.do_move(move, st, ci, moveIsCheck);
1980 // Step 14. Reduced search
1981 // if the move fails high will be re-searched at full depth.
1982 bool doFullDepthSearch = true;
1985 && !captureOrPromotion
1986 && !move_is_castle(move)
1987 && !move_is_killer(move, ss[sp->ply]))
1989 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
1990 if (ss[sp->ply].reduction)
1992 Value localAlpha = sp->alpha;
1993 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1994 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
1998 // Step 15. Full depth search
1999 if (doFullDepthSearch)
2001 Value localAlpha = sp->alpha;
2002 ss[sp->ply].reduction = Depth(0);
2003 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2005 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
2007 // If another thread has failed high then sp->alpha has been increased
2008 // to be higher or equal then beta, if so, avoid to start a PV search.
2009 localAlpha = sp->alpha;
2010 if (localAlpha < sp->beta)
2011 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2015 // Step 16. Undo move
2016 pos.undo_move(move);
2018 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2020 // Step 17. Check for new best move
2021 lock_grab(&(sp->lock));
2023 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
2025 sp->bestValue = value;
2026 if (value > sp->alpha)
2028 // Ask threads to stop before to modify sp->alpha
2029 if (value >= sp->beta)
2030 sp->stopRequest = true;
2034 sp_update_pv(sp->parentSstack, ss, sp->ply);
2035 if (value == value_mate_in(sp->ply + 1))
2036 ss[sp->ply].mateKiller = move;
2041 /* Here we have the lock still grabbed */
2043 sp->slaves[threadID] = 0;
2046 lock_release(&(sp->lock));
2050 // init_node() is called at the beginning of all the search functions
2051 // (search(), search_pv(), qsearch(), and so on) and initializes the
2052 // search stack object corresponding to the current node. Once every
2053 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2054 // for user input and checks whether it is time to stop the search.
2056 void init_node(SearchStack ss[], int ply, int threadID) {
2058 assert(ply >= 0 && ply < PLY_MAX);
2059 assert(threadID >= 0 && threadID < TM.active_threads());
2061 TM.incrementNodeCounter(threadID);
2066 if (NodesSincePoll >= NodesBetweenPolls)
2073 ss[ply + 2].initKillers();
2077 // update_pv() is called whenever a search returns a value > alpha.
2078 // It updates the PV in the SearchStack object corresponding to the
2081 void update_pv(SearchStack ss[], int ply) {
2083 assert(ply >= 0 && ply < PLY_MAX);
2087 ss[ply].pv[ply] = ss[ply].currentMove;
2089 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2090 ss[ply].pv[p] = ss[ply + 1].pv[p];
2092 ss[ply].pv[p] = MOVE_NONE;
2096 // sp_update_pv() is a variant of update_pv for use at split points. The
2097 // difference between the two functions is that sp_update_pv also updates
2098 // the PV at the parent node.
2100 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2102 assert(ply >= 0 && ply < PLY_MAX);
2106 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2108 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2109 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2111 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2115 // connected_moves() tests whether two moves are 'connected' in the sense
2116 // that the first move somehow made the second move possible (for instance
2117 // if the moving piece is the same in both moves). The first move is assumed
2118 // to be the move that was made to reach the current position, while the
2119 // second move is assumed to be a move from the current position.
2121 bool connected_moves(const Position& pos, Move m1, Move m2) {
2123 Square f1, t1, f2, t2;
2126 assert(move_is_ok(m1));
2127 assert(move_is_ok(m2));
2129 if (m2 == MOVE_NONE)
2132 // Case 1: The moving piece is the same in both moves
2138 // Case 2: The destination square for m2 was vacated by m1
2144 // Case 3: Moving through the vacated square
2145 if ( piece_is_slider(pos.piece_on(f2))
2146 && bit_is_set(squares_between(f2, t2), f1))
2149 // Case 4: The destination square for m2 is defended by the moving piece in m1
2150 p = pos.piece_on(t1);
2151 if (bit_is_set(pos.attacks_from(p, t1), t2))
2154 // Case 5: Discovered check, checking piece is the piece moved in m1
2155 if ( piece_is_slider(p)
2156 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2157 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2159 // discovered_check_candidates() works also if the Position's side to
2160 // move is the opposite of the checking piece.
2161 Color them = opposite_color(pos.side_to_move());
2162 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2164 if (bit_is_set(dcCandidates, f2))
2171 // value_is_mate() checks if the given value is a mate one
2172 // eventually compensated for the ply.
2174 bool value_is_mate(Value value) {
2176 assert(abs(value) <= VALUE_INFINITE);
2178 return value <= value_mated_in(PLY_MAX)
2179 || value >= value_mate_in(PLY_MAX);
2183 // move_is_killer() checks if the given move is among the
2184 // killer moves of that ply.
2186 bool move_is_killer(Move m, const SearchStack& ss) {
2188 const Move* k = ss.killers;
2189 for (int i = 0; i < KILLER_MAX; i++, k++)
2197 // extension() decides whether a move should be searched with normal depth,
2198 // or with extended depth. Certain classes of moves (checking moves, in
2199 // particular) are searched with bigger depth than ordinary moves and in
2200 // any case are marked as 'dangerous'. Note that also if a move is not
2201 // extended, as example because the corresponding UCI option is set to zero,
2202 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2204 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2205 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2207 assert(m != MOVE_NONE);
2209 Depth result = Depth(0);
2210 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2215 result += CheckExtension[pvNode];
2218 result += SingleEvasionExtension[pvNode];
2221 result += MateThreatExtension[pvNode];
2224 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2226 Color c = pos.side_to_move();
2227 if (relative_rank(c, move_to(m)) == RANK_7)
2229 result += PawnPushTo7thExtension[pvNode];
2232 if (pos.pawn_is_passed(c, move_to(m)))
2234 result += PassedPawnExtension[pvNode];
2239 if ( captureOrPromotion
2240 && pos.type_of_piece_on(move_to(m)) != PAWN
2241 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2242 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2243 && !move_is_promotion(m)
2246 result += PawnEndgameExtension[pvNode];
2251 && captureOrPromotion
2252 && pos.type_of_piece_on(move_to(m)) != PAWN
2253 && pos.see_sign(m) >= 0)
2259 return Min(result, OnePly);
2263 // ok_to_do_nullmove() looks at the current position and decides whether
2264 // doing a 'null move' should be allowed. In order to avoid zugzwang
2265 // problems, null moves are not allowed when the side to move has very
2266 // little material left. Currently, the test is a bit too simple: Null
2267 // moves are avoided only when the side to move has only pawns left.
2268 // It's probably a good idea to avoid null moves in at least some more
2269 // complicated endgames, e.g. KQ vs KR. FIXME
2271 bool ok_to_do_nullmove(const Position& pos) {
2273 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2277 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2278 // non-tactical moves late in the move list close to the leaves are
2279 // candidates for pruning.
2281 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2283 assert(move_is_ok(m));
2284 assert(threat == MOVE_NONE || move_is_ok(threat));
2285 assert(!pos.move_is_check(m));
2286 assert(!pos.move_is_capture_or_promotion(m));
2287 assert(!pos.move_is_passed_pawn_push(m));
2289 Square mfrom, mto, tfrom, tto;
2291 // Prune if there isn't any threat move
2292 if (threat == MOVE_NONE)
2295 mfrom = move_from(m);
2297 tfrom = move_from(threat);
2298 tto = move_to(threat);
2300 // Case 1: Don't prune moves which move the threatened piece
2304 // Case 2: If the threatened piece has value less than or equal to the
2305 // value of the threatening piece, don't prune move which defend it.
2306 if ( pos.move_is_capture(threat)
2307 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2308 || pos.type_of_piece_on(tfrom) == KING)
2309 && pos.move_attacks_square(m, tto))
2312 // Case 3: If the moving piece in the threatened move is a slider, don't
2313 // prune safe moves which block its ray.
2314 if ( piece_is_slider(pos.piece_on(tfrom))
2315 && bit_is_set(squares_between(tfrom, tto), mto)
2316 && pos.see_sign(m) >= 0)
2323 // ok_to_use_TT() returns true if a transposition table score
2324 // can be used at a given point in search.
2326 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2328 Value v = value_from_tt(tte->value(), ply);
2330 return ( tte->depth() >= depth
2331 || v >= Max(value_mate_in(PLY_MAX), beta)
2332 || v < Min(value_mated_in(PLY_MAX), beta))
2334 && ( (is_lower_bound(tte->type()) && v >= beta)
2335 || (is_upper_bound(tte->type()) && v < beta));
2339 // refine_eval() returns the transposition table score if
2340 // possible otherwise falls back on static position evaluation.
2342 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2347 Value v = value_from_tt(tte->value(), ply);
2349 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2350 || (is_upper_bound(tte->type()) && v < defaultEval))
2357 // update_history() registers a good move that produced a beta-cutoff
2358 // in history and marks as failures all the other moves of that ply.
2360 void update_history(const Position& pos, Move move, Depth depth,
2361 Move movesSearched[], int moveCount) {
2365 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2367 for (int i = 0; i < moveCount - 1; i++)
2369 m = movesSearched[i];
2373 if (!pos.move_is_capture_or_promotion(m))
2374 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2379 // update_killers() add a good move that produced a beta-cutoff
2380 // among the killer moves of that ply.
2382 void update_killers(Move m, SearchStack& ss) {
2384 if (m == ss.killers[0])
2387 for (int i = KILLER_MAX - 1; i > 0; i--)
2388 ss.killers[i] = ss.killers[i - 1];
2394 // update_gains() updates the gains table of a non-capture move given
2395 // the static position evaluation before and after the move.
2397 void update_gains(const Position& pos, Move m, Value before, Value after) {
2400 && before != VALUE_NONE
2401 && after != VALUE_NONE
2402 && pos.captured_piece() == NO_PIECE_TYPE
2403 && !move_is_castle(m)
2404 && !move_is_promotion(m))
2405 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2409 // current_search_time() returns the number of milliseconds which have passed
2410 // since the beginning of the current search.
2412 int current_search_time() {
2414 return get_system_time() - SearchStartTime;
2418 // nps() computes the current nodes/second count.
2422 int t = current_search_time();
2423 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2427 // poll() performs two different functions: It polls for user input, and it
2428 // looks at the time consumed so far and decides if it's time to abort the
2431 void poll(SearchStack ss[], int ply) {
2433 static int lastInfoTime;
2434 int t = current_search_time();
2439 // We are line oriented, don't read single chars
2440 std::string command;
2442 if (!std::getline(std::cin, command))
2445 if (command == "quit")
2448 PonderSearch = false;
2452 else if (command == "stop")
2455 PonderSearch = false;
2457 else if (command == "ponderhit")
2461 // Print search information
2465 else if (lastInfoTime > t)
2466 // HACK: Must be a new search where we searched less than
2467 // NodesBetweenPolls nodes during the first second of search.
2470 else if (t - lastInfoTime >= 1000)
2477 if (dbg_show_hit_rate)
2478 dbg_print_hit_rate();
2480 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2481 << " time " << t << " hashfull " << TT.full() << endl;
2483 // We only support current line printing in single thread mode
2484 if (ShowCurrentLine && TM.active_threads() == 1)
2486 cout << "info currline";
2487 for (int p = 0; p < ply; p++)
2488 cout << " " << ss[p].currentMove;
2494 // Should we stop the search?
2498 bool stillAtFirstMove = RootMoveNumber == 1
2499 && !AspirationFailLow
2500 && t > MaxSearchTime + ExtraSearchTime;
2502 bool noMoreTime = t > AbsoluteMaxSearchTime
2503 || stillAtFirstMove;
2505 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2506 || (ExactMaxTime && t >= ExactMaxTime)
2507 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2512 // ponderhit() is called when the program is pondering (i.e. thinking while
2513 // it's the opponent's turn to move) in order to let the engine know that
2514 // it correctly predicted the opponent's move.
2518 int t = current_search_time();
2519 PonderSearch = false;
2521 bool stillAtFirstMove = RootMoveNumber == 1
2522 && !AspirationFailLow
2523 && t > MaxSearchTime + ExtraSearchTime;
2525 bool noMoreTime = t > AbsoluteMaxSearchTime
2526 || stillAtFirstMove;
2528 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2533 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2535 void init_ss_array(SearchStack ss[]) {
2537 for (int i = 0; i < 3; i++)
2540 ss[i].initKillers();
2545 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2546 // while the program is pondering. The point is to work around a wrinkle in
2547 // the UCI protocol: When pondering, the engine is not allowed to give a
2548 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2549 // We simply wait here until one of these commands is sent, and return,
2550 // after which the bestmove and pondermove will be printed (in id_loop()).
2552 void wait_for_stop_or_ponderhit() {
2554 std::string command;
2558 if (!std::getline(std::cin, command))
2561 if (command == "quit")
2566 else if (command == "ponderhit" || command == "stop")
2572 // init_thread() is the function which is called when a new thread is
2573 // launched. It simply calls the idle_loop() function with the supplied
2574 // threadID. There are two versions of this function; one for POSIX
2575 // threads and one for Windows threads.
2577 #if !defined(_MSC_VER)
2579 void* init_thread(void *threadID) {
2581 TM.idle_loop(*(int*)threadID, NULL);
2587 DWORD WINAPI init_thread(LPVOID threadID) {
2589 TM.idle_loop(*(int*)threadID, NULL);
2596 /// The ThreadsManager class
2598 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2599 // get_beta_counters() are getters/setters for the per thread
2600 // counters used to sort the moves at root.
2602 void ThreadsManager::resetNodeCounters() {
2604 for (int i = 0; i < MAX_THREADS; i++)
2605 threads[i].nodes = 0ULL;
2608 void ThreadsManager::resetBetaCounters() {
2610 for (int i = 0; i < MAX_THREADS; i++)
2611 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2614 int64_t ThreadsManager::nodes_searched() const {
2616 int64_t result = 0ULL;
2617 for (int i = 0; i < ActiveThreads; i++)
2618 result += threads[i].nodes;
2623 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2626 for (int i = 0; i < MAX_THREADS; i++)
2628 our += threads[i].betaCutOffs[us];
2629 their += threads[i].betaCutOffs[opposite_color(us)];
2634 // idle_loop() is where the threads are parked when they have no work to do.
2635 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2636 // object for which the current thread is the master.
2638 void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2640 assert(threadID >= 0 && threadID < MAX_THREADS);
2644 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2645 // master should exit as last one.
2646 if (AllThreadsShouldExit)
2649 threads[threadID].state = THREAD_TERMINATED;
2653 // If we are not thinking, wait for a condition to be signaled
2654 // instead of wasting CPU time polling for work.
2655 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2658 assert(threadID != 0);
2659 threads[threadID].state = THREAD_SLEEPING;
2661 #if !defined(_MSC_VER)
2662 pthread_mutex_lock(&WaitLock);
2663 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2664 pthread_cond_wait(&WaitCond, &WaitLock);
2665 pthread_mutex_unlock(&WaitLock);
2667 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2671 // If thread has just woken up, mark it as available
2672 if (threads[threadID].state == THREAD_SLEEPING)
2673 threads[threadID].state = THREAD_AVAILABLE;
2675 // If this thread has been assigned work, launch a search
2676 if (threads[threadID].state == THREAD_WORKISWAITING)
2678 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2680 threads[threadID].state = THREAD_SEARCHING;
2682 if (threads[threadID].splitPoint->pvNode)
2683 sp_search_pv(threads[threadID].splitPoint, threadID);
2685 sp_search(threads[threadID].splitPoint, threadID);
2687 assert(threads[threadID].state == THREAD_SEARCHING);
2689 threads[threadID].state = THREAD_AVAILABLE;
2692 // If this thread is the master of a split point and all threads have
2693 // finished their work at this split point, return from the idle loop.
2694 if (waitSp != NULL && waitSp->cpus == 0)
2696 assert(threads[threadID].state == THREAD_AVAILABLE);
2698 threads[threadID].state = THREAD_SEARCHING;
2705 // init_threads() is called during startup. It launches all helper threads,
2706 // and initializes the split point stack and the global locks and condition
2709 void ThreadsManager::init_threads() {
2714 #if !defined(_MSC_VER)
2715 pthread_t pthread[1];
2718 // Initialize global locks
2719 lock_init(&MPLock, NULL);
2721 // Initialize SplitPointStack locks
2722 for (i = 0; i < MAX_THREADS; i++)
2723 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2725 SplitPointStack[i][j].parent = NULL;
2726 lock_init(&(SplitPointStack[i][j].lock), NULL);
2729 #if !defined(_MSC_VER)
2730 pthread_mutex_init(&WaitLock, NULL);
2731 pthread_cond_init(&WaitCond, NULL);
2733 for (i = 0; i < MAX_THREADS; i++)
2734 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2737 // Will be set just before program exits to properly end the threads
2738 AllThreadsShouldExit = false;
2740 // Threads will be put to sleep as soon as created
2741 AllThreadsShouldSleep = true;
2743 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2745 threads[0].state = THREAD_SEARCHING;
2746 for (i = 1; i < MAX_THREADS; i++)
2747 threads[i].state = THREAD_AVAILABLE;
2749 // Launch the helper threads
2750 for (i = 1; i < MAX_THREADS; i++)
2753 #if !defined(_MSC_VER)
2754 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2757 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
2762 cout << "Failed to create thread number " << i << endl;
2763 Application::exit_with_failure();
2766 // Wait until the thread has finished launching and is gone to sleep
2767 while (threads[i].state != THREAD_SLEEPING);
2772 // exit_threads() is called when the program exits. It makes all the
2773 // helper threads exit cleanly.
2775 void ThreadsManager::exit_threads() {
2777 ActiveThreads = MAX_THREADS; // HACK
2778 AllThreadsShouldSleep = true; // HACK
2779 wake_sleeping_threads();
2781 // This makes the threads to exit idle_loop()
2782 AllThreadsShouldExit = true;
2784 // Wait for thread termination
2785 for (int i = 1; i < MAX_THREADS; i++)
2786 while (threads[i].state != THREAD_TERMINATED);
2788 // Now we can safely destroy the locks
2789 for (int i = 0; i < MAX_THREADS; i++)
2790 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2791 lock_destroy(&(SplitPointStack[i][j].lock));
2795 // thread_should_stop() checks whether the thread should stop its search.
2796 // This can happen if a beta cutoff has occurred in the thread's currently
2797 // active split point, or in some ancestor of the current split point.
2799 bool ThreadsManager::thread_should_stop(int threadID) const {
2801 assert(threadID >= 0 && threadID < ActiveThreads);
2805 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent);
2810 // thread_is_available() checks whether the thread with threadID "slave" is
2811 // available to help the thread with threadID "master" at a split point. An
2812 // obvious requirement is that "slave" must be idle. With more than two
2813 // threads, this is not by itself sufficient: If "slave" is the master of
2814 // some active split point, it is only available as a slave to the other
2815 // threads which are busy searching the split point at the top of "slave"'s
2816 // split point stack (the "helpful master concept" in YBWC terminology).
2818 bool ThreadsManager::thread_is_available(int slave, int master) const {
2820 assert(slave >= 0 && slave < ActiveThreads);
2821 assert(master >= 0 && master < ActiveThreads);
2822 assert(ActiveThreads > 1);
2824 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2827 // Make a local copy to be sure doesn't change under our feet
2828 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2830 if (localActiveSplitPoints == 0)
2831 // No active split points means that the thread is available as
2832 // a slave for any other thread.
2835 if (ActiveThreads == 2)
2838 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2839 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2840 // could have been set to 0 by another thread leading to an out of bound access.
2841 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2848 // available_thread_exists() tries to find an idle thread which is available as
2849 // a slave for the thread with threadID "master".
2851 bool ThreadsManager::available_thread_exists(int master) const {
2853 assert(master >= 0 && master < ActiveThreads);
2854 assert(ActiveThreads > 1);
2856 for (int i = 0; i < ActiveThreads; i++)
2857 if (thread_is_available(i, master))
2864 // split() does the actual work of distributing the work at a node between
2865 // several threads at PV nodes. If it does not succeed in splitting the
2866 // node (because no idle threads are available, or because we have no unused
2867 // split point objects), the function immediately returns false. If
2868 // splitting is possible, a SplitPoint object is initialized with all the
2869 // data that must be copied to the helper threads (the current position and
2870 // search stack, alpha, beta, the search depth, etc.), and we tell our
2871 // helper threads that they have been assigned work. This will cause them
2872 // to instantly leave their idle loops and call sp_search_pv(). When all
2873 // threads have returned from sp_search_pv (or, equivalently, when
2874 // splitPoint->cpus becomes 0), split() returns true.
2876 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2877 Value* alpha, const Value beta, Value* bestValue,
2878 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2881 assert(sstck != NULL);
2882 assert(ply >= 0 && ply < PLY_MAX);
2883 assert(*bestValue >= -VALUE_INFINITE);
2884 assert( ( pvNode && *bestValue <= *alpha)
2885 || (!pvNode && *bestValue < beta ));
2886 assert(!pvNode || *alpha < beta);
2887 assert(beta <= VALUE_INFINITE);
2888 assert(depth > Depth(0));
2889 assert(master >= 0 && master < ActiveThreads);
2890 assert(ActiveThreads > 1);
2892 SplitPoint* splitPoint;
2896 // If no other thread is available to help us, or if we have too many
2897 // active split points, don't split.
2898 if ( !available_thread_exists(master)
2899 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2901 lock_release(&MPLock);
2905 // Pick the next available split point object from the split point stack
2906 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2908 // Initialize the split point object
2909 splitPoint->parent = threads[master].splitPoint;
2910 splitPoint->stopRequest = false;
2911 splitPoint->ply = ply;
2912 splitPoint->depth = depth;
2913 splitPoint->alpha = pvNode ? *alpha : beta - 1;
2914 splitPoint->beta = beta;
2915 splitPoint->pvNode = pvNode;
2916 splitPoint->bestValue = *bestValue;
2917 splitPoint->master = master;
2918 splitPoint->mp = mp;
2919 splitPoint->moves = *moves;
2920 splitPoint->cpus = 1;
2921 splitPoint->pos = &p;
2922 splitPoint->parentSstack = sstck;
2923 for (int i = 0; i < ActiveThreads; i++)
2924 splitPoint->slaves[i] = 0;
2926 threads[master].splitPoint = splitPoint;
2927 threads[master].activeSplitPoints++;
2929 // If we are here it means we are not available
2930 assert(threads[master].state != THREAD_AVAILABLE);
2932 // Allocate available threads setting state to THREAD_BOOKED
2933 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2934 if (thread_is_available(i, master))
2936 threads[i].state = THREAD_BOOKED;
2937 threads[i].splitPoint = splitPoint;
2938 splitPoint->slaves[i] = 1;
2942 assert(splitPoint->cpus > 1);
2944 // We can release the lock because slave threads are already booked and master is not available
2945 lock_release(&MPLock);
2947 // Tell the threads that they have work to do. This will make them leave
2948 // their idle loop. But before copy search stack tail for each thread.
2949 for (int i = 0; i < ActiveThreads; i++)
2950 if (i == master || splitPoint->slaves[i])
2952 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2954 assert(i == master || threads[i].state == THREAD_BOOKED);
2956 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2959 // Everything is set up. The master thread enters the idle loop, from
2960 // which it will instantly launch a search, because its state is
2961 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2962 // idle loop, which means that the main thread will return from the idle
2963 // loop when all threads have finished their work at this split point
2964 // (i.e. when splitPoint->cpus == 0).
2965 idle_loop(master, splitPoint);
2967 // We have returned from the idle loop, which means that all threads are
2968 // finished. Update alpha, beta and bestValue, and return.
2972 *alpha = splitPoint->alpha;
2974 *bestValue = splitPoint->bestValue;
2975 threads[master].activeSplitPoints--;
2976 threads[master].splitPoint = splitPoint->parent;
2978 lock_release(&MPLock);
2983 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2984 // to start a new search from the root.
2986 void ThreadsManager::wake_sleeping_threads() {
2988 assert(AllThreadsShouldSleep);
2989 assert(ActiveThreads > 0);
2991 AllThreadsShouldSleep = false;
2993 if (ActiveThreads == 1)
2996 for (int i = 1; i < ActiveThreads; i++)
2997 assert(threads[i].state == THREAD_SLEEPING);
2999 #if !defined(_MSC_VER)
3000 pthread_mutex_lock(&WaitLock);
3001 pthread_cond_broadcast(&WaitCond);
3002 pthread_mutex_unlock(&WaitLock);
3004 for (int i = 1; i < MAX_THREADS; i++)
3005 SetEvent(SitIdleEvent[i]);
3011 // put_threads_to_sleep() makes all the threads go to sleep just before
3012 // to leave think(), at the end of the search. Threads should have already
3013 // finished the job and should be idle.
3015 void ThreadsManager::put_threads_to_sleep() {
3017 assert(!AllThreadsShouldSleep);
3019 // This makes the threads to go to sleep
3020 AllThreadsShouldSleep = true;
3023 /// The RootMoveList class
3025 // RootMoveList c'tor
3027 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3029 SearchStack ss[PLY_MAX_PLUS_2];
3030 MoveStack mlist[MaxRootMoves];
3032 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3034 // Generate all legal moves
3035 MoveStack* last = generate_moves(pos, mlist);
3037 // Add each move to the moves[] array
3038 for (MoveStack* cur = mlist; cur != last; cur++)
3040 bool includeMove = includeAllMoves;
3042 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3043 includeMove = (searchMoves[k] == cur->move);
3048 // Find a quick score for the move
3050 pos.do_move(cur->move, st);
3051 moves[count].move = cur->move;
3052 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3053 moves[count].pv[0] = cur->move;
3054 moves[count].pv[1] = MOVE_NONE;
3055 pos.undo_move(cur->move);
3062 // RootMoveList simple methods definitions
3064 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3066 moves[moveNum].nodes = nodes;
3067 moves[moveNum].cumulativeNodes += nodes;
3070 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3072 moves[moveNum].ourBeta = our;
3073 moves[moveNum].theirBeta = their;
3076 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3080 for (j = 0; pv[j] != MOVE_NONE; j++)
3081 moves[moveNum].pv[j] = pv[j];
3083 moves[moveNum].pv[j] = MOVE_NONE;
3087 // RootMoveList::sort() sorts the root move list at the beginning of a new
3090 void RootMoveList::sort() {
3092 sort_multipv(count - 1); // Sort all items
3096 // RootMoveList::sort_multipv() sorts the first few moves in the root move
3097 // list by their scores and depths. It is used to order the different PVs
3098 // correctly in MultiPV mode.
3100 void RootMoveList::sort_multipv(int n) {
3104 for (i = 1; i <= n; i++)
3106 RootMove rm = moves[i];
3107 for (j = i; j > 0 && moves[j - 1] < rm; j--)
3108 moves[j] = moves[j - 1];