2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2009 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
43 #include "ucioption.h"
49 //// Local definitions
57 // ThreadsManager class is used to handle all the threads related stuff in search,
58 // init, starting, parking and, the most important, launching a slave thread at a
59 // split point are what this class does. All the access to shared thread data is
60 // done through this class, so that we avoid using global variables instead.
62 class ThreadsManager {
63 /* As long as the single ThreadsManager object is defined as a global we don't
64 need to explicitly initialize to zero its data members because variables with
65 static storage duration are automatically set to zero before enter main()
71 int active_threads() const { return ActiveThreads; }
72 void set_active_threads(int newActiveThreads) { ActiveThreads = newActiveThreads; }
73 void incrementNodeCounter(int threadID) { threads[threadID].nodes++; }
74 void incrementBetaCounter(Color us, Depth d, int threadID) { threads[threadID].betaCutOffs[us] += unsigned(d); }
76 void resetNodeCounters();
77 void resetBetaCounters();
78 int64_t nodes_searched() const;
79 void get_beta_counters(Color us, int64_t& our, int64_t& their) const;
80 bool available_thread_exists(int master) const;
81 bool thread_is_available(int slave, int master) const;
82 bool thread_should_stop(int threadID) const;
83 void wake_sleeping_threads();
84 void put_threads_to_sleep();
85 void idle_loop(int threadID, SplitPoint* waitSp);
86 bool split(const Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
87 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode);
90 friend void poll(SearchStack ss[], int ply);
93 volatile bool AllThreadsShouldExit, AllThreadsShouldSleep;
94 Thread threads[MAX_THREADS];
95 SplitPoint SplitPointStack[MAX_THREADS][ACTIVE_SPLIT_POINTS_MAX];
99 #if !defined(_MSC_VER)
100 pthread_cond_t WaitCond;
101 pthread_mutex_t WaitLock;
103 HANDLE SitIdleEvent[MAX_THREADS];
109 // RootMove struct is used for moves at the root at the tree. For each
110 // root move, we store a score, a node count, and a PV (really a refutation
111 // in the case of moves which fail low).
115 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
117 // RootMove::operator<() is the comparison function used when
118 // sorting the moves. A move m1 is considered to be better
119 // than a move m2 if it has a higher score, or if the moves
120 // have equal score but m1 has the higher node count.
121 bool operator<(const RootMove& m) const {
123 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
128 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
129 Move pv[PLY_MAX_PLUS_2];
133 // The RootMoveList class is essentially an array of RootMove objects, with
134 // a handful of methods for accessing the data in the individual moves.
139 RootMoveList(Position& pos, Move searchMoves[]);
141 int move_count() const { return count; }
142 Move get_move(int moveNum) const { return moves[moveNum].move; }
143 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
144 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
145 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
146 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
148 void set_move_nodes(int moveNum, int64_t nodes);
149 void set_beta_counters(int moveNum, int64_t our, int64_t their);
150 void set_move_pv(int moveNum, const Move pv[]);
152 void sort_multipv(int n);
155 static const int MaxRootMoves = 500;
156 RootMove moves[MaxRootMoves];
165 const Depth RazorDepth = 4 * OnePly;
166 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * d); }
168 // Step 8. Null move search with verification search
170 // Null move margin. A null move search will not be done if the static
171 // evaluation of the position is more than NullMoveMargin below beta.
172 const Value NullMoveMargin = Value(0x200);
174 // Step 9. Internal iterative deepening
176 const Depth IIDDepthAtPVNodes = 5 * OnePly;
177 const Depth IIDDepthAtNonPVNodes = 8 * OnePly;
179 // Internal iterative deepening margin. At Non-PV nodes
180 // we do an internal iterative deepening
181 // search when the static evaluation is at most IIDMargin below beta.
182 const Value IIDMargin = Value(0x100);
184 // Search depth at iteration 1
185 const Depth InitialDepth = OnePly;
187 // Easy move margin. An easy move candidate must be at least this much
188 // better than the second best move.
189 const Value EasyMoveMargin = Value(0x200);
191 // If the TT move is at least SingleReplyMargin better then the
192 // remaining ones we will extend it.
193 const Value SingleReplyMargin = Value(0x20);
195 /// Lookup tables initialized at startup
197 // Reduction lookup tables and their getter functions
198 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
199 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
201 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
202 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
204 // Futility lookup tables and their getter functions
205 const Value FutilityMarginQS = Value(0x80);
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 /// Variables initialized by UCI options
214 // Depth limit for use of dynamic threat detection
217 // Last seconds noise filtering (LSN)
218 const bool UseLSNFiltering = true;
219 const int LSNTime = 4000; // In milliseconds
220 const Value LSNValue = value_from_centipawns(200);
221 bool loseOnTime = false;
223 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
224 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
225 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
227 // Iteration counters
230 // Scores and number of times the best move changed for each iteration
231 Value ValueByIteration[PLY_MAX_PLUS_2];
232 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
234 // Search window management
240 // Time managment variables
243 int MaxNodes, MaxDepth;
244 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
245 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
246 bool AbortSearch, Quit;
247 bool AspirationFailLow;
249 // Show current line?
250 bool ShowCurrentLine;
254 std::ofstream LogFile;
256 // MP related variables
257 Depth MinimumSplitDepth;
258 int MaxThreadsPerSplitPoint;
261 // Node counters, used only by thread[0] but try to keep in different
262 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
264 int NodesBetweenPolls = 30000;
271 Value id_loop(const Position& pos, Move searchMoves[]);
272 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
273 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
274 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
275 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
276 void sp_search(SplitPoint* sp, int threadID);
277 void sp_search_pv(SplitPoint* sp, int threadID);
278 void init_node(SearchStack ss[], int ply, int threadID);
279 void update_pv(SearchStack ss[], int ply);
280 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
281 bool connected_moves(const Position& pos, Move m1, Move m2);
282 bool value_is_mate(Value value);
283 bool move_is_killer(Move m, const SearchStack& ss);
284 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
285 bool ok_to_do_nullmove(const Position& pos);
286 bool ok_to_prune(const Position& pos, Move m, Move threat);
287 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
288 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
289 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
290 void update_killers(Move m, SearchStack& ss);
291 void update_gains(const Position& pos, Move move, Value before, Value after);
293 int current_search_time();
295 void poll(SearchStack ss[], int ply);
297 void wait_for_stop_or_ponderhit();
298 void init_ss_array(SearchStack ss[]);
300 #if !defined(_MSC_VER)
301 void *init_thread(void *threadID);
303 DWORD WINAPI init_thread(LPVOID threadID);
313 /// init_threads(), exit_threads() and nodes_searched() are helpers to
314 /// give accessibility to some TM methods from outside of current file.
316 void init_threads() { TM.init_threads(); }
317 void exit_threads() { TM.exit_threads(); }
318 int64_t nodes_searched() { return TM.nodes_searched(); }
321 /// perft() is our utility to verify move generation is bug free. All the legal
322 /// moves up to given depth are generated and counted and the sum returned.
324 int perft(Position& pos, Depth depth)
328 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
330 // If we are at the last ply we don't need to do and undo
331 // the moves, just to count them.
332 if (depth <= OnePly) // Replace with '<' to test also qsearch
334 while (mp.get_next_move()) sum++;
338 // Loop through all legal moves
340 while ((move = mp.get_next_move()) != MOVE_NONE)
343 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
344 sum += perft(pos, depth - OnePly);
351 /// think() is the external interface to Stockfish's search, and is called when
352 /// the program receives the UCI 'go' command. It initializes various
353 /// search-related global variables, and calls root_search(). It returns false
354 /// when a quit command is received during the search.
356 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
357 int time[], int increment[], int movesToGo, int maxDepth,
358 int maxNodes, int maxTime, Move searchMoves[]) {
360 // Initialize global search variables
361 StopOnPonderhit = AbortSearch = Quit = false;
362 AspirationFailLow = false;
364 SearchStartTime = get_system_time();
365 ExactMaxTime = maxTime;
368 InfiniteSearch = infinite;
369 PonderSearch = ponder;
370 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
372 // Look for a book move, only during games, not tests
373 if (UseTimeManagement && get_option_value_bool("OwnBook"))
376 if (get_option_value_string("Book File") != OpeningBook.file_name())
377 OpeningBook.open(get_option_value_string("Book File"));
379 bookMove = OpeningBook.get_move(pos);
380 if (bookMove != MOVE_NONE)
383 wait_for_stop_or_ponderhit();
385 cout << "bestmove " << bookMove << endl;
390 TM.resetNodeCounters();
392 if (button_was_pressed("New Game"))
393 loseOnTime = false; // Reset at the beginning of a new game
395 // Read UCI option values
396 TT.set_size(get_option_value_int("Hash"));
397 if (button_was_pressed("Clear Hash"))
400 bool PonderingEnabled = get_option_value_bool("Ponder");
401 MultiPV = get_option_value_int("MultiPV");
403 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
404 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
406 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
407 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
409 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
410 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
412 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
413 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
415 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
416 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
418 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
419 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
421 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
423 Chess960 = get_option_value_bool("UCI_Chess960");
424 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
425 UseLogFile = get_option_value_bool("Use Search Log");
427 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
429 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
430 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
432 read_weights(pos.side_to_move());
434 // Set the number of active threads
435 int newActiveThreads = get_option_value_int("Threads");
436 if (newActiveThreads != TM.active_threads())
438 TM.set_active_threads(newActiveThreads);
439 init_eval(TM.active_threads());
440 // HACK: init_eval() destroys the static castleRightsMask[] array in the
441 // Position class. The below line repairs the damage.
442 Position p(pos.to_fen());
446 // Wake up sleeping threads
447 TM.wake_sleeping_threads();
450 int myTime = time[side_to_move];
451 int myIncrement = increment[side_to_move];
452 if (UseTimeManagement)
454 if (!movesToGo) // Sudden death time control
458 MaxSearchTime = myTime / 30 + myIncrement;
459 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
461 else // Blitz game without increment
463 MaxSearchTime = myTime / 30;
464 AbsoluteMaxSearchTime = myTime / 8;
467 else // (x moves) / (y minutes)
471 MaxSearchTime = myTime / 2;
472 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
476 MaxSearchTime = myTime / Min(movesToGo, 20);
477 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
481 if (PonderingEnabled)
483 MaxSearchTime += MaxSearchTime / 4;
484 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
488 // Set best NodesBetweenPolls interval
490 NodesBetweenPolls = Min(MaxNodes, 30000);
491 else if (myTime && myTime < 1000)
492 NodesBetweenPolls = 1000;
493 else if (myTime && myTime < 5000)
494 NodesBetweenPolls = 5000;
496 NodesBetweenPolls = 30000;
498 // Write information to search log file
500 LogFile << "Searching: " << pos.to_fen() << endl
501 << "infinite: " << infinite
502 << " ponder: " << ponder
503 << " time: " << myTime
504 << " increment: " << myIncrement
505 << " moves to go: " << movesToGo << endl;
507 // LSN filtering. Used only for developing purpose. Disabled by default.
511 // Step 2. If after last move we decided to lose on time, do it now!
512 while (SearchStartTime + myTime + 1000 > get_system_time())
516 // We're ready to start thinking. Call the iterative deepening loop function
517 Value v = id_loop(pos, searchMoves);
521 // Step 1. If this is sudden death game and our position is hopeless,
522 // decide to lose on time.
523 if ( !loseOnTime // If we already lost on time, go to step 3.
533 // Step 3. Now after stepping over the time limit, reset flag for next match.
541 TM.put_threads_to_sleep();
547 /// init_search() is called during startup. It initializes various lookup tables
551 // Init our reduction lookup tables
552 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
553 for (int j = 1; j < 64; j++) // j == moveNumber
555 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
556 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
557 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
558 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
561 // Init futility margins array
562 for (int i = 0; i < 14; i++) // i == depth (OnePly = 2)
563 for (int j = 0; j < 64; j++) // j == moveNumber
565 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
568 // Init futility move count array
569 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
570 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
574 // SearchStack::init() initializes a search stack. Used at the beginning of a
575 // new search from the root.
576 void SearchStack::init(int ply) {
578 pv[ply] = pv[ply + 1] = MOVE_NONE;
579 currentMove = threatMove = MOVE_NONE;
580 reduction = Depth(0);
584 void SearchStack::initKillers() {
586 mateKiller = MOVE_NONE;
587 for (int i = 0; i < KILLER_MAX; i++)
588 killers[i] = MOVE_NONE;
593 // id_loop() is the main iterative deepening loop. It calls root_search
594 // repeatedly with increasing depth until the allocated thinking time has
595 // been consumed, the user stops the search, or the maximum search depth is
598 Value id_loop(const Position& pos, Move searchMoves[]) {
601 SearchStack ss[PLY_MAX_PLUS_2];
603 // searchMoves are verified, copied, scored and sorted
604 RootMoveList rml(p, searchMoves);
606 // Handle special case of searching on a mate/stale position
607 if (rml.move_count() == 0)
610 wait_for_stop_or_ponderhit();
612 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
615 // Print RootMoveList c'tor startup scoring to the standard output,
616 // so that we print information also for iteration 1.
617 cout << "info depth " << 1 << "\ninfo depth " << 1
618 << " score " << value_to_string(rml.get_move_score(0))
619 << " time " << current_search_time()
620 << " nodes " << TM.nodes_searched()
622 << " pv " << rml.get_move(0) << "\n";
628 ValueByIteration[1] = rml.get_move_score(0);
631 // Is one move significantly better than others after initial scoring ?
632 Move EasyMove = MOVE_NONE;
633 if ( rml.move_count() == 1
634 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
635 EasyMove = rml.get_move(0);
637 // Iterative deepening loop
638 while (Iteration < PLY_MAX)
640 // Initialize iteration
643 BestMoveChangesByIteration[Iteration] = 0;
647 cout << "info depth " << Iteration << endl;
649 // Calculate dynamic search window based on previous iterations
652 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
654 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
655 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
657 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
658 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
660 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
661 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
665 alpha = - VALUE_INFINITE;
666 beta = VALUE_INFINITE;
669 // Search to the current depth
670 Value value = root_search(p, ss, rml, alpha, beta);
672 // Write PV to transposition table, in case the relevant entries have
673 // been overwritten during the search.
674 TT.insert_pv(p, ss[0].pv);
677 break; // Value cannot be trusted. Break out immediately!
679 //Save info about search result
680 ValueByIteration[Iteration] = value;
682 // Drop the easy move if it differs from the new best move
683 if (ss[0].pv[0] != EasyMove)
684 EasyMove = MOVE_NONE;
686 if (UseTimeManagement)
689 bool stopSearch = false;
691 // Stop search early if there is only a single legal move,
692 // we search up to Iteration 6 anyway to get a proper score.
693 if (Iteration >= 6 && rml.move_count() == 1)
696 // Stop search early when the last two iterations returned a mate score
698 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
699 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
702 // Stop search early if one move seems to be much better than the rest
703 int64_t nodes = TM.nodes_searched();
705 && EasyMove == ss[0].pv[0]
706 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
707 && current_search_time() > MaxSearchTime / 16)
708 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
709 && current_search_time() > MaxSearchTime / 32)))
712 // Add some extra time if the best move has changed during the last two iterations
713 if (Iteration > 5 && Iteration <= 50)
714 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
715 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
717 // Stop search if most of MaxSearchTime is consumed at the end of the
718 // iteration. We probably don't have enough time to search the first
719 // move at the next iteration anyway.
720 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
728 StopOnPonderhit = true;
732 if (MaxDepth && Iteration >= MaxDepth)
738 // If we are pondering or in infinite search, we shouldn't print the
739 // best move before we are told to do so.
740 if (!AbortSearch && (PonderSearch || InfiniteSearch))
741 wait_for_stop_or_ponderhit();
743 // Print final search statistics
744 cout << "info nodes " << TM.nodes_searched()
746 << " time " << current_search_time()
747 << " hashfull " << TT.full() << endl;
749 // Print the best move and the ponder move to the standard output
750 if (ss[0].pv[0] == MOVE_NONE)
752 ss[0].pv[0] = rml.get_move(0);
753 ss[0].pv[1] = MOVE_NONE;
755 cout << "bestmove " << ss[0].pv[0];
756 if (ss[0].pv[1] != MOVE_NONE)
757 cout << " ponder " << ss[0].pv[1];
764 dbg_print_mean(LogFile);
766 if (dbg_show_hit_rate)
767 dbg_print_hit_rate(LogFile);
769 LogFile << "\nNodes: " << TM.nodes_searched()
770 << "\nNodes/second: " << nps()
771 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
774 p.do_move(ss[0].pv[0], st);
775 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
777 return rml.get_move_score(0);
781 // root_search() is the function which searches the root node. It is
782 // similar to search_pv except that it uses a different move ordering
783 // scheme and prints some information to the standard output.
785 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
790 Depth depth, ext, newDepth;
793 int researchCount = 0;
794 bool moveIsCheck, captureOrPromotion, dangerous;
795 Value alpha = oldAlpha;
796 bool isCheck = pos.is_check();
798 // Evaluate the position statically
800 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
802 while (1) // Fail low loop
805 // Loop through all the moves in the root move list
806 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
810 // We failed high, invalidate and skip next moves, leave node-counters
811 // and beta-counters as they are and quickly return, we will try to do
812 // a research at the next iteration with a bigger aspiration window.
813 rml.set_move_score(i, -VALUE_INFINITE);
817 RootMoveNumber = i + 1;
819 // Save the current node count before the move is searched
820 nodes = TM.nodes_searched();
822 // Reset beta cut-off counters
823 TM.resetBetaCounters();
825 // Pick the next root move, and print the move and the move number to
826 // the standard output.
827 move = ss[0].currentMove = rml.get_move(i);
829 if (current_search_time() >= 1000)
830 cout << "info currmove " << move
831 << " currmovenumber " << RootMoveNumber << endl;
833 // Decide search depth for this move
834 moveIsCheck = pos.move_is_check(move);
835 captureOrPromotion = pos.move_is_capture_or_promotion(move);
836 depth = (Iteration - 2) * OnePly + InitialDepth;
837 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
838 newDepth = depth + ext;
840 value = - VALUE_INFINITE;
842 while (1) // Fail high loop
845 // Make the move, and search it
846 pos.do_move(move, st, ci, moveIsCheck);
848 if (i < MultiPV || value > alpha)
850 // Aspiration window is disabled in multi-pv case
852 alpha = -VALUE_INFINITE;
854 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
858 // Try to reduce non-pv search depth by one ply if move seems not problematic,
859 // if the move fails high will be re-searched at full depth.
860 bool doFullDepthSearch = true;
862 if ( depth >= 3*OnePly // FIXME was newDepth
864 && !captureOrPromotion
865 && !move_is_castle(move))
867 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
870 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
871 doFullDepthSearch = (value > alpha);
875 if (doFullDepthSearch)
877 ss[0].reduction = Depth(0);
878 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
881 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
887 // Can we exit fail high loop ?
888 if (AbortSearch || value < beta)
891 // We are failing high and going to do a research. It's important to update score
892 // before research in case we run out of time while researching.
893 rml.set_move_score(i, value);
895 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
896 rml.set_move_pv(i, ss[0].pv);
898 // Print search information to the standard output
899 cout << "info depth " << Iteration
900 << " score " << value_to_string(value)
901 << ((value >= beta) ? " lowerbound" :
902 ((value <= alpha)? " upperbound" : ""))
903 << " time " << current_search_time()
904 << " nodes " << TM.nodes_searched()
908 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
909 cout << ss[0].pv[j] << " ";
915 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
916 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
918 LogFile << pretty_pv(pos, current_search_time(), Iteration,
919 TM.nodes_searched(), value, type, ss[0].pv) << endl;
922 // Prepare for a research after a fail high, each time with a wider window
924 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
926 } // End of fail high loop
928 // Finished searching the move. If AbortSearch is true, the search
929 // was aborted because the user interrupted the search or because we
930 // ran out of time. In this case, the return value of the search cannot
931 // be trusted, and we break out of the loop without updating the best
936 // Remember beta-cutoff and searched nodes counts for this move. The
937 // info is used to sort the root moves at the next iteration.
939 TM.get_beta_counters(pos.side_to_move(), our, their);
940 rml.set_beta_counters(i, our, their);
941 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
943 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
945 if (value <= alpha && i >= MultiPV)
946 rml.set_move_score(i, -VALUE_INFINITE);
949 // PV move or new best move!
952 rml.set_move_score(i, value);
954 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
955 rml.set_move_pv(i, ss[0].pv);
959 // We record how often the best move has been changed in each
960 // iteration. This information is used for time managment: When
961 // the best move changes frequently, we allocate some more time.
963 BestMoveChangesByIteration[Iteration]++;
965 // Print search information to the standard output
966 cout << "info depth " << Iteration
967 << " score " << value_to_string(value)
968 << ((value >= beta) ? " lowerbound" :
969 ((value <= alpha)? " upperbound" : ""))
970 << " time " << current_search_time()
971 << " nodes " << TM.nodes_searched()
975 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
976 cout << ss[0].pv[j] << " ";
982 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
983 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
985 LogFile << pretty_pv(pos, current_search_time(), Iteration,
986 TM.nodes_searched(), value, type, ss[0].pv) << endl;
994 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
996 cout << "info multipv " << j + 1
997 << " score " << value_to_string(rml.get_move_score(j))
998 << " depth " << ((j <= i)? Iteration : Iteration - 1)
999 << " time " << current_search_time()
1000 << " nodes " << TM.nodes_searched()
1004 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1005 cout << rml.get_move_pv(j, k) << " ";
1009 alpha = rml.get_move_score(Min(i, MultiPV-1));
1011 } // PV move or new best move
1013 assert(alpha >= oldAlpha);
1015 AspirationFailLow = (alpha == oldAlpha);
1017 if (AspirationFailLow && StopOnPonderhit)
1018 StopOnPonderhit = false;
1021 // Can we exit fail low loop ?
1022 if (AbortSearch || alpha > oldAlpha)
1025 // Prepare for a research after a fail low, each time with a wider window
1027 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1036 // search_pv() is the main search function for PV nodes.
1038 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1039 Depth depth, int ply, int threadID) {
1041 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1042 assert(beta > alpha && beta <= VALUE_INFINITE);
1043 assert(ply >= 0 && ply < PLY_MAX);
1044 assert(threadID >= 0 && threadID < TM.active_threads());
1046 Move movesSearched[256];
1051 Depth ext, newDepth;
1052 Value bestValue, value, oldAlpha;
1053 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1054 bool mateThreat = false;
1056 bestValue = value = -VALUE_INFINITE;
1059 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1061 // Step 1. Initialize node and poll
1062 // Polling can abort search.
1063 init_node(ss, ply, threadID);
1065 // Step 2. Check for aborted search and immediate draw
1066 if (AbortSearch || TM.thread_should_stop(threadID))
1069 if (pos.is_draw() || ply >= PLY_MAX - 1)
1072 // Step 3. Mate distance pruning
1074 alpha = Max(value_mated_in(ply), alpha);
1075 beta = Min(value_mate_in(ply+1), beta);
1079 // Step 4. Transposition table lookup
1080 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1081 // This is to avoid problems in the following areas:
1083 // * Repetition draw detection
1084 // * Fifty move rule detection
1085 // * Searching for a mate
1086 // * Printing of full PV line
1087 tte = TT.retrieve(pos.get_key());
1088 ttMove = (tte ? tte->move() : MOVE_NONE);
1090 // Step 5. Evaluate the position statically
1091 // At PV nodes we do this only to update gain statistics
1092 isCheck = pos.is_check();
1095 ss[ply].eval = evaluate(pos, ei, threadID);
1096 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1099 // Step 6. Razoring (is omitted in PV nodes)
1100 // Step 7. Static null move pruning (is omitted in PV nodes)
1101 // Step 8. Null move search with verification search (is omitted in PV nodes)
1103 // Step 9. Internal iterative deepening
1104 if ( depth >= IIDDepthAtPVNodes
1105 && ttMove == MOVE_NONE)
1107 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1108 ttMove = ss[ply].pv[ply];
1109 tte = TT.retrieve(pos.get_key());
1112 // Step 10. Loop through moves
1113 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1115 // Initialize a MovePicker object for the current position
1116 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1117 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1120 while ( alpha < beta
1121 && (move = mp.get_next_move()) != MOVE_NONE
1122 && !TM.thread_should_stop(threadID))
1124 assert(move_is_ok(move));
1126 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1127 moveIsCheck = pos.move_is_check(move, ci);
1128 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1130 // Step 11. Decide the new search depth
1131 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1133 // Singular extension search. We extend the TT move if its value is much better than
1134 // its siblings. To verify this we do a reduced search on all the other moves but the
1135 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1136 if ( depth >= 6 * OnePly
1138 && move == tte->move()
1140 && is_lower_bound(tte->type())
1141 && tte->depth() >= depth - 3 * OnePly)
1143 Value ttValue = value_from_tt(tte->value(), ply);
1145 if (abs(ttValue) < VALUE_KNOWN_WIN)
1147 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1149 if (excValue < ttValue - SingleReplyMargin)
1154 newDepth = depth - OnePly + ext;
1156 // Update current move (this must be done after singular extension search)
1157 movesSearched[moveCount++] = ss[ply].currentMove = move;
1159 // Step 12. Futility pruning (is omitted in PV nodes)
1161 // Step 13. Make the move
1162 pos.do_move(move, st, ci, moveIsCheck);
1164 // Step extra. pv search (only in PV nodes)
1165 // The first move in list is the expected PV
1167 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1170 // Step 14. Reduced search
1171 // if the move fails high will be re-searched at full depth.
1172 bool doFullDepthSearch = true;
1174 if ( depth >= 3*OnePly
1176 && !captureOrPromotion
1177 && !move_is_castle(move)
1178 && !move_is_killer(move, ss[ply]))
1180 ss[ply].reduction = pv_reduction(depth, moveCount);
1181 if (ss[ply].reduction)
1183 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1184 doFullDepthSearch = (value > alpha);
1188 // Step 15. Full depth search
1189 if (doFullDepthSearch)
1191 ss[ply].reduction = Depth(0);
1192 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1194 // Step extra. pv search (only in PV nodes)
1195 if (value > alpha && value < beta)
1196 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1200 // Step 16. Undo move
1201 pos.undo_move(move);
1203 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1205 // Step 17. Check for new best move
1206 if (value > bestValue)
1213 if (value == value_mate_in(ply + 1))
1214 ss[ply].mateKiller = move;
1218 // Step 18. Check for split
1219 if ( TM.active_threads() > 1
1221 && depth >= MinimumSplitDepth
1223 && TM.available_thread_exists(threadID)
1225 && !TM.thread_should_stop(threadID)
1226 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1227 depth, &moveCount, &mp, threadID, true))
1231 // Step 19. Check for mate and stalemate
1232 // All legal moves have been searched and if there were
1233 // no legal moves, it must be mate or stalemate.
1235 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1237 // Step 20. Update tables
1238 // If the search is not aborted, update the transposition table,
1239 // history counters, and killer moves.
1240 if (AbortSearch || TM.thread_should_stop(threadID))
1243 if (bestValue <= oldAlpha)
1244 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1246 else if (bestValue >= beta)
1248 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1249 move = ss[ply].pv[ply];
1250 if (!pos.move_is_capture_or_promotion(move))
1252 update_history(pos, move, depth, movesSearched, moveCount);
1253 update_killers(move, ss[ply]);
1255 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1258 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1264 // search() is the search function for zero-width nodes.
1266 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1267 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1269 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1270 assert(ply >= 0 && ply < PLY_MAX);
1271 assert(threadID >= 0 && threadID < TM.active_threads());
1273 Move movesSearched[256];
1278 Depth ext, newDepth;
1279 Value bestValue, refinedValue, nullValue, value, futilityValueScaled;
1280 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1281 bool mateThreat = false;
1283 refinedValue = bestValue = value = -VALUE_INFINITE;
1286 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1288 // Step 1. Initialize node and poll
1289 // Polling can abort search.
1290 init_node(ss, ply, threadID);
1292 // Step 2. Check for aborted search and immediate draw
1293 if (AbortSearch || TM.thread_should_stop(threadID))
1296 if (pos.is_draw() || ply >= PLY_MAX - 1)
1299 // Step 3. Mate distance pruning
1300 if (value_mated_in(ply) >= beta)
1303 if (value_mate_in(ply + 1) < beta)
1306 // Step 4. Transposition table lookup
1308 // We don't want the score of a partial search to overwrite a previous full search
1309 // TT value, so we use a different position key in case of an excluded move exists.
1310 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1312 tte = TT.retrieve(posKey);
1313 ttMove = (tte ? tte->move() : MOVE_NONE);
1315 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1317 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1318 return value_from_tt(tte->value(), ply);
1321 // Step 5. Evaluate the position statically
1322 isCheck = pos.is_check();
1326 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1327 ss[ply].eval = value_from_tt(tte->value(), ply);
1329 ss[ply].eval = evaluate(pos, ei, threadID);
1331 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1332 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1336 if ( !value_is_mate(beta)
1338 && depth < RazorDepth
1339 && refinedValue < beta - razor_margin(depth)
1340 && ss[ply - 1].currentMove != MOVE_NULL
1341 && ttMove == MOVE_NONE
1342 && !pos.has_pawn_on_7th(pos.side_to_move()))
1344 Value rbeta = beta - razor_margin(depth);
1345 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1347 return v; //FIXME: Logically should be: return (v + razor_margin(depth));
1350 // Step 7. Static null move pruning
1351 // We're betting that the opponent doesn't have a move that will reduce
1352 // the score by more than fuility_margin(depth) if we do a null move.
1355 && depth < RazorDepth
1356 && refinedValue - futility_margin(depth, 0) >= beta)
1357 return refinedValue - futility_margin(depth, 0);
1359 // Step 8. Null move search with verification search
1360 // When we jump directly to qsearch() we do a null move only if static value is
1361 // at least beta. Otherwise we do a null move if static value is not more than
1362 // NullMoveMargin under beta.
1366 && !value_is_mate(beta)
1367 && ok_to_do_nullmove(pos)
1368 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1370 ss[ply].currentMove = MOVE_NULL;
1372 pos.do_null_move(st);
1374 // Null move dynamic reduction based on depth
1375 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1377 // Null move dynamic reduction based on value
1378 if (refinedValue - beta > PawnValueMidgame)
1381 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1383 pos.undo_null_move();
1385 if (nullValue >= beta)
1387 if (depth < 6 * OnePly)
1390 // Do zugzwang verification search
1391 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1395 // The null move failed low, which means that we may be faced with
1396 // some kind of threat. If the previous move was reduced, check if
1397 // the move that refuted the null move was somehow connected to the
1398 // move which was reduced. If a connection is found, return a fail
1399 // low score (which will cause the reduced move to fail high in the
1400 // parent node, which will trigger a re-search with full depth).
1401 if (nullValue == value_mated_in(ply + 2))
1404 ss[ply].threatMove = ss[ply + 1].currentMove;
1405 if ( depth < ThreatDepth
1406 && ss[ply - 1].reduction
1407 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1412 // Step 9. Internal iterative deepening
1413 if ( depth >= IIDDepthAtNonPVNodes
1414 && ttMove == MOVE_NONE
1416 && ss[ply].eval >= beta - IIDMargin)
1418 search(pos, ss, beta, depth/2, ply, false, threadID);
1419 ttMove = ss[ply].pv[ply];
1420 tte = TT.retrieve(posKey);
1423 // Step 10. Loop through moves
1424 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1426 // Initialize a MovePicker object for the current position
1427 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1430 while ( bestValue < beta
1431 && (move = mp.get_next_move()) != MOVE_NONE
1432 && !TM.thread_should_stop(threadID))
1434 assert(move_is_ok(move));
1436 if (move == excludedMove)
1439 moveIsCheck = pos.move_is_check(move, ci);
1440 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1441 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1443 // Step 11. Decide the new search depth
1444 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1446 // Singular extension search. We extend the TT move if its value is much better than
1447 // its siblings. To verify this we do a reduced search on all the other moves but the
1448 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1449 if ( depth >= 8 * OnePly
1451 && move == tte->move()
1452 && !excludedMove // Do not allow recursive single-reply search
1454 && is_lower_bound(tte->type())
1455 && tte->depth() >= depth - 3 * OnePly)
1457 Value ttValue = value_from_tt(tte->value(), ply);
1459 if (abs(ttValue) < VALUE_KNOWN_WIN)
1461 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1463 if (excValue < ttValue - SingleReplyMargin)
1468 newDepth = depth - OnePly + ext;
1470 // Update current move (this must be done after singular extension search)
1471 movesSearched[moveCount++] = ss[ply].currentMove = move;
1473 // Step 12. Futility pruning
1476 && !captureOrPromotion
1477 && !move_is_castle(move)
1480 // Move count based pruning
1481 if ( moveCount >= futility_move_count(depth)
1482 && ok_to_prune(pos, move, ss[ply].threatMove)
1483 && bestValue > value_mated_in(PLY_MAX))
1486 // Value based pruning
1487 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1488 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1489 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1491 if (futilityValueScaled < beta)
1493 if (futilityValueScaled > bestValue)
1494 bestValue = futilityValueScaled;
1499 // Step 13. Make the move
1500 pos.do_move(move, st, ci, moveIsCheck);
1502 // Step 14. Reduced search
1503 // if the move fails high will be re-searched at full depth.
1504 bool doFullDepthSearch = true;
1506 if ( depth >= 3*OnePly
1508 && !captureOrPromotion
1509 && !move_is_castle(move)
1510 && !move_is_killer(move, ss[ply]))
1512 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1513 if (ss[ply].reduction)
1515 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1516 doFullDepthSearch = (value >= beta);
1520 // Step 15. Full depth search
1521 if (doFullDepthSearch)
1523 ss[ply].reduction = Depth(0);
1524 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1527 // Step 16. Undo move
1528 pos.undo_move(move);
1530 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1532 // Step 17. Check for new best move
1533 if (value > bestValue)
1539 if (value == value_mate_in(ply + 1))
1540 ss[ply].mateKiller = move;
1543 // Step 18. Check for split
1544 if ( TM.active_threads() > 1
1546 && depth >= MinimumSplitDepth
1548 && TM.available_thread_exists(threadID)
1550 && !TM.thread_should_stop(threadID)
1551 && TM.split(pos, ss, ply, NULL, beta, &bestValue,
1552 depth, &moveCount, &mp, threadID, false))
1556 // Step 19. Check for mate and stalemate
1557 // All legal moves have been searched and if there were
1558 // no legal moves, it must be mate or stalemate.
1559 // If one move was excluded return fail low.
1561 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1563 // Step 20. Update tables
1564 // If the search is not aborted, update the transposition table,
1565 // history counters, and killer moves.
1566 if (AbortSearch || TM.thread_should_stop(threadID))
1569 if (bestValue < beta)
1570 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1573 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1574 move = ss[ply].pv[ply];
1575 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1576 if (!pos.move_is_capture_or_promotion(move))
1578 update_history(pos, move, depth, movesSearched, moveCount);
1579 update_killers(move, ss[ply]);
1584 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1590 // qsearch() is the quiescence search function, which is called by the main
1591 // search function when the remaining depth is zero (or, to be more precise,
1592 // less than OnePly).
1594 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1595 Depth depth, int ply, int threadID) {
1597 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1598 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1600 assert(ply >= 0 && ply < PLY_MAX);
1601 assert(threadID >= 0 && threadID < TM.active_threads());
1606 Value staticValue, bestValue, value, futilityBase, futilityValue;
1607 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1608 const TTEntry* tte = NULL;
1610 bool pvNode = (beta - alpha != 1);
1611 Value oldAlpha = alpha;
1613 // Initialize, and make an early exit in case of an aborted search,
1614 // an instant draw, maximum ply reached, etc.
1615 init_node(ss, ply, threadID);
1617 // After init_node() that calls poll()
1618 if (AbortSearch || TM.thread_should_stop(threadID))
1621 if (pos.is_draw() || ply >= PLY_MAX - 1)
1624 // Transposition table lookup. At PV nodes, we don't use the TT for
1625 // pruning, but only for move ordering.
1626 tte = TT.retrieve(pos.get_key());
1627 ttMove = (tte ? tte->move() : MOVE_NONE);
1629 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1631 assert(tte->type() != VALUE_TYPE_EVAL);
1633 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1634 return value_from_tt(tte->value(), ply);
1637 isCheck = pos.is_check();
1639 // Evaluate the position statically
1641 staticValue = -VALUE_INFINITE;
1642 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1643 staticValue = value_from_tt(tte->value(), ply);
1645 staticValue = evaluate(pos, ei, threadID);
1649 ss[ply].eval = staticValue;
1650 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1653 // Initialize "stand pat score", and return it immediately if it is
1655 bestValue = staticValue;
1657 if (bestValue >= beta)
1659 // Store the score to avoid a future costly evaluation() call
1660 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1661 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1666 if (bestValue > alpha)
1669 // If we are near beta then try to get a cutoff pushing checks a bit further
1670 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1672 // Initialize a MovePicker object for the current position, and prepare
1673 // to search the moves. Because the depth is <= 0 here, only captures,
1674 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1675 // and we are near beta) will be generated.
1676 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1678 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1679 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1681 // Loop through the moves until no moves remain or a beta cutoff
1683 while ( alpha < beta
1684 && (move = mp.get_next_move()) != MOVE_NONE)
1686 assert(move_is_ok(move));
1688 moveIsCheck = pos.move_is_check(move, ci);
1690 // Update current move
1692 ss[ply].currentMove = move;
1700 && !move_is_promotion(move)
1701 && !pos.move_is_passed_pawn_push(move))
1703 futilityValue = futilityBase
1704 + pos.endgame_value_of_piece_on(move_to(move))
1705 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1707 if (futilityValue < alpha)
1709 if (futilityValue > bestValue)
1710 bestValue = futilityValue;
1715 // Detect blocking evasions that are candidate to be pruned
1716 evasionPrunable = isCheck
1717 && bestValue != -VALUE_INFINITE
1718 && !pos.move_is_capture(move)
1719 && pos.type_of_piece_on(move_from(move)) != KING
1720 && !pos.can_castle(pos.side_to_move());
1722 // Don't search moves with negative SEE values
1723 if ( (!isCheck || evasionPrunable)
1726 && !move_is_promotion(move)
1727 && pos.see_sign(move) < 0)
1730 // Make and search the move
1731 pos.do_move(move, st, ci, moveIsCheck);
1732 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1733 pos.undo_move(move);
1735 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1738 if (value > bestValue)
1749 // All legal moves have been searched. A special case: If we're in check
1750 // and no legal moves were found, it is checkmate.
1751 if (!moveCount && pos.is_check()) // Mate!
1752 return value_mated_in(ply);
1754 // Update transposition table
1755 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1756 if (bestValue <= oldAlpha)
1758 // If bestValue isn't changed it means it is still the static evaluation
1759 // of the node, so keep this info to avoid a future evaluation() call.
1760 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1761 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1763 else if (bestValue >= beta)
1765 move = ss[ply].pv[ply];
1766 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1768 // Update killers only for good checking moves
1769 if (!pos.move_is_capture_or_promotion(move))
1770 update_killers(move, ss[ply]);
1773 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1775 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1781 // sp_search() is used to search from a split point. This function is called
1782 // by each thread working at the split point. It is similar to the normal
1783 // search() function, but simpler. Because we have already probed the hash
1784 // table, done a null move search, and searched the first move before
1785 // splitting, we don't have to repeat all this work in sp_search(). We
1786 // also don't need to store anything to the hash table here: This is taken
1787 // care of after we return from the split point.
1788 // FIXME: We are currently ignoring mateThreat flag here
1790 void sp_search(SplitPoint* sp, int threadID) {
1792 assert(threadID >= 0 && threadID < TM.active_threads());
1793 assert(TM.active_threads() > 1);
1797 Depth ext, newDepth;
1798 Value value, futilityValueScaled;
1799 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1801 value = -VALUE_INFINITE;
1803 Position pos(*sp->pos);
1805 SearchStack* ss = sp->sstack[threadID];
1806 isCheck = pos.is_check();
1808 // Step 10. Loop through moves
1809 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1810 lock_grab(&(sp->lock));
1812 while ( sp->bestValue < sp->beta
1813 && !TM.thread_should_stop(threadID)
1814 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1816 moveCount = ++sp->moves;
1817 lock_release(&(sp->lock));
1819 assert(move_is_ok(move));
1821 moveIsCheck = pos.move_is_check(move, ci);
1822 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1824 // Step 11. Decide the new search depth
1825 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1826 newDepth = sp->depth - OnePly + ext;
1828 // Update current move
1829 ss[sp->ply].currentMove = move;
1831 // Step 12. Futility pruning
1834 && !captureOrPromotion
1835 && !move_is_castle(move))
1837 // Move count based pruning
1838 if ( moveCount >= futility_move_count(sp->depth)
1839 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1840 && sp->bestValue > value_mated_in(PLY_MAX))
1842 lock_grab(&(sp->lock));
1846 // Value based pruning
1847 Depth predictedDepth = newDepth - nonpv_reduction(sp->depth, moveCount);
1848 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1849 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1851 if (futilityValueScaled < sp->beta)
1853 lock_grab(&(sp->lock));
1855 if (futilityValueScaled > sp->bestValue)
1856 sp->bestValue = futilityValueScaled;
1861 // Step 13. Make the move
1862 pos.do_move(move, st, ci, moveIsCheck);
1864 // Step 14. Reduced search
1865 // if the move fails high will be re-searched at full depth.
1866 bool doFullDepthSearch = true;
1869 && !captureOrPromotion
1870 && !move_is_castle(move)
1871 && !move_is_killer(move, ss[sp->ply]))
1873 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1874 if (ss[sp->ply].reduction)
1876 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1877 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1881 // Step 15. Full depth search
1882 if (doFullDepthSearch)
1884 ss[sp->ply].reduction = Depth(0);
1885 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1888 // Step 16. Undo move
1889 pos.undo_move(move);
1891 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1893 // Step 17. Check for new best move
1894 lock_grab(&(sp->lock));
1896 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1898 sp->bestValue = value;
1899 if (sp->bestValue >= sp->beta)
1901 sp->stopRequest = true;
1902 sp_update_pv(sp->parentSstack, ss, sp->ply);
1907 /* Here we have the lock still grabbed */
1909 sp->slaves[threadID] = 0;
1912 lock_release(&(sp->lock));
1916 // sp_search_pv() is used to search from a PV split point. This function
1917 // is called by each thread working at the split point. It is similar to
1918 // the normal search_pv() function, but simpler. Because we have already
1919 // probed the hash table and searched the first move before splitting, we
1920 // don't have to repeat all this work in sp_search_pv(). We also don't
1921 // need to store anything to the hash table here: This is taken care of
1922 // after we return from the split point.
1923 // FIXME: We are ignoring mateThreat flag!
1925 void sp_search_pv(SplitPoint* sp, int threadID) {
1927 assert(threadID >= 0 && threadID < TM.active_threads());
1928 assert(TM.active_threads() > 1);
1932 Depth ext, newDepth;
1934 bool moveIsCheck, captureOrPromotion, dangerous;
1936 value = -VALUE_INFINITE;
1938 Position pos(*sp->pos);
1940 SearchStack* ss = sp->sstack[threadID];
1942 // Step 10. Loop through moves
1943 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1944 lock_grab(&(sp->lock));
1946 while ( sp->alpha < sp->beta
1947 && !TM.thread_should_stop(threadID)
1948 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1950 moveCount = ++sp->moves;
1951 lock_release(&(sp->lock));
1953 assert(move_is_ok(move));
1955 moveIsCheck = pos.move_is_check(move, ci);
1956 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1958 // Step 11. Decide the new search depth
1959 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1960 newDepth = sp->depth - OnePly + ext;
1962 // Update current move
1963 ss[sp->ply].currentMove = move;
1965 // Step 12. Futility pruning (is omitted in PV nodes)
1967 // Step 13. Make the move
1968 pos.do_move(move, st, ci, moveIsCheck);
1970 // Step 14. Reduced search
1971 // if the move fails high will be re-searched at full depth.
1972 bool doFullDepthSearch = true;
1975 && !captureOrPromotion
1976 && !move_is_castle(move)
1977 && !move_is_killer(move, ss[sp->ply]))
1979 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
1980 if (ss[sp->ply].reduction)
1982 Value localAlpha = sp->alpha;
1983 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1984 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
1988 // Step 15. Full depth search
1989 if (doFullDepthSearch)
1991 Value localAlpha = sp->alpha;
1992 ss[sp->ply].reduction = Depth(0);
1993 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
1995 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
1997 // If another thread has failed high then sp->alpha has been increased
1998 // to be higher or equal then beta, if so, avoid to start a PV search.
1999 localAlpha = sp->alpha;
2000 if (localAlpha < sp->beta)
2001 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2005 // Step 16. Undo move
2006 pos.undo_move(move);
2008 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2010 // Step 17. Check for new best move
2011 lock_grab(&(sp->lock));
2013 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
2015 sp->bestValue = value;
2016 if (value > sp->alpha)
2018 // Ask threads to stop before to modify sp->alpha
2019 if (value >= sp->beta)
2020 sp->stopRequest = true;
2024 sp_update_pv(sp->parentSstack, ss, sp->ply);
2025 if (value == value_mate_in(sp->ply + 1))
2026 ss[sp->ply].mateKiller = move;
2031 /* Here we have the lock still grabbed */
2033 sp->slaves[threadID] = 0;
2036 lock_release(&(sp->lock));
2040 // init_node() is called at the beginning of all the search functions
2041 // (search(), search_pv(), qsearch(), and so on) and initializes the
2042 // search stack object corresponding to the current node. Once every
2043 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2044 // for user input and checks whether it is time to stop the search.
2046 void init_node(SearchStack ss[], int ply, int threadID) {
2048 assert(ply >= 0 && ply < PLY_MAX);
2049 assert(threadID >= 0 && threadID < TM.active_threads());
2051 TM.incrementNodeCounter(threadID);
2056 if (NodesSincePoll >= NodesBetweenPolls)
2063 ss[ply + 2].initKillers();
2067 // update_pv() is called whenever a search returns a value > alpha.
2068 // It updates the PV in the SearchStack object corresponding to the
2071 void update_pv(SearchStack ss[], int ply) {
2073 assert(ply >= 0 && ply < PLY_MAX);
2077 ss[ply].pv[ply] = ss[ply].currentMove;
2079 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2080 ss[ply].pv[p] = ss[ply + 1].pv[p];
2082 ss[ply].pv[p] = MOVE_NONE;
2086 // sp_update_pv() is a variant of update_pv for use at split points. The
2087 // difference between the two functions is that sp_update_pv also updates
2088 // the PV at the parent node.
2090 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2092 assert(ply >= 0 && ply < PLY_MAX);
2096 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2098 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2099 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2101 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2105 // connected_moves() tests whether two moves are 'connected' in the sense
2106 // that the first move somehow made the second move possible (for instance
2107 // if the moving piece is the same in both moves). The first move is assumed
2108 // to be the move that was made to reach the current position, while the
2109 // second move is assumed to be a move from the current position.
2111 bool connected_moves(const Position& pos, Move m1, Move m2) {
2113 Square f1, t1, f2, t2;
2116 assert(move_is_ok(m1));
2117 assert(move_is_ok(m2));
2119 if (m2 == MOVE_NONE)
2122 // Case 1: The moving piece is the same in both moves
2128 // Case 2: The destination square for m2 was vacated by m1
2134 // Case 3: Moving through the vacated square
2135 if ( piece_is_slider(pos.piece_on(f2))
2136 && bit_is_set(squares_between(f2, t2), f1))
2139 // Case 4: The destination square for m2 is defended by the moving piece in m1
2140 p = pos.piece_on(t1);
2141 if (bit_is_set(pos.attacks_from(p, t1), t2))
2144 // Case 5: Discovered check, checking piece is the piece moved in m1
2145 if ( piece_is_slider(p)
2146 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2147 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2149 // discovered_check_candidates() works also if the Position's side to
2150 // move is the opposite of the checking piece.
2151 Color them = opposite_color(pos.side_to_move());
2152 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2154 if (bit_is_set(dcCandidates, f2))
2161 // value_is_mate() checks if the given value is a mate one
2162 // eventually compensated for the ply.
2164 bool value_is_mate(Value value) {
2166 assert(abs(value) <= VALUE_INFINITE);
2168 return value <= value_mated_in(PLY_MAX)
2169 || value >= value_mate_in(PLY_MAX);
2173 // move_is_killer() checks if the given move is among the
2174 // killer moves of that ply.
2176 bool move_is_killer(Move m, const SearchStack& ss) {
2178 const Move* k = ss.killers;
2179 for (int i = 0; i < KILLER_MAX; i++, k++)
2187 // extension() decides whether a move should be searched with normal depth,
2188 // or with extended depth. Certain classes of moves (checking moves, in
2189 // particular) are searched with bigger depth than ordinary moves and in
2190 // any case are marked as 'dangerous'. Note that also if a move is not
2191 // extended, as example because the corresponding UCI option is set to zero,
2192 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2194 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2195 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2197 assert(m != MOVE_NONE);
2199 Depth result = Depth(0);
2200 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2205 result += CheckExtension[pvNode];
2208 result += SingleEvasionExtension[pvNode];
2211 result += MateThreatExtension[pvNode];
2214 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2216 Color c = pos.side_to_move();
2217 if (relative_rank(c, move_to(m)) == RANK_7)
2219 result += PawnPushTo7thExtension[pvNode];
2222 if (pos.pawn_is_passed(c, move_to(m)))
2224 result += PassedPawnExtension[pvNode];
2229 if ( captureOrPromotion
2230 && pos.type_of_piece_on(move_to(m)) != PAWN
2231 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2232 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2233 && !move_is_promotion(m)
2236 result += PawnEndgameExtension[pvNode];
2241 && captureOrPromotion
2242 && pos.type_of_piece_on(move_to(m)) != PAWN
2243 && pos.see_sign(m) >= 0)
2249 return Min(result, OnePly);
2253 // ok_to_do_nullmove() looks at the current position and decides whether
2254 // doing a 'null move' should be allowed. In order to avoid zugzwang
2255 // problems, null moves are not allowed when the side to move has very
2256 // little material left. Currently, the test is a bit too simple: Null
2257 // moves are avoided only when the side to move has only pawns left.
2258 // It's probably a good idea to avoid null moves in at least some more
2259 // complicated endgames, e.g. KQ vs KR. FIXME
2261 bool ok_to_do_nullmove(const Position& pos) {
2263 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2267 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2268 // non-tactical moves late in the move list close to the leaves are
2269 // candidates for pruning.
2271 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2273 assert(move_is_ok(m));
2274 assert(threat == MOVE_NONE || move_is_ok(threat));
2275 assert(!pos.move_is_check(m));
2276 assert(!pos.move_is_capture_or_promotion(m));
2277 assert(!pos.move_is_passed_pawn_push(m));
2279 Square mfrom, mto, tfrom, tto;
2281 // Prune if there isn't any threat move
2282 if (threat == MOVE_NONE)
2285 mfrom = move_from(m);
2287 tfrom = move_from(threat);
2288 tto = move_to(threat);
2290 // Case 1: Don't prune moves which move the threatened piece
2294 // Case 2: If the threatened piece has value less than or equal to the
2295 // value of the threatening piece, don't prune move which defend it.
2296 if ( pos.move_is_capture(threat)
2297 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2298 || pos.type_of_piece_on(tfrom) == KING)
2299 && pos.move_attacks_square(m, tto))
2302 // Case 3: If the moving piece in the threatened move is a slider, don't
2303 // prune safe moves which block its ray.
2304 if ( piece_is_slider(pos.piece_on(tfrom))
2305 && bit_is_set(squares_between(tfrom, tto), mto)
2306 && pos.see_sign(m) >= 0)
2313 // ok_to_use_TT() returns true if a transposition table score
2314 // can be used at a given point in search.
2316 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2318 Value v = value_from_tt(tte->value(), ply);
2320 return ( tte->depth() >= depth
2321 || v >= Max(value_mate_in(PLY_MAX), beta)
2322 || v < Min(value_mated_in(PLY_MAX), beta))
2324 && ( (is_lower_bound(tte->type()) && v >= beta)
2325 || (is_upper_bound(tte->type()) && v < beta));
2329 // refine_eval() returns the transposition table score if
2330 // possible otherwise falls back on static position evaluation.
2332 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2337 Value v = value_from_tt(tte->value(), ply);
2339 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2340 || (is_upper_bound(tte->type()) && v < defaultEval))
2347 // update_history() registers a good move that produced a beta-cutoff
2348 // in history and marks as failures all the other moves of that ply.
2350 void update_history(const Position& pos, Move move, Depth depth,
2351 Move movesSearched[], int moveCount) {
2355 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2357 for (int i = 0; i < moveCount - 1; i++)
2359 m = movesSearched[i];
2363 if (!pos.move_is_capture_or_promotion(m))
2364 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2369 // update_killers() add a good move that produced a beta-cutoff
2370 // among the killer moves of that ply.
2372 void update_killers(Move m, SearchStack& ss) {
2374 if (m == ss.killers[0])
2377 for (int i = KILLER_MAX - 1; i > 0; i--)
2378 ss.killers[i] = ss.killers[i - 1];
2384 // update_gains() updates the gains table of a non-capture move given
2385 // the static position evaluation before and after the move.
2387 void update_gains(const Position& pos, Move m, Value before, Value after) {
2390 && before != VALUE_NONE
2391 && after != VALUE_NONE
2392 && pos.captured_piece() == NO_PIECE_TYPE
2393 && !move_is_castle(m)
2394 && !move_is_promotion(m))
2395 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2399 // current_search_time() returns the number of milliseconds which have passed
2400 // since the beginning of the current search.
2402 int current_search_time() {
2404 return get_system_time() - SearchStartTime;
2408 // nps() computes the current nodes/second count.
2412 int t = current_search_time();
2413 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2417 // poll() performs two different functions: It polls for user input, and it
2418 // looks at the time consumed so far and decides if it's time to abort the
2421 void poll(SearchStack ss[], int ply) {
2423 static int lastInfoTime;
2424 int t = current_search_time();
2429 // We are line oriented, don't read single chars
2430 std::string command;
2432 if (!std::getline(std::cin, command))
2435 if (command == "quit")
2438 PonderSearch = false;
2442 else if (command == "stop")
2445 PonderSearch = false;
2447 else if (command == "ponderhit")
2451 // Print search information
2455 else if (lastInfoTime > t)
2456 // HACK: Must be a new search where we searched less than
2457 // NodesBetweenPolls nodes during the first second of search.
2460 else if (t - lastInfoTime >= 1000)
2467 if (dbg_show_hit_rate)
2468 dbg_print_hit_rate();
2470 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2471 << " time " << t << " hashfull " << TT.full() << endl;
2473 // We only support current line printing in single thread mode
2474 if (ShowCurrentLine && TM.active_threads() == 1)
2476 cout << "info currline";
2477 for (int p = 0; p < ply; p++)
2478 cout << " " << ss[p].currentMove;
2484 // Should we stop the search?
2488 bool stillAtFirstMove = RootMoveNumber == 1
2489 && !AspirationFailLow
2490 && t > MaxSearchTime + ExtraSearchTime;
2492 bool noMoreTime = t > AbsoluteMaxSearchTime
2493 || stillAtFirstMove;
2495 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2496 || (ExactMaxTime && t >= ExactMaxTime)
2497 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2502 // ponderhit() is called when the program is pondering (i.e. thinking while
2503 // it's the opponent's turn to move) in order to let the engine know that
2504 // it correctly predicted the opponent's move.
2508 int t = current_search_time();
2509 PonderSearch = false;
2511 bool stillAtFirstMove = RootMoveNumber == 1
2512 && !AspirationFailLow
2513 && t > MaxSearchTime + ExtraSearchTime;
2515 bool noMoreTime = t > AbsoluteMaxSearchTime
2516 || stillAtFirstMove;
2518 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2523 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2525 void init_ss_array(SearchStack ss[]) {
2527 for (int i = 0; i < 3; i++)
2530 ss[i].initKillers();
2535 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2536 // while the program is pondering. The point is to work around a wrinkle in
2537 // the UCI protocol: When pondering, the engine is not allowed to give a
2538 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2539 // We simply wait here until one of these commands is sent, and return,
2540 // after which the bestmove and pondermove will be printed (in id_loop()).
2542 void wait_for_stop_or_ponderhit() {
2544 std::string command;
2548 if (!std::getline(std::cin, command))
2551 if (command == "quit")
2556 else if (command == "ponderhit" || command == "stop")
2562 // init_thread() is the function which is called when a new thread is
2563 // launched. It simply calls the idle_loop() function with the supplied
2564 // threadID. There are two versions of this function; one for POSIX
2565 // threads and one for Windows threads.
2567 #if !defined(_MSC_VER)
2569 void* init_thread(void *threadID) {
2571 TM.idle_loop(*(int*)threadID, NULL);
2577 DWORD WINAPI init_thread(LPVOID threadID) {
2579 TM.idle_loop(*(int*)threadID, NULL);
2586 /// The ThreadsManager class
2588 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2589 // get_beta_counters() are getters/setters for the per thread
2590 // counters used to sort the moves at root.
2592 void ThreadsManager::resetNodeCounters() {
2594 for (int i = 0; i < MAX_THREADS; i++)
2595 threads[i].nodes = 0ULL;
2598 void ThreadsManager::resetBetaCounters() {
2600 for (int i = 0; i < MAX_THREADS; i++)
2601 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2604 int64_t ThreadsManager::nodes_searched() const {
2606 int64_t result = 0ULL;
2607 for (int i = 0; i < ActiveThreads; i++)
2608 result += threads[i].nodes;
2613 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2616 for (int i = 0; i < MAX_THREADS; i++)
2618 our += threads[i].betaCutOffs[us];
2619 their += threads[i].betaCutOffs[opposite_color(us)];
2624 // idle_loop() is where the threads are parked when they have no work to do.
2625 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2626 // object for which the current thread is the master.
2628 void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2630 assert(threadID >= 0 && threadID < MAX_THREADS);
2634 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2635 // master should exit as last one.
2636 if (AllThreadsShouldExit)
2639 threads[threadID].state = THREAD_TERMINATED;
2643 // If we are not thinking, wait for a condition to be signaled
2644 // instead of wasting CPU time polling for work.
2645 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2648 assert(threadID != 0);
2649 threads[threadID].state = THREAD_SLEEPING;
2651 #if !defined(_MSC_VER)
2652 pthread_mutex_lock(&WaitLock);
2653 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2654 pthread_cond_wait(&WaitCond, &WaitLock);
2655 pthread_mutex_unlock(&WaitLock);
2657 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2661 // If thread has just woken up, mark it as available
2662 if (threads[threadID].state == THREAD_SLEEPING)
2663 threads[threadID].state = THREAD_AVAILABLE;
2665 // If this thread has been assigned work, launch a search
2666 if (threads[threadID].state == THREAD_WORKISWAITING)
2668 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2670 threads[threadID].state = THREAD_SEARCHING;
2672 if (threads[threadID].splitPoint->pvNode)
2673 sp_search_pv(threads[threadID].splitPoint, threadID);
2675 sp_search(threads[threadID].splitPoint, threadID);
2677 assert(threads[threadID].state == THREAD_SEARCHING);
2679 threads[threadID].state = THREAD_AVAILABLE;
2682 // If this thread is the master of a split point and all threads have
2683 // finished their work at this split point, return from the idle loop.
2684 if (waitSp != NULL && waitSp->cpus == 0)
2686 assert(threads[threadID].state == THREAD_AVAILABLE);
2688 threads[threadID].state = THREAD_SEARCHING;
2695 // init_threads() is called during startup. It launches all helper threads,
2696 // and initializes the split point stack and the global locks and condition
2699 void ThreadsManager::init_threads() {
2704 #if !defined(_MSC_VER)
2705 pthread_t pthread[1];
2708 // Initialize global locks
2709 lock_init(&MPLock, NULL);
2711 // Initialize SplitPointStack locks
2712 for (i = 0; i < MAX_THREADS; i++)
2713 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2715 SplitPointStack[i][j].parent = NULL;
2716 lock_init(&(SplitPointStack[i][j].lock), NULL);
2719 #if !defined(_MSC_VER)
2720 pthread_mutex_init(&WaitLock, NULL);
2721 pthread_cond_init(&WaitCond, NULL);
2723 for (i = 0; i < MAX_THREADS; i++)
2724 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2727 // Will be set just before program exits to properly end the threads
2728 AllThreadsShouldExit = false;
2730 // Threads will be put to sleep as soon as created
2731 AllThreadsShouldSleep = true;
2733 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2735 threads[0].state = THREAD_SEARCHING;
2736 for (i = 1; i < MAX_THREADS; i++)
2737 threads[i].state = THREAD_AVAILABLE;
2739 // Launch the helper threads
2740 for (i = 1; i < MAX_THREADS; i++)
2743 #if !defined(_MSC_VER)
2744 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2747 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
2752 cout << "Failed to create thread number " << i << endl;
2753 Application::exit_with_failure();
2756 // Wait until the thread has finished launching and is gone to sleep
2757 while (threads[i].state != THREAD_SLEEPING);
2762 // exit_threads() is called when the program exits. It makes all the
2763 // helper threads exit cleanly.
2765 void ThreadsManager::exit_threads() {
2767 ActiveThreads = MAX_THREADS; // HACK
2768 AllThreadsShouldSleep = true; // HACK
2769 wake_sleeping_threads();
2771 // This makes the threads to exit idle_loop()
2772 AllThreadsShouldExit = true;
2774 // Wait for thread termination
2775 for (int i = 1; i < MAX_THREADS; i++)
2776 while (threads[i].state != THREAD_TERMINATED);
2778 // Now we can safely destroy the locks
2779 for (int i = 0; i < MAX_THREADS; i++)
2780 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2781 lock_destroy(&(SplitPointStack[i][j].lock));
2785 // thread_should_stop() checks whether the thread should stop its search.
2786 // This can happen if a beta cutoff has occurred in the thread's currently
2787 // active split point, or in some ancestor of the current split point.
2789 bool ThreadsManager::thread_should_stop(int threadID) const {
2791 assert(threadID >= 0 && threadID < ActiveThreads);
2795 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent);
2800 // thread_is_available() checks whether the thread with threadID "slave" is
2801 // available to help the thread with threadID "master" at a split point. An
2802 // obvious requirement is that "slave" must be idle. With more than two
2803 // threads, this is not by itself sufficient: If "slave" is the master of
2804 // some active split point, it is only available as a slave to the other
2805 // threads which are busy searching the split point at the top of "slave"'s
2806 // split point stack (the "helpful master concept" in YBWC terminology).
2808 bool ThreadsManager::thread_is_available(int slave, int master) const {
2810 assert(slave >= 0 && slave < ActiveThreads);
2811 assert(master >= 0 && master < ActiveThreads);
2812 assert(ActiveThreads > 1);
2814 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2817 // Make a local copy to be sure doesn't change under our feet
2818 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2820 if (localActiveSplitPoints == 0)
2821 // No active split points means that the thread is available as
2822 // a slave for any other thread.
2825 if (ActiveThreads == 2)
2828 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2829 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2830 // could have been set to 0 by another thread leading to an out of bound access.
2831 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2838 // available_thread_exists() tries to find an idle thread which is available as
2839 // a slave for the thread with threadID "master".
2841 bool ThreadsManager::available_thread_exists(int master) const {
2843 assert(master >= 0 && master < ActiveThreads);
2844 assert(ActiveThreads > 1);
2846 for (int i = 0; i < ActiveThreads; i++)
2847 if (thread_is_available(i, master))
2854 // split() does the actual work of distributing the work at a node between
2855 // several threads at PV nodes. If it does not succeed in splitting the
2856 // node (because no idle threads are available, or because we have no unused
2857 // split point objects), the function immediately returns false. If
2858 // splitting is possible, a SplitPoint object is initialized with all the
2859 // data that must be copied to the helper threads (the current position and
2860 // search stack, alpha, beta, the search depth, etc.), and we tell our
2861 // helper threads that they have been assigned work. This will cause them
2862 // to instantly leave their idle loops and call sp_search_pv(). When all
2863 // threads have returned from sp_search_pv (or, equivalently, when
2864 // splitPoint->cpus becomes 0), split() returns true.
2866 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2867 Value* alpha, const Value beta, Value* bestValue,
2868 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2871 assert(sstck != NULL);
2872 assert(ply >= 0 && ply < PLY_MAX);
2873 assert(*bestValue >= -VALUE_INFINITE);
2874 assert( ( pvNode && *bestValue <= *alpha)
2875 || (!pvNode && *bestValue < beta ));
2876 assert(!pvNode || *alpha < beta);
2877 assert(beta <= VALUE_INFINITE);
2878 assert(depth > Depth(0));
2879 assert(master >= 0 && master < ActiveThreads);
2880 assert(ActiveThreads > 1);
2882 SplitPoint* splitPoint;
2886 // If no other thread is available to help us, or if we have too many
2887 // active split points, don't split.
2888 if ( !available_thread_exists(master)
2889 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2891 lock_release(&MPLock);
2895 // Pick the next available split point object from the split point stack
2896 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2898 // Initialize the split point object
2899 splitPoint->parent = threads[master].splitPoint;
2900 splitPoint->stopRequest = false;
2901 splitPoint->ply = ply;
2902 splitPoint->depth = depth;
2903 splitPoint->alpha = pvNode ? *alpha : beta - 1;
2904 splitPoint->beta = beta;
2905 splitPoint->pvNode = pvNode;
2906 splitPoint->bestValue = *bestValue;
2907 splitPoint->master = master;
2908 splitPoint->mp = mp;
2909 splitPoint->moves = *moves;
2910 splitPoint->cpus = 1;
2911 splitPoint->pos = &p;
2912 splitPoint->parentSstack = sstck;
2913 for (int i = 0; i < ActiveThreads; i++)
2914 splitPoint->slaves[i] = 0;
2916 threads[master].splitPoint = splitPoint;
2917 threads[master].activeSplitPoints++;
2919 // If we are here it means we are not available
2920 assert(threads[master].state != THREAD_AVAILABLE);
2922 // Allocate available threads setting state to THREAD_BOOKED
2923 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2924 if (thread_is_available(i, master))
2926 threads[i].state = THREAD_BOOKED;
2927 threads[i].splitPoint = splitPoint;
2928 splitPoint->slaves[i] = 1;
2932 assert(splitPoint->cpus > 1);
2934 // We can release the lock because slave threads are already booked and master is not available
2935 lock_release(&MPLock);
2937 // Tell the threads that they have work to do. This will make them leave
2938 // their idle loop. But before copy search stack tail for each thread.
2939 for (int i = 0; i < ActiveThreads; i++)
2940 if (i == master || splitPoint->slaves[i])
2942 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2944 assert(i == master || threads[i].state == THREAD_BOOKED);
2946 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2949 // Everything is set up. The master thread enters the idle loop, from
2950 // which it will instantly launch a search, because its state is
2951 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2952 // idle loop, which means that the main thread will return from the idle
2953 // loop when all threads have finished their work at this split point
2954 // (i.e. when splitPoint->cpus == 0).
2955 idle_loop(master, splitPoint);
2957 // We have returned from the idle loop, which means that all threads are
2958 // finished. Update alpha, beta and bestValue, and return.
2962 *alpha = splitPoint->alpha;
2964 *bestValue = splitPoint->bestValue;
2965 threads[master].activeSplitPoints--;
2966 threads[master].splitPoint = splitPoint->parent;
2968 lock_release(&MPLock);
2973 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2974 // to start a new search from the root.
2976 void ThreadsManager::wake_sleeping_threads() {
2978 assert(AllThreadsShouldSleep);
2979 assert(ActiveThreads > 0);
2981 AllThreadsShouldSleep = false;
2983 if (ActiveThreads == 1)
2986 for (int i = 1; i < ActiveThreads; i++)
2987 assert(threads[i].state == THREAD_SLEEPING);
2989 #if !defined(_MSC_VER)
2990 pthread_mutex_lock(&WaitLock);
2991 pthread_cond_broadcast(&WaitCond);
2992 pthread_mutex_unlock(&WaitLock);
2994 for (int i = 1; i < MAX_THREADS; i++)
2995 SetEvent(SitIdleEvent[i]);
3001 // put_threads_to_sleep() makes all the threads go to sleep just before
3002 // to leave think(), at the end of the search. Threads should have already
3003 // finished the job and should be idle.
3005 void ThreadsManager::put_threads_to_sleep() {
3007 assert(!AllThreadsShouldSleep);
3009 // This makes the threads to go to sleep
3010 AllThreadsShouldSleep = true;
3013 /// The RootMoveList class
3015 // RootMoveList c'tor
3017 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3019 SearchStack ss[PLY_MAX_PLUS_2];
3020 MoveStack mlist[MaxRootMoves];
3022 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3024 // Generate all legal moves
3025 MoveStack* last = generate_moves(pos, mlist);
3027 // Add each move to the moves[] array
3028 for (MoveStack* cur = mlist; cur != last; cur++)
3030 bool includeMove = includeAllMoves;
3032 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3033 includeMove = (searchMoves[k] == cur->move);
3038 // Find a quick score for the move
3040 pos.do_move(cur->move, st);
3041 moves[count].move = cur->move;
3042 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3043 moves[count].pv[0] = cur->move;
3044 moves[count].pv[1] = MOVE_NONE;
3045 pos.undo_move(cur->move);
3052 // RootMoveList simple methods definitions
3054 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3056 moves[moveNum].nodes = nodes;
3057 moves[moveNum].cumulativeNodes += nodes;
3060 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3062 moves[moveNum].ourBeta = our;
3063 moves[moveNum].theirBeta = their;
3066 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3070 for (j = 0; pv[j] != MOVE_NONE; j++)
3071 moves[moveNum].pv[j] = pv[j];
3073 moves[moveNum].pv[j] = MOVE_NONE;
3077 // RootMoveList::sort() sorts the root move list at the beginning of a new
3080 void RootMoveList::sort() {
3082 sort_multipv(count - 1); // Sort all items
3086 // RootMoveList::sort_multipv() sorts the first few moves in the root move
3087 // list by their scores and depths. It is used to order the different PVs
3088 // correctly in MultiPV mode.
3090 void RootMoveList::sort_multipv(int n) {
3094 for (i = 1; i <= n; i++)
3096 RootMove rm = moves[i];
3097 for (j = i; j > 0 && moves[j - 1] < rm; j--)
3098 moves[j] = moves[j - 1];