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;
123 void sort_multipv(int n);
126 static const int MaxRootMoves = 500;
127 RootMove moves[MaxRootMoves];
134 // Search depth at iteration 1
135 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
137 // Depth limit for selective search
138 const Depth SelectiveDepth = 7 * OnePly;
140 // Use internal iterative deepening?
141 const bool UseIIDAtPVNodes = true;
142 const bool UseIIDAtNonPVNodes = false;
144 // Internal iterative deepening margin. At Non-PV moves, when
145 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
146 // search when the static evaluation is at most IIDMargin below beta.
147 const Value IIDMargin = Value(0x100);
149 // Easy move margin. An easy move candidate must be at least this much
150 // better than the second best move.
151 const Value EasyMoveMargin = Value(0x200);
153 // Problem margin. If the score of the first move at iteration N+1 has
154 // dropped by more than this since iteration N, the boolean variable
155 // "Problem" is set to true, which will make the program spend some extra
156 // time looking for a better move.
157 const Value ProblemMargin = Value(0x28);
159 // No problem margin. If the boolean "Problem" is true, and a new move
160 // is found at the root which is less than NoProblemMargin worse than the
161 // best move from the previous iteration, Problem is set back to false.
162 const Value NoProblemMargin = Value(0x14);
164 // Null move margin. A null move search will not be done if the approximate
165 // evaluation of the position is more than NullMoveMargin below beta.
166 const Value NullMoveMargin = Value(0x300);
168 // Pruning criterions. See the code and comments in ok_to_prune() to
169 // understand their precise meaning.
170 const bool PruneEscapeMoves = false;
171 const bool PruneDefendingMoves = false;
172 const bool PruneBlockingMoves = false;
174 // If the TT move is at least SingleReplyMargin better then the
175 // remaining ones we will extend it.
176 const Value SingleReplyMargin = Value(0x64);
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 excludedMove = 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 // LSN filtering. Used only for developing purpose. Disabled by default.
533 // Step 2. If after last move we decided to lose on time, do it now!
534 while (SearchStartTime + myTime + 1000 > get_system_time())
538 // We're ready to start thinking. Call the iterative deepening loop function
539 Value v = id_loop(pos, searchMoves);
541 // LSN filtering. Used only for developing purpose. Disabled by default.
544 // Step 1. If this is sudden death game and our position is hopeless,
545 // decide to lose on time.
546 if ( !loseOnTime // If we already lost on time, go to step 3.
556 // Step 3. Now after stepping over the time limit, reset flag for next match.
569 /// init_threads() is called during startup. It launches all helper threads,
570 /// and initializes the split point stack and the global locks and condition
573 void init_threads() {
577 #if !defined(_MSC_VER)
578 pthread_t pthread[1];
581 for (i = 0; i < THREAD_MAX; i++)
582 Threads[i].activeSplitPoints = 0;
584 // Initialize global locks
585 lock_init(&MPLock, NULL);
586 lock_init(&IOLock, NULL);
588 init_split_point_stack();
590 #if !defined(_MSC_VER)
591 pthread_mutex_init(&WaitLock, NULL);
592 pthread_cond_init(&WaitCond, NULL);
594 for (i = 0; i < THREAD_MAX; i++)
595 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
598 // All threads except the main thread should be initialized to idle state
599 for (i = 1; i < THREAD_MAX; i++)
601 Threads[i].stop = false;
602 Threads[i].workIsWaiting = false;
603 Threads[i].idle = true;
604 Threads[i].running = false;
607 // Launch the helper threads
608 for(i = 1; i < THREAD_MAX; i++)
610 #if !defined(_MSC_VER)
611 pthread_create(pthread, NULL, init_thread, (void*)(&i));
614 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
617 // Wait until the thread has finished launching
618 while (!Threads[i].running);
623 /// stop_threads() is called when the program exits. It makes all the
624 /// helper threads exit cleanly.
626 void stop_threads() {
628 ActiveThreads = THREAD_MAX; // HACK
629 Idle = false; // HACK
630 wake_sleeping_threads();
631 AllThreadsShouldExit = true;
632 for (int i = 1; i < THREAD_MAX; i++)
634 Threads[i].stop = true;
635 while(Threads[i].running);
637 destroy_split_point_stack();
641 /// nodes_searched() returns the total number of nodes searched so far in
642 /// the current search.
644 int64_t nodes_searched() {
646 int64_t result = 0ULL;
647 for (int i = 0; i < ActiveThreads; i++)
648 result += Threads[i].nodes;
653 // SearchStack::init() initializes a search stack. Used at the beginning of a
654 // new search from the root.
655 void SearchStack::init(int ply) {
657 pv[ply] = pv[ply + 1] = MOVE_NONE;
658 currentMove = threatMove = MOVE_NONE;
659 reduction = Depth(0);
662 void SearchStack::initKillers() {
664 mateKiller = MOVE_NONE;
665 for (int i = 0; i < KILLER_MAX; i++)
666 killers[i] = MOVE_NONE;
671 // id_loop() is the main iterative deepening loop. It calls root_search
672 // repeatedly with increasing depth until the allocated thinking time has
673 // been consumed, the user stops the search, or the maximum search depth is
676 Value id_loop(const Position& pos, Move searchMoves[]) {
679 SearchStack ss[PLY_MAX_PLUS_2];
681 // searchMoves are verified, copied, scored and sorted
682 RootMoveList rml(p, searchMoves);
684 // Print RootMoveList c'tor startup scoring to the standard output,
685 // so that we print information also for iteration 1.
686 std::cout << "info depth " << 1 << "\ninfo depth " << 1
687 << " score " << value_to_string(rml.get_move_score(0))
688 << " time " << current_search_time()
689 << " nodes " << nodes_searched()
691 << " pv " << rml.get_move(0) << "\n";
697 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
700 // Is one move significantly better than others after initial scoring ?
701 Move EasyMove = MOVE_NONE;
702 if ( rml.move_count() == 1
703 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
704 EasyMove = rml.get_move(0);
706 // Iterative deepening loop
707 while (Iteration < PLY_MAX)
709 // Initialize iteration
712 BestMoveChangesByIteration[Iteration] = 0;
716 std::cout << "info depth " << Iteration << std::endl;
718 // Calculate dynamic search window based on previous iterations
721 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
723 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
724 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
726 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
728 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
729 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
733 alpha = - VALUE_INFINITE;
734 beta = VALUE_INFINITE;
737 // Search to the current depth
738 Value value = root_search(p, ss, rml, alpha, beta);
740 // Write PV to transposition table, in case the relevant entries have
741 // been overwritten during the search.
742 TT.insert_pv(p, ss[0].pv);
745 break; // Value cannot be trusted. Break out immediately!
747 //Save info about search result
748 Value speculatedValue;
751 Value delta = value - IterationInfo[Iteration - 1].value;
758 speculatedValue = value + delta;
759 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
761 else if (value <= alpha)
763 assert(value == alpha);
767 speculatedValue = value + delta;
768 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
770 speculatedValue = value;
772 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
773 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
775 // Erase the easy move if it differs from the new best move
776 if (ss[0].pv[0] != EasyMove)
777 EasyMove = MOVE_NONE;
784 bool stopSearch = false;
786 // Stop search early if there is only a single legal move
787 if (Iteration >= 6 && rml.move_count() == 1)
790 // Stop search early when the last two iterations returned a mate score
792 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
793 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
796 // Stop search early if one move seems to be much better than the rest
797 int64_t nodes = nodes_searched();
801 && EasyMove == ss[0].pv[0]
802 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
803 && current_search_time() > MaxSearchTime / 16)
804 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
805 && current_search_time() > MaxSearchTime / 32)))
808 // Add some extra time if the best move has changed during the last two iterations
809 if (Iteration > 5 && Iteration <= 50)
810 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
811 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
813 // Stop search if most of MaxSearchTime is consumed at the end of the
814 // iteration. We probably don't have enough time to search the first
815 // move at the next iteration anyway.
816 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
824 StopOnPonderhit = true;
828 if (MaxDepth && Iteration >= MaxDepth)
834 // If we are pondering, we shouldn't print the best move before we
837 wait_for_stop_or_ponderhit();
839 // Print final search statistics
840 std::cout << "info nodes " << nodes_searched()
842 << " time " << current_search_time()
843 << " hashfull " << TT.full() << std::endl;
845 // Print the best move and the ponder move to the standard output
846 if (ss[0].pv[0] == MOVE_NONE)
848 ss[0].pv[0] = rml.get_move(0);
849 ss[0].pv[1] = MOVE_NONE;
851 std::cout << "bestmove " << ss[0].pv[0];
852 if (ss[0].pv[1] != MOVE_NONE)
853 std::cout << " ponder " << ss[0].pv[1];
855 std::cout << std::endl;
860 dbg_print_mean(LogFile);
862 if (dbg_show_hit_rate)
863 dbg_print_hit_rate(LogFile);
866 LogFile << "Nodes: " << nodes_searched() << std::endl
867 << "Nodes/second: " << nps() << std::endl
868 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
870 p.do_move(ss[0].pv[0], st);
871 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
872 << std::endl << std::endl;
874 return rml.get_move_score(0);
878 // root_search() is the function which searches the root node. It is
879 // similar to search_pv except that it uses a different move ordering
880 // scheme (perhaps we should try to use this at internal PV nodes, too?)
881 // and prints some information to the standard output.
883 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
885 Value oldAlpha = alpha;
889 // Loop through all the moves in the root move list
890 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
894 // We failed high, invalidate and skip next moves, leave node-counters
895 // and beta-counters as they are and quickly return, we will try to do
896 // a research at the next iteration with a bigger aspiration window.
897 rml.set_move_score(i, -VALUE_INFINITE);
905 RootMoveNumber = i + 1;
908 // Remember the node count before the move is searched. The node counts
909 // are used to sort the root moves at the next iteration.
910 nodes = nodes_searched();
912 // Reset beta cut-off counters
915 // Pick the next root move, and print the move and the move number to
916 // the standard output.
917 move = ss[0].currentMove = rml.get_move(i);
918 if (current_search_time() >= 1000)
919 std::cout << "info currmove " << move
920 << " currmovenumber " << i + 1 << std::endl;
922 // Decide search depth for this move
923 bool moveIsCheck = pos.move_is_check(move);
924 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
926 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
927 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
929 // Make the move, and search it
930 pos.do_move(move, st, ci, moveIsCheck);
934 // Aspiration window is disabled in multi-pv case
936 alpha = -VALUE_INFINITE;
938 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
939 // If the value has dropped a lot compared to the last iteration,
940 // set the boolean variable Problem to true. This variable is used
941 // for time managment: When Problem is true, we try to complete the
942 // current iteration before playing a move.
943 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
945 if (Problem && StopOnPonderhit)
946 StopOnPonderhit = false;
950 if ( newDepth >= 3*OnePly
951 && i >= MultiPV + LMRPVMoves
953 && !captureOrPromotion
954 && !move_is_castle(move))
956 ss[0].reduction = OnePly;
957 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
959 value = alpha + 1; // Just to trigger next condition
963 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
966 // Fail high! Set the boolean variable FailHigh to true, and
967 // re-search the move with a big window. The variable FailHigh is
968 // used for time managment: We try to avoid aborting the search
969 // prematurely during a fail high research.
971 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
978 // Finished searching the move. If AbortSearch is true, the search
979 // was aborted because the user interrupted the search or because we
980 // ran out of time. In this case, the return value of the search cannot
981 // be trusted, and we break out of the loop without updating the best
986 // Remember the node count for this move. The node counts are used to
987 // sort the root moves at the next iteration.
988 rml.set_move_nodes(i, nodes_searched() - nodes);
990 // Remember the beta-cutoff statistics
992 BetaCounter.read(pos.side_to_move(), our, their);
993 rml.set_beta_counters(i, our, their);
995 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
997 if (value <= alpha && i >= MultiPV)
998 rml.set_move_score(i, -VALUE_INFINITE);
1001 // PV move or new best move!
1004 rml.set_move_score(i, value);
1006 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1007 rml.set_move_pv(i, ss[0].pv);
1011 // We record how often the best move has been changed in each
1012 // iteration. This information is used for time managment: When
1013 // the best move changes frequently, we allocate some more time.
1015 BestMoveChangesByIteration[Iteration]++;
1017 // Print search information to the standard output
1018 std::cout << "info depth " << Iteration
1019 << " score " << value_to_string(value)
1020 << ((value >= beta)?
1021 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
1022 << " time " << current_search_time()
1023 << " nodes " << nodes_searched()
1027 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1028 std::cout << ss[0].pv[j] << " ";
1030 std::cout << std::endl;
1033 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value,
1034 ((value >= beta)? VALUE_TYPE_LOWER
1035 : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)),
1042 // Reset the global variable Problem to false if the value isn't too
1043 // far below the final value from the last iteration.
1044 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1049 rml.sort_multipv(i);
1050 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1053 std::cout << "info multipv " << j + 1
1054 << " score " << value_to_string(rml.get_move_score(j))
1055 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1056 << " time " << current_search_time()
1057 << " nodes " << nodes_searched()
1061 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1062 std::cout << rml.get_move_pv(j, k) << " ";
1064 std::cout << std::endl;
1066 alpha = rml.get_move_score(Min(i, MultiPV-1));
1068 } // New best move case
1070 assert(alpha >= oldAlpha);
1072 FailLow = (alpha == oldAlpha);
1078 // search_pv() is the main search function for PV nodes.
1080 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1081 Depth depth, int ply, int threadID) {
1083 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1084 assert(beta > alpha && beta <= VALUE_INFINITE);
1085 assert(ply >= 0 && ply < PLY_MAX);
1086 assert(threadID >= 0 && threadID < ActiveThreads);
1088 Move movesSearched[256];
1093 Depth ext, newDepth;
1094 Value oldAlpha, value;
1095 bool isCheck, mateThreat, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1097 Value bestValue = -VALUE_INFINITE;
1100 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1102 // Initialize, and make an early exit in case of an aborted search,
1103 // an instant draw, maximum ply reached, etc.
1104 init_node(ss, ply, threadID);
1106 // After init_node() that calls poll()
1107 if (AbortSearch || thread_should_stop(threadID))
1113 if (ply >= PLY_MAX - 1)
1114 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1116 // Mate distance pruning
1118 alpha = Max(value_mated_in(ply), alpha);
1119 beta = Min(value_mate_in(ply+1), beta);
1123 // Transposition table lookup. At PV nodes, we don't use the TT for
1124 // pruning, but only for move ordering.
1125 tte = TT.retrieve(pos.get_key());
1126 ttMove = (tte ? tte->move() : MOVE_NONE);
1128 // Go with internal iterative deepening if we don't have a TT move
1129 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1131 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1132 ttMove = ss[ply].pv[ply];
1135 // Initialize a MovePicker object for the current position, and prepare
1136 // to search all moves
1137 isCheck = pos.is_check();
1138 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1140 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1142 // Loop through all legal moves until no moves remain or a beta cutoff
1144 while ( alpha < beta
1145 && (move = mp.get_next_move()) != MOVE_NONE
1146 && !thread_should_stop(threadID))
1148 assert(move_is_ok(move));
1150 singleReply = (isCheck && mp.number_of_evasions() == 1);
1151 moveIsCheck = pos.move_is_check(move, ci);
1152 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1154 // Decide the new search depth
1155 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1157 // We want to extend the TT move if it is much better then remaining ones.
1158 // To verify this we do a reduced search on all the other moves but the ttMove,
1159 // if result is lower then TT value minus a margin then we assume ttMove is the
1160 // only one playable. It is a kind of relaxed single reply extension.
1161 if ( depth >= 8 * OnePly
1164 && is_lower_bound(tte->type())
1165 && tte->depth() >= depth - 3 * OnePly)
1167 Value ttValue = value_from_tt(tte->value(), ply);
1169 if (abs(ttValue) < VALUE_KNOWN_WIN)
1171 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, ttMove);
1173 // If search result is well below the foreseen score of the ttMove then we
1174 // assume ttMove is the only one realistically playable and we extend it.
1175 if (excValue < ttValue - SingleReplyMargin)
1180 newDepth = depth - OnePly + ext;
1182 // Update current move
1183 movesSearched[moveCount++] = ss[ply].currentMove = move;
1185 // Make and search the move
1186 pos.do_move(move, st, ci, moveIsCheck);
1188 if (moveCount == 1) // The first move in list is the PV
1189 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1192 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1193 // if the move fails high will be re-searched at full depth.
1194 if ( depth >= 3*OnePly
1195 && moveCount >= LMRPVMoves
1197 && !captureOrPromotion
1198 && !move_is_castle(move)
1199 && !move_is_killer(move, ss[ply]))
1201 ss[ply].reduction = OnePly;
1202 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1205 value = alpha + 1; // Just to trigger next condition
1207 if (value > alpha) // Go with full depth non-pv search
1209 ss[ply].reduction = Depth(0);
1210 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1211 if (value > alpha && value < beta)
1213 // When the search fails high at ply 1 while searching the first
1214 // move at the root, set the flag failHighPly1. This is used for
1215 // time managment: We don't want to stop the search early in
1216 // such cases, because resolving the fail high at ply 1 could
1217 // result in a big drop in score at the root.
1218 if (ply == 1 && RootMoveNumber == 1)
1219 Threads[threadID].failHighPly1 = true;
1221 // A fail high occurred. Re-search at full window (pv search)
1222 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1223 Threads[threadID].failHighPly1 = false;
1227 pos.undo_move(move);
1229 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1232 if (value > bestValue)
1239 if (value == value_mate_in(ply + 1))
1240 ss[ply].mateKiller = move;
1242 // If we are at ply 1, and we are searching the first root move at
1243 // ply 0, set the 'Problem' variable if the score has dropped a lot
1244 // (from the computer's point of view) since the previous iteration.
1247 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1252 if ( ActiveThreads > 1
1254 && depth >= MinimumSplitDepth
1256 && idle_thread_exists(threadID)
1258 && !thread_should_stop(threadID)
1259 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE,
1260 depth, &moveCount, &mp, threadID, true))
1264 // All legal moves have been searched. A special case: If there were
1265 // no legal moves, it must be mate or stalemate.
1267 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1269 // If the search is not aborted, update the transposition table,
1270 // history counters, and killer moves.
1271 if (AbortSearch || thread_should_stop(threadID))
1274 if (bestValue <= oldAlpha)
1275 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1277 else if (bestValue >= beta)
1279 BetaCounter.add(pos.side_to_move(), depth, threadID);
1280 move = ss[ply].pv[ply];
1281 if (!pos.move_is_capture_or_promotion(move))
1283 update_history(pos, move, depth, movesSearched, moveCount);
1284 update_killers(move, ss[ply]);
1286 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1289 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1295 // search() is the search function for zero-width nodes.
1297 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1298 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1300 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1301 assert(ply >= 0 && ply < PLY_MAX);
1302 assert(threadID >= 0 && threadID < ActiveThreads);
1304 Move movesSearched[256];
1309 Depth ext, newDepth;
1310 Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1311 bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1312 bool mateThreat = false;
1314 Value bestValue = -VALUE_INFINITE;
1317 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1319 // Initialize, and make an early exit in case of an aborted search,
1320 // an instant draw, maximum ply reached, etc.
1321 init_node(ss, ply, threadID);
1323 // After init_node() that calls poll()
1324 if (AbortSearch || thread_should_stop(threadID))
1330 if (ply >= PLY_MAX - 1)
1331 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1333 // Mate distance pruning
1334 if (value_mated_in(ply) >= beta)
1337 if (value_mate_in(ply + 1) < beta)
1340 // We don't want the score of a partial search to overwrite a previous full search
1341 // TT value, so we use a different position key in case of an excluded move exsists.
1342 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1344 // Transposition table lookup
1345 tte = TT.retrieve(posKey);
1346 ttMove = (tte ? tte->move() : MOVE_NONE);
1348 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1350 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1351 return value_from_tt(tte->value(), ply);
1354 approximateEval = quick_evaluate(pos);
1355 isCheck = pos.is_check();
1361 && !value_is_mate(beta)
1362 && ok_to_do_nullmove(pos)
1363 && approximateEval >= beta - NullMoveMargin)
1365 ss[ply].currentMove = MOVE_NULL;
1367 pos.do_null_move(st);
1369 // Null move dynamic reduction based on depth
1370 int R = (depth >= 5 * OnePly ? 4 : 3);
1372 // Null move dynamic reduction based on value
1373 if (approximateEval - beta > PawnValueMidgame)
1376 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1378 pos.undo_null_move();
1380 if (nullValue >= beta)
1382 if (depth < 6 * OnePly)
1385 // Do zugzwang verification search
1386 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1390 // The null move failed low, which means that we may be faced with
1391 // some kind of threat. If the previous move was reduced, check if
1392 // the move that refuted the null move was somehow connected to the
1393 // move which was reduced. If a connection is found, return a fail
1394 // low score (which will cause the reduced move to fail high in the
1395 // parent node, which will trigger a re-search with full depth).
1396 if (nullValue == value_mated_in(ply + 2))
1399 ss[ply].threatMove = ss[ply + 1].currentMove;
1400 if ( depth < ThreatDepth
1401 && ss[ply - 1].reduction
1402 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1406 // Null move search not allowed, try razoring
1407 else if ( !value_is_mate(beta)
1408 && depth < RazorDepth
1409 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1410 && ss[ply - 1].currentMove != MOVE_NULL
1411 && ttMove == MOVE_NONE
1412 && !pos.has_pawn_on_7th(pos.side_to_move()))
1414 Value rbeta = beta - RazorMargins[int(depth) - 2];
1415 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1420 // Go with internal iterative deepening if we don't have a TT move
1421 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1422 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1424 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1425 ttMove = ss[ply].pv[ply];
1428 // Initialize a MovePicker object for the current position, and prepare
1429 // to search all moves.
1430 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1432 futilityValue = VALUE_NONE;
1433 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1435 // Avoid calling evaluate() if we already have the score in TT
1436 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1437 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1439 // Move count pruning limit
1440 const int MCLimit = 3 + (1 << (3*int(depth)/8));
1442 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1443 while ( bestValue < beta
1444 && (move = mp.get_next_move()) != MOVE_NONE
1445 && !thread_should_stop(threadID))
1447 assert(move_is_ok(move));
1449 if (move == excludedMove)
1452 singleReply = (isCheck && mp.number_of_evasions() == 1);
1453 moveIsCheck = pos.move_is_check(move, ci);
1454 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1456 // Decide the new search depth
1457 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1459 // We want to extend the TT move if it is much better then remaining ones.
1460 // To verify this we do a reduced search on all the other moves but the ttMove,
1461 // if result is lower then TT value minus a margin then we assume ttMove is the
1462 // only one playable. It is a kind of relaxed single reply extension.
1463 if ( depth >= 8 * OnePly
1464 && !excludedMove // do not allow recursive single-reply search
1467 && is_lower_bound(tte->type())
1468 && tte->depth() >= depth - 3 * OnePly)
1470 Value ttValue = value_from_tt(tte->value(), ply);
1472 if (abs(ttValue) < VALUE_KNOWN_WIN)
1474 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, ttMove);
1476 // If search result is well below the foreseen score of the ttMove then we
1477 // assume ttMove is the only one realistically playable and we extend it.
1478 if (excValue < ttValue - SingleReplyMargin)
1483 newDepth = depth - OnePly + ext;
1485 // Update current move
1486 movesSearched[moveCount++] = ss[ply].currentMove = move;
1489 if ( useFutilityPruning
1491 && !captureOrPromotion
1494 // History pruning. See ok_to_prune() definition
1495 if ( moveCount >= MCLimit
1496 && ok_to_prune(pos, move, ss[ply].threatMove, depth)
1497 && bestValue > value_mated_in(PLY_MAX))
1500 // Value based pruning
1501 if (approximateEval < beta)
1503 if (futilityValue == VALUE_NONE)
1504 futilityValue = evaluate(pos, ei, threadID)
1505 + 64*(2+bitScanReverse32(int(depth) * int(depth)));
1507 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1509 if (futilityValueScaled < beta)
1511 if (futilityValueScaled > bestValue)
1512 bestValue = futilityValueScaled;
1518 // Make and search the move
1519 pos.do_move(move, st, ci, moveIsCheck);
1521 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1522 // if the move fails high will be re-searched at full depth.
1523 if ( depth >= 3*OnePly
1524 && moveCount >= LMRNonPVMoves
1526 && !captureOrPromotion
1527 && !move_is_castle(move)
1528 && !move_is_killer(move, ss[ply]))
1530 ss[ply].reduction = OnePly;
1531 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1534 value = beta; // Just to trigger next condition
1536 if (value >= beta) // Go with full depth non-pv search
1538 ss[ply].reduction = Depth(0);
1539 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1541 pos.undo_move(move);
1543 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1546 if (value > bestValue)
1552 if (value == value_mate_in(ply + 1))
1553 ss[ply].mateKiller = move;
1557 if ( ActiveThreads > 1
1559 && depth >= MinimumSplitDepth
1561 && idle_thread_exists(threadID)
1563 && !thread_should_stop(threadID)
1564 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval,
1565 depth, &moveCount, &mp, threadID, false))
1569 // All legal moves have been searched. A special case: If there were
1570 // no legal moves, it must be mate or stalemate.
1572 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1574 // If the search is not aborted, update the transposition table,
1575 // history counters, and killer moves.
1576 if (AbortSearch || thread_should_stop(threadID))
1579 if (bestValue < beta)
1580 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1583 BetaCounter.add(pos.side_to_move(), depth, threadID);
1584 move = ss[ply].pv[ply];
1585 if (!pos.move_is_capture_or_promotion(move))
1587 update_history(pos, move, depth, movesSearched, moveCount);
1588 update_killers(move, ss[ply]);
1590 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1593 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1599 // qsearch() is the quiescence search function, which is called by the main
1600 // search function when the remaining depth is zero (or, to be more precise,
1601 // less than OnePly).
1603 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1604 Depth depth, int ply, int threadID) {
1606 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1607 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1609 assert(ply >= 0 && ply < PLY_MAX);
1610 assert(threadID >= 0 && threadID < ActiveThreads);
1615 Value staticValue, bestValue, value, futilityValue;
1616 bool isCheck, enoughMaterial, moveIsCheck;
1617 const TTEntry* tte = NULL;
1619 bool pvNode = (beta - alpha != 1);
1621 // Initialize, and make an early exit in case of an aborted search,
1622 // an instant draw, maximum ply reached, etc.
1623 init_node(ss, ply, threadID);
1625 // After init_node() that calls poll()
1626 if (AbortSearch || thread_should_stop(threadID))
1632 // Transposition table lookup, only when not in PV
1635 tte = TT.retrieve(pos.get_key());
1636 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1638 assert(tte->type() != VALUE_TYPE_EVAL);
1640 return value_from_tt(tte->value(), ply);
1643 ttMove = (tte ? tte->move() : MOVE_NONE);
1645 // Evaluate the position statically
1646 isCheck = pos.is_check();
1647 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1650 staticValue = -VALUE_INFINITE;
1652 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1654 // Use the cached evaluation score if possible
1655 assert(ei.futilityMargin == Value(0));
1657 staticValue = tte->value();
1660 staticValue = evaluate(pos, ei, threadID);
1662 if (ply >= PLY_MAX - 1)
1663 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1665 // Initialize "stand pat score", and return it immediately if it is
1667 bestValue = staticValue;
1669 if (bestValue >= beta)
1671 // Store the score to avoid a future costly evaluation() call
1672 if (!isCheck && !tte && ei.futilityMargin == 0)
1673 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1678 if (bestValue > alpha)
1681 // Initialize a MovePicker object for the current position, and prepare
1682 // to search the moves. Because the depth is <= 0 here, only captures,
1683 // queen promotions and checks (only if depth == 0) will be generated.
1684 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1686 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1688 // Loop through the moves until no moves remain or a beta cutoff
1690 while ( alpha < beta
1691 && (move = mp.get_next_move()) != MOVE_NONE)
1693 assert(move_is_ok(move));
1696 ss[ply].currentMove = move;
1698 moveIsCheck = pos.move_is_check(move, ci);
1706 && !move_is_promotion(move)
1707 && !pos.move_is_passed_pawn_push(move))
1709 futilityValue = staticValue
1710 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1711 pos.endgame_value_of_piece_on(move_to(move)))
1712 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1714 + ei.futilityMargin;
1716 if (futilityValue < alpha)
1718 if (futilityValue > bestValue)
1719 bestValue = futilityValue;
1724 // Don't search captures and checks with negative SEE values
1727 && !move_is_promotion(move)
1728 && pos.see_sign(move) < 0)
1731 // Make and search the move
1732 pos.do_move(move, st, ci, moveIsCheck);
1733 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1734 pos.undo_move(move);
1736 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1739 if (value > bestValue)
1750 // All legal moves have been searched. A special case: If we're in check
1751 // and no legal moves were found, it is checkmate.
1752 if (!moveCount && pos.is_check()) // Mate!
1753 return value_mated_in(ply);
1755 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1757 // Update transposition table
1758 move = ss[ply].pv[ply];
1761 // If bestValue isn't changed it means it is still the static evaluation of
1762 // the node, so keep this info to avoid a future costly evaluation() call.
1763 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1764 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1766 if (bestValue < beta)
1767 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1769 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1772 // Update killers only for good check moves
1773 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1774 update_killers(move, ss[ply]);
1780 // sp_search() is used to search from a split point. This function is called
1781 // by each thread working at the split point. It is similar to the normal
1782 // search() function, but simpler. Because we have already probed the hash
1783 // table, done a null move search, and searched the first move before
1784 // splitting, we don't have to repeat all this work in sp_search(). We
1785 // also don't need to store anything to the hash table here: This is taken
1786 // care of after we return from the split point.
1788 void sp_search(SplitPoint* sp, int threadID) {
1790 assert(threadID >= 0 && threadID < ActiveThreads);
1791 assert(ActiveThreads > 1);
1793 Position pos = Position(sp->pos);
1795 SearchStack* ss = sp->sstack[threadID];
1798 bool isCheck = pos.is_check();
1799 bool useFutilityPruning = sp->depth < SelectiveDepth
1802 while ( sp->bestValue < sp->beta
1803 && !thread_should_stop(threadID)
1804 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1806 assert(move_is_ok(move));
1808 bool moveIsCheck = pos.move_is_check(move, ci);
1809 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1811 lock_grab(&(sp->lock));
1812 int moveCount = ++sp->moves;
1813 lock_release(&(sp->lock));
1815 ss[sp->ply].currentMove = move;
1817 // Decide the new search depth.
1819 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1820 Depth newDepth = sp->depth - OnePly + ext;
1823 if ( useFutilityPruning
1825 && !captureOrPromotion)
1827 // History pruning. See ok_to_prune() definition
1828 if ( moveCount >= 2 + int(sp->depth)
1829 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)
1830 && sp->bestValue > value_mated_in(PLY_MAX))
1833 // Value based pruning
1834 if (sp->approximateEval < sp->beta)
1836 if (sp->futilityValue == VALUE_NONE)
1839 sp->futilityValue = evaluate(pos, ei, threadID)
1840 + FutilityMargins[int(sp->depth) - 2];
1843 if (sp->futilityValue < sp->beta)
1845 if (sp->futilityValue > sp->bestValue) // Less then 1% of cases
1847 lock_grab(&(sp->lock));
1848 if (sp->futilityValue > sp->bestValue)
1849 sp->bestValue = sp->futilityValue;
1850 lock_release(&(sp->lock));
1857 // Make and search the move.
1859 pos.do_move(move, st, ci, moveIsCheck);
1861 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1862 // if the move fails high will be re-searched at full depth.
1864 && moveCount >= LMRNonPVMoves
1865 && !captureOrPromotion
1866 && !move_is_castle(move)
1867 && !move_is_killer(move, ss[sp->ply]))
1869 ss[sp->ply].reduction = OnePly;
1870 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1873 value = sp->beta; // Just to trigger next condition
1875 if (value >= sp->beta) // Go with full depth non-pv search
1877 ss[sp->ply].reduction = Depth(0);
1878 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1880 pos.undo_move(move);
1882 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1884 if (thread_should_stop(threadID))
1888 if (value > sp->bestValue) // Less then 2% of cases
1890 lock_grab(&(sp->lock));
1891 if (value > sp->bestValue && !thread_should_stop(threadID))
1893 sp->bestValue = value;
1894 if (sp->bestValue >= sp->beta)
1896 sp_update_pv(sp->parentSstack, ss, sp->ply);
1897 for (int i = 0; i < ActiveThreads; i++)
1898 if (i != threadID && (i == sp->master || sp->slaves[i]))
1899 Threads[i].stop = true;
1901 sp->finished = true;
1904 lock_release(&(sp->lock));
1908 lock_grab(&(sp->lock));
1910 // If this is the master thread and we have been asked to stop because of
1911 // a beta cutoff higher up in the tree, stop all slave threads.
1912 if (sp->master == threadID && thread_should_stop(threadID))
1913 for (int i = 0; i < ActiveThreads; i++)
1915 Threads[i].stop = true;
1918 sp->slaves[threadID] = 0;
1920 lock_release(&(sp->lock));
1924 // sp_search_pv() is used to search from a PV split point. This function
1925 // is called by each thread working at the split point. It is similar to
1926 // the normal search_pv() function, but simpler. Because we have already
1927 // probed the hash table and searched the first move before splitting, we
1928 // don't have to repeat all this work in sp_search_pv(). We also don't
1929 // need to store anything to the hash table here: This is taken care of
1930 // after we return from the split point.
1932 void sp_search_pv(SplitPoint* sp, int threadID) {
1934 assert(threadID >= 0 && threadID < ActiveThreads);
1935 assert(ActiveThreads > 1);
1937 Position pos = Position(sp->pos);
1939 SearchStack* ss = sp->sstack[threadID];
1943 while ( sp->alpha < sp->beta
1944 && !thread_should_stop(threadID)
1945 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1947 bool moveIsCheck = pos.move_is_check(move, ci);
1948 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1950 assert(move_is_ok(move));
1952 lock_grab(&(sp->lock));
1953 int moveCount = ++sp->moves;
1954 lock_release(&(sp->lock));
1956 ss[sp->ply].currentMove = move;
1958 // Decide the new search depth.
1960 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1961 Depth newDepth = sp->depth - OnePly + ext;
1963 // Make and search the move.
1965 pos.do_move(move, st, ci, moveIsCheck);
1967 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1968 // if the move fails high will be re-searched at full depth.
1970 && moveCount >= LMRPVMoves
1971 && !captureOrPromotion
1972 && !move_is_castle(move)
1973 && !move_is_killer(move, ss[sp->ply]))
1975 ss[sp->ply].reduction = OnePly;
1976 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1979 value = sp->alpha + 1; // Just to trigger next condition
1981 if (value > sp->alpha) // Go with full depth non-pv search
1983 ss[sp->ply].reduction = Depth(0);
1984 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1986 if (value > sp->alpha && value < sp->beta)
1988 // When the search fails high at ply 1 while searching the first
1989 // move at the root, set the flag failHighPly1. This is used for
1990 // time managment: We don't want to stop the search early in
1991 // such cases, because resolving the fail high at ply 1 could
1992 // result in a big drop in score at the root.
1993 if (sp->ply == 1 && RootMoveNumber == 1)
1994 Threads[threadID].failHighPly1 = true;
1996 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1997 Threads[threadID].failHighPly1 = false;
2000 pos.undo_move(move);
2002 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2004 if (thread_should_stop(threadID))
2008 lock_grab(&(sp->lock));
2009 if (value > sp->bestValue && !thread_should_stop(threadID))
2011 sp->bestValue = value;
2012 if (value > sp->alpha)
2015 sp_update_pv(sp->parentSstack, ss, sp->ply);
2016 if (value == value_mate_in(sp->ply + 1))
2017 ss[sp->ply].mateKiller = move;
2019 if (value >= sp->beta)
2021 for (int i = 0; i < ActiveThreads; i++)
2022 if (i != threadID && (i == sp->master || sp->slaves[i]))
2023 Threads[i].stop = true;
2025 sp->finished = true;
2028 // If we are at ply 1, and we are searching the first root move at
2029 // ply 0, set the 'Problem' variable if the score has dropped a lot
2030 // (from the computer's point of view) since the previous iteration.
2033 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2036 lock_release(&(sp->lock));
2039 lock_grab(&(sp->lock));
2041 // If this is the master thread and we have been asked to stop because of
2042 // a beta cutoff higher up in the tree, stop all slave threads.
2043 if (sp->master == threadID && thread_should_stop(threadID))
2044 for (int i = 0; i < ActiveThreads; i++)
2046 Threads[i].stop = true;
2049 sp->slaves[threadID] = 0;
2051 lock_release(&(sp->lock));
2054 /// The BetaCounterType class
2056 BetaCounterType::BetaCounterType() { clear(); }
2058 void BetaCounterType::clear() {
2060 for (int i = 0; i < THREAD_MAX; i++)
2061 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2064 void BetaCounterType::add(Color us, Depth d, int threadID) {
2066 // Weighted count based on depth
2067 Threads[threadID].betaCutOffs[us] += unsigned(d);
2070 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2073 for (int i = 0; i < THREAD_MAX; i++)
2075 our += Threads[i].betaCutOffs[us];
2076 their += Threads[i].betaCutOffs[opposite_color(us)];
2081 /// The RootMove class
2085 RootMove::RootMove() {
2086 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
2089 // RootMove::operator<() is the comparison function used when
2090 // sorting the moves. A move m1 is considered to be better
2091 // than a move m2 if it has a higher score, or if the moves
2092 // have equal score but m1 has the higher node count.
2094 bool RootMove::operator<(const RootMove& m) {
2096 if (score != m.score)
2097 return (score < m.score);
2099 return theirBeta <= m.theirBeta;
2102 /// The RootMoveList class
2106 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2108 MoveStack mlist[MaxRootMoves];
2109 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2111 // Generate all legal moves
2112 MoveStack* last = generate_moves(pos, mlist);
2114 // Add each move to the moves[] array
2115 for (MoveStack* cur = mlist; cur != last; cur++)
2117 bool includeMove = includeAllMoves;
2119 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2120 includeMove = (searchMoves[k] == cur->move);
2125 // Find a quick score for the move
2127 SearchStack ss[PLY_MAX_PLUS_2];
2130 moves[count].move = cur->move;
2131 pos.do_move(moves[count].move, st);
2132 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2133 pos.undo_move(moves[count].move);
2134 moves[count].pv[0] = moves[count].move;
2135 moves[count].pv[1] = MOVE_NONE;
2142 // Simple accessor methods for the RootMoveList class
2144 inline Move RootMoveList::get_move(int moveNum) const {
2145 return moves[moveNum].move;
2148 inline Value RootMoveList::get_move_score(int moveNum) const {
2149 return moves[moveNum].score;
2152 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2153 moves[moveNum].score = score;
2156 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2157 moves[moveNum].nodes = nodes;
2158 moves[moveNum].cumulativeNodes += nodes;
2161 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2162 moves[moveNum].ourBeta = our;
2163 moves[moveNum].theirBeta = their;
2166 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2168 for(j = 0; pv[j] != MOVE_NONE; j++)
2169 moves[moveNum].pv[j] = pv[j];
2170 moves[moveNum].pv[j] = MOVE_NONE;
2173 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2174 return moves[moveNum].pv[i];
2177 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2178 return moves[moveNum].cumulativeNodes;
2181 inline int RootMoveList::move_count() const {
2186 // RootMoveList::sort() sorts the root move list at the beginning of a new
2189 inline void RootMoveList::sort() {
2191 sort_multipv(count - 1); // all items
2195 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2196 // list by their scores and depths. It is used to order the different PVs
2197 // correctly in MultiPV mode.
2199 void RootMoveList::sort_multipv(int n) {
2201 for (int i = 1; i <= n; i++)
2203 RootMove rm = moves[i];
2205 for (j = i; j > 0 && moves[j-1] < rm; j--)
2206 moves[j] = moves[j-1];
2212 // init_node() is called at the beginning of all the search functions
2213 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2214 // stack object corresponding to the current node. Once every
2215 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2216 // for user input and checks whether it is time to stop the search.
2218 void init_node(SearchStack ss[], int ply, int threadID) {
2220 assert(ply >= 0 && ply < PLY_MAX);
2221 assert(threadID >= 0 && threadID < ActiveThreads);
2223 Threads[threadID].nodes++;
2228 if (NodesSincePoll >= NodesBetweenPolls)
2235 ss[ply+2].initKillers();
2237 if (Threads[threadID].printCurrentLine)
2238 print_current_line(ss, ply, threadID);
2242 // update_pv() is called whenever a search returns a value > alpha. It
2243 // updates the PV in the SearchStack object corresponding to the current
2246 void update_pv(SearchStack ss[], int ply) {
2247 assert(ply >= 0 && ply < PLY_MAX);
2249 ss[ply].pv[ply] = ss[ply].currentMove;
2251 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2252 ss[ply].pv[p] = ss[ply+1].pv[p];
2253 ss[ply].pv[p] = MOVE_NONE;
2257 // sp_update_pv() is a variant of update_pv for use at split points. The
2258 // difference between the two functions is that sp_update_pv also updates
2259 // the PV at the parent node.
2261 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2262 assert(ply >= 0 && ply < PLY_MAX);
2264 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2266 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2267 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2268 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2272 // connected_moves() tests whether two moves are 'connected' in the sense
2273 // that the first move somehow made the second move possible (for instance
2274 // if the moving piece is the same in both moves). The first move is
2275 // assumed to be the move that was made to reach the current position, while
2276 // the second move is assumed to be a move from the current position.
2278 bool connected_moves(const Position& pos, Move m1, Move m2) {
2280 Square f1, t1, f2, t2;
2283 assert(move_is_ok(m1));
2284 assert(move_is_ok(m2));
2286 if (m2 == MOVE_NONE)
2289 // Case 1: The moving piece is the same in both moves
2295 // Case 2: The destination square for m2 was vacated by m1
2301 // Case 3: Moving through the vacated square
2302 if ( piece_is_slider(pos.piece_on(f2))
2303 && bit_is_set(squares_between(f2, t2), f1))
2306 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2307 p = pos.piece_on(t1);
2308 if (bit_is_set(pos.attacks_from(p, t1), t2))
2311 // Case 5: Discovered check, checking piece is the piece moved in m1
2312 if ( piece_is_slider(p)
2313 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2314 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2316 Bitboard occ = pos.occupied_squares();
2317 Color us = pos.side_to_move();
2318 Square ksq = pos.king_square(us);
2319 clear_bit(&occ, f2);
2320 if (type_of_piece(p) == BISHOP)
2322 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2325 else if (type_of_piece(p) == ROOK)
2327 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2332 assert(type_of_piece(p) == QUEEN);
2333 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2341 // value_is_mate() checks if the given value is a mate one
2342 // eventually compensated for the ply.
2344 bool value_is_mate(Value value) {
2346 assert(abs(value) <= VALUE_INFINITE);
2348 return value <= value_mated_in(PLY_MAX)
2349 || value >= value_mate_in(PLY_MAX);
2353 // move_is_killer() checks if the given move is among the
2354 // killer moves of that ply.
2356 bool move_is_killer(Move m, const SearchStack& ss) {
2358 const Move* k = ss.killers;
2359 for (int i = 0; i < KILLER_MAX; i++, k++)
2367 // extension() decides whether a move should be searched with normal depth,
2368 // or with extended depth. Certain classes of moves (checking moves, in
2369 // particular) are searched with bigger depth than ordinary moves and in
2370 // any case are marked as 'dangerous'. Note that also if a move is not
2371 // extended, as example because the corresponding UCI option is set to zero,
2372 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2374 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2375 bool check, bool singleReply, bool mateThreat, bool* dangerous) {
2377 assert(m != MOVE_NONE);
2379 Depth result = Depth(0);
2380 *dangerous = check | singleReply | mateThreat;
2385 result += CheckExtension[pvNode];
2388 result += SingleReplyExtension[pvNode];
2391 result += MateThreatExtension[pvNode];
2394 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2396 Color c = pos.side_to_move();
2397 if (relative_rank(c, move_to(m)) == RANK_7)
2399 result += PawnPushTo7thExtension[pvNode];
2402 if (pos.pawn_is_passed(c, move_to(m)))
2404 result += PassedPawnExtension[pvNode];
2409 if ( captureOrPromotion
2410 && pos.type_of_piece_on(move_to(m)) != PAWN
2411 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2412 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2413 && !move_is_promotion(m)
2416 result += PawnEndgameExtension[pvNode];
2421 && captureOrPromotion
2422 && pos.type_of_piece_on(move_to(m)) != PAWN
2423 && pos.see_sign(m) >= 0)
2429 return Min(result, OnePly);
2433 // ok_to_do_nullmove() looks at the current position and decides whether
2434 // doing a 'null move' should be allowed. In order to avoid zugzwang
2435 // problems, null moves are not allowed when the side to move has very
2436 // little material left. Currently, the test is a bit too simple: Null
2437 // moves are avoided only when the side to move has only pawns left. It's
2438 // probably a good idea to avoid null moves in at least some more
2439 // complicated endgames, e.g. KQ vs KR. FIXME
2441 bool ok_to_do_nullmove(const Position& pos) {
2443 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2447 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2448 // non-tactical moves late in the move list close to the leaves are
2449 // candidates for pruning.
2451 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2453 assert(move_is_ok(m));
2454 assert(threat == MOVE_NONE || move_is_ok(threat));
2455 assert(!pos.move_is_check(m));
2456 assert(!pos.move_is_capture_or_promotion(m));
2457 assert(!pos.move_is_passed_pawn_push(m));
2458 assert(d >= OnePly);
2460 Square mfrom, mto, tfrom, tto;
2462 mfrom = move_from(m);
2464 tfrom = move_from(threat);
2465 tto = move_to(threat);
2467 // Case 1: Castling moves are never pruned
2468 if (move_is_castle(m))
2471 // Case 2: Don't prune moves which move the threatened piece
2472 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2475 // Case 3: If the threatened piece has value less than or equal to the
2476 // value of the threatening piece, don't prune move which defend it.
2477 if ( !PruneDefendingMoves
2478 && threat != MOVE_NONE
2479 && pos.move_is_capture(threat)
2480 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2481 || pos.type_of_piece_on(tfrom) == KING)
2482 && pos.move_attacks_square(m, tto))
2485 // Case 4: Don't prune moves with good history
2486 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2489 // Case 5: If the moving piece in the threatened move is a slider, don't
2490 // prune safe moves which block its ray.
2491 if ( !PruneBlockingMoves
2492 && threat != MOVE_NONE
2493 && piece_is_slider(pos.piece_on(tfrom))
2494 && bit_is_set(squares_between(tfrom, tto), mto)
2495 && pos.see_sign(m) >= 0)
2502 // ok_to_use_TT() returns true if a transposition table score
2503 // can be used at a given point in search.
2505 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2507 Value v = value_from_tt(tte->value(), ply);
2509 return ( tte->depth() >= depth
2510 || v >= Max(value_mate_in(100), beta)
2511 || v < Min(value_mated_in(100), beta))
2513 && ( (is_lower_bound(tte->type()) && v >= beta)
2514 || (is_upper_bound(tte->type()) && v < beta));
2518 // update_history() registers a good move that produced a beta-cutoff
2519 // in history and marks as failures all the other moves of that ply.
2521 void update_history(const Position& pos, Move m, Depth depth,
2522 Move movesSearched[], int moveCount) {
2524 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2526 for (int i = 0; i < moveCount - 1; i++)
2528 assert(m != movesSearched[i]);
2529 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2530 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2535 // update_killers() add a good move that produced a beta-cutoff
2536 // among the killer moves of that ply.
2538 void update_killers(Move m, SearchStack& ss) {
2540 if (m == ss.killers[0])
2543 for (int i = KILLER_MAX - 1; i > 0; i--)
2544 ss.killers[i] = ss.killers[i - 1];
2550 // fail_high_ply_1() checks if some thread is currently resolving a fail
2551 // high at ply 1 at the node below the first root node. This information
2552 // is used for time managment.
2554 bool fail_high_ply_1() {
2556 for(int i = 0; i < ActiveThreads; i++)
2557 if (Threads[i].failHighPly1)
2564 // current_search_time() returns the number of milliseconds which have passed
2565 // since the beginning of the current search.
2567 int current_search_time() {
2568 return get_system_time() - SearchStartTime;
2572 // nps() computes the current nodes/second count.
2575 int t = current_search_time();
2576 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2580 // poll() performs two different functions: It polls for user input, and it
2581 // looks at the time consumed so far and decides if it's time to abort the
2586 static int lastInfoTime;
2587 int t = current_search_time();
2592 // We are line oriented, don't read single chars
2593 std::string command;
2594 if (!std::getline(std::cin, command))
2597 if (command == "quit")
2600 PonderSearch = false;
2604 else if (command == "stop")
2607 PonderSearch = false;
2609 else if (command == "ponderhit")
2612 // Print search information
2616 else if (lastInfoTime > t)
2617 // HACK: Must be a new search where we searched less than
2618 // NodesBetweenPolls nodes during the first second of search.
2621 else if (t - lastInfoTime >= 1000)
2628 if (dbg_show_hit_rate)
2629 dbg_print_hit_rate();
2631 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2632 << " time " << t << " hashfull " << TT.full() << std::endl;
2633 lock_release(&IOLock);
2634 if (ShowCurrentLine)
2635 Threads[0].printCurrentLine = true;
2637 // Should we stop the search?
2641 bool overTime = t > AbsoluteMaxSearchTime
2642 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2643 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2644 && t > 6*(MaxSearchTime + ExtraSearchTime));
2646 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2647 || (ExactMaxTime && t >= ExactMaxTime)
2648 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2653 // ponderhit() is called when the program is pondering (i.e. thinking while
2654 // it's the opponent's turn to move) in order to let the engine know that
2655 // it correctly predicted the opponent's move.
2659 int t = current_search_time();
2660 PonderSearch = false;
2661 if (Iteration >= 3 &&
2662 (!InfiniteSearch && (StopOnPonderhit ||
2663 t > AbsoluteMaxSearchTime ||
2664 (RootMoveNumber == 1 &&
2665 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2666 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2667 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2672 // print_current_line() prints the current line of search for a given
2673 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2675 void print_current_line(SearchStack ss[], int ply, int threadID) {
2677 assert(ply >= 0 && ply < PLY_MAX);
2678 assert(threadID >= 0 && threadID < ActiveThreads);
2680 if (!Threads[threadID].idle)
2683 std::cout << "info currline " << (threadID + 1);
2684 for (int p = 0; p < ply; p++)
2685 std::cout << " " << ss[p].currentMove;
2687 std::cout << std::endl;
2688 lock_release(&IOLock);
2690 Threads[threadID].printCurrentLine = false;
2691 if (threadID + 1 < ActiveThreads)
2692 Threads[threadID + 1].printCurrentLine = true;
2696 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2698 void init_ss_array(SearchStack ss[]) {
2700 for (int i = 0; i < 3; i++)
2703 ss[i].initKillers();
2708 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2709 // while the program is pondering. The point is to work around a wrinkle in
2710 // the UCI protocol: When pondering, the engine is not allowed to give a
2711 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2712 // We simply wait here until one of these commands is sent, and return,
2713 // after which the bestmove and pondermove will be printed (in id_loop()).
2715 void wait_for_stop_or_ponderhit() {
2717 std::string command;
2721 if (!std::getline(std::cin, command))
2724 if (command == "quit")
2729 else if (command == "ponderhit" || command == "stop")
2735 // idle_loop() is where the threads are parked when they have no work to do.
2736 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2737 // object for which the current thread is the master.
2739 void idle_loop(int threadID, SplitPoint* waitSp) {
2740 assert(threadID >= 0 && threadID < THREAD_MAX);
2742 Threads[threadID].running = true;
2745 if(AllThreadsShouldExit && threadID != 0)
2748 // If we are not thinking, wait for a condition to be signaled instead
2749 // of wasting CPU time polling for work:
2750 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2751 #if !defined(_MSC_VER)
2752 pthread_mutex_lock(&WaitLock);
2753 if(Idle || threadID >= ActiveThreads)
2754 pthread_cond_wait(&WaitCond, &WaitLock);
2755 pthread_mutex_unlock(&WaitLock);
2757 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2761 // If this thread has been assigned work, launch a search
2762 if(Threads[threadID].workIsWaiting) {
2763 Threads[threadID].workIsWaiting = false;
2764 if(Threads[threadID].splitPoint->pvNode)
2765 sp_search_pv(Threads[threadID].splitPoint, threadID);
2767 sp_search(Threads[threadID].splitPoint, threadID);
2768 Threads[threadID].idle = true;
2771 // If this thread is the master of a split point and all threads have
2772 // finished their work at this split point, return from the idle loop.
2773 if(waitSp != NULL && waitSp->cpus == 0)
2777 Threads[threadID].running = false;
2781 // init_split_point_stack() is called during program initialization, and
2782 // initializes all split point objects.
2784 void init_split_point_stack() {
2785 for(int i = 0; i < THREAD_MAX; i++)
2786 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2787 SplitPointStack[i][j].parent = NULL;
2788 lock_init(&(SplitPointStack[i][j].lock), NULL);
2793 // destroy_split_point_stack() is called when the program exits, and
2794 // destroys all locks in the precomputed split point objects.
2796 void destroy_split_point_stack() {
2797 for(int i = 0; i < THREAD_MAX; i++)
2798 for(int j = 0; j < MaxActiveSplitPoints; j++)
2799 lock_destroy(&(SplitPointStack[i][j].lock));
2803 // thread_should_stop() checks whether the thread with a given threadID has
2804 // been asked to stop, directly or indirectly. This can happen if a beta
2805 // cutoff has occured in thre thread's currently active split point, or in
2806 // some ancestor of the current split point.
2808 bool thread_should_stop(int threadID) {
2809 assert(threadID >= 0 && threadID < ActiveThreads);
2813 if(Threads[threadID].stop)
2815 if(ActiveThreads <= 2)
2817 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2819 Threads[threadID].stop = true;
2826 // thread_is_available() checks whether the thread with threadID "slave" is
2827 // available to help the thread with threadID "master" at a split point. An
2828 // obvious requirement is that "slave" must be idle. With more than two
2829 // threads, this is not by itself sufficient: If "slave" is the master of
2830 // some active split point, it is only available as a slave to the other
2831 // threads which are busy searching the split point at the top of "slave"'s
2832 // split point stack (the "helpful master concept" in YBWC terminology).
2834 bool thread_is_available(int slave, int master) {
2835 assert(slave >= 0 && slave < ActiveThreads);
2836 assert(master >= 0 && master < ActiveThreads);
2837 assert(ActiveThreads > 1);
2839 if(!Threads[slave].idle || slave == master)
2842 if(Threads[slave].activeSplitPoints == 0)
2843 // No active split points means that the thread is available as a slave
2844 // for any other thread.
2847 if(ActiveThreads == 2)
2850 // Apply the "helpful master" concept if possible.
2851 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2858 // idle_thread_exists() tries to find an idle thread which is available as
2859 // a slave for the thread with threadID "master".
2861 bool idle_thread_exists(int master) {
2862 assert(master >= 0 && master < ActiveThreads);
2863 assert(ActiveThreads > 1);
2865 for(int i = 0; i < ActiveThreads; i++)
2866 if(thread_is_available(i, master))
2872 // split() does the actual work of distributing the work at a node between
2873 // several threads at PV nodes. If it does not succeed in splitting the
2874 // node (because no idle threads are available, or because we have no unused
2875 // split point objects), the function immediately returns false. If
2876 // splitting is possible, a SplitPoint object is initialized with all the
2877 // data that must be copied to the helper threads (the current position and
2878 // search stack, alpha, beta, the search depth, etc.), and we tell our
2879 // helper threads that they have been assigned work. This will cause them
2880 // to instantly leave their idle loops and call sp_search_pv(). When all
2881 // threads have returned from sp_search_pv (or, equivalently, when
2882 // splitPoint->cpus becomes 0), split() returns true.
2884 bool split(const Position& p, SearchStack* sstck, int ply,
2885 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2886 const Value approximateEval, Depth depth, int* moves,
2887 MovePicker* mp, int master, bool pvNode) {
2890 assert(sstck != NULL);
2891 assert(ply >= 0 && ply < PLY_MAX);
2892 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2893 assert(!pvNode || *alpha < *beta);
2894 assert(*beta <= VALUE_INFINITE);
2895 assert(depth > Depth(0));
2896 assert(master >= 0 && master < ActiveThreads);
2897 assert(ActiveThreads > 1);
2899 SplitPoint* splitPoint;
2904 // If no other thread is available to help us, or if we have too many
2905 // active split points, don't split.
2906 if(!idle_thread_exists(master) ||
2907 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2908 lock_release(&MPLock);
2912 // Pick the next available split point object from the split point stack
2913 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2914 Threads[master].activeSplitPoints++;
2916 // Initialize the split point object
2917 splitPoint->parent = Threads[master].splitPoint;
2918 splitPoint->finished = false;
2919 splitPoint->ply = ply;
2920 splitPoint->depth = depth;
2921 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2922 splitPoint->beta = *beta;
2923 splitPoint->pvNode = pvNode;
2924 splitPoint->bestValue = *bestValue;
2925 splitPoint->futilityValue = futilityValue;
2926 splitPoint->approximateEval = approximateEval;
2927 splitPoint->master = master;
2928 splitPoint->mp = mp;
2929 splitPoint->moves = *moves;
2930 splitPoint->cpus = 1;
2931 splitPoint->pos.copy(p);
2932 splitPoint->parentSstack = sstck;
2933 for(i = 0; i < ActiveThreads; i++)
2934 splitPoint->slaves[i] = 0;
2936 // Copy the current position and the search stack to the master thread
2937 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2938 Threads[master].splitPoint = splitPoint;
2940 // Make copies of the current position and search stack for each thread
2941 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2943 if(thread_is_available(i, master)) {
2944 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2945 Threads[i].splitPoint = splitPoint;
2946 splitPoint->slaves[i] = 1;
2950 // Tell the threads that they have work to do. This will make them leave
2952 for(i = 0; i < ActiveThreads; i++)
2953 if(i == master || splitPoint->slaves[i]) {
2954 Threads[i].workIsWaiting = true;
2955 Threads[i].idle = false;
2956 Threads[i].stop = false;
2959 lock_release(&MPLock);
2961 // Everything is set up. The master thread enters the idle loop, from
2962 // which it will instantly launch a search, because its workIsWaiting
2963 // slot is 'true'. We send the split point as a second parameter to the
2964 // idle loop, which means that the main thread will return from the idle
2965 // loop when all threads have finished their work at this split point
2966 // (i.e. when // splitPoint->cpus == 0).
2967 idle_loop(master, splitPoint);
2969 // We have returned from the idle loop, which means that all threads are
2970 // finished. Update alpha, beta and bestvalue, and return.
2972 if(pvNode) *alpha = splitPoint->alpha;
2973 *beta = splitPoint->beta;
2974 *bestValue = splitPoint->bestValue;
2975 Threads[master].stop = false;
2976 Threads[master].idle = false;
2977 Threads[master].activeSplitPoints--;
2978 Threads[master].splitPoint = splitPoint->parent;
2979 lock_release(&MPLock);
2985 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2986 // to start a new search from the root.
2988 void wake_sleeping_threads() {
2989 if(ActiveThreads > 1) {
2990 for(int i = 1; i < ActiveThreads; i++) {
2991 Threads[i].idle = true;
2992 Threads[i].workIsWaiting = false;
2994 #if !defined(_MSC_VER)
2995 pthread_mutex_lock(&WaitLock);
2996 pthread_cond_broadcast(&WaitCond);
2997 pthread_mutex_unlock(&WaitLock);
2999 for(int i = 1; i < THREAD_MAX; i++)
3000 SetEvent(SitIdleEvent[i]);
3006 // init_thread() is the function which is called when a new thread is
3007 // launched. It simply calls the idle_loop() function with the supplied
3008 // threadID. There are two versions of this function; one for POSIX threads
3009 // and one for Windows threads.
3011 #if !defined(_MSC_VER)
3013 void *init_thread(void *threadID) {
3014 idle_loop(*(int *)threadID, NULL);
3020 DWORD WINAPI init_thread(LPVOID threadID) {
3021 idle_loop(*(int *)threadID, NULL);