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 // Depth limit for selective search
134 const Depth SelectiveDepth = 7*OnePly;
136 // Use internal iterative deepening?
137 const bool UseIIDAtPVNodes = true;
138 const bool UseIIDAtNonPVNodes = false;
140 // Internal iterative deepening margin. At Non-PV moves, when
141 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
142 // when the static evaluation is at most IIDMargin below beta.
143 const Value IIDMargin = Value(0x100);
145 // Easy move margin. An easy move candidate must be at least this much
146 // better than the second best move.
147 const Value EasyMoveMargin = Value(0x200);
149 // Problem margin. If the score of the first move at iteration N+1 has
150 // dropped by more than this since iteration N, the boolean variable
151 // "Problem" is set to true, which will make the program spend some extra
152 // time looking for a better move.
153 const Value ProblemMargin = Value(0x28);
155 // No problem margin. If the boolean "Problem" is true, and a new move
156 // is found at the root which is less than NoProblemMargin worse than the
157 // best move from the previous iteration, Problem is set back to false.
158 const Value NoProblemMargin = Value(0x14);
160 // Null move margin. A null move search will not be done if the approximate
161 // evaluation of the position is more than NullMoveMargin below beta.
162 const Value NullMoveMargin = Value(0x300);
164 // Pruning criterions. See the code and comments in ok_to_prune() to
165 // understand their precise meaning.
166 const bool PruneEscapeMoves = false;
167 const bool PruneDefendingMoves = false;
168 const bool PruneBlockingMoves = false;
170 // Margins for futility pruning in the quiescence search, and at frontier
171 // and near frontier nodes
172 const Value FutilityMarginQS = Value(0x80);
174 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
175 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
176 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
177 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
179 const Depth RazorDepth = 4*OnePly;
181 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
182 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
184 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
185 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
188 /// Variables initialized from UCI options
190 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
192 int LMRPVMoves, LMRNonPVMoves;
194 // Depth limit for use of dynamic threat detection
197 // Last seconds noise filtering (LSN)
198 bool UseLSNFiltering;
199 bool looseOnTime = false;
200 int LSNTime; // In milliseconds
203 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
204 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
205 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
207 // Search depth at iteration 1
208 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
210 // Node counters, used only by thread[0]
212 int NodesBetweenPolls = 30000;
214 // Iteration counters
216 BetaCounterType BetaCounter; // does not have internal data
218 // Scores and number of times the best move changed for each iteration
219 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
220 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
225 // Time managment variables
227 int MaxNodes, MaxDepth;
228 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
233 bool StopOnPonderhit;
239 bool PonderingEnabled;
242 // Show current line?
243 bool ShowCurrentLine;
247 std::ofstream LogFile;
249 // MP related variables
250 Depth MinimumSplitDepth;
251 int MaxThreadsPerSplitPoint;
252 Thread Threads[THREAD_MAX];
254 bool AllThreadsShouldExit = false;
255 const int MaxActiveSplitPoints = 8;
256 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
259 #if !defined(_MSC_VER)
260 pthread_cond_t WaitCond;
261 pthread_mutex_t WaitLock;
263 HANDLE SitIdleEvent[THREAD_MAX];
269 Value id_loop(const Position &pos, Move searchMoves[]);
270 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta);
271 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
272 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
273 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
274 void sp_search(SplitPoint *sp, int threadID);
275 void sp_search_pv(SplitPoint *sp, int threadID);
276 void init_node(SearchStack ss[], int ply, int threadID);
277 void update_pv(SearchStack ss[], int ply);
278 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
279 bool connected_moves(const Position &pos, Move m1, Move m2);
280 bool value_is_mate(Value value);
281 bool move_is_killer(Move m, const SearchStack& ss);
282 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
283 bool ok_to_do_nullmove(const Position &pos);
284 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d, const History& H);
285 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
286 bool ok_to_history(const Position &pos, Move m);
287 void update_history(const Position& pos, Move m, Depth depth, History& H, Move movesSearched[], int moveCount);
288 void update_killers(Move m, SearchStack& ss);
290 bool fail_high_ply_1();
291 int current_search_time();
295 void print_current_line(SearchStack ss[], int ply, int threadID);
296 void wait_for_stop_or_ponderhit();
298 void idle_loop(int threadID, SplitPoint *waitSp);
299 void init_split_point_stack();
300 void destroy_split_point_stack();
301 bool thread_should_stop(int threadID);
302 bool thread_is_available(int slave, int master);
303 bool idle_thread_exists(int master);
304 bool split(const Position &pos, SearchStack *ss, int ply,
305 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
306 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
307 void wake_sleeping_threads();
309 #if !defined(_MSC_VER)
310 void *init_thread(void *threadID);
312 DWORD WINAPI init_thread(LPVOID threadID);
319 //// Global variables
322 // The main transposition table
323 TranspositionTable TT;
326 // Number of active threads:
327 int ActiveThreads = 1;
329 // Locks. In principle, there is no need for IOLock to be a global variable,
330 // but it could turn out to be useful for debugging.
334 // SearchStack::init() initializes a search stack. Used at the beginning of a
335 // new search from the root.
336 void SearchStack::init(int ply) {
338 pv[ply] = pv[ply + 1] = MOVE_NONE;
339 currentMove = threatMove = MOVE_NONE;
340 reduction = Depth(0);
343 void SearchStack::initKillers() {
345 mateKiller = MOVE_NONE;
346 for (int i = 0; i < KILLER_MAX; i++)
347 killers[i] = MOVE_NONE;
355 /// think() is the external interface to Stockfish's search, and is called when
356 /// the program receives the UCI 'go' command. It initializes various
357 /// search-related global variables, and calls root_search(). It returns false
358 /// when a quit command is received during the search.
360 bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
361 int time[], int increment[], int movesToGo, int maxDepth,
362 int maxNodes, int maxTime, Move searchMoves[]) {
364 // Look for a book move
365 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
368 if (get_option_value_string("Book File") != OpeningBook.file_name())
369 OpeningBook.open("book.bin");
371 bookMove = OpeningBook.get_move(pos);
372 if (bookMove != MOVE_NONE)
374 std::cout << "bestmove " << bookMove << std::endl;
379 // Initialize global search variables
381 SearchStartTime = get_system_time();
382 EasyMove = MOVE_NONE;
383 for (int i = 0; i < THREAD_MAX; i++)
385 Threads[i].nodes = 0ULL;
386 Threads[i].failHighPly1 = false;
389 InfiniteSearch = infinite;
390 PonderSearch = ponder;
391 StopOnPonderhit = false;
397 ExactMaxTime = maxTime;
399 // Read UCI option values
400 TT.set_size(get_option_value_int("Hash"));
401 if (button_was_pressed("Clear Hash"))
404 PonderingEnabled = get_option_value_bool("Ponder");
405 MultiPV = get_option_value_int("MultiPV");
407 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
408 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
410 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
411 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
413 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
414 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
416 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
417 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
419 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
420 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
422 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
423 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
425 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
426 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
427 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
429 Chess960 = get_option_value_bool("UCI_Chess960");
430 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
431 UseLogFile = get_option_value_bool("Use Search Log");
433 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
435 UseLSNFiltering = get_option_value_bool("LSN filtering");
436 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
437 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
439 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
440 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
442 read_weights(pos.side_to_move());
444 int newActiveThreads = get_option_value_int("Threads");
445 if (newActiveThreads != ActiveThreads)
447 ActiveThreads = newActiveThreads;
448 init_eval(ActiveThreads);
451 // Wake up sleeping threads:
452 wake_sleeping_threads();
454 for (int i = 1; i < ActiveThreads; i++)
455 assert(thread_is_available(i, 0));
457 // Set thinking time:
458 int myTime = time[side_to_move];
459 int myIncrement = increment[side_to_move];
461 if (!movesToGo) // Sudden death time control
465 MaxSearchTime = myTime / 30 + myIncrement;
466 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
467 } else { // Blitz game without increment
468 MaxSearchTime = myTime / 30;
469 AbsoluteMaxSearchTime = myTime / 8;
472 else // (x moves) / (y minutes)
476 MaxSearchTime = myTime / 2;
477 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
479 MaxSearchTime = myTime / Min(movesToGo, 20);
480 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
484 if (PonderingEnabled)
486 MaxSearchTime += MaxSearchTime / 4;
487 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
490 // Fixed depth or fixed number of nodes?
493 InfiniteSearch = true; // HACK
498 NodesBetweenPolls = Min(MaxNodes, 30000);
499 InfiniteSearch = true; // HACK
502 NodesBetweenPolls = 30000;
505 // Write information to search log file:
507 LogFile << "Searching: " << pos.to_fen() << std::endl
508 << "infinite: " << infinite
509 << " ponder: " << ponder
510 << " time: " << myTime
511 << " increment: " << myIncrement
512 << " moves to go: " << movesToGo << std::endl;
515 // We're ready to start thinking. Call the iterative deepening loop
519 Value v = id_loop(pos, searchMoves);
520 looseOnTime = ( UseLSNFiltering
527 looseOnTime = false; // reset for next match
528 while (SearchStartTime + myTime + 1000 > get_system_time())
530 id_loop(pos, searchMoves); // to fail gracefully
541 /// init_threads() is called during startup. It launches all helper threads,
542 /// and initializes the split point stack and the global locks and condition
545 void init_threads() {
549 #if !defined(_MSC_VER)
550 pthread_t pthread[1];
553 for (i = 0; i < THREAD_MAX; i++)
554 Threads[i].activeSplitPoints = 0;
556 // Initialize global locks:
557 lock_init(&MPLock, NULL);
558 lock_init(&IOLock, NULL);
560 init_split_point_stack();
562 #if !defined(_MSC_VER)
563 pthread_mutex_init(&WaitLock, NULL);
564 pthread_cond_init(&WaitCond, NULL);
566 for (i = 0; i < THREAD_MAX; i++)
567 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
570 // All threads except the main thread should be initialized to idle state
571 for (i = 1; i < THREAD_MAX; i++)
573 Threads[i].stop = false;
574 Threads[i].workIsWaiting = false;
575 Threads[i].idle = true;
576 Threads[i].running = false;
579 // Launch the helper threads
580 for(i = 1; i < THREAD_MAX; i++)
582 #if !defined(_MSC_VER)
583 pthread_create(pthread, NULL, init_thread, (void*)(&i));
586 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
589 // Wait until the thread has finished launching:
590 while (!Threads[i].running);
595 /// stop_threads() is called when the program exits. It makes all the
596 /// helper threads exit cleanly.
598 void stop_threads() {
600 ActiveThreads = THREAD_MAX; // HACK
601 Idle = false; // HACK
602 wake_sleeping_threads();
603 AllThreadsShouldExit = true;
604 for (int i = 1; i < THREAD_MAX; i++)
606 Threads[i].stop = true;
607 while(Threads[i].running);
609 destroy_split_point_stack();
613 /// nodes_searched() returns the total number of nodes searched so far in
614 /// the current search.
616 int64_t nodes_searched() {
618 int64_t result = 0ULL;
619 for (int i = 0; i < ActiveThreads; i++)
620 result += Threads[i].nodes;
627 // id_loop() is the main iterative deepening loop. It calls root_search
628 // repeatedly with increasing depth until the allocated thinking time has
629 // been consumed, the user stops the search, or the maximum search depth is
632 Value id_loop(const Position &pos, Move searchMoves[]) {
635 SearchStack ss[PLY_MAX_PLUS_2];
637 // searchMoves are verified, copied, scored and sorted
638 RootMoveList rml(p, searchMoves);
642 for (int i = 0; i < THREAD_MAX; i++)
643 Threads[i].H.clear();
645 for (int i = 0; i < 3; i++)
650 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
653 EasyMove = rml.scan_for_easy_move();
655 // Iterative deepening loop
656 while (Iteration < PLY_MAX)
658 // Initialize iteration
661 BestMoveChangesByIteration[Iteration] = 0;
665 std::cout << "info depth " << Iteration << std::endl;
667 // Calculate dynamic search window based on previous iterations
670 if (MultiPV == 1 && Iteration >= 6)
672 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
673 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
675 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
677 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
678 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
682 alpha = - VALUE_INFINITE;
683 beta = VALUE_INFINITE;
686 // Search to the current depth
687 Value value = root_search(p, ss, rml, alpha, beta);
689 // Write PV to transposition table, in case the relevant entries have
690 // been overwritten during the search.
691 TT.insert_pv(p, ss[0].pv);
694 break; // Value cannot be trusted. Break out immediately!
696 //Save info about search result
697 Value speculatedValue;
700 Value delta = value - IterationInfo[Iteration - 1].value;
707 speculatedValue = value + delta;
708 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
710 else if (value <= alpha)
712 assert(value == alpha);
716 speculatedValue = value + delta;
717 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
719 speculatedValue = value;
721 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
722 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
724 // Erase the easy move if it differs from the new best move
725 if (ss[0].pv[0] != EasyMove)
726 EasyMove = MOVE_NONE;
733 bool stopSearch = false;
735 // Stop search early if there is only a single legal move:
736 if (Iteration >= 6 && rml.move_count() == 1)
739 // Stop search early when the last two iterations returned a mate score
741 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
742 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
745 // Stop search early if one move seems to be much better than the rest
746 int64_t nodes = nodes_searched();
750 && EasyMove == ss[0].pv[0]
751 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
752 && current_search_time() > MaxSearchTime / 16)
753 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
754 && current_search_time() > MaxSearchTime / 32)))
757 // Add some extra time if the best move has changed during the last two iterations
758 if (Iteration > 5 && Iteration <= 50)
759 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
760 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
762 // Stop search if most of MaxSearchTime is consumed at the end of the
763 // iteration. We probably don't have enough time to search the first
764 // move at the next iteration anyway.
765 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
770 //FIXME: Implement fail-low emergency measures
774 StopOnPonderhit = true;
778 if (MaxDepth && Iteration >= MaxDepth)
784 // If we are pondering, we shouldn't print the best move before we
787 wait_for_stop_or_ponderhit();
789 // Print final search statistics
790 std::cout << "info nodes " << nodes_searched()
792 << " time " << current_search_time()
793 << " hashfull " << TT.full() << std::endl;
795 // Print the best move and the ponder move to the standard output
796 if (ss[0].pv[0] == MOVE_NONE)
798 ss[0].pv[0] = rml.get_move(0);
799 ss[0].pv[1] = MOVE_NONE;
801 std::cout << "bestmove " << ss[0].pv[0];
802 if (ss[0].pv[1] != MOVE_NONE)
803 std::cout << " ponder " << ss[0].pv[1];
805 std::cout << std::endl;
810 dbg_print_mean(LogFile);
812 if (dbg_show_hit_rate)
813 dbg_print_hit_rate(LogFile);
816 LogFile << "Nodes: " << nodes_searched() << std::endl
817 << "Nodes/second: " << nps() << std::endl
818 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
820 p.do_move(ss[0].pv[0], st);
821 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
822 << std::endl << std::endl;
824 return rml.get_move_score(0);
828 // root_search() is the function which searches the root node. It is
829 // similar to search_pv except that it uses a different move ordering
830 // scheme (perhaps we should try to use this at internal PV nodes, too?)
831 // and prints some information to the standard output.
833 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
835 Value oldAlpha = alpha;
837 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
839 // Loop through all the moves in the root move list
840 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
844 // We failed high, invalidate and skip next moves, leave node-counters
845 // and beta-counters as they are and quickly return, we will try to do
846 // a research at the next iteration with a bigger aspiration window.
847 rml.set_move_score(i, -VALUE_INFINITE);
855 RootMoveNumber = i + 1;
858 // Remember the node count before the move is searched. The node counts
859 // are used to sort the root moves at the next iteration.
860 nodes = nodes_searched();
862 // Reset beta cut-off counters
865 // Pick the next root move, and print the move and the move number to
866 // the standard output.
867 move = ss[0].currentMove = rml.get_move(i);
868 if (current_search_time() >= 1000)
869 std::cout << "info currmove " << move
870 << " currmovenumber " << i + 1 << std::endl;
872 // Decide search depth for this move
874 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
875 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
877 // Make the move, and search it
878 pos.do_move(move, st, dcCandidates);
882 // Aspiration window is disabled in multi-pv case
884 alpha = -VALUE_INFINITE;
886 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
887 // If the value has dropped a lot compared to the last iteration,
888 // set the boolean variable Problem to true. This variable is used
889 // for time managment: When Problem is true, we try to complete the
890 // current iteration before playing a move.
891 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
893 if (Problem && StopOnPonderhit)
894 StopOnPonderhit = false;
898 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
901 // Fail high! Set the boolean variable FailHigh to true, and
902 // re-search the move with a big window. The variable FailHigh is
903 // used for time managment: We try to avoid aborting the search
904 // prematurely during a fail high research.
906 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
912 // Finished searching the move. If AbortSearch is true, the search
913 // was aborted because the user interrupted the search or because we
914 // ran out of time. In this case, the return value of the search cannot
915 // be trusted, and we break out of the loop without updating the best
920 // Remember the node count for this move. The node counts are used to
921 // sort the root moves at the next iteration.
922 rml.set_move_nodes(i, nodes_searched() - nodes);
924 // Remember the beta-cutoff statistics
926 BetaCounter.read(pos.side_to_move(), our, their);
927 rml.set_beta_counters(i, our, their);
929 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
931 if (value <= alpha && i >= MultiPV)
932 rml.set_move_score(i, -VALUE_INFINITE);
935 // PV move or new best move!
938 rml.set_move_score(i, value);
940 rml.set_move_pv(i, ss[0].pv);
944 // We record how often the best move has been changed in each
945 // iteration. This information is used for time managment: When
946 // the best move changes frequently, we allocate some more time.
948 BestMoveChangesByIteration[Iteration]++;
950 // Print search information to the standard output:
951 std::cout << "info depth " << Iteration
952 << " score " << value_to_string(value)
953 << " time " << current_search_time()
954 << " nodes " << nodes_searched()
958 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
959 std::cout << ss[0].pv[j] << " ";
961 std::cout << std::endl;
964 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
970 // Reset the global variable Problem to false if the value isn't too
971 // far below the final value from the last iteration.
972 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
978 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
981 std::cout << "info multipv " << j + 1
982 << " score " << value_to_string(rml.get_move_score(j))
983 << " depth " << ((j <= i)? Iteration : Iteration - 1)
984 << " time " << current_search_time()
985 << " nodes " << nodes_searched()
989 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
990 std::cout << rml.get_move_pv(j, k) << " ";
992 std::cout << std::endl;
994 alpha = rml.get_move_score(Min(i, MultiPV-1));
996 } // New best move case
998 assert(alpha >= oldAlpha);
1000 FailLow = (alpha == oldAlpha);
1006 // search_pv() is the main search function for PV nodes.
1008 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1009 Depth depth, int ply, int threadID) {
1011 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1012 assert(beta > alpha && beta <= VALUE_INFINITE);
1013 assert(ply >= 0 && ply < PLY_MAX);
1014 assert(threadID >= 0 && threadID < ActiveThreads);
1017 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1019 // Initialize, and make an early exit in case of an aborted search,
1020 // an instant draw, maximum ply reached, etc.
1021 init_node(ss, ply, threadID);
1023 // After init_node() that calls poll()
1024 if (AbortSearch || thread_should_stop(threadID))
1032 if (ply >= PLY_MAX - 1)
1033 return evaluate(pos, ei, threadID);
1035 // Mate distance pruning
1036 Value oldAlpha = alpha;
1037 alpha = Max(value_mated_in(ply), alpha);
1038 beta = Min(value_mate_in(ply+1), beta);
1042 // Transposition table lookup. At PV nodes, we don't use the TT for
1043 // pruning, but only for move ordering.
1044 const TTEntry* tte = TT.retrieve(pos.get_key());
1045 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1047 // Go with internal iterative deepening if we don't have a TT move
1048 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1050 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1051 ttMove = ss[ply].pv[ply];
1054 // Initialize a MovePicker object for the current position, and prepare
1055 // to search all moves
1056 MovePicker mp = MovePicker(pos, true, ttMove, depth, Threads[threadID].H, &ss[ply]);
1058 Move move, movesSearched[256];
1060 Value value, bestValue = -VALUE_INFINITE;
1061 Bitboard dcCandidates = mp.discovered_check_candidates();
1062 Color us = pos.side_to_move();
1063 bool isCheck = pos.is_check();
1064 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1066 // Loop through all legal moves until no moves remain or a beta cutoff
1068 while ( alpha < beta
1069 && (move = mp.get_next_move()) != MOVE_NONE
1070 && !thread_should_stop(threadID))
1072 assert(move_is_ok(move));
1074 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1075 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1076 bool moveIsCapture = pos.move_is_capture(move);
1078 movesSearched[moveCount++] = ss[ply].currentMove = move;
1080 // Decide the new search depth
1082 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1083 Depth newDepth = depth - OnePly + ext;
1085 // Make and search the move
1087 pos.do_move(move, st, dcCandidates);
1089 if (moveCount == 1) // The first move in list is the PV
1090 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1093 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1094 // if the move fails high will be re-searched at full depth.
1095 if ( depth >= 2*OnePly
1096 && moveCount >= LMRPVMoves
1099 && !move_promotion(move)
1100 && !move_is_castle(move)
1101 && !move_is_killer(move, ss[ply]))
1103 ss[ply].reduction = OnePly;
1104 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1107 value = alpha + 1; // Just to trigger next condition
1109 if (value > alpha) // Go with full depth non-pv search
1111 ss[ply].reduction = Depth(0);
1112 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1113 if (value > alpha && value < beta)
1115 // When the search fails high at ply 1 while searching the first
1116 // move at the root, set the flag failHighPly1. This is used for
1117 // time managment: We don't want to stop the search early in
1118 // such cases, because resolving the fail high at ply 1 could
1119 // result in a big drop in score at the root.
1120 if (ply == 1 && RootMoveNumber == 1)
1121 Threads[threadID].failHighPly1 = true;
1123 // A fail high occurred. Re-search at full window (pv search)
1124 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1125 Threads[threadID].failHighPly1 = false;
1129 pos.undo_move(move);
1131 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1134 if (value > bestValue)
1141 if (value == value_mate_in(ply + 1))
1142 ss[ply].mateKiller = move;
1144 // If we are at ply 1, and we are searching the first root move at
1145 // ply 0, set the 'Problem' variable if the score has dropped a lot
1146 // (from the computer's point of view) since the previous iteration:
1149 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1154 if ( ActiveThreads > 1
1156 && depth >= MinimumSplitDepth
1158 && idle_thread_exists(threadID)
1160 && !thread_should_stop(threadID)
1161 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1162 &moveCount, &mp, dcCandidates, threadID, true))
1166 // All legal moves have been searched. A special case: If there were
1167 // no legal moves, it must be mate or stalemate:
1169 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1171 // If the search is not aborted, update the transposition table,
1172 // history counters, and killer moves.
1173 if (AbortSearch || thread_should_stop(threadID))
1176 if (bestValue <= oldAlpha)
1177 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1179 else if (bestValue >= beta)
1181 BetaCounter.add(pos.side_to_move(), depth, threadID);
1182 Move m = ss[ply].pv[ply];
1183 if (ok_to_history(pos, m)) // Only non capture moves are considered
1185 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1186 update_killers(m, ss[ply]);
1188 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1191 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1197 // search() is the search function for zero-width nodes.
1199 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1200 int ply, bool allowNullmove, int threadID) {
1202 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1203 assert(ply >= 0 && ply < PLY_MAX);
1204 assert(threadID >= 0 && threadID < ActiveThreads);
1207 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1209 // Initialize, and make an early exit in case of an aborted search,
1210 // an instant draw, maximum ply reached, etc.
1211 init_node(ss, ply, threadID);
1213 // After init_node() that calls poll()
1214 if (AbortSearch || thread_should_stop(threadID))
1222 if (ply >= PLY_MAX - 1)
1223 return evaluate(pos, ei, threadID);
1225 // Mate distance pruning
1226 if (value_mated_in(ply) >= beta)
1229 if (value_mate_in(ply + 1) < beta)
1232 // Transposition table lookup
1233 const TTEntry* tte = TT.retrieve(pos.get_key());
1234 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1236 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1238 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1239 return value_from_tt(tte->value(), ply);
1242 Value approximateEval = quick_evaluate(pos);
1243 bool mateThreat = false;
1244 bool isCheck = pos.is_check();
1250 && !value_is_mate(beta)
1251 && ok_to_do_nullmove(pos)
1252 && approximateEval >= beta - NullMoveMargin)
1254 ss[ply].currentMove = MOVE_NULL;
1257 pos.do_null_move(st);
1258 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1260 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1262 pos.undo_null_move();
1264 if (value_is_mate(nullValue))
1266 /* Do not return unproven mates */
1268 else if (nullValue >= beta)
1270 if (depth < 6 * OnePly)
1273 // Do zugzwang verification search
1274 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1278 // The null move failed low, which means that we may be faced with
1279 // some kind of threat. If the previous move was reduced, check if
1280 // the move that refuted the null move was somehow connected to the
1281 // move which was reduced. If a connection is found, return a fail
1282 // low score (which will cause the reduced move to fail high in the
1283 // parent node, which will trigger a re-search with full depth).
1284 if (nullValue == value_mated_in(ply + 2))
1287 ss[ply].threatMove = ss[ply + 1].currentMove;
1288 if ( depth < ThreatDepth
1289 && ss[ply - 1].reduction
1290 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1294 // Null move search not allowed, try razoring
1295 else if ( !value_is_mate(beta)
1296 && depth < RazorDepth
1297 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1298 && ss[ply - 1].currentMove != MOVE_NULL
1299 && ttMove == MOVE_NONE
1300 && !pos.has_pawn_on_7th(pos.side_to_move()))
1302 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1303 if (v < beta - RazorMargins[int(depth) - 2])
1307 // Go with internal iterative deepening if we don't have a TT move
1308 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1309 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1311 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1312 ttMove = ss[ply].pv[ply];
1315 // Initialize a MovePicker object for the current position, and prepare
1316 // to search all moves:
1317 MovePicker mp = MovePicker(pos, false, ttMove, depth, Threads[threadID].H, &ss[ply]);
1319 Move move, movesSearched[256];
1321 Value value, bestValue = -VALUE_INFINITE;
1322 Bitboard dcCandidates = mp.discovered_check_candidates();
1323 Value futilityValue = VALUE_NONE;
1324 bool useFutilityPruning = depth < SelectiveDepth
1327 // Loop through all legal moves until no moves remain or a beta cutoff
1329 while ( bestValue < beta
1330 && (move = mp.get_next_move()) != MOVE_NONE
1331 && !thread_should_stop(threadID))
1333 assert(move_is_ok(move));
1335 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1336 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1337 bool moveIsCapture = pos.move_is_capture(move);
1339 movesSearched[moveCount++] = ss[ply].currentMove = move;
1341 // Decide the new search depth
1343 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1344 Depth newDepth = depth - OnePly + ext;
1347 if ( useFutilityPruning
1350 && !move_promotion(move))
1352 // History pruning. See ok_to_prune() definition
1353 if ( moveCount >= 2 + int(depth)
1354 && ok_to_prune(pos, move, ss[ply].threatMove, depth, Threads[threadID].H))
1357 // Value based pruning
1358 if (approximateEval < beta)
1360 if (futilityValue == VALUE_NONE)
1361 futilityValue = evaluate(pos, ei, threadID)
1362 + FutilityMargins[int(depth) - 2];
1364 if (futilityValue < beta)
1366 if (futilityValue > bestValue)
1367 bestValue = futilityValue;
1373 // Make and search the move
1375 pos.do_move(move, st, dcCandidates);
1377 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1378 // if the move fails high will be re-searched at full depth.
1379 if ( depth >= 2*OnePly
1380 && moveCount >= LMRNonPVMoves
1383 && !move_promotion(move)
1384 && !move_is_castle(move)
1385 && !move_is_killer(move, ss[ply]))
1387 ss[ply].reduction = OnePly;
1388 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1391 value = beta; // Just to trigger next condition
1393 if (value >= beta) // Go with full depth non-pv search
1395 ss[ply].reduction = Depth(0);
1396 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1398 pos.undo_move(move);
1400 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1403 if (value > bestValue)
1409 if (value == value_mate_in(ply + 1))
1410 ss[ply].mateKiller = move;
1414 if ( ActiveThreads > 1
1416 && depth >= MinimumSplitDepth
1418 && idle_thread_exists(threadID)
1420 && !thread_should_stop(threadID)
1421 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1422 &mp, dcCandidates, threadID, false))
1426 // All legal moves have been searched. A special case: If there were
1427 // no legal moves, it must be mate or stalemate.
1429 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1431 // If the search is not aborted, update the transposition table,
1432 // history counters, and killer moves.
1433 if (AbortSearch || thread_should_stop(threadID))
1436 if (bestValue < beta)
1437 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1440 BetaCounter.add(pos.side_to_move(), depth, threadID);
1441 Move m = ss[ply].pv[ply];
1442 if (ok_to_history(pos, m)) // Only non capture moves are considered
1444 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1445 update_killers(m, ss[ply]);
1447 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1450 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1456 // qsearch() is the quiescence search function, which is called by the main
1457 // search function when the remaining depth is zero (or, to be more precise,
1458 // less than OnePly).
1460 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1461 Depth depth, int ply, int threadID) {
1463 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1464 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1466 assert(ply >= 0 && ply < PLY_MAX);
1467 assert(threadID >= 0 && threadID < ActiveThreads);
1469 // Initialize, and make an early exit in case of an aborted search,
1470 // an instant draw, maximum ply reached, etc.
1471 init_node(ss, ply, threadID);
1473 // After init_node() that calls poll()
1474 if (AbortSearch || thread_should_stop(threadID))
1480 // Transposition table lookup, only when not in PV
1481 TTEntry* tte = NULL;
1482 bool pvNode = (beta - alpha != 1);
1485 tte = TT.retrieve(pos.get_key());
1486 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1488 assert(tte->type() != VALUE_TYPE_EVAL);
1490 return value_from_tt(tte->value(), ply);
1493 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1495 // Evaluate the position statically
1498 bool isCheck = pos.is_check();
1499 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1502 staticValue = -VALUE_INFINITE;
1504 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1506 // Use the cached evaluation score if possible
1507 assert(tte->value() == evaluate(pos, ei, threadID));
1508 assert(ei.futilityMargin == Value(0));
1510 staticValue = tte->value();
1513 staticValue = evaluate(pos, ei, threadID);
1515 if (ply == PLY_MAX - 1)
1516 return evaluate(pos, ei, threadID);
1518 // Initialize "stand pat score", and return it immediately if it is
1520 Value bestValue = staticValue;
1522 if (bestValue >= beta)
1524 // Store the score to avoid a future costly evaluation() call
1525 if (!isCheck && !tte && ei.futilityMargin == 0)
1526 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE);
1531 if (bestValue > alpha)
1534 // Initialize a MovePicker object for the current position, and prepare
1535 // to search the moves. Because the depth is <= 0 here, only captures,
1536 // queen promotions and checks (only if depth == 0) will be generated.
1537 MovePicker mp = MovePicker(pos, pvNode, ttMove, depth, Threads[threadID].H);
1540 Bitboard dcCandidates = mp.discovered_check_candidates();
1541 Color us = pos.side_to_move();
1542 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1544 // Loop through the moves until no moves remain or a beta cutoff
1546 while ( alpha < beta
1547 && (move = mp.get_next_move()) != MOVE_NONE)
1549 assert(move_is_ok(move));
1552 ss[ply].currentMove = move;
1558 && !move_promotion(move)
1559 && !pos.move_is_check(move, dcCandidates)
1560 && !pos.move_is_passed_pawn_push(move))
1562 Value futilityValue = staticValue
1563 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1564 pos.endgame_value_of_piece_on(move_to(move)))
1565 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1567 + ei.futilityMargin;
1569 if (futilityValue < alpha)
1571 if (futilityValue > bestValue)
1572 bestValue = futilityValue;
1577 // Don't search captures and checks with negative SEE values
1579 && !move_promotion(move)
1580 && (pos.midgame_value_of_piece_on(move_from(move)) >
1581 pos.midgame_value_of_piece_on(move_to(move)))
1582 && pos.see(move) < 0)
1585 // Make and search the move.
1587 pos.do_move(move, st, dcCandidates);
1588 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1589 pos.undo_move(move);
1591 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1594 if (value > bestValue)
1605 // All legal moves have been searched. A special case: If we're in check
1606 // and no legal moves were found, it is checkmate:
1607 if (pos.is_check() && moveCount == 0) // Mate!
1608 return value_mated_in(ply);
1610 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1612 // Update transposition table
1613 Move m = ss[ply].pv[ply];
1616 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1617 if (bestValue < beta)
1618 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1620 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1623 // Update killers only for good check moves
1624 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1625 update_killers(m, ss[ply]);
1631 // sp_search() is used to search from a split point. This function is called
1632 // by each thread working at the split point. It is similar to the normal
1633 // search() function, but simpler. Because we have already probed the hash
1634 // table, done a null move search, and searched the first move before
1635 // splitting, we don't have to repeat all this work in sp_search(). We
1636 // also don't need to store anything to the hash table here: This is taken
1637 // care of after we return from the split point.
1639 void sp_search(SplitPoint *sp, int threadID) {
1641 assert(threadID >= 0 && threadID < ActiveThreads);
1642 assert(ActiveThreads > 1);
1644 Position pos = Position(sp->pos);
1645 SearchStack *ss = sp->sstack[threadID];
1648 bool isCheck = pos.is_check();
1649 bool useFutilityPruning = sp->depth < SelectiveDepth
1652 while ( sp->bestValue < sp->beta
1653 && !thread_should_stop(threadID)
1654 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1656 assert(move_is_ok(move));
1658 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1659 bool moveIsCapture = pos.move_is_capture(move);
1661 lock_grab(&(sp->lock));
1662 int moveCount = ++sp->moves;
1663 lock_release(&(sp->lock));
1665 ss[sp->ply].currentMove = move;
1667 // Decide the new search depth.
1669 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1670 Depth newDepth = sp->depth - OnePly + ext;
1673 if ( useFutilityPruning
1676 && !move_promotion(move)
1677 && moveCount >= 2 + int(sp->depth)
1678 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth, Threads[threadID].H))
1681 // Make and search the move.
1683 pos.do_move(move, st, sp->dcCandidates);
1685 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1686 // if the move fails high will be re-searched at full depth.
1688 && moveCount >= LMRNonPVMoves
1690 && !move_promotion(move)
1691 && !move_is_castle(move)
1692 && !move_is_killer(move, ss[sp->ply]))
1694 ss[sp->ply].reduction = OnePly;
1695 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1698 value = sp->beta; // Just to trigger next condition
1700 if (value >= sp->beta) // Go with full depth non-pv search
1702 ss[sp->ply].reduction = Depth(0);
1703 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1705 pos.undo_move(move);
1707 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1709 if (thread_should_stop(threadID))
1713 lock_grab(&(sp->lock));
1714 if (value > sp->bestValue && !thread_should_stop(threadID))
1716 sp->bestValue = value;
1717 if (sp->bestValue >= sp->beta)
1719 sp_update_pv(sp->parentSstack, ss, sp->ply);
1720 for (int i = 0; i < ActiveThreads; i++)
1721 if (i != threadID && (i == sp->master || sp->slaves[i]))
1722 Threads[i].stop = true;
1724 sp->finished = true;
1727 lock_release(&(sp->lock));
1730 lock_grab(&(sp->lock));
1732 // If this is the master thread and we have been asked to stop because of
1733 // a beta cutoff higher up in the tree, stop all slave threads:
1734 if (sp->master == threadID && thread_should_stop(threadID))
1735 for (int i = 0; i < ActiveThreads; i++)
1737 Threads[i].stop = true;
1740 sp->slaves[threadID] = 0;
1742 lock_release(&(sp->lock));
1746 // sp_search_pv() is used to search from a PV split point. This function
1747 // is called by each thread working at the split point. It is similar to
1748 // the normal search_pv() function, but simpler. Because we have already
1749 // probed the hash table and searched the first move before splitting, we
1750 // don't have to repeat all this work in sp_search_pv(). We also don't
1751 // need to store anything to the hash table here: This is taken care of
1752 // after we return from the split point.
1754 void sp_search_pv(SplitPoint *sp, int threadID) {
1756 assert(threadID >= 0 && threadID < ActiveThreads);
1757 assert(ActiveThreads > 1);
1759 Position pos = Position(sp->pos);
1760 SearchStack *ss = sp->sstack[threadID];
1764 while ( sp->alpha < sp->beta
1765 && !thread_should_stop(threadID)
1766 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1768 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1769 bool moveIsCapture = pos.move_is_capture(move);
1771 assert(move_is_ok(move));
1773 lock_grab(&(sp->lock));
1774 int moveCount = ++sp->moves;
1775 lock_release(&(sp->lock));
1777 ss[sp->ply].currentMove = move;
1779 // Decide the new search depth.
1781 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1782 Depth newDepth = sp->depth - OnePly + ext;
1784 // Make and search the move.
1786 pos.do_move(move, st, sp->dcCandidates);
1788 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1789 // if the move fails high will be re-searched at full depth.
1791 && moveCount >= LMRPVMoves
1793 && !move_promotion(move)
1794 && !move_is_castle(move)
1795 && !move_is_killer(move, ss[sp->ply]))
1797 ss[sp->ply].reduction = OnePly;
1798 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1801 value = sp->alpha + 1; // Just to trigger next condition
1803 if (value > sp->alpha) // Go with full depth non-pv search
1805 ss[sp->ply].reduction = Depth(0);
1806 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1808 if (value > sp->alpha && value < sp->beta)
1810 // When the search fails high at ply 1 while searching the first
1811 // move at the root, set the flag failHighPly1. This is used for
1812 // time managment: We don't want to stop the search early in
1813 // such cases, because resolving the fail high at ply 1 could
1814 // result in a big drop in score at the root.
1815 if (sp->ply == 1 && RootMoveNumber == 1)
1816 Threads[threadID].failHighPly1 = true;
1818 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1819 Threads[threadID].failHighPly1 = false;
1822 pos.undo_move(move);
1824 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1826 if (thread_should_stop(threadID))
1830 lock_grab(&(sp->lock));
1831 if (value > sp->bestValue && !thread_should_stop(threadID))
1833 sp->bestValue = value;
1834 if (value > sp->alpha)
1837 sp_update_pv(sp->parentSstack, ss, sp->ply);
1838 if (value == value_mate_in(sp->ply + 1))
1839 ss[sp->ply].mateKiller = move;
1841 if(value >= sp->beta)
1843 for(int i = 0; i < ActiveThreads; i++)
1844 if(i != threadID && (i == sp->master || sp->slaves[i]))
1845 Threads[i].stop = true;
1847 sp->finished = true;
1850 // If we are at ply 1, and we are searching the first root move at
1851 // ply 0, set the 'Problem' variable if the score has dropped a lot
1852 // (from the computer's point of view) since the previous iteration.
1855 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1858 lock_release(&(sp->lock));
1861 lock_grab(&(sp->lock));
1863 // If this is the master thread and we have been asked to stop because of
1864 // a beta cutoff higher up in the tree, stop all slave threads.
1865 if (sp->master == threadID && thread_should_stop(threadID))
1866 for (int i = 0; i < ActiveThreads; i++)
1868 Threads[i].stop = true;
1871 sp->slaves[threadID] = 0;
1873 lock_release(&(sp->lock));
1876 /// The BetaCounterType class
1878 BetaCounterType::BetaCounterType() { clear(); }
1880 void BetaCounterType::clear() {
1882 for (int i = 0; i < THREAD_MAX; i++)
1883 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1886 void BetaCounterType::add(Color us, Depth d, int threadID) {
1888 // Weighted count based on depth
1889 Threads[threadID].betaCutOffs[us] += unsigned(d);
1892 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1895 for (int i = 0; i < THREAD_MAX; i++)
1897 our += Threads[i].betaCutOffs[us];
1898 their += Threads[i].betaCutOffs[opposite_color(us)];
1903 /// The RootMove class
1907 RootMove::RootMove() {
1908 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1911 // RootMove::operator<() is the comparison function used when
1912 // sorting the moves. A move m1 is considered to be better
1913 // than a move m2 if it has a higher score, or if the moves
1914 // have equal score but m1 has the higher node count.
1916 bool RootMove::operator<(const RootMove& m) {
1918 if (score != m.score)
1919 return (score < m.score);
1921 return theirBeta <= m.theirBeta;
1924 /// The RootMoveList class
1928 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1930 MoveStack mlist[MaxRootMoves];
1931 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1933 // Generate all legal moves
1934 int lm_count = generate_legal_moves(pos, mlist);
1936 // Add each move to the moves[] array
1937 for (int i = 0; i < lm_count; i++)
1939 bool includeMove = includeAllMoves;
1941 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1942 includeMove = (searchMoves[k] == mlist[i].move);
1947 // Find a quick score for the move
1949 SearchStack ss[PLY_MAX_PLUS_2];
1951 moves[count].move = mlist[i].move;
1952 pos.do_move(moves[count].move, st);
1953 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1954 pos.undo_move(moves[count].move);
1955 moves[count].pv[0] = moves[count].move;
1956 moves[count].pv[1] = MOVE_NONE; // FIXME
1963 // Simple accessor methods for the RootMoveList class
1965 inline Move RootMoveList::get_move(int moveNum) const {
1966 return moves[moveNum].move;
1969 inline Value RootMoveList::get_move_score(int moveNum) const {
1970 return moves[moveNum].score;
1973 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1974 moves[moveNum].score = score;
1977 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1978 moves[moveNum].nodes = nodes;
1979 moves[moveNum].cumulativeNodes += nodes;
1982 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1983 moves[moveNum].ourBeta = our;
1984 moves[moveNum].theirBeta = their;
1987 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1989 for(j = 0; pv[j] != MOVE_NONE; j++)
1990 moves[moveNum].pv[j] = pv[j];
1991 moves[moveNum].pv[j] = MOVE_NONE;
1994 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1995 return moves[moveNum].pv[i];
1998 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1999 return moves[moveNum].cumulativeNodes;
2002 inline int RootMoveList::move_count() const {
2007 // RootMoveList::scan_for_easy_move() is called at the end of the first
2008 // iteration, and is used to detect an "easy move", i.e. a move which appears
2009 // to be much bester than all the rest. If an easy move is found, the move
2010 // is returned, otherwise the function returns MOVE_NONE. It is very
2011 // important that this function is called at the right moment: The code
2012 // assumes that the first iteration has been completed and the moves have
2013 // been sorted. This is done in RootMoveList c'tor.
2015 Move RootMoveList::scan_for_easy_move() const {
2022 // moves are sorted so just consider the best and the second one
2023 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2029 // RootMoveList::sort() sorts the root move list at the beginning of a new
2032 inline void RootMoveList::sort() {
2034 sort_multipv(count - 1); // all items
2038 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2039 // list by their scores and depths. It is used to order the different PVs
2040 // correctly in MultiPV mode.
2042 void RootMoveList::sort_multipv(int n) {
2044 for (int i = 1; i <= n; i++)
2046 RootMove rm = moves[i];
2048 for (j = i; j > 0 && moves[j-1] < rm; j--)
2049 moves[j] = moves[j-1];
2055 // init_node() is called at the beginning of all the search functions
2056 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2057 // stack object corresponding to the current node. Once every
2058 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2059 // for user input and checks whether it is time to stop the search.
2061 void init_node(SearchStack ss[], int ply, int threadID) {
2062 assert(ply >= 0 && ply < PLY_MAX);
2063 assert(threadID >= 0 && threadID < ActiveThreads);
2065 Threads[threadID].nodes++;
2069 if(NodesSincePoll >= NodesBetweenPolls) {
2076 ss[ply+2].initKillers();
2078 if(Threads[threadID].printCurrentLine)
2079 print_current_line(ss, ply, threadID);
2083 // update_pv() is called whenever a search returns a value > alpha. It
2084 // updates the PV in the SearchStack object corresponding to the current
2087 void update_pv(SearchStack ss[], int ply) {
2088 assert(ply >= 0 && ply < PLY_MAX);
2090 ss[ply].pv[ply] = ss[ply].currentMove;
2092 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2093 ss[ply].pv[p] = ss[ply+1].pv[p];
2094 ss[ply].pv[p] = MOVE_NONE;
2098 // sp_update_pv() is a variant of update_pv for use at split points. The
2099 // difference between the two functions is that sp_update_pv also updates
2100 // the PV at the parent node.
2102 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2103 assert(ply >= 0 && ply < PLY_MAX);
2105 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2107 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2108 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2109 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2113 // connected_moves() tests whether two moves are 'connected' in the sense
2114 // that the first move somehow made the second move possible (for instance
2115 // if the moving piece is the same in both moves). The first move is
2116 // assumed to be the move that was made to reach the current position, while
2117 // the second move is assumed to be a move from the current position.
2119 bool connected_moves(const Position &pos, Move m1, Move m2) {
2120 Square f1, t1, f2, t2;
2122 assert(move_is_ok(m1));
2123 assert(move_is_ok(m2));
2128 // Case 1: The moving piece is the same in both moves.
2134 // Case 2: The destination square for m2 was vacated by m1.
2140 // Case 3: Moving through the vacated square:
2141 if(piece_is_slider(pos.piece_on(f2)) &&
2142 bit_is_set(squares_between(f2, t2), f1))
2145 // Case 4: The destination square for m2 is attacked by the moving piece
2147 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2150 // Case 5: Discovered check, checking piece is the piece moved in m1:
2151 if(piece_is_slider(pos.piece_on(t1)) &&
2152 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2154 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2156 Bitboard occ = pos.occupied_squares();
2157 Color us = pos.side_to_move();
2158 Square ksq = pos.king_square(us);
2159 clear_bit(&occ, f2);
2160 if(pos.type_of_piece_on(t1) == BISHOP) {
2161 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2164 else if(pos.type_of_piece_on(t1) == ROOK) {
2165 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2169 assert(pos.type_of_piece_on(t1) == QUEEN);
2170 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2179 // value_is_mate() checks if the given value is a mate one
2180 // eventually compensated for the ply.
2182 bool value_is_mate(Value value) {
2184 assert(abs(value) <= VALUE_INFINITE);
2186 return value <= value_mated_in(PLY_MAX)
2187 || value >= value_mate_in(PLY_MAX);
2191 // move_is_killer() checks if the given move is among the
2192 // killer moves of that ply.
2194 bool move_is_killer(Move m, const SearchStack& ss) {
2196 const Move* k = ss.killers;
2197 for (int i = 0; i < KILLER_MAX; i++, k++)
2205 // extension() decides whether a move should be searched with normal depth,
2206 // or with extended depth. Certain classes of moves (checking moves, in
2207 // particular) are searched with bigger depth than ordinary moves and in
2208 // any case are marked as 'dangerous'. Note that also if a move is not
2209 // extended, as example because the corresponding UCI option is set to zero,
2210 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2212 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2213 bool singleReply, bool mateThreat, bool* dangerous) {
2215 assert(m != MOVE_NONE);
2217 Depth result = Depth(0);
2218 *dangerous = check || singleReply || mateThreat;
2221 result += CheckExtension[pvNode];
2224 result += SingleReplyExtension[pvNode];
2227 result += MateThreatExtension[pvNode];
2229 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2231 if (pos.move_is_pawn_push_to_7th(m))
2233 result += PawnPushTo7thExtension[pvNode];
2236 if (pos.move_is_passed_pawn_push(m))
2238 result += PassedPawnExtension[pvNode];
2244 && pos.type_of_piece_on(move_to(m)) != PAWN
2245 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2246 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2247 && !move_promotion(m)
2250 result += PawnEndgameExtension[pvNode];
2256 && pos.type_of_piece_on(move_to(m)) != PAWN
2263 return Min(result, OnePly);
2267 // ok_to_do_nullmove() looks at the current position and decides whether
2268 // doing a 'null move' should be allowed. In order to avoid zugzwang
2269 // problems, null moves are not allowed when the side to move has very
2270 // little material left. Currently, the test is a bit too simple: Null
2271 // moves are avoided only when the side to move has only pawns left. It's
2272 // probably a good idea to avoid null moves in at least some more
2273 // complicated endgames, e.g. KQ vs KR. FIXME
2275 bool ok_to_do_nullmove(const Position &pos) {
2276 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2282 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2283 // non-tactical moves late in the move list close to the leaves are
2284 // candidates for pruning.
2286 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d, const History& H) {
2287 Square mfrom, mto, tfrom, tto;
2289 assert(move_is_ok(m));
2290 assert(threat == MOVE_NONE || move_is_ok(threat));
2291 assert(!move_promotion(m));
2292 assert(!pos.move_is_check(m));
2293 assert(!pos.move_is_capture(m));
2294 assert(!pos.move_is_passed_pawn_push(m));
2295 assert(d >= OnePly);
2297 mfrom = move_from(m);
2299 tfrom = move_from(threat);
2300 tto = move_to(threat);
2302 // Case 1: Castling moves are never pruned.
2303 if (move_is_castle(m))
2306 // Case 2: Don't prune moves which move the threatened piece
2307 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2310 // Case 3: If the threatened piece has value less than or equal to the
2311 // value of the threatening piece, don't prune move which defend it.
2312 if ( !PruneDefendingMoves
2313 && threat != MOVE_NONE
2314 && pos.move_is_capture(threat)
2315 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2316 || pos.type_of_piece_on(tfrom) == KING)
2317 && pos.move_attacks_square(m, tto))
2320 // Case 4: Don't prune moves with good history.
2321 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2324 // Case 5: If the moving piece in the threatened move is a slider, don't
2325 // prune safe moves which block its ray.
2326 if ( !PruneBlockingMoves
2327 && threat != MOVE_NONE
2328 && piece_is_slider(pos.piece_on(tfrom))
2329 && bit_is_set(squares_between(tfrom, tto), mto)
2337 // ok_to_use_TT() returns true if a transposition table score
2338 // can be used at a given point in search.
2340 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2342 Value v = value_from_tt(tte->value(), ply);
2344 return ( tte->depth() >= depth
2345 || v >= Max(value_mate_in(100), beta)
2346 || v < Min(value_mated_in(100), beta))
2348 && ( (is_lower_bound(tte->type()) && v >= beta)
2349 || (is_upper_bound(tte->type()) && v < beta));
2353 // ok_to_history() returns true if a move m can be stored
2354 // in history. Should be a non capturing move nor a promotion.
2356 bool ok_to_history(const Position& pos, Move m) {
2358 return !pos.move_is_capture(m) && !move_promotion(m);
2362 // update_history() registers a good move that produced a beta-cutoff
2363 // in history and marks as failures all the other moves of that ply.
2365 void update_history(const Position& pos, Move m, Depth depth, History& H,
2366 Move movesSearched[], int moveCount) {
2368 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2370 for (int i = 0; i < moveCount - 1; i++)
2372 assert(m != movesSearched[i]);
2373 if (ok_to_history(pos, movesSearched[i]))
2374 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2379 // update_killers() add a good move that produced a beta-cutoff
2380 // among the killer moves of that ply.
2382 void update_killers(Move m, SearchStack& ss) {
2384 if (m == ss.killers[0])
2387 for (int i = KILLER_MAX - 1; i > 0; i--)
2388 ss.killers[i] = ss.killers[i - 1];
2393 // fail_high_ply_1() checks if some thread is currently resolving a fail
2394 // high at ply 1 at the node below the first root node. This information
2395 // is used for time managment.
2397 bool fail_high_ply_1() {
2398 for(int i = 0; i < ActiveThreads; i++)
2399 if(Threads[i].failHighPly1)
2405 // current_search_time() returns the number of milliseconds which have passed
2406 // since the beginning of the current search.
2408 int current_search_time() {
2409 return get_system_time() - SearchStartTime;
2413 // nps() computes the current nodes/second count.
2416 int t = current_search_time();
2417 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2421 // poll() performs two different functions: It polls for user input, and it
2422 // looks at the time consumed so far and decides if it's time to abort the
2427 static int lastInfoTime;
2428 int t = current_search_time();
2433 // We are line oriented, don't read single chars
2434 std::string command;
2435 if (!std::getline(std::cin, command))
2438 if (command == "quit")
2441 PonderSearch = false;
2445 else if(command == "stop")
2448 PonderSearch = false;
2450 else if(command == "ponderhit")
2453 // Print search information
2457 else if (lastInfoTime > t)
2458 // HACK: Must be a new search where we searched less than
2459 // NodesBetweenPolls nodes during the first second of search.
2462 else if (t - lastInfoTime >= 1000)
2469 if (dbg_show_hit_rate)
2470 dbg_print_hit_rate();
2472 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2473 << " time " << t << " hashfull " << TT.full() << std::endl;
2474 lock_release(&IOLock);
2475 if (ShowCurrentLine)
2476 Threads[0].printCurrentLine = true;
2478 // Should we stop the search?
2482 bool overTime = t > AbsoluteMaxSearchTime
2483 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2484 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2485 && t > 6*(MaxSearchTime + ExtraSearchTime));
2487 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2488 || (ExactMaxTime && t >= ExactMaxTime)
2489 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2494 // ponderhit() is called when the program is pondering (i.e. thinking while
2495 // it's the opponent's turn to move) in order to let the engine know that
2496 // it correctly predicted the opponent's move.
2499 int t = current_search_time();
2500 PonderSearch = false;
2501 if(Iteration >= 3 &&
2502 (!InfiniteSearch && (StopOnPonderhit ||
2503 t > AbsoluteMaxSearchTime ||
2504 (RootMoveNumber == 1 &&
2505 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2506 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2507 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2512 // print_current_line() prints the current line of search for a given
2513 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2515 void print_current_line(SearchStack ss[], int ply, int threadID) {
2516 assert(ply >= 0 && ply < PLY_MAX);
2517 assert(threadID >= 0 && threadID < ActiveThreads);
2519 if(!Threads[threadID].idle) {
2521 std::cout << "info currline " << (threadID + 1);
2522 for(int p = 0; p < ply; p++)
2523 std::cout << " " << ss[p].currentMove;
2524 std::cout << std::endl;
2525 lock_release(&IOLock);
2527 Threads[threadID].printCurrentLine = false;
2528 if(threadID + 1 < ActiveThreads)
2529 Threads[threadID + 1].printCurrentLine = true;
2533 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2534 // while the program is pondering. The point is to work around a wrinkle in
2535 // the UCI protocol: When pondering, the engine is not allowed to give a
2536 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2537 // We simply wait here until one of these commands is sent, and return,
2538 // after which the bestmove and pondermove will be printed (in id_loop()).
2540 void wait_for_stop_or_ponderhit() {
2542 std::string command;
2546 if (!std::getline(std::cin, command))
2549 if (command == "quit")
2554 else if(command == "ponderhit" || command == "stop")
2560 // idle_loop() is where the threads are parked when they have no work to do.
2561 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2562 // object for which the current thread is the master.
2564 void idle_loop(int threadID, SplitPoint *waitSp) {
2565 assert(threadID >= 0 && threadID < THREAD_MAX);
2567 Threads[threadID].running = true;
2570 if(AllThreadsShouldExit && threadID != 0)
2573 // If we are not thinking, wait for a condition to be signaled instead
2574 // of wasting CPU time polling for work:
2575 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2576 #if !defined(_MSC_VER)
2577 pthread_mutex_lock(&WaitLock);
2578 if(Idle || threadID >= ActiveThreads)
2579 pthread_cond_wait(&WaitCond, &WaitLock);
2580 pthread_mutex_unlock(&WaitLock);
2582 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2586 // If this thread has been assigned work, launch a search:
2587 if(Threads[threadID].workIsWaiting) {
2588 Threads[threadID].workIsWaiting = false;
2589 if(Threads[threadID].splitPoint->pvNode)
2590 sp_search_pv(Threads[threadID].splitPoint, threadID);
2592 sp_search(Threads[threadID].splitPoint, threadID);
2593 Threads[threadID].idle = true;
2596 // If this thread is the master of a split point and all threads have
2597 // finished their work at this split point, return from the idle loop:
2598 if(waitSp != NULL && waitSp->cpus == 0)
2602 Threads[threadID].running = false;
2606 // init_split_point_stack() is called during program initialization, and
2607 // initializes all split point objects.
2609 void init_split_point_stack() {
2610 for(int i = 0; i < THREAD_MAX; i++)
2611 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2612 SplitPointStack[i][j].parent = NULL;
2613 lock_init(&(SplitPointStack[i][j].lock), NULL);
2618 // destroy_split_point_stack() is called when the program exits, and
2619 // destroys all locks in the precomputed split point objects.
2621 void destroy_split_point_stack() {
2622 for(int i = 0; i < THREAD_MAX; i++)
2623 for(int j = 0; j < MaxActiveSplitPoints; j++)
2624 lock_destroy(&(SplitPointStack[i][j].lock));
2628 // thread_should_stop() checks whether the thread with a given threadID has
2629 // been asked to stop, directly or indirectly. This can happen if a beta
2630 // cutoff has occured in thre thread's currently active split point, or in
2631 // some ancestor of the current split point.
2633 bool thread_should_stop(int threadID) {
2634 assert(threadID >= 0 && threadID < ActiveThreads);
2638 if(Threads[threadID].stop)
2640 if(ActiveThreads <= 2)
2642 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2644 Threads[threadID].stop = true;
2651 // thread_is_available() checks whether the thread with threadID "slave" is
2652 // available to help the thread with threadID "master" at a split point. An
2653 // obvious requirement is that "slave" must be idle. With more than two
2654 // threads, this is not by itself sufficient: If "slave" is the master of
2655 // some active split point, it is only available as a slave to the other
2656 // threads which are busy searching the split point at the top of "slave"'s
2657 // split point stack (the "helpful master concept" in YBWC terminology).
2659 bool thread_is_available(int slave, int master) {
2660 assert(slave >= 0 && slave < ActiveThreads);
2661 assert(master >= 0 && master < ActiveThreads);
2662 assert(ActiveThreads > 1);
2664 if(!Threads[slave].idle || slave == master)
2667 if(Threads[slave].activeSplitPoints == 0)
2668 // No active split points means that the thread is available as a slave
2669 // for any other thread.
2672 if(ActiveThreads == 2)
2675 // Apply the "helpful master" concept if possible.
2676 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2683 // idle_thread_exists() tries to find an idle thread which is available as
2684 // a slave for the thread with threadID "master".
2686 bool idle_thread_exists(int master) {
2687 assert(master >= 0 && master < ActiveThreads);
2688 assert(ActiveThreads > 1);
2690 for(int i = 0; i < ActiveThreads; i++)
2691 if(thread_is_available(i, master))
2697 // split() does the actual work of distributing the work at a node between
2698 // several threads at PV nodes. If it does not succeed in splitting the
2699 // node (because no idle threads are available, or because we have no unused
2700 // split point objects), the function immediately returns false. If
2701 // splitting is possible, a SplitPoint object is initialized with all the
2702 // data that must be copied to the helper threads (the current position and
2703 // search stack, alpha, beta, the search depth, etc.), and we tell our
2704 // helper threads that they have been assigned work. This will cause them
2705 // to instantly leave their idle loops and call sp_search_pv(). When all
2706 // threads have returned from sp_search_pv (or, equivalently, when
2707 // splitPoint->cpus becomes 0), split() returns true.
2709 bool split(const Position &p, SearchStack *sstck, int ply,
2710 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2711 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2714 assert(sstck != NULL);
2715 assert(ply >= 0 && ply < PLY_MAX);
2716 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2717 assert(!pvNode || *alpha < *beta);
2718 assert(*beta <= VALUE_INFINITE);
2719 assert(depth > Depth(0));
2720 assert(master >= 0 && master < ActiveThreads);
2721 assert(ActiveThreads > 1);
2723 SplitPoint *splitPoint;
2728 // If no other thread is available to help us, or if we have too many
2729 // active split points, don't split:
2730 if(!idle_thread_exists(master) ||
2731 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2732 lock_release(&MPLock);
2736 // Pick the next available split point object from the split point stack:
2737 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2738 Threads[master].activeSplitPoints++;
2740 // Initialize the split point object:
2741 splitPoint->parent = Threads[master].splitPoint;
2742 splitPoint->finished = false;
2743 splitPoint->ply = ply;
2744 splitPoint->depth = depth;
2745 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2746 splitPoint->beta = *beta;
2747 splitPoint->pvNode = pvNode;
2748 splitPoint->dcCandidates = dcCandidates;
2749 splitPoint->bestValue = *bestValue;
2750 splitPoint->master = master;
2751 splitPoint->mp = mp;
2752 splitPoint->moves = *moves;
2753 splitPoint->cpus = 1;
2754 splitPoint->pos.copy(p);
2755 splitPoint->parentSstack = sstck;
2756 for(i = 0; i < ActiveThreads; i++)
2757 splitPoint->slaves[i] = 0;
2759 // Copy the current position and the search stack to the master thread:
2760 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2761 Threads[master].splitPoint = splitPoint;
2763 // Make copies of the current position and search stack for each thread:
2764 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2766 if(thread_is_available(i, master)) {
2767 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2768 Threads[i].splitPoint = splitPoint;
2769 splitPoint->slaves[i] = 1;
2773 // Tell the threads that they have work to do. This will make them leave
2775 for(i = 0; i < ActiveThreads; i++)
2776 if(i == master || splitPoint->slaves[i]) {
2777 Threads[i].workIsWaiting = true;
2778 Threads[i].idle = false;
2779 Threads[i].stop = false;
2782 lock_release(&MPLock);
2784 // Everything is set up. The master thread enters the idle loop, from
2785 // which it will instantly launch a search, because its workIsWaiting
2786 // slot is 'true'. We send the split point as a second parameter to the
2787 // idle loop, which means that the main thread will return from the idle
2788 // loop when all threads have finished their work at this split point
2789 // (i.e. when // splitPoint->cpus == 0).
2790 idle_loop(master, splitPoint);
2792 // We have returned from the idle loop, which means that all threads are
2793 // finished. Update alpha, beta and bestvalue, and return:
2795 if(pvNode) *alpha = splitPoint->alpha;
2796 *beta = splitPoint->beta;
2797 *bestValue = splitPoint->bestValue;
2798 Threads[master].stop = false;
2799 Threads[master].idle = false;
2800 Threads[master].activeSplitPoints--;
2801 Threads[master].splitPoint = splitPoint->parent;
2802 lock_release(&MPLock);
2808 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2809 // to start a new search from the root.
2811 void wake_sleeping_threads() {
2812 if(ActiveThreads > 1) {
2813 for(int i = 1; i < ActiveThreads; i++) {
2814 Threads[i].idle = true;
2815 Threads[i].workIsWaiting = false;
2817 #if !defined(_MSC_VER)
2818 pthread_mutex_lock(&WaitLock);
2819 pthread_cond_broadcast(&WaitCond);
2820 pthread_mutex_unlock(&WaitLock);
2822 for(int i = 1; i < THREAD_MAX; i++)
2823 SetEvent(SitIdleEvent[i]);
2829 // init_thread() is the function which is called when a new thread is
2830 // launched. It simply calls the idle_loop() function with the supplied
2831 // threadID. There are two versions of this function; one for POSIX threads
2832 // and one for Windows threads.
2834 #if !defined(_MSC_VER)
2836 void *init_thread(void *threadID) {
2837 idle_loop(*(int *)threadID, NULL);
2843 DWORD WINAPI init_thread(LPVOID threadID) {
2844 idle_loop(*(int *)threadID, NULL);