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).
98 bool operator<(const RootMove&) const; // Used to sort
102 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
103 Move pv[PLY_MAX_PLUS_2];
107 // The RootMoveList class is essentially an array of RootMove objects, with
108 // a handful of methods for accessing the data in the individual moves.
113 RootMoveList(Position& pos, Move searchMoves[]);
114 inline Move get_move(int moveNum) const;
115 inline Value get_move_score(int moveNum) const;
116 inline void set_move_score(int moveNum, Value score);
117 inline void set_move_nodes(int moveNum, int64_t nodes);
118 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
119 void set_move_pv(int moveNum, const Move pv[]);
120 inline Move get_move_pv(int moveNum, int i) const;
121 inline int64_t get_move_cumulative_nodes(int moveNum) const;
122 inline int move_count() const;
124 void sort_multipv(int n);
127 static const int MaxRootMoves = 500;
128 RootMove moves[MaxRootMoves];
135 // Search depth at iteration 1
136 const Depth InitialDepth = OnePly;
138 // Depth limit for selective search
139 const Depth SelectiveDepth = 7 * OnePly;
141 // Use internal iterative deepening?
142 const bool UseIIDAtPVNodes = true;
143 const bool UseIIDAtNonPVNodes = true;
145 // Internal iterative deepening margin. At Non-PV moves, when
146 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
147 // search when the static evaluation is at most IIDMargin below beta.
148 const Value IIDMargin = Value(0x100);
150 // Easy move margin. An easy move candidate must be at least this much
151 // better than the second best move.
152 const Value EasyMoveMargin = Value(0x200);
154 // Problem margin. If the score of the first move at iteration N+1 has
155 // dropped by more than this since iteration N, the boolean variable
156 // "Problem" is set to true, which will make the program spend some extra
157 // time looking for a better move.
158 const Value ProblemMargin = Value(0x28);
160 // No problem margin. If the boolean "Problem" is true, and a new move
161 // is found at the root which is less than NoProblemMargin worse than the
162 // best move from the previous iteration, Problem is set back to false.
163 const Value NoProblemMargin = Value(0x14);
165 // Null move margin. A null move search will not be done if the approximate
166 // evaluation of the position is more than NullMoveMargin below beta.
167 const Value NullMoveMargin = Value(0x300);
169 // Pruning criterions. See the code and comments in ok_to_prune() to
170 // understand their precise meaning.
171 const bool PruneEscapeMoves = false;
172 const bool PruneDefendingMoves = false;
173 const bool PruneBlockingMoves = false;
175 // If the TT move is at least SingleReplyMargin better then the
176 // remaining ones we will extend it.
177 const Value SingleReplyMargin = Value(0x20);
179 // Margins for futility pruning in the quiescence search, and at frontier
180 // and near frontier nodes.
181 const Value FutilityMarginQS = Value(0x80);
183 // Each move futility margin is decreased
184 const Value IncrementalFutilityMargin = Value(0x8);
186 // Depth limit for razoring
187 const Depth RazorDepth = 4 * OnePly;
189 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
190 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
192 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
193 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
196 /// Variables initialized by UCI options
198 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
199 int LMRPVMoves, LMRNonPVMoves;
201 // Depth limit for use of dynamic threat detection
204 // Last seconds noise filtering (LSN)
205 const bool UseLSNFiltering = true;
206 const int LSNTime = 4000; // In milliseconds
207 const Value LSNValue = value_from_centipawns(200);
208 bool loseOnTime = false;
210 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
211 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
212 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
214 // Iteration counters
216 BetaCounterType BetaCounter;
218 // Scores and number of times the best move changed for each iteration
219 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
220 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
225 // Time managment variables
228 int MaxNodes, MaxDepth;
229 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
230 bool InfiniteSearch, PonderSearch, StopOnPonderhit;
231 bool AbortSearch, Quit;
232 bool FailHigh, FailLow, Problem;
234 // Show current line?
235 bool ShowCurrentLine;
239 std::ofstream LogFile;
241 // MP related variables
242 int ActiveThreads = 1;
243 Depth MinimumSplitDepth;
244 int MaxThreadsPerSplitPoint;
245 Thread Threads[THREAD_MAX];
248 bool AllThreadsShouldExit = false;
249 const int MaxActiveSplitPoints = 8; // FIXME, sync with UCI Option
250 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
253 #if !defined(_MSC_VER)
254 pthread_cond_t WaitCond;
255 pthread_mutex_t WaitLock;
257 HANDLE SitIdleEvent[THREAD_MAX];
260 // Node counters, used only by thread[0] but try to keep in different
261 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
263 int NodesBetweenPolls = 30000;
271 Value id_loop(const Position& pos, Move searchMoves[]);
272 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
273 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
274 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
275 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
276 void sp_search(SplitPoint* sp, int threadID);
277 void sp_search_pv(SplitPoint* sp, int threadID);
278 void init_node(SearchStack ss[], int ply, int threadID);
279 void update_pv(SearchStack ss[], int ply);
280 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
281 bool connected_moves(const Position& pos, Move m1, Move m2);
282 bool value_is_mate(Value value);
283 bool move_is_killer(Move m, const SearchStack& ss);
284 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
285 bool ok_to_do_nullmove(const Position& pos);
286 bool ok_to_prune(const Position& pos, Move m, Move threat);
287 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
288 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
289 void update_killers(Move m, SearchStack& ss);
291 bool fail_high_ply_1();
292 int current_search_time();
296 void print_current_line(SearchStack ss[], int ply, int threadID);
297 void wait_for_stop_or_ponderhit();
298 void init_ss_array(SearchStack ss[]);
300 void idle_loop(int threadID, SplitPoint* waitSp);
301 void init_split_point_stack();
302 void destroy_split_point_stack();
303 bool thread_should_stop(int threadID);
304 bool thread_is_available(int slave, int master);
305 bool idle_thread_exists(int master);
306 bool split(const Position& pos, SearchStack* ss, int ply,
307 Value *alpha, Value *beta, Value *bestValue,
308 const Value futilityValue, Depth depth, int *moves,
309 MovePicker *mp, int master, bool pvNode);
310 void wake_sleeping_threads();
312 #if !defined(_MSC_VER)
313 void *init_thread(void *threadID);
315 DWORD WINAPI init_thread(LPVOID threadID);
326 /// perft() is our utility to verify move generation is bug free. All the legal
327 /// moves up to given depth are generated and counted and the sum returned.
329 int perft(Position& pos, Depth depth)
333 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
335 // If we are at the last ply we don't need to do and undo
336 // the moves, just to count them.
337 if (depth <= OnePly) // Replace with '<' to test also qsearch
339 while (mp.get_next_move()) sum++;
343 // Loop through all legal moves
345 while ((move = mp.get_next_move()) != MOVE_NONE)
348 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
349 sum += perft(pos, depth - OnePly);
356 /// think() is the external interface to Stockfish's search, and is called when
357 /// the program receives the UCI 'go' command. It initializes various
358 /// search-related global variables, and calls root_search(). It returns false
359 /// when a quit command is received during the search.
361 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
362 int time[], int increment[], int movesToGo, int maxDepth,
363 int maxNodes, int maxTime, Move searchMoves[]) {
365 // Look for a book move
366 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
369 if (get_option_value_string("Book File") != OpeningBook.file_name())
370 OpeningBook.open(get_option_value_string("Book File"));
372 bookMove = OpeningBook.get_move(pos);
373 if (bookMove != MOVE_NONE)
375 cout << "bestmove " << bookMove << endl;
380 // Initialize global search variables
381 Idle = StopOnPonderhit = AbortSearch = Quit = false;
382 FailHigh = FailLow = Problem = false;
383 SearchStartTime = get_system_time();
384 ExactMaxTime = maxTime;
386 InfiniteSearch = infinite;
387 PonderSearch = ponder;
389 for (int i = 0; i < THREAD_MAX; i++)
391 Threads[i].nodes = 0ULL;
392 Threads[i].failHighPly1 = false;
395 if (button_was_pressed("New Game"))
396 loseOnTime = false; // Reset at the beginning of a new game
398 // Read UCI option values
399 TT.set_size(get_option_value_int("Hash"));
400 if (button_was_pressed("Clear Hash"))
403 bool PonderingEnabled = get_option_value_bool("Ponder");
404 MultiPV = get_option_value_int("MultiPV");
406 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
407 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
409 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
410 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
412 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
413 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
415 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
416 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
418 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
419 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
421 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
422 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
424 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
425 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
426 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
428 Chess960 = get_option_value_bool("UCI_Chess960");
429 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
430 UseLogFile = get_option_value_bool("Use Search Log");
432 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
434 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
435 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
437 read_weights(pos.side_to_move());
439 // Set the number of active threads
440 int newActiveThreads = get_option_value_int("Threads");
441 if (newActiveThreads != ActiveThreads)
443 ActiveThreads = newActiveThreads;
444 init_eval(ActiveThreads);
447 // Wake up sleeping threads
448 wake_sleeping_threads();
450 for (int i = 1; i < ActiveThreads; i++)
451 assert(thread_is_available(i, 0));
454 int myTime = time[side_to_move];
455 int myIncrement = increment[side_to_move];
457 if (!movesToGo) // Sudden death time control
461 MaxSearchTime = myTime / 30 + myIncrement;
462 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
464 else // Blitz game without increment
466 MaxSearchTime = myTime / 30;
467 AbsoluteMaxSearchTime = myTime / 8;
470 else // (x moves) / (y minutes)
474 MaxSearchTime = myTime / 2;
475 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
479 MaxSearchTime = myTime / Min(movesToGo, 20);
480 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
484 if (PonderingEnabled)
486 MaxSearchTime += MaxSearchTime / 4;
487 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
490 // Fixed depth or fixed number of nodes?
493 InfiniteSearch = true; // HACK
498 NodesBetweenPolls = Min(MaxNodes, 30000);
499 InfiniteSearch = true; // HACK
501 else if (myTime && myTime < 1000)
502 NodesBetweenPolls = 1000;
503 else if (myTime && myTime < 5000)
504 NodesBetweenPolls = 5000;
506 NodesBetweenPolls = 30000;
508 // Write information to search log file
510 LogFile << "Searching: " << pos.to_fen() << endl
511 << "infinite: " << infinite
512 << " ponder: " << ponder
513 << " time: " << myTime
514 << " increment: " << myIncrement
515 << " moves to go: " << movesToGo << endl;
517 // LSN filtering. Used only for developing purpose. Disabled by default.
521 // Step 2. If after last move we decided to lose on time, do it now!
522 while (SearchStartTime + myTime + 1000 > get_system_time())
526 // We're ready to start thinking. Call the iterative deepening loop function
527 Value v = id_loop(pos, searchMoves);
532 // Step 1. If this is sudden death game and our position is hopeless,
533 // decide to lose on time.
534 if ( !loseOnTime // If we already lost on time, go to step 3.
544 // Step 3. Now after stepping over the time limit, reset flag for next match.
557 /// init_threads() is called during startup. It launches all helper threads,
558 /// and initializes the split point stack and the global locks and condition
561 void init_threads() {
565 #if !defined(_MSC_VER)
566 pthread_t pthread[1];
569 for (i = 0; i < THREAD_MAX; i++)
570 Threads[i].activeSplitPoints = 0;
572 // Initialize global locks
573 lock_init(&MPLock, NULL);
574 lock_init(&IOLock, NULL);
576 init_split_point_stack();
578 #if !defined(_MSC_VER)
579 pthread_mutex_init(&WaitLock, NULL);
580 pthread_cond_init(&WaitCond, NULL);
582 for (i = 0; i < THREAD_MAX; i++)
583 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
586 // All threads except the main thread should be initialized to idle state
587 for (i = 1; i < THREAD_MAX; i++)
589 Threads[i].stop = false;
590 Threads[i].workIsWaiting = false;
591 Threads[i].idle = true;
592 Threads[i].running = false;
595 // Launch the helper threads
596 for(i = 1; i < THREAD_MAX; i++)
598 #if !defined(_MSC_VER)
599 pthread_create(pthread, NULL, init_thread, (void*)(&i));
602 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
605 // Wait until the thread has finished launching
606 while (!Threads[i].running);
611 /// stop_threads() is called when the program exits. It makes all the
612 /// helper threads exit cleanly.
614 void stop_threads() {
616 ActiveThreads = THREAD_MAX; // HACK
617 Idle = false; // HACK
618 wake_sleeping_threads();
619 AllThreadsShouldExit = true;
620 for (int i = 1; i < THREAD_MAX; i++)
622 Threads[i].stop = true;
623 while(Threads[i].running);
625 destroy_split_point_stack();
629 /// nodes_searched() returns the total number of nodes searched so far in
630 /// the current search.
632 int64_t nodes_searched() {
634 int64_t result = 0ULL;
635 for (int i = 0; i < ActiveThreads; i++)
636 result += Threads[i].nodes;
641 // SearchStack::init() initializes a search stack. Used at the beginning of a
642 // new search from the root.
643 void SearchStack::init(int ply) {
645 pv[ply] = pv[ply + 1] = MOVE_NONE;
646 currentMove = threatMove = MOVE_NONE;
647 reduction = Depth(0);
650 void SearchStack::initKillers() {
652 mateKiller = MOVE_NONE;
653 for (int i = 0; i < KILLER_MAX; i++)
654 killers[i] = MOVE_NONE;
659 // id_loop() is the main iterative deepening loop. It calls root_search
660 // repeatedly with increasing depth until the allocated thinking time has
661 // been consumed, the user stops the search, or the maximum search depth is
664 Value id_loop(const Position& pos, Move searchMoves[]) {
667 SearchStack ss[PLY_MAX_PLUS_2];
669 // searchMoves are verified, copied, scored and sorted
670 RootMoveList rml(p, searchMoves);
672 if (rml.move_count() == 0)
675 wait_for_stop_or_ponderhit();
677 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
680 // Print RootMoveList c'tor startup scoring to the standard output,
681 // so that we print information also for iteration 1.
682 cout << "info depth " << 1 << "\ninfo depth " << 1
683 << " score " << value_to_string(rml.get_move_score(0))
684 << " time " << current_search_time()
685 << " nodes " << nodes_searched()
687 << " pv " << rml.get_move(0) << "\n";
693 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
696 // Is one move significantly better than others after initial scoring ?
697 Move EasyMove = MOVE_NONE;
698 if ( rml.move_count() == 1
699 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
700 EasyMove = rml.get_move(0);
702 // Iterative deepening loop
703 while (Iteration < PLY_MAX)
705 // Initialize iteration
708 BestMoveChangesByIteration[Iteration] = 0;
712 cout << "info depth " << Iteration << endl;
714 // Calculate dynamic search window based on previous iterations
717 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
719 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
720 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
722 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
724 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
725 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
729 alpha = - VALUE_INFINITE;
730 beta = VALUE_INFINITE;
733 // Search to the current depth
734 Value value = root_search(p, ss, rml, alpha, beta);
736 // Write PV to transposition table, in case the relevant entries have
737 // been overwritten during the search.
738 TT.insert_pv(p, ss[0].pv);
741 break; // Value cannot be trusted. Break out immediately!
743 //Save info about search result
744 Value speculatedValue;
747 Value delta = value - IterationInfo[Iteration - 1].value;
754 speculatedValue = value + delta;
755 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
757 else if (value <= alpha)
759 assert(value == alpha);
763 speculatedValue = value + delta;
764 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
766 speculatedValue = value;
768 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
769 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
771 // Drop the easy move if it differs from the new best move
772 if (ss[0].pv[0] != EasyMove)
773 EasyMove = MOVE_NONE;
780 bool stopSearch = false;
782 // Stop search early if there is only a single legal move,
783 // we search up to Iteration 6 anyway to get a proper score.
784 if (Iteration >= 6 && rml.move_count() == 1)
787 // Stop search early when the last two iterations returned a mate score
789 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
790 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
793 // Stop search early if one move seems to be much better than the rest
794 int64_t nodes = nodes_searched();
798 && EasyMove == ss[0].pv[0]
799 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
800 && current_search_time() > MaxSearchTime / 16)
801 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
802 && current_search_time() > MaxSearchTime / 32)))
805 // Add some extra time if the best move has changed during the last two iterations
806 if (Iteration > 5 && Iteration <= 50)
807 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
808 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
810 // Stop search if most of MaxSearchTime is consumed at the end of the
811 // iteration. We probably don't have enough time to search the first
812 // move at the next iteration anyway.
813 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
821 StopOnPonderhit = true;
825 if (MaxDepth && Iteration >= MaxDepth)
831 // If we are pondering, we shouldn't print the best move before we
834 wait_for_stop_or_ponderhit();
836 // Print final search statistics
837 cout << "info nodes " << nodes_searched()
839 << " time " << current_search_time()
840 << " hashfull " << TT.full() << endl;
842 // Print the best move and the ponder move to the standard output
843 if (ss[0].pv[0] == MOVE_NONE)
845 ss[0].pv[0] = rml.get_move(0);
846 ss[0].pv[1] = MOVE_NONE;
848 cout << "bestmove " << ss[0].pv[0];
849 if (ss[0].pv[1] != MOVE_NONE)
850 cout << " ponder " << ss[0].pv[1];
857 dbg_print_mean(LogFile);
859 if (dbg_show_hit_rate)
860 dbg_print_hit_rate(LogFile);
862 LogFile << "\nNodes: " << nodes_searched()
863 << "\nNodes/second: " << nps()
864 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
867 p.do_move(ss[0].pv[0], st);
868 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
870 return rml.get_move_score(0);
874 // root_search() is the function which searches the root node. It is
875 // similar to search_pv except that it uses a different move ordering
876 // scheme and prints some information to the standard output.
878 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta) {
880 Value oldAlpha = alpha;
884 // Loop through all the moves in the root move list
885 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
889 // We failed high, invalidate and skip next moves, leave node-counters
890 // and beta-counters as they are and quickly return, we will try to do
891 // a research at the next iteration with a bigger aspiration window.
892 rml.set_move_score(i, -VALUE_INFINITE);
900 RootMoveNumber = i + 1;
903 // Save the current node count before the move is searched
904 nodes = nodes_searched();
906 // Reset beta cut-off counters
909 // Pick the next root move, and print the move and the move number to
910 // the standard output.
911 move = ss[0].currentMove = rml.get_move(i);
913 if (current_search_time() >= 1000)
914 cout << "info currmove " << move
915 << " currmovenumber " << RootMoveNumber << endl;
917 // Decide search depth for this move
918 bool moveIsCheck = pos.move_is_check(move);
919 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
921 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
922 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
924 // Make the move, and search it
925 pos.do_move(move, st, ci, moveIsCheck);
929 // Aspiration window is disabled in multi-pv case
931 alpha = -VALUE_INFINITE;
933 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
935 // If the value has dropped a lot compared to the last iteration,
936 // set the boolean variable Problem to true. This variable is used
937 // for time managment: When Problem is true, we try to complete the
938 // current iteration before playing a move.
939 Problem = ( Iteration >= 2
940 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
942 if (Problem && StopOnPonderhit)
943 StopOnPonderhit = false;
947 // Try to reduce non-pv search depth by one ply if move seems not problematic,
948 // if the move fails high will be re-searched at full depth.
949 if ( newDepth >= 3*OnePly
950 && i >= MultiPV + LMRPVMoves
952 && !captureOrPromotion
953 && !move_is_castle(move))
955 ss[0].reduction = OnePly;
956 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
958 value = alpha + 1; // Just to trigger next condition
962 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
966 // Fail high! Set the boolean variable FailHigh to true, and
967 // re-search the move using a PV search. The variable FailHigh
968 // is used for time managment: We try to avoid aborting the
969 // search prematurely during a fail high research.
971 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
978 // Finished searching the move. If AbortSearch is true, the search
979 // was aborted because the user interrupted the search or because we
980 // ran out of time. In this case, the return value of the search cannot
981 // be trusted, and we break out of the loop without updating the best
986 // Remember beta-cutoff and searched nodes counts for this move. The
987 // info is used to sort the root moves at the next iteration.
989 BetaCounter.read(pos.side_to_move(), our, their);
990 rml.set_beta_counters(i, our, their);
991 rml.set_move_nodes(i, nodes_searched() - nodes);
993 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
995 if (value <= alpha && i >= MultiPV)
996 rml.set_move_score(i, -VALUE_INFINITE);
999 // PV move or new best move!
1002 rml.set_move_score(i, value);
1004 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1005 rml.set_move_pv(i, ss[0].pv);
1009 // We record how often the best move has been changed in each
1010 // iteration. This information is used for time managment: When
1011 // the best move changes frequently, we allocate some more time.
1013 BestMoveChangesByIteration[Iteration]++;
1015 // Print search information to the standard output
1016 cout << "info depth " << Iteration
1017 << " score " << value_to_string(value)
1018 << ((value >= beta) ? " lowerbound" :
1019 ((value <= alpha)? " upperbound" : ""))
1020 << " time " << current_search_time()
1021 << " nodes " << nodes_searched()
1025 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1026 cout << ss[0].pv[j] << " ";
1032 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1033 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1035 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1036 nodes_searched(), value, type, ss[0].pv) << endl;
1041 // Reset the global variable Problem to false if the value isn't too
1042 // far below the final value from the last iteration.
1043 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1048 rml.sort_multipv(i);
1049 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1051 cout << "info multipv " << j + 1
1052 << " score " << value_to_string(rml.get_move_score(j))
1053 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1054 << " time " << current_search_time()
1055 << " nodes " << nodes_searched()
1059 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1060 cout << rml.get_move_pv(j, k) << " ";
1064 alpha = rml.get_move_score(Min(i, MultiPV-1));
1066 } // PV move or new best move
1068 assert(alpha >= oldAlpha);
1070 FailLow = (alpha == oldAlpha);
1076 // search_pv() is the main search function for PV nodes.
1078 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1079 Depth depth, int ply, int threadID) {
1081 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1082 assert(beta > alpha && beta <= VALUE_INFINITE);
1083 assert(ply >= 0 && ply < PLY_MAX);
1084 assert(threadID >= 0 && threadID < ActiveThreads);
1086 Move movesSearched[256];
1091 Depth ext, newDepth;
1092 Value oldAlpha, value;
1093 bool isCheck, mateThreat, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1095 Value bestValue = -VALUE_INFINITE;
1098 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1100 // Initialize, and make an early exit in case of an aborted search,
1101 // an instant draw, maximum ply reached, etc.
1102 init_node(ss, ply, threadID);
1104 // After init_node() that calls poll()
1105 if (AbortSearch || thread_should_stop(threadID))
1111 if (ply >= PLY_MAX - 1)
1112 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1114 // Mate distance pruning
1116 alpha = Max(value_mated_in(ply), alpha);
1117 beta = Min(value_mate_in(ply+1), beta);
1121 // Transposition table lookup. At PV nodes, we don't use the TT for
1122 // pruning, but only for move ordering. This is to avoid problems in
1123 // the following areas:
1125 // * Repetition draw detection
1126 // * Fifty move rule detection
1127 // * Searching for a mate
1128 // * Printing of full PV line
1130 tte = TT.retrieve(pos.get_key());
1131 ttMove = (tte ? tte->move() : MOVE_NONE);
1133 // Go with internal iterative deepening if we don't have a TT move
1134 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1136 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1137 ttMove = ss[ply].pv[ply];
1138 tte = TT.retrieve(pos.get_key());
1141 // Initialize a MovePicker object for the current position, and prepare
1142 // to search all moves
1143 isCheck = pos.is_check();
1144 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1146 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1148 // Loop through all legal moves until no moves remain or a beta cutoff
1150 while ( alpha < beta
1151 && (move = mp.get_next_move()) != MOVE_NONE
1152 && !thread_should_stop(threadID))
1154 assert(move_is_ok(move));
1156 singleReply = (isCheck && mp.number_of_evasions() == 1);
1157 moveIsCheck = pos.move_is_check(move, ci);
1158 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1160 // Decide the new search depth
1161 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1163 // Singular extension search. We extend the TT move if its value is much better than
1164 // its siblings. To verify this we do a reduced search on all the other moves but the
1165 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1166 if ( depth >= 6 * OnePly
1168 && move == tte->move()
1170 && is_lower_bound(tte->type())
1171 && tte->depth() >= depth - 3 * OnePly)
1173 Value ttValue = value_from_tt(tte->value(), ply);
1175 if (abs(ttValue) < VALUE_KNOWN_WIN)
1177 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1179 if (excValue < ttValue - SingleReplyMargin)
1184 newDepth = depth - OnePly + ext;
1186 // Update current move
1187 movesSearched[moveCount++] = ss[ply].currentMove = move;
1189 // Make and search the move
1190 pos.do_move(move, st, ci, moveIsCheck);
1192 if (moveCount == 1) // The first move in list is the PV
1193 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1196 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1197 // if the move fails high will be re-searched at full depth.
1198 if ( depth >= 3*OnePly
1199 && moveCount >= LMRPVMoves
1201 && !captureOrPromotion
1202 && !move_is_castle(move)
1203 && !move_is_killer(move, ss[ply]))
1205 ss[ply].reduction = OnePly;
1206 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1209 value = alpha + 1; // Just to trigger next condition
1211 if (value > alpha) // Go with full depth non-pv search
1213 ss[ply].reduction = Depth(0);
1214 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1215 if (value > alpha && value < beta)
1217 // When the search fails high at ply 1 while searching the first
1218 // move at the root, set the flag failHighPly1. This is used for
1219 // time managment: We don't want to stop the search early in
1220 // such cases, because resolving the fail high at ply 1 could
1221 // result in a big drop in score at the root.
1222 if (ply == 1 && RootMoveNumber == 1)
1223 Threads[threadID].failHighPly1 = true;
1225 // A fail high occurred. Re-search at full window (pv search)
1226 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1227 Threads[threadID].failHighPly1 = false;
1231 pos.undo_move(move);
1233 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1236 if (value > bestValue)
1243 if (value == value_mate_in(ply + 1))
1244 ss[ply].mateKiller = move;
1246 // If we are at ply 1, and we are searching the first root move at
1247 // ply 0, set the 'Problem' variable if the score has dropped a lot
1248 // (from the computer's point of view) since the previous iteration.
1251 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1256 if ( ActiveThreads > 1
1258 && depth >= MinimumSplitDepth
1260 && idle_thread_exists(threadID)
1262 && !thread_should_stop(threadID)
1263 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1264 depth, &moveCount, &mp, threadID, true))
1268 // All legal moves have been searched. A special case: If there were
1269 // no legal moves, it must be mate or stalemate.
1271 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1273 // If the search is not aborted, update the transposition table,
1274 // history counters, and killer moves.
1275 if (AbortSearch || thread_should_stop(threadID))
1278 if (bestValue <= oldAlpha)
1279 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1281 else if (bestValue >= beta)
1283 BetaCounter.add(pos.side_to_move(), depth, threadID);
1284 move = ss[ply].pv[ply];
1285 if (!pos.move_is_capture_or_promotion(move))
1287 update_history(pos, move, depth, movesSearched, moveCount);
1288 update_killers(move, ss[ply]);
1290 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1293 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1299 // search() is the search function for zero-width nodes.
1301 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1302 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1304 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1305 assert(ply >= 0 && ply < PLY_MAX);
1306 assert(threadID >= 0 && threadID < ActiveThreads);
1308 Move movesSearched[256];
1313 Depth ext, newDepth;
1314 Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1315 bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1316 bool mateThreat = false;
1318 Value bestValue = -VALUE_INFINITE;
1321 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1323 // Initialize, and make an early exit in case of an aborted search,
1324 // an instant draw, maximum ply reached, etc.
1325 init_node(ss, ply, threadID);
1327 // After init_node() that calls poll()
1328 if (AbortSearch || thread_should_stop(threadID))
1334 if (ply >= PLY_MAX - 1)
1335 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1337 // Mate distance pruning
1338 if (value_mated_in(ply) >= beta)
1341 if (value_mate_in(ply + 1) < beta)
1344 // We don't want the score of a partial search to overwrite a previous full search
1345 // TT value, so we use a different position key in case of an excluded move exsists.
1346 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1348 // Transposition table lookup
1349 tte = TT.retrieve(posKey);
1350 ttMove = (tte ? tte->move() : MOVE_NONE);
1352 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1354 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1355 return value_from_tt(tte->value(), ply);
1358 approximateEval = quick_evaluate(pos);
1359 isCheck = pos.is_check();
1365 && !value_is_mate(beta)
1366 && ok_to_do_nullmove(pos)
1367 && approximateEval >= beta - NullMoveMargin)
1369 ss[ply].currentMove = MOVE_NULL;
1371 pos.do_null_move(st);
1373 // Null move dynamic reduction based on depth
1374 int R = (depth >= 5 * OnePly ? 4 : 3);
1376 // Null move dynamic reduction based on value
1377 if (approximateEval - beta > PawnValueMidgame)
1380 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1382 pos.undo_null_move();
1384 if (nullValue >= beta)
1386 if (depth < 6 * OnePly)
1389 // Do zugzwang verification search
1390 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1394 // The null move failed low, which means that we may be faced with
1395 // some kind of threat. If the previous move was reduced, check if
1396 // the move that refuted the null move was somehow connected to the
1397 // move which was reduced. If a connection is found, return a fail
1398 // low score (which will cause the reduced move to fail high in the
1399 // parent node, which will trigger a re-search with full depth).
1400 if (nullValue == value_mated_in(ply + 2))
1403 ss[ply].threatMove = ss[ply + 1].currentMove;
1404 if ( depth < ThreatDepth
1405 && ss[ply - 1].reduction
1406 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1410 // Null move search not allowed, try razoring
1411 else if ( !value_is_mate(beta)
1412 && depth < RazorDepth
1413 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1414 && ss[ply - 1].currentMove != MOVE_NULL
1415 && ttMove == MOVE_NONE
1416 && !pos.has_pawn_on_7th(pos.side_to_move()))
1418 Value rbeta = beta - RazorMargins[int(depth) - 2];
1419 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1424 // Go with internal iterative deepening if we don't have a TT move
1425 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1426 !isCheck && evaluate(pos, ei, threadID) >= beta - IIDMargin)
1428 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1429 ttMove = ss[ply].pv[ply];
1430 tte = TT.retrieve(pos.get_key());
1433 // Initialize a MovePicker object for the current position, and prepare
1434 // to search all moves.
1435 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1437 futilityValue = VALUE_NONE;
1438 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1440 // Calculate depth dependant futility pruning parameters
1441 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1442 const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1444 // Avoid calling evaluate() if we already have the score in TT
1445 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1446 futilityValue = value_from_tt(tte->value(), ply) + FutilityValueMargin;
1448 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1449 while ( bestValue < beta
1450 && (move = mp.get_next_move()) != MOVE_NONE
1451 && !thread_should_stop(threadID))
1453 assert(move_is_ok(move));
1455 if (move == excludedMove)
1458 singleReply = (isCheck && mp.number_of_evasions() == 1);
1459 moveIsCheck = pos.move_is_check(move, ci);
1460 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1462 // Decide the new search depth
1463 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1465 // Singular extension search. We extend the TT move if its value is much better than
1466 // its siblings. To verify this we do a reduced search on all the other moves but the
1467 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1468 if ( depth >= 8 * OnePly
1470 && move == tte->move()
1471 && !excludedMove // Do not allow recursive single-reply search
1473 && is_lower_bound(tte->type())
1474 && tte->depth() >= depth - 3 * OnePly)
1476 Value ttValue = value_from_tt(tte->value(), ply);
1478 if (abs(ttValue) < VALUE_KNOWN_WIN)
1480 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1482 if (excValue < ttValue - SingleReplyMargin)
1487 newDepth = depth - OnePly + ext;
1489 // Update current move
1490 movesSearched[moveCount++] = ss[ply].currentMove = move;
1493 if ( useFutilityPruning
1495 && !captureOrPromotion
1498 // Move count based pruning
1499 if ( moveCount >= FutilityMoveCountMargin
1500 && ok_to_prune(pos, move, ss[ply].threatMove)
1501 && bestValue > value_mated_in(PLY_MAX))
1504 // Value based pruning
1505 if (futilityValue == VALUE_NONE)
1506 futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1508 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1510 if (futilityValueScaled < beta)
1512 if (futilityValueScaled > bestValue)
1513 bestValue = futilityValueScaled;
1518 // Make and search the move
1519 pos.do_move(move, st, ci, moveIsCheck);
1521 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1522 // if the move fails high will be re-searched at full depth.
1523 if ( depth >= 3*OnePly
1524 && moveCount >= LMRNonPVMoves
1526 && !captureOrPromotion
1527 && !move_is_castle(move)
1528 && !move_is_killer(move, ss[ply]))
1530 ss[ply].reduction = OnePly;
1531 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1534 value = beta; // Just to trigger next condition
1536 if (value >= beta) // Go with full depth non-pv search
1538 ss[ply].reduction = Depth(0);
1539 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1541 pos.undo_move(move);
1543 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1546 if (value > bestValue)
1552 if (value == value_mate_in(ply + 1))
1553 ss[ply].mateKiller = move;
1557 if ( ActiveThreads > 1
1559 && depth >= MinimumSplitDepth
1561 && idle_thread_exists(threadID)
1563 && !thread_should_stop(threadID)
1564 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue,
1565 depth, &moveCount, &mp, threadID, false))
1569 // All legal moves have been searched. A special case: If there were
1570 // no legal moves, it must be mate or stalemate.
1572 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1574 // If the search is not aborted, update the transposition table,
1575 // history counters, and killer moves.
1576 if (AbortSearch || thread_should_stop(threadID))
1579 if (bestValue < beta)
1580 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1583 BetaCounter.add(pos.side_to_move(), depth, threadID);
1584 move = ss[ply].pv[ply];
1585 if (!pos.move_is_capture_or_promotion(move))
1587 update_history(pos, move, depth, movesSearched, moveCount);
1588 update_killers(move, ss[ply]);
1590 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1593 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1599 // qsearch() is the quiescence search function, which is called by the main
1600 // search function when the remaining depth is zero (or, to be more precise,
1601 // less than OnePly).
1603 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1604 Depth depth, int ply, int threadID) {
1606 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1607 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1609 assert(ply >= 0 && ply < PLY_MAX);
1610 assert(threadID >= 0 && threadID < ActiveThreads);
1615 Value staticValue, bestValue, value, futilityValue;
1616 bool isCheck, enoughMaterial, moveIsCheck;
1617 const TTEntry* tte = NULL;
1619 bool pvNode = (beta - alpha != 1);
1621 // Initialize, and make an early exit in case of an aborted search,
1622 // an instant draw, maximum ply reached, etc.
1623 init_node(ss, ply, threadID);
1625 // After init_node() that calls poll()
1626 if (AbortSearch || thread_should_stop(threadID))
1632 // Transposition table lookup, only when not in PV
1635 tte = TT.retrieve(pos.get_key());
1636 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1638 assert(tte->type() != VALUE_TYPE_EVAL);
1640 return value_from_tt(tte->value(), ply);
1643 ttMove = (tte ? tte->move() : MOVE_NONE);
1645 isCheck = pos.is_check();
1646 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1648 // Evaluate the position statically
1650 staticValue = -VALUE_INFINITE;
1652 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1654 // Use the cached evaluation score if possible
1655 assert(ei.futilityMargin == Value(0));
1657 staticValue = value_from_tt(tte->value(), ply);
1660 staticValue = evaluate(pos, ei, threadID);
1662 if (ply >= PLY_MAX - 1)
1663 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1665 // Initialize "stand pat score", and return it immediately if it is
1667 bestValue = staticValue;
1669 if (bestValue >= beta)
1671 // Store the score to avoid a future costly evaluation() call
1672 if (!isCheck && !tte && ei.futilityMargin == 0)
1673 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1678 if (bestValue > alpha)
1681 // Initialize a MovePicker object for the current position, and prepare
1682 // to search the moves. Because the depth is <= 0 here, only captures,
1683 // queen promotions and checks (only if depth == 0) will be generated.
1684 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1686 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1688 // Loop through the moves until no moves remain or a beta cutoff
1690 while ( alpha < beta
1691 && (move = mp.get_next_move()) != MOVE_NONE)
1693 assert(move_is_ok(move));
1696 ss[ply].currentMove = move;
1698 moveIsCheck = pos.move_is_check(move, ci);
1706 && !move_is_promotion(move)
1707 && !pos.move_is_passed_pawn_push(move))
1709 futilityValue = staticValue
1710 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1711 pos.endgame_value_of_piece_on(move_to(move)))
1712 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1714 + ei.futilityMargin;
1716 if (futilityValue < alpha)
1718 if (futilityValue > bestValue)
1719 bestValue = futilityValue;
1724 // Don't search captures and checks with negative SEE values
1727 && !move_is_promotion(move)
1728 && pos.see_sign(move) < 0)
1731 // Make and search the move
1732 pos.do_move(move, st, ci, moveIsCheck);
1733 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1734 pos.undo_move(move);
1736 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1739 if (value > bestValue)
1750 // All legal moves have been searched. A special case: If we're in check
1751 // and no legal moves were found, it is checkmate.
1752 if (!moveCount && pos.is_check()) // Mate!
1753 return value_mated_in(ply);
1755 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1757 // Update transposition table
1758 move = ss[ply].pv[ply];
1761 // If bestValue isn't changed it means it is still the static evaluation of
1762 // the node, so keep this info to avoid a future costly evaluation() call.
1763 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1764 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1766 if (bestValue < beta)
1767 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1769 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1772 // Update killers only for good check moves
1773 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1774 update_killers(move, ss[ply]);
1780 // sp_search() is used to search from a split point. This function is called
1781 // by each thread working at the split point. It is similar to the normal
1782 // search() function, but simpler. Because we have already probed the hash
1783 // table, done a null move search, and searched the first move before
1784 // splitting, we don't have to repeat all this work in sp_search(). We
1785 // also don't need to store anything to the hash table here: This is taken
1786 // care of after we return from the split point.
1788 void sp_search(SplitPoint* sp, int threadID) {
1790 assert(threadID >= 0 && threadID < ActiveThreads);
1791 assert(ActiveThreads > 1);
1793 Position pos = Position(sp->pos);
1795 SearchStack* ss = sp->sstack[threadID];
1798 bool isCheck = pos.is_check();
1799 bool useFutilityPruning = sp->depth < SelectiveDepth
1802 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1803 const int FutilityValueMargin = 112 * bitScanReverse32(int(sp->depth) * int(sp->depth) / 2);
1805 while ( sp->bestValue < sp->beta
1806 && !thread_should_stop(threadID)
1807 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1809 assert(move_is_ok(move));
1811 bool moveIsCheck = pos.move_is_check(move, ci);
1812 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1814 lock_grab(&(sp->lock));
1815 int moveCount = ++sp->moves;
1816 lock_release(&(sp->lock));
1818 ss[sp->ply].currentMove = move;
1820 // Decide the new search depth.
1822 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1823 Depth newDepth = sp->depth - OnePly + ext;
1826 if ( useFutilityPruning
1828 && !captureOrPromotion)
1830 // Move count based pruning
1831 if ( moveCount >= FutilityMoveCountMargin
1832 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1833 && sp->bestValue > value_mated_in(PLY_MAX))
1836 // Value based pruning
1837 if (sp->futilityValue == VALUE_NONE)
1840 sp->futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1843 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1845 if (futilityValueScaled < sp->beta)
1847 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1849 lock_grab(&(sp->lock));
1850 if (futilityValueScaled > sp->bestValue)
1851 sp->bestValue = futilityValueScaled;
1852 lock_release(&(sp->lock));
1858 // Make and search the move.
1860 pos.do_move(move, st, ci, moveIsCheck);
1862 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1863 // if the move fails high will be re-searched at full depth.
1865 && moveCount >= LMRNonPVMoves
1866 && !captureOrPromotion
1867 && !move_is_castle(move)
1868 && !move_is_killer(move, ss[sp->ply]))
1870 ss[sp->ply].reduction = OnePly;
1871 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1874 value = sp->beta; // Just to trigger next condition
1876 if (value >= sp->beta) // Go with full depth non-pv search
1878 ss[sp->ply].reduction = Depth(0);
1879 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1881 pos.undo_move(move);
1883 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1885 if (thread_should_stop(threadID))
1889 if (value > sp->bestValue) // Less then 2% of cases
1891 lock_grab(&(sp->lock));
1892 if (value > sp->bestValue && !thread_should_stop(threadID))
1894 sp->bestValue = value;
1895 if (sp->bestValue >= sp->beta)
1897 sp_update_pv(sp->parentSstack, ss, sp->ply);
1898 for (int i = 0; i < ActiveThreads; i++)
1899 if (i != threadID && (i == sp->master || sp->slaves[i]))
1900 Threads[i].stop = true;
1902 sp->finished = true;
1905 lock_release(&(sp->lock));
1909 lock_grab(&(sp->lock));
1911 // If this is the master thread and we have been asked to stop because of
1912 // a beta cutoff higher up in the tree, stop all slave threads.
1913 if (sp->master == threadID && thread_should_stop(threadID))
1914 for (int i = 0; i < ActiveThreads; i++)
1916 Threads[i].stop = true;
1919 sp->slaves[threadID] = 0;
1921 lock_release(&(sp->lock));
1925 // sp_search_pv() is used to search from a PV split point. This function
1926 // is called by each thread working at the split point. It is similar to
1927 // the normal search_pv() function, but simpler. Because we have already
1928 // probed the hash table and searched the first move before splitting, we
1929 // don't have to repeat all this work in sp_search_pv(). We also don't
1930 // need to store anything to the hash table here: This is taken care of
1931 // after we return from the split point.
1933 void sp_search_pv(SplitPoint* sp, int threadID) {
1935 assert(threadID >= 0 && threadID < ActiveThreads);
1936 assert(ActiveThreads > 1);
1938 Position pos = Position(sp->pos);
1940 SearchStack* ss = sp->sstack[threadID];
1944 while ( sp->alpha < sp->beta
1945 && !thread_should_stop(threadID)
1946 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1948 bool moveIsCheck = pos.move_is_check(move, ci);
1949 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1951 assert(move_is_ok(move));
1953 lock_grab(&(sp->lock));
1954 int moveCount = ++sp->moves;
1955 lock_release(&(sp->lock));
1957 ss[sp->ply].currentMove = move;
1959 // Decide the new search depth.
1961 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1962 Depth newDepth = sp->depth - OnePly + ext;
1964 // Make and search the move.
1966 pos.do_move(move, st, ci, moveIsCheck);
1968 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1969 // if the move fails high will be re-searched at full depth.
1971 && moveCount >= LMRPVMoves
1972 && !captureOrPromotion
1973 && !move_is_castle(move)
1974 && !move_is_killer(move, ss[sp->ply]))
1976 ss[sp->ply].reduction = OnePly;
1977 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1980 value = sp->alpha + 1; // Just to trigger next condition
1982 if (value > sp->alpha) // Go with full depth non-pv search
1984 ss[sp->ply].reduction = Depth(0);
1985 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1987 if (value > sp->alpha && value < sp->beta)
1989 // When the search fails high at ply 1 while searching the first
1990 // move at the root, set the flag failHighPly1. This is used for
1991 // time managment: We don't want to stop the search early in
1992 // such cases, because resolving the fail high at ply 1 could
1993 // result in a big drop in score at the root.
1994 if (sp->ply == 1 && RootMoveNumber == 1)
1995 Threads[threadID].failHighPly1 = true;
1997 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1998 Threads[threadID].failHighPly1 = false;
2001 pos.undo_move(move);
2003 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2005 if (thread_should_stop(threadID))
2009 lock_grab(&(sp->lock));
2010 if (value > sp->bestValue && !thread_should_stop(threadID))
2012 sp->bestValue = value;
2013 if (value > sp->alpha)
2016 sp_update_pv(sp->parentSstack, ss, sp->ply);
2017 if (value == value_mate_in(sp->ply + 1))
2018 ss[sp->ply].mateKiller = move;
2020 if (value >= sp->beta)
2022 for (int i = 0; i < ActiveThreads; i++)
2023 if (i != threadID && (i == sp->master || sp->slaves[i]))
2024 Threads[i].stop = true;
2026 sp->finished = true;
2029 // If we are at ply 1, and we are searching the first root move at
2030 // ply 0, set the 'Problem' variable if the score has dropped a lot
2031 // (from the computer's point of view) since the previous iteration.
2034 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2037 lock_release(&(sp->lock));
2040 lock_grab(&(sp->lock));
2042 // If this is the master thread and we have been asked to stop because of
2043 // a beta cutoff higher up in the tree, stop all slave threads.
2044 if (sp->master == threadID && thread_should_stop(threadID))
2045 for (int i = 0; i < ActiveThreads; i++)
2047 Threads[i].stop = true;
2050 sp->slaves[threadID] = 0;
2052 lock_release(&(sp->lock));
2055 /// The BetaCounterType class
2057 BetaCounterType::BetaCounterType() { clear(); }
2059 void BetaCounterType::clear() {
2061 for (int i = 0; i < THREAD_MAX; i++)
2062 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2065 void BetaCounterType::add(Color us, Depth d, int threadID) {
2067 // Weighted count based on depth
2068 Threads[threadID].betaCutOffs[us] += unsigned(d);
2071 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2074 for (int i = 0; i < THREAD_MAX; i++)
2076 our += Threads[i].betaCutOffs[us];
2077 their += Threads[i].betaCutOffs[opposite_color(us)];
2082 /// The RootMove class
2086 RootMove::RootMove() {
2087 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
2090 // RootMove::operator<() is the comparison function used when
2091 // sorting the moves. A move m1 is considered to be better
2092 // than a move m2 if it has a higher score, or if the moves
2093 // have equal score but m1 has the higher node count.
2095 bool RootMove::operator<(const RootMove& m) const {
2097 if (score != m.score)
2098 return (score < m.score);
2100 return theirBeta <= m.theirBeta;
2103 /// The RootMoveList class
2107 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2109 MoveStack mlist[MaxRootMoves];
2110 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2112 // Generate all legal moves
2113 MoveStack* last = generate_moves(pos, mlist);
2115 // Add each move to the moves[] array
2116 for (MoveStack* cur = mlist; cur != last; cur++)
2118 bool includeMove = includeAllMoves;
2120 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2121 includeMove = (searchMoves[k] == cur->move);
2126 // Find a quick score for the move
2128 SearchStack ss[PLY_MAX_PLUS_2];
2131 moves[count].move = cur->move;
2132 pos.do_move(moves[count].move, st);
2133 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2134 pos.undo_move(moves[count].move);
2135 moves[count].pv[0] = moves[count].move;
2136 moves[count].pv[1] = MOVE_NONE;
2143 // Simple accessor methods for the RootMoveList class
2145 inline Move RootMoveList::get_move(int moveNum) const {
2146 return moves[moveNum].move;
2149 inline Value RootMoveList::get_move_score(int moveNum) const {
2150 return moves[moveNum].score;
2153 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2154 moves[moveNum].score = score;
2157 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2158 moves[moveNum].nodes = nodes;
2159 moves[moveNum].cumulativeNodes += nodes;
2162 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2163 moves[moveNum].ourBeta = our;
2164 moves[moveNum].theirBeta = their;
2167 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2169 for(j = 0; pv[j] != MOVE_NONE; j++)
2170 moves[moveNum].pv[j] = pv[j];
2171 moves[moveNum].pv[j] = MOVE_NONE;
2174 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2175 return moves[moveNum].pv[i];
2178 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2179 return moves[moveNum].cumulativeNodes;
2182 inline int RootMoveList::move_count() const {
2187 // RootMoveList::sort() sorts the root move list at the beginning of a new
2190 inline void RootMoveList::sort() {
2192 sort_multipv(count - 1); // all items
2196 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2197 // list by their scores and depths. It is used to order the different PVs
2198 // correctly in MultiPV mode.
2200 void RootMoveList::sort_multipv(int n) {
2202 for (int i = 1; i <= n; i++)
2204 RootMove rm = moves[i];
2206 for (j = i; j > 0 && moves[j-1] < rm; j--)
2207 moves[j] = moves[j-1];
2213 // init_node() is called at the beginning of all the search functions
2214 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2215 // stack object corresponding to the current node. Once every
2216 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2217 // for user input and checks whether it is time to stop the search.
2219 void init_node(SearchStack ss[], int ply, int threadID) {
2221 assert(ply >= 0 && ply < PLY_MAX);
2222 assert(threadID >= 0 && threadID < ActiveThreads);
2224 Threads[threadID].nodes++;
2229 if (NodesSincePoll >= NodesBetweenPolls)
2236 ss[ply+2].initKillers();
2238 if (Threads[threadID].printCurrentLine)
2239 print_current_line(ss, ply, threadID);
2243 // update_pv() is called whenever a search returns a value > alpha. It
2244 // updates the PV in the SearchStack object corresponding to the current
2247 void update_pv(SearchStack ss[], int ply) {
2248 assert(ply >= 0 && ply < PLY_MAX);
2250 ss[ply].pv[ply] = ss[ply].currentMove;
2252 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2253 ss[ply].pv[p] = ss[ply+1].pv[p];
2254 ss[ply].pv[p] = MOVE_NONE;
2258 // sp_update_pv() is a variant of update_pv for use at split points. The
2259 // difference between the two functions is that sp_update_pv also updates
2260 // the PV at the parent node.
2262 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2263 assert(ply >= 0 && ply < PLY_MAX);
2265 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2267 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2268 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2269 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2273 // connected_moves() tests whether two moves are 'connected' in the sense
2274 // that the first move somehow made the second move possible (for instance
2275 // if the moving piece is the same in both moves). The first move is
2276 // assumed to be the move that was made to reach the current position, while
2277 // the second move is assumed to be a move from the current position.
2279 bool connected_moves(const Position& pos, Move m1, Move m2) {
2281 Square f1, t1, f2, t2;
2284 assert(move_is_ok(m1));
2285 assert(move_is_ok(m2));
2287 if (m2 == MOVE_NONE)
2290 // Case 1: The moving piece is the same in both moves
2296 // Case 2: The destination square for m2 was vacated by m1
2302 // Case 3: Moving through the vacated square
2303 if ( piece_is_slider(pos.piece_on(f2))
2304 && bit_is_set(squares_between(f2, t2), f1))
2307 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2308 p = pos.piece_on(t1);
2309 if (bit_is_set(pos.attacks_from(p, t1), t2))
2312 // Case 5: Discovered check, checking piece is the piece moved in m1
2313 if ( piece_is_slider(p)
2314 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2315 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2317 Bitboard occ = pos.occupied_squares();
2318 Color us = pos.side_to_move();
2319 Square ksq = pos.king_square(us);
2320 clear_bit(&occ, f2);
2321 if (type_of_piece(p) == BISHOP)
2323 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2326 else if (type_of_piece(p) == ROOK)
2328 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2333 assert(type_of_piece(p) == QUEEN);
2334 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2342 // value_is_mate() checks if the given value is a mate one
2343 // eventually compensated for the ply.
2345 bool value_is_mate(Value value) {
2347 assert(abs(value) <= VALUE_INFINITE);
2349 return value <= value_mated_in(PLY_MAX)
2350 || value >= value_mate_in(PLY_MAX);
2354 // move_is_killer() checks if the given move is among the
2355 // killer moves of that ply.
2357 bool move_is_killer(Move m, const SearchStack& ss) {
2359 const Move* k = ss.killers;
2360 for (int i = 0; i < KILLER_MAX; i++, k++)
2368 // extension() decides whether a move should be searched with normal depth,
2369 // or with extended depth. Certain classes of moves (checking moves, in
2370 // particular) are searched with bigger depth than ordinary moves and in
2371 // any case are marked as 'dangerous'. Note that also if a move is not
2372 // extended, as example because the corresponding UCI option is set to zero,
2373 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2375 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2376 bool check, bool singleReply, bool mateThreat, bool* dangerous) {
2378 assert(m != MOVE_NONE);
2380 Depth result = Depth(0);
2381 *dangerous = check | singleReply | mateThreat;
2386 result += CheckExtension[pvNode];
2389 result += SingleReplyExtension[pvNode];
2392 result += MateThreatExtension[pvNode];
2395 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2397 Color c = pos.side_to_move();
2398 if (relative_rank(c, move_to(m)) == RANK_7)
2400 result += PawnPushTo7thExtension[pvNode];
2403 if (pos.pawn_is_passed(c, move_to(m)))
2405 result += PassedPawnExtension[pvNode];
2410 if ( captureOrPromotion
2411 && pos.type_of_piece_on(move_to(m)) != PAWN
2412 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2413 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2414 && !move_is_promotion(m)
2417 result += PawnEndgameExtension[pvNode];
2422 && captureOrPromotion
2423 && pos.type_of_piece_on(move_to(m)) != PAWN
2424 && pos.see_sign(m) >= 0)
2430 return Min(result, OnePly);
2434 // ok_to_do_nullmove() looks at the current position and decides whether
2435 // doing a 'null move' should be allowed. In order to avoid zugzwang
2436 // problems, null moves are not allowed when the side to move has very
2437 // little material left. Currently, the test is a bit too simple: Null
2438 // moves are avoided only when the side to move has only pawns left. It's
2439 // probably a good idea to avoid null moves in at least some more
2440 // complicated endgames, e.g. KQ vs KR. FIXME
2442 bool ok_to_do_nullmove(const Position& pos) {
2444 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2448 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2449 // non-tactical moves late in the move list close to the leaves are
2450 // candidates for pruning.
2452 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2454 assert(move_is_ok(m));
2455 assert(threat == MOVE_NONE || move_is_ok(threat));
2456 assert(!pos.move_is_check(m));
2457 assert(!pos.move_is_capture_or_promotion(m));
2458 assert(!pos.move_is_passed_pawn_push(m));
2460 Square mfrom, mto, tfrom, tto;
2462 mfrom = move_from(m);
2464 tfrom = move_from(threat);
2465 tto = move_to(threat);
2467 // Case 1: Castling moves are never pruned
2468 if (move_is_castle(m))
2471 // Case 2: Don't prune moves which move the threatened piece
2472 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2475 // Case 3: If the threatened piece has value less than or equal to the
2476 // value of the threatening piece, don't prune move which defend it.
2477 if ( !PruneDefendingMoves
2478 && threat != MOVE_NONE
2479 && pos.move_is_capture(threat)
2480 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2481 || pos.type_of_piece_on(tfrom) == KING)
2482 && pos.move_attacks_square(m, tto))
2485 // Case 4: If the moving piece in the threatened move is a slider, don't
2486 // prune safe moves which block its ray.
2487 if ( !PruneBlockingMoves
2488 && threat != MOVE_NONE
2489 && piece_is_slider(pos.piece_on(tfrom))
2490 && bit_is_set(squares_between(tfrom, tto), mto)
2491 && pos.see_sign(m) >= 0)
2498 // ok_to_use_TT() returns true if a transposition table score
2499 // can be used at a given point in search.
2501 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2503 Value v = value_from_tt(tte->value(), ply);
2505 return ( tte->depth() >= depth
2506 || v >= Max(value_mate_in(PLY_MAX), beta)
2507 || v < Min(value_mated_in(PLY_MAX), beta))
2509 && ( (is_lower_bound(tte->type()) && v >= beta)
2510 || (is_upper_bound(tte->type()) && v < beta));
2514 // update_history() registers a good move that produced a beta-cutoff
2515 // in history and marks as failures all the other moves of that ply.
2517 void update_history(const Position& pos, Move m, Depth depth,
2518 Move movesSearched[], int moveCount) {
2520 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2522 for (int i = 0; i < moveCount - 1; i++)
2524 assert(m != movesSearched[i]);
2525 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2526 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]), depth);
2531 // update_killers() add a good move that produced a beta-cutoff
2532 // among the killer moves of that ply.
2534 void update_killers(Move m, SearchStack& ss) {
2536 if (m == ss.killers[0])
2539 for (int i = KILLER_MAX - 1; i > 0; i--)
2540 ss.killers[i] = ss.killers[i - 1];
2546 // fail_high_ply_1() checks if some thread is currently resolving a fail
2547 // high at ply 1 at the node below the first root node. This information
2548 // is used for time managment.
2550 bool fail_high_ply_1() {
2552 for(int i = 0; i < ActiveThreads; i++)
2553 if (Threads[i].failHighPly1)
2560 // current_search_time() returns the number of milliseconds which have passed
2561 // since the beginning of the current search.
2563 int current_search_time() {
2564 return get_system_time() - SearchStartTime;
2568 // nps() computes the current nodes/second count.
2571 int t = current_search_time();
2572 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2576 // poll() performs two different functions: It polls for user input, and it
2577 // looks at the time consumed so far and decides if it's time to abort the
2582 static int lastInfoTime;
2583 int t = current_search_time();
2588 // We are line oriented, don't read single chars
2589 std::string command;
2590 if (!std::getline(std::cin, command))
2593 if (command == "quit")
2596 PonderSearch = false;
2600 else if (command == "stop")
2603 PonderSearch = false;
2605 else if (command == "ponderhit")
2608 // Print search information
2612 else if (lastInfoTime > t)
2613 // HACK: Must be a new search where we searched less than
2614 // NodesBetweenPolls nodes during the first second of search.
2617 else if (t - lastInfoTime >= 1000)
2624 if (dbg_show_hit_rate)
2625 dbg_print_hit_rate();
2627 cout << "info nodes " << nodes_searched() << " nps " << nps()
2628 << " time " << t << " hashfull " << TT.full() << endl;
2629 lock_release(&IOLock);
2630 if (ShowCurrentLine)
2631 Threads[0].printCurrentLine = true;
2633 // Should we stop the search?
2637 bool overTime = t > AbsoluteMaxSearchTime
2638 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2639 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2640 && t > 6*(MaxSearchTime + ExtraSearchTime));
2642 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2643 || (ExactMaxTime && t >= ExactMaxTime)
2644 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2649 // ponderhit() is called when the program is pondering (i.e. thinking while
2650 // it's the opponent's turn to move) in order to let the engine know that
2651 // it correctly predicted the opponent's move.
2655 int t = current_search_time();
2656 PonderSearch = false;
2657 if (Iteration >= 3 &&
2658 (!InfiniteSearch && (StopOnPonderhit ||
2659 t > AbsoluteMaxSearchTime ||
2660 (RootMoveNumber == 1 &&
2661 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2662 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2663 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2668 // print_current_line() prints the current line of search for a given
2669 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2671 void print_current_line(SearchStack ss[], int ply, int threadID) {
2673 assert(ply >= 0 && ply < PLY_MAX);
2674 assert(threadID >= 0 && threadID < ActiveThreads);
2676 if (!Threads[threadID].idle)
2679 cout << "info currline " << (threadID + 1);
2680 for (int p = 0; p < ply; p++)
2681 cout << " " << ss[p].currentMove;
2684 lock_release(&IOLock);
2686 Threads[threadID].printCurrentLine = false;
2687 if (threadID + 1 < ActiveThreads)
2688 Threads[threadID + 1].printCurrentLine = true;
2692 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2694 void init_ss_array(SearchStack ss[]) {
2696 for (int i = 0; i < 3; i++)
2699 ss[i].initKillers();
2704 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2705 // while the program is pondering. The point is to work around a wrinkle in
2706 // the UCI protocol: When pondering, the engine is not allowed to give a
2707 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2708 // We simply wait here until one of these commands is sent, and return,
2709 // after which the bestmove and pondermove will be printed (in id_loop()).
2711 void wait_for_stop_or_ponderhit() {
2713 std::string command;
2717 if (!std::getline(std::cin, command))
2720 if (command == "quit")
2725 else if (command == "ponderhit" || command == "stop")
2731 // idle_loop() is where the threads are parked when they have no work to do.
2732 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2733 // object for which the current thread is the master.
2735 void idle_loop(int threadID, SplitPoint* waitSp) {
2736 assert(threadID >= 0 && threadID < THREAD_MAX);
2738 Threads[threadID].running = true;
2741 if(AllThreadsShouldExit && threadID != 0)
2744 // If we are not thinking, wait for a condition to be signaled instead
2745 // of wasting CPU time polling for work:
2746 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2747 #if !defined(_MSC_VER)
2748 pthread_mutex_lock(&WaitLock);
2749 if(Idle || threadID >= ActiveThreads)
2750 pthread_cond_wait(&WaitCond, &WaitLock);
2751 pthread_mutex_unlock(&WaitLock);
2753 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2757 // If this thread has been assigned work, launch a search
2758 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);
2764 Threads[threadID].idle = true;
2767 // If this thread is the master of a split point and all threads have
2768 // finished their work at this split point, return from the idle loop.
2769 if(waitSp != NULL && waitSp->cpus == 0)
2773 Threads[threadID].running = false;
2777 // init_split_point_stack() is called during program initialization, and
2778 // initializes all split point objects.
2780 void init_split_point_stack() {
2781 for(int i = 0; i < THREAD_MAX; i++)
2782 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2783 SplitPointStack[i][j].parent = NULL;
2784 lock_init(&(SplitPointStack[i][j].lock), NULL);
2789 // destroy_split_point_stack() is called when the program exits, and
2790 // destroys all locks in the precomputed split point objects.
2792 void destroy_split_point_stack() {
2793 for(int i = 0; i < THREAD_MAX; i++)
2794 for(int j = 0; j < MaxActiveSplitPoints; j++)
2795 lock_destroy(&(SplitPointStack[i][j].lock));
2799 // thread_should_stop() checks whether the thread with a given threadID has
2800 // been asked to stop, directly or indirectly. This can happen if a beta
2801 // cutoff has occured in thre thread's currently active split point, or in
2802 // some ancestor of the current split point.
2804 bool thread_should_stop(int threadID) {
2805 assert(threadID >= 0 && threadID < ActiveThreads);
2809 if(Threads[threadID].stop)
2811 if(ActiveThreads <= 2)
2813 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2815 Threads[threadID].stop = true;
2822 // thread_is_available() checks whether the thread with threadID "slave" is
2823 // available to help the thread with threadID "master" at a split point. An
2824 // obvious requirement is that "slave" must be idle. With more than two
2825 // threads, this is not by itself sufficient: If "slave" is the master of
2826 // some active split point, it is only available as a slave to the other
2827 // threads which are busy searching the split point at the top of "slave"'s
2828 // split point stack (the "helpful master concept" in YBWC terminology).
2830 bool thread_is_available(int slave, int master) {
2831 assert(slave >= 0 && slave < ActiveThreads);
2832 assert(master >= 0 && master < ActiveThreads);
2833 assert(ActiveThreads > 1);
2835 if(!Threads[slave].idle || slave == master)
2838 if(Threads[slave].activeSplitPoints == 0)
2839 // No active split points means that the thread is available as a slave
2840 // for any other thread.
2843 if(ActiveThreads == 2)
2846 // Apply the "helpful master" concept if possible.
2847 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2854 // idle_thread_exists() tries to find an idle thread which is available as
2855 // a slave for the thread with threadID "master".
2857 bool idle_thread_exists(int master) {
2858 assert(master >= 0 && master < ActiveThreads);
2859 assert(ActiveThreads > 1);
2861 for(int i = 0; i < ActiveThreads; i++)
2862 if(thread_is_available(i, master))
2868 // split() does the actual work of distributing the work at a node between
2869 // several threads at PV nodes. If it does not succeed in splitting the
2870 // node (because no idle threads are available, or because we have no unused
2871 // split point objects), the function immediately returns false. If
2872 // splitting is possible, a SplitPoint object is initialized with all the
2873 // data that must be copied to the helper threads (the current position and
2874 // search stack, alpha, beta, the search depth, etc.), and we tell our
2875 // helper threads that they have been assigned work. This will cause them
2876 // to instantly leave their idle loops and call sp_search_pv(). When all
2877 // threads have returned from sp_search_pv (or, equivalently, when
2878 // splitPoint->cpus becomes 0), split() returns true.
2880 bool split(const Position& p, SearchStack* sstck, int ply,
2881 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2882 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2885 assert(sstck != NULL);
2886 assert(ply >= 0 && ply < PLY_MAX);
2887 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2888 assert(!pvNode || *alpha < *beta);
2889 assert(*beta <= VALUE_INFINITE);
2890 assert(depth > Depth(0));
2891 assert(master >= 0 && master < ActiveThreads);
2892 assert(ActiveThreads > 1);
2894 SplitPoint* splitPoint;
2899 // If no other thread is available to help us, or if we have too many
2900 // active split points, don't split.
2901 if(!idle_thread_exists(master) ||
2902 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2903 lock_release(&MPLock);
2907 // Pick the next available split point object from the split point stack
2908 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2909 Threads[master].activeSplitPoints++;
2911 // Initialize the split point object
2912 splitPoint->parent = Threads[master].splitPoint;
2913 splitPoint->finished = false;
2914 splitPoint->ply = ply;
2915 splitPoint->depth = depth;
2916 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2917 splitPoint->beta = *beta;
2918 splitPoint->pvNode = pvNode;
2919 splitPoint->bestValue = *bestValue;
2920 splitPoint->futilityValue = futilityValue;
2921 splitPoint->master = master;
2922 splitPoint->mp = mp;
2923 splitPoint->moves = *moves;
2924 splitPoint->cpus = 1;
2925 splitPoint->pos.copy(p);
2926 splitPoint->parentSstack = sstck;
2927 for(i = 0; i < ActiveThreads; i++)
2928 splitPoint->slaves[i] = 0;
2930 // Copy the current position and the search stack to the master thread
2931 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2932 Threads[master].splitPoint = splitPoint;
2934 // Make copies of the current position and search stack for each thread
2935 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2937 if(thread_is_available(i, master)) {
2938 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2939 Threads[i].splitPoint = splitPoint;
2940 splitPoint->slaves[i] = 1;
2944 // Tell the threads that they have work to do. This will make them leave
2946 for(i = 0; i < ActiveThreads; i++)
2947 if(i == master || splitPoint->slaves[i]) {
2948 Threads[i].workIsWaiting = true;
2949 Threads[i].idle = false;
2950 Threads[i].stop = false;
2953 lock_release(&MPLock);
2955 // Everything is set up. The master thread enters the idle loop, from
2956 // which it will instantly launch a search, because its workIsWaiting
2957 // slot is 'true'. We send the split point as a second parameter to the
2958 // idle loop, which means that the main thread will return from the idle
2959 // loop when all threads have finished their work at this split point
2960 // (i.e. when // splitPoint->cpus == 0).
2961 idle_loop(master, splitPoint);
2963 // We have returned from the idle loop, which means that all threads are
2964 // finished. Update alpha, beta and bestvalue, and return.
2966 if(pvNode) *alpha = splitPoint->alpha;
2967 *beta = splitPoint->beta;
2968 *bestValue = splitPoint->bestValue;
2969 Threads[master].stop = false;
2970 Threads[master].idle = false;
2971 Threads[master].activeSplitPoints--;
2972 Threads[master].splitPoint = splitPoint->parent;
2973 lock_release(&MPLock);
2979 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2980 // to start a new search from the root.
2982 void wake_sleeping_threads() {
2983 if(ActiveThreads > 1) {
2984 for(int i = 1; i < ActiveThreads; i++) {
2985 Threads[i].idle = true;
2986 Threads[i].workIsWaiting = false;
2988 #if !defined(_MSC_VER)
2989 pthread_mutex_lock(&WaitLock);
2990 pthread_cond_broadcast(&WaitCond);
2991 pthread_mutex_unlock(&WaitLock);
2993 for(int i = 1; i < THREAD_MAX; i++)
2994 SetEvent(SitIdleEvent[i]);
3000 // init_thread() is the function which is called when a new thread is
3001 // launched. It simply calls the idle_loop() function with the supplied
3002 // threadID. There are two versions of this function; one for POSIX threads
3003 // and one for Windows threads.
3005 #if !defined(_MSC_VER)
3007 void *init_thread(void *threadID) {
3008 idle_loop(*(int *)threadID, NULL);
3014 DWORD WINAPI init_thread(LPVOID threadID) {
3015 idle_loop(*(int *)threadID, NULL);