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/>.
42 #include "ucioption.h"
48 //// Local definitions
55 // IterationInfoType stores search results for each iteration
57 // Because we use relatively small (dynamic) aspiration window,
58 // there happens many fail highs and fail lows in root. And
59 // because we don't do researches in those cases, "value" stored
60 // here is not necessarily exact. Instead in case of fail high/low
61 // we guess what the right value might be and store our guess
62 // as a "speculated value" and then move on. Speculated values are
63 // used just to calculate aspiration window width, so also if are
64 // not exact is not big a problem.
66 struct IterationInfoType {
68 IterationInfoType(Value v = Value(0), Value sv = Value(0))
69 : value(v), speculatedValue(sv) {}
71 Value value, speculatedValue;
75 // The BetaCounterType class is used to order moves at ply one.
76 // Apart for the first one that has its score, following moves
77 // normally have score -VALUE_INFINITE, so are ordered according
78 // to the number of beta cutoffs occurred under their subtree during
79 // the last iteration. The counters are per thread variables to avoid
80 // concurrent accessing under SMP case.
82 struct BetaCounterType {
86 void add(Color us, Depth d, int threadID);
87 void read(Color us, int64_t& our, int64_t& their);
91 // The RootMove class is used for moves at the root at the tree. For each
92 // root move, we store a score, a node count, and a PV (really a refutation
93 // in the case of moves which fail low).
97 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
99 // RootMove::operator<() is the comparison function used when
100 // sorting the moves. A move m1 is considered to be better
101 // than a move m2 if it has a higher score, or if the moves
102 // have equal score but m1 has the higher node count.
103 bool RootMove::operator<(const RootMove& m) const {
105 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
110 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
111 Move pv[PLY_MAX_PLUS_2];
115 // The RootMoveList class is essentially an array of RootMove objects, with
116 // a handful of methods for accessing the data in the individual moves.
121 RootMoveList(Position& pos, Move searchMoves[]);
123 int move_count() const { return count; }
124 Move get_move(int moveNum) const { return moves[moveNum].move; }
125 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
126 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
127 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
128 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
130 void set_move_nodes(int moveNum, int64_t nodes);
131 void set_beta_counters(int moveNum, int64_t our, int64_t their);
132 void set_move_pv(int moveNum, const Move pv[]);
134 void sort_multipv(int n);
137 static const int MaxRootMoves = 500;
138 RootMove moves[MaxRootMoves];
145 // Search depth at iteration 1
146 const Depth InitialDepth = OnePly;
148 // Depth limit for selective search
149 const Depth SelectiveDepth = 7 * OnePly;
151 // Use internal iterative deepening?
152 const bool UseIIDAtPVNodes = true;
153 const bool UseIIDAtNonPVNodes = true;
155 // Internal iterative deepening margin. At Non-PV moves, when
156 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
157 // search when the static evaluation is at most IIDMargin below beta.
158 const Value IIDMargin = Value(0x100);
160 // Easy move margin. An easy move candidate must be at least this much
161 // better than the second best move.
162 const Value EasyMoveMargin = Value(0x200);
164 // Problem margin. If the score of the first move at iteration N+1 has
165 // dropped by more than this since iteration N, the boolean variable
166 // "Problem" is set to true, which will make the program spend some extra
167 // time looking for a better move.
168 const Value ProblemMargin = Value(0x28);
170 // No problem margin. If the boolean "Problem" is true, and a new move
171 // is found at the root which is less than NoProblemMargin worse than the
172 // best move from the previous iteration, Problem is set back to false.
173 const Value NoProblemMargin = Value(0x14);
175 // Null move margin. A null move search will not be done if the approximate
176 // evaluation of the position is more than NullMoveMargin below beta.
177 const Value NullMoveMargin = Value(0x300);
179 // If the TT move is at least SingleReplyMargin better then the
180 // remaining ones we will extend it.
181 const Value SingleReplyMargin = Value(0x20);
183 // Margins for futility pruning in the quiescence search, and at frontier
184 // and near frontier nodes.
185 const Value FutilityMarginQS = Value(0x80);
187 // Each move futility margin is decreased
188 const Value IncrementalFutilityMargin = Value(0x8);
190 // Depth limit for razoring
191 const Depth RazorDepth = 4 * OnePly;
193 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
194 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
196 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
197 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
200 /// Variables initialized by UCI options
202 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
203 int LMRPVMoves, LMRNonPVMoves;
205 // Depth limit for use of dynamic threat detection
208 // Last seconds noise filtering (LSN)
209 const bool UseLSNFiltering = true;
210 const int LSNTime = 4000; // In milliseconds
211 const Value LSNValue = value_from_centipawns(200);
212 bool loseOnTime = false;
214 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
215 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
216 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
218 // Iteration counters
220 BetaCounterType BetaCounter;
222 // Scores and number of times the best move changed for each iteration
223 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
224 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
229 // Time managment variables
232 int MaxNodes, MaxDepth;
233 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
234 bool InfiniteSearch, PonderSearch, StopOnPonderhit;
235 bool AbortSearch, Quit;
236 bool FailHigh, FailLow, Problem;
238 // Show current line?
239 bool ShowCurrentLine;
243 std::ofstream LogFile;
245 // MP related variables
246 int ActiveThreads = 1;
247 Depth MinimumSplitDepth;
248 int MaxThreadsPerSplitPoint;
249 Thread Threads[THREAD_MAX];
252 bool AllThreadsShouldExit = false;
253 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
256 #if !defined(_MSC_VER)
257 pthread_cond_t WaitCond;
258 pthread_mutex_t WaitLock;
260 HANDLE SitIdleEvent[THREAD_MAX];
263 // Node counters, used only by thread[0] but try to keep in different
264 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
266 int NodesBetweenPolls = 30000;
274 Value id_loop(const Position& pos, Move searchMoves[]);
275 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
276 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
277 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
278 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
279 void sp_search(SplitPoint* sp, int threadID);
280 void sp_search_pv(SplitPoint* sp, int threadID);
281 void init_node(SearchStack ss[], int ply, int threadID);
282 void update_pv(SearchStack ss[], int ply);
283 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
284 bool connected_moves(const Position& pos, Move m1, Move m2);
285 bool value_is_mate(Value value);
286 bool move_is_killer(Move m, const SearchStack& ss);
287 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
288 bool ok_to_do_nullmove(const Position& pos);
289 bool ok_to_prune(const Position& pos, Move m, Move threat);
290 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
291 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
292 void update_killers(Move m, SearchStack& ss);
294 bool fail_high_ply_1();
295 int current_search_time();
299 void print_current_line(SearchStack ss[], int ply, int threadID);
300 void wait_for_stop_or_ponderhit();
301 void init_ss_array(SearchStack ss[]);
303 void idle_loop(int threadID, SplitPoint* waitSp);
304 void init_split_point_stack();
305 void destroy_split_point_stack();
306 bool thread_should_stop(int threadID);
307 bool thread_is_available(int slave, int master);
308 bool idle_thread_exists(int master);
309 bool split(const Position& pos, SearchStack* ss, int ply,
310 Value *alpha, Value *beta, Value *bestValue,
311 const Value futilityValue, Depth depth, int *moves,
312 MovePicker *mp, int master, bool pvNode);
313 void wake_sleeping_threads();
315 #if !defined(_MSC_VER)
316 void *init_thread(void *threadID);
318 DWORD WINAPI init_thread(LPVOID threadID);
329 /// perft() is our utility to verify move generation is bug free. All the legal
330 /// moves up to given depth are generated and counted and the sum returned.
332 int perft(Position& pos, Depth depth)
336 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
338 // If we are at the last ply we don't need to do and undo
339 // the moves, just to count them.
340 if (depth <= OnePly) // Replace with '<' to test also qsearch
342 while (mp.get_next_move()) sum++;
346 // Loop through all legal moves
348 while ((move = mp.get_next_move()) != MOVE_NONE)
351 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
352 sum += perft(pos, depth - OnePly);
359 /// think() is the external interface to Stockfish's search, and is called when
360 /// the program receives the UCI 'go' command. It initializes various
361 /// search-related global variables, and calls root_search(). It returns false
362 /// when a quit command is received during the search.
364 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
365 int time[], int increment[], int movesToGo, int maxDepth,
366 int maxNodes, int maxTime, Move searchMoves[]) {
368 // Look for a book move
369 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
372 if (get_option_value_string("Book File") != OpeningBook.file_name())
373 OpeningBook.open(get_option_value_string("Book File"));
375 bookMove = OpeningBook.get_move(pos);
376 if (bookMove != MOVE_NONE)
378 cout << "bestmove " << bookMove << endl;
383 // Initialize global search variables
384 Idle = StopOnPonderhit = AbortSearch = Quit = false;
385 FailHigh = FailLow = Problem = false;
386 SearchStartTime = get_system_time();
387 ExactMaxTime = maxTime;
389 InfiniteSearch = infinite;
390 PonderSearch = ponder;
392 for (int i = 0; i < THREAD_MAX; i++)
394 Threads[i].nodes = 0ULL;
395 Threads[i].failHighPly1 = false;
398 if (button_was_pressed("New Game"))
399 loseOnTime = false; // Reset at the beginning of a new game
401 // Read UCI option values
402 TT.set_size(get_option_value_int("Hash"));
403 if (button_was_pressed("Clear Hash"))
406 bool PonderingEnabled = get_option_value_bool("Ponder");
407 MultiPV = get_option_value_int("MultiPV");
409 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
410 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
412 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
413 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
415 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
416 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
418 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
419 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
421 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
422 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
424 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
425 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
427 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
428 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
429 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
431 Chess960 = get_option_value_bool("UCI_Chess960");
432 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
433 UseLogFile = get_option_value_bool("Use Search Log");
435 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
437 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
438 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
440 read_weights(pos.side_to_move());
442 // Set the number of active threads
443 int newActiveThreads = get_option_value_int("Threads");
444 if (newActiveThreads != ActiveThreads)
446 ActiveThreads = newActiveThreads;
447 init_eval(ActiveThreads);
450 // Wake up sleeping threads
451 wake_sleeping_threads();
453 for (int i = 1; i < ActiveThreads; i++)
454 assert(thread_is_available(i, 0));
457 int myTime = time[side_to_move];
458 int myIncrement = increment[side_to_move];
460 if (!movesToGo) // Sudden death time control
464 MaxSearchTime = myTime / 30 + myIncrement;
465 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
467 else // Blitz game without increment
469 MaxSearchTime = myTime / 30;
470 AbsoluteMaxSearchTime = myTime / 8;
473 else // (x moves) / (y minutes)
477 MaxSearchTime = myTime / 2;
478 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
482 MaxSearchTime = myTime / Min(movesToGo, 20);
483 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
487 if (PonderingEnabled)
489 MaxSearchTime += MaxSearchTime / 4;
490 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
493 // Fixed depth or fixed number of nodes?
496 InfiniteSearch = true; // HACK
501 NodesBetweenPolls = Min(MaxNodes, 30000);
502 InfiniteSearch = true; // HACK
504 else if (myTime && myTime < 1000)
505 NodesBetweenPolls = 1000;
506 else if (myTime && myTime < 5000)
507 NodesBetweenPolls = 5000;
509 NodesBetweenPolls = 30000;
511 // Write information to search log file
513 LogFile << "Searching: " << pos.to_fen() << endl
514 << "infinite: " << infinite
515 << " ponder: " << ponder
516 << " time: " << myTime
517 << " increment: " << myIncrement
518 << " moves to go: " << movesToGo << endl;
520 // LSN filtering. Used only for developing purpose. Disabled by default.
524 // Step 2. If after last move we decided to lose on time, do it now!
525 while (SearchStartTime + myTime + 1000 > get_system_time())
529 // We're ready to start thinking. Call the iterative deepening loop function
530 Value v = id_loop(pos, searchMoves);
535 // Step 1. If this is sudden death game and our position is hopeless,
536 // decide to lose on time.
537 if ( !loseOnTime // If we already lost on time, go to step 3.
547 // Step 3. Now after stepping over the time limit, reset flag for next match.
560 /// init_threads() is called during startup. It launches all helper threads,
561 /// and initializes the split point stack and the global locks and condition
564 void init_threads() {
568 #if !defined(_MSC_VER)
569 pthread_t pthread[1];
572 for (i = 0; i < THREAD_MAX; i++)
573 Threads[i].activeSplitPoints = 0;
575 // Initialize global locks
576 lock_init(&MPLock, NULL);
577 lock_init(&IOLock, NULL);
579 init_split_point_stack();
581 #if !defined(_MSC_VER)
582 pthread_mutex_init(&WaitLock, NULL);
583 pthread_cond_init(&WaitCond, NULL);
585 for (i = 0; i < THREAD_MAX; i++)
586 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
589 // All threads except the main thread should be initialized to idle state
590 for (i = 1; i < THREAD_MAX; i++)
592 Threads[i].stop = false;
593 Threads[i].workIsWaiting = false;
594 Threads[i].idle = true;
595 Threads[i].running = false;
598 // Launch the helper threads
599 for (i = 1; i < THREAD_MAX; i++)
601 #if !defined(_MSC_VER)
602 pthread_create(pthread, NULL, init_thread, (void*)(&i));
605 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
608 // Wait until the thread has finished launching
609 while (!Threads[i].running);
614 /// stop_threads() is called when the program exits. It makes all the
615 /// helper threads exit cleanly.
617 void stop_threads() {
619 ActiveThreads = THREAD_MAX; // HACK
620 Idle = false; // HACK
621 wake_sleeping_threads();
622 AllThreadsShouldExit = true;
623 for (int i = 1; i < THREAD_MAX; i++)
625 Threads[i].stop = true;
626 while (Threads[i].running);
628 destroy_split_point_stack();
632 /// nodes_searched() returns the total number of nodes searched so far in
633 /// the current search.
635 int64_t nodes_searched() {
637 int64_t result = 0ULL;
638 for (int i = 0; i < ActiveThreads; i++)
639 result += Threads[i].nodes;
644 // SearchStack::init() initializes a search stack. Used at the beginning of a
645 // new search from the root.
646 void SearchStack::init(int ply) {
648 pv[ply] = pv[ply + 1] = MOVE_NONE;
649 currentMove = threatMove = MOVE_NONE;
650 reduction = Depth(0);
653 void SearchStack::initKillers() {
655 mateKiller = MOVE_NONE;
656 for (int i = 0; i < KILLER_MAX; i++)
657 killers[i] = MOVE_NONE;
662 // id_loop() is the main iterative deepening loop. It calls root_search
663 // repeatedly with increasing depth until the allocated thinking time has
664 // been consumed, the user stops the search, or the maximum search depth is
667 Value id_loop(const Position& pos, Move searchMoves[]) {
670 SearchStack ss[PLY_MAX_PLUS_2];
672 // searchMoves are verified, copied, scored and sorted
673 RootMoveList rml(p, searchMoves);
675 if (rml.move_count() == 0)
678 wait_for_stop_or_ponderhit();
680 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
683 // Print RootMoveList c'tor startup scoring to the standard output,
684 // so that we print information also for iteration 1.
685 cout << "info depth " << 1 << "\ninfo depth " << 1
686 << " score " << value_to_string(rml.get_move_score(0))
687 << " time " << current_search_time()
688 << " nodes " << nodes_searched()
690 << " pv " << rml.get_move(0) << "\n";
696 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
699 // Is one move significantly better than others after initial scoring ?
700 Move EasyMove = MOVE_NONE;
701 if ( rml.move_count() == 1
702 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
703 EasyMove = rml.get_move(0);
705 // Iterative deepening loop
706 while (Iteration < PLY_MAX)
708 // Initialize iteration
711 BestMoveChangesByIteration[Iteration] = 0;
715 cout << "info depth " << Iteration << endl;
717 // Calculate dynamic search window based on previous iterations
720 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
722 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
723 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
725 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
727 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
728 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
732 alpha = - VALUE_INFINITE;
733 beta = VALUE_INFINITE;
736 // Search to the current depth
737 Value value = root_search(p, ss, rml, alpha, beta);
739 // Write PV to transposition table, in case the relevant entries have
740 // been overwritten during the search.
741 TT.insert_pv(p, ss[0].pv);
744 break; // Value cannot be trusted. Break out immediately!
746 //Save info about search result
747 Value speculatedValue;
750 Value delta = value - IterationInfo[Iteration - 1].value;
757 speculatedValue = value + delta;
758 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
760 else if (value <= alpha)
762 assert(value == alpha);
766 speculatedValue = value + delta;
767 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
769 speculatedValue = value;
771 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
772 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
774 // Drop the easy move if it differs from the new best move
775 if (ss[0].pv[0] != EasyMove)
776 EasyMove = MOVE_NONE;
783 bool stopSearch = false;
785 // Stop search early if there is only a single legal move,
786 // we search up to Iteration 6 anyway to get a proper score.
787 if (Iteration >= 6 && rml.move_count() == 1)
790 // Stop search early when the last two iterations returned a mate score
792 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
793 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
796 // Stop search early if one move seems to be much better than the rest
797 int64_t nodes = nodes_searched();
801 && EasyMove == ss[0].pv[0]
802 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
803 && current_search_time() > MaxSearchTime / 16)
804 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
805 && current_search_time() > MaxSearchTime / 32)))
808 // Add some extra time if the best move has changed during the last two iterations
809 if (Iteration > 5 && Iteration <= 50)
810 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
811 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
813 // Stop search if most of MaxSearchTime is consumed at the end of the
814 // iteration. We probably don't have enough time to search the first
815 // move at the next iteration anyway.
816 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
824 StopOnPonderhit = true;
828 if (MaxDepth && Iteration >= MaxDepth)
834 // If we are pondering, we shouldn't print the best move before we
837 wait_for_stop_or_ponderhit();
839 // Print final search statistics
840 cout << "info nodes " << nodes_searched()
842 << " time " << current_search_time()
843 << " hashfull " << TT.full() << endl;
845 // Print the best move and the ponder move to the standard output
846 if (ss[0].pv[0] == MOVE_NONE)
848 ss[0].pv[0] = rml.get_move(0);
849 ss[0].pv[1] = MOVE_NONE;
851 cout << "bestmove " << ss[0].pv[0];
852 if (ss[0].pv[1] != MOVE_NONE)
853 cout << " ponder " << ss[0].pv[1];
860 dbg_print_mean(LogFile);
862 if (dbg_show_hit_rate)
863 dbg_print_hit_rate(LogFile);
865 LogFile << "\nNodes: " << nodes_searched()
866 << "\nNodes/second: " << nps()
867 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
870 p.do_move(ss[0].pv[0], st);
871 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
873 return rml.get_move_score(0);
877 // root_search() is the function which searches the root node. It is
878 // similar to search_pv except that it uses a different move ordering
879 // scheme and prints some information to the standard output.
881 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta) {
883 Value oldAlpha = alpha;
887 // Loop through all the moves in the root move list
888 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
892 // We failed high, invalidate and skip next moves, leave node-counters
893 // and beta-counters as they are and quickly return, we will try to do
894 // a research at the next iteration with a bigger aspiration window.
895 rml.set_move_score(i, -VALUE_INFINITE);
903 RootMoveNumber = i + 1;
906 // Save the current node count before the move is searched
907 nodes = nodes_searched();
909 // Reset beta cut-off counters
912 // Pick the next root move, and print the move and the move number to
913 // the standard output.
914 move = ss[0].currentMove = rml.get_move(i);
916 if (current_search_time() >= 1000)
917 cout << "info currmove " << move
918 << " currmovenumber " << RootMoveNumber << endl;
920 // Decide search depth for this move
921 bool moveIsCheck = pos.move_is_check(move);
922 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
924 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
925 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
927 // Make the move, and search it
928 pos.do_move(move, st, ci, moveIsCheck);
932 // Aspiration window is disabled in multi-pv case
934 alpha = -VALUE_INFINITE;
936 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
938 // If the value has dropped a lot compared to the last iteration,
939 // set the boolean variable Problem to true. This variable is used
940 // for time managment: When Problem is true, we try to complete the
941 // current iteration before playing a move.
942 Problem = ( Iteration >= 2
943 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
945 if (Problem && StopOnPonderhit)
946 StopOnPonderhit = false;
950 // Try to reduce non-pv search depth by one ply if move seems not problematic,
951 // if the move fails high will be re-searched at full depth.
952 if ( newDepth >= 3*OnePly
953 && i >= MultiPV + LMRPVMoves
955 && !captureOrPromotion
956 && !move_is_castle(move))
958 ss[0].reduction = OnePly;
959 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
961 value = alpha + 1; // Just to trigger next condition
965 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
969 // Fail high! Set the boolean variable FailHigh to true, and
970 // re-search the move using a PV search. The variable FailHigh
971 // is used for time managment: We try to avoid aborting the
972 // search prematurely during a fail high research.
974 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
981 // Finished searching the move. If AbortSearch is true, the search
982 // was aborted because the user interrupted the search or because we
983 // ran out of time. In this case, the return value of the search cannot
984 // be trusted, and we break out of the loop without updating the best
989 // Remember beta-cutoff and searched nodes counts for this move. The
990 // info is used to sort the root moves at the next iteration.
992 BetaCounter.read(pos.side_to_move(), our, their);
993 rml.set_beta_counters(i, our, their);
994 rml.set_move_nodes(i, nodes_searched() - nodes);
996 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
998 if (value <= alpha && i >= MultiPV)
999 rml.set_move_score(i, -VALUE_INFINITE);
1002 // PV move or new best move!
1005 rml.set_move_score(i, value);
1007 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1008 rml.set_move_pv(i, ss[0].pv);
1012 // We record how often the best move has been changed in each
1013 // iteration. This information is used for time managment: When
1014 // the best move changes frequently, we allocate some more time.
1016 BestMoveChangesByIteration[Iteration]++;
1018 // Print search information to the standard output
1019 cout << "info depth " << Iteration
1020 << " score " << value_to_string(value)
1021 << ((value >= beta) ? " lowerbound" :
1022 ((value <= alpha)? " upperbound" : ""))
1023 << " time " << current_search_time()
1024 << " nodes " << nodes_searched()
1028 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1029 cout << ss[0].pv[j] << " ";
1035 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1036 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1038 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1039 nodes_searched(), value, type, ss[0].pv) << endl;
1044 // Reset the global variable Problem to false if the value isn't too
1045 // far below the final value from the last iteration.
1046 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1051 rml.sort_multipv(i);
1052 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1054 cout << "info multipv " << j + 1
1055 << " score " << value_to_string(rml.get_move_score(j))
1056 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1057 << " time " << current_search_time()
1058 << " nodes " << nodes_searched()
1062 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1063 cout << rml.get_move_pv(j, k) << " ";
1067 alpha = rml.get_move_score(Min(i, MultiPV-1));
1069 } // PV move or new best move
1071 assert(alpha >= oldAlpha);
1073 FailLow = (alpha == oldAlpha);
1079 // search_pv() is the main search function for PV nodes.
1081 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1082 Depth depth, int ply, int threadID) {
1084 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1085 assert(beta > alpha && beta <= VALUE_INFINITE);
1086 assert(ply >= 0 && ply < PLY_MAX);
1087 assert(threadID >= 0 && threadID < ActiveThreads);
1089 Move movesSearched[256];
1094 Depth ext, newDepth;
1095 Value oldAlpha, value;
1096 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1098 Value bestValue = -VALUE_INFINITE;
1101 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1103 // Initialize, and make an early exit in case of an aborted search,
1104 // an instant draw, maximum ply reached, etc.
1105 init_node(ss, ply, threadID);
1107 // After init_node() that calls poll()
1108 if (AbortSearch || thread_should_stop(threadID))
1114 if (ply >= PLY_MAX - 1)
1115 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1117 // Mate distance pruning
1119 alpha = Max(value_mated_in(ply), alpha);
1120 beta = Min(value_mate_in(ply+1), beta);
1124 // Transposition table lookup. At PV nodes, we don't use the TT for
1125 // pruning, but only for move ordering. This is to avoid problems in
1126 // the following areas:
1128 // * Repetition draw detection
1129 // * Fifty move rule detection
1130 // * Searching for a mate
1131 // * Printing of full PV line
1133 tte = TT.retrieve(pos.get_key());
1134 ttMove = (tte ? tte->move() : MOVE_NONE);
1136 // Go with internal iterative deepening if we don't have a TT move
1137 if ( UseIIDAtPVNodes
1138 && depth >= 5*OnePly
1139 && ttMove == MOVE_NONE)
1141 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1142 ttMove = ss[ply].pv[ply];
1143 tte = TT.retrieve(pos.get_key());
1146 // Initialize a MovePicker object for the current position, and prepare
1147 // to search all moves
1148 isCheck = pos.is_check();
1149 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1151 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1153 // Loop through all legal moves until no moves remain or a beta cutoff
1155 while ( alpha < beta
1156 && (move = mp.get_next_move()) != MOVE_NONE
1157 && !thread_should_stop(threadID))
1159 assert(move_is_ok(move));
1161 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1162 moveIsCheck = pos.move_is_check(move, ci);
1163 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1165 // Decide the new search depth
1166 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1168 // Singular extension search. We extend the TT move if its value is much better than
1169 // its siblings. To verify this we do a reduced search on all the other moves but the
1170 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1171 if ( depth >= 6 * OnePly
1173 && move == tte->move()
1175 && is_lower_bound(tte->type())
1176 && tte->depth() >= depth - 3 * OnePly)
1178 Value ttValue = value_from_tt(tte->value(), ply);
1180 if (abs(ttValue) < VALUE_KNOWN_WIN)
1182 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1184 if (excValue < ttValue - SingleReplyMargin)
1189 newDepth = depth - OnePly + ext;
1191 // Update current move
1192 movesSearched[moveCount++] = ss[ply].currentMove = move;
1194 // Make and search the move
1195 pos.do_move(move, st, ci, moveIsCheck);
1197 if (moveCount == 1) // The first move in list is the PV
1198 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1201 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1202 // if the move fails high will be re-searched at full depth.
1203 if ( depth >= 3*OnePly
1204 && moveCount >= LMRPVMoves
1206 && !captureOrPromotion
1207 && !move_is_castle(move)
1208 && !move_is_killer(move, ss[ply]))
1210 ss[ply].reduction = OnePly;
1211 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1214 value = alpha + 1; // Just to trigger next condition
1216 if (value > alpha) // Go with full depth non-pv search
1218 ss[ply].reduction = Depth(0);
1219 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1220 if (value > alpha && value < beta)
1222 // When the search fails high at ply 1 while searching the first
1223 // move at the root, set the flag failHighPly1. This is used for
1224 // time managment: We don't want to stop the search early in
1225 // such cases, because resolving the fail high at ply 1 could
1226 // result in a big drop in score at the root.
1227 if (ply == 1 && RootMoveNumber == 1)
1228 Threads[threadID].failHighPly1 = true;
1230 // A fail high occurred. Re-search at full window (pv search)
1231 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1232 Threads[threadID].failHighPly1 = false;
1236 pos.undo_move(move);
1238 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1241 if (value > bestValue)
1248 if (value == value_mate_in(ply + 1))
1249 ss[ply].mateKiller = move;
1251 // If we are at ply 1, and we are searching the first root move at
1252 // ply 0, set the 'Problem' variable if the score has dropped a lot
1253 // (from the computer's point of view) since the previous iteration.
1256 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1261 if ( ActiveThreads > 1
1263 && depth >= MinimumSplitDepth
1265 && idle_thread_exists(threadID)
1267 && !thread_should_stop(threadID)
1268 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1269 depth, &moveCount, &mp, threadID, true))
1273 // All legal moves have been searched. A special case: If there were
1274 // no legal moves, it must be mate or stalemate.
1276 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1278 // If the search is not aborted, update the transposition table,
1279 // history counters, and killer moves.
1280 if (AbortSearch || thread_should_stop(threadID))
1283 if (bestValue <= oldAlpha)
1284 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1286 else if (bestValue >= beta)
1288 BetaCounter.add(pos.side_to_move(), depth, threadID);
1289 move = ss[ply].pv[ply];
1290 if (!pos.move_is_capture_or_promotion(move))
1292 update_history(pos, move, depth, movesSearched, moveCount);
1293 update_killers(move, ss[ply]);
1295 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1298 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1304 // search() is the search function for zero-width nodes.
1306 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1307 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1309 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1310 assert(ply >= 0 && ply < PLY_MAX);
1311 assert(threadID >= 0 && threadID < ActiveThreads);
1313 Move movesSearched[256];
1318 Depth ext, newDepth;
1319 Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1320 bool isCheck, useFutilityPruning, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1321 bool mateThreat = false;
1323 Value bestValue = -VALUE_INFINITE;
1326 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1328 // Initialize, and make an early exit in case of an aborted search,
1329 // an instant draw, maximum ply reached, etc.
1330 init_node(ss, ply, threadID);
1332 // After init_node() that calls poll()
1333 if (AbortSearch || thread_should_stop(threadID))
1339 if (ply >= PLY_MAX - 1)
1340 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1342 // Mate distance pruning
1343 if (value_mated_in(ply) >= beta)
1346 if (value_mate_in(ply + 1) < beta)
1349 // We don't want the score of a partial search to overwrite a previous full search
1350 // TT value, so we use a different position key in case of an excluded move exsists.
1351 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1353 // Transposition table lookup
1354 tte = TT.retrieve(posKey);
1355 ttMove = (tte ? tte->move() : MOVE_NONE);
1357 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1359 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1360 return value_from_tt(tte->value(), ply);
1363 approximateEval = quick_evaluate(pos);
1364 isCheck = pos.is_check();
1370 && !value_is_mate(beta)
1371 && ok_to_do_nullmove(pos)
1372 && approximateEval >= beta - NullMoveMargin)
1374 ss[ply].currentMove = MOVE_NULL;
1376 pos.do_null_move(st);
1378 // Null move dynamic reduction based on depth
1379 int R = (depth >= 5 * OnePly ? 4 : 3);
1381 // Null move dynamic reduction based on value
1382 if (approximateEval - beta > PawnValueMidgame)
1385 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1387 pos.undo_null_move();
1389 if (nullValue >= beta)
1391 if (depth < 6 * OnePly)
1394 // Do zugzwang verification search
1395 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1399 // The null move failed low, which means that we may be faced with
1400 // some kind of threat. If the previous move was reduced, check if
1401 // the move that refuted the null move was somehow connected to the
1402 // move which was reduced. If a connection is found, return a fail
1403 // low score (which will cause the reduced move to fail high in the
1404 // parent node, which will trigger a re-search with full depth).
1405 if (nullValue == value_mated_in(ply + 2))
1408 ss[ply].threatMove = ss[ply + 1].currentMove;
1409 if ( depth < ThreatDepth
1410 && ss[ply - 1].reduction
1411 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1415 // Null move search not allowed, try razoring
1416 else if ( !value_is_mate(beta)
1417 && depth < RazorDepth
1418 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1419 && ss[ply - 1].currentMove != MOVE_NULL
1420 && ttMove == MOVE_NONE
1421 && !pos.has_pawn_on_7th(pos.side_to_move()))
1423 Value rbeta = beta - RazorMargins[int(depth) - 2];
1424 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1429 // Go with internal iterative deepening if we don't have a TT move
1430 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1431 !isCheck && evaluate(pos, ei, threadID) >= beta - IIDMargin)
1433 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1434 ttMove = ss[ply].pv[ply];
1435 tte = TT.retrieve(pos.get_key());
1438 // Initialize a MovePicker object for the current position, and prepare
1439 // to search all moves.
1440 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1442 futilityValue = VALUE_NONE;
1443 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1445 // Calculate depth dependant futility pruning parameters
1446 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1447 const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1449 // Avoid calling evaluate() if we already have the score in TT
1450 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1451 futilityValue = value_from_tt(tte->value(), ply) + FutilityValueMargin;
1453 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1454 while ( bestValue < beta
1455 && (move = mp.get_next_move()) != MOVE_NONE
1456 && !thread_should_stop(threadID))
1458 assert(move_is_ok(move));
1460 if (move == excludedMove)
1463 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1464 moveIsCheck = pos.move_is_check(move, ci);
1465 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1467 // Decide the new search depth
1468 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1470 // Singular extension search. We extend the TT move if its value is much better than
1471 // its siblings. To verify this we do a reduced search on all the other moves but the
1472 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1473 if ( depth >= 8 * OnePly
1475 && move == tte->move()
1476 && !excludedMove // Do not allow recursive single-reply search
1478 && is_lower_bound(tte->type())
1479 && tte->depth() >= depth - 3 * OnePly)
1481 Value ttValue = value_from_tt(tte->value(), ply);
1483 if (abs(ttValue) < VALUE_KNOWN_WIN)
1485 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1487 if (excValue < ttValue - SingleReplyMargin)
1492 newDepth = depth - OnePly + ext;
1494 // Update current move
1495 movesSearched[moveCount++] = ss[ply].currentMove = move;
1498 if ( useFutilityPruning
1500 && !captureOrPromotion
1503 // Move count based pruning
1504 if ( moveCount >= FutilityMoveCountMargin
1505 && ok_to_prune(pos, move, ss[ply].threatMove)
1506 && bestValue > value_mated_in(PLY_MAX))
1509 // Value based pruning
1510 if (futilityValue == VALUE_NONE)
1511 futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1513 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1515 if (futilityValueScaled < beta)
1517 if (futilityValueScaled > bestValue)
1518 bestValue = futilityValueScaled;
1523 // Make and search the move
1524 pos.do_move(move, st, ci, moveIsCheck);
1526 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1527 // if the move fails high will be re-searched at full depth.
1528 if ( depth >= 3*OnePly
1529 && moveCount >= LMRNonPVMoves
1531 && !captureOrPromotion
1532 && !move_is_castle(move)
1533 && !move_is_killer(move, ss[ply]))
1535 ss[ply].reduction = OnePly;
1536 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1539 value = beta; // Just to trigger next condition
1541 if (value >= beta) // Go with full depth non-pv search
1543 ss[ply].reduction = Depth(0);
1544 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1546 pos.undo_move(move);
1548 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1551 if (value > bestValue)
1557 if (value == value_mate_in(ply + 1))
1558 ss[ply].mateKiller = move;
1562 if ( ActiveThreads > 1
1564 && depth >= MinimumSplitDepth
1566 && idle_thread_exists(threadID)
1568 && !thread_should_stop(threadID)
1569 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue,
1570 depth, &moveCount, &mp, threadID, false))
1574 // All legal moves have been searched. A special case: If there were
1575 // no legal moves, it must be mate or stalemate.
1577 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1579 // If the search is not aborted, update the transposition table,
1580 // history counters, and killer moves.
1581 if (AbortSearch || thread_should_stop(threadID))
1584 if (bestValue < beta)
1585 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1588 BetaCounter.add(pos.side_to_move(), depth, threadID);
1589 move = ss[ply].pv[ply];
1590 if (!pos.move_is_capture_or_promotion(move))
1592 update_history(pos, move, depth, movesSearched, moveCount);
1593 update_killers(move, ss[ply]);
1595 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1598 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1604 // qsearch() is the quiescence search function, which is called by the main
1605 // search function when the remaining depth is zero (or, to be more precise,
1606 // less than OnePly).
1608 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1609 Depth depth, int ply, int threadID) {
1611 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1612 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1614 assert(ply >= 0 && ply < PLY_MAX);
1615 assert(threadID >= 0 && threadID < ActiveThreads);
1620 Value staticValue, bestValue, value, futilityValue;
1621 bool isCheck, enoughMaterial, moveIsCheck;
1622 const TTEntry* tte = NULL;
1624 bool pvNode = (beta - alpha != 1);
1626 // Initialize, and make an early exit in case of an aborted search,
1627 // an instant draw, maximum ply reached, etc.
1628 init_node(ss, ply, threadID);
1630 // After init_node() that calls poll()
1631 if (AbortSearch || thread_should_stop(threadID))
1637 // Transposition table lookup, only when not in PV
1640 tte = TT.retrieve(pos.get_key());
1641 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1643 assert(tte->type() != VALUE_TYPE_EVAL);
1645 return value_from_tt(tte->value(), ply);
1648 ttMove = (tte ? tte->move() : MOVE_NONE);
1650 isCheck = pos.is_check();
1651 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1653 // Evaluate the position statically
1655 staticValue = -VALUE_INFINITE;
1657 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1659 // Use the cached evaluation score if possible
1660 assert(ei.futilityMargin == Value(0));
1662 staticValue = value_from_tt(tte->value(), ply);
1665 staticValue = evaluate(pos, ei, threadID);
1667 if (ply >= PLY_MAX - 1)
1668 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1670 // Initialize "stand pat score", and return it immediately if it is
1672 bestValue = staticValue;
1674 if (bestValue >= beta)
1676 // Store the score to avoid a future costly evaluation() call
1677 if (!isCheck && !tte && ei.futilityMargin == 0)
1678 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1683 if (bestValue > alpha)
1686 // Initialize a MovePicker object for the current position, and prepare
1687 // to search the moves. Because the depth is <= 0 here, only captures,
1688 // queen promotions and checks (only if depth == 0) will be generated.
1689 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1691 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1693 // Loop through the moves until no moves remain or a beta cutoff
1695 while ( alpha < beta
1696 && (move = mp.get_next_move()) != MOVE_NONE)
1698 assert(move_is_ok(move));
1701 ss[ply].currentMove = move;
1703 moveIsCheck = pos.move_is_check(move, ci);
1711 && !move_is_promotion(move)
1712 && !pos.move_is_passed_pawn_push(move))
1714 futilityValue = staticValue
1715 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1716 pos.endgame_value_of_piece_on(move_to(move)))
1717 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1719 + ei.futilityMargin;
1721 if (futilityValue < alpha)
1723 if (futilityValue > bestValue)
1724 bestValue = futilityValue;
1729 // Don't search captures and checks with negative SEE values
1732 && !move_is_promotion(move)
1733 && pos.see_sign(move) < 0)
1736 // Make and search the move
1737 pos.do_move(move, st, ci, moveIsCheck);
1738 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1739 pos.undo_move(move);
1741 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1744 if (value > bestValue)
1755 // All legal moves have been searched. A special case: If we're in check
1756 // and no legal moves were found, it is checkmate.
1757 if (!moveCount && pos.is_check()) // Mate!
1758 return value_mated_in(ply);
1760 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1762 // Update transposition table
1763 move = ss[ply].pv[ply];
1766 // If bestValue isn't changed it means it is still the static evaluation of
1767 // the node, so keep this info to avoid a future costly evaluation() call.
1768 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1769 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1771 if (bestValue < beta)
1772 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1774 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1777 // Update killers only for good check moves
1778 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1779 update_killers(move, ss[ply]);
1785 // sp_search() is used to search from a split point. This function is called
1786 // by each thread working at the split point. It is similar to the normal
1787 // search() function, but simpler. Because we have already probed the hash
1788 // table, done a null move search, and searched the first move before
1789 // splitting, we don't have to repeat all this work in sp_search(). We
1790 // also don't need to store anything to the hash table here: This is taken
1791 // care of after we return from the split point.
1793 void sp_search(SplitPoint* sp, int threadID) {
1795 assert(threadID >= 0 && threadID < ActiveThreads);
1796 assert(ActiveThreads > 1);
1798 Position pos = Position(sp->pos);
1800 SearchStack* ss = sp->sstack[threadID];
1803 bool isCheck = pos.is_check();
1804 bool useFutilityPruning = sp->depth < SelectiveDepth
1807 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1808 const int FutilityValueMargin = 112 * bitScanReverse32(int(sp->depth) * int(sp->depth) / 2);
1810 while ( sp->bestValue < sp->beta
1811 && !thread_should_stop(threadID)
1812 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1814 assert(move_is_ok(move));
1816 bool moveIsCheck = pos.move_is_check(move, ci);
1817 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1819 lock_grab(&(sp->lock));
1820 int moveCount = ++sp->moves;
1821 lock_release(&(sp->lock));
1823 ss[sp->ply].currentMove = move;
1825 // Decide the new search depth.
1827 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1828 Depth newDepth = sp->depth - OnePly + ext;
1831 if ( useFutilityPruning
1833 && !captureOrPromotion)
1835 // Move count based pruning
1836 if ( moveCount >= FutilityMoveCountMargin
1837 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1838 && sp->bestValue > value_mated_in(PLY_MAX))
1841 // Value based pruning
1842 if (sp->futilityValue == VALUE_NONE)
1845 sp->futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1848 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1850 if (futilityValueScaled < sp->beta)
1852 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1854 lock_grab(&(sp->lock));
1855 if (futilityValueScaled > sp->bestValue)
1856 sp->bestValue = futilityValueScaled;
1857 lock_release(&(sp->lock));
1863 // Make and search the move.
1865 pos.do_move(move, st, ci, moveIsCheck);
1867 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1868 // if the move fails high will be re-searched at full depth.
1870 && moveCount >= LMRNonPVMoves
1871 && !captureOrPromotion
1872 && !move_is_castle(move)
1873 && !move_is_killer(move, ss[sp->ply]))
1875 ss[sp->ply].reduction = OnePly;
1876 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1879 value = sp->beta; // Just to trigger next condition
1881 if (value >= sp->beta) // Go with full depth non-pv search
1883 ss[sp->ply].reduction = Depth(0);
1884 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1886 pos.undo_move(move);
1888 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1890 if (thread_should_stop(threadID))
1894 if (value > sp->bestValue) // Less then 2% of cases
1896 lock_grab(&(sp->lock));
1897 if (value > sp->bestValue && !thread_should_stop(threadID))
1899 sp->bestValue = value;
1900 if (sp->bestValue >= sp->beta)
1902 sp_update_pv(sp->parentSstack, ss, sp->ply);
1903 for (int i = 0; i < ActiveThreads; i++)
1904 if (i != threadID && (i == sp->master || sp->slaves[i]))
1905 Threads[i].stop = true;
1907 sp->finished = true;
1910 lock_release(&(sp->lock));
1914 lock_grab(&(sp->lock));
1916 // If this is the master thread and we have been asked to stop because of
1917 // a beta cutoff higher up in the tree, stop all slave threads.
1918 if (sp->master == threadID && thread_should_stop(threadID))
1919 for (int i = 0; i < ActiveThreads; i++)
1921 Threads[i].stop = true;
1924 sp->slaves[threadID] = 0;
1926 lock_release(&(sp->lock));
1930 // sp_search_pv() is used to search from a PV split point. This function
1931 // is called by each thread working at the split point. It is similar to
1932 // the normal search_pv() function, but simpler. Because we have already
1933 // probed the hash table and searched the first move before splitting, we
1934 // don't have to repeat all this work in sp_search_pv(). We also don't
1935 // need to store anything to the hash table here: This is taken care of
1936 // after we return from the split point.
1938 void sp_search_pv(SplitPoint* sp, int threadID) {
1940 assert(threadID >= 0 && threadID < ActiveThreads);
1941 assert(ActiveThreads > 1);
1943 Position pos = Position(sp->pos);
1945 SearchStack* ss = sp->sstack[threadID];
1949 while ( sp->alpha < sp->beta
1950 && !thread_should_stop(threadID)
1951 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1953 bool moveIsCheck = pos.move_is_check(move, ci);
1954 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1956 assert(move_is_ok(move));
1958 lock_grab(&(sp->lock));
1959 int moveCount = ++sp->moves;
1960 lock_release(&(sp->lock));
1962 ss[sp->ply].currentMove = move;
1964 // Decide the new search depth.
1966 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1967 Depth newDepth = sp->depth - OnePly + ext;
1969 // Make and search the move.
1971 pos.do_move(move, st, ci, moveIsCheck);
1973 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1974 // if the move fails high will be re-searched at full depth.
1976 && moveCount >= LMRPVMoves
1977 && !captureOrPromotion
1978 && !move_is_castle(move)
1979 && !move_is_killer(move, ss[sp->ply]))
1981 ss[sp->ply].reduction = OnePly;
1982 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1985 value = sp->alpha + 1; // Just to trigger next condition
1987 if (value > sp->alpha) // Go with full depth non-pv search
1989 ss[sp->ply].reduction = Depth(0);
1990 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1992 if (value > sp->alpha && value < sp->beta)
1994 // When the search fails high at ply 1 while searching the first
1995 // move at the root, set the flag failHighPly1. This is used for
1996 // time managment: We don't want to stop the search early in
1997 // such cases, because resolving the fail high at ply 1 could
1998 // result in a big drop in score at the root.
1999 if (sp->ply == 1 && RootMoveNumber == 1)
2000 Threads[threadID].failHighPly1 = true;
2002 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2003 Threads[threadID].failHighPly1 = false;
2006 pos.undo_move(move);
2008 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2010 if (thread_should_stop(threadID))
2014 lock_grab(&(sp->lock));
2015 if (value > sp->bestValue && !thread_should_stop(threadID))
2017 sp->bestValue = value;
2018 if (value > sp->alpha)
2021 sp_update_pv(sp->parentSstack, ss, sp->ply);
2022 if (value == value_mate_in(sp->ply + 1))
2023 ss[sp->ply].mateKiller = move;
2025 if (value >= sp->beta)
2027 for (int i = 0; i < ActiveThreads; i++)
2028 if (i != threadID && (i == sp->master || sp->slaves[i]))
2029 Threads[i].stop = true;
2031 sp->finished = true;
2034 // If we are at ply 1, and we are searching the first root move at
2035 // ply 0, set the 'Problem' variable if the score has dropped a lot
2036 // (from the computer's point of view) since the previous iteration.
2039 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2042 lock_release(&(sp->lock));
2045 lock_grab(&(sp->lock));
2047 // If this is the master thread and we have been asked to stop because of
2048 // a beta cutoff higher up in the tree, stop all slave threads.
2049 if (sp->master == threadID && thread_should_stop(threadID))
2050 for (int i = 0; i < ActiveThreads; i++)
2052 Threads[i].stop = true;
2055 sp->slaves[threadID] = 0;
2057 lock_release(&(sp->lock));
2060 /// The BetaCounterType class
2062 BetaCounterType::BetaCounterType() { clear(); }
2064 void BetaCounterType::clear() {
2066 for (int i = 0; i < THREAD_MAX; i++)
2067 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2070 void BetaCounterType::add(Color us, Depth d, int threadID) {
2072 // Weighted count based on depth
2073 Threads[threadID].betaCutOffs[us] += unsigned(d);
2076 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2079 for (int i = 0; i < THREAD_MAX; i++)
2081 our += Threads[i].betaCutOffs[us];
2082 their += Threads[i].betaCutOffs[opposite_color(us)];
2087 /// The RootMoveList class
2089 // RootMoveList c'tor
2091 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2093 MoveStack mlist[MaxRootMoves];
2094 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2096 // Generate all legal moves
2097 MoveStack* last = generate_moves(pos, mlist);
2099 // Add each move to the moves[] array
2100 for (MoveStack* cur = mlist; cur != last; cur++)
2102 bool includeMove = includeAllMoves;
2104 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2105 includeMove = (searchMoves[k] == cur->move);
2110 // Find a quick score for the move
2112 SearchStack ss[PLY_MAX_PLUS_2];
2115 moves[count].move = cur->move;
2116 pos.do_move(moves[count].move, st);
2117 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2118 pos.undo_move(moves[count].move);
2119 moves[count].pv[0] = moves[count].move;
2120 moves[count].pv[1] = MOVE_NONE;
2127 // RootMoveList simple methods definitions
2129 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2131 moves[moveNum].nodes = nodes;
2132 moves[moveNum].cumulativeNodes += nodes;
2135 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2137 moves[moveNum].ourBeta = our;
2138 moves[moveNum].theirBeta = their;
2141 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2145 for (j = 0; pv[j] != MOVE_NONE; j++)
2146 moves[moveNum].pv[j] = pv[j];
2148 moves[moveNum].pv[j] = MOVE_NONE;
2152 // RootMoveList::sort() sorts the root move list at the beginning of a new
2155 inline void RootMoveList::sort() {
2157 sort_multipv(count - 1); // Sort all items
2161 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2162 // list by their scores and depths. It is used to order the different PVs
2163 // correctly in MultiPV mode.
2165 void RootMoveList::sort_multipv(int n) {
2169 for (i = 1; i <= n; i++)
2171 RootMove rm = moves[i];
2172 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2173 moves[j] = moves[j - 1];
2180 // init_node() is called at the beginning of all the search functions
2181 // (search(), search_pv(), qsearch(), and so on) and initializes the
2182 // search stack object corresponding to the current node. Once every
2183 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2184 // for user input and checks whether it is time to stop the search.
2186 void init_node(SearchStack ss[], int ply, int threadID) {
2188 assert(ply >= 0 && ply < PLY_MAX);
2189 assert(threadID >= 0 && threadID < ActiveThreads);
2191 Threads[threadID].nodes++;
2196 if (NodesSincePoll >= NodesBetweenPolls)
2203 ss[ply + 2].initKillers();
2205 if (Threads[threadID].printCurrentLine)
2206 print_current_line(ss, ply, threadID);
2210 // update_pv() is called whenever a search returns a value > alpha.
2211 // It updates the PV in the SearchStack object corresponding to the
2214 void update_pv(SearchStack ss[], int ply) {
2216 assert(ply >= 0 && ply < PLY_MAX);
2220 ss[ply].pv[ply] = ss[ply].currentMove;
2222 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2223 ss[ply].pv[p] = ss[ply + 1].pv[p];
2225 ss[ply].pv[p] = MOVE_NONE;
2229 // sp_update_pv() is a variant of update_pv for use at split points. The
2230 // difference between the two functions is that sp_update_pv also updates
2231 // the PV at the parent node.
2233 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2235 assert(ply >= 0 && ply < PLY_MAX);
2239 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2241 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2242 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2244 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2248 // connected_moves() tests whether two moves are 'connected' in the sense
2249 // that the first move somehow made the second move possible (for instance
2250 // if the moving piece is the same in both moves). The first move is assumed
2251 // to be the move that was made to reach the current position, while the
2252 // second move is assumed to be a move from the current position.
2254 bool connected_moves(const Position& pos, Move m1, Move m2) {
2256 Square f1, t1, f2, t2;
2259 assert(move_is_ok(m1));
2260 assert(move_is_ok(m2));
2262 if (m2 == MOVE_NONE)
2265 // Case 1: The moving piece is the same in both moves
2271 // Case 2: The destination square for m2 was vacated by m1
2277 // Case 3: Moving through the vacated square
2278 if ( piece_is_slider(pos.piece_on(f2))
2279 && bit_is_set(squares_between(f2, t2), f1))
2282 // Case 4: The destination square for m2 is defended by the moving piece in m1
2283 p = pos.piece_on(t1);
2284 if (bit_is_set(pos.attacks_from(p, t1), t2))
2287 // Case 5: Discovered check, checking piece is the piece moved in m1
2288 if ( piece_is_slider(p)
2289 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2290 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2292 // discovered_check_candidates() works also if the Position's side to
2293 // move is the opposite of the checking piece.
2294 Color them = opposite_color(pos.side_to_move());
2295 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2297 if (bit_is_set(dcCandidates, f2))
2304 // value_is_mate() checks if the given value is a mate one
2305 // eventually compensated for the ply.
2307 bool value_is_mate(Value value) {
2309 assert(abs(value) <= VALUE_INFINITE);
2311 return value <= value_mated_in(PLY_MAX)
2312 || value >= value_mate_in(PLY_MAX);
2316 // move_is_killer() checks if the given move is among the
2317 // killer moves of that ply.
2319 bool move_is_killer(Move m, const SearchStack& ss) {
2321 const Move* k = ss.killers;
2322 for (int i = 0; i < KILLER_MAX; i++, k++)
2330 // extension() decides whether a move should be searched with normal depth,
2331 // or with extended depth. Certain classes of moves (checking moves, in
2332 // particular) are searched with bigger depth than ordinary moves and in
2333 // any case are marked as 'dangerous'. Note that also if a move is not
2334 // extended, as example because the corresponding UCI option is set to zero,
2335 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2337 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2338 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2340 assert(m != MOVE_NONE);
2342 Depth result = Depth(0);
2343 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2348 result += CheckExtension[pvNode];
2351 result += SingleEvasionExtension[pvNode];
2354 result += MateThreatExtension[pvNode];
2357 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2359 Color c = pos.side_to_move();
2360 if (relative_rank(c, move_to(m)) == RANK_7)
2362 result += PawnPushTo7thExtension[pvNode];
2365 if (pos.pawn_is_passed(c, move_to(m)))
2367 result += PassedPawnExtension[pvNode];
2372 if ( captureOrPromotion
2373 && pos.type_of_piece_on(move_to(m)) != PAWN
2374 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2375 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2376 && !move_is_promotion(m)
2379 result += PawnEndgameExtension[pvNode];
2384 && captureOrPromotion
2385 && pos.type_of_piece_on(move_to(m)) != PAWN
2386 && pos.see_sign(m) >= 0)
2392 return Min(result, OnePly);
2396 // ok_to_do_nullmove() looks at the current position and decides whether
2397 // doing a 'null move' should be allowed. In order to avoid zugzwang
2398 // problems, null moves are not allowed when the side to move has very
2399 // little material left. Currently, the test is a bit too simple: Null
2400 // moves are avoided only when the side to move has only pawns left.
2401 // It's probably a good idea to avoid null moves in at least some more
2402 // complicated endgames, e.g. KQ vs KR. FIXME
2404 bool ok_to_do_nullmove(const Position& pos) {
2406 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2410 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2411 // non-tactical moves late in the move list close to the leaves are
2412 // candidates for pruning.
2414 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2416 assert(move_is_ok(m));
2417 assert(threat == MOVE_NONE || move_is_ok(threat));
2418 assert(!pos.move_is_check(m));
2419 assert(!pos.move_is_capture_or_promotion(m));
2420 assert(!pos.move_is_passed_pawn_push(m));
2422 Square mfrom, mto, tfrom, tto;
2424 // Prune if there isn't any threat move and
2425 // is not a castling move (common case).
2426 if (threat == MOVE_NONE && !move_is_castle(m))
2429 mfrom = move_from(m);
2431 tfrom = move_from(threat);
2432 tto = move_to(threat);
2434 // Case 1: Castling moves are never pruned
2435 if (move_is_castle(m))
2438 // Case 2: Don't prune moves which move the threatened piece
2442 // Case 3: If the threatened piece has value less than or equal to the
2443 // value of the threatening piece, don't prune move which defend it.
2444 if ( pos.move_is_capture(threat)
2445 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2446 || pos.type_of_piece_on(tfrom) == KING)
2447 && pos.move_attacks_square(m, tto))
2450 // Case 4: If the moving piece in the threatened move is a slider, don't
2451 // prune safe moves which block its ray.
2452 if ( piece_is_slider(pos.piece_on(tfrom))
2453 && bit_is_set(squares_between(tfrom, tto), mto)
2454 && pos.see_sign(m) >= 0)
2461 // ok_to_use_TT() returns true if a transposition table score
2462 // can be used at a given point in search.
2464 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2466 Value v = value_from_tt(tte->value(), ply);
2468 return ( tte->depth() >= depth
2469 || v >= Max(value_mate_in(PLY_MAX), beta)
2470 || v < Min(value_mated_in(PLY_MAX), beta))
2472 && ( (is_lower_bound(tte->type()) && v >= beta)
2473 || (is_upper_bound(tte->type()) && v < beta));
2477 // update_history() registers a good move that produced a beta-cutoff
2478 // in history and marks as failures all the other moves of that ply.
2480 void update_history(const Position& pos, Move move, Depth depth,
2481 Move movesSearched[], int moveCount) {
2485 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2487 for (int i = 0; i < moveCount - 1; i++)
2489 m = movesSearched[i];
2493 if (!pos.move_is_capture_or_promotion(m))
2494 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2499 // update_killers() add a good move that produced a beta-cutoff
2500 // among the killer moves of that ply.
2502 void update_killers(Move m, SearchStack& ss) {
2504 if (m == ss.killers[0])
2507 for (int i = KILLER_MAX - 1; i > 0; i--)
2508 ss.killers[i] = ss.killers[i - 1];
2514 // fail_high_ply_1() checks if some thread is currently resolving a fail
2515 // high at ply 1 at the node below the first root node. This information
2516 // is used for time management.
2518 bool fail_high_ply_1() {
2520 for (int i = 0; i < ActiveThreads; i++)
2521 if (Threads[i].failHighPly1)
2528 // current_search_time() returns the number of milliseconds which have passed
2529 // since the beginning of the current search.
2531 int current_search_time() {
2533 return get_system_time() - SearchStartTime;
2537 // nps() computes the current nodes/second count.
2541 int t = current_search_time();
2542 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2546 // poll() performs two different functions: It polls for user input, and it
2547 // looks at the time consumed so far and decides if it's time to abort the
2552 static int lastInfoTime;
2553 int t = current_search_time();
2558 // We are line oriented, don't read single chars
2559 std::string command;
2561 if (!std::getline(std::cin, command))
2564 if (command == "quit")
2567 PonderSearch = false;
2571 else if (command == "stop")
2574 PonderSearch = false;
2576 else if (command == "ponderhit")
2580 // Print search information
2584 else if (lastInfoTime > t)
2585 // HACK: Must be a new search where we searched less than
2586 // NodesBetweenPolls nodes during the first second of search.
2589 else if (t - lastInfoTime >= 1000)
2597 if (dbg_show_hit_rate)
2598 dbg_print_hit_rate();
2600 cout << "info nodes " << nodes_searched() << " nps " << nps()
2601 << " time " << t << " hashfull " << TT.full() << endl;
2603 lock_release(&IOLock);
2605 if (ShowCurrentLine)
2606 Threads[0].printCurrentLine = true;
2609 // Should we stop the search?
2613 bool stillAtFirstMove = RootMoveNumber == 1
2615 && t > MaxSearchTime + ExtraSearchTime;
2617 bool noProblemFound = !FailHigh
2619 && !fail_high_ply_1()
2621 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2623 bool noMoreTime = t > AbsoluteMaxSearchTime
2624 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2627 if ( (Iteration >= 3 && !InfiniteSearch && noMoreTime)
2628 || (ExactMaxTime && t >= ExactMaxTime)
2629 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2634 // ponderhit() is called when the program is pondering (i.e. thinking while
2635 // it's the opponent's turn to move) in order to let the engine know that
2636 // it correctly predicted the opponent's move.
2640 int t = current_search_time();
2641 PonderSearch = false;
2643 bool stillAtFirstMove = RootMoveNumber == 1
2645 && t > MaxSearchTime + ExtraSearchTime;
2647 bool noProblemFound = !FailHigh
2649 && !fail_high_ply_1()
2651 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2653 bool noMoreTime = t > AbsoluteMaxSearchTime
2657 if (Iteration >= 3 && !InfiniteSearch && (noMoreTime || StopOnPonderhit))
2662 // print_current_line() prints the current line of search for a given
2663 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2665 void print_current_line(SearchStack ss[], int ply, int threadID) {
2667 assert(ply >= 0 && ply < PLY_MAX);
2668 assert(threadID >= 0 && threadID < ActiveThreads);
2670 if (!Threads[threadID].idle)
2673 cout << "info currline " << (threadID + 1);
2674 for (int p = 0; p < ply; p++)
2675 cout << " " << ss[p].currentMove;
2678 lock_release(&IOLock);
2680 Threads[threadID].printCurrentLine = false;
2681 if (threadID + 1 < ActiveThreads)
2682 Threads[threadID + 1].printCurrentLine = true;
2686 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2688 void init_ss_array(SearchStack ss[]) {
2690 for (int i = 0; i < 3; i++)
2693 ss[i].initKillers();
2698 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2699 // while the program is pondering. The point is to work around a wrinkle in
2700 // the UCI protocol: When pondering, the engine is not allowed to give a
2701 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2702 // We simply wait here until one of these commands is sent, and return,
2703 // after which the bestmove and pondermove will be printed (in id_loop()).
2705 void wait_for_stop_or_ponderhit() {
2707 std::string command;
2711 if (!std::getline(std::cin, command))
2714 if (command == "quit")
2719 else if (command == "ponderhit" || command == "stop")
2725 // idle_loop() is where the threads are parked when they have no work to do.
2726 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2727 // object for which the current thread is the master.
2729 void idle_loop(int threadID, SplitPoint* waitSp) {
2731 assert(threadID >= 0 && threadID < THREAD_MAX);
2733 Threads[threadID].running = true;
2737 if (AllThreadsShouldExit && threadID != 0)
2740 // If we are not thinking, wait for a condition to be signaled
2741 // instead of wasting CPU time polling for work.
2742 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2745 #if !defined(_MSC_VER)
2746 pthread_mutex_lock(&WaitLock);
2747 if (Idle || threadID >= ActiveThreads)
2748 pthread_cond_wait(&WaitCond, &WaitLock);
2750 pthread_mutex_unlock(&WaitLock);
2752 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2756 // If this thread has been assigned work, launch a search
2757 if (Threads[threadID].workIsWaiting)
2759 Threads[threadID].workIsWaiting = false;
2760 if (Threads[threadID].splitPoint->pvNode)
2761 sp_search_pv(Threads[threadID].splitPoint, threadID);
2763 sp_search(Threads[threadID].splitPoint, threadID);
2765 Threads[threadID].idle = true;
2768 // If this thread is the master of a split point and all threads have
2769 // finished their work at this split point, return from the idle loop.
2770 if (waitSp != NULL && waitSp->cpus == 0)
2774 Threads[threadID].running = false;
2778 // init_split_point_stack() is called during program initialization, and
2779 // initializes all split point objects.
2781 void init_split_point_stack() {
2783 for (int i = 0; i < THREAD_MAX; i++)
2784 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2786 SplitPointStack[i][j].parent = NULL;
2787 lock_init(&(SplitPointStack[i][j].lock), NULL);
2792 // destroy_split_point_stack() is called when the program exits, and
2793 // destroys all locks in the precomputed split point objects.
2795 void destroy_split_point_stack() {
2797 for (int i = 0; i < THREAD_MAX; i++)
2798 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2799 lock_destroy(&(SplitPointStack[i][j].lock));
2803 // thread_should_stop() checks whether the thread with a given threadID has
2804 // been asked to stop, directly or indirectly. This can happen if a beta
2805 // cutoff has occurred in the thread's currently active split point, or in
2806 // some ancestor of the current split point.
2808 bool thread_should_stop(int threadID) {
2810 assert(threadID >= 0 && threadID < ActiveThreads);
2814 if (Threads[threadID].stop)
2816 if (ActiveThreads <= 2)
2818 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2821 Threads[threadID].stop = true;
2828 // thread_is_available() checks whether the thread with threadID "slave" is
2829 // available to help the thread with threadID "master" at a split point. An
2830 // obvious requirement is that "slave" must be idle. With more than two
2831 // threads, this is not by itself sufficient: If "slave" is the master of
2832 // some active split point, it is only available as a slave to the other
2833 // threads which are busy searching the split point at the top of "slave"'s
2834 // split point stack (the "helpful master concept" in YBWC terminology).
2836 bool thread_is_available(int slave, int master) {
2838 assert(slave >= 0 && slave < ActiveThreads);
2839 assert(master >= 0 && master < ActiveThreads);
2840 assert(ActiveThreads > 1);
2842 if (!Threads[slave].idle || slave == master)
2845 if (Threads[slave].activeSplitPoints == 0)
2846 // No active split points means that the thread is available as
2847 // a slave for any other thread.
2850 if (ActiveThreads == 2)
2853 // Apply the "helpful master" concept if possible
2854 if (SplitPointStack[slave][Threads[slave].activeSplitPoints - 1].slaves[master])
2861 // idle_thread_exists() tries to find an idle thread which is available as
2862 // a slave for the thread with threadID "master".
2864 bool idle_thread_exists(int master) {
2866 assert(master >= 0 && master < ActiveThreads);
2867 assert(ActiveThreads > 1);
2869 for (int i = 0; i < ActiveThreads; i++)
2870 if (thread_is_available(i, master))
2877 // split() does the actual work of distributing the work at a node between
2878 // several threads at PV nodes. If it does not succeed in splitting the
2879 // node (because no idle threads are available, or because we have no unused
2880 // split point objects), the function immediately returns false. If
2881 // splitting is possible, a SplitPoint object is initialized with all the
2882 // data that must be copied to the helper threads (the current position and
2883 // search stack, alpha, beta, the search depth, etc.), and we tell our
2884 // helper threads that they have been assigned work. This will cause them
2885 // to instantly leave their idle loops and call sp_search_pv(). When all
2886 // threads have returned from sp_search_pv (or, equivalently, when
2887 // splitPoint->cpus becomes 0), split() returns true.
2889 bool split(const Position& p, SearchStack* sstck, int ply,
2890 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2891 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2894 assert(sstck != NULL);
2895 assert(ply >= 0 && ply < PLY_MAX);
2896 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2897 assert(!pvNode || *alpha < *beta);
2898 assert(*beta <= VALUE_INFINITE);
2899 assert(depth > Depth(0));
2900 assert(master >= 0 && master < ActiveThreads);
2901 assert(ActiveThreads > 1);
2903 SplitPoint* splitPoint;
2908 // If no other thread is available to help us, or if we have too many
2909 // active split points, don't split.
2910 if ( !idle_thread_exists(master)
2911 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2913 lock_release(&MPLock);
2917 // Pick the next available split point object from the split point stack
2918 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2919 Threads[master].activeSplitPoints++;
2921 // Initialize the split point object and copy current position
2922 splitPoint->parent = Threads[master].splitPoint;
2923 splitPoint->finished = false;
2924 splitPoint->ply = ply;
2925 splitPoint->depth = depth;
2926 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2927 splitPoint->beta = *beta;
2928 splitPoint->pvNode = pvNode;
2929 splitPoint->bestValue = *bestValue;
2930 splitPoint->futilityValue = futilityValue;
2931 splitPoint->master = master;
2932 splitPoint->mp = mp;
2933 splitPoint->moves = *moves;
2934 splitPoint->cpus = 1;
2935 splitPoint->pos.copy(p);
2936 splitPoint->parentSstack = sstck;
2937 for (i = 0; i < ActiveThreads; i++)
2938 splitPoint->slaves[i] = 0;
2940 // Copy the current search stack to the master thread
2941 memcpy(splitPoint->sstack[master], sstck, (ply+1) * sizeof(SearchStack));
2942 Threads[master].splitPoint = splitPoint;
2944 // Make copies of the current position and search stack for each thread
2945 for (i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2946 if (thread_is_available(i, master))
2948 memcpy(splitPoint->sstack[i], sstck, (ply+1) * sizeof(SearchStack));
2949 Threads[i].splitPoint = splitPoint;
2950 splitPoint->slaves[i] = 1;
2954 // Tell the threads that they have work to do. This will make them leave
2956 for (i = 0; i < ActiveThreads; i++)
2957 if (i == master || splitPoint->slaves[i])
2959 Threads[i].workIsWaiting = true;
2960 Threads[i].idle = false;
2961 Threads[i].stop = false;
2964 lock_release(&MPLock);
2966 // Everything is set up. The master thread enters the idle loop, from
2967 // which it will instantly launch a search, because its workIsWaiting
2968 // slot is 'true'. We send the split point as a second parameter to the
2969 // idle loop, which means that the main thread will return from the idle
2970 // loop when all threads have finished their work at this split point
2971 // (i.e. when splitPoint->cpus == 0).
2972 idle_loop(master, splitPoint);
2974 // We have returned from the idle loop, which means that all threads are
2975 // finished. Update alpha, beta and bestValue, and return.
2979 *alpha = splitPoint->alpha;
2981 *beta = splitPoint->beta;
2982 *bestValue = splitPoint->bestValue;
2983 Threads[master].stop = false;
2984 Threads[master].idle = false;
2985 Threads[master].activeSplitPoints--;
2986 Threads[master].splitPoint = splitPoint->parent;
2988 lock_release(&MPLock);
2993 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2994 // to start a new search from the root.
2996 void wake_sleeping_threads() {
2998 if (ActiveThreads > 1)
3000 for (int i = 1; i < ActiveThreads; i++)
3002 Threads[i].idle = true;
3003 Threads[i].workIsWaiting = false;
3006 #if !defined(_MSC_VER)
3007 pthread_mutex_lock(&WaitLock);
3008 pthread_cond_broadcast(&WaitCond);
3009 pthread_mutex_unlock(&WaitLock);
3011 for (int i = 1; i < THREAD_MAX; i++)
3012 SetEvent(SitIdleEvent[i]);
3018 // init_thread() is the function which is called when a new thread is
3019 // launched. It simply calls the idle_loop() function with the supplied
3020 // threadID. There are two versions of this function; one for POSIX
3021 // threads and one for Windows threads.
3023 #if !defined(_MSC_VER)
3025 void* init_thread(void *threadID) {
3027 idle_loop(*(int*)threadID, NULL);
3033 DWORD WINAPI init_thread(LPVOID threadID) {
3035 idle_loop(*(int*)threadID, NULL);