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 // The BetaCounterType class is used to order moves at ply one.
51 // Apart for the first one that has its score, following moves
52 // normally have score -VALUE_INFINITE, so are ordered according
53 // to the number of beta cutoffs occurred under their subtree during
54 // the last iteration.
56 struct BetaCounterType {
60 void add(Color us, Depth d, int threadID);
61 void read(Color us, int64_t& our, int64_t& their);
63 int64_t hits[THREAD_MAX][2];
67 // The RootMove class is used for moves at the root at the tree. For each
68 // root move, we store a score, a node count, and a PV (really a refutation
69 // in the case of moves which fail low).
74 bool operator<(const RootMove&); // used to sort
78 int64_t nodes, cumulativeNodes;
79 Move pv[PLY_MAX_PLUS_2];
80 int64_t ourBeta, theirBeta;
84 // The RootMoveList class is essentially an array of RootMove objects, with
85 // a handful of methods for accessing the data in the individual moves.
90 RootMoveList(Position &pos, Move searchMoves[]);
91 inline Move get_move(int moveNum) const;
92 inline Value get_move_score(int moveNum) const;
93 inline void set_move_score(int moveNum, Value score);
94 inline void set_move_nodes(int moveNum, int64_t nodes);
95 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
96 void set_move_pv(int moveNum, const Move pv[]);
97 inline Move get_move_pv(int moveNum, int i) const;
98 inline int64_t get_move_cumulative_nodes(int moveNum) const;
99 inline int move_count() const;
100 Move scan_for_easy_move() const;
102 void sort_multipv(int n);
105 static const int MaxRootMoves = 500;
106 RootMove moves[MaxRootMoves];
111 /// Constants and variables
113 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
116 int LMRNonPVMoves = 4;
118 // Depth limit for use of dynamic threat detection:
119 Depth ThreatDepth = 5*OnePly;
121 // Depth limit for selective search:
122 Depth SelectiveDepth = 7*OnePly;
125 const bool UseDynamicLMR = false;
127 // Use internal iterative deepening?
128 const bool UseIIDAtPVNodes = true;
129 const bool UseIIDAtNonPVNodes = false;
131 // Internal iterative deepening margin. At Non-PV moves, when
132 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
133 // when the static evaluation is at most IIDMargin below beta.
134 const Value IIDMargin = Value(0x100);
136 // Easy move margin. An easy move candidate must be at least this much
137 // better than the second best move.
138 const Value EasyMoveMargin = Value(0x200);
140 // Problem margin. If the score of the first move at iteration N+1 has
141 // dropped by more than this since iteration N, the boolean variable
142 // "Problem" is set to true, which will make the program spend some extra
143 // time looking for a better move.
144 const Value ProblemMargin = Value(0x28);
146 // No problem margin. If the boolean "Problem" is true, and a new move
147 // is found at the root which is less than NoProblemMargin worse than the
148 // best move from the previous iteration, Problem is set back to false.
149 const Value NoProblemMargin = Value(0x14);
151 // Null move margin. A null move search will not be done if the approximate
152 // evaluation of the position is more than NullMoveMargin below beta.
153 const Value NullMoveMargin = Value(0x300);
155 // Pruning criterions. See the code and comments in ok_to_prune() to
156 // understand their precise meaning.
157 const bool PruneEscapeMoves = false;
158 const bool PruneDefendingMoves = false;
159 const bool PruneBlockingMoves = false;
161 // Use futility pruning?
162 bool UseQSearchFutilityPruning = true;
163 bool UseFutilityPruning = true;
165 // Margins for futility pruning in the quiescence search, and at frontier
166 // and near frontier nodes
167 Value FutilityMarginQS = Value(0x80);
168 Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
169 Value(0x2A0), Value(0x340), Value(0x3A0) };
172 const bool RazorAtDepthOne = false;
173 Depth RazorDepth = 4*OnePly;
174 Value RazorMargin = Value(0x300);
176 // Last seconds noise filtering (LSN)
177 bool UseLSNFiltering = false;
178 bool looseOnTime = false;
179 int LSNTime = 4 * 1000; // In milliseconds
180 Value LSNValue = Value(0x200);
182 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
183 Depth CheckExtension[2] = {OnePly, OnePly};
184 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
185 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
186 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
187 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
188 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
190 // Search depth at iteration 1
191 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
195 int NodesBetweenPolls = 30000;
197 // Iteration counters
199 BetaCounterType BetaCounter;
201 // Scores and number of times the best move changed for each iteration:
202 Value ValueByIteration[PLY_MAX_PLUS_2];
203 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
208 // Time managment variables
210 int MaxNodes, MaxDepth;
211 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
216 bool StopOnPonderhit;
221 bool PonderingEnabled;
224 // Show current line?
225 bool ShowCurrentLine = false;
228 bool UseLogFile = false;
229 std::ofstream LogFile;
231 // MP related variables
232 Depth MinimumSplitDepth = 4*OnePly;
233 int MaxThreadsPerSplitPoint = 4;
234 Thread Threads[THREAD_MAX];
236 bool AllThreadsShouldExit = false;
237 const int MaxActiveSplitPoints = 8;
238 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
241 #if !defined(_MSC_VER)
242 pthread_cond_t WaitCond;
243 pthread_mutex_t WaitLock;
245 HANDLE SitIdleEvent[THREAD_MAX];
251 Value id_loop(const Position &pos, Move searchMoves[]);
252 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
253 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
254 Depth depth, int ply, int threadID);
255 Value search(Position &pos, SearchStack ss[], Value beta,
256 Depth depth, int ply, bool allowNullmove, int threadID);
257 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
258 Depth depth, int ply, int threadID);
259 void sp_search(SplitPoint *sp, int threadID);
260 void sp_search_pv(SplitPoint *sp, int threadID);
261 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
262 void update_pv(SearchStack ss[], int ply);
263 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
264 bool connected_moves(const Position &pos, Move m1, Move m2);
265 bool value_is_mate(Value value);
266 bool move_is_killer(Move m, const SearchStack& ss);
267 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
268 bool ok_to_do_nullmove(const Position &pos);
269 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
270 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
271 bool ok_to_history(const Position &pos, Move m);
272 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
273 void update_killers(Move m, SearchStack& ss);
275 bool fail_high_ply_1();
276 int current_search_time();
280 void print_current_line(SearchStack ss[], int ply, int threadID);
281 void wait_for_stop_or_ponderhit();
283 void idle_loop(int threadID, SplitPoint *waitSp);
284 void init_split_point_stack();
285 void destroy_split_point_stack();
286 bool thread_should_stop(int threadID);
287 bool thread_is_available(int slave, int master);
288 bool idle_thread_exists(int master);
289 bool split(const Position &pos, SearchStack *ss, int ply,
290 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
291 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
292 void wake_sleeping_threads();
294 #if !defined(_MSC_VER)
295 void *init_thread(void *threadID);
297 DWORD WINAPI init_thread(LPVOID threadID);
304 //// Global variables
307 // The main transposition table
308 TranspositionTable TT = TranspositionTable(TTDefaultSize);
311 // Number of active threads:
312 int ActiveThreads = 1;
314 // Locks. In principle, there is no need for IOLock to be a global variable,
315 // but it could turn out to be useful for debugging.
318 History H; // Should be made local?
320 // The empty search stack
321 SearchStack EmptySearchStack;
324 // SearchStack::init() initializes a search stack. Used at the beginning of a
325 // new search from the root.
326 void SearchStack::init(int ply) {
328 pv[ply] = pv[ply + 1] = MOVE_NONE;
329 currentMove = threatMove = MOVE_NONE;
330 reduction = Depth(0);
331 currentMoveCaptureValue = Value(0);
334 void SearchStack::initKillers() {
336 mateKiller = MOVE_NONE;
337 for (int i = 0; i < KILLER_MAX; i++)
338 killers[i] = MOVE_NONE;
346 /// think() is the external interface to Stockfish's search, and is called when
347 /// the program receives the UCI 'go' command. It initializes various
348 /// search-related global variables, and calls root_search()
350 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
351 int time[], int increment[], int movesToGo, int maxDepth,
352 int maxNodes, int maxTime, Move searchMoves[]) {
354 // Look for a book move
355 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
358 if (get_option_value_string("Book File") != OpeningBook.file_name())
361 OpeningBook.open("book.bin");
363 bookMove = OpeningBook.get_move(pos);
364 if (bookMove != MOVE_NONE)
366 std::cout << "bestmove " << bookMove << std::endl;
371 // Initialize global search variables
373 SearchStartTime = get_system_time();
374 EasyMove = MOVE_NONE;
375 for (int i = 0; i < THREAD_MAX; i++)
377 Threads[i].nodes = 0ULL;
378 Threads[i].failHighPly1 = false;
381 InfiniteSearch = infinite;
382 PonderSearch = ponder;
383 StopOnPonderhit = false;
388 ExactMaxTime = maxTime;
390 // Read UCI option values
391 TT.set_size(get_option_value_int("Hash"));
392 if (button_was_pressed("Clear Hash"))
395 PonderingEnabled = get_option_value_bool("Ponder");
396 MultiPV = get_option_value_int("MultiPV");
398 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
399 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
401 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
402 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
404 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
405 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
407 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
408 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
410 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
411 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
413 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
414 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
416 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
417 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
418 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
419 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
421 Chess960 = get_option_value_bool("UCI_Chess960");
422 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
423 UseLogFile = get_option_value_bool("Use Search Log");
425 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
427 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
428 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
430 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
431 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
432 for (int i = 0; i < 6; i++)
433 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
435 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
436 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
438 UseLSNFiltering = get_option_value_bool("LSN filtering");
439 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
440 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
442 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
443 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
445 read_weights(pos.side_to_move());
447 int newActiveThreads = get_option_value_int("Threads");
448 if (newActiveThreads != ActiveThreads)
450 ActiveThreads = newActiveThreads;
451 init_eval(ActiveThreads);
454 // Wake up sleeping threads:
455 wake_sleeping_threads();
457 for (int i = 1; i < ActiveThreads; i++)
458 assert(thread_is_available(i, 0));
460 // Set thinking time:
461 int myTime = time[side_to_move];
462 int myIncrement = increment[side_to_move];
464 if (!movesToGo) // Sudden death time control
468 MaxSearchTime = myTime / 30 + myIncrement;
469 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
470 } else { // Blitz game without increment
471 MaxSearchTime = myTime / 30;
472 AbsoluteMaxSearchTime = myTime / 8;
475 else // (x moves) / (y minutes)
479 MaxSearchTime = myTime / 2;
480 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
482 MaxSearchTime = myTime / Min(movesToGo, 20);
483 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
487 if (PonderingEnabled)
489 MaxSearchTime += MaxSearchTime / 4;
490 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
493 // Fixed depth or fixed number of nodes?
496 InfiniteSearch = true; // HACK
501 NodesBetweenPolls = Min(MaxNodes, 30000);
502 InfiniteSearch = true; // HACK
505 NodesBetweenPolls = 30000;
508 // Write information to search log file:
510 LogFile << "Searching: " << pos.to_fen() << std::endl
511 << "infinite: " << infinite
512 << " ponder: " << ponder
513 << " time: " << myTime
514 << " increment: " << myIncrement
515 << " moves to go: " << movesToGo << std::endl;
518 // We're ready to start thinking. Call the iterative deepening loop
522 Value v = id_loop(pos, searchMoves);
523 looseOnTime = ( UseLSNFiltering
530 looseOnTime = false; // reset for next match
531 while (SearchStartTime + myTime + 1000 > get_system_time())
533 id_loop(pos, searchMoves); // to fail gracefully
550 /// init_threads() is called during startup. It launches all helper threads,
551 /// and initializes the split point stack and the global locks and condition
554 void init_threads() {
558 #if !defined(_MSC_VER)
559 pthread_t pthread[1];
562 for (i = 0; i < THREAD_MAX; i++)
563 Threads[i].activeSplitPoints = 0;
565 // Initialize global locks:
566 lock_init(&MPLock, NULL);
567 lock_init(&IOLock, NULL);
569 init_split_point_stack();
571 #if !defined(_MSC_VER)
572 pthread_mutex_init(&WaitLock, NULL);
573 pthread_cond_init(&WaitCond, NULL);
575 for (i = 0; i < THREAD_MAX; i++)
576 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
579 // All threads except the main thread should be initialized to idle state
580 for (i = 1; i < THREAD_MAX; i++)
582 Threads[i].stop = false;
583 Threads[i].workIsWaiting = false;
584 Threads[i].idle = true;
585 Threads[i].running = false;
588 // Launch the helper threads
589 for(i = 1; i < THREAD_MAX; i++)
591 #if !defined(_MSC_VER)
592 pthread_create(pthread, NULL, init_thread, (void*)(&i));
595 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
598 // Wait until the thread has finished launching:
599 while (!Threads[i].running);
602 // Init also the empty search stack
603 EmptySearchStack.init(0);
604 EmptySearchStack.initKillers();
608 /// stop_threads() is called when the program exits. It makes all the
609 /// helper threads exit cleanly.
611 void stop_threads() {
613 ActiveThreads = THREAD_MAX; // HACK
614 Idle = false; // HACK
615 wake_sleeping_threads();
616 AllThreadsShouldExit = true;
617 for (int i = 1; i < THREAD_MAX; i++)
619 Threads[i].stop = true;
620 while(Threads[i].running);
622 destroy_split_point_stack();
626 /// nodes_searched() returns the total number of nodes searched so far in
627 /// the current search.
629 int64_t nodes_searched() {
631 int64_t result = 0ULL;
632 for (int i = 0; i < ActiveThreads; i++)
633 result += Threads[i].nodes;
640 // id_loop() is the main iterative deepening loop. It calls root_search
641 // repeatedly with increasing depth until the allocated thinking time has
642 // been consumed, the user stops the search, or the maximum search depth is
645 Value id_loop(const Position &pos, Move searchMoves[]) {
648 SearchStack ss[PLY_MAX_PLUS_2];
650 // searchMoves are verified, copied, scored and sorted
651 RootMoveList rml(p, searchMoves);
656 for (int i = 0; i < 3; i++)
661 ValueByIteration[0] = Value(0);
662 ValueByIteration[1] = rml.get_move_score(0);
665 EasyMove = rml.scan_for_easy_move();
667 // Iterative deepening loop
668 while (!AbortSearch && Iteration < PLY_MAX)
670 // Initialize iteration
673 BestMoveChangesByIteration[Iteration] = 0;
677 std::cout << "info depth " << Iteration << std::endl;
679 // Search to the current depth
680 ValueByIteration[Iteration] = root_search(p, ss, rml);
682 // Erase the easy move if it differs from the new best move
683 if (ss[0].pv[0] != EasyMove)
684 EasyMove = MOVE_NONE;
691 bool stopSearch = false;
693 // Stop search early if there is only a single legal move:
694 if (Iteration >= 6 && rml.move_count() == 1)
697 // Stop search early when the last two iterations returned a mate score
699 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
700 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
703 // Stop search early if one move seems to be much better than the rest
704 int64_t nodes = nodes_searched();
706 && EasyMove == ss[0].pv[0]
707 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
708 && current_search_time() > MaxSearchTime / 16)
709 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
710 && current_search_time() > MaxSearchTime / 32)))
713 // Add some extra time if the best move has changed during the last two iterations
714 if (Iteration > 5 && Iteration <= 50)
715 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
716 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
718 // Stop search if most of MaxSearchTime is consumed at the end of the
719 // iteration. We probably don't have enough time to search the first
720 // move at the next iteration anyway.
721 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
729 StopOnPonderhit = true;
732 // Write PV to transposition table, in case the relevant entries have
733 // been overwritten during the search:
734 TT.insert_pv(p, ss[0].pv);
736 if (MaxDepth && Iteration >= MaxDepth)
742 // If we are pondering, we shouldn't print the best move before we
745 wait_for_stop_or_ponderhit();
747 // Print final search statistics
748 std::cout << "info nodes " << nodes_searched()
750 << " time " << current_search_time()
751 << " hashfull " << TT.full() << std::endl;
753 // Print the best move and the ponder move to the standard output
754 if (ss[0].pv[0] == MOVE_NONE)
756 ss[0].pv[0] = rml.get_move(0);
757 ss[0].pv[1] = MOVE_NONE;
759 std::cout << "bestmove " << ss[0].pv[0];
760 if (ss[0].pv[1] != MOVE_NONE)
761 std::cout << " ponder " << ss[0].pv[1];
763 std::cout << std::endl;
768 dbg_print_mean(LogFile);
770 if (dbg_show_hit_rate)
771 dbg_print_hit_rate(LogFile);
774 LogFile << "Nodes: " << nodes_searched() << std::endl
775 << "Nodes/second: " << nps() << std::endl
776 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
778 p.do_move(ss[0].pv[0], st);
779 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
780 << std::endl << std::endl;
782 return rml.get_move_score(0);
786 // root_search() is the function which searches the root node. It is
787 // similar to search_pv except that it uses a different move ordering
788 // scheme (perhaps we should try to use this at internal PV nodes, too?)
789 // and prints some information to the standard output.
791 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
793 Value alpha = -VALUE_INFINITE;
794 Value beta = VALUE_INFINITE, value;
795 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
797 // Loop through all the moves in the root move list
798 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
805 RootMoveNumber = i + 1;
808 // Remember the node count before the move is searched. The node counts
809 // are used to sort the root moves at the next iteration.
810 nodes = nodes_searched();
812 // Reset beta cut-off counters
815 // Pick the next root move, and print the move and the move number to
816 // the standard output.
817 move = ss[0].currentMove = rml.get_move(i);
818 if (current_search_time() >= 1000)
819 std::cout << "info currmove " << move
820 << " currmovenumber " << i + 1 << std::endl;
822 // Decide search depth for this move
824 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
825 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
827 // Make the move, and search it
828 pos.do_move(move, st, dcCandidates);
832 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
833 // If the value has dropped a lot compared to the last iteration,
834 // set the boolean variable Problem to true. This variable is used
835 // for time managment: When Problem is true, we try to complete the
836 // current iteration before playing a move.
837 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
839 if (Problem && StopOnPonderhit)
840 StopOnPonderhit = false;
844 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
847 // Fail high! Set the boolean variable FailHigh to true, and
848 // re-search the move with a big window. The variable FailHigh is
849 // used for time managment: We try to avoid aborting the search
850 // prematurely during a fail high research.
852 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
858 // Finished searching the move. If AbortSearch is true, the search
859 // was aborted because the user interrupted the search or because we
860 // ran out of time. In this case, the return value of the search cannot
861 // be trusted, and we break out of the loop without updating the best
866 // Remember the node count for this move. The node counts are used to
867 // sort the root moves at the next iteration.
868 rml.set_move_nodes(i, nodes_searched() - nodes);
870 // Remember the beta-cutoff statistics
872 BetaCounter.read(pos.side_to_move(), our, their);
873 rml.set_beta_counters(i, our, their);
875 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
877 if (value <= alpha && i >= MultiPV)
878 rml.set_move_score(i, -VALUE_INFINITE);
884 rml.set_move_score(i, value);
886 rml.set_move_pv(i, ss[0].pv);
890 // We record how often the best move has been changed in each
891 // iteration. This information is used for time managment: When
892 // the best move changes frequently, we allocate some more time.
894 BestMoveChangesByIteration[Iteration]++;
896 // Print search information to the standard output:
897 std::cout << "info depth " << Iteration
898 << " score " << value_to_string(value)
899 << " time " << current_search_time()
900 << " nodes " << nodes_searched()
904 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
905 std::cout << ss[0].pv[j] << " ";
907 std::cout << std::endl;
910 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
915 // Reset the global variable Problem to false if the value isn't too
916 // far below the final value from the last iteration.
917 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
923 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
926 std::cout << "info multipv " << j + 1
927 << " score " << value_to_string(rml.get_move_score(j))
928 << " depth " << ((j <= i)? Iteration : Iteration - 1)
929 << " time " << current_search_time()
930 << " nodes " << nodes_searched()
934 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
935 std::cout << rml.get_move_pv(j, k) << " ";
937 std::cout << std::endl;
939 alpha = rml.get_move_score(Min(i, MultiPV-1));
947 // search_pv() is the main search function for PV nodes.
949 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
950 Depth depth, int ply, int threadID) {
952 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
953 assert(beta > alpha && beta <= VALUE_INFINITE);
954 assert(ply >= 0 && ply < PLY_MAX);
955 assert(threadID >= 0 && threadID < ActiveThreads);
958 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
960 // Initialize, and make an early exit in case of an aborted search,
961 // an instant draw, maximum ply reached, etc.
962 init_node(pos, ss, ply, threadID);
964 // After init_node() that calls poll()
965 if (AbortSearch || thread_should_stop(threadID))
973 if (ply >= PLY_MAX - 1)
974 return evaluate(pos, ei, threadID);
976 // Mate distance pruning
977 Value oldAlpha = alpha;
978 alpha = Max(value_mated_in(ply), alpha);
979 beta = Min(value_mate_in(ply+1), beta);
983 // Transposition table lookup. At PV nodes, we don't use the TT for
984 // pruning, but only for move ordering.
985 const TTEntry* tte = TT.retrieve(pos);
986 Move ttMove = (tte ? tte->move() : MOVE_NONE);
988 // Go with internal iterative deepening if we don't have a TT move
989 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
991 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
992 ttMove = ss[ply].pv[ply];
995 // Initialize a MovePicker object for the current position, and prepare
996 // to search all moves
997 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
999 Move move, movesSearched[256];
1001 Value value, bestValue = -VALUE_INFINITE;
1002 Bitboard dcCandidates = mp.discovered_check_candidates();
1003 Color us = pos.side_to_move();
1004 bool isCheck = pos.is_check();
1005 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1007 // Loop through all legal moves until no moves remain or a beta cutoff
1009 while ( alpha < beta
1010 && (move = mp.get_next_move()) != MOVE_NONE
1011 && !thread_should_stop(threadID))
1013 assert(move_is_ok(move));
1015 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1016 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1017 bool moveIsCapture = pos.move_is_capture(move);
1019 movesSearched[moveCount++] = ss[ply].currentMove = move;
1022 ss[ply].currentMoveCaptureValue =
1023 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1025 ss[ply].currentMoveCaptureValue = Value(0);
1027 // Decide the new search depth
1029 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1030 Depth newDepth = depth - OnePly + ext;
1032 // Make and search the move
1034 pos.do_move(move, st, dcCandidates);
1036 if (moveCount == 1) // The first move in list is the PV
1037 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1040 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1041 // if the move fails high will be re-searched at full depth.
1042 if ( depth >= 2*OnePly
1043 && moveCount >= LMRPVMoves
1046 && !move_promotion(move)
1047 && !move_is_castle(move)
1048 && !move_is_killer(move, ss[ply]))
1050 ss[ply].reduction = OnePly;
1051 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1054 value = alpha + 1; // Just to trigger next condition
1056 if (value > alpha) // Go with full depth non-pv search
1058 ss[ply].reduction = Depth(0);
1059 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1060 if (value > alpha && value < beta)
1062 // When the search fails high at ply 1 while searching the first
1063 // move at the root, set the flag failHighPly1. This is used for
1064 // time managment: We don't want to stop the search early in
1065 // such cases, because resolving the fail high at ply 1 could
1066 // result in a big drop in score at the root.
1067 if (ply == 1 && RootMoveNumber == 1)
1068 Threads[threadID].failHighPly1 = true;
1070 // A fail high occurred. Re-search at full window (pv search)
1071 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1072 Threads[threadID].failHighPly1 = false;
1076 pos.undo_move(move);
1078 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1081 if (value > bestValue)
1088 if (value == value_mate_in(ply + 1))
1089 ss[ply].mateKiller = move;
1091 // If we are at ply 1, and we are searching the first root move at
1092 // ply 0, set the 'Problem' variable if the score has dropped a lot
1093 // (from the computer's point of view) since the previous iteration:
1096 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1101 if ( ActiveThreads > 1
1103 && depth >= MinimumSplitDepth
1105 && idle_thread_exists(threadID)
1107 && !thread_should_stop(threadID)
1108 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1109 &moveCount, &mp, dcCandidates, threadID, true))
1113 // All legal moves have been searched. A special case: If there were
1114 // no legal moves, it must be mate or stalemate:
1116 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1118 // If the search is not aborted, update the transposition table,
1119 // history counters, and killer moves.
1120 if (AbortSearch || thread_should_stop(threadID))
1123 if (bestValue <= oldAlpha)
1124 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1126 else if (bestValue >= beta)
1128 BetaCounter.add(pos.side_to_move(), depth, threadID);
1129 Move m = ss[ply].pv[ply];
1130 if (ok_to_history(pos, m)) // Only non capture moves are considered
1132 update_history(pos, m, depth, movesSearched, moveCount);
1133 update_killers(m, ss[ply]);
1135 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1138 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1144 // search() is the search function for zero-width nodes.
1146 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1147 int ply, bool allowNullmove, int threadID) {
1149 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1150 assert(ply >= 0 && ply < PLY_MAX);
1151 assert(threadID >= 0 && threadID < ActiveThreads);
1154 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1156 // Initialize, and make an early exit in case of an aborted search,
1157 // an instant draw, maximum ply reached, etc.
1158 init_node(pos, ss, ply, threadID);
1160 // After init_node() that calls poll()
1161 if (AbortSearch || thread_should_stop(threadID))
1169 if (ply >= PLY_MAX - 1)
1170 return evaluate(pos, ei, threadID);
1172 // Mate distance pruning
1173 if (value_mated_in(ply) >= beta)
1176 if (value_mate_in(ply + 1) < beta)
1179 // Transposition table lookup
1180 const TTEntry* tte = TT.retrieve(pos);
1181 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1183 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1185 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1186 return value_from_tt(tte->value(), ply);
1189 Value approximateEval = quick_evaluate(pos);
1190 bool mateThreat = false;
1191 bool isCheck = pos.is_check();
1197 && !value_is_mate(beta)
1198 && ok_to_do_nullmove(pos)
1199 && approximateEval >= beta - NullMoveMargin)
1201 ss[ply].currentMove = MOVE_NULL;
1204 pos.do_null_move(st);
1205 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1207 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1209 pos.undo_null_move();
1211 if (value_is_mate(nullValue))
1213 /* Do not return unproven mates */
1215 else if (nullValue >= beta)
1217 if (depth < 6 * OnePly)
1220 // Do zugzwang verification search
1221 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1225 // The null move failed low, which means that we may be faced with
1226 // some kind of threat. If the previous move was reduced, check if
1227 // the move that refuted the null move was somehow connected to the
1228 // move which was reduced. If a connection is found, return a fail
1229 // low score (which will cause the reduced move to fail high in the
1230 // parent node, which will trigger a re-search with full depth).
1231 if (nullValue == value_mated_in(ply + 2))
1234 ss[ply].threatMove = ss[ply + 1].currentMove;
1235 if ( depth < ThreatDepth
1236 && ss[ply - 1].reduction
1237 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1241 // Null move search not allowed, try razoring
1242 else if ( !value_is_mate(beta)
1243 && approximateEval < beta - RazorMargin
1244 && depth < RazorDepth
1245 && (RazorAtDepthOne || depth > OnePly)
1246 && ttMove == MOVE_NONE
1247 && !pos.has_pawn_on_7th(pos.side_to_move()))
1249 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1250 if ( (v < beta - RazorMargin - RazorMargin / 4)
1251 || (depth <= 2*OnePly && v < beta - RazorMargin)
1252 || (depth <= OnePly && v < beta - RazorMargin / 2))
1256 // Go with internal iterative deepening if we don't have a TT move
1257 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1258 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1260 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1261 ttMove = ss[ply].pv[ply];
1264 // Initialize a MovePicker object for the current position, and prepare
1265 // to search all moves:
1266 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1268 Move move, movesSearched[256];
1270 Value value, bestValue = -VALUE_INFINITE;
1271 Bitboard dcCandidates = mp.discovered_check_candidates();
1272 Value futilityValue = VALUE_NONE;
1273 bool useFutilityPruning = UseFutilityPruning
1274 && depth < SelectiveDepth
1277 // Loop through all legal moves until no moves remain or a beta cutoff
1279 while ( bestValue < beta
1280 && (move = mp.get_next_move()) != MOVE_NONE
1281 && !thread_should_stop(threadID))
1283 assert(move_is_ok(move));
1285 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1286 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1287 bool moveIsCapture = pos.move_is_capture(move);
1289 movesSearched[moveCount++] = ss[ply].currentMove = move;
1291 // Decide the new search depth
1293 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1294 Depth newDepth = depth - OnePly + ext;
1297 if ( useFutilityPruning
1300 && !move_promotion(move))
1302 // History pruning. See ok_to_prune() definition
1303 if ( moveCount >= 2 + int(depth)
1304 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1307 // Value based pruning
1308 if (depth < 7 * OnePly && approximateEval < beta)
1310 if (futilityValue == VALUE_NONE)
1311 futilityValue = evaluate(pos, ei, threadID)
1312 + FutilityMargins[int(depth)/2 - 1]
1315 if (futilityValue < beta)
1317 if (futilityValue > bestValue)
1318 bestValue = futilityValue;
1324 // Make and search the move
1326 pos.do_move(move, st, dcCandidates);
1328 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1329 // if the move fails high will be re-searched at full depth.
1330 if ( depth >= 2*OnePly
1331 && moveCount >= LMRNonPVMoves
1334 && !move_promotion(move)
1335 && !move_is_castle(move)
1336 && !move_is_killer(move, ss[ply]))
1338 // LMR dynamic reduction
1339 Depth R = UseDynamicLMR
1340 && moveCount >= 2 * LMRNonPVMoves
1341 && depth > 7*OnePly ? 2*OnePly : OnePly;
1343 ss[ply].reduction = R;
1344 value = -search(pos, ss, -(beta-1), newDepth-R, ply+1, true, threadID);
1347 value = beta; // Just to trigger next condition
1349 if (value >= beta) // Go with full depth non-pv search
1351 ss[ply].reduction = Depth(0);
1352 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1354 pos.undo_move(move);
1356 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1359 if (value > bestValue)
1365 if (value == value_mate_in(ply + 1))
1366 ss[ply].mateKiller = move;
1370 if ( ActiveThreads > 1
1372 && depth >= MinimumSplitDepth
1374 && idle_thread_exists(threadID)
1376 && !thread_should_stop(threadID)
1377 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1378 &mp, dcCandidates, threadID, false))
1382 // All legal moves have been searched. A special case: If there were
1383 // no legal moves, it must be mate or stalemate.
1385 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1387 // If the search is not aborted, update the transposition table,
1388 // history counters, and killer moves.
1389 if (AbortSearch || thread_should_stop(threadID))
1392 if (bestValue < beta)
1393 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1396 BetaCounter.add(pos.side_to_move(), depth, threadID);
1397 Move m = ss[ply].pv[ply];
1398 if (ok_to_history(pos, m)) // Only non capture moves are considered
1400 update_history(pos, m, depth, movesSearched, moveCount);
1401 update_killers(m, ss[ply]);
1403 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1406 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1412 // qsearch() is the quiescence search function, which is called by the main
1413 // search function when the remaining depth is zero (or, to be more precise,
1414 // less than OnePly).
1416 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1417 Depth depth, int ply, int threadID) {
1419 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1420 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1422 assert(ply >= 0 && ply < PLY_MAX);
1423 assert(threadID >= 0 && threadID < ActiveThreads);
1425 // Initialize, and make an early exit in case of an aborted search,
1426 // an instant draw, maximum ply reached, etc.
1427 init_node(pos, ss, ply, threadID);
1429 // After init_node() that calls poll()
1430 if (AbortSearch || thread_should_stop(threadID))
1436 // Transposition table lookup, only when not in PV
1437 TTEntry* tte = NULL;
1438 bool pvNode = (beta - alpha != 1);
1441 tte = TT.retrieve(pos);
1442 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1444 assert(tte->type() != VALUE_TYPE_EVAL);
1446 return value_from_tt(tte->value(), ply);
1450 // Evaluate the position statically
1453 bool isCheck = pos.is_check();
1456 staticValue = -VALUE_INFINITE;
1458 else if (tte && (tte->type() == VALUE_TYPE_EVAL || tte->staticValue()))
1460 // Use the cached evaluation score if possible
1461 assert(tte->value() == evaluate(pos, ei, threadID));
1462 assert(ei.futilityMargin == Value(0));
1464 staticValue = tte->value();
1465 ei.futilityMargin = Value(0); // manually initialize futilityMargin
1468 staticValue = evaluate(pos, ei, threadID);
1470 if (ply == PLY_MAX - 1)
1471 return evaluate(pos, ei, threadID);
1473 // Initialize "stand pat score", and return it immediately if it is
1475 Value bestValue = staticValue;
1477 if (bestValue >= beta)
1479 // Store the score to avoid a future costly evaluation() call
1480 if (!isCheck && !tte && ei.futilityMargin == 0)
1481 TT.store(pos, value_to_tt(bestValue, ply), Depth(-127*OnePly), MOVE_NONE, VALUE_TYPE_EVAL);
1486 if (bestValue > alpha)
1489 // Initialize a MovePicker object for the current position, and prepare
1490 // to search the moves. Because the depth is <= 0 here, only captures,
1491 // queen promotions and checks (only if depth == 0) will be generated.
1492 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth);
1495 Bitboard dcCandidates = mp.discovered_check_candidates();
1496 Color us = pos.side_to_move();
1497 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1499 // Loop through the moves until no moves remain or a beta cutoff
1501 while ( alpha < beta
1502 && (move = mp.get_next_move()) != MOVE_NONE)
1504 assert(move_is_ok(move));
1507 ss[ply].currentMove = move;
1510 if ( UseQSearchFutilityPruning
1514 && !move_promotion(move)
1515 && !pos.move_is_check(move, dcCandidates)
1516 && !pos.move_is_passed_pawn_push(move))
1518 Value futilityValue = staticValue
1519 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1520 pos.endgame_value_of_piece_on(move_to(move)))
1521 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1523 + ei.futilityMargin;
1525 if (futilityValue < alpha)
1527 if (futilityValue > bestValue)
1528 bestValue = futilityValue;
1533 // Don't search captures and checks with negative SEE values
1535 && !move_promotion(move)
1536 && (pos.midgame_value_of_piece_on(move_from(move)) >
1537 pos.midgame_value_of_piece_on(move_to(move)))
1538 && pos.see(move) < 0)
1541 // Make and search the move.
1543 pos.do_move(move, st, dcCandidates);
1544 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1545 pos.undo_move(move);
1547 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1550 if (value > bestValue)
1561 // All legal moves have been searched. A special case: If we're in check
1562 // and no legal moves were found, it is checkmate:
1563 if (pos.is_check() && moveCount == 0) // Mate!
1564 return value_mated_in(ply);
1566 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1568 // Update transposition table
1571 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1572 Value v = value_to_tt(bestValue, ply);
1574 if (bestValue < beta)
1575 e = TT.store(pos, v, d, MOVE_NONE, VALUE_TYPE_UPPER);
1577 e = TT.store(pos, v, d, MOVE_NONE, VALUE_TYPE_LOWER);
1579 assert(e && e == TT.retrieve(pos));
1580 assert(!e->staticValue());
1582 // If the just stored value happens to be equal to the static evaluation
1583 // score then set the flag, so to avoid calling evaluation() next time we
1584 // hit this position.
1585 if (staticValue == v && !ei.futilityMargin)
1586 e->setStaticValue();
1589 // Update killers only for good check moves
1590 Move m = ss[ply].currentMove;
1591 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1593 // Wrong to update history when depth is <= 0
1594 update_killers(m, ss[ply]);
1600 // sp_search() is used to search from a split point. This function is called
1601 // by each thread working at the split point. It is similar to the normal
1602 // search() function, but simpler. Because we have already probed the hash
1603 // table, done a null move search, and searched the first move before
1604 // splitting, we don't have to repeat all this work in sp_search(). We
1605 // also don't need to store anything to the hash table here: This is taken
1606 // care of after we return from the split point.
1608 void sp_search(SplitPoint *sp, int threadID) {
1610 assert(threadID >= 0 && threadID < ActiveThreads);
1611 assert(ActiveThreads > 1);
1613 Position pos = Position(sp->pos);
1614 SearchStack *ss = sp->sstack[threadID];
1617 bool isCheck = pos.is_check();
1618 bool useFutilityPruning = UseFutilityPruning
1619 && sp->depth < SelectiveDepth
1622 while ( sp->bestValue < sp->beta
1623 && !thread_should_stop(threadID)
1624 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1626 assert(move_is_ok(move));
1628 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1629 bool moveIsCapture = pos.move_is_capture(move);
1631 lock_grab(&(sp->lock));
1632 int moveCount = ++sp->moves;
1633 lock_release(&(sp->lock));
1635 ss[sp->ply].currentMove = move;
1637 // Decide the new search depth.
1639 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1640 Depth newDepth = sp->depth - OnePly + ext;
1643 if ( useFutilityPruning
1646 && !move_promotion(move)
1647 && moveCount >= 2 + int(sp->depth)
1648 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1651 // Make and search the move.
1653 pos.do_move(move, st, sp->dcCandidates);
1655 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1656 // if the move fails high will be re-searched at full depth.
1658 && moveCount >= LMRNonPVMoves
1660 && !move_promotion(move)
1661 && !move_is_castle(move)
1662 && !move_is_killer(move, ss[sp->ply]))
1664 ss[sp->ply].reduction = OnePly;
1665 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1668 value = sp->beta; // Just to trigger next condition
1670 if (value >= sp->beta) // Go with full depth non-pv search
1672 ss[sp->ply].reduction = Depth(0);
1673 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1675 pos.undo_move(move);
1677 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1679 if (thread_should_stop(threadID))
1683 lock_grab(&(sp->lock));
1684 if (value > sp->bestValue && !thread_should_stop(threadID))
1686 sp->bestValue = value;
1687 if (sp->bestValue >= sp->beta)
1689 sp_update_pv(sp->parentSstack, ss, sp->ply);
1690 for (int i = 0; i < ActiveThreads; i++)
1691 if (i != threadID && (i == sp->master || sp->slaves[i]))
1692 Threads[i].stop = true;
1694 sp->finished = true;
1697 lock_release(&(sp->lock));
1700 lock_grab(&(sp->lock));
1702 // If this is the master thread and we have been asked to stop because of
1703 // a beta cutoff higher up in the tree, stop all slave threads:
1704 if (sp->master == threadID && thread_should_stop(threadID))
1705 for (int i = 0; i < ActiveThreads; i++)
1707 Threads[i].stop = true;
1710 sp->slaves[threadID] = 0;
1712 lock_release(&(sp->lock));
1716 // sp_search_pv() is used to search from a PV split point. This function
1717 // is called by each thread working at the split point. It is similar to
1718 // the normal search_pv() function, but simpler. Because we have already
1719 // probed the hash table and searched the first move before splitting, we
1720 // don't have to repeat all this work in sp_search_pv(). We also don't
1721 // need to store anything to the hash table here: This is taken care of
1722 // after we return from the split point.
1724 void sp_search_pv(SplitPoint *sp, int threadID) {
1726 assert(threadID >= 0 && threadID < ActiveThreads);
1727 assert(ActiveThreads > 1);
1729 Position pos = Position(sp->pos);
1730 SearchStack *ss = sp->sstack[threadID];
1734 while ( sp->alpha < sp->beta
1735 && !thread_should_stop(threadID)
1736 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1738 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1739 bool moveIsCapture = pos.move_is_capture(move);
1741 assert(move_is_ok(move));
1744 ss[sp->ply].currentMoveCaptureValue =
1745 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1747 ss[sp->ply].currentMoveCaptureValue = Value(0);
1749 lock_grab(&(sp->lock));
1750 int moveCount = ++sp->moves;
1751 lock_release(&(sp->lock));
1753 ss[sp->ply].currentMove = move;
1755 // Decide the new search depth.
1757 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1758 Depth newDepth = sp->depth - OnePly + ext;
1760 // Make and search the move.
1762 pos.do_move(move, st, sp->dcCandidates);
1764 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1765 // if the move fails high will be re-searched at full depth.
1767 && moveCount >= LMRPVMoves
1769 && !move_promotion(move)
1770 && !move_is_castle(move)
1771 && !move_is_killer(move, ss[sp->ply]))
1773 ss[sp->ply].reduction = OnePly;
1774 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1777 value = sp->alpha + 1; // Just to trigger next condition
1779 if (value > sp->alpha) // Go with full depth non-pv search
1781 ss[sp->ply].reduction = Depth(0);
1782 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1784 if (value > sp->alpha && value < sp->beta)
1786 // When the search fails high at ply 1 while searching the first
1787 // move at the root, set the flag failHighPly1. This is used for
1788 // time managment: We don't want to stop the search early in
1789 // such cases, because resolving the fail high at ply 1 could
1790 // result in a big drop in score at the root.
1791 if (sp->ply == 1 && RootMoveNumber == 1)
1792 Threads[threadID].failHighPly1 = true;
1794 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1795 Threads[threadID].failHighPly1 = false;
1798 pos.undo_move(move);
1800 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1802 if (thread_should_stop(threadID))
1806 lock_grab(&(sp->lock));
1807 if (value > sp->bestValue && !thread_should_stop(threadID))
1809 sp->bestValue = value;
1810 if (value > sp->alpha)
1813 sp_update_pv(sp->parentSstack, ss, sp->ply);
1814 if (value == value_mate_in(sp->ply + 1))
1815 ss[sp->ply].mateKiller = move;
1817 if(value >= sp->beta)
1819 for(int i = 0; i < ActiveThreads; i++)
1820 if(i != threadID && (i == sp->master || sp->slaves[i]))
1821 Threads[i].stop = true;
1823 sp->finished = true;
1826 // If we are at ply 1, and we are searching the first root move at
1827 // ply 0, set the 'Problem' variable if the score has dropped a lot
1828 // (from the computer's point of view) since the previous iteration.
1831 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1834 lock_release(&(sp->lock));
1837 lock_grab(&(sp->lock));
1839 // If this is the master thread and we have been asked to stop because of
1840 // a beta cutoff higher up in the tree, stop all slave threads.
1841 if (sp->master == threadID && thread_should_stop(threadID))
1842 for (int i = 0; i < ActiveThreads; i++)
1844 Threads[i].stop = true;
1847 sp->slaves[threadID] = 0;
1849 lock_release(&(sp->lock));
1852 /// The BetaCounterType class
1854 BetaCounterType::BetaCounterType() { clear(); }
1856 void BetaCounterType::clear() {
1858 for (int i = 0; i < THREAD_MAX; i++)
1859 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1862 void BetaCounterType::add(Color us, Depth d, int threadID) {
1864 // Weighted count based on depth
1865 hits[threadID][us] += int(d);
1868 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1871 for (int i = 0; i < THREAD_MAX; i++)
1874 their += hits[i][opposite_color(us)];
1879 /// The RootMove class
1883 RootMove::RootMove() {
1884 nodes = cumulativeNodes = 0ULL;
1887 // RootMove::operator<() is the comparison function used when
1888 // sorting the moves. A move m1 is considered to be better
1889 // than a move m2 if it has a higher score, or if the moves
1890 // have equal score but m1 has the higher node count.
1892 bool RootMove::operator<(const RootMove& m) {
1894 if (score != m.score)
1895 return (score < m.score);
1897 return theirBeta <= m.theirBeta;
1900 /// The RootMoveList class
1904 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1906 MoveStack mlist[MaxRootMoves];
1907 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1909 // Generate all legal moves
1910 int lm_count = generate_legal_moves(pos, mlist);
1912 // Add each move to the moves[] array
1913 for (int i = 0; i < lm_count; i++)
1915 bool includeMove = includeAllMoves;
1917 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1918 includeMove = (searchMoves[k] == mlist[i].move);
1922 // Find a quick score for the move
1924 SearchStack ss[PLY_MAX_PLUS_2];
1926 moves[count].move = mlist[i].move;
1927 moves[count].nodes = 0ULL;
1928 pos.do_move(moves[count].move, st);
1929 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1931 pos.undo_move(moves[count].move);
1932 moves[count].pv[0] = moves[i].move;
1933 moves[count].pv[1] = MOVE_NONE; // FIXME
1941 // Simple accessor methods for the RootMoveList class
1943 inline Move RootMoveList::get_move(int moveNum) const {
1944 return moves[moveNum].move;
1947 inline Value RootMoveList::get_move_score(int moveNum) const {
1948 return moves[moveNum].score;
1951 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1952 moves[moveNum].score = score;
1955 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1956 moves[moveNum].nodes = nodes;
1957 moves[moveNum].cumulativeNodes += nodes;
1960 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1961 moves[moveNum].ourBeta = our;
1962 moves[moveNum].theirBeta = their;
1965 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1967 for(j = 0; pv[j] != MOVE_NONE; j++)
1968 moves[moveNum].pv[j] = pv[j];
1969 moves[moveNum].pv[j] = MOVE_NONE;
1972 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1973 return moves[moveNum].pv[i];
1976 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1977 return moves[moveNum].cumulativeNodes;
1980 inline int RootMoveList::move_count() const {
1985 // RootMoveList::scan_for_easy_move() is called at the end of the first
1986 // iteration, and is used to detect an "easy move", i.e. a move which appears
1987 // to be much bester than all the rest. If an easy move is found, the move
1988 // is returned, otherwise the function returns MOVE_NONE. It is very
1989 // important that this function is called at the right moment: The code
1990 // assumes that the first iteration has been completed and the moves have
1991 // been sorted. This is done in RootMoveList c'tor.
1993 Move RootMoveList::scan_for_easy_move() const {
2000 // moves are sorted so just consider the best and the second one
2001 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2007 // RootMoveList::sort() sorts the root move list at the beginning of a new
2010 inline void RootMoveList::sort() {
2012 sort_multipv(count - 1); // all items
2016 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2017 // list by their scores and depths. It is used to order the different PVs
2018 // correctly in MultiPV mode.
2020 void RootMoveList::sort_multipv(int n) {
2022 for (int i = 1; i <= n; i++)
2024 RootMove rm = moves[i];
2026 for (j = i; j > 0 && moves[j-1] < rm; j--)
2027 moves[j] = moves[j-1];
2033 // init_node() is called at the beginning of all the search functions
2034 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2035 // stack object corresponding to the current node. Once every
2036 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2037 // for user input and checks whether it is time to stop the search.
2039 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2040 assert(ply >= 0 && ply < PLY_MAX);
2041 assert(threadID >= 0 && threadID < ActiveThreads);
2043 Threads[threadID].nodes++;
2047 if(NodesSincePoll >= NodesBetweenPolls) {
2054 ss[ply+2].initKillers();
2056 if(Threads[threadID].printCurrentLine)
2057 print_current_line(ss, ply, threadID);
2061 // update_pv() is called whenever a search returns a value > alpha. It
2062 // updates the PV in the SearchStack object corresponding to the current
2065 void update_pv(SearchStack ss[], int ply) {
2066 assert(ply >= 0 && ply < PLY_MAX);
2068 ss[ply].pv[ply] = ss[ply].currentMove;
2070 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2071 ss[ply].pv[p] = ss[ply+1].pv[p];
2072 ss[ply].pv[p] = MOVE_NONE;
2076 // sp_update_pv() is a variant of update_pv for use at split points. The
2077 // difference between the two functions is that sp_update_pv also updates
2078 // the PV at the parent node.
2080 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2081 assert(ply >= 0 && ply < PLY_MAX);
2083 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2085 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2086 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2087 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2091 // connected_moves() tests whether two moves are 'connected' in the sense
2092 // that the first move somehow made the second move possible (for instance
2093 // if the moving piece is the same in both moves). The first move is
2094 // assumed to be the move that was made to reach the current position, while
2095 // the second move is assumed to be a move from the current position.
2097 bool connected_moves(const Position &pos, Move m1, Move m2) {
2098 Square f1, t1, f2, t2;
2100 assert(move_is_ok(m1));
2101 assert(move_is_ok(m2));
2106 // Case 1: The moving piece is the same in both moves.
2112 // Case 2: The destination square for m2 was vacated by m1.
2118 // Case 3: Moving through the vacated square:
2119 if(piece_is_slider(pos.piece_on(f2)) &&
2120 bit_is_set(squares_between(f2, t2), f1))
2123 // Case 4: The destination square for m2 is attacked by the moving piece
2125 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2128 // Case 5: Discovered check, checking piece is the piece moved in m1:
2129 if(piece_is_slider(pos.piece_on(t1)) &&
2130 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2132 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2134 Bitboard occ = pos.occupied_squares();
2135 Color us = pos.side_to_move();
2136 Square ksq = pos.king_square(us);
2137 clear_bit(&occ, f2);
2138 if(pos.type_of_piece_on(t1) == BISHOP) {
2139 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2142 else if(pos.type_of_piece_on(t1) == ROOK) {
2143 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2147 assert(pos.type_of_piece_on(t1) == QUEEN);
2148 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2157 // value_is_mate() checks if the given value is a mate one
2158 // eventually compensated for the ply.
2160 bool value_is_mate(Value value) {
2162 assert(abs(value) <= VALUE_INFINITE);
2164 return value <= value_mated_in(PLY_MAX)
2165 || value >= value_mate_in(PLY_MAX);
2169 // move_is_killer() checks if the given move is among the
2170 // killer moves of that ply.
2172 bool move_is_killer(Move m, const SearchStack& ss) {
2174 const Move* k = ss.killers;
2175 for (int i = 0; i < KILLER_MAX; i++, k++)
2183 // extension() decides whether a move should be searched with normal depth,
2184 // or with extended depth. Certain classes of moves (checking moves, in
2185 // particular) are searched with bigger depth than ordinary moves and in
2186 // any case are marked as 'dangerous'. Note that also if a move is not
2187 // extended, as example because the corresponding UCI option is set to zero,
2188 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2190 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2191 bool singleReply, bool mateThreat, bool* dangerous) {
2193 assert(m != MOVE_NONE);
2195 Depth result = Depth(0);
2196 *dangerous = check || singleReply || mateThreat;
2199 result += CheckExtension[pvNode];
2202 result += SingleReplyExtension[pvNode];
2205 result += MateThreatExtension[pvNode];
2207 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2209 if (pos.move_is_pawn_push_to_7th(m))
2211 result += PawnPushTo7thExtension[pvNode];
2214 if (pos.move_is_passed_pawn_push(m))
2216 result += PassedPawnExtension[pvNode];
2222 && pos.type_of_piece_on(move_to(m)) != PAWN
2223 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2224 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2225 && !move_promotion(m)
2228 result += PawnEndgameExtension[pvNode];
2234 && pos.type_of_piece_on(move_to(m)) != PAWN
2241 return Min(result, OnePly);
2245 // ok_to_do_nullmove() looks at the current position and decides whether
2246 // doing a 'null move' should be allowed. In order to avoid zugzwang
2247 // problems, null moves are not allowed when the side to move has very
2248 // little material left. Currently, the test is a bit too simple: Null
2249 // moves are avoided only when the side to move has only pawns left. It's
2250 // probably a good idea to avoid null moves in at least some more
2251 // complicated endgames, e.g. KQ vs KR. FIXME
2253 bool ok_to_do_nullmove(const Position &pos) {
2254 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2260 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2261 // non-tactical moves late in the move list close to the leaves are
2262 // candidates for pruning.
2264 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2265 Square mfrom, mto, tfrom, tto;
2267 assert(move_is_ok(m));
2268 assert(threat == MOVE_NONE || move_is_ok(threat));
2269 assert(!move_promotion(m));
2270 assert(!pos.move_is_check(m));
2271 assert(!pos.move_is_capture(m));
2272 assert(!pos.move_is_passed_pawn_push(m));
2273 assert(d >= OnePly);
2275 mfrom = move_from(m);
2277 tfrom = move_from(threat);
2278 tto = move_to(threat);
2280 // Case 1: Castling moves are never pruned.
2281 if (move_is_castle(m))
2284 // Case 2: Don't prune moves which move the threatened piece
2285 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2288 // Case 3: If the threatened piece has value less than or equal to the
2289 // value of the threatening piece, don't prune move which defend it.
2290 if ( !PruneDefendingMoves
2291 && threat != MOVE_NONE
2292 && pos.move_is_capture(threat)
2293 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2294 || pos.type_of_piece_on(tfrom) == KING)
2295 && pos.move_attacks_square(m, tto))
2298 // Case 4: Don't prune moves with good history.
2299 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2302 // Case 5: If the moving piece in the threatened move is a slider, don't
2303 // prune safe moves which block its ray.
2304 if ( !PruneBlockingMoves
2305 && threat != MOVE_NONE
2306 && piece_is_slider(pos.piece_on(tfrom))
2307 && bit_is_set(squares_between(tfrom, tto), mto)
2315 // ok_to_use_TT() returns true if a transposition table score
2316 // can be used at a given point in search.
2318 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2320 Value v = value_from_tt(tte->value(), ply);
2322 return ( tte->depth() >= depth
2323 || v >= Max(value_mate_in(100), beta)
2324 || v < Min(value_mated_in(100), beta))
2326 && ( (is_lower_bound(tte->type()) && v >= beta)
2327 || (is_upper_bound(tte->type()) && v < beta));
2331 // ok_to_history() returns true if a move m can be stored
2332 // in history. Should be a non capturing move nor a promotion.
2334 bool ok_to_history(const Position& pos, Move m) {
2336 return !pos.move_is_capture(m) && !move_promotion(m);
2340 // update_history() registers a good move that produced a beta-cutoff
2341 // in history and marks as failures all the other moves of that ply.
2343 void update_history(const Position& pos, Move m, Depth depth,
2344 Move movesSearched[], int moveCount) {
2346 H.success(pos.piece_on(move_from(m)), m, depth);
2348 for (int i = 0; i < moveCount - 1; i++)
2350 assert(m != movesSearched[i]);
2351 if (ok_to_history(pos, movesSearched[i]))
2352 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2357 // update_killers() add a good move that produced a beta-cutoff
2358 // among the killer moves of that ply.
2360 void update_killers(Move m, SearchStack& ss) {
2362 if (m == ss.killers[0])
2365 for (int i = KILLER_MAX - 1; i > 0; i--)
2366 ss.killers[i] = ss.killers[i - 1];
2371 // fail_high_ply_1() checks if some thread is currently resolving a fail
2372 // high at ply 1 at the node below the first root node. This information
2373 // is used for time managment.
2375 bool fail_high_ply_1() {
2376 for(int i = 0; i < ActiveThreads; i++)
2377 if(Threads[i].failHighPly1)
2383 // current_search_time() returns the number of milliseconds which have passed
2384 // since the beginning of the current search.
2386 int current_search_time() {
2387 return get_system_time() - SearchStartTime;
2391 // nps() computes the current nodes/second count.
2394 int t = current_search_time();
2395 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2399 // poll() performs two different functions: It polls for user input, and it
2400 // looks at the time consumed so far and decides if it's time to abort the
2405 static int lastInfoTime;
2406 int t = current_search_time();
2411 // We are line oriented, don't read single chars
2412 std::string command;
2413 if (!std::getline(std::cin, command))
2416 if (command == "quit")
2419 PonderSearch = false;
2422 else if(command == "stop")
2425 PonderSearch = false;
2427 else if(command == "ponderhit")
2430 // Print search information
2434 else if (lastInfoTime > t)
2435 // HACK: Must be a new search where we searched less than
2436 // NodesBetweenPolls nodes during the first second of search.
2439 else if (t - lastInfoTime >= 1000)
2446 if (dbg_show_hit_rate)
2447 dbg_print_hit_rate();
2449 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2450 << " time " << t << " hashfull " << TT.full() << std::endl;
2451 lock_release(&IOLock);
2452 if (ShowCurrentLine)
2453 Threads[0].printCurrentLine = true;
2455 // Should we stop the search?
2459 bool overTime = t > AbsoluteMaxSearchTime
2460 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2461 || ( !FailHigh && !fail_high_ply_1() && !Problem
2462 && t > 6*(MaxSearchTime + ExtraSearchTime));
2464 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2465 || (ExactMaxTime && t >= ExactMaxTime)
2466 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2471 // ponderhit() is called when the program is pondering (i.e. thinking while
2472 // it's the opponent's turn to move) in order to let the engine know that
2473 // it correctly predicted the opponent's move.
2476 int t = current_search_time();
2477 PonderSearch = false;
2478 if(Iteration >= 3 &&
2479 (!InfiniteSearch && (StopOnPonderhit ||
2480 t > AbsoluteMaxSearchTime ||
2481 (RootMoveNumber == 1 &&
2482 t > MaxSearchTime + ExtraSearchTime) ||
2483 (!FailHigh && !fail_high_ply_1() && !Problem &&
2484 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2489 // print_current_line() prints the current line of search for a given
2490 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2492 void print_current_line(SearchStack ss[], int ply, int threadID) {
2493 assert(ply >= 0 && ply < PLY_MAX);
2494 assert(threadID >= 0 && threadID < ActiveThreads);
2496 if(!Threads[threadID].idle) {
2498 std::cout << "info currline " << (threadID + 1);
2499 for(int p = 0; p < ply; p++)
2500 std::cout << " " << ss[p].currentMove;
2501 std::cout << std::endl;
2502 lock_release(&IOLock);
2504 Threads[threadID].printCurrentLine = false;
2505 if(threadID + 1 < ActiveThreads)
2506 Threads[threadID + 1].printCurrentLine = true;
2510 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2511 // while the program is pondering. The point is to work around a wrinkle in
2512 // the UCI protocol: When pondering, the engine is not allowed to give a
2513 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2514 // We simply wait here until one of these commands is sent, and return,
2515 // after which the bestmove and pondermove will be printed (in id_loop()).
2517 void wait_for_stop_or_ponderhit() {
2518 std::string command;
2521 if(!std::getline(std::cin, command))
2524 if(command == "quit") {
2525 OpeningBook.close();
2530 else if(command == "ponderhit" || command == "stop")
2536 // idle_loop() is where the threads are parked when they have no work to do.
2537 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2538 // object for which the current thread is the master.
2540 void idle_loop(int threadID, SplitPoint *waitSp) {
2541 assert(threadID >= 0 && threadID < THREAD_MAX);
2543 Threads[threadID].running = true;
2546 if(AllThreadsShouldExit && threadID != 0)
2549 // If we are not thinking, wait for a condition to be signaled instead
2550 // of wasting CPU time polling for work:
2551 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2552 #if !defined(_MSC_VER)
2553 pthread_mutex_lock(&WaitLock);
2554 if(Idle || threadID >= ActiveThreads)
2555 pthread_cond_wait(&WaitCond, &WaitLock);
2556 pthread_mutex_unlock(&WaitLock);
2558 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2562 // If this thread has been assigned work, launch a search:
2563 if(Threads[threadID].workIsWaiting) {
2564 Threads[threadID].workIsWaiting = false;
2565 if(Threads[threadID].splitPoint->pvNode)
2566 sp_search_pv(Threads[threadID].splitPoint, threadID);
2568 sp_search(Threads[threadID].splitPoint, threadID);
2569 Threads[threadID].idle = true;
2572 // If this thread is the master of a split point and all threads have
2573 // finished their work at this split point, return from the idle loop:
2574 if(waitSp != NULL && waitSp->cpus == 0)
2578 Threads[threadID].running = false;
2582 // init_split_point_stack() is called during program initialization, and
2583 // initializes all split point objects.
2585 void init_split_point_stack() {
2586 for(int i = 0; i < THREAD_MAX; i++)
2587 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2588 SplitPointStack[i][j].parent = NULL;
2589 lock_init(&(SplitPointStack[i][j].lock), NULL);
2594 // destroy_split_point_stack() is called when the program exits, and
2595 // destroys all locks in the precomputed split point objects.
2597 void destroy_split_point_stack() {
2598 for(int i = 0; i < THREAD_MAX; i++)
2599 for(int j = 0; j < MaxActiveSplitPoints; j++)
2600 lock_destroy(&(SplitPointStack[i][j].lock));
2604 // thread_should_stop() checks whether the thread with a given threadID has
2605 // been asked to stop, directly or indirectly. This can happen if a beta
2606 // cutoff has occured in thre thread's currently active split point, or in
2607 // some ancestor of the current split point.
2609 bool thread_should_stop(int threadID) {
2610 assert(threadID >= 0 && threadID < ActiveThreads);
2614 if(Threads[threadID].stop)
2616 if(ActiveThreads <= 2)
2618 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2620 Threads[threadID].stop = true;
2627 // thread_is_available() checks whether the thread with threadID "slave" is
2628 // available to help the thread with threadID "master" at a split point. An
2629 // obvious requirement is that "slave" must be idle. With more than two
2630 // threads, this is not by itself sufficient: If "slave" is the master of
2631 // some active split point, it is only available as a slave to the other
2632 // threads which are busy searching the split point at the top of "slave"'s
2633 // split point stack (the "helpful master concept" in YBWC terminology).
2635 bool thread_is_available(int slave, int master) {
2636 assert(slave >= 0 && slave < ActiveThreads);
2637 assert(master >= 0 && master < ActiveThreads);
2638 assert(ActiveThreads > 1);
2640 if(!Threads[slave].idle || slave == master)
2643 if(Threads[slave].activeSplitPoints == 0)
2644 // No active split points means that the thread is available as a slave
2645 // for any other thread.
2648 if(ActiveThreads == 2)
2651 // Apply the "helpful master" concept if possible.
2652 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2659 // idle_thread_exists() tries to find an idle thread which is available as
2660 // a slave for the thread with threadID "master".
2662 bool idle_thread_exists(int master) {
2663 assert(master >= 0 && master < ActiveThreads);
2664 assert(ActiveThreads > 1);
2666 for(int i = 0; i < ActiveThreads; i++)
2667 if(thread_is_available(i, master))
2673 // split() does the actual work of distributing the work at a node between
2674 // several threads at PV nodes. If it does not succeed in splitting the
2675 // node (because no idle threads are available, or because we have no unused
2676 // split point objects), the function immediately returns false. If
2677 // splitting is possible, a SplitPoint object is initialized with all the
2678 // data that must be copied to the helper threads (the current position and
2679 // search stack, alpha, beta, the search depth, etc.), and we tell our
2680 // helper threads that they have been assigned work. This will cause them
2681 // to instantly leave their idle loops and call sp_search_pv(). When all
2682 // threads have returned from sp_search_pv (or, equivalently, when
2683 // splitPoint->cpus becomes 0), split() returns true.
2685 bool split(const Position &p, SearchStack *sstck, int ply,
2686 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2687 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2690 assert(sstck != NULL);
2691 assert(ply >= 0 && ply < PLY_MAX);
2692 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2693 assert(!pvNode || *alpha < *beta);
2694 assert(*beta <= VALUE_INFINITE);
2695 assert(depth > Depth(0));
2696 assert(master >= 0 && master < ActiveThreads);
2697 assert(ActiveThreads > 1);
2699 SplitPoint *splitPoint;
2704 // If no other thread is available to help us, or if we have too many
2705 // active split points, don't split:
2706 if(!idle_thread_exists(master) ||
2707 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2708 lock_release(&MPLock);
2712 // Pick the next available split point object from the split point stack:
2713 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2714 Threads[master].activeSplitPoints++;
2716 // Initialize the split point object:
2717 splitPoint->parent = Threads[master].splitPoint;
2718 splitPoint->finished = false;
2719 splitPoint->ply = ply;
2720 splitPoint->depth = depth;
2721 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2722 splitPoint->beta = *beta;
2723 splitPoint->pvNode = pvNode;
2724 splitPoint->dcCandidates = dcCandidates;
2725 splitPoint->bestValue = *bestValue;
2726 splitPoint->master = master;
2727 splitPoint->mp = mp;
2728 splitPoint->moves = *moves;
2729 splitPoint->cpus = 1;
2730 splitPoint->pos.copy(p);
2731 splitPoint->parentSstack = sstck;
2732 for(i = 0; i < ActiveThreads; i++)
2733 splitPoint->slaves[i] = 0;
2735 // Copy the current position and the search stack to the master thread:
2736 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2737 Threads[master].splitPoint = splitPoint;
2739 // Make copies of the current position and search stack for each thread:
2740 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2742 if(thread_is_available(i, master)) {
2743 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2744 Threads[i].splitPoint = splitPoint;
2745 splitPoint->slaves[i] = 1;
2749 // Tell the threads that they have work to do. This will make them leave
2751 for(i = 0; i < ActiveThreads; i++)
2752 if(i == master || splitPoint->slaves[i]) {
2753 Threads[i].workIsWaiting = true;
2754 Threads[i].idle = false;
2755 Threads[i].stop = false;
2758 lock_release(&MPLock);
2760 // Everything is set up. The master thread enters the idle loop, from
2761 // which it will instantly launch a search, because its workIsWaiting
2762 // slot is 'true'. We send the split point as a second parameter to the
2763 // idle loop, which means that the main thread will return from the idle
2764 // loop when all threads have finished their work at this split point
2765 // (i.e. when // splitPoint->cpus == 0).
2766 idle_loop(master, splitPoint);
2768 // We have returned from the idle loop, which means that all threads are
2769 // finished. Update alpha, beta and bestvalue, and return:
2771 if(pvNode) *alpha = splitPoint->alpha;
2772 *beta = splitPoint->beta;
2773 *bestValue = splitPoint->bestValue;
2774 Threads[master].stop = false;
2775 Threads[master].idle = false;
2776 Threads[master].activeSplitPoints--;
2777 Threads[master].splitPoint = splitPoint->parent;
2778 lock_release(&MPLock);
2784 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2785 // to start a new search from the root.
2787 void wake_sleeping_threads() {
2788 if(ActiveThreads > 1) {
2789 for(int i = 1; i < ActiveThreads; i++) {
2790 Threads[i].idle = true;
2791 Threads[i].workIsWaiting = false;
2793 #if !defined(_MSC_VER)
2794 pthread_mutex_lock(&WaitLock);
2795 pthread_cond_broadcast(&WaitCond);
2796 pthread_mutex_unlock(&WaitLock);
2798 for(int i = 1; i < THREAD_MAX; i++)
2799 SetEvent(SitIdleEvent[i]);
2805 // init_thread() is the function which is called when a new thread is
2806 // launched. It simply calls the idle_loop() function with the supplied
2807 // threadID. There are two versions of this function; one for POSIX threads
2808 // and one for Windows threads.
2810 #if !defined(_MSC_VER)
2812 void *init_thread(void *threadID) {
2813 idle_loop(*(int *)threadID, NULL);
2819 DWORD WINAPI init_thread(LPVOID threadID) {
2820 idle_loop(*(int *)threadID, NULL);