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 capture, 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, int *moves,
294 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
295 void wake_sleeping_threads();
297 #if !defined(_MSC_VER)
298 void *init_thread(void *threadID);
300 DWORD WINAPI init_thread(LPVOID threadID);
307 //// Global variables
310 // The main transposition table
311 TranspositionTable TT = TranspositionTable(TTDefaultSize);
314 // Number of active threads:
315 int ActiveThreads = 1;
317 // Locks. In principle, there is no need for IOLock to be a global variable,
318 // but it could turn out to be useful for debugging.
321 History H; // Should be made local?
323 // The empty search stack
324 SearchStack EmptySearchStack;
331 /// think() is the external interface to Stockfish's search, and is called when
332 /// the program receives the UCI 'go' command. It initializes various
333 /// search-related global variables, and calls root_search()
335 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
336 int time[], int increment[], int movesToGo, int maxDepth,
337 int maxNodes, int maxTime, Move searchMoves[]) {
339 // Look for a book move
340 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
343 if (get_option_value_string("Book File") != OpeningBook.file_name())
346 OpeningBook.open("book.bin");
348 bookMove = OpeningBook.get_move(pos);
349 if (bookMove != MOVE_NONE)
351 std::cout << "bestmove " << bookMove << std::endl;
356 // Initialize global search variables
358 SearchStartTime = get_system_time();
359 BestRootMove = MOVE_NONE;
360 PonderMove = MOVE_NONE;
361 EasyMove = MOVE_NONE;
362 for (int i = 0; i < THREAD_MAX; i++)
364 Threads[i].nodes = 0ULL;
365 Threads[i].failHighPly1 = false;
368 InfiniteSearch = infinite;
369 PonderSearch = ponder;
370 StopOnPonderhit = false;
375 ExactMaxTime = maxTime;
377 // Read UCI option values
378 TT.set_size(get_option_value_int("Hash"));
379 if (button_was_pressed("Clear Hash"))
382 PonderingEnabled = get_option_value_bool("Ponder");
383 MultiPV = get_option_value_int("MultiPV");
385 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
386 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
388 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
389 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
391 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
392 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
394 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
395 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
397 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
398 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
400 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
401 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
403 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
404 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
405 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
406 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
408 Chess960 = get_option_value_bool("UCI_Chess960");
409 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
410 UseLogFile = get_option_value_bool("Use Search Log");
412 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
414 UseNullDrivenIID = get_option_value_bool("Null driven IID");
415 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
416 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
418 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
419 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
420 for (int i = 0; i < 6; i++)
421 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
423 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
424 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
426 UseLSNFiltering = get_option_value_bool("LSN filtering");
427 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
428 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
430 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
431 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
433 read_weights(pos.side_to_move());
435 int newActiveThreads = get_option_value_int("Threads");
436 if (newActiveThreads != ActiveThreads)
438 ActiveThreads = newActiveThreads;
439 init_eval(ActiveThreads);
442 // Wake up sleeping threads:
443 wake_sleeping_threads();
445 for (int i = 1; i < ActiveThreads; i++)
446 assert(thread_is_available(i, 0));
448 // Set thinking time:
449 int myTime = time[side_to_move];
450 int myIncrement = increment[side_to_move];
452 if (!movesToGo) // Sudden death time control
456 MaxSearchTime = myTime / 30 + myIncrement;
457 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
458 } else { // Blitz game without increment
459 MaxSearchTime = myTime / 30;
460 AbsoluteMaxSearchTime = myTime / 8;
463 else // (x moves) / (y minutes)
467 MaxSearchTime = myTime / 2;
468 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
470 MaxSearchTime = myTime / Min(movesToGo, 20);
471 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
475 if (PonderingEnabled)
477 MaxSearchTime += MaxSearchTime / 4;
478 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
481 // Fixed depth or fixed number of nodes?
484 InfiniteSearch = true; // HACK
489 NodesBetweenPolls = Min(MaxNodes, 30000);
490 InfiniteSearch = true; // HACK
493 NodesBetweenPolls = 30000;
496 // Write information to search log file:
498 LogFile << "Searching: " << pos.to_fen() << std::endl
499 << "infinite: " << infinite
500 << " ponder: " << ponder
501 << " time: " << myTime
502 << " increment: " << myIncrement
503 << " moves to go: " << movesToGo << std::endl;
506 // We're ready to start thinking. Call the iterative deepening loop
510 Value v = id_loop(pos, searchMoves);
511 looseOnTime = ( UseLSNFiltering
518 looseOnTime = false; // reset for next match
519 while (SearchStartTime + myTime + 1000 > get_system_time())
521 id_loop(pos, searchMoves); // to fail gracefully
538 /// init_threads() is called during startup. It launches all helper threads,
539 /// and initializes the split point stack and the global locks and condition
542 void init_threads() {
546 #if !defined(_MSC_VER)
547 pthread_t pthread[1];
550 for (i = 0; i < THREAD_MAX; i++)
551 Threads[i].activeSplitPoints = 0;
553 // Initialize global locks:
554 lock_init(&MPLock, NULL);
555 lock_init(&IOLock, NULL);
557 init_split_point_stack();
559 #if !defined(_MSC_VER)
560 pthread_mutex_init(&WaitLock, NULL);
561 pthread_cond_init(&WaitCond, NULL);
563 for (i = 0; i < THREAD_MAX; i++)
564 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
567 // All threads except the main thread should be initialized to idle state
568 for (i = 1; i < THREAD_MAX; i++)
570 Threads[i].stop = false;
571 Threads[i].workIsWaiting = false;
572 Threads[i].idle = true;
573 Threads[i].running = false;
576 // Launch the helper threads
577 for(i = 1; i < THREAD_MAX; i++)
579 #if !defined(_MSC_VER)
580 pthread_create(pthread, NULL, init_thread, (void*)(&i));
583 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
586 // Wait until the thread has finished launching:
587 while (!Threads[i].running);
590 // Init also the empty search stack
591 init_search_stack(EmptySearchStack);
595 /// stop_threads() is called when the program exits. It makes all the
596 /// helper threads exit cleanly.
598 void stop_threads() {
600 ActiveThreads = THREAD_MAX; // HACK
601 Idle = false; // HACK
602 wake_sleeping_threads();
603 AllThreadsShouldExit = true;
604 for (int i = 1; i < THREAD_MAX; i++)
606 Threads[i].stop = true;
607 while(Threads[i].running);
609 destroy_split_point_stack();
613 /// nodes_searched() returns the total number of nodes searched so far in
614 /// the current search.
616 int64_t nodes_searched() {
618 int64_t result = 0ULL;
619 for (int i = 0; i < ActiveThreads; i++)
620 result += Threads[i].nodes;
627 // id_loop() is the main iterative deepening loop. It calls root_search
628 // repeatedly with increasing depth until the allocated thinking time has
629 // been consumed, the user stops the search, or the maximum search depth is
632 Value id_loop(const Position &pos, Move searchMoves[]) {
635 SearchStack ss[PLY_MAX_PLUS_2];
637 // searchMoves are verified, copied, scored and sorted
638 RootMoveList rml(p, searchMoves);
643 init_search_stack(ss);
645 ValueByIteration[0] = Value(0);
646 ValueByIteration[1] = rml.get_move_score(0);
648 LastIterations = false;
650 EasyMove = rml.scan_for_easy_move();
652 // Iterative deepening loop
653 while (!AbortSearch && Iteration < PLY_MAX)
655 // Initialize iteration
658 BestMoveChangesByIteration[Iteration] = 0;
662 std::cout << "info depth " << Iteration << std::endl;
664 // Search to the current depth
665 ValueByIteration[Iteration] = root_search(p, ss, rml);
667 // Erase the easy move if it differs from the new best move
668 if (ss[0].pv[0] != EasyMove)
669 EasyMove = MOVE_NONE;
676 bool stopSearch = false;
678 // Stop search early if there is only a single legal move:
679 if (Iteration >= 6 && rml.move_count() == 1)
682 // Stop search early when the last two iterations returned a mate score
684 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
685 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
688 // Stop search early if one move seems to be much better than the rest
689 int64_t nodes = nodes_searched();
691 && EasyMove == ss[0].pv[0]
692 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
693 && current_search_time() > MaxSearchTime / 16)
694 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
695 && current_search_time() > MaxSearchTime / 32)))
698 // Add some extra time if the best move has changed during the last two iterations
699 if (Iteration > 5 && Iteration <= 50)
700 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
701 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
703 // Try to guess if the current iteration is the last one or the last two
704 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
706 // Stop search if most of MaxSearchTime is consumed at the end of the
707 // iteration. We probably don't have enough time to search the first
708 // move at the next iteration anyway.
709 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
717 StopOnPonderhit = true;
720 // Write PV to transposition table, in case the relevant entries have
721 // been overwritten during the search:
722 TT.insert_pv(p, ss[0].pv);
724 if (MaxDepth && Iteration >= MaxDepth)
730 // If we are pondering, we shouldn't print the best move before we
733 wait_for_stop_or_ponderhit();
735 // Print final search statistics
736 std::cout << "info nodes " << nodes_searched()
738 << " time " << current_search_time()
739 << " hashfull " << TT.full() << std::endl;
741 // Print the best move and the ponder move to the standard output
742 std::cout << "bestmove " << ss[0].pv[0];
743 if (ss[0].pv[1] != MOVE_NONE)
744 std::cout << " ponder " << ss[0].pv[1];
746 std::cout << std::endl;
751 dbg_print_mean(LogFile);
753 if (dbg_show_hit_rate)
754 dbg_print_hit_rate(LogFile);
757 LogFile << "Nodes: " << nodes_searched() << std::endl
758 << "Nodes/second: " << nps() << std::endl
759 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
761 p.do_move(ss[0].pv[0], st);
762 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
763 << std::endl << std::endl;
765 return rml.get_move_score(0);
769 // root_search() is the function which searches the root node. It is
770 // similar to search_pv except that it uses a different move ordering
771 // scheme (perhaps we should try to use this at internal PV nodes, too?)
772 // and prints some information to the standard output.
774 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
776 Value alpha = -VALUE_INFINITE;
777 Value beta = VALUE_INFINITE, value;
778 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
780 // Loop through all the moves in the root move list
781 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
788 RootMoveNumber = i + 1;
791 // Remember the node count before the move is searched. The node counts
792 // are used to sort the root moves at the next iteration.
793 nodes = nodes_searched();
795 // Reset beta cut-off counters
798 // Pick the next root move, and print the move and the move number to
799 // the standard output.
800 move = ss[0].currentMove = rml.get_move(i);
801 if (current_search_time() >= 1000)
802 std::cout << "info currmove " << move
803 << " currmovenumber " << i + 1 << std::endl;
805 // Decide search depth for this move
807 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
808 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
810 // Make the move, and search it
811 pos.do_move(move, st, dcCandidates);
815 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
816 // If the value has dropped a lot compared to the last iteration,
817 // set the boolean variable Problem to true. This variable is used
818 // for time managment: When Problem is true, we try to complete the
819 // current iteration before playing a move.
820 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
822 if (Problem && StopOnPonderhit)
823 StopOnPonderhit = false;
827 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
830 // Fail high! Set the boolean variable FailHigh to true, and
831 // re-search the move with a big window. The variable FailHigh is
832 // used for time managment: We try to avoid aborting the search
833 // prematurely during a fail high research.
835 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
841 // Finished searching the move. If AbortSearch is true, the search
842 // was aborted because the user interrupted the search or because we
843 // ran out of time. In this case, the return value of the search cannot
844 // be trusted, and we break out of the loop without updating the best
849 // Remember the node count for this move. The node counts are used to
850 // sort the root moves at the next iteration.
851 rml.set_move_nodes(i, nodes_searched() - nodes);
853 // Remember the beta-cutoff statistics
855 BetaCounter.read(pos.side_to_move(), our, their);
856 rml.set_beta_counters(i, our, their);
858 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
860 if (value <= alpha && i >= MultiPV)
861 rml.set_move_score(i, -VALUE_INFINITE);
867 rml.set_move_score(i, value);
869 rml.set_move_pv(i, ss[0].pv);
873 // We record how often the best move has been changed in each
874 // iteration. This information is used for time managment: When
875 // the best move changes frequently, we allocate some more time.
877 BestMoveChangesByIteration[Iteration]++;
879 // Print search information to the standard output:
880 std::cout << "info depth " << Iteration
881 << " score " << value_to_string(value)
882 << " time " << current_search_time()
883 << " nodes " << nodes_searched()
887 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
888 std::cout << ss[0].pv[j] << " ";
890 std::cout << std::endl;
893 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
898 // Reset the global variable Problem to false if the value isn't too
899 // far below the final value from the last iteration.
900 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
906 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
909 std::cout << "info multipv " << j + 1
910 << " score " << value_to_string(rml.get_move_score(j))
911 << " depth " << ((j <= i)? Iteration : Iteration - 1)
912 << " time " << current_search_time()
913 << " nodes " << nodes_searched()
917 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
918 std::cout << rml.get_move_pv(j, k) << " ";
920 std::cout << std::endl;
922 alpha = rml.get_move_score(Min(i, MultiPV-1));
930 // search_pv() is the main search function for PV nodes.
932 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
933 Depth depth, int ply, int threadID) {
935 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
936 assert(beta > alpha && beta <= VALUE_INFINITE);
937 assert(ply >= 0 && ply < PLY_MAX);
938 assert(threadID >= 0 && threadID < ActiveThreads);
941 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
943 // Initialize, and make an early exit in case of an aborted search,
944 // an instant draw, maximum ply reached, etc.
945 init_node(pos, ss, ply, threadID);
947 // After init_node() that calls poll()
948 if (AbortSearch || thread_should_stop(threadID))
956 if (ply >= PLY_MAX - 1)
957 return evaluate(pos, ei, threadID);
959 // Mate distance pruning
960 Value oldAlpha = alpha;
961 alpha = Max(value_mated_in(ply), alpha);
962 beta = Min(value_mate_in(ply+1), beta);
966 // Transposition table lookup. At PV nodes, we don't use the TT for
967 // pruning, but only for move ordering.
968 const TTEntry* tte = TT.retrieve(pos);
969 Move ttMove = (tte ? tte->move() : MOVE_NONE);
971 // Go with internal iterative deepening if we don't have a TT move
972 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
974 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
975 ttMove = ss[ply].pv[ply];
978 // Initialize a MovePicker object for the current position, and prepare
979 // to search all moves
980 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
982 Move move, movesSearched[256];
984 Value value, bestValue = -VALUE_INFINITE;
985 Bitboard dcCandidates = mp.discovered_check_candidates();
986 Color us = pos.side_to_move();
987 bool isCheck = pos.is_check();
988 bool mateThreat = pos.has_mate_threat(opposite_color(us));
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, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1013 Depth newDepth = depth - OnePly + ext;
1015 // Make and search the move
1017 pos.do_move(move, st, 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);
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(st);
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();
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, moveIsCapture, 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, st, 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);
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 Color us = pos.side_to_move();
1475 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1477 // Loop through the moves until no moves remain or a beta cutoff
1479 while ( alpha < beta
1480 && (move = mp.get_next_move()) != MOVE_NONE)
1482 assert(move_is_ok(move));
1485 ss[ply].currentMove = move;
1488 if ( UseQSearchFutilityPruning
1492 && !move_promotion(move)
1493 && !pos.move_is_check(move, dcCandidates)
1494 && !pos.move_is_passed_pawn_push(move))
1496 Value futilityValue = staticValue
1497 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1498 pos.endgame_value_of_piece_on(move_to(move)))
1499 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1501 + ei.futilityMargin;
1503 if (futilityValue < alpha)
1505 if (futilityValue > bestValue)
1506 bestValue = futilityValue;
1511 // Don't search captures and checks with negative SEE values
1513 && !move_promotion(move)
1514 && (pos.midgame_value_of_piece_on(move_from(move)) >
1515 pos.midgame_value_of_piece_on(move_to(move)))
1516 && pos.see(move) < 0)
1519 // Make and search the move.
1521 pos.do_move(move, st, dcCandidates);
1522 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1523 pos.undo_move(move);
1525 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1528 if (value > bestValue)
1539 // All legal moves have been searched. A special case: If we're in check
1540 // and no legal moves were found, it is checkmate:
1541 if (pos.is_check() && moveCount == 0) // Mate!
1542 return value_mated_in(ply);
1544 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1546 // Update transposition table
1547 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1549 // Update killers only for good check moves
1550 Move m = ss[ply].currentMove;
1551 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1553 // Wrong to update history when depth is <= 0
1554 update_killers(m, ss[ply]);
1560 // sp_search() is used to search from a split point. This function is called
1561 // by each thread working at the split point. It is similar to the normal
1562 // search() function, but simpler. Because we have already probed the hash
1563 // table, done a null move search, and searched the first move before
1564 // splitting, we don't have to repeat all this work in sp_search(). We
1565 // also don't need to store anything to the hash table here: This is taken
1566 // care of after we return from the split point.
1568 void sp_search(SplitPoint *sp, int threadID) {
1570 assert(threadID >= 0 && threadID < ActiveThreads);
1571 assert(ActiveThreads > 1);
1573 Position pos = Position(sp->pos);
1574 SearchStack *ss = sp->sstack[threadID];
1577 bool isCheck = pos.is_check();
1578 bool useFutilityPruning = UseFutilityPruning
1579 && sp->depth < SelectiveDepth
1582 while ( sp->bestValue < sp->beta
1583 && !thread_should_stop(threadID)
1584 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1586 assert(move_is_ok(move));
1588 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1589 bool moveIsCapture = pos.move_is_capture(move);
1591 lock_grab(&(sp->lock));
1592 int moveCount = ++sp->moves;
1593 lock_release(&(sp->lock));
1595 ss[sp->ply].currentMove = move;
1597 // Decide the new search depth.
1599 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1600 Depth newDepth = sp->depth - OnePly + ext;
1603 if ( useFutilityPruning
1606 && !move_promotion(move)
1607 && moveCount >= 2 + int(sp->depth)
1608 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1611 // Make and search the move.
1613 pos.do_move(move, st, sp->dcCandidates);
1615 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1616 // if the move fails high will be re-searched at full depth.
1618 && moveCount >= LMRNonPVMoves
1620 && !move_promotion(move)
1621 && !move_is_castle(move)
1622 && !move_is_killer(move, ss[sp->ply]))
1624 ss[sp->ply].reduction = OnePly;
1625 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1628 value = sp->beta; // Just to trigger next condition
1630 if (value >= sp->beta) // Go with full depth non-pv search
1632 ss[sp->ply].reduction = Depth(0);
1633 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1635 pos.undo_move(move);
1637 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1639 if (thread_should_stop(threadID))
1643 lock_grab(&(sp->lock));
1644 if (value > sp->bestValue && !thread_should_stop(threadID))
1646 sp->bestValue = value;
1647 if (sp->bestValue >= sp->beta)
1649 sp_update_pv(sp->parentSstack, ss, sp->ply);
1650 for (int i = 0; i < ActiveThreads; i++)
1651 if (i != threadID && (i == sp->master || sp->slaves[i]))
1652 Threads[i].stop = true;
1654 sp->finished = true;
1657 lock_release(&(sp->lock));
1660 lock_grab(&(sp->lock));
1662 // If this is the master thread and we have been asked to stop because of
1663 // a beta cutoff higher up in the tree, stop all slave threads:
1664 if (sp->master == threadID && thread_should_stop(threadID))
1665 for (int i = 0; i < ActiveThreads; i++)
1667 Threads[i].stop = true;
1670 sp->slaves[threadID] = 0;
1672 lock_release(&(sp->lock));
1676 // sp_search_pv() is used to search from a PV split point. This function
1677 // is called by each thread working at the split point. It is similar to
1678 // the normal search_pv() function, but simpler. Because we have already
1679 // probed the hash table and searched the first move before splitting, we
1680 // don't have to repeat all this work in sp_search_pv(). We also don't
1681 // need to store anything to the hash table here: This is taken care of
1682 // after we return from the split point.
1684 void sp_search_pv(SplitPoint *sp, int threadID) {
1686 assert(threadID >= 0 && threadID < ActiveThreads);
1687 assert(ActiveThreads > 1);
1689 Position pos = Position(sp->pos);
1690 SearchStack *ss = sp->sstack[threadID];
1694 while ( sp->alpha < sp->beta
1695 && !thread_should_stop(threadID)
1696 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1698 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1699 bool moveIsCapture = pos.move_is_capture(move);
1701 assert(move_is_ok(move));
1704 ss[sp->ply].currentMoveCaptureValue =
1705 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1707 ss[sp->ply].currentMoveCaptureValue = Value(0);
1709 lock_grab(&(sp->lock));
1710 int moveCount = ++sp->moves;
1711 lock_release(&(sp->lock));
1713 ss[sp->ply].currentMove = move;
1715 // Decide the new search depth.
1717 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1718 Depth newDepth = sp->depth - OnePly + ext;
1720 // Make and search the move.
1722 pos.do_move(move, st, sp->dcCandidates);
1724 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1725 // if the move fails high will be re-searched at full depth.
1727 && moveCount >= LMRPVMoves
1729 && !move_promotion(move)
1730 && !move_is_castle(move)
1731 && !move_is_killer(move, ss[sp->ply]))
1733 ss[sp->ply].reduction = OnePly;
1734 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1737 value = sp->alpha + 1; // Just to trigger next condition
1739 if (value > sp->alpha) // Go with full depth non-pv search
1741 ss[sp->ply].reduction = Depth(0);
1742 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1744 if (value > sp->alpha && value < sp->beta)
1746 // When the search fails high at ply 1 while searching the first
1747 // move at the root, set the flag failHighPly1. This is used for
1748 // time managment: We don't want to stop the search early in
1749 // such cases, because resolving the fail high at ply 1 could
1750 // result in a big drop in score at the root.
1751 if (sp->ply == 1 && RootMoveNumber == 1)
1752 Threads[threadID].failHighPly1 = true;
1754 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1755 Threads[threadID].failHighPly1 = false;
1758 pos.undo_move(move);
1760 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1762 if (thread_should_stop(threadID))
1766 lock_grab(&(sp->lock));
1767 if (value > sp->bestValue && !thread_should_stop(threadID))
1769 sp->bestValue = value;
1770 if (value > sp->alpha)
1773 sp_update_pv(sp->parentSstack, ss, sp->ply);
1774 if (value == value_mate_in(sp->ply + 1))
1775 ss[sp->ply].mateKiller = move;
1777 if(value >= sp->beta)
1779 for(int i = 0; i < ActiveThreads; i++)
1780 if(i != threadID && (i == sp->master || sp->slaves[i]))
1781 Threads[i].stop = true;
1783 sp->finished = true;
1786 // If we are at ply 1, and we are searching the first root move at
1787 // ply 0, set the 'Problem' variable if the score has dropped a lot
1788 // (from the computer's point of view) since the previous iteration.
1791 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1794 lock_release(&(sp->lock));
1797 lock_grab(&(sp->lock));
1799 // If this is the master thread and we have been asked to stop because of
1800 // a beta cutoff higher up in the tree, stop all slave threads.
1801 if (sp->master == threadID && thread_should_stop(threadID))
1802 for (int i = 0; i < ActiveThreads; i++)
1804 Threads[i].stop = true;
1807 sp->slaves[threadID] = 0;
1809 lock_release(&(sp->lock));
1812 /// The BetaCounterType class
1814 BetaCounterType::BetaCounterType() { clear(); }
1816 void BetaCounterType::clear() {
1818 for (int i = 0; i < THREAD_MAX; i++)
1819 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1822 void BetaCounterType::add(Color us, Depth d, int threadID) {
1824 // Weighted count based on depth
1825 hits[threadID][us] += int(d);
1828 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1831 for (int i = 0; i < THREAD_MAX; i++)
1834 their += hits[i][opposite_color(us)];
1839 /// The RootMove class
1843 RootMove::RootMove() {
1844 nodes = cumulativeNodes = 0ULL;
1847 // RootMove::operator<() is the comparison function used when
1848 // sorting the moves. A move m1 is considered to be better
1849 // than a move m2 if it has a higher score, or if the moves
1850 // have equal score but m1 has the higher node count.
1852 bool RootMove::operator<(const RootMove& m) {
1854 if (score != m.score)
1855 return (score < m.score);
1857 return theirBeta <= m.theirBeta;
1860 /// The RootMoveList class
1864 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1866 MoveStack mlist[MaxRootMoves];
1867 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1869 // Generate all legal moves
1870 int lm_count = generate_legal_moves(pos, mlist);
1872 // Add each move to the moves[] array
1873 for (int i = 0; i < lm_count; i++)
1875 bool includeMove = includeAllMoves;
1877 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1878 includeMove = (searchMoves[k] == mlist[i].move);
1882 // Find a quick score for the move
1884 SearchStack ss[PLY_MAX_PLUS_2];
1886 moves[count].move = mlist[i].move;
1887 moves[count].nodes = 0ULL;
1888 pos.do_move(moves[count].move, st);
1889 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1891 pos.undo_move(moves[count].move);
1892 moves[count].pv[0] = moves[i].move;
1893 moves[count].pv[1] = MOVE_NONE; // FIXME
1901 // Simple accessor methods for the RootMoveList class
1903 inline Move RootMoveList::get_move(int moveNum) const {
1904 return moves[moveNum].move;
1907 inline Value RootMoveList::get_move_score(int moveNum) const {
1908 return moves[moveNum].score;
1911 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1912 moves[moveNum].score = score;
1915 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1916 moves[moveNum].nodes = nodes;
1917 moves[moveNum].cumulativeNodes += nodes;
1920 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1921 moves[moveNum].ourBeta = our;
1922 moves[moveNum].theirBeta = their;
1925 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1927 for(j = 0; pv[j] != MOVE_NONE; j++)
1928 moves[moveNum].pv[j] = pv[j];
1929 moves[moveNum].pv[j] = MOVE_NONE;
1932 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1933 return moves[moveNum].pv[i];
1936 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1937 return moves[moveNum].cumulativeNodes;
1940 inline int RootMoveList::move_count() const {
1945 // RootMoveList::scan_for_easy_move() is called at the end of the first
1946 // iteration, and is used to detect an "easy move", i.e. a move which appears
1947 // to be much bester than all the rest. If an easy move is found, the move
1948 // is returned, otherwise the function returns MOVE_NONE. It is very
1949 // important that this function is called at the right moment: The code
1950 // assumes that the first iteration has been completed and the moves have
1951 // been sorted. This is done in RootMoveList c'tor.
1953 Move RootMoveList::scan_for_easy_move() const {
1960 // moves are sorted so just consider the best and the second one
1961 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1967 // RootMoveList::sort() sorts the root move list at the beginning of a new
1970 inline void RootMoveList::sort() {
1972 sort_multipv(count - 1); // all items
1976 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1977 // list by their scores and depths. It is used to order the different PVs
1978 // correctly in MultiPV mode.
1980 void RootMoveList::sort_multipv(int n) {
1982 for (int i = 1; i <= n; i++)
1984 RootMove rm = moves[i];
1986 for (j = i; j > 0 && moves[j-1] < rm; j--)
1987 moves[j] = moves[j-1];
1993 // init_search_stack() initializes a search stack at the beginning of a
1994 // new search from the root.
1995 void init_search_stack(SearchStack& ss) {
1997 ss.pv[0] = MOVE_NONE;
1998 ss.pv[1] = MOVE_NONE;
1999 ss.currentMove = MOVE_NONE;
2000 ss.threatMove = MOVE_NONE;
2001 ss.reduction = Depth(0);
2002 for (int j = 0; j < KILLER_MAX; j++)
2003 ss.killers[j] = MOVE_NONE;
2006 void init_search_stack(SearchStack ss[]) {
2008 for (int i = 0; i < 3; i++)
2010 ss[i].pv[i] = MOVE_NONE;
2011 ss[i].pv[i+1] = MOVE_NONE;
2012 ss[i].currentMove = MOVE_NONE;
2013 ss[i].threatMove = MOVE_NONE;
2014 ss[i].reduction = Depth(0);
2015 for (int j = 0; j < KILLER_MAX; j++)
2016 ss[i].killers[j] = MOVE_NONE;
2021 // init_node() is called at the beginning of all the search functions
2022 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2023 // stack object corresponding to the current node. Once every
2024 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2025 // for user input and checks whether it is time to stop the search.
2027 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2028 assert(ply >= 0 && ply < PLY_MAX);
2029 assert(threadID >= 0 && threadID < ActiveThreads);
2031 Threads[threadID].nodes++;
2035 if(NodesSincePoll >= NodesBetweenPolls) {
2040 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
2041 ss[ply+2].mateKiller = MOVE_NONE;
2042 ss[ply].threatMove = MOVE_NONE;
2043 ss[ply].reduction = Depth(0);
2044 ss[ply].currentMoveCaptureValue = Value(0);
2045 for (int j = 0; j < KILLER_MAX; j++)
2046 ss[ply+2].killers[j] = MOVE_NONE;
2048 if(Threads[threadID].printCurrentLine)
2049 print_current_line(ss, ply, threadID);
2053 // update_pv() is called whenever a search returns a value > alpha. It
2054 // updates the PV in the SearchStack object corresponding to the current
2057 void update_pv(SearchStack ss[], int ply) {
2058 assert(ply >= 0 && ply < PLY_MAX);
2060 ss[ply].pv[ply] = ss[ply].currentMove;
2062 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2063 ss[ply].pv[p] = ss[ply+1].pv[p];
2064 ss[ply].pv[p] = MOVE_NONE;
2068 // sp_update_pv() is a variant of update_pv for use at split points. The
2069 // difference between the two functions is that sp_update_pv also updates
2070 // the PV at the parent node.
2072 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2073 assert(ply >= 0 && ply < PLY_MAX);
2075 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2077 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2078 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2079 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2083 // connected_moves() tests whether two moves are 'connected' in the sense
2084 // that the first move somehow made the second move possible (for instance
2085 // if the moving piece is the same in both moves). The first move is
2086 // assumed to be the move that was made to reach the current position, while
2087 // the second move is assumed to be a move from the current position.
2089 bool connected_moves(const Position &pos, Move m1, Move m2) {
2090 Square f1, t1, f2, t2;
2092 assert(move_is_ok(m1));
2093 assert(move_is_ok(m2));
2098 // Case 1: The moving piece is the same in both moves.
2104 // Case 2: The destination square for m2 was vacated by m1.
2110 // Case 3: Moving through the vacated square:
2111 if(piece_is_slider(pos.piece_on(f2)) &&
2112 bit_is_set(squares_between(f2, t2), f1))
2115 // Case 4: The destination square for m2 is attacked by the moving piece
2117 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2120 // Case 5: Discovered check, checking piece is the piece moved in m1:
2121 if(piece_is_slider(pos.piece_on(t1)) &&
2122 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2124 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2126 Bitboard occ = pos.occupied_squares();
2127 Color us = pos.side_to_move();
2128 Square ksq = pos.king_square(us);
2129 clear_bit(&occ, f2);
2130 if(pos.type_of_piece_on(t1) == BISHOP) {
2131 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2134 else if(pos.type_of_piece_on(t1) == ROOK) {
2135 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2139 assert(pos.type_of_piece_on(t1) == QUEEN);
2140 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2149 // value_is_mate() checks if the given value is a mate one
2150 // eventually compensated for the ply.
2152 bool value_is_mate(Value value) {
2154 assert(abs(value) <= VALUE_INFINITE);
2156 return value <= value_mated_in(PLY_MAX)
2157 || value >= value_mate_in(PLY_MAX);
2161 // move_is_killer() checks if the given move is among the
2162 // killer moves of that ply.
2164 bool move_is_killer(Move m, const SearchStack& ss) {
2166 const Move* k = ss.killers;
2167 for (int i = 0; i < KILLER_MAX; i++, k++)
2175 // extension() decides whether a move should be searched with normal depth,
2176 // or with extended depth. Certain classes of moves (checking moves, in
2177 // particular) are searched with bigger depth than ordinary moves and in
2178 // any case are marked as 'dangerous'. Note that also if a move is not
2179 // extended, as example because the corresponding UCI option is set to zero,
2180 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2182 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2183 bool singleReply, bool mateThreat, bool* dangerous) {
2185 assert(m != MOVE_NONE);
2187 Depth result = Depth(0);
2188 *dangerous = check || singleReply || mateThreat;
2191 result += CheckExtension[pvNode];
2194 result += SingleReplyExtension[pvNode];
2197 result += MateThreatExtension[pvNode];
2199 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2201 if (pos.move_is_pawn_push_to_7th(m))
2203 result += PawnPushTo7thExtension[pvNode];
2206 if (pos.move_is_passed_pawn_push(m))
2208 result += PassedPawnExtension[pvNode];
2214 && pos.type_of_piece_on(move_to(m)) != PAWN
2215 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2216 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2217 && !move_promotion(m)
2220 result += PawnEndgameExtension[pvNode];
2226 && pos.type_of_piece_on(move_to(m)) != PAWN
2233 return Min(result, OnePly);
2237 // ok_to_do_nullmove() looks at the current position and decides whether
2238 // doing a 'null move' should be allowed. In order to avoid zugzwang
2239 // problems, null moves are not allowed when the side to move has very
2240 // little material left. Currently, the test is a bit too simple: Null
2241 // moves are avoided only when the side to move has only pawns left. It's
2242 // probably a good idea to avoid null moves in at least some more
2243 // complicated endgames, e.g. KQ vs KR. FIXME
2245 bool ok_to_do_nullmove(const Position &pos) {
2246 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2252 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2253 // non-tactical moves late in the move list close to the leaves are
2254 // candidates for pruning.
2256 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2257 Square mfrom, mto, tfrom, tto;
2259 assert(move_is_ok(m));
2260 assert(threat == MOVE_NONE || move_is_ok(threat));
2261 assert(!move_promotion(m));
2262 assert(!pos.move_is_check(m));
2263 assert(!pos.move_is_capture(m));
2264 assert(!pos.move_is_passed_pawn_push(m));
2265 assert(d >= OnePly);
2267 mfrom = move_from(m);
2269 tfrom = move_from(threat);
2270 tto = move_to(threat);
2272 // Case 1: Castling moves are never pruned.
2273 if (move_is_castle(m))
2276 // Case 2: Don't prune moves which move the threatened piece
2277 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2280 // Case 3: If the threatened piece has value less than or equal to the
2281 // value of the threatening piece, don't prune move which defend it.
2282 if ( !PruneDefendingMoves
2283 && threat != MOVE_NONE
2284 && pos.move_is_capture(threat)
2285 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2286 || pos.type_of_piece_on(tfrom) == KING)
2287 && pos.move_attacks_square(m, tto))
2290 // Case 4: Don't prune moves with good history.
2291 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2294 // Case 5: If the moving piece in the threatened move is a slider, don't
2295 // prune safe moves which block its ray.
2296 if ( !PruneBlockingMoves
2297 && threat != MOVE_NONE
2298 && piece_is_slider(pos.piece_on(tfrom))
2299 && bit_is_set(squares_between(tfrom, tto), mto)
2307 // ok_to_use_TT() returns true if a transposition table score
2308 // can be used at a given point in search.
2310 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2312 Value v = value_from_tt(tte->value(), ply);
2314 return ( tte->depth() >= depth
2315 || v >= Max(value_mate_in(100), beta)
2316 || v < Min(value_mated_in(100), beta))
2318 && ( (is_lower_bound(tte->type()) && v >= beta)
2319 || (is_upper_bound(tte->type()) && v < beta));
2323 // ok_to_history() returns true if a move m can be stored
2324 // in history. Should be a non capturing move nor a promotion.
2326 bool ok_to_history(const Position& pos, Move m) {
2328 return !pos.move_is_capture(m) && !move_promotion(m);
2332 // update_history() registers a good move that produced a beta-cutoff
2333 // in history and marks as failures all the other moves of that ply.
2335 void update_history(const Position& pos, Move m, Depth depth,
2336 Move movesSearched[], int moveCount) {
2338 H.success(pos.piece_on(move_from(m)), m, depth);
2340 for (int i = 0; i < moveCount - 1; i++)
2342 assert(m != movesSearched[i]);
2343 if (ok_to_history(pos, movesSearched[i]))
2344 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2349 // update_killers() add a good move that produced a beta-cutoff
2350 // among the killer moves of that ply.
2352 void update_killers(Move m, SearchStack& ss) {
2354 if (m == ss.killers[0])
2357 for (int i = KILLER_MAX - 1; i > 0; i--)
2358 ss.killers[i] = ss.killers[i - 1];
2363 // fail_high_ply_1() checks if some thread is currently resolving a fail
2364 // high at ply 1 at the node below the first root node. This information
2365 // is used for time managment.
2367 bool fail_high_ply_1() {
2368 for(int i = 0; i < ActiveThreads; i++)
2369 if(Threads[i].failHighPly1)
2375 // current_search_time() returns the number of milliseconds which have passed
2376 // since the beginning of the current search.
2378 int current_search_time() {
2379 return get_system_time() - SearchStartTime;
2383 // nps() computes the current nodes/second count.
2386 int t = current_search_time();
2387 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2391 // poll() performs two different functions: It polls for user input, and it
2392 // looks at the time consumed so far and decides if it's time to abort the
2397 static int lastInfoTime;
2398 int t = current_search_time();
2403 // We are line oriented, don't read single chars
2404 std::string command;
2405 if (!std::getline(std::cin, command))
2408 if (command == "quit")
2411 PonderSearch = false;
2414 else if(command == "stop")
2417 PonderSearch = false;
2419 else if(command == "ponderhit")
2422 // Print search information
2426 else if (lastInfoTime > t)
2427 // HACK: Must be a new search where we searched less than
2428 // NodesBetweenPolls nodes during the first second of search.
2431 else if (t - lastInfoTime >= 1000)
2438 if (dbg_show_hit_rate)
2439 dbg_print_hit_rate();
2441 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2442 << " time " << t << " hashfull " << TT.full() << std::endl;
2443 lock_release(&IOLock);
2444 if (ShowCurrentLine)
2445 Threads[0].printCurrentLine = true;
2447 // Should we stop the search?
2451 bool overTime = t > AbsoluteMaxSearchTime
2452 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2453 || ( !FailHigh && !fail_high_ply_1() && !Problem
2454 && t > 6*(MaxSearchTime + ExtraSearchTime));
2456 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2457 || (ExactMaxTime && t >= ExactMaxTime)
2458 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2463 // ponderhit() is called when the program is pondering (i.e. thinking while
2464 // it's the opponent's turn to move) in order to let the engine know that
2465 // it correctly predicted the opponent's move.
2468 int t = current_search_time();
2469 PonderSearch = false;
2470 if(Iteration >= 2 &&
2471 (!InfiniteSearch && (StopOnPonderhit ||
2472 t > AbsoluteMaxSearchTime ||
2473 (RootMoveNumber == 1 &&
2474 t > MaxSearchTime + ExtraSearchTime) ||
2475 (!FailHigh && !fail_high_ply_1() && !Problem &&
2476 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2481 // print_current_line() prints the current line of search for a given
2482 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2484 void print_current_line(SearchStack ss[], int ply, int threadID) {
2485 assert(ply >= 0 && ply < PLY_MAX);
2486 assert(threadID >= 0 && threadID < ActiveThreads);
2488 if(!Threads[threadID].idle) {
2490 std::cout << "info currline " << (threadID + 1);
2491 for(int p = 0; p < ply; p++)
2492 std::cout << " " << ss[p].currentMove;
2493 std::cout << std::endl;
2494 lock_release(&IOLock);
2496 Threads[threadID].printCurrentLine = false;
2497 if(threadID + 1 < ActiveThreads)
2498 Threads[threadID + 1].printCurrentLine = true;
2502 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2503 // while the program is pondering. The point is to work around a wrinkle in
2504 // the UCI protocol: When pondering, the engine is not allowed to give a
2505 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2506 // We simply wait here until one of these commands is sent, and return,
2507 // after which the bestmove and pondermove will be printed (in id_loop()).
2509 void wait_for_stop_or_ponderhit() {
2510 std::string command;
2513 if(!std::getline(std::cin, command))
2516 if(command == "quit") {
2517 OpeningBook.close();
2522 else if(command == "ponderhit" || command == "stop")
2528 // idle_loop() is where the threads are parked when they have no work to do.
2529 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2530 // object for which the current thread is the master.
2532 void idle_loop(int threadID, SplitPoint *waitSp) {
2533 assert(threadID >= 0 && threadID < THREAD_MAX);
2535 Threads[threadID].running = true;
2538 if(AllThreadsShouldExit && threadID != 0)
2541 // If we are not thinking, wait for a condition to be signaled instead
2542 // of wasting CPU time polling for work:
2543 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2544 #if !defined(_MSC_VER)
2545 pthread_mutex_lock(&WaitLock);
2546 if(Idle || threadID >= ActiveThreads)
2547 pthread_cond_wait(&WaitCond, &WaitLock);
2548 pthread_mutex_unlock(&WaitLock);
2550 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2554 // If this thread has been assigned work, launch a search:
2555 if(Threads[threadID].workIsWaiting) {
2556 Threads[threadID].workIsWaiting = false;
2557 if(Threads[threadID].splitPoint->pvNode)
2558 sp_search_pv(Threads[threadID].splitPoint, threadID);
2560 sp_search(Threads[threadID].splitPoint, threadID);
2561 Threads[threadID].idle = true;
2564 // If this thread is the master of a split point and all threads have
2565 // finished their work at this split point, return from the idle loop:
2566 if(waitSp != NULL && waitSp->cpus == 0)
2570 Threads[threadID].running = false;
2574 // init_split_point_stack() is called during program initialization, and
2575 // initializes all split point objects.
2577 void init_split_point_stack() {
2578 for(int i = 0; i < THREAD_MAX; i++)
2579 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2580 SplitPointStack[i][j].parent = NULL;
2581 lock_init(&(SplitPointStack[i][j].lock), NULL);
2586 // destroy_split_point_stack() is called when the program exits, and
2587 // destroys all locks in the precomputed split point objects.
2589 void destroy_split_point_stack() {
2590 for(int i = 0; i < THREAD_MAX; i++)
2591 for(int j = 0; j < MaxActiveSplitPoints; j++)
2592 lock_destroy(&(SplitPointStack[i][j].lock));
2596 // thread_should_stop() checks whether the thread with a given threadID has
2597 // been asked to stop, directly or indirectly. This can happen if a beta
2598 // cutoff has occured in thre thread's currently active split point, or in
2599 // some ancestor of the current split point.
2601 bool thread_should_stop(int threadID) {
2602 assert(threadID >= 0 && threadID < ActiveThreads);
2606 if(Threads[threadID].stop)
2608 if(ActiveThreads <= 2)
2610 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2612 Threads[threadID].stop = true;
2619 // thread_is_available() checks whether the thread with threadID "slave" is
2620 // available to help the thread with threadID "master" at a split point. An
2621 // obvious requirement is that "slave" must be idle. With more than two
2622 // threads, this is not by itself sufficient: If "slave" is the master of
2623 // some active split point, it is only available as a slave to the other
2624 // threads which are busy searching the split point at the top of "slave"'s
2625 // split point stack (the "helpful master concept" in YBWC terminology).
2627 bool thread_is_available(int slave, int master) {
2628 assert(slave >= 0 && slave < ActiveThreads);
2629 assert(master >= 0 && master < ActiveThreads);
2630 assert(ActiveThreads > 1);
2632 if(!Threads[slave].idle || slave == master)
2635 if(Threads[slave].activeSplitPoints == 0)
2636 // No active split points means that the thread is available as a slave
2637 // for any other thread.
2640 if(ActiveThreads == 2)
2643 // Apply the "helpful master" concept if possible.
2644 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2651 // idle_thread_exists() tries to find an idle thread which is available as
2652 // a slave for the thread with threadID "master".
2654 bool idle_thread_exists(int master) {
2655 assert(master >= 0 && master < ActiveThreads);
2656 assert(ActiveThreads > 1);
2658 for(int i = 0; i < ActiveThreads; i++)
2659 if(thread_is_available(i, master))
2665 // split() does the actual work of distributing the work at a node between
2666 // several threads at PV nodes. If it does not succeed in splitting the
2667 // node (because no idle threads are available, or because we have no unused
2668 // split point objects), the function immediately returns false. If
2669 // splitting is possible, a SplitPoint object is initialized with all the
2670 // data that must be copied to the helper threads (the current position and
2671 // search stack, alpha, beta, the search depth, etc.), and we tell our
2672 // helper threads that they have been assigned work. This will cause them
2673 // to instantly leave their idle loops and call sp_search_pv(). When all
2674 // threads have returned from sp_search_pv (or, equivalently, when
2675 // splitPoint->cpus becomes 0), split() returns true.
2677 bool split(const Position &p, SearchStack *sstck, int ply,
2678 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2679 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2682 assert(sstck != NULL);
2683 assert(ply >= 0 && ply < PLY_MAX);
2684 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2685 assert(!pvNode || *alpha < *beta);
2686 assert(*beta <= VALUE_INFINITE);
2687 assert(depth > Depth(0));
2688 assert(master >= 0 && master < ActiveThreads);
2689 assert(ActiveThreads > 1);
2691 SplitPoint *splitPoint;
2696 // If no other thread is available to help us, or if we have too many
2697 // active split points, don't split:
2698 if(!idle_thread_exists(master) ||
2699 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2700 lock_release(&MPLock);
2704 // Pick the next available split point object from the split point stack:
2705 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2706 Threads[master].activeSplitPoints++;
2708 // Initialize the split point object:
2709 splitPoint->parent = Threads[master].splitPoint;
2710 splitPoint->finished = false;
2711 splitPoint->ply = ply;
2712 splitPoint->depth = depth;
2713 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2714 splitPoint->beta = *beta;
2715 splitPoint->pvNode = pvNode;
2716 splitPoint->dcCandidates = dcCandidates;
2717 splitPoint->bestValue = *bestValue;
2718 splitPoint->master = master;
2719 splitPoint->mp = mp;
2720 splitPoint->moves = *moves;
2721 splitPoint->cpus = 1;
2722 splitPoint->pos.copy(p);
2723 splitPoint->parentSstack = sstck;
2724 for(i = 0; i < ActiveThreads; i++)
2725 splitPoint->slaves[i] = 0;
2727 // Copy the current position and the search stack to the master thread:
2728 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2729 Threads[master].splitPoint = splitPoint;
2731 // Make copies of the current position and search stack for each thread:
2732 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2734 if(thread_is_available(i, master)) {
2735 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2736 Threads[i].splitPoint = splitPoint;
2737 splitPoint->slaves[i] = 1;
2741 // Tell the threads that they have work to do. This will make them leave
2743 for(i = 0; i < ActiveThreads; i++)
2744 if(i == master || splitPoint->slaves[i]) {
2745 Threads[i].workIsWaiting = true;
2746 Threads[i].idle = false;
2747 Threads[i].stop = false;
2750 lock_release(&MPLock);
2752 // Everything is set up. The master thread enters the idle loop, from
2753 // which it will instantly launch a search, because its workIsWaiting
2754 // slot is 'true'. We send the split point as a second parameter to the
2755 // idle loop, which means that the main thread will return from the idle
2756 // loop when all threads have finished their work at this split point
2757 // (i.e. when // splitPoint->cpus == 0).
2758 idle_loop(master, splitPoint);
2760 // We have returned from the idle loop, which means that all threads are
2761 // finished. Update alpha, beta and bestvalue, and return:
2763 if(pvNode) *alpha = splitPoint->alpha;
2764 *beta = splitPoint->beta;
2765 *bestValue = splitPoint->bestValue;
2766 Threads[master].stop = false;
2767 Threads[master].idle = false;
2768 Threads[master].activeSplitPoints--;
2769 Threads[master].splitPoint = splitPoint->parent;
2770 lock_release(&MPLock);
2776 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2777 // to start a new search from the root.
2779 void wake_sleeping_threads() {
2780 if(ActiveThreads > 1) {
2781 for(int i = 1; i < ActiveThreads; i++) {
2782 Threads[i].idle = true;
2783 Threads[i].workIsWaiting = false;
2785 #if !defined(_MSC_VER)
2786 pthread_mutex_lock(&WaitLock);
2787 pthread_cond_broadcast(&WaitCond);
2788 pthread_mutex_unlock(&WaitLock);
2790 for(int i = 1; i < THREAD_MAX; i++)
2791 SetEvent(SitIdleEvent[i]);
2797 // init_thread() is the function which is called when a new thread is
2798 // launched. It simply calls the idle_loop() function with the supplied
2799 // threadID. There are two versions of this function; one for POSIX threads
2800 // and one for Windows threads.
2802 #if !defined(_MSC_VER)
2804 void *init_thread(void *threadID) {
2805 idle_loop(*(int *)threadID, NULL);
2811 DWORD WINAPI init_thread(LPVOID threadID) {
2812 idle_loop(*(int *)threadID, NULL);