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];
163 // Search depth at iteration 1
164 const Depth InitialDepth = OnePly;
166 // Use internal iterative deepening?
167 const bool UseIIDAtPVNodes = true;
168 const bool UseIIDAtNonPVNodes = true;
170 // Internal iterative deepening margin. At Non-PV moves, when
171 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
172 // search when the static evaluation is at most IIDMargin below beta.
173 const Value IIDMargin = Value(0x100);
175 // Easy move margin. An easy move candidate must be at least this much
176 // better than the second best move.
177 const Value EasyMoveMargin = Value(0x200);
179 // Null move margin. A null move search will not be done if the static
180 // evaluation of the position is more than NullMoveMargin below beta.
181 const Value NullMoveMargin = Value(0x200);
183 // If the TT move is at least SingleReplyMargin better then the
184 // remaining ones we will extend it.
185 const Value SingleReplyMargin = Value(0x20);
187 // Depth limit for razoring
188 const Depth RazorDepth = 4 * OnePly;
190 /// Lookup tables initialized at startup
192 // Reduction lookup tables and their getter functions
193 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
194 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
196 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
197 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
199 // Futility lookup tables and their getter functions
200 const Value FutilityMarginQS = Value(0x80);
201 int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
202 int FutilityMoveCountArray[32]; // [depth]
204 inline Value futility_margin(Depth d, int mn) { return Value(d < 7*OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
205 inline int futility_move_count(Depth d) { return d < 16*OnePly ? FutilityMoveCountArray[d] : 512; }
207 /// Variables initialized by UCI options
209 // Depth limit for use of dynamic threat detection
212 // Last seconds noise filtering (LSN)
213 const bool UseLSNFiltering = true;
214 const int LSNTime = 4000; // In milliseconds
215 const Value LSNValue = value_from_centipawns(200);
216 bool loseOnTime = false;
218 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
219 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
220 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
222 // Iteration counters
225 // Scores and number of times the best move changed for each iteration
226 Value ValueByIteration[PLY_MAX_PLUS_2];
227 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
229 // Search window management
235 // Time managment variables
238 int MaxNodes, MaxDepth;
239 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
240 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
241 bool AbortSearch, Quit;
242 bool AspirationFailLow;
244 // Show current line?
245 bool ShowCurrentLine;
249 std::ofstream LogFile;
251 // MP related variables
252 Depth MinimumSplitDepth;
253 int MaxThreadsPerSplitPoint;
256 // Node counters, used only by thread[0] but try to keep in different
257 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
259 int NodesBetweenPolls = 30000;
266 Value id_loop(const Position& pos, Move searchMoves[]);
267 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
268 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
269 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
270 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
271 void sp_search(SplitPoint* sp, int threadID);
272 void sp_search_pv(SplitPoint* sp, int threadID);
273 void init_node(SearchStack ss[], int ply, int threadID);
274 void update_pv(SearchStack ss[], int ply);
275 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
276 bool connected_moves(const Position& pos, Move m1, Move m2);
277 bool value_is_mate(Value value);
278 bool move_is_killer(Move m, const SearchStack& ss);
279 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
280 bool ok_to_do_nullmove(const Position& pos);
281 bool ok_to_prune(const Position& pos, Move m, Move threat);
282 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
283 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
284 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
285 void update_killers(Move m, SearchStack& ss);
286 void update_gains(const Position& pos, Move move, Value before, Value after);
288 int current_search_time();
290 void poll(SearchStack ss[], int ply);
292 void wait_for_stop_or_ponderhit();
293 void init_ss_array(SearchStack ss[]);
295 #if !defined(_MSC_VER)
296 void *init_thread(void *threadID);
298 DWORD WINAPI init_thread(LPVOID threadID);
308 /// init_threads(), exit_threads() and nodes_searched() are helpers to
309 /// give accessibility to some TM methods from outside of current file.
311 void init_threads() { TM.init_threads(); }
312 void exit_threads() { TM.exit_threads(); }
313 int64_t nodes_searched() { return TM.nodes_searched(); }
316 /// perft() is our utility to verify move generation is bug free. All the legal
317 /// moves up to given depth are generated and counted and the sum returned.
319 int perft(Position& pos, Depth depth)
323 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
325 // If we are at the last ply we don't need to do and undo
326 // the moves, just to count them.
327 if (depth <= OnePly) // Replace with '<' to test also qsearch
329 while (mp.get_next_move()) sum++;
333 // Loop through all legal moves
335 while ((move = mp.get_next_move()) != MOVE_NONE)
338 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
339 sum += perft(pos, depth - OnePly);
346 /// think() is the external interface to Stockfish's search, and is called when
347 /// the program receives the UCI 'go' command. It initializes various
348 /// search-related global variables, and calls root_search(). It returns false
349 /// when a quit command is received during the search.
351 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
352 int time[], int increment[], int movesToGo, int maxDepth,
353 int maxNodes, int maxTime, Move searchMoves[]) {
355 // Initialize global search variables
356 StopOnPonderhit = AbortSearch = Quit = false;
357 AspirationFailLow = false;
359 SearchStartTime = get_system_time();
360 ExactMaxTime = maxTime;
363 InfiniteSearch = infinite;
364 PonderSearch = ponder;
365 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
367 // Look for a book move, only during games, not tests
368 if (UseTimeManagement && get_option_value_bool("OwnBook"))
371 if (get_option_value_string("Book File") != OpeningBook.file_name())
372 OpeningBook.open(get_option_value_string("Book File"));
374 bookMove = OpeningBook.get_move(pos);
375 if (bookMove != MOVE_NONE)
378 wait_for_stop_or_ponderhit();
380 cout << "bestmove " << bookMove << endl;
385 TM.resetNodeCounters();
387 if (button_was_pressed("New Game"))
388 loseOnTime = false; // Reset at the beginning of a new game
390 // Read UCI option values
391 TT.set_size(get_option_value_int("Hash"));
392 if (button_was_pressed("Clear Hash"))
395 bool PonderingEnabled = get_option_value_bool("Ponder");
396 MultiPV = get_option_value_int("MultiPV");
398 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
399 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
401 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
402 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
404 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
405 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
407 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
408 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
410 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
411 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
413 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
414 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
416 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
418 Chess960 = get_option_value_bool("UCI_Chess960");
419 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
420 UseLogFile = get_option_value_bool("Use Search Log");
422 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
424 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
425 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
427 read_weights(pos.side_to_move());
429 // Set the number of active threads
430 int newActiveThreads = get_option_value_int("Threads");
431 if (newActiveThreads != TM.active_threads())
433 TM.set_active_threads(newActiveThreads);
434 init_eval(TM.active_threads());
435 // HACK: init_eval() destroys the static castleRightsMask[] array in the
436 // Position class. The below line repairs the damage.
437 Position p(pos.to_fen());
441 // Wake up sleeping threads
442 TM.wake_sleeping_threads();
445 int myTime = time[side_to_move];
446 int myIncrement = increment[side_to_move];
447 if (UseTimeManagement)
449 if (!movesToGo) // Sudden death time control
453 MaxSearchTime = myTime / 30 + myIncrement;
454 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
456 else // Blitz game without increment
458 MaxSearchTime = myTime / 30;
459 AbsoluteMaxSearchTime = myTime / 8;
462 else // (x moves) / (y minutes)
466 MaxSearchTime = myTime / 2;
467 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
471 MaxSearchTime = myTime / Min(movesToGo, 20);
472 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
476 if (PonderingEnabled)
478 MaxSearchTime += MaxSearchTime / 4;
479 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
483 // Set best NodesBetweenPolls interval
485 NodesBetweenPolls = Min(MaxNodes, 30000);
486 else if (myTime && myTime < 1000)
487 NodesBetweenPolls = 1000;
488 else if (myTime && myTime < 5000)
489 NodesBetweenPolls = 5000;
491 NodesBetweenPolls = 30000;
493 // Write information to search log file
495 LogFile << "Searching: " << pos.to_fen() << endl
496 << "infinite: " << infinite
497 << " ponder: " << ponder
498 << " time: " << myTime
499 << " increment: " << myIncrement
500 << " moves to go: " << movesToGo << endl;
502 // LSN filtering. Used only for developing purpose. Disabled by default.
506 // Step 2. If after last move we decided to lose on time, do it now!
507 while (SearchStartTime + myTime + 1000 > get_system_time())
511 // We're ready to start thinking. Call the iterative deepening loop function
512 Value v = id_loop(pos, searchMoves);
516 // Step 1. If this is sudden death game and our position is hopeless,
517 // decide to lose on time.
518 if ( !loseOnTime // If we already lost on time, go to step 3.
528 // Step 3. Now after stepping over the time limit, reset flag for next match.
536 TM.put_threads_to_sleep();
542 /// init_search() is called during startup. It initializes various lookup tables
546 // Init our reduction lookup tables
547 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
548 for (int j = 1; j < 64; j++) // j == moveNumber
550 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
551 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
552 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
553 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
556 // Init futility margins array
557 for (int i = 0; i < 14; i++) // i == depth (OnePly = 2)
558 for (int j = 0; j < 64; j++) // j == moveNumber
560 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
563 // Init futility move count array
564 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
565 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
569 // SearchStack::init() initializes a search stack. Used at the beginning of a
570 // new search from the root.
571 void SearchStack::init(int ply) {
573 pv[ply] = pv[ply + 1] = MOVE_NONE;
574 currentMove = threatMove = MOVE_NONE;
575 reduction = Depth(0);
579 void SearchStack::initKillers() {
581 mateKiller = MOVE_NONE;
582 for (int i = 0; i < KILLER_MAX; i++)
583 killers[i] = MOVE_NONE;
588 // id_loop() is the main iterative deepening loop. It calls root_search
589 // repeatedly with increasing depth until the allocated thinking time has
590 // been consumed, the user stops the search, or the maximum search depth is
593 Value id_loop(const Position& pos, Move searchMoves[]) {
596 SearchStack ss[PLY_MAX_PLUS_2];
598 // searchMoves are verified, copied, scored and sorted
599 RootMoveList rml(p, searchMoves);
601 // Handle special case of searching on a mate/stale position
602 if (rml.move_count() == 0)
605 wait_for_stop_or_ponderhit();
607 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
610 // Print RootMoveList c'tor startup scoring to the standard output,
611 // so that we print information also for iteration 1.
612 cout << "info depth " << 1 << "\ninfo depth " << 1
613 << " score " << value_to_string(rml.get_move_score(0))
614 << " time " << current_search_time()
615 << " nodes " << TM.nodes_searched()
617 << " pv " << rml.get_move(0) << "\n";
623 ValueByIteration[1] = rml.get_move_score(0);
626 // Is one move significantly better than others after initial scoring ?
627 Move EasyMove = MOVE_NONE;
628 if ( rml.move_count() == 1
629 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
630 EasyMove = rml.get_move(0);
632 // Iterative deepening loop
633 while (Iteration < PLY_MAX)
635 // Initialize iteration
638 BestMoveChangesByIteration[Iteration] = 0;
642 cout << "info depth " << Iteration << endl;
644 // Calculate dynamic search window based on previous iterations
647 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
649 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
650 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
652 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
653 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
655 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
656 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
660 alpha = - VALUE_INFINITE;
661 beta = VALUE_INFINITE;
664 // Search to the current depth
665 Value value = root_search(p, ss, rml, alpha, beta);
667 // Write PV to transposition table, in case the relevant entries have
668 // been overwritten during the search.
669 TT.insert_pv(p, ss[0].pv);
672 break; // Value cannot be trusted. Break out immediately!
674 //Save info about search result
675 ValueByIteration[Iteration] = value;
677 // Drop the easy move if it differs from the new best move
678 if (ss[0].pv[0] != EasyMove)
679 EasyMove = MOVE_NONE;
681 if (UseTimeManagement)
684 bool stopSearch = false;
686 // Stop search early if there is only a single legal move,
687 // we search up to Iteration 6 anyway to get a proper score.
688 if (Iteration >= 6 && rml.move_count() == 1)
691 // Stop search early when the last two iterations returned a mate score
693 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
694 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
697 // Stop search early if one move seems to be much better than the rest
698 int64_t nodes = TM.nodes_searched();
700 && EasyMove == ss[0].pv[0]
701 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
702 && current_search_time() > MaxSearchTime / 16)
703 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
704 && current_search_time() > MaxSearchTime / 32)))
707 // Add some extra time if the best move has changed during the last two iterations
708 if (Iteration > 5 && Iteration <= 50)
709 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
710 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
712 // Stop search if most of MaxSearchTime is consumed at the end of the
713 // iteration. We probably don't have enough time to search the first
714 // move at the next iteration anyway.
715 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
723 StopOnPonderhit = true;
727 if (MaxDepth && Iteration >= MaxDepth)
733 // If we are pondering or in infinite search, we shouldn't print the
734 // best move before we are told to do so.
735 if (!AbortSearch && (PonderSearch || InfiniteSearch))
736 wait_for_stop_or_ponderhit();
738 // Print final search statistics
739 cout << "info nodes " << TM.nodes_searched()
741 << " time " << current_search_time()
742 << " hashfull " << TT.full() << endl;
744 // Print the best move and the ponder move to the standard output
745 if (ss[0].pv[0] == MOVE_NONE)
747 ss[0].pv[0] = rml.get_move(0);
748 ss[0].pv[1] = MOVE_NONE;
750 cout << "bestmove " << ss[0].pv[0];
751 if (ss[0].pv[1] != MOVE_NONE)
752 cout << " ponder " << ss[0].pv[1];
759 dbg_print_mean(LogFile);
761 if (dbg_show_hit_rate)
762 dbg_print_hit_rate(LogFile);
764 LogFile << "\nNodes: " << TM.nodes_searched()
765 << "\nNodes/second: " << nps()
766 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
769 p.do_move(ss[0].pv[0], st);
770 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
772 return rml.get_move_score(0);
776 // root_search() is the function which searches the root node. It is
777 // similar to search_pv except that it uses a different move ordering
778 // scheme and prints some information to the standard output.
780 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
785 Depth depth, ext, newDepth;
788 int researchCount = 0;
789 bool moveIsCheck, captureOrPromotion, dangerous;
790 Value alpha = oldAlpha;
791 bool isCheck = pos.is_check();
793 // Evaluate the position statically
795 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
797 while (1) // Fail low loop
800 // Loop through all the moves in the root move list
801 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
805 // We failed high, invalidate and skip next moves, leave node-counters
806 // and beta-counters as they are and quickly return, we will try to do
807 // a research at the next iteration with a bigger aspiration window.
808 rml.set_move_score(i, -VALUE_INFINITE);
812 RootMoveNumber = i + 1;
814 // Save the current node count before the move is searched
815 nodes = TM.nodes_searched();
817 // Reset beta cut-off counters
818 TM.resetBetaCounters();
820 // Pick the next root move, and print the move and the move number to
821 // the standard output.
822 move = ss[0].currentMove = rml.get_move(i);
824 if (current_search_time() >= 1000)
825 cout << "info currmove " << move
826 << " currmovenumber " << RootMoveNumber << endl;
828 // Decide search depth for this move
829 moveIsCheck = pos.move_is_check(move);
830 captureOrPromotion = pos.move_is_capture_or_promotion(move);
831 depth = (Iteration - 2) * OnePly + InitialDepth;
832 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
833 newDepth = depth + ext;
835 value = - VALUE_INFINITE;
837 while (1) // Fail high loop
840 // Make the move, and search it
841 pos.do_move(move, st, ci, moveIsCheck);
843 if (i < MultiPV || value > alpha)
845 // Aspiration window is disabled in multi-pv case
847 alpha = -VALUE_INFINITE;
849 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
853 // Try to reduce non-pv search depth by one ply if move seems not problematic,
854 // if the move fails high will be re-searched at full depth.
855 bool doFullDepthSearch = true;
857 if ( depth >= 3*OnePly // FIXME was newDepth
859 && !captureOrPromotion
860 && !move_is_castle(move))
862 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
865 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
866 doFullDepthSearch = (value > alpha);
870 if (doFullDepthSearch)
872 ss[0].reduction = Depth(0);
873 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
876 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
882 // Can we exit fail high loop ?
883 if (AbortSearch || value < beta)
886 // We are failing high and going to do a research. It's important to update score
887 // before research in case we run out of time while researching.
888 rml.set_move_score(i, value);
890 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
891 rml.set_move_pv(i, ss[0].pv);
893 // Print search information to the standard output
894 cout << "info depth " << Iteration
895 << " score " << value_to_string(value)
896 << ((value >= beta) ? " lowerbound" :
897 ((value <= alpha)? " upperbound" : ""))
898 << " time " << current_search_time()
899 << " nodes " << TM.nodes_searched()
903 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
904 cout << ss[0].pv[j] << " ";
910 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
911 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
913 LogFile << pretty_pv(pos, current_search_time(), Iteration,
914 TM.nodes_searched(), value, type, ss[0].pv) << endl;
917 // Prepare for a research after a fail high, each time with a wider window
919 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
921 } // End of fail high loop
923 // Finished searching the move. If AbortSearch is true, the search
924 // was aborted because the user interrupted the search or because we
925 // ran out of time. In this case, the return value of the search cannot
926 // be trusted, and we break out of the loop without updating the best
931 // Remember beta-cutoff and searched nodes counts for this move. The
932 // info is used to sort the root moves at the next iteration.
934 TM.get_beta_counters(pos.side_to_move(), our, their);
935 rml.set_beta_counters(i, our, their);
936 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
938 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
940 if (value <= alpha && i >= MultiPV)
941 rml.set_move_score(i, -VALUE_INFINITE);
944 // PV move or new best move!
947 rml.set_move_score(i, value);
949 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
950 rml.set_move_pv(i, ss[0].pv);
954 // We record how often the best move has been changed in each
955 // iteration. This information is used for time managment: When
956 // the best move changes frequently, we allocate some more time.
958 BestMoveChangesByIteration[Iteration]++;
960 // Print search information to the standard output
961 cout << "info depth " << Iteration
962 << " score " << value_to_string(value)
963 << ((value >= beta) ? " lowerbound" :
964 ((value <= alpha)? " upperbound" : ""))
965 << " time " << current_search_time()
966 << " nodes " << TM.nodes_searched()
970 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
971 cout << ss[0].pv[j] << " ";
977 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
978 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
980 LogFile << pretty_pv(pos, current_search_time(), Iteration,
981 TM.nodes_searched(), value, type, ss[0].pv) << endl;
989 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
991 cout << "info multipv " << j + 1
992 << " score " << value_to_string(rml.get_move_score(j))
993 << " depth " << ((j <= i)? Iteration : Iteration - 1)
994 << " time " << current_search_time()
995 << " nodes " << TM.nodes_searched()
999 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1000 cout << rml.get_move_pv(j, k) << " ";
1004 alpha = rml.get_move_score(Min(i, MultiPV-1));
1006 } // PV move or new best move
1008 assert(alpha >= oldAlpha);
1010 AspirationFailLow = (alpha == oldAlpha);
1012 if (AspirationFailLow && StopOnPonderhit)
1013 StopOnPonderhit = false;
1016 // Can we exit fail low loop ?
1017 if (AbortSearch || alpha > oldAlpha)
1020 // Prepare for a research after a fail low, each time with a wider window
1022 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1031 // search_pv() is the main search function for PV nodes.
1033 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1034 Depth depth, int ply, int threadID) {
1036 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1037 assert(beta > alpha && beta <= VALUE_INFINITE);
1038 assert(ply >= 0 && ply < PLY_MAX);
1039 assert(threadID >= 0 && threadID < TM.active_threads());
1041 Move movesSearched[256];
1045 Depth ext, newDepth;
1046 Value oldAlpha, value;
1047 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1049 Value bestValue = value = -VALUE_INFINITE;
1052 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1054 // Step 1. Initialize node and poll
1055 // Polling can abort search.
1056 init_node(ss, ply, threadID);
1058 // Step 2. Check for aborted search and immediate draw
1059 if (AbortSearch || TM.thread_should_stop(threadID))
1062 if (pos.is_draw() || ply >= PLY_MAX - 1)
1065 // Step 3. Mate distance pruning
1067 alpha = Max(value_mated_in(ply), alpha);
1068 beta = Min(value_mate_in(ply+1), beta);
1072 // Step 4. Transposition table lookup
1073 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1074 // This is to avoid problems in the following areas:
1076 // * Repetition draw detection
1077 // * Fifty move rule detection
1078 // * Searching for a mate
1079 // * Printing of full PV line
1080 tte = TT.retrieve(pos.get_key());
1081 ttMove = (tte ? tte->move() : MOVE_NONE);
1083 // Step 5. Evaluate the position statically
1084 // At PV nodes we do this only to update gain statistics
1085 isCheck = pos.is_check();
1089 ss[ply].eval = evaluate(pos, ei, threadID);
1090 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1093 // Step 6. Razoring (is omitted in PV nodes)
1094 // Step 7. Static null move pruning (is omitted in PV nodes)
1095 // Step 8. Null move search with verification search (is omitted in PV nodes)
1097 // Step 9. Internal iterative deepening
1098 if ( UseIIDAtPVNodes
1099 && depth >= 5*OnePly
1100 && ttMove == MOVE_NONE)
1102 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1103 ttMove = ss[ply].pv[ply];
1104 tte = TT.retrieve(pos.get_key());
1107 // Step 10. Loop through moves
1108 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1110 // Initialize a MovePicker object for the current position
1111 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1112 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1115 while ( alpha < beta
1116 && (move = mp.get_next_move()) != MOVE_NONE
1117 && !TM.thread_should_stop(threadID))
1119 assert(move_is_ok(move));
1121 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1122 moveIsCheck = pos.move_is_check(move, ci);
1123 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1125 // Step 11. Decide the new search depth
1126 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1128 // Singular extension search. We extend the TT move if its value is much better than
1129 // its siblings. To verify this we do a reduced search on all the other moves but the
1130 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1131 if ( depth >= 6 * OnePly
1133 && move == tte->move()
1135 && is_lower_bound(tte->type())
1136 && tte->depth() >= depth - 3 * OnePly)
1138 Value ttValue = value_from_tt(tte->value(), ply);
1140 if (abs(ttValue) < VALUE_KNOWN_WIN)
1142 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1144 if (excValue < ttValue - SingleReplyMargin)
1149 newDepth = depth - OnePly + ext;
1151 // Update current move (this must be done after singular extension search)
1152 movesSearched[moveCount++] = ss[ply].currentMove = move;
1154 // Step 12. Futility pruning (is omitted in PV nodes)
1156 // Step 13. Make the move
1157 pos.do_move(move, st, ci, moveIsCheck);
1159 // Step extra. pv search (only in PV nodes)
1160 // The first move in list is the expected PV
1162 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1165 // Step 14. Reduced search
1166 // if the move fails high will be re-searched at full depth.
1167 bool doFullDepthSearch = true;
1169 if ( depth >= 3*OnePly
1171 && !captureOrPromotion
1172 && !move_is_castle(move)
1173 && !move_is_killer(move, ss[ply]))
1175 ss[ply].reduction = pv_reduction(depth, moveCount);
1176 if (ss[ply].reduction)
1178 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1179 doFullDepthSearch = (value > alpha);
1183 // Step 15. Full depth search
1184 if (doFullDepthSearch)
1186 ss[ply].reduction = Depth(0);
1187 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1189 // Step extra. pv search (only in PV nodes)
1190 if (value > alpha && value < beta)
1191 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1195 // Step 16. Undo move
1196 pos.undo_move(move);
1198 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1200 // Step 17. Check for new best move
1201 if (value > bestValue)
1208 if (value == value_mate_in(ply + 1))
1209 ss[ply].mateKiller = move;
1213 // Step 18. Check for split
1214 if ( TM.active_threads() > 1
1216 && depth >= MinimumSplitDepth
1218 && TM.available_thread_exists(threadID)
1220 && !TM.thread_should_stop(threadID)
1221 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1222 depth, &moveCount, &mp, threadID, true))
1226 // Step 19. Check for mate and stalemate
1227 // All legal moves have been searched and if there were
1228 // no legal moves, it must be mate or stalemate.
1230 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1232 // Step 20. Update tables
1233 // If the search is not aborted, update the transposition table,
1234 // history counters, and killer moves.
1235 if (AbortSearch || TM.thread_should_stop(threadID))
1238 if (bestValue <= oldAlpha)
1239 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1241 else if (bestValue >= beta)
1243 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1244 move = ss[ply].pv[ply];
1245 if (!pos.move_is_capture_or_promotion(move))
1247 update_history(pos, move, depth, movesSearched, moveCount);
1248 update_killers(move, ss[ply]);
1250 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1253 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1259 // search() is the search function for zero-width nodes.
1261 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1262 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1264 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1265 assert(ply >= 0 && ply < PLY_MAX);
1266 assert(threadID >= 0 && threadID < TM.active_threads());
1268 Move movesSearched[256];
1273 Depth ext, newDepth;
1274 Value bestValue, refinedValue, nullValue, value, futilityValueScaled;
1275 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1276 bool mateThreat = false;
1278 refinedValue = bestValue = value = -VALUE_INFINITE;
1281 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1283 // Step 1. Initialize node and poll
1284 // Polling can abort search.
1285 init_node(ss, ply, threadID);
1287 // Step 2. Check for aborted search and immediate draw
1288 if (AbortSearch || TM.thread_should_stop(threadID))
1291 if (pos.is_draw() || ply >= PLY_MAX - 1)
1294 // Step 3. Mate distance pruning
1295 if (value_mated_in(ply) >= beta)
1298 if (value_mate_in(ply + 1) < beta)
1301 // Step 4. Transposition table lookup
1303 // We don't want the score of a partial search to overwrite a previous full search
1304 // TT value, so we use a different position key in case of an excluded move exists.
1305 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1307 tte = TT.retrieve(posKey);
1308 ttMove = (tte ? tte->move() : MOVE_NONE);
1310 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1312 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1313 return value_from_tt(tte->value(), ply);
1316 // Step 5. Evaluate the position statically
1317 isCheck = pos.is_check();
1321 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1322 ss[ply].eval = value_from_tt(tte->value(), ply);
1324 ss[ply].eval = evaluate(pos, ei, threadID);
1326 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1327 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1331 if ( !value_is_mate(beta)
1333 && depth < RazorDepth
1334 && refinedValue < beta - (0x200 + 16 * depth)
1335 && ss[ply - 1].currentMove != MOVE_NULL
1336 && ttMove == MOVE_NONE
1337 && !pos.has_pawn_on_7th(pos.side_to_move()))
1339 Value rbeta = beta - (0x200 + 16 * depth);
1340 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1342 return v; //FIXME: Logically should be: return (v + 0x200 + 16 * depth);
1345 // Step 7. Static null move pruning
1346 // We're betting that the opponent doesn't have a move that will reduce
1347 // the score by more than fuility_margin(depth) if we do a null move.
1350 && depth < RazorDepth
1351 && refinedValue - futility_margin(depth, 0) >= beta)
1352 return refinedValue - futility_margin(depth, 0);
1354 // Step 8. Null move search with verification search
1355 // When we jump directly to qsearch() we do a null move only if static value is
1356 // at least beta. Otherwise we do a null move if static value is not more than
1357 // NullMoveMargin under beta.
1361 && !value_is_mate(beta)
1362 && ok_to_do_nullmove(pos)
1363 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1365 ss[ply].currentMove = MOVE_NULL;
1367 pos.do_null_move(st);
1369 // Null move dynamic reduction based on depth
1370 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1372 // Null move dynamic reduction based on value
1373 if (refinedValue - beta > PawnValueMidgame)
1376 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1378 pos.undo_null_move();
1380 if (nullValue >= beta)
1382 if (depth < 6 * OnePly)
1385 // Do zugzwang verification search
1386 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1390 // The null move failed low, which means that we may be faced with
1391 // some kind of threat. If the previous move was reduced, check if
1392 // the move that refuted the null move was somehow connected to the
1393 // move which was reduced. If a connection is found, return a fail
1394 // low score (which will cause the reduced move to fail high in the
1395 // parent node, which will trigger a re-search with full depth).
1396 if (nullValue == value_mated_in(ply + 2))
1399 ss[ply].threatMove = ss[ply + 1].currentMove;
1400 if ( depth < ThreatDepth
1401 && ss[ply - 1].reduction
1402 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1407 // Step 9. Internal iterative deepening
1408 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1409 !isCheck && ss[ply].eval >= beta - IIDMargin)
1411 search(pos, ss, beta, depth/2, ply, false, threadID);
1412 ttMove = ss[ply].pv[ply];
1413 tte = TT.retrieve(posKey);
1416 // Step 10. Loop through moves
1417 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1419 // Initialize a MovePicker object for the current position
1420 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1423 while ( bestValue < beta
1424 && (move = mp.get_next_move()) != MOVE_NONE
1425 && !TM.thread_should_stop(threadID))
1427 assert(move_is_ok(move));
1429 if (move == excludedMove)
1432 moveIsCheck = pos.move_is_check(move, ci);
1433 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1434 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1436 // Step 11. Decide the new search depth
1437 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1439 // Singular extension search. We extend the TT move if its value is much better than
1440 // its siblings. To verify this we do a reduced search on all the other moves but the
1441 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1442 if ( depth >= 8 * OnePly
1444 && move == tte->move()
1445 && !excludedMove // Do not allow recursive single-reply search
1447 && is_lower_bound(tte->type())
1448 && tte->depth() >= depth - 3 * OnePly)
1450 Value ttValue = value_from_tt(tte->value(), ply);
1452 if (abs(ttValue) < VALUE_KNOWN_WIN)
1454 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1456 if (excValue < ttValue - SingleReplyMargin)
1461 newDepth = depth - OnePly + ext;
1463 // Update current move (this must be done after singular extension search)
1464 movesSearched[moveCount++] = ss[ply].currentMove = move;
1466 // Step 12. Futility pruning
1469 && !captureOrPromotion
1470 && !move_is_castle(move)
1473 // Move count based pruning
1474 if ( moveCount >= futility_move_count(depth)
1475 && ok_to_prune(pos, move, ss[ply].threatMove)
1476 && bestValue > value_mated_in(PLY_MAX))
1479 // Value based pruning
1480 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1481 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1482 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1484 if (futilityValueScaled < beta)
1486 if (futilityValueScaled > bestValue)
1487 bestValue = futilityValueScaled;
1492 // Step 13. Make the move
1493 pos.do_move(move, st, ci, moveIsCheck);
1495 // Step 14. Reduced search
1496 // if the move fails high will be re-searched at full depth.
1497 bool doFullDepthSearch = true;
1499 if ( depth >= 3*OnePly
1501 && !captureOrPromotion
1502 && !move_is_castle(move)
1503 && !move_is_killer(move, ss[ply]))
1505 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1506 if (ss[ply].reduction)
1508 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1509 doFullDepthSearch = (value >= beta);
1513 // Step 15. Full depth search
1514 if (doFullDepthSearch)
1516 ss[ply].reduction = Depth(0);
1517 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1520 // Step 16. Undo move
1521 pos.undo_move(move);
1523 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1525 // Step 17. Check for new best move
1526 if (value > bestValue)
1532 if (value == value_mate_in(ply + 1))
1533 ss[ply].mateKiller = move;
1536 // Step 18. Check for split
1537 if ( TM.active_threads() > 1
1539 && depth >= MinimumSplitDepth
1541 && TM.available_thread_exists(threadID)
1543 && !TM.thread_should_stop(threadID)
1544 && TM.split(pos, ss, ply, NULL, beta, &bestValue,
1545 depth, &moveCount, &mp, threadID, false))
1549 // Step 19. Check for mate and stalemate
1550 // All legal moves have been searched and if there were
1551 // no legal moves, it must be mate or stalemate.
1552 // If one move was excluded return fail low.
1554 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1556 // Step 20. Update tables
1557 // If the search is not aborted, update the transposition table,
1558 // history counters, and killer moves.
1559 if (AbortSearch || TM.thread_should_stop(threadID))
1562 if (bestValue < beta)
1563 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1566 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1567 move = ss[ply].pv[ply];
1568 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1569 if (!pos.move_is_capture_or_promotion(move))
1571 update_history(pos, move, depth, movesSearched, moveCount);
1572 update_killers(move, ss[ply]);
1577 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1583 // qsearch() is the quiescence search function, which is called by the main
1584 // search function when the remaining depth is zero (or, to be more precise,
1585 // less than OnePly).
1587 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1588 Depth depth, int ply, int threadID) {
1590 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1591 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1593 assert(ply >= 0 && ply < PLY_MAX);
1594 assert(threadID >= 0 && threadID < TM.active_threads());
1599 Value staticValue, bestValue, value, futilityBase, futilityValue;
1600 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1601 const TTEntry* tte = NULL;
1603 bool pvNode = (beta - alpha != 1);
1604 Value oldAlpha = alpha;
1606 // Initialize, and make an early exit in case of an aborted search,
1607 // an instant draw, maximum ply reached, etc.
1608 init_node(ss, ply, threadID);
1610 // After init_node() that calls poll()
1611 if (AbortSearch || TM.thread_should_stop(threadID))
1614 if (pos.is_draw() || ply >= PLY_MAX - 1)
1617 // Transposition table lookup. At PV nodes, we don't use the TT for
1618 // pruning, but only for move ordering.
1619 tte = TT.retrieve(pos.get_key());
1620 ttMove = (tte ? tte->move() : MOVE_NONE);
1622 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1624 assert(tte->type() != VALUE_TYPE_EVAL);
1626 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1627 return value_from_tt(tte->value(), ply);
1630 isCheck = pos.is_check();
1632 // Evaluate the position statically
1634 staticValue = -VALUE_INFINITE;
1635 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1636 staticValue = value_from_tt(tte->value(), ply);
1638 staticValue = evaluate(pos, ei, threadID);
1642 ss[ply].eval = staticValue;
1643 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1646 // Initialize "stand pat score", and return it immediately if it is
1648 bestValue = staticValue;
1650 if (bestValue >= beta)
1652 // Store the score to avoid a future costly evaluation() call
1653 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1654 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1659 if (bestValue > alpha)
1662 // If we are near beta then try to get a cutoff pushing checks a bit further
1663 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1665 // Initialize a MovePicker object for the current position, and prepare
1666 // to search the moves. Because the depth is <= 0 here, only captures,
1667 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1668 // and we are near beta) will be generated.
1669 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1671 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1672 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1674 // Loop through the moves until no moves remain or a beta cutoff
1676 while ( alpha < beta
1677 && (move = mp.get_next_move()) != MOVE_NONE)
1679 assert(move_is_ok(move));
1681 moveIsCheck = pos.move_is_check(move, ci);
1683 // Update current move
1685 ss[ply].currentMove = move;
1693 && !move_is_promotion(move)
1694 && !pos.move_is_passed_pawn_push(move))
1696 futilityValue = futilityBase
1697 + pos.endgame_value_of_piece_on(move_to(move))
1698 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1700 if (futilityValue < alpha)
1702 if (futilityValue > bestValue)
1703 bestValue = futilityValue;
1708 // Detect blocking evasions that are candidate to be pruned
1709 evasionPrunable = isCheck
1710 && bestValue != -VALUE_INFINITE
1711 && !pos.move_is_capture(move)
1712 && pos.type_of_piece_on(move_from(move)) != KING
1713 && !pos.can_castle(pos.side_to_move());
1715 // Don't search moves with negative SEE values
1716 if ( (!isCheck || evasionPrunable)
1719 && !move_is_promotion(move)
1720 && pos.see_sign(move) < 0)
1723 // Make and search the move
1724 pos.do_move(move, st, ci, moveIsCheck);
1725 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1726 pos.undo_move(move);
1728 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1731 if (value > bestValue)
1742 // All legal moves have been searched. A special case: If we're in check
1743 // and no legal moves were found, it is checkmate.
1744 if (!moveCount && pos.is_check()) // Mate!
1745 return value_mated_in(ply);
1747 // Update transposition table
1748 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1749 if (bestValue <= oldAlpha)
1751 // If bestValue isn't changed it means it is still the static evaluation
1752 // of the node, so keep this info to avoid a future evaluation() call.
1753 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1754 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1756 else if (bestValue >= beta)
1758 move = ss[ply].pv[ply];
1759 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1761 // Update killers only for good checking moves
1762 if (!pos.move_is_capture_or_promotion(move))
1763 update_killers(move, ss[ply]);
1766 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1768 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1774 // sp_search() is used to search from a split point. This function is called
1775 // by each thread working at the split point. It is similar to the normal
1776 // search() function, but simpler. Because we have already probed the hash
1777 // table, done a null move search, and searched the first move before
1778 // splitting, we don't have to repeat all this work in sp_search(). We
1779 // also don't need to store anything to the hash table here: This is taken
1780 // care of after we return from the split point.
1782 void sp_search(SplitPoint* sp, int threadID) {
1784 assert(threadID >= 0 && threadID < TM.active_threads());
1785 assert(TM.active_threads() > 1);
1787 Position pos(*sp->pos);
1789 SearchStack* ss = sp->sstack[threadID];
1791 Value value = -VALUE_INFINITE;
1794 bool isCheck = pos.is_check();
1796 // Step 10. Loop through moves
1797 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1798 lock_grab(&(sp->lock));
1800 while ( sp->bestValue < sp->beta
1801 && !TM.thread_should_stop(threadID)
1802 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1804 moveCount = ++sp->moves;
1805 lock_release(&(sp->lock));
1807 assert(move_is_ok(move));
1809 bool moveIsCheck = pos.move_is_check(move, ci);
1810 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1812 // Step 11. Decide the new search depth
1814 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1815 Depth newDepth = sp->depth - OnePly + ext;
1817 // Update current move
1818 ss[sp->ply].currentMove = move;
1820 // Step 12. Futility pruning
1823 && !captureOrPromotion
1824 && !move_is_castle(move))
1826 // Move count based pruning
1827 if ( moveCount >= futility_move_count(sp->depth)
1828 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1829 && sp->bestValue > value_mated_in(PLY_MAX))
1831 lock_grab(&(sp->lock));
1835 // Value based pruning
1836 Depth predictedDepth = newDepth - nonpv_reduction(sp->depth, moveCount);
1837 Value futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1838 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1840 if (futilityValueScaled < sp->beta)
1842 lock_grab(&(sp->lock));
1844 if (futilityValueScaled > sp->bestValue)
1845 sp->bestValue = futilityValueScaled;
1850 // Step 13. Make the move
1851 pos.do_move(move, st, ci, moveIsCheck);
1853 // Step 14. Reduced search
1854 // if the move fails high will be re-searched at full depth.
1855 bool doFullDepthSearch = true;
1858 && !captureOrPromotion
1859 && !move_is_castle(move)
1860 && !move_is_killer(move, ss[sp->ply]))
1862 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1863 if (ss[sp->ply].reduction)
1865 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1866 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1870 // Step 15. Full depth search
1871 if (doFullDepthSearch)
1873 ss[sp->ply].reduction = Depth(0);
1874 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1877 // Step 16. Undo move
1878 pos.undo_move(move);
1880 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1882 // Step 17. Check for new best move
1883 lock_grab(&(sp->lock));
1885 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1887 sp->bestValue = value;
1888 if (sp->bestValue >= sp->beta)
1890 sp->stopRequest = true;
1891 sp_update_pv(sp->parentSstack, ss, sp->ply);
1896 /* Here we have the lock still grabbed */
1898 sp->slaves[threadID] = 0;
1901 lock_release(&(sp->lock));
1905 // sp_search_pv() is used to search from a PV split point. This function
1906 // is called by each thread working at the split point. It is similar to
1907 // the normal search_pv() function, but simpler. Because we have already
1908 // probed the hash table and searched the first move before splitting, we
1909 // don't have to repeat all this work in sp_search_pv(). We also don't
1910 // need to store anything to the hash table here: This is taken care of
1911 // after we return from the split point.
1913 void sp_search_pv(SplitPoint* sp, int threadID) {
1915 assert(threadID >= 0 && threadID < TM.active_threads());
1916 assert(TM.active_threads() > 1);
1918 Position pos(*sp->pos);
1920 SearchStack* ss = sp->sstack[threadID];
1922 Value value = -VALUE_INFINITE;
1926 // Step 10. Loop through moves
1927 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1928 lock_grab(&(sp->lock));
1930 while ( sp->alpha < sp->beta
1931 && !TM.thread_should_stop(threadID)
1932 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1934 moveCount = ++sp->moves;
1935 lock_release(&(sp->lock));
1937 assert(move_is_ok(move));
1939 bool moveIsCheck = pos.move_is_check(move, ci);
1940 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1942 // Step 11. Decide the new search depth
1944 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1945 Depth newDepth = sp->depth - OnePly + ext;
1947 // Update current move
1948 ss[sp->ply].currentMove = move;
1950 // Step 12. Futility pruning (is omitted in PV nodes)
1952 // Step 13. Make the move
1953 pos.do_move(move, st, ci, moveIsCheck);
1955 // Step 14. Reduced search
1956 // if the move fails high will be re-searched at full depth.
1957 bool doFullDepthSearch = true;
1960 && !captureOrPromotion
1961 && !move_is_castle(move)
1962 && !move_is_killer(move, ss[sp->ply]))
1964 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
1965 if (ss[sp->ply].reduction)
1967 Value localAlpha = sp->alpha;
1968 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1969 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
1973 // Step 15. Full depth search
1974 if (doFullDepthSearch)
1976 Value localAlpha = sp->alpha;
1977 ss[sp->ply].reduction = Depth(0);
1978 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
1980 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
1982 // If another thread has failed high then sp->alpha has been increased
1983 // to be higher or equal then beta, if so, avoid to start a PV search.
1984 localAlpha = sp->alpha;
1985 if (localAlpha < sp->beta)
1986 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
1990 // Step 16. Undo move
1991 pos.undo_move(move);
1993 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1995 // Step 17. Check for new best move
1996 lock_grab(&(sp->lock));
1998 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
2000 sp->bestValue = value;
2001 if (value > sp->alpha)
2003 // Ask threads to stop before to modify sp->alpha
2004 if (value >= sp->beta)
2005 sp->stopRequest = true;
2009 sp_update_pv(sp->parentSstack, ss, sp->ply);
2010 if (value == value_mate_in(sp->ply + 1))
2011 ss[sp->ply].mateKiller = move;
2016 /* Here we have the lock still grabbed */
2018 sp->slaves[threadID] = 0;
2021 lock_release(&(sp->lock));
2025 // init_node() is called at the beginning of all the search functions
2026 // (search(), search_pv(), qsearch(), and so on) and initializes the
2027 // search stack object corresponding to the current node. Once every
2028 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2029 // for user input and checks whether it is time to stop the search.
2031 void init_node(SearchStack ss[], int ply, int threadID) {
2033 assert(ply >= 0 && ply < PLY_MAX);
2034 assert(threadID >= 0 && threadID < TM.active_threads());
2036 TM.incrementNodeCounter(threadID);
2041 if (NodesSincePoll >= NodesBetweenPolls)
2048 ss[ply + 2].initKillers();
2052 // update_pv() is called whenever a search returns a value > alpha.
2053 // It updates the PV in the SearchStack object corresponding to the
2056 void update_pv(SearchStack ss[], int ply) {
2058 assert(ply >= 0 && ply < PLY_MAX);
2062 ss[ply].pv[ply] = ss[ply].currentMove;
2064 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2065 ss[ply].pv[p] = ss[ply + 1].pv[p];
2067 ss[ply].pv[p] = MOVE_NONE;
2071 // sp_update_pv() is a variant of update_pv for use at split points. The
2072 // difference between the two functions is that sp_update_pv also updates
2073 // the PV at the parent node.
2075 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2077 assert(ply >= 0 && ply < PLY_MAX);
2081 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2083 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2084 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2086 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2090 // connected_moves() tests whether two moves are 'connected' in the sense
2091 // that the first move somehow made the second move possible (for instance
2092 // if the moving piece is the same in both moves). The first move is assumed
2093 // to be the move that was made to reach the current position, while the
2094 // second move is assumed to be a move from the current position.
2096 bool connected_moves(const Position& pos, Move m1, Move m2) {
2098 Square f1, t1, f2, t2;
2101 assert(move_is_ok(m1));
2102 assert(move_is_ok(m2));
2104 if (m2 == MOVE_NONE)
2107 // Case 1: The moving piece is the same in both moves
2113 // Case 2: The destination square for m2 was vacated by m1
2119 // Case 3: Moving through the vacated square
2120 if ( piece_is_slider(pos.piece_on(f2))
2121 && bit_is_set(squares_between(f2, t2), f1))
2124 // Case 4: The destination square for m2 is defended by the moving piece in m1
2125 p = pos.piece_on(t1);
2126 if (bit_is_set(pos.attacks_from(p, t1), t2))
2129 // Case 5: Discovered check, checking piece is the piece moved in m1
2130 if ( piece_is_slider(p)
2131 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2132 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2134 // discovered_check_candidates() works also if the Position's side to
2135 // move is the opposite of the checking piece.
2136 Color them = opposite_color(pos.side_to_move());
2137 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2139 if (bit_is_set(dcCandidates, f2))
2146 // value_is_mate() checks if the given value is a mate one
2147 // eventually compensated for the ply.
2149 bool value_is_mate(Value value) {
2151 assert(abs(value) <= VALUE_INFINITE);
2153 return value <= value_mated_in(PLY_MAX)
2154 || value >= value_mate_in(PLY_MAX);
2158 // move_is_killer() checks if the given move is among the
2159 // killer moves of that ply.
2161 bool move_is_killer(Move m, const SearchStack& ss) {
2163 const Move* k = ss.killers;
2164 for (int i = 0; i < KILLER_MAX; i++, k++)
2172 // extension() decides whether a move should be searched with normal depth,
2173 // or with extended depth. Certain classes of moves (checking moves, in
2174 // particular) are searched with bigger depth than ordinary moves and in
2175 // any case are marked as 'dangerous'. Note that also if a move is not
2176 // extended, as example because the corresponding UCI option is set to zero,
2177 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2179 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2180 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2182 assert(m != MOVE_NONE);
2184 Depth result = Depth(0);
2185 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2190 result += CheckExtension[pvNode];
2193 result += SingleEvasionExtension[pvNode];
2196 result += MateThreatExtension[pvNode];
2199 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2201 Color c = pos.side_to_move();
2202 if (relative_rank(c, move_to(m)) == RANK_7)
2204 result += PawnPushTo7thExtension[pvNode];
2207 if (pos.pawn_is_passed(c, move_to(m)))
2209 result += PassedPawnExtension[pvNode];
2214 if ( captureOrPromotion
2215 && pos.type_of_piece_on(move_to(m)) != PAWN
2216 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2217 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2218 && !move_is_promotion(m)
2221 result += PawnEndgameExtension[pvNode];
2226 && captureOrPromotion
2227 && pos.type_of_piece_on(move_to(m)) != PAWN
2228 && pos.see_sign(m) >= 0)
2234 return Min(result, OnePly);
2238 // ok_to_do_nullmove() looks at the current position and decides whether
2239 // doing a 'null move' should be allowed. In order to avoid zugzwang
2240 // problems, null moves are not allowed when the side to move has very
2241 // little material left. Currently, the test is a bit too simple: Null
2242 // moves are avoided only when the side to move has only pawns left.
2243 // It's probably a good idea to avoid null moves in at least some more
2244 // complicated endgames, e.g. KQ vs KR. FIXME
2246 bool ok_to_do_nullmove(const Position& pos) {
2248 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2252 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2253 // non-tactical moves late in the move list close to the leaves are
2254 // candidates for pruning.
2256 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2258 assert(move_is_ok(m));
2259 assert(threat == MOVE_NONE || move_is_ok(threat));
2260 assert(!pos.move_is_check(m));
2261 assert(!pos.move_is_capture_or_promotion(m));
2262 assert(!pos.move_is_passed_pawn_push(m));
2264 Square mfrom, mto, tfrom, tto;
2266 // Prune if there isn't any threat move
2267 if (threat == MOVE_NONE)
2270 mfrom = move_from(m);
2272 tfrom = move_from(threat);
2273 tto = move_to(threat);
2275 // Case 1: Don't prune moves which move the threatened piece
2279 // Case 2: If the threatened piece has value less than or equal to the
2280 // value of the threatening piece, don't prune move which defend it.
2281 if ( pos.move_is_capture(threat)
2282 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2283 || pos.type_of_piece_on(tfrom) == KING)
2284 && pos.move_attacks_square(m, tto))
2287 // Case 3: If the moving piece in the threatened move is a slider, don't
2288 // prune safe moves which block its ray.
2289 if ( piece_is_slider(pos.piece_on(tfrom))
2290 && bit_is_set(squares_between(tfrom, tto), mto)
2291 && pos.see_sign(m) >= 0)
2298 // ok_to_use_TT() returns true if a transposition table score
2299 // can be used at a given point in search.
2301 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2303 Value v = value_from_tt(tte->value(), ply);
2305 return ( tte->depth() >= depth
2306 || v >= Max(value_mate_in(PLY_MAX), beta)
2307 || v < Min(value_mated_in(PLY_MAX), beta))
2309 && ( (is_lower_bound(tte->type()) && v >= beta)
2310 || (is_upper_bound(tte->type()) && v < beta));
2314 // refine_eval() returns the transposition table score if
2315 // possible otherwise falls back on static position evaluation.
2317 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2322 Value v = value_from_tt(tte->value(), ply);
2324 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2325 || (is_upper_bound(tte->type()) && v < defaultEval))
2332 // update_history() registers a good move that produced a beta-cutoff
2333 // in history and marks as failures all the other moves of that ply.
2335 void update_history(const Position& pos, Move move, Depth depth,
2336 Move movesSearched[], int moveCount) {
2340 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2342 for (int i = 0; i < moveCount - 1; i++)
2344 m = movesSearched[i];
2348 if (!pos.move_is_capture_or_promotion(m))
2349 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2354 // update_killers() add a good move that produced a beta-cutoff
2355 // among the killer moves of that ply.
2357 void update_killers(Move m, SearchStack& ss) {
2359 if (m == ss.killers[0])
2362 for (int i = KILLER_MAX - 1; i > 0; i--)
2363 ss.killers[i] = ss.killers[i - 1];
2369 // update_gains() updates the gains table of a non-capture move given
2370 // the static position evaluation before and after the move.
2372 void update_gains(const Position& pos, Move m, Value before, Value after) {
2375 && before != VALUE_NONE
2376 && after != VALUE_NONE
2377 && pos.captured_piece() == NO_PIECE_TYPE
2378 && !move_is_castle(m)
2379 && !move_is_promotion(m))
2380 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2384 // current_search_time() returns the number of milliseconds which have passed
2385 // since the beginning of the current search.
2387 int current_search_time() {
2389 return get_system_time() - SearchStartTime;
2393 // nps() computes the current nodes/second count.
2397 int t = current_search_time();
2398 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2402 // poll() performs two different functions: It polls for user input, and it
2403 // looks at the time consumed so far and decides if it's time to abort the
2406 void poll(SearchStack ss[], int ply) {
2408 static int lastInfoTime;
2409 int t = current_search_time();
2414 // We are line oriented, don't read single chars
2415 std::string command;
2417 if (!std::getline(std::cin, command))
2420 if (command == "quit")
2423 PonderSearch = false;
2427 else if (command == "stop")
2430 PonderSearch = false;
2432 else if (command == "ponderhit")
2436 // Print search information
2440 else if (lastInfoTime > t)
2441 // HACK: Must be a new search where we searched less than
2442 // NodesBetweenPolls nodes during the first second of search.
2445 else if (t - lastInfoTime >= 1000)
2452 if (dbg_show_hit_rate)
2453 dbg_print_hit_rate();
2455 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2456 << " time " << t << " hashfull " << TT.full() << endl;
2458 // We only support current line printing in single thread mode
2459 if (ShowCurrentLine && TM.active_threads() == 1)
2461 cout << "info currline";
2462 for (int p = 0; p < ply; p++)
2463 cout << " " << ss[p].currentMove;
2469 // Should we stop the search?
2473 bool stillAtFirstMove = RootMoveNumber == 1
2474 && !AspirationFailLow
2475 && t > MaxSearchTime + ExtraSearchTime;
2477 bool noMoreTime = t > AbsoluteMaxSearchTime
2478 || stillAtFirstMove;
2480 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2481 || (ExactMaxTime && t >= ExactMaxTime)
2482 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2487 // ponderhit() is called when the program is pondering (i.e. thinking while
2488 // it's the opponent's turn to move) in order to let the engine know that
2489 // it correctly predicted the opponent's move.
2493 int t = current_search_time();
2494 PonderSearch = false;
2496 bool stillAtFirstMove = RootMoveNumber == 1
2497 && !AspirationFailLow
2498 && t > MaxSearchTime + ExtraSearchTime;
2500 bool noMoreTime = t > AbsoluteMaxSearchTime
2501 || stillAtFirstMove;
2503 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2508 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2510 void init_ss_array(SearchStack ss[]) {
2512 for (int i = 0; i < 3; i++)
2515 ss[i].initKillers();
2520 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2521 // while the program is pondering. The point is to work around a wrinkle in
2522 // the UCI protocol: When pondering, the engine is not allowed to give a
2523 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2524 // We simply wait here until one of these commands is sent, and return,
2525 // after which the bestmove and pondermove will be printed (in id_loop()).
2527 void wait_for_stop_or_ponderhit() {
2529 std::string command;
2533 if (!std::getline(std::cin, command))
2536 if (command == "quit")
2541 else if (command == "ponderhit" || command == "stop")
2547 // init_thread() is the function which is called when a new thread is
2548 // launched. It simply calls the idle_loop() function with the supplied
2549 // threadID. There are two versions of this function; one for POSIX
2550 // threads and one for Windows threads.
2552 #if !defined(_MSC_VER)
2554 void* init_thread(void *threadID) {
2556 TM.idle_loop(*(int*)threadID, NULL);
2562 DWORD WINAPI init_thread(LPVOID threadID) {
2564 TM.idle_loop(*(int*)threadID, NULL);
2571 /// The ThreadsManager class
2573 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2574 // get_beta_counters() are getters/setters for the per thread
2575 // counters used to sort the moves at root.
2577 void ThreadsManager::resetNodeCounters() {
2579 for (int i = 0; i < MAX_THREADS; i++)
2580 threads[i].nodes = 0ULL;
2583 void ThreadsManager::resetBetaCounters() {
2585 for (int i = 0; i < MAX_THREADS; i++)
2586 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2589 int64_t ThreadsManager::nodes_searched() const {
2591 int64_t result = 0ULL;
2592 for (int i = 0; i < ActiveThreads; i++)
2593 result += threads[i].nodes;
2598 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2601 for (int i = 0; i < MAX_THREADS; i++)
2603 our += threads[i].betaCutOffs[us];
2604 their += threads[i].betaCutOffs[opposite_color(us)];
2609 // idle_loop() is where the threads are parked when they have no work to do.
2610 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2611 // object for which the current thread is the master.
2613 void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2615 assert(threadID >= 0 && threadID < MAX_THREADS);
2619 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2620 // master should exit as last one.
2621 if (AllThreadsShouldExit)
2624 threads[threadID].state = THREAD_TERMINATED;
2628 // If we are not thinking, wait for a condition to be signaled
2629 // instead of wasting CPU time polling for work.
2630 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2633 assert(threadID != 0);
2634 threads[threadID].state = THREAD_SLEEPING;
2636 #if !defined(_MSC_VER)
2637 pthread_mutex_lock(&WaitLock);
2638 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2639 pthread_cond_wait(&WaitCond, &WaitLock);
2640 pthread_mutex_unlock(&WaitLock);
2642 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2646 // If thread has just woken up, mark it as available
2647 if (threads[threadID].state == THREAD_SLEEPING)
2648 threads[threadID].state = THREAD_AVAILABLE;
2650 // If this thread has been assigned work, launch a search
2651 if (threads[threadID].state == THREAD_WORKISWAITING)
2653 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2655 threads[threadID].state = THREAD_SEARCHING;
2657 if (threads[threadID].splitPoint->pvNode)
2658 sp_search_pv(threads[threadID].splitPoint, threadID);
2660 sp_search(threads[threadID].splitPoint, threadID);
2662 assert(threads[threadID].state == THREAD_SEARCHING);
2664 threads[threadID].state = THREAD_AVAILABLE;
2667 // If this thread is the master of a split point and all threads have
2668 // finished their work at this split point, return from the idle loop.
2669 if (waitSp != NULL && waitSp->cpus == 0)
2671 assert(threads[threadID].state == THREAD_AVAILABLE);
2673 threads[threadID].state = THREAD_SEARCHING;
2680 // init_threads() is called during startup. It launches all helper threads,
2681 // and initializes the split point stack and the global locks and condition
2684 void ThreadsManager::init_threads() {
2689 #if !defined(_MSC_VER)
2690 pthread_t pthread[1];
2693 // Initialize global locks
2694 lock_init(&MPLock, NULL);
2696 // Initialize SplitPointStack locks
2697 for (i = 0; i < MAX_THREADS; i++)
2698 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2700 SplitPointStack[i][j].parent = NULL;
2701 lock_init(&(SplitPointStack[i][j].lock), NULL);
2704 #if !defined(_MSC_VER)
2705 pthread_mutex_init(&WaitLock, NULL);
2706 pthread_cond_init(&WaitCond, NULL);
2708 for (i = 0; i < MAX_THREADS; i++)
2709 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2712 // Will be set just before program exits to properly end the threads
2713 AllThreadsShouldExit = false;
2715 // Threads will be put to sleep as soon as created
2716 AllThreadsShouldSleep = true;
2718 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2720 threads[0].state = THREAD_SEARCHING;
2721 for (i = 1; i < MAX_THREADS; i++)
2722 threads[i].state = THREAD_AVAILABLE;
2724 // Launch the helper threads
2725 for (i = 1; i < MAX_THREADS; i++)
2728 #if !defined(_MSC_VER)
2729 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2732 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
2737 cout << "Failed to create thread number " << i << endl;
2738 Application::exit_with_failure();
2741 // Wait until the thread has finished launching and is gone to sleep
2742 while (threads[i].state != THREAD_SLEEPING);
2747 // exit_threads() is called when the program exits. It makes all the
2748 // helper threads exit cleanly.
2750 void ThreadsManager::exit_threads() {
2752 ActiveThreads = MAX_THREADS; // HACK
2753 AllThreadsShouldSleep = true; // HACK
2754 wake_sleeping_threads();
2756 // This makes the threads to exit idle_loop()
2757 AllThreadsShouldExit = true;
2759 // Wait for thread termination
2760 for (int i = 1; i < MAX_THREADS; i++)
2761 while (threads[i].state != THREAD_TERMINATED);
2763 // Now we can safely destroy the locks
2764 for (int i = 0; i < MAX_THREADS; i++)
2765 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2766 lock_destroy(&(SplitPointStack[i][j].lock));
2770 // thread_should_stop() checks whether the thread should stop its search.
2771 // This can happen if a beta cutoff has occurred in the thread's currently
2772 // active split point, or in some ancestor of the current split point.
2774 bool ThreadsManager::thread_should_stop(int threadID) const {
2776 assert(threadID >= 0 && threadID < ActiveThreads);
2780 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent);
2785 // thread_is_available() checks whether the thread with threadID "slave" is
2786 // available to help the thread with threadID "master" at a split point. An
2787 // obvious requirement is that "slave" must be idle. With more than two
2788 // threads, this is not by itself sufficient: If "slave" is the master of
2789 // some active split point, it is only available as a slave to the other
2790 // threads which are busy searching the split point at the top of "slave"'s
2791 // split point stack (the "helpful master concept" in YBWC terminology).
2793 bool ThreadsManager::thread_is_available(int slave, int master) const {
2795 assert(slave >= 0 && slave < ActiveThreads);
2796 assert(master >= 0 && master < ActiveThreads);
2797 assert(ActiveThreads > 1);
2799 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2802 // Make a local copy to be sure doesn't change under our feet
2803 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2805 if (localActiveSplitPoints == 0)
2806 // No active split points means that the thread is available as
2807 // a slave for any other thread.
2810 if (ActiveThreads == 2)
2813 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2814 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2815 // could have been set to 0 by another thread leading to an out of bound access.
2816 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2823 // available_thread_exists() tries to find an idle thread which is available as
2824 // a slave for the thread with threadID "master".
2826 bool ThreadsManager::available_thread_exists(int master) const {
2828 assert(master >= 0 && master < ActiveThreads);
2829 assert(ActiveThreads > 1);
2831 for (int i = 0; i < ActiveThreads; i++)
2832 if (thread_is_available(i, master))
2839 // split() does the actual work of distributing the work at a node between
2840 // several threads at PV nodes. If it does not succeed in splitting the
2841 // node (because no idle threads are available, or because we have no unused
2842 // split point objects), the function immediately returns false. If
2843 // splitting is possible, a SplitPoint object is initialized with all the
2844 // data that must be copied to the helper threads (the current position and
2845 // search stack, alpha, beta, the search depth, etc.), and we tell our
2846 // helper threads that they have been assigned work. This will cause them
2847 // to instantly leave their idle loops and call sp_search_pv(). When all
2848 // threads have returned from sp_search_pv (or, equivalently, when
2849 // splitPoint->cpus becomes 0), split() returns true.
2851 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2852 Value* alpha, const Value beta, Value* bestValue,
2853 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2856 assert(sstck != NULL);
2857 assert(ply >= 0 && ply < PLY_MAX);
2858 assert(*bestValue >= -VALUE_INFINITE);
2859 assert( ( pvNode && *bestValue <= *alpha)
2860 || (!pvNode && *bestValue < beta ));
2861 assert(!pvNode || *alpha < beta);
2862 assert(beta <= VALUE_INFINITE);
2863 assert(depth > Depth(0));
2864 assert(master >= 0 && master < ActiveThreads);
2865 assert(ActiveThreads > 1);
2867 SplitPoint* splitPoint;
2871 // If no other thread is available to help us, or if we have too many
2872 // active split points, don't split.
2873 if ( !available_thread_exists(master)
2874 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2876 lock_release(&MPLock);
2880 // Pick the next available split point object from the split point stack
2881 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2883 // Initialize the split point object
2884 splitPoint->parent = threads[master].splitPoint;
2885 splitPoint->stopRequest = false;
2886 splitPoint->ply = ply;
2887 splitPoint->depth = depth;
2888 splitPoint->alpha = pvNode ? *alpha : beta - 1;
2889 splitPoint->beta = beta;
2890 splitPoint->pvNode = pvNode;
2891 splitPoint->bestValue = *bestValue;
2892 splitPoint->master = master;
2893 splitPoint->mp = mp;
2894 splitPoint->moves = *moves;
2895 splitPoint->cpus = 1;
2896 splitPoint->pos = &p;
2897 splitPoint->parentSstack = sstck;
2898 for (int i = 0; i < ActiveThreads; i++)
2899 splitPoint->slaves[i] = 0;
2901 threads[master].splitPoint = splitPoint;
2902 threads[master].activeSplitPoints++;
2904 // If we are here it means we are not available
2905 assert(threads[master].state != THREAD_AVAILABLE);
2907 // Allocate available threads setting state to THREAD_BOOKED
2908 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2909 if (thread_is_available(i, master))
2911 threads[i].state = THREAD_BOOKED;
2912 threads[i].splitPoint = splitPoint;
2913 splitPoint->slaves[i] = 1;
2917 assert(splitPoint->cpus > 1);
2919 // We can release the lock because slave threads are already booked and master is not available
2920 lock_release(&MPLock);
2922 // Tell the threads that they have work to do. This will make them leave
2923 // their idle loop. But before copy search stack tail for each thread.
2924 for (int i = 0; i < ActiveThreads; i++)
2925 if (i == master || splitPoint->slaves[i])
2927 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2929 assert(i == master || threads[i].state == THREAD_BOOKED);
2931 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2934 // Everything is set up. The master thread enters the idle loop, from
2935 // which it will instantly launch a search, because its state is
2936 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2937 // idle loop, which means that the main thread will return from the idle
2938 // loop when all threads have finished their work at this split point
2939 // (i.e. when splitPoint->cpus == 0).
2940 idle_loop(master, splitPoint);
2942 // We have returned from the idle loop, which means that all threads are
2943 // finished. Update alpha, beta and bestValue, and return.
2947 *alpha = splitPoint->alpha;
2949 *bestValue = splitPoint->bestValue;
2950 threads[master].activeSplitPoints--;
2951 threads[master].splitPoint = splitPoint->parent;
2953 lock_release(&MPLock);
2958 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2959 // to start a new search from the root.
2961 void ThreadsManager::wake_sleeping_threads() {
2963 assert(AllThreadsShouldSleep);
2964 assert(ActiveThreads > 0);
2966 AllThreadsShouldSleep = false;
2968 if (ActiveThreads == 1)
2971 for (int i = 1; i < ActiveThreads; i++)
2972 assert(threads[i].state == THREAD_SLEEPING);
2974 #if !defined(_MSC_VER)
2975 pthread_mutex_lock(&WaitLock);
2976 pthread_cond_broadcast(&WaitCond);
2977 pthread_mutex_unlock(&WaitLock);
2979 for (int i = 1; i < MAX_THREADS; i++)
2980 SetEvent(SitIdleEvent[i]);
2986 // put_threads_to_sleep() makes all the threads go to sleep just before
2987 // to leave think(), at the end of the search. Threads should have already
2988 // finished the job and should be idle.
2990 void ThreadsManager::put_threads_to_sleep() {
2992 assert(!AllThreadsShouldSleep);
2994 // This makes the threads to go to sleep
2995 AllThreadsShouldSleep = true;
2998 /// The RootMoveList class
3000 // RootMoveList c'tor
3002 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3004 SearchStack ss[PLY_MAX_PLUS_2];
3005 MoveStack mlist[MaxRootMoves];
3007 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3009 // Generate all legal moves
3010 MoveStack* last = generate_moves(pos, mlist);
3012 // Add each move to the moves[] array
3013 for (MoveStack* cur = mlist; cur != last; cur++)
3015 bool includeMove = includeAllMoves;
3017 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3018 includeMove = (searchMoves[k] == cur->move);
3023 // Find a quick score for the move
3025 pos.do_move(cur->move, st);
3026 moves[count].move = cur->move;
3027 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3028 moves[count].pv[0] = cur->move;
3029 moves[count].pv[1] = MOVE_NONE;
3030 pos.undo_move(cur->move);
3037 // RootMoveList simple methods definitions
3039 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3041 moves[moveNum].nodes = nodes;
3042 moves[moveNum].cumulativeNodes += nodes;
3045 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3047 moves[moveNum].ourBeta = our;
3048 moves[moveNum].theirBeta = their;
3051 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3055 for (j = 0; pv[j] != MOVE_NONE; j++)
3056 moves[moveNum].pv[j] = pv[j];
3058 moves[moveNum].pv[j] = MOVE_NONE;
3062 // RootMoveList::sort() sorts the root move list at the beginning of a new
3065 void RootMoveList::sort() {
3067 sort_multipv(count - 1); // Sort all items
3071 // RootMoveList::sort_multipv() sorts the first few moves in the root move
3072 // list by their scores and depths. It is used to order the different PVs
3073 // correctly in MultiPV mode.
3075 void RootMoveList::sort_multipv(int n) {
3079 for (i = 1; i <= n; i++)
3081 RootMove rm = moves[i];
3082 for (j = i; j > 0 && moves[j - 1] < rm; j--)
3083 moves[j] = moves[j - 1];