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);
137 const bool UseEasyMove = true;
139 // Easy move margin. An easy move candidate must be at least this much
140 // better than the second best move.
141 const Value EasyMoveMargin = Value(0x200);
143 // Problem margin. If the score of the first move at iteration N+1 has
144 // dropped by more than this since iteration N, the boolean variable
145 // "Problem" is set to true, which will make the program spend some extra
146 // time looking for a better move.
147 const Value ProblemMargin = Value(0x28);
149 // No problem margin. If the boolean "Problem" is true, and a new move
150 // is found at the root which is less than NoProblemMargin worse than the
151 // best move from the previous iteration, Problem is set back to false.
152 const Value NoProblemMargin = Value(0x14);
154 // Null move margin. A null move search will not be done if the approximate
155 // evaluation of the position is more than NullMoveMargin below beta.
156 const Value NullMoveMargin = Value(0x300);
158 // Pruning criterions. See the code and comments in ok_to_prune() to
159 // understand their precise meaning.
160 const bool PruneEscapeMoves = false;
161 const bool PruneDefendingMoves = false;
162 const bool PruneBlockingMoves = false;
164 // Use futility pruning?
165 bool UseQSearchFutilityPruning = true;
166 bool UseFutilityPruning = true;
168 // Margins for futility pruning in the quiescence search, at frontier
169 // nodes, and at pre-frontier nodes
170 Value FutilityMargin0 = Value(0x80);
171 Value FutilityMargin1 = Value(0x100);
172 Value FutilityMargin2 = Value(0x300);
175 Depth RazorDepth = 4*OnePly;
176 Value RazorMargin = Value(0x300);
178 // Last seconds noise filtering (LSN)
179 bool UseLSNFiltering = false;
180 bool looseOnTime = false;
181 int LSNTime = 4 * 1000; // In milliseconds
182 Value LSNValue = Value(0x200);
184 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
185 Depth CheckExtension[2] = {OnePly, OnePly};
186 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
187 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
188 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
189 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
190 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
192 // Search depth at iteration 1
193 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
197 int NodesBetweenPolls = 30000;
199 // Iteration counters
202 BetaCounterType BetaCounter;
204 // Scores and number of times the best move changed for each iteration:
205 Value ValueByIteration[PLY_MAX_PLUS_2];
206 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
211 // Time managment variables
213 int MaxNodes, MaxDepth;
214 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
215 Move BestRootMove, PonderMove, EasyMove;
219 bool StopOnPonderhit;
224 bool PonderingEnabled;
227 // Show current line?
228 bool ShowCurrentLine = false;
231 bool UseLogFile = false;
232 std::ofstream LogFile;
234 // MP related variables
235 Depth MinimumSplitDepth = 4*OnePly;
236 int MaxThreadsPerSplitPoint = 4;
237 Thread Threads[THREAD_MAX];
239 bool AllThreadsShouldExit = false;
240 const int MaxActiveSplitPoints = 8;
241 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
244 #if !defined(_MSC_VER)
245 pthread_cond_t WaitCond;
246 pthread_mutex_t WaitLock;
248 HANDLE SitIdleEvent[THREAD_MAX];
254 Value id_loop(const Position &pos, Move searchMoves[]);
255 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
256 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
257 Depth depth, int ply, int threadID);
258 Value search(Position &pos, SearchStack ss[], Value beta,
259 Depth depth, int ply, bool allowNullmove, int threadID);
260 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
261 Depth depth, int ply, int threadID);
262 void sp_search(SplitPoint *sp, int threadID);
263 void sp_search_pv(SplitPoint *sp, int threadID);
264 void init_search_stack(SearchStack& ss);
265 void init_search_stack(SearchStack ss[]);
266 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
267 void update_pv(SearchStack ss[], int ply);
268 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
269 bool connected_moves(const Position &pos, Move m1, Move m2);
270 bool value_is_mate(Value value);
271 bool move_is_killer(Move m, const SearchStack& ss);
272 Depth extension(const Position &pos, Move m, bool pvNode, bool check, bool singleReply, bool mateThreat, bool* dangerous);
273 bool ok_to_do_nullmove(const Position &pos);
274 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
275 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
276 bool ok_to_history(const Position &pos, Move m);
277 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
278 void update_killers(Move m, SearchStack& ss);
280 bool fail_high_ply_1();
281 int current_search_time();
285 void print_current_line(SearchStack ss[], int ply, int threadID);
286 void wait_for_stop_or_ponderhit();
288 void idle_loop(int threadID, SplitPoint *waitSp);
289 void init_split_point_stack();
290 void destroy_split_point_stack();
291 bool thread_should_stop(int threadID);
292 bool thread_is_available(int slave, int master);
293 bool idle_thread_exists(int master);
294 bool split(const Position &pos, SearchStack *ss, int ply,
295 Value *alpha, Value *beta, Value *bestValue, Depth depth,
296 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
298 void wake_sleeping_threads();
300 #if !defined(_MSC_VER)
301 void *init_thread(void *threadID);
303 DWORD WINAPI init_thread(LPVOID threadID);
310 //// Global variables
313 // The main transposition table
314 TranspositionTable TT = TranspositionTable(TTDefaultSize);
317 // Number of active threads:
318 int ActiveThreads = 1;
320 // Locks. In principle, there is no need for IOLock to be a global variable,
321 // but it could turn out to be useful for debugging.
324 History H; // Should be made local?
326 // The empty search stack
327 SearchStack EmptySearchStack;
334 /// think() is the external interface to Stockfish's search, and is called when
335 /// the program receives the UCI 'go' command. It initializes various
336 /// search-related global variables, and calls root_search()
338 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
339 int time[], int increment[], int movesToGo, int maxDepth,
340 int maxNodes, int maxTime, Move searchMoves[]) {
342 // Look for a book move
343 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
346 if (get_option_value_string("Book File") != OpeningBook.file_name())
349 OpeningBook.open("book.bin");
351 bookMove = OpeningBook.get_move(pos);
352 if (bookMove != MOVE_NONE)
354 std::cout << "bestmove " << bookMove << std::endl;
359 // Initialize global search variables
361 SearchStartTime = get_system_time();
362 BestRootMove = MOVE_NONE;
363 PonderMove = MOVE_NONE;
364 EasyMove = MOVE_NONE;
365 for (int i = 0; i < THREAD_MAX; i++)
367 Threads[i].nodes = 0ULL;
368 Threads[i].failHighPly1 = false;
371 InfiniteSearch = infinite;
372 PonderSearch = ponder;
373 StopOnPonderhit = false;
378 ExactMaxTime = maxTime;
380 // Read UCI option values
381 TT.set_size(get_option_value_int("Hash"));
382 if (button_was_pressed("Clear Hash"))
385 PonderingEnabled = get_option_value_bool("Ponder");
386 MultiPV = get_option_value_int("MultiPV");
388 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
389 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
391 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
392 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
394 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
395 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
397 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
398 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
400 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
401 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
403 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
404 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
406 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
407 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
408 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
409 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
411 Chess960 = get_option_value_bool("UCI_Chess960");
412 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
413 UseLogFile = get_option_value_bool("Use Search Log");
415 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
417 UseNullDrivenIID = get_option_value_bool("Null driven IID");
418 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
419 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
421 FutilityMargin0 = value_from_centipawns(get_option_value_int("Futility Margin 0"));
422 FutilityMargin1 = value_from_centipawns(get_option_value_int("Futility Margin 1"));
423 FutilityMargin2 = value_from_centipawns(get_option_value_int("Futility Margin 2"));
425 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
426 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
428 UseLSNFiltering = get_option_value_bool("LSN filtering");
429 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
430 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
432 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
433 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
435 read_weights(pos.side_to_move());
437 int newActiveThreads = get_option_value_int("Threads");
438 if (newActiveThreads != ActiveThreads)
440 ActiveThreads = newActiveThreads;
441 init_eval(ActiveThreads);
444 // Wake up sleeping threads:
445 wake_sleeping_threads();
447 for (int i = 1; i < ActiveThreads; i++)
448 assert(thread_is_available(i, 0));
450 // Set thinking time:
451 int myTime = time[side_to_move];
452 int myIncrement = increment[side_to_move];
453 int oppTime = time[1 - side_to_move];
455 if (!movesToGo) // Sudden death time control
459 MaxSearchTime = myTime / 30 + myIncrement;
460 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
461 } else { // Blitz game without increment
462 MaxSearchTime = myTime / 30;
463 AbsoluteMaxSearchTime = myTime / 8;
466 else // (x moves) / (y minutes)
470 MaxSearchTime = myTime / 2;
471 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
473 MaxSearchTime = myTime / Min(movesToGo, 20);
474 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
478 if (PonderingEnabled)
480 MaxSearchTime += MaxSearchTime / 4;
481 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
484 // Fixed depth or fixed number of nodes?
487 InfiniteSearch = true; // HACK
492 NodesBetweenPolls = Min(MaxNodes, 30000);
493 InfiniteSearch = true; // HACK
496 NodesBetweenPolls = 30000;
499 // Write information to search log file:
501 LogFile << "Searching: " << pos.to_fen() << std::endl
502 << "infinite: " << infinite
503 << " ponder: " << ponder
504 << " time: " << myTime
505 << " increment: " << myIncrement
506 << " moves to go: " << movesToGo << std::endl;
509 // We're ready to start thinking. Call the iterative deepening loop
513 Value v = id_loop(pos, searchMoves);
514 looseOnTime = ( UseLSNFiltering
521 looseOnTime = false; // reset for next match
522 while (SearchStartTime + myTime + 1000 > get_system_time())
524 id_loop(pos, searchMoves); // to fail gracefully
541 /// init_threads() is called during startup. It launches all helper threads,
542 /// and initializes the split point stack and the global locks and condition
545 void init_threads() {
549 #if !defined(_MSC_VER)
550 pthread_t pthread[1];
553 for (i = 0; i < THREAD_MAX; i++)
554 Threads[i].activeSplitPoints = 0;
556 // Initialize global locks:
557 lock_init(&MPLock, NULL);
558 lock_init(&IOLock, NULL);
560 init_split_point_stack();
562 #if !defined(_MSC_VER)
563 pthread_mutex_init(&WaitLock, NULL);
564 pthread_cond_init(&WaitCond, NULL);
566 for (i = 0; i < THREAD_MAX; i++)
567 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
570 // All threads except the main thread should be initialized to idle state
571 for (i = 1; i < THREAD_MAX; i++)
573 Threads[i].stop = false;
574 Threads[i].workIsWaiting = false;
575 Threads[i].idle = true;
576 Threads[i].running = false;
579 // Launch the helper threads
580 for(i = 1; i < THREAD_MAX; i++)
582 #if !defined(_MSC_VER)
583 pthread_create(pthread, NULL, init_thread, (void*)(&i));
586 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
589 // Wait until the thread has finished launching:
590 while (!Threads[i].running);
593 // Init also the empty search stack
594 init_search_stack(EmptySearchStack);
598 /// stop_threads() is called when the program exits. It makes all the
599 /// helper threads exit cleanly.
601 void stop_threads() {
603 ActiveThreads = THREAD_MAX; // HACK
604 Idle = false; // HACK
605 wake_sleeping_threads();
606 AllThreadsShouldExit = true;
607 for (int i = 1; i < THREAD_MAX; i++)
609 Threads[i].stop = true;
610 while(Threads[i].running);
612 destroy_split_point_stack();
616 /// nodes_searched() returns the total number of nodes searched so far in
617 /// the current search.
619 int64_t nodes_searched() {
621 int64_t result = 0ULL;
622 for (int i = 0; i < ActiveThreads; i++)
623 result += Threads[i].nodes;
630 // id_loop() is the main iterative deepening loop. It calls root_search
631 // repeatedly with increasing depth until the allocated thinking time has
632 // been consumed, the user stops the search, or the maximum search depth is
635 Value id_loop(const Position &pos, Move searchMoves[]) {
638 SearchStack ss[PLY_MAX_PLUS_2];
640 // searchMoves are verified, copied, scored and sorted
641 RootMoveList rml(p, searchMoves);
646 init_search_stack(ss);
648 ValueByIteration[0] = Value(0);
649 ValueByIteration[1] = rml.get_move_score(0);
651 LastIterations = false;
653 EasyMove = rml.scan_for_easy_move();
655 // Iterative deepening loop
656 while (!AbortSearch && Iteration < PLY_MAX)
658 // Initialize iteration
661 BestMoveChangesByIteration[Iteration] = 0;
665 std::cout << "info depth " << Iteration << std::endl;
667 // Search to the current depth
668 ValueByIteration[Iteration] = root_search(p, ss, rml);
670 // Erase the easy move if it differs from the new best move
671 if (ss[0].pv[0] != EasyMove)
672 EasyMove = MOVE_NONE;
679 bool stopSearch = false;
681 // Stop search early if there is only a single legal move:
682 if (Iteration >= 6 && rml.move_count() == 1)
685 // Stop search early when the last two iterations returned a mate score
687 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
688 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
691 // Stop search early if one move seems to be much better than the rest
692 int64_t nodes = nodes_searched();
694 && EasyMove == ss[0].pv[0]
695 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
696 && current_search_time() > MaxSearchTime / 16)
697 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
698 && current_search_time() > MaxSearchTime / 32)))
701 // Add some extra time if the best move has changed during the last two iterations
702 if (Iteration > 5 && Iteration <= 50)
703 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
704 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
706 // Try to guess if the current iteration is the last one or the last two
707 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
709 // Stop search if most of MaxSearchTime is consumed at the end of the
710 // iteration. We probably don't have enough time to search the first
711 // move at the next iteration anyway.
712 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
720 StopOnPonderhit = true;
723 // Write PV to transposition table, in case the relevant entries have
724 // been overwritten during the search:
725 TT.insert_pv(p, ss[0].pv);
727 if (MaxDepth && Iteration >= MaxDepth)
733 // If we are pondering, we shouldn't print the best move before we
736 wait_for_stop_or_ponderhit();
738 // Print final search statistics
739 std::cout << "info nodes " << nodes_searched()
741 << " time " << current_search_time()
742 << " hashfull " << TT.full() << std::endl;
744 // Print the best move and the ponder move to the standard output
745 std::cout << "bestmove " << ss[0].pv[0];
746 if (ss[0].pv[1] != MOVE_NONE)
747 std::cout << " ponder " << ss[0].pv[1];
749 std::cout << std::endl;
754 dbg_print_mean(LogFile);
756 if (dbg_show_hit_rate)
757 dbg_print_hit_rate(LogFile);
760 LogFile << "Nodes: " << nodes_searched() << std::endl
761 << "Nodes/second: " << nps() << std::endl
762 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
764 p.do_move(ss[0].pv[0], u);
765 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
766 << std::endl << std::endl;
768 return rml.get_move_score(0);
772 // root_search() is the function which searches the root node. It is
773 // similar to search_pv except that it uses a different move ordering
774 // scheme (perhaps we should try to use this at internal PV nodes, too?)
775 // and prints some information to the standard output.
777 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
779 Value alpha = -VALUE_INFINITE;
780 Value beta = VALUE_INFINITE, value;
781 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
783 // Loop through all the moves in the root move list
784 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
791 RootMoveNumber = i + 1;
794 // Remember the node count before the move is searched. The node counts
795 // are used to sort the root moves at the next iteration.
796 nodes = nodes_searched();
798 // Reset beta cut-off counters
801 // Pick the next root move, and print the move and the move number to
802 // the standard output.
803 move = ss[0].currentMove = rml.get_move(i);
804 if (current_search_time() >= 1000)
805 std::cout << "info currmove " << move
806 << " currmovenumber " << i + 1 << std::endl;
808 // Decide search depth for this move
810 ext = extension(pos, move, true, pos.move_is_check(move), false, false, &dangerous);
811 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
813 // Make the move, and search it
814 pos.do_move(move, u, dcCandidates);
818 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
819 // If the value has dropped a lot compared to the last iteration,
820 // set the boolean variable Problem to true. This variable is used
821 // for time managment: When Problem is true, we try to complete the
822 // current iteration before playing a move.
823 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
825 if (Problem && StopOnPonderhit)
826 StopOnPonderhit = false;
830 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
833 // Fail high! Set the boolean variable FailHigh to true, and
834 // re-search the move with a big window. The variable FailHigh is
835 // used for time managment: We try to avoid aborting the search
836 // prematurely during a fail high research.
838 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
842 pos.undo_move(move, u);
844 // Finished searching the move. If AbortSearch is true, the search
845 // was aborted because the user interrupted the search or because we
846 // ran out of time. In this case, the return value of the search cannot
847 // be trusted, and we break out of the loop without updating the best
852 // Remember the node count for this move. The node counts are used to
853 // sort the root moves at the next iteration.
854 rml.set_move_nodes(i, nodes_searched() - nodes);
856 // Remember the beta-cutoff statistics
858 BetaCounter.read(pos.side_to_move(), our, their);
859 rml.set_beta_counters(i, our, their);
861 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
863 if (value <= alpha && i >= MultiPV)
864 rml.set_move_score(i, -VALUE_INFINITE);
870 rml.set_move_score(i, value);
872 rml.set_move_pv(i, ss[0].pv);
876 // We record how often the best move has been changed in each
877 // iteration. This information is used for time managment: When
878 // the best move changes frequently, we allocate some more time.
880 BestMoveChangesByIteration[Iteration]++;
882 // Print search information to the standard output:
883 std::cout << "info depth " << Iteration
884 << " score " << value_to_string(value)
885 << " time " << current_search_time()
886 << " nodes " << nodes_searched()
890 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
891 std::cout << ss[0].pv[j] << " ";
893 std::cout << std::endl;
896 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
901 // Reset the global variable Problem to false if the value isn't too
902 // far below the final value from the last iteration.
903 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
909 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
912 std::cout << "info multipv " << j + 1
913 << " score " << value_to_string(rml.get_move_score(j))
914 << " depth " << ((j <= i)? Iteration : Iteration - 1)
915 << " time " << current_search_time()
916 << " nodes " << nodes_searched()
920 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
921 std::cout << rml.get_move_pv(j, k) << " ";
923 std::cout << std::endl;
925 alpha = rml.get_move_score(Min(i, MultiPV-1));
933 // search_pv() is the main search function for PV nodes.
935 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
936 Depth depth, int ply, int threadID) {
938 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
939 assert(beta > alpha && beta <= VALUE_INFINITE);
940 assert(ply >= 0 && ply < PLY_MAX);
941 assert(threadID >= 0 && threadID < ActiveThreads);
943 // Initialize, and make an early exit in case of an aborted search,
944 // an instant draw, maximum ply reached, etc.
945 if (AbortSearch || thread_should_stop(threadID))
949 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
951 init_node(pos, ss, ply, 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 = pos.midgame_value_of_piece_on(move_to(move));
1007 else if (move_is_ep(move))
1008 ss[ply].currentMoveCaptureValue = PawnValueMidgame;
1010 ss[ply].currentMoveCaptureValue = Value(0);
1012 // Decide the new search depth
1014 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat, &dangerous);
1015 Depth newDepth = depth - OnePly + ext;
1017 // Make and search the move
1019 pos.do_move(move, u, dcCandidates);
1021 if (moveCount == 1) // The first move in list is the PV
1022 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1025 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1026 // if the move fails high will be re-searched at full depth.
1027 if ( depth >= 2*OnePly
1028 && moveCount >= LMRPVMoves
1031 && !move_promotion(move)
1032 && !move_is_castle(move)
1033 && !move_is_killer(move, ss[ply]))
1035 ss[ply].reduction = OnePly;
1036 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1039 value = alpha + 1; // Just to trigger next condition
1041 if (value > alpha) // Go with full depth pv search
1043 ss[ply].reduction = Depth(0);
1044 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1045 if (value > alpha && value < beta)
1047 // When the search fails high at ply 1 while searching the first
1048 // move at the root, set the flag failHighPly1. This is used for
1049 // time managment: We don't want to stop the search early in
1050 // such cases, because resolving the fail high at ply 1 could
1051 // result in a big drop in score at the root.
1052 if (ply == 1 && RootMoveNumber == 1)
1053 Threads[threadID].failHighPly1 = true;
1055 // A fail high occurred. Re-search at full window (pv search)
1056 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1057 Threads[threadID].failHighPly1 = false;
1061 pos.undo_move(move, u);
1063 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1066 if (value > bestValue)
1073 if (value == value_mate_in(ply + 1))
1074 ss[ply].mateKiller = move;
1076 // If we are at ply 1, and we are searching the first root move at
1077 // ply 0, set the 'Problem' variable if the score has dropped a lot
1078 // (from the computer's point of view) since the previous iteration:
1079 if (Iteration >= 2 && -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);
1138 // Initialize, and make an early exit in case of an aborted search,
1139 // an instant draw, maximum ply reached, etc.
1140 if (AbortSearch || thread_should_stop(threadID))
1144 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1146 init_node(pos, ss, ply, threadID);
1151 if (ply >= PLY_MAX - 1)
1152 return evaluate(pos, ei, threadID);
1154 // Mate distance pruning
1155 if (value_mated_in(ply) >= beta)
1158 if (value_mate_in(ply + 1) < beta)
1161 // Transposition table lookup
1162 const TTEntry* tte = TT.retrieve(pos);
1163 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1165 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1167 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1168 return value_from_tt(tte->value(), ply);
1171 Value approximateEval = quick_evaluate(pos);
1172 bool mateThreat = false;
1173 bool nullDrivenIID = false;
1174 bool isCheck = pos.is_check();
1180 && !value_is_mate(beta)
1181 && ok_to_do_nullmove(pos)
1182 && approximateEval >= beta - NullMoveMargin)
1184 ss[ply].currentMove = MOVE_NULL;
1187 pos.do_null_move(u);
1188 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1190 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1192 // Check for a null capture artifact, if the value without the null capture
1193 // is above beta then there is a good possibility that this is a cut-node.
1194 // We will do an IID later to find a ttMove.
1195 if ( UseNullDrivenIID
1197 && depth > 6 * OnePly
1198 &&!value_is_mate(nullValue)
1199 && ttMove == MOVE_NONE
1200 && ss[ply + 1].currentMove != MOVE_NONE
1201 && pos.move_is_capture(ss[ply + 1].currentMove)
1202 && pos.see(ss[ply + 1].currentMove) + nullValue >= beta)
1203 nullDrivenIID = true;
1205 pos.undo_null_move(u);
1207 if (value_is_mate(nullValue))
1209 /* Do not return unproven mates */
1211 else if (nullValue >= beta)
1213 if (depth < 6 * OnePly)
1216 // Do zugzwang verification search
1217 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1221 // The null move failed low, which means that we may be faced with
1222 // some kind of threat. If the previous move was reduced, check if
1223 // the move that refuted the null move was somehow connected to the
1224 // move which was reduced. If a connection is found, return a fail
1225 // low score (which will cause the reduced move to fail high in the
1226 // parent node, which will trigger a re-search with full depth).
1227 if (nullValue == value_mated_in(ply + 2))
1230 nullDrivenIID = false;
1232 ss[ply].threatMove = ss[ply + 1].currentMove;
1233 if ( depth < ThreatDepth
1234 && ss[ply - 1].reduction
1235 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1239 // Null move search not allowed, try razoring
1241 && !value_is_mate(beta)
1242 && ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1243 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly)))
1245 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1250 // Go with internal iterative deepening if we don't have a TT move
1251 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1252 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1254 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1255 ttMove = ss[ply].pv[ply];
1257 else if (nullDrivenIID)
1259 // The null move failed low due to a suspicious capture. Perhaps we
1260 // are facing a null capture artifact due to the side to move change
1261 // and this is a cut-node. So it's a good time to search for a ttMove.
1262 Move tm = ss[ply].threatMove;
1264 assert(tm != MOVE_NONE);
1265 assert(ttMove == MOVE_NONE);
1267 search(pos, ss, beta, depth/2, ply, false, threadID);
1268 ttMove = ss[ply].pv[ply];
1269 ss[ply].threatMove = tm;
1272 // Initialize a MovePicker object for the current position, and prepare
1273 // to search all moves:
1274 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1276 Move move, movesSearched[256];
1278 Value value, bestValue = -VALUE_INFINITE;
1279 Bitboard dcCandidates = mp.discovered_check_candidates();
1280 Value futilityValue = VALUE_NONE;
1281 bool useFutilityPruning = UseFutilityPruning
1282 && depth < SelectiveDepth
1285 // Loop through all legal moves until no moves remain or a beta cutoff
1287 while ( bestValue < beta
1288 && (move = mp.get_next_move()) != MOVE_NONE
1289 && !thread_should_stop(threadID))
1291 assert(move_is_ok(move));
1293 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1294 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1295 bool moveIsCapture = pos.move_is_capture(move);
1297 movesSearched[moveCount++] = ss[ply].currentMove = move;
1299 // Decide the new search depth
1301 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat, &dangerous);
1302 Depth newDepth = depth - OnePly + ext;
1305 if ( useFutilityPruning
1308 && !move_promotion(move))
1310 // History pruning. See ok_to_prune() definition.
1311 if ( moveCount >= 2 + int(depth)
1312 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1315 // Value based pruning.
1316 if (depth < 3 * OnePly && approximateEval < beta)
1318 if (futilityValue == VALUE_NONE)
1319 futilityValue = evaluate(pos, ei, threadID)
1320 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1322 if (futilityValue < beta)
1324 if (futilityValue > bestValue)
1325 bestValue = futilityValue;
1331 // Make and search the move
1333 pos.do_move(move, u, dcCandidates);
1335 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1336 // if the move fails high will be re-searched at full depth.
1337 if ( depth >= 2*OnePly
1338 && moveCount >= LMRNonPVMoves
1341 && !move_promotion(move)
1342 && !move_is_castle(move)
1343 && !move_is_killer(move, ss[ply]))
1345 ss[ply].reduction = OnePly;
1346 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1349 value = beta; // Just to trigger next condition
1351 if (value >= beta) // Go with full depth non-pv search
1353 ss[ply].reduction = Depth(0);
1354 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1356 pos.undo_move(move, u);
1358 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1361 if (value > bestValue)
1367 if (value == value_mate_in(ply + 1))
1368 ss[ply].mateKiller = move;
1372 if ( ActiveThreads > 1
1374 && depth >= MinimumSplitDepth
1376 && idle_thread_exists(threadID)
1378 && !thread_should_stop(threadID)
1379 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1380 &mp, dcCandidates, threadID, false))
1384 // All legal moves have been searched. A special case: If there were
1385 // no legal moves, it must be mate or stalemate.
1387 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1389 // If the search is not aborted, update the transposition table,
1390 // history counters, and killer moves.
1391 if (AbortSearch || thread_should_stop(threadID))
1394 if (bestValue < beta)
1395 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1398 BetaCounter.add(pos.side_to_move(), depth, threadID);
1399 Move m = ss[ply].pv[ply];
1400 if (ok_to_history(pos, m)) // Only non capture moves are considered
1402 update_history(pos, m, depth, movesSearched, moveCount);
1403 update_killers(m, ss[ply]);
1405 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1411 // qsearch() is the quiescence search function, which is called by the main
1412 // search function when the remaining depth is zero (or, to be more precise,
1413 // less than OnePly).
1415 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1416 Depth depth, int ply, int threadID) {
1418 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1419 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1421 assert(ply >= 0 && ply < PLY_MAX);
1422 assert(threadID >= 0 && threadID < ActiveThreads);
1426 // Initialize, and make an early exit in case of an aborted search,
1427 // an instant draw, maximum ply reached, etc.
1428 if (AbortSearch || thread_should_stop(threadID))
1431 init_node(pos, ss, ply, threadID);
1436 // Transposition table lookup
1437 const TTEntry* tte = TT.retrieve(pos);
1438 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1439 return value_from_tt(tte->value(), ply);
1441 // Evaluate the position statically
1442 bool isCheck = pos.is_check();
1443 Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1445 if (ply == PLY_MAX - 1)
1446 return evaluate(pos, ei, threadID);
1448 // Initialize "stand pat score", and return it immediately if it is
1450 Value bestValue = staticValue;
1452 if (bestValue >= beta)
1455 if (bestValue > alpha)
1458 // Initialize a MovePicker object for the current position, and prepare
1459 // to search the moves. Because the depth is <= 0 here, only captures,
1460 // queen promotions and checks (only if depth == 0) will be generated.
1461 bool pvNode = (beta - alpha != 1);
1462 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1465 Bitboard dcCandidates = mp.discovered_check_candidates();
1466 bool enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1468 // Loop through the moves until no moves remain or a beta cutoff
1470 while ( alpha < beta
1471 && (move = mp.get_next_move()) != MOVE_NONE)
1473 assert(move_is_ok(move));
1476 ss[ply].currentMove = move;
1479 if ( UseQSearchFutilityPruning
1483 && !move_promotion(move)
1484 && !pos.move_is_check(move, dcCandidates)
1485 && !pos.move_is_passed_pawn_push(move))
1487 Value futilityValue = staticValue
1488 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1489 pos.endgame_value_of_piece_on(move_to(move)))
1490 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1492 + ei.futilityMargin;
1494 if (futilityValue < alpha)
1496 if (futilityValue > bestValue)
1497 bestValue = futilityValue;
1502 // Don't search captures and checks with negative SEE values
1504 && !move_promotion(move)
1505 && (pos.midgame_value_of_piece_on(move_from(move)) >
1506 pos.midgame_value_of_piece_on(move_to(move)))
1507 && pos.see(move) < 0)
1510 // Make and search the move.
1512 pos.do_move(move, u, dcCandidates);
1513 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1514 pos.undo_move(move, u);
1516 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1519 if (value > bestValue)
1530 // All legal moves have been searched. A special case: If we're in check
1531 // and no legal moves were found, it is checkmate:
1532 if (pos.is_check() && moveCount == 0) // Mate!
1533 return value_mated_in(ply);
1535 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1537 // Update transposition table
1538 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1540 // Update killers only for good check moves
1541 Move m = ss[ply].currentMove;
1542 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1544 // Wrong to update history when depth is <= 0
1545 update_killers(m, ss[ply]);
1551 // sp_search() is used to search from a split point. This function is called
1552 // by each thread working at the split point. It is similar to the normal
1553 // search() function, but simpler. Because we have already probed the hash
1554 // table, done a null move search, and searched the first move before
1555 // splitting, we don't have to repeat all this work in sp_search(). We
1556 // also don't need to store anything to the hash table here: This is taken
1557 // care of after we return from the split point.
1559 void sp_search(SplitPoint *sp, int threadID) {
1561 assert(threadID >= 0 && threadID < ActiveThreads);
1562 assert(ActiveThreads > 1);
1564 Position pos = Position(sp->pos);
1565 SearchStack *ss = sp->sstack[threadID];
1568 bool isCheck = pos.is_check();
1569 bool useFutilityPruning = UseFutilityPruning
1570 && sp->depth < SelectiveDepth
1573 while ( sp->bestValue < sp->beta
1574 && !thread_should_stop(threadID)
1575 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1577 assert(move_is_ok(move));
1579 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1580 bool moveIsCapture = pos.move_is_capture(move);
1582 lock_grab(&(sp->lock));
1583 int moveCount = ++sp->moves;
1584 lock_release(&(sp->lock));
1586 ss[sp->ply].currentMove = move;
1588 // Decide the new search depth.
1590 Depth ext = extension(pos, move, false, moveIsCheck, false, false, &dangerous);
1591 Depth newDepth = sp->depth - OnePly + ext;
1594 if ( useFutilityPruning
1597 && !move_promotion(move)
1598 && moveCount >= 2 + int(sp->depth)
1599 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1602 // Make and search the move.
1604 pos.do_move(move, u, sp->dcCandidates);
1606 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1607 // if the move fails high will be re-searched at full depth.
1609 && moveCount >= LMRNonPVMoves
1611 && !move_promotion(move)
1612 && !move_is_castle(move)
1613 && !move_is_killer(move, ss[sp->ply]))
1615 ss[sp->ply].reduction = OnePly;
1616 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1619 value = sp->beta; // Just to trigger next condition
1621 if (value >= sp->beta) // Go with full depth non-pv search
1623 ss[sp->ply].reduction = Depth(0);
1624 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1626 pos.undo_move(move, u);
1628 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1630 if (thread_should_stop(threadID))
1634 lock_grab(&(sp->lock));
1635 if (value > sp->bestValue && !thread_should_stop(threadID))
1637 sp->bestValue = value;
1638 if (sp->bestValue >= sp->beta)
1640 sp_update_pv(sp->parentSstack, ss, sp->ply);
1641 for (int i = 0; i < ActiveThreads; i++)
1642 if (i != threadID && (i == sp->master || sp->slaves[i]))
1643 Threads[i].stop = true;
1645 sp->finished = true;
1648 lock_release(&(sp->lock));
1651 lock_grab(&(sp->lock));
1653 // If this is the master thread and we have been asked to stop because of
1654 // a beta cutoff higher up in the tree, stop all slave threads:
1655 if (sp->master == threadID && thread_should_stop(threadID))
1656 for (int i = 0; i < ActiveThreads; i++)
1658 Threads[i].stop = true;
1661 sp->slaves[threadID] = 0;
1663 lock_release(&(sp->lock));
1667 // sp_search_pv() is used to search from a PV split point. This function
1668 // is called by each thread working at the split point. It is similar to
1669 // the normal search_pv() function, but simpler. Because we have already
1670 // probed the hash table and searched the first move before splitting, we
1671 // don't have to repeat all this work in sp_search_pv(). We also don't
1672 // need to store anything to the hash table here: This is taken care of
1673 // after we return from the split point.
1675 void sp_search_pv(SplitPoint *sp, int threadID) {
1677 assert(threadID >= 0 && threadID < ActiveThreads);
1678 assert(ActiveThreads > 1);
1680 Position pos = Position(sp->pos);
1681 SearchStack *ss = sp->sstack[threadID];
1685 while ( sp->alpha < sp->beta
1686 && !thread_should_stop(threadID)
1687 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1689 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1690 bool moveIsCapture = pos.move_is_capture(move);
1692 assert(move_is_ok(move));
1694 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1695 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1697 lock_grab(&(sp->lock));
1698 int moveCount = ++sp->moves;
1699 lock_release(&(sp->lock));
1701 ss[sp->ply].currentMove = move;
1703 // Decide the new search depth.
1705 Depth ext = extension(pos, move, true, moveIsCheck, false, false, &dangerous);
1706 Depth newDepth = sp->depth - OnePly + ext;
1708 // Make and search the move.
1710 pos.do_move(move, u, sp->dcCandidates);
1712 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1713 // if the move fails high will be re-searched at full depth.
1715 && moveCount >= LMRPVMoves
1717 && !move_promotion(move)
1718 && !move_is_castle(move)
1719 && !move_is_killer(move, ss[sp->ply]))
1721 ss[sp->ply].reduction = OnePly;
1722 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1725 value = sp->alpha + 1; // Just to trigger next condition
1727 if (value > sp->alpha) // Go with full depth non-pv search
1729 ss[sp->ply].reduction = Depth(0);
1730 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1732 if (value > sp->alpha && value < sp->beta)
1734 // When the search fails high at ply 1 while searching the first
1735 // move at the root, set the flag failHighPly1. This is used for
1736 // time managment: We don't want to stop the search early in
1737 // such cases, because resolving the fail high at ply 1 could
1738 // result in a big drop in score at the root.
1739 if (sp->ply == 1 && RootMoveNumber == 1)
1740 Threads[threadID].failHighPly1 = true;
1742 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1743 Threads[threadID].failHighPly1 = false;
1746 pos.undo_move(move, u);
1748 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1750 if (thread_should_stop(threadID))
1754 lock_grab(&(sp->lock));
1755 if (value > sp->bestValue && !thread_should_stop(threadID))
1757 sp->bestValue = value;
1758 if (value > sp->alpha)
1761 sp_update_pv(sp->parentSstack, ss, sp->ply);
1762 if (value == value_mate_in(sp->ply + 1))
1763 ss[sp->ply].mateKiller = move;
1765 if(value >= sp->beta)
1767 for(int i = 0; i < ActiveThreads; i++)
1768 if(i != threadID && (i == sp->master || sp->slaves[i]))
1769 Threads[i].stop = true;
1771 sp->finished = true;
1774 // If we are at ply 1, and we are searching the first root move at
1775 // ply 0, set the 'Problem' variable if the score has dropped a lot
1776 // (from the computer's point of view) since the previous iteration:
1777 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1780 lock_release(&(sp->lock));
1783 lock_grab(&(sp->lock));
1785 // If this is the master thread and we have been asked to stop because of
1786 // a beta cutoff higher up in the tree, stop all slave threads:
1787 if (sp->master == threadID && thread_should_stop(threadID))
1788 for (int i = 0; i < ActiveThreads; i++)
1790 Threads[i].stop = true;
1793 sp->slaves[threadID] = 0;
1795 lock_release(&(sp->lock));
1798 /// The BetaCounterType class
1800 BetaCounterType::BetaCounterType() { clear(); }
1802 void BetaCounterType::clear() {
1804 for (int i = 0; i < THREAD_MAX; i++)
1805 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1808 void BetaCounterType::add(Color us, Depth d, int threadID) {
1810 // Weighted count based on depth
1811 hits[threadID][us] += int(d);
1814 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1817 for (int i = 0; i < THREAD_MAX; i++)
1820 their += hits[i][opposite_color(us)];
1825 /// The RootMove class
1829 RootMove::RootMove() {
1830 nodes = cumulativeNodes = 0ULL;
1833 // RootMove::operator<() is the comparison function used when
1834 // sorting the moves. A move m1 is considered to be better
1835 // than a move m2 if it has a higher score, or if the moves
1836 // have equal score but m1 has the higher node count.
1838 bool RootMove::operator<(const RootMove& m) {
1840 if (score != m.score)
1841 return (score < m.score);
1843 return theirBeta <= m.theirBeta;
1846 /// The RootMoveList class
1850 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1852 MoveStack mlist[MaxRootMoves];
1853 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1855 // Generate all legal moves
1856 int lm_count = generate_legal_moves(pos, mlist);
1858 // Add each move to the moves[] array
1859 for (int i = 0; i < lm_count; i++)
1861 bool includeMove = includeAllMoves;
1863 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1864 includeMove = (searchMoves[k] == mlist[i].move);
1868 // Find a quick score for the move
1870 SearchStack ss[PLY_MAX_PLUS_2];
1872 moves[count].move = mlist[i].move;
1873 moves[count].nodes = 0ULL;
1874 pos.do_move(moves[count].move, u);
1875 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1877 pos.undo_move(moves[count].move, u);
1878 moves[count].pv[0] = moves[i].move;
1879 moves[count].pv[1] = MOVE_NONE; // FIXME
1887 // Simple accessor methods for the RootMoveList class
1889 inline Move RootMoveList::get_move(int moveNum) const {
1890 return moves[moveNum].move;
1893 inline Value RootMoveList::get_move_score(int moveNum) const {
1894 return moves[moveNum].score;
1897 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1898 moves[moveNum].score = score;
1901 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1902 moves[moveNum].nodes = nodes;
1903 moves[moveNum].cumulativeNodes += nodes;
1906 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1907 moves[moveNum].ourBeta = our;
1908 moves[moveNum].theirBeta = their;
1911 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1913 for(j = 0; pv[j] != MOVE_NONE; j++)
1914 moves[moveNum].pv[j] = pv[j];
1915 moves[moveNum].pv[j] = MOVE_NONE;
1918 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1919 return moves[moveNum].pv[i];
1922 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1923 return moves[moveNum].cumulativeNodes;
1926 inline int RootMoveList::move_count() const {
1931 // RootMoveList::scan_for_easy_move() is called at the end of the first
1932 // iteration, and is used to detect an "easy move", i.e. a move which appears
1933 // to be much bester than all the rest. If an easy move is found, the move
1934 // is returned, otherwise the function returns MOVE_NONE. It is very
1935 // important that this function is called at the right moment: The code
1936 // assumes that the first iteration has been completed and the moves have
1937 // been sorted. This is done in RootMoveList c'tor.
1939 Move RootMoveList::scan_for_easy_move() const {
1946 // moves are sorted so just consider the best and the second one
1947 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1953 // RootMoveList::sort() sorts the root move list at the beginning of a new
1956 inline void RootMoveList::sort() {
1958 sort_multipv(count - 1); // all items
1962 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1963 // list by their scores and depths. It is used to order the different PVs
1964 // correctly in MultiPV mode.
1966 void RootMoveList::sort_multipv(int n) {
1968 for (int i = 1; i <= n; i++)
1970 RootMove rm = moves[i];
1972 for (j = i; j > 0 && moves[j-1] < rm; j--)
1973 moves[j] = moves[j-1];
1979 // init_search_stack() initializes a search stack at the beginning of a
1980 // new search from the root.
1981 void init_search_stack(SearchStack& ss) {
1983 ss.pv[0] = MOVE_NONE;
1984 ss.pv[1] = MOVE_NONE;
1985 ss.currentMove = MOVE_NONE;
1986 ss.threatMove = MOVE_NONE;
1987 ss.reduction = Depth(0);
1988 for (int j = 0; j < KILLER_MAX; j++)
1989 ss.killers[j] = MOVE_NONE;
1992 void init_search_stack(SearchStack ss[]) {
1994 for (int i = 0; i < 3; i++)
1996 ss[i].pv[i] = MOVE_NONE;
1997 ss[i].pv[i+1] = MOVE_NONE;
1998 ss[i].currentMove = MOVE_NONE;
1999 ss[i].threatMove = MOVE_NONE;
2000 ss[i].reduction = Depth(0);
2001 for (int j = 0; j < KILLER_MAX; j++)
2002 ss[i].killers[j] = MOVE_NONE;
2007 // init_node() is called at the beginning of all the search functions
2008 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2009 // stack object corresponding to the current node. Once every
2010 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2011 // for user input and checks whether it is time to stop the search.
2013 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2014 assert(ply >= 0 && ply < PLY_MAX);
2015 assert(threadID >= 0 && threadID < ActiveThreads);
2017 Threads[threadID].nodes++;
2021 if(NodesSincePoll >= NodesBetweenPolls) {
2026 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
2027 ss[ply+2].mateKiller = MOVE_NONE;
2028 ss[ply].threatMove = MOVE_NONE;
2029 ss[ply].reduction = Depth(0);
2030 ss[ply].currentMoveCaptureValue = Value(0);
2031 for (int j = 0; j < KILLER_MAX; j++)
2032 ss[ply+2].killers[j] = MOVE_NONE;
2034 if(Threads[threadID].printCurrentLine)
2035 print_current_line(ss, ply, threadID);
2039 // update_pv() is called whenever a search returns a value > alpha. It
2040 // updates the PV in the SearchStack object corresponding to the current
2043 void update_pv(SearchStack ss[], int ply) {
2044 assert(ply >= 0 && ply < PLY_MAX);
2046 ss[ply].pv[ply] = ss[ply].currentMove;
2048 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2049 ss[ply].pv[p] = ss[ply+1].pv[p];
2050 ss[ply].pv[p] = MOVE_NONE;
2054 // sp_update_pv() is a variant of update_pv for use at split points. The
2055 // difference between the two functions is that sp_update_pv also updates
2056 // the PV at the parent node.
2058 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2059 assert(ply >= 0 && ply < PLY_MAX);
2061 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2063 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2064 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2065 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2069 // connected_moves() tests whether two moves are 'connected' in the sense
2070 // that the first move somehow made the second move possible (for instance
2071 // if the moving piece is the same in both moves). The first move is
2072 // assumed to be the move that was made to reach the current position, while
2073 // the second move is assumed to be a move from the current position.
2075 bool connected_moves(const Position &pos, Move m1, Move m2) {
2076 Square f1, t1, f2, t2;
2078 assert(move_is_ok(m1));
2079 assert(move_is_ok(m2));
2084 // Case 1: The moving piece is the same in both moves.
2090 // Case 2: The destination square for m2 was vacated by m1.
2096 // Case 3: Moving through the vacated square:
2097 if(piece_is_slider(pos.piece_on(f2)) &&
2098 bit_is_set(squares_between(f2, t2), f1))
2101 // Case 4: The destination square for m2 is attacked by the moving piece
2103 if(pos.piece_attacks_square(t1, t2))
2106 // Case 5: Discovered check, checking piece is the piece moved in m1:
2107 if(piece_is_slider(pos.piece_on(t1)) &&
2108 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2110 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2112 Bitboard occ = pos.occupied_squares();
2113 Color us = pos.side_to_move();
2114 Square ksq = pos.king_square(us);
2115 clear_bit(&occ, f2);
2116 if(pos.type_of_piece_on(t1) == BISHOP) {
2117 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2120 else if(pos.type_of_piece_on(t1) == ROOK) {
2121 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2125 assert(pos.type_of_piece_on(t1) == QUEEN);
2126 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2135 // value_is_mate() checks if the given value is a mate one
2136 // eventually compensated for the ply.
2138 bool value_is_mate(Value value) {
2140 assert(abs(value) <= VALUE_INFINITE);
2142 return value <= value_mated_in(PLY_MAX)
2143 || value >= value_mate_in(PLY_MAX);
2147 // move_is_killer() checks if the given move is among the
2148 // killer moves of that ply.
2150 bool move_is_killer(Move m, const SearchStack& ss) {
2152 const Move* k = ss.killers;
2153 for (int i = 0; i < KILLER_MAX; i++, k++)
2161 // extension() decides whether a move should be searched with normal depth,
2162 // or with extended depth. Certain classes of moves (checking moves, in
2163 // particular) are searched with bigger depth than ordinary moves and in
2164 // any case are marked as 'dangerous'. Note that also if a move is not
2165 // extended, as example because the corresponding UCI option is set to zero,
2166 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2168 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
2169 bool singleReply, bool mateThreat, bool* dangerous) {
2171 Depth result = Depth(0);
2172 *dangerous = check || singleReply || mateThreat;
2175 result += CheckExtension[pvNode];
2178 result += SingleReplyExtension[pvNode];
2181 result += MateThreatExtension[pvNode];
2183 if (pos.move_is_pawn_push_to_7th(m))
2185 result += PawnPushTo7thExtension[pvNode];
2188 if (pos.move_is_passed_pawn_push(m))
2190 result += PassedPawnExtension[pvNode];
2194 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
2195 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2196 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2197 && !move_promotion(m))
2199 result += PawnEndgameExtension[pvNode];
2204 && pos.move_is_capture(m)
2205 && pos.type_of_piece_on(move_to(m)) != PAWN
2212 return Min(result, OnePly);
2216 // ok_to_do_nullmove() looks at the current position and decides whether
2217 // doing a 'null move' should be allowed. In order to avoid zugzwang
2218 // problems, null moves are not allowed when the side to move has very
2219 // little material left. Currently, the test is a bit too simple: Null
2220 // moves are avoided only when the side to move has only pawns left. It's
2221 // probably a good idea to avoid null moves in at least some more
2222 // complicated endgames, e.g. KQ vs KR. FIXME
2224 bool ok_to_do_nullmove(const Position &pos) {
2225 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2231 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2232 // non-tactical moves late in the move list close to the leaves are
2233 // candidates for pruning.
2235 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2236 Square mfrom, mto, tfrom, tto;
2238 assert(move_is_ok(m));
2239 assert(threat == MOVE_NONE || move_is_ok(threat));
2240 assert(!move_promotion(m));
2241 assert(!pos.move_is_check(m));
2242 assert(!pos.move_is_capture(m));
2243 assert(!pos.move_is_passed_pawn_push(m));
2244 assert(d >= OnePly);
2246 mfrom = move_from(m);
2248 tfrom = move_from(threat);
2249 tto = move_to(threat);
2251 // Case 1: Castling moves are never pruned.
2252 if (move_is_castle(m))
2255 // Case 2: Don't prune moves which move the threatened piece
2256 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2259 // Case 3: If the threatened piece has value less than or equal to the
2260 // value of the threatening piece, don't prune move which defend it.
2261 if ( !PruneDefendingMoves
2262 && threat != MOVE_NONE
2263 && pos.type_of_piece_on(tto) != NO_PIECE_TYPE
2264 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2265 || pos.type_of_piece_on(tfrom) == KING)
2266 && pos.move_attacks_square(m, tto))
2269 // Case 4: Don't prune moves with good history.
2270 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2273 // Case 5: If the moving piece in the threatened move is a slider, don't
2274 // prune safe moves which block its ray.
2275 if ( !PruneBlockingMoves
2276 && threat != MOVE_NONE
2277 && piece_is_slider(pos.piece_on(tfrom))
2278 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2285 // ok_to_use_TT() returns true if a transposition table score
2286 // can be used at a given point in search.
2288 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2290 Value v = value_from_tt(tte->value(), ply);
2292 return ( tte->depth() >= depth
2293 || v >= Max(value_mate_in(100), beta)
2294 || v < Min(value_mated_in(100), beta))
2296 && ( (is_lower_bound(tte->type()) && v >= beta)
2297 || (is_upper_bound(tte->type()) && v < beta));
2301 // ok_to_history() returns true if a move m can be stored
2302 // in history. Should be a non capturing move nor a promotion.
2304 bool ok_to_history(const Position& pos, Move m) {
2306 return !pos.move_is_capture(m) && !move_promotion(m);
2310 // update_history() registers a good move that produced a beta-cutoff
2311 // in history and marks as failures all the other moves of that ply.
2313 void update_history(const Position& pos, Move m, Depth depth,
2314 Move movesSearched[], int moveCount) {
2316 H.success(pos.piece_on(move_from(m)), m, depth);
2318 for (int i = 0; i < moveCount - 1; i++)
2320 assert(m != movesSearched[i]);
2321 if (ok_to_history(pos, movesSearched[i]))
2322 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2327 // update_killers() add a good move that produced a beta-cutoff
2328 // among the killer moves of that ply.
2330 void update_killers(Move m, SearchStack& ss) {
2332 if (m == ss.killers[0])
2335 for (int i = KILLER_MAX - 1; i > 0; i--)
2336 ss.killers[i] = ss.killers[i - 1];
2341 // fail_high_ply_1() checks if some thread is currently resolving a fail
2342 // high at ply 1 at the node below the first root node. This information
2343 // is used for time managment.
2345 bool fail_high_ply_1() {
2346 for(int i = 0; i < ActiveThreads; i++)
2347 if(Threads[i].failHighPly1)
2353 // current_search_time() returns the number of milliseconds which have passed
2354 // since the beginning of the current search.
2356 int current_search_time() {
2357 return get_system_time() - SearchStartTime;
2361 // nps() computes the current nodes/second count.
2364 int t = current_search_time();
2365 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2369 // poll() performs two different functions: It polls for user input, and it
2370 // looks at the time consumed so far and decides if it's time to abort the
2375 static int lastInfoTime;
2376 int t = current_search_time();
2381 // We are line oriented, don't read single chars
2382 std::string command;
2383 if (!std::getline(std::cin, command))
2386 if (command == "quit")
2389 PonderSearch = false;
2392 else if(command == "stop")
2395 PonderSearch = false;
2397 else if(command == "ponderhit")
2400 // Print search information
2404 else if (lastInfoTime > t)
2405 // HACK: Must be a new search where we searched less than
2406 // NodesBetweenPolls nodes during the first second of search.
2409 else if (t - lastInfoTime >= 1000)
2416 if (dbg_show_hit_rate)
2417 dbg_print_hit_rate();
2419 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2420 << " time " << t << " hashfull " << TT.full() << std::endl;
2421 lock_release(&IOLock);
2422 if (ShowCurrentLine)
2423 Threads[0].printCurrentLine = true;
2425 // Should we stop the search?
2429 bool overTime = t > AbsoluteMaxSearchTime
2430 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2431 || ( !FailHigh && !fail_high_ply_1() && !Problem
2432 && t > 6*(MaxSearchTime + ExtraSearchTime));
2434 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2435 || (ExactMaxTime && t >= ExactMaxTime)
2436 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2441 // ponderhit() is called when the program is pondering (i.e. thinking while
2442 // it's the opponent's turn to move) in order to let the engine know that
2443 // it correctly predicted the opponent's move.
2446 int t = current_search_time();
2447 PonderSearch = false;
2448 if(Iteration >= 2 &&
2449 (!InfiniteSearch && (StopOnPonderhit ||
2450 t > AbsoluteMaxSearchTime ||
2451 (RootMoveNumber == 1 &&
2452 t > MaxSearchTime + ExtraSearchTime) ||
2453 (!FailHigh && !fail_high_ply_1() && !Problem &&
2454 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2459 // print_current_line() prints the current line of search for a given
2460 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2462 void print_current_line(SearchStack ss[], int ply, int threadID) {
2463 assert(ply >= 0 && ply < PLY_MAX);
2464 assert(threadID >= 0 && threadID < ActiveThreads);
2466 if(!Threads[threadID].idle) {
2468 std::cout << "info currline " << (threadID + 1);
2469 for(int p = 0; p < ply; p++)
2470 std::cout << " " << ss[p].currentMove;
2471 std::cout << std::endl;
2472 lock_release(&IOLock);
2474 Threads[threadID].printCurrentLine = false;
2475 if(threadID + 1 < ActiveThreads)
2476 Threads[threadID + 1].printCurrentLine = true;
2480 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2481 // while the program is pondering. The point is to work around a wrinkle in
2482 // the UCI protocol: When pondering, the engine is not allowed to give a
2483 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2484 // We simply wait here until one of these commands is sent, and return,
2485 // after which the bestmove and pondermove will be printed (in id_loop()).
2487 void wait_for_stop_or_ponderhit() {
2488 std::string command;
2491 if(!std::getline(std::cin, command))
2494 if(command == "quit") {
2495 OpeningBook.close();
2500 else if(command == "ponderhit" || command == "stop")
2506 // idle_loop() is where the threads are parked when they have no work to do.
2507 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2508 // object for which the current thread is the master.
2510 void idle_loop(int threadID, SplitPoint *waitSp) {
2511 assert(threadID >= 0 && threadID < THREAD_MAX);
2513 Threads[threadID].running = true;
2516 if(AllThreadsShouldExit && threadID != 0)
2519 // If we are not thinking, wait for a condition to be signaled instead
2520 // of wasting CPU time polling for work:
2521 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2522 #if !defined(_MSC_VER)
2523 pthread_mutex_lock(&WaitLock);
2524 if(Idle || threadID >= ActiveThreads)
2525 pthread_cond_wait(&WaitCond, &WaitLock);
2526 pthread_mutex_unlock(&WaitLock);
2528 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2532 // If this thread has been assigned work, launch a search:
2533 if(Threads[threadID].workIsWaiting) {
2534 Threads[threadID].workIsWaiting = false;
2535 if(Threads[threadID].splitPoint->pvNode)
2536 sp_search_pv(Threads[threadID].splitPoint, threadID);
2538 sp_search(Threads[threadID].splitPoint, threadID);
2539 Threads[threadID].idle = true;
2542 // If this thread is the master of a split point and all threads have
2543 // finished their work at this split point, return from the idle loop:
2544 if(waitSp != NULL && waitSp->cpus == 0)
2548 Threads[threadID].running = false;
2552 // init_split_point_stack() is called during program initialization, and
2553 // initializes all split point objects.
2555 void init_split_point_stack() {
2556 for(int i = 0; i < THREAD_MAX; i++)
2557 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2558 SplitPointStack[i][j].parent = NULL;
2559 lock_init(&(SplitPointStack[i][j].lock), NULL);
2564 // destroy_split_point_stack() is called when the program exits, and
2565 // destroys all locks in the precomputed split point objects.
2567 void destroy_split_point_stack() {
2568 for(int i = 0; i < THREAD_MAX; i++)
2569 for(int j = 0; j < MaxActiveSplitPoints; j++)
2570 lock_destroy(&(SplitPointStack[i][j].lock));
2574 // thread_should_stop() checks whether the thread with a given threadID has
2575 // been asked to stop, directly or indirectly. This can happen if a beta
2576 // cutoff has occured in thre thread's currently active split point, or in
2577 // some ancestor of the current split point.
2579 bool thread_should_stop(int threadID) {
2580 assert(threadID >= 0 && threadID < ActiveThreads);
2584 if(Threads[threadID].stop)
2586 if(ActiveThreads <= 2)
2588 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2590 Threads[threadID].stop = true;
2597 // thread_is_available() checks whether the thread with threadID "slave" is
2598 // available to help the thread with threadID "master" at a split point. An
2599 // obvious requirement is that "slave" must be idle. With more than two
2600 // threads, this is not by itself sufficient: If "slave" is the master of
2601 // some active split point, it is only available as a slave to the other
2602 // threads which are busy searching the split point at the top of "slave"'s
2603 // split point stack (the "helpful master concept" in YBWC terminology).
2605 bool thread_is_available(int slave, int master) {
2606 assert(slave >= 0 && slave < ActiveThreads);
2607 assert(master >= 0 && master < ActiveThreads);
2608 assert(ActiveThreads > 1);
2610 if(!Threads[slave].idle || slave == master)
2613 if(Threads[slave].activeSplitPoints == 0)
2614 // No active split points means that the thread is available as a slave
2615 // for any other thread.
2618 if(ActiveThreads == 2)
2621 // Apply the "helpful master" concept if possible.
2622 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2629 // idle_thread_exists() tries to find an idle thread which is available as
2630 // a slave for the thread with threadID "master".
2632 bool idle_thread_exists(int master) {
2633 assert(master >= 0 && master < ActiveThreads);
2634 assert(ActiveThreads > 1);
2636 for(int i = 0; i < ActiveThreads; i++)
2637 if(thread_is_available(i, master))
2643 // split() does the actual work of distributing the work at a node between
2644 // several threads at PV nodes. If it does not succeed in splitting the
2645 // node (because no idle threads are available, or because we have no unused
2646 // split point objects), the function immediately returns false. If
2647 // splitting is possible, a SplitPoint object is initialized with all the
2648 // data that must be copied to the helper threads (the current position and
2649 // search stack, alpha, beta, the search depth, etc.), and we tell our
2650 // helper threads that they have been assigned work. This will cause them
2651 // to instantly leave their idle loops and call sp_search_pv(). When all
2652 // threads have returned from sp_search_pv (or, equivalently, when
2653 // splitPoint->cpus becomes 0), split() returns true.
2655 bool split(const Position &p, SearchStack *sstck, int ply,
2656 Value *alpha, Value *beta, Value *bestValue,
2657 Depth depth, int *moves,
2658 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2660 assert(sstck != NULL);
2661 assert(ply >= 0 && ply < PLY_MAX);
2662 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2663 assert(!pvNode || *alpha < *beta);
2664 assert(*beta <= VALUE_INFINITE);
2665 assert(depth > Depth(0));
2666 assert(master >= 0 && master < ActiveThreads);
2667 assert(ActiveThreads > 1);
2669 SplitPoint *splitPoint;
2674 // If no other thread is available to help us, or if we have too many
2675 // active split points, don't split:
2676 if(!idle_thread_exists(master) ||
2677 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2678 lock_release(&MPLock);
2682 // Pick the next available split point object from the split point stack:
2683 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2684 Threads[master].activeSplitPoints++;
2686 // Initialize the split point object:
2687 splitPoint->parent = Threads[master].splitPoint;
2688 splitPoint->finished = false;
2689 splitPoint->ply = ply;
2690 splitPoint->depth = depth;
2691 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2692 splitPoint->beta = *beta;
2693 splitPoint->pvNode = pvNode;
2694 splitPoint->dcCandidates = dcCandidates;
2695 splitPoint->bestValue = *bestValue;
2696 splitPoint->master = master;
2697 splitPoint->mp = mp;
2698 splitPoint->moves = *moves;
2699 splitPoint->cpus = 1;
2700 splitPoint->pos.copy(p);
2701 splitPoint->parentSstack = sstck;
2702 for(i = 0; i < ActiveThreads; i++)
2703 splitPoint->slaves[i] = 0;
2705 // Copy the current position and the search stack to the master thread:
2706 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2707 Threads[master].splitPoint = splitPoint;
2709 // Make copies of the current position and search stack for each thread:
2710 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2712 if(thread_is_available(i, master)) {
2713 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2714 Threads[i].splitPoint = splitPoint;
2715 splitPoint->slaves[i] = 1;
2719 // Tell the threads that they have work to do. This will make them leave
2721 for(i = 0; i < ActiveThreads; i++)
2722 if(i == master || splitPoint->slaves[i]) {
2723 Threads[i].workIsWaiting = true;
2724 Threads[i].idle = false;
2725 Threads[i].stop = false;
2728 lock_release(&MPLock);
2730 // Everything is set up. The master thread enters the idle loop, from
2731 // which it will instantly launch a search, because its workIsWaiting
2732 // slot is 'true'. We send the split point as a second parameter to the
2733 // idle loop, which means that the main thread will return from the idle
2734 // loop when all threads have finished their work at this split point
2735 // (i.e. when // splitPoint->cpus == 0).
2736 idle_loop(master, splitPoint);
2738 // We have returned from the idle loop, which means that all threads are
2739 // finished. Update alpha, beta and bestvalue, and return:
2741 if(pvNode) *alpha = splitPoint->alpha;
2742 *beta = splitPoint->beta;
2743 *bestValue = splitPoint->bestValue;
2744 Threads[master].stop = false;
2745 Threads[master].idle = false;
2746 Threads[master].activeSplitPoints--;
2747 Threads[master].splitPoint = splitPoint->parent;
2748 lock_release(&MPLock);
2754 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2755 // to start a new search from the root.
2757 void wake_sleeping_threads() {
2758 if(ActiveThreads > 1) {
2759 for(int i = 1; i < ActiveThreads; i++) {
2760 Threads[i].idle = true;
2761 Threads[i].workIsWaiting = false;
2763 #if !defined(_MSC_VER)
2764 pthread_mutex_lock(&WaitLock);
2765 pthread_cond_broadcast(&WaitCond);
2766 pthread_mutex_unlock(&WaitLock);
2768 for(int i = 1; i < THREAD_MAX; i++)
2769 SetEvent(SitIdleEvent[i]);
2775 // init_thread() is the function which is called when a new thread is
2776 // launched. It simply calls the idle_loop() function with the supplied
2777 // threadID. There are two versions of this function; one for POSIX threads
2778 // and one for Windows threads.
2780 #if !defined(_MSC_VER)
2782 void *init_thread(void *threadID) {
2783 idle_loop(*(int *)threadID, NULL);
2789 DWORD WINAPI init_thread(LPVOID threadID) {
2790 idle_loop(*(int *)threadID, NULL);