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/>.
43 #include "ucioption.h"
49 //// Local definitions
56 // IterationInfoType stores search results for each iteration
58 // Because we use relatively small (dynamic) aspiration window,
59 // there happens many fail highs and fail lows in root. And
60 // because we don't do researches in those cases, "value" stored
61 // here is not necessarily exact. Instead in case of fail high/low
62 // we guess what the right value might be and store our guess
63 // as a "speculated value" and then move on. Speculated values are
64 // used just to calculate aspiration window width, so also if are
65 // not exact is not big a problem.
67 struct IterationInfoType {
69 IterationInfoType(Value v = Value(0), Value sv = Value(0))
70 : value(v), speculatedValue(sv) {}
72 Value value, speculatedValue;
76 // The BetaCounterType class is used to order moves at ply one.
77 // Apart for the first one that has its score, following moves
78 // normally have score -VALUE_INFINITE, so are ordered according
79 // to the number of beta cutoffs occurred under their subtree during
80 // the last iteration. The counters are per thread variables to avoid
81 // concurrent accessing under SMP case.
83 struct BetaCounterType {
87 void add(Color us, Depth d, int threadID);
88 void read(Color us, int64_t& our, int64_t& their);
92 // The RootMove class is used for moves at the root at the tree. For each
93 // root move, we store a score, a node count, and a PV (really a refutation
94 // in the case of moves which fail low).
98 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
100 // RootMove::operator<() is the comparison function used when
101 // sorting the moves. A move m1 is considered to be better
102 // than a move m2 if it has a higher score, or if the moves
103 // have equal score but m1 has the higher node count.
104 bool operator<(const RootMove& m) const {
106 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
111 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
112 Move pv[PLY_MAX_PLUS_2];
116 // The RootMoveList class is essentially an array of RootMove objects, with
117 // a handful of methods for accessing the data in the individual moves.
122 RootMoveList(Position& pos, Move searchMoves[]);
124 int move_count() const { return count; }
125 Move get_move(int moveNum) const { return moves[moveNum].move; }
126 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
127 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
128 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
129 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
131 void set_move_nodes(int moveNum, int64_t nodes);
132 void set_beta_counters(int moveNum, int64_t our, int64_t their);
133 void set_move_pv(int moveNum, const Move pv[]);
135 void sort_multipv(int n);
138 static const int MaxRootMoves = 500;
139 RootMove moves[MaxRootMoves];
146 // Search depth at iteration 1
147 const Depth InitialDepth = OnePly;
149 // Depth limit for selective search
150 const Depth SelectiveDepth = 7 * OnePly;
152 // Use internal iterative deepening?
153 const bool UseIIDAtPVNodes = true;
154 const bool UseIIDAtNonPVNodes = true;
156 // Internal iterative deepening margin. At Non-PV moves, when
157 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
158 // search when the static evaluation is at most IIDMargin below beta.
159 const Value IIDMargin = Value(0x100);
161 // Easy move margin. An easy move candidate must be at least this much
162 // better than the second best move.
163 const Value EasyMoveMargin = Value(0x200);
165 // Problem margin. If the score of the first move at iteration N+1 has
166 // dropped by more than this since iteration N, the boolean variable
167 // "Problem" is set to true, which will make the program spend some extra
168 // time looking for a better move.
169 const Value ProblemMargin = Value(0x28);
171 // No problem margin. If the boolean "Problem" is true, and a new move
172 // is found at the root which is less than NoProblemMargin worse than the
173 // best move from the previous iteration, Problem is set back to false.
174 const Value NoProblemMargin = Value(0x14);
176 // Null move margin. A null move search will not be done if the static
177 // evaluation of the position is more than NullMoveMargin below beta.
178 const Value NullMoveMargin = Value(0x200);
180 // If the TT move is at least SingleReplyMargin better then the
181 // remaining ones we will extend it.
182 const Value SingleReplyMargin = Value(0x20);
184 // Margins for futility pruning in the quiescence search, and at frontier
185 // and near frontier nodes.
186 const Value FutilityMarginQS = Value(0x80);
188 // Each move futility margin is decreased
189 const Value IncrementalFutilityMargin = Value(0x8);
191 // Depth limit for razoring
192 const Depth RazorDepth = 4 * OnePly;
194 /// Variables initialized by UCI options
196 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
197 int LMRPVMoves, LMRNonPVMoves;
199 // Depth limit for use of dynamic threat detection
202 // Last seconds noise filtering (LSN)
203 const bool UseLSNFiltering = true;
204 const int LSNTime = 4000; // In milliseconds
205 const Value LSNValue = value_from_centipawns(200);
206 bool loseOnTime = false;
208 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
209 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
210 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
212 // Iteration counters
214 BetaCounterType BetaCounter;
216 // Scores and number of times the best move changed for each iteration
217 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
218 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
223 // Time managment variables
226 int MaxNodes, MaxDepth;
227 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
228 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
229 bool AbortSearch, Quit;
230 bool FailHigh, FailLow, Problem;
232 // Show current line?
233 bool ShowCurrentLine;
237 std::ofstream LogFile;
239 // Natural logarithmic lookup table and its getter function
241 inline double ln(int i) { return lnArray[i]; }
243 // MP related variables
244 int ActiveThreads = 1;
245 Depth MinimumSplitDepth;
246 int MaxThreadsPerSplitPoint;
247 Thread Threads[THREAD_MAX];
250 bool AllThreadsShouldExit = false;
251 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
254 #if !defined(_MSC_VER)
255 pthread_cond_t WaitCond;
256 pthread_mutex_t WaitLock;
258 HANDLE SitIdleEvent[THREAD_MAX];
261 // Node counters, used only by thread[0] but try to keep in different
262 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
264 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);
293 bool fail_high_ply_1();
294 int current_search_time();
298 void print_current_line(SearchStack ss[], int ply, int threadID);
299 void wait_for_stop_or_ponderhit();
300 void init_ss_array(SearchStack ss[]);
302 void idle_loop(int threadID, SplitPoint* waitSp);
303 void init_split_point_stack();
304 void destroy_split_point_stack();
305 bool thread_should_stop(int threadID);
306 bool thread_is_available(int slave, int master);
307 bool idle_thread_exists(int master);
308 bool split(const Position& pos, SearchStack* ss, int ply,
309 Value *alpha, Value *beta, Value *bestValue,
310 const Value futilityValue, Depth depth, int *moves,
311 MovePicker *mp, int master, bool pvNode);
312 void wake_sleeping_threads();
314 #if !defined(_MSC_VER)
315 void *init_thread(void *threadID);
317 DWORD WINAPI init_thread(LPVOID threadID);
328 /// perft() is our utility to verify move generation is bug free. All the legal
329 /// moves up to given depth are generated and counted and the sum returned.
331 int perft(Position& pos, Depth depth)
335 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
337 // If we are at the last ply we don't need to do and undo
338 // the moves, just to count them.
339 if (depth <= OnePly) // Replace with '<' to test also qsearch
341 while (mp.get_next_move()) sum++;
345 // Loop through all legal moves
347 while ((move = mp.get_next_move()) != MOVE_NONE)
350 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
351 sum += perft(pos, depth - OnePly);
358 /// think() is the external interface to Stockfish's search, and is called when
359 /// the program receives the UCI 'go' command. It initializes various
360 /// search-related global variables, and calls root_search(). It returns false
361 /// when a quit command is received during the search.
363 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
364 int time[], int increment[], int movesToGo, int maxDepth,
365 int maxNodes, int maxTime, Move searchMoves[]) {
367 // Initialize global search variables
368 Idle = StopOnPonderhit = AbortSearch = Quit = false;
369 FailHigh = FailLow = Problem = false;
371 SearchStartTime = get_system_time();
372 ExactMaxTime = maxTime;
375 InfiniteSearch = infinite;
376 PonderSearch = ponder;
377 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
379 // Look for a book move, only during games, not tests
380 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
383 if (get_option_value_string("Book File") != OpeningBook.file_name())
384 OpeningBook.open(get_option_value_string("Book File"));
386 bookMove = OpeningBook.get_move(pos);
387 if (bookMove != MOVE_NONE)
389 cout << "bestmove " << bookMove << endl;
394 for (int i = 0; i < THREAD_MAX; i++)
396 Threads[i].nodes = 0ULL;
397 Threads[i].failHighPly1 = false;
400 if (button_was_pressed("New Game"))
401 loseOnTime = false; // Reset at the beginning of a new game
403 // Read UCI option values
404 TT.set_size(get_option_value_int("Hash"));
405 if (button_was_pressed("Clear Hash"))
408 bool PonderingEnabled = get_option_value_bool("Ponder");
409 MultiPV = get_option_value_int("MultiPV");
411 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
412 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
414 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
415 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
417 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
418 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
420 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
421 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
423 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
424 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
426 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
427 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
429 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
430 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
431 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
433 Chess960 = get_option_value_bool("UCI_Chess960");
434 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
435 UseLogFile = get_option_value_bool("Use Search Log");
437 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
439 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
440 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
442 read_weights(pos.side_to_move());
444 // Set the number of active threads
445 int newActiveThreads = get_option_value_int("Threads");
446 if (newActiveThreads != ActiveThreads)
448 ActiveThreads = newActiveThreads;
449 init_eval(ActiveThreads);
452 // Wake up sleeping threads
453 wake_sleeping_threads();
455 for (int i = 1; i < ActiveThreads; i++)
456 assert(thread_is_available(i, 0));
459 int myTime = time[side_to_move];
460 int myIncrement = increment[side_to_move];
461 if (UseTimeManagement)
463 if (!movesToGo) // Sudden death time control
467 MaxSearchTime = myTime / 30 + myIncrement;
468 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
470 else // Blitz game without increment
472 MaxSearchTime = myTime / 30;
473 AbsoluteMaxSearchTime = myTime / 8;
476 else // (x moves) / (y minutes)
480 MaxSearchTime = myTime / 2;
481 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
485 MaxSearchTime = myTime / Min(movesToGo, 20);
486 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
490 if (PonderingEnabled)
492 MaxSearchTime += MaxSearchTime / 4;
493 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
497 // Set best NodesBetweenPolls interval
499 NodesBetweenPolls = Min(MaxNodes, 30000);
500 else if (myTime && myTime < 1000)
501 NodesBetweenPolls = 1000;
502 else if (myTime && myTime < 5000)
503 NodesBetweenPolls = 5000;
505 NodesBetweenPolls = 30000;
507 // Write information to search log file
509 LogFile << "Searching: " << pos.to_fen() << endl
510 << "infinite: " << infinite
511 << " ponder: " << ponder
512 << " time: " << myTime
513 << " increment: " << myIncrement
514 << " moves to go: " << movesToGo << endl;
516 // LSN filtering. Used only for developing purpose. Disabled by default.
520 // Step 2. If after last move we decided to lose on time, do it now!
521 while (SearchStartTime + myTime + 1000 > get_system_time())
525 // We're ready to start thinking. Call the iterative deepening loop function
526 Value v = id_loop(pos, searchMoves);
531 // Step 1. If this is sudden death game and our position is hopeless,
532 // decide to lose on time.
533 if ( !loseOnTime // If we already lost on time, go to step 3.
543 // Step 3. Now after stepping over the time limit, reset flag for next match.
556 /// init_threads() is called during startup. It launches all helper threads,
557 /// and initializes the split point stack and the global locks and condition
560 void init_threads() {
564 #if !defined(_MSC_VER)
565 pthread_t pthread[1];
568 // Init our logarithmic lookup table
569 for (int i = 0; i < 512; i++)
570 lnArray[i] = log(double(i)); // log() returns base-e logarithm
572 for (i = 0; i < THREAD_MAX; i++)
573 Threads[i].activeSplitPoints = 0;
575 // Initialize global locks
576 lock_init(&MPLock, NULL);
577 lock_init(&IOLock, NULL);
579 init_split_point_stack();
581 #if !defined(_MSC_VER)
582 pthread_mutex_init(&WaitLock, NULL);
583 pthread_cond_init(&WaitCond, NULL);
585 for (i = 0; i < THREAD_MAX; i++)
586 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
589 // All threads except the main thread should be initialized to idle state
590 for (i = 1; i < THREAD_MAX; i++)
592 Threads[i].stop = false;
593 Threads[i].workIsWaiting = false;
594 Threads[i].idle = true;
595 Threads[i].running = false;
598 // Launch the helper threads
599 for (i = 1; i < THREAD_MAX; i++)
601 #if !defined(_MSC_VER)
602 pthread_create(pthread, NULL, init_thread, (void*)(&i));
605 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
608 // Wait until the thread has finished launching
609 while (!Threads[i].running);
614 /// stop_threads() is called when the program exits. It makes all the
615 /// helper threads exit cleanly.
617 void stop_threads() {
619 ActiveThreads = THREAD_MAX; // HACK
620 Idle = false; // HACK
621 wake_sleeping_threads();
622 AllThreadsShouldExit = true;
623 for (int i = 1; i < THREAD_MAX; i++)
625 Threads[i].stop = true;
626 while (Threads[i].running);
628 destroy_split_point_stack();
632 /// nodes_searched() returns the total number of nodes searched so far in
633 /// the current search.
635 int64_t nodes_searched() {
637 int64_t result = 0ULL;
638 for (int i = 0; i < ActiveThreads; i++)
639 result += Threads[i].nodes;
644 // SearchStack::init() initializes a search stack. Used at the beginning of a
645 // new search from the root.
646 void SearchStack::init(int ply) {
648 pv[ply] = pv[ply + 1] = MOVE_NONE;
649 currentMove = threatMove = MOVE_NONE;
650 reduction = Depth(0);
655 void SearchStack::initKillers() {
657 mateKiller = MOVE_NONE;
658 for (int i = 0; i < KILLER_MAX; i++)
659 killers[i] = MOVE_NONE;
664 // id_loop() is the main iterative deepening loop. It calls root_search
665 // repeatedly with increasing depth until the allocated thinking time has
666 // been consumed, the user stops the search, or the maximum search depth is
669 Value id_loop(const Position& pos, Move searchMoves[]) {
672 SearchStack ss[PLY_MAX_PLUS_2];
674 // searchMoves are verified, copied, scored and sorted
675 RootMoveList rml(p, searchMoves);
677 if (rml.move_count() == 0)
680 wait_for_stop_or_ponderhit();
682 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
685 // Print RootMoveList c'tor startup scoring to the standard output,
686 // so that we print information also for iteration 1.
687 cout << "info depth " << 1 << "\ninfo depth " << 1
688 << " score " << value_to_string(rml.get_move_score(0))
689 << " time " << current_search_time()
690 << " nodes " << nodes_searched()
692 << " pv " << rml.get_move(0) << "\n";
698 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
701 // Is one move significantly better than others after initial scoring ?
702 Move EasyMove = MOVE_NONE;
703 if ( rml.move_count() == 1
704 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
705 EasyMove = rml.get_move(0);
707 // Iterative deepening loop
708 while (Iteration < PLY_MAX)
710 // Initialize iteration
713 BestMoveChangesByIteration[Iteration] = 0;
717 cout << "info depth " << Iteration << endl;
719 // Calculate dynamic search window based on previous iterations
722 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
724 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
725 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
727 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
729 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
730 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
734 alpha = - VALUE_INFINITE;
735 beta = VALUE_INFINITE;
738 // Search to the current depth
739 Value value = root_search(p, ss, rml, alpha, beta);
741 // Write PV to transposition table, in case the relevant entries have
742 // been overwritten during the search.
743 TT.insert_pv(p, ss[0].pv);
746 break; // Value cannot be trusted. Break out immediately!
748 //Save info about search result
749 Value speculatedValue;
752 Value delta = value - IterationInfo[Iteration - 1].value;
759 speculatedValue = value + delta;
760 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
762 else if (value <= alpha)
764 assert(value == alpha);
768 speculatedValue = value + delta;
769 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
771 speculatedValue = value;
773 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
774 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
776 // Drop the easy move if it differs from the new best move
777 if (ss[0].pv[0] != EasyMove)
778 EasyMove = MOVE_NONE;
782 if (UseTimeManagement)
785 bool stopSearch = false;
787 // Stop search early if there is only a single legal move,
788 // we search up to Iteration 6 anyway to get a proper score.
789 if (Iteration >= 6 && rml.move_count() == 1)
792 // Stop search early when the last two iterations returned a mate score
794 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
795 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
798 // Stop search early if one move seems to be much better than the rest
799 int64_t nodes = nodes_searched();
803 && EasyMove == ss[0].pv[0]
804 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
805 && current_search_time() > MaxSearchTime / 16)
806 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
807 && current_search_time() > MaxSearchTime / 32)))
810 // Add some extra time if the best move has changed during the last two iterations
811 if (Iteration > 5 && Iteration <= 50)
812 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
813 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
815 // Stop search if most of MaxSearchTime is consumed at the end of the
816 // iteration. We probably don't have enough time to search the first
817 // move at the next iteration anyway.
818 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
826 StopOnPonderhit = true;
830 if (MaxDepth && Iteration >= MaxDepth)
836 // If we are pondering or in infinite search, we shouldn't print the
837 // best move before we are told to do so.
838 if (!AbortSearch && (PonderSearch || InfiniteSearch))
839 wait_for_stop_or_ponderhit();
841 // Print final search statistics
842 cout << "info nodes " << nodes_searched()
844 << " time " << current_search_time()
845 << " hashfull " << TT.full() << endl;
847 // Print the best move and the ponder move to the standard output
848 if (ss[0].pv[0] == MOVE_NONE)
850 ss[0].pv[0] = rml.get_move(0);
851 ss[0].pv[1] = MOVE_NONE;
853 cout << "bestmove " << ss[0].pv[0];
854 if (ss[0].pv[1] != MOVE_NONE)
855 cout << " ponder " << ss[0].pv[1];
862 dbg_print_mean(LogFile);
864 if (dbg_show_hit_rate)
865 dbg_print_hit_rate(LogFile);
867 LogFile << "\nNodes: " << nodes_searched()
868 << "\nNodes/second: " << nps()
869 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
872 p.do_move(ss[0].pv[0], st);
873 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
875 return rml.get_move_score(0);
879 // root_search() is the function which searches the root node. It is
880 // similar to search_pv except that it uses a different move ordering
881 // scheme 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;
886 Value value = -VALUE_INFINITE;
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);
903 Depth depth, ext, newDepth;
905 RootMoveNumber = i + 1;
908 // Save the current node count before the move is searched
909 nodes = nodes_searched();
911 // Reset beta cut-off counters
914 // Pick the next root move, and print the move and the move number to
915 // the standard output.
916 move = ss[0].currentMove = rml.get_move(i);
918 if (current_search_time() >= 1000)
919 cout << "info currmove " << move
920 << " currmovenumber " << RootMoveNumber << 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 depth = (Iteration - 2) * OnePly + InitialDepth;
927 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
928 newDepth = depth + ext;
930 // Make the move, and search it
931 pos.do_move(move, st, ci, moveIsCheck);
935 // Aspiration window is disabled in multi-pv case
937 alpha = -VALUE_INFINITE;
939 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
941 // If the value has dropped a lot compared to the last iteration,
942 // set the boolean variable Problem to true. This variable is used
943 // for time managment: When Problem is true, we try to complete the
944 // current iteration before playing a move.
945 Problem = ( Iteration >= 2
946 && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
948 if (Problem && StopOnPonderhit)
949 StopOnPonderhit = false;
953 // Try to reduce non-pv search depth by one ply if move seems not problematic,
954 // if the move fails high will be re-searched at full depth.
955 bool doFullDepthSearch = true;
957 if ( depth >= 3*OnePly // FIXME was newDepth
959 && !captureOrPromotion
960 && !move_is_castle(move))
962 double red = 0.5 + ln(RootMoveNumber - MultiPV + 1) * ln(depth / 2) / 6.0;
965 ss[0].reduction = Depth(int(floor(red * int(OnePly))));
966 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
967 doFullDepthSearch = (value > alpha);
971 if (doFullDepthSearch)
973 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
977 // Fail high! Set the boolean variable FailHigh to true, and
978 // re-search the move using a PV search. The variable FailHigh
979 // is used for time managment: We try to avoid aborting the
980 // search prematurely during a fail high research.
982 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
989 // Finished searching the move. If AbortSearch is true, the search
990 // was aborted because the user interrupted the search or because we
991 // ran out of time. In this case, the return value of the search cannot
992 // be trusted, and we break out of the loop without updating the best
997 // Remember beta-cutoff and searched nodes counts for this move. The
998 // info is used to sort the root moves at the next iteration.
1000 BetaCounter.read(pos.side_to_move(), our, their);
1001 rml.set_beta_counters(i, our, their);
1002 rml.set_move_nodes(i, nodes_searched() - nodes);
1004 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1006 if (value <= alpha && i >= MultiPV)
1007 rml.set_move_score(i, -VALUE_INFINITE);
1010 // PV move or new best move!
1013 rml.set_move_score(i, value);
1015 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1016 rml.set_move_pv(i, ss[0].pv);
1020 // We record how often the best move has been changed in each
1021 // iteration. This information is used for time managment: When
1022 // the best move changes frequently, we allocate some more time.
1024 BestMoveChangesByIteration[Iteration]++;
1026 // Print search information to the standard output
1027 cout << "info depth " << Iteration
1028 << " score " << value_to_string(value)
1029 << ((value >= beta) ? " lowerbound" :
1030 ((value <= alpha)? " upperbound" : ""))
1031 << " time " << current_search_time()
1032 << " nodes " << nodes_searched()
1036 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1037 cout << ss[0].pv[j] << " ";
1043 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1044 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1046 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1047 nodes_searched(), value, type, ss[0].pv) << endl;
1052 // Reset the global variable Problem to false if the value isn't too
1053 // far below the final value from the last iteration.
1054 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1059 rml.sort_multipv(i);
1060 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1062 cout << "info multipv " << j + 1
1063 << " score " << value_to_string(rml.get_move_score(j))
1064 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1065 << " time " << current_search_time()
1066 << " nodes " << nodes_searched()
1070 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1071 cout << rml.get_move_pv(j, k) << " ";
1075 alpha = rml.get_move_score(Min(i, MultiPV-1));
1077 } // PV move or new best move
1079 assert(alpha >= oldAlpha);
1081 FailLow = (alpha == oldAlpha);
1087 // search_pv() is the main search function for PV nodes.
1089 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1090 Depth depth, int ply, int threadID) {
1092 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1093 assert(beta > alpha && beta <= VALUE_INFINITE);
1094 assert(ply >= 0 && ply < PLY_MAX);
1095 assert(threadID >= 0 && threadID < ActiveThreads);
1097 Move movesSearched[256];
1101 Depth ext, newDepth;
1102 Value oldAlpha, value;
1103 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1105 Value bestValue = value = -VALUE_INFINITE;
1108 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1110 // Initialize, and make an early exit in case of an aborted search,
1111 // an instant draw, maximum ply reached, etc.
1112 init_node(ss, ply, threadID);
1114 // After init_node() that calls poll()
1115 if (AbortSearch || thread_should_stop(threadID))
1118 if (pos.is_draw() || ply >= PLY_MAX - 1)
1121 // Mate distance pruning
1123 alpha = Max(value_mated_in(ply), alpha);
1124 beta = Min(value_mate_in(ply+1), beta);
1128 // Transposition table lookup. At PV nodes, we don't use the TT for
1129 // pruning, but only for move ordering. This is to avoid problems in
1130 // the following areas:
1132 // * Repetition draw detection
1133 // * Fifty move rule detection
1134 // * Searching for a mate
1135 // * Printing of full PV line
1137 tte = TT.retrieve(pos.get_key());
1138 ttMove = (tte ? tte->move() : MOVE_NONE);
1140 // Go with internal iterative deepening if we don't have a TT move
1141 if ( UseIIDAtPVNodes
1142 && depth >= 5*OnePly
1143 && ttMove == MOVE_NONE)
1145 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1146 ttMove = ss[ply].pv[ply];
1147 tte = TT.retrieve(pos.get_key());
1150 // Initialize a MovePicker object for the current position, and prepare
1151 // to search all moves
1152 isCheck = pos.is_check();
1153 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1155 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1157 // Loop through all legal moves until no moves remain or a beta cutoff
1159 while ( alpha < beta
1160 && (move = mp.get_next_move()) != MOVE_NONE
1161 && !thread_should_stop(threadID))
1163 assert(move_is_ok(move));
1165 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1166 moveIsCheck = pos.move_is_check(move, ci);
1167 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1169 // Decide the new search depth
1170 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1172 // Singular extension search. We extend the TT move if its value is much better than
1173 // its siblings. To verify this we do a reduced search on all the other moves but the
1174 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1175 if ( depth >= 6 * OnePly
1177 && move == tte->move()
1179 && is_lower_bound(tte->type())
1180 && tte->depth() >= depth - 3 * OnePly)
1182 Value ttValue = value_from_tt(tte->value(), ply);
1184 if (abs(ttValue) < VALUE_KNOWN_WIN)
1186 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1188 if (excValue < ttValue - SingleReplyMargin)
1193 newDepth = depth - OnePly + ext;
1195 // Update current move
1196 movesSearched[moveCount++] = ss[ply].currentMove = move;
1198 // Make and search the move
1199 pos.do_move(move, st, ci, moveIsCheck);
1201 if (moveCount == 1) // The first move in list is the PV
1202 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1205 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1206 // if the move fails high will be re-searched at full depth.
1207 bool doFullDepthSearch = true;
1209 if ( depth >= 3*OnePly
1211 && !captureOrPromotion
1212 && !move_is_castle(move)
1213 && !move_is_killer(move, ss[ply]))
1215 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 6.0;
1218 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1219 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1220 doFullDepthSearch = (value > alpha);
1224 if (doFullDepthSearch) // Go with full depth non-pv search
1226 ss[ply].reduction = Depth(0);
1227 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1228 if (value > alpha && value < beta)
1230 // When the search fails high at ply 1 while searching the first
1231 // move at the root, set the flag failHighPly1. This is used for
1232 // time managment: We don't want to stop the search early in
1233 // such cases, because resolving the fail high at ply 1 could
1234 // result in a big drop in score at the root.
1235 if (ply == 1 && RootMoveNumber == 1)
1236 Threads[threadID].failHighPly1 = true;
1238 // A fail high occurred. Re-search at full window (pv search)
1239 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1240 Threads[threadID].failHighPly1 = false;
1244 pos.undo_move(move);
1246 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1249 if (value > bestValue)
1256 if (value == value_mate_in(ply + 1))
1257 ss[ply].mateKiller = move;
1259 // If we are at ply 1, and we are searching the first root move at
1260 // ply 0, set the 'Problem' variable if the score has dropped a lot
1261 // (from the computer's point of view) since the previous iteration.
1264 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1269 if ( ActiveThreads > 1
1271 && depth >= MinimumSplitDepth
1273 && idle_thread_exists(threadID)
1275 && !thread_should_stop(threadID)
1276 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1277 depth, &moveCount, &mp, threadID, true))
1281 // All legal moves have been searched. A special case: If there were
1282 // no legal moves, it must be mate or stalemate.
1284 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1286 // If the search is not aborted, update the transposition table,
1287 // history counters, and killer moves.
1288 if (AbortSearch || thread_should_stop(threadID))
1291 if (bestValue <= oldAlpha)
1292 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1294 else if (bestValue >= beta)
1296 BetaCounter.add(pos.side_to_move(), depth, threadID);
1297 move = ss[ply].pv[ply];
1298 if (!pos.move_is_capture_or_promotion(move))
1300 update_history(pos, move, depth, movesSearched, moveCount);
1301 update_killers(move, ss[ply]);
1303 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1306 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1312 // search() is the search function for zero-width nodes.
1314 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1315 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1317 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1318 assert(ply >= 0 && ply < PLY_MAX);
1319 assert(threadID >= 0 && threadID < ActiveThreads);
1321 Move movesSearched[256];
1326 Depth ext, newDepth;
1327 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1328 bool isCheck, useFutilityPruning, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1329 bool mateThreat = false;
1331 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1334 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1336 // Initialize, and make an early exit in case of an aborted search,
1337 // an instant draw, maximum ply reached, etc.
1338 init_node(ss, ply, threadID);
1340 // After init_node() that calls poll()
1341 if (AbortSearch || thread_should_stop(threadID))
1344 if (pos.is_draw() || ply >= PLY_MAX - 1)
1347 // Mate distance pruning
1348 if (value_mated_in(ply) >= beta)
1351 if (value_mate_in(ply + 1) < beta)
1354 // We don't want the score of a partial search to overwrite a previous full search
1355 // TT value, so we use a different position key in case of an excluded move exsists.
1356 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1358 // Transposition table lookup
1359 tte = TT.retrieve(posKey);
1360 ttMove = (tte ? tte->move() : MOVE_NONE);
1362 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1364 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1365 return value_from_tt(tte->value(), ply);
1368 isCheck = pos.is_check();
1370 // Calculate depth dependant futility pruning parameters
1371 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1372 const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1374 // Evaluate the position statically
1377 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1378 staticValue = value_from_tt(tte->value(), ply);
1381 staticValue = evaluate(pos, ei, threadID);
1382 ss[ply].evalInfo = &ei;
1385 ss[ply].eval = staticValue;
1386 futilityValue = staticValue + FutilityValueMargin;
1387 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1394 && !value_is_mate(beta)
1395 && ok_to_do_nullmove(pos)
1396 && staticValue >= beta - NullMoveMargin)
1398 ss[ply].currentMove = MOVE_NULL;
1400 pos.do_null_move(st);
1402 // Null move dynamic reduction based on depth
1403 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1405 // Null move dynamic reduction based on value
1406 if (staticValue - beta > PawnValueMidgame)
1409 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1411 pos.undo_null_move();
1413 if (nullValue >= beta)
1415 if (depth < 6 * OnePly)
1418 // Do zugzwang verification search
1419 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1423 // The null move failed low, which means that we may be faced with
1424 // some kind of threat. If the previous move was reduced, check if
1425 // the move that refuted the null move was somehow connected to the
1426 // move which was reduced. If a connection is found, return a fail
1427 // low score (which will cause the reduced move to fail high in the
1428 // parent node, which will trigger a re-search with full depth).
1429 if (nullValue == value_mated_in(ply + 2))
1432 ss[ply].threatMove = ss[ply + 1].currentMove;
1433 if ( depth < ThreatDepth
1434 && ss[ply - 1].reduction
1435 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1439 // Null move search not allowed, try razoring
1440 else if ( !value_is_mate(beta)
1442 && depth < RazorDepth
1443 && staticValue < beta - (NullMoveMargin + 16 * depth)
1444 && ss[ply - 1].currentMove != MOVE_NULL
1445 && ttMove == MOVE_NONE
1446 && !pos.has_pawn_on_7th(pos.side_to_move()))
1448 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1449 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1454 // Go with internal iterative deepening if we don't have a TT move
1455 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1456 !isCheck && ss[ply].eval >= beta - IIDMargin)
1458 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1459 ttMove = ss[ply].pv[ply];
1460 tte = TT.retrieve(pos.get_key());
1463 // Initialize a MovePicker object for the current position, and prepare
1464 // to search all moves.
1465 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1467 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1469 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1470 while ( bestValue < beta
1471 && (move = mp.get_next_move()) != MOVE_NONE
1472 && !thread_should_stop(threadID))
1474 assert(move_is_ok(move));
1476 if (move == excludedMove)
1479 moveIsCheck = pos.move_is_check(move, ci);
1480 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1481 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1483 // Decide the new search depth
1484 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1486 // Singular extension search. We extend the TT move if its value is much better than
1487 // its siblings. To verify this we do a reduced search on all the other moves but the
1488 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1489 if ( depth >= 8 * OnePly
1491 && move == tte->move()
1492 && !excludedMove // Do not allow recursive single-reply search
1494 && is_lower_bound(tte->type())
1495 && tte->depth() >= depth - 3 * OnePly)
1497 Value ttValue = value_from_tt(tte->value(), ply);
1499 if (abs(ttValue) < VALUE_KNOWN_WIN)
1501 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1503 if (excValue < ttValue - SingleReplyMargin)
1508 newDepth = depth - OnePly + ext;
1510 // Update current move
1511 movesSearched[moveCount++] = ss[ply].currentMove = move;
1514 if ( useFutilityPruning
1516 && !captureOrPromotion
1519 // Move count based pruning
1520 if ( moveCount >= FutilityMoveCountMargin
1521 && ok_to_prune(pos, move, ss[ply].threatMove)
1522 && bestValue > value_mated_in(PLY_MAX))
1525 // Value based pruning
1526 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1528 if (futilityValueScaled < beta)
1530 if (futilityValueScaled > bestValue)
1531 bestValue = futilityValueScaled;
1536 // Make and search the move
1537 pos.do_move(move, st, ci, moveIsCheck);
1539 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1540 // if the move fails high will be re-searched at full depth.
1541 bool doFullDepthSearch = true;
1543 if ( depth >= 3*OnePly
1545 && !captureOrPromotion
1546 && !move_is_castle(move)
1547 && !move_is_killer(move, ss[ply])
1548 /* && move != ttMove*/)
1550 double red = 0.5 + ln(moveCount) * ln(depth / 2) / 3.0;
1553 ss[ply].reduction = Depth(int(floor(red * int(OnePly))));
1554 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1555 doFullDepthSearch = (value >= beta);
1559 if (doFullDepthSearch) // Go with full depth non-pv search
1561 ss[ply].reduction = Depth(0);
1562 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1564 pos.undo_move(move);
1566 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1569 if (value > bestValue)
1575 if (value == value_mate_in(ply + 1))
1576 ss[ply].mateKiller = move;
1580 if ( ActiveThreads > 1
1582 && depth >= MinimumSplitDepth
1584 && idle_thread_exists(threadID)
1586 && !thread_should_stop(threadID)
1587 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue,
1588 depth, &moveCount, &mp, threadID, false))
1592 // All legal moves have been searched. A special case: If there were
1593 // no legal moves, it must be mate or stalemate.
1595 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1597 // If the search is not aborted, update the transposition table,
1598 // history counters, and killer moves.
1599 if (AbortSearch || thread_should_stop(threadID))
1602 if (bestValue < beta)
1603 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1606 BetaCounter.add(pos.side_to_move(), depth, threadID);
1607 move = ss[ply].pv[ply];
1608 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1609 if (!pos.move_is_capture_or_promotion(move))
1611 update_history(pos, move, depth, movesSearched, moveCount);
1612 update_killers(move, ss[ply]);
1617 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1623 // qsearch() is the quiescence search function, which is called by the main
1624 // search function when the remaining depth is zero (or, to be more precise,
1625 // less than OnePly).
1627 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1628 Depth depth, int ply, int threadID) {
1630 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1631 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1633 assert(ply >= 0 && ply < PLY_MAX);
1634 assert(threadID >= 0 && threadID < ActiveThreads);
1639 Value staticValue, bestValue, value, futilityBase, futilityValue;
1640 bool isCheck, enoughMaterial, moveIsCheck;
1641 const TTEntry* tte = NULL;
1643 bool pvNode = (beta - alpha != 1);
1645 // Initialize, and make an early exit in case of an aborted search,
1646 // an instant draw, maximum ply reached, etc.
1647 init_node(ss, ply, threadID);
1649 // After init_node() that calls poll()
1650 if (AbortSearch || thread_should_stop(threadID))
1653 if (pos.is_draw() || ply >= PLY_MAX - 1)
1656 // Transposition table lookup. At PV nodes, we don't use the TT for
1657 // pruning, but only for move ordering.
1658 tte = TT.retrieve(pos.get_key());
1659 ttMove = (tte ? tte->move() : MOVE_NONE);
1661 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1663 assert(tte->type() != VALUE_TYPE_EVAL);
1665 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1666 return value_from_tt(tte->value(), ply);
1669 isCheck = pos.is_check();
1671 // Evaluate the position statically
1673 staticValue = -VALUE_INFINITE;
1674 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1675 staticValue = value_from_tt(tte->value(), ply);
1677 staticValue = evaluate(pos, ei, threadID);
1679 // Initialize "stand pat score", and return it immediately if it is
1681 bestValue = staticValue;
1683 if (bestValue >= beta)
1685 // Store the score to avoid a future costly evaluation() call
1686 if (!isCheck && !tte && ei.futilityMargin == 0)
1687 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1692 if (bestValue > alpha)
1695 // Initialize a MovePicker object for the current position, and prepare
1696 // to search the moves. Because the depth is <= 0 here, only captures,
1697 // queen promotions and checks (only if depth == 0) will be generated.
1698 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1700 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1701 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin;
1703 // Loop through the moves until no moves remain or a beta cutoff
1705 while ( alpha < beta
1706 && (move = mp.get_next_move()) != MOVE_NONE)
1708 assert(move_is_ok(move));
1710 moveIsCheck = pos.move_is_check(move, ci);
1712 // Update current move
1714 ss[ply].currentMove = move;
1722 && !move_is_promotion(move)
1723 && !pos.move_is_passed_pawn_push(move))
1725 futilityValue = futilityBase
1726 + pos.endgame_value_of_piece_on(move_to(move))
1727 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1729 if (futilityValue < alpha)
1731 if (futilityValue > bestValue)
1732 bestValue = futilityValue;
1737 // Don't search captures and checks with negative SEE values
1740 && !move_is_promotion(move)
1741 && pos.see_sign(move) < 0)
1744 // Make and search the move
1745 pos.do_move(move, st, ci, moveIsCheck);
1746 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1747 pos.undo_move(move);
1749 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1752 if (value > bestValue)
1763 // All legal moves have been searched. A special case: If we're in check
1764 // and no legal moves were found, it is checkmate.
1765 if (!moveCount && pos.is_check()) // Mate!
1766 return value_mated_in(ply);
1768 // Update transposition table
1769 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1770 if (bestValue < beta)
1772 // If bestValue isn't changed it means it is still the static evaluation
1773 // of the node, so keep this info to avoid a future evaluation() call.
1774 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1775 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1779 move = ss[ply].pv[ply];
1780 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1782 // Update killers only for good checking moves
1783 if (!pos.move_is_capture_or_promotion(move))
1784 update_killers(move, ss[ply]);
1787 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1793 // sp_search() is used to search from a split point. This function is called
1794 // by each thread working at the split point. It is similar to the normal
1795 // search() function, but simpler. Because we have already probed the hash
1796 // table, done a null move search, and searched the first move before
1797 // splitting, we don't have to repeat all this work in sp_search(). We
1798 // also don't need to store anything to the hash table here: This is taken
1799 // care of after we return from the split point.
1801 void sp_search(SplitPoint* sp, int threadID) {
1803 assert(threadID >= 0 && threadID < ActiveThreads);
1804 assert(ActiveThreads > 1);
1806 Position pos = Position(sp->pos);
1808 SearchStack* ss = sp->sstack[threadID];
1809 Value value = -VALUE_INFINITE;
1811 bool isCheck = pos.is_check();
1812 bool useFutilityPruning = sp->depth < SelectiveDepth
1815 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1817 while ( sp->bestValue < sp->beta
1818 && !thread_should_stop(threadID)
1819 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1821 assert(move_is_ok(move));
1823 bool moveIsCheck = pos.move_is_check(move, ci);
1824 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1826 lock_grab(&(sp->lock));
1827 int moveCount = ++sp->moves;
1828 lock_release(&(sp->lock));
1830 ss[sp->ply].currentMove = move;
1832 // Decide the new search depth.
1834 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1835 Depth newDepth = sp->depth - OnePly + ext;
1838 if ( useFutilityPruning
1840 && !captureOrPromotion)
1842 // Move count based pruning
1843 if ( moveCount >= FutilityMoveCountMargin
1844 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1845 && sp->bestValue > value_mated_in(PLY_MAX))
1848 // Value based pruning
1849 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1851 if (futilityValueScaled < sp->beta)
1853 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1855 lock_grab(&(sp->lock));
1856 if (futilityValueScaled > sp->bestValue)
1857 sp->bestValue = futilityValueScaled;
1858 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.
1870 bool doFullDepthSearch = true;
1873 && !captureOrPromotion
1874 && !move_is_castle(move)
1875 && !move_is_killer(move, ss[sp->ply]))
1877 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 3.0;
1880 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1881 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1882 doFullDepthSearch = (value >= sp->beta);
1886 if (doFullDepthSearch) // Go with full depth non-pv search
1888 ss[sp->ply].reduction = Depth(0);
1889 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1891 pos.undo_move(move);
1893 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1895 if (thread_should_stop(threadID))
1899 if (value > sp->bestValue) // Less then 2% of cases
1901 lock_grab(&(sp->lock));
1902 if (value > sp->bestValue && !thread_should_stop(threadID))
1904 sp->bestValue = value;
1905 if (sp->bestValue >= sp->beta)
1907 sp_update_pv(sp->parentSstack, ss, sp->ply);
1908 for (int i = 0; i < ActiveThreads; i++)
1909 if (i != threadID && (i == sp->master || sp->slaves[i]))
1910 Threads[i].stop = true;
1912 sp->finished = true;
1915 lock_release(&(sp->lock));
1919 lock_grab(&(sp->lock));
1921 // If this is the master thread and we have been asked to stop because of
1922 // a beta cutoff higher up in the tree, stop all slave threads.
1923 if (sp->master == threadID && thread_should_stop(threadID))
1924 for (int i = 0; i < ActiveThreads; i++)
1926 Threads[i].stop = true;
1929 sp->slaves[threadID] = 0;
1931 lock_release(&(sp->lock));
1935 // sp_search_pv() is used to search from a PV split point. This function
1936 // is called by each thread working at the split point. It is similar to
1937 // the normal search_pv() function, but simpler. Because we have already
1938 // probed the hash table and searched the first move before splitting, we
1939 // don't have to repeat all this work in sp_search_pv(). We also don't
1940 // need to store anything to the hash table here: This is taken care of
1941 // after we return from the split point.
1943 void sp_search_pv(SplitPoint* sp, int threadID) {
1945 assert(threadID >= 0 && threadID < ActiveThreads);
1946 assert(ActiveThreads > 1);
1948 Position pos = Position(sp->pos);
1950 SearchStack* ss = sp->sstack[threadID];
1951 Value value = -VALUE_INFINITE;
1954 while ( sp->alpha < sp->beta
1955 && !thread_should_stop(threadID)
1956 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1958 bool moveIsCheck = pos.move_is_check(move, ci);
1959 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1961 assert(move_is_ok(move));
1963 lock_grab(&(sp->lock));
1964 int moveCount = ++sp->moves;
1965 lock_release(&(sp->lock));
1967 ss[sp->ply].currentMove = move;
1969 // Decide the new search depth.
1971 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1972 Depth newDepth = sp->depth - OnePly + ext;
1974 // Make and search the move.
1976 pos.do_move(move, st, ci, moveIsCheck);
1978 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1979 // if the move fails high will be re-searched at full depth.
1980 bool doFullDepthSearch = true;
1983 && !captureOrPromotion
1984 && !move_is_castle(move)
1985 && !move_is_killer(move, ss[sp->ply]))
1987 double red = 0.5 + ln(moveCount) * ln(sp->depth / 2) / 6.0;
1990 Value localAlpha = sp->alpha;
1991 ss[sp->ply].reduction = Depth(int(floor(red * int(OnePly))));
1992 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1993 doFullDepthSearch = (value > localAlpha);
1997 if (doFullDepthSearch) // Go with full depth non-pv search
1999 Value localAlpha = sp->alpha;
2000 ss[sp->ply].reduction = Depth(0);
2001 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2003 if (value > localAlpha && value < sp->beta)
2005 // When the search fails high at ply 1 while searching the first
2006 // move at the root, set the flag failHighPly1. This is used for
2007 // time managment: We don't want to stop the search early in
2008 // such cases, because resolving the fail high at ply 1 could
2009 // result in a big drop in score at the root.
2010 if (sp->ply == 1 && RootMoveNumber == 1)
2011 Threads[threadID].failHighPly1 = true;
2013 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2014 Threads[threadID].failHighPly1 = false;
2017 pos.undo_move(move);
2019 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2021 if (thread_should_stop(threadID))
2025 lock_grab(&(sp->lock));
2026 if (value > sp->bestValue && !thread_should_stop(threadID))
2028 sp->bestValue = value;
2029 if (value > sp->alpha)
2032 sp_update_pv(sp->parentSstack, ss, sp->ply);
2033 if (value == value_mate_in(sp->ply + 1))
2034 ss[sp->ply].mateKiller = move;
2036 if (value >= sp->beta)
2038 for (int i = 0; i < ActiveThreads; i++)
2039 if (i != threadID && (i == sp->master || sp->slaves[i]))
2040 Threads[i].stop = true;
2042 sp->finished = true;
2045 // If we are at ply 1, and we are searching the first root move at
2046 // ply 0, set the 'Problem' variable if the score has dropped a lot
2047 // (from the computer's point of view) since the previous iteration.
2050 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2053 lock_release(&(sp->lock));
2056 lock_grab(&(sp->lock));
2058 // If this is the master thread and we have been asked to stop because of
2059 // a beta cutoff higher up in the tree, stop all slave threads.
2060 if (sp->master == threadID && thread_should_stop(threadID))
2061 for (int i = 0; i < ActiveThreads; i++)
2063 Threads[i].stop = true;
2066 sp->slaves[threadID] = 0;
2068 lock_release(&(sp->lock));
2071 /// The BetaCounterType class
2073 BetaCounterType::BetaCounterType() { clear(); }
2075 void BetaCounterType::clear() {
2077 for (int i = 0; i < THREAD_MAX; i++)
2078 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2081 void BetaCounterType::add(Color us, Depth d, int threadID) {
2083 // Weighted count based on depth
2084 Threads[threadID].betaCutOffs[us] += unsigned(d);
2087 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2090 for (int i = 0; i < THREAD_MAX; i++)
2092 our += Threads[i].betaCutOffs[us];
2093 their += Threads[i].betaCutOffs[opposite_color(us)];
2098 /// The RootMoveList class
2100 // RootMoveList c'tor
2102 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2104 MoveStack mlist[MaxRootMoves];
2105 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2107 // Generate all legal moves
2108 MoveStack* last = generate_moves(pos, mlist);
2110 // Add each move to the moves[] array
2111 for (MoveStack* cur = mlist; cur != last; cur++)
2113 bool includeMove = includeAllMoves;
2115 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2116 includeMove = (searchMoves[k] == cur->move);
2121 // Find a quick score for the move
2123 SearchStack ss[PLY_MAX_PLUS_2];
2126 moves[count].move = cur->move;
2127 pos.do_move(moves[count].move, st);
2128 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2129 pos.undo_move(moves[count].move);
2130 moves[count].pv[0] = moves[count].move;
2131 moves[count].pv[1] = MOVE_NONE;
2138 // RootMoveList simple methods definitions
2140 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2142 moves[moveNum].nodes = nodes;
2143 moves[moveNum].cumulativeNodes += nodes;
2146 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2148 moves[moveNum].ourBeta = our;
2149 moves[moveNum].theirBeta = their;
2152 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2156 for (j = 0; pv[j] != MOVE_NONE; j++)
2157 moves[moveNum].pv[j] = pv[j];
2159 moves[moveNum].pv[j] = MOVE_NONE;
2163 // RootMoveList::sort() sorts the root move list at the beginning of a new
2166 void RootMoveList::sort() {
2168 sort_multipv(count - 1); // Sort all items
2172 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2173 // list by their scores and depths. It is used to order the different PVs
2174 // correctly in MultiPV mode.
2176 void RootMoveList::sort_multipv(int n) {
2180 for (i = 1; i <= n; i++)
2182 RootMove rm = moves[i];
2183 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2184 moves[j] = moves[j - 1];
2191 // init_node() is called at the beginning of all the search functions
2192 // (search(), search_pv(), qsearch(), and so on) and initializes the
2193 // search stack object corresponding to the current node. Once every
2194 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2195 // for user input and checks whether it is time to stop the search.
2197 void init_node(SearchStack ss[], int ply, int threadID) {
2199 assert(ply >= 0 && ply < PLY_MAX);
2200 assert(threadID >= 0 && threadID < ActiveThreads);
2202 Threads[threadID].nodes++;
2207 if (NodesSincePoll >= NodesBetweenPolls)
2214 ss[ply + 2].initKillers();
2216 if (Threads[threadID].printCurrentLine)
2217 print_current_line(ss, ply, threadID);
2221 // update_pv() is called whenever a search returns a value > alpha.
2222 // It updates the PV in the SearchStack object corresponding to the
2225 void update_pv(SearchStack ss[], int ply) {
2227 assert(ply >= 0 && ply < PLY_MAX);
2231 ss[ply].pv[ply] = ss[ply].currentMove;
2233 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2234 ss[ply].pv[p] = ss[ply + 1].pv[p];
2236 ss[ply].pv[p] = MOVE_NONE;
2240 // sp_update_pv() is a variant of update_pv for use at split points. The
2241 // difference between the two functions is that sp_update_pv also updates
2242 // the PV at the parent node.
2244 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2246 assert(ply >= 0 && ply < PLY_MAX);
2250 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2252 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2253 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2255 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2259 // connected_moves() tests whether two moves are 'connected' in the sense
2260 // that the first move somehow made the second move possible (for instance
2261 // if the moving piece is the same in both moves). The first move is assumed
2262 // to be the move that was made to reach the current position, while the
2263 // second move is assumed to be a move from the current position.
2265 bool connected_moves(const Position& pos, Move m1, Move m2) {
2267 Square f1, t1, f2, t2;
2270 assert(move_is_ok(m1));
2271 assert(move_is_ok(m2));
2273 if (m2 == MOVE_NONE)
2276 // Case 1: The moving piece is the same in both moves
2282 // Case 2: The destination square for m2 was vacated by m1
2288 // Case 3: Moving through the vacated square
2289 if ( piece_is_slider(pos.piece_on(f2))
2290 && bit_is_set(squares_between(f2, t2), f1))
2293 // Case 4: The destination square for m2 is defended by the moving piece in m1
2294 p = pos.piece_on(t1);
2295 if (bit_is_set(pos.attacks_from(p, t1), t2))
2298 // Case 5: Discovered check, checking piece is the piece moved in m1
2299 if ( piece_is_slider(p)
2300 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2301 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2303 // discovered_check_candidates() works also if the Position's side to
2304 // move is the opposite of the checking piece.
2305 Color them = opposite_color(pos.side_to_move());
2306 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2308 if (bit_is_set(dcCandidates, f2))
2315 // value_is_mate() checks if the given value is a mate one
2316 // eventually compensated for the ply.
2318 bool value_is_mate(Value value) {
2320 assert(abs(value) <= VALUE_INFINITE);
2322 return value <= value_mated_in(PLY_MAX)
2323 || value >= value_mate_in(PLY_MAX);
2327 // move_is_killer() checks if the given move is among the
2328 // killer moves of that ply.
2330 bool move_is_killer(Move m, const SearchStack& ss) {
2332 const Move* k = ss.killers;
2333 for (int i = 0; i < KILLER_MAX; i++, k++)
2341 // extension() decides whether a move should be searched with normal depth,
2342 // or with extended depth. Certain classes of moves (checking moves, in
2343 // particular) are searched with bigger depth than ordinary moves and in
2344 // any case are marked as 'dangerous'. Note that also if a move is not
2345 // extended, as example because the corresponding UCI option is set to zero,
2346 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2348 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2349 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2351 assert(m != MOVE_NONE);
2353 Depth result = Depth(0);
2354 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2359 result += CheckExtension[pvNode];
2362 result += SingleEvasionExtension[pvNode];
2365 result += MateThreatExtension[pvNode];
2368 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2370 Color c = pos.side_to_move();
2371 if (relative_rank(c, move_to(m)) == RANK_7)
2373 result += PawnPushTo7thExtension[pvNode];
2376 if (pos.pawn_is_passed(c, move_to(m)))
2378 result += PassedPawnExtension[pvNode];
2383 if ( captureOrPromotion
2384 && pos.type_of_piece_on(move_to(m)) != PAWN
2385 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2386 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2387 && !move_is_promotion(m)
2390 result += PawnEndgameExtension[pvNode];
2395 && captureOrPromotion
2396 && pos.type_of_piece_on(move_to(m)) != PAWN
2397 && pos.see_sign(m) >= 0)
2403 return Min(result, OnePly);
2407 // ok_to_do_nullmove() looks at the current position and decides whether
2408 // doing a 'null move' should be allowed. In order to avoid zugzwang
2409 // problems, null moves are not allowed when the side to move has very
2410 // little material left. Currently, the test is a bit too simple: Null
2411 // moves are avoided only when the side to move has only pawns left.
2412 // It's probably a good idea to avoid null moves in at least some more
2413 // complicated endgames, e.g. KQ vs KR. FIXME
2415 bool ok_to_do_nullmove(const Position& pos) {
2417 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2421 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2422 // non-tactical moves late in the move list close to the leaves are
2423 // candidates for pruning.
2425 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2427 assert(move_is_ok(m));
2428 assert(threat == MOVE_NONE || move_is_ok(threat));
2429 assert(!pos.move_is_check(m));
2430 assert(!pos.move_is_capture_or_promotion(m));
2431 assert(!pos.move_is_passed_pawn_push(m));
2433 Square mfrom, mto, tfrom, tto;
2435 // Prune if there isn't any threat move and
2436 // is not a castling move (common case).
2437 if (threat == MOVE_NONE && !move_is_castle(m))
2440 mfrom = move_from(m);
2442 tfrom = move_from(threat);
2443 tto = move_to(threat);
2445 // Case 1: Castling moves are never pruned
2446 if (move_is_castle(m))
2449 // Case 2: Don't prune moves which move the threatened piece
2453 // Case 3: If the threatened piece has value less than or equal to the
2454 // value of the threatening piece, don't prune move which defend it.
2455 if ( pos.move_is_capture(threat)
2456 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2457 || pos.type_of_piece_on(tfrom) == KING)
2458 && pos.move_attacks_square(m, tto))
2461 // Case 4: If the moving piece in the threatened move is a slider, don't
2462 // prune safe moves which block its ray.
2463 if ( piece_is_slider(pos.piece_on(tfrom))
2464 && bit_is_set(squares_between(tfrom, tto), mto)
2465 && pos.see_sign(m) >= 0)
2472 // ok_to_use_TT() returns true if a transposition table score
2473 // can be used at a given point in search.
2475 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2477 Value v = value_from_tt(tte->value(), ply);
2479 return ( tte->depth() >= depth
2480 || v >= Max(value_mate_in(PLY_MAX), beta)
2481 || v < Min(value_mated_in(PLY_MAX), beta))
2483 && ( (is_lower_bound(tte->type()) && v >= beta)
2484 || (is_upper_bound(tte->type()) && v < beta));
2488 // refine_eval() returns the transposition table score if
2489 // possible otherwise falls back on static position evaluation.
2491 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2496 Value v = value_from_tt(tte->value(), ply);
2498 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2499 || (is_upper_bound(tte->type()) && v < defaultEval))
2505 // update_history() registers a good move that produced a beta-cutoff
2506 // in history and marks as failures all the other moves of that ply.
2508 void update_history(const Position& pos, Move move, Depth depth,
2509 Move movesSearched[], int moveCount) {
2513 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2515 for (int i = 0; i < moveCount - 1; i++)
2517 m = movesSearched[i];
2521 if (!pos.move_is_capture_or_promotion(m))
2522 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2527 // update_killers() add a good move that produced a beta-cutoff
2528 // among the killer moves of that ply.
2530 void update_killers(Move m, SearchStack& ss) {
2532 if (m == ss.killers[0])
2535 for (int i = KILLER_MAX - 1; i > 0; i--)
2536 ss.killers[i] = ss.killers[i - 1];
2542 // fail_high_ply_1() checks if some thread is currently resolving a fail
2543 // high at ply 1 at the node below the first root node. This information
2544 // is used for time management.
2546 bool fail_high_ply_1() {
2548 for (int i = 0; i < ActiveThreads; i++)
2549 if (Threads[i].failHighPly1)
2556 // current_search_time() returns the number of milliseconds which have passed
2557 // since the beginning of the current search.
2559 int current_search_time() {
2561 return get_system_time() - SearchStartTime;
2565 // nps() computes the current nodes/second count.
2569 int t = current_search_time();
2570 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2574 // poll() performs two different functions: It polls for user input, and it
2575 // looks at the time consumed so far and decides if it's time to abort the
2580 static int lastInfoTime;
2581 int t = current_search_time();
2586 // We are line oriented, don't read single chars
2587 std::string command;
2589 if (!std::getline(std::cin, command))
2592 if (command == "quit")
2595 PonderSearch = false;
2599 else if (command == "stop")
2602 PonderSearch = false;
2604 else if (command == "ponderhit")
2608 // Print search information
2612 else if (lastInfoTime > t)
2613 // HACK: Must be a new search where we searched less than
2614 // NodesBetweenPolls nodes during the first second of search.
2617 else if (t - lastInfoTime >= 1000)
2625 if (dbg_show_hit_rate)
2626 dbg_print_hit_rate();
2628 cout << "info nodes " << nodes_searched() << " nps " << nps()
2629 << " time " << t << " hashfull " << TT.full() << endl;
2631 lock_release(&IOLock);
2633 if (ShowCurrentLine)
2634 Threads[0].printCurrentLine = true;
2637 // Should we stop the search?
2641 bool stillAtFirstMove = RootMoveNumber == 1
2643 && t > MaxSearchTime + ExtraSearchTime;
2645 bool noProblemFound = !FailHigh
2647 && !fail_high_ply_1()
2649 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2651 bool noMoreTime = t > AbsoluteMaxSearchTime
2652 || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2655 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2656 || (ExactMaxTime && t >= ExactMaxTime)
2657 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2662 // ponderhit() is called when the program is pondering (i.e. thinking while
2663 // it's the opponent's turn to move) in order to let the engine know that
2664 // it correctly predicted the opponent's move.
2668 int t = current_search_time();
2669 PonderSearch = false;
2671 bool stillAtFirstMove = RootMoveNumber == 1
2673 && t > MaxSearchTime + ExtraSearchTime;
2675 bool noProblemFound = !FailHigh
2677 && !fail_high_ply_1()
2679 && t > 6 * (MaxSearchTime + ExtraSearchTime);
2681 bool noMoreTime = t > AbsoluteMaxSearchTime
2685 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2690 // print_current_line() prints the current line of search for a given
2691 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2693 void print_current_line(SearchStack ss[], int ply, int threadID) {
2695 assert(ply >= 0 && ply < PLY_MAX);
2696 assert(threadID >= 0 && threadID < ActiveThreads);
2698 if (!Threads[threadID].idle)
2701 cout << "info currline " << (threadID + 1);
2702 for (int p = 0; p < ply; p++)
2703 cout << " " << ss[p].currentMove;
2706 lock_release(&IOLock);
2708 Threads[threadID].printCurrentLine = false;
2709 if (threadID + 1 < ActiveThreads)
2710 Threads[threadID + 1].printCurrentLine = true;
2714 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2716 void init_ss_array(SearchStack ss[]) {
2718 for (int i = 0; i < 3; i++)
2721 ss[i].initKillers();
2726 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2727 // while the program is pondering. The point is to work around a wrinkle in
2728 // the UCI protocol: When pondering, the engine is not allowed to give a
2729 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2730 // We simply wait here until one of these commands is sent, and return,
2731 // after which the bestmove and pondermove will be printed (in id_loop()).
2733 void wait_for_stop_or_ponderhit() {
2735 std::string command;
2739 if (!std::getline(std::cin, command))
2742 if (command == "quit")
2747 else if (command == "ponderhit" || command == "stop")
2753 // idle_loop() is where the threads are parked when they have no work to do.
2754 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2755 // object for which the current thread is the master.
2757 void idle_loop(int threadID, SplitPoint* waitSp) {
2759 assert(threadID >= 0 && threadID < THREAD_MAX);
2761 Threads[threadID].running = true;
2765 if (AllThreadsShouldExit && threadID != 0)
2768 // If we are not thinking, wait for a condition to be signaled
2769 // instead of wasting CPU time polling for work.
2770 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2773 #if !defined(_MSC_VER)
2774 pthread_mutex_lock(&WaitLock);
2775 if (Idle || threadID >= ActiveThreads)
2776 pthread_cond_wait(&WaitCond, &WaitLock);
2778 pthread_mutex_unlock(&WaitLock);
2780 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2784 // If this thread has been assigned work, launch a search
2785 if (Threads[threadID].workIsWaiting)
2787 Threads[threadID].workIsWaiting = false;
2788 if (Threads[threadID].splitPoint->pvNode)
2789 sp_search_pv(Threads[threadID].splitPoint, threadID);
2791 sp_search(Threads[threadID].splitPoint, threadID);
2793 Threads[threadID].idle = true;
2796 // If this thread is the master of a split point and all threads have
2797 // finished their work at this split point, return from the idle loop.
2798 if (waitSp != NULL && waitSp->cpus == 0)
2802 Threads[threadID].running = false;
2806 // init_split_point_stack() is called during program initialization, and
2807 // initializes all split point objects.
2809 void init_split_point_stack() {
2811 for (int i = 0; i < THREAD_MAX; i++)
2812 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2814 SplitPointStack[i][j].parent = NULL;
2815 lock_init(&(SplitPointStack[i][j].lock), NULL);
2820 // destroy_split_point_stack() is called when the program exits, and
2821 // destroys all locks in the precomputed split point objects.
2823 void destroy_split_point_stack() {
2825 for (int i = 0; i < THREAD_MAX; i++)
2826 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2827 lock_destroy(&(SplitPointStack[i][j].lock));
2831 // thread_should_stop() checks whether the thread with a given threadID has
2832 // been asked to stop, directly or indirectly. This can happen if a beta
2833 // cutoff has occurred in the thread's currently active split point, or in
2834 // some ancestor of the current split point.
2836 bool thread_should_stop(int threadID) {
2838 assert(threadID >= 0 && threadID < ActiveThreads);
2842 if (Threads[threadID].stop)
2844 if (ActiveThreads <= 2)
2846 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2849 Threads[threadID].stop = true;
2856 // thread_is_available() checks whether the thread with threadID "slave" is
2857 // available to help the thread with threadID "master" at a split point. An
2858 // obvious requirement is that "slave" must be idle. With more than two
2859 // threads, this is not by itself sufficient: If "slave" is the master of
2860 // some active split point, it is only available as a slave to the other
2861 // threads which are busy searching the split point at the top of "slave"'s
2862 // split point stack (the "helpful master concept" in YBWC terminology).
2864 bool thread_is_available(int slave, int master) {
2866 assert(slave >= 0 && slave < ActiveThreads);
2867 assert(master >= 0 && master < ActiveThreads);
2868 assert(ActiveThreads > 1);
2870 if (!Threads[slave].idle || slave == master)
2873 if (Threads[slave].activeSplitPoints == 0)
2874 // No active split points means that the thread is available as
2875 // a slave for any other thread.
2878 if (ActiveThreads == 2)
2881 // Apply the "helpful master" concept if possible
2882 if (SplitPointStack[slave][Threads[slave].activeSplitPoints - 1].slaves[master])
2889 // idle_thread_exists() tries to find an idle thread which is available as
2890 // a slave for the thread with threadID "master".
2892 bool idle_thread_exists(int master) {
2894 assert(master >= 0 && master < ActiveThreads);
2895 assert(ActiveThreads > 1);
2897 for (int i = 0; i < ActiveThreads; i++)
2898 if (thread_is_available(i, master))
2905 // split() does the actual work of distributing the work at a node between
2906 // several threads at PV nodes. If it does not succeed in splitting the
2907 // node (because no idle threads are available, or because we have no unused
2908 // split point objects), the function immediately returns false. If
2909 // splitting is possible, a SplitPoint object is initialized with all the
2910 // data that must be copied to the helper threads (the current position and
2911 // search stack, alpha, beta, the search depth, etc.), and we tell our
2912 // helper threads that they have been assigned work. This will cause them
2913 // to instantly leave their idle loops and call sp_search_pv(). When all
2914 // threads have returned from sp_search_pv (or, equivalently, when
2915 // splitPoint->cpus becomes 0), split() returns true.
2917 bool split(const Position& p, SearchStack* sstck, int ply,
2918 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2919 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2922 assert(sstck != NULL);
2923 assert(ply >= 0 && ply < PLY_MAX);
2924 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2925 assert(!pvNode || *alpha < *beta);
2926 assert(*beta <= VALUE_INFINITE);
2927 assert(depth > Depth(0));
2928 assert(master >= 0 && master < ActiveThreads);
2929 assert(ActiveThreads > 1);
2931 SplitPoint* splitPoint;
2936 // If no other thread is available to help us, or if we have too many
2937 // active split points, don't split.
2938 if ( !idle_thread_exists(master)
2939 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2941 lock_release(&MPLock);
2945 // Pick the next available split point object from the split point stack
2946 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2947 Threads[master].activeSplitPoints++;
2949 // Initialize the split point object and copy current position
2950 splitPoint->parent = Threads[master].splitPoint;
2951 splitPoint->finished = false;
2952 splitPoint->ply = ply;
2953 splitPoint->depth = depth;
2954 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2955 splitPoint->beta = *beta;
2956 splitPoint->pvNode = pvNode;
2957 splitPoint->bestValue = *bestValue;
2958 splitPoint->futilityValue = futilityValue;
2959 splitPoint->master = master;
2960 splitPoint->mp = mp;
2961 splitPoint->moves = *moves;
2962 splitPoint->cpus = 1;
2963 splitPoint->pos.copy(p);
2964 splitPoint->parentSstack = sstck;
2965 for (i = 0; i < ActiveThreads; i++)
2966 splitPoint->slaves[i] = 0;
2968 // Copy the current search stack to the master thread
2969 memcpy(splitPoint->sstack[master], sstck, (ply+1) * sizeof(SearchStack));
2970 Threads[master].splitPoint = splitPoint;
2972 // Make copies of the current position and search stack for each thread
2973 for (i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2974 if (thread_is_available(i, master))
2976 memcpy(splitPoint->sstack[i], sstck, (ply+1) * sizeof(SearchStack));
2977 Threads[i].splitPoint = splitPoint;
2978 splitPoint->slaves[i] = 1;
2982 // Tell the threads that they have work to do. This will make them leave
2984 for (i = 0; i < ActiveThreads; i++)
2985 if (i == master || splitPoint->slaves[i])
2987 Threads[i].workIsWaiting = true;
2988 Threads[i].idle = false;
2989 Threads[i].stop = false;
2992 lock_release(&MPLock);
2994 // Everything is set up. The master thread enters the idle loop, from
2995 // which it will instantly launch a search, because its workIsWaiting
2996 // slot is 'true'. We send the split point as a second parameter to the
2997 // idle loop, which means that the main thread will return from the idle
2998 // loop when all threads have finished their work at this split point
2999 // (i.e. when splitPoint->cpus == 0).
3000 idle_loop(master, splitPoint);
3002 // We have returned from the idle loop, which means that all threads are
3003 // finished. Update alpha, beta and bestValue, and return.
3007 *alpha = splitPoint->alpha;
3009 *beta = splitPoint->beta;
3010 *bestValue = splitPoint->bestValue;
3011 Threads[master].stop = false;
3012 Threads[master].idle = false;
3013 Threads[master].activeSplitPoints--;
3014 Threads[master].splitPoint = splitPoint->parent;
3016 lock_release(&MPLock);
3021 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3022 // to start a new search from the root.
3024 void wake_sleeping_threads() {
3026 if (ActiveThreads > 1)
3028 for (int i = 1; i < ActiveThreads; i++)
3030 Threads[i].idle = true;
3031 Threads[i].workIsWaiting = false;
3034 #if !defined(_MSC_VER)
3035 pthread_mutex_lock(&WaitLock);
3036 pthread_cond_broadcast(&WaitCond);
3037 pthread_mutex_unlock(&WaitLock);
3039 for (int i = 1; i < THREAD_MAX; i++)
3040 SetEvent(SitIdleEvent[i]);
3046 // init_thread() is the function which is called when a new thread is
3047 // launched. It simply calls the idle_loop() function with the supplied
3048 // threadID. There are two versions of this function; one for POSIX
3049 // threads and one for Windows threads.
3051 #if !defined(_MSC_VER)
3053 void* init_thread(void *threadID) {
3055 idle_loop(*(int*)threadID, NULL);
3061 DWORD WINAPI init_thread(LPVOID threadID) {
3063 idle_loop(*(int*)threadID, NULL);