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, at frontier
166 // nodes, and at pre-frontier nodes
167 Value FutilityMargin0 = Value(0x80);
168 Value FutilityMargin1 = Value(0x100);
169 Value FutilityMargin2 = Value(0x200);
170 const Value FutilityMargins[6] = { Value(0x120), Value(0x220), Value(0x250),
171 Value(0x280), Value(0x320), Value(0x360) };
174 Depth RazorDepth = 4*OnePly;
175 Value RazorMargin = Value(0x300);
177 // Last seconds noise filtering (LSN)
178 bool UseLSNFiltering = false;
179 bool looseOnTime = false;
180 int LSNTime = 4 * 1000; // In milliseconds
181 Value LSNValue = Value(0x200);
183 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
184 Depth CheckExtension[2] = {OnePly, OnePly};
185 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
186 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
187 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
188 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
189 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
191 // Search depth at iteration 1
192 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
196 int NodesBetweenPolls = 30000;
198 // Iteration counters
201 BetaCounterType BetaCounter;
203 // Scores and number of times the best move changed for each iteration:
204 Value ValueByIteration[PLY_MAX_PLUS_2];
205 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
210 // Time managment variables
212 int MaxNodes, MaxDepth;
213 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
214 Move BestRootMove, PonderMove, EasyMove;
218 bool StopOnPonderhit;
223 bool PonderingEnabled;
226 // Show current line?
227 bool ShowCurrentLine = false;
230 bool UseLogFile = false;
231 std::ofstream LogFile;
233 // MP related variables
234 Depth MinimumSplitDepth = 4*OnePly;
235 int MaxThreadsPerSplitPoint = 4;
236 Thread Threads[THREAD_MAX];
238 bool AllThreadsShouldExit = false;
239 const int MaxActiveSplitPoints = 8;
240 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
243 #if !defined(_MSC_VER)
244 pthread_cond_t WaitCond;
245 pthread_mutex_t WaitLock;
247 HANDLE SitIdleEvent[THREAD_MAX];
253 Value id_loop(const Position &pos, Move searchMoves[]);
254 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
255 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
256 Depth depth, int ply, int threadID);
257 Value search(Position &pos, SearchStack ss[], Value beta,
258 Depth depth, int ply, bool allowNullmove, int threadID);
259 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
260 Depth depth, int ply, int threadID);
261 void sp_search(SplitPoint *sp, int threadID);
262 void sp_search_pv(SplitPoint *sp, int threadID);
263 void init_search_stack(SearchStack& ss);
264 void init_search_stack(SearchStack ss[]);
265 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
266 void update_pv(SearchStack ss[], int ply);
267 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
268 bool connected_moves(const Position &pos, Move m1, Move m2);
269 bool value_is_mate(Value value);
270 bool move_is_killer(Move m, const SearchStack& ss);
271 Depth extension(const Position &pos, Move m, bool pvNode, bool check, bool singleReply, bool mateThreat, bool* dangerous);
272 bool ok_to_do_nullmove(const Position &pos);
273 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
274 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
275 bool ok_to_history(const Position &pos, Move m);
276 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
277 void update_killers(Move m, SearchStack& ss);
279 bool fail_high_ply_1();
280 int current_search_time();
284 void print_current_line(SearchStack ss[], int ply, int threadID);
285 void wait_for_stop_or_ponderhit();
287 void idle_loop(int threadID, SplitPoint *waitSp);
288 void init_split_point_stack();
289 void destroy_split_point_stack();
290 bool thread_should_stop(int threadID);
291 bool thread_is_available(int slave, int master);
292 bool idle_thread_exists(int master);
293 bool split(const Position &pos, SearchStack *ss, int ply,
294 Value *alpha, Value *beta, Value *bestValue, Depth depth,
295 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
297 void wake_sleeping_threads();
299 #if !defined(_MSC_VER)
300 void *init_thread(void *threadID);
302 DWORD WINAPI init_thread(LPVOID threadID);
309 //// Global variables
312 // The main transposition table
313 TranspositionTable TT = TranspositionTable(TTDefaultSize);
316 // Number of active threads:
317 int ActiveThreads = 1;
319 // Locks. In principle, there is no need for IOLock to be a global variable,
320 // but it could turn out to be useful for debugging.
323 History H; // Should be made local?
325 // The empty search stack
326 SearchStack EmptySearchStack;
333 /// think() is the external interface to Stockfish's search, and is called when
334 /// the program receives the UCI 'go' command. It initializes various
335 /// search-related global variables, and calls root_search()
337 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
338 int time[], int increment[], int movesToGo, int maxDepth,
339 int maxNodes, int maxTime, Move searchMoves[]) {
341 // Look for a book move
342 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
345 if (get_option_value_string("Book File") != OpeningBook.file_name())
348 OpeningBook.open("book.bin");
350 bookMove = OpeningBook.get_move(pos);
351 if (bookMove != MOVE_NONE)
353 std::cout << "bestmove " << bookMove << std::endl;
358 // Initialize global search variables
360 SearchStartTime = get_system_time();
361 BestRootMove = MOVE_NONE;
362 PonderMove = MOVE_NONE;
363 EasyMove = MOVE_NONE;
364 for (int i = 0; i < THREAD_MAX; i++)
366 Threads[i].nodes = 0ULL;
367 Threads[i].failHighPly1 = false;
370 InfiniteSearch = infinite;
371 PonderSearch = ponder;
372 StopOnPonderhit = false;
377 ExactMaxTime = maxTime;
379 // Read UCI option values
380 TT.set_size(get_option_value_int("Hash"));
381 if (button_was_pressed("Clear Hash"))
384 PonderingEnabled = get_option_value_bool("Ponder");
385 MultiPV = get_option_value_int("MultiPV");
387 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
388 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
390 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
391 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
393 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
394 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
396 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
397 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
399 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
400 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
402 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
403 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
405 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
406 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
407 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
408 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
410 Chess960 = get_option_value_bool("UCI_Chess960");
411 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
412 UseLogFile = get_option_value_bool("Use Search Log");
414 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
416 UseNullDrivenIID = get_option_value_bool("Null driven IID");
417 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
418 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
420 FutilityMargin0 = value_from_centipawns(get_option_value_int("Futility Margin 0"));
421 FutilityMargin1 = value_from_centipawns(get_option_value_int("Futility Margin 1"));
422 FutilityMargin2 = value_from_centipawns(get_option_value_int("Futility Margin 2"));
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];
452 int oppTime = time[1 - side_to_move];
454 if (!movesToGo) // Sudden death time control
458 MaxSearchTime = myTime / 30 + myIncrement;
459 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
460 } else { // Blitz game without increment
461 MaxSearchTime = myTime / 30;
462 AbsoluteMaxSearchTime = myTime / 8;
465 else // (x moves) / (y minutes)
469 MaxSearchTime = myTime / 2;
470 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
472 MaxSearchTime = myTime / Min(movesToGo, 20);
473 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
477 if (PonderingEnabled)
479 MaxSearchTime += MaxSearchTime / 4;
480 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
483 // Fixed depth or fixed number of nodes?
486 InfiniteSearch = true; // HACK
491 NodesBetweenPolls = Min(MaxNodes, 30000);
492 InfiniteSearch = true; // HACK
495 NodesBetweenPolls = 30000;
498 // Write information to search log file:
500 LogFile << "Searching: " << pos.to_fen() << std::endl
501 << "infinite: " << infinite
502 << " ponder: " << ponder
503 << " time: " << myTime
504 << " increment: " << myIncrement
505 << " moves to go: " << movesToGo << std::endl;
508 // We're ready to start thinking. Call the iterative deepening loop
512 Value v = id_loop(pos, searchMoves);
513 looseOnTime = ( UseLSNFiltering
520 looseOnTime = false; // reset for next match
521 while (SearchStartTime + myTime + 1000 > get_system_time())
523 id_loop(pos, searchMoves); // to fail gracefully
540 /// init_threads() is called during startup. It launches all helper threads,
541 /// and initializes the split point stack and the global locks and condition
544 void init_threads() {
548 #if !defined(_MSC_VER)
549 pthread_t pthread[1];
552 for (i = 0; i < THREAD_MAX; i++)
553 Threads[i].activeSplitPoints = 0;
555 // Initialize global locks:
556 lock_init(&MPLock, NULL);
557 lock_init(&IOLock, NULL);
559 init_split_point_stack();
561 #if !defined(_MSC_VER)
562 pthread_mutex_init(&WaitLock, NULL);
563 pthread_cond_init(&WaitCond, NULL);
565 for (i = 0; i < THREAD_MAX; i++)
566 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
569 // All threads except the main thread should be initialized to idle state
570 for (i = 1; i < THREAD_MAX; i++)
572 Threads[i].stop = false;
573 Threads[i].workIsWaiting = false;
574 Threads[i].idle = true;
575 Threads[i].running = false;
578 // Launch the helper threads
579 for(i = 1; i < THREAD_MAX; i++)
581 #if !defined(_MSC_VER)
582 pthread_create(pthread, NULL, init_thread, (void*)(&i));
585 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
588 // Wait until the thread has finished launching:
589 while (!Threads[i].running);
592 // Init also the empty search stack
593 init_search_stack(EmptySearchStack);
597 /// stop_threads() is called when the program exits. It makes all the
598 /// helper threads exit cleanly.
600 void stop_threads() {
602 ActiveThreads = THREAD_MAX; // HACK
603 Idle = false; // HACK
604 wake_sleeping_threads();
605 AllThreadsShouldExit = true;
606 for (int i = 1; i < THREAD_MAX; i++)
608 Threads[i].stop = true;
609 while(Threads[i].running);
611 destroy_split_point_stack();
615 /// nodes_searched() returns the total number of nodes searched so far in
616 /// the current search.
618 int64_t nodes_searched() {
620 int64_t result = 0ULL;
621 for (int i = 0; i < ActiveThreads; i++)
622 result += Threads[i].nodes;
629 // id_loop() is the main iterative deepening loop. It calls root_search
630 // repeatedly with increasing depth until the allocated thinking time has
631 // been consumed, the user stops the search, or the maximum search depth is
634 Value id_loop(const Position &pos, Move searchMoves[]) {
637 SearchStack ss[PLY_MAX_PLUS_2];
639 // searchMoves are verified, copied, scored and sorted
640 RootMoveList rml(p, searchMoves);
645 init_search_stack(ss);
647 ValueByIteration[0] = Value(0);
648 ValueByIteration[1] = rml.get_move_score(0);
650 LastIterations = false;
652 EasyMove = rml.scan_for_easy_move();
654 // Iterative deepening loop
655 while (!AbortSearch && Iteration < PLY_MAX)
657 // Initialize iteration
660 BestMoveChangesByIteration[Iteration] = 0;
664 std::cout << "info depth " << Iteration << std::endl;
666 // Search to the current depth
667 ValueByIteration[Iteration] = root_search(p, ss, rml);
669 // Erase the easy move if it differs from the new best move
670 if (ss[0].pv[0] != EasyMove)
671 EasyMove = MOVE_NONE;
678 bool stopSearch = false;
680 // Stop search early if there is only a single legal move:
681 if (Iteration >= 6 && rml.move_count() == 1)
684 // Stop search early when the last two iterations returned a mate score
686 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
687 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
690 // Stop search early if one move seems to be much better than the rest
691 int64_t nodes = nodes_searched();
693 && EasyMove == ss[0].pv[0]
694 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
695 && current_search_time() > MaxSearchTime / 16)
696 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
697 && current_search_time() > MaxSearchTime / 32)))
700 // Add some extra time if the best move has changed during the last two iterations
701 if (Iteration > 5 && Iteration <= 50)
702 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
703 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
705 // Try to guess if the current iteration is the last one or the last two
706 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
708 // Stop search if most of MaxSearchTime is consumed at the end of the
709 // iteration. We probably don't have enough time to search the first
710 // move at the next iteration anyway.
711 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
719 StopOnPonderhit = true;
722 // Write PV to transposition table, in case the relevant entries have
723 // been overwritten during the search:
724 TT.insert_pv(p, ss[0].pv);
726 if (MaxDepth && Iteration >= MaxDepth)
732 // If we are pondering, we shouldn't print the best move before we
735 wait_for_stop_or_ponderhit();
737 // Print final search statistics
738 std::cout << "info nodes " << nodes_searched()
740 << " time " << current_search_time()
741 << " hashfull " << TT.full() << std::endl;
743 // Print the best move and the ponder move to the standard output
744 std::cout << "bestmove " << ss[0].pv[0];
745 if (ss[0].pv[1] != MOVE_NONE)
746 std::cout << " ponder " << ss[0].pv[1];
748 std::cout << std::endl;
753 dbg_print_mean(LogFile);
755 if (dbg_show_hit_rate)
756 dbg_print_hit_rate(LogFile);
759 LogFile << "Nodes: " << nodes_searched() << std::endl
760 << "Nodes/second: " << nps() << std::endl
761 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
763 p.do_move(ss[0].pv[0], u);
764 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
765 << std::endl << std::endl;
767 return rml.get_move_score(0);
771 // root_search() is the function which searches the root node. It is
772 // similar to search_pv except that it uses a different move ordering
773 // scheme (perhaps we should try to use this at internal PV nodes, too?)
774 // and prints some information to the standard output.
776 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
778 Value alpha = -VALUE_INFINITE;
779 Value beta = VALUE_INFINITE, value;
780 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
782 // Loop through all the moves in the root move list
783 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
790 RootMoveNumber = i + 1;
793 // Remember the node count before the move is searched. The node counts
794 // are used to sort the root moves at the next iteration.
795 nodes = nodes_searched();
797 // Reset beta cut-off counters
800 // Pick the next root move, and print the move and the move number to
801 // the standard output.
802 move = ss[0].currentMove = rml.get_move(i);
803 if (current_search_time() >= 1000)
804 std::cout << "info currmove " << move
805 << " currmovenumber " << i + 1 << std::endl;
807 // Decide search depth for this move
809 ext = extension(pos, move, true, pos.move_is_check(move), false, false, &dangerous);
810 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
812 // Make the move, and search it
813 pos.do_move(move, u, dcCandidates);
817 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
818 // If the value has dropped a lot compared to the last iteration,
819 // set the boolean variable Problem to true. This variable is used
820 // for time managment: When Problem is true, we try to complete the
821 // current iteration before playing a move.
822 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
824 if (Problem && StopOnPonderhit)
825 StopOnPonderhit = false;
829 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
832 // Fail high! Set the boolean variable FailHigh to true, and
833 // re-search the move with a big window. The variable FailHigh is
834 // used for time managment: We try to avoid aborting the search
835 // prematurely during a fail high research.
837 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
841 pos.undo_move(move, u);
843 // Finished searching the move. If AbortSearch is true, the search
844 // was aborted because the user interrupted the search or because we
845 // ran out of time. In this case, the return value of the search cannot
846 // be trusted, and we break out of the loop without updating the best
851 // Remember the node count for this move. The node counts are used to
852 // sort the root moves at the next iteration.
853 rml.set_move_nodes(i, nodes_searched() - nodes);
855 // Remember the beta-cutoff statistics
857 BetaCounter.read(pos.side_to_move(), our, their);
858 rml.set_beta_counters(i, our, their);
860 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
862 if (value <= alpha && i >= MultiPV)
863 rml.set_move_score(i, -VALUE_INFINITE);
869 rml.set_move_score(i, value);
871 rml.set_move_pv(i, ss[0].pv);
875 // We record how often the best move has been changed in each
876 // iteration. This information is used for time managment: When
877 // the best move changes frequently, we allocate some more time.
879 BestMoveChangesByIteration[Iteration]++;
881 // Print search information to the standard output:
882 std::cout << "info depth " << Iteration
883 << " score " << value_to_string(value)
884 << " time " << current_search_time()
885 << " nodes " << nodes_searched()
889 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
890 std::cout << ss[0].pv[j] << " ";
892 std::cout << std::endl;
895 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
900 // Reset the global variable Problem to false if the value isn't too
901 // far below the final value from the last iteration.
902 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
908 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
911 std::cout << "info multipv " << j + 1
912 << " score " << value_to_string(rml.get_move_score(j))
913 << " depth " << ((j <= i)? Iteration : Iteration - 1)
914 << " time " << current_search_time()
915 << " nodes " << nodes_searched()
919 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
920 std::cout << rml.get_move_pv(j, k) << " ";
922 std::cout << std::endl;
924 alpha = rml.get_move_score(Min(i, MultiPV-1));
932 // search_pv() is the main search function for PV nodes.
934 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
935 Depth depth, int ply, int threadID) {
937 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
938 assert(beta > alpha && beta <= VALUE_INFINITE);
939 assert(ply >= 0 && ply < PLY_MAX);
940 assert(threadID >= 0 && threadID < ActiveThreads);
943 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
945 // Initialize, and make an early exit in case of an aborted search,
946 // an instant draw, maximum ply reached, etc.
947 init_node(pos, ss, ply, threadID);
949 // After init_node() that calls poll()
950 if (AbortSearch || thread_should_stop(threadID))
958 if (ply >= PLY_MAX - 1)
959 return evaluate(pos, ei, threadID);
961 // Mate distance pruning
962 Value oldAlpha = alpha;
963 alpha = Max(value_mated_in(ply), alpha);
964 beta = Min(value_mate_in(ply+1), beta);
968 // Transposition table lookup. At PV nodes, we don't use the TT for
969 // pruning, but only for move ordering.
970 const TTEntry* tte = TT.retrieve(pos);
971 Move ttMove = (tte ? tte->move() : MOVE_NONE);
973 // Go with internal iterative deepening if we don't have a TT move
974 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
976 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
977 ttMove = ss[ply].pv[ply];
980 // Initialize a MovePicker object for the current position, and prepare
981 // to search all moves
982 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
984 Move move, movesSearched[256];
986 Value value, bestValue = -VALUE_INFINITE;
987 Bitboard dcCandidates = mp.discovered_check_candidates();
988 bool isCheck = pos.is_check();
989 bool mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
991 // Loop through all legal moves until no moves remain or a beta cutoff
994 && (move = mp.get_next_move()) != MOVE_NONE
995 && !thread_should_stop(threadID))
997 assert(move_is_ok(move));
999 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1000 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1001 bool moveIsCapture = pos.move_is_capture(move);
1003 movesSearched[moveCount++] = ss[ply].currentMove = move;
1006 ss[ply].currentMoveCaptureValue =
1007 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1009 ss[ply].currentMoveCaptureValue = Value(0);
1011 // Decide the new search depth
1013 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat, &dangerous);
1014 Depth newDepth = depth - OnePly + ext;
1016 // Make and search the move
1018 pos.do_move(move, u, dcCandidates);
1020 if (moveCount == 1) // The first move in list is the PV
1021 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1024 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1025 // if the move fails high will be re-searched at full depth.
1026 if ( depth >= 2*OnePly
1027 && moveCount >= LMRPVMoves
1030 && !move_promotion(move)
1031 && !move_is_castle(move)
1032 && !move_is_killer(move, ss[ply]))
1034 ss[ply].reduction = OnePly;
1035 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1038 value = alpha + 1; // Just to trigger next condition
1040 if (value > alpha) // Go with full depth non-pv search
1042 ss[ply].reduction = Depth(0);
1043 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1044 if (value > alpha && value < beta)
1046 // When the search fails high at ply 1 while searching the first
1047 // move at the root, set the flag failHighPly1. This is used for
1048 // time managment: We don't want to stop the search early in
1049 // such cases, because resolving the fail high at ply 1 could
1050 // result in a big drop in score at the root.
1051 if (ply == 1 && RootMoveNumber == 1)
1052 Threads[threadID].failHighPly1 = true;
1054 // A fail high occurred. Re-search at full window (pv search)
1055 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1056 Threads[threadID].failHighPly1 = false;
1060 pos.undo_move(move, u);
1062 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1065 if (value > bestValue)
1072 if (value == value_mate_in(ply + 1))
1073 ss[ply].mateKiller = move;
1075 // If we are at ply 1, and we are searching the first root move at
1076 // ply 0, set the 'Problem' variable if the score has dropped a lot
1077 // (from the computer's point of view) since the previous iteration:
1080 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1085 if ( ActiveThreads > 1
1087 && depth >= MinimumSplitDepth
1089 && idle_thread_exists(threadID)
1091 && !thread_should_stop(threadID)
1092 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1093 &moveCount, &mp, dcCandidates, threadID, true))
1097 // All legal moves have been searched. A special case: If there were
1098 // no legal moves, it must be mate or stalemate:
1100 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1102 // If the search is not aborted, update the transposition table,
1103 // history counters, and killer moves.
1104 if (AbortSearch || thread_should_stop(threadID))
1107 if (bestValue <= oldAlpha)
1108 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1110 else if (bestValue >= beta)
1112 BetaCounter.add(pos.side_to_move(), depth, threadID);
1113 Move m = ss[ply].pv[ply];
1114 if (ok_to_history(pos, m)) // Only non capture moves are considered
1116 update_history(pos, m, depth, movesSearched, moveCount);
1117 update_killers(m, ss[ply]);
1119 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1122 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1128 // search() is the search function for zero-width nodes.
1130 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1131 int ply, bool allowNullmove, int threadID) {
1133 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1134 assert(ply >= 0 && ply < PLY_MAX);
1135 assert(threadID >= 0 && threadID < ActiveThreads);
1138 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1140 // Initialize, and make an early exit in case of an aborted search,
1141 // an instant draw, maximum ply reached, etc.
1142 init_node(pos, ss, ply, threadID);
1144 // After init_node() that calls poll()
1145 if (AbortSearch || thread_should_stop(threadID))
1153 if (ply >= PLY_MAX - 1)
1154 return evaluate(pos, ei, threadID);
1156 // Mate distance pruning
1157 if (value_mated_in(ply) >= beta)
1160 if (value_mate_in(ply + 1) < beta)
1163 // Transposition table lookup
1164 const TTEntry* tte = TT.retrieve(pos);
1165 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1167 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1169 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1170 return value_from_tt(tte->value(), ply);
1173 Value approximateEval = quick_evaluate(pos);
1174 bool mateThreat = false;
1175 bool nullDrivenIID = false;
1176 bool isCheck = pos.is_check();
1182 && !value_is_mate(beta)
1183 && ok_to_do_nullmove(pos)
1184 && approximateEval >= beta - NullMoveMargin)
1186 ss[ply].currentMove = MOVE_NULL;
1189 pos.do_null_move(u);
1190 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1192 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1194 // Check for a null capture artifact, if the value without the null capture
1195 // is above beta then mark the node as a suspicious failed low. We will verify
1196 // later if we are really under threat.
1197 if ( UseNullDrivenIID
1199 && depth > 6 * OnePly
1200 &&!value_is_mate(nullValue)
1201 && ttMove == MOVE_NONE
1202 && ss[ply + 1].currentMove != MOVE_NONE
1203 && pos.move_is_capture(ss[ply + 1].currentMove)
1204 && pos.see(ss[ply + 1].currentMove) + nullValue >= beta)
1205 nullDrivenIID = true;
1207 pos.undo_null_move(u);
1209 if (value_is_mate(nullValue))
1211 /* Do not return unproven mates */
1213 else if (nullValue >= beta)
1215 if (depth < 6 * OnePly)
1218 // Do zugzwang verification search
1219 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1223 // The null move failed low, which means that we may be faced with
1224 // some kind of threat. If the previous move was reduced, check if
1225 // the move that refuted the null move was somehow connected to the
1226 // move which was reduced. If a connection is found, return a fail
1227 // low score (which will cause the reduced move to fail high in the
1228 // parent node, which will trigger a re-search with full depth).
1229 if (nullValue == value_mated_in(ply + 2))
1232 nullDrivenIID = false;
1234 ss[ply].threatMove = ss[ply + 1].currentMove;
1235 if ( depth < ThreatDepth
1236 && ss[ply - 1].reduction
1237 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1241 // Null move search not allowed, try razoring
1242 else if ( !value_is_mate(beta)
1243 && approximateEval < beta - RazorMargin
1244 && depth < RazorDepth
1246 && ttMove == MOVE_NONE
1247 && !pos.has_pawn_on_7th(pos.side_to_move()))
1249 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1250 if (v < beta - RazorMargin / 2 - int(depth - OnePly) * RazorMargin / 8)
1254 // Go with internal iterative deepening if we don't have a TT move
1255 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1256 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1258 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1259 ttMove = ss[ply].pv[ply];
1261 else if (nullDrivenIID)
1263 // The null move failed low due to a suspicious capture. Perhaps we
1264 // are facing a null capture artifact due to the side to move change
1265 // and this position should fail high. So do a normal search with a
1266 // reduced depth to get a good ttMove to use in the following full
1268 Move tm = ss[ply].threatMove;
1270 assert(tm != MOVE_NONE);
1271 assert(ttMove == MOVE_NONE);
1273 search(pos, ss, beta, depth/2, ply, false, threadID);
1274 ttMove = ss[ply].pv[ply];
1275 ss[ply].threatMove = tm;
1278 // Initialize a MovePicker object for the current position, and prepare
1279 // to search all moves:
1280 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1282 Move move, movesSearched[256];
1284 Value value, bestValue = -VALUE_INFINITE;
1285 Bitboard dcCandidates = mp.discovered_check_candidates();
1286 Value futilityValue = VALUE_NONE;
1287 bool useFutilityPruning = UseFutilityPruning
1288 && depth < SelectiveDepth
1291 // Loop through all legal moves until no moves remain or a beta cutoff
1293 while ( bestValue < beta
1294 && (move = mp.get_next_move()) != MOVE_NONE
1295 && !thread_should_stop(threadID))
1297 assert(move_is_ok(move));
1299 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1300 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1301 bool moveIsCapture = pos.move_is_capture(move);
1303 movesSearched[moveCount++] = ss[ply].currentMove = move;
1305 // Decide the new search depth
1307 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat, &dangerous);
1308 Depth newDepth = depth - OnePly + ext;
1311 if ( useFutilityPruning
1314 && !move_promotion(move))
1316 // History pruning. See ok_to_prune() definition
1317 if ( moveCount >= 2 + int(depth)
1318 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1321 // Value based pruning
1322 if (depth < 7 * OnePly && approximateEval < beta)
1324 if (futilityValue == VALUE_NONE)
1325 futilityValue = evaluate(pos, ei, threadID)
1326 + FutilityMargins[int(depth)/2 - 1]
1329 if (futilityValue < beta)
1331 if (futilityValue > bestValue)
1332 bestValue = futilityValue;
1338 // Make and search the move
1340 pos.do_move(move, u, dcCandidates);
1342 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1343 // if the move fails high will be re-searched at full depth.
1344 if ( depth >= 2*OnePly
1345 && moveCount >= LMRNonPVMoves
1348 && !move_promotion(move)
1349 && !move_is_castle(move)
1350 && !move_is_killer(move, ss[ply]))
1352 ss[ply].reduction = OnePly;
1353 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1356 value = beta; // Just to trigger next condition
1358 if (value >= beta) // Go with full depth non-pv search
1360 ss[ply].reduction = Depth(0);
1361 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1363 pos.undo_move(move, u);
1365 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1368 if (value > bestValue)
1374 if (value == value_mate_in(ply + 1))
1375 ss[ply].mateKiller = move;
1379 if ( ActiveThreads > 1
1381 && depth >= MinimumSplitDepth
1383 && idle_thread_exists(threadID)
1385 && !thread_should_stop(threadID)
1386 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1387 &mp, dcCandidates, threadID, false))
1391 // All legal moves have been searched. A special case: If there were
1392 // no legal moves, it must be mate or stalemate.
1394 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1396 // If the search is not aborted, update the transposition table,
1397 // history counters, and killer moves.
1398 if (AbortSearch || thread_should_stop(threadID))
1401 if (bestValue < beta)
1402 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1405 BetaCounter.add(pos.side_to_move(), depth, threadID);
1406 Move m = ss[ply].pv[ply];
1407 if (ok_to_history(pos, m)) // Only non capture moves are considered
1409 update_history(pos, m, depth, movesSearched, moveCount);
1410 update_killers(m, ss[ply]);
1412 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1418 // qsearch() is the quiescence search function, which is called by the main
1419 // search function when the remaining depth is zero (or, to be more precise,
1420 // less than OnePly).
1422 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1423 Depth depth, int ply, int threadID) {
1425 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1426 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1428 assert(ply >= 0 && ply < PLY_MAX);
1429 assert(threadID >= 0 && threadID < ActiveThreads);
1431 // Initialize, and make an early exit in case of an aborted search,
1432 // an instant draw, maximum ply reached, etc.
1433 init_node(pos, ss, ply, threadID);
1435 // After init_node() that calls poll()
1436 if (AbortSearch || thread_should_stop(threadID))
1442 // Transposition table lookup
1443 const TTEntry* tte = TT.retrieve(pos);
1444 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1445 return value_from_tt(tte->value(), ply);
1447 // Evaluate the position statically
1449 bool isCheck = pos.is_check();
1450 Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1452 if (ply == PLY_MAX - 1)
1453 return evaluate(pos, ei, threadID);
1455 // Initialize "stand pat score", and return it immediately if it is
1457 Value bestValue = staticValue;
1459 if (bestValue >= beta)
1462 if (bestValue > alpha)
1465 // Initialize a MovePicker object for the current position, and prepare
1466 // to search the moves. Because the depth is <= 0 here, only captures,
1467 // queen promotions and checks (only if depth == 0) will be generated.
1468 bool pvNode = (beta - alpha != 1);
1469 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1472 Bitboard dcCandidates = mp.discovered_check_candidates();
1473 bool enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1475 // Loop through the moves until no moves remain or a beta cutoff
1477 while ( alpha < beta
1478 && (move = mp.get_next_move()) != MOVE_NONE)
1480 assert(move_is_ok(move));
1483 ss[ply].currentMove = move;
1486 if ( UseQSearchFutilityPruning
1490 && !move_promotion(move)
1491 && !pos.move_is_check(move, dcCandidates)
1492 && !pos.move_is_passed_pawn_push(move))
1494 Value futilityValue = staticValue
1495 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1496 pos.endgame_value_of_piece_on(move_to(move)))
1497 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1499 + ei.futilityMargin;
1501 if (futilityValue < alpha)
1503 if (futilityValue > bestValue)
1504 bestValue = futilityValue;
1509 // Don't search captures and checks with negative SEE values
1511 && !move_promotion(move)
1512 && (pos.midgame_value_of_piece_on(move_from(move)) >
1513 pos.midgame_value_of_piece_on(move_to(move)))
1514 && pos.see(move) < 0)
1517 // Make and search the move.
1519 pos.do_move(move, u, dcCandidates);
1520 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1521 pos.undo_move(move, u);
1523 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1526 if (value > bestValue)
1537 // All legal moves have been searched. A special case: If we're in check
1538 // and no legal moves were found, it is checkmate:
1539 if (pos.is_check() && moveCount == 0) // Mate!
1540 return value_mated_in(ply);
1542 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1544 // Update transposition table
1545 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1547 // Update killers only for good check moves
1548 Move m = ss[ply].currentMove;
1549 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1551 // Wrong to update history when depth is <= 0
1552 update_killers(m, ss[ply]);
1558 // sp_search() is used to search from a split point. This function is called
1559 // by each thread working at the split point. It is similar to the normal
1560 // search() function, but simpler. Because we have already probed the hash
1561 // table, done a null move search, and searched the first move before
1562 // splitting, we don't have to repeat all this work in sp_search(). We
1563 // also don't need to store anything to the hash table here: This is taken
1564 // care of after we return from the split point.
1566 void sp_search(SplitPoint *sp, int threadID) {
1568 assert(threadID >= 0 && threadID < ActiveThreads);
1569 assert(ActiveThreads > 1);
1571 Position pos = Position(sp->pos);
1572 SearchStack *ss = sp->sstack[threadID];
1575 bool isCheck = pos.is_check();
1576 bool useFutilityPruning = UseFutilityPruning
1577 && sp->depth < SelectiveDepth
1580 while ( sp->bestValue < sp->beta
1581 && !thread_should_stop(threadID)
1582 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1584 assert(move_is_ok(move));
1586 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1587 bool moveIsCapture = pos.move_is_capture(move);
1589 lock_grab(&(sp->lock));
1590 int moveCount = ++sp->moves;
1591 lock_release(&(sp->lock));
1593 ss[sp->ply].currentMove = move;
1595 // Decide the new search depth.
1597 Depth ext = extension(pos, move, false, moveIsCheck, false, false, &dangerous);
1598 Depth newDepth = sp->depth - OnePly + ext;
1601 if ( useFutilityPruning
1604 && !move_promotion(move)
1605 && moveCount >= 2 + int(sp->depth)
1606 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1609 // Make and search the move.
1611 pos.do_move(move, u, sp->dcCandidates);
1613 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1614 // if the move fails high will be re-searched at full depth.
1616 && moveCount >= LMRNonPVMoves
1618 && !move_promotion(move)
1619 && !move_is_castle(move)
1620 && !move_is_killer(move, ss[sp->ply]))
1622 ss[sp->ply].reduction = OnePly;
1623 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1626 value = sp->beta; // Just to trigger next condition
1628 if (value >= sp->beta) // Go with full depth non-pv search
1630 ss[sp->ply].reduction = Depth(0);
1631 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1633 pos.undo_move(move, u);
1635 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1637 if (thread_should_stop(threadID))
1641 lock_grab(&(sp->lock));
1642 if (value > sp->bestValue && !thread_should_stop(threadID))
1644 sp->bestValue = value;
1645 if (sp->bestValue >= sp->beta)
1647 sp_update_pv(sp->parentSstack, ss, sp->ply);
1648 for (int i = 0; i < ActiveThreads; i++)
1649 if (i != threadID && (i == sp->master || sp->slaves[i]))
1650 Threads[i].stop = true;
1652 sp->finished = true;
1655 lock_release(&(sp->lock));
1658 lock_grab(&(sp->lock));
1660 // If this is the master thread and we have been asked to stop because of
1661 // a beta cutoff higher up in the tree, stop all slave threads:
1662 if (sp->master == threadID && thread_should_stop(threadID))
1663 for (int i = 0; i < ActiveThreads; i++)
1665 Threads[i].stop = true;
1668 sp->slaves[threadID] = 0;
1670 lock_release(&(sp->lock));
1674 // sp_search_pv() is used to search from a PV split point. This function
1675 // is called by each thread working at the split point. It is similar to
1676 // the normal search_pv() function, but simpler. Because we have already
1677 // probed the hash table and searched the first move before splitting, we
1678 // don't have to repeat all this work in sp_search_pv(). We also don't
1679 // need to store anything to the hash table here: This is taken care of
1680 // after we return from the split point.
1682 void sp_search_pv(SplitPoint *sp, int threadID) {
1684 assert(threadID >= 0 && threadID < ActiveThreads);
1685 assert(ActiveThreads > 1);
1687 Position pos = Position(sp->pos);
1688 SearchStack *ss = sp->sstack[threadID];
1692 while ( sp->alpha < sp->beta
1693 && !thread_should_stop(threadID)
1694 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1696 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1697 bool moveIsCapture = pos.move_is_capture(move);
1699 assert(move_is_ok(move));
1702 ss[sp->ply].currentMoveCaptureValue =
1703 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1705 ss[sp->ply].currentMoveCaptureValue = Value(0);
1707 lock_grab(&(sp->lock));
1708 int moveCount = ++sp->moves;
1709 lock_release(&(sp->lock));
1711 ss[sp->ply].currentMove = move;
1713 // Decide the new search depth.
1715 Depth ext = extension(pos, move, true, moveIsCheck, false, false, &dangerous);
1716 Depth newDepth = sp->depth - OnePly + ext;
1718 // Make and search the move.
1720 pos.do_move(move, u, sp->dcCandidates);
1722 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1723 // if the move fails high will be re-searched at full depth.
1725 && moveCount >= LMRPVMoves
1727 && !move_promotion(move)
1728 && !move_is_castle(move)
1729 && !move_is_killer(move, ss[sp->ply]))
1731 ss[sp->ply].reduction = OnePly;
1732 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1735 value = sp->alpha + 1; // Just to trigger next condition
1737 if (value > sp->alpha) // Go with full depth non-pv search
1739 ss[sp->ply].reduction = Depth(0);
1740 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1742 if (value > sp->alpha && value < sp->beta)
1744 // When the search fails high at ply 1 while searching the first
1745 // move at the root, set the flag failHighPly1. This is used for
1746 // time managment: We don't want to stop the search early in
1747 // such cases, because resolving the fail high at ply 1 could
1748 // result in a big drop in score at the root.
1749 if (sp->ply == 1 && RootMoveNumber == 1)
1750 Threads[threadID].failHighPly1 = true;
1752 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1753 Threads[threadID].failHighPly1 = false;
1756 pos.undo_move(move, u);
1758 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1760 if (thread_should_stop(threadID))
1764 lock_grab(&(sp->lock));
1765 if (value > sp->bestValue && !thread_should_stop(threadID))
1767 sp->bestValue = value;
1768 if (value > sp->alpha)
1771 sp_update_pv(sp->parentSstack, ss, sp->ply);
1772 if (value == value_mate_in(sp->ply + 1))
1773 ss[sp->ply].mateKiller = move;
1775 if(value >= sp->beta)
1777 for(int i = 0; i < ActiveThreads; i++)
1778 if(i != threadID && (i == sp->master || sp->slaves[i]))
1779 Threads[i].stop = true;
1781 sp->finished = true;
1784 // If we are at ply 1, and we are searching the first root move at
1785 // ply 0, set the 'Problem' variable if the score has dropped a lot
1786 // (from the computer's point of view) since the previous iteration.
1789 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1792 lock_release(&(sp->lock));
1795 lock_grab(&(sp->lock));
1797 // If this is the master thread and we have been asked to stop because of
1798 // a beta cutoff higher up in the tree, stop all slave threads.
1799 if (sp->master == threadID && thread_should_stop(threadID))
1800 for (int i = 0; i < ActiveThreads; i++)
1802 Threads[i].stop = true;
1805 sp->slaves[threadID] = 0;
1807 lock_release(&(sp->lock));
1810 /// The BetaCounterType class
1812 BetaCounterType::BetaCounterType() { clear(); }
1814 void BetaCounterType::clear() {
1816 for (int i = 0; i < THREAD_MAX; i++)
1817 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1820 void BetaCounterType::add(Color us, Depth d, int threadID) {
1822 // Weighted count based on depth
1823 hits[threadID][us] += int(d);
1826 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1829 for (int i = 0; i < THREAD_MAX; i++)
1832 their += hits[i][opposite_color(us)];
1837 /// The RootMove class
1841 RootMove::RootMove() {
1842 nodes = cumulativeNodes = 0ULL;
1845 // RootMove::operator<() is the comparison function used when
1846 // sorting the moves. A move m1 is considered to be better
1847 // than a move m2 if it has a higher score, or if the moves
1848 // have equal score but m1 has the higher node count.
1850 bool RootMove::operator<(const RootMove& m) {
1852 if (score != m.score)
1853 return (score < m.score);
1855 return theirBeta <= m.theirBeta;
1858 /// The RootMoveList class
1862 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1864 MoveStack mlist[MaxRootMoves];
1865 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1867 // Generate all legal moves
1868 int lm_count = generate_legal_moves(pos, mlist);
1870 // Add each move to the moves[] array
1871 for (int i = 0; i < lm_count; i++)
1873 bool includeMove = includeAllMoves;
1875 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1876 includeMove = (searchMoves[k] == mlist[i].move);
1880 // Find a quick score for the move
1882 SearchStack ss[PLY_MAX_PLUS_2];
1884 moves[count].move = mlist[i].move;
1885 moves[count].nodes = 0ULL;
1886 pos.do_move(moves[count].move, u);
1887 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1889 pos.undo_move(moves[count].move, u);
1890 moves[count].pv[0] = moves[i].move;
1891 moves[count].pv[1] = MOVE_NONE; // FIXME
1899 // Simple accessor methods for the RootMoveList class
1901 inline Move RootMoveList::get_move(int moveNum) const {
1902 return moves[moveNum].move;
1905 inline Value RootMoveList::get_move_score(int moveNum) const {
1906 return moves[moveNum].score;
1909 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1910 moves[moveNum].score = score;
1913 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1914 moves[moveNum].nodes = nodes;
1915 moves[moveNum].cumulativeNodes += nodes;
1918 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1919 moves[moveNum].ourBeta = our;
1920 moves[moveNum].theirBeta = their;
1923 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1925 for(j = 0; pv[j] != MOVE_NONE; j++)
1926 moves[moveNum].pv[j] = pv[j];
1927 moves[moveNum].pv[j] = MOVE_NONE;
1930 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1931 return moves[moveNum].pv[i];
1934 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1935 return moves[moveNum].cumulativeNodes;
1938 inline int RootMoveList::move_count() const {
1943 // RootMoveList::scan_for_easy_move() is called at the end of the first
1944 // iteration, and is used to detect an "easy move", i.e. a move which appears
1945 // to be much bester than all the rest. If an easy move is found, the move
1946 // is returned, otherwise the function returns MOVE_NONE. It is very
1947 // important that this function is called at the right moment: The code
1948 // assumes that the first iteration has been completed and the moves have
1949 // been sorted. This is done in RootMoveList c'tor.
1951 Move RootMoveList::scan_for_easy_move() const {
1958 // moves are sorted so just consider the best and the second one
1959 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1965 // RootMoveList::sort() sorts the root move list at the beginning of a new
1968 inline void RootMoveList::sort() {
1970 sort_multipv(count - 1); // all items
1974 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1975 // list by their scores and depths. It is used to order the different PVs
1976 // correctly in MultiPV mode.
1978 void RootMoveList::sort_multipv(int n) {
1980 for (int i = 1; i <= n; i++)
1982 RootMove rm = moves[i];
1984 for (j = i; j > 0 && moves[j-1] < rm; j--)
1985 moves[j] = moves[j-1];
1991 // init_search_stack() initializes a search stack at the beginning of a
1992 // new search from the root.
1993 void init_search_stack(SearchStack& ss) {
1995 ss.pv[0] = MOVE_NONE;
1996 ss.pv[1] = MOVE_NONE;
1997 ss.currentMove = MOVE_NONE;
1998 ss.threatMove = MOVE_NONE;
1999 ss.reduction = Depth(0);
2000 for (int j = 0; j < KILLER_MAX; j++)
2001 ss.killers[j] = MOVE_NONE;
2004 void init_search_stack(SearchStack ss[]) {
2006 for (int i = 0; i < 3; i++)
2008 ss[i].pv[i] = MOVE_NONE;
2009 ss[i].pv[i+1] = MOVE_NONE;
2010 ss[i].currentMove = MOVE_NONE;
2011 ss[i].threatMove = MOVE_NONE;
2012 ss[i].reduction = Depth(0);
2013 for (int j = 0; j < KILLER_MAX; j++)
2014 ss[i].killers[j] = MOVE_NONE;
2019 // init_node() is called at the beginning of all the search functions
2020 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2021 // stack object corresponding to the current node. Once every
2022 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2023 // for user input and checks whether it is time to stop the search.
2025 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2026 assert(ply >= 0 && ply < PLY_MAX);
2027 assert(threadID >= 0 && threadID < ActiveThreads);
2029 Threads[threadID].nodes++;
2033 if(NodesSincePoll >= NodesBetweenPolls) {
2038 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
2039 ss[ply+2].mateKiller = MOVE_NONE;
2040 ss[ply].threatMove = MOVE_NONE;
2041 ss[ply].reduction = Depth(0);
2042 ss[ply].currentMoveCaptureValue = Value(0);
2043 for (int j = 0; j < KILLER_MAX; j++)
2044 ss[ply+2].killers[j] = MOVE_NONE;
2046 if(Threads[threadID].printCurrentLine)
2047 print_current_line(ss, ply, threadID);
2051 // update_pv() is called whenever a search returns a value > alpha. It
2052 // updates the PV in the SearchStack object corresponding to the current
2055 void update_pv(SearchStack ss[], int ply) {
2056 assert(ply >= 0 && ply < PLY_MAX);
2058 ss[ply].pv[ply] = ss[ply].currentMove;
2060 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2061 ss[ply].pv[p] = ss[ply+1].pv[p];
2062 ss[ply].pv[p] = MOVE_NONE;
2066 // sp_update_pv() is a variant of update_pv for use at split points. The
2067 // difference between the two functions is that sp_update_pv also updates
2068 // the PV at the parent node.
2070 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2071 assert(ply >= 0 && ply < PLY_MAX);
2073 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2075 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2076 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2077 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2081 // connected_moves() tests whether two moves are 'connected' in the sense
2082 // that the first move somehow made the second move possible (for instance
2083 // if the moving piece is the same in both moves). The first move is
2084 // assumed to be the move that was made to reach the current position, while
2085 // the second move is assumed to be a move from the current position.
2087 bool connected_moves(const Position &pos, Move m1, Move m2) {
2088 Square f1, t1, f2, t2;
2090 assert(move_is_ok(m1));
2091 assert(move_is_ok(m2));
2096 // Case 1: The moving piece is the same in both moves.
2102 // Case 2: The destination square for m2 was vacated by m1.
2108 // Case 3: Moving through the vacated square:
2109 if(piece_is_slider(pos.piece_on(f2)) &&
2110 bit_is_set(squares_between(f2, t2), f1))
2113 // Case 4: The destination square for m2 is attacked by the moving piece
2115 if(pos.piece_attacks_square(t1, t2))
2118 // Case 5: Discovered check, checking piece is the piece moved in m1:
2119 if(piece_is_slider(pos.piece_on(t1)) &&
2120 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2122 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2124 Bitboard occ = pos.occupied_squares();
2125 Color us = pos.side_to_move();
2126 Square ksq = pos.king_square(us);
2127 clear_bit(&occ, f2);
2128 if(pos.type_of_piece_on(t1) == BISHOP) {
2129 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2132 else if(pos.type_of_piece_on(t1) == ROOK) {
2133 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2137 assert(pos.type_of_piece_on(t1) == QUEEN);
2138 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2147 // value_is_mate() checks if the given value is a mate one
2148 // eventually compensated for the ply.
2150 bool value_is_mate(Value value) {
2152 assert(abs(value) <= VALUE_INFINITE);
2154 return value <= value_mated_in(PLY_MAX)
2155 || value >= value_mate_in(PLY_MAX);
2159 // move_is_killer() checks if the given move is among the
2160 // killer moves of that ply.
2162 bool move_is_killer(Move m, const SearchStack& ss) {
2164 const Move* k = ss.killers;
2165 for (int i = 0; i < KILLER_MAX; i++, k++)
2173 // extension() decides whether a move should be searched with normal depth,
2174 // or with extended depth. Certain classes of moves (checking moves, in
2175 // particular) are searched with bigger depth than ordinary moves and in
2176 // any case are marked as 'dangerous'. Note that also if a move is not
2177 // extended, as example because the corresponding UCI option is set to zero,
2178 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2180 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
2181 bool singleReply, bool mateThreat, bool* dangerous) {
2183 assert(m != MOVE_NONE);
2185 Depth result = Depth(0);
2186 *dangerous = check || singleReply || mateThreat;
2189 result += CheckExtension[pvNode];
2192 result += SingleReplyExtension[pvNode];
2195 result += MateThreatExtension[pvNode];
2197 if (pos.move_is_pawn_push_to_7th(m))
2199 result += PawnPushTo7thExtension[pvNode];
2202 if (pos.move_is_passed_pawn_push(m))
2204 result += PassedPawnExtension[pvNode];
2208 if ( pos.move_is_capture(m)
2209 && pos.type_of_piece_on(move_to(m)) != PAWN
2210 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2211 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2212 && !move_promotion(m)
2215 result += PawnEndgameExtension[pvNode];
2220 && pos.move_is_capture(m)
2221 && pos.type_of_piece_on(move_to(m)) != PAWN
2228 return Min(result, OnePly);
2232 // ok_to_do_nullmove() looks at the current position and decides whether
2233 // doing a 'null move' should be allowed. In order to avoid zugzwang
2234 // problems, null moves are not allowed when the side to move has very
2235 // little material left. Currently, the test is a bit too simple: Null
2236 // moves are avoided only when the side to move has only pawns left. It's
2237 // probably a good idea to avoid null moves in at least some more
2238 // complicated endgames, e.g. KQ vs KR. FIXME
2240 bool ok_to_do_nullmove(const Position &pos) {
2241 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2247 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2248 // non-tactical moves late in the move list close to the leaves are
2249 // candidates for pruning.
2251 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2252 Square mfrom, mto, tfrom, tto;
2254 assert(move_is_ok(m));
2255 assert(threat == MOVE_NONE || move_is_ok(threat));
2256 assert(!move_promotion(m));
2257 assert(!pos.move_is_check(m));
2258 assert(!pos.move_is_capture(m));
2259 assert(!pos.move_is_passed_pawn_push(m));
2260 assert(d >= OnePly);
2262 mfrom = move_from(m);
2264 tfrom = move_from(threat);
2265 tto = move_to(threat);
2267 // Case 1: Castling moves are never pruned.
2268 if (move_is_castle(m))
2271 // Case 2: Don't prune moves which move the threatened piece
2272 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2275 // Case 3: If the threatened piece has value less than or equal to the
2276 // value of the threatening piece, don't prune move which defend it.
2277 if ( !PruneDefendingMoves
2278 && threat != MOVE_NONE
2279 && pos.move_is_capture(threat)
2280 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2281 || pos.type_of_piece_on(tfrom) == KING)
2282 && pos.move_attacks_square(m, tto))
2285 // Case 4: Don't prune moves with good history.
2286 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2289 // Case 5: If the moving piece in the threatened move is a slider, don't
2290 // prune safe moves which block its ray.
2291 if ( !PruneBlockingMoves
2292 && threat != MOVE_NONE
2293 && piece_is_slider(pos.piece_on(tfrom))
2294 && bit_is_set(squares_between(tfrom, tto), mto)
2302 // ok_to_use_TT() returns true if a transposition table score
2303 // can be used at a given point in search.
2305 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2307 Value v = value_from_tt(tte->value(), ply);
2309 return ( tte->depth() >= depth
2310 || v >= Max(value_mate_in(100), beta)
2311 || v < Min(value_mated_in(100), beta))
2313 && ( (is_lower_bound(tte->type()) && v >= beta)
2314 || (is_upper_bound(tte->type()) && v < beta));
2318 // ok_to_history() returns true if a move m can be stored
2319 // in history. Should be a non capturing move nor a promotion.
2321 bool ok_to_history(const Position& pos, Move m) {
2323 return !pos.move_is_capture(m) && !move_promotion(m);
2327 // update_history() registers a good move that produced a beta-cutoff
2328 // in history and marks as failures all the other moves of that ply.
2330 void update_history(const Position& pos, Move m, Depth depth,
2331 Move movesSearched[], int moveCount) {
2333 H.success(pos.piece_on(move_from(m)), m, depth);
2335 for (int i = 0; i < moveCount - 1; i++)
2337 assert(m != movesSearched[i]);
2338 if (ok_to_history(pos, movesSearched[i]))
2339 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2344 // update_killers() add a good move that produced a beta-cutoff
2345 // among the killer moves of that ply.
2347 void update_killers(Move m, SearchStack& ss) {
2349 if (m == ss.killers[0])
2352 for (int i = KILLER_MAX - 1; i > 0; i--)
2353 ss.killers[i] = ss.killers[i - 1];
2358 // fail_high_ply_1() checks if some thread is currently resolving a fail
2359 // high at ply 1 at the node below the first root node. This information
2360 // is used for time managment.
2362 bool fail_high_ply_1() {
2363 for(int i = 0; i < ActiveThreads; i++)
2364 if(Threads[i].failHighPly1)
2370 // current_search_time() returns the number of milliseconds which have passed
2371 // since the beginning of the current search.
2373 int current_search_time() {
2374 return get_system_time() - SearchStartTime;
2378 // nps() computes the current nodes/second count.
2381 int t = current_search_time();
2382 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2386 // poll() performs two different functions: It polls for user input, and it
2387 // looks at the time consumed so far and decides if it's time to abort the
2392 static int lastInfoTime;
2393 int t = current_search_time();
2398 // We are line oriented, don't read single chars
2399 std::string command;
2400 if (!std::getline(std::cin, command))
2403 if (command == "quit")
2406 PonderSearch = false;
2409 else if(command == "stop")
2412 PonderSearch = false;
2414 else if(command == "ponderhit")
2417 // Print search information
2421 else if (lastInfoTime > t)
2422 // HACK: Must be a new search where we searched less than
2423 // NodesBetweenPolls nodes during the first second of search.
2426 else if (t - lastInfoTime >= 1000)
2433 if (dbg_show_hit_rate)
2434 dbg_print_hit_rate();
2436 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2437 << " time " << t << " hashfull " << TT.full() << std::endl;
2438 lock_release(&IOLock);
2439 if (ShowCurrentLine)
2440 Threads[0].printCurrentLine = true;
2442 // Should we stop the search?
2446 bool overTime = t > AbsoluteMaxSearchTime
2447 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2448 || ( !FailHigh && !fail_high_ply_1() && !Problem
2449 && t > 6*(MaxSearchTime + ExtraSearchTime));
2451 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2452 || (ExactMaxTime && t >= ExactMaxTime)
2453 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2458 // ponderhit() is called when the program is pondering (i.e. thinking while
2459 // it's the opponent's turn to move) in order to let the engine know that
2460 // it correctly predicted the opponent's move.
2463 int t = current_search_time();
2464 PonderSearch = false;
2465 if(Iteration >= 2 &&
2466 (!InfiniteSearch && (StopOnPonderhit ||
2467 t > AbsoluteMaxSearchTime ||
2468 (RootMoveNumber == 1 &&
2469 t > MaxSearchTime + ExtraSearchTime) ||
2470 (!FailHigh && !fail_high_ply_1() && !Problem &&
2471 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2476 // print_current_line() prints the current line of search for a given
2477 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2479 void print_current_line(SearchStack ss[], int ply, int threadID) {
2480 assert(ply >= 0 && ply < PLY_MAX);
2481 assert(threadID >= 0 && threadID < ActiveThreads);
2483 if(!Threads[threadID].idle) {
2485 std::cout << "info currline " << (threadID + 1);
2486 for(int p = 0; p < ply; p++)
2487 std::cout << " " << ss[p].currentMove;
2488 std::cout << std::endl;
2489 lock_release(&IOLock);
2491 Threads[threadID].printCurrentLine = false;
2492 if(threadID + 1 < ActiveThreads)
2493 Threads[threadID + 1].printCurrentLine = true;
2497 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2498 // while the program is pondering. The point is to work around a wrinkle in
2499 // the UCI protocol: When pondering, the engine is not allowed to give a
2500 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2501 // We simply wait here until one of these commands is sent, and return,
2502 // after which the bestmove and pondermove will be printed (in id_loop()).
2504 void wait_for_stop_or_ponderhit() {
2505 std::string command;
2508 if(!std::getline(std::cin, command))
2511 if(command == "quit") {
2512 OpeningBook.close();
2517 else if(command == "ponderhit" || command == "stop")
2523 // idle_loop() is where the threads are parked when they have no work to do.
2524 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2525 // object for which the current thread is the master.
2527 void idle_loop(int threadID, SplitPoint *waitSp) {
2528 assert(threadID >= 0 && threadID < THREAD_MAX);
2530 Threads[threadID].running = true;
2533 if(AllThreadsShouldExit && threadID != 0)
2536 // If we are not thinking, wait for a condition to be signaled instead
2537 // of wasting CPU time polling for work:
2538 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2539 #if !defined(_MSC_VER)
2540 pthread_mutex_lock(&WaitLock);
2541 if(Idle || threadID >= ActiveThreads)
2542 pthread_cond_wait(&WaitCond, &WaitLock);
2543 pthread_mutex_unlock(&WaitLock);
2545 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2549 // If this thread has been assigned work, launch a search:
2550 if(Threads[threadID].workIsWaiting) {
2551 Threads[threadID].workIsWaiting = false;
2552 if(Threads[threadID].splitPoint->pvNode)
2553 sp_search_pv(Threads[threadID].splitPoint, threadID);
2555 sp_search(Threads[threadID].splitPoint, threadID);
2556 Threads[threadID].idle = true;
2559 // If this thread is the master of a split point and all threads have
2560 // finished their work at this split point, return from the idle loop:
2561 if(waitSp != NULL && waitSp->cpus == 0)
2565 Threads[threadID].running = false;
2569 // init_split_point_stack() is called during program initialization, and
2570 // initializes all split point objects.
2572 void init_split_point_stack() {
2573 for(int i = 0; i < THREAD_MAX; i++)
2574 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2575 SplitPointStack[i][j].parent = NULL;
2576 lock_init(&(SplitPointStack[i][j].lock), NULL);
2581 // destroy_split_point_stack() is called when the program exits, and
2582 // destroys all locks in the precomputed split point objects.
2584 void destroy_split_point_stack() {
2585 for(int i = 0; i < THREAD_MAX; i++)
2586 for(int j = 0; j < MaxActiveSplitPoints; j++)
2587 lock_destroy(&(SplitPointStack[i][j].lock));
2591 // thread_should_stop() checks whether the thread with a given threadID has
2592 // been asked to stop, directly or indirectly. This can happen if a beta
2593 // cutoff has occured in thre thread's currently active split point, or in
2594 // some ancestor of the current split point.
2596 bool thread_should_stop(int threadID) {
2597 assert(threadID >= 0 && threadID < ActiveThreads);
2601 if(Threads[threadID].stop)
2603 if(ActiveThreads <= 2)
2605 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2607 Threads[threadID].stop = true;
2614 // thread_is_available() checks whether the thread with threadID "slave" is
2615 // available to help the thread with threadID "master" at a split point. An
2616 // obvious requirement is that "slave" must be idle. With more than two
2617 // threads, this is not by itself sufficient: If "slave" is the master of
2618 // some active split point, it is only available as a slave to the other
2619 // threads which are busy searching the split point at the top of "slave"'s
2620 // split point stack (the "helpful master concept" in YBWC terminology).
2622 bool thread_is_available(int slave, int master) {
2623 assert(slave >= 0 && slave < ActiveThreads);
2624 assert(master >= 0 && master < ActiveThreads);
2625 assert(ActiveThreads > 1);
2627 if(!Threads[slave].idle || slave == master)
2630 if(Threads[slave].activeSplitPoints == 0)
2631 // No active split points means that the thread is available as a slave
2632 // for any other thread.
2635 if(ActiveThreads == 2)
2638 // Apply the "helpful master" concept if possible.
2639 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2646 // idle_thread_exists() tries to find an idle thread which is available as
2647 // a slave for the thread with threadID "master".
2649 bool idle_thread_exists(int master) {
2650 assert(master >= 0 && master < ActiveThreads);
2651 assert(ActiveThreads > 1);
2653 for(int i = 0; i < ActiveThreads; i++)
2654 if(thread_is_available(i, master))
2660 // split() does the actual work of distributing the work at a node between
2661 // several threads at PV nodes. If it does not succeed in splitting the
2662 // node (because no idle threads are available, or because we have no unused
2663 // split point objects), the function immediately returns false. If
2664 // splitting is possible, a SplitPoint object is initialized with all the
2665 // data that must be copied to the helper threads (the current position and
2666 // search stack, alpha, beta, the search depth, etc.), and we tell our
2667 // helper threads that they have been assigned work. This will cause them
2668 // to instantly leave their idle loops and call sp_search_pv(). When all
2669 // threads have returned from sp_search_pv (or, equivalently, when
2670 // splitPoint->cpus becomes 0), split() returns true.
2672 bool split(const Position &p, SearchStack *sstck, int ply,
2673 Value *alpha, Value *beta, Value *bestValue,
2674 Depth depth, int *moves,
2675 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2677 assert(sstck != NULL);
2678 assert(ply >= 0 && ply < PLY_MAX);
2679 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2680 assert(!pvNode || *alpha < *beta);
2681 assert(*beta <= VALUE_INFINITE);
2682 assert(depth > Depth(0));
2683 assert(master >= 0 && master < ActiveThreads);
2684 assert(ActiveThreads > 1);
2686 SplitPoint *splitPoint;
2691 // If no other thread is available to help us, or if we have too many
2692 // active split points, don't split:
2693 if(!idle_thread_exists(master) ||
2694 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2695 lock_release(&MPLock);
2699 // Pick the next available split point object from the split point stack:
2700 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2701 Threads[master].activeSplitPoints++;
2703 // Initialize the split point object:
2704 splitPoint->parent = Threads[master].splitPoint;
2705 splitPoint->finished = false;
2706 splitPoint->ply = ply;
2707 splitPoint->depth = depth;
2708 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2709 splitPoint->beta = *beta;
2710 splitPoint->pvNode = pvNode;
2711 splitPoint->dcCandidates = dcCandidates;
2712 splitPoint->bestValue = *bestValue;
2713 splitPoint->master = master;
2714 splitPoint->mp = mp;
2715 splitPoint->moves = *moves;
2716 splitPoint->cpus = 1;
2717 splitPoint->pos.copy(p);
2718 splitPoint->parentSstack = sstck;
2719 for(i = 0; i < ActiveThreads; i++)
2720 splitPoint->slaves[i] = 0;
2722 // Copy the current position and the search stack to the master thread:
2723 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2724 Threads[master].splitPoint = splitPoint;
2726 // Make copies of the current position and search stack for each thread:
2727 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2729 if(thread_is_available(i, master)) {
2730 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2731 Threads[i].splitPoint = splitPoint;
2732 splitPoint->slaves[i] = 1;
2736 // Tell the threads that they have work to do. This will make them leave
2738 for(i = 0; i < ActiveThreads; i++)
2739 if(i == master || splitPoint->slaves[i]) {
2740 Threads[i].workIsWaiting = true;
2741 Threads[i].idle = false;
2742 Threads[i].stop = false;
2745 lock_release(&MPLock);
2747 // Everything is set up. The master thread enters the idle loop, from
2748 // which it will instantly launch a search, because its workIsWaiting
2749 // slot is 'true'. We send the split point as a second parameter to the
2750 // idle loop, which means that the main thread will return from the idle
2751 // loop when all threads have finished their work at this split point
2752 // (i.e. when // splitPoint->cpus == 0).
2753 idle_loop(master, splitPoint);
2755 // We have returned from the idle loop, which means that all threads are
2756 // finished. Update alpha, beta and bestvalue, and return:
2758 if(pvNode) *alpha = splitPoint->alpha;
2759 *beta = splitPoint->beta;
2760 *bestValue = splitPoint->bestValue;
2761 Threads[master].stop = false;
2762 Threads[master].idle = false;
2763 Threads[master].activeSplitPoints--;
2764 Threads[master].splitPoint = splitPoint->parent;
2765 lock_release(&MPLock);
2771 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2772 // to start a new search from the root.
2774 void wake_sleeping_threads() {
2775 if(ActiveThreads > 1) {
2776 for(int i = 1; i < ActiveThreads; i++) {
2777 Threads[i].idle = true;
2778 Threads[i].workIsWaiting = false;
2780 #if !defined(_MSC_VER)
2781 pthread_mutex_lock(&WaitLock);
2782 pthread_cond_broadcast(&WaitCond);
2783 pthread_mutex_unlock(&WaitLock);
2785 for(int i = 1; i < THREAD_MAX; i++)
2786 SetEvent(SitIdleEvent[i]);
2792 // init_thread() is the function which is called when a new thread is
2793 // launched. It simply calls the idle_loop() function with the supplied
2794 // threadID. There are two versions of this function; one for POSIX threads
2795 // and one for Windows threads.
2797 #if !defined(_MSC_VER)
2799 void *init_thread(void *threadID) {
2800 idle_loop(*(int *)threadID, NULL);
2806 DWORD WINAPI init_thread(LPVOID threadID) {
2807 idle_loop(*(int *)threadID, NULL);