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. The counters are per thread variables to avoid
76 // concurrent accessing under SMP case.
78 struct BetaCounterType {
82 void add(Color us, Depth d, int threadID);
83 void read(Color us, int64_t& our, int64_t& their);
87 // The RootMove class is used for moves at the root at the tree. For each
88 // root move, we store a score, a node count, and a PV (really a refutation
89 // in the case of moves which fail low).
94 bool operator<(const RootMove&); // used to sort
98 int64_t nodes, cumulativeNodes;
99 Move pv[PLY_MAX_PLUS_2];
100 int64_t ourBeta, theirBeta;
104 // The RootMoveList class is essentially an array of RootMove objects, with
105 // a handful of methods for accessing the data in the individual moves.
110 RootMoveList(Position &pos, Move searchMoves[]);
111 inline Move get_move(int moveNum) const;
112 inline Value get_move_score(int moveNum) const;
113 inline void set_move_score(int moveNum, Value score);
114 inline void set_move_nodes(int moveNum, int64_t nodes);
115 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
116 void set_move_pv(int moveNum, const Move pv[]);
117 inline Move get_move_pv(int moveNum, int i) const;
118 inline int64_t get_move_cumulative_nodes(int moveNum) const;
119 inline int move_count() const;
120 Move scan_for_easy_move() const;
122 void sort_multipv(int n);
125 static const int MaxRootMoves = 500;
126 RootMove moves[MaxRootMoves];
133 // Search depth at iteration 1
134 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
136 // Depth limit for selective search
137 const Depth SelectiveDepth = 7 * OnePly;
139 // Use internal iterative deepening?
140 const bool UseIIDAtPVNodes = true;
141 const bool UseIIDAtNonPVNodes = false;
143 // Internal iterative deepening margin. At Non-PV moves, when
144 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
145 // when the static evaluation is at most IIDMargin below beta.
146 const Value IIDMargin = Value(0x100);
148 // Easy move margin. An easy move candidate must be at least this much
149 // better than the second best move.
150 const Value EasyMoveMargin = Value(0x200);
152 // Problem margin. If the score of the first move at iteration N+1 has
153 // dropped by more than this since iteration N, the boolean variable
154 // "Problem" is set to true, which will make the program spend some extra
155 // time looking for a better move.
156 const Value ProblemMargin = Value(0x28);
158 // No problem margin. If the boolean "Problem" is true, and a new move
159 // is found at the root which is less than NoProblemMargin worse than the
160 // best move from the previous iteration, Problem is set back to false.
161 const Value NoProblemMargin = Value(0x14);
163 // Null move margin. A null move search will not be done if the approximate
164 // evaluation of the position is more than NullMoveMargin below beta.
165 const Value NullMoveMargin = Value(0x300);
167 // Pruning criterions. See the code and comments in ok_to_prune() to
168 // understand their precise meaning.
169 const bool PruneEscapeMoves = false;
170 const bool PruneDefendingMoves = false;
171 const bool PruneBlockingMoves = false;
173 // Margins for futility pruning in the quiescence search, and at frontier
174 // and near frontier nodes
175 const Value FutilityMarginQS = Value(0x80);
177 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
178 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
179 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
180 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
182 const Depth RazorDepth = 4*OnePly;
184 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
185 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
187 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
188 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
191 /// Variables initialized from UCI options
193 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
194 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
196 // Depth limit for use of dynamic threat detection
197 Depth ThreatDepth; // heavy SMP read access
199 // Last seconds noise filtering (LSN)
200 bool UseLSNFiltering;
201 bool looseOnTime = false;
202 int LSNTime; // In milliseconds
205 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
206 // There is heavy SMP read access on these arrays
207 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
208 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
210 // Iteration counters
212 BetaCounterType BetaCounter; // has per-thread internal data
214 // Scores and number of times the best move changed for each iteration
215 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
216 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
221 // Time managment variables
223 int MaxNodes, MaxDepth;
224 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
229 bool StopOnPonderhit;
230 bool AbortSearch; // heavy SMP read access
235 bool PonderingEnabled;
238 // Show current line?
239 bool ShowCurrentLine;
243 std::ofstream LogFile;
245 // MP related variables
246 Depth MinimumSplitDepth;
247 int MaxThreadsPerSplitPoint;
248 Thread Threads[THREAD_MAX];
250 bool AllThreadsShouldExit = false;
251 const int MaxActiveSplitPoints = 8;
252 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
255 #if !defined(_MSC_VER)
256 pthread_cond_t WaitCond;
257 pthread_mutex_t WaitLock;
259 HANDLE SitIdleEvent[THREAD_MAX];
262 // Node counters, used only by thread[0] but try to keep in different
263 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
265 int NodesBetweenPolls = 30000;
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, const History& H);
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, History& H, 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.
335 // SearchStack::init() initializes a search stack. Used at the beginning of a
336 // new search from the root.
337 void SearchStack::init(int ply) {
339 pv[ply] = pv[ply + 1] = MOVE_NONE;
340 currentMove = threatMove = MOVE_NONE;
341 reduction = Depth(0);
344 void SearchStack::initKillers() {
346 mateKiller = MOVE_NONE;
347 for (int i = 0; i < KILLER_MAX; i++)
348 killers[i] = MOVE_NONE;
356 /// think() is the external interface to Stockfish's search, and is called when
357 /// the program receives the UCI 'go' command. It initializes various
358 /// search-related global variables, and calls root_search(). It returns false
359 /// when a quit command is received during the search.
361 bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
362 int time[], int increment[], int movesToGo, int maxDepth,
363 int maxNodes, int maxTime, Move searchMoves[]) {
365 // Look for a book move
366 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
369 if (get_option_value_string("Book File") != OpeningBook.file_name())
370 OpeningBook.open("book.bin");
372 bookMove = OpeningBook.get_move(pos);
373 if (bookMove != MOVE_NONE)
375 std::cout << "bestmove " << bookMove << std::endl;
380 // Initialize global search variables
382 SearchStartTime = get_system_time();
383 EasyMove = MOVE_NONE;
384 for (int i = 0; i < THREAD_MAX; i++)
386 Threads[i].nodes = 0ULL;
387 Threads[i].failHighPly1 = false;
390 InfiniteSearch = infinite;
391 PonderSearch = ponder;
392 StopOnPonderhit = false;
398 ExactMaxTime = maxTime;
400 // Read UCI option values
401 TT.set_size(get_option_value_int("Hash"));
402 if (button_was_pressed("Clear Hash"))
405 PonderingEnabled = get_option_value_bool("Ponder");
406 MultiPV = get_option_value_int("MultiPV");
408 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
409 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
411 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
412 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
414 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
415 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
417 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
418 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
420 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
421 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
423 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
424 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
426 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
427 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
428 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
430 Chess960 = get_option_value_bool("UCI_Chess960");
431 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
432 UseLogFile = get_option_value_bool("Use Search Log");
434 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
436 UseLSNFiltering = get_option_value_bool("LSN filtering");
437 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
438 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
440 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
441 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
443 read_weights(pos.side_to_move());
445 int newActiveThreads = get_option_value_int("Threads");
446 if (newActiveThreads != ActiveThreads)
448 ActiveThreads = newActiveThreads;
449 init_eval(ActiveThreads);
452 // Wake up sleeping threads:
453 wake_sleeping_threads();
455 for (int i = 1; i < ActiveThreads; i++)
456 assert(thread_is_available(i, 0));
458 // Set thinking time:
459 int myTime = time[side_to_move];
460 int myIncrement = increment[side_to_move];
462 if (!movesToGo) // Sudden death time control
466 MaxSearchTime = myTime / 30 + myIncrement;
467 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
468 } else { // Blitz game without increment
469 MaxSearchTime = myTime / 30;
470 AbsoluteMaxSearchTime = myTime / 8;
473 else // (x moves) / (y minutes)
477 MaxSearchTime = myTime / 2;
478 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
480 MaxSearchTime = myTime / Min(movesToGo, 20);
481 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
485 if (PonderingEnabled)
487 MaxSearchTime += MaxSearchTime / 4;
488 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
491 // Fixed depth or fixed number of nodes?
494 InfiniteSearch = true; // HACK
499 NodesBetweenPolls = Min(MaxNodes, 30000);
500 InfiniteSearch = true; // HACK
503 NodesBetweenPolls = 30000;
506 // Write information to search log file:
508 LogFile << "Searching: " << pos.to_fen() << std::endl
509 << "infinite: " << infinite
510 << " ponder: " << ponder
511 << " time: " << myTime
512 << " increment: " << myIncrement
513 << " moves to go: " << movesToGo << std::endl;
516 // We're ready to start thinking. Call the iterative deepening loop
520 Value v = id_loop(pos, searchMoves);
521 looseOnTime = ( UseLSNFiltering
528 looseOnTime = false; // reset for next match
529 while (SearchStartTime + myTime + 1000 > get_system_time())
531 id_loop(pos, searchMoves); // to fail gracefully
542 /// init_threads() is called during startup. It launches all helper threads,
543 /// and initializes the split point stack and the global locks and condition
546 void init_threads() {
550 #if !defined(_MSC_VER)
551 pthread_t pthread[1];
554 for (i = 0; i < THREAD_MAX; i++)
555 Threads[i].activeSplitPoints = 0;
557 // Initialize global locks:
558 lock_init(&MPLock, NULL);
559 lock_init(&IOLock, NULL);
561 init_split_point_stack();
563 #if !defined(_MSC_VER)
564 pthread_mutex_init(&WaitLock, NULL);
565 pthread_cond_init(&WaitCond, NULL);
567 for (i = 0; i < THREAD_MAX; i++)
568 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
571 // All threads except the main thread should be initialized to idle state
572 for (i = 1; i < THREAD_MAX; i++)
574 Threads[i].stop = false;
575 Threads[i].workIsWaiting = false;
576 Threads[i].idle = true;
577 Threads[i].running = false;
580 // Launch the helper threads
581 for(i = 1; i < THREAD_MAX; i++)
583 #if !defined(_MSC_VER)
584 pthread_create(pthread, NULL, init_thread, (void*)(&i));
587 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
590 // Wait until the thread has finished launching:
591 while (!Threads[i].running);
596 /// stop_threads() is called when the program exits. It makes all the
597 /// helper threads exit cleanly.
599 void stop_threads() {
601 ActiveThreads = THREAD_MAX; // HACK
602 Idle = false; // HACK
603 wake_sleeping_threads();
604 AllThreadsShouldExit = true;
605 for (int i = 1; i < THREAD_MAX; i++)
607 Threads[i].stop = true;
608 while(Threads[i].running);
610 destroy_split_point_stack();
614 /// nodes_searched() returns the total number of nodes searched so far in
615 /// the current search.
617 int64_t nodes_searched() {
619 int64_t result = 0ULL;
620 for (int i = 0; i < ActiveThreads; i++)
621 result += Threads[i].nodes;
628 // id_loop() is the main iterative deepening loop. It calls root_search
629 // repeatedly with increasing depth until the allocated thinking time has
630 // been consumed, the user stops the search, or the maximum search depth is
633 Value id_loop(const Position &pos, Move searchMoves[]) {
636 SearchStack ss[PLY_MAX_PLUS_2];
638 // searchMoves are verified, copied, scored and sorted
639 RootMoveList rml(p, searchMoves);
643 for (int i = 0; i < THREAD_MAX; i++)
644 Threads[i].H.clear();
646 for (int i = 0; i < 3; i++)
651 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
654 EasyMove = rml.scan_for_easy_move();
656 // Iterative deepening loop
657 while (Iteration < PLY_MAX)
659 // Initialize iteration
662 BestMoveChangesByIteration[Iteration] = 0;
666 std::cout << "info depth " << Iteration << std::endl;
668 // Calculate dynamic search window based on previous iterations
671 if (MultiPV == 1 && Iteration >= 6)
673 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
674 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
676 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
678 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
679 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
683 alpha = - VALUE_INFINITE;
684 beta = VALUE_INFINITE;
687 // Search to the current depth
688 Value value = root_search(p, ss, rml, alpha, beta);
690 // Write PV to transposition table, in case the relevant entries have
691 // been overwritten during the search.
692 TT.insert_pv(p, ss[0].pv);
695 break; // Value cannot be trusted. Break out immediately!
697 //Save info about search result
698 Value speculatedValue;
701 Value delta = value - IterationInfo[Iteration - 1].value;
708 speculatedValue = value + delta;
709 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
711 else if (value <= alpha)
713 assert(value == alpha);
717 speculatedValue = value + delta;
718 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
720 speculatedValue = value;
722 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
723 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
725 // Erase the easy move if it differs from the new best move
726 if (ss[0].pv[0] != EasyMove)
727 EasyMove = MOVE_NONE;
734 bool stopSearch = false;
736 // Stop search early if there is only a single legal move:
737 if (Iteration >= 6 && rml.move_count() == 1)
740 // Stop search early when the last two iterations returned a mate score
742 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
743 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
746 // Stop search early if one move seems to be much better than the rest
747 int64_t nodes = nodes_searched();
751 && EasyMove == ss[0].pv[0]
752 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
753 && current_search_time() > MaxSearchTime / 16)
754 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
755 && current_search_time() > MaxSearchTime / 32)))
758 // Add some extra time if the best move has changed during the last two iterations
759 if (Iteration > 5 && Iteration <= 50)
760 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
761 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
763 // Stop search if most of MaxSearchTime is consumed at the end of the
764 // iteration. We probably don't have enough time to search the first
765 // move at the next iteration anyway.
766 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
771 //FIXME: Implement fail-low emergency measures
775 StopOnPonderhit = true;
779 if (MaxDepth && Iteration >= MaxDepth)
785 // If we are pondering, we shouldn't print the best move before we
788 wait_for_stop_or_ponderhit();
790 // Print final search statistics
791 std::cout << "info nodes " << nodes_searched()
793 << " time " << current_search_time()
794 << " hashfull " << TT.full() << std::endl;
796 // Print the best move and the ponder move to the standard output
797 if (ss[0].pv[0] == MOVE_NONE)
799 ss[0].pv[0] = rml.get_move(0);
800 ss[0].pv[1] = MOVE_NONE;
802 std::cout << "bestmove " << ss[0].pv[0];
803 if (ss[0].pv[1] != MOVE_NONE)
804 std::cout << " ponder " << ss[0].pv[1];
806 std::cout << std::endl;
811 dbg_print_mean(LogFile);
813 if (dbg_show_hit_rate)
814 dbg_print_hit_rate(LogFile);
817 LogFile << "Nodes: " << nodes_searched() << std::endl
818 << "Nodes/second: " << nps() << std::endl
819 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
821 p.do_move(ss[0].pv[0], st);
822 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
823 << std::endl << std::endl;
825 return rml.get_move_score(0);
829 // root_search() is the function which searches the root node. It is
830 // similar to search_pv except that it uses a different move ordering
831 // scheme (perhaps we should try to use this at internal PV nodes, too?)
832 // and prints some information to the standard output.
834 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
836 Value oldAlpha = alpha;
838 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
840 // Loop through all the moves in the root move list
841 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
845 // We failed high, invalidate and skip next moves, leave node-counters
846 // and beta-counters as they are and quickly return, we will try to do
847 // a research at the next iteration with a bigger aspiration window.
848 rml.set_move_score(i, -VALUE_INFINITE);
856 RootMoveNumber = i + 1;
859 // Remember the node count before the move is searched. The node counts
860 // are used to sort the root moves at the next iteration.
861 nodes = nodes_searched();
863 // Reset beta cut-off counters
866 // Pick the next root move, and print the move and the move number to
867 // the standard output.
868 move = ss[0].currentMove = rml.get_move(i);
869 if (current_search_time() >= 1000)
870 std::cout << "info currmove " << move
871 << " currmovenumber " << i + 1 << std::endl;
873 // Decide search depth for this move
875 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
876 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
878 // Make the move, and search it
879 pos.do_move(move, st, dcCandidates);
883 // Aspiration window is disabled in multi-pv case
885 alpha = -VALUE_INFINITE;
887 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
888 // If the value has dropped a lot compared to the last iteration,
889 // set the boolean variable Problem to true. This variable is used
890 // for time managment: When Problem is true, we try to complete the
891 // current iteration before playing a move.
892 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
894 if (Problem && StopOnPonderhit)
895 StopOnPonderhit = false;
899 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
902 // Fail high! Set the boolean variable FailHigh to true, and
903 // re-search the move with a big window. The variable FailHigh is
904 // used for time managment: We try to avoid aborting the search
905 // prematurely during a fail high research.
907 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
913 // Finished searching the move. If AbortSearch is true, the search
914 // was aborted because the user interrupted the search or because we
915 // ran out of time. In this case, the return value of the search cannot
916 // be trusted, and we break out of the loop without updating the best
921 // Remember the node count for this move. The node counts are used to
922 // sort the root moves at the next iteration.
923 rml.set_move_nodes(i, nodes_searched() - nodes);
925 // Remember the beta-cutoff statistics
927 BetaCounter.read(pos.side_to_move(), our, their);
928 rml.set_beta_counters(i, our, their);
930 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
932 if (value <= alpha && i >= MultiPV)
933 rml.set_move_score(i, -VALUE_INFINITE);
936 // PV move or new best move!
939 rml.set_move_score(i, value);
941 rml.set_move_pv(i, ss[0].pv);
945 // We record how often the best move has been changed in each
946 // iteration. This information is used for time managment: When
947 // the best move changes frequently, we allocate some more time.
949 BestMoveChangesByIteration[Iteration]++;
951 // Print search information to the standard output:
952 std::cout << "info depth " << Iteration
953 << " score " << value_to_string(value)
954 << " time " << current_search_time()
955 << " nodes " << nodes_searched()
959 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
960 std::cout << ss[0].pv[j] << " ";
962 std::cout << std::endl;
965 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
971 // Reset the global variable Problem to false if the value isn't too
972 // far below the final value from the last iteration.
973 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
979 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
982 std::cout << "info multipv " << j + 1
983 << " score " << value_to_string(rml.get_move_score(j))
984 << " depth " << ((j <= i)? Iteration : Iteration - 1)
985 << " time " << current_search_time()
986 << " nodes " << nodes_searched()
990 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
991 std::cout << rml.get_move_pv(j, k) << " ";
993 std::cout << std::endl;
995 alpha = rml.get_move_score(Min(i, MultiPV-1));
997 } // New best move case
999 assert(alpha >= oldAlpha);
1001 FailLow = (alpha == oldAlpha);
1007 // search_pv() is the main search function for PV nodes.
1009 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1010 Depth depth, int ply, int threadID) {
1012 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1013 assert(beta > alpha && beta <= VALUE_INFINITE);
1014 assert(ply >= 0 && ply < PLY_MAX);
1015 assert(threadID >= 0 && threadID < ActiveThreads);
1018 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1020 // Initialize, and make an early exit in case of an aborted search,
1021 // an instant draw, maximum ply reached, etc.
1022 init_node(ss, ply, threadID);
1024 // After init_node() that calls poll()
1025 if (AbortSearch || thread_should_stop(threadID))
1033 if (ply >= PLY_MAX - 1)
1034 return evaluate(pos, ei, threadID);
1036 // Mate distance pruning
1037 Value oldAlpha = alpha;
1038 alpha = Max(value_mated_in(ply), alpha);
1039 beta = Min(value_mate_in(ply+1), beta);
1043 // Transposition table lookup. At PV nodes, we don't use the TT for
1044 // pruning, but only for move ordering.
1045 const TTEntry* tte = TT.retrieve(pos.get_key());
1046 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1048 // Go with internal iterative deepening if we don't have a TT move
1049 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1051 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1052 ttMove = ss[ply].pv[ply];
1055 // Initialize a MovePicker object for the current position, and prepare
1056 // to search all moves
1057 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H, &ss[ply]);
1059 Move move, movesSearched[256];
1061 Value value, bestValue = -VALUE_INFINITE;
1062 Bitboard dcCandidates = mp.discovered_check_candidates();
1063 Color us = pos.side_to_move();
1064 bool isCheck = pos.is_check();
1065 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1067 // Loop through all legal moves until no moves remain or a beta cutoff
1069 while ( alpha < beta
1070 && (move = mp.get_next_move()) != MOVE_NONE
1071 && !thread_should_stop(threadID))
1073 assert(move_is_ok(move));
1075 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1076 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1077 bool moveIsCapture = pos.move_is_capture(move);
1079 movesSearched[moveCount++] = ss[ply].currentMove = move;
1081 // Decide the new search depth
1083 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1084 Depth newDepth = depth - OnePly + ext;
1086 // Make and search the move
1088 pos.do_move(move, st, dcCandidates);
1090 if (moveCount == 1) // The first move in list is the PV
1091 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1094 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1095 // if the move fails high will be re-searched at full depth.
1096 if ( depth >= 2*OnePly
1097 && moveCount >= LMRPVMoves
1100 && !move_promotion(move)
1101 && !move_is_castle(move)
1102 && !move_is_killer(move, ss[ply]))
1104 ss[ply].reduction = OnePly;
1105 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1108 value = alpha + 1; // Just to trigger next condition
1110 if (value > alpha) // Go with full depth non-pv search
1112 ss[ply].reduction = Depth(0);
1113 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1114 if (value > alpha && value < beta)
1116 // When the search fails high at ply 1 while searching the first
1117 // move at the root, set the flag failHighPly1. This is used for
1118 // time managment: We don't want to stop the search early in
1119 // such cases, because resolving the fail high at ply 1 could
1120 // result in a big drop in score at the root.
1121 if (ply == 1 && RootMoveNumber == 1)
1122 Threads[threadID].failHighPly1 = true;
1124 // A fail high occurred. Re-search at full window (pv search)
1125 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1126 Threads[threadID].failHighPly1 = false;
1130 pos.undo_move(move);
1132 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1135 if (value > bestValue)
1142 if (value == value_mate_in(ply + 1))
1143 ss[ply].mateKiller = move;
1145 // If we are at ply 1, and we are searching the first root move at
1146 // ply 0, set the 'Problem' variable if the score has dropped a lot
1147 // (from the computer's point of view) since the previous iteration:
1150 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1155 if ( ActiveThreads > 1
1157 && depth >= MinimumSplitDepth
1159 && idle_thread_exists(threadID)
1161 && !thread_should_stop(threadID)
1162 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1163 &moveCount, &mp, dcCandidates, threadID, true))
1167 // All legal moves have been searched. A special case: If there were
1168 // no legal moves, it must be mate or stalemate:
1170 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1172 // If the search is not aborted, update the transposition table,
1173 // history counters, and killer moves.
1174 if (AbortSearch || thread_should_stop(threadID))
1177 if (bestValue <= oldAlpha)
1178 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1180 else if (bestValue >= beta)
1182 BetaCounter.add(pos.side_to_move(), depth, threadID);
1183 Move m = ss[ply].pv[ply];
1184 if (ok_to_history(pos, m)) // Only non capture moves are considered
1186 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1187 update_killers(m, ss[ply]);
1189 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1192 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1198 // search() is the search function for zero-width nodes.
1200 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1201 int ply, bool allowNullmove, int threadID) {
1203 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1204 assert(ply >= 0 && ply < PLY_MAX);
1205 assert(threadID >= 0 && threadID < ActiveThreads);
1208 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1210 // Initialize, and make an early exit in case of an aborted search,
1211 // an instant draw, maximum ply reached, etc.
1212 init_node(ss, ply, threadID);
1214 // After init_node() that calls poll()
1215 if (AbortSearch || thread_should_stop(threadID))
1223 if (ply >= PLY_MAX - 1)
1224 return evaluate(pos, ei, threadID);
1226 // Mate distance pruning
1227 if (value_mated_in(ply) >= beta)
1230 if (value_mate_in(ply + 1) < beta)
1233 // Transposition table lookup
1234 const TTEntry* tte = TT.retrieve(pos.get_key());
1235 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1237 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1239 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1240 return value_from_tt(tte->value(), ply);
1243 Value approximateEval = quick_evaluate(pos);
1244 bool mateThreat = false;
1245 bool isCheck = pos.is_check();
1251 && !value_is_mate(beta)
1252 && ok_to_do_nullmove(pos)
1253 && approximateEval >= beta - NullMoveMargin)
1255 ss[ply].currentMove = MOVE_NULL;
1258 pos.do_null_move(st);
1259 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1261 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1263 pos.undo_null_move();
1265 if (value_is_mate(nullValue))
1267 /* Do not return unproven mates */
1269 else if (nullValue >= beta)
1271 if (depth < 6 * OnePly)
1274 // Do zugzwang verification search
1275 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1279 // The null move failed low, which means that we may be faced with
1280 // some kind of threat. If the previous move was reduced, check if
1281 // the move that refuted the null move was somehow connected to the
1282 // move which was reduced. If a connection is found, return a fail
1283 // low score (which will cause the reduced move to fail high in the
1284 // parent node, which will trigger a re-search with full depth).
1285 if (nullValue == value_mated_in(ply + 2))
1288 ss[ply].threatMove = ss[ply + 1].currentMove;
1289 if ( depth < ThreatDepth
1290 && ss[ply - 1].reduction
1291 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1295 // Null move search not allowed, try razoring
1296 else if ( !value_is_mate(beta)
1297 && depth < RazorDepth
1298 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1299 && ss[ply - 1].currentMove != MOVE_NULL
1300 && ttMove == MOVE_NONE
1301 && !pos.has_pawn_on_7th(pos.side_to_move()))
1303 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1304 if (v < beta - RazorMargins[int(depth) - 2])
1308 // Go with internal iterative deepening if we don't have a TT move
1309 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1310 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1312 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1313 ttMove = ss[ply].pv[ply];
1316 // Initialize a MovePicker object for the current position, and prepare
1317 // to search all moves:
1318 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H, &ss[ply]);
1320 Move move, movesSearched[256];
1322 Value value, bestValue = -VALUE_INFINITE;
1323 Bitboard dcCandidates = mp.discovered_check_candidates();
1324 Value futilityValue = VALUE_NONE;
1325 bool useFutilityPruning = depth < SelectiveDepth
1328 // Loop through all legal moves until no moves remain or a beta cutoff
1330 while ( bestValue < beta
1331 && (move = mp.get_next_move()) != MOVE_NONE
1332 && !thread_should_stop(threadID))
1334 assert(move_is_ok(move));
1336 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1337 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1338 bool moveIsCapture = pos.move_is_capture(move);
1340 movesSearched[moveCount++] = ss[ply].currentMove = move;
1342 // Decide the new search depth
1344 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1345 Depth newDepth = depth - OnePly + ext;
1348 if ( useFutilityPruning
1351 && !move_promotion(move))
1353 // History pruning. See ok_to_prune() definition
1354 if ( moveCount >= 2 + int(depth)
1355 && ok_to_prune(pos, move, ss[ply].threatMove, depth, Threads[threadID].H))
1358 // Value based pruning
1359 if (approximateEval < beta)
1361 if (futilityValue == VALUE_NONE)
1362 futilityValue = evaluate(pos, ei, threadID)
1363 + FutilityMargins[int(depth) - 2];
1365 if (futilityValue < beta)
1367 if (futilityValue > bestValue)
1368 bestValue = futilityValue;
1374 // Make and search the move
1376 pos.do_move(move, st, dcCandidates);
1378 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1379 // if the move fails high will be re-searched at full depth.
1380 if ( depth >= 2*OnePly
1381 && moveCount >= LMRNonPVMoves
1384 && !move_promotion(move)
1385 && !move_is_castle(move)
1386 && !move_is_killer(move, ss[ply]))
1388 ss[ply].reduction = OnePly;
1389 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1392 value = beta; // Just to trigger next condition
1394 if (value >= beta) // Go with full depth non-pv search
1396 ss[ply].reduction = Depth(0);
1397 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1399 pos.undo_move(move);
1401 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1404 if (value > bestValue)
1410 if (value == value_mate_in(ply + 1))
1411 ss[ply].mateKiller = move;
1415 if ( ActiveThreads > 1
1417 && depth >= MinimumSplitDepth
1419 && idle_thread_exists(threadID)
1421 && !thread_should_stop(threadID)
1422 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1423 &mp, dcCandidates, threadID, false))
1427 // All legal moves have been searched. A special case: If there were
1428 // no legal moves, it must be mate or stalemate.
1430 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1432 // If the search is not aborted, update the transposition table,
1433 // history counters, and killer moves.
1434 if (AbortSearch || thread_should_stop(threadID))
1437 if (bestValue < beta)
1438 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1441 BetaCounter.add(pos.side_to_move(), depth, threadID);
1442 Move m = ss[ply].pv[ply];
1443 if (ok_to_history(pos, m)) // Only non capture moves are considered
1445 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1446 update_killers(m, ss[ply]);
1448 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1451 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1457 // qsearch() is the quiescence search function, which is called by the main
1458 // search function when the remaining depth is zero (or, to be more precise,
1459 // less than OnePly).
1461 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1462 Depth depth, int ply, int threadID) {
1464 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1465 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1467 assert(ply >= 0 && ply < PLY_MAX);
1468 assert(threadID >= 0 && threadID < ActiveThreads);
1470 // Initialize, and make an early exit in case of an aborted search,
1471 // an instant draw, maximum ply reached, etc.
1472 init_node(ss, ply, threadID);
1474 // After init_node() that calls poll()
1475 if (AbortSearch || thread_should_stop(threadID))
1481 // Transposition table lookup, only when not in PV
1482 TTEntry* tte = NULL;
1483 bool pvNode = (beta - alpha != 1);
1486 tte = TT.retrieve(pos.get_key());
1487 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1489 assert(tte->type() != VALUE_TYPE_EVAL);
1491 return value_from_tt(tte->value(), ply);
1494 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1496 // Evaluate the position statically
1499 bool isCheck = pos.is_check();
1500 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1503 staticValue = -VALUE_INFINITE;
1505 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1507 // Use the cached evaluation score if possible
1508 assert(tte->value() == evaluate(pos, ei, threadID));
1509 assert(ei.futilityMargin == Value(0));
1511 staticValue = tte->value();
1514 staticValue = evaluate(pos, ei, threadID);
1516 if (ply == PLY_MAX - 1)
1517 return evaluate(pos, ei, threadID);
1519 // Initialize "stand pat score", and return it immediately if it is
1521 Value bestValue = staticValue;
1523 if (bestValue >= beta)
1525 // Store the score to avoid a future costly evaluation() call
1526 if (!isCheck && !tte && ei.futilityMargin == 0)
1527 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE);
1532 if (bestValue > alpha)
1535 // Initialize a MovePicker object for the current position, and prepare
1536 // to search the moves. Because the depth is <= 0 here, only captures,
1537 // queen promotions and checks (only if depth == 0) will be generated.
1538 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H);
1541 Bitboard dcCandidates = mp.discovered_check_candidates();
1542 Color us = pos.side_to_move();
1543 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1545 // Loop through the moves until no moves remain or a beta cutoff
1547 while ( alpha < beta
1548 && (move = mp.get_next_move()) != MOVE_NONE)
1550 assert(move_is_ok(move));
1553 ss[ply].currentMove = move;
1559 && !move_promotion(move)
1560 && !pos.move_is_check(move, dcCandidates)
1561 && !pos.move_is_passed_pawn_push(move))
1563 Value futilityValue = staticValue
1564 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1565 pos.endgame_value_of_piece_on(move_to(move)))
1566 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1568 + ei.futilityMargin;
1570 if (futilityValue < alpha)
1572 if (futilityValue > bestValue)
1573 bestValue = futilityValue;
1578 // Don't search captures and checks with negative SEE values
1580 && !move_promotion(move)
1581 && (pos.midgame_value_of_piece_on(move_from(move)) >
1582 pos.midgame_value_of_piece_on(move_to(move)))
1583 && pos.see(move) < 0)
1586 // Make and search the move.
1588 pos.do_move(move, st, dcCandidates);
1589 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1590 pos.undo_move(move);
1592 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1595 if (value > bestValue)
1606 // All legal moves have been searched. A special case: If we're in check
1607 // and no legal moves were found, it is checkmate:
1608 if (pos.is_check() && moveCount == 0) // Mate!
1609 return value_mated_in(ply);
1611 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1613 // Update transposition table
1614 Move m = ss[ply].pv[ply];
1617 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1618 if (bestValue < beta)
1619 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1621 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1624 // Update killers only for good check moves
1625 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1626 update_killers(m, ss[ply]);
1632 // sp_search() is used to search from a split point. This function is called
1633 // by each thread working at the split point. It is similar to the normal
1634 // search() function, but simpler. Because we have already probed the hash
1635 // table, done a null move search, and searched the first move before
1636 // splitting, we don't have to repeat all this work in sp_search(). We
1637 // also don't need to store anything to the hash table here: This is taken
1638 // care of after we return from the split point.
1640 void sp_search(SplitPoint *sp, int threadID) {
1642 assert(threadID >= 0 && threadID < ActiveThreads);
1643 assert(ActiveThreads > 1);
1645 Position pos = Position(sp->pos);
1646 SearchStack *ss = sp->sstack[threadID];
1649 bool isCheck = pos.is_check();
1650 bool useFutilityPruning = sp->depth < SelectiveDepth
1653 while ( sp->bestValue < sp->beta
1654 && !thread_should_stop(threadID)
1655 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1657 assert(move_is_ok(move));
1659 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1660 bool moveIsCapture = pos.move_is_capture(move);
1662 lock_grab(&(sp->lock));
1663 int moveCount = ++sp->moves;
1664 lock_release(&(sp->lock));
1666 ss[sp->ply].currentMove = move;
1668 // Decide the new search depth.
1670 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1671 Depth newDepth = sp->depth - OnePly + ext;
1674 if ( useFutilityPruning
1677 && !move_promotion(move)
1678 && moveCount >= 2 + int(sp->depth)
1679 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth, Threads[threadID].H))
1682 // Make and search the move.
1684 pos.do_move(move, st, sp->dcCandidates);
1686 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1687 // if the move fails high will be re-searched at full depth.
1689 && moveCount >= LMRNonPVMoves
1691 && !move_promotion(move)
1692 && !move_is_castle(move)
1693 && !move_is_killer(move, ss[sp->ply]))
1695 ss[sp->ply].reduction = OnePly;
1696 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1699 value = sp->beta; // Just to trigger next condition
1701 if (value >= sp->beta) // Go with full depth non-pv search
1703 ss[sp->ply].reduction = Depth(0);
1704 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1706 pos.undo_move(move);
1708 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1710 if (thread_should_stop(threadID))
1714 lock_grab(&(sp->lock));
1715 if (value > sp->bestValue && !thread_should_stop(threadID))
1717 sp->bestValue = value;
1718 if (sp->bestValue >= sp->beta)
1720 sp_update_pv(sp->parentSstack, ss, sp->ply);
1721 for (int i = 0; i < ActiveThreads; i++)
1722 if (i != threadID && (i == sp->master || sp->slaves[i]))
1723 Threads[i].stop = true;
1725 sp->finished = true;
1728 lock_release(&(sp->lock));
1731 lock_grab(&(sp->lock));
1733 // If this is the master thread and we have been asked to stop because of
1734 // a beta cutoff higher up in the tree, stop all slave threads:
1735 if (sp->master == threadID && thread_should_stop(threadID))
1736 for (int i = 0; i < ActiveThreads; i++)
1738 Threads[i].stop = true;
1741 sp->slaves[threadID] = 0;
1743 lock_release(&(sp->lock));
1747 // sp_search_pv() is used to search from a PV split point. This function
1748 // is called by each thread working at the split point. It is similar to
1749 // the normal search_pv() function, but simpler. Because we have already
1750 // probed the hash table and searched the first move before splitting, we
1751 // don't have to repeat all this work in sp_search_pv(). We also don't
1752 // need to store anything to the hash table here: This is taken care of
1753 // after we return from the split point.
1755 void sp_search_pv(SplitPoint *sp, int threadID) {
1757 assert(threadID >= 0 && threadID < ActiveThreads);
1758 assert(ActiveThreads > 1);
1760 Position pos = Position(sp->pos);
1761 SearchStack *ss = sp->sstack[threadID];
1765 while ( sp->alpha < sp->beta
1766 && !thread_should_stop(threadID)
1767 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1769 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1770 bool moveIsCapture = pos.move_is_capture(move);
1772 assert(move_is_ok(move));
1774 lock_grab(&(sp->lock));
1775 int moveCount = ++sp->moves;
1776 lock_release(&(sp->lock));
1778 ss[sp->ply].currentMove = move;
1780 // Decide the new search depth.
1782 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1783 Depth newDepth = sp->depth - OnePly + ext;
1785 // Make and search the move.
1787 pos.do_move(move, st, sp->dcCandidates);
1789 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1790 // if the move fails high will be re-searched at full depth.
1792 && moveCount >= LMRPVMoves
1794 && !move_promotion(move)
1795 && !move_is_castle(move)
1796 && !move_is_killer(move, ss[sp->ply]))
1798 ss[sp->ply].reduction = OnePly;
1799 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1802 value = sp->alpha + 1; // Just to trigger next condition
1804 if (value > sp->alpha) // Go with full depth non-pv search
1806 ss[sp->ply].reduction = Depth(0);
1807 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1809 if (value > sp->alpha && value < sp->beta)
1811 // When the search fails high at ply 1 while searching the first
1812 // move at the root, set the flag failHighPly1. This is used for
1813 // time managment: We don't want to stop the search early in
1814 // such cases, because resolving the fail high at ply 1 could
1815 // result in a big drop in score at the root.
1816 if (sp->ply == 1 && RootMoveNumber == 1)
1817 Threads[threadID].failHighPly1 = true;
1819 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1820 Threads[threadID].failHighPly1 = false;
1823 pos.undo_move(move);
1825 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1827 if (thread_should_stop(threadID))
1831 lock_grab(&(sp->lock));
1832 if (value > sp->bestValue && !thread_should_stop(threadID))
1834 sp->bestValue = value;
1835 if (value > sp->alpha)
1838 sp_update_pv(sp->parentSstack, ss, sp->ply);
1839 if (value == value_mate_in(sp->ply + 1))
1840 ss[sp->ply].mateKiller = move;
1842 if(value >= sp->beta)
1844 for(int i = 0; i < ActiveThreads; i++)
1845 if(i != threadID && (i == sp->master || sp->slaves[i]))
1846 Threads[i].stop = true;
1848 sp->finished = true;
1851 // If we are at ply 1, and we are searching the first root move at
1852 // ply 0, set the 'Problem' variable if the score has dropped a lot
1853 // (from the computer's point of view) since the previous iteration.
1856 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1859 lock_release(&(sp->lock));
1862 lock_grab(&(sp->lock));
1864 // If this is the master thread and we have been asked to stop because of
1865 // a beta cutoff higher up in the tree, stop all slave threads.
1866 if (sp->master == threadID && thread_should_stop(threadID))
1867 for (int i = 0; i < ActiveThreads; i++)
1869 Threads[i].stop = true;
1872 sp->slaves[threadID] = 0;
1874 lock_release(&(sp->lock));
1877 /// The BetaCounterType class
1879 BetaCounterType::BetaCounterType() { clear(); }
1881 void BetaCounterType::clear() {
1883 for (int i = 0; i < THREAD_MAX; i++)
1884 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1887 void BetaCounterType::add(Color us, Depth d, int threadID) {
1889 // Weighted count based on depth
1890 Threads[threadID].betaCutOffs[us] += unsigned(d);
1893 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1896 for (int i = 0; i < THREAD_MAX; i++)
1898 our += Threads[i].betaCutOffs[us];
1899 their += Threads[i].betaCutOffs[opposite_color(us)];
1904 /// The RootMove class
1908 RootMove::RootMove() {
1909 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1912 // RootMove::operator<() is the comparison function used when
1913 // sorting the moves. A move m1 is considered to be better
1914 // than a move m2 if it has a higher score, or if the moves
1915 // have equal score but m1 has the higher node count.
1917 bool RootMove::operator<(const RootMove& m) {
1919 if (score != m.score)
1920 return (score < m.score);
1922 return theirBeta <= m.theirBeta;
1925 /// The RootMoveList class
1929 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1931 MoveStack mlist[MaxRootMoves];
1932 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1934 // Generate all legal moves
1935 int lm_count = generate_legal_moves(pos, mlist);
1937 // Add each move to the moves[] array
1938 for (int i = 0; i < lm_count; i++)
1940 bool includeMove = includeAllMoves;
1942 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1943 includeMove = (searchMoves[k] == mlist[i].move);
1948 // Find a quick score for the move
1950 SearchStack ss[PLY_MAX_PLUS_2];
1952 moves[count].move = mlist[i].move;
1953 pos.do_move(moves[count].move, st);
1954 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1955 pos.undo_move(moves[count].move);
1956 moves[count].pv[0] = moves[count].move;
1957 moves[count].pv[1] = MOVE_NONE; // FIXME
1964 // Simple accessor methods for the RootMoveList class
1966 inline Move RootMoveList::get_move(int moveNum) const {
1967 return moves[moveNum].move;
1970 inline Value RootMoveList::get_move_score(int moveNum) const {
1971 return moves[moveNum].score;
1974 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1975 moves[moveNum].score = score;
1978 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1979 moves[moveNum].nodes = nodes;
1980 moves[moveNum].cumulativeNodes += nodes;
1983 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1984 moves[moveNum].ourBeta = our;
1985 moves[moveNum].theirBeta = their;
1988 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1990 for(j = 0; pv[j] != MOVE_NONE; j++)
1991 moves[moveNum].pv[j] = pv[j];
1992 moves[moveNum].pv[j] = MOVE_NONE;
1995 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1996 return moves[moveNum].pv[i];
1999 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2000 return moves[moveNum].cumulativeNodes;
2003 inline int RootMoveList::move_count() const {
2008 // RootMoveList::scan_for_easy_move() is called at the end of the first
2009 // iteration, and is used to detect an "easy move", i.e. a move which appears
2010 // to be much bester than all the rest. If an easy move is found, the move
2011 // is returned, otherwise the function returns MOVE_NONE. It is very
2012 // important that this function is called at the right moment: The code
2013 // assumes that the first iteration has been completed and the moves have
2014 // been sorted. This is done in RootMoveList c'tor.
2016 Move RootMoveList::scan_for_easy_move() const {
2023 // moves are sorted so just consider the best and the second one
2024 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2030 // RootMoveList::sort() sorts the root move list at the beginning of a new
2033 inline void RootMoveList::sort() {
2035 sort_multipv(count - 1); // all items
2039 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2040 // list by their scores and depths. It is used to order the different PVs
2041 // correctly in MultiPV mode.
2043 void RootMoveList::sort_multipv(int n) {
2045 for (int i = 1; i <= n; i++)
2047 RootMove rm = moves[i];
2049 for (j = i; j > 0 && moves[j-1] < rm; j--)
2050 moves[j] = moves[j-1];
2056 // init_node() is called at the beginning of all the search functions
2057 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2058 // stack object corresponding to the current node. Once every
2059 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2060 // for user input and checks whether it is time to stop the search.
2062 void init_node(SearchStack ss[], int ply, int threadID) {
2063 assert(ply >= 0 && ply < PLY_MAX);
2064 assert(threadID >= 0 && threadID < ActiveThreads);
2066 Threads[threadID].nodes++;
2070 if(NodesSincePoll >= NodesBetweenPolls) {
2077 ss[ply+2].initKillers();
2079 if(Threads[threadID].printCurrentLine)
2080 print_current_line(ss, ply, threadID);
2084 // update_pv() is called whenever a search returns a value > alpha. It
2085 // updates the PV in the SearchStack object corresponding to the current
2088 void update_pv(SearchStack ss[], int ply) {
2089 assert(ply >= 0 && ply < PLY_MAX);
2091 ss[ply].pv[ply] = ss[ply].currentMove;
2093 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2094 ss[ply].pv[p] = ss[ply+1].pv[p];
2095 ss[ply].pv[p] = MOVE_NONE;
2099 // sp_update_pv() is a variant of update_pv for use at split points. The
2100 // difference between the two functions is that sp_update_pv also updates
2101 // the PV at the parent node.
2103 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2104 assert(ply >= 0 && ply < PLY_MAX);
2106 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2108 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2109 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2110 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2114 // connected_moves() tests whether two moves are 'connected' in the sense
2115 // that the first move somehow made the second move possible (for instance
2116 // if the moving piece is the same in both moves). The first move is
2117 // assumed to be the move that was made to reach the current position, while
2118 // the second move is assumed to be a move from the current position.
2120 bool connected_moves(const Position &pos, Move m1, Move m2) {
2121 Square f1, t1, f2, t2;
2123 assert(move_is_ok(m1));
2124 assert(move_is_ok(m2));
2129 // Case 1: The moving piece is the same in both moves.
2135 // Case 2: The destination square for m2 was vacated by m1.
2141 // Case 3: Moving through the vacated square:
2142 if(piece_is_slider(pos.piece_on(f2)) &&
2143 bit_is_set(squares_between(f2, t2), f1))
2146 // Case 4: The destination square for m2 is attacked by the moving piece
2148 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2151 // Case 5: Discovered check, checking piece is the piece moved in m1:
2152 if(piece_is_slider(pos.piece_on(t1)) &&
2153 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2155 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2157 Bitboard occ = pos.occupied_squares();
2158 Color us = pos.side_to_move();
2159 Square ksq = pos.king_square(us);
2160 clear_bit(&occ, f2);
2161 if(pos.type_of_piece_on(t1) == BISHOP) {
2162 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2165 else if(pos.type_of_piece_on(t1) == ROOK) {
2166 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2170 assert(pos.type_of_piece_on(t1) == QUEEN);
2171 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2180 // value_is_mate() checks if the given value is a mate one
2181 // eventually compensated for the ply.
2183 bool value_is_mate(Value value) {
2185 assert(abs(value) <= VALUE_INFINITE);
2187 return value <= value_mated_in(PLY_MAX)
2188 || value >= value_mate_in(PLY_MAX);
2192 // move_is_killer() checks if the given move is among the
2193 // killer moves of that ply.
2195 bool move_is_killer(Move m, const SearchStack& ss) {
2197 const Move* k = ss.killers;
2198 for (int i = 0; i < KILLER_MAX; i++, k++)
2206 // extension() decides whether a move should be searched with normal depth,
2207 // or with extended depth. Certain classes of moves (checking moves, in
2208 // particular) are searched with bigger depth than ordinary moves and in
2209 // any case are marked as 'dangerous'. Note that also if a move is not
2210 // extended, as example because the corresponding UCI option is set to zero,
2211 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2213 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2214 bool singleReply, bool mateThreat, bool* dangerous) {
2216 assert(m != MOVE_NONE);
2218 Depth result = Depth(0);
2219 *dangerous = check || singleReply || mateThreat;
2222 result += CheckExtension[pvNode];
2225 result += SingleReplyExtension[pvNode];
2228 result += MateThreatExtension[pvNode];
2230 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2232 if (pos.move_is_pawn_push_to_7th(m))
2234 result += PawnPushTo7thExtension[pvNode];
2237 if (pos.move_is_passed_pawn_push(m))
2239 result += PassedPawnExtension[pvNode];
2245 && pos.type_of_piece_on(move_to(m)) != PAWN
2246 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2247 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2248 && !move_promotion(m)
2251 result += PawnEndgameExtension[pvNode];
2257 && pos.type_of_piece_on(move_to(m)) != PAWN
2264 return Min(result, OnePly);
2268 // ok_to_do_nullmove() looks at the current position and decides whether
2269 // doing a 'null move' should be allowed. In order to avoid zugzwang
2270 // problems, null moves are not allowed when the side to move has very
2271 // little material left. Currently, the test is a bit too simple: Null
2272 // moves are avoided only when the side to move has only pawns left. It's
2273 // probably a good idea to avoid null moves in at least some more
2274 // complicated endgames, e.g. KQ vs KR. FIXME
2276 bool ok_to_do_nullmove(const Position &pos) {
2277 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2283 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2284 // non-tactical moves late in the move list close to the leaves are
2285 // candidates for pruning.
2287 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d, const History& H) {
2288 Square mfrom, mto, tfrom, tto;
2290 assert(move_is_ok(m));
2291 assert(threat == MOVE_NONE || move_is_ok(threat));
2292 assert(!move_promotion(m));
2293 assert(!pos.move_is_check(m));
2294 assert(!pos.move_is_capture(m));
2295 assert(!pos.move_is_passed_pawn_push(m));
2296 assert(d >= OnePly);
2298 mfrom = move_from(m);
2300 tfrom = move_from(threat);
2301 tto = move_to(threat);
2303 // Case 1: Castling moves are never pruned.
2304 if (move_is_castle(m))
2307 // Case 2: Don't prune moves which move the threatened piece
2308 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2311 // Case 3: If the threatened piece has value less than or equal to the
2312 // value of the threatening piece, don't prune move which defend it.
2313 if ( !PruneDefendingMoves
2314 && threat != MOVE_NONE
2315 && pos.move_is_capture(threat)
2316 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2317 || pos.type_of_piece_on(tfrom) == KING)
2318 && pos.move_attacks_square(m, tto))
2321 // Case 4: Don't prune moves with good history.
2322 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2325 // Case 5: If the moving piece in the threatened move is a slider, don't
2326 // prune safe moves which block its ray.
2327 if ( !PruneBlockingMoves
2328 && threat != MOVE_NONE
2329 && piece_is_slider(pos.piece_on(tfrom))
2330 && bit_is_set(squares_between(tfrom, tto), mto)
2338 // ok_to_use_TT() returns true if a transposition table score
2339 // can be used at a given point in search.
2341 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2343 Value v = value_from_tt(tte->value(), ply);
2345 return ( tte->depth() >= depth
2346 || v >= Max(value_mate_in(100), beta)
2347 || v < Min(value_mated_in(100), beta))
2349 && ( (is_lower_bound(tte->type()) && v >= beta)
2350 || (is_upper_bound(tte->type()) && v < beta));
2354 // ok_to_history() returns true if a move m can be stored
2355 // in history. Should be a non capturing move nor a promotion.
2357 bool ok_to_history(const Position& pos, Move m) {
2359 return !pos.move_is_capture(m) && !move_promotion(m);
2363 // update_history() registers a good move that produced a beta-cutoff
2364 // in history and marks as failures all the other moves of that ply.
2366 void update_history(const Position& pos, Move m, Depth depth, History& H,
2367 Move movesSearched[], int moveCount) {
2369 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2371 for (int i = 0; i < moveCount - 1; i++)
2373 assert(m != movesSearched[i]);
2374 if (ok_to_history(pos, movesSearched[i]))
2375 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2380 // update_killers() add a good move that produced a beta-cutoff
2381 // among the killer moves of that ply.
2383 void update_killers(Move m, SearchStack& ss) {
2385 if (m == ss.killers[0])
2388 for (int i = KILLER_MAX - 1; i > 0; i--)
2389 ss.killers[i] = ss.killers[i - 1];
2394 // fail_high_ply_1() checks if some thread is currently resolving a fail
2395 // high at ply 1 at the node below the first root node. This information
2396 // is used for time managment.
2398 bool fail_high_ply_1() {
2399 for(int i = 0; i < ActiveThreads; i++)
2400 if(Threads[i].failHighPly1)
2406 // current_search_time() returns the number of milliseconds which have passed
2407 // since the beginning of the current search.
2409 int current_search_time() {
2410 return get_system_time() - SearchStartTime;
2414 // nps() computes the current nodes/second count.
2417 int t = current_search_time();
2418 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2422 // poll() performs two different functions: It polls for user input, and it
2423 // looks at the time consumed so far and decides if it's time to abort the
2428 static int lastInfoTime;
2429 int t = current_search_time();
2434 // We are line oriented, don't read single chars
2435 std::string command;
2436 if (!std::getline(std::cin, command))
2439 if (command == "quit")
2442 PonderSearch = false;
2446 else if(command == "stop")
2449 PonderSearch = false;
2451 else if(command == "ponderhit")
2454 // Print search information
2458 else if (lastInfoTime > t)
2459 // HACK: Must be a new search where we searched less than
2460 // NodesBetweenPolls nodes during the first second of search.
2463 else if (t - lastInfoTime >= 1000)
2470 if (dbg_show_hit_rate)
2471 dbg_print_hit_rate();
2473 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2474 << " time " << t << " hashfull " << TT.full() << std::endl;
2475 lock_release(&IOLock);
2476 if (ShowCurrentLine)
2477 Threads[0].printCurrentLine = true;
2479 // Should we stop the search?
2483 bool overTime = t > AbsoluteMaxSearchTime
2484 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2485 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2486 && t > 6*(MaxSearchTime + ExtraSearchTime));
2488 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2489 || (ExactMaxTime && t >= ExactMaxTime)
2490 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2495 // ponderhit() is called when the program is pondering (i.e. thinking while
2496 // it's the opponent's turn to move) in order to let the engine know that
2497 // it correctly predicted the opponent's move.
2500 int t = current_search_time();
2501 PonderSearch = false;
2502 if(Iteration >= 3 &&
2503 (!InfiniteSearch && (StopOnPonderhit ||
2504 t > AbsoluteMaxSearchTime ||
2505 (RootMoveNumber == 1 &&
2506 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2507 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2508 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2513 // print_current_line() prints the current line of search for a given
2514 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2516 void print_current_line(SearchStack ss[], int ply, int threadID) {
2517 assert(ply >= 0 && ply < PLY_MAX);
2518 assert(threadID >= 0 && threadID < ActiveThreads);
2520 if(!Threads[threadID].idle) {
2522 std::cout << "info currline " << (threadID + 1);
2523 for(int p = 0; p < ply; p++)
2524 std::cout << " " << ss[p].currentMove;
2525 std::cout << std::endl;
2526 lock_release(&IOLock);
2528 Threads[threadID].printCurrentLine = false;
2529 if(threadID + 1 < ActiveThreads)
2530 Threads[threadID + 1].printCurrentLine = true;
2534 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2535 // while the program is pondering. The point is to work around a wrinkle in
2536 // the UCI protocol: When pondering, the engine is not allowed to give a
2537 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2538 // We simply wait here until one of these commands is sent, and return,
2539 // after which the bestmove and pondermove will be printed (in id_loop()).
2541 void wait_for_stop_or_ponderhit() {
2543 std::string command;
2547 if (!std::getline(std::cin, command))
2550 if (command == "quit")
2555 else if(command == "ponderhit" || command == "stop")
2561 // idle_loop() is where the threads are parked when they have no work to do.
2562 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2563 // object for which the current thread is the master.
2565 void idle_loop(int threadID, SplitPoint *waitSp) {
2566 assert(threadID >= 0 && threadID < THREAD_MAX);
2568 Threads[threadID].running = true;
2571 if(AllThreadsShouldExit && threadID != 0)
2574 // If we are not thinking, wait for a condition to be signaled instead
2575 // of wasting CPU time polling for work:
2576 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2577 #if !defined(_MSC_VER)
2578 pthread_mutex_lock(&WaitLock);
2579 if(Idle || threadID >= ActiveThreads)
2580 pthread_cond_wait(&WaitCond, &WaitLock);
2581 pthread_mutex_unlock(&WaitLock);
2583 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2587 // If this thread has been assigned work, launch a search:
2588 if(Threads[threadID].workIsWaiting) {
2589 Threads[threadID].workIsWaiting = false;
2590 if(Threads[threadID].splitPoint->pvNode)
2591 sp_search_pv(Threads[threadID].splitPoint, threadID);
2593 sp_search(Threads[threadID].splitPoint, threadID);
2594 Threads[threadID].idle = true;
2597 // If this thread is the master of a split point and all threads have
2598 // finished their work at this split point, return from the idle loop:
2599 if(waitSp != NULL && waitSp->cpus == 0)
2603 Threads[threadID].running = false;
2607 // init_split_point_stack() is called during program initialization, and
2608 // initializes all split point objects.
2610 void init_split_point_stack() {
2611 for(int i = 0; i < THREAD_MAX; i++)
2612 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2613 SplitPointStack[i][j].parent = NULL;
2614 lock_init(&(SplitPointStack[i][j].lock), NULL);
2619 // destroy_split_point_stack() is called when the program exits, and
2620 // destroys all locks in the precomputed split point objects.
2622 void destroy_split_point_stack() {
2623 for(int i = 0; i < THREAD_MAX; i++)
2624 for(int j = 0; j < MaxActiveSplitPoints; j++)
2625 lock_destroy(&(SplitPointStack[i][j].lock));
2629 // thread_should_stop() checks whether the thread with a given threadID has
2630 // been asked to stop, directly or indirectly. This can happen if a beta
2631 // cutoff has occured in thre thread's currently active split point, or in
2632 // some ancestor of the current split point.
2634 bool thread_should_stop(int threadID) {
2635 assert(threadID >= 0 && threadID < ActiveThreads);
2639 if(Threads[threadID].stop)
2641 if(ActiveThreads <= 2)
2643 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2645 Threads[threadID].stop = true;
2652 // thread_is_available() checks whether the thread with threadID "slave" is
2653 // available to help the thread with threadID "master" at a split point. An
2654 // obvious requirement is that "slave" must be idle. With more than two
2655 // threads, this is not by itself sufficient: If "slave" is the master of
2656 // some active split point, it is only available as a slave to the other
2657 // threads which are busy searching the split point at the top of "slave"'s
2658 // split point stack (the "helpful master concept" in YBWC terminology).
2660 bool thread_is_available(int slave, int master) {
2661 assert(slave >= 0 && slave < ActiveThreads);
2662 assert(master >= 0 && master < ActiveThreads);
2663 assert(ActiveThreads > 1);
2665 if(!Threads[slave].idle || slave == master)
2668 if(Threads[slave].activeSplitPoints == 0)
2669 // No active split points means that the thread is available as a slave
2670 // for any other thread.
2673 if(ActiveThreads == 2)
2676 // Apply the "helpful master" concept if possible.
2677 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2684 // idle_thread_exists() tries to find an idle thread which is available as
2685 // a slave for the thread with threadID "master".
2687 bool idle_thread_exists(int master) {
2688 assert(master >= 0 && master < ActiveThreads);
2689 assert(ActiveThreads > 1);
2691 for(int i = 0; i < ActiveThreads; i++)
2692 if(thread_is_available(i, master))
2698 // split() does the actual work of distributing the work at a node between
2699 // several threads at PV nodes. If it does not succeed in splitting the
2700 // node (because no idle threads are available, or because we have no unused
2701 // split point objects), the function immediately returns false. If
2702 // splitting is possible, a SplitPoint object is initialized with all the
2703 // data that must be copied to the helper threads (the current position and
2704 // search stack, alpha, beta, the search depth, etc.), and we tell our
2705 // helper threads that they have been assigned work. This will cause them
2706 // to instantly leave their idle loops and call sp_search_pv(). When all
2707 // threads have returned from sp_search_pv (or, equivalently, when
2708 // splitPoint->cpus becomes 0), split() returns true.
2710 bool split(const Position &p, SearchStack *sstck, int ply,
2711 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2712 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2715 assert(sstck != NULL);
2716 assert(ply >= 0 && ply < PLY_MAX);
2717 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2718 assert(!pvNode || *alpha < *beta);
2719 assert(*beta <= VALUE_INFINITE);
2720 assert(depth > Depth(0));
2721 assert(master >= 0 && master < ActiveThreads);
2722 assert(ActiveThreads > 1);
2724 SplitPoint *splitPoint;
2729 // If no other thread is available to help us, or if we have too many
2730 // active split points, don't split:
2731 if(!idle_thread_exists(master) ||
2732 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2733 lock_release(&MPLock);
2737 // Pick the next available split point object from the split point stack:
2738 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2739 Threads[master].activeSplitPoints++;
2741 // Initialize the split point object:
2742 splitPoint->parent = Threads[master].splitPoint;
2743 splitPoint->finished = false;
2744 splitPoint->ply = ply;
2745 splitPoint->depth = depth;
2746 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2747 splitPoint->beta = *beta;
2748 splitPoint->pvNode = pvNode;
2749 splitPoint->dcCandidates = dcCandidates;
2750 splitPoint->bestValue = *bestValue;
2751 splitPoint->master = master;
2752 splitPoint->mp = mp;
2753 splitPoint->moves = *moves;
2754 splitPoint->cpus = 1;
2755 splitPoint->pos.copy(p);
2756 splitPoint->parentSstack = sstck;
2757 for(i = 0; i < ActiveThreads; i++)
2758 splitPoint->slaves[i] = 0;
2760 // Copy the current position and the search stack to the master thread:
2761 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2762 Threads[master].splitPoint = splitPoint;
2764 // Make copies of the current position and search stack for each thread:
2765 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2767 if(thread_is_available(i, master)) {
2768 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2769 Threads[i].splitPoint = splitPoint;
2770 splitPoint->slaves[i] = 1;
2774 // Tell the threads that they have work to do. This will make them leave
2776 for(i = 0; i < ActiveThreads; i++)
2777 if(i == master || splitPoint->slaves[i]) {
2778 Threads[i].workIsWaiting = true;
2779 Threads[i].idle = false;
2780 Threads[i].stop = false;
2783 lock_release(&MPLock);
2785 // Everything is set up. The master thread enters the idle loop, from
2786 // which it will instantly launch a search, because its workIsWaiting
2787 // slot is 'true'. We send the split point as a second parameter to the
2788 // idle loop, which means that the main thread will return from the idle
2789 // loop when all threads have finished their work at this split point
2790 // (i.e. when // splitPoint->cpus == 0).
2791 idle_loop(master, splitPoint);
2793 // We have returned from the idle loop, which means that all threads are
2794 // finished. Update alpha, beta and bestvalue, and return:
2796 if(pvNode) *alpha = splitPoint->alpha;
2797 *beta = splitPoint->beta;
2798 *bestValue = splitPoint->bestValue;
2799 Threads[master].stop = false;
2800 Threads[master].idle = false;
2801 Threads[master].activeSplitPoints--;
2802 Threads[master].splitPoint = splitPoint->parent;
2803 lock_release(&MPLock);
2809 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2810 // to start a new search from the root.
2812 void wake_sleeping_threads() {
2813 if(ActiveThreads > 1) {
2814 for(int i = 1; i < ActiveThreads; i++) {
2815 Threads[i].idle = true;
2816 Threads[i].workIsWaiting = false;
2818 #if !defined(_MSC_VER)
2819 pthread_mutex_lock(&WaitLock);
2820 pthread_cond_broadcast(&WaitCond);
2821 pthread_mutex_unlock(&WaitLock);
2823 for(int i = 1; i < THREAD_MAX; i++)
2824 SetEvent(SitIdleEvent[i]);
2830 // init_thread() is the function which is called when a new thread is
2831 // launched. It simply calls the idle_loop() function with the supplied
2832 // threadID. There are two versions of this function; one for POSIX threads
2833 // and one for Windows threads.
2835 #if !defined(_MSC_VER)
2837 void *init_thread(void *threadID) {
2838 idle_loop(*(int *)threadID, NULL);
2844 DWORD WINAPI init_thread(LPVOID threadID) {
2845 idle_loop(*(int *)threadID, NULL);