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/>.
40 #include "ucioption.h"
44 //// Local definitions
51 // IterationInfoType stores search results for each iteration
53 // Because we use relatively small (dynamic) aspiration window,
54 // there happens many fail highs and fail lows in root. And
55 // because we don't do researches in those cases, "value" stored
56 // here is not necessarily exact. Instead in case of fail high/low
57 // we guess what the right value might be and store our guess
58 // as a "speculated value" and then move on. Speculated values are
59 // used just to calculate aspiration window width, so also if are
60 // not exact is not big a problem.
62 struct IterationInfoType {
64 IterationInfoType(Value v = Value(0), Value sv = Value(0))
65 : value(v), speculatedValue(sv) {}
67 Value value, speculatedValue;
71 // The BetaCounterType class is used to order moves at ply one.
72 // Apart for the first one that has its score, following moves
73 // normally have score -VALUE_INFINITE, so are ordered according
74 // to the number of beta cutoffs occurred under their subtree during
75 // the last iteration.
77 struct BetaCounterType {
81 void add(Color us, Depth d, int threadID);
82 void read(Color us, int64_t& our, int64_t& their);
84 int64_t hits[THREAD_MAX][2];
88 // The RootMove class is used for moves at the root at the tree. For each
89 // root move, we store a score, a node count, and a PV (really a refutation
90 // in the case of moves which fail low).
95 bool operator<(const RootMove&); // used to sort
99 int64_t nodes, cumulativeNodes;
100 Move pv[PLY_MAX_PLUS_2];
101 int64_t ourBeta, theirBeta;
105 // The RootMoveList class is essentially an array of RootMove objects, with
106 // a handful of methods for accessing the data in the individual moves.
111 RootMoveList(Position &pos, Move searchMoves[]);
112 inline Move get_move(int moveNum) const;
113 inline Value get_move_score(int moveNum) const;
114 inline void set_move_score(int moveNum, Value score);
115 inline void set_move_nodes(int moveNum, int64_t nodes);
116 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
117 void set_move_pv(int moveNum, const Move pv[]);
118 inline Move get_move_pv(int moveNum, int i) const;
119 inline int64_t get_move_cumulative_nodes(int moveNum) const;
120 inline int move_count() const;
121 Move scan_for_easy_move() const;
123 void sort_multipv(int n);
126 static const int MaxRootMoves = 500;
127 RootMove moves[MaxRootMoves];
132 /// Constants and variables initialized from UCI options
134 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
136 int LMRPVMoves, LMRNonPVMoves;
138 // Depth limit for use of dynamic threat detection
141 // Depth limit for selective search
142 const Depth SelectiveDepth = 7*OnePly;
144 // Use internal iterative deepening?
145 const bool UseIIDAtPVNodes = true;
146 const bool UseIIDAtNonPVNodes = false;
148 // Internal iterative deepening margin. At Non-PV moves, when
149 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
150 // when the static evaluation is at most IIDMargin below beta.
151 const Value IIDMargin = Value(0x100);
153 // Easy move margin. An easy move candidate must be at least this much
154 // better than the second best move.
155 const Value EasyMoveMargin = Value(0x200);
157 // Problem margin. If the score of the first move at iteration N+1 has
158 // dropped by more than this since iteration N, the boolean variable
159 // "Problem" is set to true, which will make the program spend some extra
160 // time looking for a better move.
161 const Value ProblemMargin = Value(0x28);
163 // No problem margin. If the boolean "Problem" is true, and a new move
164 // is found at the root which is less than NoProblemMargin worse than the
165 // best move from the previous iteration, Problem is set back to false.
166 const Value NoProblemMargin = Value(0x14);
168 // Null move margin. A null move search will not be done if the approximate
169 // evaluation of the position is more than NullMoveMargin below beta.
170 const Value NullMoveMargin = Value(0x300);
172 // Pruning criterions. See the code and comments in ok_to_prune() to
173 // understand their precise meaning.
174 const bool PruneEscapeMoves = false;
175 const bool PruneDefendingMoves = false;
176 const bool PruneBlockingMoves = false;
178 // Use futility pruning?
179 bool UseQSearchFutilityPruning, UseFutilityPruning;
181 // Margins for futility pruning in the quiescence search, and at frontier
182 // and near frontier nodes
183 const Value FutilityMarginQS = Value(0x80);
185 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
186 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
187 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
188 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
190 const Depth RazorDepth = 4*OnePly;
192 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
193 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
195 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
196 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
198 // Last seconds noise filtering (LSN)
199 bool UseLSNFiltering;
200 bool looseOnTime = false;
201 int LSNTime; // In milliseconds
204 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
205 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
206 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
208 // Search depth at iteration 1
209 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
213 int NodesBetweenPolls = 30000;
215 // Iteration counters
217 BetaCounterType BetaCounter;
219 // Scores and number of times the best move changed for each iteration:
220 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
221 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
226 // Time managment variables
228 int MaxNodes, MaxDepth;
229 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
234 bool StopOnPonderhit;
240 bool PonderingEnabled;
243 // Show current line?
244 bool ShowCurrentLine;
248 std::ofstream LogFile;
250 // MP related variables
251 Depth MinimumSplitDepth;
252 int MaxThreadsPerSplitPoint;
253 Thread Threads[THREAD_MAX];
255 bool AllThreadsShouldExit = false;
256 const int MaxActiveSplitPoints = 8;
257 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
260 #if !defined(_MSC_VER)
261 pthread_cond_t WaitCond;
262 pthread_mutex_t WaitLock;
264 HANDLE SitIdleEvent[THREAD_MAX];
270 Value id_loop(const Position &pos, Move searchMoves[]);
271 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta);
272 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
273 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
274 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
275 void sp_search(SplitPoint *sp, int threadID);
276 void sp_search_pv(SplitPoint *sp, int threadID);
277 void init_node(SearchStack ss[], int ply, int threadID);
278 void update_pv(SearchStack ss[], int ply);
279 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
280 bool connected_moves(const Position &pos, Move m1, Move m2);
281 bool value_is_mate(Value value);
282 bool move_is_killer(Move m, const SearchStack& ss);
283 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
284 bool ok_to_do_nullmove(const Position &pos);
285 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
286 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
287 bool ok_to_history(const Position &pos, Move m);
288 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
289 void update_killers(Move m, SearchStack& ss);
291 bool fail_high_ply_1();
292 int current_search_time();
296 void print_current_line(SearchStack ss[], int ply, int threadID);
297 void wait_for_stop_or_ponderhit();
299 void idle_loop(int threadID, SplitPoint *waitSp);
300 void init_split_point_stack();
301 void destroy_split_point_stack();
302 bool thread_should_stop(int threadID);
303 bool thread_is_available(int slave, int master);
304 bool idle_thread_exists(int master);
305 bool split(const Position &pos, SearchStack *ss, int ply,
306 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
307 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
308 void wake_sleeping_threads();
310 #if !defined(_MSC_VER)
311 void *init_thread(void *threadID);
313 DWORD WINAPI init_thread(LPVOID threadID);
320 //// Global variables
323 // The main transposition table
324 TranspositionTable TT;
327 // Number of active threads:
328 int ActiveThreads = 1;
330 // Locks. In principle, there is no need for IOLock to be a global variable,
331 // but it could turn out to be useful for debugging.
334 History H; // Should be made local?
336 // The empty search stack
337 SearchStack EmptySearchStack;
340 // SearchStack::init() initializes a search stack. Used at the beginning of a
341 // new search from the root.
342 void SearchStack::init(int ply) {
344 pv[ply] = pv[ply + 1] = MOVE_NONE;
345 currentMove = threatMove = MOVE_NONE;
346 reduction = Depth(0);
349 void SearchStack::initKillers() {
351 mateKiller = MOVE_NONE;
352 for (int i = 0; i < KILLER_MAX; i++)
353 killers[i] = MOVE_NONE;
361 /// think() is the external interface to Stockfish's search, and is called when
362 /// the program receives the UCI 'go' command. It initializes various
363 /// search-related global variables, and calls root_search(). It returns false
364 /// when a quit command is received during the search.
366 bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
367 int time[], int increment[], int movesToGo, int maxDepth,
368 int maxNodes, int maxTime, Move searchMoves[]) {
370 // Look for a book move
371 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
374 if (get_option_value_string("Book File") != OpeningBook.file_name())
375 OpeningBook.open("book.bin");
377 bookMove = OpeningBook.get_move(pos);
378 if (bookMove != MOVE_NONE)
380 std::cout << "bestmove " << bookMove << std::endl;
385 // Initialize global search variables
387 SearchStartTime = get_system_time();
388 EasyMove = MOVE_NONE;
389 for (int i = 0; i < THREAD_MAX; i++)
391 Threads[i].nodes = 0ULL;
392 Threads[i].failHighPly1 = false;
395 InfiniteSearch = infinite;
396 PonderSearch = ponder;
397 StopOnPonderhit = false;
403 ExactMaxTime = maxTime;
405 // Read UCI option values
406 TT.set_size(get_option_value_int("Hash"));
407 if (button_was_pressed("Clear Hash"))
410 PonderingEnabled = get_option_value_bool("Ponder");
411 MultiPV = get_option_value_int("MultiPV");
413 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
414 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
416 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
417 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
419 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
420 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
422 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
423 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
425 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
426 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
428 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
429 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
431 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
432 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
433 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
435 Chess960 = get_option_value_bool("UCI_Chess960");
436 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
437 UseLogFile = get_option_value_bool("Use Search Log");
439 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
441 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
442 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
444 UseLSNFiltering = get_option_value_bool("LSN filtering");
445 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
446 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
448 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
449 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
451 read_weights(pos.side_to_move());
453 int newActiveThreads = get_option_value_int("Threads");
454 if (newActiveThreads != ActiveThreads)
456 ActiveThreads = newActiveThreads;
457 init_eval(ActiveThreads);
460 // Wake up sleeping threads:
461 wake_sleeping_threads();
463 for (int i = 1; i < ActiveThreads; i++)
464 assert(thread_is_available(i, 0));
466 // Set thinking time:
467 int myTime = time[side_to_move];
468 int myIncrement = increment[side_to_move];
470 if (!movesToGo) // Sudden death time control
474 MaxSearchTime = myTime / 30 + myIncrement;
475 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
476 } else { // Blitz game without increment
477 MaxSearchTime = myTime / 30;
478 AbsoluteMaxSearchTime = myTime / 8;
481 else // (x moves) / (y minutes)
485 MaxSearchTime = myTime / 2;
486 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
488 MaxSearchTime = myTime / Min(movesToGo, 20);
489 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
493 if (PonderingEnabled)
495 MaxSearchTime += MaxSearchTime / 4;
496 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
499 // Fixed depth or fixed number of nodes?
502 InfiniteSearch = true; // HACK
507 NodesBetweenPolls = Min(MaxNodes, 30000);
508 InfiniteSearch = true; // HACK
511 NodesBetweenPolls = 30000;
514 // Write information to search log file:
516 LogFile << "Searching: " << pos.to_fen() << std::endl
517 << "infinite: " << infinite
518 << " ponder: " << ponder
519 << " time: " << myTime
520 << " increment: " << myIncrement
521 << " moves to go: " << movesToGo << std::endl;
524 // We're ready to start thinking. Call the iterative deepening loop
528 Value v = id_loop(pos, searchMoves);
529 looseOnTime = ( UseLSNFiltering
536 looseOnTime = false; // reset for next match
537 while (SearchStartTime + myTime + 1000 > get_system_time())
539 id_loop(pos, searchMoves); // to fail gracefully
550 /// init_threads() is called during startup. It launches all helper threads,
551 /// and initializes the split point stack and the global locks and condition
554 void init_threads() {
558 #if !defined(_MSC_VER)
559 pthread_t pthread[1];
562 for (i = 0; i < THREAD_MAX; i++)
563 Threads[i].activeSplitPoints = 0;
565 // Initialize global locks:
566 lock_init(&MPLock, NULL);
567 lock_init(&IOLock, NULL);
569 init_split_point_stack();
571 #if !defined(_MSC_VER)
572 pthread_mutex_init(&WaitLock, NULL);
573 pthread_cond_init(&WaitCond, NULL);
575 for (i = 0; i < THREAD_MAX; i++)
576 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
579 // All threads except the main thread should be initialized to idle state
580 for (i = 1; i < THREAD_MAX; i++)
582 Threads[i].stop = false;
583 Threads[i].workIsWaiting = false;
584 Threads[i].idle = true;
585 Threads[i].running = false;
588 // Launch the helper threads
589 for(i = 1; i < THREAD_MAX; i++)
591 #if !defined(_MSC_VER)
592 pthread_create(pthread, NULL, init_thread, (void*)(&i));
595 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
598 // Wait until the thread has finished launching:
599 while (!Threads[i].running);
602 // Init also the empty search stack
603 EmptySearchStack.init(0);
604 EmptySearchStack.initKillers();
608 /// stop_threads() is called when the program exits. It makes all the
609 /// helper threads exit cleanly.
611 void stop_threads() {
613 ActiveThreads = THREAD_MAX; // HACK
614 Idle = false; // HACK
615 wake_sleeping_threads();
616 AllThreadsShouldExit = true;
617 for (int i = 1; i < THREAD_MAX; i++)
619 Threads[i].stop = true;
620 while(Threads[i].running);
622 destroy_split_point_stack();
626 /// nodes_searched() returns the total number of nodes searched so far in
627 /// the current search.
629 int64_t nodes_searched() {
631 int64_t result = 0ULL;
632 for (int i = 0; i < ActiveThreads; i++)
633 result += Threads[i].nodes;
640 // id_loop() is the main iterative deepening loop. It calls root_search
641 // repeatedly with increasing depth until the allocated thinking time has
642 // been consumed, the user stops the search, or the maximum search depth is
645 Value id_loop(const Position &pos, Move searchMoves[]) {
648 SearchStack ss[PLY_MAX_PLUS_2];
650 // searchMoves are verified, copied, scored and sorted
651 RootMoveList rml(p, searchMoves);
656 for (int i = 0; i < 3; i++)
661 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
664 EasyMove = rml.scan_for_easy_move();
666 // Iterative deepening loop
667 while (Iteration < PLY_MAX)
669 // Initialize iteration
672 BestMoveChangesByIteration[Iteration] = 0;
676 std::cout << "info depth " << Iteration << std::endl;
678 // Calculate dynamic search window based on previous iterations
681 if (MultiPV == 1 && Iteration >= 6)
683 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
684 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
686 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
688 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
689 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
693 alpha = - VALUE_INFINITE;
694 beta = VALUE_INFINITE;
697 // Search to the current depth
698 Value value = root_search(p, ss, rml, alpha, beta);
700 // Write PV to transposition table, in case the relevant entries have
701 // been overwritten during the search.
702 TT.insert_pv(p, ss[0].pv);
705 break; // Value cannot be trusted. Break out immediately!
707 //Save info about search result
708 Value speculatedValue;
711 Value delta = value - IterationInfo[Iteration - 1].value;
718 speculatedValue = value + delta;
719 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
721 else if (value <= alpha)
723 assert(value == alpha);
727 speculatedValue = value + delta;
728 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
730 speculatedValue = value;
732 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
733 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
735 // Erase the easy move if it differs from the new best move
736 if (ss[0].pv[0] != EasyMove)
737 EasyMove = MOVE_NONE;
744 bool stopSearch = false;
746 // Stop search early if there is only a single legal move:
747 if (Iteration >= 6 && rml.move_count() == 1)
750 // Stop search early when the last two iterations returned a mate score
752 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
753 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
756 // Stop search early if one move seems to be much better than the rest
757 int64_t nodes = nodes_searched();
761 && EasyMove == ss[0].pv[0]
762 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
763 && current_search_time() > MaxSearchTime / 16)
764 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
765 && current_search_time() > MaxSearchTime / 32)))
768 // Add some extra time if the best move has changed during the last two iterations
769 if (Iteration > 5 && Iteration <= 50)
770 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
771 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
773 // Stop search if most of MaxSearchTime is consumed at the end of the
774 // iteration. We probably don't have enough time to search the first
775 // move at the next iteration anyway.
776 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
781 //FIXME: Implement fail-low emergency measures
785 StopOnPonderhit = true;
789 if (MaxDepth && Iteration >= MaxDepth)
795 // If we are pondering, we shouldn't print the best move before we
798 wait_for_stop_or_ponderhit();
800 // Print final search statistics
801 std::cout << "info nodes " << nodes_searched()
803 << " time " << current_search_time()
804 << " hashfull " << TT.full() << std::endl;
806 // Print the best move and the ponder move to the standard output
807 if (ss[0].pv[0] == MOVE_NONE)
809 ss[0].pv[0] = rml.get_move(0);
810 ss[0].pv[1] = MOVE_NONE;
812 std::cout << "bestmove " << ss[0].pv[0];
813 if (ss[0].pv[1] != MOVE_NONE)
814 std::cout << " ponder " << ss[0].pv[1];
816 std::cout << std::endl;
821 dbg_print_mean(LogFile);
823 if (dbg_show_hit_rate)
824 dbg_print_hit_rate(LogFile);
827 LogFile << "Nodes: " << nodes_searched() << std::endl
828 << "Nodes/second: " << nps() << std::endl
829 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
831 p.do_move(ss[0].pv[0], st);
832 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
833 << std::endl << std::endl;
835 return rml.get_move_score(0);
839 // root_search() is the function which searches the root node. It is
840 // similar to search_pv except that it uses a different move ordering
841 // scheme (perhaps we should try to use this at internal PV nodes, too?)
842 // and prints some information to the standard output.
844 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
846 Value oldAlpha = alpha;
848 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
850 // Loop through all the moves in the root move list
851 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
855 // We failed high, invalidate and skip next moves, leave node-counters
856 // and beta-counters as they are and quickly return, we will try to do
857 // a research at the next iteration with a bigger aspiration window.
858 rml.set_move_score(i, -VALUE_INFINITE);
866 RootMoveNumber = i + 1;
869 // Remember the node count before the move is searched. The node counts
870 // are used to sort the root moves at the next iteration.
871 nodes = nodes_searched();
873 // Reset beta cut-off counters
876 // Pick the next root move, and print the move and the move number to
877 // the standard output.
878 move = ss[0].currentMove = rml.get_move(i);
879 if (current_search_time() >= 1000)
880 std::cout << "info currmove " << move
881 << " currmovenumber " << i + 1 << std::endl;
883 // Decide search depth for this move
885 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
886 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
888 // Make the move, and search it
889 pos.do_move(move, st, dcCandidates);
893 // Aspiration window is disabled in multi-pv case
895 alpha = -VALUE_INFINITE;
897 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
898 // If the value has dropped a lot compared to the last iteration,
899 // set the boolean variable Problem to true. This variable is used
900 // for time managment: When Problem is true, we try to complete the
901 // current iteration before playing a move.
902 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
904 if (Problem && StopOnPonderhit)
905 StopOnPonderhit = false;
909 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
912 // Fail high! Set the boolean variable FailHigh to true, and
913 // re-search the move with a big window. The variable FailHigh is
914 // used for time managment: We try to avoid aborting the search
915 // prematurely during a fail high research.
917 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
923 // Finished searching the move. If AbortSearch is true, the search
924 // was aborted because the user interrupted the search or because we
925 // ran out of time. In this case, the return value of the search cannot
926 // be trusted, and we break out of the loop without updating the best
931 // Remember the node count for this move. The node counts are used to
932 // sort the root moves at the next iteration.
933 rml.set_move_nodes(i, nodes_searched() - nodes);
935 // Remember the beta-cutoff statistics
937 BetaCounter.read(pos.side_to_move(), our, their);
938 rml.set_beta_counters(i, our, their);
940 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
942 if (value <= alpha && i >= MultiPV)
943 rml.set_move_score(i, -VALUE_INFINITE);
946 // PV move or new best move!
949 rml.set_move_score(i, value);
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)
964 << " time " << current_search_time()
965 << " nodes " << nodes_searched()
969 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
970 std::cout << ss[0].pv[j] << " ";
972 std::cout << std::endl;
975 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
981 // Reset the global variable Problem to false if the value isn't too
982 // far below the final value from the last iteration.
983 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
989 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
992 std::cout << "info multipv " << j + 1
993 << " score " << value_to_string(rml.get_move_score(j))
994 << " depth " << ((j <= i)? Iteration : Iteration - 1)
995 << " time " << current_search_time()
996 << " nodes " << nodes_searched()
1000 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1001 std::cout << rml.get_move_pv(j, k) << " ";
1003 std::cout << std::endl;
1005 alpha = rml.get_move_score(Min(i, MultiPV-1));
1007 } // New best move case
1009 assert(alpha >= oldAlpha);
1011 FailLow = (alpha == oldAlpha);
1017 // search_pv() is the main search function for PV nodes.
1019 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1020 Depth depth, int ply, int threadID) {
1022 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1023 assert(beta > alpha && beta <= VALUE_INFINITE);
1024 assert(ply >= 0 && ply < PLY_MAX);
1025 assert(threadID >= 0 && threadID < ActiveThreads);
1028 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1030 // Initialize, and make an early exit in case of an aborted search,
1031 // an instant draw, maximum ply reached, etc.
1032 init_node(ss, ply, threadID);
1034 // After init_node() that calls poll()
1035 if (AbortSearch || thread_should_stop(threadID))
1043 if (ply >= PLY_MAX - 1)
1044 return evaluate(pos, ei, threadID);
1046 // Mate distance pruning
1047 Value oldAlpha = alpha;
1048 alpha = Max(value_mated_in(ply), alpha);
1049 beta = Min(value_mate_in(ply+1), beta);
1053 // Transposition table lookup. At PV nodes, we don't use the TT for
1054 // pruning, but only for move ordering.
1055 const TTEntry* tte = TT.retrieve(pos.get_key());
1056 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1058 // Go with internal iterative deepening if we don't have a TT move
1059 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1061 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1062 ttMove = ss[ply].pv[ply];
1065 // Initialize a MovePicker object for the current position, and prepare
1066 // to search all moves
1067 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1069 Move move, movesSearched[256];
1071 Value value, bestValue = -VALUE_INFINITE;
1072 Bitboard dcCandidates = mp.discovered_check_candidates();
1073 Color us = pos.side_to_move();
1074 bool isCheck = pos.is_check();
1075 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1077 // Loop through all legal moves until no moves remain or a beta cutoff
1079 while ( alpha < beta
1080 && (move = mp.get_next_move()) != MOVE_NONE
1081 && !thread_should_stop(threadID))
1083 assert(move_is_ok(move));
1085 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1086 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1087 bool moveIsCapture = pos.move_is_capture(move);
1089 movesSearched[moveCount++] = ss[ply].currentMove = move;
1091 // Decide the new search depth
1093 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1094 Depth newDepth = depth - OnePly + ext;
1096 // Make and search the move
1098 pos.do_move(move, st, dcCandidates);
1100 if (moveCount == 1) // The first move in list is the PV
1101 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1104 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1105 // if the move fails high will be re-searched at full depth.
1106 if ( depth >= 2*OnePly
1107 && moveCount >= LMRPVMoves
1110 && !move_promotion(move)
1111 && !move_is_castle(move)
1112 && !move_is_killer(move, ss[ply]))
1114 ss[ply].reduction = OnePly;
1115 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1118 value = alpha + 1; // Just to trigger next condition
1120 if (value > alpha) // Go with full depth non-pv search
1122 ss[ply].reduction = Depth(0);
1123 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1124 if (value > alpha && value < beta)
1126 // When the search fails high at ply 1 while searching the first
1127 // move at the root, set the flag failHighPly1. This is used for
1128 // time managment: We don't want to stop the search early in
1129 // such cases, because resolving the fail high at ply 1 could
1130 // result in a big drop in score at the root.
1131 if (ply == 1 && RootMoveNumber == 1)
1132 Threads[threadID].failHighPly1 = true;
1134 // A fail high occurred. Re-search at full window (pv search)
1135 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1136 Threads[threadID].failHighPly1 = false;
1140 pos.undo_move(move);
1142 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1145 if (value > bestValue)
1152 if (value == value_mate_in(ply + 1))
1153 ss[ply].mateKiller = move;
1155 // If we are at ply 1, and we are searching the first root move at
1156 // ply 0, set the 'Problem' variable if the score has dropped a lot
1157 // (from the computer's point of view) since the previous iteration:
1160 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1165 if ( ActiveThreads > 1
1167 && depth >= MinimumSplitDepth
1169 && idle_thread_exists(threadID)
1171 && !thread_should_stop(threadID)
1172 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1173 &moveCount, &mp, dcCandidates, threadID, true))
1177 // All legal moves have been searched. A special case: If there were
1178 // no legal moves, it must be mate or stalemate:
1180 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1182 // If the search is not aborted, update the transposition table,
1183 // history counters, and killer moves.
1184 if (AbortSearch || thread_should_stop(threadID))
1187 if (bestValue <= oldAlpha)
1188 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1190 else if (bestValue >= beta)
1192 BetaCounter.add(pos.side_to_move(), depth, threadID);
1193 Move m = ss[ply].pv[ply];
1194 if (ok_to_history(pos, m)) // Only non capture moves are considered
1196 update_history(pos, m, depth, movesSearched, moveCount);
1197 update_killers(m, ss[ply]);
1199 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1202 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1208 // search() is the search function for zero-width nodes.
1210 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1211 int ply, bool allowNullmove, int threadID) {
1213 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1214 assert(ply >= 0 && ply < PLY_MAX);
1215 assert(threadID >= 0 && threadID < ActiveThreads);
1218 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1220 // Initialize, and make an early exit in case of an aborted search,
1221 // an instant draw, maximum ply reached, etc.
1222 init_node(ss, ply, threadID);
1224 // After init_node() that calls poll()
1225 if (AbortSearch || thread_should_stop(threadID))
1233 if (ply >= PLY_MAX - 1)
1234 return evaluate(pos, ei, threadID);
1236 // Mate distance pruning
1237 if (value_mated_in(ply) >= beta)
1240 if (value_mate_in(ply + 1) < beta)
1243 // Transposition table lookup
1244 const TTEntry* tte = TT.retrieve(pos.get_key());
1245 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1247 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1249 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1250 return value_from_tt(tte->value(), ply);
1253 Value approximateEval = quick_evaluate(pos);
1254 bool mateThreat = false;
1255 bool isCheck = pos.is_check();
1261 && !value_is_mate(beta)
1262 && ok_to_do_nullmove(pos)
1263 && approximateEval >= beta - NullMoveMargin)
1265 ss[ply].currentMove = MOVE_NULL;
1268 pos.do_null_move(st);
1269 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1271 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1273 pos.undo_null_move();
1275 if (value_is_mate(nullValue))
1277 /* Do not return unproven mates */
1279 else if (nullValue >= beta)
1281 if (depth < 6 * OnePly)
1284 // Do zugzwang verification search
1285 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1289 // The null move failed low, which means that we may be faced with
1290 // some kind of threat. If the previous move was reduced, check if
1291 // the move that refuted the null move was somehow connected to the
1292 // move which was reduced. If a connection is found, return a fail
1293 // low score (which will cause the reduced move to fail high in the
1294 // parent node, which will trigger a re-search with full depth).
1295 if (nullValue == value_mated_in(ply + 2))
1298 ss[ply].threatMove = ss[ply + 1].currentMove;
1299 if ( depth < ThreatDepth
1300 && ss[ply - 1].reduction
1301 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1305 // Null move search not allowed, try razoring
1306 else if ( !value_is_mate(beta)
1307 && depth < RazorDepth
1308 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1309 && ss[ply - 1].currentMove != MOVE_NULL
1310 && ttMove == MOVE_NONE
1311 && !pos.has_pawn_on_7th(pos.side_to_move()))
1313 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1314 if (v < beta - RazorMargins[int(depth) - 2])
1318 // Go with internal iterative deepening if we don't have a TT move
1319 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1320 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1322 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1323 ttMove = ss[ply].pv[ply];
1326 // Initialize a MovePicker object for the current position, and prepare
1327 // to search all moves:
1328 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1330 Move move, movesSearched[256];
1332 Value value, bestValue = -VALUE_INFINITE;
1333 Bitboard dcCandidates = mp.discovered_check_candidates();
1334 Value futilityValue = VALUE_NONE;
1335 bool useFutilityPruning = UseFutilityPruning
1336 && depth < SelectiveDepth
1339 // Loop through all legal moves until no moves remain or a beta cutoff
1341 while ( bestValue < beta
1342 && (move = mp.get_next_move()) != MOVE_NONE
1343 && !thread_should_stop(threadID))
1345 assert(move_is_ok(move));
1347 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1348 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1349 bool moveIsCapture = pos.move_is_capture(move);
1351 movesSearched[moveCount++] = ss[ply].currentMove = move;
1353 // Decide the new search depth
1355 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1356 Depth newDepth = depth - OnePly + ext;
1359 if ( useFutilityPruning
1362 && !move_promotion(move))
1364 // History pruning. See ok_to_prune() definition
1365 if ( moveCount >= 2 + int(depth)
1366 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1369 // Value based pruning
1370 if (approximateEval < beta)
1372 if (futilityValue == VALUE_NONE)
1373 futilityValue = evaluate(pos, ei, threadID)
1374 + FutilityMargins[int(depth) - 2];
1376 if (futilityValue < beta)
1378 if (futilityValue > bestValue)
1379 bestValue = futilityValue;
1385 // Make and search the move
1387 pos.do_move(move, st, dcCandidates);
1389 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1390 // if the move fails high will be re-searched at full depth.
1391 if ( depth >= 2*OnePly
1392 && moveCount >= LMRNonPVMoves
1395 && !move_promotion(move)
1396 && !move_is_castle(move)
1397 && !move_is_killer(move, ss[ply]))
1399 ss[ply].reduction = OnePly;
1400 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1403 value = beta; // Just to trigger next condition
1405 if (value >= beta) // Go with full depth non-pv search
1407 ss[ply].reduction = Depth(0);
1408 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1410 pos.undo_move(move);
1412 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1415 if (value > bestValue)
1421 if (value == value_mate_in(ply + 1))
1422 ss[ply].mateKiller = move;
1426 if ( ActiveThreads > 1
1428 && depth >= MinimumSplitDepth
1430 && idle_thread_exists(threadID)
1432 && !thread_should_stop(threadID)
1433 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1434 &mp, dcCandidates, threadID, false))
1438 // All legal moves have been searched. A special case: If there were
1439 // no legal moves, it must be mate or stalemate.
1441 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1443 // If the search is not aborted, update the transposition table,
1444 // history counters, and killer moves.
1445 if (AbortSearch || thread_should_stop(threadID))
1448 if (bestValue < beta)
1449 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1452 BetaCounter.add(pos.side_to_move(), depth, threadID);
1453 Move m = ss[ply].pv[ply];
1454 if (ok_to_history(pos, m)) // Only non capture moves are considered
1456 update_history(pos, m, depth, movesSearched, moveCount);
1457 update_killers(m, ss[ply]);
1459 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1462 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1468 // qsearch() is the quiescence search function, which is called by the main
1469 // search function when the remaining depth is zero (or, to be more precise,
1470 // less than OnePly).
1472 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1473 Depth depth, int ply, int threadID) {
1475 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1476 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1478 assert(ply >= 0 && ply < PLY_MAX);
1479 assert(threadID >= 0 && threadID < ActiveThreads);
1481 // Initialize, and make an early exit in case of an aborted search,
1482 // an instant draw, maximum ply reached, etc.
1483 init_node(ss, ply, threadID);
1485 // After init_node() that calls poll()
1486 if (AbortSearch || thread_should_stop(threadID))
1492 // Transposition table lookup, only when not in PV
1493 TTEntry* tte = NULL;
1494 bool pvNode = (beta - alpha != 1);
1497 tte = TT.retrieve(pos.get_key());
1498 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1500 assert(tte->type() != VALUE_TYPE_EVAL);
1502 return value_from_tt(tte->value(), ply);
1505 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1507 // Evaluate the position statically
1510 bool isCheck = pos.is_check();
1511 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1514 staticValue = -VALUE_INFINITE;
1516 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1518 // Use the cached evaluation score if possible
1519 assert(tte->value() == evaluate(pos, ei, threadID));
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_EVAL, 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, pvNode, ttMove, EmptySearchStack, depth);
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;
1567 if ( UseQSearchFutilityPruning
1571 && !move_promotion(move)
1572 && !pos.move_is_check(move, dcCandidates)
1573 && !pos.move_is_passed_pawn_push(move))
1575 Value futilityValue = staticValue
1576 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1577 pos.endgame_value_of_piece_on(move_to(move)))
1578 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1580 + ei.futilityMargin;
1582 if (futilityValue < alpha)
1584 if (futilityValue > bestValue)
1585 bestValue = futilityValue;
1590 // Don't search captures and checks with negative SEE values
1592 && !move_promotion(move)
1593 && (pos.midgame_value_of_piece_on(move_from(move)) >
1594 pos.midgame_value_of_piece_on(move_to(move)))
1595 && pos.see(move) < 0)
1598 // Make and search the move.
1600 pos.do_move(move, st, dcCandidates);
1601 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1602 pos.undo_move(move);
1604 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1607 if (value > bestValue)
1618 // All legal moves have been searched. A special case: If we're in check
1619 // and no legal moves were found, it is checkmate:
1620 if (pos.is_check() && moveCount == 0) // Mate!
1621 return value_mated_in(ply);
1623 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1625 // Update transposition table
1626 Move m = ss[ply].pv[ply];
1629 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1630 if (bestValue < beta)
1631 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1633 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1636 // Update killers only for good check moves
1637 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1638 update_killers(m, ss[ply]);
1644 // sp_search() is used to search from a split point. This function is called
1645 // by each thread working at the split point. It is similar to the normal
1646 // search() function, but simpler. Because we have already probed the hash
1647 // table, done a null move search, and searched the first move before
1648 // splitting, we don't have to repeat all this work in sp_search(). We
1649 // also don't need to store anything to the hash table here: This is taken
1650 // care of after we return from the split point.
1652 void sp_search(SplitPoint *sp, int threadID) {
1654 assert(threadID >= 0 && threadID < ActiveThreads);
1655 assert(ActiveThreads > 1);
1657 Position pos = Position(sp->pos);
1658 SearchStack *ss = sp->sstack[threadID];
1661 bool isCheck = pos.is_check();
1662 bool useFutilityPruning = UseFutilityPruning
1663 && 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_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_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_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 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1900 void BetaCounterType::add(Color us, Depth d, int threadID) {
1902 // Weighted count based on depth
1903 hits[threadID][us] += int(d);
1906 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1909 for (int i = 0; i < THREAD_MAX; i++)
1912 their += hits[i][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 int lm_count = generate_legal_moves(pos, mlist);
1950 // Add each move to the moves[] array
1951 for (int i = 0; i < lm_count; i++)
1953 bool includeMove = includeAllMoves;
1955 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1956 includeMove = (searchMoves[k] == mlist[i].move);
1961 // Find a quick score for the move
1963 SearchStack ss[PLY_MAX_PLUS_2];
1965 moves[count].move = mlist[i].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) {
2076 assert(ply >= 0 && ply < PLY_MAX);
2077 assert(threadID >= 0 && threadID < ActiveThreads);
2079 Threads[threadID].nodes++;
2083 if(NodesSincePoll >= NodesBetweenPolls) {
2090 ss[ply+2].initKillers();
2092 if(Threads[threadID].printCurrentLine)
2093 print_current_line(ss, ply, threadID);
2097 // update_pv() is called whenever a search returns a value > alpha. It
2098 // updates the PV in the SearchStack object corresponding to the current
2101 void update_pv(SearchStack ss[], int ply) {
2102 assert(ply >= 0 && ply < PLY_MAX);
2104 ss[ply].pv[ply] = ss[ply].currentMove;
2106 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2107 ss[ply].pv[p] = ss[ply+1].pv[p];
2108 ss[ply].pv[p] = MOVE_NONE;
2112 // sp_update_pv() is a variant of update_pv for use at split points. The
2113 // difference between the two functions is that sp_update_pv also updates
2114 // the PV at the parent node.
2116 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2117 assert(ply >= 0 && ply < PLY_MAX);
2119 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2121 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2122 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2123 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2127 // connected_moves() tests whether two moves are 'connected' in the sense
2128 // that the first move somehow made the second move possible (for instance
2129 // if the moving piece is the same in both moves). The first move is
2130 // assumed to be the move that was made to reach the current position, while
2131 // the second move is assumed to be a move from the current position.
2133 bool connected_moves(const Position &pos, Move m1, Move m2) {
2134 Square f1, t1, f2, t2;
2136 assert(move_is_ok(m1));
2137 assert(move_is_ok(m2));
2142 // Case 1: The moving piece is the same in both moves.
2148 // Case 2: The destination square for m2 was vacated by m1.
2154 // Case 3: Moving through the vacated square:
2155 if(piece_is_slider(pos.piece_on(f2)) &&
2156 bit_is_set(squares_between(f2, t2), f1))
2159 // Case 4: The destination square for m2 is attacked by the moving piece
2161 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2164 // Case 5: Discovered check, checking piece is the piece moved in m1:
2165 if(piece_is_slider(pos.piece_on(t1)) &&
2166 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2168 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2170 Bitboard occ = pos.occupied_squares();
2171 Color us = pos.side_to_move();
2172 Square ksq = pos.king_square(us);
2173 clear_bit(&occ, f2);
2174 if(pos.type_of_piece_on(t1) == BISHOP) {
2175 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2178 else if(pos.type_of_piece_on(t1) == ROOK) {
2179 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2183 assert(pos.type_of_piece_on(t1) == QUEEN);
2184 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2193 // value_is_mate() checks if the given value is a mate one
2194 // eventually compensated for the ply.
2196 bool value_is_mate(Value value) {
2198 assert(abs(value) <= VALUE_INFINITE);
2200 return value <= value_mated_in(PLY_MAX)
2201 || value >= value_mate_in(PLY_MAX);
2205 // move_is_killer() checks if the given move is among the
2206 // killer moves of that ply.
2208 bool move_is_killer(Move m, const SearchStack& ss) {
2210 const Move* k = ss.killers;
2211 for (int i = 0; i < KILLER_MAX; i++, k++)
2219 // extension() decides whether a move should be searched with normal depth,
2220 // or with extended depth. Certain classes of moves (checking moves, in
2221 // particular) are searched with bigger depth than ordinary moves and in
2222 // any case are marked as 'dangerous'. Note that also if a move is not
2223 // extended, as example because the corresponding UCI option is set to zero,
2224 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2226 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2227 bool singleReply, bool mateThreat, bool* dangerous) {
2229 assert(m != MOVE_NONE);
2231 Depth result = Depth(0);
2232 *dangerous = check || singleReply || mateThreat;
2235 result += CheckExtension[pvNode];
2238 result += SingleReplyExtension[pvNode];
2241 result += MateThreatExtension[pvNode];
2243 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2245 if (pos.move_is_pawn_push_to_7th(m))
2247 result += PawnPushTo7thExtension[pvNode];
2250 if (pos.move_is_passed_pawn_push(m))
2252 result += PassedPawnExtension[pvNode];
2258 && pos.type_of_piece_on(move_to(m)) != PAWN
2259 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2260 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2261 && !move_promotion(m)
2264 result += PawnEndgameExtension[pvNode];
2270 && pos.type_of_piece_on(move_to(m)) != PAWN
2277 return Min(result, OnePly);
2281 // ok_to_do_nullmove() looks at the current position and decides whether
2282 // doing a 'null move' should be allowed. In order to avoid zugzwang
2283 // problems, null moves are not allowed when the side to move has very
2284 // little material left. Currently, the test is a bit too simple: Null
2285 // moves are avoided only when the side to move has only pawns left. It's
2286 // probably a good idea to avoid null moves in at least some more
2287 // complicated endgames, e.g. KQ vs KR. FIXME
2289 bool ok_to_do_nullmove(const Position &pos) {
2290 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2296 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2297 // non-tactical moves late in the move list close to the leaves are
2298 // candidates for pruning.
2300 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2301 Square mfrom, mto, tfrom, tto;
2303 assert(move_is_ok(m));
2304 assert(threat == MOVE_NONE || move_is_ok(threat));
2305 assert(!move_promotion(m));
2306 assert(!pos.move_is_check(m));
2307 assert(!pos.move_is_capture(m));
2308 assert(!pos.move_is_passed_pawn_push(m));
2309 assert(d >= OnePly);
2311 mfrom = move_from(m);
2313 tfrom = move_from(threat);
2314 tto = move_to(threat);
2316 // Case 1: Castling moves are never pruned.
2317 if (move_is_castle(m))
2320 // Case 2: Don't prune moves which move the threatened piece
2321 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2324 // Case 3: If the threatened piece has value less than or equal to the
2325 // value of the threatening piece, don't prune move which defend it.
2326 if ( !PruneDefendingMoves
2327 && threat != MOVE_NONE
2328 && pos.move_is_capture(threat)
2329 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2330 || pos.type_of_piece_on(tfrom) == KING)
2331 && pos.move_attacks_square(m, tto))
2334 // Case 4: Don't prune moves with good history.
2335 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2338 // Case 5: If the moving piece in the threatened move is a slider, don't
2339 // prune safe moves which block its ray.
2340 if ( !PruneBlockingMoves
2341 && threat != MOVE_NONE
2342 && piece_is_slider(pos.piece_on(tfrom))
2343 && bit_is_set(squares_between(tfrom, tto), mto)
2351 // ok_to_use_TT() returns true if a transposition table score
2352 // can be used at a given point in search.
2354 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2356 Value v = value_from_tt(tte->value(), ply);
2358 return ( tte->depth() >= depth
2359 || v >= Max(value_mate_in(100), beta)
2360 || v < Min(value_mated_in(100), beta))
2362 && ( (is_lower_bound(tte->type()) && v >= beta)
2363 || (is_upper_bound(tte->type()) && v < beta));
2367 // ok_to_history() returns true if a move m can be stored
2368 // in history. Should be a non capturing move nor a promotion.
2370 bool ok_to_history(const Position& pos, Move m) {
2372 return !pos.move_is_capture(m) && !move_promotion(m);
2376 // update_history() registers a good move that produced a beta-cutoff
2377 // in history and marks as failures all the other moves of that ply.
2379 void update_history(const Position& pos, Move m, Depth depth,
2380 Move movesSearched[], int moveCount) {
2382 H.success(pos.piece_on(move_from(m)), m, depth);
2384 for (int i = 0; i < moveCount - 1; i++)
2386 assert(m != movesSearched[i]);
2387 if (ok_to_history(pos, movesSearched[i]))
2388 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2393 // update_killers() add a good move that produced a beta-cutoff
2394 // among the killer moves of that ply.
2396 void update_killers(Move m, SearchStack& ss) {
2398 if (m == ss.killers[0])
2401 for (int i = KILLER_MAX - 1; i > 0; i--)
2402 ss.killers[i] = ss.killers[i - 1];
2407 // fail_high_ply_1() checks if some thread is currently resolving a fail
2408 // high at ply 1 at the node below the first root node. This information
2409 // is used for time managment.
2411 bool fail_high_ply_1() {
2412 for(int i = 0; i < ActiveThreads; i++)
2413 if(Threads[i].failHighPly1)
2419 // current_search_time() returns the number of milliseconds which have passed
2420 // since the beginning of the current search.
2422 int current_search_time() {
2423 return get_system_time() - SearchStartTime;
2427 // nps() computes the current nodes/second count.
2430 int t = current_search_time();
2431 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2435 // poll() performs two different functions: It polls for user input, and it
2436 // looks at the time consumed so far and decides if it's time to abort the
2441 static int lastInfoTime;
2442 int t = current_search_time();
2447 // We are line oriented, don't read single chars
2448 std::string command;
2449 if (!std::getline(std::cin, command))
2452 if (command == "quit")
2455 PonderSearch = false;
2459 else if(command == "stop")
2462 PonderSearch = false;
2464 else if(command == "ponderhit")
2467 // Print search information
2471 else if (lastInfoTime > t)
2472 // HACK: Must be a new search where we searched less than
2473 // NodesBetweenPolls nodes during the first second of search.
2476 else if (t - lastInfoTime >= 1000)
2483 if (dbg_show_hit_rate)
2484 dbg_print_hit_rate();
2486 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2487 << " time " << t << " hashfull " << TT.full() << std::endl;
2488 lock_release(&IOLock);
2489 if (ShowCurrentLine)
2490 Threads[0].printCurrentLine = true;
2492 // Should we stop the search?
2496 bool overTime = t > AbsoluteMaxSearchTime
2497 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2498 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2499 && t > 6*(MaxSearchTime + ExtraSearchTime));
2501 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2502 || (ExactMaxTime && t >= ExactMaxTime)
2503 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2508 // ponderhit() is called when the program is pondering (i.e. thinking while
2509 // it's the opponent's turn to move) in order to let the engine know that
2510 // it correctly predicted the opponent's move.
2513 int t = current_search_time();
2514 PonderSearch = false;
2515 if(Iteration >= 3 &&
2516 (!InfiniteSearch && (StopOnPonderhit ||
2517 t > AbsoluteMaxSearchTime ||
2518 (RootMoveNumber == 1 &&
2519 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2520 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2521 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2526 // print_current_line() prints the current line of search for a given
2527 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2529 void print_current_line(SearchStack ss[], int ply, int threadID) {
2530 assert(ply >= 0 && ply < PLY_MAX);
2531 assert(threadID >= 0 && threadID < ActiveThreads);
2533 if(!Threads[threadID].idle) {
2535 std::cout << "info currline " << (threadID + 1);
2536 for(int p = 0; p < ply; p++)
2537 std::cout << " " << ss[p].currentMove;
2538 std::cout << std::endl;
2539 lock_release(&IOLock);
2541 Threads[threadID].printCurrentLine = false;
2542 if(threadID + 1 < ActiveThreads)
2543 Threads[threadID + 1].printCurrentLine = true;
2547 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2548 // while the program is pondering. The point is to work around a wrinkle in
2549 // the UCI protocol: When pondering, the engine is not allowed to give a
2550 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2551 // We simply wait here until one of these commands is sent, and return,
2552 // after which the bestmove and pondermove will be printed (in id_loop()).
2554 void wait_for_stop_or_ponderhit() {
2556 std::string command;
2560 if (!std::getline(std::cin, command))
2563 if (command == "quit")
2568 else if(command == "ponderhit" || command == "stop")
2574 // idle_loop() is where the threads are parked when they have no work to do.
2575 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2576 // object for which the current thread is the master.
2578 void idle_loop(int threadID, SplitPoint *waitSp) {
2579 assert(threadID >= 0 && threadID < THREAD_MAX);
2581 Threads[threadID].running = true;
2584 if(AllThreadsShouldExit && threadID != 0)
2587 // If we are not thinking, wait for a condition to be signaled instead
2588 // of wasting CPU time polling for work:
2589 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2590 #if !defined(_MSC_VER)
2591 pthread_mutex_lock(&WaitLock);
2592 if(Idle || threadID >= ActiveThreads)
2593 pthread_cond_wait(&WaitCond, &WaitLock);
2594 pthread_mutex_unlock(&WaitLock);
2596 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2600 // If this thread has been assigned work, launch a search:
2601 if(Threads[threadID].workIsWaiting) {
2602 Threads[threadID].workIsWaiting = false;
2603 if(Threads[threadID].splitPoint->pvNode)
2604 sp_search_pv(Threads[threadID].splitPoint, threadID);
2606 sp_search(Threads[threadID].splitPoint, threadID);
2607 Threads[threadID].idle = true;
2610 // If this thread is the master of a split point and all threads have
2611 // finished their work at this split point, return from the idle loop:
2612 if(waitSp != NULL && waitSp->cpus == 0)
2616 Threads[threadID].running = false;
2620 // init_split_point_stack() is called during program initialization, and
2621 // initializes all split point objects.
2623 void init_split_point_stack() {
2624 for(int i = 0; i < THREAD_MAX; i++)
2625 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2626 SplitPointStack[i][j].parent = NULL;
2627 lock_init(&(SplitPointStack[i][j].lock), NULL);
2632 // destroy_split_point_stack() is called when the program exits, and
2633 // destroys all locks in the precomputed split point objects.
2635 void destroy_split_point_stack() {
2636 for(int i = 0; i < THREAD_MAX; i++)
2637 for(int j = 0; j < MaxActiveSplitPoints; j++)
2638 lock_destroy(&(SplitPointStack[i][j].lock));
2642 // thread_should_stop() checks whether the thread with a given threadID has
2643 // been asked to stop, directly or indirectly. This can happen if a beta
2644 // cutoff has occured in thre thread's currently active split point, or in
2645 // some ancestor of the current split point.
2647 bool thread_should_stop(int threadID) {
2648 assert(threadID >= 0 && threadID < ActiveThreads);
2652 if(Threads[threadID].stop)
2654 if(ActiveThreads <= 2)
2656 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2658 Threads[threadID].stop = true;
2665 // thread_is_available() checks whether the thread with threadID "slave" is
2666 // available to help the thread with threadID "master" at a split point. An
2667 // obvious requirement is that "slave" must be idle. With more than two
2668 // threads, this is not by itself sufficient: If "slave" is the master of
2669 // some active split point, it is only available as a slave to the other
2670 // threads which are busy searching the split point at the top of "slave"'s
2671 // split point stack (the "helpful master concept" in YBWC terminology).
2673 bool thread_is_available(int slave, int master) {
2674 assert(slave >= 0 && slave < ActiveThreads);
2675 assert(master >= 0 && master < ActiveThreads);
2676 assert(ActiveThreads > 1);
2678 if(!Threads[slave].idle || slave == master)
2681 if(Threads[slave].activeSplitPoints == 0)
2682 // No active split points means that the thread is available as a slave
2683 // for any other thread.
2686 if(ActiveThreads == 2)
2689 // Apply the "helpful master" concept if possible.
2690 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2697 // idle_thread_exists() tries to find an idle thread which is available as
2698 // a slave for the thread with threadID "master".
2700 bool idle_thread_exists(int master) {
2701 assert(master >= 0 && master < ActiveThreads);
2702 assert(ActiveThreads > 1);
2704 for(int i = 0; i < ActiveThreads; i++)
2705 if(thread_is_available(i, master))
2711 // split() does the actual work of distributing the work at a node between
2712 // several threads at PV nodes. If it does not succeed in splitting the
2713 // node (because no idle threads are available, or because we have no unused
2714 // split point objects), the function immediately returns false. If
2715 // splitting is possible, a SplitPoint object is initialized with all the
2716 // data that must be copied to the helper threads (the current position and
2717 // search stack, alpha, beta, the search depth, etc.), and we tell our
2718 // helper threads that they have been assigned work. This will cause them
2719 // to instantly leave their idle loops and call sp_search_pv(). When all
2720 // threads have returned from sp_search_pv (or, equivalently, when
2721 // splitPoint->cpus becomes 0), split() returns true.
2723 bool split(const Position &p, SearchStack *sstck, int ply,
2724 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2725 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2728 assert(sstck != NULL);
2729 assert(ply >= 0 && ply < PLY_MAX);
2730 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2731 assert(!pvNode || *alpha < *beta);
2732 assert(*beta <= VALUE_INFINITE);
2733 assert(depth > Depth(0));
2734 assert(master >= 0 && master < ActiveThreads);
2735 assert(ActiveThreads > 1);
2737 SplitPoint *splitPoint;
2742 // If no other thread is available to help us, or if we have too many
2743 // active split points, don't split:
2744 if(!idle_thread_exists(master) ||
2745 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2746 lock_release(&MPLock);
2750 // Pick the next available split point object from the split point stack:
2751 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2752 Threads[master].activeSplitPoints++;
2754 // Initialize the split point object:
2755 splitPoint->parent = Threads[master].splitPoint;
2756 splitPoint->finished = false;
2757 splitPoint->ply = ply;
2758 splitPoint->depth = depth;
2759 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2760 splitPoint->beta = *beta;
2761 splitPoint->pvNode = pvNode;
2762 splitPoint->dcCandidates = dcCandidates;
2763 splitPoint->bestValue = *bestValue;
2764 splitPoint->master = master;
2765 splitPoint->mp = mp;
2766 splitPoint->moves = *moves;
2767 splitPoint->cpus = 1;
2768 splitPoint->pos.copy(p);
2769 splitPoint->parentSstack = sstck;
2770 for(i = 0; i < ActiveThreads; i++)
2771 splitPoint->slaves[i] = 0;
2773 // Copy the current position and the search stack to the master thread:
2774 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2775 Threads[master].splitPoint = splitPoint;
2777 // Make copies of the current position and search stack for each thread:
2778 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2780 if(thread_is_available(i, master)) {
2781 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2782 Threads[i].splitPoint = splitPoint;
2783 splitPoint->slaves[i] = 1;
2787 // Tell the threads that they have work to do. This will make them leave
2789 for(i = 0; i < ActiveThreads; i++)
2790 if(i == master || splitPoint->slaves[i]) {
2791 Threads[i].workIsWaiting = true;
2792 Threads[i].idle = false;
2793 Threads[i].stop = false;
2796 lock_release(&MPLock);
2798 // Everything is set up. The master thread enters the idle loop, from
2799 // which it will instantly launch a search, because its workIsWaiting
2800 // slot is 'true'. We send the split point as a second parameter to the
2801 // idle loop, which means that the main thread will return from the idle
2802 // loop when all threads have finished their work at this split point
2803 // (i.e. when // splitPoint->cpus == 0).
2804 idle_loop(master, splitPoint);
2806 // We have returned from the idle loop, which means that all threads are
2807 // finished. Update alpha, beta and bestvalue, and return:
2809 if(pvNode) *alpha = splitPoint->alpha;
2810 *beta = splitPoint->beta;
2811 *bestValue = splitPoint->bestValue;
2812 Threads[master].stop = false;
2813 Threads[master].idle = false;
2814 Threads[master].activeSplitPoints--;
2815 Threads[master].splitPoint = splitPoint->parent;
2816 lock_release(&MPLock);
2822 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2823 // to start a new search from the root.
2825 void wake_sleeping_threads() {
2826 if(ActiveThreads > 1) {
2827 for(int i = 1; i < ActiveThreads; i++) {
2828 Threads[i].idle = true;
2829 Threads[i].workIsWaiting = false;
2831 #if !defined(_MSC_VER)
2832 pthread_mutex_lock(&WaitLock);
2833 pthread_cond_broadcast(&WaitCond);
2834 pthread_mutex_unlock(&WaitLock);
2836 for(int i = 1; i < THREAD_MAX; i++)
2837 SetEvent(SitIdleEvent[i]);
2843 // init_thread() is the function which is called when a new thread is
2844 // launched. It simply calls the idle_loop() function with the supplied
2845 // threadID. There are two versions of this function; one for POSIX threads
2846 // and one for Windows threads.
2848 #if !defined(_MSC_VER)
2850 void *init_thread(void *threadID) {
2851 idle_loop(*(int *)threadID, NULL);
2857 DWORD WINAPI init_thread(LPVOID threadID) {
2858 idle_loop(*(int *)threadID, NULL);