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 = true;
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(0x20);
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);
186 const Depth RazorDepth = 4*OnePly;
188 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
189 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
191 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
192 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
195 /// Variables initialized by UCI options
197 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
198 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
200 // Depth limit for use of dynamic threat detection
201 Depth ThreatDepth; // heavy SMP read access
203 // Last seconds noise filtering (LSN)
204 const bool UseLSNFiltering = true;
205 const int LSNTime = 4000; // In milliseconds
206 const Value LSNValue = value_from_centipawns(200);
207 bool loseOnTime = false;
209 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
210 // There is heavy SMP read access on these arrays
211 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
212 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
214 // Iteration counters
216 BetaCounterType BetaCounter; // has per-thread internal data
218 // Scores and number of times the best move changed for each iteration
219 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
220 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
225 // Time managment variables
227 int MaxNodes, MaxDepth;
228 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
232 bool StopOnPonderhit;
233 bool AbortSearch; // heavy SMP read access
239 // Show current line?
240 bool ShowCurrentLine;
244 std::ofstream LogFile;
246 // MP related variables
247 int ActiveThreads = 1;
248 Depth MinimumSplitDepth;
249 int MaxThreadsPerSplitPoint;
250 Thread Threads[THREAD_MAX];
253 bool AllThreadsShouldExit = false;
254 const int MaxActiveSplitPoints = 8;
255 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
258 #if !defined(_MSC_VER)
259 pthread_cond_t WaitCond;
260 pthread_mutex_t WaitLock;
262 HANDLE SitIdleEvent[THREAD_MAX];
265 // Node counters, used only by thread[0] but try to keep in different
266 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
268 int NodesBetweenPolls = 30000;
276 Value id_loop(const Position& pos, Move searchMoves[]);
277 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
278 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
279 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
280 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
281 void sp_search(SplitPoint* sp, int threadID);
282 void sp_search_pv(SplitPoint* sp, int threadID);
283 void init_node(SearchStack ss[], int ply, int threadID);
284 void update_pv(SearchStack ss[], int ply);
285 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
286 bool connected_moves(const Position& pos, Move m1, Move m2);
287 bool value_is_mate(Value value);
288 bool move_is_killer(Move m, const SearchStack& ss);
289 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
290 bool ok_to_do_nullmove(const Position& pos);
291 bool ok_to_prune(const Position& pos, Move m, Move threat);
292 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
293 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
294 void update_killers(Move m, SearchStack& ss);
296 bool fail_high_ply_1();
297 int current_search_time();
301 void print_current_line(SearchStack ss[], int ply, int threadID);
302 void wait_for_stop_or_ponderhit();
303 void init_ss_array(SearchStack ss[]);
305 void idle_loop(int threadID, SplitPoint* waitSp);
306 void init_split_point_stack();
307 void destroy_split_point_stack();
308 bool thread_should_stop(int threadID);
309 bool thread_is_available(int slave, int master);
310 bool idle_thread_exists(int master);
311 bool split(const Position& pos, SearchStack* ss, int ply,
312 Value *alpha, Value *beta, Value *bestValue,
313 const Value futilityValue, const Value approximateValue,
314 Depth depth, int *moves,
315 MovePicker *mp, int master, bool pvNode);
316 void wake_sleeping_threads();
318 #if !defined(_MSC_VER)
319 void *init_thread(void *threadID);
321 DWORD WINAPI init_thread(LPVOID threadID);
332 /// perft() is our utility to verify move generation is bug free. All the
333 /// legal moves up to given depth are generated and counted and the sum returned.
335 int perft(Position& pos, Depth depth)
339 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
341 // If we are at the last ply we don't need to do and undo
342 // the moves, just to count them.
343 if (depth <= OnePly) // Replace with '<' to test also qsearch
345 while (mp.get_next_move()) sum++;
349 // Loop through all legal moves
351 while ((move = mp.get_next_move()) != MOVE_NONE)
354 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
355 sum += perft(pos, depth - OnePly);
362 /// think() is the external interface to Stockfish's search, and is called when
363 /// the program receives the UCI 'go' command. It initializes various
364 /// search-related global variables, and calls root_search(). It returns false
365 /// when a quit command is received during the search.
367 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
368 int time[], int increment[], int movesToGo, int maxDepth,
369 int maxNodes, int maxTime, Move searchMoves[]) {
371 // Look for a book move
372 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
375 if (get_option_value_string("Book File") != OpeningBook.file_name())
376 OpeningBook.open(get_option_value_string("Book File"));
378 bookMove = OpeningBook.get_move(pos);
379 if (bookMove != MOVE_NONE)
381 std::cout << "bestmove " << bookMove << std::endl;
386 // Initialize global search variables
388 SearchStartTime = get_system_time();
389 for (int i = 0; i < THREAD_MAX; i++)
391 Threads[i].nodes = 0ULL;
392 Threads[i].failHighPly1 = false;
395 InfiniteSearch = infinite;
396 PonderSearch = ponder;
397 StopOnPonderhit = false;
403 ExactMaxTime = maxTime;
405 if (button_was_pressed("New Game"))
406 loseOnTime = false; // reset at the beginning of a new game
408 // Read UCI option values
409 TT.set_size(get_option_value_int("Hash"));
410 if (button_was_pressed("Clear Hash"))
413 bool PonderingEnabled = get_option_value_bool("Ponder");
414 MultiPV = get_option_value_int("MultiPV");
416 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
417 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
419 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
420 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
422 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
423 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
425 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
426 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
428 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
429 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
431 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
432 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
434 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
435 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
436 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
438 Chess960 = get_option_value_bool("UCI_Chess960");
439 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
440 UseLogFile = get_option_value_bool("Use Search Log");
442 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
444 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
445 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
447 read_weights(pos.side_to_move());
449 // Set the number of active threads
450 int newActiveThreads = get_option_value_int("Threads");
451 if (newActiveThreads != ActiveThreads)
453 ActiveThreads = newActiveThreads;
454 init_eval(ActiveThreads);
457 // Wake up sleeping threads
458 wake_sleeping_threads();
460 for (int i = 1; i < ActiveThreads; i++)
461 assert(thread_is_available(i, 0));
464 int myTime = time[side_to_move];
465 int myIncrement = increment[side_to_move];
467 if (!movesToGo) // Sudden death time control
471 MaxSearchTime = myTime / 30 + myIncrement;
472 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
473 } else { // Blitz game without increment
474 MaxSearchTime = myTime / 30;
475 AbsoluteMaxSearchTime = myTime / 8;
478 else // (x moves) / (y minutes)
482 MaxSearchTime = myTime / 2;
483 AbsoluteMaxSearchTime =
484 (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
486 MaxSearchTime = myTime / Min(movesToGo, 20);
487 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
491 if (PonderingEnabled)
493 MaxSearchTime += MaxSearchTime / 4;
494 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
497 // Fixed depth or fixed number of nodes?
500 InfiniteSearch = true; // HACK
505 NodesBetweenPolls = Min(MaxNodes, 30000);
506 InfiniteSearch = true; // HACK
508 else if (myTime && myTime < 1000)
509 NodesBetweenPolls = 1000;
510 else if (myTime && myTime < 5000)
511 NodesBetweenPolls = 5000;
513 NodesBetweenPolls = 30000;
515 // Write information to search log file
517 LogFile << "Searching: " << pos.to_fen() << std::endl
518 << "infinite: " << infinite
519 << " ponder: " << ponder
520 << " time: " << myTime
521 << " increment: " << myIncrement
522 << " moves to go: " << movesToGo << std::endl;
525 // LSN filtering. Used only for developing purpose. Disabled by default.
529 // Step 2. If after last move we decided to lose on time, do it now!
530 while (SearchStartTime + myTime + 1000 > get_system_time())
534 // We're ready to start thinking. Call the iterative deepening loop function
535 Value v = id_loop(pos, searchMoves);
537 // LSN filtering. Used only for developing purpose. Disabled by default.
540 // Step 1. If this is sudden death game and our position is hopeless,
541 // decide to lose on time.
542 if ( !loseOnTime // If we already lost on time, go to step 3.
552 // Step 3. Now after stepping over the time limit, reset flag for next match.
565 /// init_threads() is called during startup. It launches all helper threads,
566 /// and initializes the split point stack and the global locks and condition
569 void init_threads() {
573 #if !defined(_MSC_VER)
574 pthread_t pthread[1];
577 for (i = 0; i < THREAD_MAX; i++)
578 Threads[i].activeSplitPoints = 0;
580 // Initialize global locks
581 lock_init(&MPLock, NULL);
582 lock_init(&IOLock, NULL);
584 init_split_point_stack();
586 #if !defined(_MSC_VER)
587 pthread_mutex_init(&WaitLock, NULL);
588 pthread_cond_init(&WaitCond, NULL);
590 for (i = 0; i < THREAD_MAX; i++)
591 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
594 // All threads except the main thread should be initialized to idle state
595 for (i = 1; i < THREAD_MAX; i++)
597 Threads[i].stop = false;
598 Threads[i].workIsWaiting = false;
599 Threads[i].idle = true;
600 Threads[i].running = false;
603 // Launch the helper threads
604 for(i = 1; i < THREAD_MAX; i++)
606 #if !defined(_MSC_VER)
607 pthread_create(pthread, NULL, init_thread, (void*)(&i));
610 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
613 // Wait until the thread has finished launching
614 while (!Threads[i].running);
619 /// stop_threads() is called when the program exits. It makes all the
620 /// helper threads exit cleanly.
622 void stop_threads() {
624 ActiveThreads = THREAD_MAX; // HACK
625 Idle = false; // HACK
626 wake_sleeping_threads();
627 AllThreadsShouldExit = true;
628 for (int i = 1; i < THREAD_MAX; i++)
630 Threads[i].stop = true;
631 while(Threads[i].running);
633 destroy_split_point_stack();
637 /// nodes_searched() returns the total number of nodes searched so far in
638 /// the current search.
640 int64_t nodes_searched() {
642 int64_t result = 0ULL;
643 for (int i = 0; i < ActiveThreads; i++)
644 result += Threads[i].nodes;
649 // SearchStack::init() initializes a search stack. Used at the beginning of a
650 // new search from the root.
651 void SearchStack::init(int ply) {
653 pv[ply] = pv[ply + 1] = MOVE_NONE;
654 currentMove = threatMove = MOVE_NONE;
655 reduction = Depth(0);
658 void SearchStack::initKillers() {
660 mateKiller = MOVE_NONE;
661 for (int i = 0; i < KILLER_MAX; i++)
662 killers[i] = MOVE_NONE;
667 // id_loop() is the main iterative deepening loop. It calls root_search
668 // repeatedly with increasing depth until the allocated thinking time has
669 // been consumed, the user stops the search, or the maximum search depth is
672 Value id_loop(const Position& pos, Move searchMoves[]) {
675 SearchStack ss[PLY_MAX_PLUS_2];
677 // searchMoves are verified, copied, scored and sorted
678 RootMoveList rml(p, searchMoves);
680 if (rml.move_count() == 0)
683 wait_for_stop_or_ponderhit();
685 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
688 // Print RootMoveList c'tor startup scoring to the standard output,
689 // so that we print information also for iteration 1.
690 std::cout << "info depth " << 1 << "\ninfo depth " << 1
691 << " score " << value_to_string(rml.get_move_score(0))
692 << " time " << current_search_time()
693 << " nodes " << nodes_searched()
695 << " pv " << rml.get_move(0) << "\n";
701 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
704 // Is one move significantly better than others after initial scoring ?
705 Move EasyMove = MOVE_NONE;
706 if ( rml.move_count() == 1
707 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
708 EasyMove = rml.get_move(0);
710 // Iterative deepening loop
711 while (Iteration < PLY_MAX)
713 // Initialize iteration
716 BestMoveChangesByIteration[Iteration] = 0;
720 std::cout << "info depth " << Iteration << std::endl;
722 // Calculate dynamic search window based on previous iterations
725 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
727 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
728 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
730 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
732 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
733 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
737 alpha = - VALUE_INFINITE;
738 beta = VALUE_INFINITE;
741 // Search to the current depth
742 Value value = root_search(p, ss, rml, alpha, beta);
744 // Write PV to transposition table, in case the relevant entries have
745 // been overwritten during the search.
746 TT.insert_pv(p, ss[0].pv);
749 break; // Value cannot be trusted. Break out immediately!
751 //Save info about search result
752 Value speculatedValue;
755 Value delta = value - IterationInfo[Iteration - 1].value;
762 speculatedValue = value + delta;
763 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
765 else if (value <= alpha)
767 assert(value == alpha);
771 speculatedValue = value + delta;
772 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
774 speculatedValue = value;
776 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
777 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
779 // Erase the easy move if it differs from the new best move
780 if (ss[0].pv[0] != EasyMove)
781 EasyMove = MOVE_NONE;
788 bool stopSearch = false;
790 // Stop search early if there is only a single legal move
791 if (Iteration >= 6 && rml.move_count() == 1)
794 // Stop search early when the last two iterations returned a mate score
796 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
797 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
800 // Stop search early if one move seems to be much better than the rest
801 int64_t nodes = nodes_searched();
805 && EasyMove == ss[0].pv[0]
806 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
807 && current_search_time() > MaxSearchTime / 16)
808 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
809 && current_search_time() > MaxSearchTime / 32)))
812 // Add some extra time if the best move has changed during the last two iterations
813 if (Iteration > 5 && Iteration <= 50)
814 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
815 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
817 // Stop search if most of MaxSearchTime is consumed at the end of the
818 // iteration. We probably don't have enough time to search the first
819 // move at the next iteration anyway.
820 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
828 StopOnPonderhit = true;
832 if (MaxDepth && Iteration >= MaxDepth)
838 // If we are pondering, we shouldn't print the best move before we
841 wait_for_stop_or_ponderhit();
843 // Print final search statistics
844 std::cout << "info nodes " << nodes_searched()
846 << " time " << current_search_time()
847 << " hashfull " << TT.full() << std::endl;
849 // Print the best move and the ponder move to the standard output
850 if (ss[0].pv[0] == MOVE_NONE)
852 ss[0].pv[0] = rml.get_move(0);
853 ss[0].pv[1] = MOVE_NONE;
855 std::cout << "bestmove " << ss[0].pv[0];
856 if (ss[0].pv[1] != MOVE_NONE)
857 std::cout << " ponder " << ss[0].pv[1];
859 std::cout << std::endl;
864 dbg_print_mean(LogFile);
866 if (dbg_show_hit_rate)
867 dbg_print_hit_rate(LogFile);
870 LogFile << "Nodes: " << nodes_searched() << std::endl
871 << "Nodes/second: " << nps() << std::endl
872 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
874 p.do_move(ss[0].pv[0], st);
875 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
876 << std::endl << std::endl;
878 return rml.get_move_score(0);
882 // root_search() is the function which searches the root node. It is
883 // similar to search_pv except that it uses a different move ordering
884 // scheme (perhaps we should try to use this at internal PV nodes, too?)
885 // and prints some information to the standard output.
887 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
889 Value oldAlpha = alpha;
893 // Loop through all the moves in the root move list
894 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
898 // We failed high, invalidate and skip next moves, leave node-counters
899 // and beta-counters as they are and quickly return, we will try to do
900 // a research at the next iteration with a bigger aspiration window.
901 rml.set_move_score(i, -VALUE_INFINITE);
909 RootMoveNumber = i + 1;
912 // Remember the node count before the move is searched. The node counts
913 // are used to sort the root moves at the next iteration.
914 nodes = nodes_searched();
916 // Reset beta cut-off counters
919 // Pick the next root move, and print the move and the move number to
920 // the standard output.
921 move = ss[0].currentMove = rml.get_move(i);
922 if (current_search_time() >= 1000)
923 std::cout << "info currmove " << move
924 << " currmovenumber " << i + 1 << std::endl;
926 // Decide search depth for this move
927 bool moveIsCheck = pos.move_is_check(move);
928 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
930 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
931 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
933 // Make the move, and search it
934 pos.do_move(move, st, ci, moveIsCheck);
938 // Aspiration window is disabled in multi-pv case
940 alpha = -VALUE_INFINITE;
942 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
943 // If the value has dropped a lot compared to the last iteration,
944 // set the boolean variable Problem to true. This variable is used
945 // for time managment: When Problem is true, we try to complete the
946 // current iteration before playing a move.
947 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
949 if (Problem && StopOnPonderhit)
950 StopOnPonderhit = false;
954 if ( newDepth >= 3*OnePly
955 && i >= MultiPV + LMRPVMoves
957 && !captureOrPromotion
958 && !move_is_castle(move))
960 ss[0].reduction = OnePly;
961 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
963 value = alpha + 1; // Just to trigger next condition
967 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
970 // Fail high! Set the boolean variable FailHigh to true, and
971 // re-search the move with a big window. The variable FailHigh is
972 // used for time managment: We try to avoid aborting the search
973 // prematurely during a fail high research.
975 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
982 // Finished searching the move. If AbortSearch is true, the search
983 // was aborted because the user interrupted the search or because we
984 // ran out of time. In this case, the return value of the search cannot
985 // be trusted, and we break out of the loop without updating the best
990 // Remember the node count for this move. The node counts are used to
991 // sort the root moves at the next iteration.
992 rml.set_move_nodes(i, nodes_searched() - nodes);
994 // Remember the beta-cutoff statistics
996 BetaCounter.read(pos.side_to_move(), our, their);
997 rml.set_beta_counters(i, our, their);
999 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1001 if (value <= alpha && i >= MultiPV)
1002 rml.set_move_score(i, -VALUE_INFINITE);
1005 // PV move or new best move!
1008 rml.set_move_score(i, value);
1010 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1011 rml.set_move_pv(i, ss[0].pv);
1015 // We record how often the best move has been changed in each
1016 // iteration. This information is used for time managment: When
1017 // the best move changes frequently, we allocate some more time.
1019 BestMoveChangesByIteration[Iteration]++;
1021 // Print search information to the standard output
1022 std::cout << "info depth " << Iteration
1023 << " score " << value_to_string(value)
1024 << ((value >= beta)?
1025 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
1026 << " time " << current_search_time()
1027 << " nodes " << nodes_searched()
1031 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1032 std::cout << ss[0].pv[j] << " ";
1034 std::cout << std::endl;
1037 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value,
1038 ((value >= beta)? VALUE_TYPE_LOWER
1039 : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)),
1046 // Reset the global variable Problem to false if the value isn't too
1047 // far below the final value from the last iteration.
1048 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1053 rml.sort_multipv(i);
1054 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1057 std::cout << "info multipv " << j + 1
1058 << " score " << value_to_string(rml.get_move_score(j))
1059 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1060 << " time " << current_search_time()
1061 << " nodes " << nodes_searched()
1065 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1066 std::cout << rml.get_move_pv(j, k) << " ";
1068 std::cout << std::endl;
1070 alpha = rml.get_move_score(Min(i, MultiPV-1));
1072 } // New best move case
1074 assert(alpha >= oldAlpha);
1076 FailLow = (alpha == oldAlpha);
1082 // search_pv() is the main search function for PV nodes.
1084 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1085 Depth depth, int ply, int threadID) {
1087 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1088 assert(beta > alpha && beta <= VALUE_INFINITE);
1089 assert(ply >= 0 && ply < PLY_MAX);
1090 assert(threadID >= 0 && threadID < ActiveThreads);
1092 Move movesSearched[256];
1097 Depth ext, newDepth;
1098 Value oldAlpha, value;
1099 bool isCheck, mateThreat, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1101 Value bestValue = -VALUE_INFINITE;
1104 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1106 // Initialize, and make an early exit in case of an aborted search,
1107 // an instant draw, maximum ply reached, etc.
1108 init_node(ss, ply, threadID);
1110 // After init_node() that calls poll()
1111 if (AbortSearch || thread_should_stop(threadID))
1117 if (ply >= PLY_MAX - 1)
1118 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1120 // Mate distance pruning
1122 alpha = Max(value_mated_in(ply), alpha);
1123 beta = Min(value_mate_in(ply+1), beta);
1127 // Transposition table lookup. At PV nodes, we don't use the TT for
1128 // pruning, but only for move ordering. This is to avoid problems in
1129 // the following areas:
1131 // * Repetition draw detection
1132 // * Fifty move rule detection
1133 // * Searching for a mate
1134 // * Printing of full PV line
1136 tte = TT.retrieve(pos.get_key());
1137 ttMove = (tte ? tte->move() : MOVE_NONE);
1139 // Go with internal iterative deepening if we don't have a TT move
1140 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1142 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1143 ttMove = ss[ply].pv[ply];
1144 tte = TT.retrieve(pos.get_key());
1147 // Initialize a MovePicker object for the current position, and prepare
1148 // to search all moves
1149 isCheck = pos.is_check();
1150 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1152 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1154 // Loop through all legal moves until no moves remain or a beta cutoff
1156 while ( alpha < beta
1157 && (move = mp.get_next_move()) != MOVE_NONE
1158 && !thread_should_stop(threadID))
1160 assert(move_is_ok(move));
1162 singleReply = (isCheck && mp.number_of_evasions() == 1);
1163 moveIsCheck = pos.move_is_check(move, ci);
1164 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1166 // Decide the new search depth
1167 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1169 // We want to extend the TT move if it is much better then remaining ones.
1170 // To verify this we do a reduced search on all the other moves but the ttMove,
1171 // if result is lower then TT value minus a margin then we assume ttMove is the
1172 // only one playable. It is a kind of relaxed single reply extension.
1173 if ( depth >= 6 * OnePly
1175 && move == tte->move()
1177 && is_lower_bound(tte->type())
1178 && tte->depth() >= depth - 3 * OnePly)
1180 Value ttValue = value_from_tt(tte->value(), ply);
1182 if (abs(ttValue) < VALUE_KNOWN_WIN)
1184 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1186 // If search result is well below the foreseen score of the ttMove then we
1187 // assume ttMove is the only one realistically playable and we extend it.
1188 if (excValue < ttValue - SingleReplyMargin)
1193 newDepth = depth - OnePly + ext;
1195 // Update current move
1196 movesSearched[moveCount++] = ss[ply].currentMove = move;
1198 // Make and search the move
1199 pos.do_move(move, st, ci, moveIsCheck);
1201 if (moveCount == 1) // The first move in list is the PV
1202 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1205 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1206 // if the move fails high will be re-searched at full depth.
1207 if ( depth >= 3*OnePly
1208 && moveCount >= LMRPVMoves
1210 && !captureOrPromotion
1211 && !move_is_castle(move)
1212 && !move_is_killer(move, ss[ply]))
1214 ss[ply].reduction = OnePly;
1215 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1218 value = alpha + 1; // Just to trigger next condition
1220 if (value > alpha) // Go with full depth non-pv search
1222 ss[ply].reduction = Depth(0);
1223 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1224 if (value > alpha && value < beta)
1226 // When the search fails high at ply 1 while searching the first
1227 // move at the root, set the flag failHighPly1. This is used for
1228 // time managment: We don't want to stop the search early in
1229 // such cases, because resolving the fail high at ply 1 could
1230 // result in a big drop in score at the root.
1231 if (ply == 1 && RootMoveNumber == 1)
1232 Threads[threadID].failHighPly1 = true;
1234 // A fail high occurred. Re-search at full window (pv search)
1235 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1236 Threads[threadID].failHighPly1 = false;
1240 pos.undo_move(move);
1242 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1245 if (value > bestValue)
1252 if (value == value_mate_in(ply + 1))
1253 ss[ply].mateKiller = move;
1255 // If we are at ply 1, and we are searching the first root move at
1256 // ply 0, set the 'Problem' variable if the score has dropped a lot
1257 // (from the computer's point of view) since the previous iteration.
1260 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1265 if ( ActiveThreads > 1
1267 && depth >= MinimumSplitDepth
1269 && idle_thread_exists(threadID)
1271 && !thread_should_stop(threadID)
1272 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE,
1273 depth, &moveCount, &mp, threadID, true))
1277 // All legal moves have been searched. A special case: If there were
1278 // no legal moves, it must be mate or stalemate.
1280 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1282 // If the search is not aborted, update the transposition table,
1283 // history counters, and killer moves.
1284 if (AbortSearch || thread_should_stop(threadID))
1287 if (bestValue <= oldAlpha)
1288 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1290 else if (bestValue >= beta)
1292 BetaCounter.add(pos.side_to_move(), depth, threadID);
1293 move = ss[ply].pv[ply];
1294 if (!pos.move_is_capture_or_promotion(move))
1296 update_history(pos, move, depth, movesSearched, moveCount);
1297 update_killers(move, ss[ply]);
1299 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1302 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1308 // search() is the search function for zero-width nodes.
1310 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1311 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1313 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1314 assert(ply >= 0 && ply < PLY_MAX);
1315 assert(threadID >= 0 && threadID < ActiveThreads);
1317 Move movesSearched[256];
1322 Depth ext, newDepth;
1323 Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1324 bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1325 bool mateThreat = false;
1327 Value bestValue = -VALUE_INFINITE;
1330 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1332 // Initialize, and make an early exit in case of an aborted search,
1333 // an instant draw, maximum ply reached, etc.
1334 init_node(ss, ply, threadID);
1336 // After init_node() that calls poll()
1337 if (AbortSearch || thread_should_stop(threadID))
1343 if (ply >= PLY_MAX - 1)
1344 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1346 // Mate distance pruning
1347 if (value_mated_in(ply) >= beta)
1350 if (value_mate_in(ply + 1) < beta)
1353 // We don't want the score of a partial search to overwrite a previous full search
1354 // TT value, so we use a different position key in case of an excluded move exsists.
1355 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1357 // Transposition table lookup
1358 tte = TT.retrieve(posKey);
1359 ttMove = (tte ? tte->move() : MOVE_NONE);
1361 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1363 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1364 return value_from_tt(tte->value(), ply);
1367 approximateEval = quick_evaluate(pos);
1368 isCheck = pos.is_check();
1374 && !value_is_mate(beta)
1375 && ok_to_do_nullmove(pos)
1376 && approximateEval >= beta - NullMoveMargin)
1378 ss[ply].currentMove = MOVE_NULL;
1380 pos.do_null_move(st);
1382 // Null move dynamic reduction based on depth
1383 int R = (depth >= 5 * OnePly ? 4 : 3);
1385 // Null move dynamic reduction based on value
1386 if (approximateEval - beta > PawnValueMidgame)
1389 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1391 pos.undo_null_move();
1393 if (nullValue >= beta)
1395 if (depth < 6 * OnePly)
1398 // Do zugzwang verification search
1399 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1403 // The null move failed low, which means that we may be faced with
1404 // some kind of threat. If the previous move was reduced, check if
1405 // the move that refuted the null move was somehow connected to the
1406 // move which was reduced. If a connection is found, return a fail
1407 // low score (which will cause the reduced move to fail high in the
1408 // parent node, which will trigger a re-search with full depth).
1409 if (nullValue == value_mated_in(ply + 2))
1412 ss[ply].threatMove = ss[ply + 1].currentMove;
1413 if ( depth < ThreatDepth
1414 && ss[ply - 1].reduction
1415 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1419 // Null move search not allowed, try razoring
1420 else if ( !value_is_mate(beta)
1421 && depth < RazorDepth
1422 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1423 && ss[ply - 1].currentMove != MOVE_NULL
1424 && ttMove == MOVE_NONE
1425 && !pos.has_pawn_on_7th(pos.side_to_move()))
1427 Value rbeta = beta - RazorMargins[int(depth) - 2];
1428 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1433 // Go with internal iterative deepening if we don't have a TT move
1434 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1435 !isCheck && evaluate(pos, ei, threadID) >= beta - IIDMargin)
1437 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1438 ttMove = ss[ply].pv[ply];
1439 tte = TT.retrieve(pos.get_key());
1442 // Initialize a MovePicker object for the current position, and prepare
1443 // to search all moves.
1444 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1446 futilityValue = VALUE_NONE;
1447 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1449 // Calculate depth dependant futility pruning parameters
1450 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1451 const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1453 // Avoid calling evaluate() if we already have the score in TT
1454 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1455 futilityValue = value_from_tt(tte->value(), ply) + FutilityValueMargin;
1457 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1458 while ( bestValue < beta
1459 && (move = mp.get_next_move()) != MOVE_NONE
1460 && !thread_should_stop(threadID))
1462 assert(move_is_ok(move));
1464 if (move == excludedMove)
1467 singleReply = (isCheck && mp.number_of_evasions() == 1);
1468 moveIsCheck = pos.move_is_check(move, ci);
1469 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1471 // Decide the new search depth
1472 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1474 // We want to extend the TT move if it is much better then remaining ones.
1475 // To verify this we do a reduced search on all the other moves but the ttMove,
1476 // if result is lower then TT value minus a margin then we assume ttMove is the
1477 // only one playable. It is a kind of relaxed single reply extension.
1478 if ( depth >= 8 * OnePly
1480 && move == tte->move()
1481 && !excludedMove // Do not allow recursive single-reply search
1483 && is_lower_bound(tte->type())
1484 && tte->depth() >= depth - 3 * OnePly)
1486 Value ttValue = value_from_tt(tte->value(), ply);
1488 if (abs(ttValue) < VALUE_KNOWN_WIN)
1490 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1492 // If search result is well below the foreseen score of the ttMove then we
1493 // assume ttMove is the only one realistically playable and we extend it.
1494 if (excValue < ttValue - SingleReplyMargin)
1499 newDepth = depth - OnePly + ext;
1501 // Update current move
1502 movesSearched[moveCount++] = ss[ply].currentMove = move;
1505 if ( useFutilityPruning
1507 && !captureOrPromotion
1510 // Move count based pruning
1511 if ( moveCount >= FutilityMoveCountMargin
1512 && ok_to_prune(pos, move, ss[ply].threatMove)
1513 && bestValue > value_mated_in(PLY_MAX))
1516 // Value based pruning
1517 if (futilityValue == VALUE_NONE)
1518 futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1520 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1522 if (futilityValueScaled < beta)
1524 if (futilityValueScaled > bestValue)
1525 bestValue = futilityValueScaled;
1530 // Make and search the move
1531 pos.do_move(move, st, ci, moveIsCheck);
1533 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1534 // if the move fails high will be re-searched at full depth.
1535 if ( depth >= 3*OnePly
1536 && moveCount >= LMRNonPVMoves
1538 && !captureOrPromotion
1539 && !move_is_castle(move)
1540 && !move_is_killer(move, ss[ply]))
1542 ss[ply].reduction = OnePly;
1543 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1546 value = beta; // Just to trigger next condition
1548 if (value >= beta) // Go with full depth non-pv search
1550 ss[ply].reduction = Depth(0);
1551 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1553 pos.undo_move(move);
1555 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1558 if (value > bestValue)
1564 if (value == value_mate_in(ply + 1))
1565 ss[ply].mateKiller = move;
1569 if ( ActiveThreads > 1
1571 && depth >= MinimumSplitDepth
1573 && idle_thread_exists(threadID)
1575 && !thread_should_stop(threadID)
1576 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval,
1577 depth, &moveCount, &mp, threadID, false))
1581 // All legal moves have been searched. A special case: If there were
1582 // no legal moves, it must be mate or stalemate.
1584 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1586 // If the search is not aborted, update the transposition table,
1587 // history counters, and killer moves.
1588 if (AbortSearch || thread_should_stop(threadID))
1591 if (bestValue < beta)
1592 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1595 BetaCounter.add(pos.side_to_move(), depth, threadID);
1596 move = ss[ply].pv[ply];
1597 if (!pos.move_is_capture_or_promotion(move))
1599 update_history(pos, move, depth, movesSearched, moveCount);
1600 update_killers(move, ss[ply]);
1602 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1605 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1611 // qsearch() is the quiescence search function, which is called by the main
1612 // search function when the remaining depth is zero (or, to be more precise,
1613 // less than OnePly).
1615 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1616 Depth depth, int ply, int threadID) {
1618 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1619 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1621 assert(ply >= 0 && ply < PLY_MAX);
1622 assert(threadID >= 0 && threadID < ActiveThreads);
1627 Value staticValue, bestValue, value, futilityValue;
1628 bool isCheck, enoughMaterial, moveIsCheck;
1629 const TTEntry* tte = NULL;
1631 bool pvNode = (beta - alpha != 1);
1633 // Initialize, and make an early exit in case of an aborted search,
1634 // an instant draw, maximum ply reached, etc.
1635 init_node(ss, ply, threadID);
1637 // After init_node() that calls poll()
1638 if (AbortSearch || thread_should_stop(threadID))
1644 // Transposition table lookup, only when not in PV
1647 tte = TT.retrieve(pos.get_key());
1648 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1650 assert(tte->type() != VALUE_TYPE_EVAL);
1652 return value_from_tt(tte->value(), ply);
1655 ttMove = (tte ? tte->move() : MOVE_NONE);
1657 isCheck = pos.is_check();
1658 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1660 // Evaluate the position statically
1662 staticValue = -VALUE_INFINITE;
1664 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1666 // Use the cached evaluation score if possible
1667 assert(ei.futilityMargin == Value(0));
1669 staticValue = value_from_tt(tte->value(), ply);
1672 staticValue = evaluate(pos, ei, threadID);
1674 if (ply >= PLY_MAX - 1)
1675 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1677 // Initialize "stand pat score", and return it immediately if it is
1679 bestValue = staticValue;
1681 if (bestValue >= beta)
1683 // Store the score to avoid a future costly evaluation() call
1684 if (!isCheck && !tte && ei.futilityMargin == 0)
1685 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1690 if (bestValue > alpha)
1693 // Initialize a MovePicker object for the current position, and prepare
1694 // to search the moves. Because the depth is <= 0 here, only captures,
1695 // queen promotions and checks (only if depth == 0) will be generated.
1696 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1698 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1700 // Loop through the moves until no moves remain or a beta cutoff
1702 while ( alpha < beta
1703 && (move = mp.get_next_move()) != MOVE_NONE)
1705 assert(move_is_ok(move));
1708 ss[ply].currentMove = move;
1710 moveIsCheck = pos.move_is_check(move, ci);
1718 && !move_is_promotion(move)
1719 && !pos.move_is_passed_pawn_push(move))
1721 futilityValue = staticValue
1722 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1723 pos.endgame_value_of_piece_on(move_to(move)))
1724 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1726 + ei.futilityMargin;
1728 if (futilityValue < alpha)
1730 if (futilityValue > bestValue)
1731 bestValue = futilityValue;
1736 // Don't search captures and checks with negative SEE values
1739 && !move_is_promotion(move)
1740 && pos.see_sign(move) < 0)
1743 // Make and search the move
1744 pos.do_move(move, st, ci, moveIsCheck);
1745 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1746 pos.undo_move(move);
1748 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1751 if (value > bestValue)
1762 // All legal moves have been searched. A special case: If we're in check
1763 // and no legal moves were found, it is checkmate.
1764 if (!moveCount && pos.is_check()) // Mate!
1765 return value_mated_in(ply);
1767 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1769 // Update transposition table
1770 move = ss[ply].pv[ply];
1773 // If bestValue isn't changed it means it is still the static evaluation of
1774 // the node, so keep this info to avoid a future costly evaluation() call.
1775 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1776 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1778 if (bestValue < beta)
1779 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1781 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1784 // Update killers only for good check moves
1785 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1786 update_killers(move, ss[ply]);
1792 // sp_search() is used to search from a split point. This function is called
1793 // by each thread working at the split point. It is similar to the normal
1794 // search() function, but simpler. Because we have already probed the hash
1795 // table, done a null move search, and searched the first move before
1796 // splitting, we don't have to repeat all this work in sp_search(). We
1797 // also don't need to store anything to the hash table here: This is taken
1798 // care of after we return from the split point.
1800 void sp_search(SplitPoint* sp, int threadID) {
1802 assert(threadID >= 0 && threadID < ActiveThreads);
1803 assert(ActiveThreads > 1);
1805 Position pos = Position(sp->pos);
1807 SearchStack* ss = sp->sstack[threadID];
1810 bool isCheck = pos.is_check();
1811 bool useFutilityPruning = sp->depth < SelectiveDepth
1814 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1815 const int FutilityValueMargin = 112 * bitScanReverse32(int(sp->depth) * int(sp->depth) / 2);
1817 while ( sp->bestValue < sp->beta
1818 && !thread_should_stop(threadID)
1819 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1821 assert(move_is_ok(move));
1823 bool moveIsCheck = pos.move_is_check(move, ci);
1824 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1826 lock_grab(&(sp->lock));
1827 int moveCount = ++sp->moves;
1828 lock_release(&(sp->lock));
1830 ss[sp->ply].currentMove = move;
1832 // Decide the new search depth.
1834 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1835 Depth newDepth = sp->depth - OnePly + ext;
1838 if ( useFutilityPruning
1840 && !captureOrPromotion)
1842 // Move count based pruning
1843 if ( moveCount >= FutilityMoveCountMargin
1844 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1845 && sp->bestValue > value_mated_in(PLY_MAX))
1848 // Value based pruning
1849 if (sp->futilityValue == VALUE_NONE)
1852 sp->futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1855 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1857 if (futilityValueScaled < sp->beta)
1859 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1861 lock_grab(&(sp->lock));
1862 if (futilityValueScaled > sp->bestValue)
1863 sp->bestValue = futilityValueScaled;
1864 lock_release(&(sp->lock));
1870 // Make and search the move.
1872 pos.do_move(move, st, ci, moveIsCheck);
1874 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1875 // if the move fails high will be re-searched at full depth.
1877 && moveCount >= LMRNonPVMoves
1878 && !captureOrPromotion
1879 && !move_is_castle(move)
1880 && !move_is_killer(move, ss[sp->ply]))
1882 ss[sp->ply].reduction = OnePly;
1883 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1886 value = sp->beta; // Just to trigger next condition
1888 if (value >= sp->beta) // Go with full depth non-pv search
1890 ss[sp->ply].reduction = Depth(0);
1891 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1893 pos.undo_move(move);
1895 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1897 if (thread_should_stop(threadID))
1901 if (value > sp->bestValue) // Less then 2% of cases
1903 lock_grab(&(sp->lock));
1904 if (value > sp->bestValue && !thread_should_stop(threadID))
1906 sp->bestValue = value;
1907 if (sp->bestValue >= sp->beta)
1909 sp_update_pv(sp->parentSstack, ss, sp->ply);
1910 for (int i = 0; i < ActiveThreads; i++)
1911 if (i != threadID && (i == sp->master || sp->slaves[i]))
1912 Threads[i].stop = true;
1914 sp->finished = true;
1917 lock_release(&(sp->lock));
1921 lock_grab(&(sp->lock));
1923 // If this is the master thread and we have been asked to stop because of
1924 // a beta cutoff higher up in the tree, stop all slave threads.
1925 if (sp->master == threadID && thread_should_stop(threadID))
1926 for (int i = 0; i < ActiveThreads; i++)
1928 Threads[i].stop = true;
1931 sp->slaves[threadID] = 0;
1933 lock_release(&(sp->lock));
1937 // sp_search_pv() is used to search from a PV split point. This function
1938 // is called by each thread working at the split point. It is similar to
1939 // the normal search_pv() function, but simpler. Because we have already
1940 // probed the hash table and searched the first move before splitting, we
1941 // don't have to repeat all this work in sp_search_pv(). We also don't
1942 // need to store anything to the hash table here: This is taken care of
1943 // after we return from the split point.
1945 void sp_search_pv(SplitPoint* sp, int threadID) {
1947 assert(threadID >= 0 && threadID < ActiveThreads);
1948 assert(ActiveThreads > 1);
1950 Position pos = Position(sp->pos);
1952 SearchStack* ss = sp->sstack[threadID];
1956 while ( sp->alpha < sp->beta
1957 && !thread_should_stop(threadID)
1958 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1960 bool moveIsCheck = pos.move_is_check(move, ci);
1961 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1963 assert(move_is_ok(move));
1965 lock_grab(&(sp->lock));
1966 int moveCount = ++sp->moves;
1967 lock_release(&(sp->lock));
1969 ss[sp->ply].currentMove = move;
1971 // Decide the new search depth.
1973 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1974 Depth newDepth = sp->depth - OnePly + ext;
1976 // Make and search the move.
1978 pos.do_move(move, st, ci, moveIsCheck);
1980 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1981 // if the move fails high will be re-searched at full depth.
1983 && moveCount >= LMRPVMoves
1984 && !captureOrPromotion
1985 && !move_is_castle(move)
1986 && !move_is_killer(move, ss[sp->ply]))
1988 ss[sp->ply].reduction = OnePly;
1989 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1992 value = sp->alpha + 1; // Just to trigger next condition
1994 if (value > sp->alpha) // Go with full depth non-pv search
1996 ss[sp->ply].reduction = Depth(0);
1997 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1999 if (value > sp->alpha && value < sp->beta)
2001 // When the search fails high at ply 1 while searching the first
2002 // move at the root, set the flag failHighPly1. This is used for
2003 // time managment: We don't want to stop the search early in
2004 // such cases, because resolving the fail high at ply 1 could
2005 // result in a big drop in score at the root.
2006 if (sp->ply == 1 && RootMoveNumber == 1)
2007 Threads[threadID].failHighPly1 = true;
2009 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2010 Threads[threadID].failHighPly1 = false;
2013 pos.undo_move(move);
2015 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2017 if (thread_should_stop(threadID))
2021 lock_grab(&(sp->lock));
2022 if (value > sp->bestValue && !thread_should_stop(threadID))
2024 sp->bestValue = value;
2025 if (value > sp->alpha)
2028 sp_update_pv(sp->parentSstack, ss, sp->ply);
2029 if (value == value_mate_in(sp->ply + 1))
2030 ss[sp->ply].mateKiller = move;
2032 if (value >= sp->beta)
2034 for (int i = 0; i < ActiveThreads; i++)
2035 if (i != threadID && (i == sp->master || sp->slaves[i]))
2036 Threads[i].stop = true;
2038 sp->finished = true;
2041 // If we are at ply 1, and we are searching the first root move at
2042 // ply 0, set the 'Problem' variable if the score has dropped a lot
2043 // (from the computer's point of view) since the previous iteration.
2046 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2049 lock_release(&(sp->lock));
2052 lock_grab(&(sp->lock));
2054 // If this is the master thread and we have been asked to stop because of
2055 // a beta cutoff higher up in the tree, stop all slave threads.
2056 if (sp->master == threadID && thread_should_stop(threadID))
2057 for (int i = 0; i < ActiveThreads; i++)
2059 Threads[i].stop = true;
2062 sp->slaves[threadID] = 0;
2064 lock_release(&(sp->lock));
2067 /// The BetaCounterType class
2069 BetaCounterType::BetaCounterType() { clear(); }
2071 void BetaCounterType::clear() {
2073 for (int i = 0; i < THREAD_MAX; i++)
2074 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2077 void BetaCounterType::add(Color us, Depth d, int threadID) {
2079 // Weighted count based on depth
2080 Threads[threadID].betaCutOffs[us] += unsigned(d);
2083 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2086 for (int i = 0; i < THREAD_MAX; i++)
2088 our += Threads[i].betaCutOffs[us];
2089 their += Threads[i].betaCutOffs[opposite_color(us)];
2094 /// The RootMove class
2098 RootMove::RootMove() {
2099 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
2102 // RootMove::operator<() is the comparison function used when
2103 // sorting the moves. A move m1 is considered to be better
2104 // than a move m2 if it has a higher score, or if the moves
2105 // have equal score but m1 has the higher node count.
2107 bool RootMove::operator<(const RootMove& m) {
2109 if (score != m.score)
2110 return (score < m.score);
2112 return theirBeta <= m.theirBeta;
2115 /// The RootMoveList class
2119 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2121 MoveStack mlist[MaxRootMoves];
2122 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2124 // Generate all legal moves
2125 MoveStack* last = generate_moves(pos, mlist);
2127 // Add each move to the moves[] array
2128 for (MoveStack* cur = mlist; cur != last; cur++)
2130 bool includeMove = includeAllMoves;
2132 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2133 includeMove = (searchMoves[k] == cur->move);
2138 // Find a quick score for the move
2140 SearchStack ss[PLY_MAX_PLUS_2];
2143 moves[count].move = cur->move;
2144 pos.do_move(moves[count].move, st);
2145 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2146 pos.undo_move(moves[count].move);
2147 moves[count].pv[0] = moves[count].move;
2148 moves[count].pv[1] = MOVE_NONE;
2155 // Simple accessor methods for the RootMoveList class
2157 inline Move RootMoveList::get_move(int moveNum) const {
2158 return moves[moveNum].move;
2161 inline Value RootMoveList::get_move_score(int moveNum) const {
2162 return moves[moveNum].score;
2165 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2166 moves[moveNum].score = score;
2169 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2170 moves[moveNum].nodes = nodes;
2171 moves[moveNum].cumulativeNodes += nodes;
2174 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2175 moves[moveNum].ourBeta = our;
2176 moves[moveNum].theirBeta = their;
2179 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2181 for(j = 0; pv[j] != MOVE_NONE; j++)
2182 moves[moveNum].pv[j] = pv[j];
2183 moves[moveNum].pv[j] = MOVE_NONE;
2186 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2187 return moves[moveNum].pv[i];
2190 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2191 return moves[moveNum].cumulativeNodes;
2194 inline int RootMoveList::move_count() const {
2199 // RootMoveList::sort() sorts the root move list at the beginning of a new
2202 inline void RootMoveList::sort() {
2204 sort_multipv(count - 1); // all items
2208 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2209 // list by their scores and depths. It is used to order the different PVs
2210 // correctly in MultiPV mode.
2212 void RootMoveList::sort_multipv(int n) {
2214 for (int i = 1; i <= n; i++)
2216 RootMove rm = moves[i];
2218 for (j = i; j > 0 && moves[j-1] < rm; j--)
2219 moves[j] = moves[j-1];
2225 // init_node() is called at the beginning of all the search functions
2226 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2227 // stack object corresponding to the current node. Once every
2228 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2229 // for user input and checks whether it is time to stop the search.
2231 void init_node(SearchStack ss[], int ply, int threadID) {
2233 assert(ply >= 0 && ply < PLY_MAX);
2234 assert(threadID >= 0 && threadID < ActiveThreads);
2236 Threads[threadID].nodes++;
2241 if (NodesSincePoll >= NodesBetweenPolls)
2248 ss[ply+2].initKillers();
2250 if (Threads[threadID].printCurrentLine)
2251 print_current_line(ss, ply, threadID);
2255 // update_pv() is called whenever a search returns a value > alpha. It
2256 // updates the PV in the SearchStack object corresponding to the current
2259 void update_pv(SearchStack ss[], int ply) {
2260 assert(ply >= 0 && ply < PLY_MAX);
2262 ss[ply].pv[ply] = ss[ply].currentMove;
2264 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2265 ss[ply].pv[p] = ss[ply+1].pv[p];
2266 ss[ply].pv[p] = MOVE_NONE;
2270 // sp_update_pv() is a variant of update_pv for use at split points. The
2271 // difference between the two functions is that sp_update_pv also updates
2272 // the PV at the parent node.
2274 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2275 assert(ply >= 0 && ply < PLY_MAX);
2277 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2279 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2280 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2281 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2285 // connected_moves() tests whether two moves are 'connected' in the sense
2286 // that the first move somehow made the second move possible (for instance
2287 // if the moving piece is the same in both moves). The first move is
2288 // assumed to be the move that was made to reach the current position, while
2289 // the second move is assumed to be a move from the current position.
2291 bool connected_moves(const Position& pos, Move m1, Move m2) {
2293 Square f1, t1, f2, t2;
2296 assert(move_is_ok(m1));
2297 assert(move_is_ok(m2));
2299 if (m2 == MOVE_NONE)
2302 // Case 1: The moving piece is the same in both moves
2308 // Case 2: The destination square for m2 was vacated by m1
2314 // Case 3: Moving through the vacated square
2315 if ( piece_is_slider(pos.piece_on(f2))
2316 && bit_is_set(squares_between(f2, t2), f1))
2319 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2320 p = pos.piece_on(t1);
2321 if (bit_is_set(pos.attacks_from(p, t1), t2))
2324 // Case 5: Discovered check, checking piece is the piece moved in m1
2325 if ( piece_is_slider(p)
2326 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2327 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2329 Bitboard occ = pos.occupied_squares();
2330 Color us = pos.side_to_move();
2331 Square ksq = pos.king_square(us);
2332 clear_bit(&occ, f2);
2333 if (type_of_piece(p) == BISHOP)
2335 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2338 else if (type_of_piece(p) == ROOK)
2340 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2345 assert(type_of_piece(p) == QUEEN);
2346 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2354 // value_is_mate() checks if the given value is a mate one
2355 // eventually compensated for the ply.
2357 bool value_is_mate(Value value) {
2359 assert(abs(value) <= VALUE_INFINITE);
2361 return value <= value_mated_in(PLY_MAX)
2362 || value >= value_mate_in(PLY_MAX);
2366 // move_is_killer() checks if the given move is among the
2367 // killer moves of that ply.
2369 bool move_is_killer(Move m, const SearchStack& ss) {
2371 const Move* k = ss.killers;
2372 for (int i = 0; i < KILLER_MAX; i++, k++)
2380 // extension() decides whether a move should be searched with normal depth,
2381 // or with extended depth. Certain classes of moves (checking moves, in
2382 // particular) are searched with bigger depth than ordinary moves and in
2383 // any case are marked as 'dangerous'. Note that also if a move is not
2384 // extended, as example because the corresponding UCI option is set to zero,
2385 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2387 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2388 bool check, bool singleReply, bool mateThreat, bool* dangerous) {
2390 assert(m != MOVE_NONE);
2392 Depth result = Depth(0);
2393 *dangerous = check | singleReply | mateThreat;
2398 result += CheckExtension[pvNode];
2401 result += SingleReplyExtension[pvNode];
2404 result += MateThreatExtension[pvNode];
2407 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2409 Color c = pos.side_to_move();
2410 if (relative_rank(c, move_to(m)) == RANK_7)
2412 result += PawnPushTo7thExtension[pvNode];
2415 if (pos.pawn_is_passed(c, move_to(m)))
2417 result += PassedPawnExtension[pvNode];
2422 if ( captureOrPromotion
2423 && pos.type_of_piece_on(move_to(m)) != PAWN
2424 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2425 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2426 && !move_is_promotion(m)
2429 result += PawnEndgameExtension[pvNode];
2434 && captureOrPromotion
2435 && pos.type_of_piece_on(move_to(m)) != PAWN
2436 && pos.see_sign(m) >= 0)
2442 return Min(result, OnePly);
2446 // ok_to_do_nullmove() looks at the current position and decides whether
2447 // doing a 'null move' should be allowed. In order to avoid zugzwang
2448 // problems, null moves are not allowed when the side to move has very
2449 // little material left. Currently, the test is a bit too simple: Null
2450 // moves are avoided only when the side to move has only pawns left. It's
2451 // probably a good idea to avoid null moves in at least some more
2452 // complicated endgames, e.g. KQ vs KR. FIXME
2454 bool ok_to_do_nullmove(const Position& pos) {
2456 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2460 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2461 // non-tactical moves late in the move list close to the leaves are
2462 // candidates for pruning.
2464 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2466 assert(move_is_ok(m));
2467 assert(threat == MOVE_NONE || move_is_ok(threat));
2468 assert(!pos.move_is_check(m));
2469 assert(!pos.move_is_capture_or_promotion(m));
2470 assert(!pos.move_is_passed_pawn_push(m));
2472 Square mfrom, mto, tfrom, tto;
2474 mfrom = move_from(m);
2476 tfrom = move_from(threat);
2477 tto = move_to(threat);
2479 // Case 1: Castling moves are never pruned
2480 if (move_is_castle(m))
2483 // Case 2: Don't prune moves which move the threatened piece
2484 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2487 // Case 3: If the threatened piece has value less than or equal to the
2488 // value of the threatening piece, don't prune move which defend it.
2489 if ( !PruneDefendingMoves
2490 && threat != MOVE_NONE
2491 && pos.move_is_capture(threat)
2492 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2493 || pos.type_of_piece_on(tfrom) == KING)
2494 && pos.move_attacks_square(m, tto))
2497 // Case 4: If the moving piece in the threatened move is a slider, don't
2498 // prune safe moves which block its ray.
2499 if ( !PruneBlockingMoves
2500 && threat != MOVE_NONE
2501 && piece_is_slider(pos.piece_on(tfrom))
2502 && bit_is_set(squares_between(tfrom, tto), mto)
2503 && pos.see_sign(m) >= 0)
2510 // ok_to_use_TT() returns true if a transposition table score
2511 // can be used at a given point in search.
2513 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2515 Value v = value_from_tt(tte->value(), ply);
2517 return ( tte->depth() >= depth
2518 || v >= Max(value_mate_in(PLY_MAX), beta)
2519 || v < Min(value_mated_in(PLY_MAX), beta))
2521 && ( (is_lower_bound(tte->type()) && v >= beta)
2522 || (is_upper_bound(tte->type()) && v < beta));
2526 // update_history() registers a good move that produced a beta-cutoff
2527 // in history and marks as failures all the other moves of that ply.
2529 void update_history(const Position& pos, Move m, Depth depth,
2530 Move movesSearched[], int moveCount) {
2532 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2534 for (int i = 0; i < moveCount - 1; i++)
2536 assert(m != movesSearched[i]);
2537 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2538 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]), depth);
2543 // update_killers() add a good move that produced a beta-cutoff
2544 // among the killer moves of that ply.
2546 void update_killers(Move m, SearchStack& ss) {
2548 if (m == ss.killers[0])
2551 for (int i = KILLER_MAX - 1; i > 0; i--)
2552 ss.killers[i] = ss.killers[i - 1];
2558 // fail_high_ply_1() checks if some thread is currently resolving a fail
2559 // high at ply 1 at the node below the first root node. This information
2560 // is used for time managment.
2562 bool fail_high_ply_1() {
2564 for(int i = 0; i < ActiveThreads; i++)
2565 if (Threads[i].failHighPly1)
2572 // current_search_time() returns the number of milliseconds which have passed
2573 // since the beginning of the current search.
2575 int current_search_time() {
2576 return get_system_time() - SearchStartTime;
2580 // nps() computes the current nodes/second count.
2583 int t = current_search_time();
2584 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2588 // poll() performs two different functions: It polls for user input, and it
2589 // looks at the time consumed so far and decides if it's time to abort the
2594 static int lastInfoTime;
2595 int t = current_search_time();
2600 // We are line oriented, don't read single chars
2601 std::string command;
2602 if (!std::getline(std::cin, command))
2605 if (command == "quit")
2608 PonderSearch = false;
2612 else if (command == "stop")
2615 PonderSearch = false;
2617 else if (command == "ponderhit")
2620 // Print search information
2624 else if (lastInfoTime > t)
2625 // HACK: Must be a new search where we searched less than
2626 // NodesBetweenPolls nodes during the first second of search.
2629 else if (t - lastInfoTime >= 1000)
2636 if (dbg_show_hit_rate)
2637 dbg_print_hit_rate();
2639 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2640 << " time " << t << " hashfull " << TT.full() << std::endl;
2641 lock_release(&IOLock);
2642 if (ShowCurrentLine)
2643 Threads[0].printCurrentLine = true;
2645 // Should we stop the search?
2649 bool overTime = t > AbsoluteMaxSearchTime
2650 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2651 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2652 && t > 6*(MaxSearchTime + ExtraSearchTime));
2654 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2655 || (ExactMaxTime && t >= ExactMaxTime)
2656 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2661 // ponderhit() is called when the program is pondering (i.e. thinking while
2662 // it's the opponent's turn to move) in order to let the engine know that
2663 // it correctly predicted the opponent's move.
2667 int t = current_search_time();
2668 PonderSearch = false;
2669 if (Iteration >= 3 &&
2670 (!InfiniteSearch && (StopOnPonderhit ||
2671 t > AbsoluteMaxSearchTime ||
2672 (RootMoveNumber == 1 &&
2673 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2674 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2675 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2680 // print_current_line() prints the current line of search for a given
2681 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2683 void print_current_line(SearchStack ss[], int ply, int threadID) {
2685 assert(ply >= 0 && ply < PLY_MAX);
2686 assert(threadID >= 0 && threadID < ActiveThreads);
2688 if (!Threads[threadID].idle)
2691 std::cout << "info currline " << (threadID + 1);
2692 for (int p = 0; p < ply; p++)
2693 std::cout << " " << ss[p].currentMove;
2695 std::cout << std::endl;
2696 lock_release(&IOLock);
2698 Threads[threadID].printCurrentLine = false;
2699 if (threadID + 1 < ActiveThreads)
2700 Threads[threadID + 1].printCurrentLine = true;
2704 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2706 void init_ss_array(SearchStack ss[]) {
2708 for (int i = 0; i < 3; i++)
2711 ss[i].initKillers();
2716 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2717 // while the program is pondering. The point is to work around a wrinkle in
2718 // the UCI protocol: When pondering, the engine is not allowed to give a
2719 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2720 // We simply wait here until one of these commands is sent, and return,
2721 // after which the bestmove and pondermove will be printed (in id_loop()).
2723 void wait_for_stop_or_ponderhit() {
2725 std::string command;
2729 if (!std::getline(std::cin, command))
2732 if (command == "quit")
2737 else if (command == "ponderhit" || command == "stop")
2743 // idle_loop() is where the threads are parked when they have no work to do.
2744 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2745 // object for which the current thread is the master.
2747 void idle_loop(int threadID, SplitPoint* waitSp) {
2748 assert(threadID >= 0 && threadID < THREAD_MAX);
2750 Threads[threadID].running = true;
2753 if(AllThreadsShouldExit && threadID != 0)
2756 // If we are not thinking, wait for a condition to be signaled instead
2757 // of wasting CPU time polling for work:
2758 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2759 #if !defined(_MSC_VER)
2760 pthread_mutex_lock(&WaitLock);
2761 if(Idle || threadID >= ActiveThreads)
2762 pthread_cond_wait(&WaitCond, &WaitLock);
2763 pthread_mutex_unlock(&WaitLock);
2765 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2769 // If this thread has been assigned work, launch a search
2770 if(Threads[threadID].workIsWaiting) {
2771 Threads[threadID].workIsWaiting = false;
2772 if(Threads[threadID].splitPoint->pvNode)
2773 sp_search_pv(Threads[threadID].splitPoint, threadID);
2775 sp_search(Threads[threadID].splitPoint, threadID);
2776 Threads[threadID].idle = true;
2779 // If this thread is the master of a split point and all threads have
2780 // finished their work at this split point, return from the idle loop.
2781 if(waitSp != NULL && waitSp->cpus == 0)
2785 Threads[threadID].running = false;
2789 // init_split_point_stack() is called during program initialization, and
2790 // initializes all split point objects.
2792 void init_split_point_stack() {
2793 for(int i = 0; i < THREAD_MAX; i++)
2794 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2795 SplitPointStack[i][j].parent = NULL;
2796 lock_init(&(SplitPointStack[i][j].lock), NULL);
2801 // destroy_split_point_stack() is called when the program exits, and
2802 // destroys all locks in the precomputed split point objects.
2804 void destroy_split_point_stack() {
2805 for(int i = 0; i < THREAD_MAX; i++)
2806 for(int j = 0; j < MaxActiveSplitPoints; j++)
2807 lock_destroy(&(SplitPointStack[i][j].lock));
2811 // thread_should_stop() checks whether the thread with a given threadID has
2812 // been asked to stop, directly or indirectly. This can happen if a beta
2813 // cutoff has occured in thre thread's currently active split point, or in
2814 // some ancestor of the current split point.
2816 bool thread_should_stop(int threadID) {
2817 assert(threadID >= 0 && threadID < ActiveThreads);
2821 if(Threads[threadID].stop)
2823 if(ActiveThreads <= 2)
2825 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2827 Threads[threadID].stop = true;
2834 // thread_is_available() checks whether the thread with threadID "slave" is
2835 // available to help the thread with threadID "master" at a split point. An
2836 // obvious requirement is that "slave" must be idle. With more than two
2837 // threads, this is not by itself sufficient: If "slave" is the master of
2838 // some active split point, it is only available as a slave to the other
2839 // threads which are busy searching the split point at the top of "slave"'s
2840 // split point stack (the "helpful master concept" in YBWC terminology).
2842 bool thread_is_available(int slave, int master) {
2843 assert(slave >= 0 && slave < ActiveThreads);
2844 assert(master >= 0 && master < ActiveThreads);
2845 assert(ActiveThreads > 1);
2847 if(!Threads[slave].idle || slave == master)
2850 if(Threads[slave].activeSplitPoints == 0)
2851 // No active split points means that the thread is available as a slave
2852 // for any other thread.
2855 if(ActiveThreads == 2)
2858 // Apply the "helpful master" concept if possible.
2859 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2866 // idle_thread_exists() tries to find an idle thread which is available as
2867 // a slave for the thread with threadID "master".
2869 bool idle_thread_exists(int master) {
2870 assert(master >= 0 && master < ActiveThreads);
2871 assert(ActiveThreads > 1);
2873 for(int i = 0; i < ActiveThreads; i++)
2874 if(thread_is_available(i, master))
2880 // split() does the actual work of distributing the work at a node between
2881 // several threads at PV nodes. If it does not succeed in splitting the
2882 // node (because no idle threads are available, or because we have no unused
2883 // split point objects), the function immediately returns false. If
2884 // splitting is possible, a SplitPoint object is initialized with all the
2885 // data that must be copied to the helper threads (the current position and
2886 // search stack, alpha, beta, the search depth, etc.), and we tell our
2887 // helper threads that they have been assigned work. This will cause them
2888 // to instantly leave their idle loops and call sp_search_pv(). When all
2889 // threads have returned from sp_search_pv (or, equivalently, when
2890 // splitPoint->cpus becomes 0), split() returns true.
2892 bool split(const Position& p, SearchStack* sstck, int ply,
2893 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2894 const Value approximateEval, Depth depth, int* moves,
2895 MovePicker* mp, int master, bool pvNode) {
2898 assert(sstck != NULL);
2899 assert(ply >= 0 && ply < PLY_MAX);
2900 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2901 assert(!pvNode || *alpha < *beta);
2902 assert(*beta <= VALUE_INFINITE);
2903 assert(depth > Depth(0));
2904 assert(master >= 0 && master < ActiveThreads);
2905 assert(ActiveThreads > 1);
2907 SplitPoint* splitPoint;
2912 // If no other thread is available to help us, or if we have too many
2913 // active split points, don't split.
2914 if(!idle_thread_exists(master) ||
2915 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2916 lock_release(&MPLock);
2920 // Pick the next available split point object from the split point stack
2921 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2922 Threads[master].activeSplitPoints++;
2924 // Initialize the split point object
2925 splitPoint->parent = Threads[master].splitPoint;
2926 splitPoint->finished = false;
2927 splitPoint->ply = ply;
2928 splitPoint->depth = depth;
2929 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2930 splitPoint->beta = *beta;
2931 splitPoint->pvNode = pvNode;
2932 splitPoint->bestValue = *bestValue;
2933 splitPoint->futilityValue = futilityValue;
2934 splitPoint->approximateEval = approximateEval;
2935 splitPoint->master = master;
2936 splitPoint->mp = mp;
2937 splitPoint->moves = *moves;
2938 splitPoint->cpus = 1;
2939 splitPoint->pos.copy(p);
2940 splitPoint->parentSstack = sstck;
2941 for(i = 0; i < ActiveThreads; i++)
2942 splitPoint->slaves[i] = 0;
2944 // Copy the current position and the search stack to the master thread
2945 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2946 Threads[master].splitPoint = splitPoint;
2948 // Make copies of the current position and search stack for each thread
2949 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2951 if(thread_is_available(i, master)) {
2952 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2953 Threads[i].splitPoint = splitPoint;
2954 splitPoint->slaves[i] = 1;
2958 // Tell the threads that they have work to do. This will make them leave
2960 for(i = 0; i < ActiveThreads; i++)
2961 if(i == master || splitPoint->slaves[i]) {
2962 Threads[i].workIsWaiting = true;
2963 Threads[i].idle = false;
2964 Threads[i].stop = false;
2967 lock_release(&MPLock);
2969 // Everything is set up. The master thread enters the idle loop, from
2970 // which it will instantly launch a search, because its workIsWaiting
2971 // slot is 'true'. We send the split point as a second parameter to the
2972 // idle loop, which means that the main thread will return from the idle
2973 // loop when all threads have finished their work at this split point
2974 // (i.e. when // splitPoint->cpus == 0).
2975 idle_loop(master, splitPoint);
2977 // We have returned from the idle loop, which means that all threads are
2978 // finished. Update alpha, beta and bestvalue, and return.
2980 if(pvNode) *alpha = splitPoint->alpha;
2981 *beta = splitPoint->beta;
2982 *bestValue = splitPoint->bestValue;
2983 Threads[master].stop = false;
2984 Threads[master].idle = false;
2985 Threads[master].activeSplitPoints--;
2986 Threads[master].splitPoint = splitPoint->parent;
2987 lock_release(&MPLock);
2993 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2994 // to start a new search from the root.
2996 void wake_sleeping_threads() {
2997 if(ActiveThreads > 1) {
2998 for(int i = 1; i < ActiveThreads; i++) {
2999 Threads[i].idle = true;
3000 Threads[i].workIsWaiting = false;
3002 #if !defined(_MSC_VER)
3003 pthread_mutex_lock(&WaitLock);
3004 pthread_cond_broadcast(&WaitCond);
3005 pthread_mutex_unlock(&WaitLock);
3007 for(int i = 1; i < THREAD_MAX; i++)
3008 SetEvent(SitIdleEvent[i]);
3014 // init_thread() is the function which is called when a new thread is
3015 // launched. It simply calls the idle_loop() function with the supplied
3016 // threadID. There are two versions of this function; one for POSIX threads
3017 // and one for Windows threads.
3019 #if !defined(_MSC_VER)
3021 void *init_thread(void *threadID) {
3022 idle_loop(*(int *)threadID, NULL);
3028 DWORD WINAPI init_thread(LPVOID threadID) {
3029 idle_loop(*(int *)threadID, NULL);