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_search_stack(SearchStack& ss);
263 void init_search_stack(SearchStack ss[]);
264 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
265 void update_pv(SearchStack ss[], int ply);
266 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
267 bool connected_moves(const Position &pos, Move m1, Move m2);
268 bool value_is_mate(Value value);
269 bool move_is_killer(Move m, const SearchStack& ss);
270 Depth extension(const Position &pos, Move m, bool pvNode, bool check, bool singleReply, bool mateThreat, bool* dangerous);
271 bool ok_to_do_nullmove(const Position &pos);
272 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
273 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
274 bool ok_to_history(const Position &pos, Move m);
275 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
276 void update_killers(Move m, SearchStack& ss);
278 bool fail_high_ply_1();
279 int current_search_time();
283 void print_current_line(SearchStack ss[], int ply, int threadID);
284 void wait_for_stop_or_ponderhit();
286 void idle_loop(int threadID, SplitPoint *waitSp);
287 void init_split_point_stack();
288 void destroy_split_point_stack();
289 bool thread_should_stop(int threadID);
290 bool thread_is_available(int slave, int master);
291 bool idle_thread_exists(int master);
292 bool split(const Position &pos, SearchStack *ss, int ply,
293 Value *alpha, Value *beta, Value *bestValue, Depth depth,
294 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
296 void wake_sleeping_threads();
298 #if !defined(_MSC_VER)
299 void *init_thread(void *threadID);
301 DWORD WINAPI init_thread(LPVOID threadID);
308 //// Global variables
311 // The main transposition table
312 TranspositionTable TT = TranspositionTable(TTDefaultSize);
315 // Number of active threads:
316 int ActiveThreads = 1;
318 // Locks. In principle, there is no need for IOLock to be a global variable,
319 // but it could turn out to be useful for debugging.
322 History H; // Should be made local?
324 // The empty search stack
325 SearchStack EmptySearchStack;
332 /// think() is the external interface to Stockfish's search, and is called when
333 /// the program receives the UCI 'go' command. It initializes various
334 /// search-related global variables, and calls root_search()
336 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
337 int time[], int increment[], int movesToGo, int maxDepth,
338 int maxNodes, int maxTime, Move searchMoves[]) {
340 // Look for a book move
341 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
344 if (get_option_value_string("Book File") != OpeningBook.file_name())
347 OpeningBook.open("book.bin");
349 bookMove = OpeningBook.get_move(pos);
350 if (bookMove != MOVE_NONE)
352 std::cout << "bestmove " << bookMove << std::endl;
357 // Initialize global search variables
359 SearchStartTime = get_system_time();
360 BestRootMove = MOVE_NONE;
361 PonderMove = MOVE_NONE;
362 EasyMove = MOVE_NONE;
363 for (int i = 0; i < THREAD_MAX; i++)
365 Threads[i].nodes = 0ULL;
366 Threads[i].failHighPly1 = false;
369 InfiniteSearch = infinite;
370 PonderSearch = ponder;
371 StopOnPonderhit = false;
376 ExactMaxTime = maxTime;
378 // Read UCI option values
379 TT.set_size(get_option_value_int("Hash"));
380 if (button_was_pressed("Clear Hash"))
383 PonderingEnabled = get_option_value_bool("Ponder");
384 MultiPV = get_option_value_int("MultiPV");
386 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
387 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
389 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
390 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
392 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
393 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
395 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
396 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
398 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
399 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
401 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
402 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
404 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
405 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
406 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
407 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
409 Chess960 = get_option_value_bool("UCI_Chess960");
410 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
411 UseLogFile = get_option_value_bool("Use Search Log");
413 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
415 UseNullDrivenIID = get_option_value_bool("Null driven IID");
416 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
417 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
419 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
420 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
421 for (int i = 0; i < 6; i++)
422 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
424 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
425 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
427 UseLSNFiltering = get_option_value_bool("LSN filtering");
428 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
429 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
431 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
432 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
434 read_weights(pos.side_to_move());
436 int newActiveThreads = get_option_value_int("Threads");
437 if (newActiveThreads != ActiveThreads)
439 ActiveThreads = newActiveThreads;
440 init_eval(ActiveThreads);
443 // Wake up sleeping threads:
444 wake_sleeping_threads();
446 for (int i = 1; i < ActiveThreads; i++)
447 assert(thread_is_available(i, 0));
449 // Set thinking time:
450 int myTime = time[side_to_move];
451 int myIncrement = increment[side_to_move];
453 if (!movesToGo) // Sudden death time control
457 MaxSearchTime = myTime / 30 + myIncrement;
458 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
459 } else { // Blitz game without increment
460 MaxSearchTime = myTime / 30;
461 AbsoluteMaxSearchTime = myTime / 8;
464 else // (x moves) / (y minutes)
468 MaxSearchTime = myTime / 2;
469 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
471 MaxSearchTime = myTime / Min(movesToGo, 20);
472 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
476 if (PonderingEnabled)
478 MaxSearchTime += MaxSearchTime / 4;
479 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
482 // Fixed depth or fixed number of nodes?
485 InfiniteSearch = true; // HACK
490 NodesBetweenPolls = Min(MaxNodes, 30000);
491 InfiniteSearch = true; // HACK
494 NodesBetweenPolls = 30000;
497 // Write information to search log file:
499 LogFile << "Searching: " << pos.to_fen() << std::endl
500 << "infinite: " << infinite
501 << " ponder: " << ponder
502 << " time: " << myTime
503 << " increment: " << myIncrement
504 << " moves to go: " << movesToGo << std::endl;
507 // We're ready to start thinking. Call the iterative deepening loop
511 Value v = id_loop(pos, searchMoves);
512 looseOnTime = ( UseLSNFiltering
519 looseOnTime = false; // reset for next match
520 while (SearchStartTime + myTime + 1000 > get_system_time())
522 id_loop(pos, searchMoves); // to fail gracefully
539 /// init_threads() is called during startup. It launches all helper threads,
540 /// and initializes the split point stack and the global locks and condition
543 void init_threads() {
547 #if !defined(_MSC_VER)
548 pthread_t pthread[1];
551 for (i = 0; i < THREAD_MAX; i++)
552 Threads[i].activeSplitPoints = 0;
554 // Initialize global locks:
555 lock_init(&MPLock, NULL);
556 lock_init(&IOLock, NULL);
558 init_split_point_stack();
560 #if !defined(_MSC_VER)
561 pthread_mutex_init(&WaitLock, NULL);
562 pthread_cond_init(&WaitCond, NULL);
564 for (i = 0; i < THREAD_MAX; i++)
565 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
568 // All threads except the main thread should be initialized to idle state
569 for (i = 1; i < THREAD_MAX; i++)
571 Threads[i].stop = false;
572 Threads[i].workIsWaiting = false;
573 Threads[i].idle = true;
574 Threads[i].running = false;
577 // Launch the helper threads
578 for(i = 1; i < THREAD_MAX; i++)
580 #if !defined(_MSC_VER)
581 pthread_create(pthread, NULL, init_thread, (void*)(&i));
584 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
587 // Wait until the thread has finished launching:
588 while (!Threads[i].running);
591 // Init also the empty search stack
592 init_search_stack(EmptySearchStack);
596 /// stop_threads() is called when the program exits. It makes all the
597 /// helper threads exit cleanly.
599 void stop_threads() {
601 ActiveThreads = THREAD_MAX; // HACK
602 Idle = false; // HACK
603 wake_sleeping_threads();
604 AllThreadsShouldExit = true;
605 for (int i = 1; i < THREAD_MAX; i++)
607 Threads[i].stop = true;
608 while(Threads[i].running);
610 destroy_split_point_stack();
614 /// nodes_searched() returns the total number of nodes searched so far in
615 /// the current search.
617 int64_t nodes_searched() {
619 int64_t result = 0ULL;
620 for (int i = 0; i < ActiveThreads; i++)
621 result += Threads[i].nodes;
628 // id_loop() is the main iterative deepening loop. It calls root_search
629 // repeatedly with increasing depth until the allocated thinking time has
630 // been consumed, the user stops the search, or the maximum search depth is
633 Value id_loop(const Position &pos, Move searchMoves[]) {
636 SearchStack ss[PLY_MAX_PLUS_2];
638 // searchMoves are verified, copied, scored and sorted
639 RootMoveList rml(p, searchMoves);
644 init_search_stack(ss);
646 ValueByIteration[0] = Value(0);
647 ValueByIteration[1] = rml.get_move_score(0);
649 LastIterations = false;
651 EasyMove = rml.scan_for_easy_move();
653 // Iterative deepening loop
654 while (!AbortSearch && Iteration < PLY_MAX)
656 // Initialize iteration
659 BestMoveChangesByIteration[Iteration] = 0;
663 std::cout << "info depth " << Iteration << std::endl;
665 // Search to the current depth
666 ValueByIteration[Iteration] = root_search(p, ss, rml);
668 // Erase the easy move if it differs from the new best move
669 if (ss[0].pv[0] != EasyMove)
670 EasyMove = MOVE_NONE;
677 bool stopSearch = false;
679 // Stop search early if there is only a single legal move:
680 if (Iteration >= 6 && rml.move_count() == 1)
683 // Stop search early when the last two iterations returned a mate score
685 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
686 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
689 // Stop search early if one move seems to be much better than the rest
690 int64_t nodes = nodes_searched();
692 && EasyMove == ss[0].pv[0]
693 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
694 && current_search_time() > MaxSearchTime / 16)
695 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
696 && current_search_time() > MaxSearchTime / 32)))
699 // Add some extra time if the best move has changed during the last two iterations
700 if (Iteration > 5 && Iteration <= 50)
701 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
702 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
704 // Try to guess if the current iteration is the last one or the last two
705 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
707 // Stop search if most of MaxSearchTime is consumed at the end of the
708 // iteration. We probably don't have enough time to search the first
709 // move at the next iteration anyway.
710 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
718 StopOnPonderhit = true;
721 // Write PV to transposition table, in case the relevant entries have
722 // been overwritten during the search:
723 TT.insert_pv(p, ss[0].pv);
725 if (MaxDepth && Iteration >= MaxDepth)
731 // If we are pondering, we shouldn't print the best move before we
734 wait_for_stop_or_ponderhit();
736 // Print final search statistics
737 std::cout << "info nodes " << nodes_searched()
739 << " time " << current_search_time()
740 << " hashfull " << TT.full() << std::endl;
742 // Print the best move and the ponder move to the standard output
743 std::cout << "bestmove " << ss[0].pv[0];
744 if (ss[0].pv[1] != MOVE_NONE)
745 std::cout << " ponder " << ss[0].pv[1];
747 std::cout << std::endl;
752 dbg_print_mean(LogFile);
754 if (dbg_show_hit_rate)
755 dbg_print_hit_rate(LogFile);
758 LogFile << "Nodes: " << nodes_searched() << std::endl
759 << "Nodes/second: " << nps() << std::endl
760 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
762 p.do_move(ss[0].pv[0], u);
763 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
764 << std::endl << std::endl;
766 return rml.get_move_score(0);
770 // root_search() is the function which searches the root node. It is
771 // similar to search_pv except that it uses a different move ordering
772 // scheme (perhaps we should try to use this at internal PV nodes, too?)
773 // and prints some information to the standard output.
775 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
777 Value alpha = -VALUE_INFINITE;
778 Value beta = VALUE_INFINITE, value;
779 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
781 // Loop through all the moves in the root move list
782 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
789 RootMoveNumber = i + 1;
792 // Remember the node count before the move is searched. The node counts
793 // are used to sort the root moves at the next iteration.
794 nodes = nodes_searched();
796 // Reset beta cut-off counters
799 // Pick the next root move, and print the move and the move number to
800 // the standard output.
801 move = ss[0].currentMove = rml.get_move(i);
802 if (current_search_time() >= 1000)
803 std::cout << "info currmove " << move
804 << " currmovenumber " << i + 1 << std::endl;
806 // Decide search depth for this move
808 ext = extension(pos, move, true, pos.move_is_check(move), false, false, &dangerous);
809 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
811 // Make the move, and search it
812 pos.do_move(move, u, dcCandidates);
816 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
817 // If the value has dropped a lot compared to the last iteration,
818 // set the boolean variable Problem to true. This variable is used
819 // for time managment: When Problem is true, we try to complete the
820 // current iteration before playing a move.
821 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
823 if (Problem && StopOnPonderhit)
824 StopOnPonderhit = false;
828 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
831 // Fail high! Set the boolean variable FailHigh to true, and
832 // re-search the move with a big window. The variable FailHigh is
833 // used for time managment: We try to avoid aborting the search
834 // prematurely during a fail high research.
836 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
840 pos.undo_move(move, u);
842 // Finished searching the move. If AbortSearch is true, the search
843 // was aborted because the user interrupted the search or because we
844 // ran out of time. In this case, the return value of the search cannot
845 // be trusted, and we break out of the loop without updating the best
850 // Remember the node count for this move. The node counts are used to
851 // sort the root moves at the next iteration.
852 rml.set_move_nodes(i, nodes_searched() - nodes);
854 // Remember the beta-cutoff statistics
856 BetaCounter.read(pos.side_to_move(), our, their);
857 rml.set_beta_counters(i, our, their);
859 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
861 if (value <= alpha && i >= MultiPV)
862 rml.set_move_score(i, -VALUE_INFINITE);
868 rml.set_move_score(i, value);
870 rml.set_move_pv(i, ss[0].pv);
874 // We record how often the best move has been changed in each
875 // iteration. This information is used for time managment: When
876 // the best move changes frequently, we allocate some more time.
878 BestMoveChangesByIteration[Iteration]++;
880 // Print search information to the standard output:
881 std::cout << "info depth " << Iteration
882 << " score " << value_to_string(value)
883 << " time " << current_search_time()
884 << " nodes " << nodes_searched()
888 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
889 std::cout << ss[0].pv[j] << " ";
891 std::cout << std::endl;
894 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
899 // Reset the global variable Problem to false if the value isn't too
900 // far below the final value from the last iteration.
901 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
907 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
910 std::cout << "info multipv " << j + 1
911 << " score " << value_to_string(rml.get_move_score(j))
912 << " depth " << ((j <= i)? Iteration : Iteration - 1)
913 << " time " << current_search_time()
914 << " nodes " << nodes_searched()
918 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
919 std::cout << rml.get_move_pv(j, k) << " ";
921 std::cout << std::endl;
923 alpha = rml.get_move_score(Min(i, MultiPV-1));
931 // search_pv() is the main search function for PV nodes.
933 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
934 Depth depth, int ply, int threadID) {
936 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
937 assert(beta > alpha && beta <= VALUE_INFINITE);
938 assert(ply >= 0 && ply < PLY_MAX);
939 assert(threadID >= 0 && threadID < ActiveThreads);
942 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
944 // Initialize, and make an early exit in case of an aborted search,
945 // an instant draw, maximum ply reached, etc.
946 init_node(pos, ss, ply, threadID);
948 // After init_node() that calls poll()
949 if (AbortSearch || thread_should_stop(threadID))
957 if (ply >= PLY_MAX - 1)
958 return evaluate(pos, ei, threadID);
960 // Mate distance pruning
961 Value oldAlpha = alpha;
962 alpha = Max(value_mated_in(ply), alpha);
963 beta = Min(value_mate_in(ply+1), beta);
967 // Transposition table lookup. At PV nodes, we don't use the TT for
968 // pruning, but only for move ordering.
969 const TTEntry* tte = TT.retrieve(pos);
970 Move ttMove = (tte ? tte->move() : MOVE_NONE);
972 // Go with internal iterative deepening if we don't have a TT move
973 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
975 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
976 ttMove = ss[ply].pv[ply];
979 // Initialize a MovePicker object for the current position, and prepare
980 // to search all moves
981 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
983 Move move, movesSearched[256];
985 Value value, bestValue = -VALUE_INFINITE;
986 Bitboard dcCandidates = mp.discovered_check_candidates();
987 bool isCheck = pos.is_check();
988 bool mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
990 // Loop through all legal moves until no moves remain or a beta cutoff
993 && (move = mp.get_next_move()) != MOVE_NONE
994 && !thread_should_stop(threadID))
996 assert(move_is_ok(move));
998 bool singleReply = (isCheck && mp.number_of_moves() == 1);
999 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1000 bool moveIsCapture = pos.move_is_capture(move);
1002 movesSearched[moveCount++] = ss[ply].currentMove = move;
1005 ss[ply].currentMoveCaptureValue =
1006 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1008 ss[ply].currentMoveCaptureValue = Value(0);
1010 // Decide the new search depth
1012 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat, &dangerous);
1013 Depth newDepth = depth - OnePly + ext;
1015 // Make and search the move
1017 pos.do_move(move, u, dcCandidates);
1019 if (moveCount == 1) // The first move in list is the PV
1020 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1023 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1024 // if the move fails high will be re-searched at full depth.
1025 if ( depth >= 2*OnePly
1026 && moveCount >= LMRPVMoves
1029 && !move_promotion(move)
1030 && !move_is_castle(move)
1031 && !move_is_killer(move, ss[ply]))
1033 ss[ply].reduction = OnePly;
1034 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1037 value = alpha + 1; // Just to trigger next condition
1039 if (value > alpha) // Go with full depth non-pv search
1041 ss[ply].reduction = Depth(0);
1042 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1043 if (value > alpha && value < beta)
1045 // When the search fails high at ply 1 while searching the first
1046 // move at the root, set the flag failHighPly1. This is used for
1047 // time managment: We don't want to stop the search early in
1048 // such cases, because resolving the fail high at ply 1 could
1049 // result in a big drop in score at the root.
1050 if (ply == 1 && RootMoveNumber == 1)
1051 Threads[threadID].failHighPly1 = true;
1053 // A fail high occurred. Re-search at full window (pv search)
1054 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1055 Threads[threadID].failHighPly1 = false;
1059 pos.undo_move(move, u);
1061 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1064 if (value > bestValue)
1071 if (value == value_mate_in(ply + 1))
1072 ss[ply].mateKiller = move;
1074 // If we are at ply 1, and we are searching the first root move at
1075 // ply 0, set the 'Problem' variable if the score has dropped a lot
1076 // (from the computer's point of view) since the previous iteration:
1079 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1084 if ( ActiveThreads > 1
1086 && depth >= MinimumSplitDepth
1088 && idle_thread_exists(threadID)
1090 && !thread_should_stop(threadID)
1091 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1092 &moveCount, &mp, dcCandidates, threadID, true))
1096 // All legal moves have been searched. A special case: If there were
1097 // no legal moves, it must be mate or stalemate:
1099 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1101 // If the search is not aborted, update the transposition table,
1102 // history counters, and killer moves.
1103 if (AbortSearch || thread_should_stop(threadID))
1106 if (bestValue <= oldAlpha)
1107 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1109 else if (bestValue >= beta)
1111 BetaCounter.add(pos.side_to_move(), depth, threadID);
1112 Move m = ss[ply].pv[ply];
1113 if (ok_to_history(pos, m)) // Only non capture moves are considered
1115 update_history(pos, m, depth, movesSearched, moveCount);
1116 update_killers(m, ss[ply]);
1118 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1121 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1127 // search() is the search function for zero-width nodes.
1129 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1130 int ply, bool allowNullmove, int threadID) {
1132 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1133 assert(ply >= 0 && ply < PLY_MAX);
1134 assert(threadID >= 0 && threadID < ActiveThreads);
1137 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1139 // Initialize, and make an early exit in case of an aborted search,
1140 // an instant draw, maximum ply reached, etc.
1141 init_node(pos, ss, ply, threadID);
1143 // After init_node() that calls poll()
1144 if (AbortSearch || thread_should_stop(threadID))
1152 if (ply >= PLY_MAX - 1)
1153 return evaluate(pos, ei, threadID);
1155 // Mate distance pruning
1156 if (value_mated_in(ply) >= beta)
1159 if (value_mate_in(ply + 1) < beta)
1162 // Transposition table lookup
1163 const TTEntry* tte = TT.retrieve(pos);
1164 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1166 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1168 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1169 return value_from_tt(tte->value(), ply);
1172 Value approximateEval = quick_evaluate(pos);
1173 bool mateThreat = false;
1174 bool nullDrivenIID = false;
1175 bool isCheck = pos.is_check();
1181 && !value_is_mate(beta)
1182 && ok_to_do_nullmove(pos)
1183 && approximateEval >= beta - NullMoveMargin)
1185 ss[ply].currentMove = MOVE_NULL;
1188 pos.do_null_move(u);
1189 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1191 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1193 // Check for a null capture artifact, if the value without the null capture
1194 // is above beta then mark the node as a suspicious failed low. We will verify
1195 // later if we are really under threat.
1196 if ( UseNullDrivenIID
1198 && depth > 6 * OnePly
1199 &&!value_is_mate(nullValue)
1200 && ttMove == MOVE_NONE
1201 && ss[ply + 1].currentMove != MOVE_NONE
1202 && pos.move_is_capture(ss[ply + 1].currentMove)
1203 && pos.see(ss[ply + 1].currentMove) + nullValue >= beta)
1204 nullDrivenIID = true;
1206 pos.undo_null_move(u);
1208 if (value_is_mate(nullValue))
1210 /* Do not return unproven mates */
1212 else if (nullValue >= beta)
1214 if (depth < 6 * OnePly)
1217 // Do zugzwang verification search
1218 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1222 // The null move failed low, which means that we may be faced with
1223 // some kind of threat. If the previous move was reduced, check if
1224 // the move that refuted the null move was somehow connected to the
1225 // move which was reduced. If a connection is found, return a fail
1226 // low score (which will cause the reduced move to fail high in the
1227 // parent node, which will trigger a re-search with full depth).
1228 if (nullValue == value_mated_in(ply + 2))
1231 nullDrivenIID = false;
1233 ss[ply].threatMove = ss[ply + 1].currentMove;
1234 if ( depth < ThreatDepth
1235 && ss[ply - 1].reduction
1236 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1240 // Null move search not allowed, try razoring
1241 else if ( !value_is_mate(beta)
1242 && approximateEval < beta - RazorMargin
1243 && depth < RazorDepth
1244 && (RazorAtDepthOne || depth > OnePly)
1245 && ttMove == MOVE_NONE
1246 && !pos.has_pawn_on_7th(pos.side_to_move()))
1248 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1249 if ( (v < beta - RazorMargin - RazorMargin / 4)
1250 || (depth < 3*OnePly && v < beta - RazorMargin)
1251 || (depth < 2*OnePly && v < beta - RazorMargin / 2))
1255 // Go with internal iterative deepening if we don't have a TT move
1256 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1257 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1259 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1260 ttMove = ss[ply].pv[ply];
1262 else if (nullDrivenIID)
1264 // The null move failed low due to a suspicious capture. Perhaps we
1265 // are facing a null capture artifact due to the side to move change
1266 // and this position should fail high. So do a normal search with a
1267 // reduced depth to get a good ttMove to use in the following full
1269 Move tm = ss[ply].threatMove;
1271 assert(tm != MOVE_NONE);
1272 assert(ttMove == MOVE_NONE);
1274 search(pos, ss, beta, depth/2, ply, false, threadID);
1275 ttMove = ss[ply].pv[ply];
1276 ss[ply].threatMove = tm;
1279 // Initialize a MovePicker object for the current position, and prepare
1280 // to search all moves:
1281 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1283 Move move, movesSearched[256];
1285 Value value, bestValue = -VALUE_INFINITE;
1286 Bitboard dcCandidates = mp.discovered_check_candidates();
1287 Value futilityValue = VALUE_NONE;
1288 bool useFutilityPruning = UseFutilityPruning
1289 && depth < SelectiveDepth
1292 // Loop through all legal moves until no moves remain or a beta cutoff
1294 while ( bestValue < beta
1295 && (move = mp.get_next_move()) != MOVE_NONE
1296 && !thread_should_stop(threadID))
1298 assert(move_is_ok(move));
1300 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1301 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1302 bool moveIsCapture = pos.move_is_capture(move);
1304 movesSearched[moveCount++] = ss[ply].currentMove = move;
1306 // Decide the new search depth
1308 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat, &dangerous);
1309 Depth newDepth = depth - OnePly + ext;
1312 if ( useFutilityPruning
1315 && !move_promotion(move))
1317 // History pruning. See ok_to_prune() definition
1318 if ( moveCount >= 2 + int(depth)
1319 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1322 // Value based pruning
1323 if (depth < 7 * OnePly && approximateEval < beta)
1325 if (futilityValue == VALUE_NONE)
1326 futilityValue = evaluate(pos, ei, threadID)
1327 + FutilityMargins[int(depth)/2 - 1]
1330 if (futilityValue < beta)
1332 if (futilityValue > bestValue)
1333 bestValue = futilityValue;
1339 // Make and search the move
1341 pos.do_move(move, u, dcCandidates);
1343 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1344 // if the move fails high will be re-searched at full depth.
1345 if ( depth >= 2*OnePly
1346 && moveCount >= LMRNonPVMoves
1349 && !move_promotion(move)
1350 && !move_is_castle(move)
1351 && !move_is_killer(move, ss[ply]))
1353 ss[ply].reduction = OnePly;
1354 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1357 value = beta; // Just to trigger next condition
1359 if (value >= beta) // Go with full depth non-pv search
1361 ss[ply].reduction = Depth(0);
1362 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1364 pos.undo_move(move, u);
1366 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1369 if (value > bestValue)
1375 if (value == value_mate_in(ply + 1))
1376 ss[ply].mateKiller = move;
1380 if ( ActiveThreads > 1
1382 && depth >= MinimumSplitDepth
1384 && idle_thread_exists(threadID)
1386 && !thread_should_stop(threadID)
1387 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1388 &mp, dcCandidates, threadID, false))
1392 // All legal moves have been searched. A special case: If there were
1393 // no legal moves, it must be mate or stalemate.
1395 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1397 // If the search is not aborted, update the transposition table,
1398 // history counters, and killer moves.
1399 if (AbortSearch || thread_should_stop(threadID))
1402 if (bestValue < beta)
1403 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1406 BetaCounter.add(pos.side_to_move(), depth, threadID);
1407 Move m = ss[ply].pv[ply];
1408 if (ok_to_history(pos, m)) // Only non capture moves are considered
1410 update_history(pos, m, depth, movesSearched, moveCount);
1411 update_killers(m, ss[ply]);
1413 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1419 // qsearch() is the quiescence search function, which is called by the main
1420 // search function when the remaining depth is zero (or, to be more precise,
1421 // less than OnePly).
1423 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1424 Depth depth, int ply, int threadID) {
1426 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1427 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1429 assert(ply >= 0 && ply < PLY_MAX);
1430 assert(threadID >= 0 && threadID < ActiveThreads);
1432 // Initialize, and make an early exit in case of an aborted search,
1433 // an instant draw, maximum ply reached, etc.
1434 init_node(pos, ss, ply, threadID);
1436 // After init_node() that calls poll()
1437 if (AbortSearch || thread_should_stop(threadID))
1443 // Transposition table lookup
1444 const TTEntry* tte = TT.retrieve(pos);
1445 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1446 return value_from_tt(tte->value(), ply);
1448 // Evaluate the position statically
1450 bool isCheck = pos.is_check();
1451 Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1453 if (ply == PLY_MAX - 1)
1454 return evaluate(pos, ei, threadID);
1456 // Initialize "stand pat score", and return it immediately if it is
1458 Value bestValue = staticValue;
1460 if (bestValue >= beta)
1463 if (bestValue > alpha)
1466 // Initialize a MovePicker object for the current position, and prepare
1467 // to search the moves. Because the depth is <= 0 here, only captures,
1468 // queen promotions and checks (only if depth == 0) will be generated.
1469 bool pvNode = (beta - alpha != 1);
1470 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1473 Bitboard dcCandidates = mp.discovered_check_candidates();
1474 bool enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1476 // Loop through the moves until no moves remain or a beta cutoff
1478 while ( alpha < beta
1479 && (move = mp.get_next_move()) != MOVE_NONE)
1481 assert(move_is_ok(move));
1484 ss[ply].currentMove = move;
1487 if ( UseQSearchFutilityPruning
1491 && !move_promotion(move)
1492 && !pos.move_is_check(move, dcCandidates)
1493 && !pos.move_is_passed_pawn_push(move))
1495 Value futilityValue = staticValue
1496 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1497 pos.endgame_value_of_piece_on(move_to(move)))
1498 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1500 + ei.futilityMargin;
1502 if (futilityValue < alpha)
1504 if (futilityValue > bestValue)
1505 bestValue = futilityValue;
1510 // Don't search captures and checks with negative SEE values
1512 && !move_promotion(move)
1513 && (pos.midgame_value_of_piece_on(move_from(move)) >
1514 pos.midgame_value_of_piece_on(move_to(move)))
1515 && pos.see(move) < 0)
1518 // Make and search the move.
1520 pos.do_move(move, u, dcCandidates);
1521 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1522 pos.undo_move(move, u);
1524 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1527 if (value > bestValue)
1538 // All legal moves have been searched. A special case: If we're in check
1539 // and no legal moves were found, it is checkmate:
1540 if (pos.is_check() && moveCount == 0) // Mate!
1541 return value_mated_in(ply);
1543 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1545 // Update transposition table
1546 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1548 // Update killers only for good check moves
1549 Move m = ss[ply].currentMove;
1550 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1552 // Wrong to update history when depth is <= 0
1553 update_killers(m, ss[ply]);
1559 // sp_search() is used to search from a split point. This function is called
1560 // by each thread working at the split point. It is similar to the normal
1561 // search() function, but simpler. Because we have already probed the hash
1562 // table, done a null move search, and searched the first move before
1563 // splitting, we don't have to repeat all this work in sp_search(). We
1564 // also don't need to store anything to the hash table here: This is taken
1565 // care of after we return from the split point.
1567 void sp_search(SplitPoint *sp, int threadID) {
1569 assert(threadID >= 0 && threadID < ActiveThreads);
1570 assert(ActiveThreads > 1);
1572 Position pos = Position(sp->pos);
1573 SearchStack *ss = sp->sstack[threadID];
1576 bool isCheck = pos.is_check();
1577 bool useFutilityPruning = UseFutilityPruning
1578 && sp->depth < SelectiveDepth
1581 while ( sp->bestValue < sp->beta
1582 && !thread_should_stop(threadID)
1583 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1585 assert(move_is_ok(move));
1587 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1588 bool moveIsCapture = pos.move_is_capture(move);
1590 lock_grab(&(sp->lock));
1591 int moveCount = ++sp->moves;
1592 lock_release(&(sp->lock));
1594 ss[sp->ply].currentMove = move;
1596 // Decide the new search depth.
1598 Depth ext = extension(pos, move, false, moveIsCheck, false, false, &dangerous);
1599 Depth newDepth = sp->depth - OnePly + ext;
1602 if ( useFutilityPruning
1605 && !move_promotion(move)
1606 && moveCount >= 2 + int(sp->depth)
1607 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1610 // Make and search the move.
1612 pos.do_move(move, u, sp->dcCandidates);
1614 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1615 // if the move fails high will be re-searched at full depth.
1617 && moveCount >= LMRNonPVMoves
1619 && !move_promotion(move)
1620 && !move_is_castle(move)
1621 && !move_is_killer(move, ss[sp->ply]))
1623 ss[sp->ply].reduction = OnePly;
1624 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1627 value = sp->beta; // Just to trigger next condition
1629 if (value >= sp->beta) // Go with full depth non-pv search
1631 ss[sp->ply].reduction = Depth(0);
1632 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1634 pos.undo_move(move, u);
1636 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1638 if (thread_should_stop(threadID))
1642 lock_grab(&(sp->lock));
1643 if (value > sp->bestValue && !thread_should_stop(threadID))
1645 sp->bestValue = value;
1646 if (sp->bestValue >= sp->beta)
1648 sp_update_pv(sp->parentSstack, ss, sp->ply);
1649 for (int i = 0; i < ActiveThreads; i++)
1650 if (i != threadID && (i == sp->master || sp->slaves[i]))
1651 Threads[i].stop = true;
1653 sp->finished = true;
1656 lock_release(&(sp->lock));
1659 lock_grab(&(sp->lock));
1661 // If this is the master thread and we have been asked to stop because of
1662 // a beta cutoff higher up in the tree, stop all slave threads:
1663 if (sp->master == threadID && thread_should_stop(threadID))
1664 for (int i = 0; i < ActiveThreads; i++)
1666 Threads[i].stop = true;
1669 sp->slaves[threadID] = 0;
1671 lock_release(&(sp->lock));
1675 // sp_search_pv() is used to search from a PV split point. This function
1676 // is called by each thread working at the split point. It is similar to
1677 // the normal search_pv() function, but simpler. Because we have already
1678 // probed the hash table and searched the first move before splitting, we
1679 // don't have to repeat all this work in sp_search_pv(). We also don't
1680 // need to store anything to the hash table here: This is taken care of
1681 // after we return from the split point.
1683 void sp_search_pv(SplitPoint *sp, int threadID) {
1685 assert(threadID >= 0 && threadID < ActiveThreads);
1686 assert(ActiveThreads > 1);
1688 Position pos = Position(sp->pos);
1689 SearchStack *ss = sp->sstack[threadID];
1693 while ( sp->alpha < sp->beta
1694 && !thread_should_stop(threadID)
1695 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1697 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1698 bool moveIsCapture = pos.move_is_capture(move);
1700 assert(move_is_ok(move));
1703 ss[sp->ply].currentMoveCaptureValue =
1704 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1706 ss[sp->ply].currentMoveCaptureValue = Value(0);
1708 lock_grab(&(sp->lock));
1709 int moveCount = ++sp->moves;
1710 lock_release(&(sp->lock));
1712 ss[sp->ply].currentMove = move;
1714 // Decide the new search depth.
1716 Depth ext = extension(pos, move, true, moveIsCheck, false, false, &dangerous);
1717 Depth newDepth = sp->depth - OnePly + ext;
1719 // Make and search the move.
1721 pos.do_move(move, u, sp->dcCandidates);
1723 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1724 // if the move fails high will be re-searched at full depth.
1726 && moveCount >= LMRPVMoves
1728 && !move_promotion(move)
1729 && !move_is_castle(move)
1730 && !move_is_killer(move, ss[sp->ply]))
1732 ss[sp->ply].reduction = OnePly;
1733 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1736 value = sp->alpha + 1; // Just to trigger next condition
1738 if (value > sp->alpha) // Go with full depth non-pv search
1740 ss[sp->ply].reduction = Depth(0);
1741 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1743 if (value > sp->alpha && value < sp->beta)
1745 // When the search fails high at ply 1 while searching the first
1746 // move at the root, set the flag failHighPly1. This is used for
1747 // time managment: We don't want to stop the search early in
1748 // such cases, because resolving the fail high at ply 1 could
1749 // result in a big drop in score at the root.
1750 if (sp->ply == 1 && RootMoveNumber == 1)
1751 Threads[threadID].failHighPly1 = true;
1753 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1754 Threads[threadID].failHighPly1 = false;
1757 pos.undo_move(move, u);
1759 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1761 if (thread_should_stop(threadID))
1765 lock_grab(&(sp->lock));
1766 if (value > sp->bestValue && !thread_should_stop(threadID))
1768 sp->bestValue = value;
1769 if (value > sp->alpha)
1772 sp_update_pv(sp->parentSstack, ss, sp->ply);
1773 if (value == value_mate_in(sp->ply + 1))
1774 ss[sp->ply].mateKiller = move;
1776 if(value >= sp->beta)
1778 for(int i = 0; i < ActiveThreads; i++)
1779 if(i != threadID && (i == sp->master || sp->slaves[i]))
1780 Threads[i].stop = true;
1782 sp->finished = true;
1785 // If we are at ply 1, and we are searching the first root move at
1786 // ply 0, set the 'Problem' variable if the score has dropped a lot
1787 // (from the computer's point of view) since the previous iteration.
1790 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1793 lock_release(&(sp->lock));
1796 lock_grab(&(sp->lock));
1798 // If this is the master thread and we have been asked to stop because of
1799 // a beta cutoff higher up in the tree, stop all slave threads.
1800 if (sp->master == threadID && thread_should_stop(threadID))
1801 for (int i = 0; i < ActiveThreads; i++)
1803 Threads[i].stop = true;
1806 sp->slaves[threadID] = 0;
1808 lock_release(&(sp->lock));
1811 /// The BetaCounterType class
1813 BetaCounterType::BetaCounterType() { clear(); }
1815 void BetaCounterType::clear() {
1817 for (int i = 0; i < THREAD_MAX; i++)
1818 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1821 void BetaCounterType::add(Color us, Depth d, int threadID) {
1823 // Weighted count based on depth
1824 hits[threadID][us] += int(d);
1827 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1830 for (int i = 0; i < THREAD_MAX; i++)
1833 their += hits[i][opposite_color(us)];
1838 /// The RootMove class
1842 RootMove::RootMove() {
1843 nodes = cumulativeNodes = 0ULL;
1846 // RootMove::operator<() is the comparison function used when
1847 // sorting the moves. A move m1 is considered to be better
1848 // than a move m2 if it has a higher score, or if the moves
1849 // have equal score but m1 has the higher node count.
1851 bool RootMove::operator<(const RootMove& m) {
1853 if (score != m.score)
1854 return (score < m.score);
1856 return theirBeta <= m.theirBeta;
1859 /// The RootMoveList class
1863 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1865 MoveStack mlist[MaxRootMoves];
1866 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1868 // Generate all legal moves
1869 int lm_count = generate_legal_moves(pos, mlist);
1871 // Add each move to the moves[] array
1872 for (int i = 0; i < lm_count; i++)
1874 bool includeMove = includeAllMoves;
1876 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1877 includeMove = (searchMoves[k] == mlist[i].move);
1881 // Find a quick score for the move
1883 SearchStack ss[PLY_MAX_PLUS_2];
1885 moves[count].move = mlist[i].move;
1886 moves[count].nodes = 0ULL;
1887 pos.do_move(moves[count].move, u);
1888 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1890 pos.undo_move(moves[count].move, u);
1891 moves[count].pv[0] = moves[i].move;
1892 moves[count].pv[1] = MOVE_NONE; // FIXME
1900 // Simple accessor methods for the RootMoveList class
1902 inline Move RootMoveList::get_move(int moveNum) const {
1903 return moves[moveNum].move;
1906 inline Value RootMoveList::get_move_score(int moveNum) const {
1907 return moves[moveNum].score;
1910 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1911 moves[moveNum].score = score;
1914 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1915 moves[moveNum].nodes = nodes;
1916 moves[moveNum].cumulativeNodes += nodes;
1919 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1920 moves[moveNum].ourBeta = our;
1921 moves[moveNum].theirBeta = their;
1924 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1926 for(j = 0; pv[j] != MOVE_NONE; j++)
1927 moves[moveNum].pv[j] = pv[j];
1928 moves[moveNum].pv[j] = MOVE_NONE;
1931 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1932 return moves[moveNum].pv[i];
1935 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1936 return moves[moveNum].cumulativeNodes;
1939 inline int RootMoveList::move_count() const {
1944 // RootMoveList::scan_for_easy_move() is called at the end of the first
1945 // iteration, and is used to detect an "easy move", i.e. a move which appears
1946 // to be much bester than all the rest. If an easy move is found, the move
1947 // is returned, otherwise the function returns MOVE_NONE. It is very
1948 // important that this function is called at the right moment: The code
1949 // assumes that the first iteration has been completed and the moves have
1950 // been sorted. This is done in RootMoveList c'tor.
1952 Move RootMoveList::scan_for_easy_move() const {
1959 // moves are sorted so just consider the best and the second one
1960 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1966 // RootMoveList::sort() sorts the root move list at the beginning of a new
1969 inline void RootMoveList::sort() {
1971 sort_multipv(count - 1); // all items
1975 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1976 // list by their scores and depths. It is used to order the different PVs
1977 // correctly in MultiPV mode.
1979 void RootMoveList::sort_multipv(int n) {
1981 for (int i = 1; i <= n; i++)
1983 RootMove rm = moves[i];
1985 for (j = i; j > 0 && moves[j-1] < rm; j--)
1986 moves[j] = moves[j-1];
1992 // init_search_stack() initializes a search stack at the beginning of a
1993 // new search from the root.
1994 void init_search_stack(SearchStack& ss) {
1996 ss.pv[0] = MOVE_NONE;
1997 ss.pv[1] = MOVE_NONE;
1998 ss.currentMove = MOVE_NONE;
1999 ss.threatMove = MOVE_NONE;
2000 ss.reduction = Depth(0);
2001 for (int j = 0; j < KILLER_MAX; j++)
2002 ss.killers[j] = MOVE_NONE;
2005 void init_search_stack(SearchStack ss[]) {
2007 for (int i = 0; i < 3; i++)
2009 ss[i].pv[i] = MOVE_NONE;
2010 ss[i].pv[i+1] = MOVE_NONE;
2011 ss[i].currentMove = MOVE_NONE;
2012 ss[i].threatMove = MOVE_NONE;
2013 ss[i].reduction = Depth(0);
2014 for (int j = 0; j < KILLER_MAX; j++)
2015 ss[i].killers[j] = MOVE_NONE;
2020 // init_node() is called at the beginning of all the search functions
2021 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2022 // stack object corresponding to the current node. Once every
2023 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2024 // for user input and checks whether it is time to stop the search.
2026 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2027 assert(ply >= 0 && ply < PLY_MAX);
2028 assert(threadID >= 0 && threadID < ActiveThreads);
2030 Threads[threadID].nodes++;
2034 if(NodesSincePoll >= NodesBetweenPolls) {
2039 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
2040 ss[ply+2].mateKiller = MOVE_NONE;
2041 ss[ply].threatMove = MOVE_NONE;
2042 ss[ply].reduction = Depth(0);
2043 ss[ply].currentMoveCaptureValue = Value(0);
2044 for (int j = 0; j < KILLER_MAX; j++)
2045 ss[ply+2].killers[j] = MOVE_NONE;
2047 if(Threads[threadID].printCurrentLine)
2048 print_current_line(ss, ply, threadID);
2052 // update_pv() is called whenever a search returns a value > alpha. It
2053 // updates the PV in the SearchStack object corresponding to the current
2056 void update_pv(SearchStack ss[], int ply) {
2057 assert(ply >= 0 && ply < PLY_MAX);
2059 ss[ply].pv[ply] = ss[ply].currentMove;
2061 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2062 ss[ply].pv[p] = ss[ply+1].pv[p];
2063 ss[ply].pv[p] = MOVE_NONE;
2067 // sp_update_pv() is a variant of update_pv for use at split points. The
2068 // difference between the two functions is that sp_update_pv also updates
2069 // the PV at the parent node.
2071 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2072 assert(ply >= 0 && ply < PLY_MAX);
2074 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2076 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2077 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2078 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2082 // connected_moves() tests whether two moves are 'connected' in the sense
2083 // that the first move somehow made the second move possible (for instance
2084 // if the moving piece is the same in both moves). The first move is
2085 // assumed to be the move that was made to reach the current position, while
2086 // the second move is assumed to be a move from the current position.
2088 bool connected_moves(const Position &pos, Move m1, Move m2) {
2089 Square f1, t1, f2, t2;
2091 assert(move_is_ok(m1));
2092 assert(move_is_ok(m2));
2097 // Case 1: The moving piece is the same in both moves.
2103 // Case 2: The destination square for m2 was vacated by m1.
2109 // Case 3: Moving through the vacated square:
2110 if(piece_is_slider(pos.piece_on(f2)) &&
2111 bit_is_set(squares_between(f2, t2), f1))
2114 // Case 4: The destination square for m2 is attacked by the moving piece
2116 if(pos.piece_attacks_square(t1, t2))
2119 // Case 5: Discovered check, checking piece is the piece moved in m1:
2120 if(piece_is_slider(pos.piece_on(t1)) &&
2121 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2123 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2125 Bitboard occ = pos.occupied_squares();
2126 Color us = pos.side_to_move();
2127 Square ksq = pos.king_square(us);
2128 clear_bit(&occ, f2);
2129 if(pos.type_of_piece_on(t1) == BISHOP) {
2130 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2133 else if(pos.type_of_piece_on(t1) == ROOK) {
2134 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2138 assert(pos.type_of_piece_on(t1) == QUEEN);
2139 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2148 // value_is_mate() checks if the given value is a mate one
2149 // eventually compensated for the ply.
2151 bool value_is_mate(Value value) {
2153 assert(abs(value) <= VALUE_INFINITE);
2155 return value <= value_mated_in(PLY_MAX)
2156 || value >= value_mate_in(PLY_MAX);
2160 // move_is_killer() checks if the given move is among the
2161 // killer moves of that ply.
2163 bool move_is_killer(Move m, const SearchStack& ss) {
2165 const Move* k = ss.killers;
2166 for (int i = 0; i < KILLER_MAX; i++, k++)
2174 // extension() decides whether a move should be searched with normal depth,
2175 // or with extended depth. Certain classes of moves (checking moves, in
2176 // particular) are searched with bigger depth than ordinary moves and in
2177 // any case are marked as 'dangerous'. Note that also if a move is not
2178 // extended, as example because the corresponding UCI option is set to zero,
2179 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2181 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
2182 bool singleReply, bool mateThreat, bool* dangerous) {
2184 assert(m != MOVE_NONE);
2186 Depth result = Depth(0);
2187 *dangerous = check || singleReply || mateThreat;
2190 result += CheckExtension[pvNode];
2193 result += SingleReplyExtension[pvNode];
2196 result += MateThreatExtension[pvNode];
2198 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2200 if (pos.move_is_pawn_push_to_7th(m))
2202 result += PawnPushTo7thExtension[pvNode];
2205 if (pos.move_is_passed_pawn_push(m))
2207 result += PassedPawnExtension[pvNode];
2212 if ( pos.move_is_capture(m)
2213 && pos.type_of_piece_on(move_to(m)) != PAWN
2214 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2215 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2216 && !move_promotion(m)
2219 result += PawnEndgameExtension[pvNode];
2224 && pos.move_is_capture(m)
2225 && pos.type_of_piece_on(move_to(m)) != PAWN
2232 return Min(result, OnePly);
2236 // ok_to_do_nullmove() looks at the current position and decides whether
2237 // doing a 'null move' should be allowed. In order to avoid zugzwang
2238 // problems, null moves are not allowed when the side to move has very
2239 // little material left. Currently, the test is a bit too simple: Null
2240 // moves are avoided only when the side to move has only pawns left. It's
2241 // probably a good idea to avoid null moves in at least some more
2242 // complicated endgames, e.g. KQ vs KR. FIXME
2244 bool ok_to_do_nullmove(const Position &pos) {
2245 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2251 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2252 // non-tactical moves late in the move list close to the leaves are
2253 // candidates for pruning.
2255 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2256 Square mfrom, mto, tfrom, tto;
2258 assert(move_is_ok(m));
2259 assert(threat == MOVE_NONE || move_is_ok(threat));
2260 assert(!move_promotion(m));
2261 assert(!pos.move_is_check(m));
2262 assert(!pos.move_is_capture(m));
2263 assert(!pos.move_is_passed_pawn_push(m));
2264 assert(d >= OnePly);
2266 mfrom = move_from(m);
2268 tfrom = move_from(threat);
2269 tto = move_to(threat);
2271 // Case 1: Castling moves are never pruned.
2272 if (move_is_castle(m))
2275 // Case 2: Don't prune moves which move the threatened piece
2276 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2279 // Case 3: If the threatened piece has value less than or equal to the
2280 // value of the threatening piece, don't prune move which defend it.
2281 if ( !PruneDefendingMoves
2282 && threat != MOVE_NONE
2283 && pos.move_is_capture(threat)
2284 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2285 || pos.type_of_piece_on(tfrom) == KING)
2286 && pos.move_attacks_square(m, tto))
2289 // Case 4: Don't prune moves with good history.
2290 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2293 // Case 5: If the moving piece in the threatened move is a slider, don't
2294 // prune safe moves which block its ray.
2295 if ( !PruneBlockingMoves
2296 && threat != MOVE_NONE
2297 && piece_is_slider(pos.piece_on(tfrom))
2298 && bit_is_set(squares_between(tfrom, tto), mto)
2306 // ok_to_use_TT() returns true if a transposition table score
2307 // can be used at a given point in search.
2309 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2311 Value v = value_from_tt(tte->value(), ply);
2313 return ( tte->depth() >= depth
2314 || v >= Max(value_mate_in(100), beta)
2315 || v < Min(value_mated_in(100), beta))
2317 && ( (is_lower_bound(tte->type()) && v >= beta)
2318 || (is_upper_bound(tte->type()) && v < beta));
2322 // ok_to_history() returns true if a move m can be stored
2323 // in history. Should be a non capturing move nor a promotion.
2325 bool ok_to_history(const Position& pos, Move m) {
2327 return !pos.move_is_capture(m) && !move_promotion(m);
2331 // update_history() registers a good move that produced a beta-cutoff
2332 // in history and marks as failures all the other moves of that ply.
2334 void update_history(const Position& pos, Move m, Depth depth,
2335 Move movesSearched[], int moveCount) {
2337 H.success(pos.piece_on(move_from(m)), m, depth);
2339 for (int i = 0; i < moveCount - 1; i++)
2341 assert(m != movesSearched[i]);
2342 if (ok_to_history(pos, movesSearched[i]))
2343 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2348 // update_killers() add a good move that produced a beta-cutoff
2349 // among the killer moves of that ply.
2351 void update_killers(Move m, SearchStack& ss) {
2353 if (m == ss.killers[0])
2356 for (int i = KILLER_MAX - 1; i > 0; i--)
2357 ss.killers[i] = ss.killers[i - 1];
2362 // fail_high_ply_1() checks if some thread is currently resolving a fail
2363 // high at ply 1 at the node below the first root node. This information
2364 // is used for time managment.
2366 bool fail_high_ply_1() {
2367 for(int i = 0; i < ActiveThreads; i++)
2368 if(Threads[i].failHighPly1)
2374 // current_search_time() returns the number of milliseconds which have passed
2375 // since the beginning of the current search.
2377 int current_search_time() {
2378 return get_system_time() - SearchStartTime;
2382 // nps() computes the current nodes/second count.
2385 int t = current_search_time();
2386 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2390 // poll() performs two different functions: It polls for user input, and it
2391 // looks at the time consumed so far and decides if it's time to abort the
2396 static int lastInfoTime;
2397 int t = current_search_time();
2402 // We are line oriented, don't read single chars
2403 std::string command;
2404 if (!std::getline(std::cin, command))
2407 if (command == "quit")
2410 PonderSearch = false;
2413 else if(command == "stop")
2416 PonderSearch = false;
2418 else if(command == "ponderhit")
2421 // Print search information
2425 else if (lastInfoTime > t)
2426 // HACK: Must be a new search where we searched less than
2427 // NodesBetweenPolls nodes during the first second of search.
2430 else if (t - lastInfoTime >= 1000)
2437 if (dbg_show_hit_rate)
2438 dbg_print_hit_rate();
2440 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2441 << " time " << t << " hashfull " << TT.full() << std::endl;
2442 lock_release(&IOLock);
2443 if (ShowCurrentLine)
2444 Threads[0].printCurrentLine = true;
2446 // Should we stop the search?
2450 bool overTime = t > AbsoluteMaxSearchTime
2451 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2452 || ( !FailHigh && !fail_high_ply_1() && !Problem
2453 && t > 6*(MaxSearchTime + ExtraSearchTime));
2455 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2456 || (ExactMaxTime && t >= ExactMaxTime)
2457 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2462 // ponderhit() is called when the program is pondering (i.e. thinking while
2463 // it's the opponent's turn to move) in order to let the engine know that
2464 // it correctly predicted the opponent's move.
2467 int t = current_search_time();
2468 PonderSearch = false;
2469 if(Iteration >= 2 &&
2470 (!InfiniteSearch && (StopOnPonderhit ||
2471 t > AbsoluteMaxSearchTime ||
2472 (RootMoveNumber == 1 &&
2473 t > MaxSearchTime + ExtraSearchTime) ||
2474 (!FailHigh && !fail_high_ply_1() && !Problem &&
2475 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2480 // print_current_line() prints the current line of search for a given
2481 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2483 void print_current_line(SearchStack ss[], int ply, int threadID) {
2484 assert(ply >= 0 && ply < PLY_MAX);
2485 assert(threadID >= 0 && threadID < ActiveThreads);
2487 if(!Threads[threadID].idle) {
2489 std::cout << "info currline " << (threadID + 1);
2490 for(int p = 0; p < ply; p++)
2491 std::cout << " " << ss[p].currentMove;
2492 std::cout << std::endl;
2493 lock_release(&IOLock);
2495 Threads[threadID].printCurrentLine = false;
2496 if(threadID + 1 < ActiveThreads)
2497 Threads[threadID + 1].printCurrentLine = true;
2501 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2502 // while the program is pondering. The point is to work around a wrinkle in
2503 // the UCI protocol: When pondering, the engine is not allowed to give a
2504 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2505 // We simply wait here until one of these commands is sent, and return,
2506 // after which the bestmove and pondermove will be printed (in id_loop()).
2508 void wait_for_stop_or_ponderhit() {
2509 std::string command;
2512 if(!std::getline(std::cin, command))
2515 if(command == "quit") {
2516 OpeningBook.close();
2521 else if(command == "ponderhit" || command == "stop")
2527 // idle_loop() is where the threads are parked when they have no work to do.
2528 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2529 // object for which the current thread is the master.
2531 void idle_loop(int threadID, SplitPoint *waitSp) {
2532 assert(threadID >= 0 && threadID < THREAD_MAX);
2534 Threads[threadID].running = true;
2537 if(AllThreadsShouldExit && threadID != 0)
2540 // If we are not thinking, wait for a condition to be signaled instead
2541 // of wasting CPU time polling for work:
2542 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2543 #if !defined(_MSC_VER)
2544 pthread_mutex_lock(&WaitLock);
2545 if(Idle || threadID >= ActiveThreads)
2546 pthread_cond_wait(&WaitCond, &WaitLock);
2547 pthread_mutex_unlock(&WaitLock);
2549 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2553 // If this thread has been assigned work, launch a search:
2554 if(Threads[threadID].workIsWaiting) {
2555 Threads[threadID].workIsWaiting = false;
2556 if(Threads[threadID].splitPoint->pvNode)
2557 sp_search_pv(Threads[threadID].splitPoint, threadID);
2559 sp_search(Threads[threadID].splitPoint, threadID);
2560 Threads[threadID].idle = true;
2563 // If this thread is the master of a split point and all threads have
2564 // finished their work at this split point, return from the idle loop:
2565 if(waitSp != NULL && waitSp->cpus == 0)
2569 Threads[threadID].running = false;
2573 // init_split_point_stack() is called during program initialization, and
2574 // initializes all split point objects.
2576 void init_split_point_stack() {
2577 for(int i = 0; i < THREAD_MAX; i++)
2578 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2579 SplitPointStack[i][j].parent = NULL;
2580 lock_init(&(SplitPointStack[i][j].lock), NULL);
2585 // destroy_split_point_stack() is called when the program exits, and
2586 // destroys all locks in the precomputed split point objects.
2588 void destroy_split_point_stack() {
2589 for(int i = 0; i < THREAD_MAX; i++)
2590 for(int j = 0; j < MaxActiveSplitPoints; j++)
2591 lock_destroy(&(SplitPointStack[i][j].lock));
2595 // thread_should_stop() checks whether the thread with a given threadID has
2596 // been asked to stop, directly or indirectly. This can happen if a beta
2597 // cutoff has occured in thre thread's currently active split point, or in
2598 // some ancestor of the current split point.
2600 bool thread_should_stop(int threadID) {
2601 assert(threadID >= 0 && threadID < ActiveThreads);
2605 if(Threads[threadID].stop)
2607 if(ActiveThreads <= 2)
2609 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2611 Threads[threadID].stop = true;
2618 // thread_is_available() checks whether the thread with threadID "slave" is
2619 // available to help the thread with threadID "master" at a split point. An
2620 // obvious requirement is that "slave" must be idle. With more than two
2621 // threads, this is not by itself sufficient: If "slave" is the master of
2622 // some active split point, it is only available as a slave to the other
2623 // threads which are busy searching the split point at the top of "slave"'s
2624 // split point stack (the "helpful master concept" in YBWC terminology).
2626 bool thread_is_available(int slave, int master) {
2627 assert(slave >= 0 && slave < ActiveThreads);
2628 assert(master >= 0 && master < ActiveThreads);
2629 assert(ActiveThreads > 1);
2631 if(!Threads[slave].idle || slave == master)
2634 if(Threads[slave].activeSplitPoints == 0)
2635 // No active split points means that the thread is available as a slave
2636 // for any other thread.
2639 if(ActiveThreads == 2)
2642 // Apply the "helpful master" concept if possible.
2643 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2650 // idle_thread_exists() tries to find an idle thread which is available as
2651 // a slave for the thread with threadID "master".
2653 bool idle_thread_exists(int master) {
2654 assert(master >= 0 && master < ActiveThreads);
2655 assert(ActiveThreads > 1);
2657 for(int i = 0; i < ActiveThreads; i++)
2658 if(thread_is_available(i, master))
2664 // split() does the actual work of distributing the work at a node between
2665 // several threads at PV nodes. If it does not succeed in splitting the
2666 // node (because no idle threads are available, or because we have no unused
2667 // split point objects), the function immediately returns false. If
2668 // splitting is possible, a SplitPoint object is initialized with all the
2669 // data that must be copied to the helper threads (the current position and
2670 // search stack, alpha, beta, the search depth, etc.), and we tell our
2671 // helper threads that they have been assigned work. This will cause them
2672 // to instantly leave their idle loops and call sp_search_pv(). When all
2673 // threads have returned from sp_search_pv (or, equivalently, when
2674 // splitPoint->cpus becomes 0), split() returns true.
2676 bool split(const Position &p, SearchStack *sstck, int ply,
2677 Value *alpha, Value *beta, Value *bestValue,
2678 Depth depth, int *moves,
2679 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2681 assert(sstck != NULL);
2682 assert(ply >= 0 && ply < PLY_MAX);
2683 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2684 assert(!pvNode || *alpha < *beta);
2685 assert(*beta <= VALUE_INFINITE);
2686 assert(depth > Depth(0));
2687 assert(master >= 0 && master < ActiveThreads);
2688 assert(ActiveThreads > 1);
2690 SplitPoint *splitPoint;
2695 // If no other thread is available to help us, or if we have too many
2696 // active split points, don't split:
2697 if(!idle_thread_exists(master) ||
2698 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2699 lock_release(&MPLock);
2703 // Pick the next available split point object from the split point stack:
2704 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2705 Threads[master].activeSplitPoints++;
2707 // Initialize the split point object:
2708 splitPoint->parent = Threads[master].splitPoint;
2709 splitPoint->finished = false;
2710 splitPoint->ply = ply;
2711 splitPoint->depth = depth;
2712 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2713 splitPoint->beta = *beta;
2714 splitPoint->pvNode = pvNode;
2715 splitPoint->dcCandidates = dcCandidates;
2716 splitPoint->bestValue = *bestValue;
2717 splitPoint->master = master;
2718 splitPoint->mp = mp;
2719 splitPoint->moves = *moves;
2720 splitPoint->cpus = 1;
2721 splitPoint->pos.copy(p);
2722 splitPoint->parentSstack = sstck;
2723 for(i = 0; i < ActiveThreads; i++)
2724 splitPoint->slaves[i] = 0;
2726 // Copy the current position and the search stack to the master thread:
2727 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2728 Threads[master].splitPoint = splitPoint;
2730 // Make copies of the current position and search stack for each thread:
2731 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2733 if(thread_is_available(i, master)) {
2734 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2735 Threads[i].splitPoint = splitPoint;
2736 splitPoint->slaves[i] = 1;
2740 // Tell the threads that they have work to do. This will make them leave
2742 for(i = 0; i < ActiveThreads; i++)
2743 if(i == master || splitPoint->slaves[i]) {
2744 Threads[i].workIsWaiting = true;
2745 Threads[i].idle = false;
2746 Threads[i].stop = false;
2749 lock_release(&MPLock);
2751 // Everything is set up. The master thread enters the idle loop, from
2752 // which it will instantly launch a search, because its workIsWaiting
2753 // slot is 'true'. We send the split point as a second parameter to the
2754 // idle loop, which means that the main thread will return from the idle
2755 // loop when all threads have finished their work at this split point
2756 // (i.e. when // splitPoint->cpus == 0).
2757 idle_loop(master, splitPoint);
2759 // We have returned from the idle loop, which means that all threads are
2760 // finished. Update alpha, beta and bestvalue, and return:
2762 if(pvNode) *alpha = splitPoint->alpha;
2763 *beta = splitPoint->beta;
2764 *bestValue = splitPoint->bestValue;
2765 Threads[master].stop = false;
2766 Threads[master].idle = false;
2767 Threads[master].activeSplitPoints--;
2768 Threads[master].splitPoint = splitPoint->parent;
2769 lock_release(&MPLock);
2775 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2776 // to start a new search from the root.
2778 void wake_sleeping_threads() {
2779 if(ActiveThreads > 1) {
2780 for(int i = 1; i < ActiveThreads; i++) {
2781 Threads[i].idle = true;
2782 Threads[i].workIsWaiting = false;
2784 #if !defined(_MSC_VER)
2785 pthread_mutex_lock(&WaitLock);
2786 pthread_cond_broadcast(&WaitCond);
2787 pthread_mutex_unlock(&WaitLock);
2789 for(int i = 1; i < THREAD_MAX; i++)
2790 SetEvent(SitIdleEvent[i]);
2796 // init_thread() is the function which is called when a new thread is
2797 // launched. It simply calls the idle_loop() function with the supplied
2798 // threadID. There are two versions of this function; one for POSIX threads
2799 // and one for Windows threads.
2801 #if !defined(_MSC_VER)
2803 void *init_thread(void *threadID) {
2804 idle_loop(*(int *)threadID, NULL);
2810 DWORD WINAPI init_thread(LPVOID threadID) {
2811 idle_loop(*(int *)threadID, NULL);