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;
124 // Use internal iterative deepening?
125 const bool UseIIDAtPVNodes = true;
126 const bool UseIIDAtNonPVNodes = false;
128 // Use null move driven internal iterative deepening?
129 bool UseNullDrivenIID = 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
200 BetaCounterType BetaCounter;
202 // Scores and number of times the best move changed for each iteration:
203 Value ValueByIteration[PLY_MAX_PLUS_2];
204 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
209 // Time managment variables
211 int MaxNodes, MaxDepth;
212 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
213 Move BestRootMove, PonderMove, EasyMove;
217 bool StopOnPonderhit;
222 bool PonderingEnabled;
225 // Show current line?
226 bool ShowCurrentLine = false;
229 bool UseLogFile = false;
230 std::ofstream LogFile;
232 // MP related variables
233 Depth MinimumSplitDepth = 4*OnePly;
234 int MaxThreadsPerSplitPoint = 4;
235 Thread Threads[THREAD_MAX];
237 bool AllThreadsShouldExit = false;
238 const int MaxActiveSplitPoints = 8;
239 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
242 #if !defined(_MSC_VER)
243 pthread_cond_t WaitCond;
244 pthread_mutex_t WaitLock;
246 HANDLE SitIdleEvent[THREAD_MAX];
252 Value id_loop(const Position &pos, Move searchMoves[]);
253 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
254 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
255 Depth depth, int ply, int threadID);
256 Value search(Position &pos, SearchStack ss[], Value beta,
257 Depth depth, int ply, bool allowNullmove, int threadID);
258 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
259 Depth depth, int ply, int threadID);
260 void sp_search(SplitPoint *sp, int threadID);
261 void sp_search_pv(SplitPoint *sp, int threadID);
262 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
263 void update_pv(SearchStack ss[], int ply);
264 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
265 bool connected_moves(const Position &pos, Move m1, Move m2);
266 bool value_is_mate(Value value);
267 bool move_is_killer(Move m, const SearchStack& ss);
268 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
269 bool ok_to_do_nullmove(const Position &pos);
270 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
271 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
272 bool ok_to_history(const Position &pos, Move m);
273 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
274 void update_killers(Move m, SearchStack& ss);
276 bool fail_high_ply_1();
277 int current_search_time();
281 void print_current_line(SearchStack ss[], int ply, int threadID);
282 void wait_for_stop_or_ponderhit();
284 void idle_loop(int threadID, SplitPoint *waitSp);
285 void init_split_point_stack();
286 void destroy_split_point_stack();
287 bool thread_should_stop(int threadID);
288 bool thread_is_available(int slave, int master);
289 bool idle_thread_exists(int master);
290 bool split(const Position &pos, SearchStack *ss, int ply,
291 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
292 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
293 void wake_sleeping_threads();
295 #if !defined(_MSC_VER)
296 void *init_thread(void *threadID);
298 DWORD WINAPI init_thread(LPVOID threadID);
305 //// Global variables
308 // The main transposition table
309 TranspositionTable TT = TranspositionTable(TTDefaultSize);
312 // Number of active threads:
313 int ActiveThreads = 1;
315 // Locks. In principle, there is no need for IOLock to be a global variable,
316 // but it could turn out to be useful for debugging.
319 History H; // Should be made local?
321 // The empty search stack
322 SearchStack EmptySearchStack;
325 // SearchStack::init() initializes a search stack. Used at the beginning of a
326 // new search from the root.
327 void SearchStack::init(int ply) {
329 pv[ply] = pv[ply + 1] = MOVE_NONE;
330 currentMove = threatMove = MOVE_NONE;
331 reduction = Depth(0);
332 currentMoveCaptureValue = Value(0);
335 void SearchStack::initKillers() {
337 mateKiller = MOVE_NONE;
338 for (int i = 0; i < KILLER_MAX; i++)
339 killers[i] = MOVE_NONE;
347 /// think() is the external interface to Stockfish's search, and is called when
348 /// the program receives the UCI 'go' command. It initializes various
349 /// search-related global variables, and calls root_search()
351 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
352 int time[], int increment[], int movesToGo, int maxDepth,
353 int maxNodes, int maxTime, Move searchMoves[]) {
355 // Look for a book move
356 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
359 if (get_option_value_string("Book File") != OpeningBook.file_name())
362 OpeningBook.open("book.bin");
364 bookMove = OpeningBook.get_move(pos);
365 if (bookMove != MOVE_NONE)
367 std::cout << "bestmove " << bookMove << std::endl;
372 // Initialize global search variables
374 SearchStartTime = get_system_time();
375 BestRootMove = MOVE_NONE;
376 PonderMove = MOVE_NONE;
377 EasyMove = MOVE_NONE;
378 for (int i = 0; i < THREAD_MAX; i++)
380 Threads[i].nodes = 0ULL;
381 Threads[i].failHighPly1 = false;
384 InfiniteSearch = infinite;
385 PonderSearch = ponder;
386 StopOnPonderhit = false;
391 ExactMaxTime = maxTime;
393 // Read UCI option values
394 TT.set_size(get_option_value_int("Hash"));
395 if (button_was_pressed("Clear Hash"))
398 PonderingEnabled = get_option_value_bool("Ponder");
399 MultiPV = get_option_value_int("MultiPV");
401 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
402 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
404 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
405 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
407 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
408 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
410 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
411 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
413 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
414 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
416 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
417 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
419 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
420 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
421 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
422 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
424 Chess960 = get_option_value_bool("UCI_Chess960");
425 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
426 UseLogFile = get_option_value_bool("Use Search Log");
428 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
430 UseNullDrivenIID = get_option_value_bool("Null driven IID");
431 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
432 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
434 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
435 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
436 for (int i = 0; i < 6; i++)
437 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
439 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
440 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
442 UseLSNFiltering = get_option_value_bool("LSN filtering");
443 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
444 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
446 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
447 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
449 read_weights(pos.side_to_move());
451 int newActiveThreads = get_option_value_int("Threads");
452 if (newActiveThreads != ActiveThreads)
454 ActiveThreads = newActiveThreads;
455 init_eval(ActiveThreads);
458 // Wake up sleeping threads:
459 wake_sleeping_threads();
461 for (int i = 1; i < ActiveThreads; i++)
462 assert(thread_is_available(i, 0));
464 // Set thinking time:
465 int myTime = time[side_to_move];
466 int myIncrement = increment[side_to_move];
468 if (!movesToGo) // Sudden death time control
472 MaxSearchTime = myTime / 30 + myIncrement;
473 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
474 } else { // Blitz game without increment
475 MaxSearchTime = myTime / 30;
476 AbsoluteMaxSearchTime = myTime / 8;
479 else // (x moves) / (y minutes)
483 MaxSearchTime = myTime / 2;
484 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
486 MaxSearchTime = myTime / Min(movesToGo, 20);
487 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
491 if (PonderingEnabled)
493 MaxSearchTime += MaxSearchTime / 4;
494 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
497 // Fixed depth or fixed number of nodes?
500 InfiniteSearch = true; // HACK
505 NodesBetweenPolls = Min(MaxNodes, 30000);
506 InfiniteSearch = true; // HACK
509 NodesBetweenPolls = 30000;
512 // Write information to search log file:
514 LogFile << "Searching: " << pos.to_fen() << std::endl
515 << "infinite: " << infinite
516 << " ponder: " << ponder
517 << " time: " << myTime
518 << " increment: " << myIncrement
519 << " moves to go: " << movesToGo << std::endl;
522 // We're ready to start thinking. Call the iterative deepening loop
526 Value v = id_loop(pos, searchMoves);
527 looseOnTime = ( UseLSNFiltering
534 looseOnTime = false; // reset for next match
535 while (SearchStartTime + myTime + 1000 > get_system_time())
537 id_loop(pos, searchMoves); // to fail gracefully
554 /// init_threads() is called during startup. It launches all helper threads,
555 /// and initializes the split point stack and the global locks and condition
558 void init_threads() {
562 #if !defined(_MSC_VER)
563 pthread_t pthread[1];
566 for (i = 0; i < THREAD_MAX; i++)
567 Threads[i].activeSplitPoints = 0;
569 // Initialize global locks:
570 lock_init(&MPLock, NULL);
571 lock_init(&IOLock, NULL);
573 init_split_point_stack();
575 #if !defined(_MSC_VER)
576 pthread_mutex_init(&WaitLock, NULL);
577 pthread_cond_init(&WaitCond, NULL);
579 for (i = 0; i < THREAD_MAX; i++)
580 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
583 // All threads except the main thread should be initialized to idle state
584 for (i = 1; i < THREAD_MAX; i++)
586 Threads[i].stop = false;
587 Threads[i].workIsWaiting = false;
588 Threads[i].idle = true;
589 Threads[i].running = false;
592 // Launch the helper threads
593 for(i = 1; i < THREAD_MAX; i++)
595 #if !defined(_MSC_VER)
596 pthread_create(pthread, NULL, init_thread, (void*)(&i));
599 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
602 // Wait until the thread has finished launching:
603 while (!Threads[i].running);
606 // Init also the empty search stack
607 EmptySearchStack.init(0);
608 EmptySearchStack.initKillers();
612 /// stop_threads() is called when the program exits. It makes all the
613 /// helper threads exit cleanly.
615 void stop_threads() {
617 ActiveThreads = THREAD_MAX; // HACK
618 Idle = false; // HACK
619 wake_sleeping_threads();
620 AllThreadsShouldExit = true;
621 for (int i = 1; i < THREAD_MAX; i++)
623 Threads[i].stop = true;
624 while(Threads[i].running);
626 destroy_split_point_stack();
630 /// nodes_searched() returns the total number of nodes searched so far in
631 /// the current search.
633 int64_t nodes_searched() {
635 int64_t result = 0ULL;
636 for (int i = 0; i < ActiveThreads; i++)
637 result += Threads[i].nodes;
644 // id_loop() is the main iterative deepening loop. It calls root_search
645 // repeatedly with increasing depth until the allocated thinking time has
646 // been consumed, the user stops the search, or the maximum search depth is
649 Value id_loop(const Position &pos, Move searchMoves[]) {
652 SearchStack ss[PLY_MAX_PLUS_2];
654 // searchMoves are verified, copied, scored and sorted
655 RootMoveList rml(p, searchMoves);
660 for (int i = 0; i < 3; i++)
665 ValueByIteration[0] = Value(0);
666 ValueByIteration[1] = rml.get_move_score(0);
668 LastIterations = false;
670 EasyMove = rml.scan_for_easy_move();
672 // Iterative deepening loop
673 while (!AbortSearch && Iteration < PLY_MAX)
675 // Initialize iteration
678 BestMoveChangesByIteration[Iteration] = 0;
682 std::cout << "info depth " << Iteration << std::endl;
684 // Search to the current depth
685 ValueByIteration[Iteration] = root_search(p, ss, rml);
687 // Erase the easy move if it differs from the new best move
688 if (ss[0].pv[0] != EasyMove)
689 EasyMove = MOVE_NONE;
696 bool stopSearch = false;
698 // Stop search early if there is only a single legal move:
699 if (Iteration >= 6 && rml.move_count() == 1)
702 // Stop search early when the last two iterations returned a mate score
704 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
705 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
708 // Stop search early if one move seems to be much better than the rest
709 int64_t nodes = nodes_searched();
711 && EasyMove == ss[0].pv[0]
712 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
713 && current_search_time() > MaxSearchTime / 16)
714 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
715 && current_search_time() > MaxSearchTime / 32)))
718 // Add some extra time if the best move has changed during the last two iterations
719 if (Iteration > 5 && Iteration <= 50)
720 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
721 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
723 // Try to guess if the current iteration is the last one or the last two
724 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
726 // Stop search if most of MaxSearchTime is consumed at the end of the
727 // iteration. We probably don't have enough time to search the first
728 // move at the next iteration anyway.
729 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
737 StopOnPonderhit = true;
740 // Write PV to transposition table, in case the relevant entries have
741 // been overwritten during the search:
742 TT.insert_pv(p, ss[0].pv);
744 if (MaxDepth && Iteration >= MaxDepth)
750 // If we are pondering, we shouldn't print the best move before we
753 wait_for_stop_or_ponderhit();
755 // Print final search statistics
756 std::cout << "info nodes " << nodes_searched()
758 << " time " << current_search_time()
759 << " hashfull " << TT.full() << std::endl;
761 // Print the best move and the ponder move to the standard output
762 std::cout << "bestmove " << ss[0].pv[0];
763 if (ss[0].pv[1] != MOVE_NONE)
764 std::cout << " ponder " << ss[0].pv[1];
766 std::cout << std::endl;
771 dbg_print_mean(LogFile);
773 if (dbg_show_hit_rate)
774 dbg_print_hit_rate(LogFile);
777 LogFile << "Nodes: " << nodes_searched() << std::endl
778 << "Nodes/second: " << nps() << std::endl
779 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
781 p.do_move(ss[0].pv[0], st);
782 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
783 << std::endl << std::endl;
785 return rml.get_move_score(0);
789 // root_search() is the function which searches the root node. It is
790 // similar to search_pv except that it uses a different move ordering
791 // scheme (perhaps we should try to use this at internal PV nodes, too?)
792 // and prints some information to the standard output.
794 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
796 Value alpha = -VALUE_INFINITE;
797 Value beta = VALUE_INFINITE, value;
798 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
800 // Loop through all the moves in the root move list
801 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
808 RootMoveNumber = i + 1;
811 // Remember the node count before the move is searched. The node counts
812 // are used to sort the root moves at the next iteration.
813 nodes = nodes_searched();
815 // Reset beta cut-off counters
818 // Pick the next root move, and print the move and the move number to
819 // the standard output.
820 move = ss[0].currentMove = rml.get_move(i);
821 if (current_search_time() >= 1000)
822 std::cout << "info currmove " << move
823 << " currmovenumber " << i + 1 << std::endl;
825 // Decide search depth for this move
827 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
828 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
830 // Make the move, and search it
831 pos.do_move(move, st, dcCandidates);
835 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
836 // If the value has dropped a lot compared to the last iteration,
837 // set the boolean variable Problem to true. This variable is used
838 // for time managment: When Problem is true, we try to complete the
839 // current iteration before playing a move.
840 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
842 if (Problem && StopOnPonderhit)
843 StopOnPonderhit = false;
847 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
850 // Fail high! Set the boolean variable FailHigh to true, and
851 // re-search the move with a big window. The variable FailHigh is
852 // used for time managment: We try to avoid aborting the search
853 // prematurely during a fail high research.
855 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
861 // Finished searching the move. If AbortSearch is true, the search
862 // was aborted because the user interrupted the search or because we
863 // ran out of time. In this case, the return value of the search cannot
864 // be trusted, and we break out of the loop without updating the best
869 // Remember the node count for this move. The node counts are used to
870 // sort the root moves at the next iteration.
871 rml.set_move_nodes(i, nodes_searched() - nodes);
873 // Remember the beta-cutoff statistics
875 BetaCounter.read(pos.side_to_move(), our, their);
876 rml.set_beta_counters(i, our, their);
878 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
880 if (value <= alpha && i >= MultiPV)
881 rml.set_move_score(i, -VALUE_INFINITE);
887 rml.set_move_score(i, value);
889 rml.set_move_pv(i, ss[0].pv);
893 // We record how often the best move has been changed in each
894 // iteration. This information is used for time managment: When
895 // the best move changes frequently, we allocate some more time.
897 BestMoveChangesByIteration[Iteration]++;
899 // Print search information to the standard output:
900 std::cout << "info depth " << Iteration
901 << " score " << value_to_string(value)
902 << " time " << current_search_time()
903 << " nodes " << nodes_searched()
907 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
908 std::cout << ss[0].pv[j] << " ";
910 std::cout << std::endl;
913 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
918 // Reset the global variable Problem to false if the value isn't too
919 // far below the final value from the last iteration.
920 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
926 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
929 std::cout << "info multipv " << j + 1
930 << " score " << value_to_string(rml.get_move_score(j))
931 << " depth " << ((j <= i)? Iteration : Iteration - 1)
932 << " time " << current_search_time()
933 << " nodes " << nodes_searched()
937 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
938 std::cout << rml.get_move_pv(j, k) << " ";
940 std::cout << std::endl;
942 alpha = rml.get_move_score(Min(i, MultiPV-1));
950 // search_pv() is the main search function for PV nodes.
952 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
953 Depth depth, int ply, int threadID) {
955 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
956 assert(beta > alpha && beta <= VALUE_INFINITE);
957 assert(ply >= 0 && ply < PLY_MAX);
958 assert(threadID >= 0 && threadID < ActiveThreads);
961 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
963 // Initialize, and make an early exit in case of an aborted search,
964 // an instant draw, maximum ply reached, etc.
965 init_node(pos, ss, ply, threadID);
967 // After init_node() that calls poll()
968 if (AbortSearch || thread_should_stop(threadID))
976 if (ply >= PLY_MAX - 1)
977 return evaluate(pos, ei, threadID);
979 // Mate distance pruning
980 Value oldAlpha = alpha;
981 alpha = Max(value_mated_in(ply), alpha);
982 beta = Min(value_mate_in(ply+1), beta);
986 // Transposition table lookup. At PV nodes, we don't use the TT for
987 // pruning, but only for move ordering.
988 const TTEntry* tte = TT.retrieve(pos);
989 Move ttMove = (tte ? tte->move() : MOVE_NONE);
991 // Go with internal iterative deepening if we don't have a TT move
992 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
994 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
995 ttMove = ss[ply].pv[ply];
998 // Initialize a MovePicker object for the current position, and prepare
999 // to search all moves
1000 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
1002 Move move, movesSearched[256];
1004 Value value, bestValue = -VALUE_INFINITE;
1005 Bitboard dcCandidates = mp.discovered_check_candidates();
1006 Color us = pos.side_to_move();
1007 bool isCheck = pos.is_check();
1008 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1010 // Loop through all legal moves until no moves remain or a beta cutoff
1012 while ( alpha < beta
1013 && (move = mp.get_next_move()) != MOVE_NONE
1014 && !thread_should_stop(threadID))
1016 assert(move_is_ok(move));
1018 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1019 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1020 bool moveIsCapture = pos.move_is_capture(move);
1022 movesSearched[moveCount++] = ss[ply].currentMove = move;
1025 ss[ply].currentMoveCaptureValue =
1026 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1028 ss[ply].currentMoveCaptureValue = Value(0);
1030 // Decide the new search depth
1032 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1033 Depth newDepth = depth - OnePly + ext;
1035 // Make and search the move
1037 pos.do_move(move, st, dcCandidates);
1039 if (moveCount == 1) // The first move in list is the PV
1040 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1043 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1044 // if the move fails high will be re-searched at full depth.
1045 if ( depth >= 2*OnePly
1046 && moveCount >= LMRPVMoves
1049 && !move_promotion(move)
1050 && !move_is_castle(move)
1051 && !move_is_killer(move, ss[ply]))
1053 ss[ply].reduction = OnePly;
1054 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1057 value = alpha + 1; // Just to trigger next condition
1059 if (value > alpha) // Go with full depth non-pv search
1061 ss[ply].reduction = Depth(0);
1062 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1063 if (value > alpha && value < beta)
1065 // When the search fails high at ply 1 while searching the first
1066 // move at the root, set the flag failHighPly1. This is used for
1067 // time managment: We don't want to stop the search early in
1068 // such cases, because resolving the fail high at ply 1 could
1069 // result in a big drop in score at the root.
1070 if (ply == 1 && RootMoveNumber == 1)
1071 Threads[threadID].failHighPly1 = true;
1073 // A fail high occurred. Re-search at full window (pv search)
1074 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1075 Threads[threadID].failHighPly1 = false;
1079 pos.undo_move(move);
1081 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1084 if (value > bestValue)
1091 if (value == value_mate_in(ply + 1))
1092 ss[ply].mateKiller = move;
1094 // If we are at ply 1, and we are searching the first root move at
1095 // ply 0, set the 'Problem' variable if the score has dropped a lot
1096 // (from the computer's point of view) since the previous iteration:
1099 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1104 if ( ActiveThreads > 1
1106 && depth >= MinimumSplitDepth
1108 && idle_thread_exists(threadID)
1110 && !thread_should_stop(threadID)
1111 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1112 &moveCount, &mp, dcCandidates, threadID, true))
1116 // All legal moves have been searched. A special case: If there were
1117 // no legal moves, it must be mate or stalemate:
1119 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1121 // If the search is not aborted, update the transposition table,
1122 // history counters, and killer moves.
1123 if (AbortSearch || thread_should_stop(threadID))
1126 if (bestValue <= oldAlpha)
1127 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1129 else if (bestValue >= beta)
1131 BetaCounter.add(pos.side_to_move(), depth, threadID);
1132 Move m = ss[ply].pv[ply];
1133 if (ok_to_history(pos, m)) // Only non capture moves are considered
1135 update_history(pos, m, depth, movesSearched, moveCount);
1136 update_killers(m, ss[ply]);
1138 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1141 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1147 // search() is the search function for zero-width nodes.
1149 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1150 int ply, bool allowNullmove, int threadID) {
1152 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1153 assert(ply >= 0 && ply < PLY_MAX);
1154 assert(threadID >= 0 && threadID < ActiveThreads);
1157 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1159 // Initialize, and make an early exit in case of an aborted search,
1160 // an instant draw, maximum ply reached, etc.
1161 init_node(pos, ss, ply, threadID);
1163 // After init_node() that calls poll()
1164 if (AbortSearch || thread_should_stop(threadID))
1172 if (ply >= PLY_MAX - 1)
1173 return evaluate(pos, ei, threadID);
1175 // Mate distance pruning
1176 if (value_mated_in(ply) >= beta)
1179 if (value_mate_in(ply + 1) < beta)
1182 // Transposition table lookup
1183 const TTEntry* tte = TT.retrieve(pos);
1184 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1186 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1188 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1189 return value_from_tt(tte->value(), ply);
1192 Value approximateEval = quick_evaluate(pos);
1193 bool mateThreat = false;
1194 bool nullDrivenIID = false;
1195 bool isCheck = pos.is_check();
1201 && !value_is_mate(beta)
1202 && ok_to_do_nullmove(pos)
1203 && approximateEval >= beta - NullMoveMargin)
1205 ss[ply].currentMove = MOVE_NULL;
1208 pos.do_null_move(st);
1209 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1211 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1213 // Check for a null capture artifact, if the value without the null capture
1214 // is above beta then mark the node as a suspicious failed low. We will verify
1215 // later if we are really under threat.
1216 if ( UseNullDrivenIID
1218 && depth > 6 * OnePly
1219 &&!value_is_mate(nullValue)
1220 && ttMove == MOVE_NONE
1221 && ss[ply + 1].currentMove != MOVE_NONE
1222 && pos.move_is_capture(ss[ply + 1].currentMove)
1223 && pos.see(ss[ply + 1].currentMove) + nullValue >= beta)
1224 nullDrivenIID = true;
1226 pos.undo_null_move();
1228 if (value_is_mate(nullValue))
1230 /* Do not return unproven mates */
1232 else if (nullValue >= beta)
1234 if (depth < 6 * OnePly)
1237 // Do zugzwang verification search
1238 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1242 // The null move failed low, which means that we may be faced with
1243 // some kind of threat. If the previous move was reduced, check if
1244 // the move that refuted the null move was somehow connected to the
1245 // move which was reduced. If a connection is found, return a fail
1246 // low score (which will cause the reduced move to fail high in the
1247 // parent node, which will trigger a re-search with full depth).
1248 if (nullValue == value_mated_in(ply + 2))
1251 nullDrivenIID = false;
1253 ss[ply].threatMove = ss[ply + 1].currentMove;
1254 if ( depth < ThreatDepth
1255 && ss[ply - 1].reduction
1256 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1260 // Null move search not allowed, try razoring
1261 else if ( !value_is_mate(beta)
1262 && approximateEval < beta - RazorMargin
1263 && depth < RazorDepth
1264 && (RazorAtDepthOne || depth > OnePly)
1265 && ttMove == MOVE_NONE
1266 && !pos.has_pawn_on_7th(pos.side_to_move()))
1268 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1269 if ( (v < beta - RazorMargin - RazorMargin / 4)
1270 || (depth < 3*OnePly && v < beta - RazorMargin)
1271 || (depth < 2*OnePly && v < beta - RazorMargin / 2))
1275 // Go with internal iterative deepening if we don't have a TT move
1276 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1277 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1279 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1280 ttMove = ss[ply].pv[ply];
1282 else if (nullDrivenIID)
1284 // The null move failed low due to a suspicious capture. Perhaps we
1285 // are facing a null capture artifact due to the side to move change
1286 // and this position should fail high. So do a normal search with a
1287 // reduced depth to get a good ttMove to use in the following full
1289 Move tm = ss[ply].threatMove;
1291 assert(tm != MOVE_NONE);
1292 assert(ttMove == MOVE_NONE);
1294 search(pos, ss, beta, depth/2, ply, false, threadID);
1295 ttMove = ss[ply].pv[ply];
1296 ss[ply].threatMove = tm;
1299 // Initialize a MovePicker object for the current position, and prepare
1300 // to search all moves:
1301 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1303 Move move, movesSearched[256];
1305 Value value, bestValue = -VALUE_INFINITE;
1306 Bitboard dcCandidates = mp.discovered_check_candidates();
1307 Value futilityValue = VALUE_NONE;
1308 bool useFutilityPruning = UseFutilityPruning
1309 && depth < SelectiveDepth
1312 // Loop through all legal moves until no moves remain or a beta cutoff
1314 while ( bestValue < beta
1315 && (move = mp.get_next_move()) != MOVE_NONE
1316 && !thread_should_stop(threadID))
1318 assert(move_is_ok(move));
1320 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1321 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1322 bool moveIsCapture = pos.move_is_capture(move);
1324 movesSearched[moveCount++] = ss[ply].currentMove = move;
1326 // Decide the new search depth
1328 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1329 Depth newDepth = depth - OnePly + ext;
1332 if ( useFutilityPruning
1335 && !move_promotion(move))
1337 // History pruning. See ok_to_prune() definition
1338 if ( moveCount >= 2 + int(depth)
1339 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1342 // Value based pruning
1343 if (depth < 7 * OnePly && approximateEval < beta)
1345 if (futilityValue == VALUE_NONE)
1346 futilityValue = evaluate(pos, ei, threadID)
1347 + FutilityMargins[int(depth)/2 - 1]
1350 if (futilityValue < beta)
1352 if (futilityValue > bestValue)
1353 bestValue = futilityValue;
1359 // Make and search the move
1361 pos.do_move(move, st, dcCandidates);
1363 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1364 // if the move fails high will be re-searched at full depth.
1365 if ( depth >= 2*OnePly
1366 && moveCount >= LMRNonPVMoves
1369 && !move_promotion(move)
1370 && !move_is_castle(move)
1371 && !move_is_killer(move, ss[ply]))
1373 ss[ply].reduction = OnePly;
1374 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1377 value = beta; // Just to trigger next condition
1379 if (value >= beta) // Go with full depth non-pv search
1381 ss[ply].reduction = Depth(0);
1382 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1384 pos.undo_move(move);
1386 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1389 if (value > bestValue)
1395 if (value == value_mate_in(ply + 1))
1396 ss[ply].mateKiller = move;
1400 if ( ActiveThreads > 1
1402 && depth >= MinimumSplitDepth
1404 && idle_thread_exists(threadID)
1406 && !thread_should_stop(threadID)
1407 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1408 &mp, dcCandidates, threadID, false))
1412 // All legal moves have been searched. A special case: If there were
1413 // no legal moves, it must be mate or stalemate.
1415 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1417 // If the search is not aborted, update the transposition table,
1418 // history counters, and killer moves.
1419 if (AbortSearch || thread_should_stop(threadID))
1422 if (bestValue < beta)
1423 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1426 BetaCounter.add(pos.side_to_move(), depth, threadID);
1427 Move m = ss[ply].pv[ply];
1428 if (ok_to_history(pos, m)) // Only non capture moves are considered
1430 update_history(pos, m, depth, movesSearched, moveCount);
1431 update_killers(m, ss[ply]);
1433 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1439 // qsearch() is the quiescence search function, which is called by the main
1440 // search function when the remaining depth is zero (or, to be more precise,
1441 // less than OnePly).
1443 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1444 Depth depth, int ply, int threadID) {
1446 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1447 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1449 assert(ply >= 0 && ply < PLY_MAX);
1450 assert(threadID >= 0 && threadID < ActiveThreads);
1452 // Initialize, and make an early exit in case of an aborted search,
1453 // an instant draw, maximum ply reached, etc.
1454 init_node(pos, ss, ply, threadID);
1456 // After init_node() that calls poll()
1457 if (AbortSearch || thread_should_stop(threadID))
1463 // Transposition table lookup
1464 const TTEntry* tte = TT.retrieve(pos);
1465 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1466 return value_from_tt(tte->value(), ply);
1468 // Evaluate the position statically
1470 bool isCheck = pos.is_check();
1471 Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1473 if (ply == PLY_MAX - 1)
1474 return evaluate(pos, ei, threadID);
1476 // Initialize "stand pat score", and return it immediately if it is
1478 Value bestValue = staticValue;
1480 if (bestValue >= beta)
1483 if (bestValue > alpha)
1486 // Initialize a MovePicker object for the current position, and prepare
1487 // to search the moves. Because the depth is <= 0 here, only captures,
1488 // queen promotions and checks (only if depth == 0) will be generated.
1489 bool pvNode = (beta - alpha != 1);
1490 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1493 Bitboard dcCandidates = mp.discovered_check_candidates();
1494 Color us = pos.side_to_move();
1495 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1497 // Loop through the moves until no moves remain or a beta cutoff
1499 while ( alpha < beta
1500 && (move = mp.get_next_move()) != MOVE_NONE)
1502 assert(move_is_ok(move));
1505 ss[ply].currentMove = move;
1508 if ( UseQSearchFutilityPruning
1512 && !move_promotion(move)
1513 && !pos.move_is_check(move, dcCandidates)
1514 && !pos.move_is_passed_pawn_push(move))
1516 Value futilityValue = staticValue
1517 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1518 pos.endgame_value_of_piece_on(move_to(move)))
1519 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1521 + ei.futilityMargin;
1523 if (futilityValue < alpha)
1525 if (futilityValue > bestValue)
1526 bestValue = futilityValue;
1531 // Don't search captures and checks with negative SEE values
1533 && !move_promotion(move)
1534 && (pos.midgame_value_of_piece_on(move_from(move)) >
1535 pos.midgame_value_of_piece_on(move_to(move)))
1536 && pos.see(move) < 0)
1539 // Make and search the move.
1541 pos.do_move(move, st, dcCandidates);
1542 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1543 pos.undo_move(move);
1545 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1548 if (value > bestValue)
1559 // All legal moves have been searched. A special case: If we're in check
1560 // and no legal moves were found, it is checkmate:
1561 if (pos.is_check() && moveCount == 0) // Mate!
1562 return value_mated_in(ply);
1564 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1566 // Update transposition table
1567 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1569 // Update killers only for good check moves
1570 Move m = ss[ply].currentMove;
1571 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1573 // Wrong to update history when depth is <= 0
1574 update_killers(m, ss[ply]);
1580 // sp_search() is used to search from a split point. This function is called
1581 // by each thread working at the split point. It is similar to the normal
1582 // search() function, but simpler. Because we have already probed the hash
1583 // table, done a null move search, and searched the first move before
1584 // splitting, we don't have to repeat all this work in sp_search(). We
1585 // also don't need to store anything to the hash table here: This is taken
1586 // care of after we return from the split point.
1588 void sp_search(SplitPoint *sp, int threadID) {
1590 assert(threadID >= 0 && threadID < ActiveThreads);
1591 assert(ActiveThreads > 1);
1593 Position pos = Position(sp->pos);
1594 SearchStack *ss = sp->sstack[threadID];
1597 bool isCheck = pos.is_check();
1598 bool useFutilityPruning = UseFutilityPruning
1599 && sp->depth < SelectiveDepth
1602 while ( sp->bestValue < sp->beta
1603 && !thread_should_stop(threadID)
1604 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1606 assert(move_is_ok(move));
1608 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1609 bool moveIsCapture = pos.move_is_capture(move);
1611 lock_grab(&(sp->lock));
1612 int moveCount = ++sp->moves;
1613 lock_release(&(sp->lock));
1615 ss[sp->ply].currentMove = move;
1617 // Decide the new search depth.
1619 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1620 Depth newDepth = sp->depth - OnePly + ext;
1623 if ( useFutilityPruning
1626 && !move_promotion(move)
1627 && moveCount >= 2 + int(sp->depth)
1628 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1631 // Make and search the move.
1633 pos.do_move(move, st, sp->dcCandidates);
1635 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1636 // if the move fails high will be re-searched at full depth.
1638 && moveCount >= LMRNonPVMoves
1640 && !move_promotion(move)
1641 && !move_is_castle(move)
1642 && !move_is_killer(move, ss[sp->ply]))
1644 ss[sp->ply].reduction = OnePly;
1645 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1648 value = sp->beta; // Just to trigger next condition
1650 if (value >= sp->beta) // Go with full depth non-pv search
1652 ss[sp->ply].reduction = Depth(0);
1653 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1655 pos.undo_move(move);
1657 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1659 if (thread_should_stop(threadID))
1663 lock_grab(&(sp->lock));
1664 if (value > sp->bestValue && !thread_should_stop(threadID))
1666 sp->bestValue = value;
1667 if (sp->bestValue >= sp->beta)
1669 sp_update_pv(sp->parentSstack, ss, sp->ply);
1670 for (int i = 0; i < ActiveThreads; i++)
1671 if (i != threadID && (i == sp->master || sp->slaves[i]))
1672 Threads[i].stop = true;
1674 sp->finished = true;
1677 lock_release(&(sp->lock));
1680 lock_grab(&(sp->lock));
1682 // If this is the master thread and we have been asked to stop because of
1683 // a beta cutoff higher up in the tree, stop all slave threads:
1684 if (sp->master == threadID && thread_should_stop(threadID))
1685 for (int i = 0; i < ActiveThreads; i++)
1687 Threads[i].stop = true;
1690 sp->slaves[threadID] = 0;
1692 lock_release(&(sp->lock));
1696 // sp_search_pv() is used to search from a PV split point. This function
1697 // is called by each thread working at the split point. It is similar to
1698 // the normal search_pv() function, but simpler. Because we have already
1699 // probed the hash table and searched the first move before splitting, we
1700 // don't have to repeat all this work in sp_search_pv(). We also don't
1701 // need to store anything to the hash table here: This is taken care of
1702 // after we return from the split point.
1704 void sp_search_pv(SplitPoint *sp, int threadID) {
1706 assert(threadID >= 0 && threadID < ActiveThreads);
1707 assert(ActiveThreads > 1);
1709 Position pos = Position(sp->pos);
1710 SearchStack *ss = sp->sstack[threadID];
1714 while ( sp->alpha < sp->beta
1715 && !thread_should_stop(threadID)
1716 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1718 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1719 bool moveIsCapture = pos.move_is_capture(move);
1721 assert(move_is_ok(move));
1724 ss[sp->ply].currentMoveCaptureValue =
1725 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1727 ss[sp->ply].currentMoveCaptureValue = Value(0);
1729 lock_grab(&(sp->lock));
1730 int moveCount = ++sp->moves;
1731 lock_release(&(sp->lock));
1733 ss[sp->ply].currentMove = move;
1735 // Decide the new search depth.
1737 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1738 Depth newDepth = sp->depth - OnePly + ext;
1740 // Make and search the move.
1742 pos.do_move(move, st, sp->dcCandidates);
1744 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1745 // if the move fails high will be re-searched at full depth.
1747 && moveCount >= LMRPVMoves
1749 && !move_promotion(move)
1750 && !move_is_castle(move)
1751 && !move_is_killer(move, ss[sp->ply]))
1753 ss[sp->ply].reduction = OnePly;
1754 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1757 value = sp->alpha + 1; // Just to trigger next condition
1759 if (value > sp->alpha) // Go with full depth non-pv search
1761 ss[sp->ply].reduction = Depth(0);
1762 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1764 if (value > sp->alpha && value < sp->beta)
1766 // When the search fails high at ply 1 while searching the first
1767 // move at the root, set the flag failHighPly1. This is used for
1768 // time managment: We don't want to stop the search early in
1769 // such cases, because resolving the fail high at ply 1 could
1770 // result in a big drop in score at the root.
1771 if (sp->ply == 1 && RootMoveNumber == 1)
1772 Threads[threadID].failHighPly1 = true;
1774 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1775 Threads[threadID].failHighPly1 = false;
1778 pos.undo_move(move);
1780 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1782 if (thread_should_stop(threadID))
1786 lock_grab(&(sp->lock));
1787 if (value > sp->bestValue && !thread_should_stop(threadID))
1789 sp->bestValue = value;
1790 if (value > sp->alpha)
1793 sp_update_pv(sp->parentSstack, ss, sp->ply);
1794 if (value == value_mate_in(sp->ply + 1))
1795 ss[sp->ply].mateKiller = move;
1797 if(value >= sp->beta)
1799 for(int i = 0; i < ActiveThreads; i++)
1800 if(i != threadID && (i == sp->master || sp->slaves[i]))
1801 Threads[i].stop = true;
1803 sp->finished = true;
1806 // If we are at ply 1, and we are searching the first root move at
1807 // ply 0, set the 'Problem' variable if the score has dropped a lot
1808 // (from the computer's point of view) since the previous iteration.
1811 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1814 lock_release(&(sp->lock));
1817 lock_grab(&(sp->lock));
1819 // If this is the master thread and we have been asked to stop because of
1820 // a beta cutoff higher up in the tree, stop all slave threads.
1821 if (sp->master == threadID && thread_should_stop(threadID))
1822 for (int i = 0; i < ActiveThreads; i++)
1824 Threads[i].stop = true;
1827 sp->slaves[threadID] = 0;
1829 lock_release(&(sp->lock));
1832 /// The BetaCounterType class
1834 BetaCounterType::BetaCounterType() { clear(); }
1836 void BetaCounterType::clear() {
1838 for (int i = 0; i < THREAD_MAX; i++)
1839 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1842 void BetaCounterType::add(Color us, Depth d, int threadID) {
1844 // Weighted count based on depth
1845 hits[threadID][us] += int(d);
1848 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1851 for (int i = 0; i < THREAD_MAX; i++)
1854 their += hits[i][opposite_color(us)];
1859 /// The RootMove class
1863 RootMove::RootMove() {
1864 nodes = cumulativeNodes = 0ULL;
1867 // RootMove::operator<() is the comparison function used when
1868 // sorting the moves. A move m1 is considered to be better
1869 // than a move m2 if it has a higher score, or if the moves
1870 // have equal score but m1 has the higher node count.
1872 bool RootMove::operator<(const RootMove& m) {
1874 if (score != m.score)
1875 return (score < m.score);
1877 return theirBeta <= m.theirBeta;
1880 /// The RootMoveList class
1884 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1886 MoveStack mlist[MaxRootMoves];
1887 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1889 // Generate all legal moves
1890 int lm_count = generate_legal_moves(pos, mlist);
1892 // Add each move to the moves[] array
1893 for (int i = 0; i < lm_count; i++)
1895 bool includeMove = includeAllMoves;
1897 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1898 includeMove = (searchMoves[k] == mlist[i].move);
1902 // Find a quick score for the move
1904 SearchStack ss[PLY_MAX_PLUS_2];
1906 moves[count].move = mlist[i].move;
1907 moves[count].nodes = 0ULL;
1908 pos.do_move(moves[count].move, st);
1909 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1911 pos.undo_move(moves[count].move);
1912 moves[count].pv[0] = moves[i].move;
1913 moves[count].pv[1] = MOVE_NONE; // FIXME
1921 // Simple accessor methods for the RootMoveList class
1923 inline Move RootMoveList::get_move(int moveNum) const {
1924 return moves[moveNum].move;
1927 inline Value RootMoveList::get_move_score(int moveNum) const {
1928 return moves[moveNum].score;
1931 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1932 moves[moveNum].score = score;
1935 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1936 moves[moveNum].nodes = nodes;
1937 moves[moveNum].cumulativeNodes += nodes;
1940 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1941 moves[moveNum].ourBeta = our;
1942 moves[moveNum].theirBeta = their;
1945 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1947 for(j = 0; pv[j] != MOVE_NONE; j++)
1948 moves[moveNum].pv[j] = pv[j];
1949 moves[moveNum].pv[j] = MOVE_NONE;
1952 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1953 return moves[moveNum].pv[i];
1956 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1957 return moves[moveNum].cumulativeNodes;
1960 inline int RootMoveList::move_count() const {
1965 // RootMoveList::scan_for_easy_move() is called at the end of the first
1966 // iteration, and is used to detect an "easy move", i.e. a move which appears
1967 // to be much bester than all the rest. If an easy move is found, the move
1968 // is returned, otherwise the function returns MOVE_NONE. It is very
1969 // important that this function is called at the right moment: The code
1970 // assumes that the first iteration has been completed and the moves have
1971 // been sorted. This is done in RootMoveList c'tor.
1973 Move RootMoveList::scan_for_easy_move() const {
1980 // moves are sorted so just consider the best and the second one
1981 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1987 // RootMoveList::sort() sorts the root move list at the beginning of a new
1990 inline void RootMoveList::sort() {
1992 sort_multipv(count - 1); // all items
1996 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1997 // list by their scores and depths. It is used to order the different PVs
1998 // correctly in MultiPV mode.
2000 void RootMoveList::sort_multipv(int n) {
2002 for (int i = 1; i <= n; i++)
2004 RootMove rm = moves[i];
2006 for (j = i; j > 0 && moves[j-1] < rm; j--)
2007 moves[j] = moves[j-1];
2013 // init_node() is called at the beginning of all the search functions
2014 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2015 // stack object corresponding to the current node. Once every
2016 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2017 // for user input and checks whether it is time to stop the search.
2019 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2020 assert(ply >= 0 && ply < PLY_MAX);
2021 assert(threadID >= 0 && threadID < ActiveThreads);
2023 Threads[threadID].nodes++;
2027 if(NodesSincePoll >= NodesBetweenPolls) {
2034 ss[ply+2].initKillers();
2036 if(Threads[threadID].printCurrentLine)
2037 print_current_line(ss, ply, threadID);
2041 // update_pv() is called whenever a search returns a value > alpha. It
2042 // updates the PV in the SearchStack object corresponding to the current
2045 void update_pv(SearchStack ss[], int ply) {
2046 assert(ply >= 0 && ply < PLY_MAX);
2048 ss[ply].pv[ply] = ss[ply].currentMove;
2050 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2051 ss[ply].pv[p] = ss[ply+1].pv[p];
2052 ss[ply].pv[p] = MOVE_NONE;
2056 // sp_update_pv() is a variant of update_pv for use at split points. The
2057 // difference between the two functions is that sp_update_pv also updates
2058 // the PV at the parent node.
2060 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2061 assert(ply >= 0 && ply < PLY_MAX);
2063 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2065 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2066 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2067 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2071 // connected_moves() tests whether two moves are 'connected' in the sense
2072 // that the first move somehow made the second move possible (for instance
2073 // if the moving piece is the same in both moves). The first move is
2074 // assumed to be the move that was made to reach the current position, while
2075 // the second move is assumed to be a move from the current position.
2077 bool connected_moves(const Position &pos, Move m1, Move m2) {
2078 Square f1, t1, f2, t2;
2080 assert(move_is_ok(m1));
2081 assert(move_is_ok(m2));
2086 // Case 1: The moving piece is the same in both moves.
2092 // Case 2: The destination square for m2 was vacated by m1.
2098 // Case 3: Moving through the vacated square:
2099 if(piece_is_slider(pos.piece_on(f2)) &&
2100 bit_is_set(squares_between(f2, t2), f1))
2103 // Case 4: The destination square for m2 is attacked by the moving piece
2105 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2108 // Case 5: Discovered check, checking piece is the piece moved in m1:
2109 if(piece_is_slider(pos.piece_on(t1)) &&
2110 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2112 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2114 Bitboard occ = pos.occupied_squares();
2115 Color us = pos.side_to_move();
2116 Square ksq = pos.king_square(us);
2117 clear_bit(&occ, f2);
2118 if(pos.type_of_piece_on(t1) == BISHOP) {
2119 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2122 else if(pos.type_of_piece_on(t1) == ROOK) {
2123 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2127 assert(pos.type_of_piece_on(t1) == QUEEN);
2128 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2137 // value_is_mate() checks if the given value is a mate one
2138 // eventually compensated for the ply.
2140 bool value_is_mate(Value value) {
2142 assert(abs(value) <= VALUE_INFINITE);
2144 return value <= value_mated_in(PLY_MAX)
2145 || value >= value_mate_in(PLY_MAX);
2149 // move_is_killer() checks if the given move is among the
2150 // killer moves of that ply.
2152 bool move_is_killer(Move m, const SearchStack& ss) {
2154 const Move* k = ss.killers;
2155 for (int i = 0; i < KILLER_MAX; i++, k++)
2163 // extension() decides whether a move should be searched with normal depth,
2164 // or with extended depth. Certain classes of moves (checking moves, in
2165 // particular) are searched with bigger depth than ordinary moves and in
2166 // any case are marked as 'dangerous'. Note that also if a move is not
2167 // extended, as example because the corresponding UCI option is set to zero,
2168 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2170 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2171 bool singleReply, bool mateThreat, bool* dangerous) {
2173 assert(m != MOVE_NONE);
2175 Depth result = Depth(0);
2176 *dangerous = check || singleReply || mateThreat;
2179 result += CheckExtension[pvNode];
2182 result += SingleReplyExtension[pvNode];
2185 result += MateThreatExtension[pvNode];
2187 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2189 if (pos.move_is_pawn_push_to_7th(m))
2191 result += PawnPushTo7thExtension[pvNode];
2194 if (pos.move_is_passed_pawn_push(m))
2196 result += PassedPawnExtension[pvNode];
2202 && pos.type_of_piece_on(move_to(m)) != PAWN
2203 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2204 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2205 && !move_promotion(m)
2208 result += PawnEndgameExtension[pvNode];
2214 && pos.type_of_piece_on(move_to(m)) != PAWN
2221 return Min(result, OnePly);
2225 // ok_to_do_nullmove() looks at the current position and decides whether
2226 // doing a 'null move' should be allowed. In order to avoid zugzwang
2227 // problems, null moves are not allowed when the side to move has very
2228 // little material left. Currently, the test is a bit too simple: Null
2229 // moves are avoided only when the side to move has only pawns left. It's
2230 // probably a good idea to avoid null moves in at least some more
2231 // complicated endgames, e.g. KQ vs KR. FIXME
2233 bool ok_to_do_nullmove(const Position &pos) {
2234 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2240 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2241 // non-tactical moves late in the move list close to the leaves are
2242 // candidates for pruning.
2244 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2245 Square mfrom, mto, tfrom, tto;
2247 assert(move_is_ok(m));
2248 assert(threat == MOVE_NONE || move_is_ok(threat));
2249 assert(!move_promotion(m));
2250 assert(!pos.move_is_check(m));
2251 assert(!pos.move_is_capture(m));
2252 assert(!pos.move_is_passed_pawn_push(m));
2253 assert(d >= OnePly);
2255 mfrom = move_from(m);
2257 tfrom = move_from(threat);
2258 tto = move_to(threat);
2260 // Case 1: Castling moves are never pruned.
2261 if (move_is_castle(m))
2264 // Case 2: Don't prune moves which move the threatened piece
2265 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2268 // Case 3: If the threatened piece has value less than or equal to the
2269 // value of the threatening piece, don't prune move which defend it.
2270 if ( !PruneDefendingMoves
2271 && threat != MOVE_NONE
2272 && pos.move_is_capture(threat)
2273 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2274 || pos.type_of_piece_on(tfrom) == KING)
2275 && pos.move_attacks_square(m, tto))
2278 // Case 4: Don't prune moves with good history.
2279 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2282 // Case 5: If the moving piece in the threatened move is a slider, don't
2283 // prune safe moves which block its ray.
2284 if ( !PruneBlockingMoves
2285 && threat != MOVE_NONE
2286 && piece_is_slider(pos.piece_on(tfrom))
2287 && bit_is_set(squares_between(tfrom, tto), mto)
2295 // ok_to_use_TT() returns true if a transposition table score
2296 // can be used at a given point in search.
2298 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2300 Value v = value_from_tt(tte->value(), ply);
2302 return ( tte->depth() >= depth
2303 || v >= Max(value_mate_in(100), beta)
2304 || v < Min(value_mated_in(100), beta))
2306 && ( (is_lower_bound(tte->type()) && v >= beta)
2307 || (is_upper_bound(tte->type()) && v < beta));
2311 // ok_to_history() returns true if a move m can be stored
2312 // in history. Should be a non capturing move nor a promotion.
2314 bool ok_to_history(const Position& pos, Move m) {
2316 return !pos.move_is_capture(m) && !move_promotion(m);
2320 // update_history() registers a good move that produced a beta-cutoff
2321 // in history and marks as failures all the other moves of that ply.
2323 void update_history(const Position& pos, Move m, Depth depth,
2324 Move movesSearched[], int moveCount) {
2326 H.success(pos.piece_on(move_from(m)), m, depth);
2328 for (int i = 0; i < moveCount - 1; i++)
2330 assert(m != movesSearched[i]);
2331 if (ok_to_history(pos, movesSearched[i]))
2332 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2337 // update_killers() add a good move that produced a beta-cutoff
2338 // among the killer moves of that ply.
2340 void update_killers(Move m, SearchStack& ss) {
2342 if (m == ss.killers[0])
2345 for (int i = KILLER_MAX - 1; i > 0; i--)
2346 ss.killers[i] = ss.killers[i - 1];
2351 // fail_high_ply_1() checks if some thread is currently resolving a fail
2352 // high at ply 1 at the node below the first root node. This information
2353 // is used for time managment.
2355 bool fail_high_ply_1() {
2356 for(int i = 0; i < ActiveThreads; i++)
2357 if(Threads[i].failHighPly1)
2363 // current_search_time() returns the number of milliseconds which have passed
2364 // since the beginning of the current search.
2366 int current_search_time() {
2367 return get_system_time() - SearchStartTime;
2371 // nps() computes the current nodes/second count.
2374 int t = current_search_time();
2375 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2379 // poll() performs two different functions: It polls for user input, and it
2380 // looks at the time consumed so far and decides if it's time to abort the
2385 static int lastInfoTime;
2386 int t = current_search_time();
2391 // We are line oriented, don't read single chars
2392 std::string command;
2393 if (!std::getline(std::cin, command))
2396 if (command == "quit")
2399 PonderSearch = false;
2402 else if(command == "stop")
2405 PonderSearch = false;
2407 else if(command == "ponderhit")
2410 // Print search information
2414 else if (lastInfoTime > t)
2415 // HACK: Must be a new search where we searched less than
2416 // NodesBetweenPolls nodes during the first second of search.
2419 else if (t - lastInfoTime >= 1000)
2426 if (dbg_show_hit_rate)
2427 dbg_print_hit_rate();
2429 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2430 << " time " << t << " hashfull " << TT.full() << std::endl;
2431 lock_release(&IOLock);
2432 if (ShowCurrentLine)
2433 Threads[0].printCurrentLine = true;
2435 // Should we stop the search?
2439 bool overTime = t > AbsoluteMaxSearchTime
2440 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2441 || ( !FailHigh && !fail_high_ply_1() && !Problem
2442 && t > 6*(MaxSearchTime + ExtraSearchTime));
2444 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2445 || (ExactMaxTime && t >= ExactMaxTime)
2446 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2451 // ponderhit() is called when the program is pondering (i.e. thinking while
2452 // it's the opponent's turn to move) in order to let the engine know that
2453 // it correctly predicted the opponent's move.
2456 int t = current_search_time();
2457 PonderSearch = false;
2458 if(Iteration >= 2 &&
2459 (!InfiniteSearch && (StopOnPonderhit ||
2460 t > AbsoluteMaxSearchTime ||
2461 (RootMoveNumber == 1 &&
2462 t > MaxSearchTime + ExtraSearchTime) ||
2463 (!FailHigh && !fail_high_ply_1() && !Problem &&
2464 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2469 // print_current_line() prints the current line of search for a given
2470 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2472 void print_current_line(SearchStack ss[], int ply, int threadID) {
2473 assert(ply >= 0 && ply < PLY_MAX);
2474 assert(threadID >= 0 && threadID < ActiveThreads);
2476 if(!Threads[threadID].idle) {
2478 std::cout << "info currline " << (threadID + 1);
2479 for(int p = 0; p < ply; p++)
2480 std::cout << " " << ss[p].currentMove;
2481 std::cout << std::endl;
2482 lock_release(&IOLock);
2484 Threads[threadID].printCurrentLine = false;
2485 if(threadID + 1 < ActiveThreads)
2486 Threads[threadID + 1].printCurrentLine = true;
2490 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2491 // while the program is pondering. The point is to work around a wrinkle in
2492 // the UCI protocol: When pondering, the engine is not allowed to give a
2493 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2494 // We simply wait here until one of these commands is sent, and return,
2495 // after which the bestmove and pondermove will be printed (in id_loop()).
2497 void wait_for_stop_or_ponderhit() {
2498 std::string command;
2501 if(!std::getline(std::cin, command))
2504 if(command == "quit") {
2505 OpeningBook.close();
2510 else if(command == "ponderhit" || command == "stop")
2516 // idle_loop() is where the threads are parked when they have no work to do.
2517 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2518 // object for which the current thread is the master.
2520 void idle_loop(int threadID, SplitPoint *waitSp) {
2521 assert(threadID >= 0 && threadID < THREAD_MAX);
2523 Threads[threadID].running = true;
2526 if(AllThreadsShouldExit && threadID != 0)
2529 // If we are not thinking, wait for a condition to be signaled instead
2530 // of wasting CPU time polling for work:
2531 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2532 #if !defined(_MSC_VER)
2533 pthread_mutex_lock(&WaitLock);
2534 if(Idle || threadID >= ActiveThreads)
2535 pthread_cond_wait(&WaitCond, &WaitLock);
2536 pthread_mutex_unlock(&WaitLock);
2538 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2542 // If this thread has been assigned work, launch a search:
2543 if(Threads[threadID].workIsWaiting) {
2544 Threads[threadID].workIsWaiting = false;
2545 if(Threads[threadID].splitPoint->pvNode)
2546 sp_search_pv(Threads[threadID].splitPoint, threadID);
2548 sp_search(Threads[threadID].splitPoint, threadID);
2549 Threads[threadID].idle = true;
2552 // If this thread is the master of a split point and all threads have
2553 // finished their work at this split point, return from the idle loop:
2554 if(waitSp != NULL && waitSp->cpus == 0)
2558 Threads[threadID].running = false;
2562 // init_split_point_stack() is called during program initialization, and
2563 // initializes all split point objects.
2565 void init_split_point_stack() {
2566 for(int i = 0; i < THREAD_MAX; i++)
2567 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2568 SplitPointStack[i][j].parent = NULL;
2569 lock_init(&(SplitPointStack[i][j].lock), NULL);
2574 // destroy_split_point_stack() is called when the program exits, and
2575 // destroys all locks in the precomputed split point objects.
2577 void destroy_split_point_stack() {
2578 for(int i = 0; i < THREAD_MAX; i++)
2579 for(int j = 0; j < MaxActiveSplitPoints; j++)
2580 lock_destroy(&(SplitPointStack[i][j].lock));
2584 // thread_should_stop() checks whether the thread with a given threadID has
2585 // been asked to stop, directly or indirectly. This can happen if a beta
2586 // cutoff has occured in thre thread's currently active split point, or in
2587 // some ancestor of the current split point.
2589 bool thread_should_stop(int threadID) {
2590 assert(threadID >= 0 && threadID < ActiveThreads);
2594 if(Threads[threadID].stop)
2596 if(ActiveThreads <= 2)
2598 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2600 Threads[threadID].stop = true;
2607 // thread_is_available() checks whether the thread with threadID "slave" is
2608 // available to help the thread with threadID "master" at a split point. An
2609 // obvious requirement is that "slave" must be idle. With more than two
2610 // threads, this is not by itself sufficient: If "slave" is the master of
2611 // some active split point, it is only available as a slave to the other
2612 // threads which are busy searching the split point at the top of "slave"'s
2613 // split point stack (the "helpful master concept" in YBWC terminology).
2615 bool thread_is_available(int slave, int master) {
2616 assert(slave >= 0 && slave < ActiveThreads);
2617 assert(master >= 0 && master < ActiveThreads);
2618 assert(ActiveThreads > 1);
2620 if(!Threads[slave].idle || slave == master)
2623 if(Threads[slave].activeSplitPoints == 0)
2624 // No active split points means that the thread is available as a slave
2625 // for any other thread.
2628 if(ActiveThreads == 2)
2631 // Apply the "helpful master" concept if possible.
2632 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2639 // idle_thread_exists() tries to find an idle thread which is available as
2640 // a slave for the thread with threadID "master".
2642 bool idle_thread_exists(int master) {
2643 assert(master >= 0 && master < ActiveThreads);
2644 assert(ActiveThreads > 1);
2646 for(int i = 0; i < ActiveThreads; i++)
2647 if(thread_is_available(i, master))
2653 // split() does the actual work of distributing the work at a node between
2654 // several threads at PV nodes. If it does not succeed in splitting the
2655 // node (because no idle threads are available, or because we have no unused
2656 // split point objects), the function immediately returns false. If
2657 // splitting is possible, a SplitPoint object is initialized with all the
2658 // data that must be copied to the helper threads (the current position and
2659 // search stack, alpha, beta, the search depth, etc.), and we tell our
2660 // helper threads that they have been assigned work. This will cause them
2661 // to instantly leave their idle loops and call sp_search_pv(). When all
2662 // threads have returned from sp_search_pv (or, equivalently, when
2663 // splitPoint->cpus becomes 0), split() returns true.
2665 bool split(const Position &p, SearchStack *sstck, int ply,
2666 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2667 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2670 assert(sstck != NULL);
2671 assert(ply >= 0 && ply < PLY_MAX);
2672 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2673 assert(!pvNode || *alpha < *beta);
2674 assert(*beta <= VALUE_INFINITE);
2675 assert(depth > Depth(0));
2676 assert(master >= 0 && master < ActiveThreads);
2677 assert(ActiveThreads > 1);
2679 SplitPoint *splitPoint;
2684 // If no other thread is available to help us, or if we have too many
2685 // active split points, don't split:
2686 if(!idle_thread_exists(master) ||
2687 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2688 lock_release(&MPLock);
2692 // Pick the next available split point object from the split point stack:
2693 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2694 Threads[master].activeSplitPoints++;
2696 // Initialize the split point object:
2697 splitPoint->parent = Threads[master].splitPoint;
2698 splitPoint->finished = false;
2699 splitPoint->ply = ply;
2700 splitPoint->depth = depth;
2701 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2702 splitPoint->beta = *beta;
2703 splitPoint->pvNode = pvNode;
2704 splitPoint->dcCandidates = dcCandidates;
2705 splitPoint->bestValue = *bestValue;
2706 splitPoint->master = master;
2707 splitPoint->mp = mp;
2708 splitPoint->moves = *moves;
2709 splitPoint->cpus = 1;
2710 splitPoint->pos.copy(p);
2711 splitPoint->parentSstack = sstck;
2712 for(i = 0; i < ActiveThreads; i++)
2713 splitPoint->slaves[i] = 0;
2715 // Copy the current position and the search stack to the master thread:
2716 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2717 Threads[master].splitPoint = splitPoint;
2719 // Make copies of the current position and search stack for each thread:
2720 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2722 if(thread_is_available(i, master)) {
2723 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2724 Threads[i].splitPoint = splitPoint;
2725 splitPoint->slaves[i] = 1;
2729 // Tell the threads that they have work to do. This will make them leave
2731 for(i = 0; i < ActiveThreads; i++)
2732 if(i == master || splitPoint->slaves[i]) {
2733 Threads[i].workIsWaiting = true;
2734 Threads[i].idle = false;
2735 Threads[i].stop = false;
2738 lock_release(&MPLock);
2740 // Everything is set up. The master thread enters the idle loop, from
2741 // which it will instantly launch a search, because its workIsWaiting
2742 // slot is 'true'. We send the split point as a second parameter to the
2743 // idle loop, which means that the main thread will return from the idle
2744 // loop when all threads have finished their work at this split point
2745 // (i.e. when // splitPoint->cpus == 0).
2746 idle_loop(master, splitPoint);
2748 // We have returned from the idle loop, which means that all threads are
2749 // finished. Update alpha, beta and bestvalue, and return:
2751 if(pvNode) *alpha = splitPoint->alpha;
2752 *beta = splitPoint->beta;
2753 *bestValue = splitPoint->bestValue;
2754 Threads[master].stop = false;
2755 Threads[master].idle = false;
2756 Threads[master].activeSplitPoints--;
2757 Threads[master].splitPoint = splitPoint->parent;
2758 lock_release(&MPLock);
2764 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2765 // to start a new search from the root.
2767 void wake_sleeping_threads() {
2768 if(ActiveThreads > 1) {
2769 for(int i = 1; i < ActiveThreads; i++) {
2770 Threads[i].idle = true;
2771 Threads[i].workIsWaiting = false;
2773 #if !defined(_MSC_VER)
2774 pthread_mutex_lock(&WaitLock);
2775 pthread_cond_broadcast(&WaitCond);
2776 pthread_mutex_unlock(&WaitLock);
2778 for(int i = 1; i < THREAD_MAX; i++)
2779 SetEvent(SitIdleEvent[i]);
2785 // init_thread() is the function which is called when a new thread is
2786 // launched. It simply calls the idle_loop() function with the supplied
2787 // threadID. There are two versions of this function; one for POSIX threads
2788 // and one for Windows threads.
2790 #if !defined(_MSC_VER)
2792 void *init_thread(void *threadID) {
2793 idle_loop(*(int *)threadID, NULL);
2799 DWORD WINAPI init_thread(LPVOID threadID) {
2800 idle_loop(*(int *)threadID, NULL);