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-2009 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/>.
42 #include "ucioption.h"
46 //// Local definitions
53 // IterationInfoType stores search results for each iteration
55 // Because we use relatively small (dynamic) aspiration window,
56 // there happens many fail highs and fail lows in root. And
57 // because we don't do researches in those cases, "value" stored
58 // here is not necessarily exact. Instead in case of fail high/low
59 // we guess what the right value might be and store our guess
60 // as a "speculated value" and then move on. Speculated values are
61 // used just to calculate aspiration window width, so also if are
62 // not exact is not big a problem.
64 struct IterationInfoType {
66 IterationInfoType(Value v = Value(0), Value sv = Value(0))
67 : value(v), speculatedValue(sv) {}
69 Value value, speculatedValue;
73 // The BetaCounterType class is used to order moves at ply one.
74 // Apart for the first one that has its score, following moves
75 // normally have score -VALUE_INFINITE, so are ordered according
76 // to the number of beta cutoffs occurred under their subtree during
77 // the last iteration. The counters are per thread variables to avoid
78 // concurrent accessing under SMP case.
80 struct BetaCounterType {
84 void add(Color us, Depth d, int threadID);
85 void read(Color us, int64_t& our, int64_t& their);
89 // The RootMove class is used for moves at the root at the tree. For each
90 // root move, we store a score, a node count, and a PV (really a refutation
91 // in the case of moves which fail low).
96 bool operator<(const RootMove&); // used to sort
100 int64_t nodes, cumulativeNodes;
101 Move pv[PLY_MAX_PLUS_2];
102 int64_t ourBeta, theirBeta;
106 // The RootMoveList class is essentially an array of RootMove objects, with
107 // a handful of methods for accessing the data in the individual moves.
112 RootMoveList(Position& pos, Move searchMoves[]);
113 inline Move get_move(int moveNum) const;
114 inline Value get_move_score(int moveNum) const;
115 inline void set_move_score(int moveNum, Value score);
116 inline void set_move_nodes(int moveNum, int64_t nodes);
117 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
118 void set_move_pv(int moveNum, const Move pv[]);
119 inline Move get_move_pv(int moveNum, int i) const;
120 inline int64_t get_move_cumulative_nodes(int moveNum) const;
121 inline int move_count() const;
122 Move scan_for_easy_move() const;
124 void sort_multipv(int n);
127 static const int MaxRootMoves = 500;
128 RootMove moves[MaxRootMoves];
135 // Search depth at iteration 1
136 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
138 // Depth limit for selective search
139 const Depth SelectiveDepth = 7 * OnePly;
141 // Use internal iterative deepening?
142 const bool UseIIDAtPVNodes = true;
143 const bool UseIIDAtNonPVNodes = false;
145 // Internal iterative deepening margin. At Non-PV moves, when
146 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
147 // search when the static evaluation is at most IIDMargin below beta.
148 const Value IIDMargin = Value(0x100);
150 // Easy move margin. An easy move candidate must be at least this much
151 // better than the second best move.
152 const Value EasyMoveMargin = Value(0x200);
154 // Problem margin. If the score of the first move at iteration N+1 has
155 // dropped by more than this since iteration N, the boolean variable
156 // "Problem" is set to true, which will make the program spend some extra
157 // time looking for a better move.
158 const Value ProblemMargin = Value(0x28);
160 // No problem margin. If the boolean "Problem" is true, and a new move
161 // is found at the root which is less than NoProblemMargin worse than the
162 // best move from the previous iteration, Problem is set back to false.
163 const Value NoProblemMargin = Value(0x14);
165 // Null move margin. A null move search will not be done if the approximate
166 // evaluation of the position is more than NullMoveMargin below beta.
167 const Value NullMoveMargin = Value(0x300);
169 // Pruning criterions. See the code and comments in ok_to_prune() to
170 // understand their precise meaning.
171 const bool PruneEscapeMoves = false;
172 const bool PruneDefendingMoves = false;
173 const bool PruneBlockingMoves = false;
176 const Value OnlyMoveMargin = Value(100);
178 // Margins for futility pruning in the quiescence search, and at frontier
179 // and near frontier nodes.
180 const Value FutilityMarginQS = Value(0x80);
182 // Each move futility margin is decreased
183 const Value IncrementalFutilityMargin = Value(0x8);
185 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
186 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
187 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
188 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
190 const Depth RazorDepth = 4*OnePly;
192 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
193 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
195 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
196 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
199 /// Variables initialized by UCI options
201 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
202 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
204 // Depth limit for use of dynamic threat detection
205 Depth ThreatDepth; // heavy SMP read access
207 // Last seconds noise filtering (LSN)
208 const bool UseLSNFiltering = true;
209 const int LSNTime = 4000; // In milliseconds
210 const Value LSNValue = value_from_centipawns(200);
211 bool loseOnTime = false;
213 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
214 // There is heavy SMP read access on these arrays
215 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
216 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
218 // Iteration counters
220 BetaCounterType BetaCounter; // has per-thread internal data
222 // Scores and number of times the best move changed for each iteration
223 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
224 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
229 // Time managment variables
231 int MaxNodes, MaxDepth;
232 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
236 bool StopOnPonderhit;
237 bool AbortSearch; // heavy SMP read access
243 // Show current line?
244 bool ShowCurrentLine;
248 std::ofstream LogFile;
250 // MP related variables
251 int ActiveThreads = 1;
252 Depth MinimumSplitDepth;
253 int MaxThreadsPerSplitPoint;
254 Thread Threads[THREAD_MAX];
257 bool AllThreadsShouldExit = false;
258 const int MaxActiveSplitPoints = 8;
259 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
262 #if !defined(_MSC_VER)
263 pthread_cond_t WaitCond;
264 pthread_mutex_t WaitLock;
266 HANDLE SitIdleEvent[THREAD_MAX];
269 // Node counters, used only by thread[0] but try to keep in different
270 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
272 int NodesBetweenPolls = 30000;
280 Value id_loop(const Position& pos, Move searchMoves[]);
281 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
282 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
283 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move forbiddenMove = MOVE_NONE);
284 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
285 void sp_search(SplitPoint* sp, int threadID);
286 void sp_search_pv(SplitPoint* sp, int threadID);
287 void init_node(SearchStack ss[], int ply, int threadID);
288 void update_pv(SearchStack ss[], int ply);
289 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
290 bool connected_moves(const Position& pos, Move m1, Move m2);
291 bool value_is_mate(Value value);
292 bool move_is_killer(Move m, const SearchStack& ss);
293 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
294 bool ok_to_do_nullmove(const Position& pos);
295 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d);
296 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
297 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
298 void update_killers(Move m, SearchStack& ss);
300 bool fail_high_ply_1();
301 int current_search_time();
305 void print_current_line(SearchStack ss[], int ply, int threadID);
306 void wait_for_stop_or_ponderhit();
307 void init_ss_array(SearchStack ss[]);
309 void idle_loop(int threadID, SplitPoint* waitSp);
310 void init_split_point_stack();
311 void destroy_split_point_stack();
312 bool thread_should_stop(int threadID);
313 bool thread_is_available(int slave, int master);
314 bool idle_thread_exists(int master);
315 bool split(const Position& pos, SearchStack* ss, int ply,
316 Value *alpha, Value *beta, Value *bestValue,
317 const Value futilityValue, const Value approximateValue,
318 Depth depth, int *moves,
319 MovePicker *mp, int master, bool pvNode);
320 void wake_sleeping_threads();
322 #if !defined(_MSC_VER)
323 void *init_thread(void *threadID);
325 DWORD WINAPI init_thread(LPVOID threadID);
336 /// perft() is our utility to verify move generation is bug free. All the
337 /// legal moves up to given depth are generated and counted and the sum returned.
339 int perft(Position& pos, Depth depth)
343 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
345 // If we are at the last ply we don't need to do and undo
346 // the moves, just to count them.
347 if (depth <= OnePly) // Replace with '<' to test also qsearch
349 while (mp.get_next_move()) sum++;
353 // Loop through all legal moves
355 while ((move = mp.get_next_move()) != MOVE_NONE)
358 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
359 sum += perft(pos, depth - OnePly);
366 /// think() is the external interface to Stockfish's search, and is called when
367 /// the program receives the UCI 'go' command. It initializes various
368 /// search-related global variables, and calls root_search(). It returns false
369 /// when a quit command is received during the search.
371 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
372 int time[], int increment[], int movesToGo, int maxDepth,
373 int maxNodes, int maxTime, Move searchMoves[]) {
375 // Look for a book move
376 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
379 if (get_option_value_string("Book File") != OpeningBook.file_name())
380 OpeningBook.open("book.bin");
382 bookMove = OpeningBook.get_move(pos);
383 if (bookMove != MOVE_NONE)
385 std::cout << "bestmove " << bookMove << std::endl;
390 // Initialize global search variables
392 SearchStartTime = get_system_time();
393 for (int i = 0; i < THREAD_MAX; i++)
395 Threads[i].nodes = 0ULL;
396 Threads[i].failHighPly1 = false;
399 InfiniteSearch = infinite;
400 PonderSearch = ponder;
401 StopOnPonderhit = false;
407 ExactMaxTime = maxTime;
409 // Read UCI option values
410 TT.set_size(get_option_value_int("Hash"));
411 if (button_was_pressed("Clear Hash"))
414 loseOnTime = false; // reset at the beginning of a new game
417 bool PonderingEnabled = get_option_value_bool("Ponder");
418 MultiPV = get_option_value_int("MultiPV");
420 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
421 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
423 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
424 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
426 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
427 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
429 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
430 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
432 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
433 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
435 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
436 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
438 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
439 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
440 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
442 Chess960 = get_option_value_bool("UCI_Chess960");
443 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
444 UseLogFile = get_option_value_bool("Use Search Log");
446 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
448 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
449 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
451 read_weights(pos.side_to_move());
453 // Set the number of active threads
454 int newActiveThreads = get_option_value_int("Threads");
455 if (newActiveThreads != ActiveThreads)
457 ActiveThreads = newActiveThreads;
458 init_eval(ActiveThreads);
461 // Wake up sleeping threads
462 wake_sleeping_threads();
464 for (int i = 1; i < ActiveThreads; i++)
465 assert(thread_is_available(i, 0));
468 int myTime = time[side_to_move];
469 int myIncrement = increment[side_to_move];
471 if (!movesToGo) // Sudden death time control
475 MaxSearchTime = myTime / 30 + myIncrement;
476 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
477 } else { // Blitz game without increment
478 MaxSearchTime = myTime / 30;
479 AbsoluteMaxSearchTime = myTime / 8;
482 else // (x moves) / (y minutes)
486 MaxSearchTime = myTime / 2;
487 AbsoluteMaxSearchTime =
488 (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
490 MaxSearchTime = myTime / Min(movesToGo, 20);
491 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
495 if (PonderingEnabled)
497 MaxSearchTime += MaxSearchTime / 4;
498 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
501 // Fixed depth or fixed number of nodes?
504 InfiniteSearch = true; // HACK
509 NodesBetweenPolls = Min(MaxNodes, 30000);
510 InfiniteSearch = true; // HACK
512 else if (myTime && myTime < 1000)
513 NodesBetweenPolls = 1000;
514 else if (myTime && myTime < 5000)
515 NodesBetweenPolls = 5000;
517 NodesBetweenPolls = 30000;
519 // Write information to search log file
521 LogFile << "Searching: " << pos.to_fen() << std::endl
522 << "infinite: " << infinite
523 << " ponder: " << ponder
524 << " time: " << myTime
525 << " increment: " << myIncrement
526 << " moves to go: " << movesToGo << std::endl;
529 // We're ready to start thinking. Call the iterative deepening loop function
531 // FIXME we really need to cleanup all this LSN ugliness
534 Value v = id_loop(pos, searchMoves);
535 loseOnTime = ( UseLSNFiltering
542 loseOnTime = false; // reset for next match
543 while (SearchStartTime + myTime + 1000 > get_system_time())
545 id_loop(pos, searchMoves); // to fail gracefully
556 /// init_threads() is called during startup. It launches all helper threads,
557 /// and initializes the split point stack and the global locks and condition
560 void init_threads() {
564 #if !defined(_MSC_VER)
565 pthread_t pthread[1];
568 for (i = 0; i < THREAD_MAX; i++)
569 Threads[i].activeSplitPoints = 0;
571 // Initialize global locks
572 lock_init(&MPLock, NULL);
573 lock_init(&IOLock, NULL);
575 init_split_point_stack();
577 #if !defined(_MSC_VER)
578 pthread_mutex_init(&WaitLock, NULL);
579 pthread_cond_init(&WaitCond, NULL);
581 for (i = 0; i < THREAD_MAX; i++)
582 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
585 // All threads except the main thread should be initialized to idle state
586 for (i = 1; i < THREAD_MAX; i++)
588 Threads[i].stop = false;
589 Threads[i].workIsWaiting = false;
590 Threads[i].idle = true;
591 Threads[i].running = false;
594 // Launch the helper threads
595 for(i = 1; i < THREAD_MAX; i++)
597 #if !defined(_MSC_VER)
598 pthread_create(pthread, NULL, init_thread, (void*)(&i));
601 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
604 // Wait until the thread has finished launching
605 while (!Threads[i].running);
610 /// stop_threads() is called when the program exits. It makes all the
611 /// helper threads exit cleanly.
613 void stop_threads() {
615 ActiveThreads = THREAD_MAX; // HACK
616 Idle = false; // HACK
617 wake_sleeping_threads();
618 AllThreadsShouldExit = true;
619 for (int i = 1; i < THREAD_MAX; i++)
621 Threads[i].stop = true;
622 while(Threads[i].running);
624 destroy_split_point_stack();
628 /// nodes_searched() returns the total number of nodes searched so far in
629 /// the current search.
631 int64_t nodes_searched() {
633 int64_t result = 0ULL;
634 for (int i = 0; i < ActiveThreads; i++)
635 result += Threads[i].nodes;
640 // SearchStack::init() initializes a search stack. Used at the beginning of a
641 // new search from the root.
642 void SearchStack::init(int ply) {
644 pv[ply] = pv[ply + 1] = MOVE_NONE;
645 currentMove = threatMove = MOVE_NONE;
646 reduction = Depth(0);
649 void SearchStack::initKillers() {
651 mateKiller = MOVE_NONE;
652 for (int i = 0; i < KILLER_MAX; i++)
653 killers[i] = MOVE_NONE;
658 // id_loop() is the main iterative deepening loop. It calls root_search
659 // repeatedly with increasing depth until the allocated thinking time has
660 // been consumed, the user stops the search, or the maximum search depth is
663 Value id_loop(const Position& pos, Move searchMoves[]) {
666 SearchStack ss[PLY_MAX_PLUS_2];
668 // searchMoves are verified, copied, scored and sorted
669 RootMoveList rml(p, searchMoves);
671 // Print RootMoveList c'tor startup scoring to the standard output,
672 // so that we print information also for iteration 1.
673 std::cout << "info depth " << 1 << "\ninfo depth " << 1
674 << " score " << value_to_string(rml.get_move_score(0))
675 << " time " << current_search_time()
676 << " nodes " << nodes_searched()
678 << " pv " << rml.get_move(0) << "\n";
684 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
687 Move EasyMove = rml.scan_for_easy_move();
689 // Iterative deepening loop
690 while (Iteration < PLY_MAX)
692 // Initialize iteration
695 BestMoveChangesByIteration[Iteration] = 0;
699 std::cout << "info depth " << Iteration << std::endl;
701 // Calculate dynamic search window based on previous iterations
704 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
706 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
707 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
709 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
711 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
712 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
716 alpha = - VALUE_INFINITE;
717 beta = VALUE_INFINITE;
720 // Search to the current depth
721 Value value = root_search(p, ss, rml, alpha, beta);
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);
728 break; // Value cannot be trusted. Break out immediately!
730 //Save info about search result
731 Value speculatedValue;
734 Value delta = value - IterationInfo[Iteration - 1].value;
741 speculatedValue = value + delta;
742 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
744 else if (value <= alpha)
746 assert(value == alpha);
750 speculatedValue = value + delta;
751 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
753 speculatedValue = value;
755 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
756 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
758 // Erase the easy move if it differs from the new best move
759 if (ss[0].pv[0] != EasyMove)
760 EasyMove = MOVE_NONE;
767 bool stopSearch = false;
769 // Stop search early if there is only a single legal move
770 if (Iteration >= 6 && rml.move_count() == 1)
773 // Stop search early when the last two iterations returned a mate score
775 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
776 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
779 // Stop search early if one move seems to be much better than the rest
780 int64_t nodes = nodes_searched();
784 && EasyMove == ss[0].pv[0]
785 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
786 && current_search_time() > MaxSearchTime / 16)
787 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
788 && current_search_time() > MaxSearchTime / 32)))
791 // Add some extra time if the best move has changed during the last two iterations
792 if (Iteration > 5 && Iteration <= 50)
793 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
794 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
796 // Stop search if most of MaxSearchTime is consumed at the end of the
797 // iteration. We probably don't have enough time to search the first
798 // move at the next iteration anyway.
799 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
804 //FIXME: Implement fail-low emergency measures
808 StopOnPonderhit = true;
812 if (MaxDepth && Iteration >= MaxDepth)
818 // If we are pondering, we shouldn't print the best move before we
821 wait_for_stop_or_ponderhit();
823 // Print final search statistics
824 std::cout << "info nodes " << nodes_searched()
826 << " time " << current_search_time()
827 << " hashfull " << TT.full() << std::endl;
829 // Print the best move and the ponder move to the standard output
830 if (ss[0].pv[0] == MOVE_NONE)
832 ss[0].pv[0] = rml.get_move(0);
833 ss[0].pv[1] = MOVE_NONE;
835 std::cout << "bestmove " << ss[0].pv[0];
836 if (ss[0].pv[1] != MOVE_NONE)
837 std::cout << " ponder " << ss[0].pv[1];
839 std::cout << std::endl;
844 dbg_print_mean(LogFile);
846 if (dbg_show_hit_rate)
847 dbg_print_hit_rate(LogFile);
850 LogFile << "Nodes: " << nodes_searched() << std::endl
851 << "Nodes/second: " << nps() << std::endl
852 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
854 p.do_move(ss[0].pv[0], st);
855 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
856 << std::endl << std::endl;
858 return rml.get_move_score(0);
862 // root_search() is the function which searches the root node. It is
863 // similar to search_pv except that it uses a different move ordering
864 // scheme (perhaps we should try to use this at internal PV nodes, too?)
865 // and prints some information to the standard output.
867 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
869 Value oldAlpha = alpha;
873 // Loop through all the moves in the root move list
874 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
878 // We failed high, invalidate and skip next moves, leave node-counters
879 // and beta-counters as they are and quickly return, we will try to do
880 // a research at the next iteration with a bigger aspiration window.
881 rml.set_move_score(i, -VALUE_INFINITE);
889 RootMoveNumber = i + 1;
892 // Remember the node count before the move is searched. The node counts
893 // are used to sort the root moves at the next iteration.
894 nodes = nodes_searched();
896 // Reset beta cut-off counters
899 // Pick the next root move, and print the move and the move number to
900 // the standard output.
901 move = ss[0].currentMove = rml.get_move(i);
902 if (current_search_time() >= 1000)
903 std::cout << "info currmove " << move
904 << " currmovenumber " << i + 1 << std::endl;
906 // Decide search depth for this move
907 bool moveIsCheck = pos.move_is_check(move);
908 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
910 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
911 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
913 // Make the move, and search it
914 pos.do_move(move, st, ci, moveIsCheck);
918 // Aspiration window is disabled in multi-pv case
920 alpha = -VALUE_INFINITE;
922 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
923 // If the value has dropped a lot compared to the last iteration,
924 // set the boolean variable Problem to true. This variable is used
925 // for time managment: When Problem is true, we try to complete the
926 // current iteration before playing a move.
927 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
929 if (Problem && StopOnPonderhit)
930 StopOnPonderhit = false;
934 if ( newDepth >= 3*OnePly
935 && i >= MultiPV + LMRPVMoves
937 && !captureOrPromotion
938 && !move_is_castle(move))
940 ss[0].reduction = OnePly;
941 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
943 value = alpha + 1; // Just to trigger next condition
947 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
950 // Fail high! Set the boolean variable FailHigh to true, and
951 // re-search the move with a big window. The variable FailHigh is
952 // used for time managment: We try to avoid aborting the search
953 // prematurely during a fail high research.
955 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
962 // Finished searching the move. If AbortSearch is true, the search
963 // was aborted because the user interrupted the search or because we
964 // ran out of time. In this case, the return value of the search cannot
965 // be trusted, and we break out of the loop without updating the best
970 // Remember the node count for this move. The node counts are used to
971 // sort the root moves at the next iteration.
972 rml.set_move_nodes(i, nodes_searched() - nodes);
974 // Remember the beta-cutoff statistics
976 BetaCounter.read(pos.side_to_move(), our, their);
977 rml.set_beta_counters(i, our, their);
979 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
981 if (value <= alpha && i >= MultiPV)
982 rml.set_move_score(i, -VALUE_INFINITE);
985 // PV move or new best move!
988 rml.set_move_score(i, value);
990 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
991 rml.set_move_pv(i, ss[0].pv);
995 // We record how often the best move has been changed in each
996 // iteration. This information is used for time managment: When
997 // the best move changes frequently, we allocate some more time.
999 BestMoveChangesByIteration[Iteration]++;
1001 // Print search information to the standard output
1002 std::cout << "info depth " << Iteration
1003 << " score " << value_to_string(value)
1004 << ((value >= beta)?
1005 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
1006 << " time " << current_search_time()
1007 << " nodes " << nodes_searched()
1011 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1012 std::cout << ss[0].pv[j] << " ";
1014 std::cout << std::endl;
1017 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value,
1018 ((value >= beta)? VALUE_TYPE_LOWER
1019 : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)),
1026 // Reset the global variable Problem to false if the value isn't too
1027 // far below the final value from the last iteration.
1028 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1033 rml.sort_multipv(i);
1034 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1037 std::cout << "info multipv " << j + 1
1038 << " score " << value_to_string(rml.get_move_score(j))
1039 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1040 << " time " << current_search_time()
1041 << " nodes " << nodes_searched()
1045 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1046 std::cout << rml.get_move_pv(j, k) << " ";
1048 std::cout << std::endl;
1050 alpha = rml.get_move_score(Min(i, MultiPV-1));
1052 } // New best move case
1054 assert(alpha >= oldAlpha);
1056 FailLow = (alpha == oldAlpha);
1062 // search_pv() is the main search function for PV nodes.
1064 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1065 Depth depth, int ply, int threadID) {
1067 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1068 assert(beta > alpha && beta <= VALUE_INFINITE);
1069 assert(ply >= 0 && ply < PLY_MAX);
1070 assert(threadID >= 0 && threadID < ActiveThreads);
1072 Move movesSearched[256];
1077 Depth ext, newDepth;
1078 Value oldAlpha, value;
1079 bool isCheck, mateThreat, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1081 Value bestValue = -VALUE_INFINITE;
1084 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1086 // Initialize, and make an early exit in case of an aborted search,
1087 // an instant draw, maximum ply reached, etc.
1088 init_node(ss, ply, threadID);
1090 // After init_node() that calls poll()
1091 if (AbortSearch || thread_should_stop(threadID))
1097 if (ply >= PLY_MAX - 1)
1098 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1100 // Mate distance pruning
1102 alpha = Max(value_mated_in(ply), alpha);
1103 beta = Min(value_mate_in(ply+1), beta);
1107 // Transposition table lookup. At PV nodes, we don't use the TT for
1108 // pruning, but only for move ordering.
1109 tte = TT.retrieve(pos.get_key());
1110 ttMove = (tte ? tte->move() : MOVE_NONE);
1112 // Go with internal iterative deepening if we don't have a TT move
1113 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1115 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1116 ttMove = ss[ply].pv[ply];
1119 // Initialize a MovePicker object for the current position, and prepare
1120 // to search all moves
1121 isCheck = pos.is_check();
1122 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1124 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1126 // Loop through all legal moves until no moves remain or a beta cutoff
1128 while ( alpha < beta
1129 && (move = mp.get_next_move()) != MOVE_NONE
1130 && !thread_should_stop(threadID))
1132 assert(move_is_ok(move));
1134 singleReply = (isCheck && mp.number_of_evasions() == 1);
1135 moveIsCheck = pos.move_is_check(move, ci);
1136 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1138 movesSearched[moveCount++] = move;
1140 // Decide the new search depth
1141 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1143 // Only move extension
1146 && depth >= 4 * OnePly
1148 && (tte->type() & VALUE_TYPE_LOWER)
1149 && tte->move() != MOVE_NONE
1150 && tte->depth() >= depth - 3 * OnePly)
1152 Value ttValue = value_from_tt(tte->value(), ply);
1153 if (abs(ttValue) < VALUE_KNOWN_WIN)
1155 Value excValue = search(pos, ss, ttValue - OnlyMoveMargin, Max(Min(depth / 2, depth - 4 * OnePly), OnePly), ply, false, threadID, tte->move());
1156 if (excValue < ttValue - OnlyMoveMargin)
1157 ext = (depth >= 8 * OnePly)? OnePly : ext + OnePly / 2;
1161 newDepth = depth - OnePly + ext;
1163 // Update current move
1164 ss[ply].currentMove = move;
1166 // Make and search the move
1167 pos.do_move(move, st, ci, moveIsCheck);
1169 if (moveCount == 1) // The first move in list is the PV
1170 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1173 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1174 // if the move fails high will be re-searched at full depth.
1175 if ( depth >= 3*OnePly
1176 && moveCount >= LMRPVMoves
1178 && !captureOrPromotion
1179 && !move_is_castle(move)
1180 && !move_is_killer(move, ss[ply]))
1182 ss[ply].reduction = OnePly;
1183 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1186 value = alpha + 1; // Just to trigger next condition
1188 if (value > alpha) // Go with full depth non-pv search
1190 ss[ply].reduction = Depth(0);
1191 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1192 if (value > alpha && value < beta)
1194 // When the search fails high at ply 1 while searching the first
1195 // move at the root, set the flag failHighPly1. This is used for
1196 // time managment: We don't want to stop the search early in
1197 // such cases, because resolving the fail high at ply 1 could
1198 // result in a big drop in score at the root.
1199 if (ply == 1 && RootMoveNumber == 1)
1200 Threads[threadID].failHighPly1 = true;
1202 // A fail high occurred. Re-search at full window (pv search)
1203 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1204 Threads[threadID].failHighPly1 = false;
1208 pos.undo_move(move);
1210 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1213 if (value > bestValue)
1220 if (value == value_mate_in(ply + 1))
1221 ss[ply].mateKiller = move;
1223 // If we are at ply 1, and we are searching the first root move at
1224 // ply 0, set the 'Problem' variable if the score has dropped a lot
1225 // (from the computer's point of view) since the previous iteration.
1228 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1233 if ( ActiveThreads > 1
1235 && depth >= MinimumSplitDepth
1237 && idle_thread_exists(threadID)
1239 && !thread_should_stop(threadID)
1240 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE,
1241 depth, &moveCount, &mp, threadID, true))
1245 // All legal moves have been searched. A special case: If there were
1246 // no legal moves, it must be mate or stalemate.
1248 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1250 // If the search is not aborted, update the transposition table,
1251 // history counters, and killer moves.
1252 if (AbortSearch || thread_should_stop(threadID))
1255 if (bestValue <= oldAlpha)
1256 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1258 else if (bestValue >= beta)
1260 BetaCounter.add(pos.side_to_move(), depth, threadID);
1261 move = ss[ply].pv[ply];
1262 if (!pos.move_is_capture_or_promotion(move))
1264 update_history(pos, move, depth, movesSearched, moveCount);
1265 update_killers(move, ss[ply]);
1267 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1270 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1276 // search() is the search function for zero-width nodes.
1278 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1279 int ply, bool allowNullmove, int threadID, Move forbiddenMove) {
1281 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1282 assert(ply >= 0 && ply < PLY_MAX);
1283 assert(threadID >= 0 && threadID < ActiveThreads);
1285 Move movesSearched[256];
1290 Depth ext, newDepth;
1291 Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1292 bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1293 bool mateThreat = false;
1295 Value bestValue = -VALUE_INFINITE;
1298 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1300 // Initialize, and make an early exit in case of an aborted search,
1301 // an instant draw, maximum ply reached, etc.
1302 init_node(ss, ply, threadID);
1304 // After init_node() that calls poll()
1305 if (AbortSearch || thread_should_stop(threadID))
1311 if (ply >= PLY_MAX - 1)
1312 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1314 // Mate distance pruning
1315 if (value_mated_in(ply) >= beta)
1318 if (value_mate_in(ply + 1) < beta)
1321 // Position key calculation
1322 Key posKey = pos.get_key();
1324 if (forbiddenMove != MOVE_NONE)
1325 posKey ^= Position::zobExclusion;
1327 // Transposition table lookup
1328 tte = TT.retrieve(posKey);
1329 ttMove = (tte ? tte->move() : MOVE_NONE);
1331 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1333 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1334 return value_from_tt(tte->value(), ply);
1337 approximateEval = quick_evaluate(pos);
1338 isCheck = pos.is_check();
1344 && !value_is_mate(beta)
1345 && ok_to_do_nullmove(pos)
1346 && approximateEval >= beta - NullMoveMargin)
1348 ss[ply].currentMove = MOVE_NULL;
1350 pos.do_null_move(st);
1352 // Null move dynamic reduction based on depth
1353 int R = (depth >= 5 * OnePly ? 4 : 3);
1355 // Null move dynamic reduction based on value
1356 if (approximateEval - beta > PawnValueMidgame)
1359 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1361 pos.undo_null_move();
1363 if (nullValue >= beta)
1365 if (depth < 6 * OnePly)
1368 // Do zugzwang verification search
1369 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1373 // The null move failed low, which means that we may be faced with
1374 // some kind of threat. If the previous move was reduced, check if
1375 // the move that refuted the null move was somehow connected to the
1376 // move which was reduced. If a connection is found, return a fail
1377 // low score (which will cause the reduced move to fail high in the
1378 // parent node, which will trigger a re-search with full depth).
1379 if (nullValue == value_mated_in(ply + 2))
1382 ss[ply].threatMove = ss[ply + 1].currentMove;
1383 if ( depth < ThreatDepth
1384 && ss[ply - 1].reduction
1385 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1389 // Null move search not allowed, try razoring
1390 else if ( !value_is_mate(beta)
1391 && depth < RazorDepth
1392 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1393 && ss[ply - 1].currentMove != MOVE_NULL
1394 && ttMove == MOVE_NONE
1395 && !pos.has_pawn_on_7th(pos.side_to_move()))
1397 Value rbeta = beta - RazorMargins[int(depth) - 2];
1398 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1403 // Go with internal iterative deepening if we don't have a TT move
1404 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1405 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1407 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1408 ttMove = ss[ply].pv[ply];
1411 // Initialize a MovePicker object for the current position, and prepare
1412 // to search all moves.
1413 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1415 futilityValue = VALUE_NONE;
1416 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1418 // Avoid calling evaluate() if we already have the score in TT
1419 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1420 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1422 // Move count pruning limit
1423 const int MCLimit = 3 + (1 << (3*int(depth)/8));
1425 // Loop through all legal moves until no moves remain or a beta cutoff
1427 while ( bestValue < beta
1428 && (move = mp.get_next_move()) != MOVE_NONE
1429 && !thread_should_stop(threadID))
1431 assert(move_is_ok(move));
1433 if (move == forbiddenMove)
1436 singleReply = (isCheck && mp.number_of_evasions() == 1);
1437 moveIsCheck = pos.move_is_check(move, ci);
1438 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1440 movesSearched[moveCount++] = move;
1442 // Decide the new search depth
1443 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1445 // Only move extension
1446 if ( forbiddenMove == MOVE_NONE
1449 && depth >= 4 * OnePly
1451 && (tte->type() & VALUE_TYPE_LOWER)
1452 && tte->move() != MOVE_NONE
1453 && tte->depth() >= depth - 3 * OnePly)
1455 Value ttValue = value_from_tt(tte->value(), ply);
1456 if (abs(ttValue) < VALUE_KNOWN_WIN)
1458 Value excValue = search(pos, ss, ttValue - OnlyMoveMargin, Max(Min(depth / 2, depth - 4 * OnePly), OnePly), ply, false, threadID, tte->move());
1459 if (excValue < ttValue - OnlyMoveMargin)
1460 ext = (depth >= 8 * OnePly)? OnePly : ext + OnePly / 2;
1464 newDepth = depth - OnePly + ext;
1466 // Update current move
1467 ss[ply].currentMove = move;
1470 if ( useFutilityPruning
1472 && !captureOrPromotion
1475 //std::cout << std::endl;
1476 //for (int d = 2; d < 14; d++)
1477 // std::cout << d << ", " << 64*(1+bitScanReverse32(d*d)) << std::endl;
1479 //std::cout << std::endl;
1481 64*(1+bitScanReverse32(d*d))
1496 300 + 2*(1 << (3*d/4))
1512 3 + (1 << (3*int(depth)/8))
1514 1 * onePly - > moveCount >= 4
1515 2 * onePly - > moveCount >= 5
1516 3 * onePly - > moveCount >= 7
1517 4 * onePly - > moveCount >= 11
1518 5 * onePly - > moveCount >= 11
1519 6 * onePly - > moveCount >= 19
1520 7 * onePly - > moveCount >= 35
1522 // History pruning. See ok_to_prune() definition
1523 if ( moveCount >= MCLimit
1524 && ok_to_prune(pos, move, ss[ply].threatMove, depth)
1525 && bestValue > value_mated_in(PLY_MAX))
1528 // Value based pruning
1529 if (approximateEval < beta)
1531 if (futilityValue == VALUE_NONE)
1532 futilityValue = evaluate(pos, ei, threadID)
1533 + 64*(2+bitScanReverse32(int(depth) * int(depth)));
1535 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1537 if (futilityValueScaled < beta)
1539 if (futilityValueScaled > bestValue)
1540 bestValue = futilityValueScaled;
1546 // Make and search the move
1547 pos.do_move(move, st, ci, moveIsCheck);
1549 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1550 // if the move fails high will be re-searched at full depth.
1551 if ( depth >= 3*OnePly
1552 && moveCount >= LMRNonPVMoves
1554 && !captureOrPromotion
1555 && !move_is_castle(move)
1556 && !move_is_killer(move, ss[ply]))
1558 ss[ply].reduction = OnePly;
1559 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1562 value = beta; // Just to trigger next condition
1564 if (value >= beta) // Go with full depth non-pv search
1566 ss[ply].reduction = Depth(0);
1567 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1569 pos.undo_move(move);
1571 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1574 if (value > bestValue)
1580 if (value == value_mate_in(ply + 1))
1581 ss[ply].mateKiller = move;
1585 if ( ActiveThreads > 1
1587 && depth >= MinimumSplitDepth
1589 && idle_thread_exists(threadID)
1591 && !thread_should_stop(threadID)
1592 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval,
1593 depth, &moveCount, &mp, threadID, false))
1597 // All legal moves have been searched. A special case: If there were
1598 // no legal moves, it must be mate or stalemate.
1600 return (forbiddenMove == MOVE_NONE ? (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW) : beta - 1);
1602 // If the search is not aborted, update the transposition table,
1603 // history counters, and killer moves.
1604 if (AbortSearch || thread_should_stop(threadID))
1607 if (bestValue < beta)
1608 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1611 BetaCounter.add(pos.side_to_move(), depth, threadID);
1612 move = ss[ply].pv[ply];
1613 if (!pos.move_is_capture_or_promotion(move))
1615 update_history(pos, move, depth, movesSearched, moveCount);
1616 update_killers(move, ss[ply]);
1618 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1621 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1627 // qsearch() is the quiescence search function, which is called by the main
1628 // search function when the remaining depth is zero (or, to be more precise,
1629 // less than OnePly).
1631 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1632 Depth depth, int ply, int threadID) {
1634 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1635 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1637 assert(ply >= 0 && ply < PLY_MAX);
1638 assert(threadID >= 0 && threadID < ActiveThreads);
1643 Value staticValue, bestValue, value, futilityValue;
1644 bool isCheck, enoughMaterial, moveIsCheck;
1645 const TTEntry* tte = NULL;
1647 bool pvNode = (beta - alpha != 1);
1649 // Initialize, and make an early exit in case of an aborted search,
1650 // an instant draw, maximum ply reached, etc.
1651 init_node(ss, ply, threadID);
1653 // After init_node() that calls poll()
1654 if (AbortSearch || thread_should_stop(threadID))
1660 // Transposition table lookup, only when not in PV
1663 tte = TT.retrieve(pos.get_key());
1664 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1666 assert(tte->type() != VALUE_TYPE_EVAL);
1668 return value_from_tt(tte->value(), ply);
1671 ttMove = (tte ? tte->move() : MOVE_NONE);
1673 // Evaluate the position statically
1674 isCheck = pos.is_check();
1675 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1678 staticValue = -VALUE_INFINITE;
1680 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1682 // Use the cached evaluation score if possible
1683 assert(ei.futilityMargin == Value(0));
1685 staticValue = tte->value();
1688 staticValue = evaluate(pos, ei, threadID);
1690 if (ply >= PLY_MAX - 1)
1691 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1693 // Initialize "stand pat score", and return it immediately if it is
1695 bestValue = staticValue;
1697 if (bestValue >= beta)
1699 // Store the score to avoid a future costly evaluation() call
1700 if (!isCheck && !tte && ei.futilityMargin == 0)
1701 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1706 if (bestValue > alpha)
1709 // Initialize a MovePicker object for the current position, and prepare
1710 // to search the moves. Because the depth is <= 0 here, only captures,
1711 // queen promotions and checks (only if depth == 0) will be generated.
1712 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1714 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1716 // Loop through the moves until no moves remain or a beta cutoff
1718 while ( alpha < beta
1719 && (move = mp.get_next_move()) != MOVE_NONE)
1721 assert(move_is_ok(move));
1724 ss[ply].currentMove = move;
1726 moveIsCheck = pos.move_is_check(move, ci);
1734 && !move_is_promotion(move)
1735 && !pos.move_is_passed_pawn_push(move))
1737 futilityValue = staticValue
1738 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1739 pos.endgame_value_of_piece_on(move_to(move)))
1740 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1742 + ei.futilityMargin;
1744 if (futilityValue < alpha)
1746 if (futilityValue > bestValue)
1747 bestValue = futilityValue;
1752 // Don't search captures and checks with negative SEE values
1755 && !move_is_promotion(move)
1756 && pos.see_sign(move) < 0)
1759 // Make and search the move
1760 pos.do_move(move, st, ci, moveIsCheck);
1761 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1762 pos.undo_move(move);
1764 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1767 if (value > bestValue)
1778 // All legal moves have been searched. A special case: If we're in check
1779 // and no legal moves were found, it is checkmate.
1780 if (!moveCount && pos.is_check()) // Mate!
1781 return value_mated_in(ply);
1783 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1785 // Update transposition table
1786 move = ss[ply].pv[ply];
1789 // If bestValue isn't changed it means it is still the static evaluation of
1790 // the node, so keep this info to avoid a future costly evaluation() call.
1791 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1792 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1794 if (bestValue < beta)
1795 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1797 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1800 // Update killers only for good check moves
1801 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1802 update_killers(move, ss[ply]);
1808 // sp_search() is used to search from a split point. This function is called
1809 // by each thread working at the split point. It is similar to the normal
1810 // search() function, but simpler. Because we have already probed the hash
1811 // table, done a null move search, and searched the first move before
1812 // splitting, we don't have to repeat all this work in sp_search(). We
1813 // also don't need to store anything to the hash table here: This is taken
1814 // care of after we return from the split point.
1816 void sp_search(SplitPoint* sp, int threadID) {
1818 assert(threadID >= 0 && threadID < ActiveThreads);
1819 assert(ActiveThreads > 1);
1821 Position pos = Position(sp->pos);
1823 SearchStack* ss = sp->sstack[threadID];
1826 bool isCheck = pos.is_check();
1827 bool useFutilityPruning = sp->depth < SelectiveDepth
1830 while ( sp->bestValue < sp->beta
1831 && !thread_should_stop(threadID)
1832 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1834 assert(move_is_ok(move));
1836 bool moveIsCheck = pos.move_is_check(move, ci);
1837 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1839 lock_grab(&(sp->lock));
1840 int moveCount = ++sp->moves;
1841 lock_release(&(sp->lock));
1843 ss[sp->ply].currentMove = move;
1845 // Decide the new search depth.
1847 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1848 Depth newDepth = sp->depth - OnePly + ext;
1851 if ( useFutilityPruning
1853 && !captureOrPromotion)
1855 // History pruning. See ok_to_prune() definition
1856 if ( moveCount >= 2 + int(sp->depth)
1857 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)
1858 && sp->bestValue > value_mated_in(PLY_MAX))
1861 // Value based pruning
1862 if (sp->approximateEval < sp->beta)
1864 if (sp->futilityValue == VALUE_NONE)
1867 sp->futilityValue = evaluate(pos, ei, threadID)
1868 + FutilityMargins[int(sp->depth) - 2];
1871 if (sp->futilityValue < sp->beta)
1873 if (sp->futilityValue > sp->bestValue) // Less then 1% of cases
1875 lock_grab(&(sp->lock));
1876 if (sp->futilityValue > sp->bestValue)
1877 sp->bestValue = sp->futilityValue;
1878 lock_release(&(sp->lock));
1885 // Make and search the move.
1887 pos.do_move(move, st, ci, moveIsCheck);
1889 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1890 // if the move fails high will be re-searched at full depth.
1892 && moveCount >= LMRNonPVMoves
1893 && !captureOrPromotion
1894 && !move_is_castle(move)
1895 && !move_is_killer(move, ss[sp->ply]))
1897 ss[sp->ply].reduction = OnePly;
1898 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1901 value = sp->beta; // Just to trigger next condition
1903 if (value >= sp->beta) // Go with full depth non-pv search
1905 ss[sp->ply].reduction = Depth(0);
1906 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1908 pos.undo_move(move);
1910 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1912 if (thread_should_stop(threadID))
1916 if (value > sp->bestValue) // Less then 2% of cases
1918 lock_grab(&(sp->lock));
1919 if (value > sp->bestValue && !thread_should_stop(threadID))
1921 sp->bestValue = value;
1922 if (sp->bestValue >= sp->beta)
1924 sp_update_pv(sp->parentSstack, ss, sp->ply);
1925 for (int i = 0; i < ActiveThreads; i++)
1926 if (i != threadID && (i == sp->master || sp->slaves[i]))
1927 Threads[i].stop = true;
1929 sp->finished = true;
1932 lock_release(&(sp->lock));
1936 lock_grab(&(sp->lock));
1938 // If this is the master thread and we have been asked to stop because of
1939 // a beta cutoff higher up in the tree, stop all slave threads.
1940 if (sp->master == threadID && thread_should_stop(threadID))
1941 for (int i = 0; i < ActiveThreads; i++)
1943 Threads[i].stop = true;
1946 sp->slaves[threadID] = 0;
1948 lock_release(&(sp->lock));
1952 // sp_search_pv() is used to search from a PV split point. This function
1953 // is called by each thread working at the split point. It is similar to
1954 // the normal search_pv() function, but simpler. Because we have already
1955 // probed the hash table and searched the first move before splitting, we
1956 // don't have to repeat all this work in sp_search_pv(). We also don't
1957 // need to store anything to the hash table here: This is taken care of
1958 // after we return from the split point.
1960 void sp_search_pv(SplitPoint* sp, int threadID) {
1962 assert(threadID >= 0 && threadID < ActiveThreads);
1963 assert(ActiveThreads > 1);
1965 Position pos = Position(sp->pos);
1967 SearchStack* ss = sp->sstack[threadID];
1971 while ( sp->alpha < sp->beta
1972 && !thread_should_stop(threadID)
1973 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1975 bool moveIsCheck = pos.move_is_check(move, ci);
1976 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1978 assert(move_is_ok(move));
1980 lock_grab(&(sp->lock));
1981 int moveCount = ++sp->moves;
1982 lock_release(&(sp->lock));
1984 ss[sp->ply].currentMove = move;
1986 // Decide the new search depth.
1988 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1989 Depth newDepth = sp->depth - OnePly + ext;
1991 // Make and search the move.
1993 pos.do_move(move, st, ci, moveIsCheck);
1995 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1996 // if the move fails high will be re-searched at full depth.
1998 && moveCount >= LMRPVMoves
1999 && !captureOrPromotion
2000 && !move_is_castle(move)
2001 && !move_is_killer(move, ss[sp->ply]))
2003 ss[sp->ply].reduction = OnePly;
2004 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
2007 value = sp->alpha + 1; // Just to trigger next condition
2009 if (value > sp->alpha) // Go with full depth non-pv search
2011 ss[sp->ply].reduction = Depth(0);
2012 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
2014 if (value > sp->alpha && value < sp->beta)
2016 // When the search fails high at ply 1 while searching the first
2017 // move at the root, set the flag failHighPly1. This is used for
2018 // time managment: We don't want to stop the search early in
2019 // such cases, because resolving the fail high at ply 1 could
2020 // result in a big drop in score at the root.
2021 if (sp->ply == 1 && RootMoveNumber == 1)
2022 Threads[threadID].failHighPly1 = true;
2024 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2025 Threads[threadID].failHighPly1 = false;
2028 pos.undo_move(move);
2030 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2032 if (thread_should_stop(threadID))
2036 lock_grab(&(sp->lock));
2037 if (value > sp->bestValue && !thread_should_stop(threadID))
2039 sp->bestValue = value;
2040 if (value > sp->alpha)
2043 sp_update_pv(sp->parentSstack, ss, sp->ply);
2044 if (value == value_mate_in(sp->ply + 1))
2045 ss[sp->ply].mateKiller = move;
2047 if (value >= sp->beta)
2049 for (int i = 0; i < ActiveThreads; i++)
2050 if (i != threadID && (i == sp->master || sp->slaves[i]))
2051 Threads[i].stop = true;
2053 sp->finished = true;
2056 // If we are at ply 1, and we are searching the first root move at
2057 // ply 0, set the 'Problem' variable if the score has dropped a lot
2058 // (from the computer's point of view) since the previous iteration.
2061 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2064 lock_release(&(sp->lock));
2067 lock_grab(&(sp->lock));
2069 // If this is the master thread and we have been asked to stop because of
2070 // a beta cutoff higher up in the tree, stop all slave threads.
2071 if (sp->master == threadID && thread_should_stop(threadID))
2072 for (int i = 0; i < ActiveThreads; i++)
2074 Threads[i].stop = true;
2077 sp->slaves[threadID] = 0;
2079 lock_release(&(sp->lock));
2082 /// The BetaCounterType class
2084 BetaCounterType::BetaCounterType() { clear(); }
2086 void BetaCounterType::clear() {
2088 for (int i = 0; i < THREAD_MAX; i++)
2089 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2092 void BetaCounterType::add(Color us, Depth d, int threadID) {
2094 // Weighted count based on depth
2095 Threads[threadID].betaCutOffs[us] += unsigned(d);
2098 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2101 for (int i = 0; i < THREAD_MAX; i++)
2103 our += Threads[i].betaCutOffs[us];
2104 their += Threads[i].betaCutOffs[opposite_color(us)];
2109 /// The RootMove class
2113 RootMove::RootMove() {
2114 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
2117 // RootMove::operator<() is the comparison function used when
2118 // sorting the moves. A move m1 is considered to be better
2119 // than a move m2 if it has a higher score, or if the moves
2120 // have equal score but m1 has the higher node count.
2122 bool RootMove::operator<(const RootMove& m) {
2124 if (score != m.score)
2125 return (score < m.score);
2127 return theirBeta <= m.theirBeta;
2130 /// The RootMoveList class
2134 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2136 MoveStack mlist[MaxRootMoves];
2137 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2139 // Generate all legal moves
2140 MoveStack* last = generate_moves(pos, mlist);
2142 // Add each move to the moves[] array
2143 for (MoveStack* cur = mlist; cur != last; cur++)
2145 bool includeMove = includeAllMoves;
2147 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2148 includeMove = (searchMoves[k] == cur->move);
2153 // Find a quick score for the move
2155 SearchStack ss[PLY_MAX_PLUS_2];
2158 moves[count].move = cur->move;
2159 pos.do_move(moves[count].move, st);
2160 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2161 pos.undo_move(moves[count].move);
2162 moves[count].pv[0] = moves[count].move;
2163 moves[count].pv[1] = MOVE_NONE; // FIXME
2170 // Simple accessor methods for the RootMoveList class
2172 inline Move RootMoveList::get_move(int moveNum) const {
2173 return moves[moveNum].move;
2176 inline Value RootMoveList::get_move_score(int moveNum) const {
2177 return moves[moveNum].score;
2180 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2181 moves[moveNum].score = score;
2184 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2185 moves[moveNum].nodes = nodes;
2186 moves[moveNum].cumulativeNodes += nodes;
2189 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2190 moves[moveNum].ourBeta = our;
2191 moves[moveNum].theirBeta = their;
2194 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2196 for(j = 0; pv[j] != MOVE_NONE; j++)
2197 moves[moveNum].pv[j] = pv[j];
2198 moves[moveNum].pv[j] = MOVE_NONE;
2201 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2202 return moves[moveNum].pv[i];
2205 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2206 return moves[moveNum].cumulativeNodes;
2209 inline int RootMoveList::move_count() const {
2214 // RootMoveList::scan_for_easy_move() is called at the end of the first
2215 // iteration, and is used to detect an "easy move", i.e. a move which appears
2216 // to be much bester than all the rest. If an easy move is found, the move
2217 // is returned, otherwise the function returns MOVE_NONE. It is very
2218 // important that this function is called at the right moment: The code
2219 // assumes that the first iteration has been completed and the moves have
2220 // been sorted. This is done in RootMoveList c'tor.
2222 Move RootMoveList::scan_for_easy_move() const {
2229 // moves are sorted so just consider the best and the second one
2230 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2236 // RootMoveList::sort() sorts the root move list at the beginning of a new
2239 inline void RootMoveList::sort() {
2241 sort_multipv(count - 1); // all items
2245 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2246 // list by their scores and depths. It is used to order the different PVs
2247 // correctly in MultiPV mode.
2249 void RootMoveList::sort_multipv(int n) {
2251 for (int i = 1; i <= n; i++)
2253 RootMove rm = moves[i];
2255 for (j = i; j > 0 && moves[j-1] < rm; j--)
2256 moves[j] = moves[j-1];
2262 // init_node() is called at the beginning of all the search functions
2263 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2264 // stack object corresponding to the current node. Once every
2265 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2266 // for user input and checks whether it is time to stop the search.
2268 void init_node(SearchStack ss[], int ply, int threadID) {
2270 assert(ply >= 0 && ply < PLY_MAX);
2271 assert(threadID >= 0 && threadID < ActiveThreads);
2273 Threads[threadID].nodes++;
2278 if (NodesSincePoll >= NodesBetweenPolls)
2285 ss[ply+2].initKillers();
2287 if (Threads[threadID].printCurrentLine)
2288 print_current_line(ss, ply, threadID);
2292 // update_pv() is called whenever a search returns a value > alpha. It
2293 // updates the PV in the SearchStack object corresponding to the current
2296 void update_pv(SearchStack ss[], int ply) {
2297 assert(ply >= 0 && ply < PLY_MAX);
2299 ss[ply].pv[ply] = ss[ply].currentMove;
2301 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2302 ss[ply].pv[p] = ss[ply+1].pv[p];
2303 ss[ply].pv[p] = MOVE_NONE;
2307 // sp_update_pv() is a variant of update_pv for use at split points. The
2308 // difference between the two functions is that sp_update_pv also updates
2309 // the PV at the parent node.
2311 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2312 assert(ply >= 0 && ply < PLY_MAX);
2314 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2316 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2317 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2318 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2322 // connected_moves() tests whether two moves are 'connected' in the sense
2323 // that the first move somehow made the second move possible (for instance
2324 // if the moving piece is the same in both moves). The first move is
2325 // assumed to be the move that was made to reach the current position, while
2326 // the second move is assumed to be a move from the current position.
2328 bool connected_moves(const Position& pos, Move m1, Move m2) {
2330 Square f1, t1, f2, t2;
2333 assert(move_is_ok(m1));
2334 assert(move_is_ok(m2));
2336 if (m2 == MOVE_NONE)
2339 // Case 1: The moving piece is the same in both moves
2345 // Case 2: The destination square for m2 was vacated by m1
2351 // Case 3: Moving through the vacated square
2352 if ( piece_is_slider(pos.piece_on(f2))
2353 && bit_is_set(squares_between(f2, t2), f1))
2356 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2357 p = pos.piece_on(t1);
2358 if (bit_is_set(pos.attacks_from(p, t1), t2))
2361 // Case 5: Discovered check, checking piece is the piece moved in m1
2362 if ( piece_is_slider(p)
2363 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2364 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2366 Bitboard occ = pos.occupied_squares();
2367 Color us = pos.side_to_move();
2368 Square ksq = pos.king_square(us);
2369 clear_bit(&occ, f2);
2370 if (type_of_piece(p) == BISHOP)
2372 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2375 else if (type_of_piece(p) == ROOK)
2377 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2382 assert(type_of_piece(p) == QUEEN);
2383 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2391 // value_is_mate() checks if the given value is a mate one
2392 // eventually compensated for the ply.
2394 bool value_is_mate(Value value) {
2396 assert(abs(value) <= VALUE_INFINITE);
2398 return value <= value_mated_in(PLY_MAX)
2399 || value >= value_mate_in(PLY_MAX);
2403 // move_is_killer() checks if the given move is among the
2404 // killer moves of that ply.
2406 bool move_is_killer(Move m, const SearchStack& ss) {
2408 const Move* k = ss.killers;
2409 for (int i = 0; i < KILLER_MAX; i++, k++)
2417 // extension() decides whether a move should be searched with normal depth,
2418 // or with extended depth. Certain classes of moves (checking moves, in
2419 // particular) are searched with bigger depth than ordinary moves and in
2420 // any case are marked as 'dangerous'. Note that also if a move is not
2421 // extended, as example because the corresponding UCI option is set to zero,
2422 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2424 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2425 bool check, bool singleReply, bool mateThreat, bool* dangerous) {
2427 assert(m != MOVE_NONE);
2429 Depth result = Depth(0);
2430 *dangerous = check | singleReply | mateThreat;
2435 result += CheckExtension[pvNode];
2438 result += SingleReplyExtension[pvNode];
2441 result += MateThreatExtension[pvNode];
2444 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2446 Color c = pos.side_to_move();
2447 if (relative_rank(c, move_to(m)) == RANK_7)
2449 result += PawnPushTo7thExtension[pvNode];
2452 if (pos.pawn_is_passed(c, move_to(m)))
2454 result += PassedPawnExtension[pvNode];
2459 if ( captureOrPromotion
2460 && pos.type_of_piece_on(move_to(m)) != PAWN
2461 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2462 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2463 && !move_is_promotion(m)
2466 result += PawnEndgameExtension[pvNode];
2471 && captureOrPromotion
2472 && pos.type_of_piece_on(move_to(m)) != PAWN
2473 && pos.see_sign(m) >= 0)
2479 return Min(result, OnePly);
2483 // ok_to_do_nullmove() looks at the current position and decides whether
2484 // doing a 'null move' should be allowed. In order to avoid zugzwang
2485 // problems, null moves are not allowed when the side to move has very
2486 // little material left. Currently, the test is a bit too simple: Null
2487 // moves are avoided only when the side to move has only pawns left. It's
2488 // probably a good idea to avoid null moves in at least some more
2489 // complicated endgames, e.g. KQ vs KR. FIXME
2491 bool ok_to_do_nullmove(const Position& pos) {
2493 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2497 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2498 // non-tactical moves late in the move list close to the leaves are
2499 // candidates for pruning.
2501 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2503 assert(move_is_ok(m));
2504 assert(threat == MOVE_NONE || move_is_ok(threat));
2505 assert(!pos.move_is_check(m));
2506 assert(!pos.move_is_capture_or_promotion(m));
2507 assert(!pos.move_is_passed_pawn_push(m));
2508 assert(d >= OnePly);
2510 Square mfrom, mto, tfrom, tto;
2512 mfrom = move_from(m);
2514 tfrom = move_from(threat);
2515 tto = move_to(threat);
2517 // Case 1: Castling moves are never pruned
2518 if (move_is_castle(m))
2521 // Case 2: Don't prune moves which move the threatened piece
2522 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2525 // Case 3: If the threatened piece has value less than or equal to the
2526 // value of the threatening piece, don't prune move which defend it.
2527 if ( !PruneDefendingMoves
2528 && threat != MOVE_NONE
2529 && pos.move_is_capture(threat)
2530 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2531 || pos.type_of_piece_on(tfrom) == KING)
2532 && pos.move_attacks_square(m, tto))
2535 // Case 4: Don't prune moves with good history
2536 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2539 // Case 5: If the moving piece in the threatened move is a slider, don't
2540 // prune safe moves which block its ray.
2541 if ( !PruneBlockingMoves
2542 && threat != MOVE_NONE
2543 && piece_is_slider(pos.piece_on(tfrom))
2544 && bit_is_set(squares_between(tfrom, tto), mto)
2545 && pos.see_sign(m) >= 0)
2552 // ok_to_use_TT() returns true if a transposition table score
2553 // can be used at a given point in search.
2555 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2557 Value v = value_from_tt(tte->value(), ply);
2559 return ( tte->depth() >= depth
2560 || v >= Max(value_mate_in(100), beta)
2561 || v < Min(value_mated_in(100), beta))
2563 && ( (is_lower_bound(tte->type()) && v >= beta)
2564 || (is_upper_bound(tte->type()) && v < beta));
2568 // update_history() registers a good move that produced a beta-cutoff
2569 // in history and marks as failures all the other moves of that ply.
2571 void update_history(const Position& pos, Move m, Depth depth,
2572 Move movesSearched[], int moveCount) {
2574 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2576 for (int i = 0; i < moveCount - 1; i++)
2578 assert(m != movesSearched[i]);
2579 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2580 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2585 // update_killers() add a good move that produced a beta-cutoff
2586 // among the killer moves of that ply.
2588 void update_killers(Move m, SearchStack& ss) {
2590 if (m == ss.killers[0])
2593 for (int i = KILLER_MAX - 1; i > 0; i--)
2594 ss.killers[i] = ss.killers[i - 1];
2600 // fail_high_ply_1() checks if some thread is currently resolving a fail
2601 // high at ply 1 at the node below the first root node. This information
2602 // is used for time managment.
2604 bool fail_high_ply_1() {
2606 for(int i = 0; i < ActiveThreads; i++)
2607 if (Threads[i].failHighPly1)
2614 // current_search_time() returns the number of milliseconds which have passed
2615 // since the beginning of the current search.
2617 int current_search_time() {
2618 return get_system_time() - SearchStartTime;
2622 // nps() computes the current nodes/second count.
2625 int t = current_search_time();
2626 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2630 // poll() performs two different functions: It polls for user input, and it
2631 // looks at the time consumed so far and decides if it's time to abort the
2636 static int lastInfoTime;
2637 int t = current_search_time();
2642 // We are line oriented, don't read single chars
2643 std::string command;
2644 if (!std::getline(std::cin, command))
2647 if (command == "quit")
2650 PonderSearch = false;
2654 else if (command == "stop")
2657 PonderSearch = false;
2659 else if (command == "ponderhit")
2662 // Print search information
2666 else if (lastInfoTime > t)
2667 // HACK: Must be a new search where we searched less than
2668 // NodesBetweenPolls nodes during the first second of search.
2671 else if (t - lastInfoTime >= 1000)
2678 if (dbg_show_hit_rate)
2679 dbg_print_hit_rate();
2681 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2682 << " time " << t << " hashfull " << TT.full() << std::endl;
2683 lock_release(&IOLock);
2684 if (ShowCurrentLine)
2685 Threads[0].printCurrentLine = true;
2687 // Should we stop the search?
2691 bool overTime = t > AbsoluteMaxSearchTime
2692 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2693 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2694 && t > 6*(MaxSearchTime + ExtraSearchTime));
2696 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2697 || (ExactMaxTime && t >= ExactMaxTime)
2698 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2703 // ponderhit() is called when the program is pondering (i.e. thinking while
2704 // it's the opponent's turn to move) in order to let the engine know that
2705 // it correctly predicted the opponent's move.
2709 int t = current_search_time();
2710 PonderSearch = false;
2711 if (Iteration >= 3 &&
2712 (!InfiniteSearch && (StopOnPonderhit ||
2713 t > AbsoluteMaxSearchTime ||
2714 (RootMoveNumber == 1 &&
2715 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2716 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2717 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2722 // print_current_line() prints the current line of search for a given
2723 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2725 void print_current_line(SearchStack ss[], int ply, int threadID) {
2727 assert(ply >= 0 && ply < PLY_MAX);
2728 assert(threadID >= 0 && threadID < ActiveThreads);
2730 if (!Threads[threadID].idle)
2733 std::cout << "info currline " << (threadID + 1);
2734 for (int p = 0; p < ply; p++)
2735 std::cout << " " << ss[p].currentMove;
2737 std::cout << std::endl;
2738 lock_release(&IOLock);
2740 Threads[threadID].printCurrentLine = false;
2741 if (threadID + 1 < ActiveThreads)
2742 Threads[threadID + 1].printCurrentLine = true;
2746 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2748 void init_ss_array(SearchStack ss[]) {
2750 for (int i = 0; i < 3; i++)
2753 ss[i].initKillers();
2758 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2759 // while the program is pondering. The point is to work around a wrinkle in
2760 // the UCI protocol: When pondering, the engine is not allowed to give a
2761 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2762 // We simply wait here until one of these commands is sent, and return,
2763 // after which the bestmove and pondermove will be printed (in id_loop()).
2765 void wait_for_stop_or_ponderhit() {
2767 std::string command;
2771 if (!std::getline(std::cin, command))
2774 if (command == "quit")
2779 else if (command == "ponderhit" || command == "stop")
2785 // idle_loop() is where the threads are parked when they have no work to do.
2786 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2787 // object for which the current thread is the master.
2789 void idle_loop(int threadID, SplitPoint* waitSp) {
2790 assert(threadID >= 0 && threadID < THREAD_MAX);
2792 Threads[threadID].running = true;
2795 if(AllThreadsShouldExit && threadID != 0)
2798 // If we are not thinking, wait for a condition to be signaled instead
2799 // of wasting CPU time polling for work:
2800 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2801 #if !defined(_MSC_VER)
2802 pthread_mutex_lock(&WaitLock);
2803 if(Idle || threadID >= ActiveThreads)
2804 pthread_cond_wait(&WaitCond, &WaitLock);
2805 pthread_mutex_unlock(&WaitLock);
2807 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2811 // If this thread has been assigned work, launch a search
2812 if(Threads[threadID].workIsWaiting) {
2813 Threads[threadID].workIsWaiting = false;
2814 if(Threads[threadID].splitPoint->pvNode)
2815 sp_search_pv(Threads[threadID].splitPoint, threadID);
2817 sp_search(Threads[threadID].splitPoint, threadID);
2818 Threads[threadID].idle = true;
2821 // If this thread is the master of a split point and all threads have
2822 // finished their work at this split point, return from the idle loop.
2823 if(waitSp != NULL && waitSp->cpus == 0)
2827 Threads[threadID].running = false;
2831 // init_split_point_stack() is called during program initialization, and
2832 // initializes all split point objects.
2834 void init_split_point_stack() {
2835 for(int i = 0; i < THREAD_MAX; i++)
2836 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2837 SplitPointStack[i][j].parent = NULL;
2838 lock_init(&(SplitPointStack[i][j].lock), NULL);
2843 // destroy_split_point_stack() is called when the program exits, and
2844 // destroys all locks in the precomputed split point objects.
2846 void destroy_split_point_stack() {
2847 for(int i = 0; i < THREAD_MAX; i++)
2848 for(int j = 0; j < MaxActiveSplitPoints; j++)
2849 lock_destroy(&(SplitPointStack[i][j].lock));
2853 // thread_should_stop() checks whether the thread with a given threadID has
2854 // been asked to stop, directly or indirectly. This can happen if a beta
2855 // cutoff has occured in thre thread's currently active split point, or in
2856 // some ancestor of the current split point.
2858 bool thread_should_stop(int threadID) {
2859 assert(threadID >= 0 && threadID < ActiveThreads);
2863 if(Threads[threadID].stop)
2865 if(ActiveThreads <= 2)
2867 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2869 Threads[threadID].stop = true;
2876 // thread_is_available() checks whether the thread with threadID "slave" is
2877 // available to help the thread with threadID "master" at a split point. An
2878 // obvious requirement is that "slave" must be idle. With more than two
2879 // threads, this is not by itself sufficient: If "slave" is the master of
2880 // some active split point, it is only available as a slave to the other
2881 // threads which are busy searching the split point at the top of "slave"'s
2882 // split point stack (the "helpful master concept" in YBWC terminology).
2884 bool thread_is_available(int slave, int master) {
2885 assert(slave >= 0 && slave < ActiveThreads);
2886 assert(master >= 0 && master < ActiveThreads);
2887 assert(ActiveThreads > 1);
2889 if(!Threads[slave].idle || slave == master)
2892 if(Threads[slave].activeSplitPoints == 0)
2893 // No active split points means that the thread is available as a slave
2894 // for any other thread.
2897 if(ActiveThreads == 2)
2900 // Apply the "helpful master" concept if possible.
2901 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2908 // idle_thread_exists() tries to find an idle thread which is available as
2909 // a slave for the thread with threadID "master".
2911 bool idle_thread_exists(int master) {
2912 assert(master >= 0 && master < ActiveThreads);
2913 assert(ActiveThreads > 1);
2915 for(int i = 0; i < ActiveThreads; i++)
2916 if(thread_is_available(i, master))
2922 // split() does the actual work of distributing the work at a node between
2923 // several threads at PV nodes. If it does not succeed in splitting the
2924 // node (because no idle threads are available, or because we have no unused
2925 // split point objects), the function immediately returns false. If
2926 // splitting is possible, a SplitPoint object is initialized with all the
2927 // data that must be copied to the helper threads (the current position and
2928 // search stack, alpha, beta, the search depth, etc.), and we tell our
2929 // helper threads that they have been assigned work. This will cause them
2930 // to instantly leave their idle loops and call sp_search_pv(). When all
2931 // threads have returned from sp_search_pv (or, equivalently, when
2932 // splitPoint->cpus becomes 0), split() returns true.
2934 bool split(const Position& p, SearchStack* sstck, int ply,
2935 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2936 const Value approximateEval, Depth depth, int* moves,
2937 MovePicker* mp, int master, bool pvNode) {
2940 assert(sstck != NULL);
2941 assert(ply >= 0 && ply < PLY_MAX);
2942 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2943 assert(!pvNode || *alpha < *beta);
2944 assert(*beta <= VALUE_INFINITE);
2945 assert(depth > Depth(0));
2946 assert(master >= 0 && master < ActiveThreads);
2947 assert(ActiveThreads > 1);
2949 SplitPoint* splitPoint;
2954 // If no other thread is available to help us, or if we have too many
2955 // active split points, don't split.
2956 if(!idle_thread_exists(master) ||
2957 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2958 lock_release(&MPLock);
2962 // Pick the next available split point object from the split point stack
2963 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2964 Threads[master].activeSplitPoints++;
2966 // Initialize the split point object
2967 splitPoint->parent = Threads[master].splitPoint;
2968 splitPoint->finished = false;
2969 splitPoint->ply = ply;
2970 splitPoint->depth = depth;
2971 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2972 splitPoint->beta = *beta;
2973 splitPoint->pvNode = pvNode;
2974 splitPoint->bestValue = *bestValue;
2975 splitPoint->futilityValue = futilityValue;
2976 splitPoint->approximateEval = approximateEval;
2977 splitPoint->master = master;
2978 splitPoint->mp = mp;
2979 splitPoint->moves = *moves;
2980 splitPoint->cpus = 1;
2981 splitPoint->pos.copy(p);
2982 splitPoint->parentSstack = sstck;
2983 for(i = 0; i < ActiveThreads; i++)
2984 splitPoint->slaves[i] = 0;
2986 // Copy the current position and the search stack to the master thread
2987 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2988 Threads[master].splitPoint = splitPoint;
2990 // Make copies of the current position and search stack for each thread
2991 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2993 if(thread_is_available(i, master)) {
2994 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2995 Threads[i].splitPoint = splitPoint;
2996 splitPoint->slaves[i] = 1;
3000 // Tell the threads that they have work to do. This will make them leave
3002 for(i = 0; i < ActiveThreads; i++)
3003 if(i == master || splitPoint->slaves[i]) {
3004 Threads[i].workIsWaiting = true;
3005 Threads[i].idle = false;
3006 Threads[i].stop = false;
3009 lock_release(&MPLock);
3011 // Everything is set up. The master thread enters the idle loop, from
3012 // which it will instantly launch a search, because its workIsWaiting
3013 // slot is 'true'. We send the split point as a second parameter to the
3014 // idle loop, which means that the main thread will return from the idle
3015 // loop when all threads have finished their work at this split point
3016 // (i.e. when // splitPoint->cpus == 0).
3017 idle_loop(master, splitPoint);
3019 // We have returned from the idle loop, which means that all threads are
3020 // finished. Update alpha, beta and bestvalue, and return.
3022 if(pvNode) *alpha = splitPoint->alpha;
3023 *beta = splitPoint->beta;
3024 *bestValue = splitPoint->bestValue;
3025 Threads[master].stop = false;
3026 Threads[master].idle = false;
3027 Threads[master].activeSplitPoints--;
3028 Threads[master].splitPoint = splitPoint->parent;
3029 lock_release(&MPLock);
3035 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3036 // to start a new search from the root.
3038 void wake_sleeping_threads() {
3039 if(ActiveThreads > 1) {
3040 for(int i = 1; i < ActiveThreads; i++) {
3041 Threads[i].idle = true;
3042 Threads[i].workIsWaiting = false;
3044 #if !defined(_MSC_VER)
3045 pthread_mutex_lock(&WaitLock);
3046 pthread_cond_broadcast(&WaitCond);
3047 pthread_mutex_unlock(&WaitLock);
3049 for(int i = 1; i < THREAD_MAX; i++)
3050 SetEvent(SitIdleEvent[i]);
3056 // init_thread() is the function which is called when a new thread is
3057 // launched. It simply calls the idle_loop() function with the supplied
3058 // threadID. There are two versions of this function; one for POSIX threads
3059 // and one for Windows threads.
3061 #if !defined(_MSC_VER)
3063 void *init_thread(void *threadID) {
3064 idle_loop(*(int *)threadID, NULL);
3070 DWORD WINAPI init_thread(LPVOID threadID) {
3071 idle_loop(*(int *)threadID, NULL);