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. This is to avoid problems in
1125 // the following areas:
1127 // * Repetition draw detection
1128 // * Fifty move rule detection
1129 // * Searching for a mate
1130 // * Printing of full PV line
1132 tte = TT.retrieve(pos.get_key());
1133 ttMove = (tte ? tte->move() : MOVE_NONE);
1135 // Go with internal iterative deepening if we don't have a TT move
1136 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1138 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1139 ttMove = ss[ply].pv[ply];
1142 // Initialize a MovePicker object for the current position, and prepare
1143 // to search all moves
1144 isCheck = pos.is_check();
1145 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1147 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1149 // Loop through all legal moves until no moves remain or a beta cutoff
1151 while ( alpha < beta
1152 && (move = mp.get_next_move()) != MOVE_NONE
1153 && !thread_should_stop(threadID))
1155 assert(move_is_ok(move));
1157 singleReply = (isCheck && mp.number_of_evasions() == 1);
1158 moveIsCheck = pos.move_is_check(move, ci);
1159 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1161 // Decide the new search depth
1162 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1164 // We want to extend the TT move if it is much better then remaining ones.
1165 // To verify this we do a reduced search on all the other moves but the ttMove,
1166 // if result is lower then TT value minus a margin then we assume ttMove is the
1167 // only one playable. It is a kind of relaxed single reply extension.
1168 if ( depth >= 8 * OnePly
1171 && is_lower_bound(tte->type())
1172 && tte->depth() >= depth - 3 * OnePly)
1174 Value ttValue = value_from_tt(tte->value(), ply);
1176 if (abs(ttValue) < VALUE_KNOWN_WIN)
1178 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, ttMove);
1180 // If search result is well below the foreseen score of the ttMove then we
1181 // assume ttMove is the only one realistically playable and we extend it.
1182 if (excValue < ttValue - SingleReplyMargin)
1187 newDepth = depth - OnePly + ext;
1189 // Update current move
1190 movesSearched[moveCount++] = ss[ply].currentMove = move;
1192 // Make and search the move
1193 pos.do_move(move, st, ci, moveIsCheck);
1195 if (moveCount == 1) // The first move in list is the PV
1196 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1199 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1200 // if the move fails high will be re-searched at full depth.
1201 if ( depth >= 3*OnePly
1202 && moveCount >= LMRPVMoves
1204 && !captureOrPromotion
1205 && !move_is_castle(move)
1206 && !move_is_killer(move, ss[ply]))
1208 ss[ply].reduction = OnePly;
1209 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1212 value = alpha + 1; // Just to trigger next condition
1214 if (value > alpha) // Go with full depth non-pv search
1216 ss[ply].reduction = Depth(0);
1217 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1218 if (value > alpha && value < beta)
1220 // When the search fails high at ply 1 while searching the first
1221 // move at the root, set the flag failHighPly1. This is used for
1222 // time managment: We don't want to stop the search early in
1223 // such cases, because resolving the fail high at ply 1 could
1224 // result in a big drop in score at the root.
1225 if (ply == 1 && RootMoveNumber == 1)
1226 Threads[threadID].failHighPly1 = true;
1228 // A fail high occurred. Re-search at full window (pv search)
1229 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1230 Threads[threadID].failHighPly1 = false;
1234 pos.undo_move(move);
1236 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1239 if (value > bestValue)
1246 if (value == value_mate_in(ply + 1))
1247 ss[ply].mateKiller = move;
1249 // If we are at ply 1, and we are searching the first root move at
1250 // ply 0, set the 'Problem' variable if the score has dropped a lot
1251 // (from the computer's point of view) since the previous iteration.
1254 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1259 if ( ActiveThreads > 1
1261 && depth >= MinimumSplitDepth
1263 && idle_thread_exists(threadID)
1265 && !thread_should_stop(threadID)
1266 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE,
1267 depth, &moveCount, &mp, threadID, true))
1271 // All legal moves have been searched. A special case: If there were
1272 // no legal moves, it must be mate or stalemate.
1274 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1276 // If the search is not aborted, update the transposition table,
1277 // history counters, and killer moves.
1278 if (AbortSearch || thread_should_stop(threadID))
1281 if (bestValue <= oldAlpha)
1282 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1284 else if (bestValue >= beta)
1286 BetaCounter.add(pos.side_to_move(), depth, threadID);
1287 move = ss[ply].pv[ply];
1288 if (!pos.move_is_capture_or_promotion(move))
1290 update_history(pos, move, depth, movesSearched, moveCount);
1291 update_killers(move, ss[ply]);
1293 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1296 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1302 // search() is the search function for zero-width nodes.
1304 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1305 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1307 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1308 assert(ply >= 0 && ply < PLY_MAX);
1309 assert(threadID >= 0 && threadID < ActiveThreads);
1311 Move movesSearched[256];
1316 Depth ext, newDepth;
1317 Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1318 bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1319 bool mateThreat = false;
1321 Value bestValue = -VALUE_INFINITE;
1324 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1326 // Initialize, and make an early exit in case of an aborted search,
1327 // an instant draw, maximum ply reached, etc.
1328 init_node(ss, ply, threadID);
1330 // After init_node() that calls poll()
1331 if (AbortSearch || thread_should_stop(threadID))
1337 if (ply >= PLY_MAX - 1)
1338 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1340 // Mate distance pruning
1341 if (value_mated_in(ply) >= beta)
1344 if (value_mate_in(ply + 1) < beta)
1347 // We don't want the score of a partial search to overwrite a previous full search
1348 // TT value, so we use a different position key in case of an excluded move exsists.
1349 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1351 // Transposition table lookup
1352 tte = TT.retrieve(posKey);
1353 ttMove = (tte ? tte->move() : MOVE_NONE);
1355 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1357 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1358 return value_from_tt(tte->value(), ply);
1361 approximateEval = quick_evaluate(pos);
1362 isCheck = pos.is_check();
1368 && !value_is_mate(beta)
1369 && ok_to_do_nullmove(pos)
1370 && approximateEval >= beta - NullMoveMargin)
1372 ss[ply].currentMove = MOVE_NULL;
1374 pos.do_null_move(st);
1376 // Null move dynamic reduction based on depth
1377 int R = (depth >= 5 * OnePly ? 4 : 3);
1379 // Null move dynamic reduction based on value
1380 if (approximateEval - beta > PawnValueMidgame)
1383 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1385 pos.undo_null_move();
1387 if (nullValue >= beta)
1389 if (depth < 6 * OnePly)
1392 // Do zugzwang verification search
1393 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1397 // The null move failed low, which means that we may be faced with
1398 // some kind of threat. If the previous move was reduced, check if
1399 // the move that refuted the null move was somehow connected to the
1400 // move which was reduced. If a connection is found, return a fail
1401 // low score (which will cause the reduced move to fail high in the
1402 // parent node, which will trigger a re-search with full depth).
1403 if (nullValue == value_mated_in(ply + 2))
1406 ss[ply].threatMove = ss[ply + 1].currentMove;
1407 if ( depth < ThreatDepth
1408 && ss[ply - 1].reduction
1409 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1413 // Null move search not allowed, try razoring
1414 else if ( !value_is_mate(beta)
1415 && depth < RazorDepth
1416 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1417 && ss[ply - 1].currentMove != MOVE_NULL
1418 && ttMove == MOVE_NONE
1419 && !pos.has_pawn_on_7th(pos.side_to_move()))
1421 Value rbeta = beta - RazorMargins[int(depth) - 2];
1422 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1427 // Go with internal iterative deepening if we don't have a TT move
1428 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1429 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1431 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1432 ttMove = ss[ply].pv[ply];
1435 // Initialize a MovePicker object for the current position, and prepare
1436 // to search all moves.
1437 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1439 futilityValue = VALUE_NONE;
1440 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1442 // Avoid calling evaluate() if we already have the score in TT
1443 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1444 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1446 // Move count pruning limit
1447 const int MCLimit = 3 + (1 << (3*int(depth)/8));
1449 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1450 while ( bestValue < beta
1451 && (move = mp.get_next_move()) != MOVE_NONE
1452 && !thread_should_stop(threadID))
1454 assert(move_is_ok(move));
1456 if (move == excludedMove)
1459 singleReply = (isCheck && mp.number_of_evasions() == 1);
1460 moveIsCheck = pos.move_is_check(move, ci);
1461 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1463 // Decide the new search depth
1464 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1466 // We want to extend the TT move if it is much better then remaining ones.
1467 // To verify this we do a reduced search on all the other moves but the ttMove,
1468 // if result is lower then TT value minus a margin then we assume ttMove is the
1469 // only one playable. It is a kind of relaxed single reply extension.
1470 if ( depth >= 8 * OnePly
1471 && !excludedMove // do not allow recursive single-reply search
1474 && is_lower_bound(tte->type())
1475 && tte->depth() >= depth - 3 * OnePly)
1477 Value ttValue = value_from_tt(tte->value(), ply);
1479 if (abs(ttValue) < VALUE_KNOWN_WIN)
1481 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, ttMove);
1483 // If search result is well below the foreseen score of the ttMove then we
1484 // assume ttMove is the only one realistically playable and we extend it.
1485 if (excValue < ttValue - SingleReplyMargin)
1490 newDepth = depth - OnePly + ext;
1492 // Update current move
1493 movesSearched[moveCount++] = ss[ply].currentMove = move;
1496 if ( useFutilityPruning
1498 && !captureOrPromotion
1501 // History pruning. See ok_to_prune() definition
1502 if ( moveCount >= MCLimit
1503 && ok_to_prune(pos, move, ss[ply].threatMove, depth)
1504 && bestValue > value_mated_in(PLY_MAX))
1507 // Value based pruning
1508 if (approximateEval < beta)
1510 if (futilityValue == VALUE_NONE)
1511 futilityValue = evaluate(pos, ei, threadID)
1512 + 64*(2+bitScanReverse32(int(depth) * int(depth)));
1514 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1516 if (futilityValueScaled < beta)
1518 if (futilityValueScaled > bestValue)
1519 bestValue = futilityValueScaled;
1525 // Make and search the move
1526 pos.do_move(move, st, ci, moveIsCheck);
1528 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1529 // if the move fails high will be re-searched at full depth.
1530 if ( depth >= 3*OnePly
1531 && moveCount >= LMRNonPVMoves
1533 && !captureOrPromotion
1534 && !move_is_castle(move)
1535 && !move_is_killer(move, ss[ply]))
1537 ss[ply].reduction = OnePly;
1538 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1541 value = beta; // Just to trigger next condition
1543 if (value >= beta) // Go with full depth non-pv search
1545 ss[ply].reduction = Depth(0);
1546 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1548 pos.undo_move(move);
1550 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1553 if (value > bestValue)
1559 if (value == value_mate_in(ply + 1))
1560 ss[ply].mateKiller = move;
1564 if ( ActiveThreads > 1
1566 && depth >= MinimumSplitDepth
1568 && idle_thread_exists(threadID)
1570 && !thread_should_stop(threadID)
1571 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval,
1572 depth, &moveCount, &mp, threadID, false))
1576 // All legal moves have been searched. A special case: If there were
1577 // no legal moves, it must be mate or stalemate.
1579 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1581 // If the search is not aborted, update the transposition table,
1582 // history counters, and killer moves.
1583 if (AbortSearch || thread_should_stop(threadID))
1586 if (bestValue < beta)
1587 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1590 BetaCounter.add(pos.side_to_move(), depth, threadID);
1591 move = ss[ply].pv[ply];
1592 if (!pos.move_is_capture_or_promotion(move))
1594 update_history(pos, move, depth, movesSearched, moveCount);
1595 update_killers(move, ss[ply]);
1597 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1600 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1606 // qsearch() is the quiescence search function, which is called by the main
1607 // search function when the remaining depth is zero (or, to be more precise,
1608 // less than OnePly).
1610 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1611 Depth depth, int ply, int threadID) {
1613 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1614 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1616 assert(ply >= 0 && ply < PLY_MAX);
1617 assert(threadID >= 0 && threadID < ActiveThreads);
1622 Value staticValue, bestValue, value, futilityValue;
1623 bool isCheck, enoughMaterial, moveIsCheck;
1624 const TTEntry* tte = NULL;
1626 bool pvNode = (beta - alpha != 1);
1628 // Initialize, and make an early exit in case of an aborted search,
1629 // an instant draw, maximum ply reached, etc.
1630 init_node(ss, ply, threadID);
1632 // After init_node() that calls poll()
1633 if (AbortSearch || thread_should_stop(threadID))
1639 // Transposition table lookup, only when not in PV
1642 tte = TT.retrieve(pos.get_key());
1643 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1645 assert(tte->type() != VALUE_TYPE_EVAL);
1647 return value_from_tt(tte->value(), ply);
1650 ttMove = (tte ? tte->move() : MOVE_NONE);
1652 // Evaluate the position statically
1653 isCheck = pos.is_check();
1654 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1657 staticValue = -VALUE_INFINITE;
1659 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1661 // Use the cached evaluation score if possible
1662 assert(ei.futilityMargin == Value(0));
1664 staticValue = tte->value();
1667 staticValue = evaluate(pos, ei, threadID);
1669 if (ply >= PLY_MAX - 1)
1670 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1672 // Initialize "stand pat score", and return it immediately if it is
1674 bestValue = staticValue;
1676 if (bestValue >= beta)
1678 // Store the score to avoid a future costly evaluation() call
1679 if (!isCheck && !tte && ei.futilityMargin == 0)
1680 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1685 if (bestValue > alpha)
1688 // Initialize a MovePicker object for the current position, and prepare
1689 // to search the moves. Because the depth is <= 0 here, only captures,
1690 // queen promotions and checks (only if depth == 0) will be generated.
1691 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1693 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1695 // Loop through the moves until no moves remain or a beta cutoff
1697 while ( alpha < beta
1698 && (move = mp.get_next_move()) != MOVE_NONE)
1700 assert(move_is_ok(move));
1703 ss[ply].currentMove = move;
1705 moveIsCheck = pos.move_is_check(move, ci);
1713 && !move_is_promotion(move)
1714 && !pos.move_is_passed_pawn_push(move))
1716 futilityValue = staticValue
1717 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1718 pos.endgame_value_of_piece_on(move_to(move)))
1719 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1721 + ei.futilityMargin;
1723 if (futilityValue < alpha)
1725 if (futilityValue > bestValue)
1726 bestValue = futilityValue;
1731 // Don't search captures and checks with negative SEE values
1734 && !move_is_promotion(move)
1735 && pos.see_sign(move) < 0)
1738 // Make and search the move
1739 pos.do_move(move, st, ci, moveIsCheck);
1740 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1741 pos.undo_move(move);
1743 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1746 if (value > bestValue)
1757 // All legal moves have been searched. A special case: If we're in check
1758 // and no legal moves were found, it is checkmate.
1759 if (!moveCount && pos.is_check()) // Mate!
1760 return value_mated_in(ply);
1762 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1764 // Update transposition table
1765 move = ss[ply].pv[ply];
1768 // If bestValue isn't changed it means it is still the static evaluation of
1769 // the node, so keep this info to avoid a future costly evaluation() call.
1770 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1771 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1773 if (bestValue < beta)
1774 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1776 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1779 // Update killers only for good check moves
1780 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1781 update_killers(move, ss[ply]);
1787 // sp_search() is used to search from a split point. This function is called
1788 // by each thread working at the split point. It is similar to the normal
1789 // search() function, but simpler. Because we have already probed the hash
1790 // table, done a null move search, and searched the first move before
1791 // splitting, we don't have to repeat all this work in sp_search(). We
1792 // also don't need to store anything to the hash table here: This is taken
1793 // care of after we return from the split point.
1795 void sp_search(SplitPoint* sp, int threadID) {
1797 assert(threadID >= 0 && threadID < ActiveThreads);
1798 assert(ActiveThreads > 1);
1800 Position pos = Position(sp->pos);
1802 SearchStack* ss = sp->sstack[threadID];
1805 bool isCheck = pos.is_check();
1806 bool useFutilityPruning = sp->depth < SelectiveDepth
1809 while ( sp->bestValue < sp->beta
1810 && !thread_should_stop(threadID)
1811 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1813 assert(move_is_ok(move));
1815 bool moveIsCheck = pos.move_is_check(move, ci);
1816 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1818 lock_grab(&(sp->lock));
1819 int moveCount = ++sp->moves;
1820 lock_release(&(sp->lock));
1822 ss[sp->ply].currentMove = move;
1824 // Decide the new search depth.
1826 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1827 Depth newDepth = sp->depth - OnePly + ext;
1830 if ( useFutilityPruning
1832 && !captureOrPromotion)
1834 // History pruning. See ok_to_prune() definition
1835 if ( moveCount >= 2 + int(sp->depth)
1836 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)
1837 && sp->bestValue > value_mated_in(PLY_MAX))
1840 // Value based pruning
1841 if (sp->approximateEval < sp->beta)
1843 if (sp->futilityValue == VALUE_NONE)
1846 sp->futilityValue = evaluate(pos, ei, threadID)
1847 + FutilityMargins[int(sp->depth) - 2];
1850 if (sp->futilityValue < sp->beta)
1852 if (sp->futilityValue > sp->bestValue) // Less then 1% of cases
1854 lock_grab(&(sp->lock));
1855 if (sp->futilityValue > sp->bestValue)
1856 sp->bestValue = sp->futilityValue;
1857 lock_release(&(sp->lock));
1864 // Make and search the move.
1866 pos.do_move(move, st, ci, moveIsCheck);
1868 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1869 // if the move fails high will be re-searched at full depth.
1871 && moveCount >= LMRNonPVMoves
1872 && !captureOrPromotion
1873 && !move_is_castle(move)
1874 && !move_is_killer(move, ss[sp->ply]))
1876 ss[sp->ply].reduction = OnePly;
1877 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1880 value = sp->beta; // Just to trigger next condition
1882 if (value >= sp->beta) // Go with full depth non-pv search
1884 ss[sp->ply].reduction = Depth(0);
1885 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1887 pos.undo_move(move);
1889 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1891 if (thread_should_stop(threadID))
1895 if (value > sp->bestValue) // Less then 2% of cases
1897 lock_grab(&(sp->lock));
1898 if (value > sp->bestValue && !thread_should_stop(threadID))
1900 sp->bestValue = value;
1901 if (sp->bestValue >= sp->beta)
1903 sp_update_pv(sp->parentSstack, ss, sp->ply);
1904 for (int i = 0; i < ActiveThreads; i++)
1905 if (i != threadID && (i == sp->master || sp->slaves[i]))
1906 Threads[i].stop = true;
1908 sp->finished = true;
1911 lock_release(&(sp->lock));
1915 lock_grab(&(sp->lock));
1917 // If this is the master thread and we have been asked to stop because of
1918 // a beta cutoff higher up in the tree, stop all slave threads.
1919 if (sp->master == threadID && thread_should_stop(threadID))
1920 for (int i = 0; i < ActiveThreads; i++)
1922 Threads[i].stop = true;
1925 sp->slaves[threadID] = 0;
1927 lock_release(&(sp->lock));
1931 // sp_search_pv() is used to search from a PV split point. This function
1932 // is called by each thread working at the split point. It is similar to
1933 // the normal search_pv() function, but simpler. Because we have already
1934 // probed the hash table and searched the first move before splitting, we
1935 // don't have to repeat all this work in sp_search_pv(). We also don't
1936 // need to store anything to the hash table here: This is taken care of
1937 // after we return from the split point.
1939 void sp_search_pv(SplitPoint* sp, int threadID) {
1941 assert(threadID >= 0 && threadID < ActiveThreads);
1942 assert(ActiveThreads > 1);
1944 Position pos = Position(sp->pos);
1946 SearchStack* ss = sp->sstack[threadID];
1950 while ( sp->alpha < sp->beta
1951 && !thread_should_stop(threadID)
1952 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1954 bool moveIsCheck = pos.move_is_check(move, ci);
1955 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1957 assert(move_is_ok(move));
1959 lock_grab(&(sp->lock));
1960 int moveCount = ++sp->moves;
1961 lock_release(&(sp->lock));
1963 ss[sp->ply].currentMove = move;
1965 // Decide the new search depth.
1967 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1968 Depth newDepth = sp->depth - OnePly + ext;
1970 // Make and search the move.
1972 pos.do_move(move, st, ci, moveIsCheck);
1974 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1975 // if the move fails high will be re-searched at full depth.
1977 && moveCount >= LMRPVMoves
1978 && !captureOrPromotion
1979 && !move_is_castle(move)
1980 && !move_is_killer(move, ss[sp->ply]))
1982 ss[sp->ply].reduction = OnePly;
1983 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1986 value = sp->alpha + 1; // Just to trigger next condition
1988 if (value > sp->alpha) // Go with full depth non-pv search
1990 ss[sp->ply].reduction = Depth(0);
1991 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1993 if (value > sp->alpha && value < sp->beta)
1995 // When the search fails high at ply 1 while searching the first
1996 // move at the root, set the flag failHighPly1. This is used for
1997 // time managment: We don't want to stop the search early in
1998 // such cases, because resolving the fail high at ply 1 could
1999 // result in a big drop in score at the root.
2000 if (sp->ply == 1 && RootMoveNumber == 1)
2001 Threads[threadID].failHighPly1 = true;
2003 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2004 Threads[threadID].failHighPly1 = false;
2007 pos.undo_move(move);
2009 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2011 if (thread_should_stop(threadID))
2015 lock_grab(&(sp->lock));
2016 if (value > sp->bestValue && !thread_should_stop(threadID))
2018 sp->bestValue = value;
2019 if (value > sp->alpha)
2022 sp_update_pv(sp->parentSstack, ss, sp->ply);
2023 if (value == value_mate_in(sp->ply + 1))
2024 ss[sp->ply].mateKiller = move;
2026 if (value >= sp->beta)
2028 for (int i = 0; i < ActiveThreads; i++)
2029 if (i != threadID && (i == sp->master || sp->slaves[i]))
2030 Threads[i].stop = true;
2032 sp->finished = true;
2035 // If we are at ply 1, and we are searching the first root move at
2036 // ply 0, set the 'Problem' variable if the score has dropped a lot
2037 // (from the computer's point of view) since the previous iteration.
2040 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2043 lock_release(&(sp->lock));
2046 lock_grab(&(sp->lock));
2048 // If this is the master thread and we have been asked to stop because of
2049 // a beta cutoff higher up in the tree, stop all slave threads.
2050 if (sp->master == threadID && thread_should_stop(threadID))
2051 for (int i = 0; i < ActiveThreads; i++)
2053 Threads[i].stop = true;
2056 sp->slaves[threadID] = 0;
2058 lock_release(&(sp->lock));
2061 /// The BetaCounterType class
2063 BetaCounterType::BetaCounterType() { clear(); }
2065 void BetaCounterType::clear() {
2067 for (int i = 0; i < THREAD_MAX; i++)
2068 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2071 void BetaCounterType::add(Color us, Depth d, int threadID) {
2073 // Weighted count based on depth
2074 Threads[threadID].betaCutOffs[us] += unsigned(d);
2077 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2080 for (int i = 0; i < THREAD_MAX; i++)
2082 our += Threads[i].betaCutOffs[us];
2083 their += Threads[i].betaCutOffs[opposite_color(us)];
2088 /// The RootMove class
2092 RootMove::RootMove() {
2093 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
2096 // RootMove::operator<() is the comparison function used when
2097 // sorting the moves. A move m1 is considered to be better
2098 // than a move m2 if it has a higher score, or if the moves
2099 // have equal score but m1 has the higher node count.
2101 bool RootMove::operator<(const RootMove& m) {
2103 if (score != m.score)
2104 return (score < m.score);
2106 return theirBeta <= m.theirBeta;
2109 /// The RootMoveList class
2113 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2115 MoveStack mlist[MaxRootMoves];
2116 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2118 // Generate all legal moves
2119 MoveStack* last = generate_moves(pos, mlist);
2121 // Add each move to the moves[] array
2122 for (MoveStack* cur = mlist; cur != last; cur++)
2124 bool includeMove = includeAllMoves;
2126 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2127 includeMove = (searchMoves[k] == cur->move);
2132 // Find a quick score for the move
2134 SearchStack ss[PLY_MAX_PLUS_2];
2137 moves[count].move = cur->move;
2138 pos.do_move(moves[count].move, st);
2139 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2140 pos.undo_move(moves[count].move);
2141 moves[count].pv[0] = moves[count].move;
2142 moves[count].pv[1] = MOVE_NONE;
2149 // Simple accessor methods for the RootMoveList class
2151 inline Move RootMoveList::get_move(int moveNum) const {
2152 return moves[moveNum].move;
2155 inline Value RootMoveList::get_move_score(int moveNum) const {
2156 return moves[moveNum].score;
2159 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2160 moves[moveNum].score = score;
2163 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2164 moves[moveNum].nodes = nodes;
2165 moves[moveNum].cumulativeNodes += nodes;
2168 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2169 moves[moveNum].ourBeta = our;
2170 moves[moveNum].theirBeta = their;
2173 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2175 for(j = 0; pv[j] != MOVE_NONE; j++)
2176 moves[moveNum].pv[j] = pv[j];
2177 moves[moveNum].pv[j] = MOVE_NONE;
2180 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2181 return moves[moveNum].pv[i];
2184 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2185 return moves[moveNum].cumulativeNodes;
2188 inline int RootMoveList::move_count() const {
2193 // RootMoveList::sort() sorts the root move list at the beginning of a new
2196 inline void RootMoveList::sort() {
2198 sort_multipv(count - 1); // all items
2202 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2203 // list by their scores and depths. It is used to order the different PVs
2204 // correctly in MultiPV mode.
2206 void RootMoveList::sort_multipv(int n) {
2208 for (int i = 1; i <= n; i++)
2210 RootMove rm = moves[i];
2212 for (j = i; j > 0 && moves[j-1] < rm; j--)
2213 moves[j] = moves[j-1];
2219 // init_node() is called at the beginning of all the search functions
2220 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2221 // stack object corresponding to the current node. Once every
2222 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2223 // for user input and checks whether it is time to stop the search.
2225 void init_node(SearchStack ss[], int ply, int threadID) {
2227 assert(ply >= 0 && ply < PLY_MAX);
2228 assert(threadID >= 0 && threadID < ActiveThreads);
2230 Threads[threadID].nodes++;
2235 if (NodesSincePoll >= NodesBetweenPolls)
2242 ss[ply+2].initKillers();
2244 if (Threads[threadID].printCurrentLine)
2245 print_current_line(ss, ply, threadID);
2249 // update_pv() is called whenever a search returns a value > alpha. It
2250 // updates the PV in the SearchStack object corresponding to the current
2253 void update_pv(SearchStack ss[], int ply) {
2254 assert(ply >= 0 && ply < PLY_MAX);
2256 ss[ply].pv[ply] = ss[ply].currentMove;
2258 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2259 ss[ply].pv[p] = ss[ply+1].pv[p];
2260 ss[ply].pv[p] = MOVE_NONE;
2264 // sp_update_pv() is a variant of update_pv for use at split points. The
2265 // difference between the two functions is that sp_update_pv also updates
2266 // the PV at the parent node.
2268 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2269 assert(ply >= 0 && ply < PLY_MAX);
2271 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2273 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2274 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2275 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2279 // connected_moves() tests whether two moves are 'connected' in the sense
2280 // that the first move somehow made the second move possible (for instance
2281 // if the moving piece is the same in both moves). The first move is
2282 // assumed to be the move that was made to reach the current position, while
2283 // the second move is assumed to be a move from the current position.
2285 bool connected_moves(const Position& pos, Move m1, Move m2) {
2287 Square f1, t1, f2, t2;
2290 assert(move_is_ok(m1));
2291 assert(move_is_ok(m2));
2293 if (m2 == MOVE_NONE)
2296 // Case 1: The moving piece is the same in both moves
2302 // Case 2: The destination square for m2 was vacated by m1
2308 // Case 3: Moving through the vacated square
2309 if ( piece_is_slider(pos.piece_on(f2))
2310 && bit_is_set(squares_between(f2, t2), f1))
2313 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2314 p = pos.piece_on(t1);
2315 if (bit_is_set(pos.attacks_from(p, t1), t2))
2318 // Case 5: Discovered check, checking piece is the piece moved in m1
2319 if ( piece_is_slider(p)
2320 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2321 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2323 Bitboard occ = pos.occupied_squares();
2324 Color us = pos.side_to_move();
2325 Square ksq = pos.king_square(us);
2326 clear_bit(&occ, f2);
2327 if (type_of_piece(p) == BISHOP)
2329 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2332 else if (type_of_piece(p) == ROOK)
2334 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2339 assert(type_of_piece(p) == QUEEN);
2340 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2348 // value_is_mate() checks if the given value is a mate one
2349 // eventually compensated for the ply.
2351 bool value_is_mate(Value value) {
2353 assert(abs(value) <= VALUE_INFINITE);
2355 return value <= value_mated_in(PLY_MAX)
2356 || value >= value_mate_in(PLY_MAX);
2360 // move_is_killer() checks if the given move is among the
2361 // killer moves of that ply.
2363 bool move_is_killer(Move m, const SearchStack& ss) {
2365 const Move* k = ss.killers;
2366 for (int i = 0; i < KILLER_MAX; i++, k++)
2374 // extension() decides whether a move should be searched with normal depth,
2375 // or with extended depth. Certain classes of moves (checking moves, in
2376 // particular) are searched with bigger depth than ordinary moves and in
2377 // any case are marked as 'dangerous'. Note that also if a move is not
2378 // extended, as example because the corresponding UCI option is set to zero,
2379 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2381 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2382 bool check, bool singleReply, bool mateThreat, bool* dangerous) {
2384 assert(m != MOVE_NONE);
2386 Depth result = Depth(0);
2387 *dangerous = check | singleReply | mateThreat;
2392 result += CheckExtension[pvNode];
2395 result += SingleReplyExtension[pvNode];
2398 result += MateThreatExtension[pvNode];
2401 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2403 Color c = pos.side_to_move();
2404 if (relative_rank(c, move_to(m)) == RANK_7)
2406 result += PawnPushTo7thExtension[pvNode];
2409 if (pos.pawn_is_passed(c, move_to(m)))
2411 result += PassedPawnExtension[pvNode];
2416 if ( captureOrPromotion
2417 && pos.type_of_piece_on(move_to(m)) != PAWN
2418 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2419 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2420 && !move_is_promotion(m)
2423 result += PawnEndgameExtension[pvNode];
2428 && captureOrPromotion
2429 && pos.type_of_piece_on(move_to(m)) != PAWN
2430 && pos.see_sign(m) >= 0)
2436 return Min(result, OnePly);
2440 // ok_to_do_nullmove() looks at the current position and decides whether
2441 // doing a 'null move' should be allowed. In order to avoid zugzwang
2442 // problems, null moves are not allowed when the side to move has very
2443 // little material left. Currently, the test is a bit too simple: Null
2444 // moves are avoided only when the side to move has only pawns left. It's
2445 // probably a good idea to avoid null moves in at least some more
2446 // complicated endgames, e.g. KQ vs KR. FIXME
2448 bool ok_to_do_nullmove(const Position& pos) {
2450 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2454 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2455 // non-tactical moves late in the move list close to the leaves are
2456 // candidates for pruning.
2458 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2460 assert(move_is_ok(m));
2461 assert(threat == MOVE_NONE || move_is_ok(threat));
2462 assert(!pos.move_is_check(m));
2463 assert(!pos.move_is_capture_or_promotion(m));
2464 assert(!pos.move_is_passed_pawn_push(m));
2465 assert(d >= OnePly);
2467 Square mfrom, mto, tfrom, tto;
2469 mfrom = move_from(m);
2471 tfrom = move_from(threat);
2472 tto = move_to(threat);
2474 // Case 1: Castling moves are never pruned
2475 if (move_is_castle(m))
2478 // Case 2: Don't prune moves which move the threatened piece
2479 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2482 // Case 3: If the threatened piece has value less than or equal to the
2483 // value of the threatening piece, don't prune move which defend it.
2484 if ( !PruneDefendingMoves
2485 && threat != MOVE_NONE
2486 && pos.move_is_capture(threat)
2487 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2488 || pos.type_of_piece_on(tfrom) == KING)
2489 && pos.move_attacks_square(m, tto))
2492 // Case 4: Don't prune moves with good history
2493 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2496 // Case 5: If the moving piece in the threatened move is a slider, don't
2497 // prune safe moves which block its ray.
2498 if ( !PruneBlockingMoves
2499 && threat != MOVE_NONE
2500 && piece_is_slider(pos.piece_on(tfrom))
2501 && bit_is_set(squares_between(tfrom, tto), mto)
2502 && pos.see_sign(m) >= 0)
2509 // ok_to_use_TT() returns true if a transposition table score
2510 // can be used at a given point in search.
2512 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2514 Value v = value_from_tt(tte->value(), ply);
2516 return ( tte->depth() >= depth
2517 || v >= Max(value_mate_in(100), beta)
2518 || v < Min(value_mated_in(100), beta))
2520 && ( (is_lower_bound(tte->type()) && v >= beta)
2521 || (is_upper_bound(tte->type()) && v < beta));
2525 // update_history() registers a good move that produced a beta-cutoff
2526 // in history and marks as failures all the other moves of that ply.
2528 void update_history(const Position& pos, Move m, Depth depth,
2529 Move movesSearched[], int moveCount) {
2531 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2533 for (int i = 0; i < moveCount - 1; i++)
2535 assert(m != movesSearched[i]);
2536 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2537 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2542 // update_killers() add a good move that produced a beta-cutoff
2543 // among the killer moves of that ply.
2545 void update_killers(Move m, SearchStack& ss) {
2547 if (m == ss.killers[0])
2550 for (int i = KILLER_MAX - 1; i > 0; i--)
2551 ss.killers[i] = ss.killers[i - 1];
2557 // fail_high_ply_1() checks if some thread is currently resolving a fail
2558 // high at ply 1 at the node below the first root node. This information
2559 // is used for time managment.
2561 bool fail_high_ply_1() {
2563 for(int i = 0; i < ActiveThreads; i++)
2564 if (Threads[i].failHighPly1)
2571 // current_search_time() returns the number of milliseconds which have passed
2572 // since the beginning of the current search.
2574 int current_search_time() {
2575 return get_system_time() - SearchStartTime;
2579 // nps() computes the current nodes/second count.
2582 int t = current_search_time();
2583 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2587 // poll() performs two different functions: It polls for user input, and it
2588 // looks at the time consumed so far and decides if it's time to abort the
2593 static int lastInfoTime;
2594 int t = current_search_time();
2599 // We are line oriented, don't read single chars
2600 std::string command;
2601 if (!std::getline(std::cin, command))
2604 if (command == "quit")
2607 PonderSearch = false;
2611 else if (command == "stop")
2614 PonderSearch = false;
2616 else if (command == "ponderhit")
2619 // Print search information
2623 else if (lastInfoTime > t)
2624 // HACK: Must be a new search where we searched less than
2625 // NodesBetweenPolls nodes during the first second of search.
2628 else if (t - lastInfoTime >= 1000)
2635 if (dbg_show_hit_rate)
2636 dbg_print_hit_rate();
2638 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2639 << " time " << t << " hashfull " << TT.full() << std::endl;
2640 lock_release(&IOLock);
2641 if (ShowCurrentLine)
2642 Threads[0].printCurrentLine = true;
2644 // Should we stop the search?
2648 bool overTime = t > AbsoluteMaxSearchTime
2649 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2650 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2651 && t > 6*(MaxSearchTime + ExtraSearchTime));
2653 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2654 || (ExactMaxTime && t >= ExactMaxTime)
2655 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2660 // ponderhit() is called when the program is pondering (i.e. thinking while
2661 // it's the opponent's turn to move) in order to let the engine know that
2662 // it correctly predicted the opponent's move.
2666 int t = current_search_time();
2667 PonderSearch = false;
2668 if (Iteration >= 3 &&
2669 (!InfiniteSearch && (StopOnPonderhit ||
2670 t > AbsoluteMaxSearchTime ||
2671 (RootMoveNumber == 1 &&
2672 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2673 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2674 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2679 // print_current_line() prints the current line of search for a given
2680 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2682 void print_current_line(SearchStack ss[], int ply, int threadID) {
2684 assert(ply >= 0 && ply < PLY_MAX);
2685 assert(threadID >= 0 && threadID < ActiveThreads);
2687 if (!Threads[threadID].idle)
2690 std::cout << "info currline " << (threadID + 1);
2691 for (int p = 0; p < ply; p++)
2692 std::cout << " " << ss[p].currentMove;
2694 std::cout << std::endl;
2695 lock_release(&IOLock);
2697 Threads[threadID].printCurrentLine = false;
2698 if (threadID + 1 < ActiveThreads)
2699 Threads[threadID + 1].printCurrentLine = true;
2703 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2705 void init_ss_array(SearchStack ss[]) {
2707 for (int i = 0; i < 3; i++)
2710 ss[i].initKillers();
2715 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2716 // while the program is pondering. The point is to work around a wrinkle in
2717 // the UCI protocol: When pondering, the engine is not allowed to give a
2718 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2719 // We simply wait here until one of these commands is sent, and return,
2720 // after which the bestmove and pondermove will be printed (in id_loop()).
2722 void wait_for_stop_or_ponderhit() {
2724 std::string command;
2728 if (!std::getline(std::cin, command))
2731 if (command == "quit")
2736 else if (command == "ponderhit" || command == "stop")
2742 // idle_loop() is where the threads are parked when they have no work to do.
2743 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2744 // object for which the current thread is the master.
2746 void idle_loop(int threadID, SplitPoint* waitSp) {
2747 assert(threadID >= 0 && threadID < THREAD_MAX);
2749 Threads[threadID].running = true;
2752 if(AllThreadsShouldExit && threadID != 0)
2755 // If we are not thinking, wait for a condition to be signaled instead
2756 // of wasting CPU time polling for work:
2757 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2758 #if !defined(_MSC_VER)
2759 pthread_mutex_lock(&WaitLock);
2760 if(Idle || threadID >= ActiveThreads)
2761 pthread_cond_wait(&WaitCond, &WaitLock);
2762 pthread_mutex_unlock(&WaitLock);
2764 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2768 // If this thread has been assigned work, launch a search
2769 if(Threads[threadID].workIsWaiting) {
2770 Threads[threadID].workIsWaiting = false;
2771 if(Threads[threadID].splitPoint->pvNode)
2772 sp_search_pv(Threads[threadID].splitPoint, threadID);
2774 sp_search(Threads[threadID].splitPoint, threadID);
2775 Threads[threadID].idle = true;
2778 // If this thread is the master of a split point and all threads have
2779 // finished their work at this split point, return from the idle loop.
2780 if(waitSp != NULL && waitSp->cpus == 0)
2784 Threads[threadID].running = false;
2788 // init_split_point_stack() is called during program initialization, and
2789 // initializes all split point objects.
2791 void init_split_point_stack() {
2792 for(int i = 0; i < THREAD_MAX; i++)
2793 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2794 SplitPointStack[i][j].parent = NULL;
2795 lock_init(&(SplitPointStack[i][j].lock), NULL);
2800 // destroy_split_point_stack() is called when the program exits, and
2801 // destroys all locks in the precomputed split point objects.
2803 void destroy_split_point_stack() {
2804 for(int i = 0; i < THREAD_MAX; i++)
2805 for(int j = 0; j < MaxActiveSplitPoints; j++)
2806 lock_destroy(&(SplitPointStack[i][j].lock));
2810 // thread_should_stop() checks whether the thread with a given threadID has
2811 // been asked to stop, directly or indirectly. This can happen if a beta
2812 // cutoff has occured in thre thread's currently active split point, or in
2813 // some ancestor of the current split point.
2815 bool thread_should_stop(int threadID) {
2816 assert(threadID >= 0 && threadID < ActiveThreads);
2820 if(Threads[threadID].stop)
2822 if(ActiveThreads <= 2)
2824 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2826 Threads[threadID].stop = true;
2833 // thread_is_available() checks whether the thread with threadID "slave" is
2834 // available to help the thread with threadID "master" at a split point. An
2835 // obvious requirement is that "slave" must be idle. With more than two
2836 // threads, this is not by itself sufficient: If "slave" is the master of
2837 // some active split point, it is only available as a slave to the other
2838 // threads which are busy searching the split point at the top of "slave"'s
2839 // split point stack (the "helpful master concept" in YBWC terminology).
2841 bool thread_is_available(int slave, int master) {
2842 assert(slave >= 0 && slave < ActiveThreads);
2843 assert(master >= 0 && master < ActiveThreads);
2844 assert(ActiveThreads > 1);
2846 if(!Threads[slave].idle || slave == master)
2849 if(Threads[slave].activeSplitPoints == 0)
2850 // No active split points means that the thread is available as a slave
2851 // for any other thread.
2854 if(ActiveThreads == 2)
2857 // Apply the "helpful master" concept if possible.
2858 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2865 // idle_thread_exists() tries to find an idle thread which is available as
2866 // a slave for the thread with threadID "master".
2868 bool idle_thread_exists(int master) {
2869 assert(master >= 0 && master < ActiveThreads);
2870 assert(ActiveThreads > 1);
2872 for(int i = 0; i < ActiveThreads; i++)
2873 if(thread_is_available(i, master))
2879 // split() does the actual work of distributing the work at a node between
2880 // several threads at PV nodes. If it does not succeed in splitting the
2881 // node (because no idle threads are available, or because we have no unused
2882 // split point objects), the function immediately returns false. If
2883 // splitting is possible, a SplitPoint object is initialized with all the
2884 // data that must be copied to the helper threads (the current position and
2885 // search stack, alpha, beta, the search depth, etc.), and we tell our
2886 // helper threads that they have been assigned work. This will cause them
2887 // to instantly leave their idle loops and call sp_search_pv(). When all
2888 // threads have returned from sp_search_pv (or, equivalently, when
2889 // splitPoint->cpus becomes 0), split() returns true.
2891 bool split(const Position& p, SearchStack* sstck, int ply,
2892 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2893 const Value approximateEval, Depth depth, int* moves,
2894 MovePicker* mp, int master, bool pvNode) {
2897 assert(sstck != NULL);
2898 assert(ply >= 0 && ply < PLY_MAX);
2899 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2900 assert(!pvNode || *alpha < *beta);
2901 assert(*beta <= VALUE_INFINITE);
2902 assert(depth > Depth(0));
2903 assert(master >= 0 && master < ActiveThreads);
2904 assert(ActiveThreads > 1);
2906 SplitPoint* splitPoint;
2911 // If no other thread is available to help us, or if we have too many
2912 // active split points, don't split.
2913 if(!idle_thread_exists(master) ||
2914 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2915 lock_release(&MPLock);
2919 // Pick the next available split point object from the split point stack
2920 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2921 Threads[master].activeSplitPoints++;
2923 // Initialize the split point object
2924 splitPoint->parent = Threads[master].splitPoint;
2925 splitPoint->finished = false;
2926 splitPoint->ply = ply;
2927 splitPoint->depth = depth;
2928 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2929 splitPoint->beta = *beta;
2930 splitPoint->pvNode = pvNode;
2931 splitPoint->bestValue = *bestValue;
2932 splitPoint->futilityValue = futilityValue;
2933 splitPoint->approximateEval = approximateEval;
2934 splitPoint->master = master;
2935 splitPoint->mp = mp;
2936 splitPoint->moves = *moves;
2937 splitPoint->cpus = 1;
2938 splitPoint->pos.copy(p);
2939 splitPoint->parentSstack = sstck;
2940 for(i = 0; i < ActiveThreads; i++)
2941 splitPoint->slaves[i] = 0;
2943 // Copy the current position and the search stack to the master thread
2944 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2945 Threads[master].splitPoint = splitPoint;
2947 // Make copies of the current position and search stack for each thread
2948 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2950 if(thread_is_available(i, master)) {
2951 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2952 Threads[i].splitPoint = splitPoint;
2953 splitPoint->slaves[i] = 1;
2957 // Tell the threads that they have work to do. This will make them leave
2959 for(i = 0; i < ActiveThreads; i++)
2960 if(i == master || splitPoint->slaves[i]) {
2961 Threads[i].workIsWaiting = true;
2962 Threads[i].idle = false;
2963 Threads[i].stop = false;
2966 lock_release(&MPLock);
2968 // Everything is set up. The master thread enters the idle loop, from
2969 // which it will instantly launch a search, because its workIsWaiting
2970 // slot is 'true'. We send the split point as a second parameter to the
2971 // idle loop, which means that the main thread will return from the idle
2972 // loop when all threads have finished their work at this split point
2973 // (i.e. when // splitPoint->cpus == 0).
2974 idle_loop(master, splitPoint);
2976 // We have returned from the idle loop, which means that all threads are
2977 // finished. Update alpha, beta and bestvalue, and return.
2979 if(pvNode) *alpha = splitPoint->alpha;
2980 *beta = splitPoint->beta;
2981 *bestValue = splitPoint->bestValue;
2982 Threads[master].stop = false;
2983 Threads[master].idle = false;
2984 Threads[master].activeSplitPoints--;
2985 Threads[master].splitPoint = splitPoint->parent;
2986 lock_release(&MPLock);
2992 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2993 // to start a new search from the root.
2995 void wake_sleeping_threads() {
2996 if(ActiveThreads > 1) {
2997 for(int i = 1; i < ActiveThreads; i++) {
2998 Threads[i].idle = true;
2999 Threads[i].workIsWaiting = false;
3001 #if !defined(_MSC_VER)
3002 pthread_mutex_lock(&WaitLock);
3003 pthread_cond_broadcast(&WaitCond);
3004 pthread_mutex_unlock(&WaitLock);
3006 for(int i = 1; i < THREAD_MAX; i++)
3007 SetEvent(SitIdleEvent[i]);
3013 // init_thread() is the function which is called when a new thread is
3014 // launched. It simply calls the idle_loop() function with the supplied
3015 // threadID. There are two versions of this function; one for POSIX threads
3016 // and one for Windows threads.
3018 #if !defined(_MSC_VER)
3020 void *init_thread(void *threadID) {
3021 idle_loop(*(int *)threadID, NULL);
3027 DWORD WINAPI init_thread(LPVOID threadID) {
3028 idle_loop(*(int *)threadID, NULL);