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) };
192 // The main transposition table
193 TranspositionTable TT;
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; // heavy SMP read access for the latter
201 // Depth limit for use of dynamic threat detection
202 Depth ThreatDepth; // heavy SMP read access
204 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
205 // There is heavy SMP read access on these arrays
206 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
207 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
209 // Iteration counters
211 BetaCounterType BetaCounter; // has per-thread internal data
213 // Scores and number of times the best move changed for each iteration
214 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
215 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
220 // Time managment variables
222 int MaxNodes, MaxDepth;
223 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
227 bool StopOnPonderhit;
228 bool AbortSearch; // heavy SMP read access
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;
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);
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, Depth d);
287 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
288 bool ok_to_history(const Position& pos, Move m);
289 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
290 void update_killers(Move m, SearchStack& ss);
292 bool fail_high_ply_1();
293 int current_search_time();
297 void print_current_line(SearchStack ss[], int ply, int threadID);
298 void wait_for_stop_or_ponderhit();
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, Depth depth, int *moves,
308 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
309 void wake_sleeping_threads();
311 #if !defined(_MSC_VER)
312 void *init_thread(void *threadID);
314 DWORD WINAPI init_thread(LPVOID threadID);
324 /// think() is the external interface to Stockfish's search, and is called when
325 /// the program receives the UCI 'go' command. It initializes various
326 /// search-related global variables, and calls root_search(). It returns false
327 /// when a quit command is received during the search.
329 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
330 int time[], int increment[], int movesToGo, int maxDepth,
331 int maxNodes, int maxTime, Move searchMoves[]) {
333 // Look for a book move
334 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
337 if (get_option_value_string("Book File") != OpeningBook.file_name())
338 OpeningBook.open("book.bin");
340 bookMove = OpeningBook.get_move(pos);
341 if (bookMove != MOVE_NONE)
343 std::cout << "bestmove " << bookMove << std::endl;
348 // Initialize global search variables
350 SearchStartTime = get_system_time();
351 for (int i = 0; i < THREAD_MAX; i++)
353 Threads[i].nodes = 0ULL;
354 Threads[i].failHighPly1 = false;
357 InfiniteSearch = infinite;
358 PonderSearch = ponder;
359 StopOnPonderhit = false;
365 ExactMaxTime = maxTime;
367 // Read UCI option values
368 TT.set_size(get_option_value_int("Hash"));
369 if (button_was_pressed("Clear Hash"))
372 bool PonderingEnabled = get_option_value_bool("Ponder");
373 MultiPV = get_option_value_int("MultiPV");
375 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
376 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
378 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
379 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
381 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
382 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
384 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
385 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
387 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
388 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
390 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
391 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
393 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
394 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
395 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
397 Chess960 = get_option_value_bool("UCI_Chess960");
398 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
399 UseLogFile = get_option_value_bool("Use Search Log");
401 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
403 bool UseLSNFiltering = get_option_value_bool("LSN filtering");
404 int LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
405 Value LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
407 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
408 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
410 read_weights(pos.side_to_move());
412 int newActiveThreads = get_option_value_int("Threads");
413 if (newActiveThreads != ActiveThreads)
415 ActiveThreads = newActiveThreads;
416 init_eval(ActiveThreads);
419 // Wake up sleeping threads
420 wake_sleeping_threads();
422 for (int i = 1; i < ActiveThreads; i++)
423 assert(thread_is_available(i, 0));
426 int myTime = time[side_to_move];
427 int myIncrement = increment[side_to_move];
429 if (!movesToGo) // Sudden death time control
433 MaxSearchTime = myTime / 30 + myIncrement;
434 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
435 } else { // Blitz game without increment
436 MaxSearchTime = myTime / 30;
437 AbsoluteMaxSearchTime = myTime / 8;
440 else // (x moves) / (y minutes)
444 MaxSearchTime = myTime / 2;
445 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
447 MaxSearchTime = myTime / Min(movesToGo, 20);
448 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
452 if (PonderingEnabled)
454 MaxSearchTime += MaxSearchTime / 4;
455 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
458 // Fixed depth or fixed number of nodes?
461 InfiniteSearch = true; // HACK
466 NodesBetweenPolls = Min(MaxNodes, 30000);
467 InfiniteSearch = true; // HACK
470 NodesBetweenPolls = 30000;
473 // Write information to search log file
475 LogFile << "Searching: " << pos.to_fen() << std::endl
476 << "infinite: " << infinite
477 << " ponder: " << ponder
478 << " time: " << myTime
479 << " increment: " << myIncrement
480 << " moves to go: " << movesToGo << std::endl;
483 // We're ready to start thinking. Call the iterative deepening loop function
484 static bool looseOnTime = false;
486 // FIXME we really need to cleanup all this LSN ugliness
489 Value v = id_loop(pos, searchMoves);
490 looseOnTime = ( UseLSNFiltering
497 looseOnTime = false; // reset for next match
498 while (SearchStartTime + myTime + 1000 > get_system_time())
500 id_loop(pos, searchMoves); // to fail gracefully
511 /// init_threads() is called during startup. It launches all helper threads,
512 /// and initializes the split point stack and the global locks and condition
515 void init_threads() {
519 #if !defined(_MSC_VER)
520 pthread_t pthread[1];
523 for (i = 0; i < THREAD_MAX; i++)
524 Threads[i].activeSplitPoints = 0;
526 // Initialize global locks
527 lock_init(&MPLock, NULL);
528 lock_init(&IOLock, NULL);
530 init_split_point_stack();
532 #if !defined(_MSC_VER)
533 pthread_mutex_init(&WaitLock, NULL);
534 pthread_cond_init(&WaitCond, NULL);
536 for (i = 0; i < THREAD_MAX; i++)
537 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
540 // All threads except the main thread should be initialized to idle state
541 for (i = 1; i < THREAD_MAX; i++)
543 Threads[i].stop = false;
544 Threads[i].workIsWaiting = false;
545 Threads[i].idle = true;
546 Threads[i].running = false;
549 // Launch the helper threads
550 for(i = 1; i < THREAD_MAX; i++)
552 #if !defined(_MSC_VER)
553 pthread_create(pthread, NULL, init_thread, (void*)(&i));
556 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
559 // Wait until the thread has finished launching
560 while (!Threads[i].running);
565 /// stop_threads() is called when the program exits. It makes all the
566 /// helper threads exit cleanly.
568 void stop_threads() {
570 ActiveThreads = THREAD_MAX; // HACK
571 Idle = false; // HACK
572 wake_sleeping_threads();
573 AllThreadsShouldExit = true;
574 for (int i = 1; i < THREAD_MAX; i++)
576 Threads[i].stop = true;
577 while(Threads[i].running);
579 destroy_split_point_stack();
583 /// nodes_searched() returns the total number of nodes searched so far in
584 /// the current search.
586 int64_t nodes_searched() {
588 int64_t result = 0ULL;
589 for (int i = 0; i < ActiveThreads; i++)
590 result += Threads[i].nodes;
595 // SearchStack::init() initializes a search stack. Used at the beginning of a
596 // new search from the root.
597 void SearchStack::init(int ply) {
599 pv[ply] = pv[ply + 1] = MOVE_NONE;
600 currentMove = threatMove = MOVE_NONE;
601 reduction = Depth(0);
604 void SearchStack::initKillers() {
606 mateKiller = MOVE_NONE;
607 for (int i = 0; i < KILLER_MAX; i++)
608 killers[i] = MOVE_NONE;
613 // id_loop() is the main iterative deepening loop. It calls root_search
614 // repeatedly with increasing depth until the allocated thinking time has
615 // been consumed, the user stops the search, or the maximum search depth is
618 Value id_loop(const Position& pos, Move searchMoves[]) {
621 SearchStack ss[PLY_MAX_PLUS_2];
623 // searchMoves are verified, copied, scored and sorted
624 RootMoveList rml(p, searchMoves);
629 for (int i = 0; i < 3; i++)
634 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
637 Move EasyMove = rml.scan_for_easy_move();
639 // Iterative deepening loop
640 while (Iteration < PLY_MAX)
642 // Initialize iteration
645 BestMoveChangesByIteration[Iteration] = 0;
649 std::cout << "info depth " << Iteration << std::endl;
651 // Calculate dynamic search window based on previous iterations
654 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
656 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
657 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
659 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
661 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
662 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
666 alpha = - VALUE_INFINITE;
667 beta = VALUE_INFINITE;
670 // Search to the current depth
671 Value value = root_search(p, ss, rml, alpha, beta);
673 // Write PV to transposition table, in case the relevant entries have
674 // been overwritten during the search.
675 TT.insert_pv(p, ss[0].pv);
678 break; // Value cannot be trusted. Break out immediately!
680 //Save info about search result
681 Value speculatedValue;
684 Value delta = value - IterationInfo[Iteration - 1].value;
691 speculatedValue = value + delta;
692 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
694 else if (value <= alpha)
696 assert(value == alpha);
700 speculatedValue = value + delta;
701 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
703 speculatedValue = value;
705 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
706 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
708 // Erase the easy move if it differs from the new best move
709 if (ss[0].pv[0] != EasyMove)
710 EasyMove = MOVE_NONE;
717 bool stopSearch = false;
719 // Stop search early if there is only a single legal move
720 if (Iteration >= 6 && rml.move_count() == 1)
723 // Stop search early when the last two iterations returned a mate score
725 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
726 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
729 // Stop search early if one move seems to be much better than the rest
730 int64_t nodes = nodes_searched();
734 && EasyMove == ss[0].pv[0]
735 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
736 && current_search_time() > MaxSearchTime / 16)
737 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
738 && current_search_time() > MaxSearchTime / 32)))
741 // Add some extra time if the best move has changed during the last two iterations
742 if (Iteration > 5 && Iteration <= 50)
743 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
744 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
746 // Stop search if most of MaxSearchTime is consumed at the end of the
747 // iteration. We probably don't have enough time to search the first
748 // move at the next iteration anyway.
749 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
754 //FIXME: Implement fail-low emergency measures
758 StopOnPonderhit = true;
762 if (MaxDepth && Iteration >= MaxDepth)
768 // If we are pondering, we shouldn't print the best move before we
771 wait_for_stop_or_ponderhit();
773 // Print final search statistics
774 std::cout << "info nodes " << nodes_searched()
776 << " time " << current_search_time()
777 << " hashfull " << TT.full() << std::endl;
779 // Print the best move and the ponder move to the standard output
780 if (ss[0].pv[0] == MOVE_NONE)
782 ss[0].pv[0] = rml.get_move(0);
783 ss[0].pv[1] = MOVE_NONE;
785 std::cout << "bestmove " << ss[0].pv[0];
786 if (ss[0].pv[1] != MOVE_NONE)
787 std::cout << " ponder " << ss[0].pv[1];
789 std::cout << std::endl;
794 dbg_print_mean(LogFile);
796 if (dbg_show_hit_rate)
797 dbg_print_hit_rate(LogFile);
800 LogFile << "Nodes: " << nodes_searched() << std::endl
801 << "Nodes/second: " << nps() << std::endl
802 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
804 p.do_move(ss[0].pv[0], st);
805 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
806 << std::endl << std::endl;
808 return rml.get_move_score(0);
812 // root_search() is the function which searches the root node. It is
813 // similar to search_pv except that it uses a different move ordering
814 // scheme (perhaps we should try to use this at internal PV nodes, too?)
815 // and prints some information to the standard output.
817 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
819 Value oldAlpha = alpha;
821 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
823 // Loop through all the moves in the root move list
824 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
828 // We failed high, invalidate and skip next moves, leave node-counters
829 // and beta-counters as they are and quickly return, we will try to do
830 // a research at the next iteration with a bigger aspiration window.
831 rml.set_move_score(i, -VALUE_INFINITE);
839 RootMoveNumber = i + 1;
842 // Remember the node count before the move is searched. The node counts
843 // are used to sort the root moves at the next iteration.
844 nodes = nodes_searched();
846 // Reset beta cut-off counters
849 // Pick the next root move, and print the move and the move number to
850 // the standard output.
851 move = ss[0].currentMove = rml.get_move(i);
852 if (current_search_time() >= 1000)
853 std::cout << "info currmove " << move
854 << " currmovenumber " << i + 1 << std::endl;
856 // Decide search depth for this move
858 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
859 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
861 // Make the move, and search it
862 pos.do_move(move, st, dcCandidates);
866 // Aspiration window is disabled in multi-pv case
868 alpha = -VALUE_INFINITE;
870 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
871 // If the value has dropped a lot compared to the last iteration,
872 // set the boolean variable Problem to true. This variable is used
873 // for time managment: When Problem is true, we try to complete the
874 // current iteration before playing a move.
875 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
877 if (Problem && StopOnPonderhit)
878 StopOnPonderhit = false;
882 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
885 // Fail high! Set the boolean variable FailHigh to true, and
886 // re-search the move with a big window. The variable FailHigh is
887 // used for time managment: We try to avoid aborting the search
888 // prematurely during a fail high research.
890 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
896 // Finished searching the move. If AbortSearch is true, the search
897 // was aborted because the user interrupted the search or because we
898 // ran out of time. In this case, the return value of the search cannot
899 // be trusted, and we break out of the loop without updating the best
904 // Remember the node count for this move. The node counts are used to
905 // sort the root moves at the next iteration.
906 rml.set_move_nodes(i, nodes_searched() - nodes);
908 // Remember the beta-cutoff statistics
910 BetaCounter.read(pos.side_to_move(), our, their);
911 rml.set_beta_counters(i, our, their);
913 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
915 if (value <= alpha && i >= MultiPV)
916 rml.set_move_score(i, -VALUE_INFINITE);
919 // PV move or new best move!
922 rml.set_move_score(i, value);
924 rml.set_move_pv(i, ss[0].pv);
928 // We record how often the best move has been changed in each
929 // iteration. This information is used for time managment: When
930 // the best move changes frequently, we allocate some more time.
932 BestMoveChangesByIteration[Iteration]++;
934 // Print search information to the standard output
935 std::cout << "info depth " << Iteration
936 << " score " << value_to_string(value)
937 << " time " << current_search_time()
938 << " nodes " << nodes_searched()
942 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
943 std::cout << ss[0].pv[j] << " ";
945 std::cout << std::endl;
948 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
954 // Reset the global variable Problem to false if the value isn't too
955 // far below the final value from the last iteration.
956 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
962 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
965 std::cout << "info multipv " << j + 1
966 << " score " << value_to_string(rml.get_move_score(j))
967 << " depth " << ((j <= i)? Iteration : Iteration - 1)
968 << " time " << current_search_time()
969 << " nodes " << nodes_searched()
973 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
974 std::cout << rml.get_move_pv(j, k) << " ";
976 std::cout << std::endl;
978 alpha = rml.get_move_score(Min(i, MultiPV-1));
980 } // New best move case
982 assert(alpha >= oldAlpha);
984 FailLow = (alpha == oldAlpha);
990 // search_pv() is the main search function for PV nodes.
992 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
993 Depth depth, int ply, int threadID) {
995 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
996 assert(beta > alpha && beta <= VALUE_INFINITE);
997 assert(ply >= 0 && ply < PLY_MAX);
998 assert(threadID >= 0 && threadID < ActiveThreads);
1001 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1003 // Initialize, and make an early exit in case of an aborted search,
1004 // an instant draw, maximum ply reached, etc.
1005 init_node(ss, ply, threadID);
1007 // After init_node() that calls poll()
1008 if (AbortSearch || thread_should_stop(threadID))
1016 if (ply >= PLY_MAX - 1)
1017 return evaluate(pos, ei, threadID);
1019 // Mate distance pruning
1020 Value oldAlpha = alpha;
1021 alpha = Max(value_mated_in(ply), alpha);
1022 beta = Min(value_mate_in(ply+1), beta);
1026 // Transposition table lookup. At PV nodes, we don't use the TT for
1027 // pruning, but only for move ordering.
1028 const TTEntry* tte = TT.retrieve(pos.get_key());
1029 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1031 // Go with internal iterative deepening if we don't have a TT move
1032 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1034 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1035 ttMove = ss[ply].pv[ply];
1038 // Initialize a MovePicker object for the current position, and prepare
1039 // to search all moves
1040 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1042 Move move, movesSearched[256];
1044 Value value, bestValue = -VALUE_INFINITE;
1045 Bitboard dcCandidates = mp.discovered_check_candidates();
1046 Color us = pos.side_to_move();
1047 bool isCheck = pos.is_check();
1048 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1050 // Loop through all legal moves until no moves remain or a beta cutoff
1052 while ( alpha < beta
1053 && (move = mp.get_next_move()) != MOVE_NONE
1054 && !thread_should_stop(threadID))
1056 assert(move_is_ok(move));
1058 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1059 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1060 bool moveIsCapture = pos.move_is_capture(move);
1062 movesSearched[moveCount++] = ss[ply].currentMove = move;
1064 // Decide the new search depth
1066 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1067 Depth newDepth = depth - OnePly + ext;
1069 // Make and search the move
1071 pos.do_move(move, st, dcCandidates);
1073 if (moveCount == 1) // The first move in list is the PV
1074 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1077 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1078 // if the move fails high will be re-searched at full depth.
1079 if ( depth >= 2*OnePly
1080 && moveCount >= LMRPVMoves
1083 && !move_is_promotion(move)
1084 && !move_is_castle(move)
1085 && !move_is_killer(move, ss[ply]))
1087 ss[ply].reduction = OnePly;
1088 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1091 value = alpha + 1; // Just to trigger next condition
1093 if (value > alpha) // Go with full depth non-pv search
1095 ss[ply].reduction = Depth(0);
1096 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1097 if (value > alpha && value < beta)
1099 // When the search fails high at ply 1 while searching the first
1100 // move at the root, set the flag failHighPly1. This is used for
1101 // time managment: We don't want to stop the search early in
1102 // such cases, because resolving the fail high at ply 1 could
1103 // result in a big drop in score at the root.
1104 if (ply == 1 && RootMoveNumber == 1)
1105 Threads[threadID].failHighPly1 = true;
1107 // A fail high occurred. Re-search at full window (pv search)
1108 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1109 Threads[threadID].failHighPly1 = false;
1113 pos.undo_move(move);
1115 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1118 if (value > bestValue)
1125 if (value == value_mate_in(ply + 1))
1126 ss[ply].mateKiller = move;
1128 // If we are at ply 1, and we are searching the first root move at
1129 // ply 0, set the 'Problem' variable if the score has dropped a lot
1130 // (from the computer's point of view) since the previous iteration.
1133 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1138 if ( ActiveThreads > 1
1140 && depth >= MinimumSplitDepth
1142 && idle_thread_exists(threadID)
1144 && !thread_should_stop(threadID)
1145 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1146 &moveCount, &mp, dcCandidates, threadID, true))
1150 // All legal moves have been searched. A special case: If there were
1151 // no legal moves, it must be mate or stalemate.
1153 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1155 // If the search is not aborted, update the transposition table,
1156 // history counters, and killer moves.
1157 if (AbortSearch || thread_should_stop(threadID))
1160 if (bestValue <= oldAlpha)
1161 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1163 else if (bestValue >= beta)
1165 BetaCounter.add(pos.side_to_move(), depth, threadID);
1166 Move m = ss[ply].pv[ply];
1167 if (ok_to_history(pos, m)) // Only non capture moves are considered
1169 update_history(pos, m, depth, movesSearched, moveCount);
1170 update_killers(m, ss[ply]);
1172 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1175 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1181 // search() is the search function for zero-width nodes.
1183 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1184 int ply, bool allowNullmove, int threadID) {
1186 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1187 assert(ply >= 0 && ply < PLY_MAX);
1188 assert(threadID >= 0 && threadID < ActiveThreads);
1191 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1193 // Initialize, and make an early exit in case of an aborted search,
1194 // an instant draw, maximum ply reached, etc.
1195 init_node(ss, ply, threadID);
1197 // After init_node() that calls poll()
1198 if (AbortSearch || thread_should_stop(threadID))
1206 if (ply >= PLY_MAX - 1)
1207 return evaluate(pos, ei, threadID);
1209 // Mate distance pruning
1210 if (value_mated_in(ply) >= beta)
1213 if (value_mate_in(ply + 1) < beta)
1216 // Transposition table lookup
1217 const TTEntry* tte = TT.retrieve(pos.get_key());
1218 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1220 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1222 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1223 return value_from_tt(tte->value(), ply);
1226 Value approximateEval = quick_evaluate(pos);
1227 bool mateThreat = false;
1228 bool isCheck = pos.is_check();
1234 && !value_is_mate(beta)
1235 && ok_to_do_nullmove(pos)
1236 && approximateEval >= beta - NullMoveMargin)
1238 ss[ply].currentMove = MOVE_NULL;
1241 pos.do_null_move(st);
1242 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1244 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1246 pos.undo_null_move();
1248 if (value_is_mate(nullValue))
1250 /* Do not return unproven mates */
1252 else if (nullValue >= beta)
1254 if (depth < 6 * OnePly)
1257 // Do zugzwang verification search
1258 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1262 // The null move failed low, which means that we may be faced with
1263 // some kind of threat. If the previous move was reduced, check if
1264 // the move that refuted the null move was somehow connected to the
1265 // move which was reduced. If a connection is found, return a fail
1266 // low score (which will cause the reduced move to fail high in the
1267 // parent node, which will trigger a re-search with full depth).
1268 if (nullValue == value_mated_in(ply + 2))
1271 ss[ply].threatMove = ss[ply + 1].currentMove;
1272 if ( depth < ThreatDepth
1273 && ss[ply - 1].reduction
1274 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1278 // Null move search not allowed, try razoring
1279 else if ( !value_is_mate(beta)
1280 && depth < RazorDepth
1281 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1282 && ss[ply - 1].currentMove != MOVE_NULL
1283 && ttMove == MOVE_NONE
1284 && !pos.has_pawn_on_7th(pos.side_to_move()))
1286 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1287 if (v < beta - RazorMargins[int(depth) - 2])
1291 // Go with internal iterative deepening if we don't have a TT move
1292 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1293 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1295 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1296 ttMove = ss[ply].pv[ply];
1299 // Initialize a MovePicker object for the current position, and prepare
1300 // to search all moves.
1301 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1303 Move move, movesSearched[256];
1305 Value value, bestValue = -VALUE_INFINITE;
1306 Bitboard dcCandidates = mp.discovered_check_candidates();
1307 Value futilityValue = VALUE_NONE;
1308 bool useFutilityPruning = depth < SelectiveDepth
1311 // Loop through all legal moves until no moves remain or a beta cutoff
1313 while ( bestValue < beta
1314 && (move = mp.get_next_move()) != MOVE_NONE
1315 && !thread_should_stop(threadID))
1317 assert(move_is_ok(move));
1319 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1320 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1321 bool moveIsCapture = pos.move_is_capture(move);
1323 movesSearched[moveCount++] = ss[ply].currentMove = move;
1325 // Decide the new search depth
1327 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1328 Depth newDepth = depth - OnePly + ext;
1331 if ( useFutilityPruning
1334 && !move_is_promotion(move))
1336 // History pruning. See ok_to_prune() definition
1337 if ( moveCount >= 2 + int(depth)
1338 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1341 // Value based pruning
1342 if (approximateEval < beta)
1344 if (futilityValue == VALUE_NONE)
1345 futilityValue = evaluate(pos, ei, threadID)
1346 + FutilityMargins[int(depth) - 2];
1348 if (futilityValue < beta)
1350 if (futilityValue > bestValue)
1351 bestValue = futilityValue;
1357 // Make and search the move
1359 pos.do_move(move, st, dcCandidates);
1361 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1362 // if the move fails high will be re-searched at full depth.
1363 if ( depth >= 2*OnePly
1364 && moveCount >= LMRNonPVMoves
1367 && !move_is_promotion(move)
1368 && !move_is_castle(move)
1369 && !move_is_killer(move, ss[ply]))
1371 ss[ply].reduction = OnePly;
1372 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1375 value = beta; // Just to trigger next condition
1377 if (value >= beta) // Go with full depth non-pv search
1379 ss[ply].reduction = Depth(0);
1380 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1382 pos.undo_move(move);
1384 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1387 if (value > bestValue)
1393 if (value == value_mate_in(ply + 1))
1394 ss[ply].mateKiller = move;
1398 if ( ActiveThreads > 1
1400 && depth >= MinimumSplitDepth
1402 && idle_thread_exists(threadID)
1404 && !thread_should_stop(threadID)
1405 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1406 &mp, dcCandidates, threadID, false))
1410 // All legal moves have been searched. A special case: If there were
1411 // no legal moves, it must be mate or stalemate.
1413 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1415 // If the search is not aborted, update the transposition table,
1416 // history counters, and killer moves.
1417 if (AbortSearch || thread_should_stop(threadID))
1420 if (bestValue < beta)
1421 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1424 BetaCounter.add(pos.side_to_move(), depth, threadID);
1425 Move m = ss[ply].pv[ply];
1426 if (ok_to_history(pos, m)) // Only non capture moves are considered
1428 update_history(pos, m, depth, movesSearched, moveCount);
1429 update_killers(m, ss[ply]);
1431 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1434 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1440 // qsearch() is the quiescence search function, which is called by the main
1441 // search function when the remaining depth is zero (or, to be more precise,
1442 // less than OnePly).
1444 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1445 Depth depth, int ply, int threadID) {
1447 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1448 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1450 assert(ply >= 0 && ply < PLY_MAX);
1451 assert(threadID >= 0 && threadID < ActiveThreads);
1453 // Initialize, and make an early exit in case of an aborted search,
1454 // an instant draw, maximum ply reached, etc.
1455 init_node(ss, ply, threadID);
1457 // After init_node() that calls poll()
1458 if (AbortSearch || thread_should_stop(threadID))
1464 // Transposition table lookup, only when not in PV
1465 TTEntry* tte = NULL;
1466 bool pvNode = (beta - alpha != 1);
1469 tte = TT.retrieve(pos.get_key());
1470 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1472 assert(tte->type() != VALUE_TYPE_EVAL);
1474 return value_from_tt(tte->value(), ply);
1477 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1479 // Evaluate the position statically
1482 bool isCheck = pos.is_check();
1483 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1486 staticValue = -VALUE_INFINITE;
1488 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1490 // Use the cached evaluation score if possible
1491 assert(tte->value() == evaluate(pos, ei, threadID));
1492 assert(ei.futilityMargin == Value(0));
1494 staticValue = tte->value();
1497 staticValue = evaluate(pos, ei, threadID);
1499 if (ply == PLY_MAX - 1)
1500 return evaluate(pos, ei, threadID);
1502 // Initialize "stand pat score", and return it immediately if it is
1504 Value bestValue = staticValue;
1506 if (bestValue >= beta)
1508 // Store the score to avoid a future costly evaluation() call
1509 if (!isCheck && !tte && ei.futilityMargin == 0)
1510 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE);
1515 if (bestValue > alpha)
1518 // Initialize a MovePicker object for the current position, and prepare
1519 // to search the moves. Because the depth is <= 0 here, only captures,
1520 // queen promotions and checks (only if depth == 0) will be generated.
1521 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1524 Bitboard dcCandidates = mp.discovered_check_candidates();
1525 Color us = pos.side_to_move();
1526 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1528 // Loop through the moves until no moves remain or a beta cutoff
1530 while ( alpha < beta
1531 && (move = mp.get_next_move()) != MOVE_NONE)
1533 assert(move_is_ok(move));
1536 ss[ply].currentMove = move;
1542 && !move_is_promotion(move)
1543 && !pos.move_is_check(move, dcCandidates)
1544 && !pos.move_is_passed_pawn_push(move))
1546 Value futilityValue = staticValue
1547 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1548 pos.endgame_value_of_piece_on(move_to(move)))
1549 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1551 + ei.futilityMargin;
1553 if (futilityValue < alpha)
1555 if (futilityValue > bestValue)
1556 bestValue = futilityValue;
1561 // Don't search captures and checks with negative SEE values
1563 && !move_is_promotion(move)
1564 && pos.see_sign(move) < 0)
1567 // Make and search the move.
1569 pos.do_move(move, st, dcCandidates);
1570 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1571 pos.undo_move(move);
1573 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1576 if (value > bestValue)
1587 // All legal moves have been searched. A special case: If we're in check
1588 // and no legal moves were found, it is checkmate.
1589 if (pos.is_check() && moveCount == 0) // Mate!
1590 return value_mated_in(ply);
1592 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1594 // Update transposition table
1595 Move m = ss[ply].pv[ply];
1598 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1599 if (bestValue < beta)
1600 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1602 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1605 // Update killers only for good check moves
1606 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1607 update_killers(m, ss[ply]);
1613 // sp_search() is used to search from a split point. This function is called
1614 // by each thread working at the split point. It is similar to the normal
1615 // search() function, but simpler. Because we have already probed the hash
1616 // table, done a null move search, and searched the first move before
1617 // splitting, we don't have to repeat all this work in sp_search(). We
1618 // also don't need to store anything to the hash table here: This is taken
1619 // care of after we return from the split point.
1621 void sp_search(SplitPoint* sp, int threadID) {
1623 assert(threadID >= 0 && threadID < ActiveThreads);
1624 assert(ActiveThreads > 1);
1626 Position pos = Position(sp->pos);
1627 SearchStack* ss = sp->sstack[threadID];
1630 bool isCheck = pos.is_check();
1631 bool useFutilityPruning = sp->depth < SelectiveDepth
1634 while ( sp->bestValue < sp->beta
1635 && !thread_should_stop(threadID)
1636 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1638 assert(move_is_ok(move));
1640 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1641 bool moveIsCapture = pos.move_is_capture(move);
1643 lock_grab(&(sp->lock));
1644 int moveCount = ++sp->moves;
1645 lock_release(&(sp->lock));
1647 ss[sp->ply].currentMove = move;
1649 // Decide the new search depth.
1651 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1652 Depth newDepth = sp->depth - OnePly + ext;
1655 if ( useFutilityPruning
1658 && !move_is_promotion(move)
1659 && moveCount >= 2 + int(sp->depth)
1660 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1663 // Make and search the move.
1665 pos.do_move(move, st, sp->dcCandidates);
1667 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1668 // if the move fails high will be re-searched at full depth.
1670 && moveCount >= LMRNonPVMoves
1672 && !move_is_promotion(move)
1673 && !move_is_castle(move)
1674 && !move_is_killer(move, ss[sp->ply]))
1676 ss[sp->ply].reduction = OnePly;
1677 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1680 value = sp->beta; // Just to trigger next condition
1682 if (value >= sp->beta) // Go with full depth non-pv search
1684 ss[sp->ply].reduction = Depth(0);
1685 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1687 pos.undo_move(move);
1689 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1691 if (thread_should_stop(threadID))
1695 lock_grab(&(sp->lock));
1696 if (value > sp->bestValue && !thread_should_stop(threadID))
1698 sp->bestValue = value;
1699 if (sp->bestValue >= sp->beta)
1701 sp_update_pv(sp->parentSstack, ss, sp->ply);
1702 for (int i = 0; i < ActiveThreads; i++)
1703 if (i != threadID && (i == sp->master || sp->slaves[i]))
1704 Threads[i].stop = true;
1706 sp->finished = true;
1709 lock_release(&(sp->lock));
1712 lock_grab(&(sp->lock));
1714 // If this is the master thread and we have been asked to stop because of
1715 // a beta cutoff higher up in the tree, stop all slave threads.
1716 if (sp->master == threadID && thread_should_stop(threadID))
1717 for (int i = 0; i < ActiveThreads; i++)
1719 Threads[i].stop = true;
1722 sp->slaves[threadID] = 0;
1724 lock_release(&(sp->lock));
1728 // sp_search_pv() is used to search from a PV split point. This function
1729 // is called by each thread working at the split point. It is similar to
1730 // the normal search_pv() function, but simpler. Because we have already
1731 // probed the hash table and searched the first move before splitting, we
1732 // don't have to repeat all this work in sp_search_pv(). We also don't
1733 // need to store anything to the hash table here: This is taken care of
1734 // after we return from the split point.
1736 void sp_search_pv(SplitPoint* sp, int threadID) {
1738 assert(threadID >= 0 && threadID < ActiveThreads);
1739 assert(ActiveThreads > 1);
1741 Position pos = Position(sp->pos);
1742 SearchStack* ss = sp->sstack[threadID];
1746 while ( sp->alpha < sp->beta
1747 && !thread_should_stop(threadID)
1748 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1750 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1751 bool moveIsCapture = pos.move_is_capture(move);
1753 assert(move_is_ok(move));
1755 lock_grab(&(sp->lock));
1756 int moveCount = ++sp->moves;
1757 lock_release(&(sp->lock));
1759 ss[sp->ply].currentMove = move;
1761 // Decide the new search depth.
1763 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1764 Depth newDepth = sp->depth - OnePly + ext;
1766 // Make and search the move.
1768 pos.do_move(move, st, sp->dcCandidates);
1770 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1771 // if the move fails high will be re-searched at full depth.
1773 && moveCount >= LMRPVMoves
1775 && !move_is_promotion(move)
1776 && !move_is_castle(move)
1777 && !move_is_killer(move, ss[sp->ply]))
1779 ss[sp->ply].reduction = OnePly;
1780 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1783 value = sp->alpha + 1; // Just to trigger next condition
1785 if (value > sp->alpha) // Go with full depth non-pv search
1787 ss[sp->ply].reduction = Depth(0);
1788 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1790 if (value > sp->alpha && value < sp->beta)
1792 // When the search fails high at ply 1 while searching the first
1793 // move at the root, set the flag failHighPly1. This is used for
1794 // time managment: We don't want to stop the search early in
1795 // such cases, because resolving the fail high at ply 1 could
1796 // result in a big drop in score at the root.
1797 if (sp->ply == 1 && RootMoveNumber == 1)
1798 Threads[threadID].failHighPly1 = true;
1800 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1801 Threads[threadID].failHighPly1 = false;
1804 pos.undo_move(move);
1806 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1808 if (thread_should_stop(threadID))
1812 lock_grab(&(sp->lock));
1813 if (value > sp->bestValue && !thread_should_stop(threadID))
1815 sp->bestValue = value;
1816 if (value > sp->alpha)
1819 sp_update_pv(sp->parentSstack, ss, sp->ply);
1820 if (value == value_mate_in(sp->ply + 1))
1821 ss[sp->ply].mateKiller = move;
1823 if (value >= sp->beta)
1825 for (int i = 0; i < ActiveThreads; i++)
1826 if (i != threadID && (i == sp->master || sp->slaves[i]))
1827 Threads[i].stop = true;
1829 sp->finished = true;
1832 // If we are at ply 1, and we are searching the first root move at
1833 // ply 0, set the 'Problem' variable if the score has dropped a lot
1834 // (from the computer's point of view) since the previous iteration.
1837 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1840 lock_release(&(sp->lock));
1843 lock_grab(&(sp->lock));
1845 // If this is the master thread and we have been asked to stop because of
1846 // a beta cutoff higher up in the tree, stop all slave threads.
1847 if (sp->master == threadID && thread_should_stop(threadID))
1848 for (int i = 0; i < ActiveThreads; i++)
1850 Threads[i].stop = true;
1853 sp->slaves[threadID] = 0;
1855 lock_release(&(sp->lock));
1858 /// The BetaCounterType class
1860 BetaCounterType::BetaCounterType() { clear(); }
1862 void BetaCounterType::clear() {
1864 for (int i = 0; i < THREAD_MAX; i++)
1865 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1868 void BetaCounterType::add(Color us, Depth d, int threadID) {
1870 // Weighted count based on depth
1871 Threads[threadID].betaCutOffs[us] += unsigned(d);
1874 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1877 for (int i = 0; i < THREAD_MAX; i++)
1879 our += Threads[i].betaCutOffs[us];
1880 their += Threads[i].betaCutOffs[opposite_color(us)];
1885 /// The RootMove class
1889 RootMove::RootMove() {
1890 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1893 // RootMove::operator<() is the comparison function used when
1894 // sorting the moves. A move m1 is considered to be better
1895 // than a move m2 if it has a higher score, or if the moves
1896 // have equal score but m1 has the higher node count.
1898 bool RootMove::operator<(const RootMove& m) {
1900 if (score != m.score)
1901 return (score < m.score);
1903 return theirBeta <= m.theirBeta;
1906 /// The RootMoveList class
1910 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1912 MoveStack mlist[MaxRootMoves];
1913 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1915 // Generate all legal moves
1916 int lm_count = generate_legal_moves(pos, mlist);
1918 // Add each move to the moves[] array
1919 for (int i = 0; i < lm_count; i++)
1921 bool includeMove = includeAllMoves;
1923 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1924 includeMove = (searchMoves[k] == mlist[i].move);
1929 // Find a quick score for the move
1931 SearchStack ss[PLY_MAX_PLUS_2];
1933 moves[count].move = mlist[i].move;
1934 pos.do_move(moves[count].move, st);
1935 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1936 pos.undo_move(moves[count].move);
1937 moves[count].pv[0] = moves[count].move;
1938 moves[count].pv[1] = MOVE_NONE; // FIXME
1945 // Simple accessor methods for the RootMoveList class
1947 inline Move RootMoveList::get_move(int moveNum) const {
1948 return moves[moveNum].move;
1951 inline Value RootMoveList::get_move_score(int moveNum) const {
1952 return moves[moveNum].score;
1955 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1956 moves[moveNum].score = score;
1959 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1960 moves[moveNum].nodes = nodes;
1961 moves[moveNum].cumulativeNodes += nodes;
1964 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1965 moves[moveNum].ourBeta = our;
1966 moves[moveNum].theirBeta = their;
1969 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1971 for(j = 0; pv[j] != MOVE_NONE; j++)
1972 moves[moveNum].pv[j] = pv[j];
1973 moves[moveNum].pv[j] = MOVE_NONE;
1976 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1977 return moves[moveNum].pv[i];
1980 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1981 return moves[moveNum].cumulativeNodes;
1984 inline int RootMoveList::move_count() const {
1989 // RootMoveList::scan_for_easy_move() is called at the end of the first
1990 // iteration, and is used to detect an "easy move", i.e. a move which appears
1991 // to be much bester than all the rest. If an easy move is found, the move
1992 // is returned, otherwise the function returns MOVE_NONE. It is very
1993 // important that this function is called at the right moment: The code
1994 // assumes that the first iteration has been completed and the moves have
1995 // been sorted. This is done in RootMoveList c'tor.
1997 Move RootMoveList::scan_for_easy_move() const {
2004 // moves are sorted so just consider the best and the second one
2005 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2011 // RootMoveList::sort() sorts the root move list at the beginning of a new
2014 inline void RootMoveList::sort() {
2016 sort_multipv(count - 1); // all items
2020 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2021 // list by their scores and depths. It is used to order the different PVs
2022 // correctly in MultiPV mode.
2024 void RootMoveList::sort_multipv(int n) {
2026 for (int i = 1; i <= n; i++)
2028 RootMove rm = moves[i];
2030 for (j = i; j > 0 && moves[j-1] < rm; j--)
2031 moves[j] = moves[j-1];
2037 // init_node() is called at the beginning of all the search functions
2038 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2039 // stack object corresponding to the current node. Once every
2040 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2041 // for user input and checks whether it is time to stop the search.
2043 void init_node(SearchStack ss[], int ply, int threadID) {
2045 assert(ply >= 0 && ply < PLY_MAX);
2046 assert(threadID >= 0 && threadID < ActiveThreads);
2048 Threads[threadID].nodes++;
2053 if (NodesSincePoll >= NodesBetweenPolls)
2060 ss[ply+2].initKillers();
2062 if (Threads[threadID].printCurrentLine)
2063 print_current_line(ss, ply, threadID);
2067 // update_pv() is called whenever a search returns a value > alpha. It
2068 // updates the PV in the SearchStack object corresponding to the current
2071 void update_pv(SearchStack ss[], int ply) {
2072 assert(ply >= 0 && ply < PLY_MAX);
2074 ss[ply].pv[ply] = ss[ply].currentMove;
2076 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2077 ss[ply].pv[p] = ss[ply+1].pv[p];
2078 ss[ply].pv[p] = MOVE_NONE;
2082 // sp_update_pv() is a variant of update_pv for use at split points. The
2083 // difference between the two functions is that sp_update_pv also updates
2084 // the PV at the parent node.
2086 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2087 assert(ply >= 0 && ply < PLY_MAX);
2089 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2091 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2092 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2093 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2097 // connected_moves() tests whether two moves are 'connected' in the sense
2098 // that the first move somehow made the second move possible (for instance
2099 // if the moving piece is the same in both moves). The first move is
2100 // assumed to be the move that was made to reach the current position, while
2101 // the second move is assumed to be a move from the current position.
2103 bool connected_moves(const Position& pos, Move m1, Move m2) {
2104 Square f1, t1, f2, t2;
2106 assert(move_is_ok(m1));
2107 assert(move_is_ok(m2));
2109 if (m2 == MOVE_NONE)
2112 // Case 1: The moving piece is the same in both moves
2118 // Case 2: The destination square for m2 was vacated by m1
2124 // Case 3: Moving through the vacated square
2125 if ( piece_is_slider(pos.piece_on(f2))
2126 && bit_is_set(squares_between(f2, t2), f1))
2129 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2130 if (pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2133 // Case 5: Discovered check, checking piece is the piece moved in m1
2134 if ( piece_is_slider(pos.piece_on(t1))
2135 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2136 && !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())), t2))
2138 Bitboard occ = pos.occupied_squares();
2139 Color us = pos.side_to_move();
2140 Square ksq = pos.king_square(us);
2141 clear_bit(&occ, f2);
2142 if (pos.type_of_piece_on(t1) == BISHOP)
2144 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2147 else if (pos.type_of_piece_on(t1) == ROOK)
2149 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2154 assert(pos.type_of_piece_on(t1) == QUEEN);
2155 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2163 // value_is_mate() checks if the given value is a mate one
2164 // eventually compensated for the ply.
2166 bool value_is_mate(Value value) {
2168 assert(abs(value) <= VALUE_INFINITE);
2170 return value <= value_mated_in(PLY_MAX)
2171 || value >= value_mate_in(PLY_MAX);
2175 // move_is_killer() checks if the given move is among the
2176 // killer moves of that ply.
2178 bool move_is_killer(Move m, const SearchStack& ss) {
2180 const Move* k = ss.killers;
2181 for (int i = 0; i < KILLER_MAX; i++, k++)
2189 // extension() decides whether a move should be searched with normal depth,
2190 // or with extended depth. Certain classes of moves (checking moves, in
2191 // particular) are searched with bigger depth than ordinary moves and in
2192 // any case are marked as 'dangerous'. Note that also if a move is not
2193 // extended, as example because the corresponding UCI option is set to zero,
2194 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2196 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2197 bool singleReply, bool mateThreat, bool* dangerous) {
2199 assert(m != MOVE_NONE);
2201 Depth result = Depth(0);
2202 *dangerous = check || singleReply || mateThreat;
2205 result += CheckExtension[pvNode];
2208 result += SingleReplyExtension[pvNode];
2211 result += MateThreatExtension[pvNode];
2213 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2215 if (pos.move_is_pawn_push_to_7th(m))
2217 result += PawnPushTo7thExtension[pvNode];
2220 if (pos.move_is_passed_pawn_push(m))
2222 result += PassedPawnExtension[pvNode];
2228 && pos.type_of_piece_on(move_to(m)) != PAWN
2229 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2230 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2231 && !move_is_promotion(m)
2234 result += PawnEndgameExtension[pvNode];
2240 && pos.type_of_piece_on(move_to(m)) != PAWN
2241 && pos.see_sign(m) >= 0)
2247 return Min(result, OnePly);
2251 // ok_to_do_nullmove() looks at the current position and decides whether
2252 // doing a 'null move' should be allowed. In order to avoid zugzwang
2253 // problems, null moves are not allowed when the side to move has very
2254 // little material left. Currently, the test is a bit too simple: Null
2255 // moves are avoided only when the side to move has only pawns left. It's
2256 // probably a good idea to avoid null moves in at least some more
2257 // complicated endgames, e.g. KQ vs KR. FIXME
2259 bool ok_to_do_nullmove(const Position& pos) {
2261 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2265 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2266 // non-tactical moves late in the move list close to the leaves are
2267 // candidates for pruning.
2269 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2271 assert(move_is_ok(m));
2272 assert(threat == MOVE_NONE || move_is_ok(threat));
2273 assert(!move_is_promotion(m));
2274 assert(!pos.move_is_check(m));
2275 assert(!pos.move_is_capture(m));
2276 assert(!pos.move_is_passed_pawn_push(m));
2277 assert(d >= OnePly);
2279 Square mfrom, mto, tfrom, tto;
2281 mfrom = move_from(m);
2283 tfrom = move_from(threat);
2284 tto = move_to(threat);
2286 // Case 1: Castling moves are never pruned
2287 if (move_is_castle(m))
2290 // Case 2: Don't prune moves which move the threatened piece
2291 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2294 // Case 3: If the threatened piece has value less than or equal to the
2295 // value of the threatening piece, don't prune move which defend it.
2296 if ( !PruneDefendingMoves
2297 && threat != MOVE_NONE
2298 && pos.move_is_capture(threat)
2299 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2300 || pos.type_of_piece_on(tfrom) == KING)
2301 && pos.move_attacks_square(m, tto))
2304 // Case 4: Don't prune moves with good history
2305 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2308 // Case 5: If the moving piece in the threatened move is a slider, don't
2309 // prune safe moves which block its ray.
2310 if ( !PruneBlockingMoves
2311 && threat != MOVE_NONE
2312 && piece_is_slider(pos.piece_on(tfrom))
2313 && bit_is_set(squares_between(tfrom, tto), mto)
2314 && pos.see_sign(m) >= 0)
2321 // ok_to_use_TT() returns true if a transposition table score
2322 // can be used at a given point in search.
2324 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2326 Value v = value_from_tt(tte->value(), ply);
2328 return ( tte->depth() >= depth
2329 || v >= Max(value_mate_in(100), beta)
2330 || v < Min(value_mated_in(100), beta))
2332 && ( (is_lower_bound(tte->type()) && v >= beta)
2333 || (is_upper_bound(tte->type()) && v < beta));
2337 // ok_to_history() returns true if a move m can be stored
2338 // in history. Should be a non capturing move nor a promotion.
2340 bool ok_to_history(const Position& pos, Move m) {
2342 return !pos.move_is_capture(m) && !move_is_promotion(m);
2346 // update_history() registers a good move that produced a beta-cutoff
2347 // in history and marks as failures all the other moves of that ply.
2349 void update_history(const Position& pos, Move m, Depth depth,
2350 Move movesSearched[], int moveCount) {
2352 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2354 for (int i = 0; i < moveCount - 1; i++)
2356 assert(m != movesSearched[i]);
2357 if (ok_to_history(pos, movesSearched[i]))
2358 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2363 // update_killers() add a good move that produced a beta-cutoff
2364 // among the killer moves of that ply.
2366 void update_killers(Move m, SearchStack& ss) {
2368 if (m == ss.killers[0])
2371 for (int i = KILLER_MAX - 1; i > 0; i--)
2372 ss.killers[i] = ss.killers[i - 1];
2377 // fail_high_ply_1() checks if some thread is currently resolving a fail
2378 // high at ply 1 at the node below the first root node. This information
2379 // is used for time managment.
2381 bool fail_high_ply_1() {
2383 for(int i = 0; i < ActiveThreads; i++)
2384 if (Threads[i].failHighPly1)
2391 // current_search_time() returns the number of milliseconds which have passed
2392 // since the beginning of the current search.
2394 int current_search_time() {
2395 return get_system_time() - SearchStartTime;
2399 // nps() computes the current nodes/second count.
2402 int t = current_search_time();
2403 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2407 // poll() performs two different functions: It polls for user input, and it
2408 // looks at the time consumed so far and decides if it's time to abort the
2413 static int lastInfoTime;
2414 int t = current_search_time();
2419 // We are line oriented, don't read single chars
2420 std::string command;
2421 if (!std::getline(std::cin, command))
2424 if (command == "quit")
2427 PonderSearch = false;
2431 else if (command == "stop")
2434 PonderSearch = false;
2436 else if (command == "ponderhit")
2439 // Print search information
2443 else if (lastInfoTime > t)
2444 // HACK: Must be a new search where we searched less than
2445 // NodesBetweenPolls nodes during the first second of search.
2448 else if (t - lastInfoTime >= 1000)
2455 if (dbg_show_hit_rate)
2456 dbg_print_hit_rate();
2458 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2459 << " time " << t << " hashfull " << TT.full() << std::endl;
2460 lock_release(&IOLock);
2461 if (ShowCurrentLine)
2462 Threads[0].printCurrentLine = true;
2464 // Should we stop the search?
2468 bool overTime = t > AbsoluteMaxSearchTime
2469 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2470 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2471 && t > 6*(MaxSearchTime + ExtraSearchTime));
2473 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2474 || (ExactMaxTime && t >= ExactMaxTime)
2475 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2480 // ponderhit() is called when the program is pondering (i.e. thinking while
2481 // it's the opponent's turn to move) in order to let the engine know that
2482 // it correctly predicted the opponent's move.
2486 int t = current_search_time();
2487 PonderSearch = false;
2488 if (Iteration >= 3 &&
2489 (!InfiniteSearch && (StopOnPonderhit ||
2490 t > AbsoluteMaxSearchTime ||
2491 (RootMoveNumber == 1 &&
2492 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2493 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2494 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2499 // print_current_line() prints the current line of search for a given
2500 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2502 void print_current_line(SearchStack ss[], int ply, int threadID) {
2504 assert(ply >= 0 && ply < PLY_MAX);
2505 assert(threadID >= 0 && threadID < ActiveThreads);
2507 if (!Threads[threadID].idle)
2510 std::cout << "info currline " << (threadID + 1);
2511 for (int p = 0; p < ply; p++)
2512 std::cout << " " << ss[p].currentMove;
2514 std::cout << std::endl;
2515 lock_release(&IOLock);
2517 Threads[threadID].printCurrentLine = false;
2518 if (threadID + 1 < ActiveThreads)
2519 Threads[threadID + 1].printCurrentLine = true;
2523 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2524 // while the program is pondering. The point is to work around a wrinkle in
2525 // the UCI protocol: When pondering, the engine is not allowed to give a
2526 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2527 // We simply wait here until one of these commands is sent, and return,
2528 // after which the bestmove and pondermove will be printed (in id_loop()).
2530 void wait_for_stop_or_ponderhit() {
2532 std::string command;
2536 if (!std::getline(std::cin, command))
2539 if (command == "quit")
2544 else if (command == "ponderhit" || command == "stop")
2550 // idle_loop() is where the threads are parked when they have no work to do.
2551 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2552 // object for which the current thread is the master.
2554 void idle_loop(int threadID, SplitPoint* waitSp) {
2555 assert(threadID >= 0 && threadID < THREAD_MAX);
2557 Threads[threadID].running = true;
2560 if(AllThreadsShouldExit && threadID != 0)
2563 // If we are not thinking, wait for a condition to be signaled instead
2564 // of wasting CPU time polling for work:
2565 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2566 #if !defined(_MSC_VER)
2567 pthread_mutex_lock(&WaitLock);
2568 if(Idle || threadID >= ActiveThreads)
2569 pthread_cond_wait(&WaitCond, &WaitLock);
2570 pthread_mutex_unlock(&WaitLock);
2572 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2576 // If this thread has been assigned work, launch a search
2577 if(Threads[threadID].workIsWaiting) {
2578 Threads[threadID].workIsWaiting = false;
2579 if(Threads[threadID].splitPoint->pvNode)
2580 sp_search_pv(Threads[threadID].splitPoint, threadID);
2582 sp_search(Threads[threadID].splitPoint, threadID);
2583 Threads[threadID].idle = true;
2586 // If this thread is the master of a split point and all threads have
2587 // finished their work at this split point, return from the idle loop.
2588 if(waitSp != NULL && waitSp->cpus == 0)
2592 Threads[threadID].running = false;
2596 // init_split_point_stack() is called during program initialization, and
2597 // initializes all split point objects.
2599 void init_split_point_stack() {
2600 for(int i = 0; i < THREAD_MAX; i++)
2601 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2602 SplitPointStack[i][j].parent = NULL;
2603 lock_init(&(SplitPointStack[i][j].lock), NULL);
2608 // destroy_split_point_stack() is called when the program exits, and
2609 // destroys all locks in the precomputed split point objects.
2611 void destroy_split_point_stack() {
2612 for(int i = 0; i < THREAD_MAX; i++)
2613 for(int j = 0; j < MaxActiveSplitPoints; j++)
2614 lock_destroy(&(SplitPointStack[i][j].lock));
2618 // thread_should_stop() checks whether the thread with a given threadID has
2619 // been asked to stop, directly or indirectly. This can happen if a beta
2620 // cutoff has occured in thre thread's currently active split point, or in
2621 // some ancestor of the current split point.
2623 bool thread_should_stop(int threadID) {
2624 assert(threadID >= 0 && threadID < ActiveThreads);
2628 if(Threads[threadID].stop)
2630 if(ActiveThreads <= 2)
2632 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2634 Threads[threadID].stop = true;
2641 // thread_is_available() checks whether the thread with threadID "slave" is
2642 // available to help the thread with threadID "master" at a split point. An
2643 // obvious requirement is that "slave" must be idle. With more than two
2644 // threads, this is not by itself sufficient: If "slave" is the master of
2645 // some active split point, it is only available as a slave to the other
2646 // threads which are busy searching the split point at the top of "slave"'s
2647 // split point stack (the "helpful master concept" in YBWC terminology).
2649 bool thread_is_available(int slave, int master) {
2650 assert(slave >= 0 && slave < ActiveThreads);
2651 assert(master >= 0 && master < ActiveThreads);
2652 assert(ActiveThreads > 1);
2654 if(!Threads[slave].idle || slave == master)
2657 if(Threads[slave].activeSplitPoints == 0)
2658 // No active split points means that the thread is available as a slave
2659 // for any other thread.
2662 if(ActiveThreads == 2)
2665 // Apply the "helpful master" concept if possible.
2666 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2673 // idle_thread_exists() tries to find an idle thread which is available as
2674 // a slave for the thread with threadID "master".
2676 bool idle_thread_exists(int master) {
2677 assert(master >= 0 && master < ActiveThreads);
2678 assert(ActiveThreads > 1);
2680 for(int i = 0; i < ActiveThreads; i++)
2681 if(thread_is_available(i, master))
2687 // split() does the actual work of distributing the work at a node between
2688 // several threads at PV nodes. If it does not succeed in splitting the
2689 // node (because no idle threads are available, or because we have no unused
2690 // split point objects), the function immediately returns false. If
2691 // splitting is possible, a SplitPoint object is initialized with all the
2692 // data that must be copied to the helper threads (the current position and
2693 // search stack, alpha, beta, the search depth, etc.), and we tell our
2694 // helper threads that they have been assigned work. This will cause them
2695 // to instantly leave their idle loops and call sp_search_pv(). When all
2696 // threads have returned from sp_search_pv (or, equivalently, when
2697 // splitPoint->cpus becomes 0), split() returns true.
2699 bool split(const Position& p, SearchStack* sstck, int ply,
2700 Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves,
2701 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2704 assert(sstck != NULL);
2705 assert(ply >= 0 && ply < PLY_MAX);
2706 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2707 assert(!pvNode || *alpha < *beta);
2708 assert(*beta <= VALUE_INFINITE);
2709 assert(depth > Depth(0));
2710 assert(master >= 0 && master < ActiveThreads);
2711 assert(ActiveThreads > 1);
2713 SplitPoint* splitPoint;
2718 // If no other thread is available to help us, or if we have too many
2719 // active split points, don't split.
2720 if(!idle_thread_exists(master) ||
2721 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2722 lock_release(&MPLock);
2726 // Pick the next available split point object from the split point stack
2727 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2728 Threads[master].activeSplitPoints++;
2730 // Initialize the split point object
2731 splitPoint->parent = Threads[master].splitPoint;
2732 splitPoint->finished = false;
2733 splitPoint->ply = ply;
2734 splitPoint->depth = depth;
2735 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2736 splitPoint->beta = *beta;
2737 splitPoint->pvNode = pvNode;
2738 splitPoint->dcCandidates = dcCandidates;
2739 splitPoint->bestValue = *bestValue;
2740 splitPoint->master = master;
2741 splitPoint->mp = mp;
2742 splitPoint->moves = *moves;
2743 splitPoint->cpus = 1;
2744 splitPoint->pos.copy(p);
2745 splitPoint->parentSstack = sstck;
2746 for(i = 0; i < ActiveThreads; i++)
2747 splitPoint->slaves[i] = 0;
2749 // Copy the current position and the search stack to the master thread
2750 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2751 Threads[master].splitPoint = splitPoint;
2753 // Make copies of the current position and search stack for each thread
2754 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2756 if(thread_is_available(i, master)) {
2757 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2758 Threads[i].splitPoint = splitPoint;
2759 splitPoint->slaves[i] = 1;
2763 // Tell the threads that they have work to do. This will make them leave
2765 for(i = 0; i < ActiveThreads; i++)
2766 if(i == master || splitPoint->slaves[i]) {
2767 Threads[i].workIsWaiting = true;
2768 Threads[i].idle = false;
2769 Threads[i].stop = false;
2772 lock_release(&MPLock);
2774 // Everything is set up. The master thread enters the idle loop, from
2775 // which it will instantly launch a search, because its workIsWaiting
2776 // slot is 'true'. We send the split point as a second parameter to the
2777 // idle loop, which means that the main thread will return from the idle
2778 // loop when all threads have finished their work at this split point
2779 // (i.e. when // splitPoint->cpus == 0).
2780 idle_loop(master, splitPoint);
2782 // We have returned from the idle loop, which means that all threads are
2783 // finished. Update alpha, beta and bestvalue, and return.
2785 if(pvNode) *alpha = splitPoint->alpha;
2786 *beta = splitPoint->beta;
2787 *bestValue = splitPoint->bestValue;
2788 Threads[master].stop = false;
2789 Threads[master].idle = false;
2790 Threads[master].activeSplitPoints--;
2791 Threads[master].splitPoint = splitPoint->parent;
2792 lock_release(&MPLock);
2798 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2799 // to start a new search from the root.
2801 void wake_sleeping_threads() {
2802 if(ActiveThreads > 1) {
2803 for(int i = 1; i < ActiveThreads; i++) {
2804 Threads[i].idle = true;
2805 Threads[i].workIsWaiting = false;
2807 #if !defined(_MSC_VER)
2808 pthread_mutex_lock(&WaitLock);
2809 pthread_cond_broadcast(&WaitCond);
2810 pthread_mutex_unlock(&WaitLock);
2812 for(int i = 1; i < THREAD_MAX; i++)
2813 SetEvent(SitIdleEvent[i]);
2819 // init_thread() is the function which is called when a new thread is
2820 // launched. It simply calls the idle_loop() function with the supplied
2821 // threadID. There are two versions of this function; one for POSIX threads
2822 // and one for Windows threads.
2824 #if !defined(_MSC_VER)
2826 void *init_thread(void *threadID) {
2827 idle_loop(*(int *)threadID, NULL);
2833 DWORD WINAPI init_thread(LPVOID threadID) {
2834 idle_loop(*(int *)threadID, NULL);