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 set_stop_request(int threadID) { threads[threadID].stopRequest = true; }
74 void incrementNodeCounter(int threadID) { threads[threadID].nodes++; }
75 void incrementBetaCounter(Color us, Depth d, int threadID) { threads[threadID].betaCutOffs[us] += unsigned(d); }
76 void print_current_line(SearchStack ss[], int ply, int threadID);
78 void resetNodeCounters();
79 void resetBetaCounters();
80 int64_t nodes_searched() const;
81 void get_beta_counters(Color us, int64_t& our, int64_t& their) const;
82 bool available_thread_exists(int master) const;
83 bool thread_is_available(int slave, int master) const;
84 bool thread_should_stop(int threadID) const;
85 void wake_sleeping_threads();
86 void put_threads_to_sleep();
87 void idle_loop(int threadID, SplitPoint* waitSp);
88 bool split(const Position& pos, SearchStack* ss, int ply, Value* alpha, Value* beta, Value* bestValue,
89 const Value futilityValue, Depth depth, int* moves, MovePicker* mp, int master, bool pvNode);
95 bool AllThreadsShouldExit, AllThreadsShouldSleep;
96 Thread threads[MAX_THREADS];
97 SplitPoint SplitPointStack[MAX_THREADS][ACTIVE_SPLIT_POINTS_MAX];
101 #if !defined(_MSC_VER)
102 pthread_cond_t WaitCond;
103 pthread_mutex_t WaitLock;
105 HANDLE SitIdleEvent[MAX_THREADS];
111 // RootMove struct is used for moves at the root at the tree. For each
112 // root move, we store a score, a node count, and a PV (really a refutation
113 // in the case of moves which fail low).
117 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
119 // RootMove::operator<() is the comparison function used when
120 // sorting the moves. A move m1 is considered to be better
121 // than a move m2 if it has a higher score, or if the moves
122 // have equal score but m1 has the higher node count.
123 bool operator<(const RootMove& m) const {
125 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
130 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
131 Move pv[PLY_MAX_PLUS_2];
135 // The RootMoveList class is essentially an array of RootMove objects, with
136 // a handful of methods for accessing the data in the individual moves.
141 RootMoveList(Position& pos, Move searchMoves[]);
143 int move_count() const { return count; }
144 Move get_move(int moveNum) const { return moves[moveNum].move; }
145 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
146 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
147 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
148 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
150 void set_move_nodes(int moveNum, int64_t nodes);
151 void set_beta_counters(int moveNum, int64_t our, int64_t their);
152 void set_move_pv(int moveNum, const Move pv[]);
154 void sort_multipv(int n);
157 static const int MaxRootMoves = 500;
158 RootMove moves[MaxRootMoves];
165 // Search depth at iteration 1
166 const Depth InitialDepth = OnePly;
168 // Use internal iterative deepening?
169 const bool UseIIDAtPVNodes = true;
170 const bool UseIIDAtNonPVNodes = true;
172 // Internal iterative deepening margin. At Non-PV moves, when
173 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
174 // search when the static evaluation is at most IIDMargin below beta.
175 const Value IIDMargin = Value(0x100);
177 // Easy move margin. An easy move candidate must be at least this much
178 // better than the second best move.
179 const Value EasyMoveMargin = Value(0x200);
181 // Null move margin. A null move search will not be done if the static
182 // evaluation of the position is more than NullMoveMargin below beta.
183 const Value NullMoveMargin = Value(0x200);
185 // If the TT move is at least SingleReplyMargin better then the
186 // remaining ones we will extend it.
187 const Value SingleReplyMargin = Value(0x20);
189 // Depth limit for razoring
190 const Depth RazorDepth = 4 * OnePly;
192 /// Lookup tables initialized at startup
194 // Reduction lookup tables and their getter functions
195 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
196 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
198 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
199 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
201 // Futility lookup tables and their getter functions
202 const Value FutilityMarginQS = Value(0x80);
203 int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
204 int FutilityMoveCountArray[32]; // [depth]
206 inline Value futility_margin(Depth d, int mn) { return Value(d < 7*OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
207 inline int futility_move_count(Depth d) { return d < 16*OnePly ? FutilityMoveCountArray[d] : 512; }
209 /// Variables initialized by UCI options
211 // Depth limit for use of dynamic threat detection
214 // Last seconds noise filtering (LSN)
215 const bool UseLSNFiltering = true;
216 const int LSNTime = 4000; // In milliseconds
217 const Value LSNValue = value_from_centipawns(200);
218 bool loseOnTime = false;
220 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
221 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
222 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
224 // Iteration counters
227 // Scores and number of times the best move changed for each iteration
228 Value ValueByIteration[PLY_MAX_PLUS_2];
229 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
231 // Search window management
237 // Time managment variables
240 int MaxNodes, MaxDepth;
241 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
242 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
243 bool AbortSearch, Quit;
244 bool AspirationFailLow;
246 // Show current line?
247 bool ShowCurrentLine;
251 std::ofstream LogFile;
253 // MP related variables
254 Depth MinimumSplitDepth;
255 int MaxThreadsPerSplitPoint;
258 // Node counters, used only by thread[0] but try to keep in different
259 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
261 int NodesBetweenPolls = 30000;
268 Value id_loop(const Position& pos, Move searchMoves[]);
269 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
270 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
271 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
272 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
273 void sp_search(SplitPoint* sp, int threadID);
274 void sp_search_pv(SplitPoint* sp, int threadID);
275 void init_node(SearchStack ss[], int ply, int threadID);
276 void update_pv(SearchStack ss[], int ply);
277 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
278 bool connected_moves(const Position& pos, Move m1, Move m2);
279 bool value_is_mate(Value value);
280 bool move_is_killer(Move m, const SearchStack& ss);
281 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
282 bool ok_to_do_nullmove(const Position& pos);
283 bool ok_to_prune(const Position& pos, Move m, Move threat);
284 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
285 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
286 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
287 void update_killers(Move m, SearchStack& ss);
288 void update_gains(const Position& pos, Move move, Value before, Value after);
290 int current_search_time();
294 void wait_for_stop_or_ponderhit();
295 void init_ss_array(SearchStack ss[]);
297 #if !defined(_MSC_VER)
298 void *init_thread(void *threadID);
300 DWORD WINAPI init_thread(LPVOID threadID);
310 /// init_threads(), exit_threads() and nodes_searched() are helpers to
311 /// give accessibility to some TM methods from outside of current file.
313 void init_threads() { TM.init_threads(); }
314 void exit_threads() { TM.exit_threads(); }
315 int64_t nodes_searched() { return TM.nodes_searched(); }
318 /// perft() is our utility to verify move generation is bug free. All the legal
319 /// moves up to given depth are generated and counted and the sum returned.
321 int perft(Position& pos, Depth depth)
325 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
327 // If we are at the last ply we don't need to do and undo
328 // the moves, just to count them.
329 if (depth <= OnePly) // Replace with '<' to test also qsearch
331 while (mp.get_next_move()) sum++;
335 // Loop through all legal moves
337 while ((move = mp.get_next_move()) != MOVE_NONE)
340 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
341 sum += perft(pos, depth - OnePly);
348 /// think() is the external interface to Stockfish's search, and is called when
349 /// the program receives the UCI 'go' command. It initializes various
350 /// search-related global variables, and calls root_search(). It returns false
351 /// when a quit command is received during the search.
353 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
354 int time[], int increment[], int movesToGo, int maxDepth,
355 int maxNodes, int maxTime, Move searchMoves[]) {
357 // Initialize global search variables
358 StopOnPonderhit = AbortSearch = Quit = false;
359 AspirationFailLow = false;
361 SearchStartTime = get_system_time();
362 ExactMaxTime = maxTime;
365 InfiniteSearch = infinite;
366 PonderSearch = ponder;
367 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
369 // Look for a book move, only during games, not tests
370 if (UseTimeManagement && get_option_value_bool("OwnBook"))
373 if (get_option_value_string("Book File") != OpeningBook.file_name())
374 OpeningBook.open(get_option_value_string("Book File"));
376 bookMove = OpeningBook.get_move(pos);
377 if (bookMove != MOVE_NONE)
380 wait_for_stop_or_ponderhit();
382 cout << "bestmove " << bookMove << endl;
387 TM.resetNodeCounters();
389 if (button_was_pressed("New Game"))
390 loseOnTime = false; // Reset at the beginning of a new game
392 // Read UCI option values
393 TT.set_size(get_option_value_int("Hash"));
394 if (button_was_pressed("Clear Hash"))
397 bool PonderingEnabled = get_option_value_bool("Ponder");
398 MultiPV = get_option_value_int("MultiPV");
400 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
401 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
403 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
404 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
406 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
407 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
409 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
410 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
412 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
413 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
415 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
416 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
418 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
420 Chess960 = get_option_value_bool("UCI_Chess960");
421 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
422 UseLogFile = get_option_value_bool("Use Search Log");
424 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
426 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
427 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
429 read_weights(pos.side_to_move());
431 // Set the number of active threads
432 int newActiveThreads = get_option_value_int("Threads");
433 if (newActiveThreads != TM.active_threads())
435 TM.set_active_threads(newActiveThreads);
436 init_eval(TM.active_threads());
437 // HACK: init_eval() destroys the static castleRightsMask[] array in the
438 // Position class. The below line repairs the damage.
439 Position p(pos.to_fen());
443 // Wake up sleeping threads
444 TM.wake_sleeping_threads();
446 for (int i = 1; i < TM.active_threads(); i++)
447 assert(TM.thread_is_available(i, 0));
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];
1050 Depth ext, newDepth;
1051 Value oldAlpha, value;
1052 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1054 Value bestValue = value = -VALUE_INFINITE;
1057 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1059 // Initialize, and make an early exit in case of an aborted search,
1060 // an instant draw, maximum ply reached, etc.
1061 init_node(ss, ply, threadID);
1063 // After init_node() that calls poll()
1064 if (AbortSearch || TM.thread_should_stop(threadID))
1067 if (pos.is_draw() || ply >= PLY_MAX - 1)
1070 // Mate distance pruning
1072 alpha = Max(value_mated_in(ply), alpha);
1073 beta = Min(value_mate_in(ply+1), beta);
1077 // Transposition table lookup. At PV nodes, we don't use the TT for
1078 // pruning, but only for move ordering. This is to avoid problems in
1079 // the following areas:
1081 // * Repetition draw detection
1082 // * Fifty move rule detection
1083 // * Searching for a mate
1084 // * Printing of full PV line
1086 tte = TT.retrieve(pos.get_key());
1087 ttMove = (tte ? tte->move() : MOVE_NONE);
1089 // Go with internal iterative deepening if we don't have a TT move
1090 if ( UseIIDAtPVNodes
1091 && depth >= 5*OnePly
1092 && ttMove == MOVE_NONE)
1094 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1095 ttMove = ss[ply].pv[ply];
1096 tte = TT.retrieve(pos.get_key());
1099 isCheck = pos.is_check();
1102 // Update gain statistics of the previous move that lead
1103 // us in this position.
1105 ss[ply].eval = evaluate(pos, ei, threadID);
1106 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1109 // Initialize a MovePicker object for the current position, and prepare
1110 // to search all moves
1111 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1113 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1115 // Loop through all legal moves until no moves remain or a beta cutoff
1117 while ( alpha < beta
1118 && (move = mp.get_next_move()) != MOVE_NONE
1119 && !TM.thread_should_stop(threadID))
1121 assert(move_is_ok(move));
1123 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1124 moveIsCheck = pos.move_is_check(move, ci);
1125 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1127 // Decide the new search depth
1128 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1130 // Singular extension search. We extend the TT move if its value is much better than
1131 // its siblings. To verify this we do a reduced search on all the other moves but the
1132 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1133 if ( depth >= 6 * OnePly
1135 && move == tte->move()
1137 && is_lower_bound(tte->type())
1138 && tte->depth() >= depth - 3 * OnePly)
1140 Value ttValue = value_from_tt(tte->value(), ply);
1142 if (abs(ttValue) < VALUE_KNOWN_WIN)
1144 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1146 if (excValue < ttValue - SingleReplyMargin)
1151 newDepth = depth - OnePly + ext;
1153 // Update current move
1154 movesSearched[moveCount++] = ss[ply].currentMove = move;
1156 // Make and search the move
1157 pos.do_move(move, st, ci, moveIsCheck);
1159 if (moveCount == 1) // The first move in list is the PV
1160 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1163 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1164 // if the move fails high will be re-searched at full depth.
1165 bool doFullDepthSearch = true;
1167 if ( depth >= 3*OnePly
1169 && !captureOrPromotion
1170 && !move_is_castle(move)
1171 && !move_is_killer(move, ss[ply]))
1173 ss[ply].reduction = pv_reduction(depth, moveCount);
1174 if (ss[ply].reduction)
1176 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1177 doFullDepthSearch = (value > alpha);
1181 if (doFullDepthSearch) // Go with full depth non-pv search
1183 ss[ply].reduction = Depth(0);
1184 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1185 if (value > alpha && value < beta)
1186 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1189 pos.undo_move(move);
1191 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1194 if (value > bestValue)
1201 if (value == value_mate_in(ply + 1))
1202 ss[ply].mateKiller = move;
1207 if ( TM.active_threads() > 1
1209 && depth >= MinimumSplitDepth
1211 && TM.available_thread_exists(threadID)
1213 && !TM.thread_should_stop(threadID)
1214 && TM.split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1215 depth, &moveCount, &mp, threadID, true))
1219 // All legal moves have been searched. A special case: If there were
1220 // no legal moves, it must be mate or stalemate.
1222 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1224 // If the search is not aborted, update the transposition table,
1225 // history counters, and killer moves.
1226 if (AbortSearch || TM.thread_should_stop(threadID))
1229 if (bestValue <= oldAlpha)
1230 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1232 else if (bestValue >= beta)
1234 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1235 move = ss[ply].pv[ply];
1236 if (!pos.move_is_capture_or_promotion(move))
1238 update_history(pos, move, depth, movesSearched, moveCount);
1239 update_killers(move, ss[ply]);
1241 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1244 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1250 // search() is the search function for zero-width nodes.
1252 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1253 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1255 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1256 assert(ply >= 0 && ply < PLY_MAX);
1257 assert(threadID >= 0 && threadID < TM.active_threads());
1259 Move movesSearched[256];
1264 Depth ext, newDepth;
1265 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1266 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1267 bool mateThreat = false;
1269 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1272 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1274 // Initialize, and make an early exit in case of an aborted search,
1275 // an instant draw, maximum ply reached, etc.
1276 init_node(ss, ply, threadID);
1278 // After init_node() that calls poll()
1279 if (AbortSearch || TM.thread_should_stop(threadID))
1282 if (pos.is_draw() || ply >= PLY_MAX - 1)
1285 // Mate distance pruning
1286 if (value_mated_in(ply) >= beta)
1289 if (value_mate_in(ply + 1) < beta)
1292 // We don't want the score of a partial search to overwrite a previous full search
1293 // TT value, so we use a different position key in case of an excluded move exsists.
1294 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1296 // Transposition table lookup
1297 tte = TT.retrieve(posKey);
1298 ttMove = (tte ? tte->move() : MOVE_NONE);
1300 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1302 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1303 return value_from_tt(tte->value(), ply);
1306 isCheck = pos.is_check();
1308 // Evaluate the position statically
1311 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1312 staticValue = value_from_tt(tte->value(), ply);
1314 staticValue = evaluate(pos, ei, threadID);
1316 ss[ply].eval = staticValue;
1317 futilityValue = staticValue + futility_margin(depth, 0); //FIXME: Remove me, only for split
1318 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1319 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1322 // Static null move pruning. We're betting that the opponent doesn't have
1323 // a move that will reduce the score by more than FutilityMargins[int(depth)]
1324 // if we do a null move.
1327 && depth < RazorDepth
1328 && staticValue - futility_margin(depth, 0) >= beta)
1329 return staticValue - futility_margin(depth, 0);
1335 && !value_is_mate(beta)
1336 && ok_to_do_nullmove(pos)
1337 && staticValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1339 ss[ply].currentMove = MOVE_NULL;
1341 pos.do_null_move(st);
1343 // Null move dynamic reduction based on depth
1344 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1346 // Null move dynamic reduction based on value
1347 if (staticValue - beta > PawnValueMidgame)
1350 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1352 pos.undo_null_move();
1354 if (nullValue >= beta)
1356 if (depth < 6 * OnePly)
1359 // Do zugzwang verification search
1360 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1364 // The null move failed low, which means that we may be faced with
1365 // some kind of threat. If the previous move was reduced, check if
1366 // the move that refuted the null move was somehow connected to the
1367 // move which was reduced. If a connection is found, return a fail
1368 // low score (which will cause the reduced move to fail high in the
1369 // parent node, which will trigger a re-search with full depth).
1370 if (nullValue == value_mated_in(ply + 2))
1373 ss[ply].threatMove = ss[ply + 1].currentMove;
1374 if ( depth < ThreatDepth
1375 && ss[ply - 1].reduction
1376 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1380 // Null move search not allowed, try razoring
1381 else if ( !value_is_mate(beta)
1383 && depth < RazorDepth
1384 && staticValue < beta - (NullMoveMargin + 16 * depth)
1385 && ss[ply - 1].currentMove != MOVE_NULL
1386 && ttMove == MOVE_NONE
1387 && !pos.has_pawn_on_7th(pos.side_to_move()))
1389 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1390 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1395 // Go with internal iterative deepening if we don't have a TT move
1396 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1397 !isCheck && ss[ply].eval >= beta - IIDMargin)
1399 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1400 ttMove = ss[ply].pv[ply];
1401 tte = TT.retrieve(posKey);
1404 // Initialize a MovePicker object for the current position, and prepare
1405 // to search all moves.
1406 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1409 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1410 while ( bestValue < beta
1411 && (move = mp.get_next_move()) != MOVE_NONE
1412 && !TM.thread_should_stop(threadID))
1414 assert(move_is_ok(move));
1416 if (move == excludedMove)
1419 moveIsCheck = pos.move_is_check(move, ci);
1420 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1421 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1423 // Decide the new search depth
1424 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1426 // Singular extension search. We extend the TT move if its value is much better than
1427 // its siblings. To verify this we do a reduced search on all the other moves but the
1428 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1429 if ( depth >= 8 * OnePly
1431 && move == tte->move()
1432 && !excludedMove // Do not allow recursive single-reply search
1434 && is_lower_bound(tte->type())
1435 && tte->depth() >= depth - 3 * OnePly)
1437 Value ttValue = value_from_tt(tte->value(), ply);
1439 if (abs(ttValue) < VALUE_KNOWN_WIN)
1441 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1443 if (excValue < ttValue - SingleReplyMargin)
1448 newDepth = depth - OnePly + ext;
1450 // Update current move
1451 movesSearched[moveCount++] = ss[ply].currentMove = move;
1456 && !captureOrPromotion
1457 && !move_is_castle(move)
1460 // Move count based pruning
1461 if ( moveCount >= futility_move_count(depth)
1462 && ok_to_prune(pos, move, ss[ply].threatMove)
1463 && bestValue > value_mated_in(PLY_MAX))
1466 // Value based pruning
1467 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1468 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1469 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1471 if (futilityValueScaled < beta)
1473 if (futilityValueScaled > bestValue)
1474 bestValue = futilityValueScaled;
1479 // Make and search the move
1480 pos.do_move(move, st, ci, moveIsCheck);
1482 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1483 // if the move fails high will be re-searched at full depth.
1484 bool doFullDepthSearch = true;
1486 if ( depth >= 3*OnePly
1488 && !captureOrPromotion
1489 && !move_is_castle(move)
1490 && !move_is_killer(move, ss[ply]))
1492 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1493 if (ss[ply].reduction)
1495 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1496 doFullDepthSearch = (value >= beta);
1500 if (doFullDepthSearch) // Go with full depth non-pv search
1502 ss[ply].reduction = Depth(0);
1503 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1505 pos.undo_move(move);
1507 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1510 if (value > bestValue)
1516 if (value == value_mate_in(ply + 1))
1517 ss[ply].mateKiller = move;
1521 if ( TM.active_threads() > 1
1523 && depth >= MinimumSplitDepth
1525 && TM.available_thread_exists(threadID)
1527 && !TM.thread_should_stop(threadID)
1528 && TM.split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1529 depth, &moveCount, &mp, threadID, false))
1533 // All legal moves have been searched. A special case: If there were
1534 // no legal moves, it must be mate or stalemate.
1536 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1538 // If the search is not aborted, update the transposition table,
1539 // history counters, and killer moves.
1540 if (AbortSearch || TM.thread_should_stop(threadID))
1543 if (bestValue < beta)
1544 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1547 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1548 move = ss[ply].pv[ply];
1549 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1550 if (!pos.move_is_capture_or_promotion(move))
1552 update_history(pos, move, depth, movesSearched, moveCount);
1553 update_killers(move, ss[ply]);
1558 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1564 // qsearch() is the quiescence search function, which is called by the main
1565 // search function when the remaining depth is zero (or, to be more precise,
1566 // less than OnePly).
1568 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1569 Depth depth, int ply, int threadID) {
1571 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1572 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1574 assert(ply >= 0 && ply < PLY_MAX);
1575 assert(threadID >= 0 && threadID < TM.active_threads());
1580 Value staticValue, bestValue, value, futilityBase, futilityValue;
1581 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1582 const TTEntry* tte = NULL;
1584 bool pvNode = (beta - alpha != 1);
1585 Value oldAlpha = alpha;
1587 // Initialize, and make an early exit in case of an aborted search,
1588 // an instant draw, maximum ply reached, etc.
1589 init_node(ss, ply, threadID);
1591 // After init_node() that calls poll()
1592 if (AbortSearch || TM.thread_should_stop(threadID))
1595 if (pos.is_draw() || ply >= PLY_MAX - 1)
1598 // Transposition table lookup. At PV nodes, we don't use the TT for
1599 // pruning, but only for move ordering.
1600 tte = TT.retrieve(pos.get_key());
1601 ttMove = (tte ? tte->move() : MOVE_NONE);
1603 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1605 assert(tte->type() != VALUE_TYPE_EVAL);
1607 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1608 return value_from_tt(tte->value(), ply);
1611 isCheck = pos.is_check();
1613 // Evaluate the position statically
1615 staticValue = -VALUE_INFINITE;
1616 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1617 staticValue = value_from_tt(tte->value(), ply);
1619 staticValue = evaluate(pos, ei, threadID);
1623 ss[ply].eval = staticValue;
1624 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1627 // Initialize "stand pat score", and return it immediately if it is
1629 bestValue = staticValue;
1631 if (bestValue >= beta)
1633 // Store the score to avoid a future costly evaluation() call
1634 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1635 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1640 if (bestValue > alpha)
1643 // If we are near beta then try to get a cutoff pushing checks a bit further
1644 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1646 // Initialize a MovePicker object for the current position, and prepare
1647 // to search the moves. Because the depth is <= 0 here, only captures,
1648 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1649 // and we are near beta) will be generated.
1650 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1652 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1653 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1655 // Loop through the moves until no moves remain or a beta cutoff
1657 while ( alpha < beta
1658 && (move = mp.get_next_move()) != MOVE_NONE)
1660 assert(move_is_ok(move));
1662 moveIsCheck = pos.move_is_check(move, ci);
1664 // Update current move
1666 ss[ply].currentMove = move;
1674 && !move_is_promotion(move)
1675 && !pos.move_is_passed_pawn_push(move))
1677 futilityValue = futilityBase
1678 + pos.endgame_value_of_piece_on(move_to(move))
1679 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1681 if (futilityValue < alpha)
1683 if (futilityValue > bestValue)
1684 bestValue = futilityValue;
1689 // Detect blocking evasions that are candidate to be pruned
1690 evasionPrunable = isCheck
1691 && bestValue != -VALUE_INFINITE
1692 && !pos.move_is_capture(move)
1693 && pos.type_of_piece_on(move_from(move)) != KING
1694 && !pos.can_castle(pos.side_to_move());
1696 // Don't search moves with negative SEE values
1697 if ( (!isCheck || evasionPrunable)
1700 && !move_is_promotion(move)
1701 && pos.see_sign(move) < 0)
1704 // Make and search the move
1705 pos.do_move(move, st, ci, moveIsCheck);
1706 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1707 pos.undo_move(move);
1709 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1712 if (value > bestValue)
1723 // All legal moves have been searched. A special case: If we're in check
1724 // and no legal moves were found, it is checkmate.
1725 if (!moveCount && pos.is_check()) // Mate!
1726 return value_mated_in(ply);
1728 // Update transposition table
1729 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1730 if (bestValue <= oldAlpha)
1732 // If bestValue isn't changed it means it is still the static evaluation
1733 // of the node, so keep this info to avoid a future evaluation() call.
1734 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1735 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1737 else if (bestValue >= beta)
1739 move = ss[ply].pv[ply];
1740 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1742 // Update killers only for good checking moves
1743 if (!pos.move_is_capture_or_promotion(move))
1744 update_killers(move, ss[ply]);
1747 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1749 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1755 // sp_search() is used to search from a split point. This function is called
1756 // by each thread working at the split point. It is similar to the normal
1757 // search() function, but simpler. Because we have already probed the hash
1758 // table, done a null move search, and searched the first move before
1759 // splitting, we don't have to repeat all this work in sp_search(). We
1760 // also don't need to store anything to the hash table here: This is taken
1761 // care of after we return from the split point.
1763 void sp_search(SplitPoint* sp, int threadID) {
1765 assert(threadID >= 0 && threadID < TM.active_threads());
1766 assert(TM.active_threads() > 1);
1768 Position pos(*sp->pos);
1770 SearchStack* ss = sp->sstack[threadID];
1771 Value value = -VALUE_INFINITE;
1774 bool isCheck = pos.is_check();
1775 bool useFutilityPruning = sp->depth < 7 * OnePly //FIXME: sync with search
1778 while ( lock_grab_bool(&(sp->lock))
1779 && sp->bestValue < sp->beta
1780 && !TM.thread_should_stop(threadID)
1781 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1783 moveCount = ++sp->moves;
1784 lock_release(&(sp->lock));
1786 assert(move_is_ok(move));
1788 bool moveIsCheck = pos.move_is_check(move, ci);
1789 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1791 ss[sp->ply].currentMove = move;
1793 // Decide the new search depth
1795 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1796 Depth newDepth = sp->depth - OnePly + ext;
1799 if ( useFutilityPruning
1801 && !captureOrPromotion)
1803 // Move count based pruning
1804 if ( moveCount >= futility_move_count(sp->depth)
1805 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1806 && sp->bestValue > value_mated_in(PLY_MAX))
1809 // Value based pruning
1810 Value futilityValueScaled = sp->futilityValue - moveCount * 8; //FIXME: sync with search
1812 if (futilityValueScaled < sp->beta)
1814 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1816 lock_grab(&(sp->lock));
1817 if (futilityValueScaled > sp->bestValue)
1818 sp->bestValue = futilityValueScaled;
1819 lock_release(&(sp->lock));
1825 // Make and search the move.
1827 pos.do_move(move, st, ci, moveIsCheck);
1829 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1830 // if the move fails high will be re-searched at full depth.
1831 bool doFullDepthSearch = true;
1834 && !captureOrPromotion
1835 && !move_is_castle(move)
1836 && !move_is_killer(move, ss[sp->ply]))
1838 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1839 if (ss[sp->ply].reduction)
1841 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1842 doFullDepthSearch = (value >= sp->beta);
1846 if (doFullDepthSearch) // Go with full depth non-pv search
1848 ss[sp->ply].reduction = Depth(0);
1849 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1851 pos.undo_move(move);
1853 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1855 if (TM.thread_should_stop(threadID))
1857 lock_grab(&(sp->lock));
1862 if (value > sp->bestValue) // Less then 2% of cases
1864 lock_grab(&(sp->lock));
1865 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1867 sp->bestValue = value;
1868 if (sp->bestValue >= sp->beta)
1870 sp_update_pv(sp->parentSstack, ss, sp->ply);
1871 for (int i = 0; i < TM.active_threads(); i++)
1872 if (i != threadID && (i == sp->master || sp->slaves[i]))
1873 TM.set_stop_request(i);
1875 sp->finished = true;
1878 lock_release(&(sp->lock));
1882 /* Here we have the lock still grabbed */
1884 // If this is the master thread and we have been asked to stop because of
1885 // a beta cutoff higher up in the tree, stop all slave threads. Note that
1886 // thread_should_stop(threadID) does not imply that 'stop' flag is set, so
1887 // do this explicitly now, under lock protection.
1888 if (sp->master == threadID && TM.thread_should_stop(threadID))
1889 for (int i = 0; i < TM.active_threads(); i++)
1890 if (sp->slaves[i] || i == threadID)
1891 TM.set_stop_request(i);
1894 sp->slaves[threadID] = 0;
1896 lock_release(&(sp->lock));
1900 // sp_search_pv() is used to search from a PV split point. This function
1901 // is called by each thread working at the split point. It is similar to
1902 // the normal search_pv() function, but simpler. Because we have already
1903 // probed the hash table and searched the first move before splitting, we
1904 // don't have to repeat all this work in sp_search_pv(). We also don't
1905 // need to store anything to the hash table here: This is taken care of
1906 // after we return from the split point.
1908 void sp_search_pv(SplitPoint* sp, int threadID) {
1910 assert(threadID >= 0 && threadID < TM.active_threads());
1911 assert(TM.active_threads() > 1);
1913 Position pos(*sp->pos);
1915 SearchStack* ss = sp->sstack[threadID];
1916 Value value = -VALUE_INFINITE;
1920 while ( lock_grab_bool(&(sp->lock))
1921 && sp->alpha < sp->beta
1922 && !TM.thread_should_stop(threadID)
1923 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1925 moveCount = ++sp->moves;
1926 lock_release(&(sp->lock));
1928 assert(move_is_ok(move));
1930 bool moveIsCheck = pos.move_is_check(move, ci);
1931 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1933 ss[sp->ply].currentMove = move;
1935 // Decide the new search depth
1937 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1938 Depth newDepth = sp->depth - OnePly + ext;
1940 // Make and search the move.
1942 pos.do_move(move, st, ci, moveIsCheck);
1944 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1945 // if the move fails high will be re-searched at full depth.
1946 bool doFullDepthSearch = true;
1949 && !captureOrPromotion
1950 && !move_is_castle(move)
1951 && !move_is_killer(move, ss[sp->ply]))
1953 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
1954 if (ss[sp->ply].reduction)
1956 Value localAlpha = sp->alpha;
1957 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1958 doFullDepthSearch = (value > localAlpha);
1962 if (doFullDepthSearch) // Go with full depth non-pv search
1964 Value localAlpha = sp->alpha;
1965 ss[sp->ply].reduction = Depth(0);
1966 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
1968 if (value > localAlpha && value < sp->beta)
1970 // If another thread has failed high then sp->alpha has been increased
1971 // to be higher or equal then beta, if so, avoid to start a PV search.
1972 localAlpha = sp->alpha;
1973 if (localAlpha < sp->beta)
1974 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
1976 assert(TM.thread_should_stop(threadID));
1979 pos.undo_move(move);
1981 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1983 if (TM.thread_should_stop(threadID))
1985 lock_grab(&(sp->lock));
1990 if (value > sp->bestValue) // Less then 2% of cases
1992 lock_grab(&(sp->lock));
1993 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1995 sp->bestValue = value;
1996 if (value > sp->alpha)
1998 // Ask threads to stop before to modify sp->alpha
1999 if (value >= sp->beta)
2001 for (int i = 0; i < TM.active_threads(); i++)
2002 if (i != threadID && (i == sp->master || sp->slaves[i]))
2003 TM.set_stop_request(i);
2005 sp->finished = true;
2010 sp_update_pv(sp->parentSstack, ss, sp->ply);
2011 if (value == value_mate_in(sp->ply + 1))
2012 ss[sp->ply].mateKiller = move;
2015 lock_release(&(sp->lock));
2019 /* Here we have the lock still grabbed */
2021 // If this is the master thread and we have been asked to stop because of
2022 // a beta cutoff higher up in the tree, stop all slave threads. Note that
2023 // thread_should_stop(threadID) does not imply that 'stop' flag is set, so
2024 // do this explicitly now, under lock protection.
2025 if (sp->master == threadID && TM.thread_should_stop(threadID))
2026 for (int i = 0; i < TM.active_threads(); i++)
2027 if (sp->slaves[i] || i == threadID)
2028 TM.set_stop_request(i);
2031 sp->slaves[threadID] = 0;
2033 lock_release(&(sp->lock));
2037 // init_node() is called at the beginning of all the search functions
2038 // (search(), search_pv(), qsearch(), and so on) and initializes the
2039 // search stack object corresponding to the current node. Once every
2040 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2041 // for user input and checks whether it is time to stop the search.
2043 void init_node(SearchStack ss[], int ply, int threadID) {
2045 assert(ply >= 0 && ply < PLY_MAX);
2046 assert(threadID >= 0 && threadID < TM.active_threads());
2048 TM.incrementNodeCounter(threadID);
2053 if (NodesSincePoll >= NodesBetweenPolls)
2060 ss[ply + 2].initKillers();
2061 TM.print_current_line(ss, ply, threadID);
2065 // update_pv() is called whenever a search returns a value > alpha.
2066 // It updates the PV in the SearchStack object corresponding to the
2069 void update_pv(SearchStack ss[], int ply) {
2071 assert(ply >= 0 && ply < PLY_MAX);
2075 ss[ply].pv[ply] = ss[ply].currentMove;
2077 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2078 ss[ply].pv[p] = ss[ply + 1].pv[p];
2080 ss[ply].pv[p] = MOVE_NONE;
2084 // sp_update_pv() is a variant of update_pv for use at split points. The
2085 // difference between the two functions is that sp_update_pv also updates
2086 // the PV at the parent node.
2088 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2090 assert(ply >= 0 && ply < PLY_MAX);
2094 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2096 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2097 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2099 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2103 // connected_moves() tests whether two moves are 'connected' in the sense
2104 // that the first move somehow made the second move possible (for instance
2105 // if the moving piece is the same in both moves). The first move is assumed
2106 // to be the move that was made to reach the current position, while the
2107 // second move is assumed to be a move from the current position.
2109 bool connected_moves(const Position& pos, Move m1, Move m2) {
2111 Square f1, t1, f2, t2;
2114 assert(move_is_ok(m1));
2115 assert(move_is_ok(m2));
2117 if (m2 == MOVE_NONE)
2120 // Case 1: The moving piece is the same in both moves
2126 // Case 2: The destination square for m2 was vacated by m1
2132 // Case 3: Moving through the vacated square
2133 if ( piece_is_slider(pos.piece_on(f2))
2134 && bit_is_set(squares_between(f2, t2), f1))
2137 // Case 4: The destination square for m2 is defended by the moving piece in m1
2138 p = pos.piece_on(t1);
2139 if (bit_is_set(pos.attacks_from(p, t1), t2))
2142 // Case 5: Discovered check, checking piece is the piece moved in m1
2143 if ( piece_is_slider(p)
2144 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2145 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2147 // discovered_check_candidates() works also if the Position's side to
2148 // move is the opposite of the checking piece.
2149 Color them = opposite_color(pos.side_to_move());
2150 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2152 if (bit_is_set(dcCandidates, f2))
2159 // value_is_mate() checks if the given value is a mate one
2160 // eventually compensated for the ply.
2162 bool value_is_mate(Value value) {
2164 assert(abs(value) <= VALUE_INFINITE);
2166 return value <= value_mated_in(PLY_MAX)
2167 || value >= value_mate_in(PLY_MAX);
2171 // move_is_killer() checks if the given move is among the
2172 // killer moves of that ply.
2174 bool move_is_killer(Move m, const SearchStack& ss) {
2176 const Move* k = ss.killers;
2177 for (int i = 0; i < KILLER_MAX; i++, k++)
2185 // extension() decides whether a move should be searched with normal depth,
2186 // or with extended depth. Certain classes of moves (checking moves, in
2187 // particular) are searched with bigger depth than ordinary moves and in
2188 // any case are marked as 'dangerous'. Note that also if a move is not
2189 // extended, as example because the corresponding UCI option is set to zero,
2190 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2192 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2193 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2195 assert(m != MOVE_NONE);
2197 Depth result = Depth(0);
2198 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2203 result += CheckExtension[pvNode];
2206 result += SingleEvasionExtension[pvNode];
2209 result += MateThreatExtension[pvNode];
2212 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2214 Color c = pos.side_to_move();
2215 if (relative_rank(c, move_to(m)) == RANK_7)
2217 result += PawnPushTo7thExtension[pvNode];
2220 if (pos.pawn_is_passed(c, move_to(m)))
2222 result += PassedPawnExtension[pvNode];
2227 if ( captureOrPromotion
2228 && pos.type_of_piece_on(move_to(m)) != PAWN
2229 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2230 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2231 && !move_is_promotion(m)
2234 result += PawnEndgameExtension[pvNode];
2239 && captureOrPromotion
2240 && pos.type_of_piece_on(move_to(m)) != PAWN
2241 && pos.see_sign(m) >= 0)
2247 return Min(result, OnePly);
2251 // ok_to_do_nullmove() looks at the current position and decides whether
2252 // doing a 'null move' should be allowed. In order to avoid zugzwang
2253 // problems, null moves are not allowed when the side to move has very
2254 // little material left. Currently, the test is a bit too simple: Null
2255 // moves are avoided only when the side to move has only pawns left.
2256 // It's probably a good idea to avoid null moves in at least some more
2257 // complicated endgames, e.g. KQ vs KR. FIXME
2259 bool ok_to_do_nullmove(const Position& pos) {
2261 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2265 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2266 // non-tactical moves late in the move list close to the leaves are
2267 // candidates for pruning.
2269 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2271 assert(move_is_ok(m));
2272 assert(threat == MOVE_NONE || move_is_ok(threat));
2273 assert(!pos.move_is_check(m));
2274 assert(!pos.move_is_capture_or_promotion(m));
2275 assert(!pos.move_is_passed_pawn_push(m));
2277 Square mfrom, mto, tfrom, tto;
2279 // Prune if there isn't any threat move
2280 if (threat == MOVE_NONE)
2283 mfrom = move_from(m);
2285 tfrom = move_from(threat);
2286 tto = move_to(threat);
2288 // Case 1: Don't prune moves which move the threatened piece
2292 // Case 2: If the threatened piece has value less than or equal to the
2293 // value of the threatening piece, don't prune move which defend it.
2294 if ( pos.move_is_capture(threat)
2295 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2296 || pos.type_of_piece_on(tfrom) == KING)
2297 && pos.move_attacks_square(m, tto))
2300 // Case 3: If the moving piece in the threatened move is a slider, don't
2301 // prune safe moves which block its ray.
2302 if ( piece_is_slider(pos.piece_on(tfrom))
2303 && bit_is_set(squares_between(tfrom, tto), mto)
2304 && pos.see_sign(m) >= 0)
2311 // ok_to_use_TT() returns true if a transposition table score
2312 // can be used at a given point in search.
2314 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2316 Value v = value_from_tt(tte->value(), ply);
2318 return ( tte->depth() >= depth
2319 || v >= Max(value_mate_in(PLY_MAX), beta)
2320 || v < Min(value_mated_in(PLY_MAX), beta))
2322 && ( (is_lower_bound(tte->type()) && v >= beta)
2323 || (is_upper_bound(tte->type()) && v < beta));
2327 // refine_eval() returns the transposition table score if
2328 // possible otherwise falls back on static position evaluation.
2330 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2335 Value v = value_from_tt(tte->value(), ply);
2337 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2338 || (is_upper_bound(tte->type()) && v < defaultEval))
2345 // update_history() registers a good move that produced a beta-cutoff
2346 // in history and marks as failures all the other moves of that ply.
2348 void update_history(const Position& pos, Move move, Depth depth,
2349 Move movesSearched[], int moveCount) {
2353 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2355 for (int i = 0; i < moveCount - 1; i++)
2357 m = movesSearched[i];
2361 if (!pos.move_is_capture_or_promotion(m))
2362 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2367 // update_killers() add a good move that produced a beta-cutoff
2368 // among the killer moves of that ply.
2370 void update_killers(Move m, SearchStack& ss) {
2372 if (m == ss.killers[0])
2375 for (int i = KILLER_MAX - 1; i > 0; i--)
2376 ss.killers[i] = ss.killers[i - 1];
2382 // update_gains() updates the gains table of a non-capture move given
2383 // the static position evaluation before and after the move.
2385 void update_gains(const Position& pos, Move m, Value before, Value after) {
2388 && before != VALUE_NONE
2389 && after != VALUE_NONE
2390 && pos.captured_piece() == NO_PIECE_TYPE
2391 && !move_is_castle(m)
2392 && !move_is_promotion(m))
2393 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2397 // current_search_time() returns the number of milliseconds which have passed
2398 // since the beginning of the current search.
2400 int current_search_time() {
2402 return get_system_time() - SearchStartTime;
2406 // nps() computes the current nodes/second count.
2410 int t = current_search_time();
2411 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2415 // poll() performs two different functions: It polls for user input, and it
2416 // looks at the time consumed so far and decides if it's time to abort the
2421 static int lastInfoTime;
2422 int t = current_search_time();
2427 // We are line oriented, don't read single chars
2428 std::string command;
2430 if (!std::getline(std::cin, command))
2433 if (command == "quit")
2436 PonderSearch = false;
2440 else if (command == "stop")
2443 PonderSearch = false;
2445 else if (command == "ponderhit")
2449 // Print search information
2453 else if (lastInfoTime > t)
2454 // HACK: Must be a new search where we searched less than
2455 // NodesBetweenPolls nodes during the first second of search.
2458 else if (t - lastInfoTime >= 1000)
2461 lock_grab(&TM.IOLock);
2466 if (dbg_show_hit_rate)
2467 dbg_print_hit_rate();
2469 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2470 << " time " << t << " hashfull " << TT.full() << endl;
2472 lock_release(&TM.IOLock);
2474 if (ShowCurrentLine)
2475 TM.threads[0].printCurrentLineRequest = true;
2478 // Should we stop the search?
2482 bool stillAtFirstMove = RootMoveNumber == 1
2483 && !AspirationFailLow
2484 && t > MaxSearchTime + ExtraSearchTime;
2486 bool noMoreTime = t > AbsoluteMaxSearchTime
2487 || stillAtFirstMove;
2489 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2490 || (ExactMaxTime && t >= ExactMaxTime)
2491 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2496 // ponderhit() is called when the program is pondering (i.e. thinking while
2497 // it's the opponent's turn to move) in order to let the engine know that
2498 // it correctly predicted the opponent's move.
2502 int t = current_search_time();
2503 PonderSearch = false;
2505 bool stillAtFirstMove = RootMoveNumber == 1
2506 && !AspirationFailLow
2507 && t > MaxSearchTime + ExtraSearchTime;
2509 bool noMoreTime = t > AbsoluteMaxSearchTime
2510 || stillAtFirstMove;
2512 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2517 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2519 void init_ss_array(SearchStack ss[]) {
2521 for (int i = 0; i < 3; i++)
2524 ss[i].initKillers();
2529 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2530 // while the program is pondering. The point is to work around a wrinkle in
2531 // the UCI protocol: When pondering, the engine is not allowed to give a
2532 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2533 // We simply wait here until one of these commands is sent, and return,
2534 // after which the bestmove and pondermove will be printed (in id_loop()).
2536 void wait_for_stop_or_ponderhit() {
2538 std::string command;
2542 if (!std::getline(std::cin, command))
2545 if (command == "quit")
2550 else if (command == "ponderhit" || command == "stop")
2556 // init_thread() is the function which is called when a new thread is
2557 // launched. It simply calls the idle_loop() function with the supplied
2558 // threadID. There are two versions of this function; one for POSIX
2559 // threads and one for Windows threads.
2561 #if !defined(_MSC_VER)
2563 void* init_thread(void *threadID) {
2565 TM.idle_loop(*(int*)threadID, NULL);
2571 DWORD WINAPI init_thread(LPVOID threadID) {
2573 TM.idle_loop(*(int*)threadID, NULL);
2580 /// The ThreadsManager class
2582 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2583 // get_beta_counters() are getters/setters for the per thread
2584 // counters used to sort the moves at root.
2586 void ThreadsManager::resetNodeCounters() {
2588 for (int i = 0; i < MAX_THREADS; i++)
2589 threads[i].nodes = 0ULL;
2592 void ThreadsManager::resetBetaCounters() {
2594 for (int i = 0; i < MAX_THREADS; i++)
2595 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2598 int64_t ThreadsManager::nodes_searched() const {
2600 int64_t result = 0ULL;
2601 for (int i = 0; i < ActiveThreads; i++)
2602 result += threads[i].nodes;
2607 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2610 for (int i = 0; i < MAX_THREADS; i++)
2612 our += threads[i].betaCutOffs[us];
2613 their += threads[i].betaCutOffs[opposite_color(us)];
2618 // idle_loop() is where the threads are parked when they have no work to do.
2619 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2620 // object for which the current thread is the master.
2622 void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2624 assert(threadID >= 0 && threadID < MAX_THREADS);
2626 threads[threadID].running = true;
2628 while (!AllThreadsShouldExit || threadID == 0)
2630 // If we are not thinking, wait for a condition to be signaled
2631 // instead of wasting CPU time polling for work.
2632 while ( threadID != 0
2633 && !AllThreadsShouldExit
2634 && (AllThreadsShouldSleep || threadID >= ActiveThreads))
2637 threads[threadID].sleeping = true;
2639 #if !defined(_MSC_VER)
2640 pthread_mutex_lock(&WaitLock);
2641 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2642 pthread_cond_wait(&WaitCond, &WaitLock);
2644 pthread_mutex_unlock(&WaitLock);
2646 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2650 // Out of the while loop to avoid races in case thread is woken up but
2651 // while condition still holds true so that is put to sleep again.
2652 threads[threadID].sleeping = false;
2654 // If this thread has been assigned work, launch a search
2655 if (threads[threadID].workIsWaiting)
2657 assert(!threads[threadID].idle);
2659 threads[threadID].workIsWaiting = false;
2660 if (threads[threadID].splitPoint->pvNode)
2661 sp_search_pv(threads[threadID].splitPoint, threadID);
2663 sp_search(threads[threadID].splitPoint, threadID);
2665 threads[threadID].idle = true;
2668 // If this thread is the master of a split point and all threads have
2669 // finished their work at this split point, return from the idle loop.
2670 if (waitSp != NULL && waitSp->cpus == 0)
2674 threads[threadID].running = false;
2678 // init_threads() is called during startup. It launches all helper threads,
2679 // and initializes the split point stack and the global locks and condition
2682 void ThreadsManager::init_threads() {
2687 #if !defined(_MSC_VER)
2688 pthread_t pthread[1];
2691 // Initialize global locks
2692 lock_init(&MPLock, NULL);
2693 lock_init(&IOLock, NULL);
2695 // Initialize SplitPointStack locks
2696 for (int i = 0; i < MAX_THREADS; i++)
2697 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2699 SplitPointStack[i][j].parent = NULL;
2700 lock_init(&(SplitPointStack[i][j].lock), NULL);
2703 #if !defined(_MSC_VER)
2704 pthread_mutex_init(&WaitLock, NULL);
2705 pthread_cond_init(&WaitCond, NULL);
2707 for (i = 0; i < MAX_THREADS; i++)
2708 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2711 // Will be set just before program exits to properly end the threads
2712 AllThreadsShouldExit = false;
2714 // Threads will be put to sleep as soon as created
2715 AllThreadsShouldSleep = true;
2717 // All threads except the main thread should be initialized to idle state
2719 for (i = 1; i < MAX_THREADS; i++)
2720 threads[i].idle = true;
2722 // Launch the helper threads
2723 for (i = 1; i < MAX_THREADS; i++)
2726 #if !defined(_MSC_VER)
2727 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2730 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
2735 cout << "Failed to create thread number " << i << endl;
2736 Application::exit_with_failure();
2739 // Wait until the thread has finished launching and is gone to sleep
2740 while (!threads[i].running || !threads[i].sleeping);
2745 // exit_threads() is called when the program exits. It makes all the
2746 // helper threads exit cleanly.
2748 void ThreadsManager::exit_threads() {
2750 ActiveThreads = MAX_THREADS; // HACK
2751 AllThreadsShouldSleep = true; // HACK
2752 wake_sleeping_threads();
2753 AllThreadsShouldExit = true;
2754 for (int i = 1; i < MAX_THREADS; i++)
2756 threads[i].stopRequest = true;
2757 while (threads[i].running);
2760 // Now we can safely destroy the locks
2761 for (int i = 0; i < MAX_THREADS; i++)
2762 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2763 lock_destroy(&(SplitPointStack[i][j].lock));
2767 // thread_should_stop() checks whether the thread with a given threadID has
2768 // been asked to stop, directly or indirectly. This can happen if a beta
2769 // cutoff has occurred in the thread's currently active split point, or in
2770 // some ancestor of the current split point.
2772 bool ThreadsManager::thread_should_stop(int threadID) const {
2774 assert(threadID >= 0 && threadID < ActiveThreads);
2778 if (threads[threadID].stopRequest)
2781 if (ActiveThreads <= 2)
2784 for (sp = threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2792 // thread_is_available() checks whether the thread with threadID "slave" is
2793 // available to help the thread with threadID "master" at a split point. An
2794 // obvious requirement is that "slave" must be idle. With more than two
2795 // threads, this is not by itself sufficient: If "slave" is the master of
2796 // some active split point, it is only available as a slave to the other
2797 // threads which are busy searching the split point at the top of "slave"'s
2798 // split point stack (the "helpful master concept" in YBWC terminology).
2800 bool ThreadsManager::thread_is_available(int slave, int master) const {
2802 assert(slave >= 0 && slave < ActiveThreads);
2803 assert(master >= 0 && master < ActiveThreads);
2804 assert(ActiveThreads > 1);
2806 if (!threads[slave].idle || slave == master)
2809 // Make a local copy to be sure doesn't change under our feet
2810 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2812 if (localActiveSplitPoints == 0)
2813 // No active split points means that the thread is available as
2814 // a slave for any other thread.
2817 if (ActiveThreads == 2)
2820 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2821 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2822 // could have been set to 0 by another thread leading to an out of bound access.
2823 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2830 // available_thread_exists() tries to find an idle thread which is available as
2831 // a slave for the thread with threadID "master".
2833 bool ThreadsManager::available_thread_exists(int master) const {
2835 assert(master >= 0 && master < ActiveThreads);
2836 assert(ActiveThreads > 1);
2838 for (int i = 0; i < ActiveThreads; i++)
2839 if (thread_is_available(i, master))
2846 // split() does the actual work of distributing the work at a node between
2847 // several threads at PV nodes. If it does not succeed in splitting the
2848 // node (because no idle threads are available, or because we have no unused
2849 // split point objects), the function immediately returns false. If
2850 // splitting is possible, a SplitPoint object is initialized with all the
2851 // data that must be copied to the helper threads (the current position and
2852 // search stack, alpha, beta, the search depth, etc.), and we tell our
2853 // helper threads that they have been assigned work. This will cause them
2854 // to instantly leave their idle loops and call sp_search_pv(). When all
2855 // threads have returned from sp_search_pv (or, equivalently, when
2856 // splitPoint->cpus becomes 0), split() returns true.
2858 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2859 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2860 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2863 assert(sstck != NULL);
2864 assert(ply >= 0 && ply < PLY_MAX);
2865 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2866 assert(!pvNode || *alpha < *beta);
2867 assert(*beta <= VALUE_INFINITE);
2868 assert(depth > Depth(0));
2869 assert(master >= 0 && master < ActiveThreads);
2870 assert(ActiveThreads > 1);
2872 SplitPoint* splitPoint;
2876 // If no other thread is available to help us, or if we have too many
2877 // active split points, don't split.
2878 if ( !available_thread_exists(master)
2879 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2881 lock_release(&MPLock);
2885 // Pick the next available split point object from the split point stack
2886 splitPoint = SplitPointStack[master] + threads[master].activeSplitPoints;
2887 threads[master].activeSplitPoints++;
2889 // Initialize the split point object
2890 splitPoint->parent = threads[master].splitPoint;
2891 splitPoint->finished = false;
2892 splitPoint->ply = ply;
2893 splitPoint->depth = depth;
2894 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2895 splitPoint->beta = *beta;
2896 splitPoint->pvNode = pvNode;
2897 splitPoint->bestValue = *bestValue;
2898 splitPoint->futilityValue = futilityValue;
2899 splitPoint->master = master;
2900 splitPoint->mp = mp;
2901 splitPoint->moves = *moves;
2902 splitPoint->cpus = 1;
2903 splitPoint->pos = &p;
2904 splitPoint->parentSstack = sstck;
2905 for (int i = 0; i < ActiveThreads; i++)
2906 splitPoint->slaves[i] = 0;
2908 threads[master].splitPoint = splitPoint;
2910 // If we are here it means we are not idle
2911 assert(!threads[master].idle);
2913 // Following assert could fail because we could be slave of a master
2914 // thread that has just raised a stop request. Note that stopRequest
2915 // can be changed with only splitPoint::lock held, not with MPLock.
2916 /* assert(!threads[master].stopRequest); */
2918 // Allocate available threads setting idle flag to false
2919 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2920 if (thread_is_available(i, master))
2922 threads[i].idle = false;
2923 threads[i].stopRequest = false;
2924 threads[i].splitPoint = splitPoint;
2925 splitPoint->slaves[i] = 1;
2929 assert(splitPoint->cpus > 1);
2931 // We can release the lock because master and slave threads are already booked
2932 lock_release(&MPLock);
2934 // Tell the threads that they have work to do. This will make them leave
2935 // their idle loop. But before copy search stack tail for each thread.
2936 for (int i = 0; i < ActiveThreads; i++)
2937 if (i == master || splitPoint->slaves[i])
2939 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2940 threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
2943 // Everything is set up. The master thread enters the idle loop, from
2944 // which it will instantly launch a search, because its workIsWaiting
2945 // slot is 'true'. We send the split point as a second parameter to the
2946 // idle loop, which means that the main thread will return from the idle
2947 // loop when all threads have finished their work at this split point
2948 // (i.e. when splitPoint->cpus == 0).
2949 idle_loop(master, splitPoint);
2951 // We have returned from the idle loop, which means that all threads are
2952 // finished. Update alpha, beta and bestValue, and return.
2956 *alpha = splitPoint->alpha;
2958 *beta = splitPoint->beta;
2959 *bestValue = splitPoint->bestValue;
2960 threads[master].stopRequest = false;
2961 threads[master].idle = false;
2962 threads[master].activeSplitPoints--;
2963 threads[master].splitPoint = splitPoint->parent;
2965 lock_release(&MPLock);
2970 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2971 // to start a new search from the root.
2973 void ThreadsManager::wake_sleeping_threads() {
2975 assert(AllThreadsShouldSleep);
2976 assert(ActiveThreads > 0);
2978 AllThreadsShouldSleep = false;
2980 if (ActiveThreads == 1)
2983 for (int i = 1; i < ActiveThreads; i++)
2985 assert(threads[i].sleeping == true);
2987 threads[i].idle = true;
2988 threads[i].workIsWaiting = false;
2991 #if !defined(_MSC_VER)
2992 pthread_mutex_lock(&WaitLock);
2993 pthread_cond_broadcast(&WaitCond);
2994 pthread_mutex_unlock(&WaitLock);
2996 for (int i = 1; i < MAX_THREADS; i++)
2997 SetEvent(SitIdleEvent[i]);
3000 // Wait for the threads to be all woken up
3001 for (int i = 1; i < ActiveThreads; i++)
3002 while (threads[i].sleeping);
3006 // put_threads_to_sleep() makes all the threads go to sleep just before
3007 // to leave think(), at the end of the search. threads should have already
3008 // finished the job and should be idle.
3010 void ThreadsManager::put_threads_to_sleep() {
3012 assert(!AllThreadsShouldSleep);
3014 AllThreadsShouldSleep = true;
3016 // Wait for the threads to be all sleeping and reset flags
3017 // to a known state.
3018 for (int i = 1; i < ActiveThreads; i++)
3020 while (!threads[i].sleeping);
3022 assert(threads[i].idle);
3023 assert(threads[i].running);
3024 assert(!threads[i].workIsWaiting);
3026 // These two flags can be in a random state
3027 threads[i].stopRequest = threads[i].printCurrentLineRequest = false;
3031 // print_current_line() prints _once_ the current line of search for a
3032 // given thread and then setup the print request for the next thread.
3033 // Called when the UCI option UCI_ShowCurrLine is 'true'.
3035 void ThreadsManager::print_current_line(SearchStack ss[], int ply, int threadID) {
3037 assert(ply >= 0 && ply < PLY_MAX);
3038 assert(threadID >= 0 && threadID < ActiveThreads);
3040 if (!threads[threadID].printCurrentLineRequest)
3044 threads[threadID].printCurrentLineRequest = false;
3046 if (!threads[threadID].idle)
3049 cout << "info currline " << (threadID + 1);
3050 for (int p = 0; p < ply; p++)
3051 cout << " " << ss[p].currentMove;
3054 lock_release(&IOLock);
3057 // Setup print request for the next thread ID
3058 if (threadID + 1 < ActiveThreads)
3059 threads[threadID + 1].printCurrentLineRequest = true;
3063 /// The RootMoveList class
3065 // RootMoveList c'tor
3067 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3069 SearchStack ss[PLY_MAX_PLUS_2];
3070 MoveStack mlist[MaxRootMoves];
3072 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3074 // Generate all legal moves
3075 MoveStack* last = generate_moves(pos, mlist);
3077 // Add each move to the moves[] array
3078 for (MoveStack* cur = mlist; cur != last; cur++)
3080 bool includeMove = includeAllMoves;
3082 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3083 includeMove = (searchMoves[k] == cur->move);
3088 // Find a quick score for the move
3090 pos.do_move(cur->move, st);
3091 moves[count].move = cur->move;
3092 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3093 moves[count].pv[0] = cur->move;
3094 moves[count].pv[1] = MOVE_NONE;
3095 pos.undo_move(cur->move);
3102 // RootMoveList simple methods definitions
3104 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3106 moves[moveNum].nodes = nodes;
3107 moves[moveNum].cumulativeNodes += nodes;
3110 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3112 moves[moveNum].ourBeta = our;
3113 moves[moveNum].theirBeta = their;
3116 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3120 for (j = 0; pv[j] != MOVE_NONE; j++)
3121 moves[moveNum].pv[j] = pv[j];
3123 moves[moveNum].pv[j] = MOVE_NONE;
3127 // RootMoveList::sort() sorts the root move list at the beginning of a new
3130 void RootMoveList::sort() {
3132 sort_multipv(count - 1); // Sort all items
3136 // RootMoveList::sort_multipv() sorts the first few moves in the root move
3137 // list by their scores and depths. It is used to order the different PVs
3138 // correctly in MultiPV mode.
3140 void RootMoveList::sort_multipv(int n) {
3144 for (i = 1; i <= n; i++)
3146 RootMove rm = moves[i];
3147 for (j = i; j > 0 && moves[j - 1] < rm; j--)
3148 moves[j] = moves[j - 1];