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/>.
44 #include "ucioption.h"
50 //// Local definitions
57 // IterationInfoType stores search results for each iteration
59 // Because we use relatively small (dynamic) aspiration window,
60 // there happens many fail highs and fail lows in root. And
61 // because we don't do researches in those cases, "value" stored
62 // here is not necessarily exact. Instead in case of fail high/low
63 // we guess what the right value might be and store our guess
64 // as a "speculated value" and then move on. Speculated values are
65 // used just to calculate aspiration window width, so also if are
66 // not exact is not big a problem.
68 struct IterationInfoType {
70 IterationInfoType(Value v = Value(0), Value sv = Value(0))
71 : value(v), speculatedValue(sv) {}
73 Value value, speculatedValue;
77 // The BetaCounterType class is used to order moves at ply one.
78 // Apart for the first one that has its score, following moves
79 // normally have score -VALUE_INFINITE, so are ordered according
80 // to the number of beta cutoffs occurred under their subtree during
81 // the last iteration. The counters are per thread variables to avoid
82 // concurrent accessing under SMP case.
84 struct BetaCounterType {
88 void add(Color us, Depth d, int threadID);
89 void read(Color us, int64_t& our, int64_t& their);
93 // The RootMove class is used for moves at the root at the tree. For each
94 // root move, we store a score, a node count, and a PV (really a refutation
95 // in the case of moves which fail low).
99 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
101 // RootMove::operator<() is the comparison function used when
102 // sorting the moves. A move m1 is considered to be better
103 // than a move m2 if it has a higher score, or if the moves
104 // have equal score but m1 has the higher node count.
105 bool operator<(const RootMove& m) const {
107 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
112 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
113 Move pv[PLY_MAX_PLUS_2];
117 // The RootMoveList class is essentially an array of RootMove objects, with
118 // a handful of methods for accessing the data in the individual moves.
123 RootMoveList(Position& pos, Move searchMoves[]);
125 int move_count() const { return count; }
126 Move get_move(int moveNum) const { return moves[moveNum].move; }
127 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
128 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
129 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
130 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
132 void set_move_nodes(int moveNum, int64_t nodes);
133 void set_beta_counters(int moveNum, int64_t our, int64_t their);
134 void set_move_pv(int moveNum, const Move pv[]);
136 void sort_multipv(int n);
139 static const int MaxRootMoves = 500;
140 RootMove moves[MaxRootMoves];
147 // Search depth at iteration 1
148 const Depth InitialDepth = OnePly;
150 // Depth limit for selective search
151 const Depth SelectiveDepth = 7 * OnePly;
153 // Use internal iterative deepening?
154 const bool UseIIDAtPVNodes = true;
155 const bool UseIIDAtNonPVNodes = true;
157 // Internal iterative deepening margin. At Non-PV moves, when
158 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
159 // search when the static evaluation is at most IIDMargin below beta.
160 const Value IIDMargin = Value(0x100);
162 // Easy move margin. An easy move candidate must be at least this much
163 // better than the second best move.
164 const Value EasyMoveMargin = Value(0x200);
166 // Problem margin. If the score of the first move at iteration N+1 has
167 // dropped by more than this since iteration N, the boolean variable
168 // "Problem" is set to true, which will make the program spend some extra
169 // time looking for a better move.
170 const Value ProblemMargin = Value(0x28);
172 // No problem margin. If the boolean "Problem" is true, and a new move
173 // is found at the root which is less than NoProblemMargin worse than the
174 // best move from the previous iteration, Problem is set back to false.
175 const Value NoProblemMargin = Value(0x14);
177 // Null move margin. A null move search will not be done if the static
178 // evaluation of the position is more than NullMoveMargin below beta.
179 const Value NullMoveMargin = Value(0x200);
181 // If the TT move is at least SingleReplyMargin better then the
182 // remaining ones we will extend it.
183 const Value SingleReplyMargin = Value(0x20);
185 // Margins for futility pruning in the quiescence search, and at frontier
186 // and near frontier nodes.
187 const Value FutilityMarginQS = Value(0x80);
189 // Each move futility margin is decreased
190 const Value IncrementalFutilityMargin = Value(0x8);
192 // Depth limit for razoring
193 const Depth RazorDepth = 4 * OnePly;
195 /// Variables initialized by UCI options
197 // Depth limit for use of dynamic threat detection
200 // Last seconds noise filtering (LSN)
201 const bool UseLSNFiltering = true;
202 const int LSNTime = 4000; // In milliseconds
203 const Value LSNValue = value_from_centipawns(200);
204 bool loseOnTime = false;
206 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
207 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
208 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
210 // Iteration counters
212 BetaCounterType BetaCounter;
214 // Scores and number of times the best move changed for each iteration
215 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
216 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
221 // Time managment variables
224 int MaxNodes, MaxDepth;
225 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
226 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
227 bool AbortSearch, Quit;
228 bool FailHigh, FailLow, Problem;
230 // Show current line?
231 bool ShowCurrentLine;
235 std::ofstream LogFile;
237 // Natural logarithmic lookup table and its getter function
239 inline double ln(int i) { return lnArray[i]; }
241 // MP related variables
242 int ActiveThreads = 1;
243 Depth MinimumSplitDepth;
244 int MaxThreadsPerSplitPoint;
245 Thread Threads[THREAD_MAX];
248 bool AllThreadsShouldExit = false;
249 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
252 #if !defined(_MSC_VER)
253 pthread_cond_t WaitCond;
254 pthread_mutex_t WaitLock;
256 HANDLE SitIdleEvent[THREAD_MAX];
259 // Node counters, used only by thread[0] but try to keep in different
260 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
262 int NodesBetweenPolls = 30000;
272 Value id_loop(const Position& pos, Move searchMoves[]);
273 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
274 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
275 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
276 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
277 void sp_search(SplitPoint* sp, int threadID);
278 void sp_search_pv(SplitPoint* sp, int threadID);
279 void init_node(SearchStack ss[], int ply, int threadID);
280 void update_pv(SearchStack ss[], int ply);
281 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
282 bool connected_moves(const Position& pos, Move m1, Move m2);
283 bool value_is_mate(Value value);
284 bool move_is_killer(Move m, const SearchStack& ss);
285 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
286 bool ok_to_do_nullmove(const Position& pos);
287 bool ok_to_prune(const Position& pos, Move m, Move threat);
288 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
289 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
290 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
291 void update_killers(Move m, SearchStack& ss);
292 void update_gains(const Position& pos, Move move, Value before, Value after);
294 bool fail_high_ply_1();
295 int current_search_time();
299 void print_current_line(SearchStack ss[], int ply, int threadID);
300 void wait_for_stop_or_ponderhit();
301 void init_ss_array(SearchStack ss[]);
303 void idle_loop(int threadID, SplitPoint* waitSp);
304 void init_split_point_stack();
305 void destroy_split_point_stack();
306 bool thread_should_stop(int threadID);
307 bool thread_is_available(int slave, int master);
308 bool idle_thread_exists(int master);
309 bool split(const Position& pos, SearchStack* ss, int ply,
310 Value *alpha, Value *beta, Value *bestValue,
311 const Value futilityValue, Depth depth, int *moves,
312 MovePicker *mp, int master, bool pvNode);
313 void wake_sleeping_threads();
315 #if !defined(_MSC_VER)
316 void *init_thread(void *threadID);
318 DWORD WINAPI init_thread(LPVOID threadID);
329 /// perft() is our utility to verify move generation is bug free. All the legal
330 /// moves up to given depth are generated and counted and the sum returned.
332 int perft(Position& pos, Depth depth)
336 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
338 // If we are at the last ply we don't need to do and undo
339 // the moves, just to count them.
340 if (depth <= OnePly) // Replace with '<' to test also qsearch
342 while (mp.get_next_move()) sum++;
346 // Loop through all legal moves
348 while ((move = mp.get_next_move()) != MOVE_NONE)
351 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
352 sum += perft(pos, depth - OnePly);
359 /// think() is the external interface to Stockfish's search, and is called when
360 /// the program receives the UCI 'go' command. It initializes various
361 /// search-related global variables, and calls root_search(). It returns false
362 /// when a quit command is received during the search.
364 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
365 int time[], int increment[], int movesToGo, int maxDepth,
366 int maxNodes, int maxTime, Move searchMoves[]) {
368 // Initialize global search variables
369 Idle = StopOnPonderhit = AbortSearch = Quit = false;
370 FailHigh = FailLow = Problem = false;
372 SearchStartTime = get_system_time();
373 ExactMaxTime = maxTime;
376 InfiniteSearch = infinite;
377 PonderSearch = ponder;
378 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
380 // Look for a book move, only during games, not tests
381 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
384 if (get_option_value_string("Book File") != OpeningBook.file_name())
385 OpeningBook.open(get_option_value_string("Book File"));
387 bookMove = OpeningBook.get_move(pos);
388 if (bookMove != MOVE_NONE)
390 cout << "bestmove " << bookMove << endl;
395 for (int i = 0; i < THREAD_MAX; i++)
397 Threads[i].nodes = 0ULL;
398 Threads[i].failHighPly1 = false;
401 if (button_was_pressed("New Game"))
402 loseOnTime = false; // Reset at the beginning of a new game
404 // Read UCI option values
405 TT.set_size(get_option_value_int("Hash"));
406 if (button_was_pressed("Clear Hash"))
409 bool PonderingEnabled = get_option_value_bool("Ponder");
410 MultiPV = get_option_value_int("MultiPV");
412 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
413 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
415 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
416 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
418 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
419 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
421 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
422 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
424 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
425 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
427 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
428 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
430 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
432 Chess960 = get_option_value_bool("UCI_Chess960");
433 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
434 UseLogFile = get_option_value_bool("Use Search Log");
436 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
438 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
439 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
441 read_weights(pos.side_to_move());
443 // Set the number of active threads
444 int newActiveThreads = get_option_value_int("Threads");
445 if (newActiveThreads != ActiveThreads)
447 ActiveThreads = newActiveThreads;
448 init_eval(ActiveThreads);
449 // HACK: init_eval() destroys the static castleRightsMask[] array in the
450 // Position class. The below line repairs the damage.
451 Position p(pos.to_fen());
455 // Wake up sleeping threads
456 wake_sleeping_threads();
458 for (int i = 1; i < ActiveThreads; i++)
459 assert(thread_is_available(i, 0));
462 int myTime = time[side_to_move];
463 int myIncrement = increment[side_to_move];
464 if (UseTimeManagement)
466 if (!movesToGo) // Sudden death time control
470 MaxSearchTime = myTime / 30 + myIncrement;
471 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
473 else // Blitz game without increment
475 MaxSearchTime = myTime / 30;
476 AbsoluteMaxSearchTime = myTime / 8;
479 else // (x moves) / (y minutes)
483 MaxSearchTime = myTime / 2;
484 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
488 MaxSearchTime = myTime / Min(movesToGo, 20);
489 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
493 if (PonderingEnabled)
495 MaxSearchTime += MaxSearchTime / 4;
496 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
500 // Set best NodesBetweenPolls interval
502 NodesBetweenPolls = Min(MaxNodes, 30000);
503 else if (myTime && myTime < 1000)
504 NodesBetweenPolls = 1000;
505 else if (myTime && myTime < 5000)
506 NodesBetweenPolls = 5000;
508 NodesBetweenPolls = 30000;
510 // Write information to search log file
512 LogFile << "Searching: " << pos.to_fen() << endl
513 << "infinite: " << infinite
514 << " ponder: " << ponder
515 << " time: " << myTime
516 << " increment: " << myIncrement
517 << " moves to go: " << movesToGo << endl;
519 // LSN filtering. Used only for developing purpose. Disabled by default.
523 // Step 2. If after last move we decided to lose on time, do it now!
524 while (SearchStartTime + myTime + 1000 > get_system_time())
528 // We're ready to start thinking. Call the iterative deepening loop function
529 Value v = id_loop(pos, searchMoves);
534 // Step 1. If this is sudden death game and our position is hopeless,
535 // decide to lose on time.
536 if ( !loseOnTime // If we already lost on time, go to step 3.
546 // Step 3. Now after stepping over the time limit, reset flag for next match.
559 /// init_threads() is called during startup. It launches all helper threads,
560 /// and initializes the split point stack and the global locks and condition
563 void init_threads() {
568 #if !defined(_MSC_VER)
569 pthread_t pthread[1];
572 // Init our logarithmic lookup table
573 for (i = 0; i < 512; i++)
574 lnArray[i] = log(double(i)); // log() returns base-e logarithm
576 for (i = 0; i < THREAD_MAX; i++)
577 Threads[i].activeSplitPoints = 0;
579 // Initialize global locks
580 lock_init(&MPLock, NULL);
581 lock_init(&IOLock, NULL);
583 init_split_point_stack();
585 #if !defined(_MSC_VER)
586 pthread_mutex_init(&WaitLock, NULL);
587 pthread_cond_init(&WaitCond, NULL);
589 for (i = 0; i < THREAD_MAX; i++)
590 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
593 // All threads except the main thread should be initialized to idle state
594 for (i = 1; i < THREAD_MAX; i++)
596 Threads[i].stop = false;
597 Threads[i].workIsWaiting = false;
598 Threads[i].idle = true;
599 Threads[i].running = false;
602 // Launch the helper threads
603 for (i = 1; i < THREAD_MAX; i++)
605 #if !defined(_MSC_VER)
606 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
609 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
614 cout << "Failed to create thread number " << i << endl;
615 Application::exit_with_failure();
618 // Wait until the thread has finished launching
619 while (!Threads[i].running);
624 /// stop_threads() is called when the program exits. It makes all the
625 /// helper threads exit cleanly.
627 void stop_threads() {
629 ActiveThreads = THREAD_MAX; // HACK
630 Idle = false; // HACK
631 wake_sleeping_threads();
632 AllThreadsShouldExit = true;
633 for (int i = 1; i < THREAD_MAX; i++)
635 Threads[i].stop = true;
636 while (Threads[i].running);
638 destroy_split_point_stack();
642 /// nodes_searched() returns the total number of nodes searched so far in
643 /// the current search.
645 int64_t nodes_searched() {
647 int64_t result = 0ULL;
648 for (int i = 0; i < ActiveThreads; i++)
649 result += Threads[i].nodes;
654 // SearchStack::init() initializes a search stack. Used at the beginning of a
655 // new search from the root.
656 void SearchStack::init(int ply) {
658 pv[ply] = pv[ply + 1] = MOVE_NONE;
659 currentMove = threatMove = MOVE_NONE;
660 reduction = Depth(0);
665 void SearchStack::initKillers() {
667 mateKiller = MOVE_NONE;
668 for (int i = 0; i < KILLER_MAX; i++)
669 killers[i] = MOVE_NONE;
674 // id_loop() is the main iterative deepening loop. It calls root_search
675 // repeatedly with increasing depth until the allocated thinking time has
676 // been consumed, the user stops the search, or the maximum search depth is
679 Value id_loop(const Position& pos, Move searchMoves[]) {
682 SearchStack ss[PLY_MAX_PLUS_2];
684 // searchMoves are verified, copied, scored and sorted
685 RootMoveList rml(p, searchMoves);
687 if (rml.move_count() == 0)
690 wait_for_stop_or_ponderhit();
692 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
695 // Print RootMoveList c'tor startup scoring to the standard output,
696 // so that we print information also for iteration 1.
697 cout << "info depth " << 1 << "\ninfo depth " << 1
698 << " score " << value_to_string(rml.get_move_score(0))
699 << " time " << current_search_time()
700 << " nodes " << nodes_searched()
702 << " pv " << rml.get_move(0) << "\n";
709 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
712 // Is one move significantly better than others after initial scoring ?
713 Move EasyMove = MOVE_NONE;
714 if ( rml.move_count() == 1
715 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
716 EasyMove = rml.get_move(0);
718 // Iterative deepening loop
719 while (Iteration < PLY_MAX)
721 // Initialize iteration
724 BestMoveChangesByIteration[Iteration] = 0;
728 cout << "info depth " << Iteration << endl;
730 // Calculate dynamic search window based on previous iterations
733 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
735 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
736 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
738 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
740 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
741 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
745 alpha = - VALUE_INFINITE;
746 beta = VALUE_INFINITE;
749 // Search to the current depth
750 Value value = root_search(p, ss, rml, alpha, beta);
752 // Write PV to transposition table, in case the relevant entries have
753 // been overwritten during the search.
754 TT.insert_pv(p, ss[0].pv);
757 break; // Value cannot be trusted. Break out immediately!
759 //Save info about search result
760 Value speculatedValue;
763 Value delta = value - IterationInfo[Iteration - 1].value;
770 speculatedValue = value + delta;
771 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
773 else if (value <= alpha)
775 assert(value == alpha);
779 speculatedValue = value + delta;
780 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
782 speculatedValue = value;
784 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
785 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
787 // Drop the easy move if it differs from the new best move
788 if (ss[0].pv[0] != EasyMove)
789 EasyMove = MOVE_NONE;
793 if (UseTimeManagement)
796 bool stopSearch = false;
798 // Stop search early if there is only a single legal move,
799 // we search up to Iteration 6 anyway to get a proper score.
800 if (Iteration >= 6 && rml.move_count() == 1)
803 // Stop search early when the last two iterations returned a mate score
805 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
806 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
809 // Stop search early if one move seems to be much better than the rest
810 int64_t nodes = nodes_searched();
814 && EasyMove == ss[0].pv[0]
815 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
816 && current_search_time() > MaxSearchTime / 16)
817 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
818 && current_search_time() > MaxSearchTime / 32)))
821 // Add some extra time if the best move has changed during the last two iterations
822 if (Iteration > 5 && Iteration <= 50)
823 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
824 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
826 // Stop search if most of MaxSearchTime is consumed at the end of the
827 // iteration. We probably don't have enough time to search the first
828 // move at the next iteration anyway.
829 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
837 StopOnPonderhit = true;
841 if (MaxDepth && Iteration >= MaxDepth)
847 // If we are pondering or in infinite search, we shouldn't print the
848 // best move before we are told to do so.
849 if (!AbortSearch && (PonderSearch || InfiniteSearch))
850 wait_for_stop_or_ponderhit();
852 // Print final search statistics
853 cout << "info nodes " << nodes_searched()
855 << " time " << current_search_time()
856 << " hashfull " << TT.full() << endl;
858 // Print the best move and the ponder move to the standard output
859 if (ss[0].pv[0] == MOVE_NONE)
861 ss[0].pv[0] = rml.get_move(0);
862 ss[0].pv[1] = MOVE_NONE;
864 cout << "bestmove " << ss[0].pv[0];
865 if (ss[0].pv[1] != MOVE_NONE)
866 cout << " ponder " << ss[0].pv[1];
873 dbg_print_mean(LogFile);
875 if (dbg_show_hit_rate)
876 dbg_print_hit_rate(LogFile);
878 LogFile << "\nNodes: " << nodes_searched()
879 << "\nNodes/second: " << nps()
880 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
883 p.do_move(ss[0].pv[0], st);
884 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
886 return rml.get_move_score(0);
890 // root_search() is the function which searches the root node. It is
891 // similar to search_pv except that it uses a different move ordering
892 // scheme and prints some information to the standard output.
894 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta) {
896 Value oldAlpha = alpha;
897 Value value = -VALUE_INFINITE;
899 bool isCheck = pos.is_check();
901 // Evaluate the position statically
904 ss[0].eval = evaluate(pos, ei, 0);
906 ss[0].eval = VALUE_NONE;
908 // Loop through all the moves in the root move list
909 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
913 // We failed high, invalidate and skip next moves, leave node-counters
914 // and beta-counters as they are and quickly return, we will try to do
915 // a research at the next iteration with a bigger aspiration window.
916 rml.set_move_score(i, -VALUE_INFINITE);
922 Depth depth, ext, newDepth;
924 RootMoveNumber = i + 1;
927 // Save the current node count before the move is searched
928 nodes = nodes_searched();
930 // Reset beta cut-off counters
933 // Pick the next root move, and print the move and the move number to
934 // the standard output.
935 move = ss[0].currentMove = rml.get_move(i);
937 if (current_search_time() >= 1000)
938 cout << "info currmove " << move
939 << " currmovenumber " << RootMoveNumber << endl;
941 // Decide search depth for this move
942 bool moveIsCheck = pos.move_is_check(move);
943 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
945 depth = (Iteration - 2) * OnePly + InitialDepth;
946 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
947 newDepth = depth + ext;
949 // Make the move, and search it
950 pos.do_move(move, st, ci, moveIsCheck);
954 // Aspiration window is disabled in multi-pv case
956 alpha = -VALUE_INFINITE;
958 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
960 // If the value has dropped a lot compared to the last iteration,
961 // set the boolean variable Problem to true. This variable is used
962 // for time managment: When Problem is true, we try to complete the
963 // current iteration before playing a move.
964 Problem = ( Iteration >= 2
965 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
967 if (Problem && StopOnPonderhit)
968 StopOnPonderhit = false;
972 // Try to reduce non-pv search depth by one ply if move seems not problematic,
973 // if the move fails high will be re-searched at full depth.
974 bool doFullDepthSearch = true;
976 if ( depth >= 3*OnePly // FIXME was newDepth
978 && !captureOrPromotion
979 && !move_is_castle(move))
981 double red = 0.5 + ln(RootMoveNumber - MultiPV + 1) * ln(depth / 2) / 6.0;
984 ss[0].reduction = Depth(int(floor(red * int(OnePly))));
985 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
986 doFullDepthSearch = (value > alpha);
990 if (doFullDepthSearch)
992 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
996 // Fail high! Set the boolean variable FailHigh to true, and
997 // re-search the move using a PV search. The variable FailHigh
998 // is used for time managment: We try to avoid aborting the
999 // search prematurely during a fail high research.
1001 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
1006 pos.undo_move(move);
1008 // Finished searching the move. If AbortSearch is true, the search
1009 // was aborted because the user interrupted the search or because we
1010 // ran out of time. In this case, the return value of the search cannot
1011 // be trusted, and we break out of the loop without updating the best
1016 // Remember beta-cutoff and searched nodes counts for this move. The
1017 // info is used to sort the root moves at the next iteration.
1019 BetaCounter.read(pos.side_to_move(), our, their);
1020 rml.set_beta_counters(i, our, their);
1021 rml.set_move_nodes(i, nodes_searched() - nodes);
1023 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1025 if (value <= alpha && i >= MultiPV)
1026 rml.set_move_score(i, -VALUE_INFINITE);
1029 // PV move or new best move!
1032 rml.set_move_score(i, value);
1034 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1035 rml.set_move_pv(i, ss[0].pv);
1039 // We record how often the best move has been changed in each
1040 // iteration. This information is used for time managment: When
1041 // the best move changes frequently, we allocate some more time.
1043 BestMoveChangesByIteration[Iteration]++;
1045 // Print search information to the standard output
1046 cout << "info depth " << Iteration
1047 << " score " << value_to_string(value)
1048 << ((value >= beta) ? " lowerbound" :
1049 ((value <= alpha)? " upperbound" : ""))
1050 << " time " << current_search_time()
1051 << " nodes " << nodes_searched()
1055 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1056 cout << ss[0].pv[j] << " ";
1062 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1063 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1065 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1066 nodes_searched(), value, type, ss[0].pv) << endl;
1071 // Reset the global variable Problem to false if the value isn't too
1072 // far below the final value from the last iteration.
1073 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1078 rml.sort_multipv(i);
1079 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1081 cout << "info multipv " << j + 1
1082 << " score " << value_to_string(rml.get_move_score(j))
1083 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1084 << " time " << current_search_time()
1085 << " nodes " << nodes_searched()
1089 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1090 cout << rml.get_move_pv(j, k) << " ";
1094 alpha = rml.get_move_score(Min(i, MultiPV-1));
1096 } // PV move or new best move
1098 assert(alpha >= oldAlpha);
1100 FailLow = (alpha == oldAlpha);
1106 // search_pv() is the main search function for PV nodes.
1108 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1109 Depth depth, int ply, int threadID) {
1111 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1112 assert(beta > alpha && beta <= VALUE_INFINITE);
1113 assert(ply >= 0 && ply < PLY_MAX);
1114 assert(threadID >= 0 && threadID < ActiveThreads);
1116 Move movesSearched[256];
1120 Depth ext, newDepth;
1121 Value oldAlpha, value;
1122 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1124 Value bestValue = value = -VALUE_INFINITE;
1127 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1129 // Initialize, and make an early exit in case of an aborted search,
1130 // an instant draw, maximum ply reached, etc.
1131 init_node(ss, ply, threadID);
1133 // After init_node() that calls poll()
1134 if (AbortSearch || thread_should_stop(threadID))
1137 if (pos.is_draw() || ply >= PLY_MAX - 1)
1140 // Mate distance pruning
1142 alpha = Max(value_mated_in(ply), alpha);
1143 beta = Min(value_mate_in(ply+1), beta);
1147 // Transposition table lookup. At PV nodes, we don't use the TT for
1148 // pruning, but only for move ordering. This is to avoid problems in
1149 // the following areas:
1151 // * Repetition draw detection
1152 // * Fifty move rule detection
1153 // * Searching for a mate
1154 // * Printing of full PV line
1156 tte = TT.retrieve(pos.get_key());
1157 ttMove = (tte ? tte->move() : MOVE_NONE);
1159 // Go with internal iterative deepening if we don't have a TT move
1160 if ( UseIIDAtPVNodes
1161 && depth >= 5*OnePly
1162 && ttMove == MOVE_NONE)
1164 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1165 ttMove = ss[ply].pv[ply];
1166 tte = TT.retrieve(pos.get_key());
1169 isCheck = pos.is_check();
1172 // Update gain statistics of the previous move that lead
1173 // us in this position.
1175 ss[ply].eval = evaluate(pos, ei, threadID);
1176 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1179 // Initialize a MovePicker object for the current position, and prepare
1180 // to search all moves
1181 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1183 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1185 // Loop through all legal moves until no moves remain or a beta cutoff
1187 while ( alpha < beta
1188 && (move = mp.get_next_move()) != MOVE_NONE
1189 && !thread_should_stop(threadID))
1191 assert(move_is_ok(move));
1193 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1194 moveIsCheck = pos.move_is_check(move, ci);
1195 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1197 // Decide the new search depth
1198 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1200 // Singular extension search. We extend the TT move if its value is much better than
1201 // its siblings. To verify this we do a reduced search on all the other moves but the
1202 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1203 if ( depth >= 6 * OnePly
1205 && move == tte->move()
1207 && is_lower_bound(tte->type())
1208 && tte->depth() >= depth - 3 * OnePly)
1210 Value ttValue = value_from_tt(tte->value(), ply);
1212 if (abs(ttValue) < VALUE_KNOWN_WIN)
1214 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1216 if (excValue < ttValue - SingleReplyMargin)
1221 newDepth = depth - OnePly + ext;
1223 // Update current move
1224 movesSearched[moveCount++] = ss[ply].currentMove = move;
1226 // Make and search the move
1227 pos.do_move(move, st, ci, moveIsCheck);
1229 if (moveCount == 1) // The first move in list is the PV
1230 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1233 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1234 // if the move fails high will be re-searched at full depth.
1235 bool doFullDepthSearch = true;
1237 if ( depth >= 3*OnePly
1239 && !captureOrPromotion
1240 && !move_is_castle(move)
1241 && !move_is_killer(move, ss[ply]))
1243 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 6.0;
1246 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1247 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1248 doFullDepthSearch = (value > alpha);
1252 if (doFullDepthSearch) // Go with full depth non-pv search
1254 ss[ply].reduction = Depth(0);
1255 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1256 if (value > alpha && value < beta)
1258 // When the search fails high at ply 1 while searching the first
1259 // move at the root, set the flag failHighPly1. This is used for
1260 // time managment: We don't want to stop the search early in
1261 // such cases, because resolving the fail high at ply 1 could
1262 // result in a big drop in score at the root.
1263 if (ply == 1 && RootMoveNumber == 1)
1264 Threads[threadID].failHighPly1 = true;
1266 // A fail high occurred. Re-search at full window (pv search)
1267 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1268 Threads[threadID].failHighPly1 = false;
1272 pos.undo_move(move);
1274 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1277 if (value > bestValue)
1284 if (value == value_mate_in(ply + 1))
1285 ss[ply].mateKiller = move;
1287 // If we are at ply 1, and we are searching the first root move at
1288 // ply 0, set the 'Problem' variable if the score has dropped a lot
1289 // (from the computer's point of view) since the previous iteration.
1292 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1297 if ( ActiveThreads > 1
1299 && depth >= MinimumSplitDepth
1301 && idle_thread_exists(threadID)
1303 && !thread_should_stop(threadID)
1304 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1305 depth, &moveCount, &mp, threadID, true))
1309 // All legal moves have been searched. A special case: If there were
1310 // no legal moves, it must be mate or stalemate.
1312 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1314 // If the search is not aborted, update the transposition table,
1315 // history counters, and killer moves.
1316 if (AbortSearch || thread_should_stop(threadID))
1319 if (bestValue <= oldAlpha)
1320 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1322 else if (bestValue >= beta)
1324 BetaCounter.add(pos.side_to_move(), depth, threadID);
1325 move = ss[ply].pv[ply];
1326 if (!pos.move_is_capture_or_promotion(move))
1328 update_history(pos, move, depth, movesSearched, moveCount);
1329 update_killers(move, ss[ply]);
1331 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1334 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1340 // search() is the search function for zero-width nodes.
1342 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1343 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1345 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1346 assert(ply >= 0 && ply < PLY_MAX);
1347 assert(threadID >= 0 && threadID < ActiveThreads);
1349 Move movesSearched[256];
1354 Depth ext, newDepth;
1355 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1356 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1357 bool mateThreat = false;
1359 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1362 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1364 // Initialize, and make an early exit in case of an aborted search,
1365 // an instant draw, maximum ply reached, etc.
1366 init_node(ss, ply, threadID);
1368 // After init_node() that calls poll()
1369 if (AbortSearch || thread_should_stop(threadID))
1372 if (pos.is_draw() || ply >= PLY_MAX - 1)
1375 // Mate distance pruning
1376 if (value_mated_in(ply) >= beta)
1379 if (value_mate_in(ply + 1) < beta)
1382 // We don't want the score of a partial search to overwrite a previous full search
1383 // TT value, so we use a different position key in case of an excluded move exsists.
1384 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1386 // Transposition table lookup
1387 tte = TT.retrieve(posKey);
1388 ttMove = (tte ? tte->move() : MOVE_NONE);
1390 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1392 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1393 return value_from_tt(tte->value(), ply);
1396 isCheck = pos.is_check();
1398 // Calculate depth dependant futility pruning parameters
1399 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1400 const int PostFutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1402 // Evaluate the position statically
1405 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1406 staticValue = value_from_tt(tte->value(), ply);
1409 staticValue = evaluate(pos, ei, threadID);
1410 ss[ply].evalInfo = &ei;
1413 ss[ply].eval = staticValue;
1414 futilityValue = staticValue + PostFutilityValueMargin; //FIXME: Remove me, only for split
1415 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1416 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1419 // Post futility pruning
1420 if (depth < SelectiveDepth && staticValue - PostFutilityValueMargin >= beta)
1421 return (staticValue - PostFutilityValueMargin);
1427 && !value_is_mate(beta)
1428 && ok_to_do_nullmove(pos)
1429 && staticValue >= beta - NullMoveMargin)
1431 ss[ply].currentMove = MOVE_NULL;
1433 pos.do_null_move(st);
1435 // Null move dynamic reduction based on depth
1436 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1438 // Null move dynamic reduction based on value
1439 if (staticValue - beta > PawnValueMidgame)
1442 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1444 pos.undo_null_move();
1446 if (nullValue >= beta)
1448 if (depth < 6 * OnePly)
1451 // Do zugzwang verification search
1452 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1456 // The null move failed low, which means that we may be faced with
1457 // some kind of threat. If the previous move was reduced, check if
1458 // the move that refuted the null move was somehow connected to the
1459 // move which was reduced. If a connection is found, return a fail
1460 // low score (which will cause the reduced move to fail high in the
1461 // parent node, which will trigger a re-search with full depth).
1462 if (nullValue == value_mated_in(ply + 2))
1465 ss[ply].threatMove = ss[ply + 1].currentMove;
1466 if ( depth < ThreatDepth
1467 && ss[ply - 1].reduction
1468 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1472 // Null move search not allowed, try razoring
1473 else if ( !value_is_mate(beta)
1475 && depth < RazorDepth
1476 && staticValue < beta - (NullMoveMargin + 16 * depth)
1477 && ss[ply - 1].currentMove != MOVE_NULL
1478 && ttMove == MOVE_NONE
1479 && !pos.has_pawn_on_7th(pos.side_to_move()))
1481 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1482 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1487 // Go with internal iterative deepening if we don't have a TT move
1488 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1489 !isCheck && ss[ply].eval >= beta - IIDMargin)
1491 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1492 ttMove = ss[ply].pv[ply];
1493 tte = TT.retrieve(pos.get_key());
1496 // Initialize a MovePicker object for the current position, and prepare
1497 // to search all moves.
1498 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1501 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1502 while ( bestValue < beta
1503 && (move = mp.get_next_move()) != MOVE_NONE
1504 && !thread_should_stop(threadID))
1506 assert(move_is_ok(move));
1508 if (move == excludedMove)
1511 moveIsCheck = pos.move_is_check(move, ci);
1512 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1513 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1515 // Decide the new search depth
1516 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1518 // Singular extension search. We extend the TT move if its value is much better than
1519 // its siblings. To verify this we do a reduced search on all the other moves but the
1520 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1521 if ( depth >= 8 * OnePly
1523 && move == tte->move()
1524 && !excludedMove // Do not allow recursive single-reply search
1526 && is_lower_bound(tte->type())
1527 && tte->depth() >= depth - 3 * OnePly)
1529 Value ttValue = value_from_tt(tte->value(), ply);
1531 if (abs(ttValue) < VALUE_KNOWN_WIN)
1533 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1535 if (excValue < ttValue - SingleReplyMargin)
1540 newDepth = depth - OnePly + ext;
1542 // Update current move
1543 movesSearched[moveCount++] = ss[ply].currentMove = move;
1545 // Futility pruning for captures
1546 Color them = opposite_color(pos.side_to_move());
1549 && newDepth < SelectiveDepth
1551 && pos.move_is_capture(move)
1552 && !pos.move_is_check(move, ci)
1553 && !move_is_promotion(move)
1555 && !move_is_ep(move)
1556 && (pos.type_of_piece_on(move_to(move)) != PAWN || !pos.pawn_is_passed(them, move_to(move)))) // Do not prune passed pawn captures
1558 int preFutilityValueMargin = 0;
1560 if (newDepth >= OnePly)
1561 preFutilityValueMargin = 112 * bitScanReverse32(int(newDepth) * int(newDepth) / 2);
1563 if (ss[ply].eval + pos.endgame_value_of_piece_on(move_to(move)) + preFutilityValueMargin + ei.futilityMargin + 90 < beta)
1571 && !captureOrPromotion
1572 && !move_is_castle(move)
1575 // Move count based pruning
1576 if ( moveCount >= FutilityMoveCountMargin
1577 && ok_to_prune(pos, move, ss[ply].threatMove)
1578 && bestValue > value_mated_in(PLY_MAX))
1581 // Value based pruning
1582 Depth predictedDepth = newDepth;
1584 //FIXME HACK: awful code duplication
1585 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1587 predictedDepth -= int(floor(red * int(OnePly)));
1589 if (predictedDepth < SelectiveDepth)
1591 int preFutilityValueMargin = 0;
1592 if (predictedDepth >= OnePly)
1593 preFutilityValueMargin = 112 * bitScanReverse32(int(predictedDepth) * int(predictedDepth) / 2);
1595 preFutilityValueMargin += MG.retrieve(pos.piece_on(move_from(move)), move_from(move), move_to(move)) + 45;
1597 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1599 if (futilityValueScaled < beta)
1601 if (futilityValueScaled > bestValue)
1602 bestValue = futilityValueScaled;
1608 // Make and search the move
1609 pos.do_move(move, st, ci, moveIsCheck);
1611 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1612 // if the move fails high will be re-searched at full depth.
1613 bool doFullDepthSearch = true;
1615 if ( depth >= 3*OnePly
1617 && !captureOrPromotion
1618 && !move_is_castle(move)
1619 && !move_is_killer(move, ss[ply])
1620 /* && move != ttMove*/)
1622 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1625 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1626 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1627 doFullDepthSearch = (value >= beta);
1631 if (doFullDepthSearch) // Go with full depth non-pv search
1633 ss[ply].reduction = Depth(0);
1634 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1636 pos.undo_move(move);
1638 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1641 if (value > bestValue)
1647 if (value == value_mate_in(ply + 1))
1648 ss[ply].mateKiller = move;
1652 if ( ActiveThreads > 1
1654 && depth >= MinimumSplitDepth
1656 && idle_thread_exists(threadID)
1658 && !thread_should_stop(threadID)
1659 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1660 depth, &moveCount, &mp, threadID, false))
1664 // All legal moves have been searched. A special case: If there were
1665 // no legal moves, it must be mate or stalemate.
1667 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1669 // If the search is not aborted, update the transposition table,
1670 // history counters, and killer moves.
1671 if (AbortSearch || thread_should_stop(threadID))
1674 if (bestValue < beta)
1675 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1678 BetaCounter.add(pos.side_to_move(), depth, threadID);
1679 move = ss[ply].pv[ply];
1680 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1681 if (!pos.move_is_capture_or_promotion(move))
1683 update_history(pos, move, depth, movesSearched, moveCount);
1684 update_killers(move, ss[ply]);
1689 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1695 // qsearch() is the quiescence search function, which is called by the main
1696 // search function when the remaining depth is zero (or, to be more precise,
1697 // less than OnePly).
1699 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1700 Depth depth, int ply, int threadID) {
1702 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1703 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1705 assert(ply >= 0 && ply < PLY_MAX);
1706 assert(threadID >= 0 && threadID < ActiveThreads);
1711 Value staticValue, bestValue, value, futilityBase, futilityValue;
1712 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1713 const TTEntry* tte = NULL;
1715 bool pvNode = (beta - alpha != 1);
1717 // Initialize, and make an early exit in case of an aborted search,
1718 // an instant draw, maximum ply reached, etc.
1719 init_node(ss, ply, threadID);
1721 // After init_node() that calls poll()
1722 if (AbortSearch || thread_should_stop(threadID))
1725 if (pos.is_draw() || ply >= PLY_MAX - 1)
1728 // Transposition table lookup. At PV nodes, we don't use the TT for
1729 // pruning, but only for move ordering.
1730 tte = TT.retrieve(pos.get_key());
1731 ttMove = (tte ? tte->move() : MOVE_NONE);
1733 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1735 assert(tte->type() != VALUE_TYPE_EVAL);
1737 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1738 return value_from_tt(tte->value(), ply);
1741 isCheck = pos.is_check();
1743 // Evaluate the position statically
1745 staticValue = -VALUE_INFINITE;
1746 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1747 staticValue = value_from_tt(tte->value(), ply);
1749 staticValue = evaluate(pos, ei, threadID);
1753 ss[ply].eval = staticValue;
1754 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1757 // Initialize "stand pat score", and return it immediately if it is
1759 bestValue = staticValue;
1761 if (bestValue >= beta)
1763 // Store the score to avoid a future costly evaluation() call
1764 if (!isCheck && !tte && ei.futilityMargin == 0)
1765 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1770 if (bestValue > alpha)
1773 // If we are near beta then try to get a cutoff pushing checks a bit further
1774 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1776 // Initialize a MovePicker object for the current position, and prepare
1777 // to search the moves. Because the depth is <= 0 here, only captures,
1778 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1779 // and we are near beta) will be generated.
1780 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1782 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1783 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1785 // Loop through the moves until no moves remain or a beta cutoff
1787 while ( alpha < beta
1788 && (move = mp.get_next_move()) != MOVE_NONE)
1790 assert(move_is_ok(move));
1792 moveIsCheck = pos.move_is_check(move, ci);
1794 // Update current move
1796 ss[ply].currentMove = move;
1804 && !move_is_promotion(move)
1805 && !pos.move_is_passed_pawn_push(move))
1807 futilityValue = futilityBase
1808 + pos.endgame_value_of_piece_on(move_to(move))
1809 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1811 if (futilityValue < alpha)
1813 if (futilityValue > bestValue)
1814 bestValue = futilityValue;
1819 // Detect blocking evasions that are candidate to be pruned
1820 evasionPrunable = isCheck
1821 && bestValue != -VALUE_INFINITE
1822 && !pos.move_is_capture(move)
1823 && pos.type_of_piece_on(move_from(move)) != KING
1824 && !pos.can_castle(pos.side_to_move());
1826 // Don't search moves with negative SEE values
1827 if ( (!isCheck || evasionPrunable)
1829 && !move_is_promotion(move)
1830 && pos.see_sign(move) < 0)
1833 // Make and search the move
1834 pos.do_move(move, st, ci, moveIsCheck);
1835 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1836 pos.undo_move(move);
1838 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1841 if (value > bestValue)
1852 // All legal moves have been searched. A special case: If we're in check
1853 // and no legal moves were found, it is checkmate.
1854 if (!moveCount && pos.is_check()) // Mate!
1855 return value_mated_in(ply);
1857 // Update transposition table
1858 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1859 if (bestValue < beta)
1861 // If bestValue isn't changed it means it is still the static evaluation
1862 // of the node, so keep this info to avoid a future evaluation() call.
1863 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1864 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1868 move = ss[ply].pv[ply];
1869 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1871 // Update killers only for good checking moves
1872 if (!pos.move_is_capture_or_promotion(move))
1873 update_killers(move, ss[ply]);
1876 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1882 // sp_search() is used to search from a split point. This function is called
1883 // by each thread working at the split point. It is similar to the normal
1884 // search() function, but simpler. Because we have already probed the hash
1885 // table, done a null move search, and searched the first move before
1886 // splitting, we don't have to repeat all this work in sp_search(). We
1887 // also don't need to store anything to the hash table here: This is taken
1888 // care of after we return from the split point.
1890 void sp_search(SplitPoint* sp, int threadID) {
1892 assert(threadID >= 0 && threadID < ActiveThreads);
1893 assert(ActiveThreads > 1);
1895 Position pos(*sp->pos);
1897 SearchStack* ss = sp->sstack[threadID];
1898 Value value = -VALUE_INFINITE;
1900 bool isCheck = pos.is_check();
1901 bool useFutilityPruning = sp->depth < SelectiveDepth
1904 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1906 while ( sp->bestValue < sp->beta
1907 && !thread_should_stop(threadID)
1908 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1910 assert(move_is_ok(move));
1912 bool moveIsCheck = pos.move_is_check(move, ci);
1913 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1915 lock_grab(&(sp->lock));
1916 int moveCount = ++sp->moves;
1917 lock_release(&(sp->lock));
1919 ss[sp->ply].currentMove = move;
1921 // Decide the new search depth.
1923 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1924 Depth newDepth = sp->depth - OnePly + ext;
1927 if ( useFutilityPruning
1929 && !captureOrPromotion)
1931 // Move count based pruning
1932 if ( moveCount >= FutilityMoveCountMargin
1933 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1934 && sp->bestValue > value_mated_in(PLY_MAX))
1937 // Value based pruning
1938 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1940 if (futilityValueScaled < sp->beta)
1942 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1944 lock_grab(&(sp->lock));
1945 if (futilityValueScaled > sp->bestValue)
1946 sp->bestValue = futilityValueScaled;
1947 lock_release(&(sp->lock));
1953 // Make and search the move.
1955 pos.do_move(move, st, ci, moveIsCheck);
1957 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1958 // if the move fails high will be re-searched at full depth.
1959 bool doFullDepthSearch = true;
1962 && !captureOrPromotion
1963 && !move_is_castle(move)
1964 && !move_is_killer(move, ss[sp->ply]))
1966 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 3.0;
1969 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1970 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1971 doFullDepthSearch = (value >= sp->beta);
1975 if (doFullDepthSearch) // Go with full depth non-pv search
1977 ss[sp->ply].reduction = Depth(0);
1978 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1980 pos.undo_move(move);
1982 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1984 if (thread_should_stop(threadID))
1988 if (value > sp->bestValue) // Less then 2% of cases
1990 lock_grab(&(sp->lock));
1991 if (value > sp->bestValue && !thread_should_stop(threadID))
1993 sp->bestValue = value;
1994 if (sp->bestValue >= sp->beta)
1996 sp_update_pv(sp->parentSstack, ss, sp->ply);
1997 for (int i = 0; i < ActiveThreads; i++)
1998 if (i != threadID && (i == sp->master || sp->slaves[i]))
1999 Threads[i].stop = true;
2001 sp->finished = true;
2004 lock_release(&(sp->lock));
2008 lock_grab(&(sp->lock));
2010 // If this is the master thread and we have been asked to stop because of
2011 // a beta cutoff higher up in the tree, stop all slave threads.
2012 if (sp->master == threadID && thread_should_stop(threadID))
2013 for (int i = 0; i < ActiveThreads; i++)
2015 Threads[i].stop = true;
2018 sp->slaves[threadID] = 0;
2020 lock_release(&(sp->lock));
2024 // sp_search_pv() is used to search from a PV split point. This function
2025 // is called by each thread working at the split point. It is similar to
2026 // the normal search_pv() function, but simpler. Because we have already
2027 // probed the hash table and searched the first move before splitting, we
2028 // don't have to repeat all this work in sp_search_pv(). We also don't
2029 // need to store anything to the hash table here: This is taken care of
2030 // after we return from the split point.
2032 void sp_search_pv(SplitPoint* sp, int threadID) {
2034 assert(threadID >= 0 && threadID < ActiveThreads);
2035 assert(ActiveThreads > 1);
2037 Position pos(*sp->pos);
2039 SearchStack* ss = sp->sstack[threadID];
2040 Value value = -VALUE_INFINITE;
2043 while ( sp->alpha < sp->beta
2044 && !thread_should_stop(threadID)
2045 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
2047 bool moveIsCheck = pos.move_is_check(move, ci);
2048 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2050 assert(move_is_ok(move));
2052 lock_grab(&(sp->lock));
2053 int moveCount = ++sp->moves;
2054 lock_release(&(sp->lock));
2056 ss[sp->ply].currentMove = move;
2058 // Decide the new search depth.
2060 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2061 Depth newDepth = sp->depth - OnePly + ext;
2063 // Make and search the move.
2065 pos.do_move(move, st, ci, moveIsCheck);
2067 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2068 // if the move fails high will be re-searched at full depth.
2069 bool doFullDepthSearch = true;
2072 && !captureOrPromotion
2073 && !move_is_castle(move)
2074 && !move_is_killer(move, ss[sp->ply]))
2076 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 6.0;
2079 Value localAlpha = sp->alpha;
2080 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
2081 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2082 doFullDepthSearch = (value > localAlpha);
2086 if (doFullDepthSearch) // Go with full depth non-pv search
2088 Value localAlpha = sp->alpha;
2089 ss[sp->ply].reduction = Depth(0);
2090 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2092 if (value > localAlpha && value < sp->beta)
2094 // When the search fails high at ply 1 while searching the first
2095 // move at the root, set the flag failHighPly1. This is used for
2096 // time managment: We don't want to stop the search early in
2097 // such cases, because resolving the fail high at ply 1 could
2098 // result in a big drop in score at the root.
2099 if (sp->ply == 1 && RootMoveNumber == 1)
2100 Threads[threadID].failHighPly1 = true;
2102 // If another thread has failed high then sp->alpha has been increased
2103 // to be higher or equal then beta, if so, avoid to start a PV search.
2104 localAlpha = sp->alpha;
2105 if (localAlpha < sp->beta)
2106 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2108 assert(thread_should_stop(threadID));
2110 Threads[threadID].failHighPly1 = false;
2113 pos.undo_move(move);
2115 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2117 if (thread_should_stop(threadID))
2121 if (value > sp->bestValue) // Less then 2% of cases
2123 lock_grab(&(sp->lock));
2124 if (value > sp->bestValue && !thread_should_stop(threadID))
2126 sp->bestValue = value;
2127 if (value > sp->alpha)
2129 // Ask threads to stop before to modify sp->alpha
2130 if (value >= sp->beta)
2132 for (int i = 0; i < ActiveThreads; i++)
2133 if (i != threadID && (i == sp->master || sp->slaves[i]))
2134 Threads[i].stop = true;
2136 sp->finished = true;
2141 sp_update_pv(sp->parentSstack, ss, sp->ply);
2142 if (value == value_mate_in(sp->ply + 1))
2143 ss[sp->ply].mateKiller = move;
2145 // If we are at ply 1, and we are searching the first root move at
2146 // ply 0, set the 'Problem' variable if the score has dropped a lot
2147 // (from the computer's point of view) since the previous iteration.
2150 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2153 lock_release(&(sp->lock));
2157 lock_grab(&(sp->lock));
2159 // If this is the master thread and we have been asked to stop because of
2160 // a beta cutoff higher up in the tree, stop all slave threads.
2161 if (sp->master == threadID && thread_should_stop(threadID))
2162 for (int i = 0; i < ActiveThreads; i++)
2164 Threads[i].stop = true;
2167 sp->slaves[threadID] = 0;
2169 lock_release(&(sp->lock));
2172 /// The BetaCounterType class
2174 BetaCounterType::BetaCounterType() { clear(); }
2176 void BetaCounterType::clear() {
2178 for (int i = 0; i < THREAD_MAX; i++)
2179 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2182 void BetaCounterType::add(Color us, Depth d, int threadID) {
2184 // Weighted count based on depth
2185 Threads[threadID].betaCutOffs[us] += unsigned(d);
2188 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2191 for (int i = 0; i < THREAD_MAX; i++)
2193 our += Threads[i].betaCutOffs[us];
2194 their += Threads[i].betaCutOffs[opposite_color(us)];
2199 /// The RootMoveList class
2201 // RootMoveList c'tor
2203 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2205 MoveStack mlist[MaxRootMoves];
2206 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2208 // Generate all legal moves
2209 MoveStack* last = generate_moves(pos, mlist);
2211 // Add each move to the moves[] array
2212 for (MoveStack* cur = mlist; cur != last; cur++)
2214 bool includeMove = includeAllMoves;
2216 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2217 includeMove = (searchMoves[k] == cur->move);
2222 // Find a quick score for the move
2224 SearchStack ss[PLY_MAX_PLUS_2];
2227 moves[count].move = cur->move;
2228 pos.do_move(moves[count].move, st);
2229 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2230 pos.undo_move(moves[count].move);
2231 moves[count].pv[0] = moves[count].move;
2232 moves[count].pv[1] = MOVE_NONE;
2239 // RootMoveList simple methods definitions
2241 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2243 moves[moveNum].nodes = nodes;
2244 moves[moveNum].cumulativeNodes += nodes;
2247 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2249 moves[moveNum].ourBeta = our;
2250 moves[moveNum].theirBeta = their;
2253 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2257 for (j = 0; pv[j] != MOVE_NONE; j++)
2258 moves[moveNum].pv[j] = pv[j];
2260 moves[moveNum].pv[j] = MOVE_NONE;
2264 // RootMoveList::sort() sorts the root move list at the beginning of a new
2267 void RootMoveList::sort() {
2269 sort_multipv(count - 1); // Sort all items
2273 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2274 // list by their scores and depths. It is used to order the different PVs
2275 // correctly in MultiPV mode.
2277 void RootMoveList::sort_multipv(int n) {
2281 for (i = 1; i <= n; i++)
2283 RootMove rm = moves[i];
2284 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2285 moves[j] = moves[j - 1];
2292 // init_node() is called at the beginning of all the search functions
2293 // (search(), search_pv(), qsearch(), and so on) and initializes the
2294 // search stack object corresponding to the current node. Once every
2295 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2296 // for user input and checks whether it is time to stop the search.
2298 void init_node(SearchStack ss[], int ply, int threadID) {
2300 assert(ply >= 0 && ply < PLY_MAX);
2301 assert(threadID >= 0 && threadID < ActiveThreads);
2303 Threads[threadID].nodes++;
2308 if (NodesSincePoll >= NodesBetweenPolls)
2315 ss[ply + 2].initKillers();
2317 if (Threads[threadID].printCurrentLine)
2318 print_current_line(ss, ply, threadID);
2322 // update_pv() is called whenever a search returns a value > alpha.
2323 // It updates the PV in the SearchStack object corresponding to the
2326 void update_pv(SearchStack ss[], int ply) {
2328 assert(ply >= 0 && ply < PLY_MAX);
2332 ss[ply].pv[ply] = ss[ply].currentMove;
2334 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2335 ss[ply].pv[p] = ss[ply + 1].pv[p];
2337 ss[ply].pv[p] = MOVE_NONE;
2341 // sp_update_pv() is a variant of update_pv for use at split points. The
2342 // difference between the two functions is that sp_update_pv also updates
2343 // the PV at the parent node.
2345 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2347 assert(ply >= 0 && ply < PLY_MAX);
2351 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2353 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2354 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2356 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2360 // connected_moves() tests whether two moves are 'connected' in the sense
2361 // that the first move somehow made the second move possible (for instance
2362 // if the moving piece is the same in both moves). The first move is assumed
2363 // to be the move that was made to reach the current position, while the
2364 // second move is assumed to be a move from the current position.
2366 bool connected_moves(const Position& pos, Move m1, Move m2) {
2368 Square f1, t1, f2, t2;
2371 assert(move_is_ok(m1));
2372 assert(move_is_ok(m2));
2374 if (m2 == MOVE_NONE)
2377 // Case 1: The moving piece is the same in both moves
2383 // Case 2: The destination square for m2 was vacated by m1
2389 // Case 3: Moving through the vacated square
2390 if ( piece_is_slider(pos.piece_on(f2))
2391 && bit_is_set(squares_between(f2, t2), f1))
2394 // Case 4: The destination square for m2 is defended by the moving piece in m1
2395 p = pos.piece_on(t1);
2396 if (bit_is_set(pos.attacks_from(p, t1), t2))
2399 // Case 5: Discovered check, checking piece is the piece moved in m1
2400 if ( piece_is_slider(p)
2401 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2402 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2404 // discovered_check_candidates() works also if the Position's side to
2405 // move is the opposite of the checking piece.
2406 Color them = opposite_color(pos.side_to_move());
2407 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2409 if (bit_is_set(dcCandidates, f2))
2416 // value_is_mate() checks if the given value is a mate one
2417 // eventually compensated for the ply.
2419 bool value_is_mate(Value value) {
2421 assert(abs(value) <= VALUE_INFINITE);
2423 return value <= value_mated_in(PLY_MAX)
2424 || value >= value_mate_in(PLY_MAX);
2428 // move_is_killer() checks if the given move is among the
2429 // killer moves of that ply.
2431 bool move_is_killer(Move m, const SearchStack& ss) {
2433 const Move* k = ss.killers;
2434 for (int i = 0; i < KILLER_MAX; i++, k++)
2442 // extension() decides whether a move should be searched with normal depth,
2443 // or with extended depth. Certain classes of moves (checking moves, in
2444 // particular) are searched with bigger depth than ordinary moves and in
2445 // any case are marked as 'dangerous'. Note that also if a move is not
2446 // extended, as example because the corresponding UCI option is set to zero,
2447 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2449 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2450 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2452 assert(m != MOVE_NONE);
2454 Depth result = Depth(0);
2455 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2460 result += CheckExtension[pvNode];
2463 result += SingleEvasionExtension[pvNode];
2466 result += MateThreatExtension[pvNode];
2469 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2471 Color c = pos.side_to_move();
2472 if (relative_rank(c, move_to(m)) == RANK_7)
2474 result += PawnPushTo7thExtension[pvNode];
2477 if (pos.pawn_is_passed(c, move_to(m)))
2479 result += PassedPawnExtension[pvNode];
2484 if ( captureOrPromotion
2485 && pos.type_of_piece_on(move_to(m)) != PAWN
2486 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2487 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2488 && !move_is_promotion(m)
2491 result += PawnEndgameExtension[pvNode];
2496 && captureOrPromotion
2497 && pos.type_of_piece_on(move_to(m)) != PAWN
2498 && pos.see_sign(m) >= 0)
2504 return Min(result, OnePly);
2508 // ok_to_do_nullmove() looks at the current position and decides whether
2509 // doing a 'null move' should be allowed. In order to avoid zugzwang
2510 // problems, null moves are not allowed when the side to move has very
2511 // little material left. Currently, the test is a bit too simple: Null
2512 // moves are avoided only when the side to move has only pawns left.
2513 // It's probably a good idea to avoid null moves in at least some more
2514 // complicated endgames, e.g. KQ vs KR. FIXME
2516 bool ok_to_do_nullmove(const Position& pos) {
2518 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2522 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2523 // non-tactical moves late in the move list close to the leaves are
2524 // candidates for pruning.
2526 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2528 assert(move_is_ok(m));
2529 assert(threat == MOVE_NONE || move_is_ok(threat));
2530 assert(!pos.move_is_check(m));
2531 assert(!pos.move_is_capture_or_promotion(m));
2532 assert(!pos.move_is_passed_pawn_push(m));
2534 Square mfrom, mto, tfrom, tto;
2536 // Prune if there isn't any threat move
2537 if (threat == MOVE_NONE)
2540 mfrom = move_from(m);
2542 tfrom = move_from(threat);
2543 tto = move_to(threat);
2545 // Case 1: Don't prune moves which move the threatened piece
2549 // Case 2: If the threatened piece has value less than or equal to the
2550 // value of the threatening piece, don't prune move which defend it.
2551 if ( pos.move_is_capture(threat)
2552 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2553 || pos.type_of_piece_on(tfrom) == KING)
2554 && pos.move_attacks_square(m, tto))
2557 // Case 3: If the moving piece in the threatened move is a slider, don't
2558 // prune safe moves which block its ray.
2559 if ( piece_is_slider(pos.piece_on(tfrom))
2560 && bit_is_set(squares_between(tfrom, tto), mto)
2561 && pos.see_sign(m) >= 0)
2568 // ok_to_use_TT() returns true if a transposition table score
2569 // can be used at a given point in search.
2571 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2573 Value v = value_from_tt(tte->value(), ply);
2575 return ( tte->depth() >= depth
2576 || v >= Max(value_mate_in(PLY_MAX), beta)
2577 || v < Min(value_mated_in(PLY_MAX), beta))
2579 && ( (is_lower_bound(tte->type()) && v >= beta)
2580 || (is_upper_bound(tte->type()) && v < beta));
2584 // refine_eval() returns the transposition table score if
2585 // possible otherwise falls back on static position evaluation.
2587 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2592 Value v = value_from_tt(tte->value(), ply);
2594 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2595 || (is_upper_bound(tte->type()) && v < defaultEval))
2601 // update_history() registers a good move that produced a beta-cutoff
2602 // in history and marks as failures all the other moves of that ply.
2604 void update_history(const Position& pos, Move move, Depth depth,
2605 Move movesSearched[], int moveCount) {
2609 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2611 for (int i = 0; i < moveCount - 1; i++)
2613 m = movesSearched[i];
2617 if (!pos.move_is_capture_or_promotion(m))
2618 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2623 // update_killers() add a good move that produced a beta-cutoff
2624 // among the killer moves of that ply.
2626 void update_killers(Move m, SearchStack& ss) {
2628 if (m == ss.killers[0])
2631 for (int i = KILLER_MAX - 1; i > 0; i--)
2632 ss.killers[i] = ss.killers[i - 1];
2638 // update_gains() updates the gains table of a non-capture move given
2639 // the static position evaluation before and after the move.
2641 void update_gains(const Position& pos, Move m, Value before, Value after) {
2644 && before != VALUE_NONE
2645 && after != VALUE_NONE
2646 && pos.captured_piece() == NO_PIECE_TYPE
2647 && !move_is_castle(m)
2648 && !move_is_promotion(m))
2649 MG.store(pos.piece_on(move_to(m)), move_from(m), move_to(m), -(before + after));
2653 // fail_high_ply_1() checks if some thread is currently resolving a fail
2654 // high at ply 1 at the node below the first root node. This information
2655 // is used for time management.
2657 bool fail_high_ply_1() {
2659 for (int i = 0; i < ActiveThreads; i++)
2660 if (Threads[i].failHighPly1)
2667 // current_search_time() returns the number of milliseconds which have passed
2668 // since the beginning of the current search.
2670 int current_search_time() {
2672 return get_system_time() - SearchStartTime;
2676 // nps() computes the current nodes/second count.
2680 int t = current_search_time();
2681 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2685 // poll() performs two different functions: It polls for user input, and it
2686 // looks at the time consumed so far and decides if it's time to abort the
2691 static int lastInfoTime;
2692 int t = current_search_time();
2697 // We are line oriented, don't read single chars
2698 std::string command;
2700 if (!std::getline(std::cin, command))
2703 if (command == "quit")
2706 PonderSearch = false;
2710 else if (command == "stop")
2713 PonderSearch = false;
2715 else if (command == "ponderhit")
2719 // Print search information
2723 else if (lastInfoTime > t)
2724 // HACK: Must be a new search where we searched less than
2725 // NodesBetweenPolls nodes during the first second of search.
2728 else if (t - lastInfoTime >= 1000)
2736 if (dbg_show_hit_rate)
2737 dbg_print_hit_rate();
2739 cout << "info nodes " << nodes_searched() << " nps " << nps()
2740 << " time " << t << " hashfull " << TT.full() << endl;
2742 lock_release(&IOLock);
2744 if (ShowCurrentLine)
2745 Threads[0].printCurrentLine = true;
2748 // Should we stop the search?
2752 bool stillAtFirstMove = RootMoveNumber == 1
2754 && t > MaxSearchTime + ExtraSearchTime;
2756 bool noProblemFound = !FailHigh
2758 && !fail_high_ply_1()
2760 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2762 bool noMoreTime = t > AbsoluteMaxSearchTime
2763 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2766 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2767 || (ExactMaxTime && t >= ExactMaxTime)
2768 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2773 // ponderhit() is called when the program is pondering (i.e. thinking while
2774 // it's the opponent's turn to move) in order to let the engine know that
2775 // it correctly predicted the opponent's move.
2779 int t = current_search_time();
2780 PonderSearch = false;
2782 bool stillAtFirstMove = RootMoveNumber == 1
2784 && t > MaxSearchTime + ExtraSearchTime;
2786 bool noProblemFound = !FailHigh
2788 && !fail_high_ply_1()
2790 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2792 bool noMoreTime = t > AbsoluteMaxSearchTime
2796 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2801 // print_current_line() prints the current line of search for a given
2802 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2804 void print_current_line(SearchStack ss[], int ply, int threadID) {
2806 assert(ply >= 0 && ply < PLY_MAX);
2807 assert(threadID >= 0 && threadID < ActiveThreads);
2809 if (!Threads[threadID].idle)
2812 cout << "info currline " << (threadID + 1);
2813 for (int p = 0; p < ply; p++)
2814 cout << " " << ss[p].currentMove;
2817 lock_release(&IOLock);
2819 Threads[threadID].printCurrentLine = false;
2820 if (threadID + 1 < ActiveThreads)
2821 Threads[threadID + 1].printCurrentLine = true;
2825 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2827 void init_ss_array(SearchStack ss[]) {
2829 for (int i = 0; i < 3; i++)
2832 ss[i].initKillers();
2837 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2838 // while the program is pondering. The point is to work around a wrinkle in
2839 // the UCI protocol: When pondering, the engine is not allowed to give a
2840 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2841 // We simply wait here until one of these commands is sent, and return,
2842 // after which the bestmove and pondermove will be printed (in id_loop()).
2844 void wait_for_stop_or_ponderhit() {
2846 std::string command;
2850 if (!std::getline(std::cin, command))
2853 if (command == "quit")
2858 else if (command == "ponderhit" || command == "stop")
2864 // idle_loop() is where the threads are parked when they have no work to do.
2865 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2866 // object for which the current thread is the master.
2868 void idle_loop(int threadID, SplitPoint* waitSp) {
2870 assert(threadID >= 0 && threadID < THREAD_MAX);
2872 Threads[threadID].running = true;
2876 if (AllThreadsShouldExit && threadID != 0)
2879 // If we are not thinking, wait for a condition to be signaled
2880 // instead of wasting CPU time polling for work.
2881 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2884 #if !defined(_MSC_VER)
2885 pthread_mutex_lock(&WaitLock);
2886 if (Idle || threadID >= ActiveThreads)
2887 pthread_cond_wait(&WaitCond, &WaitLock);
2889 pthread_mutex_unlock(&WaitLock);
2891 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2895 // If this thread has been assigned work, launch a search
2896 if (Threads[threadID].workIsWaiting)
2898 assert(!Threads[threadID].idle);
2900 Threads[threadID].workIsWaiting = false;
2901 if (Threads[threadID].splitPoint->pvNode)
2902 sp_search_pv(Threads[threadID].splitPoint, threadID);
2904 sp_search(Threads[threadID].splitPoint, threadID);
2906 Threads[threadID].idle = true;
2909 // If this thread is the master of a split point and all threads have
2910 // finished their work at this split point, return from the idle loop.
2911 if (waitSp != NULL && waitSp->cpus == 0)
2915 Threads[threadID].running = false;
2919 // init_split_point_stack() is called during program initialization, and
2920 // initializes all split point objects.
2922 void init_split_point_stack() {
2924 for (int i = 0; i < THREAD_MAX; i++)
2925 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2927 SplitPointStack[i][j].parent = NULL;
2928 lock_init(&(SplitPointStack[i][j].lock), NULL);
2933 // destroy_split_point_stack() is called when the program exits, and
2934 // destroys all locks in the precomputed split point objects.
2936 void destroy_split_point_stack() {
2938 for (int i = 0; i < THREAD_MAX; i++)
2939 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2940 lock_destroy(&(SplitPointStack[i][j].lock));
2944 // thread_should_stop() checks whether the thread with a given threadID has
2945 // been asked to stop, directly or indirectly. This can happen if a beta
2946 // cutoff has occurred in the thread's currently active split point, or in
2947 // some ancestor of the current split point.
2949 bool thread_should_stop(int threadID) {
2951 assert(threadID >= 0 && threadID < ActiveThreads);
2955 if (Threads[threadID].stop)
2957 if (ActiveThreads <= 2)
2959 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2962 Threads[threadID].stop = true;
2969 // thread_is_available() checks whether the thread with threadID "slave" is
2970 // available to help the thread with threadID "master" at a split point. An
2971 // obvious requirement is that "slave" must be idle. With more than two
2972 // threads, this is not by itself sufficient: If "slave" is the master of
2973 // some active split point, it is only available as a slave to the other
2974 // threads which are busy searching the split point at the top of "slave"'s
2975 // split point stack (the "helpful master concept" in YBWC terminology).
2977 bool thread_is_available(int slave, int master) {
2979 assert(slave >= 0 && slave < ActiveThreads);
2980 assert(master >= 0 && master < ActiveThreads);
2981 assert(ActiveThreads > 1);
2983 if (!Threads[slave].idle || slave == master)
2986 // Make a local copy to be sure doesn't change under our feet
2987 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
2989 if (localActiveSplitPoints == 0)
2990 // No active split points means that the thread is available as
2991 // a slave for any other thread.
2994 if (ActiveThreads == 2)
2997 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2998 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
2999 // could have been set to 0 by another thread leading to an out of bound access.
3000 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
3007 // idle_thread_exists() tries to find an idle thread which is available as
3008 // a slave for the thread with threadID "master".
3010 bool idle_thread_exists(int master) {
3012 assert(master >= 0 && master < ActiveThreads);
3013 assert(ActiveThreads > 1);
3015 for (int i = 0; i < ActiveThreads; i++)
3016 if (thread_is_available(i, master))
3023 // split() does the actual work of distributing the work at a node between
3024 // several threads at PV nodes. If it does not succeed in splitting the
3025 // node (because no idle threads are available, or because we have no unused
3026 // split point objects), the function immediately returns false. If
3027 // splitting is possible, a SplitPoint object is initialized with all the
3028 // data that must be copied to the helper threads (the current position and
3029 // search stack, alpha, beta, the search depth, etc.), and we tell our
3030 // helper threads that they have been assigned work. This will cause them
3031 // to instantly leave their idle loops and call sp_search_pv(). When all
3032 // threads have returned from sp_search_pv (or, equivalently, when
3033 // splitPoint->cpus becomes 0), split() returns true.
3035 bool split(const Position& p, SearchStack* sstck, int ply,
3036 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
3037 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
3040 assert(sstck != NULL);
3041 assert(ply >= 0 && ply < PLY_MAX);
3042 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
3043 assert(!pvNode || *alpha < *beta);
3044 assert(*beta <= VALUE_INFINITE);
3045 assert(depth > Depth(0));
3046 assert(master >= 0 && master < ActiveThreads);
3047 assert(ActiveThreads > 1);
3049 SplitPoint* splitPoint;
3053 // If no other thread is available to help us, or if we have too many
3054 // active split points, don't split.
3055 if ( !idle_thread_exists(master)
3056 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
3058 lock_release(&MPLock);
3062 // Pick the next available split point object from the split point stack
3063 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
3064 Threads[master].activeSplitPoints++;
3066 // Initialize the split point object
3067 splitPoint->parent = Threads[master].splitPoint;
3068 splitPoint->finished = false;
3069 splitPoint->ply = ply;
3070 splitPoint->depth = depth;
3071 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
3072 splitPoint->beta = *beta;
3073 splitPoint->pvNode = pvNode;
3074 splitPoint->bestValue = *bestValue;
3075 splitPoint->futilityValue = futilityValue;
3076 splitPoint->master = master;
3077 splitPoint->mp = mp;
3078 splitPoint->moves = *moves;
3079 splitPoint->cpus = 1;
3080 splitPoint->pos = &p;
3081 splitPoint->parentSstack = sstck;
3082 for (int i = 0; i < ActiveThreads; i++)
3083 splitPoint->slaves[i] = 0;
3085 Threads[master].idle = false;
3086 Threads[master].stop = false;
3087 Threads[master].splitPoint = splitPoint;
3089 // Allocate available threads setting idle flag to false
3090 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3091 if (thread_is_available(i, master))
3093 Threads[i].idle = false;
3094 Threads[i].stop = false;
3095 Threads[i].splitPoint = splitPoint;
3096 splitPoint->slaves[i] = 1;
3100 assert(splitPoint->cpus > 1);
3102 // We can release the lock because master and slave threads are already booked
3103 lock_release(&MPLock);
3105 // Tell the threads that they have work to do. This will make them leave
3106 // their idle loop. But before copy search stack tail for each thread.
3107 for (int i = 0; i < ActiveThreads; i++)
3108 if (i == master || splitPoint->slaves[i])
3110 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3111 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3114 // Everything is set up. The master thread enters the idle loop, from
3115 // which it will instantly launch a search, because its workIsWaiting
3116 // slot is 'true'. We send the split point as a second parameter to the
3117 // idle loop, which means that the main thread will return from the idle
3118 // loop when all threads have finished their work at this split point
3119 // (i.e. when splitPoint->cpus == 0).
3120 idle_loop(master, splitPoint);
3122 // We have returned from the idle loop, which means that all threads are
3123 // finished. Update alpha, beta and bestValue, and return.
3127 *alpha = splitPoint->alpha;
3129 *beta = splitPoint->beta;
3130 *bestValue = splitPoint->bestValue;
3131 Threads[master].stop = false;
3132 Threads[master].idle = false;
3133 Threads[master].activeSplitPoints--;
3134 Threads[master].splitPoint = splitPoint->parent;
3136 lock_release(&MPLock);
3141 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3142 // to start a new search from the root.
3144 void wake_sleeping_threads() {
3146 if (ActiveThreads > 1)
3148 for (int i = 1; i < ActiveThreads; i++)
3150 Threads[i].idle = true;
3151 Threads[i].workIsWaiting = false;
3154 #if !defined(_MSC_VER)
3155 pthread_mutex_lock(&WaitLock);
3156 pthread_cond_broadcast(&WaitCond);
3157 pthread_mutex_unlock(&WaitLock);
3159 for (int i = 1; i < THREAD_MAX; i++)
3160 SetEvent(SitIdleEvent[i]);
3166 // init_thread() is the function which is called when a new thread is
3167 // launched. It simply calls the idle_loop() function with the supplied
3168 // threadID. There are two versions of this function; one for POSIX
3169 // threads and one for Windows threads.
3171 #if !defined(_MSC_VER)
3173 void* init_thread(void *threadID) {
3175 idle_loop(*(int*)threadID, NULL);
3181 DWORD WINAPI init_thread(LPVOID threadID) {
3183 idle_loop(*(int*)threadID, NULL);