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"
46 //// Local definitions
53 // IterationInfoType stores search results for each iteration
55 // Because we use relatively small (dynamic) aspiration window,
56 // there happens many fail highs and fail lows in root. And
57 // because we don't do researches in those cases, "value" stored
58 // here is not necessarily exact. Instead in case of fail high/low
59 // we guess what the right value might be and store our guess
60 // as a "speculated value" and then move on. Speculated values are
61 // used just to calculate aspiration window width, so also if are
62 // not exact is not big a problem.
64 struct IterationInfoType {
66 IterationInfoType(Value v = Value(0), Value sv = Value(0))
67 : value(v), speculatedValue(sv) {}
69 Value value, speculatedValue;
73 // The BetaCounterType class is used to order moves at ply one.
74 // Apart for the first one that has its score, following moves
75 // normally have score -VALUE_INFINITE, so are ordered according
76 // to the number of beta cutoffs occurred under their subtree during
77 // the last iteration. The counters are per thread variables to avoid
78 // concurrent accessing under SMP case.
80 struct BetaCounterType {
84 void add(Color us, Depth d, int threadID);
85 void read(Color us, int64_t& our, int64_t& their);
89 // The RootMove class is used for moves at the root at the tree. For each
90 // root move, we store a score, a node count, and a PV (really a refutation
91 // in the case of moves which fail low).
96 bool operator<(const RootMove&); // used to sort
100 int64_t nodes, cumulativeNodes;
101 Move pv[PLY_MAX_PLUS_2];
102 int64_t ourBeta, theirBeta;
106 // The RootMoveList class is essentially an array of RootMove objects, with
107 // a handful of methods for accessing the data in the individual moves.
112 RootMoveList(Position& pos, Move searchMoves[]);
113 inline Move get_move(int moveNum) const;
114 inline Value get_move_score(int moveNum) const;
115 inline void set_move_score(int moveNum, Value score);
116 inline void set_move_nodes(int moveNum, int64_t nodes);
117 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
118 void set_move_pv(int moveNum, const Move pv[]);
119 inline Move get_move_pv(int moveNum, int i) const;
120 inline int64_t get_move_cumulative_nodes(int moveNum) const;
121 inline int move_count() const;
122 Move scan_for_easy_move() 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 /*+ OnePly/2*/;
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 = false;
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 // Margins for futility pruning in the quiescence search, and at frontier
176 // and near frontier nodes.
177 const Value FutilityMarginQS = Value(0x80);
179 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
180 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
181 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
182 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
184 const Depth RazorDepth = 4*OnePly;
186 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
187 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
189 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
190 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
193 /// Variables initialized by UCI options
195 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
196 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
198 // Depth limit for use of dynamic threat detection
199 Depth ThreatDepth; // heavy SMP read access
201 // Last seconds noise filtering (LSN)
202 const bool UseLSNFiltering = true;
203 const int LSNTime = 4000; // In milliseconds
204 const Value LSNValue = value_from_centipawns(200);
205 bool loseOnTime = false;
207 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
208 // There is heavy SMP read access on these arrays
209 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
210 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
212 // Iteration counters
214 BetaCounterType BetaCounter; // has per-thread internal data
216 // Scores and number of times the best move changed for each iteration
217 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
218 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
223 // Time managment variables
225 int MaxNodes, MaxDepth;
226 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
230 bool StopOnPonderhit;
231 bool AbortSearch; // heavy SMP read access
237 // Show current line?
238 bool ShowCurrentLine;
242 std::ofstream LogFile;
244 // MP related variables
245 int ActiveThreads = 1;
246 Depth MinimumSplitDepth;
247 int MaxThreadsPerSplitPoint;
248 Thread Threads[THREAD_MAX];
251 bool AllThreadsShouldExit = false;
252 const int MaxActiveSplitPoints = 8;
253 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
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);
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& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
288 bool ok_to_do_nullmove(const Position& pos);
289 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d);
290 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
291 bool ok_to_history(const Position& pos, Move m);
292 void update_history(const Position& pos, Move m, 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();
303 void idle_loop(int threadID, SplitPoint* waitSp);
304 void init_split_point_stack();
305 void destroy_split_point_stack();
306 bool thread_should_stop(int threadID);
307 bool thread_is_available(int slave, int master);
308 bool idle_thread_exists(int master);
309 bool split(const Position& pos, SearchStack* ss, int ply,
310 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
311 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
312 void wake_sleeping_threads();
314 #if !defined(_MSC_VER)
315 void *init_thread(void *threadID);
317 DWORD WINAPI init_thread(LPVOID threadID);
327 /// think() is the external interface to Stockfish's search, and is called when
328 /// the program receives the UCI 'go' command. It initializes various
329 /// search-related global variables, and calls root_search(). It returns false
330 /// when a quit command is received during the search.
332 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
333 int time[], int increment[], int movesToGo, int maxDepth,
334 int maxNodes, int maxTime, Move searchMoves[]) {
336 // Look for a book move
337 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
340 if (get_option_value_string("Book File") != OpeningBook.file_name())
341 OpeningBook.open("book.bin");
343 bookMove = OpeningBook.get_move(pos);
344 if (bookMove != MOVE_NONE)
346 std::cout << "bestmove " << bookMove << std::endl;
351 // Initialize global search variables
353 SearchStartTime = get_system_time();
354 for (int i = 0; i < THREAD_MAX; i++)
356 Threads[i].nodes = 0ULL;
357 Threads[i].failHighPly1 = false;
360 InfiniteSearch = infinite;
361 PonderSearch = ponder;
362 StopOnPonderhit = false;
368 ExactMaxTime = maxTime;
370 // Read UCI option values
371 TT.set_size(get_option_value_int("Hash"));
372 if (button_was_pressed("Clear Hash"))
375 loseOnTime = false; // reset at the beginning of a new game
378 bool PonderingEnabled = get_option_value_bool("Ponder");
379 MultiPV = get_option_value_int("MultiPV");
381 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
382 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
384 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
385 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
387 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
388 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
390 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
391 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
393 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
394 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
396 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
397 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
399 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
400 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
401 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
403 Chess960 = get_option_value_bool("UCI_Chess960");
404 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
405 UseLogFile = get_option_value_bool("Use Search Log");
407 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
409 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
410 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
412 read_weights(pos.side_to_move());
414 // Set the number of active threads
415 int newActiveThreads = get_option_value_int("Threads");
416 if (newActiveThreads != ActiveThreads)
418 ActiveThreads = newActiveThreads;
419 init_eval(ActiveThreads);
422 // Wake up sleeping threads
423 wake_sleeping_threads();
425 for (int i = 1; i < ActiveThreads; i++)
426 assert(thread_is_available(i, 0));
429 int myTime = time[side_to_move];
430 int myIncrement = increment[side_to_move];
432 if (!movesToGo) // Sudden death time control
436 MaxSearchTime = myTime / 30 + myIncrement;
437 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
438 } else { // Blitz game without increment
439 MaxSearchTime = myTime / 30;
440 AbsoluteMaxSearchTime = myTime / 8;
443 else // (x moves) / (y minutes)
447 MaxSearchTime = myTime / 2;
448 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
450 MaxSearchTime = myTime / Min(movesToGo, 20);
451 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
455 if (PonderingEnabled)
457 MaxSearchTime += MaxSearchTime / 4;
458 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
461 // Fixed depth or fixed number of nodes?
464 InfiniteSearch = true; // HACK
469 NodesBetweenPolls = Min(MaxNodes, 30000);
470 InfiniteSearch = true; // HACK
473 NodesBetweenPolls = 30000;
475 // Write information to search log file
477 LogFile << "Searching: " << pos.to_fen() << std::endl
478 << "infinite: " << infinite
479 << " ponder: " << ponder
480 << " time: " << myTime
481 << " increment: " << myIncrement
482 << " moves to go: " << movesToGo << std::endl;
485 // We're ready to start thinking. Call the iterative deepening loop function
487 // FIXME we really need to cleanup all this LSN ugliness
490 Value v = id_loop(pos, searchMoves);
491 loseOnTime = ( UseLSNFiltering
498 loseOnTime = false; // reset for next match
499 while (SearchStartTime + myTime + 1000 > get_system_time())
501 id_loop(pos, searchMoves); // to fail gracefully
512 /// init_threads() is called during startup. It launches all helper threads,
513 /// and initializes the split point stack and the global locks and condition
516 void init_threads() {
520 #if !defined(_MSC_VER)
521 pthread_t pthread[1];
524 for (i = 0; i < THREAD_MAX; i++)
525 Threads[i].activeSplitPoints = 0;
527 // Initialize global locks
528 lock_init(&MPLock, NULL);
529 lock_init(&IOLock, NULL);
531 init_split_point_stack();
533 #if !defined(_MSC_VER)
534 pthread_mutex_init(&WaitLock, NULL);
535 pthread_cond_init(&WaitCond, NULL);
537 for (i = 0; i < THREAD_MAX; i++)
538 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
541 // All threads except the main thread should be initialized to idle state
542 for (i = 1; i < THREAD_MAX; i++)
544 Threads[i].stop = false;
545 Threads[i].workIsWaiting = false;
546 Threads[i].idle = true;
547 Threads[i].running = false;
550 // Launch the helper threads
551 for(i = 1; i < THREAD_MAX; i++)
553 #if !defined(_MSC_VER)
554 pthread_create(pthread, NULL, init_thread, (void*)(&i));
557 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
560 // Wait until the thread has finished launching
561 while (!Threads[i].running);
566 /// stop_threads() is called when the program exits. It makes all the
567 /// helper threads exit cleanly.
569 void stop_threads() {
571 ActiveThreads = THREAD_MAX; // HACK
572 Idle = false; // HACK
573 wake_sleeping_threads();
574 AllThreadsShouldExit = true;
575 for (int i = 1; i < THREAD_MAX; i++)
577 Threads[i].stop = true;
578 while(Threads[i].running);
580 destroy_split_point_stack();
584 /// nodes_searched() returns the total number of nodes searched so far in
585 /// the current search.
587 int64_t nodes_searched() {
589 int64_t result = 0ULL;
590 for (int i = 0; i < ActiveThreads; i++)
591 result += Threads[i].nodes;
596 // SearchStack::init() initializes a search stack. Used at the beginning of a
597 // new search from the root.
598 void SearchStack::init(int ply) {
600 pv[ply] = pv[ply + 1] = MOVE_NONE;
601 currentMove = threatMove = MOVE_NONE;
602 reduction = Depth(0);
605 void SearchStack::initKillers() {
607 mateKiller = MOVE_NONE;
608 for (int i = 0; i < KILLER_MAX; i++)
609 killers[i] = MOVE_NONE;
614 // id_loop() is the main iterative deepening loop. It calls root_search
615 // repeatedly with increasing depth until the allocated thinking time has
616 // been consumed, the user stops the search, or the maximum search depth is
619 Value id_loop(const Position& pos, Move searchMoves[]) {
622 SearchStack ss[PLY_MAX_PLUS_2];
624 // searchMoves are verified, copied, scored and sorted
625 RootMoveList rml(p, searchMoves);
627 // Print RootMoveList c'tor startup scoring to the standard output,
628 // so that we print information also for iteration 1.
629 std::cout << "info depth " << 1 << "\ninfo depth " << 1
630 << " score " << value_to_string(rml.get_move_score(0))
631 << " time " << current_search_time()
632 << " nodes " << nodes_searched()
634 << " pv " << rml.get_move(0) << "\n";
639 for (int i = 0; i < 3; i++)
644 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
647 Move EasyMove = rml.scan_for_easy_move();
649 // Iterative deepening loop
650 while (Iteration < PLY_MAX)
652 // Initialize iteration
655 BestMoveChangesByIteration[Iteration] = 0;
659 std::cout << "info depth " << Iteration << std::endl;
661 // Calculate dynamic search window based on previous iterations
664 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
666 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
667 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
669 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
671 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
672 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
676 alpha = - VALUE_INFINITE;
677 beta = VALUE_INFINITE;
680 // Search to the current depth
681 Value value = root_search(p, ss, rml, alpha, beta);
683 // Write PV to transposition table, in case the relevant entries have
684 // been overwritten during the search.
685 TT.insert_pv(p, ss[0].pv);
688 break; // Value cannot be trusted. Break out immediately!
690 //Save info about search result
691 Value speculatedValue;
694 Value delta = value - IterationInfo[Iteration - 1].value;
701 speculatedValue = value + delta;
702 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
704 else if (value <= alpha)
706 assert(value == alpha);
710 speculatedValue = value + delta;
711 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
713 speculatedValue = value;
715 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
716 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
718 // Erase the easy move if it differs from the new best move
719 if (ss[0].pv[0] != EasyMove)
720 EasyMove = MOVE_NONE;
727 bool stopSearch = false;
729 // Stop search early if there is only a single legal move
730 if (Iteration >= 6 && rml.move_count() == 1)
733 // Stop search early when the last two iterations returned a mate score
735 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
736 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
739 // Stop search early if one move seems to be much better than the rest
740 int64_t nodes = nodes_searched();
744 && EasyMove == ss[0].pv[0]
745 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
746 && current_search_time() > MaxSearchTime / 16)
747 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
748 && current_search_time() > MaxSearchTime / 32)))
751 // Add some extra time if the best move has changed during the last two iterations
752 if (Iteration > 5 && Iteration <= 50)
753 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
754 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
756 // Stop search if most of MaxSearchTime is consumed at the end of the
757 // iteration. We probably don't have enough time to search the first
758 // move at the next iteration anyway.
759 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
764 //FIXME: Implement fail-low emergency measures
768 StopOnPonderhit = true;
772 if (MaxDepth && Iteration >= MaxDepth)
778 // If we are pondering, we shouldn't print the best move before we
781 wait_for_stop_or_ponderhit();
783 // Print final search statistics
784 std::cout << "info nodes " << nodes_searched()
786 << " time " << current_search_time()
787 << " hashfull " << TT.full() << std::endl;
789 // Print the best move and the ponder move to the standard output
790 if (ss[0].pv[0] == MOVE_NONE)
792 ss[0].pv[0] = rml.get_move(0);
793 ss[0].pv[1] = MOVE_NONE;
795 std::cout << "bestmove " << ss[0].pv[0];
796 if (ss[0].pv[1] != MOVE_NONE)
797 std::cout << " ponder " << ss[0].pv[1];
799 std::cout << std::endl;
804 dbg_print_mean(LogFile);
806 if (dbg_show_hit_rate)
807 dbg_print_hit_rate(LogFile);
810 LogFile << "Nodes: " << nodes_searched() << std::endl
811 << "Nodes/second: " << nps() << std::endl
812 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
814 p.do_move(ss[0].pv[0], st);
815 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
816 << std::endl << std::endl;
818 return rml.get_move_score(0);
822 // root_search() is the function which searches the root node. It is
823 // similar to search_pv except that it uses a different move ordering
824 // scheme (perhaps we should try to use this at internal PV nodes, too?)
825 // and prints some information to the standard output.
827 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
829 Value oldAlpha = alpha;
831 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
833 // Loop through all the moves in the root move list
834 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
838 // We failed high, invalidate and skip next moves, leave node-counters
839 // and beta-counters as they are and quickly return, we will try to do
840 // a research at the next iteration with a bigger aspiration window.
841 rml.set_move_score(i, -VALUE_INFINITE);
849 RootMoveNumber = i + 1;
852 // Remember the node count before the move is searched. The node counts
853 // are used to sort the root moves at the next iteration.
854 nodes = nodes_searched();
856 // Reset beta cut-off counters
859 // Pick the next root move, and print the move and the move number to
860 // the standard output.
861 move = ss[0].currentMove = rml.get_move(i);
862 if (current_search_time() >= 1000)
863 std::cout << "info currmove " << move
864 << " currmovenumber " << i + 1 << std::endl;
866 // Decide search depth for this move
867 bool moveIsCapture = pos.move_is_capture(move);
869 ext = extension(pos, move, true, moveIsCapture, pos.move_is_check(move), false, false, &dangerous);
870 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
872 // Make the move, and search it
873 pos.do_move(move, st, dcCandidates);
877 // Aspiration window is disabled in multi-pv case
879 alpha = -VALUE_INFINITE;
881 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
882 // If the value has dropped a lot compared to the last iteration,
883 // set the boolean variable Problem to true. This variable is used
884 // for time managment: When Problem is true, we try to complete the
885 // current iteration before playing a move.
886 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
888 if (Problem && StopOnPonderhit)
889 StopOnPonderhit = false;
893 if ( newDepth >= 3*OnePly
894 && i >= MultiPV + LMRPVMoves
897 && !move_is_promotion(move)
898 && !move_is_castle(move))
900 ss[0].reduction = OnePly;
901 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
903 value = alpha + 1; // Just to trigger next condition
907 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
910 // Fail high! Set the boolean variable FailHigh to true, and
911 // re-search the move with a big window. The variable FailHigh is
912 // used for time managment: We try to avoid aborting the search
913 // prematurely during a fail high research.
915 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
922 // Finished searching the move. If AbortSearch is true, the search
923 // was aborted because the user interrupted the search or because we
924 // ran out of time. In this case, the return value of the search cannot
925 // be trusted, and we break out of the loop without updating the best
930 // Remember the node count for this move. The node counts are used to
931 // sort the root moves at the next iteration.
932 rml.set_move_nodes(i, nodes_searched() - nodes);
934 // Remember the beta-cutoff statistics
936 BetaCounter.read(pos.side_to_move(), our, their);
937 rml.set_beta_counters(i, our, their);
939 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
941 if (value <= alpha && i >= MultiPV)
942 rml.set_move_score(i, -VALUE_INFINITE);
945 // PV move or new best move!
948 rml.set_move_score(i, value);
950 TT.extract_pv(pos, ss[0].pv);
951 rml.set_move_pv(i, ss[0].pv);
955 // We record how often the best move has been changed in each
956 // iteration. This information is used for time managment: When
957 // the best move changes frequently, we allocate some more time.
959 BestMoveChangesByIteration[Iteration]++;
961 // Print search information to the standard output
962 std::cout << "info depth " << Iteration
963 << " score " << value_to_string(value)
965 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
966 << " time " << current_search_time()
967 << " nodes " << nodes_searched()
971 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
972 std::cout << ss[0].pv[j] << " ";
974 std::cout << std::endl;
977 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
983 // Reset the global variable Problem to false if the value isn't too
984 // far below the final value from the last iteration.
985 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
991 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
994 std::cout << "info multipv " << j + 1
995 << " score " << value_to_string(rml.get_move_score(j))
996 << " depth " << ((j <= i)? Iteration : Iteration - 1)
997 << " time " << current_search_time()
998 << " nodes " << nodes_searched()
1002 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1003 std::cout << rml.get_move_pv(j, k) << " ";
1005 std::cout << std::endl;
1007 alpha = rml.get_move_score(Min(i, MultiPV-1));
1009 } // New best move case
1011 assert(alpha >= oldAlpha);
1013 FailLow = (alpha == oldAlpha);
1019 // search_pv() is the main search function for PV nodes.
1021 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1022 Depth depth, int ply, int threadID) {
1024 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1025 assert(beta > alpha && beta <= VALUE_INFINITE);
1026 assert(ply >= 0 && ply < PLY_MAX);
1027 assert(threadID >= 0 && threadID < ActiveThreads);
1030 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1032 // Initialize, and make an early exit in case of an aborted search,
1033 // an instant draw, maximum ply reached, etc.
1034 init_node(ss, ply, threadID);
1036 // After init_node() that calls poll()
1037 if (AbortSearch || thread_should_stop(threadID))
1045 if (ply >= PLY_MAX - 1)
1046 return evaluate(pos, ei, threadID);
1048 // Mate distance pruning
1049 Value oldAlpha = alpha;
1050 alpha = Max(value_mated_in(ply), alpha);
1051 beta = Min(value_mate_in(ply+1), beta);
1055 // Transposition table lookup. At PV nodes, we don't use the TT for
1056 // pruning, but only for move ordering.
1057 const TTEntry* tte = TT.retrieve(pos.get_key());
1058 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1060 // Go with internal iterative deepening if we don't have a TT move
1061 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1063 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1064 ttMove = ss[ply].pv[ply];
1067 // Initialize a MovePicker object for the current position, and prepare
1068 // to search all moves
1069 Move move, movesSearched[256];
1071 Value value, bestValue = -VALUE_INFINITE;
1072 Color us = pos.side_to_move();
1073 bool isCheck = pos.is_check();
1074 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1076 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1077 Bitboard dcCandidates = mp.discovered_check_candidates();
1079 // Loop through all legal moves until no moves remain or a beta cutoff
1081 while ( alpha < beta
1082 && (move = mp.get_next_move()) != MOVE_NONE
1083 && !thread_should_stop(threadID))
1085 assert(move_is_ok(move));
1087 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1088 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1089 bool moveIsCapture = pos.move_is_capture(move);
1091 movesSearched[moveCount++] = ss[ply].currentMove = move;
1093 // Decide the new search depth
1095 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1096 Depth newDepth = depth - OnePly + ext;
1098 // Make and search the move
1100 pos.do_move(move, st, dcCandidates);
1102 if (moveCount == 1) // The first move in list is the PV
1103 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1106 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1107 // if the move fails high will be re-searched at full depth.
1108 if ( depth >= 3*OnePly
1109 && moveCount >= LMRPVMoves
1112 && !move_is_promotion(move)
1113 && !move_is_castle(move)
1114 && !move_is_killer(move, ss[ply]))
1116 ss[ply].reduction = OnePly;
1117 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1120 value = alpha + 1; // Just to trigger next condition
1122 if (value > alpha) // Go with full depth non-pv search
1124 ss[ply].reduction = Depth(0);
1125 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1126 if (value > alpha && value < beta)
1128 // When the search fails high at ply 1 while searching the first
1129 // move at the root, set the flag failHighPly1. This is used for
1130 // time managment: We don't want to stop the search early in
1131 // such cases, because resolving the fail high at ply 1 could
1132 // result in a big drop in score at the root.
1133 if (ply == 1 && RootMoveNumber == 1)
1134 Threads[threadID].failHighPly1 = true;
1136 // A fail high occurred. Re-search at full window (pv search)
1137 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1138 Threads[threadID].failHighPly1 = false;
1142 pos.undo_move(move);
1144 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1147 if (value > bestValue)
1154 if (value == value_mate_in(ply + 1))
1155 ss[ply].mateKiller = move;
1157 // If we are at ply 1, and we are searching the first root move at
1158 // ply 0, set the 'Problem' variable if the score has dropped a lot
1159 // (from the computer's point of view) since the previous iteration.
1162 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1167 if ( ActiveThreads > 1
1169 && depth >= MinimumSplitDepth
1171 && idle_thread_exists(threadID)
1173 && !thread_should_stop(threadID)
1174 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1175 &moveCount, &mp, dcCandidates, threadID, true))
1179 // All legal moves have been searched. A special case: If there were
1180 // no legal moves, it must be mate or stalemate.
1182 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1184 // If the search is not aborted, update the transposition table,
1185 // history counters, and killer moves.
1186 if (AbortSearch || thread_should_stop(threadID))
1189 if (bestValue <= oldAlpha)
1190 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1192 else if (bestValue >= beta)
1194 BetaCounter.add(pos.side_to_move(), depth, threadID);
1195 Move m = ss[ply].pv[ply];
1196 if (ok_to_history(pos, m)) // Only non capture moves are considered
1198 update_history(pos, m, depth, movesSearched, moveCount);
1199 update_killers(m, ss[ply]);
1201 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1204 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1210 // search() is the search function for zero-width nodes.
1212 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1213 int ply, bool allowNullmove, int threadID) {
1215 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1216 assert(ply >= 0 && ply < PLY_MAX);
1217 assert(threadID >= 0 && threadID < ActiveThreads);
1220 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1222 // Initialize, and make an early exit in case of an aborted search,
1223 // an instant draw, maximum ply reached, etc.
1224 init_node(ss, ply, threadID);
1226 // After init_node() that calls poll()
1227 if (AbortSearch || thread_should_stop(threadID))
1235 if (ply >= PLY_MAX - 1)
1236 return evaluate(pos, ei, threadID);
1238 // Mate distance pruning
1239 if (value_mated_in(ply) >= beta)
1242 if (value_mate_in(ply + 1) < beta)
1245 // Transposition table lookup
1246 const TTEntry* tte = TT.retrieve(pos.get_key());
1247 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1249 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1251 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1252 return value_from_tt(tte->value(), ply);
1255 Value approximateEval = quick_evaluate(pos);
1256 bool mateThreat = false;
1257 bool isCheck = pos.is_check();
1263 && !value_is_mate(beta)
1264 && ok_to_do_nullmove(pos)
1265 && approximateEval >= beta - NullMoveMargin)
1267 ss[ply].currentMove = MOVE_NULL;
1270 pos.do_null_move(st);
1271 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1273 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1275 pos.undo_null_move();
1277 if (nullValue >= beta)
1279 if (depth < 6 * OnePly)
1282 // Do zugzwang verification search
1283 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1287 // The null move failed low, which means that we may be faced with
1288 // some kind of threat. If the previous move was reduced, check if
1289 // the move that refuted the null move was somehow connected to the
1290 // move which was reduced. If a connection is found, return a fail
1291 // low score (which will cause the reduced move to fail high in the
1292 // parent node, which will trigger a re-search with full depth).
1293 if (nullValue == value_mated_in(ply + 2))
1296 ss[ply].threatMove = ss[ply + 1].currentMove;
1297 if ( depth < ThreatDepth
1298 && ss[ply - 1].reduction
1299 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1303 // Null move search not allowed, try razoring
1304 else if ( !value_is_mate(beta)
1305 && depth < RazorDepth
1306 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1307 && ss[ply - 1].currentMove != MOVE_NULL
1308 && ttMove == MOVE_NONE
1309 && !pos.has_pawn_on_7th(pos.side_to_move()))
1311 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1312 if (v < beta - RazorMargins[int(depth) - 2])
1316 // Go with internal iterative deepening if we don't have a TT move
1317 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1318 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1320 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1321 ttMove = ss[ply].pv[ply];
1324 // Initialize a MovePicker object for the current position, and prepare
1325 // to search all moves.
1326 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1328 Move move, movesSearched[256];
1330 Value value, bestValue = -VALUE_INFINITE;
1331 Bitboard dcCandidates = mp.discovered_check_candidates();
1332 Value futilityValue = VALUE_NONE;
1333 bool useFutilityPruning = depth < SelectiveDepth
1336 // Avoid calling evaluate() if we already have the score in TT
1337 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1338 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1340 // Loop through all legal moves until no moves remain or a beta cutoff
1342 while ( bestValue < beta
1343 && (move = mp.get_next_move()) != MOVE_NONE
1344 && !thread_should_stop(threadID))
1346 assert(move_is_ok(move));
1348 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1349 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1350 bool moveIsCapture = pos.move_is_capture(move);
1352 movesSearched[moveCount++] = ss[ply].currentMove = move;
1354 // Decide the new search depth
1356 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1357 Depth newDepth = depth - OnePly + ext;
1360 if ( useFutilityPruning
1363 && !move_is_promotion(move))
1365 // History pruning. See ok_to_prune() definition
1366 if ( moveCount >= 2 + int(depth)
1367 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1370 // Value based pruning
1371 if (approximateEval < beta)
1373 if (futilityValue == VALUE_NONE)
1374 futilityValue = evaluate(pos, ei, threadID)
1375 + FutilityMargins[int(depth) - 2];
1377 if (futilityValue < beta)
1379 if (futilityValue > bestValue)
1380 bestValue = futilityValue;
1386 // Make and search the move
1388 pos.do_move(move, st, dcCandidates);
1390 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1391 // if the move fails high will be re-searched at full depth.
1392 if ( depth >= 3*OnePly
1393 && moveCount >= LMRNonPVMoves
1396 && !move_is_promotion(move)
1397 && !move_is_castle(move)
1398 && !move_is_killer(move, ss[ply]))
1400 ss[ply].reduction = OnePly;
1401 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1404 value = beta; // Just to trigger next condition
1406 if (value >= beta) // Go with full depth non-pv search
1408 ss[ply].reduction = Depth(0);
1409 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1411 pos.undo_move(move);
1413 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1416 if (value > bestValue)
1422 if (value == value_mate_in(ply + 1))
1423 ss[ply].mateKiller = move;
1427 if ( ActiveThreads > 1
1429 && depth >= MinimumSplitDepth
1431 && idle_thread_exists(threadID)
1433 && !thread_should_stop(threadID)
1434 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1435 &mp, dcCandidates, threadID, false))
1439 // All legal moves have been searched. A special case: If there were
1440 // no legal moves, it must be mate or stalemate.
1442 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1444 // If the search is not aborted, update the transposition table,
1445 // history counters, and killer moves.
1446 if (AbortSearch || thread_should_stop(threadID))
1449 if (bestValue < beta)
1450 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1453 BetaCounter.add(pos.side_to_move(), depth, threadID);
1454 Move m = ss[ply].pv[ply];
1455 if (ok_to_history(pos, m)) // Only non capture moves are considered
1457 update_history(pos, m, depth, movesSearched, moveCount);
1458 update_killers(m, ss[ply]);
1460 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1463 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1469 // qsearch() is the quiescence search function, which is called by the main
1470 // search function when the remaining depth is zero (or, to be more precise,
1471 // less than OnePly).
1473 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1474 Depth depth, int ply, int threadID) {
1476 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1477 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1479 assert(ply >= 0 && ply < PLY_MAX);
1480 assert(threadID >= 0 && threadID < ActiveThreads);
1482 // Initialize, and make an early exit in case of an aborted search,
1483 // an instant draw, maximum ply reached, etc.
1484 init_node(ss, ply, threadID);
1486 // After init_node() that calls poll()
1487 if (AbortSearch || thread_should_stop(threadID))
1493 // Transposition table lookup, only when not in PV
1494 TTEntry* tte = NULL;
1495 bool pvNode = (beta - alpha != 1);
1498 tte = TT.retrieve(pos.get_key());
1499 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1501 assert(tte->type() != VALUE_TYPE_EVAL);
1503 return value_from_tt(tte->value(), ply);
1506 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1508 // Evaluate the position statically
1511 bool isCheck = pos.is_check();
1512 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1515 staticValue = -VALUE_INFINITE;
1517 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1519 // Use the cached evaluation score if possible
1520 assert(ei.futilityMargin == Value(0));
1522 staticValue = tte->value();
1525 staticValue = evaluate(pos, ei, threadID);
1527 if (ply == PLY_MAX - 1)
1528 return evaluate(pos, ei, threadID);
1530 // Initialize "stand pat score", and return it immediately if it is
1532 Value bestValue = staticValue;
1534 if (bestValue >= beta)
1536 // Store the score to avoid a future costly evaluation() call
1537 if (!isCheck && !tte && ei.futilityMargin == 0)
1538 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1543 if (bestValue > alpha)
1546 // Initialize a MovePicker object for the current position, and prepare
1547 // to search the moves. Because the depth is <= 0 here, only captures,
1548 // queen promotions and checks (only if depth == 0) will be generated.
1549 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1552 Bitboard dcCandidates = mp.discovered_check_candidates();
1553 Color us = pos.side_to_move();
1554 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1556 // Loop through the moves until no moves remain or a beta cutoff
1558 while ( alpha < beta
1559 && (move = mp.get_next_move()) != MOVE_NONE)
1561 assert(move_is_ok(move));
1564 ss[ply].currentMove = move;
1570 && !move_is_promotion(move)
1571 && !pos.move_is_check(move, dcCandidates)
1572 && !pos.move_is_passed_pawn_push(move))
1574 Value futilityValue = staticValue
1575 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1576 pos.endgame_value_of_piece_on(move_to(move)))
1577 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1579 + ei.futilityMargin;
1581 if (futilityValue < alpha)
1583 if (futilityValue > bestValue)
1584 bestValue = futilityValue;
1589 // Don't search captures and checks with negative SEE values
1591 && !move_is_promotion(move)
1592 && pos.see_sign(move) < 0)
1595 // Make and search the move.
1597 pos.do_move(move, st, dcCandidates);
1598 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1599 pos.undo_move(move);
1601 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1604 if (value > bestValue)
1615 // All legal moves have been searched. A special case: If we're in check
1616 // and no legal moves were found, it is checkmate.
1617 if (pos.is_check() && moveCount == 0) // Mate!
1618 return value_mated_in(ply);
1620 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1622 // Update transposition table
1623 Move m = ss[ply].pv[ply];
1626 // If bestValue isn't changed it means it is still the static evaluation of
1627 // the node, so keep this info to avoid a future costly evaluation() call.
1628 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1629 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1631 if (bestValue < beta)
1632 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1634 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1637 // Update killers only for good check moves
1638 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1639 update_killers(m, ss[ply]);
1645 // sp_search() is used to search from a split point. This function is called
1646 // by each thread working at the split point. It is similar to the normal
1647 // search() function, but simpler. Because we have already probed the hash
1648 // table, done a null move search, and searched the first move before
1649 // splitting, we don't have to repeat all this work in sp_search(). We
1650 // also don't need to store anything to the hash table here: This is taken
1651 // care of after we return from the split point.
1653 void sp_search(SplitPoint* sp, int threadID) {
1655 assert(threadID >= 0 && threadID < ActiveThreads);
1656 assert(ActiveThreads > 1);
1658 Position pos = Position(sp->pos);
1659 SearchStack* ss = sp->sstack[threadID];
1662 bool isCheck = pos.is_check();
1663 bool useFutilityPruning = sp->depth < SelectiveDepth
1666 while ( sp->bestValue < sp->beta
1667 && !thread_should_stop(threadID)
1668 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1670 assert(move_is_ok(move));
1672 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1673 bool moveIsCapture = pos.move_is_capture(move);
1675 lock_grab(&(sp->lock));
1676 int moveCount = ++sp->moves;
1677 lock_release(&(sp->lock));
1679 ss[sp->ply].currentMove = move;
1681 // Decide the new search depth.
1683 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1684 Depth newDepth = sp->depth - OnePly + ext;
1687 if ( useFutilityPruning
1690 && !move_is_promotion(move)
1691 && moveCount >= 2 + int(sp->depth)
1692 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1695 // Make and search the move.
1697 pos.do_move(move, st, sp->dcCandidates);
1699 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1700 // if the move fails high will be re-searched at full depth.
1702 && moveCount >= LMRNonPVMoves
1704 && !move_is_promotion(move)
1705 && !move_is_castle(move)
1706 && !move_is_killer(move, ss[sp->ply]))
1708 ss[sp->ply].reduction = OnePly;
1709 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1712 value = sp->beta; // Just to trigger next condition
1714 if (value >= sp->beta) // Go with full depth non-pv search
1716 ss[sp->ply].reduction = Depth(0);
1717 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1719 pos.undo_move(move);
1721 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1723 if (thread_should_stop(threadID))
1727 lock_grab(&(sp->lock));
1728 if (value > sp->bestValue && !thread_should_stop(threadID))
1730 sp->bestValue = value;
1731 if (sp->bestValue >= sp->beta)
1733 sp_update_pv(sp->parentSstack, ss, sp->ply);
1734 for (int i = 0; i < ActiveThreads; i++)
1735 if (i != threadID && (i == sp->master || sp->slaves[i]))
1736 Threads[i].stop = true;
1738 sp->finished = true;
1741 lock_release(&(sp->lock));
1744 lock_grab(&(sp->lock));
1746 // If this is the master thread and we have been asked to stop because of
1747 // a beta cutoff higher up in the tree, stop all slave threads.
1748 if (sp->master == threadID && thread_should_stop(threadID))
1749 for (int i = 0; i < ActiveThreads; i++)
1751 Threads[i].stop = true;
1754 sp->slaves[threadID] = 0;
1756 lock_release(&(sp->lock));
1760 // sp_search_pv() is used to search from a PV split point. This function
1761 // is called by each thread working at the split point. It is similar to
1762 // the normal search_pv() function, but simpler. Because we have already
1763 // probed the hash table and searched the first move before splitting, we
1764 // don't have to repeat all this work in sp_search_pv(). We also don't
1765 // need to store anything to the hash table here: This is taken care of
1766 // after we return from the split point.
1768 void sp_search_pv(SplitPoint* sp, int threadID) {
1770 assert(threadID >= 0 && threadID < ActiveThreads);
1771 assert(ActiveThreads > 1);
1773 Position pos = Position(sp->pos);
1774 SearchStack* ss = sp->sstack[threadID];
1778 while ( sp->alpha < sp->beta
1779 && !thread_should_stop(threadID)
1780 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1782 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1783 bool moveIsCapture = pos.move_is_capture(move);
1785 assert(move_is_ok(move));
1787 lock_grab(&(sp->lock));
1788 int moveCount = ++sp->moves;
1789 lock_release(&(sp->lock));
1791 ss[sp->ply].currentMove = move;
1793 // Decide the new search depth.
1795 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1796 Depth newDepth = sp->depth - OnePly + ext;
1798 // Make and search the move.
1800 pos.do_move(move, st, sp->dcCandidates);
1802 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1803 // if the move fails high will be re-searched at full depth.
1805 && moveCount >= LMRPVMoves
1807 && !move_is_promotion(move)
1808 && !move_is_castle(move)
1809 && !move_is_killer(move, ss[sp->ply]))
1811 ss[sp->ply].reduction = OnePly;
1812 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1815 value = sp->alpha + 1; // Just to trigger next condition
1817 if (value > sp->alpha) // Go with full depth non-pv search
1819 ss[sp->ply].reduction = Depth(0);
1820 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1822 if (value > sp->alpha && value < sp->beta)
1824 // When the search fails high at ply 1 while searching the first
1825 // move at the root, set the flag failHighPly1. This is used for
1826 // time managment: We don't want to stop the search early in
1827 // such cases, because resolving the fail high at ply 1 could
1828 // result in a big drop in score at the root.
1829 if (sp->ply == 1 && RootMoveNumber == 1)
1830 Threads[threadID].failHighPly1 = true;
1832 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1833 Threads[threadID].failHighPly1 = false;
1836 pos.undo_move(move);
1838 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1840 if (thread_should_stop(threadID))
1844 lock_grab(&(sp->lock));
1845 if (value > sp->bestValue && !thread_should_stop(threadID))
1847 sp->bestValue = value;
1848 if (value > sp->alpha)
1851 sp_update_pv(sp->parentSstack, ss, sp->ply);
1852 if (value == value_mate_in(sp->ply + 1))
1853 ss[sp->ply].mateKiller = move;
1855 if (value >= sp->beta)
1857 for (int i = 0; i < ActiveThreads; i++)
1858 if (i != threadID && (i == sp->master || sp->slaves[i]))
1859 Threads[i].stop = true;
1861 sp->finished = true;
1864 // If we are at ply 1, and we are searching the first root move at
1865 // ply 0, set the 'Problem' variable if the score has dropped a lot
1866 // (from the computer's point of view) since the previous iteration.
1869 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1872 lock_release(&(sp->lock));
1875 lock_grab(&(sp->lock));
1877 // If this is the master thread and we have been asked to stop because of
1878 // a beta cutoff higher up in the tree, stop all slave threads.
1879 if (sp->master == threadID && thread_should_stop(threadID))
1880 for (int i = 0; i < ActiveThreads; i++)
1882 Threads[i].stop = true;
1885 sp->slaves[threadID] = 0;
1887 lock_release(&(sp->lock));
1890 /// The BetaCounterType class
1892 BetaCounterType::BetaCounterType() { clear(); }
1894 void BetaCounterType::clear() {
1896 for (int i = 0; i < THREAD_MAX; i++)
1897 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1900 void BetaCounterType::add(Color us, Depth d, int threadID) {
1902 // Weighted count based on depth
1903 Threads[threadID].betaCutOffs[us] += unsigned(d);
1906 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1909 for (int i = 0; i < THREAD_MAX; i++)
1911 our += Threads[i].betaCutOffs[us];
1912 their += Threads[i].betaCutOffs[opposite_color(us)];
1917 /// The RootMove class
1921 RootMove::RootMove() {
1922 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1925 // RootMove::operator<() is the comparison function used when
1926 // sorting the moves. A move m1 is considered to be better
1927 // than a move m2 if it has a higher score, or if the moves
1928 // have equal score but m1 has the higher node count.
1930 bool RootMove::operator<(const RootMove& m) {
1932 if (score != m.score)
1933 return (score < m.score);
1935 return theirBeta <= m.theirBeta;
1938 /// The RootMoveList class
1942 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1944 MoveStack mlist[MaxRootMoves];
1945 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1947 // Generate all legal moves
1948 MoveStack* last = generate_moves(pos, mlist);
1950 // Add each move to the moves[] array
1951 for (MoveStack* cur = mlist; cur != last; cur++)
1953 bool includeMove = includeAllMoves;
1955 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1956 includeMove = (searchMoves[k] == cur->move);
1961 // Find a quick score for the move
1963 SearchStack ss[PLY_MAX_PLUS_2];
1965 moves[count].move = cur->move;
1966 pos.do_move(moves[count].move, st);
1967 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1968 pos.undo_move(moves[count].move);
1969 moves[count].pv[0] = moves[count].move;
1970 moves[count].pv[1] = MOVE_NONE; // FIXME
1977 // Simple accessor methods for the RootMoveList class
1979 inline Move RootMoveList::get_move(int moveNum) const {
1980 return moves[moveNum].move;
1983 inline Value RootMoveList::get_move_score(int moveNum) const {
1984 return moves[moveNum].score;
1987 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1988 moves[moveNum].score = score;
1991 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1992 moves[moveNum].nodes = nodes;
1993 moves[moveNum].cumulativeNodes += nodes;
1996 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1997 moves[moveNum].ourBeta = our;
1998 moves[moveNum].theirBeta = their;
2001 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2003 for(j = 0; pv[j] != MOVE_NONE; j++)
2004 moves[moveNum].pv[j] = pv[j];
2005 moves[moveNum].pv[j] = MOVE_NONE;
2008 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2009 return moves[moveNum].pv[i];
2012 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2013 return moves[moveNum].cumulativeNodes;
2016 inline int RootMoveList::move_count() const {
2021 // RootMoveList::scan_for_easy_move() is called at the end of the first
2022 // iteration, and is used to detect an "easy move", i.e. a move which appears
2023 // to be much bester than all the rest. If an easy move is found, the move
2024 // is returned, otherwise the function returns MOVE_NONE. It is very
2025 // important that this function is called at the right moment: The code
2026 // assumes that the first iteration has been completed and the moves have
2027 // been sorted. This is done in RootMoveList c'tor.
2029 Move RootMoveList::scan_for_easy_move() const {
2036 // moves are sorted so just consider the best and the second one
2037 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2043 // RootMoveList::sort() sorts the root move list at the beginning of a new
2046 inline void RootMoveList::sort() {
2048 sort_multipv(count - 1); // all items
2052 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2053 // list by their scores and depths. It is used to order the different PVs
2054 // correctly in MultiPV mode.
2056 void RootMoveList::sort_multipv(int n) {
2058 for (int i = 1; i <= n; i++)
2060 RootMove rm = moves[i];
2062 for (j = i; j > 0 && moves[j-1] < rm; j--)
2063 moves[j] = moves[j-1];
2069 // init_node() is called at the beginning of all the search functions
2070 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2071 // stack object corresponding to the current node. Once every
2072 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2073 // for user input and checks whether it is time to stop the search.
2075 void init_node(SearchStack ss[], int ply, int threadID) {
2077 assert(ply >= 0 && ply < PLY_MAX);
2078 assert(threadID >= 0 && threadID < ActiveThreads);
2080 Threads[threadID].nodes++;
2085 if (NodesSincePoll >= NodesBetweenPolls)
2092 ss[ply+2].initKillers();
2094 if (Threads[threadID].printCurrentLine)
2095 print_current_line(ss, ply, threadID);
2099 // update_pv() is called whenever a search returns a value > alpha. It
2100 // updates the PV in the SearchStack object corresponding to the current
2103 void update_pv(SearchStack ss[], int ply) {
2104 assert(ply >= 0 && ply < PLY_MAX);
2106 ss[ply].pv[ply] = ss[ply].currentMove;
2108 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2109 ss[ply].pv[p] = ss[ply+1].pv[p];
2110 ss[ply].pv[p] = MOVE_NONE;
2114 // sp_update_pv() is a variant of update_pv for use at split points. The
2115 // difference between the two functions is that sp_update_pv also updates
2116 // the PV at the parent node.
2118 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2119 assert(ply >= 0 && ply < PLY_MAX);
2121 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2123 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2124 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2125 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2129 // connected_moves() tests whether two moves are 'connected' in the sense
2130 // that the first move somehow made the second move possible (for instance
2131 // if the moving piece is the same in both moves). The first move is
2132 // assumed to be the move that was made to reach the current position, while
2133 // the second move is assumed to be a move from the current position.
2135 bool connected_moves(const Position& pos, Move m1, Move m2) {
2137 Square f1, t1, f2, t2;
2140 assert(move_is_ok(m1));
2141 assert(move_is_ok(m2));
2143 if (m2 == MOVE_NONE)
2146 // Case 1: The moving piece is the same in both moves
2152 // Case 2: The destination square for m2 was vacated by m1
2158 // Case 3: Moving through the vacated square
2159 if ( piece_is_slider(pos.piece_on(f2))
2160 && bit_is_set(squares_between(f2, t2), f1))
2163 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2164 p = pos.piece_on(t1);
2165 if (bit_is_set(pos.attacks_from(p, t1), t2))
2168 // Case 5: Discovered check, checking piece is the piece moved in m1
2169 if ( piece_is_slider(p)
2170 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2171 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2173 Bitboard occ = pos.occupied_squares();
2174 Color us = pos.side_to_move();
2175 Square ksq = pos.king_square(us);
2176 clear_bit(&occ, f2);
2177 if (type_of_piece(p) == BISHOP)
2179 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2182 else if (type_of_piece(p) == ROOK)
2184 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2189 assert(type_of_piece(p) == QUEEN);
2190 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2198 // value_is_mate() checks if the given value is a mate one
2199 // eventually compensated for the ply.
2201 bool value_is_mate(Value value) {
2203 assert(abs(value) <= VALUE_INFINITE);
2205 return value <= value_mated_in(PLY_MAX)
2206 || value >= value_mate_in(PLY_MAX);
2210 // move_is_killer() checks if the given move is among the
2211 // killer moves of that ply.
2213 bool move_is_killer(Move m, const SearchStack& ss) {
2215 const Move* k = ss.killers;
2216 for (int i = 0; i < KILLER_MAX; i++, k++)
2224 // extension() decides whether a move should be searched with normal depth,
2225 // or with extended depth. Certain classes of moves (checking moves, in
2226 // particular) are searched with bigger depth than ordinary moves and in
2227 // any case are marked as 'dangerous'. Note that also if a move is not
2228 // extended, as example because the corresponding UCI option is set to zero,
2229 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2231 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2232 bool singleReply, bool mateThreat, bool* dangerous) {
2234 assert(m != MOVE_NONE);
2236 Depth result = Depth(0);
2237 *dangerous = check | singleReply | mateThreat;
2242 result += CheckExtension[pvNode];
2245 result += SingleReplyExtension[pvNode];
2248 result += MateThreatExtension[pvNode];
2251 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2253 Color c = pos.side_to_move();
2254 if (relative_rank(c, move_to(m)) == RANK_7)
2256 result += PawnPushTo7thExtension[pvNode];
2259 if (pos.pawn_is_passed(c, move_to(m)))
2261 result += PassedPawnExtension[pvNode];
2267 && pos.type_of_piece_on(move_to(m)) != PAWN
2268 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2269 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2270 && !move_is_promotion(m)
2273 result += PawnEndgameExtension[pvNode];
2279 && pos.type_of_piece_on(move_to(m)) != PAWN
2280 && pos.see_sign(m) >= 0)
2286 return Min(result, OnePly);
2290 // ok_to_do_nullmove() looks at the current position and decides whether
2291 // doing a 'null move' should be allowed. In order to avoid zugzwang
2292 // problems, null moves are not allowed when the side to move has very
2293 // little material left. Currently, the test is a bit too simple: Null
2294 // moves are avoided only when the side to move has only pawns left. It's
2295 // probably a good idea to avoid null moves in at least some more
2296 // complicated endgames, e.g. KQ vs KR. FIXME
2298 bool ok_to_do_nullmove(const Position& pos) {
2300 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2304 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2305 // non-tactical moves late in the move list close to the leaves are
2306 // candidates for pruning.
2308 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2310 assert(move_is_ok(m));
2311 assert(threat == MOVE_NONE || move_is_ok(threat));
2312 assert(!move_is_promotion(m));
2313 assert(!pos.move_is_check(m));
2314 assert(!pos.move_is_capture(m));
2315 assert(!pos.move_is_passed_pawn_push(m));
2316 assert(d >= OnePly);
2318 Square mfrom, mto, tfrom, tto;
2320 mfrom = move_from(m);
2322 tfrom = move_from(threat);
2323 tto = move_to(threat);
2325 // Case 1: Castling moves are never pruned
2326 if (move_is_castle(m))
2329 // Case 2: Don't prune moves which move the threatened piece
2330 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2333 // Case 3: If the threatened piece has value less than or equal to the
2334 // value of the threatening piece, don't prune move which defend it.
2335 if ( !PruneDefendingMoves
2336 && threat != MOVE_NONE
2337 && pos.move_is_capture(threat)
2338 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2339 || pos.type_of_piece_on(tfrom) == KING)
2340 && pos.move_attacks_square(m, tto))
2343 // Case 4: Don't prune moves with good history
2344 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2347 // Case 5: If the moving piece in the threatened move is a slider, don't
2348 // prune safe moves which block its ray.
2349 if ( !PruneBlockingMoves
2350 && threat != MOVE_NONE
2351 && piece_is_slider(pos.piece_on(tfrom))
2352 && bit_is_set(squares_between(tfrom, tto), mto)
2353 && pos.see_sign(m) >= 0)
2360 // ok_to_use_TT() returns true if a transposition table score
2361 // can be used at a given point in search.
2363 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2365 Value v = value_from_tt(tte->value(), ply);
2367 return ( tte->depth() >= depth
2368 || v >= Max(value_mate_in(100), beta)
2369 || v < Min(value_mated_in(100), beta))
2371 && ( (is_lower_bound(tte->type()) && v >= beta)
2372 || (is_upper_bound(tte->type()) && v < beta));
2376 // ok_to_history() returns true if a move m can be stored
2377 // in history. Should be a non capturing move nor a promotion.
2379 bool ok_to_history(const Position& pos, Move m) {
2381 return !pos.move_is_capture(m) && !move_is_promotion(m);
2385 // update_history() registers a good move that produced a beta-cutoff
2386 // in history and marks as failures all the other moves of that ply.
2388 void update_history(const Position& pos, Move m, Depth depth,
2389 Move movesSearched[], int moveCount) {
2391 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2393 for (int i = 0; i < moveCount - 1; i++)
2395 assert(m != movesSearched[i]);
2396 if (ok_to_history(pos, movesSearched[i]))
2397 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2402 // update_killers() add a good move that produced a beta-cutoff
2403 // among the killer moves of that ply.
2405 void update_killers(Move m, SearchStack& ss) {
2407 if (m == ss.killers[0])
2410 for (int i = KILLER_MAX - 1; i > 0; i--)
2411 ss.killers[i] = ss.killers[i - 1];
2417 // fail_high_ply_1() checks if some thread is currently resolving a fail
2418 // high at ply 1 at the node below the first root node. This information
2419 // is used for time managment.
2421 bool fail_high_ply_1() {
2423 for(int i = 0; i < ActiveThreads; i++)
2424 if (Threads[i].failHighPly1)
2431 // current_search_time() returns the number of milliseconds which have passed
2432 // since the beginning of the current search.
2434 int current_search_time() {
2435 return get_system_time() - SearchStartTime;
2439 // nps() computes the current nodes/second count.
2442 int t = current_search_time();
2443 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2447 // poll() performs two different functions: It polls for user input, and it
2448 // looks at the time consumed so far and decides if it's time to abort the
2453 static int lastInfoTime;
2454 int t = current_search_time();
2459 // We are line oriented, don't read single chars
2460 std::string command;
2461 if (!std::getline(std::cin, command))
2464 if (command == "quit")
2467 PonderSearch = false;
2471 else if (command == "stop")
2474 PonderSearch = false;
2476 else if (command == "ponderhit")
2479 // Print search information
2483 else if (lastInfoTime > t)
2484 // HACK: Must be a new search where we searched less than
2485 // NodesBetweenPolls nodes during the first second of search.
2488 else if (t - lastInfoTime >= 1000)
2495 if (dbg_show_hit_rate)
2496 dbg_print_hit_rate();
2498 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2499 << " time " << t << " hashfull " << TT.full() << std::endl;
2500 lock_release(&IOLock);
2501 if (ShowCurrentLine)
2502 Threads[0].printCurrentLine = true;
2504 // Should we stop the search?
2508 bool overTime = t > AbsoluteMaxSearchTime
2509 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2510 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2511 && t > 6*(MaxSearchTime + ExtraSearchTime));
2513 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2514 || (ExactMaxTime && t >= ExactMaxTime)
2515 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2520 // ponderhit() is called when the program is pondering (i.e. thinking while
2521 // it's the opponent's turn to move) in order to let the engine know that
2522 // it correctly predicted the opponent's move.
2526 int t = current_search_time();
2527 PonderSearch = false;
2528 if (Iteration >= 3 &&
2529 (!InfiniteSearch && (StopOnPonderhit ||
2530 t > AbsoluteMaxSearchTime ||
2531 (RootMoveNumber == 1 &&
2532 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2533 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2534 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2539 // print_current_line() prints the current line of search for a given
2540 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2542 void print_current_line(SearchStack ss[], int ply, int threadID) {
2544 assert(ply >= 0 && ply < PLY_MAX);
2545 assert(threadID >= 0 && threadID < ActiveThreads);
2547 if (!Threads[threadID].idle)
2550 std::cout << "info currline " << (threadID + 1);
2551 for (int p = 0; p < ply; p++)
2552 std::cout << " " << ss[p].currentMove;
2554 std::cout << std::endl;
2555 lock_release(&IOLock);
2557 Threads[threadID].printCurrentLine = false;
2558 if (threadID + 1 < ActiveThreads)
2559 Threads[threadID + 1].printCurrentLine = true;
2563 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2564 // while the program is pondering. The point is to work around a wrinkle in
2565 // the UCI protocol: When pondering, the engine is not allowed to give a
2566 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2567 // We simply wait here until one of these commands is sent, and return,
2568 // after which the bestmove and pondermove will be printed (in id_loop()).
2570 void wait_for_stop_or_ponderhit() {
2572 std::string command;
2576 if (!std::getline(std::cin, command))
2579 if (command == "quit")
2584 else if (command == "ponderhit" || command == "stop")
2590 // idle_loop() is where the threads are parked when they have no work to do.
2591 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2592 // object for which the current thread is the master.
2594 void idle_loop(int threadID, SplitPoint* waitSp) {
2595 assert(threadID >= 0 && threadID < THREAD_MAX);
2597 Threads[threadID].running = true;
2600 if(AllThreadsShouldExit && threadID != 0)
2603 // If we are not thinking, wait for a condition to be signaled instead
2604 // of wasting CPU time polling for work:
2605 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2606 #if !defined(_MSC_VER)
2607 pthread_mutex_lock(&WaitLock);
2608 if(Idle || threadID >= ActiveThreads)
2609 pthread_cond_wait(&WaitCond, &WaitLock);
2610 pthread_mutex_unlock(&WaitLock);
2612 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2616 // If this thread has been assigned work, launch a search
2617 if(Threads[threadID].workIsWaiting) {
2618 Threads[threadID].workIsWaiting = false;
2619 if(Threads[threadID].splitPoint->pvNode)
2620 sp_search_pv(Threads[threadID].splitPoint, threadID);
2622 sp_search(Threads[threadID].splitPoint, threadID);
2623 Threads[threadID].idle = true;
2626 // If this thread is the master of a split point and all threads have
2627 // finished their work at this split point, return from the idle loop.
2628 if(waitSp != NULL && waitSp->cpus == 0)
2632 Threads[threadID].running = false;
2636 // init_split_point_stack() is called during program initialization, and
2637 // initializes all split point objects.
2639 void init_split_point_stack() {
2640 for(int i = 0; i < THREAD_MAX; i++)
2641 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2642 SplitPointStack[i][j].parent = NULL;
2643 lock_init(&(SplitPointStack[i][j].lock), NULL);
2648 // destroy_split_point_stack() is called when the program exits, and
2649 // destroys all locks in the precomputed split point objects.
2651 void destroy_split_point_stack() {
2652 for(int i = 0; i < THREAD_MAX; i++)
2653 for(int j = 0; j < MaxActiveSplitPoints; j++)
2654 lock_destroy(&(SplitPointStack[i][j].lock));
2658 // thread_should_stop() checks whether the thread with a given threadID has
2659 // been asked to stop, directly or indirectly. This can happen if a beta
2660 // cutoff has occured in thre thread's currently active split point, or in
2661 // some ancestor of the current split point.
2663 bool thread_should_stop(int threadID) {
2664 assert(threadID >= 0 && threadID < ActiveThreads);
2668 if(Threads[threadID].stop)
2670 if(ActiveThreads <= 2)
2672 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2674 Threads[threadID].stop = true;
2681 // thread_is_available() checks whether the thread with threadID "slave" is
2682 // available to help the thread with threadID "master" at a split point. An
2683 // obvious requirement is that "slave" must be idle. With more than two
2684 // threads, this is not by itself sufficient: If "slave" is the master of
2685 // some active split point, it is only available as a slave to the other
2686 // threads which are busy searching the split point at the top of "slave"'s
2687 // split point stack (the "helpful master concept" in YBWC terminology).
2689 bool thread_is_available(int slave, int master) {
2690 assert(slave >= 0 && slave < ActiveThreads);
2691 assert(master >= 0 && master < ActiveThreads);
2692 assert(ActiveThreads > 1);
2694 if(!Threads[slave].idle || slave == master)
2697 if(Threads[slave].activeSplitPoints == 0)
2698 // No active split points means that the thread is available as a slave
2699 // for any other thread.
2702 if(ActiveThreads == 2)
2705 // Apply the "helpful master" concept if possible.
2706 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2713 // idle_thread_exists() tries to find an idle thread which is available as
2714 // a slave for the thread with threadID "master".
2716 bool idle_thread_exists(int master) {
2717 assert(master >= 0 && master < ActiveThreads);
2718 assert(ActiveThreads > 1);
2720 for(int i = 0; i < ActiveThreads; i++)
2721 if(thread_is_available(i, master))
2727 // split() does the actual work of distributing the work at a node between
2728 // several threads at PV nodes. If it does not succeed in splitting the
2729 // node (because no idle threads are available, or because we have no unused
2730 // split point objects), the function immediately returns false. If
2731 // splitting is possible, a SplitPoint object is initialized with all the
2732 // data that must be copied to the helper threads (the current position and
2733 // search stack, alpha, beta, the search depth, etc.), and we tell our
2734 // helper threads that they have been assigned work. This will cause them
2735 // to instantly leave their idle loops and call sp_search_pv(). When all
2736 // threads have returned from sp_search_pv (or, equivalently, when
2737 // splitPoint->cpus becomes 0), split() returns true.
2739 bool split(const Position& p, SearchStack* sstck, int ply,
2740 Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves,
2741 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2744 assert(sstck != NULL);
2745 assert(ply >= 0 && ply < PLY_MAX);
2746 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2747 assert(!pvNode || *alpha < *beta);
2748 assert(*beta <= VALUE_INFINITE);
2749 assert(depth > Depth(0));
2750 assert(master >= 0 && master < ActiveThreads);
2751 assert(ActiveThreads > 1);
2753 SplitPoint* splitPoint;
2758 // If no other thread is available to help us, or if we have too many
2759 // active split points, don't split.
2760 if(!idle_thread_exists(master) ||
2761 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2762 lock_release(&MPLock);
2766 // Pick the next available split point object from the split point stack
2767 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2768 Threads[master].activeSplitPoints++;
2770 // Initialize the split point object
2771 splitPoint->parent = Threads[master].splitPoint;
2772 splitPoint->finished = false;
2773 splitPoint->ply = ply;
2774 splitPoint->depth = depth;
2775 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2776 splitPoint->beta = *beta;
2777 splitPoint->pvNode = pvNode;
2778 splitPoint->dcCandidates = dcCandidates;
2779 splitPoint->bestValue = *bestValue;
2780 splitPoint->master = master;
2781 splitPoint->mp = mp;
2782 splitPoint->moves = *moves;
2783 splitPoint->cpus = 1;
2784 splitPoint->pos.copy(p);
2785 splitPoint->parentSstack = sstck;
2786 for(i = 0; i < ActiveThreads; i++)
2787 splitPoint->slaves[i] = 0;
2789 // Copy the current position and the search stack to the master thread
2790 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2791 Threads[master].splitPoint = splitPoint;
2793 // Make copies of the current position and search stack for each thread
2794 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2796 if(thread_is_available(i, master)) {
2797 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2798 Threads[i].splitPoint = splitPoint;
2799 splitPoint->slaves[i] = 1;
2803 // Tell the threads that they have work to do. This will make them leave
2805 for(i = 0; i < ActiveThreads; i++)
2806 if(i == master || splitPoint->slaves[i]) {
2807 Threads[i].workIsWaiting = true;
2808 Threads[i].idle = false;
2809 Threads[i].stop = false;
2812 lock_release(&MPLock);
2814 // Everything is set up. The master thread enters the idle loop, from
2815 // which it will instantly launch a search, because its workIsWaiting
2816 // slot is 'true'. We send the split point as a second parameter to the
2817 // idle loop, which means that the main thread will return from the idle
2818 // loop when all threads have finished their work at this split point
2819 // (i.e. when // splitPoint->cpus == 0).
2820 idle_loop(master, splitPoint);
2822 // We have returned from the idle loop, which means that all threads are
2823 // finished. Update alpha, beta and bestvalue, and return.
2825 if(pvNode) *alpha = splitPoint->alpha;
2826 *beta = splitPoint->beta;
2827 *bestValue = splitPoint->bestValue;
2828 Threads[master].stop = false;
2829 Threads[master].idle = false;
2830 Threads[master].activeSplitPoints--;
2831 Threads[master].splitPoint = splitPoint->parent;
2832 lock_release(&MPLock);
2838 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2839 // to start a new search from the root.
2841 void wake_sleeping_threads() {
2842 if(ActiveThreads > 1) {
2843 for(int i = 1; i < ActiveThreads; i++) {
2844 Threads[i].idle = true;
2845 Threads[i].workIsWaiting = false;
2847 #if !defined(_MSC_VER)
2848 pthread_mutex_lock(&WaitLock);
2849 pthread_cond_broadcast(&WaitCond);
2850 pthread_mutex_unlock(&WaitLock);
2852 for(int i = 1; i < THREAD_MAX; i++)
2853 SetEvent(SitIdleEvent[i]);
2859 // init_thread() is the function which is called when a new thread is
2860 // launched. It simply calls the idle_loop() function with the supplied
2861 // threadID. There are two versions of this function; one for POSIX threads
2862 // and one for Windows threads.
2864 #if !defined(_MSC_VER)
2866 void *init_thread(void *threadID) {
2867 idle_loop(*(int *)threadID, NULL);
2873 DWORD WINAPI init_thread(LPVOID threadID) {
2874 idle_loop(*(int *)threadID, NULL);