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 // The BetaCounterType class is used to order moves at ply one.
57 // Apart for the first one that has its score, following moves
58 // normally have score -VALUE_INFINITE, so are ordered according
59 // to the number of beta cutoffs occurred under their subtree during
60 // the last iteration. The counters are per thread variables to avoid
61 // concurrent accessing under SMP case.
63 struct BetaCounterType {
67 void add(Color us, Depth d, int threadID);
68 void read(Color us, int64_t& our, int64_t& their);
72 // The RootMove class is used for moves at the root at the tree. For each
73 // root move, we store a score, a node count, and a PV (really a refutation
74 // in the case of moves which fail low).
78 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
80 // RootMove::operator<() is the comparison function used when
81 // sorting the moves. A move m1 is considered to be better
82 // than a move m2 if it has a higher score, or if the moves
83 // have equal score but m1 has the higher node count.
84 bool operator<(const RootMove& m) const {
86 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
91 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
92 Move pv[PLY_MAX_PLUS_2];
96 // The RootMoveList class is essentially an array of RootMove objects, with
97 // a handful of methods for accessing the data in the individual moves.
102 RootMoveList(Position& pos, Move searchMoves[]);
104 int move_count() const { return count; }
105 Move get_move(int moveNum) const { return moves[moveNum].move; }
106 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
107 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
108 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
109 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
111 void set_move_nodes(int moveNum, int64_t nodes);
112 void set_beta_counters(int moveNum, int64_t our, int64_t their);
113 void set_move_pv(int moveNum, const Move pv[]);
115 void sort_multipv(int n);
118 static const int MaxRootMoves = 500;
119 RootMove moves[MaxRootMoves];
126 // Search depth at iteration 1
127 const Depth InitialDepth = OnePly;
129 // Depth limit for selective search
130 const Depth SelectiveDepth = 7 * OnePly;
132 // Use internal iterative deepening?
133 const bool UseIIDAtPVNodes = true;
134 const bool UseIIDAtNonPVNodes = true;
136 // Internal iterative deepening margin. At Non-PV moves, when
137 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
138 // search when the static evaluation is at most IIDMargin below beta.
139 const Value IIDMargin = Value(0x100);
141 // Easy move margin. An easy move candidate must be at least this much
142 // better than the second best move.
143 const Value EasyMoveMargin = Value(0x200);
145 // Problem margin. If the score of the first move at iteration N+1 has
146 // dropped by more than this since iteration N, the boolean variable
147 // "Problem" is set to true, which will make the program spend some extra
148 // time looking for a better move.
149 const Value ProblemMargin = Value(0x28);
151 // No problem margin. If the boolean "Problem" is true, and a new move
152 // is found at the root which is less than NoProblemMargin worse than the
153 // best move from the previous iteration, Problem is set back to false.
154 const Value NoProblemMargin = Value(0x14);
156 // Null move margin. A null move search will not be done if the static
157 // evaluation of the position is more than NullMoveMargin below beta.
158 const Value NullMoveMargin = Value(0x200);
160 // If the TT move is at least SingleReplyMargin better then the
161 // remaining ones we will extend it.
162 const Value SingleReplyMargin = Value(0x20);
164 // Margins for futility pruning in the quiescence search, and at frontier
165 // and near frontier nodes.
166 const Value FutilityMarginQS = Value(0x80);
168 Value FutilityMargins[2 * PLY_MAX_PLUS_2]; // Initialized at startup.
170 // Each move futility margin is decreased
171 const Value IncrementalFutilityMargin = Value(0x8);
173 // Depth limit for razoring
174 const Depth RazorDepth = 4 * OnePly;
176 /// Variables initialized by UCI options
178 // Depth limit for use of dynamic threat detection
181 // Last seconds noise filtering (LSN)
182 const bool UseLSNFiltering = true;
183 const int LSNTime = 4000; // In milliseconds
184 const Value LSNValue = value_from_centipawns(200);
185 bool loseOnTime = false;
187 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
188 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
189 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
191 // Iteration counters
193 BetaCounterType BetaCounter;
195 // Scores and number of times the best move changed for each iteration
196 Value ValueByIteration[PLY_MAX_PLUS_2];
197 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
199 // Search window management
205 // Time managment variables
208 int MaxNodes, MaxDepth;
209 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
210 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
211 bool AbortSearch, Quit;
212 bool FailLow, Problem;
214 // Show current line?
215 bool ShowCurrentLine;
219 std::ofstream LogFile;
221 // Reduction lookup tables and their getter functions
222 // Initialized at startup
223 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
224 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
226 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
227 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
229 // MP related variables
230 int ActiveThreads = 1;
231 Depth MinimumSplitDepth;
232 int MaxThreadsPerSplitPoint;
233 Thread Threads[THREAD_MAX];
236 bool AllThreadsShouldExit = false;
237 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
240 #if !defined(_MSC_VER)
241 pthread_cond_t WaitCond;
242 pthread_mutex_t WaitLock;
244 HANDLE SitIdleEvent[THREAD_MAX];
247 // Node counters, used only by thread[0] but try to keep in different
248 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
250 int NodesBetweenPolls = 30000;
257 Value id_loop(const Position& pos, Move searchMoves[]);
258 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
259 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
260 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
261 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
262 void sp_search(SplitPoint* sp, int threadID);
263 void sp_search_pv(SplitPoint* sp, int threadID);
264 void init_node(SearchStack ss[], int ply, int threadID);
265 void update_pv(SearchStack ss[], int ply);
266 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
267 bool connected_moves(const Position& pos, Move m1, Move m2);
268 bool value_is_mate(Value value);
269 bool move_is_killer(Move m, const SearchStack& ss);
270 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
271 bool ok_to_do_nullmove(const Position& pos);
272 bool ok_to_prune(const Position& pos, Move m, Move threat);
273 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
274 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
275 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
276 void update_killers(Move m, SearchStack& ss);
277 void update_gains(const Position& pos, Move move, Value before, Value after);
279 bool fail_high_ply_1();
280 int current_search_time();
284 void print_current_line(SearchStack ss[], int ply, int threadID);
285 void wait_for_stop_or_ponderhit();
286 void init_ss_array(SearchStack ss[]);
288 void idle_loop(int threadID, SplitPoint* waitSp);
289 void init_split_point_stack();
290 void destroy_split_point_stack();
291 bool thread_should_stop(int threadID);
292 bool thread_is_available(int slave, int master);
293 bool idle_thread_exists(int master);
294 bool split(const Position& pos, SearchStack* ss, int ply,
295 Value *alpha, Value *beta, Value *bestValue,
296 const Value futilityValue, Depth depth, int *moves,
297 MovePicker *mp, int master, bool pvNode);
298 void wake_sleeping_threads();
300 #if !defined(_MSC_VER)
301 void *init_thread(void *threadID);
303 DWORD WINAPI init_thread(LPVOID threadID);
314 /// perft() is our utility to verify move generation is bug free. All the legal
315 /// moves up to given depth are generated and counted and the sum returned.
317 int perft(Position& pos, Depth depth)
321 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
323 // If we are at the last ply we don't need to do and undo
324 // the moves, just to count them.
325 if (depth <= OnePly) // Replace with '<' to test also qsearch
327 while (mp.get_next_move()) sum++;
331 // Loop through all legal moves
333 while ((move = mp.get_next_move()) != MOVE_NONE)
336 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
337 sum += perft(pos, depth - OnePly);
344 /// think() is the external interface to Stockfish's search, and is called when
345 /// the program receives the UCI 'go' command. It initializes various
346 /// search-related global variables, and calls root_search(). It returns false
347 /// when a quit command is received during the search.
349 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
350 int time[], int increment[], int movesToGo, int maxDepth,
351 int maxNodes, int maxTime, Move searchMoves[]) {
353 // Initialize global search variables
354 Idle = StopOnPonderhit = AbortSearch = Quit = false;
355 FailLow = Problem = false;
357 SearchStartTime = get_system_time();
358 ExactMaxTime = maxTime;
361 InfiniteSearch = infinite;
362 PonderSearch = ponder;
363 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
365 // Look for a book move, only during games, not tests
366 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
369 if (get_option_value_string("Book File") != OpeningBook.file_name())
370 OpeningBook.open(get_option_value_string("Book File"));
372 bookMove = OpeningBook.get_move(pos);
373 if (bookMove != MOVE_NONE)
375 cout << "bestmove " << bookMove << endl;
380 for (int i = 0; i < THREAD_MAX; i++)
382 Threads[i].nodes = 0ULL;
383 Threads[i].failHighPly1 = false;
386 if (button_was_pressed("New Game"))
387 loseOnTime = false; // Reset at the beginning of a new game
389 // Read UCI option values
390 TT.set_size(get_option_value_int("Hash"));
391 if (button_was_pressed("Clear Hash"))
394 bool PonderingEnabled = get_option_value_bool("Ponder");
395 MultiPV = get_option_value_int("MultiPV");
397 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
398 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
400 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
401 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
403 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
404 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
406 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
407 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
409 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
410 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
412 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
413 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
415 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
417 Chess960 = get_option_value_bool("UCI_Chess960");
418 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
419 UseLogFile = get_option_value_bool("Use Search Log");
421 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
423 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
424 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
426 read_weights(pos.side_to_move());
428 // Set the number of active threads
429 int newActiveThreads = get_option_value_int("Threads");
430 if (newActiveThreads != ActiveThreads)
432 ActiveThreads = newActiveThreads;
433 init_eval(ActiveThreads);
434 // HACK: init_eval() destroys the static castleRightsMask[] array in the
435 // Position class. The below line repairs the damage.
436 Position p(pos.to_fen());
440 // Wake up sleeping threads
441 wake_sleeping_threads();
443 for (int i = 1; i < ActiveThreads; i++)
444 assert(thread_is_available(i, 0));
447 int myTime = time[side_to_move];
448 int myIncrement = increment[side_to_move];
449 if (UseTimeManagement)
451 if (!movesToGo) // Sudden death time control
455 MaxSearchTime = myTime / 30 + myIncrement;
456 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
458 else // Blitz game without increment
460 MaxSearchTime = myTime / 30;
461 AbsoluteMaxSearchTime = myTime / 8;
464 else // (x moves) / (y minutes)
468 MaxSearchTime = myTime / 2;
469 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
473 MaxSearchTime = myTime / Min(movesToGo, 20);
474 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
478 if (PonderingEnabled)
480 MaxSearchTime += MaxSearchTime / 4;
481 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
485 // Set best NodesBetweenPolls interval
487 NodesBetweenPolls = Min(MaxNodes, 30000);
488 else if (myTime && myTime < 1000)
489 NodesBetweenPolls = 1000;
490 else if (myTime && myTime < 5000)
491 NodesBetweenPolls = 5000;
493 NodesBetweenPolls = 30000;
495 // Write information to search log file
497 LogFile << "Searching: " << pos.to_fen() << endl
498 << "infinite: " << infinite
499 << " ponder: " << ponder
500 << " time: " << myTime
501 << " increment: " << myIncrement
502 << " moves to go: " << movesToGo << endl;
504 // LSN filtering. Used only for developing purpose. Disabled by default.
508 // Step 2. If after last move we decided to lose on time, do it now!
509 while (SearchStartTime + myTime + 1000 > get_system_time())
513 // We're ready to start thinking. Call the iterative deepening loop function
514 Value v = id_loop(pos, searchMoves);
518 // Step 1. If this is sudden death game and our position is hopeless,
519 // decide to lose on time.
520 if ( !loseOnTime // If we already lost on time, go to step 3.
530 // Step 3. Now after stepping over the time limit, reset flag for next match.
543 /// init_threads() is called during startup. It launches all helper threads,
544 /// and initializes the split point stack and the global locks and condition
547 void init_threads() {
552 #if !defined(_MSC_VER)
553 pthread_t pthread[1];
556 // Init our reduction lookup tables
557 for (i = 1; i < 64; i++) // i == depth
558 for (int j = 1; j < 64; j++) // j == moveNumber
560 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
561 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
562 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
563 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
566 // Init futility margins array
567 FutilityMargins[0] = FutilityMargins[1] = Value(0);
569 for (i = 2; i < 2 * PLY_MAX_PLUS_2; i++)
571 FutilityMargins[i] = Value(112 * bitScanReverse32(i * i / 2)); // FIXME: test using log instead of BSR
574 for (i = 0; i < THREAD_MAX; i++)
575 Threads[i].activeSplitPoints = 0;
577 // Initialize global locks
578 lock_init(&MPLock, NULL);
579 lock_init(&IOLock, NULL);
581 init_split_point_stack();
583 #if !defined(_MSC_VER)
584 pthread_mutex_init(&WaitLock, NULL);
585 pthread_cond_init(&WaitCond, NULL);
587 for (i = 0; i < THREAD_MAX; i++)
588 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
591 // All threads except the main thread should be initialized to idle state
592 for (i = 1; i < THREAD_MAX; i++)
594 Threads[i].stop = false;
595 Threads[i].workIsWaiting = false;
596 Threads[i].idle = true;
597 Threads[i].running = false;
600 // Launch the helper threads
601 for (i = 1; i < THREAD_MAX; i++)
603 #if !defined(_MSC_VER)
604 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
607 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
612 cout << "Failed to create thread number " << i << endl;
613 Application::exit_with_failure();
616 // Wait until the thread has finished launching
617 while (!Threads[i].running);
622 /// stop_threads() is called when the program exits. It makes all the
623 /// helper threads exit cleanly.
625 void stop_threads() {
627 ActiveThreads = THREAD_MAX; // HACK
628 Idle = false; // HACK
629 wake_sleeping_threads();
630 AllThreadsShouldExit = true;
631 for (int i = 1; i < THREAD_MAX; i++)
633 Threads[i].stop = true;
634 while (Threads[i].running);
636 destroy_split_point_stack();
640 /// nodes_searched() returns the total number of nodes searched so far in
641 /// the current search.
643 int64_t nodes_searched() {
645 int64_t result = 0ULL;
646 for (int i = 0; i < ActiveThreads; i++)
647 result += Threads[i].nodes;
652 // SearchStack::init() initializes a search stack. Used at the beginning of a
653 // new search from the root.
654 void SearchStack::init(int ply) {
656 pv[ply] = pv[ply + 1] = MOVE_NONE;
657 currentMove = threatMove = MOVE_NONE;
658 reduction = Depth(0);
663 void SearchStack::initKillers() {
665 mateKiller = MOVE_NONE;
666 for (int i = 0; i < KILLER_MAX; i++)
667 killers[i] = MOVE_NONE;
672 // id_loop() is the main iterative deepening loop. It calls root_search
673 // repeatedly with increasing depth until the allocated thinking time has
674 // been consumed, the user stops the search, or the maximum search depth is
677 Value id_loop(const Position& pos, Move searchMoves[]) {
680 SearchStack ss[PLY_MAX_PLUS_2];
682 // searchMoves are verified, copied, scored and sorted
683 RootMoveList rml(p, searchMoves);
685 // Handle special case of searching on a mate/stale position
686 if (rml.move_count() == 0)
689 wait_for_stop_or_ponderhit();
691 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
694 // Print RootMoveList c'tor startup scoring to the standard output,
695 // so that we print information also for iteration 1.
696 cout << "info depth " << 1 << "\ninfo depth " << 1
697 << " score " << value_to_string(rml.get_move_score(0))
698 << " time " << current_search_time()
699 << " nodes " << nodes_searched()
701 << " pv " << rml.get_move(0) << "\n";
707 ValueByIteration[1] = rml.get_move_score(0);
710 // Is one move significantly better than others after initial scoring ?
711 Move EasyMove = MOVE_NONE;
712 if ( rml.move_count() == 1
713 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
714 EasyMove = rml.get_move(0);
716 // Iterative deepening loop
717 while (Iteration < PLY_MAX)
719 // Initialize iteration
722 BestMoveChangesByIteration[Iteration] = 0;
726 cout << "info depth " << Iteration << endl;
728 // Calculate dynamic search window based on previous iterations
731 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
733 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
734 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
736 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
737 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
739 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
740 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
744 alpha = - VALUE_INFINITE;
745 beta = VALUE_INFINITE;
748 // Search to the current depth
749 Value value = root_search(p, ss, rml, alpha, beta);
751 // Write PV to transposition table, in case the relevant entries have
752 // been overwritten during the search.
753 TT.insert_pv(p, ss[0].pv);
756 break; // Value cannot be trusted. Break out immediately!
758 //Save info about search result
759 ValueByIteration[Iteration] = value;
761 // Drop the easy move if it differs from the new best move
762 if (ss[0].pv[0] != EasyMove)
763 EasyMove = MOVE_NONE;
767 if (UseTimeManagement)
770 bool stopSearch = false;
772 // Stop search early if there is only a single legal move,
773 // we search up to Iteration 6 anyway to get a proper score.
774 if (Iteration >= 6 && rml.move_count() == 1)
777 // Stop search early when the last two iterations returned a mate score
779 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
780 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
783 // Stop search early if one move seems to be much better than the rest
784 int64_t nodes = nodes_searched();
786 && EasyMove == ss[0].pv[0]
787 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
788 && current_search_time() > MaxSearchTime / 16)
789 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
790 && current_search_time() > MaxSearchTime / 32)))
793 // Add some extra time if the best move has changed during the last two iterations
794 if (Iteration > 5 && Iteration <= 50)
795 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
796 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
798 // Stop search if most of MaxSearchTime is consumed at the end of the
799 // iteration. We probably don't have enough time to search the first
800 // move at the next iteration anyway.
801 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
809 StopOnPonderhit = true;
813 if (MaxDepth && Iteration >= MaxDepth)
819 // If we are pondering or in infinite search, we shouldn't print the
820 // best move before we are told to do so.
821 if (!AbortSearch && (PonderSearch || InfiniteSearch))
822 wait_for_stop_or_ponderhit();
824 // Print final search statistics
825 cout << "info nodes " << nodes_searched()
827 << " time " << current_search_time()
828 << " hashfull " << TT.full() << endl;
830 // Print the best move and the ponder move to the standard output
831 if (ss[0].pv[0] == MOVE_NONE)
833 ss[0].pv[0] = rml.get_move(0);
834 ss[0].pv[1] = MOVE_NONE;
836 cout << "bestmove " << ss[0].pv[0];
837 if (ss[0].pv[1] != MOVE_NONE)
838 cout << " ponder " << ss[0].pv[1];
845 dbg_print_mean(LogFile);
847 if (dbg_show_hit_rate)
848 dbg_print_hit_rate(LogFile);
850 LogFile << "\nNodes: " << nodes_searched()
851 << "\nNodes/second: " << nps()
852 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
855 p.do_move(ss[0].pv[0], st);
856 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
858 return rml.get_move_score(0);
862 // root_search() is the function which searches the root node. It is
863 // similar to search_pv except that it uses a different move ordering
864 // scheme and prints some information to the standard output.
866 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
871 Depth depth, ext, newDepth;
874 int researchCount = 0;
875 bool moveIsCheck, captureOrPromotion, dangerous;
876 Value alpha = oldAlpha;
877 bool isCheck = pos.is_check();
879 // Evaluate the position statically
881 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
883 while (1) // Fail low loop
886 // Loop through all the moves in the root move list
887 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
891 // We failed high, invalidate and skip next moves, leave node-counters
892 // and beta-counters as they are and quickly return, we will try to do
893 // a research at the next iteration with a bigger aspiration window.
894 rml.set_move_score(i, -VALUE_INFINITE);
898 RootMoveNumber = i + 1;
900 // Save the current node count before the move is searched
901 nodes = nodes_searched();
903 // Reset beta cut-off counters
906 // Pick the next root move, and print the move and the move number to
907 // the standard output.
908 move = ss[0].currentMove = rml.get_move(i);
910 if (current_search_time() >= 1000)
911 cout << "info currmove " << move
912 << " currmovenumber " << RootMoveNumber << endl;
914 // Decide search depth for this move
915 moveIsCheck = pos.move_is_check(move);
916 captureOrPromotion = pos.move_is_capture_or_promotion(move);
917 depth = (Iteration - 2) * OnePly + InitialDepth;
918 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
919 newDepth = depth + ext;
921 value = - VALUE_INFINITE;
923 while (1) // Fail high loop
926 // Make the move, and search it
927 pos.do_move(move, st, ci, moveIsCheck);
929 if (i < MultiPV || value > alpha)
931 // Aspiration window is disabled in multi-pv case
933 alpha = -VALUE_INFINITE;
935 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
937 // If the value has dropped a lot compared to the last iteration,
938 // set the boolean variable Problem to true. This variable is used
939 // for time managment: When Problem is true, we try to complete the
940 // current iteration before playing a move.
941 Problem = ( Iteration >= 2
942 && value <= ValueByIteration[Iteration - 1] - ProblemMargin);
944 if (Problem && StopOnPonderhit)
945 StopOnPonderhit = false;
949 // Try to reduce non-pv search depth by one ply if move seems not problematic,
950 // if the move fails high will be re-searched at full depth.
951 bool doFullDepthSearch = true;
953 if ( depth >= 3*OnePly // FIXME was newDepth
955 && !captureOrPromotion
956 && !move_is_castle(move))
958 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
961 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
962 doFullDepthSearch = (value > alpha);
966 if (doFullDepthSearch)
968 ss[0].reduction = Depth(0);
969 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
972 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
978 // Can we exit fail high loop ?
979 if (AbortSearch || value < beta)
982 // We are failing high and going to do a research. It's important to update score
983 // before research in case we run out of time while researching.
984 rml.set_move_score(i, value);
986 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
987 rml.set_move_pv(i, ss[0].pv);
989 // Print search information to the standard output
990 cout << "info depth " << Iteration
991 << " score " << value_to_string(value)
992 << ((value >= beta) ? " lowerbound" :
993 ((value <= alpha)? " upperbound" : ""))
994 << " time " << current_search_time()
995 << " nodes " << nodes_searched()
999 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1000 cout << ss[0].pv[j] << " ";
1006 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1007 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1009 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1010 nodes_searched(), value, type, ss[0].pv) << endl;
1013 // Prepare for a research after a fail high, each time with a wider window
1015 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
1017 } // End of fail high loop
1019 // Finished searching the move. If AbortSearch is true, the search
1020 // was aborted because the user interrupted the search or because we
1021 // ran out of time. In this case, the return value of the search cannot
1022 // be trusted, and we break out of the loop without updating the best
1027 // Remember beta-cutoff and searched nodes counts for this move. The
1028 // info is used to sort the root moves at the next iteration.
1030 BetaCounter.read(pos.side_to_move(), our, their);
1031 rml.set_beta_counters(i, our, their);
1032 rml.set_move_nodes(i, nodes_searched() - nodes);
1034 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1036 if (value <= alpha && i >= MultiPV)
1037 rml.set_move_score(i, -VALUE_INFINITE);
1040 // PV move or new best move!
1043 rml.set_move_score(i, value);
1045 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1046 rml.set_move_pv(i, ss[0].pv);
1050 // We record how often the best move has been changed in each
1051 // iteration. This information is used for time managment: When
1052 // the best move changes frequently, we allocate some more time.
1054 BestMoveChangesByIteration[Iteration]++;
1056 // Print search information to the standard output
1057 cout << "info depth " << Iteration
1058 << " score " << value_to_string(value)
1059 << ((value >= beta) ? " lowerbound" :
1060 ((value <= alpha)? " upperbound" : ""))
1061 << " time " << current_search_time()
1062 << " nodes " << nodes_searched()
1066 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1067 cout << ss[0].pv[j] << " ";
1073 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1074 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1076 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1077 nodes_searched(), value, type, ss[0].pv) << endl;
1082 // Reset the global variable Problem to false if the value isn't too
1083 // far below the final value from the last iteration.
1084 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
1089 rml.sort_multipv(i);
1090 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1092 cout << "info multipv " << j + 1
1093 << " score " << value_to_string(rml.get_move_score(j))
1094 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1095 << " time " << current_search_time()
1096 << " nodes " << nodes_searched()
1100 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1101 cout << rml.get_move_pv(j, k) << " ";
1105 alpha = rml.get_move_score(Min(i, MultiPV-1));
1107 } // PV move or new best move
1109 assert(alpha >= oldAlpha);
1111 FailLow = (alpha == oldAlpha);
1114 // Can we exit fail low loop ?
1115 if (AbortSearch || alpha > oldAlpha)
1118 // Prepare for a research after a fail low, each time with a wider window
1120 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1129 // search_pv() is the main search function for PV nodes.
1131 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1132 Depth depth, int ply, int threadID) {
1134 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1135 assert(beta > alpha && beta <= VALUE_INFINITE);
1136 assert(ply >= 0 && ply < PLY_MAX);
1137 assert(threadID >= 0 && threadID < ActiveThreads);
1139 Move movesSearched[256];
1143 Depth ext, newDepth;
1144 Value oldAlpha, value;
1145 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1147 Value bestValue = value = -VALUE_INFINITE;
1150 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1152 // Initialize, and make an early exit in case of an aborted search,
1153 // an instant draw, maximum ply reached, etc.
1154 init_node(ss, ply, threadID);
1156 // After init_node() that calls poll()
1157 if (AbortSearch || thread_should_stop(threadID))
1160 if (pos.is_draw() || ply >= PLY_MAX - 1)
1163 // Mate distance pruning
1165 alpha = Max(value_mated_in(ply), alpha);
1166 beta = Min(value_mate_in(ply+1), beta);
1170 // Transposition table lookup. At PV nodes, we don't use the TT for
1171 // pruning, but only for move ordering. This is to avoid problems in
1172 // the following areas:
1174 // * Repetition draw detection
1175 // * Fifty move rule detection
1176 // * Searching for a mate
1177 // * Printing of full PV line
1179 tte = TT.retrieve(pos.get_key());
1180 ttMove = (tte ? tte->move() : MOVE_NONE);
1182 // Go with internal iterative deepening if we don't have a TT move
1183 if ( UseIIDAtPVNodes
1184 && depth >= 5*OnePly
1185 && ttMove == MOVE_NONE)
1187 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1188 ttMove = ss[ply].pv[ply];
1189 tte = TT.retrieve(pos.get_key());
1192 isCheck = pos.is_check();
1195 // Update gain statistics of the previous move that lead
1196 // us in this position.
1198 ss[ply].eval = evaluate(pos, ei, threadID);
1199 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1202 // Initialize a MovePicker object for the current position, and prepare
1203 // to search all moves
1204 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1206 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1208 // Loop through all legal moves until no moves remain or a beta cutoff
1210 while ( alpha < beta
1211 && (move = mp.get_next_move()) != MOVE_NONE
1212 && !thread_should_stop(threadID))
1214 assert(move_is_ok(move));
1216 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1217 moveIsCheck = pos.move_is_check(move, ci);
1218 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1220 // Decide the new search depth
1221 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1223 // Singular extension search. We extend the TT move if its value is much better than
1224 // its siblings. To verify this we do a reduced search on all the other moves but the
1225 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1226 if ( depth >= 6 * OnePly
1228 && move == tte->move()
1230 && is_lower_bound(tte->type())
1231 && tte->depth() >= depth - 3 * OnePly)
1233 Value ttValue = value_from_tt(tte->value(), ply);
1235 if (abs(ttValue) < VALUE_KNOWN_WIN)
1237 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1239 if (excValue < ttValue - SingleReplyMargin)
1244 newDepth = depth - OnePly + ext;
1246 // Update current move
1247 movesSearched[moveCount++] = ss[ply].currentMove = move;
1249 // Make and search the move
1250 pos.do_move(move, st, ci, moveIsCheck);
1252 if (moveCount == 1) // The first move in list is the PV
1253 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1256 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1257 // if the move fails high will be re-searched at full depth.
1258 bool doFullDepthSearch = true;
1260 if ( depth >= 3*OnePly
1262 && !captureOrPromotion
1263 && !move_is_castle(move)
1264 && !move_is_killer(move, ss[ply]))
1266 ss[ply].reduction = pv_reduction(depth, moveCount);
1267 if (ss[ply].reduction)
1269 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1270 doFullDepthSearch = (value > alpha);
1274 if (doFullDepthSearch) // Go with full depth non-pv search
1276 ss[ply].reduction = Depth(0);
1277 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1278 if (value > alpha && value < beta)
1280 // When the search fails high at ply 1 while searching the first
1281 // move at the root, set the flag failHighPly1. This is used for
1282 // time managment: We don't want to stop the search early in
1283 // such cases, because resolving the fail high at ply 1 could
1284 // result in a big drop in score at the root.
1285 if (ply == 1 && RootMoveNumber == 1)
1286 Threads[threadID].failHighPly1 = true;
1288 // A fail high occurred. Re-search at full window (pv search)
1289 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1290 Threads[threadID].failHighPly1 = false;
1294 pos.undo_move(move);
1296 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1299 if (value > bestValue)
1306 if (value == value_mate_in(ply + 1))
1307 ss[ply].mateKiller = move;
1309 // If we are at ply 1, and we are searching the first root move at
1310 // ply 0, set the 'Problem' variable if the score has dropped a lot
1311 // (from the computer's point of view) since the previous iteration.
1314 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1319 if ( ActiveThreads > 1
1321 && depth >= MinimumSplitDepth
1323 && idle_thread_exists(threadID)
1325 && !thread_should_stop(threadID)
1326 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1327 depth, &moveCount, &mp, threadID, true))
1331 // All legal moves have been searched. A special case: If there were
1332 // no legal moves, it must be mate or stalemate.
1334 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1336 // If the search is not aborted, update the transposition table,
1337 // history counters, and killer moves.
1338 if (AbortSearch || thread_should_stop(threadID))
1341 if (bestValue <= oldAlpha)
1342 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1344 else if (bestValue >= beta)
1346 BetaCounter.add(pos.side_to_move(), depth, threadID);
1347 move = ss[ply].pv[ply];
1348 if (!pos.move_is_capture_or_promotion(move))
1350 update_history(pos, move, depth, movesSearched, moveCount);
1351 update_killers(move, ss[ply]);
1353 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1356 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1362 // search() is the search function for zero-width nodes.
1364 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1365 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1367 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1368 assert(ply >= 0 && ply < PLY_MAX);
1369 assert(threadID >= 0 && threadID < ActiveThreads);
1371 Move movesSearched[256];
1376 Depth ext, newDepth;
1377 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1378 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1379 bool mateThreat = false;
1381 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1384 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1386 // Initialize, and make an early exit in case of an aborted search,
1387 // an instant draw, maximum ply reached, etc.
1388 init_node(ss, ply, threadID);
1390 // After init_node() that calls poll()
1391 if (AbortSearch || thread_should_stop(threadID))
1394 if (pos.is_draw() || ply >= PLY_MAX - 1)
1397 // Mate distance pruning
1398 if (value_mated_in(ply) >= beta)
1401 if (value_mate_in(ply + 1) < beta)
1404 // We don't want the score of a partial search to overwrite a previous full search
1405 // TT value, so we use a different position key in case of an excluded move exsists.
1406 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1408 // Transposition table lookup
1409 tte = TT.retrieve(posKey);
1410 ttMove = (tte ? tte->move() : MOVE_NONE);
1412 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1414 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1415 return value_from_tt(tte->value(), ply);
1418 isCheck = pos.is_check();
1420 // Calculate depth dependant futility pruning parameters
1421 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1423 // Evaluate the position statically
1426 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1427 staticValue = value_from_tt(tte->value(), ply);
1430 staticValue = evaluate(pos, ei, threadID);
1431 ss[ply].evalInfo = &ei;
1434 ss[ply].eval = staticValue;
1435 futilityValue = staticValue + FutilityMargins[int(depth)]; //FIXME: Remove me, only for split
1436 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1437 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1440 // Static null move pruning. We're betting that the opponent doesn't have
1441 // a move that will reduce the score by more than FutilityMargins[int(depth)]
1442 // if we do a null move.
1445 && depth < RazorDepth
1446 && staticValue - FutilityMargins[int(depth)] >= beta)
1447 return staticValue - FutilityMargins[int(depth)];
1453 && !value_is_mate(beta)
1454 && ok_to_do_nullmove(pos)
1455 && staticValue >= beta - NullMoveMargin)
1457 ss[ply].currentMove = MOVE_NULL;
1459 pos.do_null_move(st);
1461 // Null move dynamic reduction based on depth
1462 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1464 // Null move dynamic reduction based on value
1465 if (staticValue - beta > PawnValueMidgame)
1468 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1470 pos.undo_null_move();
1472 if (nullValue >= beta)
1474 if (depth < 6 * OnePly)
1477 // Do zugzwang verification search
1478 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1482 // The null move failed low, which means that we may be faced with
1483 // some kind of threat. If the previous move was reduced, check if
1484 // the move that refuted the null move was somehow connected to the
1485 // move which was reduced. If a connection is found, return a fail
1486 // low score (which will cause the reduced move to fail high in the
1487 // parent node, which will trigger a re-search with full depth).
1488 if (nullValue == value_mated_in(ply + 2))
1491 ss[ply].threatMove = ss[ply + 1].currentMove;
1492 if ( depth < ThreatDepth
1493 && ss[ply - 1].reduction
1494 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1498 // Null move search not allowed, try razoring
1499 else if ( !value_is_mate(beta)
1501 && depth < RazorDepth
1502 && staticValue < beta - (NullMoveMargin + 16 * depth)
1503 && ss[ply - 1].currentMove != MOVE_NULL
1504 && ttMove == MOVE_NONE
1505 && !pos.has_pawn_on_7th(pos.side_to_move()))
1507 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1508 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1513 // Go with internal iterative deepening if we don't have a TT move
1514 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1515 !isCheck && ss[ply].eval >= beta - IIDMargin)
1517 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1518 ttMove = ss[ply].pv[ply];
1519 tte = TT.retrieve(pos.get_key());
1522 // Initialize a MovePicker object for the current position, and prepare
1523 // to search all moves.
1524 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1527 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1528 while ( bestValue < beta
1529 && (move = mp.get_next_move()) != MOVE_NONE
1530 && !thread_should_stop(threadID))
1532 assert(move_is_ok(move));
1534 if (move == excludedMove)
1537 moveIsCheck = pos.move_is_check(move, ci);
1538 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1539 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1541 // Decide the new search depth
1542 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1544 // Singular extension search. We extend the TT move if its value is much better than
1545 // its siblings. To verify this we do a reduced search on all the other moves but the
1546 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1547 if ( depth >= 8 * OnePly
1549 && move == tte->move()
1550 && !excludedMove // Do not allow recursive single-reply search
1552 && is_lower_bound(tte->type())
1553 && tte->depth() >= depth - 3 * OnePly)
1555 Value ttValue = value_from_tt(tte->value(), ply);
1557 if (abs(ttValue) < VALUE_KNOWN_WIN)
1559 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1561 if (excValue < ttValue - SingleReplyMargin)
1566 newDepth = depth - OnePly + ext;
1568 // Update current move
1569 movesSearched[moveCount++] = ss[ply].currentMove = move;
1574 && !captureOrPromotion
1575 && !move_is_castle(move)
1578 // Move count based pruning
1579 if ( moveCount >= FutilityMoveCountMargin
1580 && ok_to_prune(pos, move, ss[ply].threatMove)
1581 && bestValue > value_mated_in(PLY_MAX))
1584 // Value based pruning
1585 Depth predictedDepth = newDepth;
1587 //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1588 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1589 if (ss[ply].reduction)
1590 predictedDepth -= ss[ply].reduction;
1592 if (predictedDepth < SelectiveDepth)
1594 int preFutilityValueMargin = 0;
1595 if (predictedDepth >= OnePly)
1596 preFutilityValueMargin = FutilityMargins[int(predictedDepth)];
1598 preFutilityValueMargin += H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1600 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1602 if (futilityValueScaled < beta)
1604 if (futilityValueScaled > bestValue)
1605 bestValue = futilityValueScaled;
1611 // Make and search the move
1612 pos.do_move(move, st, ci, moveIsCheck);
1614 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1615 // if the move fails high will be re-searched at full depth.
1616 bool doFullDepthSearch = true;
1618 if ( depth >= 3*OnePly
1620 && !captureOrPromotion
1621 && !move_is_castle(move)
1622 && !move_is_killer(move, ss[ply]))
1624 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1625 if (ss[ply].reduction)
1627 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1628 doFullDepthSearch = (value >= beta);
1632 if (doFullDepthSearch) // Go with full depth non-pv search
1634 ss[ply].reduction = Depth(0);
1635 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1637 pos.undo_move(move);
1639 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1642 if (value > bestValue)
1648 if (value == value_mate_in(ply + 1))
1649 ss[ply].mateKiller = move;
1653 if ( ActiveThreads > 1
1655 && depth >= MinimumSplitDepth
1657 && idle_thread_exists(threadID)
1659 && !thread_should_stop(threadID)
1660 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1661 depth, &moveCount, &mp, threadID, false))
1665 // All legal moves have been searched. A special case: If there were
1666 // no legal moves, it must be mate or stalemate.
1668 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1670 // If the search is not aborted, update the transposition table,
1671 // history counters, and killer moves.
1672 if (AbortSearch || thread_should_stop(threadID))
1675 if (bestValue < beta)
1676 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1679 BetaCounter.add(pos.side_to_move(), depth, threadID);
1680 move = ss[ply].pv[ply];
1681 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1682 if (!pos.move_is_capture_or_promotion(move))
1684 update_history(pos, move, depth, movesSearched, moveCount);
1685 update_killers(move, ss[ply]);
1690 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1696 // qsearch() is the quiescence search function, which is called by the main
1697 // search function when the remaining depth is zero (or, to be more precise,
1698 // less than OnePly).
1700 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1701 Depth depth, int ply, int threadID) {
1703 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1704 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1706 assert(ply >= 0 && ply < PLY_MAX);
1707 assert(threadID >= 0 && threadID < ActiveThreads);
1712 Value staticValue, bestValue, value, futilityBase, futilityValue;
1713 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1714 const TTEntry* tte = NULL;
1716 bool pvNode = (beta - alpha != 1);
1717 Value oldAlpha = alpha;
1719 // Initialize, and make an early exit in case of an aborted search,
1720 // an instant draw, maximum ply reached, etc.
1721 init_node(ss, ply, threadID);
1723 // After init_node() that calls poll()
1724 if (AbortSearch || thread_should_stop(threadID))
1727 if (pos.is_draw() || ply >= PLY_MAX - 1)
1730 // Transposition table lookup. At PV nodes, we don't use the TT for
1731 // pruning, but only for move ordering.
1732 tte = TT.retrieve(pos.get_key());
1733 ttMove = (tte ? tte->move() : MOVE_NONE);
1735 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1737 assert(tte->type() != VALUE_TYPE_EVAL);
1739 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1740 return value_from_tt(tte->value(), ply);
1743 isCheck = pos.is_check();
1745 // Evaluate the position statically
1747 staticValue = -VALUE_INFINITE;
1748 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1749 staticValue = value_from_tt(tte->value(), ply);
1751 staticValue = evaluate(pos, ei, threadID);
1755 ss[ply].eval = staticValue;
1756 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1759 // Initialize "stand pat score", and return it immediately if it is
1761 bestValue = staticValue;
1763 if (bestValue >= beta)
1765 // Store the score to avoid a future costly evaluation() call
1766 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1767 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1772 if (bestValue > alpha)
1775 // If we are near beta then try to get a cutoff pushing checks a bit further
1776 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1778 // Initialize a MovePicker object for the current position, and prepare
1779 // to search the moves. Because the depth is <= 0 here, only captures,
1780 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1781 // and we are near beta) will be generated.
1782 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1784 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1785 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1787 // Loop through the moves until no moves remain or a beta cutoff
1789 while ( alpha < beta
1790 && (move = mp.get_next_move()) != MOVE_NONE)
1792 assert(move_is_ok(move));
1794 moveIsCheck = pos.move_is_check(move, ci);
1796 // Update current move
1798 ss[ply].currentMove = move;
1806 && !move_is_promotion(move)
1807 && !pos.move_is_passed_pawn_push(move))
1809 futilityValue = futilityBase
1810 + pos.endgame_value_of_piece_on(move_to(move))
1811 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1813 if (futilityValue < alpha)
1815 if (futilityValue > bestValue)
1816 bestValue = futilityValue;
1821 // Detect blocking evasions that are candidate to be pruned
1822 evasionPrunable = isCheck
1823 && bestValue != -VALUE_INFINITE
1824 && !pos.move_is_capture(move)
1825 && pos.type_of_piece_on(move_from(move)) != KING
1826 && !pos.can_castle(pos.side_to_move());
1828 // Don't search moves with negative SEE values
1829 if ( (!isCheck || evasionPrunable)
1831 && !move_is_promotion(move)
1832 && pos.see_sign(move) < 0)
1835 // Make and search the move
1836 pos.do_move(move, st, ci, moveIsCheck);
1837 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1838 pos.undo_move(move);
1840 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1843 if (value > bestValue)
1854 // All legal moves have been searched. A special case: If we're in check
1855 // and no legal moves were found, it is checkmate.
1856 if (!moveCount && pos.is_check()) // Mate!
1857 return value_mated_in(ply);
1859 // Update transposition table
1860 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1861 if (bestValue <= oldAlpha)
1863 // If bestValue isn't changed it means it is still the static evaluation
1864 // of the node, so keep this info to avoid a future evaluation() call.
1865 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1866 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1868 else if (bestValue >= beta)
1870 move = ss[ply].pv[ply];
1871 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1873 // Update killers only for good checking moves
1874 if (!pos.move_is_capture_or_promotion(move))
1875 update_killers(move, ss[ply]);
1878 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1880 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1886 // sp_search() is used to search from a split point. This function is called
1887 // by each thread working at the split point. It is similar to the normal
1888 // search() function, but simpler. Because we have already probed the hash
1889 // table, done a null move search, and searched the first move before
1890 // splitting, we don't have to repeat all this work in sp_search(). We
1891 // also don't need to store anything to the hash table here: This is taken
1892 // care of after we return from the split point.
1894 void sp_search(SplitPoint* sp, int threadID) {
1896 assert(threadID >= 0 && threadID < ActiveThreads);
1897 assert(ActiveThreads > 1);
1899 Position pos(*sp->pos);
1901 SearchStack* ss = sp->sstack[threadID];
1902 Value value = -VALUE_INFINITE;
1905 bool isCheck = pos.is_check();
1906 bool useFutilityPruning = sp->depth < SelectiveDepth
1909 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1911 while ( lock_grab_bool(&(sp->lock))
1912 && sp->bestValue < sp->beta
1913 && !thread_should_stop(threadID)
1914 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1916 moveCount = ++sp->moves;
1917 lock_release(&(sp->lock));
1919 assert(move_is_ok(move));
1921 bool moveIsCheck = pos.move_is_check(move, ci);
1922 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1924 ss[sp->ply].currentMove = move;
1926 // Decide the new search depth
1928 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1929 Depth newDepth = sp->depth - OnePly + ext;
1932 if ( useFutilityPruning
1934 && !captureOrPromotion)
1936 // Move count based pruning
1937 if ( moveCount >= FutilityMoveCountMargin
1938 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1939 && sp->bestValue > value_mated_in(PLY_MAX))
1942 // Value based pruning
1943 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1945 if (futilityValueScaled < sp->beta)
1947 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1949 lock_grab(&(sp->lock));
1950 if (futilityValueScaled > sp->bestValue)
1951 sp->bestValue = futilityValueScaled;
1952 lock_release(&(sp->lock));
1958 // Make and search the move.
1960 pos.do_move(move, st, ci, moveIsCheck);
1962 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1963 // if the move fails high will be re-searched at full depth.
1964 bool doFullDepthSearch = true;
1967 && !captureOrPromotion
1968 && !move_is_castle(move)
1969 && !move_is_killer(move, ss[sp->ply]))
1971 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1972 if (ss[sp->ply].reduction)
1974 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1975 doFullDepthSearch = (value >= sp->beta);
1979 if (doFullDepthSearch) // Go with full depth non-pv search
1981 ss[sp->ply].reduction = Depth(0);
1982 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1984 pos.undo_move(move);
1986 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1988 if (thread_should_stop(threadID))
1990 lock_grab(&(sp->lock));
1995 if (value > sp->bestValue) // Less then 2% of cases
1997 lock_grab(&(sp->lock));
1998 if (value > sp->bestValue && !thread_should_stop(threadID))
2000 sp->bestValue = value;
2001 if (sp->bestValue >= sp->beta)
2003 sp_update_pv(sp->parentSstack, ss, sp->ply);
2004 for (int i = 0; i < ActiveThreads; i++)
2005 if (i != threadID && (i == sp->master || sp->slaves[i]))
2006 Threads[i].stop = true;
2008 sp->finished = true;
2011 lock_release(&(sp->lock));
2015 /* Here we have the lock still grabbed */
2017 // If this is the master thread and we have been asked to stop because of
2018 // a beta cutoff higher up in the tree, stop all slave threads.
2019 if (sp->master == threadID && thread_should_stop(threadID))
2020 for (int i = 0; i < ActiveThreads; i++)
2022 Threads[i].stop = true;
2025 sp->slaves[threadID] = 0;
2027 lock_release(&(sp->lock));
2031 // sp_search_pv() is used to search from a PV split point. This function
2032 // is called by each thread working at the split point. It is similar to
2033 // the normal search_pv() function, but simpler. Because we have already
2034 // probed the hash table and searched the first move before splitting, we
2035 // don't have to repeat all this work in sp_search_pv(). We also don't
2036 // need to store anything to the hash table here: This is taken care of
2037 // after we return from the split point.
2039 void sp_search_pv(SplitPoint* sp, int threadID) {
2041 assert(threadID >= 0 && threadID < ActiveThreads);
2042 assert(ActiveThreads > 1);
2044 Position pos(*sp->pos);
2046 SearchStack* ss = sp->sstack[threadID];
2047 Value value = -VALUE_INFINITE;
2051 while ( lock_grab_bool(&(sp->lock))
2052 && sp->alpha < sp->beta
2053 && !thread_should_stop(threadID)
2054 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2056 moveCount = ++sp->moves;
2057 lock_release(&(sp->lock));
2059 assert(move_is_ok(move));
2061 bool moveIsCheck = pos.move_is_check(move, ci);
2062 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2064 ss[sp->ply].currentMove = move;
2066 // Decide the new search depth
2068 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2069 Depth newDepth = sp->depth - OnePly + ext;
2071 // Make and search the move.
2073 pos.do_move(move, st, ci, moveIsCheck);
2075 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2076 // if the move fails high will be re-searched at full depth.
2077 bool doFullDepthSearch = true;
2080 && !captureOrPromotion
2081 && !move_is_castle(move)
2082 && !move_is_killer(move, ss[sp->ply]))
2084 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
2085 if (ss[sp->ply].reduction)
2087 Value localAlpha = sp->alpha;
2088 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2089 doFullDepthSearch = (value > localAlpha);
2093 if (doFullDepthSearch) // Go with full depth non-pv search
2095 Value localAlpha = sp->alpha;
2096 ss[sp->ply].reduction = Depth(0);
2097 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2099 if (value > localAlpha && value < sp->beta)
2101 // When the search fails high at ply 1 while searching the first
2102 // move at the root, set the flag failHighPly1. This is used for
2103 // time managment: We don't want to stop the search early in
2104 // such cases, because resolving the fail high at ply 1 could
2105 // result in a big drop in score at the root.
2106 if (sp->ply == 1 && RootMoveNumber == 1)
2107 Threads[threadID].failHighPly1 = true;
2109 // If another thread has failed high then sp->alpha has been increased
2110 // to be higher or equal then beta, if so, avoid to start a PV search.
2111 localAlpha = sp->alpha;
2112 if (localAlpha < sp->beta)
2113 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2115 assert(thread_should_stop(threadID));
2117 Threads[threadID].failHighPly1 = false;
2120 pos.undo_move(move);
2122 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2124 if (thread_should_stop(threadID))
2126 lock_grab(&(sp->lock));
2131 if (value > sp->bestValue) // Less then 2% of cases
2133 lock_grab(&(sp->lock));
2134 if (value > sp->bestValue && !thread_should_stop(threadID))
2136 sp->bestValue = value;
2137 if (value > sp->alpha)
2139 // Ask threads to stop before to modify sp->alpha
2140 if (value >= sp->beta)
2142 for (int i = 0; i < ActiveThreads; i++)
2143 if (i != threadID && (i == sp->master || sp->slaves[i]))
2144 Threads[i].stop = true;
2146 sp->finished = true;
2151 sp_update_pv(sp->parentSstack, ss, sp->ply);
2152 if (value == value_mate_in(sp->ply + 1))
2153 ss[sp->ply].mateKiller = move;
2155 // If we are at ply 1, and we are searching the first root move at
2156 // ply 0, set the 'Problem' variable if the score has dropped a lot
2157 // (from the computer's point of view) since the previous iteration.
2160 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
2163 lock_release(&(sp->lock));
2167 /* Here we have the lock still grabbed */
2169 // If this is the master thread and we have been asked to stop because of
2170 // a beta cutoff higher up in the tree, stop all slave threads.
2171 if (sp->master == threadID && thread_should_stop(threadID))
2172 for (int i = 0; i < ActiveThreads; i++)
2174 Threads[i].stop = true;
2177 sp->slaves[threadID] = 0;
2179 lock_release(&(sp->lock));
2182 /// The BetaCounterType class
2184 BetaCounterType::BetaCounterType() { clear(); }
2186 void BetaCounterType::clear() {
2188 for (int i = 0; i < THREAD_MAX; i++)
2189 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2192 void BetaCounterType::add(Color us, Depth d, int threadID) {
2194 // Weighted count based on depth
2195 Threads[threadID].betaCutOffs[us] += unsigned(d);
2198 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2201 for (int i = 0; i < THREAD_MAX; i++)
2203 our += Threads[i].betaCutOffs[us];
2204 their += Threads[i].betaCutOffs[opposite_color(us)];
2209 /// The RootMoveList class
2211 // RootMoveList c'tor
2213 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2215 SearchStack ss[PLY_MAX_PLUS_2];
2216 MoveStack mlist[MaxRootMoves];
2218 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2220 // Generate all legal moves
2221 MoveStack* last = generate_moves(pos, mlist);
2223 // Add each move to the moves[] array
2224 for (MoveStack* cur = mlist; cur != last; cur++)
2226 bool includeMove = includeAllMoves;
2228 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2229 includeMove = (searchMoves[k] == cur->move);
2234 // Find a quick score for the move
2236 pos.do_move(cur->move, st);
2237 moves[count].move = cur->move;
2238 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2239 moves[count].pv[0] = cur->move;
2240 moves[count].pv[1] = MOVE_NONE;
2241 pos.undo_move(cur->move);
2248 // RootMoveList simple methods definitions
2250 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2252 moves[moveNum].nodes = nodes;
2253 moves[moveNum].cumulativeNodes += nodes;
2256 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2258 moves[moveNum].ourBeta = our;
2259 moves[moveNum].theirBeta = their;
2262 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2266 for (j = 0; pv[j] != MOVE_NONE; j++)
2267 moves[moveNum].pv[j] = pv[j];
2269 moves[moveNum].pv[j] = MOVE_NONE;
2273 // RootMoveList::sort() sorts the root move list at the beginning of a new
2276 void RootMoveList::sort() {
2278 sort_multipv(count - 1); // Sort all items
2282 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2283 // list by their scores and depths. It is used to order the different PVs
2284 // correctly in MultiPV mode.
2286 void RootMoveList::sort_multipv(int n) {
2290 for (i = 1; i <= n; i++)
2292 RootMove rm = moves[i];
2293 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2294 moves[j] = moves[j - 1];
2301 // init_node() is called at the beginning of all the search functions
2302 // (search(), search_pv(), qsearch(), and so on) and initializes the
2303 // search stack object corresponding to the current node. Once every
2304 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2305 // for user input and checks whether it is time to stop the search.
2307 void init_node(SearchStack ss[], int ply, int threadID) {
2309 assert(ply >= 0 && ply < PLY_MAX);
2310 assert(threadID >= 0 && threadID < ActiveThreads);
2312 Threads[threadID].nodes++;
2317 if (NodesSincePoll >= NodesBetweenPolls)
2324 ss[ply + 2].initKillers();
2326 if (Threads[threadID].printCurrentLine)
2327 print_current_line(ss, ply, threadID);
2331 // update_pv() is called whenever a search returns a value > alpha.
2332 // It updates the PV in the SearchStack object corresponding to the
2335 void update_pv(SearchStack ss[], int ply) {
2337 assert(ply >= 0 && ply < PLY_MAX);
2341 ss[ply].pv[ply] = ss[ply].currentMove;
2343 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2344 ss[ply].pv[p] = ss[ply + 1].pv[p];
2346 ss[ply].pv[p] = MOVE_NONE;
2350 // sp_update_pv() is a variant of update_pv for use at split points. The
2351 // difference between the two functions is that sp_update_pv also updates
2352 // the PV at the parent node.
2354 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2356 assert(ply >= 0 && ply < PLY_MAX);
2360 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2362 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2363 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2365 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2369 // connected_moves() tests whether two moves are 'connected' in the sense
2370 // that the first move somehow made the second move possible (for instance
2371 // if the moving piece is the same in both moves). The first move is assumed
2372 // to be the move that was made to reach the current position, while the
2373 // second move is assumed to be a move from the current position.
2375 bool connected_moves(const Position& pos, Move m1, Move m2) {
2377 Square f1, t1, f2, t2;
2380 assert(move_is_ok(m1));
2381 assert(move_is_ok(m2));
2383 if (m2 == MOVE_NONE)
2386 // Case 1: The moving piece is the same in both moves
2392 // Case 2: The destination square for m2 was vacated by m1
2398 // Case 3: Moving through the vacated square
2399 if ( piece_is_slider(pos.piece_on(f2))
2400 && bit_is_set(squares_between(f2, t2), f1))
2403 // Case 4: The destination square for m2 is defended by the moving piece in m1
2404 p = pos.piece_on(t1);
2405 if (bit_is_set(pos.attacks_from(p, t1), t2))
2408 // Case 5: Discovered check, checking piece is the piece moved in m1
2409 if ( piece_is_slider(p)
2410 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2411 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2413 // discovered_check_candidates() works also if the Position's side to
2414 // move is the opposite of the checking piece.
2415 Color them = opposite_color(pos.side_to_move());
2416 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2418 if (bit_is_set(dcCandidates, f2))
2425 // value_is_mate() checks if the given value is a mate one
2426 // eventually compensated for the ply.
2428 bool value_is_mate(Value value) {
2430 assert(abs(value) <= VALUE_INFINITE);
2432 return value <= value_mated_in(PLY_MAX)
2433 || value >= value_mate_in(PLY_MAX);
2437 // move_is_killer() checks if the given move is among the
2438 // killer moves of that ply.
2440 bool move_is_killer(Move m, const SearchStack& ss) {
2442 const Move* k = ss.killers;
2443 for (int i = 0; i < KILLER_MAX; i++, k++)
2451 // extension() decides whether a move should be searched with normal depth,
2452 // or with extended depth. Certain classes of moves (checking moves, in
2453 // particular) are searched with bigger depth than ordinary moves and in
2454 // any case are marked as 'dangerous'. Note that also if a move is not
2455 // extended, as example because the corresponding UCI option is set to zero,
2456 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2458 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2459 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2461 assert(m != MOVE_NONE);
2463 Depth result = Depth(0);
2464 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2469 result += CheckExtension[pvNode];
2472 result += SingleEvasionExtension[pvNode];
2475 result += MateThreatExtension[pvNode];
2478 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2480 Color c = pos.side_to_move();
2481 if (relative_rank(c, move_to(m)) == RANK_7)
2483 result += PawnPushTo7thExtension[pvNode];
2486 if (pos.pawn_is_passed(c, move_to(m)))
2488 result += PassedPawnExtension[pvNode];
2493 if ( captureOrPromotion
2494 && pos.type_of_piece_on(move_to(m)) != PAWN
2495 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2496 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2497 && !move_is_promotion(m)
2500 result += PawnEndgameExtension[pvNode];
2505 && captureOrPromotion
2506 && pos.type_of_piece_on(move_to(m)) != PAWN
2507 && pos.see_sign(m) >= 0)
2513 return Min(result, OnePly);
2517 // ok_to_do_nullmove() looks at the current position and decides whether
2518 // doing a 'null move' should be allowed. In order to avoid zugzwang
2519 // problems, null moves are not allowed when the side to move has very
2520 // little material left. Currently, the test is a bit too simple: Null
2521 // moves are avoided only when the side to move has only pawns left.
2522 // It's probably a good idea to avoid null moves in at least some more
2523 // complicated endgames, e.g. KQ vs KR. FIXME
2525 bool ok_to_do_nullmove(const Position& pos) {
2527 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2531 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2532 // non-tactical moves late in the move list close to the leaves are
2533 // candidates for pruning.
2535 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2537 assert(move_is_ok(m));
2538 assert(threat == MOVE_NONE || move_is_ok(threat));
2539 assert(!pos.move_is_check(m));
2540 assert(!pos.move_is_capture_or_promotion(m));
2541 assert(!pos.move_is_passed_pawn_push(m));
2543 Square mfrom, mto, tfrom, tto;
2545 // Prune if there isn't any threat move
2546 if (threat == MOVE_NONE)
2549 mfrom = move_from(m);
2551 tfrom = move_from(threat);
2552 tto = move_to(threat);
2554 // Case 1: Don't prune moves which move the threatened piece
2558 // Case 2: If the threatened piece has value less than or equal to the
2559 // value of the threatening piece, don't prune move which defend it.
2560 if ( pos.move_is_capture(threat)
2561 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2562 || pos.type_of_piece_on(tfrom) == KING)
2563 && pos.move_attacks_square(m, tto))
2566 // Case 3: If the moving piece in the threatened move is a slider, don't
2567 // prune safe moves which block its ray.
2568 if ( piece_is_slider(pos.piece_on(tfrom))
2569 && bit_is_set(squares_between(tfrom, tto), mto)
2570 && pos.see_sign(m) >= 0)
2577 // ok_to_use_TT() returns true if a transposition table score
2578 // can be used at a given point in search.
2580 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2582 Value v = value_from_tt(tte->value(), ply);
2584 return ( tte->depth() >= depth
2585 || v >= Max(value_mate_in(PLY_MAX), beta)
2586 || v < Min(value_mated_in(PLY_MAX), beta))
2588 && ( (is_lower_bound(tte->type()) && v >= beta)
2589 || (is_upper_bound(tte->type()) && v < beta));
2593 // refine_eval() returns the transposition table score if
2594 // possible otherwise falls back on static position evaluation.
2596 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2601 Value v = value_from_tt(tte->value(), ply);
2603 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2604 || (is_upper_bound(tte->type()) && v < defaultEval))
2611 // update_history() registers a good move that produced a beta-cutoff
2612 // in history and marks as failures all the other moves of that ply.
2614 void update_history(const Position& pos, Move move, Depth depth,
2615 Move movesSearched[], int moveCount) {
2619 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2621 for (int i = 0; i < moveCount - 1; i++)
2623 m = movesSearched[i];
2627 if (!pos.move_is_capture_or_promotion(m))
2628 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2633 // update_killers() add a good move that produced a beta-cutoff
2634 // among the killer moves of that ply.
2636 void update_killers(Move m, SearchStack& ss) {
2638 if (m == ss.killers[0])
2641 for (int i = KILLER_MAX - 1; i > 0; i--)
2642 ss.killers[i] = ss.killers[i - 1];
2648 // update_gains() updates the gains table of a non-capture move given
2649 // the static position evaluation before and after the move.
2651 void update_gains(const Position& pos, Move m, Value before, Value after) {
2654 && before != VALUE_NONE
2655 && after != VALUE_NONE
2656 && pos.captured_piece() == NO_PIECE_TYPE
2657 && !move_is_castle(m)
2658 && !move_is_promotion(m))
2659 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2663 // fail_high_ply_1() checks if some thread is currently resolving a fail
2664 // high at ply 1 at the node below the first root node. This information
2665 // is used for time management.
2667 bool fail_high_ply_1() {
2669 for (int i = 0; i < ActiveThreads; i++)
2670 if (Threads[i].failHighPly1)
2677 // current_search_time() returns the number of milliseconds which have passed
2678 // since the beginning of the current search.
2680 int current_search_time() {
2682 return get_system_time() - SearchStartTime;
2686 // nps() computes the current nodes/second count.
2690 int t = current_search_time();
2691 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2695 // poll() performs two different functions: It polls for user input, and it
2696 // looks at the time consumed so far and decides if it's time to abort the
2701 static int lastInfoTime;
2702 int t = current_search_time();
2707 // We are line oriented, don't read single chars
2708 std::string command;
2710 if (!std::getline(std::cin, command))
2713 if (command == "quit")
2716 PonderSearch = false;
2720 else if (command == "stop")
2723 PonderSearch = false;
2725 else if (command == "ponderhit")
2729 // Print search information
2733 else if (lastInfoTime > t)
2734 // HACK: Must be a new search where we searched less than
2735 // NodesBetweenPolls nodes during the first second of search.
2738 else if (t - lastInfoTime >= 1000)
2746 if (dbg_show_hit_rate)
2747 dbg_print_hit_rate();
2749 cout << "info nodes " << nodes_searched() << " nps " << nps()
2750 << " time " << t << " hashfull " << TT.full() << endl;
2752 lock_release(&IOLock);
2754 if (ShowCurrentLine)
2755 Threads[0].printCurrentLine = true;
2758 // Should we stop the search?
2762 bool stillAtFirstMove = RootMoveNumber == 1
2764 && t > MaxSearchTime + ExtraSearchTime;
2766 bool noMoreTime = t > AbsoluteMaxSearchTime
2767 || stillAtFirstMove;
2769 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2770 || (ExactMaxTime && t >= ExactMaxTime)
2771 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2776 // ponderhit() is called when the program is pondering (i.e. thinking while
2777 // it's the opponent's turn to move) in order to let the engine know that
2778 // it correctly predicted the opponent's move.
2782 int t = current_search_time();
2783 PonderSearch = false;
2785 bool stillAtFirstMove = RootMoveNumber == 1
2787 && t > MaxSearchTime + ExtraSearchTime;
2789 bool noMoreTime = t > AbsoluteMaxSearchTime
2790 || stillAtFirstMove;
2792 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2797 // print_current_line() prints the current line of search for a given
2798 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2800 void print_current_line(SearchStack ss[], int ply, int threadID) {
2802 assert(ply >= 0 && ply < PLY_MAX);
2803 assert(threadID >= 0 && threadID < ActiveThreads);
2805 if (!Threads[threadID].idle)
2808 cout << "info currline " << (threadID + 1);
2809 for (int p = 0; p < ply; p++)
2810 cout << " " << ss[p].currentMove;
2813 lock_release(&IOLock);
2815 Threads[threadID].printCurrentLine = false;
2816 if (threadID + 1 < ActiveThreads)
2817 Threads[threadID + 1].printCurrentLine = true;
2821 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2823 void init_ss_array(SearchStack ss[]) {
2825 for (int i = 0; i < 3; i++)
2828 ss[i].initKillers();
2833 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2834 // while the program is pondering. The point is to work around a wrinkle in
2835 // the UCI protocol: When pondering, the engine is not allowed to give a
2836 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2837 // We simply wait here until one of these commands is sent, and return,
2838 // after which the bestmove and pondermove will be printed (in id_loop()).
2840 void wait_for_stop_or_ponderhit() {
2842 std::string command;
2846 if (!std::getline(std::cin, command))
2849 if (command == "quit")
2854 else if (command == "ponderhit" || command == "stop")
2860 // idle_loop() is where the threads are parked when they have no work to do.
2861 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2862 // object for which the current thread is the master.
2864 void idle_loop(int threadID, SplitPoint* waitSp) {
2866 assert(threadID >= 0 && threadID < THREAD_MAX);
2868 Threads[threadID].running = true;
2872 if (AllThreadsShouldExit && threadID != 0)
2875 // If we are not thinking, wait for a condition to be signaled
2876 // instead of wasting CPU time polling for work.
2877 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2880 #if !defined(_MSC_VER)
2881 pthread_mutex_lock(&WaitLock);
2882 if (Idle || threadID >= ActiveThreads)
2883 pthread_cond_wait(&WaitCond, &WaitLock);
2885 pthread_mutex_unlock(&WaitLock);
2887 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2891 // If this thread has been assigned work, launch a search
2892 if (Threads[threadID].workIsWaiting)
2894 assert(!Threads[threadID].idle);
2896 Threads[threadID].workIsWaiting = false;
2897 if (Threads[threadID].splitPoint->pvNode)
2898 sp_search_pv(Threads[threadID].splitPoint, threadID);
2900 sp_search(Threads[threadID].splitPoint, threadID);
2902 Threads[threadID].idle = true;
2905 // If this thread is the master of a split point and all threads have
2906 // finished their work at this split point, return from the idle loop.
2907 if (waitSp != NULL && waitSp->cpus == 0)
2911 Threads[threadID].running = false;
2915 // init_split_point_stack() is called during program initialization, and
2916 // initializes all split point objects.
2918 void init_split_point_stack() {
2920 for (int i = 0; i < THREAD_MAX; i++)
2921 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2923 SplitPointStack[i][j].parent = NULL;
2924 lock_init(&(SplitPointStack[i][j].lock), NULL);
2929 // destroy_split_point_stack() is called when the program exits, and
2930 // destroys all locks in the precomputed split point objects.
2932 void destroy_split_point_stack() {
2934 for (int i = 0; i < THREAD_MAX; i++)
2935 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2936 lock_destroy(&(SplitPointStack[i][j].lock));
2940 // thread_should_stop() checks whether the thread with a given threadID has
2941 // been asked to stop, directly or indirectly. This can happen if a beta
2942 // cutoff has occurred in the thread's currently active split point, or in
2943 // some ancestor of the current split point.
2945 bool thread_should_stop(int threadID) {
2947 assert(threadID >= 0 && threadID < ActiveThreads);
2951 if (Threads[threadID].stop)
2953 if (ActiveThreads <= 2)
2955 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2958 Threads[threadID].stop = true;
2965 // thread_is_available() checks whether the thread with threadID "slave" is
2966 // available to help the thread with threadID "master" at a split point. An
2967 // obvious requirement is that "slave" must be idle. With more than two
2968 // threads, this is not by itself sufficient: If "slave" is the master of
2969 // some active split point, it is only available as a slave to the other
2970 // threads which are busy searching the split point at the top of "slave"'s
2971 // split point stack (the "helpful master concept" in YBWC terminology).
2973 bool thread_is_available(int slave, int master) {
2975 assert(slave >= 0 && slave < ActiveThreads);
2976 assert(master >= 0 && master < ActiveThreads);
2977 assert(ActiveThreads > 1);
2979 if (!Threads[slave].idle || slave == master)
2982 // Make a local copy to be sure doesn't change under our feet
2983 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
2985 if (localActiveSplitPoints == 0)
2986 // No active split points means that the thread is available as
2987 // a slave for any other thread.
2990 if (ActiveThreads == 2)
2993 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2994 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
2995 // could have been set to 0 by another thread leading to an out of bound access.
2996 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
3003 // idle_thread_exists() tries to find an idle thread which is available as
3004 // a slave for the thread with threadID "master".
3006 bool idle_thread_exists(int master) {
3008 assert(master >= 0 && master < ActiveThreads);
3009 assert(ActiveThreads > 1);
3011 for (int i = 0; i < ActiveThreads; i++)
3012 if (thread_is_available(i, master))
3019 // split() does the actual work of distributing the work at a node between
3020 // several threads at PV nodes. If it does not succeed in splitting the
3021 // node (because no idle threads are available, or because we have no unused
3022 // split point objects), the function immediately returns false. If
3023 // splitting is possible, a SplitPoint object is initialized with all the
3024 // data that must be copied to the helper threads (the current position and
3025 // search stack, alpha, beta, the search depth, etc.), and we tell our
3026 // helper threads that they have been assigned work. This will cause them
3027 // to instantly leave their idle loops and call sp_search_pv(). When all
3028 // threads have returned from sp_search_pv (or, equivalently, when
3029 // splitPoint->cpus becomes 0), split() returns true.
3031 bool split(const Position& p, SearchStack* sstck, int ply,
3032 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
3033 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
3036 assert(sstck != NULL);
3037 assert(ply >= 0 && ply < PLY_MAX);
3038 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
3039 assert(!pvNode || *alpha < *beta);
3040 assert(*beta <= VALUE_INFINITE);
3041 assert(depth > Depth(0));
3042 assert(master >= 0 && master < ActiveThreads);
3043 assert(ActiveThreads > 1);
3045 SplitPoint* splitPoint;
3049 // If no other thread is available to help us, or if we have too many
3050 // active split points, don't split.
3051 if ( !idle_thread_exists(master)
3052 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
3054 lock_release(&MPLock);
3058 // Pick the next available split point object from the split point stack
3059 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
3060 Threads[master].activeSplitPoints++;
3062 // Initialize the split point object
3063 splitPoint->parent = Threads[master].splitPoint;
3064 splitPoint->finished = false;
3065 splitPoint->ply = ply;
3066 splitPoint->depth = depth;
3067 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
3068 splitPoint->beta = *beta;
3069 splitPoint->pvNode = pvNode;
3070 splitPoint->bestValue = *bestValue;
3071 splitPoint->futilityValue = futilityValue;
3072 splitPoint->master = master;
3073 splitPoint->mp = mp;
3074 splitPoint->moves = *moves;
3075 splitPoint->cpus = 1;
3076 splitPoint->pos = &p;
3077 splitPoint->parentSstack = sstck;
3078 for (int i = 0; i < ActiveThreads; i++)
3079 splitPoint->slaves[i] = 0;
3081 Threads[master].idle = false;
3082 Threads[master].stop = false;
3083 Threads[master].splitPoint = splitPoint;
3085 // Allocate available threads setting idle flag to false
3086 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3087 if (thread_is_available(i, master))
3089 Threads[i].idle = false;
3090 Threads[i].stop = false;
3091 Threads[i].splitPoint = splitPoint;
3092 splitPoint->slaves[i] = 1;
3096 assert(splitPoint->cpus > 1);
3098 // We can release the lock because master and slave threads are already booked
3099 lock_release(&MPLock);
3101 // Tell the threads that they have work to do. This will make them leave
3102 // their idle loop. But before copy search stack tail for each thread.
3103 for (int i = 0; i < ActiveThreads; i++)
3104 if (i == master || splitPoint->slaves[i])
3106 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3107 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3110 // Everything is set up. The master thread enters the idle loop, from
3111 // which it will instantly launch a search, because its workIsWaiting
3112 // slot is 'true'. We send the split point as a second parameter to the
3113 // idle loop, which means that the main thread will return from the idle
3114 // loop when all threads have finished their work at this split point
3115 // (i.e. when splitPoint->cpus == 0).
3116 idle_loop(master, splitPoint);
3118 // We have returned from the idle loop, which means that all threads are
3119 // finished. Update alpha, beta and bestValue, and return.
3123 *alpha = splitPoint->alpha;
3125 *beta = splitPoint->beta;
3126 *bestValue = splitPoint->bestValue;
3127 Threads[master].stop = false;
3128 Threads[master].idle = false;
3129 Threads[master].activeSplitPoints--;
3130 Threads[master].splitPoint = splitPoint->parent;
3132 lock_release(&MPLock);
3137 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3138 // to start a new search from the root.
3140 void wake_sleeping_threads() {
3142 if (ActiveThreads > 1)
3144 for (int i = 1; i < ActiveThreads; i++)
3146 Threads[i].idle = true;
3147 Threads[i].workIsWaiting = false;
3150 #if !defined(_MSC_VER)
3151 pthread_mutex_lock(&WaitLock);
3152 pthread_cond_broadcast(&WaitCond);
3153 pthread_mutex_unlock(&WaitLock);
3155 for (int i = 1; i < THREAD_MAX; i++)
3156 SetEvent(SitIdleEvent[i]);
3162 // init_thread() is the function which is called when a new thread is
3163 // launched. It simply calls the idle_loop() function with the supplied
3164 // threadID. There are two versions of this function; one for POSIX
3165 // threads and one for Windows threads.
3167 #if !defined(_MSC_VER)
3169 void* init_thread(void *threadID) {
3171 idle_loop(*(int*)threadID, NULL);
3177 DWORD WINAPI init_thread(LPVOID threadID) {
3179 idle_loop(*(int*)threadID, NULL);