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 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 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
292 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
293 void update_killers(Move m, SearchStack& ss);
295 bool fail_high_ply_1();
296 int current_search_time();
300 void print_current_line(SearchStack ss[], int ply, int threadID);
301 void wait_for_stop_or_ponderhit();
302 void init_ss_array(SearchStack ss[]);
304 void idle_loop(int threadID, SplitPoint* waitSp);
305 void init_split_point_stack();
306 void destroy_split_point_stack();
307 bool thread_should_stop(int threadID);
308 bool thread_is_available(int slave, int master);
309 bool idle_thread_exists(int master);
310 bool split(const Position& pos, SearchStack* ss, int ply,
311 Value *alpha, Value *beta, Value *bestValue,
312 const Value futilityValue, Depth depth, int *moves,
313 MovePicker *mp, int master, bool pvNode);
314 void wake_sleeping_threads();
316 #if !defined(_MSC_VER)
317 void *init_thread(void *threadID);
319 DWORD WINAPI init_thread(LPVOID threadID);
330 static double lnArray[512];
332 inline double ln(int i)
337 /// perft() is our utility to verify move generation is bug free. All the legal
338 /// moves up to given depth are generated and counted and the sum returned.
340 int perft(Position& pos, Depth depth)
344 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
346 // If we are at the last ply we don't need to do and undo
347 // the moves, just to count them.
348 if (depth <= OnePly) // Replace with '<' to test also qsearch
350 while (mp.get_next_move()) sum++;
354 // Loop through all legal moves
356 while ((move = mp.get_next_move()) != MOVE_NONE)
359 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
360 sum += perft(pos, depth - OnePly);
367 /// think() is the external interface to Stockfish's search, and is called when
368 /// the program receives the UCI 'go' command. It initializes various
369 /// search-related global variables, and calls root_search(). It returns false
370 /// when a quit command is received during the search.
372 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
373 int time[], int increment[], int movesToGo, int maxDepth,
374 int maxNodes, int maxTime, Move searchMoves[]) {
376 // Look for a book move
377 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
380 if (get_option_value_string("Book File") != OpeningBook.file_name())
381 OpeningBook.open(get_option_value_string("Book File"));
383 bookMove = OpeningBook.get_move(pos);
384 if (bookMove != MOVE_NONE)
386 cout << "bestmove " << bookMove << endl;
391 // Initialize global search variables
392 Idle = StopOnPonderhit = AbortSearch = Quit = false;
393 FailHigh = FailLow = Problem = false;
394 SearchStartTime = get_system_time();
395 ExactMaxTime = maxTime;
397 InfiniteSearch = infinite;
398 PonderSearch = ponder;
400 for (int i = 0; i < THREAD_MAX; i++)
402 Threads[i].nodes = 0ULL;
403 Threads[i].failHighPly1 = false;
406 if (button_was_pressed("New Game"))
407 loseOnTime = false; // Reset at the beginning of a new game
409 // Read UCI option values
410 TT.set_size(get_option_value_int("Hash"));
411 if (button_was_pressed("Clear Hash"))
414 bool PonderingEnabled = get_option_value_bool("Ponder");
415 MultiPV = get_option_value_int("MultiPV");
417 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
418 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
420 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
421 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
423 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
424 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
426 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
427 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
429 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
430 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
432 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
433 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
435 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
436 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
437 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
439 Chess960 = get_option_value_bool("UCI_Chess960");
440 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
441 UseLogFile = get_option_value_bool("Use Search Log");
443 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
445 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
446 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
448 read_weights(pos.side_to_move());
450 // Set the number of active threads
451 int newActiveThreads = get_option_value_int("Threads");
452 if (newActiveThreads != ActiveThreads)
454 ActiveThreads = newActiveThreads;
455 init_eval(ActiveThreads);
458 // Wake up sleeping threads
459 wake_sleeping_threads();
461 for (int i = 1; i < ActiveThreads; i++)
462 assert(thread_is_available(i, 0));
465 int myTime = time[side_to_move];
466 int myIncrement = increment[side_to_move];
468 if (!movesToGo) // Sudden death time control
472 MaxSearchTime = myTime / 30 + myIncrement;
473 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
475 else // Blitz game without increment
477 MaxSearchTime = myTime / 30;
478 AbsoluteMaxSearchTime = myTime / 8;
481 else // (x moves) / (y minutes)
485 MaxSearchTime = myTime / 2;
486 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
490 MaxSearchTime = myTime / Min(movesToGo, 20);
491 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
495 if (PonderingEnabled)
497 MaxSearchTime += MaxSearchTime / 4;
498 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
501 // Fixed depth or fixed number of nodes?
504 InfiniteSearch = true; // HACK
509 NodesBetweenPolls = Min(MaxNodes, 30000);
510 InfiniteSearch = true; // HACK
512 else if (myTime && myTime < 1000)
513 NodesBetweenPolls = 1000;
514 else if (myTime && myTime < 5000)
515 NodesBetweenPolls = 5000;
517 NodesBetweenPolls = 30000;
519 // Write information to search log file
521 LogFile << "Searching: " << pos.to_fen() << endl
522 << "infinite: " << infinite
523 << " ponder: " << ponder
524 << " time: " << myTime
525 << " increment: " << myIncrement
526 << " moves to go: " << movesToGo << endl;
528 // LSN filtering. Used only for developing purpose. Disabled by default.
532 // Step 2. If after last move we decided to lose on time, do it now!
533 while (SearchStartTime + myTime + 1000 > get_system_time())
537 // We're ready to start thinking. Call the iterative deepening loop function
538 Value v = id_loop(pos, searchMoves);
543 // Step 1. If this is sudden death game and our position is hopeless,
544 // decide to lose on time.
545 if ( !loseOnTime // If we already lost on time, go to step 3.
555 // Step 3. Now after stepping over the time limit, reset flag for next match.
568 /// init_threads() is called during startup. It launches all helper threads,
569 /// and initializes the split point stack and the global locks and condition
572 #include <cmath> //FIXME: HACK
574 void init_threads() {
577 for (int i = 0; i < 512; i++)
578 lnArray[i] = log(double(i));
582 #if !defined(_MSC_VER)
583 pthread_t pthread[1];
586 for (i = 0; i < THREAD_MAX; i++)
587 Threads[i].activeSplitPoints = 0;
589 // Initialize global locks
590 lock_init(&MPLock, NULL);
591 lock_init(&IOLock, NULL);
593 init_split_point_stack();
595 #if !defined(_MSC_VER)
596 pthread_mutex_init(&WaitLock, NULL);
597 pthread_cond_init(&WaitCond, NULL);
599 for (i = 0; i < THREAD_MAX; i++)
600 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
603 // All threads except the main thread should be initialized to idle state
604 for (i = 1; i < THREAD_MAX; i++)
606 Threads[i].stop = false;
607 Threads[i].workIsWaiting = false;
608 Threads[i].idle = true;
609 Threads[i].running = false;
612 // Launch the helper threads
613 for (i = 1; i < THREAD_MAX; i++)
615 #if !defined(_MSC_VER)
616 pthread_create(pthread, NULL, init_thread, (void*)(&i));
619 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
622 // Wait until the thread has finished launching
623 while (!Threads[i].running);
628 /// stop_threads() is called when the program exits. It makes all the
629 /// helper threads exit cleanly.
631 void stop_threads() {
633 ActiveThreads = THREAD_MAX; // HACK
634 Idle = false; // HACK
635 wake_sleeping_threads();
636 AllThreadsShouldExit = true;
637 for (int i = 1; i < THREAD_MAX; i++)
639 Threads[i].stop = true;
640 while (Threads[i].running);
642 destroy_split_point_stack();
646 /// nodes_searched() returns the total number of nodes searched so far in
647 /// the current search.
649 int64_t nodes_searched() {
651 int64_t result = 0ULL;
652 for (int i = 0; i < ActiveThreads; i++)
653 result += Threads[i].nodes;
658 // SearchStack::init() initializes a search stack. Used at the beginning of a
659 // new search from the root.
660 void SearchStack::init(int ply) {
662 pv[ply] = pv[ply + 1] = MOVE_NONE;
663 currentMove = threatMove = MOVE_NONE;
664 reduction = Depth(0);
667 void SearchStack::initKillers() {
669 mateKiller = MOVE_NONE;
670 for (int i = 0; i < KILLER_MAX; i++)
671 killers[i] = MOVE_NONE;
676 // id_loop() is the main iterative deepening loop. It calls root_search
677 // repeatedly with increasing depth until the allocated thinking time has
678 // been consumed, the user stops the search, or the maximum search depth is
681 Value id_loop(const Position& pos, Move searchMoves[]) {
684 SearchStack ss[PLY_MAX_PLUS_2];
686 // searchMoves are verified, copied, scored and sorted
687 RootMoveList rml(p, searchMoves);
689 if (rml.move_count() == 0)
692 wait_for_stop_or_ponderhit();
694 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
697 // Print RootMoveList c'tor startup scoring to the standard output,
698 // so that we print information also for iteration 1.
699 cout << "info depth " << 1 << "\ninfo depth " << 1
700 << " score " << value_to_string(rml.get_move_score(0))
701 << " time " << current_search_time()
702 << " nodes " << nodes_searched()
704 << " pv " << rml.get_move(0) << "\n";
710 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
713 // Is one move significantly better than others after initial scoring ?
714 Move EasyMove = MOVE_NONE;
715 if ( rml.move_count() == 1
716 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
717 EasyMove = rml.get_move(0);
719 // Iterative deepening loop
720 while (Iteration < PLY_MAX)
722 // Initialize iteration
725 BestMoveChangesByIteration[Iteration] = 0;
729 cout << "info depth " << Iteration << endl;
731 // Calculate dynamic search window based on previous iterations
734 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
736 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
737 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
739 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
741 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
742 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
746 alpha = - VALUE_INFINITE;
747 beta = VALUE_INFINITE;
750 // Search to the current depth
751 Value value = root_search(p, ss, rml, alpha, beta);
753 // Write PV to transposition table, in case the relevant entries have
754 // been overwritten during the search.
755 TT.insert_pv(p, ss[0].pv);
758 break; // Value cannot be trusted. Break out immediately!
760 //Save info about search result
761 Value speculatedValue;
764 Value delta = value - IterationInfo[Iteration - 1].value;
771 speculatedValue = value + delta;
772 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
774 else if (value <= alpha)
776 assert(value == alpha);
780 speculatedValue = value + delta;
781 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
783 speculatedValue = value;
785 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
786 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
788 // Drop the easy move if it differs from the new best move
789 if (ss[0].pv[0] != EasyMove)
790 EasyMove = MOVE_NONE;
797 bool stopSearch = false;
799 // Stop search early if there is only a single legal move,
800 // we search up to Iteration 6 anyway to get a proper score.
801 if (Iteration >= 6 && rml.move_count() == 1)
804 // Stop search early when the last two iterations returned a mate score
806 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
807 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
810 // Stop search early if one move seems to be much better than the rest
811 int64_t nodes = nodes_searched();
815 && EasyMove == ss[0].pv[0]
816 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
817 && current_search_time() > MaxSearchTime / 16)
818 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
819 && current_search_time() > MaxSearchTime / 32)))
822 // Add some extra time if the best move has changed during the last two iterations
823 if (Iteration > 5 && Iteration <= 50)
824 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
825 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
827 // Stop search if most of MaxSearchTime is consumed at the end of the
828 // iteration. We probably don't have enough time to search the first
829 // move at the next iteration anyway.
830 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
838 StopOnPonderhit = true;
842 if (MaxDepth && Iteration >= MaxDepth)
848 // If we are pondering, we shouldn't print the best move before we
851 wait_for_stop_or_ponderhit();
853 // Print final search statistics
854 cout << "info nodes " << nodes_searched()
856 << " time " << current_search_time()
857 << " hashfull " << TT.full() << endl;
859 // Print the best move and the ponder move to the standard output
860 if (ss[0].pv[0] == MOVE_NONE)
862 ss[0].pv[0] = rml.get_move(0);
863 ss[0].pv[1] = MOVE_NONE;
865 cout << "bestmove " << ss[0].pv[0];
866 if (ss[0].pv[1] != MOVE_NONE)
867 cout << " ponder " << ss[0].pv[1];
874 dbg_print_mean(LogFile);
876 if (dbg_show_hit_rate)
877 dbg_print_hit_rate(LogFile);
879 LogFile << "\nNodes: " << nodes_searched()
880 << "\nNodes/second: " << nps()
881 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
884 p.do_move(ss[0].pv[0], st);
885 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
887 return rml.get_move_score(0);
891 // root_search() is the function which searches the root node. It is
892 // similar to search_pv except that it uses a different move ordering
893 // scheme and prints some information to the standard output.
895 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta) {
897 Value oldAlpha = alpha;
901 // Loop through all the moves in the root move list
902 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
906 // We failed high, invalidate and skip next moves, leave node-counters
907 // and beta-counters as they are and quickly return, we will try to do
908 // a research at the next iteration with a bigger aspiration window.
909 rml.set_move_score(i, -VALUE_INFINITE);
915 Depth depth, ext, newDepth;
917 RootMoveNumber = i + 1;
920 // Save the current node count before the move is searched
921 nodes = nodes_searched();
923 // Reset beta cut-off counters
926 // Pick the next root move, and print the move and the move number to
927 // the standard output.
928 move = ss[0].currentMove = rml.get_move(i);
930 if (current_search_time() >= 1000)
931 cout << "info currmove " << move
932 << " currmovenumber " << RootMoveNumber << endl;
934 // Decide search depth for this move
935 bool moveIsCheck = pos.move_is_check(move);
936 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
938 depth = (Iteration - 2) * OnePly + InitialDepth;
939 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
940 newDepth = depth + ext;
942 // Make the move, and search it
943 pos.do_move(move, st, ci, moveIsCheck);
947 // Aspiration window is disabled in multi-pv case
949 alpha = -VALUE_INFINITE;
951 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
953 // If the value has dropped a lot compared to the last iteration,
954 // set the boolean variable Problem to true. This variable is used
955 // for time managment: When Problem is true, we try to complete the
956 // current iteration before playing a move.
957 Problem = ( Iteration >= 2
958 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
960 if (Problem && StopOnPonderhit)
961 StopOnPonderhit = false;
965 // Try to reduce non-pv search depth by one ply if move seems not problematic,
966 // if the move fails high will be re-searched at full depth.
967 if ( depth >= 3*OnePly // FIXME was newDepth
969 && !captureOrPromotion
970 && !move_is_castle(move))
972 double red = 0.5 + ln(RootMoveNumber - MultiPV + 1) * ln(depth / 2) / 6.0;
975 ss[0].reduction = Depth(int(floor(red * int(OnePly))));
976 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
979 value = alpha + 1; // Just to trigger next condition
981 value = alpha + 1; // Just to trigger next condition
985 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
989 // Fail high! Set the boolean variable FailHigh to true, and
990 // re-search the move using a PV search. The variable FailHigh
991 // is used for time managment: We try to avoid aborting the
992 // search prematurely during a fail high research.
994 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
1001 // Finished searching the move. If AbortSearch is true, the search
1002 // was aborted because the user interrupted the search or because we
1003 // ran out of time. In this case, the return value of the search cannot
1004 // be trusted, and we break out of the loop without updating the best
1009 // Remember beta-cutoff and searched nodes counts for this move. The
1010 // info is used to sort the root moves at the next iteration.
1012 BetaCounter.read(pos.side_to_move(), our, their);
1013 rml.set_beta_counters(i, our, their);
1014 rml.set_move_nodes(i, nodes_searched() - nodes);
1016 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1018 if (value <= alpha && i >= MultiPV)
1019 rml.set_move_score(i, -VALUE_INFINITE);
1022 // PV move or new best move!
1025 rml.set_move_score(i, value);
1027 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1028 rml.set_move_pv(i, ss[0].pv);
1032 // We record how often the best move has been changed in each
1033 // iteration. This information is used for time managment: When
1034 // the best move changes frequently, we allocate some more time.
1036 BestMoveChangesByIteration[Iteration]++;
1038 // Print search information to the standard output
1039 cout << "info depth " << Iteration
1040 << " score " << value_to_string(value)
1041 << ((value >= beta) ? " lowerbound" :
1042 ((value <= alpha)? " upperbound" : ""))
1043 << " time " << current_search_time()
1044 << " nodes " << nodes_searched()
1048 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1049 cout << ss[0].pv[j] << " ";
1055 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1056 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1058 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1059 nodes_searched(), value, type, ss[0].pv) << endl;
1064 // Reset the global variable Problem to false if the value isn't too
1065 // far below the final value from the last iteration.
1066 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1071 rml.sort_multipv(i);
1072 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1074 cout << "info multipv " << j + 1
1075 << " score " << value_to_string(rml.get_move_score(j))
1076 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1077 << " time " << current_search_time()
1078 << " nodes " << nodes_searched()
1082 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1083 cout << rml.get_move_pv(j, k) << " ";
1087 alpha = rml.get_move_score(Min(i, MultiPV-1));
1089 } // PV move or new best move
1091 assert(alpha >= oldAlpha);
1093 FailLow = (alpha == oldAlpha);
1099 // search_pv() is the main search function for PV nodes.
1101 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1102 Depth depth, int ply, int threadID) {
1104 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1105 assert(beta > alpha && beta <= VALUE_INFINITE);
1106 assert(ply >= 0 && ply < PLY_MAX);
1107 assert(threadID >= 0 && threadID < ActiveThreads);
1109 Move movesSearched[256];
1114 Depth ext, newDepth;
1115 Value oldAlpha, value;
1116 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1118 Value bestValue = -VALUE_INFINITE;
1121 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1123 // Initialize, and make an early exit in case of an aborted search,
1124 // an instant draw, maximum ply reached, etc.
1125 init_node(ss, ply, threadID);
1127 // After init_node() that calls poll()
1128 if (AbortSearch || thread_should_stop(threadID))
1134 if (ply >= PLY_MAX - 1)
1135 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1137 // Mate distance pruning
1139 alpha = Max(value_mated_in(ply), alpha);
1140 beta = Min(value_mate_in(ply+1), beta);
1144 // Transposition table lookup. At PV nodes, we don't use the TT for
1145 // pruning, but only for move ordering. This is to avoid problems in
1146 // the following areas:
1148 // * Repetition draw detection
1149 // * Fifty move rule detection
1150 // * Searching for a mate
1151 // * Printing of full PV line
1153 tte = TT.retrieve(pos.get_key());
1154 ttMove = (tte ? tte->move() : MOVE_NONE);
1156 // Go with internal iterative deepening if we don't have a TT move
1157 if ( UseIIDAtPVNodes
1158 && depth >= 5*OnePly
1159 && ttMove == MOVE_NONE)
1161 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1162 ttMove = ss[ply].pv[ply];
1163 tte = TT.retrieve(pos.get_key());
1166 // Initialize a MovePicker object for the current position, and prepare
1167 // to search all moves
1168 isCheck = pos.is_check();
1169 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1171 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1173 // Loop through all legal moves until no moves remain or a beta cutoff
1175 while ( alpha < beta
1176 && (move = mp.get_next_move()) != MOVE_NONE
1177 && !thread_should_stop(threadID))
1179 assert(move_is_ok(move));
1181 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1182 moveIsCheck = pos.move_is_check(move, ci);
1183 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1185 // Decide the new search depth
1186 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1188 // Singular extension search. We extend the TT move if its value is much better than
1189 // its siblings. To verify this we do a reduced search on all the other moves but the
1190 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1191 if ( depth >= 6 * OnePly
1193 && move == tte->move()
1195 && is_lower_bound(tte->type())
1196 && tte->depth() >= depth - 3 * OnePly)
1198 Value ttValue = value_from_tt(tte->value(), ply);
1200 if (abs(ttValue) < VALUE_KNOWN_WIN)
1202 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1204 if (excValue < ttValue - SingleReplyMargin)
1209 newDepth = depth - OnePly + ext;
1211 // Update current move
1212 movesSearched[moveCount++] = ss[ply].currentMove = move;
1214 // Make and search the move
1215 pos.do_move(move, st, ci, moveIsCheck);
1217 if (moveCount == 1) // The first move in list is the PV
1218 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1221 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1222 // if the move fails high will be re-searched at full depth.
1223 if ( depth >= 3*OnePly
1225 && !captureOrPromotion
1226 && !move_is_castle(move)
1227 && !move_is_killer(move, ss[ply]))
1229 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 6.0;
1232 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1233 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1236 value = alpha + 1; // Just to trigger next condition
1239 value = alpha + 1; // Just to trigger next condition
1241 if (value > alpha) // Go with full depth non-pv search
1243 ss[ply].reduction = Depth(0);
1244 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1245 if (value > alpha && value < beta)
1247 // When the search fails high at ply 1 while searching the first
1248 // move at the root, set the flag failHighPly1. This is used for
1249 // time managment: We don't want to stop the search early in
1250 // such cases, because resolving the fail high at ply 1 could
1251 // result in a big drop in score at the root.
1252 if (ply == 1 && RootMoveNumber == 1)
1253 Threads[threadID].failHighPly1 = true;
1255 // A fail high occurred. Re-search at full window (pv search)
1256 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1257 Threads[threadID].failHighPly1 = false;
1261 pos.undo_move(move);
1263 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1266 if (value > bestValue)
1273 if (value == value_mate_in(ply + 1))
1274 ss[ply].mateKiller = move;
1276 // If we are at ply 1, and we are searching the first root move at
1277 // ply 0, set the 'Problem' variable if the score has dropped a lot
1278 // (from the computer's point of view) since the previous iteration.
1281 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1286 if ( ActiveThreads > 1
1288 && depth >= MinimumSplitDepth
1290 && idle_thread_exists(threadID)
1292 && !thread_should_stop(threadID)
1293 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1294 depth, &moveCount, &mp, threadID, true))
1298 // All legal moves have been searched. A special case: If there were
1299 // no legal moves, it must be mate or stalemate.
1301 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1303 // If the search is not aborted, update the transposition table,
1304 // history counters, and killer moves.
1305 if (AbortSearch || thread_should_stop(threadID))
1308 if (bestValue <= oldAlpha)
1309 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1311 else if (bestValue >= beta)
1313 BetaCounter.add(pos.side_to_move(), depth, threadID);
1314 move = ss[ply].pv[ply];
1315 if (!pos.move_is_capture_or_promotion(move))
1317 update_history(pos, move, depth, movesSearched, moveCount);
1318 update_killers(move, ss[ply]);
1320 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1323 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1329 // search() is the search function for zero-width nodes.
1331 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1332 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1334 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1335 assert(ply >= 0 && ply < PLY_MAX);
1336 assert(threadID >= 0 && threadID < ActiveThreads);
1338 Move movesSearched[256];
1343 Depth ext, newDepth;
1344 Value staticValue, nullValue, value, futilityValue, futilityValueScaled;
1345 bool isCheck, useFutilityPruning, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1346 bool mateThreat = false;
1348 Value bestValue = -VALUE_INFINITE;
1351 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1353 // Initialize, and make an early exit in case of an aborted search,
1354 // an instant draw, maximum ply reached, etc.
1355 init_node(ss, ply, threadID);
1357 // After init_node() that calls poll()
1358 if (AbortSearch || thread_should_stop(threadID))
1364 if (ply >= PLY_MAX - 1)
1365 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1367 // Mate distance pruning
1368 if (value_mated_in(ply) >= beta)
1371 if (value_mate_in(ply + 1) < beta)
1374 // We don't want the score of a partial search to overwrite a previous full search
1375 // TT value, so we use a different position key in case of an excluded move exsists.
1376 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1378 // Transposition table lookup
1379 tte = TT.retrieve(posKey);
1380 ttMove = (tte ? tte->move() : MOVE_NONE);
1382 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1384 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1385 return value_from_tt(tte->value(), ply);
1388 isCheck = pos.is_check();
1389 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1391 // Evaluate the position statically
1393 staticValue = quick_evaluate(pos);
1394 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1395 staticValue = value_from_tt(tte->value(), ply);
1397 staticValue = evaluate(pos, ei, threadID);
1399 // Calculate depth dependant futility pruning parameters
1400 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1401 const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1403 // Enhance score accuracy with TT value if possible
1404 futilityValue = staticValue + FutilityValueMargin;
1405 staticValue = refine_eval(tte, staticValue, ply);
1411 && !value_is_mate(beta)
1412 && ok_to_do_nullmove(pos)
1413 && staticValue >= beta - NullMoveMargin)
1415 ss[ply].currentMove = MOVE_NULL;
1417 pos.do_null_move(st);
1419 // Null move dynamic reduction based on depth
1420 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1422 // Null move dynamic reduction based on value
1423 if (staticValue - beta > PawnValueMidgame)
1426 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1428 pos.undo_null_move();
1430 if (nullValue >= beta)
1432 if (depth < 6 * OnePly)
1435 // Do zugzwang verification search
1436 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1440 // The null move failed low, which means that we may be faced with
1441 // some kind of threat. If the previous move was reduced, check if
1442 // the move that refuted the null move was somehow connected to the
1443 // move which was reduced. If a connection is found, return a fail
1444 // low score (which will cause the reduced move to fail high in the
1445 // parent node, which will trigger a re-search with full depth).
1446 if (nullValue == value_mated_in(ply + 2))
1449 ss[ply].threatMove = ss[ply + 1].currentMove;
1450 if ( depth < ThreatDepth
1451 && ss[ply - 1].reduction
1452 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1456 // Null move search not allowed, try razoring
1457 else if ( !value_is_mate(beta)
1458 && depth < RazorDepth
1459 && staticValue < beta - RazorApprMargins[int(depth) - 2]
1460 && ss[ply - 1].currentMove != MOVE_NULL
1461 && ttMove == MOVE_NONE
1462 && !pos.has_pawn_on_7th(pos.side_to_move()))
1464 Value rbeta = beta - RazorMargins[int(depth) - 2];
1465 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1470 // Go with internal iterative deepening if we don't have a TT move
1471 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1472 !isCheck && evaluate(pos, ei, threadID) >= beta - IIDMargin)
1474 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1475 ttMove = ss[ply].pv[ply];
1476 tte = TT.retrieve(pos.get_key());
1479 // Initialize a MovePicker object for the current position, and prepare
1480 // to search all moves.
1481 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1483 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1485 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1486 while ( bestValue < beta
1487 && (move = mp.get_next_move()) != MOVE_NONE
1488 && !thread_should_stop(threadID))
1490 assert(move_is_ok(move));
1492 if (move == excludedMove)
1495 moveIsCheck = pos.move_is_check(move, ci);
1496 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1497 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1499 // Decide the new search depth
1500 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1502 // Singular extension search. We extend the TT move if its value is much better than
1503 // its siblings. To verify this we do a reduced search on all the other moves but the
1504 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1505 if ( depth >= 8 * OnePly
1507 && move == tte->move()
1508 && !excludedMove // Do not allow recursive single-reply search
1510 && is_lower_bound(tte->type())
1511 && tte->depth() >= depth - 3 * OnePly)
1513 Value ttValue = value_from_tt(tte->value(), ply);
1515 if (abs(ttValue) < VALUE_KNOWN_WIN)
1517 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1519 if (excValue < ttValue - SingleReplyMargin)
1524 newDepth = depth - OnePly + ext;
1526 // Update current move
1527 movesSearched[moveCount++] = ss[ply].currentMove = move;
1530 if ( useFutilityPruning
1532 && !captureOrPromotion
1535 // Move count based pruning
1536 if ( moveCount >= FutilityMoveCountMargin
1537 && ok_to_prune(pos, move, ss[ply].threatMove)
1538 && bestValue > value_mated_in(PLY_MAX))
1541 // Value based pruning
1542 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1544 if (futilityValueScaled < beta)
1546 if (futilityValueScaled > bestValue)
1547 bestValue = futilityValueScaled;
1552 // Make and search the move
1553 pos.do_move(move, st, ci, moveIsCheck);
1555 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1556 // if the move fails high will be re-searched at full depth.
1557 if ( depth >= 3*OnePly
1559 && !captureOrPromotion
1560 && !move_is_castle(move)
1561 && !move_is_killer(move, ss[ply])
1562 /* && move != ttMove*/)
1564 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1567 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1568 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1571 value = beta; // Just to trigger next condition
1574 value = beta; // Just to trigger next condition
1576 if (value >= beta) // Go with full depth non-pv search
1578 ss[ply].reduction = Depth(0);
1579 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1581 pos.undo_move(move);
1583 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1586 if (value > bestValue)
1592 if (value == value_mate_in(ply + 1))
1593 ss[ply].mateKiller = move;
1597 if ( ActiveThreads > 1
1599 && depth >= MinimumSplitDepth
1601 && idle_thread_exists(threadID)
1603 && !thread_should_stop(threadID)
1604 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue,
1605 depth, &moveCount, &mp, threadID, false))
1609 // All legal moves have been searched. A special case: If there were
1610 // no legal moves, it must be mate or stalemate.
1612 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1614 // If the search is not aborted, update the transposition table,
1615 // history counters, and killer moves.
1616 if (AbortSearch || thread_should_stop(threadID))
1619 if (bestValue < beta)
1620 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1623 BetaCounter.add(pos.side_to_move(), depth, threadID);
1624 move = ss[ply].pv[ply];
1625 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1626 if (!pos.move_is_capture_or_promotion(move))
1628 update_history(pos, move, depth, movesSearched, moveCount);
1629 update_killers(move, ss[ply]);
1634 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1640 // qsearch() is the quiescence search function, which is called by the main
1641 // search function when the remaining depth is zero (or, to be more precise,
1642 // less than OnePly).
1644 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1645 Depth depth, int ply, int threadID) {
1647 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1648 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1650 assert(ply >= 0 && ply < PLY_MAX);
1651 assert(threadID >= 0 && threadID < ActiveThreads);
1656 Value staticValue, bestValue, value, futilityBase, futilityValue;
1657 bool isCheck, enoughMaterial, moveIsCheck;
1658 const TTEntry* tte = NULL;
1660 bool pvNode = (beta - alpha != 1);
1662 // Initialize, and make an early exit in case of an aborted search,
1663 // an instant draw, maximum ply reached, etc.
1664 init_node(ss, ply, threadID);
1666 // After init_node() that calls poll()
1667 if (AbortSearch || thread_should_stop(threadID))
1673 if (ply >= PLY_MAX - 1)
1674 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1676 // Transposition table lookup. At PV nodes, we don't use the TT for
1677 // pruning, but only for move ordering.
1678 tte = TT.retrieve(pos.get_key());
1679 ttMove = (tte ? tte->move() : MOVE_NONE);
1681 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1683 assert(tte->type() != VALUE_TYPE_EVAL);
1685 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1686 return value_from_tt(tte->value(), ply);
1689 isCheck = pos.is_check();
1690 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1692 // Evaluate the position statically
1694 staticValue = -VALUE_INFINITE;
1695 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1696 staticValue = value_from_tt(tte->value(), ply);
1698 staticValue = evaluate(pos, ei, threadID);
1700 // Initialize "stand pat score", and return it immediately if it is
1702 bestValue = staticValue;
1704 if (bestValue >= beta)
1706 // Store the score to avoid a future costly evaluation() call
1707 if (!isCheck && !tte && ei.futilityMargin == 0)
1708 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1713 if (bestValue > alpha)
1716 // Initialize a MovePicker object for the current position, and prepare
1717 // to search the moves. Because the depth is <= 0 here, only captures,
1718 // queen promotions and checks (only if depth == 0) will be generated.
1719 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1721 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1722 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1724 // Loop through the moves until no moves remain or a beta cutoff
1726 while ( alpha < beta
1727 && (move = mp.get_next_move()) != MOVE_NONE)
1729 assert(move_is_ok(move));
1731 moveIsCheck = pos.move_is_check(move, ci);
1733 // Update current move
1735 ss[ply].currentMove = move;
1743 && !move_is_promotion(move)
1744 && !pos.move_is_passed_pawn_push(move))
1746 futilityValue = futilityBase
1747 + pos.endgame_value_of_piece_on(move_to(move))
1748 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1750 if (futilityValue < alpha)
1752 if (futilityValue > bestValue)
1753 bestValue = futilityValue;
1758 // Don't search captures and checks with negative SEE values
1761 && !move_is_promotion(move)
1762 && pos.see_sign(move) < 0)
1765 // Make and search the move
1766 pos.do_move(move, st, ci, moveIsCheck);
1767 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1768 pos.undo_move(move);
1770 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1773 if (value > bestValue)
1784 // All legal moves have been searched. A special case: If we're in check
1785 // and no legal moves were found, it is checkmate.
1786 if (!moveCount && pos.is_check()) // Mate!
1787 return value_mated_in(ply);
1789 // Update transposition table
1790 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1791 if (bestValue < beta)
1793 // If bestValue isn't changed it means it is still the static evaluation
1794 // of the node, so keep this info to avoid a future evaluation() call.
1795 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1796 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1800 move = ss[ply].pv[ply];
1801 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1803 // Update killers only for good checking moves
1804 if (!pos.move_is_capture_or_promotion(move))
1805 update_killers(move, ss[ply]);
1808 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1814 // sp_search() is used to search from a split point. This function is called
1815 // by each thread working at the split point. It is similar to the normal
1816 // search() function, but simpler. Because we have already probed the hash
1817 // table, done a null move search, and searched the first move before
1818 // splitting, we don't have to repeat all this work in sp_search(). We
1819 // also don't need to store anything to the hash table here: This is taken
1820 // care of after we return from the split point.
1822 void sp_search(SplitPoint* sp, int threadID) {
1824 assert(threadID >= 0 && threadID < ActiveThreads);
1825 assert(ActiveThreads > 1);
1827 Position pos = Position(sp->pos);
1829 SearchStack* ss = sp->sstack[threadID];
1832 bool isCheck = pos.is_check();
1833 bool useFutilityPruning = sp->depth < SelectiveDepth
1836 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1837 const int FutilityValueMargin = 112 * bitScanReverse32(int(sp->depth) * int(sp->depth) / 2);
1839 while ( sp->bestValue < sp->beta
1840 && !thread_should_stop(threadID)
1841 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1843 assert(move_is_ok(move));
1845 bool moveIsCheck = pos.move_is_check(move, ci);
1846 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1848 lock_grab(&(sp->lock));
1849 int moveCount = ++sp->moves;
1850 lock_release(&(sp->lock));
1852 ss[sp->ply].currentMove = move;
1854 // Decide the new search depth.
1856 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1857 Depth newDepth = sp->depth - OnePly + ext;
1860 if ( useFutilityPruning
1862 && !captureOrPromotion)
1864 // Move count based pruning
1865 if ( moveCount >= FutilityMoveCountMargin
1866 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1867 && sp->bestValue > value_mated_in(PLY_MAX))
1870 // Value based pruning
1871 if (sp->futilityValue == VALUE_NONE)
1874 sp->futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1877 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1879 if (futilityValueScaled < sp->beta)
1881 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1883 lock_grab(&(sp->lock));
1884 if (futilityValueScaled > sp->bestValue)
1885 sp->bestValue = futilityValueScaled;
1886 lock_release(&(sp->lock));
1892 // Make and search the move.
1894 pos.do_move(move, st, ci, moveIsCheck);
1896 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1897 // if the move fails high will be re-searched at full depth.
1899 && !captureOrPromotion
1900 && !move_is_castle(move)
1901 && !move_is_killer(move, ss[sp->ply]))
1903 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 3.0;
1906 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1907 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1910 value = sp->beta; // Just to trigger next condition
1913 value = sp->beta; // Just to trigger next condition
1915 if (value >= sp->beta) // Go with full depth non-pv search
1917 ss[sp->ply].reduction = Depth(0);
1918 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1920 pos.undo_move(move);
1922 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1924 if (thread_should_stop(threadID))
1928 if (value > sp->bestValue) // Less then 2% of cases
1930 lock_grab(&(sp->lock));
1931 if (value > sp->bestValue && !thread_should_stop(threadID))
1933 sp->bestValue = value;
1934 if (sp->bestValue >= sp->beta)
1936 sp_update_pv(sp->parentSstack, ss, sp->ply);
1937 for (int i = 0; i < ActiveThreads; i++)
1938 if (i != threadID && (i == sp->master || sp->slaves[i]))
1939 Threads[i].stop = true;
1941 sp->finished = true;
1944 lock_release(&(sp->lock));
1948 lock_grab(&(sp->lock));
1950 // If this is the master thread and we have been asked to stop because of
1951 // a beta cutoff higher up in the tree, stop all slave threads.
1952 if (sp->master == threadID && thread_should_stop(threadID))
1953 for (int i = 0; i < ActiveThreads; i++)
1955 Threads[i].stop = true;
1958 sp->slaves[threadID] = 0;
1960 lock_release(&(sp->lock));
1964 // sp_search_pv() is used to search from a PV split point. This function
1965 // is called by each thread working at the split point. It is similar to
1966 // the normal search_pv() function, but simpler. Because we have already
1967 // probed the hash table and searched the first move before splitting, we
1968 // don't have to repeat all this work in sp_search_pv(). We also don't
1969 // need to store anything to the hash table here: This is taken care of
1970 // after we return from the split point.
1972 void sp_search_pv(SplitPoint* sp, int threadID) {
1974 assert(threadID >= 0 && threadID < ActiveThreads);
1975 assert(ActiveThreads > 1);
1977 Position pos = Position(sp->pos);
1979 SearchStack* ss = sp->sstack[threadID];
1983 while ( sp->alpha < sp->beta
1984 && !thread_should_stop(threadID)
1985 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1987 bool moveIsCheck = pos.move_is_check(move, ci);
1988 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1990 assert(move_is_ok(move));
1992 lock_grab(&(sp->lock));
1993 int moveCount = ++sp->moves;
1994 lock_release(&(sp->lock));
1996 ss[sp->ply].currentMove = move;
1998 // Decide the new search depth.
2000 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2001 Depth newDepth = sp->depth - OnePly + ext;
2003 // Make and search the move.
2005 pos.do_move(move, st, ci, moveIsCheck);
2007 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2008 // if the move fails high will be re-searched at full depth.
2010 && !captureOrPromotion
2011 && !move_is_castle(move)
2012 && !move_is_killer(move, ss[sp->ply]))
2014 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 6.0;
2017 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
2018 value = -search(pos, ss, -sp->alpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2021 value = sp->alpha + 1; // Just to trigger next condition
2024 value = sp->alpha + 1; // Just to trigger next condition
2026 if (value > sp->alpha) // Go with full depth non-pv search
2028 ss[sp->ply].reduction = Depth(0);
2029 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
2031 if (value > sp->alpha && value < sp->beta)
2033 // When the search fails high at ply 1 while searching the first
2034 // move at the root, set the flag failHighPly1. This is used for
2035 // time managment: We don't want to stop the search early in
2036 // such cases, because resolving the fail high at ply 1 could
2037 // result in a big drop in score at the root.
2038 if (sp->ply == 1 && RootMoveNumber == 1)
2039 Threads[threadID].failHighPly1 = true;
2041 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2042 Threads[threadID].failHighPly1 = false;
2045 pos.undo_move(move);
2047 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2049 if (thread_should_stop(threadID))
2053 lock_grab(&(sp->lock));
2054 if (value > sp->bestValue && !thread_should_stop(threadID))
2056 sp->bestValue = value;
2057 if (value > sp->alpha)
2060 sp_update_pv(sp->parentSstack, ss, sp->ply);
2061 if (value == value_mate_in(sp->ply + 1))
2062 ss[sp->ply].mateKiller = move;
2064 if (value >= sp->beta)
2066 for (int i = 0; i < ActiveThreads; i++)
2067 if (i != threadID && (i == sp->master || sp->slaves[i]))
2068 Threads[i].stop = true;
2070 sp->finished = true;
2073 // If we are at ply 1, and we are searching the first root move at
2074 // ply 0, set the 'Problem' variable if the score has dropped a lot
2075 // (from the computer's point of view) since the previous iteration.
2078 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2081 lock_release(&(sp->lock));
2084 lock_grab(&(sp->lock));
2086 // If this is the master thread and we have been asked to stop because of
2087 // a beta cutoff higher up in the tree, stop all slave threads.
2088 if (sp->master == threadID && thread_should_stop(threadID))
2089 for (int i = 0; i < ActiveThreads; i++)
2091 Threads[i].stop = true;
2094 sp->slaves[threadID] = 0;
2096 lock_release(&(sp->lock));
2099 /// The BetaCounterType class
2101 BetaCounterType::BetaCounterType() { clear(); }
2103 void BetaCounterType::clear() {
2105 for (int i = 0; i < THREAD_MAX; i++)
2106 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2109 void BetaCounterType::add(Color us, Depth d, int threadID) {
2111 // Weighted count based on depth
2112 Threads[threadID].betaCutOffs[us] += unsigned(d);
2115 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2118 for (int i = 0; i < THREAD_MAX; i++)
2120 our += Threads[i].betaCutOffs[us];
2121 their += Threads[i].betaCutOffs[opposite_color(us)];
2126 /// The RootMoveList class
2128 // RootMoveList c'tor
2130 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2132 MoveStack mlist[MaxRootMoves];
2133 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2135 // Generate all legal moves
2136 MoveStack* last = generate_moves(pos, mlist);
2138 // Add each move to the moves[] array
2139 for (MoveStack* cur = mlist; cur != last; cur++)
2141 bool includeMove = includeAllMoves;
2143 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2144 includeMove = (searchMoves[k] == cur->move);
2149 // Find a quick score for the move
2151 SearchStack ss[PLY_MAX_PLUS_2];
2154 moves[count].move = cur->move;
2155 pos.do_move(moves[count].move, st);
2156 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2157 pos.undo_move(moves[count].move);
2158 moves[count].pv[0] = moves[count].move;
2159 moves[count].pv[1] = MOVE_NONE;
2166 // RootMoveList simple methods definitions
2168 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2170 moves[moveNum].nodes = nodes;
2171 moves[moveNum].cumulativeNodes += nodes;
2174 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2176 moves[moveNum].ourBeta = our;
2177 moves[moveNum].theirBeta = their;
2180 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2184 for (j = 0; pv[j] != MOVE_NONE; j++)
2185 moves[moveNum].pv[j] = pv[j];
2187 moves[moveNum].pv[j] = MOVE_NONE;
2191 // RootMoveList::sort() sorts the root move list at the beginning of a new
2194 void RootMoveList::sort() {
2196 sort_multipv(count - 1); // Sort all items
2200 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2201 // list by their scores and depths. It is used to order the different PVs
2202 // correctly in MultiPV mode.
2204 void RootMoveList::sort_multipv(int n) {
2208 for (i = 1; i <= n; i++)
2210 RootMove rm = moves[i];
2211 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2212 moves[j] = moves[j - 1];
2219 // init_node() is called at the beginning of all the search functions
2220 // (search(), search_pv(), qsearch(), and so on) and initializes the
2221 // search stack object corresponding to the current node. Once every
2222 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2223 // for user input and checks whether it is time to stop the search.
2225 void init_node(SearchStack ss[], int ply, int threadID) {
2227 assert(ply >= 0 && ply < PLY_MAX);
2228 assert(threadID >= 0 && threadID < ActiveThreads);
2230 Threads[threadID].nodes++;
2235 if (NodesSincePoll >= NodesBetweenPolls)
2242 ss[ply + 2].initKillers();
2244 if (Threads[threadID].printCurrentLine)
2245 print_current_line(ss, ply, threadID);
2249 // update_pv() is called whenever a search returns a value > alpha.
2250 // It updates the PV in the SearchStack object corresponding to the
2253 void update_pv(SearchStack ss[], int ply) {
2255 assert(ply >= 0 && ply < PLY_MAX);
2259 ss[ply].pv[ply] = ss[ply].currentMove;
2261 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2262 ss[ply].pv[p] = ss[ply + 1].pv[p];
2264 ss[ply].pv[p] = MOVE_NONE;
2268 // sp_update_pv() is a variant of update_pv for use at split points. The
2269 // difference between the two functions is that sp_update_pv also updates
2270 // the PV at the parent node.
2272 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2274 assert(ply >= 0 && ply < PLY_MAX);
2278 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2280 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2281 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2283 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2287 // connected_moves() tests whether two moves are 'connected' in the sense
2288 // that the first move somehow made the second move possible (for instance
2289 // if the moving piece is the same in both moves). The first move is assumed
2290 // to be the move that was made to reach the current position, while the
2291 // second move is assumed to be a move from the current position.
2293 bool connected_moves(const Position& pos, Move m1, Move m2) {
2295 Square f1, t1, f2, t2;
2298 assert(move_is_ok(m1));
2299 assert(move_is_ok(m2));
2301 if (m2 == MOVE_NONE)
2304 // Case 1: The moving piece is the same in both moves
2310 // Case 2: The destination square for m2 was vacated by m1
2316 // Case 3: Moving through the vacated square
2317 if ( piece_is_slider(pos.piece_on(f2))
2318 && bit_is_set(squares_between(f2, t2), f1))
2321 // Case 4: The destination square for m2 is defended by the moving piece in m1
2322 p = pos.piece_on(t1);
2323 if (bit_is_set(pos.attacks_from(p, t1), t2))
2326 // Case 5: Discovered check, checking piece is the piece moved in m1
2327 if ( piece_is_slider(p)
2328 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2329 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2331 // discovered_check_candidates() works also if the Position's side to
2332 // move is the opposite of the checking piece.
2333 Color them = opposite_color(pos.side_to_move());
2334 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2336 if (bit_is_set(dcCandidates, f2))
2343 // value_is_mate() checks if the given value is a mate one
2344 // eventually compensated for the ply.
2346 bool value_is_mate(Value value) {
2348 assert(abs(value) <= VALUE_INFINITE);
2350 return value <= value_mated_in(PLY_MAX)
2351 || value >= value_mate_in(PLY_MAX);
2355 // move_is_killer() checks if the given move is among the
2356 // killer moves of that ply.
2358 bool move_is_killer(Move m, const SearchStack& ss) {
2360 const Move* k = ss.killers;
2361 for (int i = 0; i < KILLER_MAX; i++, k++)
2369 // extension() decides whether a move should be searched with normal depth,
2370 // or with extended depth. Certain classes of moves (checking moves, in
2371 // particular) are searched with bigger depth than ordinary moves and in
2372 // any case are marked as 'dangerous'. Note that also if a move is not
2373 // extended, as example because the corresponding UCI option is set to zero,
2374 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2376 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2377 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2379 assert(m != MOVE_NONE);
2381 Depth result = Depth(0);
2382 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2387 result += CheckExtension[pvNode];
2390 result += SingleEvasionExtension[pvNode];
2393 result += MateThreatExtension[pvNode];
2396 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2398 Color c = pos.side_to_move();
2399 if (relative_rank(c, move_to(m)) == RANK_7)
2401 result += PawnPushTo7thExtension[pvNode];
2404 if (pos.pawn_is_passed(c, move_to(m)))
2406 result += PassedPawnExtension[pvNode];
2411 if ( captureOrPromotion
2412 && pos.type_of_piece_on(move_to(m)) != PAWN
2413 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2414 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2415 && !move_is_promotion(m)
2418 result += PawnEndgameExtension[pvNode];
2423 && captureOrPromotion
2424 && pos.type_of_piece_on(move_to(m)) != PAWN
2425 && pos.see_sign(m) >= 0)
2431 return Min(result, OnePly);
2435 // ok_to_do_nullmove() looks at the current position and decides whether
2436 // doing a 'null move' should be allowed. In order to avoid zugzwang
2437 // problems, null moves are not allowed when the side to move has very
2438 // little material left. Currently, the test is a bit too simple: Null
2439 // moves are avoided only when the side to move has only pawns left.
2440 // It's probably a good idea to avoid null moves in at least some more
2441 // complicated endgames, e.g. KQ vs KR. FIXME
2443 bool ok_to_do_nullmove(const Position& pos) {
2445 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2449 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2450 // non-tactical moves late in the move list close to the leaves are
2451 // candidates for pruning.
2453 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2455 assert(move_is_ok(m));
2456 assert(threat == MOVE_NONE || move_is_ok(threat));
2457 assert(!pos.move_is_check(m));
2458 assert(!pos.move_is_capture_or_promotion(m));
2459 assert(!pos.move_is_passed_pawn_push(m));
2461 Square mfrom, mto, tfrom, tto;
2463 // Prune if there isn't any threat move and
2464 // is not a castling move (common case).
2465 if (threat == MOVE_NONE && !move_is_castle(m))
2468 mfrom = move_from(m);
2470 tfrom = move_from(threat);
2471 tto = move_to(threat);
2473 // Case 1: Castling moves are never pruned
2474 if (move_is_castle(m))
2477 // Case 2: Don't prune moves which move the threatened piece
2481 // Case 3: If the threatened piece has value less than or equal to the
2482 // value of the threatening piece, don't prune move which defend it.
2483 if ( pos.move_is_capture(threat)
2484 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2485 || pos.type_of_piece_on(tfrom) == KING)
2486 && pos.move_attacks_square(m, tto))
2489 // Case 4: If the moving piece in the threatened move is a slider, don't
2490 // prune safe moves which block its ray.
2491 if ( piece_is_slider(pos.piece_on(tfrom))
2492 && bit_is_set(squares_between(tfrom, tto), mto)
2493 && pos.see_sign(m) >= 0)
2500 // ok_to_use_TT() returns true if a transposition table score
2501 // can be used at a given point in search.
2503 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2505 Value v = value_from_tt(tte->value(), ply);
2507 return ( tte->depth() >= depth
2508 || v >= Max(value_mate_in(PLY_MAX), beta)
2509 || v < Min(value_mated_in(PLY_MAX), beta))
2511 && ( (is_lower_bound(tte->type()) && v >= beta)
2512 || (is_upper_bound(tte->type()) && v < beta));
2516 // refine_eval() returns the transposition table score if
2517 // possible otherwise falls back on static position evaluation.
2519 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2524 Value v = value_from_tt(tte->value(), ply);
2526 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2527 || (is_upper_bound(tte->type()) && v < defaultEval))
2533 // update_history() registers a good move that produced a beta-cutoff
2534 // in history and marks as failures all the other moves of that ply.
2536 void update_history(const Position& pos, Move move, Depth depth,
2537 Move movesSearched[], int moveCount) {
2541 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2543 for (int i = 0; i < moveCount - 1; i++)
2545 m = movesSearched[i];
2549 if (!pos.move_is_capture_or_promotion(m))
2550 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2555 // update_killers() add a good move that produced a beta-cutoff
2556 // among the killer moves of that ply.
2558 void update_killers(Move m, SearchStack& ss) {
2560 if (m == ss.killers[0])
2563 for (int i = KILLER_MAX - 1; i > 0; i--)
2564 ss.killers[i] = ss.killers[i - 1];
2570 // fail_high_ply_1() checks if some thread is currently resolving a fail
2571 // high at ply 1 at the node below the first root node. This information
2572 // is used for time management.
2574 bool fail_high_ply_1() {
2576 for (int i = 0; i < ActiveThreads; i++)
2577 if (Threads[i].failHighPly1)
2584 // current_search_time() returns the number of milliseconds which have passed
2585 // since the beginning of the current search.
2587 int current_search_time() {
2589 return get_system_time() - SearchStartTime;
2593 // nps() computes the current nodes/second count.
2597 int t = current_search_time();
2598 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2602 // poll() performs two different functions: It polls for user input, and it
2603 // looks at the time consumed so far and decides if it's time to abort the
2608 static int lastInfoTime;
2609 int t = current_search_time();
2614 // We are line oriented, don't read single chars
2615 std::string command;
2617 if (!std::getline(std::cin, command))
2620 if (command == "quit")
2623 PonderSearch = false;
2627 else if (command == "stop")
2630 PonderSearch = false;
2632 else if (command == "ponderhit")
2636 // Print search information
2640 else if (lastInfoTime > t)
2641 // HACK: Must be a new search where we searched less than
2642 // NodesBetweenPolls nodes during the first second of search.
2645 else if (t - lastInfoTime >= 1000)
2653 if (dbg_show_hit_rate)
2654 dbg_print_hit_rate();
2656 cout << "info nodes " << nodes_searched() << " nps " << nps()
2657 << " time " << t << " hashfull " << TT.full() << endl;
2659 lock_release(&IOLock);
2661 if (ShowCurrentLine)
2662 Threads[0].printCurrentLine = true;
2665 // Should we stop the search?
2669 bool stillAtFirstMove = RootMoveNumber == 1
2671 && t > MaxSearchTime + ExtraSearchTime;
2673 bool noProblemFound = !FailHigh
2675 && !fail_high_ply_1()
2677 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2679 bool noMoreTime = t > AbsoluteMaxSearchTime
2680 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2683 if ( (Iteration >= 3 && !InfiniteSearch && noMoreTime)
2684 || (ExactMaxTime && t >= ExactMaxTime)
2685 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2690 // ponderhit() is called when the program is pondering (i.e. thinking while
2691 // it's the opponent's turn to move) in order to let the engine know that
2692 // it correctly predicted the opponent's move.
2696 int t = current_search_time();
2697 PonderSearch = false;
2699 bool stillAtFirstMove = RootMoveNumber == 1
2701 && t > MaxSearchTime + ExtraSearchTime;
2703 bool noProblemFound = !FailHigh
2705 && !fail_high_ply_1()
2707 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2709 bool noMoreTime = t > AbsoluteMaxSearchTime
2713 if (Iteration >= 3 && !InfiniteSearch && (noMoreTime || StopOnPonderhit))
2718 // print_current_line() prints the current line of search for a given
2719 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2721 void print_current_line(SearchStack ss[], int ply, int threadID) {
2723 assert(ply >= 0 && ply < PLY_MAX);
2724 assert(threadID >= 0 && threadID < ActiveThreads);
2726 if (!Threads[threadID].idle)
2729 cout << "info currline " << (threadID + 1);
2730 for (int p = 0; p < ply; p++)
2731 cout << " " << ss[p].currentMove;
2734 lock_release(&IOLock);
2736 Threads[threadID].printCurrentLine = false;
2737 if (threadID + 1 < ActiveThreads)
2738 Threads[threadID + 1].printCurrentLine = true;
2742 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2744 void init_ss_array(SearchStack ss[]) {
2746 for (int i = 0; i < 3; i++)
2749 ss[i].initKillers();
2754 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2755 // while the program is pondering. The point is to work around a wrinkle in
2756 // the UCI protocol: When pondering, the engine is not allowed to give a
2757 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2758 // We simply wait here until one of these commands is sent, and return,
2759 // after which the bestmove and pondermove will be printed (in id_loop()).
2761 void wait_for_stop_or_ponderhit() {
2763 std::string command;
2767 if (!std::getline(std::cin, command))
2770 if (command == "quit")
2775 else if (command == "ponderhit" || command == "stop")
2781 // idle_loop() is where the threads are parked when they have no work to do.
2782 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2783 // object for which the current thread is the master.
2785 void idle_loop(int threadID, SplitPoint* waitSp) {
2787 assert(threadID >= 0 && threadID < THREAD_MAX);
2789 Threads[threadID].running = true;
2793 if (AllThreadsShouldExit && threadID != 0)
2796 // If we are not thinking, wait for a condition to be signaled
2797 // instead of wasting CPU time polling for work.
2798 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2801 #if !defined(_MSC_VER)
2802 pthread_mutex_lock(&WaitLock);
2803 if (Idle || threadID >= ActiveThreads)
2804 pthread_cond_wait(&WaitCond, &WaitLock);
2806 pthread_mutex_unlock(&WaitLock);
2808 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2812 // If this thread has been assigned work, launch a search
2813 if (Threads[threadID].workIsWaiting)
2815 Threads[threadID].workIsWaiting = false;
2816 if (Threads[threadID].splitPoint->pvNode)
2817 sp_search_pv(Threads[threadID].splitPoint, threadID);
2819 sp_search(Threads[threadID].splitPoint, threadID);
2821 Threads[threadID].idle = true;
2824 // If this thread is the master of a split point and all threads have
2825 // finished their work at this split point, return from the idle loop.
2826 if (waitSp != NULL && waitSp->cpus == 0)
2830 Threads[threadID].running = false;
2834 // init_split_point_stack() is called during program initialization, and
2835 // initializes all split point objects.
2837 void init_split_point_stack() {
2839 for (int i = 0; i < THREAD_MAX; i++)
2840 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2842 SplitPointStack[i][j].parent = NULL;
2843 lock_init(&(SplitPointStack[i][j].lock), NULL);
2848 // destroy_split_point_stack() is called when the program exits, and
2849 // destroys all locks in the precomputed split point objects.
2851 void destroy_split_point_stack() {
2853 for (int i = 0; i < THREAD_MAX; i++)
2854 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2855 lock_destroy(&(SplitPointStack[i][j].lock));
2859 // thread_should_stop() checks whether the thread with a given threadID has
2860 // been asked to stop, directly or indirectly. This can happen if a beta
2861 // cutoff has occurred in the thread's currently active split point, or in
2862 // some ancestor of the current split point.
2864 bool thread_should_stop(int threadID) {
2866 assert(threadID >= 0 && threadID < ActiveThreads);
2870 if (Threads[threadID].stop)
2872 if (ActiveThreads <= 2)
2874 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2877 Threads[threadID].stop = true;
2884 // thread_is_available() checks whether the thread with threadID "slave" is
2885 // available to help the thread with threadID "master" at a split point. An
2886 // obvious requirement is that "slave" must be idle. With more than two
2887 // threads, this is not by itself sufficient: If "slave" is the master of
2888 // some active split point, it is only available as a slave to the other
2889 // threads which are busy searching the split point at the top of "slave"'s
2890 // split point stack (the "helpful master concept" in YBWC terminology).
2892 bool thread_is_available(int slave, int master) {
2894 assert(slave >= 0 && slave < ActiveThreads);
2895 assert(master >= 0 && master < ActiveThreads);
2896 assert(ActiveThreads > 1);
2898 if (!Threads[slave].idle || slave == master)
2901 if (Threads[slave].activeSplitPoints == 0)
2902 // No active split points means that the thread is available as
2903 // a slave for any other thread.
2906 if (ActiveThreads == 2)
2909 // Apply the "helpful master" concept if possible
2910 if (SplitPointStack[slave][Threads[slave].activeSplitPoints - 1].slaves[master])
2917 // idle_thread_exists() tries to find an idle thread which is available as
2918 // a slave for the thread with threadID "master".
2920 bool idle_thread_exists(int master) {
2922 assert(master >= 0 && master < ActiveThreads);
2923 assert(ActiveThreads > 1);
2925 for (int i = 0; i < ActiveThreads; i++)
2926 if (thread_is_available(i, master))
2933 // split() does the actual work of distributing the work at a node between
2934 // several threads at PV nodes. If it does not succeed in splitting the
2935 // node (because no idle threads are available, or because we have no unused
2936 // split point objects), the function immediately returns false. If
2937 // splitting is possible, a SplitPoint object is initialized with all the
2938 // data that must be copied to the helper threads (the current position and
2939 // search stack, alpha, beta, the search depth, etc.), and we tell our
2940 // helper threads that they have been assigned work. This will cause them
2941 // to instantly leave their idle loops and call sp_search_pv(). When all
2942 // threads have returned from sp_search_pv (or, equivalently, when
2943 // splitPoint->cpus becomes 0), split() returns true.
2945 bool split(const Position& p, SearchStack* sstck, int ply,
2946 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2947 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2950 assert(sstck != NULL);
2951 assert(ply >= 0 && ply < PLY_MAX);
2952 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2953 assert(!pvNode || *alpha < *beta);
2954 assert(*beta <= VALUE_INFINITE);
2955 assert(depth > Depth(0));
2956 assert(master >= 0 && master < ActiveThreads);
2957 assert(ActiveThreads > 1);
2959 SplitPoint* splitPoint;
2964 // If no other thread is available to help us, or if we have too many
2965 // active split points, don't split.
2966 if ( !idle_thread_exists(master)
2967 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2969 lock_release(&MPLock);
2973 // Pick the next available split point object from the split point stack
2974 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2975 Threads[master].activeSplitPoints++;
2977 // Initialize the split point object and copy current position
2978 splitPoint->parent = Threads[master].splitPoint;
2979 splitPoint->finished = false;
2980 splitPoint->ply = ply;
2981 splitPoint->depth = depth;
2982 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2983 splitPoint->beta = *beta;
2984 splitPoint->pvNode = pvNode;
2985 splitPoint->bestValue = *bestValue;
2986 splitPoint->futilityValue = futilityValue;
2987 splitPoint->master = master;
2988 splitPoint->mp = mp;
2989 splitPoint->moves = *moves;
2990 splitPoint->cpus = 1;
2991 splitPoint->pos.copy(p);
2992 splitPoint->parentSstack = sstck;
2993 for (i = 0; i < ActiveThreads; i++)
2994 splitPoint->slaves[i] = 0;
2996 // Copy the current search stack to the master thread
2997 memcpy(splitPoint->sstack[master], sstck, (ply+1) * sizeof(SearchStack));
2998 Threads[master].splitPoint = splitPoint;
3000 // Make copies of the current position and search stack for each thread
3001 for (i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3002 if (thread_is_available(i, master))
3004 memcpy(splitPoint->sstack[i], sstck, (ply+1) * sizeof(SearchStack));
3005 Threads[i].splitPoint = splitPoint;
3006 splitPoint->slaves[i] = 1;
3010 // Tell the threads that they have work to do. This will make them leave
3012 for (i = 0; i < ActiveThreads; i++)
3013 if (i == master || splitPoint->slaves[i])
3015 Threads[i].workIsWaiting = true;
3016 Threads[i].idle = false;
3017 Threads[i].stop = false;
3020 lock_release(&MPLock);
3022 // Everything is set up. The master thread enters the idle loop, from
3023 // which it will instantly launch a search, because its workIsWaiting
3024 // slot is 'true'. We send the split point as a second parameter to the
3025 // idle loop, which means that the main thread will return from the idle
3026 // loop when all threads have finished their work at this split point
3027 // (i.e. when splitPoint->cpus == 0).
3028 idle_loop(master, splitPoint);
3030 // We have returned from the idle loop, which means that all threads are
3031 // finished. Update alpha, beta and bestValue, and return.
3035 *alpha = splitPoint->alpha;
3037 *beta = splitPoint->beta;
3038 *bestValue = splitPoint->bestValue;
3039 Threads[master].stop = false;
3040 Threads[master].idle = false;
3041 Threads[master].activeSplitPoints--;
3042 Threads[master].splitPoint = splitPoint->parent;
3044 lock_release(&MPLock);
3049 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3050 // to start a new search from the root.
3052 void wake_sleeping_threads() {
3054 if (ActiveThreads > 1)
3056 for (int i = 1; i < ActiveThreads; i++)
3058 Threads[i].idle = true;
3059 Threads[i].workIsWaiting = false;
3062 #if !defined(_MSC_VER)
3063 pthread_mutex_lock(&WaitLock);
3064 pthread_cond_broadcast(&WaitCond);
3065 pthread_mutex_unlock(&WaitLock);
3067 for (int i = 1; i < THREAD_MAX; i++)
3068 SetEvent(SitIdleEvent[i]);
3074 // init_thread() is the function which is called when a new thread is
3075 // launched. It simply calls the idle_loop() function with the supplied
3076 // threadID. There are two versions of this function; one for POSIX
3077 // threads and one for Windows threads.
3079 #if !defined(_MSC_VER)
3081 void* init_thread(void *threadID) {
3083 idle_loop(*(int*)threadID, NULL);
3089 DWORD WINAPI init_thread(LPVOID threadID) {
3091 idle_loop(*(int*)threadID, NULL);