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 // Null move margin. A null move search will not be done if the static
146 // evaluation of the position is more than NullMoveMargin below beta.
147 const Value NullMoveMargin = Value(0x200);
149 // If the TT move is at least SingleReplyMargin better then the
150 // remaining ones we will extend it.
151 const Value SingleReplyMargin = Value(0x20);
153 // Margins for futility pruning in the quiescence search, and at frontier
154 // and near frontier nodes.
155 const Value FutilityMarginQS = Value(0x80);
157 Value FutilityMargins[2 * PLY_MAX_PLUS_2]; // Initialized at startup.
159 // Each move futility margin is decreased
160 const Value IncrementalFutilityMargin = Value(0x8);
162 // Depth limit for razoring
163 const Depth RazorDepth = 4 * OnePly;
165 /// Variables initialized by UCI options
167 // Depth limit for use of dynamic threat detection
170 // Last seconds noise filtering (LSN)
171 const bool UseLSNFiltering = true;
172 const int LSNTime = 4000; // In milliseconds
173 const Value LSNValue = value_from_centipawns(200);
174 bool loseOnTime = false;
176 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
177 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
178 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
180 // Iteration counters
182 BetaCounterType BetaCounter;
184 // Scores and number of times the best move changed for each iteration
185 Value ValueByIteration[PLY_MAX_PLUS_2];
186 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
188 // Search window management
194 // Time managment variables
197 int MaxNodes, MaxDepth;
198 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
199 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
200 bool AbortSearch, Quit;
201 bool AspirationFailLow;
203 // Show current line?
204 bool ShowCurrentLine;
208 std::ofstream LogFile;
210 // Reduction lookup tables and their getter functions
211 // Initialized at startup
212 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
213 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
215 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
216 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
218 // MP related variables
219 int ActiveThreads = 1;
220 Depth MinimumSplitDepth;
221 int MaxThreadsPerSplitPoint;
222 Thread Threads[THREAD_MAX];
225 bool AllThreadsShouldExit = false;
226 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
229 #if !defined(_MSC_VER)
230 pthread_cond_t WaitCond;
231 pthread_mutex_t WaitLock;
233 HANDLE SitIdleEvent[THREAD_MAX];
236 // Node counters, used only by thread[0] but try to keep in different
237 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
239 int NodesBetweenPolls = 30000;
246 Value id_loop(const Position& pos, Move searchMoves[]);
247 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
248 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
249 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
250 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
251 void sp_search(SplitPoint* sp, int threadID);
252 void sp_search_pv(SplitPoint* sp, int threadID);
253 void init_node(SearchStack ss[], int ply, int threadID);
254 void update_pv(SearchStack ss[], int ply);
255 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
256 bool connected_moves(const Position& pos, Move m1, Move m2);
257 bool value_is_mate(Value value);
258 bool move_is_killer(Move m, const SearchStack& ss);
259 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
260 bool ok_to_do_nullmove(const Position& pos);
261 bool ok_to_prune(const Position& pos, Move m, Move threat);
262 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
263 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
264 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
265 void update_killers(Move m, SearchStack& ss);
266 void update_gains(const Position& pos, Move move, Value before, Value after);
268 int current_search_time();
272 void print_current_line(SearchStack ss[], int ply, int threadID);
273 void wait_for_stop_or_ponderhit();
274 void init_ss_array(SearchStack ss[]);
276 void idle_loop(int threadID, SplitPoint* waitSp);
277 void init_split_point_stack();
278 void destroy_split_point_stack();
279 bool thread_should_stop(int threadID);
280 bool thread_is_available(int slave, int master);
281 bool idle_thread_exists(int master);
282 bool split(const Position& pos, SearchStack* ss, int ply,
283 Value *alpha, Value *beta, Value *bestValue,
284 const Value futilityValue, Depth depth, int *moves,
285 MovePicker *mp, int master, bool pvNode);
286 void wake_sleeping_threads();
288 #if !defined(_MSC_VER)
289 void *init_thread(void *threadID);
291 DWORD WINAPI init_thread(LPVOID threadID);
302 /// perft() is our utility to verify move generation is bug free. All the legal
303 /// moves up to given depth are generated and counted and the sum returned.
305 int perft(Position& pos, Depth depth)
309 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
311 // If we are at the last ply we don't need to do and undo
312 // the moves, just to count them.
313 if (depth <= OnePly) // Replace with '<' to test also qsearch
315 while (mp.get_next_move()) sum++;
319 // Loop through all legal moves
321 while ((move = mp.get_next_move()) != MOVE_NONE)
324 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
325 sum += perft(pos, depth - OnePly);
332 /// think() is the external interface to Stockfish's search, and is called when
333 /// the program receives the UCI 'go' command. It initializes various
334 /// search-related global variables, and calls root_search(). It returns false
335 /// when a quit command is received during the search.
337 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
338 int time[], int increment[], int movesToGo, int maxDepth,
339 int maxNodes, int maxTime, Move searchMoves[]) {
341 // Initialize global search variables
342 Idle = StopOnPonderhit = AbortSearch = Quit = false;
343 AspirationFailLow = false;
345 SearchStartTime = get_system_time();
346 ExactMaxTime = maxTime;
349 InfiniteSearch = infinite;
350 PonderSearch = ponder;
351 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
353 // Look for a book move, only during games, not tests
354 if (UseTimeManagement && !ponder && get_option_value_bool("OwnBook"))
357 if (get_option_value_string("Book File") != OpeningBook.file_name())
358 OpeningBook.open(get_option_value_string("Book File"));
360 bookMove = OpeningBook.get_move(pos);
361 if (bookMove != MOVE_NONE)
363 cout << "bestmove " << bookMove << endl;
368 for (int i = 0; i < THREAD_MAX; i++)
370 Threads[i].nodes = 0ULL;
373 if (button_was_pressed("New Game"))
374 loseOnTime = false; // Reset at the beginning of a new game
376 // Read UCI option values
377 TT.set_size(get_option_value_int("Hash"));
378 if (button_was_pressed("Clear Hash"))
381 bool PonderingEnabled = get_option_value_bool("Ponder");
382 MultiPV = get_option_value_int("MultiPV");
384 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
385 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
387 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
388 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
390 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
391 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
393 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
394 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
396 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
397 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
399 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
400 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
402 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
404 Chess960 = get_option_value_bool("UCI_Chess960");
405 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
406 UseLogFile = get_option_value_bool("Use Search Log");
408 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
410 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
411 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
413 read_weights(pos.side_to_move());
415 // Set the number of active threads
416 int newActiveThreads = get_option_value_int("Threads");
417 if (newActiveThreads != ActiveThreads)
419 ActiveThreads = newActiveThreads;
420 init_eval(ActiveThreads);
421 // HACK: init_eval() destroys the static castleRightsMask[] array in the
422 // Position class. The below line repairs the damage.
423 Position p(pos.to_fen());
427 // Wake up sleeping threads
428 wake_sleeping_threads();
430 for (int i = 1; i < ActiveThreads; i++)
431 assert(thread_is_available(i, 0));
434 int myTime = time[side_to_move];
435 int myIncrement = increment[side_to_move];
436 if (UseTimeManagement)
438 if (!movesToGo) // Sudden death time control
442 MaxSearchTime = myTime / 30 + myIncrement;
443 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
445 else // Blitz game without increment
447 MaxSearchTime = myTime / 30;
448 AbsoluteMaxSearchTime = myTime / 8;
451 else // (x moves) / (y minutes)
455 MaxSearchTime = myTime / 2;
456 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
460 MaxSearchTime = myTime / Min(movesToGo, 20);
461 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
465 if (PonderingEnabled)
467 MaxSearchTime += MaxSearchTime / 4;
468 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
472 // Set best NodesBetweenPolls interval
474 NodesBetweenPolls = Min(MaxNodes, 30000);
475 else if (myTime && myTime < 1000)
476 NodesBetweenPolls = 1000;
477 else if (myTime && myTime < 5000)
478 NodesBetweenPolls = 5000;
480 NodesBetweenPolls = 30000;
482 // Write information to search log file
484 LogFile << "Searching: " << pos.to_fen() << endl
485 << "infinite: " << infinite
486 << " ponder: " << ponder
487 << " time: " << myTime
488 << " increment: " << myIncrement
489 << " moves to go: " << movesToGo << endl;
491 // LSN filtering. Used only for developing purpose. Disabled by default.
495 // Step 2. If after last move we decided to lose on time, do it now!
496 while (SearchStartTime + myTime + 1000 > get_system_time())
500 // We're ready to start thinking. Call the iterative deepening loop function
501 Value v = id_loop(pos, searchMoves);
505 // Step 1. If this is sudden death game and our position is hopeless,
506 // decide to lose on time.
507 if ( !loseOnTime // If we already lost on time, go to step 3.
517 // Step 3. Now after stepping over the time limit, reset flag for next match.
530 /// init_threads() is called during startup. It launches all helper threads,
531 /// and initializes the split point stack and the global locks and condition
534 void init_threads() {
539 #if !defined(_MSC_VER)
540 pthread_t pthread[1];
543 // Init our reduction lookup tables
544 for (i = 1; i < 64; i++) // i == depth
545 for (int j = 1; j < 64; j++) // j == moveNumber
547 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
548 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
549 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
550 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
553 // Init futility margins array
554 FutilityMargins[0] = FutilityMargins[1] = Value(0);
556 for (i = 2; i < 2 * PLY_MAX_PLUS_2; i++)
558 FutilityMargins[i] = Value(112 * bitScanReverse32(i * i / 2)); // FIXME: test using log instead of BSR
561 for (i = 0; i < THREAD_MAX; i++)
562 Threads[i].activeSplitPoints = 0;
564 // Initialize global locks
565 lock_init(&MPLock, NULL);
566 lock_init(&IOLock, NULL);
568 init_split_point_stack();
570 #if !defined(_MSC_VER)
571 pthread_mutex_init(&WaitLock, NULL);
572 pthread_cond_init(&WaitCond, NULL);
574 for (i = 0; i < THREAD_MAX; i++)
575 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
578 // All threads except the main thread should be initialized to idle state
579 for (i = 1; i < THREAD_MAX; i++)
581 Threads[i].stop = false;
582 Threads[i].workIsWaiting = false;
583 Threads[i].idle = true;
584 Threads[i].running = false;
587 // Launch the helper threads
588 for (i = 1; i < THREAD_MAX; i++)
590 #if !defined(_MSC_VER)
591 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
594 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
599 cout << "Failed to create thread number " << i << endl;
600 Application::exit_with_failure();
603 // Wait until the thread has finished launching
604 while (!Threads[i].running);
609 /// stop_threads() is called when the program exits. It makes all the
610 /// helper threads exit cleanly.
612 void stop_threads() {
614 ActiveThreads = THREAD_MAX; // HACK
615 Idle = false; // HACK
616 wake_sleeping_threads();
617 AllThreadsShouldExit = true;
618 for (int i = 1; i < THREAD_MAX; i++)
620 Threads[i].stop = true;
621 while (Threads[i].running);
623 destroy_split_point_stack();
627 /// nodes_searched() returns the total number of nodes searched so far in
628 /// the current search.
630 int64_t nodes_searched() {
632 int64_t result = 0ULL;
633 for (int i = 0; i < ActiveThreads; i++)
634 result += Threads[i].nodes;
639 // SearchStack::init() initializes a search stack. Used at the beginning of a
640 // new search from the root.
641 void SearchStack::init(int ply) {
643 pv[ply] = pv[ply + 1] = MOVE_NONE;
644 currentMove = threatMove = MOVE_NONE;
645 reduction = Depth(0);
650 void SearchStack::initKillers() {
652 mateKiller = MOVE_NONE;
653 for (int i = 0; i < KILLER_MAX; i++)
654 killers[i] = MOVE_NONE;
659 // id_loop() is the main iterative deepening loop. It calls root_search
660 // repeatedly with increasing depth until the allocated thinking time has
661 // been consumed, the user stops the search, or the maximum search depth is
664 Value id_loop(const Position& pos, Move searchMoves[]) {
667 SearchStack ss[PLY_MAX_PLUS_2];
669 // searchMoves are verified, copied, scored and sorted
670 RootMoveList rml(p, searchMoves);
672 // Handle special case of searching on a mate/stale position
673 if (rml.move_count() == 0)
676 wait_for_stop_or_ponderhit();
678 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
681 // Print RootMoveList c'tor startup scoring to the standard output,
682 // so that we print information also for iteration 1.
683 cout << "info depth " << 1 << "\ninfo depth " << 1
684 << " score " << value_to_string(rml.get_move_score(0))
685 << " time " << current_search_time()
686 << " nodes " << nodes_searched()
688 << " pv " << rml.get_move(0) << "\n";
694 ValueByIteration[1] = rml.get_move_score(0);
697 // Is one move significantly better than others after initial scoring ?
698 Move EasyMove = MOVE_NONE;
699 if ( rml.move_count() == 1
700 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
701 EasyMove = rml.get_move(0);
703 // Iterative deepening loop
704 while (Iteration < PLY_MAX)
706 // Initialize iteration
709 BestMoveChangesByIteration[Iteration] = 0;
713 cout << "info depth " << Iteration << endl;
715 // Calculate dynamic search window based on previous iterations
718 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
720 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
721 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
723 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
724 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
726 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
727 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
731 alpha = - VALUE_INFINITE;
732 beta = VALUE_INFINITE;
735 // Search to the current depth
736 Value value = root_search(p, ss, rml, alpha, beta);
738 // Write PV to transposition table, in case the relevant entries have
739 // been overwritten during the search.
740 TT.insert_pv(p, ss[0].pv);
743 break; // Value cannot be trusted. Break out immediately!
745 //Save info about search result
746 ValueByIteration[Iteration] = value;
748 // Drop the easy move if it differs from the new best move
749 if (ss[0].pv[0] != EasyMove)
750 EasyMove = MOVE_NONE;
752 if (UseTimeManagement)
755 bool stopSearch = false;
757 // Stop search early if there is only a single legal move,
758 // we search up to Iteration 6 anyway to get a proper score.
759 if (Iteration >= 6 && rml.move_count() == 1)
762 // Stop search early when the last two iterations returned a mate score
764 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
765 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
768 // Stop search early if one move seems to be much better than the rest
769 int64_t nodes = nodes_searched();
771 && EasyMove == ss[0].pv[0]
772 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
773 && current_search_time() > MaxSearchTime / 16)
774 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
775 && current_search_time() > MaxSearchTime / 32)))
778 // Add some extra time if the best move has changed during the last two iterations
779 if (Iteration > 5 && Iteration <= 50)
780 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
781 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
783 // Stop search if most of MaxSearchTime is consumed at the end of the
784 // iteration. We probably don't have enough time to search the first
785 // move at the next iteration anyway.
786 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
794 StopOnPonderhit = true;
798 if (MaxDepth && Iteration >= MaxDepth)
804 // If we are pondering or in infinite search, we shouldn't print the
805 // best move before we are told to do so.
806 if (!AbortSearch && (PonderSearch || InfiniteSearch))
807 wait_for_stop_or_ponderhit();
809 // Print final search statistics
810 cout << "info nodes " << nodes_searched()
812 << " time " << current_search_time()
813 << " hashfull " << TT.full() << endl;
815 // Print the best move and the ponder move to the standard output
816 if (ss[0].pv[0] == MOVE_NONE)
818 ss[0].pv[0] = rml.get_move(0);
819 ss[0].pv[1] = MOVE_NONE;
821 cout << "bestmove " << ss[0].pv[0];
822 if (ss[0].pv[1] != MOVE_NONE)
823 cout << " ponder " << ss[0].pv[1];
830 dbg_print_mean(LogFile);
832 if (dbg_show_hit_rate)
833 dbg_print_hit_rate(LogFile);
835 LogFile << "\nNodes: " << nodes_searched()
836 << "\nNodes/second: " << nps()
837 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
840 p.do_move(ss[0].pv[0], st);
841 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
843 return rml.get_move_score(0);
847 // root_search() is the function which searches the root node. It is
848 // similar to search_pv except that it uses a different move ordering
849 // scheme and prints some information to the standard output.
851 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
856 Depth depth, ext, newDepth;
859 int researchCount = 0;
860 bool moveIsCheck, captureOrPromotion, dangerous;
861 Value alpha = oldAlpha;
862 bool isCheck = pos.is_check();
864 // Evaluate the position statically
866 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
868 while (1) // Fail low loop
871 // Loop through all the moves in the root move list
872 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
876 // We failed high, invalidate and skip next moves, leave node-counters
877 // and beta-counters as they are and quickly return, we will try to do
878 // a research at the next iteration with a bigger aspiration window.
879 rml.set_move_score(i, -VALUE_INFINITE);
883 RootMoveNumber = i + 1;
885 // Save the current node count before the move is searched
886 nodes = nodes_searched();
888 // Reset beta cut-off counters
891 // Pick the next root move, and print the move and the move number to
892 // the standard output.
893 move = ss[0].currentMove = rml.get_move(i);
895 if (current_search_time() >= 1000)
896 cout << "info currmove " << move
897 << " currmovenumber " << RootMoveNumber << endl;
899 // Decide search depth for this move
900 moveIsCheck = pos.move_is_check(move);
901 captureOrPromotion = pos.move_is_capture_or_promotion(move);
902 depth = (Iteration - 2) * OnePly + InitialDepth;
903 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
904 newDepth = depth + ext;
906 value = - VALUE_INFINITE;
908 while (1) // Fail high loop
911 // Make the move, and search it
912 pos.do_move(move, st, ci, moveIsCheck);
914 if (i < MultiPV || value > alpha)
916 // Aspiration window is disabled in multi-pv case
918 alpha = -VALUE_INFINITE;
920 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
924 // Try to reduce non-pv search depth by one ply if move seems not problematic,
925 // if the move fails high will be re-searched at full depth.
926 bool doFullDepthSearch = true;
928 if ( depth >= 3*OnePly // FIXME was newDepth
930 && !captureOrPromotion
931 && !move_is_castle(move))
933 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
936 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
937 doFullDepthSearch = (value > alpha);
941 if (doFullDepthSearch)
943 ss[0].reduction = Depth(0);
944 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
947 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
953 // Can we exit fail high loop ?
954 if (AbortSearch || value < beta)
957 // We are failing high and going to do a research. It's important to update score
958 // before research in case we run out of time while researching.
959 rml.set_move_score(i, value);
961 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
962 rml.set_move_pv(i, ss[0].pv);
964 // Print search information to the standard output
965 cout << "info depth " << Iteration
966 << " score " << value_to_string(value)
967 << ((value >= beta) ? " lowerbound" :
968 ((value <= alpha)? " upperbound" : ""))
969 << " time " << current_search_time()
970 << " nodes " << nodes_searched()
974 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
975 cout << ss[0].pv[j] << " ";
981 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
982 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
984 LogFile << pretty_pv(pos, current_search_time(), Iteration,
985 nodes_searched(), value, type, ss[0].pv) << endl;
988 // Prepare for a research after a fail high, each time with a wider window
990 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
992 } // End of fail high loop
994 // Finished searching the move. If AbortSearch is true, the search
995 // was aborted because the user interrupted the search or because we
996 // ran out of time. In this case, the return value of the search cannot
997 // be trusted, and we break out of the loop without updating the best
1002 // Remember beta-cutoff and searched nodes counts for this move. The
1003 // info is used to sort the root moves at the next iteration.
1005 BetaCounter.read(pos.side_to_move(), our, their);
1006 rml.set_beta_counters(i, our, their);
1007 rml.set_move_nodes(i, nodes_searched() - nodes);
1009 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1011 if (value <= alpha && i >= MultiPV)
1012 rml.set_move_score(i, -VALUE_INFINITE);
1015 // PV move or new best move!
1018 rml.set_move_score(i, value);
1020 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1021 rml.set_move_pv(i, ss[0].pv);
1025 // We record how often the best move has been changed in each
1026 // iteration. This information is used for time managment: When
1027 // the best move changes frequently, we allocate some more time.
1029 BestMoveChangesByIteration[Iteration]++;
1031 // Print search information to the standard output
1032 cout << "info depth " << Iteration
1033 << " score " << value_to_string(value)
1034 << ((value >= beta) ? " lowerbound" :
1035 ((value <= alpha)? " upperbound" : ""))
1036 << " time " << current_search_time()
1037 << " nodes " << nodes_searched()
1041 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1042 cout << ss[0].pv[j] << " ";
1048 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1049 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1051 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1052 nodes_searched(), value, type, ss[0].pv) << endl;
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 AspirationFailLow = (alpha == oldAlpha);
1083 if (AspirationFailLow && StopOnPonderhit)
1084 StopOnPonderhit = false;
1087 // Can we exit fail low loop ?
1088 if (AbortSearch || alpha > oldAlpha)
1091 // Prepare for a research after a fail low, each time with a wider window
1093 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1102 // search_pv() is the main search function for PV nodes.
1104 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1105 Depth depth, int ply, int threadID) {
1107 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1108 assert(beta > alpha && beta <= VALUE_INFINITE);
1109 assert(ply >= 0 && ply < PLY_MAX);
1110 assert(threadID >= 0 && threadID < ActiveThreads);
1112 Move movesSearched[256];
1116 Depth ext, newDepth;
1117 Value oldAlpha, value;
1118 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1120 Value bestValue = value = -VALUE_INFINITE;
1123 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1125 // Initialize, and make an early exit in case of an aborted search,
1126 // an instant draw, maximum ply reached, etc.
1127 init_node(ss, ply, threadID);
1129 // After init_node() that calls poll()
1130 if (AbortSearch || thread_should_stop(threadID))
1133 if (pos.is_draw() || ply >= PLY_MAX - 1)
1136 // Mate distance pruning
1138 alpha = Max(value_mated_in(ply), alpha);
1139 beta = Min(value_mate_in(ply+1), beta);
1143 // Transposition table lookup. At PV nodes, we don't use the TT for
1144 // pruning, but only for move ordering. This is to avoid problems in
1145 // the following areas:
1147 // * Repetition draw detection
1148 // * Fifty move rule detection
1149 // * Searching for a mate
1150 // * Printing of full PV line
1152 tte = TT.retrieve(pos.get_key());
1153 ttMove = (tte ? tte->move() : MOVE_NONE);
1155 // Go with internal iterative deepening if we don't have a TT move
1156 if ( UseIIDAtPVNodes
1157 && depth >= 5*OnePly
1158 && ttMove == MOVE_NONE)
1160 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1161 ttMove = ss[ply].pv[ply];
1162 tte = TT.retrieve(pos.get_key());
1165 isCheck = pos.is_check();
1168 // Update gain statistics of the previous move that lead
1169 // us in this position.
1171 ss[ply].eval = evaluate(pos, ei, threadID);
1172 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1175 // Initialize a MovePicker object for the current position, and prepare
1176 // to search all moves
1177 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1179 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1181 // Loop through all legal moves until no moves remain or a beta cutoff
1183 while ( alpha < beta
1184 && (move = mp.get_next_move()) != MOVE_NONE
1185 && !thread_should_stop(threadID))
1187 assert(move_is_ok(move));
1189 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1190 moveIsCheck = pos.move_is_check(move, ci);
1191 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1193 // Decide the new search depth
1194 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1196 // Singular extension search. We extend the TT move if its value is much better than
1197 // its siblings. To verify this we do a reduced search on all the other moves but the
1198 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1199 if ( depth >= 6 * OnePly
1201 && move == tte->move()
1203 && is_lower_bound(tte->type())
1204 && tte->depth() >= depth - 3 * OnePly)
1206 Value ttValue = value_from_tt(tte->value(), ply);
1208 if (abs(ttValue) < VALUE_KNOWN_WIN)
1210 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1212 if (excValue < ttValue - SingleReplyMargin)
1217 newDepth = depth - OnePly + ext;
1219 // Update current move
1220 movesSearched[moveCount++] = ss[ply].currentMove = move;
1222 // Make and search the move
1223 pos.do_move(move, st, ci, moveIsCheck);
1225 if (moveCount == 1) // The first move in list is the PV
1226 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1229 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1230 // if the move fails high will be re-searched at full depth.
1231 bool doFullDepthSearch = true;
1233 if ( depth >= 3*OnePly
1235 && !captureOrPromotion
1236 && !move_is_castle(move)
1237 && !move_is_killer(move, ss[ply]))
1239 ss[ply].reduction = pv_reduction(depth, moveCount);
1240 if (ss[ply].reduction)
1242 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1243 doFullDepthSearch = (value > alpha);
1247 if (doFullDepthSearch) // Go with full depth non-pv search
1249 ss[ply].reduction = Depth(0);
1250 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1251 if (value > alpha && value < beta)
1252 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1255 pos.undo_move(move);
1257 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1260 if (value > bestValue)
1267 if (value == value_mate_in(ply + 1))
1268 ss[ply].mateKiller = move;
1273 if ( ActiveThreads > 1
1275 && depth >= MinimumSplitDepth
1277 && idle_thread_exists(threadID)
1279 && !thread_should_stop(threadID)
1280 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1281 depth, &moveCount, &mp, threadID, true))
1285 // All legal moves have been searched. A special case: If there were
1286 // no legal moves, it must be mate or stalemate.
1288 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1290 // If the search is not aborted, update the transposition table,
1291 // history counters, and killer moves.
1292 if (AbortSearch || thread_should_stop(threadID))
1295 if (bestValue <= oldAlpha)
1296 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1298 else if (bestValue >= beta)
1300 BetaCounter.add(pos.side_to_move(), depth, threadID);
1301 move = ss[ply].pv[ply];
1302 if (!pos.move_is_capture_or_promotion(move))
1304 update_history(pos, move, depth, movesSearched, moveCount);
1305 update_killers(move, ss[ply]);
1307 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1310 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1316 // search() is the search function for zero-width nodes.
1318 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1319 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1321 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1322 assert(ply >= 0 && ply < PLY_MAX);
1323 assert(threadID >= 0 && threadID < ActiveThreads);
1325 Move movesSearched[256];
1330 Depth ext, newDepth;
1331 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1332 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1333 bool mateThreat = false;
1335 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1338 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1340 // Initialize, and make an early exit in case of an aborted search,
1341 // an instant draw, maximum ply reached, etc.
1342 init_node(ss, ply, threadID);
1344 // After init_node() that calls poll()
1345 if (AbortSearch || thread_should_stop(threadID))
1348 if (pos.is_draw() || ply >= PLY_MAX - 1)
1351 // Mate distance pruning
1352 if (value_mated_in(ply) >= beta)
1355 if (value_mate_in(ply + 1) < beta)
1358 // We don't want the score of a partial search to overwrite a previous full search
1359 // TT value, so we use a different position key in case of an excluded move exsists.
1360 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1362 // Transposition table lookup
1363 tte = TT.retrieve(posKey);
1364 ttMove = (tte ? tte->move() : MOVE_NONE);
1366 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1368 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1369 return value_from_tt(tte->value(), ply);
1372 isCheck = pos.is_check();
1374 // Calculate depth dependant futility pruning parameters
1375 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1377 // Evaluate the position statically
1380 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1381 staticValue = value_from_tt(tte->value(), ply);
1384 staticValue = evaluate(pos, ei, threadID);
1385 ss[ply].evalInfo = &ei;
1388 ss[ply].eval = staticValue;
1389 futilityValue = staticValue + FutilityMargins[int(depth)]; //FIXME: Remove me, only for split
1390 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1391 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1394 // Static null move pruning. We're betting that the opponent doesn't have
1395 // a move that will reduce the score by more than FutilityMargins[int(depth)]
1396 // if we do a null move.
1399 && depth < RazorDepth
1400 && staticValue - FutilityMargins[int(depth)] >= beta)
1401 return staticValue - FutilityMargins[int(depth)];
1407 && !value_is_mate(beta)
1408 && ok_to_do_nullmove(pos)
1409 && staticValue >= beta - NullMoveMargin)
1411 ss[ply].currentMove = MOVE_NULL;
1413 pos.do_null_move(st);
1415 // Null move dynamic reduction based on depth
1416 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1418 // Null move dynamic reduction based on value
1419 if (staticValue - beta > PawnValueMidgame)
1422 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1424 pos.undo_null_move();
1426 if (nullValue >= beta)
1428 if (depth < 6 * OnePly)
1431 // Do zugzwang verification search
1432 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1436 // The null move failed low, which means that we may be faced with
1437 // some kind of threat. If the previous move was reduced, check if
1438 // the move that refuted the null move was somehow connected to the
1439 // move which was reduced. If a connection is found, return a fail
1440 // low score (which will cause the reduced move to fail high in the
1441 // parent node, which will trigger a re-search with full depth).
1442 if (nullValue == value_mated_in(ply + 2))
1445 ss[ply].threatMove = ss[ply + 1].currentMove;
1446 if ( depth < ThreatDepth
1447 && ss[ply - 1].reduction
1448 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1452 // Null move search not allowed, try razoring
1453 else if ( !value_is_mate(beta)
1455 && depth < RazorDepth
1456 && staticValue < beta - (NullMoveMargin + 16 * depth)
1457 && ss[ply - 1].currentMove != MOVE_NULL
1458 && ttMove == MOVE_NONE
1459 && !pos.has_pawn_on_7th(pos.side_to_move()))
1461 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1462 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1467 // Go with internal iterative deepening if we don't have a TT move
1468 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1469 !isCheck && ss[ply].eval >= beta - IIDMargin)
1471 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1472 ttMove = ss[ply].pv[ply];
1473 tte = TT.retrieve(pos.get_key());
1476 // Initialize a MovePicker object for the current position, and prepare
1477 // to search all moves.
1478 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1481 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1482 while ( bestValue < beta
1483 && (move = mp.get_next_move()) != MOVE_NONE
1484 && !thread_should_stop(threadID))
1486 assert(move_is_ok(move));
1488 if (move == excludedMove)
1491 moveIsCheck = pos.move_is_check(move, ci);
1492 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1493 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1495 // Decide the new search depth
1496 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1498 // Singular extension search. We extend the TT move if its value is much better than
1499 // its siblings. To verify this we do a reduced search on all the other moves but the
1500 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1501 if ( depth >= 8 * OnePly
1503 && move == tte->move()
1504 && !excludedMove // Do not allow recursive single-reply search
1506 && is_lower_bound(tte->type())
1507 && tte->depth() >= depth - 3 * OnePly)
1509 Value ttValue = value_from_tt(tte->value(), ply);
1511 if (abs(ttValue) < VALUE_KNOWN_WIN)
1513 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1515 if (excValue < ttValue - SingleReplyMargin)
1520 newDepth = depth - OnePly + ext;
1522 // Update current move
1523 movesSearched[moveCount++] = ss[ply].currentMove = move;
1528 && !captureOrPromotion
1529 && !move_is_castle(move)
1532 // Move count based pruning
1533 if ( moveCount >= FutilityMoveCountMargin
1534 && ok_to_prune(pos, move, ss[ply].threatMove)
1535 && bestValue > value_mated_in(PLY_MAX))
1538 // Value based pruning
1539 Depth predictedDepth = newDepth;
1541 //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1542 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1543 if (ss[ply].reduction)
1544 predictedDepth -= ss[ply].reduction;
1546 if (predictedDepth < SelectiveDepth)
1548 int preFutilityValueMargin = 0;
1549 if (predictedDepth >= OnePly)
1550 preFutilityValueMargin = FutilityMargins[int(predictedDepth)];
1552 preFutilityValueMargin += H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1554 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1556 if (futilityValueScaled < beta)
1558 if (futilityValueScaled > bestValue)
1559 bestValue = futilityValueScaled;
1565 // Make and search the move
1566 pos.do_move(move, st, ci, moveIsCheck);
1568 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1569 // if the move fails high will be re-searched at full depth.
1570 bool doFullDepthSearch = true;
1572 if ( depth >= 3*OnePly
1574 && !captureOrPromotion
1575 && !move_is_castle(move)
1576 && !move_is_killer(move, ss[ply]))
1578 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1579 if (ss[ply].reduction)
1581 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1582 doFullDepthSearch = (value >= beta);
1586 if (doFullDepthSearch) // Go with full depth non-pv search
1588 ss[ply].reduction = Depth(0);
1589 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1591 pos.undo_move(move);
1593 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1596 if (value > bestValue)
1602 if (value == value_mate_in(ply + 1))
1603 ss[ply].mateKiller = move;
1607 if ( ActiveThreads > 1
1609 && depth >= MinimumSplitDepth
1611 && idle_thread_exists(threadID)
1613 && !thread_should_stop(threadID)
1614 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1615 depth, &moveCount, &mp, threadID, false))
1619 // All legal moves have been searched. A special case: If there were
1620 // no legal moves, it must be mate or stalemate.
1622 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1624 // If the search is not aborted, update the transposition table,
1625 // history counters, and killer moves.
1626 if (AbortSearch || thread_should_stop(threadID))
1629 if (bestValue < beta)
1630 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1633 BetaCounter.add(pos.side_to_move(), depth, threadID);
1634 move = ss[ply].pv[ply];
1635 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1636 if (!pos.move_is_capture_or_promotion(move))
1638 update_history(pos, move, depth, movesSearched, moveCount);
1639 update_killers(move, ss[ply]);
1644 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1650 // qsearch() is the quiescence search function, which is called by the main
1651 // search function when the remaining depth is zero (or, to be more precise,
1652 // less than OnePly).
1654 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1655 Depth depth, int ply, int threadID) {
1657 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1658 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1660 assert(ply >= 0 && ply < PLY_MAX);
1661 assert(threadID >= 0 && threadID < ActiveThreads);
1666 Value staticValue, bestValue, value, futilityBase, futilityValue;
1667 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1668 const TTEntry* tte = NULL;
1670 bool pvNode = (beta - alpha != 1);
1671 Value oldAlpha = alpha;
1673 // Initialize, and make an early exit in case of an aborted search,
1674 // an instant draw, maximum ply reached, etc.
1675 init_node(ss, ply, threadID);
1677 // After init_node() that calls poll()
1678 if (AbortSearch || thread_should_stop(threadID))
1681 if (pos.is_draw() || ply >= PLY_MAX - 1)
1684 // Transposition table lookup. At PV nodes, we don't use the TT for
1685 // pruning, but only for move ordering.
1686 tte = TT.retrieve(pos.get_key());
1687 ttMove = (tte ? tte->move() : MOVE_NONE);
1689 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1691 assert(tte->type() != VALUE_TYPE_EVAL);
1693 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1694 return value_from_tt(tte->value(), ply);
1697 isCheck = pos.is_check();
1699 // Evaluate the position statically
1701 staticValue = -VALUE_INFINITE;
1702 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1703 staticValue = value_from_tt(tte->value(), ply);
1705 staticValue = evaluate(pos, ei, threadID);
1709 ss[ply].eval = staticValue;
1710 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1713 // Initialize "stand pat score", and return it immediately if it is
1715 bestValue = staticValue;
1717 if (bestValue >= beta)
1719 // Store the score to avoid a future costly evaluation() call
1720 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1721 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1726 if (bestValue > alpha)
1729 // If we are near beta then try to get a cutoff pushing checks a bit further
1730 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1732 // Initialize a MovePicker object for the current position, and prepare
1733 // to search the moves. Because the depth is <= 0 here, only captures,
1734 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1735 // and we are near beta) will be generated.
1736 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1738 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1739 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1741 // Loop through the moves until no moves remain or a beta cutoff
1743 while ( alpha < beta
1744 && (move = mp.get_next_move()) != MOVE_NONE)
1746 assert(move_is_ok(move));
1748 moveIsCheck = pos.move_is_check(move, ci);
1750 // Update current move
1752 ss[ply].currentMove = move;
1760 && !move_is_promotion(move)
1761 && !pos.move_is_passed_pawn_push(move))
1763 futilityValue = futilityBase
1764 + pos.endgame_value_of_piece_on(move_to(move))
1765 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1767 if (futilityValue < alpha)
1769 if (futilityValue > bestValue)
1770 bestValue = futilityValue;
1775 // Detect blocking evasions that are candidate to be pruned
1776 evasionPrunable = isCheck
1777 && bestValue != -VALUE_INFINITE
1778 && !pos.move_is_capture(move)
1779 && pos.type_of_piece_on(move_from(move)) != KING
1780 && !pos.can_castle(pos.side_to_move());
1782 // Don't search moves with negative SEE values
1783 if ( (!isCheck || evasionPrunable)
1785 && !move_is_promotion(move)
1786 && pos.see_sign(move) < 0)
1789 // Make and search the move
1790 pos.do_move(move, st, ci, moveIsCheck);
1791 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1792 pos.undo_move(move);
1794 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1797 if (value > bestValue)
1808 // All legal moves have been searched. A special case: If we're in check
1809 // and no legal moves were found, it is checkmate.
1810 if (!moveCount && pos.is_check()) // Mate!
1811 return value_mated_in(ply);
1813 // Update transposition table
1814 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1815 if (bestValue <= oldAlpha)
1817 // If bestValue isn't changed it means it is still the static evaluation
1818 // of the node, so keep this info to avoid a future evaluation() call.
1819 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1820 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1822 else if (bestValue >= beta)
1824 move = ss[ply].pv[ply];
1825 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1827 // Update killers only for good checking moves
1828 if (!pos.move_is_capture_or_promotion(move))
1829 update_killers(move, ss[ply]);
1832 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1834 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1840 // sp_search() is used to search from a split point. This function is called
1841 // by each thread working at the split point. It is similar to the normal
1842 // search() function, but simpler. Because we have already probed the hash
1843 // table, done a null move search, and searched the first move before
1844 // splitting, we don't have to repeat all this work in sp_search(). We
1845 // also don't need to store anything to the hash table here: This is taken
1846 // care of after we return from the split point.
1848 void sp_search(SplitPoint* sp, int threadID) {
1850 assert(threadID >= 0 && threadID < ActiveThreads);
1851 assert(ActiveThreads > 1);
1853 Position pos(*sp->pos);
1855 SearchStack* ss = sp->sstack[threadID];
1856 Value value = -VALUE_INFINITE;
1859 bool isCheck = pos.is_check();
1860 bool useFutilityPruning = sp->depth < SelectiveDepth
1863 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1865 while ( lock_grab_bool(&(sp->lock))
1866 && sp->bestValue < sp->beta
1867 && !thread_should_stop(threadID)
1868 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1870 moveCount = ++sp->moves;
1871 lock_release(&(sp->lock));
1873 assert(move_is_ok(move));
1875 bool moveIsCheck = pos.move_is_check(move, ci);
1876 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1878 ss[sp->ply].currentMove = move;
1880 // Decide the new search depth
1882 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1883 Depth newDepth = sp->depth - OnePly + ext;
1886 if ( useFutilityPruning
1888 && !captureOrPromotion)
1890 // Move count based pruning
1891 if ( moveCount >= FutilityMoveCountMargin
1892 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1893 && sp->bestValue > value_mated_in(PLY_MAX))
1896 // Value based pruning
1897 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1899 if (futilityValueScaled < sp->beta)
1901 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1903 lock_grab(&(sp->lock));
1904 if (futilityValueScaled > sp->bestValue)
1905 sp->bestValue = futilityValueScaled;
1906 lock_release(&(sp->lock));
1912 // Make and search the move.
1914 pos.do_move(move, st, ci, moveIsCheck);
1916 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1917 // if the move fails high will be re-searched at full depth.
1918 bool doFullDepthSearch = true;
1921 && !captureOrPromotion
1922 && !move_is_castle(move)
1923 && !move_is_killer(move, ss[sp->ply]))
1925 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1926 if (ss[sp->ply].reduction)
1928 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1929 doFullDepthSearch = (value >= sp->beta);
1933 if (doFullDepthSearch) // Go with full depth non-pv search
1935 ss[sp->ply].reduction = Depth(0);
1936 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1938 pos.undo_move(move);
1940 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1942 if (thread_should_stop(threadID))
1944 lock_grab(&(sp->lock));
1949 if (value > sp->bestValue) // Less then 2% of cases
1951 lock_grab(&(sp->lock));
1952 if (value > sp->bestValue && !thread_should_stop(threadID))
1954 sp->bestValue = value;
1955 if (sp->bestValue >= sp->beta)
1957 sp_update_pv(sp->parentSstack, ss, sp->ply);
1958 for (int i = 0; i < ActiveThreads; i++)
1959 if (i != threadID && (i == sp->master || sp->slaves[i]))
1960 Threads[i].stop = true;
1962 sp->finished = true;
1965 lock_release(&(sp->lock));
1969 /* Here we have the lock still grabbed */
1971 // If this is the master thread and we have been asked to stop because of
1972 // a beta cutoff higher up in the tree, stop all slave threads.
1973 if (sp->master == threadID && thread_should_stop(threadID))
1974 for (int i = 0; i < ActiveThreads; i++)
1976 Threads[i].stop = true;
1979 sp->slaves[threadID] = 0;
1981 lock_release(&(sp->lock));
1985 // sp_search_pv() is used to search from a PV split point. This function
1986 // is called by each thread working at the split point. It is similar to
1987 // the normal search_pv() function, but simpler. Because we have already
1988 // probed the hash table and searched the first move before splitting, we
1989 // don't have to repeat all this work in sp_search_pv(). We also don't
1990 // need to store anything to the hash table here: This is taken care of
1991 // after we return from the split point.
1993 void sp_search_pv(SplitPoint* sp, int threadID) {
1995 assert(threadID >= 0 && threadID < ActiveThreads);
1996 assert(ActiveThreads > 1);
1998 Position pos(*sp->pos);
2000 SearchStack* ss = sp->sstack[threadID];
2001 Value value = -VALUE_INFINITE;
2005 while ( lock_grab_bool(&(sp->lock))
2006 && sp->alpha < sp->beta
2007 && !thread_should_stop(threadID)
2008 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2010 moveCount = ++sp->moves;
2011 lock_release(&(sp->lock));
2013 assert(move_is_ok(move));
2015 bool moveIsCheck = pos.move_is_check(move, ci);
2016 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2018 ss[sp->ply].currentMove = move;
2020 // Decide the new search depth
2022 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2023 Depth newDepth = sp->depth - OnePly + ext;
2025 // Make and search the move.
2027 pos.do_move(move, st, ci, moveIsCheck);
2029 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2030 // if the move fails high will be re-searched at full depth.
2031 bool doFullDepthSearch = true;
2034 && !captureOrPromotion
2035 && !move_is_castle(move)
2036 && !move_is_killer(move, ss[sp->ply]))
2038 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
2039 if (ss[sp->ply].reduction)
2041 Value localAlpha = sp->alpha;
2042 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2043 doFullDepthSearch = (value > localAlpha);
2047 if (doFullDepthSearch) // Go with full depth non-pv search
2049 Value localAlpha = sp->alpha;
2050 ss[sp->ply].reduction = Depth(0);
2051 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2053 if (value > localAlpha && value < sp->beta)
2055 // If another thread has failed high then sp->alpha has been increased
2056 // to be higher or equal then beta, if so, avoid to start a PV search.
2057 localAlpha = sp->alpha;
2058 if (localAlpha < sp->beta)
2059 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2061 assert(thread_should_stop(threadID));
2064 pos.undo_move(move);
2066 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2068 if (thread_should_stop(threadID))
2070 lock_grab(&(sp->lock));
2075 if (value > sp->bestValue) // Less then 2% of cases
2077 lock_grab(&(sp->lock));
2078 if (value > sp->bestValue && !thread_should_stop(threadID))
2080 sp->bestValue = value;
2081 if (value > sp->alpha)
2083 // Ask threads to stop before to modify sp->alpha
2084 if (value >= sp->beta)
2086 for (int i = 0; i < ActiveThreads; i++)
2087 if (i != threadID && (i == sp->master || sp->slaves[i]))
2088 Threads[i].stop = true;
2090 sp->finished = true;
2095 sp_update_pv(sp->parentSstack, ss, sp->ply);
2096 if (value == value_mate_in(sp->ply + 1))
2097 ss[sp->ply].mateKiller = move;
2100 lock_release(&(sp->lock));
2104 /* Here we have the lock still grabbed */
2106 // If this is the master thread and we have been asked to stop because of
2107 // a beta cutoff higher up in the tree, stop all slave threads.
2108 if (sp->master == threadID && thread_should_stop(threadID))
2109 for (int i = 0; i < ActiveThreads; i++)
2111 Threads[i].stop = true;
2114 sp->slaves[threadID] = 0;
2116 lock_release(&(sp->lock));
2119 /// The BetaCounterType class
2121 BetaCounterType::BetaCounterType() { clear(); }
2123 void BetaCounterType::clear() {
2125 for (int i = 0; i < THREAD_MAX; i++)
2126 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2129 void BetaCounterType::add(Color us, Depth d, int threadID) {
2131 // Weighted count based on depth
2132 Threads[threadID].betaCutOffs[us] += unsigned(d);
2135 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2138 for (int i = 0; i < THREAD_MAX; i++)
2140 our += Threads[i].betaCutOffs[us];
2141 their += Threads[i].betaCutOffs[opposite_color(us)];
2146 /// The RootMoveList class
2148 // RootMoveList c'tor
2150 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2152 SearchStack ss[PLY_MAX_PLUS_2];
2153 MoveStack mlist[MaxRootMoves];
2155 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2157 // Generate all legal moves
2158 MoveStack* last = generate_moves(pos, mlist);
2160 // Add each move to the moves[] array
2161 for (MoveStack* cur = mlist; cur != last; cur++)
2163 bool includeMove = includeAllMoves;
2165 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2166 includeMove = (searchMoves[k] == cur->move);
2171 // Find a quick score for the move
2173 pos.do_move(cur->move, st);
2174 moves[count].move = cur->move;
2175 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2176 moves[count].pv[0] = cur->move;
2177 moves[count].pv[1] = MOVE_NONE;
2178 pos.undo_move(cur->move);
2185 // RootMoveList simple methods definitions
2187 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2189 moves[moveNum].nodes = nodes;
2190 moves[moveNum].cumulativeNodes += nodes;
2193 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2195 moves[moveNum].ourBeta = our;
2196 moves[moveNum].theirBeta = their;
2199 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2203 for (j = 0; pv[j] != MOVE_NONE; j++)
2204 moves[moveNum].pv[j] = pv[j];
2206 moves[moveNum].pv[j] = MOVE_NONE;
2210 // RootMoveList::sort() sorts the root move list at the beginning of a new
2213 void RootMoveList::sort() {
2215 sort_multipv(count - 1); // Sort all items
2219 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2220 // list by their scores and depths. It is used to order the different PVs
2221 // correctly in MultiPV mode.
2223 void RootMoveList::sort_multipv(int n) {
2227 for (i = 1; i <= n; i++)
2229 RootMove rm = moves[i];
2230 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2231 moves[j] = moves[j - 1];
2238 // init_node() is called at the beginning of all the search functions
2239 // (search(), search_pv(), qsearch(), and so on) and initializes the
2240 // search stack object corresponding to the current node. Once every
2241 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2242 // for user input and checks whether it is time to stop the search.
2244 void init_node(SearchStack ss[], int ply, int threadID) {
2246 assert(ply >= 0 && ply < PLY_MAX);
2247 assert(threadID >= 0 && threadID < ActiveThreads);
2249 Threads[threadID].nodes++;
2254 if (NodesSincePoll >= NodesBetweenPolls)
2261 ss[ply + 2].initKillers();
2263 if (Threads[threadID].printCurrentLine)
2264 print_current_line(ss, ply, threadID);
2268 // update_pv() is called whenever a search returns a value > alpha.
2269 // It updates the PV in the SearchStack object corresponding to the
2272 void update_pv(SearchStack ss[], int ply) {
2274 assert(ply >= 0 && ply < PLY_MAX);
2278 ss[ply].pv[ply] = ss[ply].currentMove;
2280 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2281 ss[ply].pv[p] = ss[ply + 1].pv[p];
2283 ss[ply].pv[p] = MOVE_NONE;
2287 // sp_update_pv() is a variant of update_pv for use at split points. The
2288 // difference between the two functions is that sp_update_pv also updates
2289 // the PV at the parent node.
2291 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2293 assert(ply >= 0 && ply < PLY_MAX);
2297 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2299 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2300 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2302 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2306 // connected_moves() tests whether two moves are 'connected' in the sense
2307 // that the first move somehow made the second move possible (for instance
2308 // if the moving piece is the same in both moves). The first move is assumed
2309 // to be the move that was made to reach the current position, while the
2310 // second move is assumed to be a move from the current position.
2312 bool connected_moves(const Position& pos, Move m1, Move m2) {
2314 Square f1, t1, f2, t2;
2317 assert(move_is_ok(m1));
2318 assert(move_is_ok(m2));
2320 if (m2 == MOVE_NONE)
2323 // Case 1: The moving piece is the same in both moves
2329 // Case 2: The destination square for m2 was vacated by m1
2335 // Case 3: Moving through the vacated square
2336 if ( piece_is_slider(pos.piece_on(f2))
2337 && bit_is_set(squares_between(f2, t2), f1))
2340 // Case 4: The destination square for m2 is defended by the moving piece in m1
2341 p = pos.piece_on(t1);
2342 if (bit_is_set(pos.attacks_from(p, t1), t2))
2345 // Case 5: Discovered check, checking piece is the piece moved in m1
2346 if ( piece_is_slider(p)
2347 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2348 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2350 // discovered_check_candidates() works also if the Position's side to
2351 // move is the opposite of the checking piece.
2352 Color them = opposite_color(pos.side_to_move());
2353 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2355 if (bit_is_set(dcCandidates, f2))
2362 // value_is_mate() checks if the given value is a mate one
2363 // eventually compensated for the ply.
2365 bool value_is_mate(Value value) {
2367 assert(abs(value) <= VALUE_INFINITE);
2369 return value <= value_mated_in(PLY_MAX)
2370 || value >= value_mate_in(PLY_MAX);
2374 // move_is_killer() checks if the given move is among the
2375 // killer moves of that ply.
2377 bool move_is_killer(Move m, const SearchStack& ss) {
2379 const Move* k = ss.killers;
2380 for (int i = 0; i < KILLER_MAX; i++, k++)
2388 // extension() decides whether a move should be searched with normal depth,
2389 // or with extended depth. Certain classes of moves (checking moves, in
2390 // particular) are searched with bigger depth than ordinary moves and in
2391 // any case are marked as 'dangerous'. Note that also if a move is not
2392 // extended, as example because the corresponding UCI option is set to zero,
2393 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2395 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2396 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2398 assert(m != MOVE_NONE);
2400 Depth result = Depth(0);
2401 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2406 result += CheckExtension[pvNode];
2409 result += SingleEvasionExtension[pvNode];
2412 result += MateThreatExtension[pvNode];
2415 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2417 Color c = pos.side_to_move();
2418 if (relative_rank(c, move_to(m)) == RANK_7)
2420 result += PawnPushTo7thExtension[pvNode];
2423 if (pos.pawn_is_passed(c, move_to(m)))
2425 result += PassedPawnExtension[pvNode];
2430 if ( captureOrPromotion
2431 && pos.type_of_piece_on(move_to(m)) != PAWN
2432 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2433 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2434 && !move_is_promotion(m)
2437 result += PawnEndgameExtension[pvNode];
2442 && captureOrPromotion
2443 && pos.type_of_piece_on(move_to(m)) != PAWN
2444 && pos.see_sign(m) >= 0)
2450 return Min(result, OnePly);
2454 // ok_to_do_nullmove() looks at the current position and decides whether
2455 // doing a 'null move' should be allowed. In order to avoid zugzwang
2456 // problems, null moves are not allowed when the side to move has very
2457 // little material left. Currently, the test is a bit too simple: Null
2458 // moves are avoided only when the side to move has only pawns left.
2459 // It's probably a good idea to avoid null moves in at least some more
2460 // complicated endgames, e.g. KQ vs KR. FIXME
2462 bool ok_to_do_nullmove(const Position& pos) {
2464 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2468 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2469 // non-tactical moves late in the move list close to the leaves are
2470 // candidates for pruning.
2472 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2474 assert(move_is_ok(m));
2475 assert(threat == MOVE_NONE || move_is_ok(threat));
2476 assert(!pos.move_is_check(m));
2477 assert(!pos.move_is_capture_or_promotion(m));
2478 assert(!pos.move_is_passed_pawn_push(m));
2480 Square mfrom, mto, tfrom, tto;
2482 // Prune if there isn't any threat move
2483 if (threat == MOVE_NONE)
2486 mfrom = move_from(m);
2488 tfrom = move_from(threat);
2489 tto = move_to(threat);
2491 // Case 1: Don't prune moves which move the threatened piece
2495 // Case 2: If the threatened piece has value less than or equal to the
2496 // value of the threatening piece, don't prune move which defend it.
2497 if ( pos.move_is_capture(threat)
2498 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2499 || pos.type_of_piece_on(tfrom) == KING)
2500 && pos.move_attacks_square(m, tto))
2503 // Case 3: If the moving piece in the threatened move is a slider, don't
2504 // prune safe moves which block its ray.
2505 if ( piece_is_slider(pos.piece_on(tfrom))
2506 && bit_is_set(squares_between(tfrom, tto), mto)
2507 && pos.see_sign(m) >= 0)
2514 // ok_to_use_TT() returns true if a transposition table score
2515 // can be used at a given point in search.
2517 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2519 Value v = value_from_tt(tte->value(), ply);
2521 return ( tte->depth() >= depth
2522 || v >= Max(value_mate_in(PLY_MAX), beta)
2523 || v < Min(value_mated_in(PLY_MAX), beta))
2525 && ( (is_lower_bound(tte->type()) && v >= beta)
2526 || (is_upper_bound(tte->type()) && v < beta));
2530 // refine_eval() returns the transposition table score if
2531 // possible otherwise falls back on static position evaluation.
2533 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2538 Value v = value_from_tt(tte->value(), ply);
2540 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2541 || (is_upper_bound(tte->type()) && v < defaultEval))
2548 // update_history() registers a good move that produced a beta-cutoff
2549 // in history and marks as failures all the other moves of that ply.
2551 void update_history(const Position& pos, Move move, Depth depth,
2552 Move movesSearched[], int moveCount) {
2556 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2558 for (int i = 0; i < moveCount - 1; i++)
2560 m = movesSearched[i];
2564 if (!pos.move_is_capture_or_promotion(m))
2565 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2570 // update_killers() add a good move that produced a beta-cutoff
2571 // among the killer moves of that ply.
2573 void update_killers(Move m, SearchStack& ss) {
2575 if (m == ss.killers[0])
2578 for (int i = KILLER_MAX - 1; i > 0; i--)
2579 ss.killers[i] = ss.killers[i - 1];
2585 // update_gains() updates the gains table of a non-capture move given
2586 // the static position evaluation before and after the move.
2588 void update_gains(const Position& pos, Move m, Value before, Value after) {
2591 && before != VALUE_NONE
2592 && after != VALUE_NONE
2593 && pos.captured_piece() == NO_PIECE_TYPE
2594 && !move_is_castle(m)
2595 && !move_is_promotion(m))
2596 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2600 // current_search_time() returns the number of milliseconds which have passed
2601 // since the beginning of the current search.
2603 int current_search_time() {
2605 return get_system_time() - SearchStartTime;
2609 // nps() computes the current nodes/second count.
2613 int t = current_search_time();
2614 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2618 // poll() performs two different functions: It polls for user input, and it
2619 // looks at the time consumed so far and decides if it's time to abort the
2624 static int lastInfoTime;
2625 int t = current_search_time();
2630 // We are line oriented, don't read single chars
2631 std::string command;
2633 if (!std::getline(std::cin, command))
2636 if (command == "quit")
2639 PonderSearch = false;
2643 else if (command == "stop")
2646 PonderSearch = false;
2648 else if (command == "ponderhit")
2652 // Print search information
2656 else if (lastInfoTime > t)
2657 // HACK: Must be a new search where we searched less than
2658 // NodesBetweenPolls nodes during the first second of search.
2661 else if (t - lastInfoTime >= 1000)
2669 if (dbg_show_hit_rate)
2670 dbg_print_hit_rate();
2672 cout << "info nodes " << nodes_searched() << " nps " << nps()
2673 << " time " << t << " hashfull " << TT.full() << endl;
2675 lock_release(&IOLock);
2677 if (ShowCurrentLine)
2678 Threads[0].printCurrentLine = true;
2681 // Should we stop the search?
2685 bool stillAtFirstMove = RootMoveNumber == 1
2686 && !AspirationFailLow
2687 && t > MaxSearchTime + ExtraSearchTime;
2689 bool noMoreTime = t > AbsoluteMaxSearchTime
2690 || stillAtFirstMove;
2692 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2693 || (ExactMaxTime && t >= ExactMaxTime)
2694 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2699 // ponderhit() is called when the program is pondering (i.e. thinking while
2700 // it's the opponent's turn to move) in order to let the engine know that
2701 // it correctly predicted the opponent's move.
2705 int t = current_search_time();
2706 PonderSearch = false;
2708 bool stillAtFirstMove = RootMoveNumber == 1
2709 && !AspirationFailLow
2710 && t > MaxSearchTime + ExtraSearchTime;
2712 bool noMoreTime = t > AbsoluteMaxSearchTime
2713 || stillAtFirstMove;
2715 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2720 // print_current_line() prints the current line of search for a given
2721 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2723 void print_current_line(SearchStack ss[], int ply, int threadID) {
2725 assert(ply >= 0 && ply < PLY_MAX);
2726 assert(threadID >= 0 && threadID < ActiveThreads);
2728 if (!Threads[threadID].idle)
2731 cout << "info currline " << (threadID + 1);
2732 for (int p = 0; p < ply; p++)
2733 cout << " " << ss[p].currentMove;
2736 lock_release(&IOLock);
2738 Threads[threadID].printCurrentLine = false;
2739 if (threadID + 1 < ActiveThreads)
2740 Threads[threadID + 1].printCurrentLine = true;
2744 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2746 void init_ss_array(SearchStack ss[]) {
2748 for (int i = 0; i < 3; i++)
2751 ss[i].initKillers();
2756 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2757 // while the program is pondering. The point is to work around a wrinkle in
2758 // the UCI protocol: When pondering, the engine is not allowed to give a
2759 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2760 // We simply wait here until one of these commands is sent, and return,
2761 // after which the bestmove and pondermove will be printed (in id_loop()).
2763 void wait_for_stop_or_ponderhit() {
2765 std::string command;
2769 if (!std::getline(std::cin, command))
2772 if (command == "quit")
2777 else if (command == "ponderhit" || command == "stop")
2783 // idle_loop() is where the threads are parked when they have no work to do.
2784 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2785 // object for which the current thread is the master.
2787 void idle_loop(int threadID, SplitPoint* waitSp) {
2789 assert(threadID >= 0 && threadID < THREAD_MAX);
2791 Threads[threadID].running = true;
2795 if (AllThreadsShouldExit && threadID != 0)
2798 // If we are not thinking, wait for a condition to be signaled
2799 // instead of wasting CPU time polling for work.
2800 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2803 #if !defined(_MSC_VER)
2804 pthread_mutex_lock(&WaitLock);
2805 if (Idle || threadID >= ActiveThreads)
2806 pthread_cond_wait(&WaitCond, &WaitLock);
2808 pthread_mutex_unlock(&WaitLock);
2810 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2814 // If this thread has been assigned work, launch a search
2815 if (Threads[threadID].workIsWaiting)
2817 assert(!Threads[threadID].idle);
2819 Threads[threadID].workIsWaiting = false;
2820 if (Threads[threadID].splitPoint->pvNode)
2821 sp_search_pv(Threads[threadID].splitPoint, threadID);
2823 sp_search(Threads[threadID].splitPoint, threadID);
2825 Threads[threadID].idle = true;
2828 // If this thread is the master of a split point and all threads have
2829 // finished their work at this split point, return from the idle loop.
2830 if (waitSp != NULL && waitSp->cpus == 0)
2834 Threads[threadID].running = false;
2838 // init_split_point_stack() is called during program initialization, and
2839 // initializes all split point objects.
2841 void init_split_point_stack() {
2843 for (int i = 0; i < THREAD_MAX; i++)
2844 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2846 SplitPointStack[i][j].parent = NULL;
2847 lock_init(&(SplitPointStack[i][j].lock), NULL);
2852 // destroy_split_point_stack() is called when the program exits, and
2853 // destroys all locks in the precomputed split point objects.
2855 void destroy_split_point_stack() {
2857 for (int i = 0; i < THREAD_MAX; i++)
2858 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2859 lock_destroy(&(SplitPointStack[i][j].lock));
2863 // thread_should_stop() checks whether the thread with a given threadID has
2864 // been asked to stop, directly or indirectly. This can happen if a beta
2865 // cutoff has occurred in the thread's currently active split point, or in
2866 // some ancestor of the current split point.
2868 bool thread_should_stop(int threadID) {
2870 assert(threadID >= 0 && threadID < ActiveThreads);
2874 if (Threads[threadID].stop)
2876 if (ActiveThreads <= 2)
2878 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2881 Threads[threadID].stop = true;
2888 // thread_is_available() checks whether the thread with threadID "slave" is
2889 // available to help the thread with threadID "master" at a split point. An
2890 // obvious requirement is that "slave" must be idle. With more than two
2891 // threads, this is not by itself sufficient: If "slave" is the master of
2892 // some active split point, it is only available as a slave to the other
2893 // threads which are busy searching the split point at the top of "slave"'s
2894 // split point stack (the "helpful master concept" in YBWC terminology).
2896 bool thread_is_available(int slave, int master) {
2898 assert(slave >= 0 && slave < ActiveThreads);
2899 assert(master >= 0 && master < ActiveThreads);
2900 assert(ActiveThreads > 1);
2902 if (!Threads[slave].idle || slave == master)
2905 // Make a local copy to be sure doesn't change under our feet
2906 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
2908 if (localActiveSplitPoints == 0)
2909 // No active split points means that the thread is available as
2910 // a slave for any other thread.
2913 if (ActiveThreads == 2)
2916 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2917 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
2918 // could have been set to 0 by another thread leading to an out of bound access.
2919 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2926 // idle_thread_exists() tries to find an idle thread which is available as
2927 // a slave for the thread with threadID "master".
2929 bool idle_thread_exists(int master) {
2931 assert(master >= 0 && master < ActiveThreads);
2932 assert(ActiveThreads > 1);
2934 for (int i = 0; i < ActiveThreads; i++)
2935 if (thread_is_available(i, master))
2942 // split() does the actual work of distributing the work at a node between
2943 // several threads at PV nodes. If it does not succeed in splitting the
2944 // node (because no idle threads are available, or because we have no unused
2945 // split point objects), the function immediately returns false. If
2946 // splitting is possible, a SplitPoint object is initialized with all the
2947 // data that must be copied to the helper threads (the current position and
2948 // search stack, alpha, beta, the search depth, etc.), and we tell our
2949 // helper threads that they have been assigned work. This will cause them
2950 // to instantly leave their idle loops and call sp_search_pv(). When all
2951 // threads have returned from sp_search_pv (or, equivalently, when
2952 // splitPoint->cpus becomes 0), split() returns true.
2954 bool split(const Position& p, SearchStack* sstck, int ply,
2955 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2956 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2959 assert(sstck != NULL);
2960 assert(ply >= 0 && ply < PLY_MAX);
2961 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2962 assert(!pvNode || *alpha < *beta);
2963 assert(*beta <= VALUE_INFINITE);
2964 assert(depth > Depth(0));
2965 assert(master >= 0 && master < ActiveThreads);
2966 assert(ActiveThreads > 1);
2968 SplitPoint* splitPoint;
2972 // If no other thread is available to help us, or if we have too many
2973 // active split points, don't split.
2974 if ( !idle_thread_exists(master)
2975 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2977 lock_release(&MPLock);
2981 // Pick the next available split point object from the split point stack
2982 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2983 Threads[master].activeSplitPoints++;
2985 // Initialize the split point object
2986 splitPoint->parent = Threads[master].splitPoint;
2987 splitPoint->finished = false;
2988 splitPoint->ply = ply;
2989 splitPoint->depth = depth;
2990 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2991 splitPoint->beta = *beta;
2992 splitPoint->pvNode = pvNode;
2993 splitPoint->bestValue = *bestValue;
2994 splitPoint->futilityValue = futilityValue;
2995 splitPoint->master = master;
2996 splitPoint->mp = mp;
2997 splitPoint->moves = *moves;
2998 splitPoint->cpus = 1;
2999 splitPoint->pos = &p;
3000 splitPoint->parentSstack = sstck;
3001 for (int i = 0; i < ActiveThreads; i++)
3002 splitPoint->slaves[i] = 0;
3004 Threads[master].idle = false;
3005 Threads[master].stop = false;
3006 Threads[master].splitPoint = splitPoint;
3008 // Allocate available threads setting idle flag to false
3009 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3010 if (thread_is_available(i, master))
3012 Threads[i].idle = false;
3013 Threads[i].stop = false;
3014 Threads[i].splitPoint = splitPoint;
3015 splitPoint->slaves[i] = 1;
3019 assert(splitPoint->cpus > 1);
3021 // We can release the lock because master and slave threads are already booked
3022 lock_release(&MPLock);
3024 // Tell the threads that they have work to do. This will make them leave
3025 // their idle loop. But before copy search stack tail for each thread.
3026 for (int i = 0; i < ActiveThreads; i++)
3027 if (i == master || splitPoint->slaves[i])
3029 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3030 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3033 // Everything is set up. The master thread enters the idle loop, from
3034 // which it will instantly launch a search, because its workIsWaiting
3035 // slot is 'true'. We send the split point as a second parameter to the
3036 // idle loop, which means that the main thread will return from the idle
3037 // loop when all threads have finished their work at this split point
3038 // (i.e. when splitPoint->cpus == 0).
3039 idle_loop(master, splitPoint);
3041 // We have returned from the idle loop, which means that all threads are
3042 // finished. Update alpha, beta and bestValue, and return.
3046 *alpha = splitPoint->alpha;
3048 *beta = splitPoint->beta;
3049 *bestValue = splitPoint->bestValue;
3050 Threads[master].stop = false;
3051 Threads[master].idle = false;
3052 Threads[master].activeSplitPoints--;
3053 Threads[master].splitPoint = splitPoint->parent;
3055 lock_release(&MPLock);
3060 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3061 // to start a new search from the root.
3063 void wake_sleeping_threads() {
3065 if (ActiveThreads > 1)
3067 for (int i = 1; i < ActiveThreads; i++)
3069 Threads[i].idle = true;
3070 Threads[i].workIsWaiting = false;
3073 #if !defined(_MSC_VER)
3074 pthread_mutex_lock(&WaitLock);
3075 pthread_cond_broadcast(&WaitCond);
3076 pthread_mutex_unlock(&WaitLock);
3078 for (int i = 1; i < THREAD_MAX; i++)
3079 SetEvent(SitIdleEvent[i]);
3085 // init_thread() is the function which is called when a new thread is
3086 // launched. It simply calls the idle_loop() function with the supplied
3087 // threadID. There are two versions of this function; one for POSIX
3088 // threads and one for Windows threads.
3090 #if !defined(_MSC_VER)
3092 void* init_thread(void *threadID) {
3094 idle_loop(*(int*)threadID, NULL);
3100 DWORD WINAPI init_thread(LPVOID threadID) {
3102 idle_loop(*(int*)threadID, NULL);