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 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/>.
39 #include "ucioption.h"
43 //// Local definitions
50 // IterationInfoType stores search results for each iteration
52 // Because we use relatively small (dynamic) aspiration window,
53 // there happens many fail highs and fail lows in root. And
54 // because we don't do researches in those cases, "value" stored
55 // here is not necessarily exact. Instead in case of fail high/low
56 // we guess what the right value might be and store our guess
57 // as a "speculated value" and then move on. Speculated values are
58 // used just to calculate aspiration window width, so also if are
59 // not exact is not big a problem.
61 struct IterationInfoType {
63 IterationInfoType(Value v = Value(0), Value sv = Value(0))
64 : value(v), speculatedValue(sv) {}
66 Value value, speculatedValue;
70 // The BetaCounterType class is used to order moves at ply one.
71 // Apart for the first one that has its score, following moves
72 // normally have score -VALUE_INFINITE, so are ordered according
73 // to the number of beta cutoffs occurred under their subtree during
74 // the last iteration.
76 struct BetaCounterType {
80 void add(Color us, Depth d, int threadID);
81 void read(Color us, int64_t& our, int64_t& their);
83 int64_t hits[THREAD_MAX][2];
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];
131 /// Constants and variables
133 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
136 int LMRNonPVMoves = 4;
138 // Depth limit for use of dynamic threat detection:
139 Depth ThreatDepth = 5*OnePly;
141 // Depth limit for selective search:
142 Depth SelectiveDepth = 7*OnePly;
144 // Use internal iterative deepening?
145 const bool UseIIDAtPVNodes = true;
146 const bool UseIIDAtNonPVNodes = false;
148 // Internal iterative deepening margin. At Non-PV moves, when
149 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
150 // when the static evaluation is at most IIDMargin below beta.
151 const Value IIDMargin = Value(0x100);
153 // Easy move margin. An easy move candidate must be at least this much
154 // better than the second best move.
155 const Value EasyMoveMargin = Value(0x200);
157 // Problem margin. If the score of the first move at iteration N+1 has
158 // dropped by more than this since iteration N, the boolean variable
159 // "Problem" is set to true, which will make the program spend some extra
160 // time looking for a better move.
161 const Value ProblemMargin = Value(0x28);
163 // No problem margin. If the boolean "Problem" is true, and a new move
164 // is found at the root which is less than NoProblemMargin worse than the
165 // best move from the previous iteration, Problem is set back to false.
166 const Value NoProblemMargin = Value(0x14);
168 // Null move margin. A null move search will not be done if the approximate
169 // evaluation of the position is more than NullMoveMargin below beta.
170 const Value NullMoveMargin = Value(0x300);
172 // Pruning criterions. See the code and comments in ok_to_prune() to
173 // understand their precise meaning.
174 const bool PruneEscapeMoves = false;
175 const bool PruneDefendingMoves = false;
176 const bool PruneBlockingMoves = false;
178 // Use futility pruning?
179 bool UseQSearchFutilityPruning = true;
180 bool UseFutilityPruning = true;
182 // Margins for futility pruning in the quiescence search, and at frontier
183 // and near frontier nodes
184 Value FutilityMarginQS = Value(0x80);
185 Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
186 Value(0x2A0), Value(0x340), Value(0x3A0) };
189 const bool RazorAtDepthOne = false;
190 Depth RazorDepth = 4*OnePly;
191 Value RazorMargin = Value(0x300);
193 // Last seconds noise filtering (LSN)
194 bool UseLSNFiltering = false;
195 bool looseOnTime = false;
196 int LSNTime = 4 * 1000; // In milliseconds
197 Value LSNValue = Value(0x200);
199 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
200 Depth CheckExtension[2] = {OnePly, OnePly};
201 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
202 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
203 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
204 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
205 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
207 // Search depth at iteration 1
208 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
212 int NodesBetweenPolls = 30000;
214 // Iteration counters
216 BetaCounterType BetaCounter;
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 = false;
246 bool UseLogFile = false;
247 std::ofstream LogFile;
249 // MP related variables
250 Depth MinimumSplitDepth = 4*OnePly;
251 int MaxThreadsPerSplitPoint = 4;
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);
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, 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 = TranspositionTable(TTDefaultSize);
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.
333 History H; // Should be made local?
335 // The empty search stack
336 SearchStack EmptySearchStack;
339 // SearchStack::init() initializes a search stack. Used at the beginning of a
340 // new search from the root.
341 void SearchStack::init(int ply) {
343 pv[ply] = pv[ply + 1] = MOVE_NONE;
344 currentMove = threatMove = MOVE_NONE;
345 reduction = Depth(0);
348 void SearchStack::initKillers() {
350 mateKiller = MOVE_NONE;
351 for (int i = 0; i < KILLER_MAX; i++)
352 killers[i] = MOVE_NONE;
360 /// think() is the external interface to Stockfish's search, and is called when
361 /// the program receives the UCI 'go' command. It initializes various
362 /// search-related global variables, and calls root_search()
364 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
365 int time[], int increment[], int movesToGo, int maxDepth,
366 int maxNodes, int maxTime, Move searchMoves[]) {
368 // Look for a book move
369 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
372 if (get_option_value_string("Book File") != OpeningBook.file_name())
375 OpeningBook.open("book.bin");
377 bookMove = OpeningBook.get_move(pos);
378 if (bookMove != MOVE_NONE)
380 std::cout << "bestmove " << bookMove << std::endl;
385 // Initialize global search variables
387 SearchStartTime = get_system_time();
388 EasyMove = MOVE_NONE;
389 for (int i = 0; i < THREAD_MAX; i++)
391 Threads[i].nodes = 0ULL;
392 Threads[i].failHighPly1 = false;
395 InfiniteSearch = infinite;
396 PonderSearch = ponder;
397 StopOnPonderhit = false;
403 ExactMaxTime = maxTime;
405 // Read UCI option values
406 TT.set_size(get_option_value_int("Hash"));
407 if (button_was_pressed("Clear Hash"))
410 PonderingEnabled = get_option_value_bool("Ponder");
411 MultiPV = get_option_value_int("MultiPV");
413 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
414 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
416 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
417 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
419 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
420 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
422 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
423 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
425 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
426 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
428 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
429 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
431 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
432 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
433 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
434 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
436 Chess960 = get_option_value_bool("UCI_Chess960");
437 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
438 UseLogFile = get_option_value_bool("Use Search Log");
440 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
442 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
443 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
445 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
446 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
447 for (int i = 0; i < 6; i++)
448 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
450 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
451 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
453 UseLSNFiltering = get_option_value_bool("LSN filtering");
454 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
455 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
457 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
458 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
460 read_weights(pos.side_to_move());
462 int newActiveThreads = get_option_value_int("Threads");
463 if (newActiveThreads != ActiveThreads)
465 ActiveThreads = newActiveThreads;
466 init_eval(ActiveThreads);
469 // Wake up sleeping threads:
470 wake_sleeping_threads();
472 for (int i = 1; i < ActiveThreads; i++)
473 assert(thread_is_available(i, 0));
475 // Set thinking time:
476 int myTime = time[side_to_move];
477 int myIncrement = increment[side_to_move];
479 if (!movesToGo) // Sudden death time control
483 MaxSearchTime = myTime / 30 + myIncrement;
484 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
485 } else { // Blitz game without increment
486 MaxSearchTime = myTime / 30;
487 AbsoluteMaxSearchTime = myTime / 8;
490 else // (x moves) / (y minutes)
494 MaxSearchTime = myTime / 2;
495 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
497 MaxSearchTime = myTime / Min(movesToGo, 20);
498 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
502 if (PonderingEnabled)
504 MaxSearchTime += MaxSearchTime / 4;
505 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
508 // Fixed depth or fixed number of nodes?
511 InfiniteSearch = true; // HACK
516 NodesBetweenPolls = Min(MaxNodes, 30000);
517 InfiniteSearch = true; // HACK
520 NodesBetweenPolls = 30000;
523 // Write information to search log file:
525 LogFile << "Searching: " << pos.to_fen() << std::endl
526 << "infinite: " << infinite
527 << " ponder: " << ponder
528 << " time: " << myTime
529 << " increment: " << myIncrement
530 << " moves to go: " << movesToGo << std::endl;
533 // We're ready to start thinking. Call the iterative deepening loop
537 Value v = id_loop(pos, searchMoves);
538 looseOnTime = ( UseLSNFiltering
545 looseOnTime = false; // reset for next match
546 while (SearchStartTime + myTime + 1000 > get_system_time())
548 id_loop(pos, searchMoves); // to fail gracefully
565 /// init_threads() is called during startup. It launches all helper threads,
566 /// and initializes the split point stack and the global locks and condition
569 void init_threads() {
573 #if !defined(_MSC_VER)
574 pthread_t pthread[1];
577 for (i = 0; i < THREAD_MAX; i++)
578 Threads[i].activeSplitPoints = 0;
580 // Initialize global locks:
581 lock_init(&MPLock, NULL);
582 lock_init(&IOLock, NULL);
584 init_split_point_stack();
586 #if !defined(_MSC_VER)
587 pthread_mutex_init(&WaitLock, NULL);
588 pthread_cond_init(&WaitCond, NULL);
590 for (i = 0; i < THREAD_MAX; i++)
591 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
594 // All threads except the main thread should be initialized to idle state
595 for (i = 1; i < THREAD_MAX; i++)
597 Threads[i].stop = false;
598 Threads[i].workIsWaiting = false;
599 Threads[i].idle = true;
600 Threads[i].running = false;
603 // Launch the helper threads
604 for(i = 1; i < THREAD_MAX; i++)
606 #if !defined(_MSC_VER)
607 pthread_create(pthread, NULL, init_thread, (void*)(&i));
610 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
613 // Wait until the thread has finished launching:
614 while (!Threads[i].running);
617 // Init also the empty search stack
618 EmptySearchStack.init(0);
619 EmptySearchStack.initKillers();
623 /// stop_threads() is called when the program exits. It makes all the
624 /// helper threads exit cleanly.
626 void stop_threads() {
628 ActiveThreads = THREAD_MAX; // HACK
629 Idle = false; // HACK
630 wake_sleeping_threads();
631 AllThreadsShouldExit = true;
632 for (int i = 1; i < THREAD_MAX; i++)
634 Threads[i].stop = true;
635 while(Threads[i].running);
637 destroy_split_point_stack();
641 /// nodes_searched() returns the total number of nodes searched so far in
642 /// the current search.
644 int64_t nodes_searched() {
646 int64_t result = 0ULL;
647 for (int i = 0; i < ActiveThreads; i++)
648 result += Threads[i].nodes;
655 // id_loop() is the main iterative deepening loop. It calls root_search
656 // repeatedly with increasing depth until the allocated thinking time has
657 // been consumed, the user stops the search, or the maximum search depth is
660 Value id_loop(const Position &pos, Move searchMoves[]) {
663 SearchStack ss[PLY_MAX_PLUS_2];
665 // searchMoves are verified, copied, scored and sorted
666 RootMoveList rml(p, searchMoves);
671 for (int i = 0; i < 3; i++)
676 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
679 EasyMove = rml.scan_for_easy_move();
681 // Iterative deepening loop
682 while (Iteration < PLY_MAX)
684 // Initialize iteration
687 BestMoveChangesByIteration[Iteration] = 0;
691 std::cout << "info depth " << Iteration << std::endl;
693 // Calculate dynamic search window based on previous iterations
696 if (MultiPV == 1 && Iteration >= 6)
698 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
699 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
701 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
703 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
704 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
708 alpha = - VALUE_INFINITE;
709 beta = VALUE_INFINITE;
712 // Search to the current depth
713 Value value = root_search(p, ss, rml, alpha, beta);
715 // Write PV to transposition table, in case the relevant entries have
716 // been overwritten during the search.
717 TT.insert_pv(p, ss[0].pv);
720 break; // Value cannot be trusted. Break out immediately!
722 //Save info about search result
723 Value speculatedValue;
726 Value delta = value - IterationInfo[Iteration - 1].value;
733 speculatedValue = value + delta;
734 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
736 else if (value <= alpha)
738 assert(value == alpha);
742 speculatedValue = value + delta;
743 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
745 speculatedValue = value;
747 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
748 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
750 // Erase the easy move if it differs from the new best move
751 if (ss[0].pv[0] != EasyMove)
752 EasyMove = MOVE_NONE;
759 bool stopSearch = false;
761 // Stop search early if there is only a single legal move:
762 if (Iteration >= 6 && rml.move_count() == 1)
765 // Stop search early when the last two iterations returned a mate score
767 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
768 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
771 // Stop search early if one move seems to be much better than the rest
772 int64_t nodes = nodes_searched();
776 && EasyMove == ss[0].pv[0]
777 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
778 && current_search_time() > MaxSearchTime / 16)
779 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
780 && current_search_time() > MaxSearchTime / 32)))
783 // Add some extra time if the best move has changed during the last two iterations
784 if (Iteration > 5 && Iteration <= 50)
785 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
786 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
788 // Stop search if most of MaxSearchTime is consumed at the end of the
789 // iteration. We probably don't have enough time to search the first
790 // move at the next iteration anyway.
791 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
796 //FIXME: Implement fail-low emergency measures
800 StopOnPonderhit = true;
804 if (MaxDepth && Iteration >= MaxDepth)
810 // If we are pondering, we shouldn't print the best move before we
813 wait_for_stop_or_ponderhit();
815 // Print final search statistics
816 std::cout << "info nodes " << nodes_searched()
818 << " time " << current_search_time()
819 << " hashfull " << TT.full() << std::endl;
821 // Print the best move and the ponder move to the standard output
822 if (ss[0].pv[0] == MOVE_NONE)
824 ss[0].pv[0] = rml.get_move(0);
825 ss[0].pv[1] = MOVE_NONE;
827 std::cout << "bestmove " << ss[0].pv[0];
828 if (ss[0].pv[1] != MOVE_NONE)
829 std::cout << " ponder " << ss[0].pv[1];
831 std::cout << std::endl;
836 dbg_print_mean(LogFile);
838 if (dbg_show_hit_rate)
839 dbg_print_hit_rate(LogFile);
842 LogFile << "Nodes: " << nodes_searched() << std::endl
843 << "Nodes/second: " << nps() << std::endl
844 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
846 p.do_move(ss[0].pv[0], st);
847 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
848 << std::endl << std::endl;
850 return rml.get_move_score(0);
854 // root_search() is the function which searches the root node. It is
855 // similar to search_pv except that it uses a different move ordering
856 // scheme (perhaps we should try to use this at internal PV nodes, too?)
857 // and prints some information to the standard output.
859 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
861 Value oldAlpha = alpha;
863 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
865 // Loop through all the moves in the root move list
866 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
870 // We failed high, invalidate and skip next moves, leave node-counters
871 // and beta-counters as they are and quickly return, we will try to do
872 // a research at the next iteration with a bigger aspiration window.
873 rml.set_move_score(i, -VALUE_INFINITE);
881 RootMoveNumber = i + 1;
884 // Remember the node count before the move is searched. The node counts
885 // are used to sort the root moves at the next iteration.
886 nodes = nodes_searched();
888 // Reset beta cut-off counters
891 // Pick the next root move, and print the move and the move number to
892 // the standard output.
893 move = ss[0].currentMove = rml.get_move(i);
894 if (current_search_time() >= 1000)
895 std::cout << "info currmove " << move
896 << " currmovenumber " << i + 1 << std::endl;
898 // Decide search depth for this move
900 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
901 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
903 // Make the move, and search it
904 pos.do_move(move, st, dcCandidates);
908 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
909 // If the value has dropped a lot compared to the last iteration,
910 // set the boolean variable Problem to true. This variable is used
911 // for time managment: When Problem is true, we try to complete the
912 // current iteration before playing a move.
913 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
915 if (Problem && StopOnPonderhit)
916 StopOnPonderhit = false;
920 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
923 // Fail high! Set the boolean variable FailHigh to true, and
924 // re-search the move with a big window. The variable FailHigh is
925 // used for time managment: We try to avoid aborting the search
926 // prematurely during a fail high research.
928 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
934 // Finished searching the move. If AbortSearch is true, the search
935 // was aborted because the user interrupted the search or because we
936 // ran out of time. In this case, the return value of the search cannot
937 // be trusted, and we break out of the loop without updating the best
942 // Remember the node count for this move. The node counts are used to
943 // sort the root moves at the next iteration.
944 rml.set_move_nodes(i, nodes_searched() - nodes);
946 // Remember the beta-cutoff statistics
948 BetaCounter.read(pos.side_to_move(), our, their);
949 rml.set_beta_counters(i, our, their);
951 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
953 if (value <= alpha && i >= MultiPV)
954 rml.set_move_score(i, -VALUE_INFINITE);
957 // PV move or new best move!
960 rml.set_move_score(i, value);
962 rml.set_move_pv(i, ss[0].pv);
966 // We record how often the best move has been changed in each
967 // iteration. This information is used for time managment: When
968 // the best move changes frequently, we allocate some more time.
970 BestMoveChangesByIteration[Iteration]++;
972 // Print search information to the standard output:
973 std::cout << "info depth " << Iteration
974 << " score " << value_to_string(value)
975 << " time " << current_search_time()
976 << " nodes " << nodes_searched()
980 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
981 std::cout << ss[0].pv[j] << " ";
983 std::cout << std::endl;
986 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
992 // Reset the global variable Problem to false if the value isn't too
993 // far below the final value from the last iteration.
994 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1000 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1003 std::cout << "info multipv " << j + 1
1004 << " score " << value_to_string(rml.get_move_score(j))
1005 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1006 << " time " << current_search_time()
1007 << " nodes " << nodes_searched()
1011 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1012 std::cout << rml.get_move_pv(j, k) << " ";
1014 std::cout << std::endl;
1016 alpha = rml.get_move_score(Min(i, MultiPV-1));
1018 } // New best move case
1020 assert(alpha >= oldAlpha);
1022 FailLow = (alpha == oldAlpha);
1028 // search_pv() is the main search function for PV nodes.
1030 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1031 Depth depth, int ply, int threadID) {
1033 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1034 assert(beta > alpha && beta <= VALUE_INFINITE);
1035 assert(ply >= 0 && ply < PLY_MAX);
1036 assert(threadID >= 0 && threadID < ActiveThreads);
1039 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1041 // Initialize, and make an early exit in case of an aborted search,
1042 // an instant draw, maximum ply reached, etc.
1043 init_node(ss, ply, threadID);
1045 // After init_node() that calls poll()
1046 if (AbortSearch || thread_should_stop(threadID))
1054 if (ply >= PLY_MAX - 1)
1055 return evaluate(pos, ei, threadID);
1057 // Mate distance pruning
1058 Value oldAlpha = alpha;
1059 alpha = Max(value_mated_in(ply), alpha);
1060 beta = Min(value_mate_in(ply+1), beta);
1064 // Transposition table lookup. At PV nodes, we don't use the TT for
1065 // pruning, but only for move ordering.
1066 const TTEntry* tte = TT.retrieve(pos);
1067 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1069 // Go with internal iterative deepening if we don't have a TT move
1070 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1072 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1073 ttMove = ss[ply].pv[ply];
1076 // Initialize a MovePicker object for the current position, and prepare
1077 // to search all moves
1078 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1080 Move move, movesSearched[256];
1082 Value value, bestValue = -VALUE_INFINITE;
1083 Bitboard dcCandidates = mp.discovered_check_candidates();
1084 Color us = pos.side_to_move();
1085 bool isCheck = pos.is_check();
1086 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1088 // Loop through all legal moves until no moves remain or a beta cutoff
1090 while ( alpha < beta
1091 && (move = mp.get_next_move()) != MOVE_NONE
1092 && !thread_should_stop(threadID))
1094 assert(move_is_ok(move));
1096 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1097 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1098 bool moveIsCapture = pos.move_is_capture(move);
1100 movesSearched[moveCount++] = ss[ply].currentMove = move;
1102 // Decide the new search depth
1104 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1105 Depth newDepth = depth - OnePly + ext;
1107 // Make and search the move
1109 pos.do_move(move, st, dcCandidates);
1111 if (moveCount == 1) // The first move in list is the PV
1112 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1115 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1116 // if the move fails high will be re-searched at full depth.
1117 if ( depth >= 2*OnePly
1118 && moveCount >= LMRPVMoves
1121 && !move_promotion(move)
1122 && !move_is_castle(move)
1123 && !move_is_killer(move, ss[ply]))
1125 ss[ply].reduction = OnePly;
1126 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1129 value = alpha + 1; // Just to trigger next condition
1131 if (value > alpha) // Go with full depth non-pv search
1133 ss[ply].reduction = Depth(0);
1134 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1135 if (value > alpha && value < beta)
1137 // When the search fails high at ply 1 while searching the first
1138 // move at the root, set the flag failHighPly1. This is used for
1139 // time managment: We don't want to stop the search early in
1140 // such cases, because resolving the fail high at ply 1 could
1141 // result in a big drop in score at the root.
1142 if (ply == 1 && RootMoveNumber == 1)
1143 Threads[threadID].failHighPly1 = true;
1145 // A fail high occurred. Re-search at full window (pv search)
1146 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1147 Threads[threadID].failHighPly1 = false;
1151 pos.undo_move(move);
1153 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1156 if (value > bestValue)
1163 if (value == value_mate_in(ply + 1))
1164 ss[ply].mateKiller = move;
1166 // If we are at ply 1, and we are searching the first root move at
1167 // ply 0, set the 'Problem' variable if the score has dropped a lot
1168 // (from the computer's point of view) since the previous iteration:
1171 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1176 if ( ActiveThreads > 1
1178 && depth >= MinimumSplitDepth
1180 && idle_thread_exists(threadID)
1182 && !thread_should_stop(threadID)
1183 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1184 &moveCount, &mp, dcCandidates, threadID, true))
1188 // All legal moves have been searched. A special case: If there were
1189 // no legal moves, it must be mate or stalemate:
1191 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1193 // If the search is not aborted, update the transposition table,
1194 // history counters, and killer moves.
1195 if (AbortSearch || thread_should_stop(threadID))
1198 if (bestValue <= oldAlpha)
1199 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1201 else if (bestValue >= beta)
1203 BetaCounter.add(pos.side_to_move(), depth, threadID);
1204 Move m = ss[ply].pv[ply];
1205 if (ok_to_history(pos, m)) // Only non capture moves are considered
1207 update_history(pos, m, depth, movesSearched, moveCount);
1208 update_killers(m, ss[ply]);
1210 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1213 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1219 // search() is the search function for zero-width nodes.
1221 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1222 int ply, bool allowNullmove, int threadID) {
1224 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1225 assert(ply >= 0 && ply < PLY_MAX);
1226 assert(threadID >= 0 && threadID < ActiveThreads);
1229 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1231 // Initialize, and make an early exit in case of an aborted search,
1232 // an instant draw, maximum ply reached, etc.
1233 init_node(ss, ply, threadID);
1235 // After init_node() that calls poll()
1236 if (AbortSearch || thread_should_stop(threadID))
1244 if (ply >= PLY_MAX - 1)
1245 return evaluate(pos, ei, threadID);
1247 // Mate distance pruning
1248 if (value_mated_in(ply) >= beta)
1251 if (value_mate_in(ply + 1) < beta)
1254 // Transposition table lookup
1255 const TTEntry* tte = TT.retrieve(pos);
1256 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1258 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1260 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1261 return value_from_tt(tte->value(), ply);
1264 Value approximateEval = quick_evaluate(pos);
1265 bool mateThreat = false;
1266 bool isCheck = pos.is_check();
1272 && !value_is_mate(beta)
1273 && ok_to_do_nullmove(pos)
1274 && approximateEval >= beta - NullMoveMargin)
1276 ss[ply].currentMove = MOVE_NULL;
1279 pos.do_null_move(st);
1280 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1282 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1284 pos.undo_null_move();
1286 if (value_is_mate(nullValue))
1288 /* Do not return unproven mates */
1290 else if (nullValue >= beta)
1292 if (depth < 6 * OnePly)
1295 // Do zugzwang verification search
1296 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1300 // The null move failed low, which means that we may be faced with
1301 // some kind of threat. If the previous move was reduced, check if
1302 // the move that refuted the null move was somehow connected to the
1303 // move which was reduced. If a connection is found, return a fail
1304 // low score (which will cause the reduced move to fail high in the
1305 // parent node, which will trigger a re-search with full depth).
1306 if (nullValue == value_mated_in(ply + 2))
1309 ss[ply].threatMove = ss[ply + 1].currentMove;
1310 if ( depth < ThreatDepth
1311 && ss[ply - 1].reduction
1312 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1316 // Null move search not allowed, try razoring
1317 else if ( !value_is_mate(beta)
1318 && approximateEval < beta - RazorMargin
1319 && depth < RazorDepth
1320 && (RazorAtDepthOne || depth > OnePly)
1321 && ttMove == MOVE_NONE
1322 && !pos.has_pawn_on_7th(pos.side_to_move()))
1324 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1325 if ( (v < beta - RazorMargin - RazorMargin / 4)
1326 || (depth <= 2*OnePly && v < beta - RazorMargin)
1327 || (depth <= OnePly && v < beta - RazorMargin / 2))
1331 // Go with internal iterative deepening if we don't have a TT move
1332 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1333 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1335 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1336 ttMove = ss[ply].pv[ply];
1339 // Initialize a MovePicker object for the current position, and prepare
1340 // to search all moves:
1341 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1343 Move move, movesSearched[256];
1345 Value value, bestValue = -VALUE_INFINITE;
1346 Bitboard dcCandidates = mp.discovered_check_candidates();
1347 Value futilityValue = VALUE_NONE;
1348 bool useFutilityPruning = UseFutilityPruning
1349 && depth < SelectiveDepth
1352 // Loop through all legal moves until no moves remain or a beta cutoff
1354 while ( bestValue < beta
1355 && (move = mp.get_next_move()) != MOVE_NONE
1356 && !thread_should_stop(threadID))
1358 assert(move_is_ok(move));
1360 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1361 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1362 bool moveIsCapture = pos.move_is_capture(move);
1364 movesSearched[moveCount++] = ss[ply].currentMove = move;
1366 // Decide the new search depth
1368 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1369 Depth newDepth = depth - OnePly + ext;
1372 if ( useFutilityPruning
1375 && !move_promotion(move))
1377 // History pruning. See ok_to_prune() definition
1378 if ( moveCount >= 2 + int(depth)
1379 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1382 // Value based pruning
1383 if (depth < 7 * OnePly && approximateEval < beta)
1385 if (futilityValue == VALUE_NONE)
1386 futilityValue = evaluate(pos, ei, threadID)
1387 + FutilityMargins[int(depth)/2 - 1]
1390 if (futilityValue < beta)
1392 if (futilityValue > bestValue)
1393 bestValue = futilityValue;
1399 // Make and search the move
1401 pos.do_move(move, st, dcCandidates);
1403 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1404 // if the move fails high will be re-searched at full depth.
1405 if ( depth >= 2*OnePly
1406 && moveCount >= LMRNonPVMoves
1409 && !move_promotion(move)
1410 && !move_is_castle(move)
1411 && !move_is_killer(move, ss[ply]))
1413 ss[ply].reduction = OnePly;
1414 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1417 value = beta; // Just to trigger next condition
1419 if (value >= beta) // Go with full depth non-pv search
1421 ss[ply].reduction = Depth(0);
1422 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1424 pos.undo_move(move);
1426 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1429 if (value > bestValue)
1435 if (value == value_mate_in(ply + 1))
1436 ss[ply].mateKiller = move;
1440 if ( ActiveThreads > 1
1442 && depth >= MinimumSplitDepth
1444 && idle_thread_exists(threadID)
1446 && !thread_should_stop(threadID)
1447 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1448 &mp, dcCandidates, threadID, false))
1452 // All legal moves have been searched. A special case: If there were
1453 // no legal moves, it must be mate or stalemate.
1455 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1457 // If the search is not aborted, update the transposition table,
1458 // history counters, and killer moves.
1459 if (AbortSearch || thread_should_stop(threadID))
1462 if (bestValue < beta)
1463 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1466 BetaCounter.add(pos.side_to_move(), depth, threadID);
1467 Move m = ss[ply].pv[ply];
1468 if (ok_to_history(pos, m)) // Only non capture moves are considered
1470 update_history(pos, m, depth, movesSearched, moveCount);
1471 update_killers(m, ss[ply]);
1473 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1476 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1482 // qsearch() is the quiescence search function, which is called by the main
1483 // search function when the remaining depth is zero (or, to be more precise,
1484 // less than OnePly).
1486 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1487 Depth depth, int ply, int threadID) {
1489 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1490 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1492 assert(ply >= 0 && ply < PLY_MAX);
1493 assert(threadID >= 0 && threadID < ActiveThreads);
1495 // Initialize, and make an early exit in case of an aborted search,
1496 // an instant draw, maximum ply reached, etc.
1497 init_node(ss, ply, threadID);
1499 // After init_node() that calls poll()
1500 if (AbortSearch || thread_should_stop(threadID))
1506 // Transposition table lookup, only when not in PV
1507 TTEntry* tte = NULL;
1508 bool pvNode = (beta - alpha != 1);
1511 tte = TT.retrieve(pos);
1512 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1514 assert(tte->type() != VALUE_TYPE_EVAL);
1516 return value_from_tt(tte->value(), ply);
1519 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1521 // Evaluate the position statically
1524 bool isCheck = pos.is_check();
1525 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1528 staticValue = -VALUE_INFINITE;
1530 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1532 // Use the cached evaluation score if possible
1533 assert(tte->value() == evaluate(pos, ei, threadID));
1534 assert(ei.futilityMargin == Value(0));
1536 staticValue = tte->value();
1539 staticValue = evaluate(pos, ei, threadID);
1541 if (ply == PLY_MAX - 1)
1542 return evaluate(pos, ei, threadID);
1544 // Initialize "stand pat score", and return it immediately if it is
1546 Value bestValue = staticValue;
1548 if (bestValue >= beta)
1550 // Store the score to avoid a future costly evaluation() call
1551 if (!isCheck && !tte && ei.futilityMargin == 0)
1552 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1557 if (bestValue > alpha)
1560 // Initialize a MovePicker object for the current position, and prepare
1561 // to search the moves. Because the depth is <= 0 here, only captures,
1562 // queen promotions and checks (only if depth == 0) will be generated.
1563 MovePicker mp = MovePicker(pos, pvNode, ttMove, EmptySearchStack, depth);
1566 Bitboard dcCandidates = mp.discovered_check_candidates();
1567 Color us = pos.side_to_move();
1568 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1570 // Loop through the moves until no moves remain or a beta cutoff
1572 while ( alpha < beta
1573 && (move = mp.get_next_move()) != MOVE_NONE)
1575 assert(move_is_ok(move));
1578 ss[ply].currentMove = move;
1581 if ( UseQSearchFutilityPruning
1585 && !move_promotion(move)
1586 && !pos.move_is_check(move, dcCandidates)
1587 && !pos.move_is_passed_pawn_push(move))
1589 Value futilityValue = staticValue
1590 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1591 pos.endgame_value_of_piece_on(move_to(move)))
1592 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1594 + ei.futilityMargin;
1596 if (futilityValue < alpha)
1598 if (futilityValue > bestValue)
1599 bestValue = futilityValue;
1604 // Don't search captures and checks with negative SEE values
1606 && !move_promotion(move)
1607 && (pos.midgame_value_of_piece_on(move_from(move)) >
1608 pos.midgame_value_of_piece_on(move_to(move)))
1609 && pos.see(move) < 0)
1612 // Make and search the move.
1614 pos.do_move(move, st, dcCandidates);
1615 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1616 pos.undo_move(move);
1618 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1621 if (value > bestValue)
1632 // All legal moves have been searched. A special case: If we're in check
1633 // and no legal moves were found, it is checkmate:
1634 if (pos.is_check() && moveCount == 0) // Mate!
1635 return value_mated_in(ply);
1637 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1639 // Update transposition table
1640 Move m = ss[ply].pv[ply];
1643 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1644 if (bestValue < beta)
1645 TT.store(pos, value_to_tt(bestValue, ply), d, MOVE_NONE, VALUE_TYPE_UPPER);
1647 TT.store(pos, value_to_tt(bestValue, ply), d, m, VALUE_TYPE_LOWER);
1650 // Update killers only for good check moves
1651 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1652 update_killers(m, ss[ply]);
1658 // sp_search() is used to search from a split point. This function is called
1659 // by each thread working at the split point. It is similar to the normal
1660 // search() function, but simpler. Because we have already probed the hash
1661 // table, done a null move search, and searched the first move before
1662 // splitting, we don't have to repeat all this work in sp_search(). We
1663 // also don't need to store anything to the hash table here: This is taken
1664 // care of after we return from the split point.
1666 void sp_search(SplitPoint *sp, int threadID) {
1668 assert(threadID >= 0 && threadID < ActiveThreads);
1669 assert(ActiveThreads > 1);
1671 Position pos = Position(sp->pos);
1672 SearchStack *ss = sp->sstack[threadID];
1675 bool isCheck = pos.is_check();
1676 bool useFutilityPruning = UseFutilityPruning
1677 && sp->depth < SelectiveDepth
1680 while ( sp->bestValue < sp->beta
1681 && !thread_should_stop(threadID)
1682 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1684 assert(move_is_ok(move));
1686 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1687 bool moveIsCapture = pos.move_is_capture(move);
1689 lock_grab(&(sp->lock));
1690 int moveCount = ++sp->moves;
1691 lock_release(&(sp->lock));
1693 ss[sp->ply].currentMove = move;
1695 // Decide the new search depth.
1697 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1698 Depth newDepth = sp->depth - OnePly + ext;
1701 if ( useFutilityPruning
1704 && !move_promotion(move)
1705 && moveCount >= 2 + int(sp->depth)
1706 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1709 // Make and search the move.
1711 pos.do_move(move, st, sp->dcCandidates);
1713 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1714 // if the move fails high will be re-searched at full depth.
1716 && moveCount >= LMRNonPVMoves
1718 && !move_promotion(move)
1719 && !move_is_castle(move)
1720 && !move_is_killer(move, ss[sp->ply]))
1722 ss[sp->ply].reduction = OnePly;
1723 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1726 value = sp->beta; // Just to trigger next condition
1728 if (value >= sp->beta) // Go with full depth non-pv search
1730 ss[sp->ply].reduction = Depth(0);
1731 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1733 pos.undo_move(move);
1735 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1737 if (thread_should_stop(threadID))
1741 lock_grab(&(sp->lock));
1742 if (value > sp->bestValue && !thread_should_stop(threadID))
1744 sp->bestValue = value;
1745 if (sp->bestValue >= sp->beta)
1747 sp_update_pv(sp->parentSstack, ss, sp->ply);
1748 for (int i = 0; i < ActiveThreads; i++)
1749 if (i != threadID && (i == sp->master || sp->slaves[i]))
1750 Threads[i].stop = true;
1752 sp->finished = true;
1755 lock_release(&(sp->lock));
1758 lock_grab(&(sp->lock));
1760 // If this is the master thread and we have been asked to stop because of
1761 // a beta cutoff higher up in the tree, stop all slave threads:
1762 if (sp->master == threadID && thread_should_stop(threadID))
1763 for (int i = 0; i < ActiveThreads; i++)
1765 Threads[i].stop = true;
1768 sp->slaves[threadID] = 0;
1770 lock_release(&(sp->lock));
1774 // sp_search_pv() is used to search from a PV split point. This function
1775 // is called by each thread working at the split point. It is similar to
1776 // the normal search_pv() function, but simpler. Because we have already
1777 // probed the hash table and searched the first move before splitting, we
1778 // don't have to repeat all this work in sp_search_pv(). We also don't
1779 // need to store anything to the hash table here: This is taken care of
1780 // after we return from the split point.
1782 void sp_search_pv(SplitPoint *sp, int threadID) {
1784 assert(threadID >= 0 && threadID < ActiveThreads);
1785 assert(ActiveThreads > 1);
1787 Position pos = Position(sp->pos);
1788 SearchStack *ss = sp->sstack[threadID];
1792 while ( sp->alpha < sp->beta
1793 && !thread_should_stop(threadID)
1794 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1796 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1797 bool moveIsCapture = pos.move_is_capture(move);
1799 assert(move_is_ok(move));
1801 lock_grab(&(sp->lock));
1802 int moveCount = ++sp->moves;
1803 lock_release(&(sp->lock));
1805 ss[sp->ply].currentMove = move;
1807 // Decide the new search depth.
1809 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1810 Depth newDepth = sp->depth - OnePly + ext;
1812 // Make and search the move.
1814 pos.do_move(move, st, sp->dcCandidates);
1816 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1817 // if the move fails high will be re-searched at full depth.
1819 && moveCount >= LMRPVMoves
1821 && !move_promotion(move)
1822 && !move_is_castle(move)
1823 && !move_is_killer(move, ss[sp->ply]))
1825 ss[sp->ply].reduction = OnePly;
1826 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1829 value = sp->alpha + 1; // Just to trigger next condition
1831 if (value > sp->alpha) // Go with full depth non-pv search
1833 ss[sp->ply].reduction = Depth(0);
1834 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1836 if (value > sp->alpha && value < sp->beta)
1838 // When the search fails high at ply 1 while searching the first
1839 // move at the root, set the flag failHighPly1. This is used for
1840 // time managment: We don't want to stop the search early in
1841 // such cases, because resolving the fail high at ply 1 could
1842 // result in a big drop in score at the root.
1843 if (sp->ply == 1 && RootMoveNumber == 1)
1844 Threads[threadID].failHighPly1 = true;
1846 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1847 Threads[threadID].failHighPly1 = false;
1850 pos.undo_move(move);
1852 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1854 if (thread_should_stop(threadID))
1858 lock_grab(&(sp->lock));
1859 if (value > sp->bestValue && !thread_should_stop(threadID))
1861 sp->bestValue = value;
1862 if (value > sp->alpha)
1865 sp_update_pv(sp->parentSstack, ss, sp->ply);
1866 if (value == value_mate_in(sp->ply + 1))
1867 ss[sp->ply].mateKiller = move;
1869 if(value >= sp->beta)
1871 for(int i = 0; i < ActiveThreads; i++)
1872 if(i != threadID && (i == sp->master || sp->slaves[i]))
1873 Threads[i].stop = true;
1875 sp->finished = true;
1878 // If we are at ply 1, and we are searching the first root move at
1879 // ply 0, set the 'Problem' variable if the score has dropped a lot
1880 // (from the computer's point of view) since the previous iteration.
1883 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1886 lock_release(&(sp->lock));
1889 lock_grab(&(sp->lock));
1891 // If this is the master thread and we have been asked to stop because of
1892 // a beta cutoff higher up in the tree, stop all slave threads.
1893 if (sp->master == threadID && thread_should_stop(threadID))
1894 for (int i = 0; i < ActiveThreads; i++)
1896 Threads[i].stop = true;
1899 sp->slaves[threadID] = 0;
1901 lock_release(&(sp->lock));
1904 /// The BetaCounterType class
1906 BetaCounterType::BetaCounterType() { clear(); }
1908 void BetaCounterType::clear() {
1910 for (int i = 0; i < THREAD_MAX; i++)
1911 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1914 void BetaCounterType::add(Color us, Depth d, int threadID) {
1916 // Weighted count based on depth
1917 hits[threadID][us] += int(d);
1920 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1923 for (int i = 0; i < THREAD_MAX; i++)
1926 their += hits[i][opposite_color(us)];
1931 /// The RootMove class
1935 RootMove::RootMove() {
1936 nodes = cumulativeNodes = 0ULL;
1939 // RootMove::operator<() is the comparison function used when
1940 // sorting the moves. A move m1 is considered to be better
1941 // than a move m2 if it has a higher score, or if the moves
1942 // have equal score but m1 has the higher node count.
1944 bool RootMove::operator<(const RootMove& m) {
1946 if (score != m.score)
1947 return (score < m.score);
1949 return theirBeta <= m.theirBeta;
1952 /// The RootMoveList class
1956 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1958 MoveStack mlist[MaxRootMoves];
1959 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1961 // Generate all legal moves
1962 int lm_count = generate_legal_moves(pos, mlist);
1964 // Add each move to the moves[] array
1965 for (int i = 0; i < lm_count; i++)
1967 bool includeMove = includeAllMoves;
1969 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1970 includeMove = (searchMoves[k] == mlist[i].move);
1974 // Find a quick score for the move
1976 SearchStack ss[PLY_MAX_PLUS_2];
1978 moves[count].move = mlist[i].move;
1979 moves[count].nodes = 0ULL;
1980 pos.do_move(moves[count].move, st);
1981 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1983 pos.undo_move(moves[count].move);
1984 moves[count].pv[0] = moves[i].move;
1985 moves[count].pv[1] = MOVE_NONE; // FIXME
1993 // Simple accessor methods for the RootMoveList class
1995 inline Move RootMoveList::get_move(int moveNum) const {
1996 return moves[moveNum].move;
1999 inline Value RootMoveList::get_move_score(int moveNum) const {
2000 return moves[moveNum].score;
2003 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2004 moves[moveNum].score = score;
2007 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2008 moves[moveNum].nodes = nodes;
2009 moves[moveNum].cumulativeNodes += nodes;
2012 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2013 moves[moveNum].ourBeta = our;
2014 moves[moveNum].theirBeta = their;
2017 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2019 for(j = 0; pv[j] != MOVE_NONE; j++)
2020 moves[moveNum].pv[j] = pv[j];
2021 moves[moveNum].pv[j] = MOVE_NONE;
2024 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2025 return moves[moveNum].pv[i];
2028 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2029 return moves[moveNum].cumulativeNodes;
2032 inline int RootMoveList::move_count() const {
2037 // RootMoveList::scan_for_easy_move() is called at the end of the first
2038 // iteration, and is used to detect an "easy move", i.e. a move which appears
2039 // to be much bester than all the rest. If an easy move is found, the move
2040 // is returned, otherwise the function returns MOVE_NONE. It is very
2041 // important that this function is called at the right moment: The code
2042 // assumes that the first iteration has been completed and the moves have
2043 // been sorted. This is done in RootMoveList c'tor.
2045 Move RootMoveList::scan_for_easy_move() const {
2052 // moves are sorted so just consider the best and the second one
2053 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2059 // RootMoveList::sort() sorts the root move list at the beginning of a new
2062 inline void RootMoveList::sort() {
2064 sort_multipv(count - 1); // all items
2068 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2069 // list by their scores and depths. It is used to order the different PVs
2070 // correctly in MultiPV mode.
2072 void RootMoveList::sort_multipv(int n) {
2074 for (int i = 1; i <= n; i++)
2076 RootMove rm = moves[i];
2078 for (j = i; j > 0 && moves[j-1] < rm; j--)
2079 moves[j] = moves[j-1];
2085 // init_node() is called at the beginning of all the search functions
2086 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2087 // stack object corresponding to the current node. Once every
2088 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2089 // for user input and checks whether it is time to stop the search.
2091 void init_node(SearchStack ss[], int ply, int threadID) {
2092 assert(ply >= 0 && ply < PLY_MAX);
2093 assert(threadID >= 0 && threadID < ActiveThreads);
2095 Threads[threadID].nodes++;
2099 if(NodesSincePoll >= NodesBetweenPolls) {
2106 ss[ply+2].initKillers();
2108 if(Threads[threadID].printCurrentLine)
2109 print_current_line(ss, ply, threadID);
2113 // update_pv() is called whenever a search returns a value > alpha. It
2114 // updates the PV in the SearchStack object corresponding to the current
2117 void update_pv(SearchStack ss[], int ply) {
2118 assert(ply >= 0 && ply < PLY_MAX);
2120 ss[ply].pv[ply] = ss[ply].currentMove;
2122 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2123 ss[ply].pv[p] = ss[ply+1].pv[p];
2124 ss[ply].pv[p] = MOVE_NONE;
2128 // sp_update_pv() is a variant of update_pv for use at split points. The
2129 // difference between the two functions is that sp_update_pv also updates
2130 // the PV at the parent node.
2132 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2133 assert(ply >= 0 && ply < PLY_MAX);
2135 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2137 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2138 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2139 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2143 // connected_moves() tests whether two moves are 'connected' in the sense
2144 // that the first move somehow made the second move possible (for instance
2145 // if the moving piece is the same in both moves). The first move is
2146 // assumed to be the move that was made to reach the current position, while
2147 // the second move is assumed to be a move from the current position.
2149 bool connected_moves(const Position &pos, Move m1, Move m2) {
2150 Square f1, t1, f2, t2;
2152 assert(move_is_ok(m1));
2153 assert(move_is_ok(m2));
2158 // Case 1: The moving piece is the same in both moves.
2164 // Case 2: The destination square for m2 was vacated by m1.
2170 // Case 3: Moving through the vacated square:
2171 if(piece_is_slider(pos.piece_on(f2)) &&
2172 bit_is_set(squares_between(f2, t2), f1))
2175 // Case 4: The destination square for m2 is attacked by the moving piece
2177 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2180 // Case 5: Discovered check, checking piece is the piece moved in m1:
2181 if(piece_is_slider(pos.piece_on(t1)) &&
2182 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2184 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2186 Bitboard occ = pos.occupied_squares();
2187 Color us = pos.side_to_move();
2188 Square ksq = pos.king_square(us);
2189 clear_bit(&occ, f2);
2190 if(pos.type_of_piece_on(t1) == BISHOP) {
2191 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2194 else if(pos.type_of_piece_on(t1) == ROOK) {
2195 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2199 assert(pos.type_of_piece_on(t1) == QUEEN);
2200 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2209 // value_is_mate() checks if the given value is a mate one
2210 // eventually compensated for the ply.
2212 bool value_is_mate(Value value) {
2214 assert(abs(value) <= VALUE_INFINITE);
2216 return value <= value_mated_in(PLY_MAX)
2217 || value >= value_mate_in(PLY_MAX);
2221 // move_is_killer() checks if the given move is among the
2222 // killer moves of that ply.
2224 bool move_is_killer(Move m, const SearchStack& ss) {
2226 const Move* k = ss.killers;
2227 for (int i = 0; i < KILLER_MAX; i++, k++)
2235 // extension() decides whether a move should be searched with normal depth,
2236 // or with extended depth. Certain classes of moves (checking moves, in
2237 // particular) are searched with bigger depth than ordinary moves and in
2238 // any case are marked as 'dangerous'. Note that also if a move is not
2239 // extended, as example because the corresponding UCI option is set to zero,
2240 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2242 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2243 bool singleReply, bool mateThreat, bool* dangerous) {
2245 assert(m != MOVE_NONE);
2247 Depth result = Depth(0);
2248 *dangerous = check || singleReply || mateThreat;
2251 result += CheckExtension[pvNode];
2254 result += SingleReplyExtension[pvNode];
2257 result += MateThreatExtension[pvNode];
2259 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2261 if (pos.move_is_pawn_push_to_7th(m))
2263 result += PawnPushTo7thExtension[pvNode];
2266 if (pos.move_is_passed_pawn_push(m))
2268 result += PassedPawnExtension[pvNode];
2274 && pos.type_of_piece_on(move_to(m)) != PAWN
2275 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2276 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2277 && !move_promotion(m)
2280 result += PawnEndgameExtension[pvNode];
2286 && pos.type_of_piece_on(move_to(m)) != PAWN
2293 return Min(result, OnePly);
2297 // ok_to_do_nullmove() looks at the current position and decides whether
2298 // doing a 'null move' should be allowed. In order to avoid zugzwang
2299 // problems, null moves are not allowed when the side to move has very
2300 // little material left. Currently, the test is a bit too simple: Null
2301 // moves are avoided only when the side to move has only pawns left. It's
2302 // probably a good idea to avoid null moves in at least some more
2303 // complicated endgames, e.g. KQ vs KR. FIXME
2305 bool ok_to_do_nullmove(const Position &pos) {
2306 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2312 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2313 // non-tactical moves late in the move list close to the leaves are
2314 // candidates for pruning.
2316 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2317 Square mfrom, mto, tfrom, tto;
2319 assert(move_is_ok(m));
2320 assert(threat == MOVE_NONE || move_is_ok(threat));
2321 assert(!move_promotion(m));
2322 assert(!pos.move_is_check(m));
2323 assert(!pos.move_is_capture(m));
2324 assert(!pos.move_is_passed_pawn_push(m));
2325 assert(d >= OnePly);
2327 mfrom = move_from(m);
2329 tfrom = move_from(threat);
2330 tto = move_to(threat);
2332 // Case 1: Castling moves are never pruned.
2333 if (move_is_castle(m))
2336 // Case 2: Don't prune moves which move the threatened piece
2337 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2340 // Case 3: If the threatened piece has value less than or equal to the
2341 // value of the threatening piece, don't prune move which defend it.
2342 if ( !PruneDefendingMoves
2343 && threat != MOVE_NONE
2344 && pos.move_is_capture(threat)
2345 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2346 || pos.type_of_piece_on(tfrom) == KING)
2347 && pos.move_attacks_square(m, tto))
2350 // Case 4: Don't prune moves with good history.
2351 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2354 // Case 5: If the moving piece in the threatened move is a slider, don't
2355 // prune safe moves which block its ray.
2356 if ( !PruneBlockingMoves
2357 && threat != MOVE_NONE
2358 && piece_is_slider(pos.piece_on(tfrom))
2359 && bit_is_set(squares_between(tfrom, tto), mto)
2367 // ok_to_use_TT() returns true if a transposition table score
2368 // can be used at a given point in search.
2370 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2372 Value v = value_from_tt(tte->value(), ply);
2374 return ( tte->depth() >= depth
2375 || v >= Max(value_mate_in(100), beta)
2376 || v < Min(value_mated_in(100), beta))
2378 && ( (is_lower_bound(tte->type()) && v >= beta)
2379 || (is_upper_bound(tte->type()) && v < beta));
2383 // ok_to_history() returns true if a move m can be stored
2384 // in history. Should be a non capturing move nor a promotion.
2386 bool ok_to_history(const Position& pos, Move m) {
2388 return !pos.move_is_capture(m) && !move_promotion(m);
2392 // update_history() registers a good move that produced a beta-cutoff
2393 // in history and marks as failures all the other moves of that ply.
2395 void update_history(const Position& pos, Move m, Depth depth,
2396 Move movesSearched[], int moveCount) {
2398 H.success(pos.piece_on(move_from(m)), m, depth);
2400 for (int i = 0; i < moveCount - 1; i++)
2402 assert(m != movesSearched[i]);
2403 if (ok_to_history(pos, movesSearched[i]))
2404 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2409 // update_killers() add a good move that produced a beta-cutoff
2410 // among the killer moves of that ply.
2412 void update_killers(Move m, SearchStack& ss) {
2414 if (m == ss.killers[0])
2417 for (int i = KILLER_MAX - 1; i > 0; i--)
2418 ss.killers[i] = ss.killers[i - 1];
2423 // fail_high_ply_1() checks if some thread is currently resolving a fail
2424 // high at ply 1 at the node below the first root node. This information
2425 // is used for time managment.
2427 bool fail_high_ply_1() {
2428 for(int i = 0; i < ActiveThreads; i++)
2429 if(Threads[i].failHighPly1)
2435 // current_search_time() returns the number of milliseconds which have passed
2436 // since the beginning of the current search.
2438 int current_search_time() {
2439 return get_system_time() - SearchStartTime;
2443 // nps() computes the current nodes/second count.
2446 int t = current_search_time();
2447 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2451 // poll() performs two different functions: It polls for user input, and it
2452 // looks at the time consumed so far and decides if it's time to abort the
2457 static int lastInfoTime;
2458 int t = current_search_time();
2463 // We are line oriented, don't read single chars
2464 std::string command;
2465 if (!std::getline(std::cin, command))
2468 if (command == "quit")
2471 PonderSearch = false;
2474 else if(command == "stop")
2477 PonderSearch = false;
2479 else if(command == "ponderhit")
2482 // Print search information
2486 else if (lastInfoTime > t)
2487 // HACK: Must be a new search where we searched less than
2488 // NodesBetweenPolls nodes during the first second of search.
2491 else if (t - lastInfoTime >= 1000)
2498 if (dbg_show_hit_rate)
2499 dbg_print_hit_rate();
2501 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2502 << " time " << t << " hashfull " << TT.full() << std::endl;
2503 lock_release(&IOLock);
2504 if (ShowCurrentLine)
2505 Threads[0].printCurrentLine = true;
2507 // Should we stop the search?
2511 bool overTime = t > AbsoluteMaxSearchTime
2512 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2513 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2514 && t > 6*(MaxSearchTime + ExtraSearchTime));
2516 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2517 || (ExactMaxTime && t >= ExactMaxTime)
2518 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2523 // ponderhit() is called when the program is pondering (i.e. thinking while
2524 // it's the opponent's turn to move) in order to let the engine know that
2525 // it correctly predicted the opponent's move.
2528 int t = current_search_time();
2529 PonderSearch = false;
2530 if(Iteration >= 3 &&
2531 (!InfiniteSearch && (StopOnPonderhit ||
2532 t > AbsoluteMaxSearchTime ||
2533 (RootMoveNumber == 1 &&
2534 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2535 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2536 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2541 // print_current_line() prints the current line of search for a given
2542 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2544 void print_current_line(SearchStack ss[], int ply, int threadID) {
2545 assert(ply >= 0 && ply < PLY_MAX);
2546 assert(threadID >= 0 && threadID < ActiveThreads);
2548 if(!Threads[threadID].idle) {
2550 std::cout << "info currline " << (threadID + 1);
2551 for(int p = 0; p < ply; p++)
2552 std::cout << " " << ss[p].currentMove;
2553 std::cout << std::endl;
2554 lock_release(&IOLock);
2556 Threads[threadID].printCurrentLine = false;
2557 if(threadID + 1 < ActiveThreads)
2558 Threads[threadID + 1].printCurrentLine = true;
2562 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2563 // while the program is pondering. The point is to work around a wrinkle in
2564 // the UCI protocol: When pondering, the engine is not allowed to give a
2565 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2566 // We simply wait here until one of these commands is sent, and return,
2567 // after which the bestmove and pondermove will be printed (in id_loop()).
2569 void wait_for_stop_or_ponderhit() {
2570 std::string command;
2573 if(!std::getline(std::cin, command))
2576 if(command == "quit") {
2577 OpeningBook.close();
2582 else if(command == "ponderhit" || command == "stop")
2588 // idle_loop() is where the threads are parked when they have no work to do.
2589 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2590 // object for which the current thread is the master.
2592 void idle_loop(int threadID, SplitPoint *waitSp) {
2593 assert(threadID >= 0 && threadID < THREAD_MAX);
2595 Threads[threadID].running = true;
2598 if(AllThreadsShouldExit && threadID != 0)
2601 // If we are not thinking, wait for a condition to be signaled instead
2602 // of wasting CPU time polling for work:
2603 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2604 #if !defined(_MSC_VER)
2605 pthread_mutex_lock(&WaitLock);
2606 if(Idle || threadID >= ActiveThreads)
2607 pthread_cond_wait(&WaitCond, &WaitLock);
2608 pthread_mutex_unlock(&WaitLock);
2610 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2614 // If this thread has been assigned work, launch a search:
2615 if(Threads[threadID].workIsWaiting) {
2616 Threads[threadID].workIsWaiting = false;
2617 if(Threads[threadID].splitPoint->pvNode)
2618 sp_search_pv(Threads[threadID].splitPoint, threadID);
2620 sp_search(Threads[threadID].splitPoint, threadID);
2621 Threads[threadID].idle = true;
2624 // If this thread is the master of a split point and all threads have
2625 // finished their work at this split point, return from the idle loop:
2626 if(waitSp != NULL && waitSp->cpus == 0)
2630 Threads[threadID].running = false;
2634 // init_split_point_stack() is called during program initialization, and
2635 // initializes all split point objects.
2637 void init_split_point_stack() {
2638 for(int i = 0; i < THREAD_MAX; i++)
2639 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2640 SplitPointStack[i][j].parent = NULL;
2641 lock_init(&(SplitPointStack[i][j].lock), NULL);
2646 // destroy_split_point_stack() is called when the program exits, and
2647 // destroys all locks in the precomputed split point objects.
2649 void destroy_split_point_stack() {
2650 for(int i = 0; i < THREAD_MAX; i++)
2651 for(int j = 0; j < MaxActiveSplitPoints; j++)
2652 lock_destroy(&(SplitPointStack[i][j].lock));
2656 // thread_should_stop() checks whether the thread with a given threadID has
2657 // been asked to stop, directly or indirectly. This can happen if a beta
2658 // cutoff has occured in thre thread's currently active split point, or in
2659 // some ancestor of the current split point.
2661 bool thread_should_stop(int threadID) {
2662 assert(threadID >= 0 && threadID < ActiveThreads);
2666 if(Threads[threadID].stop)
2668 if(ActiveThreads <= 2)
2670 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2672 Threads[threadID].stop = true;
2679 // thread_is_available() checks whether the thread with threadID "slave" is
2680 // available to help the thread with threadID "master" at a split point. An
2681 // obvious requirement is that "slave" must be idle. With more than two
2682 // threads, this is not by itself sufficient: If "slave" is the master of
2683 // some active split point, it is only available as a slave to the other
2684 // threads which are busy searching the split point at the top of "slave"'s
2685 // split point stack (the "helpful master concept" in YBWC terminology).
2687 bool thread_is_available(int slave, int master) {
2688 assert(slave >= 0 && slave < ActiveThreads);
2689 assert(master >= 0 && master < ActiveThreads);
2690 assert(ActiveThreads > 1);
2692 if(!Threads[slave].idle || slave == master)
2695 if(Threads[slave].activeSplitPoints == 0)
2696 // No active split points means that the thread is available as a slave
2697 // for any other thread.
2700 if(ActiveThreads == 2)
2703 // Apply the "helpful master" concept if possible.
2704 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2711 // idle_thread_exists() tries to find an idle thread which is available as
2712 // a slave for the thread with threadID "master".
2714 bool idle_thread_exists(int master) {
2715 assert(master >= 0 && master < ActiveThreads);
2716 assert(ActiveThreads > 1);
2718 for(int i = 0; i < ActiveThreads; i++)
2719 if(thread_is_available(i, master))
2725 // split() does the actual work of distributing the work at a node between
2726 // several threads at PV nodes. If it does not succeed in splitting the
2727 // node (because no idle threads are available, or because we have no unused
2728 // split point objects), the function immediately returns false. If
2729 // splitting is possible, a SplitPoint object is initialized with all the
2730 // data that must be copied to the helper threads (the current position and
2731 // search stack, alpha, beta, the search depth, etc.), and we tell our
2732 // helper threads that they have been assigned work. This will cause them
2733 // to instantly leave their idle loops and call sp_search_pv(). When all
2734 // threads have returned from sp_search_pv (or, equivalently, when
2735 // splitPoint->cpus becomes 0), split() returns true.
2737 bool split(const Position &p, SearchStack *sstck, int ply,
2738 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2739 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2742 assert(sstck != NULL);
2743 assert(ply >= 0 && ply < PLY_MAX);
2744 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2745 assert(!pvNode || *alpha < *beta);
2746 assert(*beta <= VALUE_INFINITE);
2747 assert(depth > Depth(0));
2748 assert(master >= 0 && master < ActiveThreads);
2749 assert(ActiveThreads > 1);
2751 SplitPoint *splitPoint;
2756 // If no other thread is available to help us, or if we have too many
2757 // active split points, don't split:
2758 if(!idle_thread_exists(master) ||
2759 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2760 lock_release(&MPLock);
2764 // Pick the next available split point object from the split point stack:
2765 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2766 Threads[master].activeSplitPoints++;
2768 // Initialize the split point object:
2769 splitPoint->parent = Threads[master].splitPoint;
2770 splitPoint->finished = false;
2771 splitPoint->ply = ply;
2772 splitPoint->depth = depth;
2773 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2774 splitPoint->beta = *beta;
2775 splitPoint->pvNode = pvNode;
2776 splitPoint->dcCandidates = dcCandidates;
2777 splitPoint->bestValue = *bestValue;
2778 splitPoint->master = master;
2779 splitPoint->mp = mp;
2780 splitPoint->moves = *moves;
2781 splitPoint->cpus = 1;
2782 splitPoint->pos.copy(p);
2783 splitPoint->parentSstack = sstck;
2784 for(i = 0; i < ActiveThreads; i++)
2785 splitPoint->slaves[i] = 0;
2787 // Copy the current position and the search stack to the master thread:
2788 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2789 Threads[master].splitPoint = splitPoint;
2791 // Make copies of the current position and search stack for each thread:
2792 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2794 if(thread_is_available(i, master)) {
2795 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2796 Threads[i].splitPoint = splitPoint;
2797 splitPoint->slaves[i] = 1;
2801 // Tell the threads that they have work to do. This will make them leave
2803 for(i = 0; i < ActiveThreads; i++)
2804 if(i == master || splitPoint->slaves[i]) {
2805 Threads[i].workIsWaiting = true;
2806 Threads[i].idle = false;
2807 Threads[i].stop = false;
2810 lock_release(&MPLock);
2812 // Everything is set up. The master thread enters the idle loop, from
2813 // which it will instantly launch a search, because its workIsWaiting
2814 // slot is 'true'. We send the split point as a second parameter to the
2815 // idle loop, which means that the main thread will return from the idle
2816 // loop when all threads have finished their work at this split point
2817 // (i.e. when // splitPoint->cpus == 0).
2818 idle_loop(master, splitPoint);
2820 // We have returned from the idle loop, which means that all threads are
2821 // finished. Update alpha, beta and bestvalue, and return:
2823 if(pvNode) *alpha = splitPoint->alpha;
2824 *beta = splitPoint->beta;
2825 *bestValue = splitPoint->bestValue;
2826 Threads[master].stop = false;
2827 Threads[master].idle = false;
2828 Threads[master].activeSplitPoints--;
2829 Threads[master].splitPoint = splitPoint->parent;
2830 lock_release(&MPLock);
2836 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2837 // to start a new search from the root.
2839 void wake_sleeping_threads() {
2840 if(ActiveThreads > 1) {
2841 for(int i = 1; i < ActiveThreads; i++) {
2842 Threads[i].idle = true;
2843 Threads[i].workIsWaiting = false;
2845 #if !defined(_MSC_VER)
2846 pthread_mutex_lock(&WaitLock);
2847 pthread_cond_broadcast(&WaitCond);
2848 pthread_mutex_unlock(&WaitLock);
2850 for(int i = 1; i < THREAD_MAX; i++)
2851 SetEvent(SitIdleEvent[i]);
2857 // init_thread() is the function which is called when a new thread is
2858 // launched. It simply calls the idle_loop() function with the supplied
2859 // threadID. There are two versions of this function; one for POSIX threads
2860 // and one for Windows threads.
2862 #if !defined(_MSC_VER)
2864 void *init_thread(void *threadID) {
2865 idle_loop(*(int *)threadID, NULL);
2871 DWORD WINAPI init_thread(LPVOID threadID) {
2872 idle_loop(*(int *)threadID, NULL);