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 FailHigh, 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 FailHigh = 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;
901 // Save the current node count before the move is searched
902 nodes = nodes_searched();
904 // Reset beta cut-off counters
907 // Pick the next root move, and print the move and the move number to
908 // the standard output.
909 move = ss[0].currentMove = rml.get_move(i);
911 if (current_search_time() >= 1000)
912 cout << "info currmove " << move
913 << " currmovenumber " << RootMoveNumber << endl;
915 // Decide search depth for this move
916 moveIsCheck = pos.move_is_check(move);
917 captureOrPromotion = pos.move_is_capture_or_promotion(move);
918 depth = (Iteration - 2) * OnePly + InitialDepth;
919 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
920 newDepth = depth + ext;
922 value = - VALUE_INFINITE;
924 while (1) // Fail high loop
927 // Make the move, and search it
928 pos.do_move(move, st, ci, moveIsCheck);
930 if (i < MultiPV || value > alpha)
932 // Aspiration window is disabled in multi-pv case
934 alpha = -VALUE_INFINITE;
936 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
938 // If the value has dropped a lot compared to the last iteration,
939 // set the boolean variable Problem to true. This variable is used
940 // for time managment: When Problem is true, we try to complete the
941 // current iteration before playing a move.
942 Problem = ( Iteration >= 2
943 && value <= ValueByIteration[Iteration - 1] - ProblemMargin);
945 if (Problem && StopOnPonderhit)
946 StopOnPonderhit = false;
950 // Try to reduce non-pv search depth by one ply if move seems not problematic,
951 // if the move fails high will be re-searched at full depth.
952 bool doFullDepthSearch = true;
954 if ( depth >= 3*OnePly // FIXME was newDepth
956 && !captureOrPromotion
957 && !move_is_castle(move))
959 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
962 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
963 doFullDepthSearch = (value > alpha);
967 if (doFullDepthSearch)
969 ss[0].reduction = Depth(0);
970 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
974 // Fail high! Set the boolean variable FailHigh to true, and
975 // re-search the move using a PV search. The variable FailHigh
976 // is used for time managment: We try to avoid aborting the
977 // search prematurely during a fail high research.
979 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
986 // Can we exit fail high loop ?
987 if (AbortSearch || value < beta)
990 // We are failing high and going to do a research. It's important to update score
991 // before research in case we run out of time while researching.
992 rml.set_move_score(i, value);
994 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
995 rml.set_move_pv(i, ss[0].pv);
997 // Print search information to the standard output
998 cout << "info depth " << Iteration
999 << " score " << value_to_string(value)
1000 << ((value >= beta) ? " lowerbound" :
1001 ((value <= alpha)? " upperbound" : ""))
1002 << " time " << current_search_time()
1003 << " nodes " << nodes_searched()
1007 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1008 cout << ss[0].pv[j] << " ";
1014 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1015 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1017 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1018 nodes_searched(), value, type, ss[0].pv) << endl;
1021 // Prepare for a research after a fail high, each time with a wider window
1023 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
1025 } // End of fail high loop
1027 // Finished searching the move. If AbortSearch is true, the search
1028 // was aborted because the user interrupted the search or because we
1029 // ran out of time. In this case, the return value of the search cannot
1030 // be trusted, and we break out of the loop without updating the best
1035 // Remember beta-cutoff and searched nodes counts for this move. The
1036 // info is used to sort the root moves at the next iteration.
1038 BetaCounter.read(pos.side_to_move(), our, their);
1039 rml.set_beta_counters(i, our, their);
1040 rml.set_move_nodes(i, nodes_searched() - nodes);
1042 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1044 if (value <= alpha && i >= MultiPV)
1045 rml.set_move_score(i, -VALUE_INFINITE);
1048 // PV move or new best move!
1051 rml.set_move_score(i, value);
1053 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1054 rml.set_move_pv(i, ss[0].pv);
1058 // We record how often the best move has been changed in each
1059 // iteration. This information is used for time managment: When
1060 // the best move changes frequently, we allocate some more time.
1062 BestMoveChangesByIteration[Iteration]++;
1064 // Print search information to the standard output
1065 cout << "info depth " << Iteration
1066 << " score " << value_to_string(value)
1067 << ((value >= beta) ? " lowerbound" :
1068 ((value <= alpha)? " upperbound" : ""))
1069 << " time " << current_search_time()
1070 << " nodes " << nodes_searched()
1074 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1075 cout << ss[0].pv[j] << " ";
1081 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1082 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1084 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1085 nodes_searched(), value, type, ss[0].pv) << endl;
1090 // Reset the global variable Problem to false if the value isn't too
1091 // far below the final value from the last iteration.
1092 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
1097 rml.sort_multipv(i);
1098 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1100 cout << "info multipv " << j + 1
1101 << " score " << value_to_string(rml.get_move_score(j))
1102 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1103 << " time " << current_search_time()
1104 << " nodes " << nodes_searched()
1108 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1109 cout << rml.get_move_pv(j, k) << " ";
1113 alpha = rml.get_move_score(Min(i, MultiPV-1));
1115 } // PV move or new best move
1117 assert(alpha >= oldAlpha);
1119 FailLow = (alpha == oldAlpha);
1122 // Can we exit fail low loop ?
1123 if (AbortSearch || alpha > oldAlpha)
1126 // Prepare for a research after a fail low, each time with a wider window
1128 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1137 // search_pv() is the main search function for PV nodes.
1139 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1140 Depth depth, int ply, int threadID) {
1142 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1143 assert(beta > alpha && beta <= VALUE_INFINITE);
1144 assert(ply >= 0 && ply < PLY_MAX);
1145 assert(threadID >= 0 && threadID < ActiveThreads);
1147 Move movesSearched[256];
1151 Depth ext, newDepth;
1152 Value oldAlpha, value;
1153 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1155 Value bestValue = value = -VALUE_INFINITE;
1158 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1160 // Initialize, and make an early exit in case of an aborted search,
1161 // an instant draw, maximum ply reached, etc.
1162 init_node(ss, ply, threadID);
1164 // After init_node() that calls poll()
1165 if (AbortSearch || thread_should_stop(threadID))
1168 if (pos.is_draw() || ply >= PLY_MAX - 1)
1171 // Mate distance pruning
1173 alpha = Max(value_mated_in(ply), alpha);
1174 beta = Min(value_mate_in(ply+1), beta);
1178 // Transposition table lookup. At PV nodes, we don't use the TT for
1179 // pruning, but only for move ordering. This is to avoid problems in
1180 // the following areas:
1182 // * Repetition draw detection
1183 // * Fifty move rule detection
1184 // * Searching for a mate
1185 // * Printing of full PV line
1187 tte = TT.retrieve(pos.get_key());
1188 ttMove = (tte ? tte->move() : MOVE_NONE);
1190 // Go with internal iterative deepening if we don't have a TT move
1191 if ( UseIIDAtPVNodes
1192 && depth >= 5*OnePly
1193 && ttMove == MOVE_NONE)
1195 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1196 ttMove = ss[ply].pv[ply];
1197 tte = TT.retrieve(pos.get_key());
1200 isCheck = pos.is_check();
1203 // Update gain statistics of the previous move that lead
1204 // us in this position.
1206 ss[ply].eval = evaluate(pos, ei, threadID);
1207 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1210 // Initialize a MovePicker object for the current position, and prepare
1211 // to search all moves
1212 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1214 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1216 // Loop through all legal moves until no moves remain or a beta cutoff
1218 while ( alpha < beta
1219 && (move = mp.get_next_move()) != MOVE_NONE
1220 && !thread_should_stop(threadID))
1222 assert(move_is_ok(move));
1224 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1225 moveIsCheck = pos.move_is_check(move, ci);
1226 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1228 // Decide the new search depth
1229 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1231 // Singular extension search. We extend the TT move if its value is much better than
1232 // its siblings. To verify this we do a reduced search on all the other moves but the
1233 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1234 if ( depth >= 6 * OnePly
1236 && move == tte->move()
1238 && is_lower_bound(tte->type())
1239 && tte->depth() >= depth - 3 * OnePly)
1241 Value ttValue = value_from_tt(tte->value(), ply);
1243 if (abs(ttValue) < VALUE_KNOWN_WIN)
1245 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1247 if (excValue < ttValue - SingleReplyMargin)
1252 newDepth = depth - OnePly + ext;
1254 // Update current move
1255 movesSearched[moveCount++] = ss[ply].currentMove = move;
1257 // Make and search the move
1258 pos.do_move(move, st, ci, moveIsCheck);
1260 if (moveCount == 1) // The first move in list is the PV
1261 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1264 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1265 // if the move fails high will be re-searched at full depth.
1266 bool doFullDepthSearch = true;
1268 if ( depth >= 3*OnePly
1270 && !captureOrPromotion
1271 && !move_is_castle(move)
1272 && !move_is_killer(move, ss[ply]))
1274 ss[ply].reduction = pv_reduction(depth, moveCount);
1275 if (ss[ply].reduction)
1277 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1278 doFullDepthSearch = (value > alpha);
1282 if (doFullDepthSearch) // Go with full depth non-pv search
1284 ss[ply].reduction = Depth(0);
1285 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1286 if (value > alpha && value < beta)
1288 // When the search fails high at ply 1 while searching the first
1289 // move at the root, set the flag failHighPly1. This is used for
1290 // time managment: We don't want to stop the search early in
1291 // such cases, because resolving the fail high at ply 1 could
1292 // result in a big drop in score at the root.
1293 if (ply == 1 && RootMoveNumber == 1)
1294 Threads[threadID].failHighPly1 = true;
1296 // A fail high occurred. Re-search at full window (pv search)
1297 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1298 Threads[threadID].failHighPly1 = false;
1302 pos.undo_move(move);
1304 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1307 if (value > bestValue)
1314 if (value == value_mate_in(ply + 1))
1315 ss[ply].mateKiller = move;
1317 // If we are at ply 1, and we are searching the first root move at
1318 // ply 0, set the 'Problem' variable if the score has dropped a lot
1319 // (from the computer's point of view) since the previous iteration.
1322 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1327 if ( ActiveThreads > 1
1329 && depth >= MinimumSplitDepth
1331 && idle_thread_exists(threadID)
1333 && !thread_should_stop(threadID)
1334 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1335 depth, &moveCount, &mp, threadID, true))
1339 // All legal moves have been searched. A special case: If there were
1340 // no legal moves, it must be mate or stalemate.
1342 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1344 // If the search is not aborted, update the transposition table,
1345 // history counters, and killer moves.
1346 if (AbortSearch || thread_should_stop(threadID))
1349 if (bestValue <= oldAlpha)
1350 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1352 else if (bestValue >= beta)
1354 BetaCounter.add(pos.side_to_move(), depth, threadID);
1355 move = ss[ply].pv[ply];
1356 if (!pos.move_is_capture_or_promotion(move))
1358 update_history(pos, move, depth, movesSearched, moveCount);
1359 update_killers(move, ss[ply]);
1361 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1364 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1370 // search() is the search function for zero-width nodes.
1372 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1373 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1375 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1376 assert(ply >= 0 && ply < PLY_MAX);
1377 assert(threadID >= 0 && threadID < ActiveThreads);
1379 Move movesSearched[256];
1384 Depth ext, newDepth;
1385 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1386 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1387 bool mateThreat = false;
1389 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1392 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1394 // Initialize, and make an early exit in case of an aborted search,
1395 // an instant draw, maximum ply reached, etc.
1396 init_node(ss, ply, threadID);
1398 // After init_node() that calls poll()
1399 if (AbortSearch || thread_should_stop(threadID))
1402 if (pos.is_draw() || ply >= PLY_MAX - 1)
1405 // Mate distance pruning
1406 if (value_mated_in(ply) >= beta)
1409 if (value_mate_in(ply + 1) < beta)
1412 // We don't want the score of a partial search to overwrite a previous full search
1413 // TT value, so we use a different position key in case of an excluded move exsists.
1414 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1416 // Transposition table lookup
1417 tte = TT.retrieve(posKey);
1418 ttMove = (tte ? tte->move() : MOVE_NONE);
1420 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1422 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1423 return value_from_tt(tte->value(), ply);
1426 isCheck = pos.is_check();
1428 // Calculate depth dependant futility pruning parameters
1429 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1431 // Evaluate the position statically
1434 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1435 staticValue = value_from_tt(tte->value(), ply);
1438 staticValue = evaluate(pos, ei, threadID);
1439 ss[ply].evalInfo = &ei;
1442 ss[ply].eval = staticValue;
1443 futilityValue = staticValue + FutilityMargins[int(depth)]; //FIXME: Remove me, only for split
1444 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1445 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1448 // Static null move pruning. We're betting that the opponent doesn't have
1449 // a move that will reduce the score by more than FutilityMargins[int(depth)]
1450 // if we do a null move.
1453 && depth < RazorDepth
1454 && staticValue - FutilityMargins[int(depth)] >= beta)
1455 return staticValue - FutilityMargins[int(depth)];
1461 && !value_is_mate(beta)
1462 && ok_to_do_nullmove(pos)
1463 && staticValue >= beta - NullMoveMargin)
1465 ss[ply].currentMove = MOVE_NULL;
1467 pos.do_null_move(st);
1469 // Null move dynamic reduction based on depth
1470 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1472 // Null move dynamic reduction based on value
1473 if (staticValue - beta > PawnValueMidgame)
1476 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1478 pos.undo_null_move();
1480 if (nullValue >= beta)
1482 if (depth < 6 * OnePly)
1485 // Do zugzwang verification search
1486 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1490 // The null move failed low, which means that we may be faced with
1491 // some kind of threat. If the previous move was reduced, check if
1492 // the move that refuted the null move was somehow connected to the
1493 // move which was reduced. If a connection is found, return a fail
1494 // low score (which will cause the reduced move to fail high in the
1495 // parent node, which will trigger a re-search with full depth).
1496 if (nullValue == value_mated_in(ply + 2))
1499 ss[ply].threatMove = ss[ply + 1].currentMove;
1500 if ( depth < ThreatDepth
1501 && ss[ply - 1].reduction
1502 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1506 // Null move search not allowed, try razoring
1507 else if ( !value_is_mate(beta)
1509 && depth < RazorDepth
1510 && staticValue < beta - (NullMoveMargin + 16 * depth)
1511 && ss[ply - 1].currentMove != MOVE_NULL
1512 && ttMove == MOVE_NONE
1513 && !pos.has_pawn_on_7th(pos.side_to_move()))
1515 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1516 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1521 // Go with internal iterative deepening if we don't have a TT move
1522 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1523 !isCheck && ss[ply].eval >= beta - IIDMargin)
1525 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1526 ttMove = ss[ply].pv[ply];
1527 tte = TT.retrieve(pos.get_key());
1530 // Initialize a MovePicker object for the current position, and prepare
1531 // to search all moves.
1532 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1535 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1536 while ( bestValue < beta
1537 && (move = mp.get_next_move()) != MOVE_NONE
1538 && !thread_should_stop(threadID))
1540 assert(move_is_ok(move));
1542 if (move == excludedMove)
1545 moveIsCheck = pos.move_is_check(move, ci);
1546 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1547 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1549 // Decide the new search depth
1550 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1552 // Singular extension search. We extend the TT move if its value is much better than
1553 // its siblings. To verify this we do a reduced search on all the other moves but the
1554 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1555 if ( depth >= 8 * OnePly
1557 && move == tte->move()
1558 && !excludedMove // Do not allow recursive single-reply search
1560 && is_lower_bound(tte->type())
1561 && tte->depth() >= depth - 3 * OnePly)
1563 Value ttValue = value_from_tt(tte->value(), ply);
1565 if (abs(ttValue) < VALUE_KNOWN_WIN)
1567 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1569 if (excValue < ttValue - SingleReplyMargin)
1574 newDepth = depth - OnePly + ext;
1576 // Update current move
1577 movesSearched[moveCount++] = ss[ply].currentMove = move;
1582 && !captureOrPromotion
1583 && !move_is_castle(move)
1586 // Move count based pruning
1587 if ( moveCount >= FutilityMoveCountMargin
1588 && ok_to_prune(pos, move, ss[ply].threatMove)
1589 && bestValue > value_mated_in(PLY_MAX))
1592 // Value based pruning
1593 Depth predictedDepth = newDepth;
1595 //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1596 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1597 if (ss[ply].reduction)
1598 predictedDepth -= ss[ply].reduction;
1600 if (predictedDepth < SelectiveDepth)
1602 int preFutilityValueMargin = 0;
1603 if (predictedDepth >= OnePly)
1604 preFutilityValueMargin = FutilityMargins[int(predictedDepth)];
1606 preFutilityValueMargin += H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1608 futilityValueScaled = ss[ply].eval + preFutilityValueMargin - moveCount * IncrementalFutilityMargin;
1610 if (futilityValueScaled < beta)
1612 if (futilityValueScaled > bestValue)
1613 bestValue = futilityValueScaled;
1619 // Make and search the move
1620 pos.do_move(move, st, ci, moveIsCheck);
1622 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1623 // if the move fails high will be re-searched at full depth.
1624 bool doFullDepthSearch = true;
1626 if ( depth >= 3*OnePly
1628 && !captureOrPromotion
1629 && !move_is_castle(move)
1630 && !move_is_killer(move, ss[ply]))
1632 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1633 if (ss[ply].reduction)
1635 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1636 doFullDepthSearch = (value >= beta);
1640 if (doFullDepthSearch) // Go with full depth non-pv search
1642 ss[ply].reduction = Depth(0);
1643 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1645 pos.undo_move(move);
1647 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1650 if (value > bestValue)
1656 if (value == value_mate_in(ply + 1))
1657 ss[ply].mateKiller = move;
1661 if ( ActiveThreads > 1
1663 && depth >= MinimumSplitDepth
1665 && idle_thread_exists(threadID)
1667 && !thread_should_stop(threadID)
1668 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1669 depth, &moveCount, &mp, threadID, false))
1673 // All legal moves have been searched. A special case: If there were
1674 // no legal moves, it must be mate or stalemate.
1676 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1678 // If the search is not aborted, update the transposition table,
1679 // history counters, and killer moves.
1680 if (AbortSearch || thread_should_stop(threadID))
1683 if (bestValue < beta)
1684 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1687 BetaCounter.add(pos.side_to_move(), depth, threadID);
1688 move = ss[ply].pv[ply];
1689 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1690 if (!pos.move_is_capture_or_promotion(move))
1692 update_history(pos, move, depth, movesSearched, moveCount);
1693 update_killers(move, ss[ply]);
1698 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1704 // qsearch() is the quiescence search function, which is called by the main
1705 // search function when the remaining depth is zero (or, to be more precise,
1706 // less than OnePly).
1708 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1709 Depth depth, int ply, int threadID) {
1711 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1712 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1714 assert(ply >= 0 && ply < PLY_MAX);
1715 assert(threadID >= 0 && threadID < ActiveThreads);
1720 Value staticValue, bestValue, value, futilityBase, futilityValue;
1721 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1722 const TTEntry* tte = NULL;
1724 bool pvNode = (beta - alpha != 1);
1725 Value oldAlpha = alpha;
1727 // Initialize, and make an early exit in case of an aborted search,
1728 // an instant draw, maximum ply reached, etc.
1729 init_node(ss, ply, threadID);
1731 // After init_node() that calls poll()
1732 if (AbortSearch || thread_should_stop(threadID))
1735 if (pos.is_draw() || ply >= PLY_MAX - 1)
1738 // Transposition table lookup. At PV nodes, we don't use the TT for
1739 // pruning, but only for move ordering.
1740 tte = TT.retrieve(pos.get_key());
1741 ttMove = (tte ? tte->move() : MOVE_NONE);
1743 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1745 assert(tte->type() != VALUE_TYPE_EVAL);
1747 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1748 return value_from_tt(tte->value(), ply);
1751 isCheck = pos.is_check();
1753 // Evaluate the position statically
1755 staticValue = -VALUE_INFINITE;
1756 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1757 staticValue = value_from_tt(tte->value(), ply);
1759 staticValue = evaluate(pos, ei, threadID);
1763 ss[ply].eval = staticValue;
1764 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1767 // Initialize "stand pat score", and return it immediately if it is
1769 bestValue = staticValue;
1771 if (bestValue >= beta)
1773 // Store the score to avoid a future costly evaluation() call
1774 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1775 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1780 if (bestValue > alpha)
1783 // If we are near beta then try to get a cutoff pushing checks a bit further
1784 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1786 // Initialize a MovePicker object for the current position, and prepare
1787 // to search the moves. Because the depth is <= 0 here, only captures,
1788 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1789 // and we are near beta) will be generated.
1790 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1792 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1793 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1795 // Loop through the moves until no moves remain or a beta cutoff
1797 while ( alpha < beta
1798 && (move = mp.get_next_move()) != MOVE_NONE)
1800 assert(move_is_ok(move));
1802 moveIsCheck = pos.move_is_check(move, ci);
1804 // Update current move
1806 ss[ply].currentMove = move;
1814 && !move_is_promotion(move)
1815 && !pos.move_is_passed_pawn_push(move))
1817 futilityValue = futilityBase
1818 + pos.endgame_value_of_piece_on(move_to(move))
1819 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1821 if (futilityValue < alpha)
1823 if (futilityValue > bestValue)
1824 bestValue = futilityValue;
1829 // Detect blocking evasions that are candidate to be pruned
1830 evasionPrunable = isCheck
1831 && bestValue != -VALUE_INFINITE
1832 && !pos.move_is_capture(move)
1833 && pos.type_of_piece_on(move_from(move)) != KING
1834 && !pos.can_castle(pos.side_to_move());
1836 // Don't search moves with negative SEE values
1837 if ( (!isCheck || evasionPrunable)
1839 && !move_is_promotion(move)
1840 && pos.see_sign(move) < 0)
1843 // Make and search the move
1844 pos.do_move(move, st, ci, moveIsCheck);
1845 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1846 pos.undo_move(move);
1848 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1851 if (value > bestValue)
1862 // All legal moves have been searched. A special case: If we're in check
1863 // and no legal moves were found, it is checkmate.
1864 if (!moveCount && pos.is_check()) // Mate!
1865 return value_mated_in(ply);
1867 // Update transposition table
1868 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1869 if (bestValue <= oldAlpha)
1871 // If bestValue isn't changed it means it is still the static evaluation
1872 // of the node, so keep this info to avoid a future evaluation() call.
1873 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1874 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1876 else if (bestValue >= beta)
1878 move = ss[ply].pv[ply];
1879 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1881 // Update killers only for good checking moves
1882 if (!pos.move_is_capture_or_promotion(move))
1883 update_killers(move, ss[ply]);
1886 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1888 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1894 // sp_search() is used to search from a split point. This function is called
1895 // by each thread working at the split point. It is similar to the normal
1896 // search() function, but simpler. Because we have already probed the hash
1897 // table, done a null move search, and searched the first move before
1898 // splitting, we don't have to repeat all this work in sp_search(). We
1899 // also don't need to store anything to the hash table here: This is taken
1900 // care of after we return from the split point.
1902 void sp_search(SplitPoint* sp, int threadID) {
1904 assert(threadID >= 0 && threadID < ActiveThreads);
1905 assert(ActiveThreads > 1);
1907 Position pos(*sp->pos);
1909 SearchStack* ss = sp->sstack[threadID];
1910 Value value = -VALUE_INFINITE;
1913 bool isCheck = pos.is_check();
1914 bool useFutilityPruning = sp->depth < SelectiveDepth
1917 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1919 while ( lock_grab_bool(&(sp->lock))
1920 && sp->bestValue < sp->beta
1921 && !thread_should_stop(threadID)
1922 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1924 moveCount = ++sp->moves;
1925 lock_release(&(sp->lock));
1927 assert(move_is_ok(move));
1929 bool moveIsCheck = pos.move_is_check(move, ci);
1930 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1932 ss[sp->ply].currentMove = move;
1934 // Decide the new search depth
1936 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1937 Depth newDepth = sp->depth - OnePly + ext;
1940 if ( useFutilityPruning
1942 && !captureOrPromotion)
1944 // Move count based pruning
1945 if ( moveCount >= FutilityMoveCountMargin
1946 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1947 && sp->bestValue > value_mated_in(PLY_MAX))
1950 // Value based pruning
1951 Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1953 if (futilityValueScaled < sp->beta)
1955 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1957 lock_grab(&(sp->lock));
1958 if (futilityValueScaled > sp->bestValue)
1959 sp->bestValue = futilityValueScaled;
1960 lock_release(&(sp->lock));
1966 // Make and search the move.
1968 pos.do_move(move, st, ci, moveIsCheck);
1970 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1971 // if the move fails high will be re-searched at full depth.
1972 bool doFullDepthSearch = true;
1975 && !captureOrPromotion
1976 && !move_is_castle(move)
1977 && !move_is_killer(move, ss[sp->ply]))
1979 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1980 if (ss[sp->ply].reduction)
1982 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1983 doFullDepthSearch = (value >= sp->beta);
1987 if (doFullDepthSearch) // Go with full depth non-pv search
1989 ss[sp->ply].reduction = Depth(0);
1990 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1992 pos.undo_move(move);
1994 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1996 if (thread_should_stop(threadID))
1998 lock_grab(&(sp->lock));
2003 if (value > sp->bestValue) // Less then 2% of cases
2005 lock_grab(&(sp->lock));
2006 if (value > sp->bestValue && !thread_should_stop(threadID))
2008 sp->bestValue = value;
2009 if (sp->bestValue >= sp->beta)
2011 sp_update_pv(sp->parentSstack, ss, sp->ply);
2012 for (int i = 0; i < ActiveThreads; i++)
2013 if (i != threadID && (i == sp->master || sp->slaves[i]))
2014 Threads[i].stop = true;
2016 sp->finished = true;
2019 lock_release(&(sp->lock));
2023 /* Here we have the lock still grabbed */
2025 // If this is the master thread and we have been asked to stop because of
2026 // a beta cutoff higher up in the tree, stop all slave threads.
2027 if (sp->master == threadID && thread_should_stop(threadID))
2028 for (int i = 0; i < ActiveThreads; i++)
2030 Threads[i].stop = true;
2033 sp->slaves[threadID] = 0;
2035 lock_release(&(sp->lock));
2039 // sp_search_pv() is used to search from a PV split point. This function
2040 // is called by each thread working at the split point. It is similar to
2041 // the normal search_pv() function, but simpler. Because we have already
2042 // probed the hash table and searched the first move before splitting, we
2043 // don't have to repeat all this work in sp_search_pv(). We also don't
2044 // need to store anything to the hash table here: This is taken care of
2045 // after we return from the split point.
2047 void sp_search_pv(SplitPoint* sp, int threadID) {
2049 assert(threadID >= 0 && threadID < ActiveThreads);
2050 assert(ActiveThreads > 1);
2052 Position pos(*sp->pos);
2054 SearchStack* ss = sp->sstack[threadID];
2055 Value value = -VALUE_INFINITE;
2059 while ( lock_grab_bool(&(sp->lock))
2060 && sp->alpha < sp->beta
2061 && !thread_should_stop(threadID)
2062 && (move = sp->mp->get_next_move()) != MOVE_NONE)
2064 moveCount = ++sp->moves;
2065 lock_release(&(sp->lock));
2067 assert(move_is_ok(move));
2069 bool moveIsCheck = pos.move_is_check(move, ci);
2070 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2072 ss[sp->ply].currentMove = move;
2074 // Decide the new search depth
2076 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2077 Depth newDepth = sp->depth - OnePly + ext;
2079 // Make and search the move.
2081 pos.do_move(move, st, ci, moveIsCheck);
2083 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2084 // if the move fails high will be re-searched at full depth.
2085 bool doFullDepthSearch = true;
2088 && !captureOrPromotion
2089 && !move_is_castle(move)
2090 && !move_is_killer(move, ss[sp->ply]))
2092 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
2093 if (ss[sp->ply].reduction)
2095 Value localAlpha = sp->alpha;
2096 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2097 doFullDepthSearch = (value > localAlpha);
2101 if (doFullDepthSearch) // Go with full depth non-pv search
2103 Value localAlpha = sp->alpha;
2104 ss[sp->ply].reduction = Depth(0);
2105 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2107 if (value > localAlpha && value < sp->beta)
2109 // When the search fails high at ply 1 while searching the first
2110 // move at the root, set the flag failHighPly1. This is used for
2111 // time managment: We don't want to stop the search early in
2112 // such cases, because resolving the fail high at ply 1 could
2113 // result in a big drop in score at the root.
2114 if (sp->ply == 1 && RootMoveNumber == 1)
2115 Threads[threadID].failHighPly1 = true;
2117 // If another thread has failed high then sp->alpha has been increased
2118 // to be higher or equal then beta, if so, avoid to start a PV search.
2119 localAlpha = sp->alpha;
2120 if (localAlpha < sp->beta)
2121 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2123 assert(thread_should_stop(threadID));
2125 Threads[threadID].failHighPly1 = false;
2128 pos.undo_move(move);
2130 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2132 if (thread_should_stop(threadID))
2134 lock_grab(&(sp->lock));
2139 if (value > sp->bestValue) // Less then 2% of cases
2141 lock_grab(&(sp->lock));
2142 if (value > sp->bestValue && !thread_should_stop(threadID))
2144 sp->bestValue = value;
2145 if (value > sp->alpha)
2147 // Ask threads to stop before to modify sp->alpha
2148 if (value >= sp->beta)
2150 for (int i = 0; i < ActiveThreads; i++)
2151 if (i != threadID && (i == sp->master || sp->slaves[i]))
2152 Threads[i].stop = true;
2154 sp->finished = true;
2159 sp_update_pv(sp->parentSstack, ss, sp->ply);
2160 if (value == value_mate_in(sp->ply + 1))
2161 ss[sp->ply].mateKiller = move;
2163 // If we are at ply 1, and we are searching the first root move at
2164 // ply 0, set the 'Problem' variable if the score has dropped a lot
2165 // (from the computer's point of view) since the previous iteration.
2168 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
2171 lock_release(&(sp->lock));
2175 /* Here we have the lock still grabbed */
2177 // If this is the master thread and we have been asked to stop because of
2178 // a beta cutoff higher up in the tree, stop all slave threads.
2179 if (sp->master == threadID && thread_should_stop(threadID))
2180 for (int i = 0; i < ActiveThreads; i++)
2182 Threads[i].stop = true;
2185 sp->slaves[threadID] = 0;
2187 lock_release(&(sp->lock));
2190 /// The BetaCounterType class
2192 BetaCounterType::BetaCounterType() { clear(); }
2194 void BetaCounterType::clear() {
2196 for (int i = 0; i < THREAD_MAX; i++)
2197 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2200 void BetaCounterType::add(Color us, Depth d, int threadID) {
2202 // Weighted count based on depth
2203 Threads[threadID].betaCutOffs[us] += unsigned(d);
2206 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2209 for (int i = 0; i < THREAD_MAX; i++)
2211 our += Threads[i].betaCutOffs[us];
2212 their += Threads[i].betaCutOffs[opposite_color(us)];
2217 /// The RootMoveList class
2219 // RootMoveList c'tor
2221 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2223 SearchStack ss[PLY_MAX_PLUS_2];
2224 MoveStack mlist[MaxRootMoves];
2226 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2228 // Generate all legal moves
2229 MoveStack* last = generate_moves(pos, mlist);
2231 // Add each move to the moves[] array
2232 for (MoveStack* cur = mlist; cur != last; cur++)
2234 bool includeMove = includeAllMoves;
2236 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2237 includeMove = (searchMoves[k] == cur->move);
2242 // Find a quick score for the move
2244 pos.do_move(cur->move, st);
2245 moves[count].move = cur->move;
2246 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2247 moves[count].pv[0] = cur->move;
2248 moves[count].pv[1] = MOVE_NONE;
2249 pos.undo_move(cur->move);
2256 // RootMoveList simple methods definitions
2258 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2260 moves[moveNum].nodes = nodes;
2261 moves[moveNum].cumulativeNodes += nodes;
2264 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2266 moves[moveNum].ourBeta = our;
2267 moves[moveNum].theirBeta = their;
2270 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2274 for (j = 0; pv[j] != MOVE_NONE; j++)
2275 moves[moveNum].pv[j] = pv[j];
2277 moves[moveNum].pv[j] = MOVE_NONE;
2281 // RootMoveList::sort() sorts the root move list at the beginning of a new
2284 void RootMoveList::sort() {
2286 sort_multipv(count - 1); // Sort all items
2290 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2291 // list by their scores and depths. It is used to order the different PVs
2292 // correctly in MultiPV mode.
2294 void RootMoveList::sort_multipv(int n) {
2298 for (i = 1; i <= n; i++)
2300 RootMove rm = moves[i];
2301 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2302 moves[j] = moves[j - 1];
2309 // init_node() is called at the beginning of all the search functions
2310 // (search(), search_pv(), qsearch(), and so on) and initializes the
2311 // search stack object corresponding to the current node. Once every
2312 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2313 // for user input and checks whether it is time to stop the search.
2315 void init_node(SearchStack ss[], int ply, int threadID) {
2317 assert(ply >= 0 && ply < PLY_MAX);
2318 assert(threadID >= 0 && threadID < ActiveThreads);
2320 Threads[threadID].nodes++;
2325 if (NodesSincePoll >= NodesBetweenPolls)
2332 ss[ply + 2].initKillers();
2334 if (Threads[threadID].printCurrentLine)
2335 print_current_line(ss, ply, threadID);
2339 // update_pv() is called whenever a search returns a value > alpha.
2340 // It updates the PV in the SearchStack object corresponding to the
2343 void update_pv(SearchStack ss[], int ply) {
2345 assert(ply >= 0 && ply < PLY_MAX);
2349 ss[ply].pv[ply] = ss[ply].currentMove;
2351 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2352 ss[ply].pv[p] = ss[ply + 1].pv[p];
2354 ss[ply].pv[p] = MOVE_NONE;
2358 // sp_update_pv() is a variant of update_pv for use at split points. The
2359 // difference between the two functions is that sp_update_pv also updates
2360 // the PV at the parent node.
2362 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2364 assert(ply >= 0 && ply < PLY_MAX);
2368 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2370 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2371 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2373 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2377 // connected_moves() tests whether two moves are 'connected' in the sense
2378 // that the first move somehow made the second move possible (for instance
2379 // if the moving piece is the same in both moves). The first move is assumed
2380 // to be the move that was made to reach the current position, while the
2381 // second move is assumed to be a move from the current position.
2383 bool connected_moves(const Position& pos, Move m1, Move m2) {
2385 Square f1, t1, f2, t2;
2388 assert(move_is_ok(m1));
2389 assert(move_is_ok(m2));
2391 if (m2 == MOVE_NONE)
2394 // Case 1: The moving piece is the same in both moves
2400 // Case 2: The destination square for m2 was vacated by m1
2406 // Case 3: Moving through the vacated square
2407 if ( piece_is_slider(pos.piece_on(f2))
2408 && bit_is_set(squares_between(f2, t2), f1))
2411 // Case 4: The destination square for m2 is defended by the moving piece in m1
2412 p = pos.piece_on(t1);
2413 if (bit_is_set(pos.attacks_from(p, t1), t2))
2416 // Case 5: Discovered check, checking piece is the piece moved in m1
2417 if ( piece_is_slider(p)
2418 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2419 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2421 // discovered_check_candidates() works also if the Position's side to
2422 // move is the opposite of the checking piece.
2423 Color them = opposite_color(pos.side_to_move());
2424 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2426 if (bit_is_set(dcCandidates, f2))
2433 // value_is_mate() checks if the given value is a mate one
2434 // eventually compensated for the ply.
2436 bool value_is_mate(Value value) {
2438 assert(abs(value) <= VALUE_INFINITE);
2440 return value <= value_mated_in(PLY_MAX)
2441 || value >= value_mate_in(PLY_MAX);
2445 // move_is_killer() checks if the given move is among the
2446 // killer moves of that ply.
2448 bool move_is_killer(Move m, const SearchStack& ss) {
2450 const Move* k = ss.killers;
2451 for (int i = 0; i < KILLER_MAX; i++, k++)
2459 // extension() decides whether a move should be searched with normal depth,
2460 // or with extended depth. Certain classes of moves (checking moves, in
2461 // particular) are searched with bigger depth than ordinary moves and in
2462 // any case are marked as 'dangerous'. Note that also if a move is not
2463 // extended, as example because the corresponding UCI option is set to zero,
2464 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2466 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2467 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2469 assert(m != MOVE_NONE);
2471 Depth result = Depth(0);
2472 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2477 result += CheckExtension[pvNode];
2480 result += SingleEvasionExtension[pvNode];
2483 result += MateThreatExtension[pvNode];
2486 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2488 Color c = pos.side_to_move();
2489 if (relative_rank(c, move_to(m)) == RANK_7)
2491 result += PawnPushTo7thExtension[pvNode];
2494 if (pos.pawn_is_passed(c, move_to(m)))
2496 result += PassedPawnExtension[pvNode];
2501 if ( captureOrPromotion
2502 && pos.type_of_piece_on(move_to(m)) != PAWN
2503 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2504 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2505 && !move_is_promotion(m)
2508 result += PawnEndgameExtension[pvNode];
2513 && captureOrPromotion
2514 && pos.type_of_piece_on(move_to(m)) != PAWN
2515 && pos.see_sign(m) >= 0)
2521 return Min(result, OnePly);
2525 // ok_to_do_nullmove() looks at the current position and decides whether
2526 // doing a 'null move' should be allowed. In order to avoid zugzwang
2527 // problems, null moves are not allowed when the side to move has very
2528 // little material left. Currently, the test is a bit too simple: Null
2529 // moves are avoided only when the side to move has only pawns left.
2530 // It's probably a good idea to avoid null moves in at least some more
2531 // complicated endgames, e.g. KQ vs KR. FIXME
2533 bool ok_to_do_nullmove(const Position& pos) {
2535 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2539 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2540 // non-tactical moves late in the move list close to the leaves are
2541 // candidates for pruning.
2543 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2545 assert(move_is_ok(m));
2546 assert(threat == MOVE_NONE || move_is_ok(threat));
2547 assert(!pos.move_is_check(m));
2548 assert(!pos.move_is_capture_or_promotion(m));
2549 assert(!pos.move_is_passed_pawn_push(m));
2551 Square mfrom, mto, tfrom, tto;
2553 // Prune if there isn't any threat move
2554 if (threat == MOVE_NONE)
2557 mfrom = move_from(m);
2559 tfrom = move_from(threat);
2560 tto = move_to(threat);
2562 // Case 1: Don't prune moves which move the threatened piece
2566 // Case 2: If the threatened piece has value less than or equal to the
2567 // value of the threatening piece, don't prune move which defend it.
2568 if ( pos.move_is_capture(threat)
2569 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2570 || pos.type_of_piece_on(tfrom) == KING)
2571 && pos.move_attacks_square(m, tto))
2574 // Case 3: If the moving piece in the threatened move is a slider, don't
2575 // prune safe moves which block its ray.
2576 if ( piece_is_slider(pos.piece_on(tfrom))
2577 && bit_is_set(squares_between(tfrom, tto), mto)
2578 && pos.see_sign(m) >= 0)
2585 // ok_to_use_TT() returns true if a transposition table score
2586 // can be used at a given point in search.
2588 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2590 Value v = value_from_tt(tte->value(), ply);
2592 return ( tte->depth() >= depth
2593 || v >= Max(value_mate_in(PLY_MAX), beta)
2594 || v < Min(value_mated_in(PLY_MAX), beta))
2596 && ( (is_lower_bound(tte->type()) && v >= beta)
2597 || (is_upper_bound(tte->type()) && v < beta));
2601 // refine_eval() returns the transposition table score if
2602 // possible otherwise falls back on static position evaluation.
2604 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2609 Value v = value_from_tt(tte->value(), ply);
2611 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2612 || (is_upper_bound(tte->type()) && v < defaultEval))
2619 // update_history() registers a good move that produced a beta-cutoff
2620 // in history and marks as failures all the other moves of that ply.
2622 void update_history(const Position& pos, Move move, Depth depth,
2623 Move movesSearched[], int moveCount) {
2627 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2629 for (int i = 0; i < moveCount - 1; i++)
2631 m = movesSearched[i];
2635 if (!pos.move_is_capture_or_promotion(m))
2636 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2641 // update_killers() add a good move that produced a beta-cutoff
2642 // among the killer moves of that ply.
2644 void update_killers(Move m, SearchStack& ss) {
2646 if (m == ss.killers[0])
2649 for (int i = KILLER_MAX - 1; i > 0; i--)
2650 ss.killers[i] = ss.killers[i - 1];
2656 // update_gains() updates the gains table of a non-capture move given
2657 // the static position evaluation before and after the move.
2659 void update_gains(const Position& pos, Move m, Value before, Value after) {
2662 && before != VALUE_NONE
2663 && after != VALUE_NONE
2664 && pos.captured_piece() == NO_PIECE_TYPE
2665 && !move_is_castle(m)
2666 && !move_is_promotion(m))
2667 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2671 // fail_high_ply_1() checks if some thread is currently resolving a fail
2672 // high at ply 1 at the node below the first root node. This information
2673 // is used for time management.
2675 bool fail_high_ply_1() {
2677 for (int i = 0; i < ActiveThreads; i++)
2678 if (Threads[i].failHighPly1)
2685 // current_search_time() returns the number of milliseconds which have passed
2686 // since the beginning of the current search.
2688 int current_search_time() {
2690 return get_system_time() - SearchStartTime;
2694 // nps() computes the current nodes/second count.
2698 int t = current_search_time();
2699 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2703 // poll() performs two different functions: It polls for user input, and it
2704 // looks at the time consumed so far and decides if it's time to abort the
2709 static int lastInfoTime;
2710 int t = current_search_time();
2715 // We are line oriented, don't read single chars
2716 std::string command;
2718 if (!std::getline(std::cin, command))
2721 if (command == "quit")
2724 PonderSearch = false;
2728 else if (command == "stop")
2731 PonderSearch = false;
2733 else if (command == "ponderhit")
2737 // Print search information
2741 else if (lastInfoTime > t)
2742 // HACK: Must be a new search where we searched less than
2743 // NodesBetweenPolls nodes during the first second of search.
2746 else if (t - lastInfoTime >= 1000)
2754 if (dbg_show_hit_rate)
2755 dbg_print_hit_rate();
2757 cout << "info nodes " << nodes_searched() << " nps " << nps()
2758 << " time " << t << " hashfull " << TT.full() << endl;
2760 lock_release(&IOLock);
2762 if (ShowCurrentLine)
2763 Threads[0].printCurrentLine = true;
2766 // Should we stop the search?
2770 bool stillAtFirstMove = RootMoveNumber == 1
2772 && t > MaxSearchTime + ExtraSearchTime;
2774 bool noMoreTime = t > AbsoluteMaxSearchTime
2775 || stillAtFirstMove;
2777 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2778 || (ExactMaxTime && t >= ExactMaxTime)
2779 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2784 // ponderhit() is called when the program is pondering (i.e. thinking while
2785 // it's the opponent's turn to move) in order to let the engine know that
2786 // it correctly predicted the opponent's move.
2790 int t = current_search_time();
2791 PonderSearch = false;
2793 bool stillAtFirstMove = RootMoveNumber == 1
2795 && t > MaxSearchTime + ExtraSearchTime;
2797 bool noMoreTime = t > AbsoluteMaxSearchTime
2798 || stillAtFirstMove;
2800 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2805 // print_current_line() prints the current line of search for a given
2806 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2808 void print_current_line(SearchStack ss[], int ply, int threadID) {
2810 assert(ply >= 0 && ply < PLY_MAX);
2811 assert(threadID >= 0 && threadID < ActiveThreads);
2813 if (!Threads[threadID].idle)
2816 cout << "info currline " << (threadID + 1);
2817 for (int p = 0; p < ply; p++)
2818 cout << " " << ss[p].currentMove;
2821 lock_release(&IOLock);
2823 Threads[threadID].printCurrentLine = false;
2824 if (threadID + 1 < ActiveThreads)
2825 Threads[threadID + 1].printCurrentLine = true;
2829 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2831 void init_ss_array(SearchStack ss[]) {
2833 for (int i = 0; i < 3; i++)
2836 ss[i].initKillers();
2841 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2842 // while the program is pondering. The point is to work around a wrinkle in
2843 // the UCI protocol: When pondering, the engine is not allowed to give a
2844 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2845 // We simply wait here until one of these commands is sent, and return,
2846 // after which the bestmove and pondermove will be printed (in id_loop()).
2848 void wait_for_stop_or_ponderhit() {
2850 std::string command;
2854 if (!std::getline(std::cin, command))
2857 if (command == "quit")
2862 else if (command == "ponderhit" || command == "stop")
2868 // idle_loop() is where the threads are parked when they have no work to do.
2869 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2870 // object for which the current thread is the master.
2872 void idle_loop(int threadID, SplitPoint* waitSp) {
2874 assert(threadID >= 0 && threadID < THREAD_MAX);
2876 Threads[threadID].running = true;
2880 if (AllThreadsShouldExit && threadID != 0)
2883 // If we are not thinking, wait for a condition to be signaled
2884 // instead of wasting CPU time polling for work.
2885 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2888 #if !defined(_MSC_VER)
2889 pthread_mutex_lock(&WaitLock);
2890 if (Idle || threadID >= ActiveThreads)
2891 pthread_cond_wait(&WaitCond, &WaitLock);
2893 pthread_mutex_unlock(&WaitLock);
2895 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2899 // If this thread has been assigned work, launch a search
2900 if (Threads[threadID].workIsWaiting)
2902 assert(!Threads[threadID].idle);
2904 Threads[threadID].workIsWaiting = false;
2905 if (Threads[threadID].splitPoint->pvNode)
2906 sp_search_pv(Threads[threadID].splitPoint, threadID);
2908 sp_search(Threads[threadID].splitPoint, threadID);
2910 Threads[threadID].idle = true;
2913 // If this thread is the master of a split point and all threads have
2914 // finished their work at this split point, return from the idle loop.
2915 if (waitSp != NULL && waitSp->cpus == 0)
2919 Threads[threadID].running = false;
2923 // init_split_point_stack() is called during program initialization, and
2924 // initializes all split point objects.
2926 void init_split_point_stack() {
2928 for (int i = 0; i < THREAD_MAX; i++)
2929 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2931 SplitPointStack[i][j].parent = NULL;
2932 lock_init(&(SplitPointStack[i][j].lock), NULL);
2937 // destroy_split_point_stack() is called when the program exits, and
2938 // destroys all locks in the precomputed split point objects.
2940 void destroy_split_point_stack() {
2942 for (int i = 0; i < THREAD_MAX; i++)
2943 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2944 lock_destroy(&(SplitPointStack[i][j].lock));
2948 // thread_should_stop() checks whether the thread with a given threadID has
2949 // been asked to stop, directly or indirectly. This can happen if a beta
2950 // cutoff has occurred in the thread's currently active split point, or in
2951 // some ancestor of the current split point.
2953 bool thread_should_stop(int threadID) {
2955 assert(threadID >= 0 && threadID < ActiveThreads);
2959 if (Threads[threadID].stop)
2961 if (ActiveThreads <= 2)
2963 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2966 Threads[threadID].stop = true;
2973 // thread_is_available() checks whether the thread with threadID "slave" is
2974 // available to help the thread with threadID "master" at a split point. An
2975 // obvious requirement is that "slave" must be idle. With more than two
2976 // threads, this is not by itself sufficient: If "slave" is the master of
2977 // some active split point, it is only available as a slave to the other
2978 // threads which are busy searching the split point at the top of "slave"'s
2979 // split point stack (the "helpful master concept" in YBWC terminology).
2981 bool thread_is_available(int slave, int master) {
2983 assert(slave >= 0 && slave < ActiveThreads);
2984 assert(master >= 0 && master < ActiveThreads);
2985 assert(ActiveThreads > 1);
2987 if (!Threads[slave].idle || slave == master)
2990 // Make a local copy to be sure doesn't change under our feet
2991 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
2993 if (localActiveSplitPoints == 0)
2994 // No active split points means that the thread is available as
2995 // a slave for any other thread.
2998 if (ActiveThreads == 2)
3001 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
3002 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
3003 // could have been set to 0 by another thread leading to an out of bound access.
3004 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
3011 // idle_thread_exists() tries to find an idle thread which is available as
3012 // a slave for the thread with threadID "master".
3014 bool idle_thread_exists(int master) {
3016 assert(master >= 0 && master < ActiveThreads);
3017 assert(ActiveThreads > 1);
3019 for (int i = 0; i < ActiveThreads; i++)
3020 if (thread_is_available(i, master))
3027 // split() does the actual work of distributing the work at a node between
3028 // several threads at PV nodes. If it does not succeed in splitting the
3029 // node (because no idle threads are available, or because we have no unused
3030 // split point objects), the function immediately returns false. If
3031 // splitting is possible, a SplitPoint object is initialized with all the
3032 // data that must be copied to the helper threads (the current position and
3033 // search stack, alpha, beta, the search depth, etc.), and we tell our
3034 // helper threads that they have been assigned work. This will cause them
3035 // to instantly leave their idle loops and call sp_search_pv(). When all
3036 // threads have returned from sp_search_pv (or, equivalently, when
3037 // splitPoint->cpus becomes 0), split() returns true.
3039 bool split(const Position& p, SearchStack* sstck, int ply,
3040 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
3041 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
3044 assert(sstck != NULL);
3045 assert(ply >= 0 && ply < PLY_MAX);
3046 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
3047 assert(!pvNode || *alpha < *beta);
3048 assert(*beta <= VALUE_INFINITE);
3049 assert(depth > Depth(0));
3050 assert(master >= 0 && master < ActiveThreads);
3051 assert(ActiveThreads > 1);
3053 SplitPoint* splitPoint;
3057 // If no other thread is available to help us, or if we have too many
3058 // active split points, don't split.
3059 if ( !idle_thread_exists(master)
3060 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
3062 lock_release(&MPLock);
3066 // Pick the next available split point object from the split point stack
3067 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
3068 Threads[master].activeSplitPoints++;
3070 // Initialize the split point object
3071 splitPoint->parent = Threads[master].splitPoint;
3072 splitPoint->finished = false;
3073 splitPoint->ply = ply;
3074 splitPoint->depth = depth;
3075 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
3076 splitPoint->beta = *beta;
3077 splitPoint->pvNode = pvNode;
3078 splitPoint->bestValue = *bestValue;
3079 splitPoint->futilityValue = futilityValue;
3080 splitPoint->master = master;
3081 splitPoint->mp = mp;
3082 splitPoint->moves = *moves;
3083 splitPoint->cpus = 1;
3084 splitPoint->pos = &p;
3085 splitPoint->parentSstack = sstck;
3086 for (int i = 0; i < ActiveThreads; i++)
3087 splitPoint->slaves[i] = 0;
3089 Threads[master].idle = false;
3090 Threads[master].stop = false;
3091 Threads[master].splitPoint = splitPoint;
3093 // Allocate available threads setting idle flag to false
3094 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
3095 if (thread_is_available(i, master))
3097 Threads[i].idle = false;
3098 Threads[i].stop = false;
3099 Threads[i].splitPoint = splitPoint;
3100 splitPoint->slaves[i] = 1;
3104 assert(splitPoint->cpus > 1);
3106 // We can release the lock because master and slave threads are already booked
3107 lock_release(&MPLock);
3109 // Tell the threads that they have work to do. This will make them leave
3110 // their idle loop. But before copy search stack tail for each thread.
3111 for (int i = 0; i < ActiveThreads; i++)
3112 if (i == master || splitPoint->slaves[i])
3114 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 3 * sizeof(SearchStack));
3115 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3118 // Everything is set up. The master thread enters the idle loop, from
3119 // which it will instantly launch a search, because its workIsWaiting
3120 // slot is 'true'. We send the split point as a second parameter to the
3121 // idle loop, which means that the main thread will return from the idle
3122 // loop when all threads have finished their work at this split point
3123 // (i.e. when splitPoint->cpus == 0).
3124 idle_loop(master, splitPoint);
3126 // We have returned from the idle loop, which means that all threads are
3127 // finished. Update alpha, beta and bestValue, and return.
3131 *alpha = splitPoint->alpha;
3133 *beta = splitPoint->beta;
3134 *bestValue = splitPoint->bestValue;
3135 Threads[master].stop = false;
3136 Threads[master].idle = false;
3137 Threads[master].activeSplitPoints--;
3138 Threads[master].splitPoint = splitPoint->parent;
3140 lock_release(&MPLock);
3145 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3146 // to start a new search from the root.
3148 void wake_sleeping_threads() {
3150 if (ActiveThreads > 1)
3152 for (int i = 1; i < ActiveThreads; i++)
3154 Threads[i].idle = true;
3155 Threads[i].workIsWaiting = false;
3158 #if !defined(_MSC_VER)
3159 pthread_mutex_lock(&WaitLock);
3160 pthread_cond_broadcast(&WaitCond);
3161 pthread_mutex_unlock(&WaitLock);
3163 for (int i = 1; i < THREAD_MAX; i++)
3164 SetEvent(SitIdleEvent[i]);
3170 // init_thread() is the function which is called when a new thread is
3171 // launched. It simply calls the idle_loop() function with the supplied
3172 // threadID. There are two versions of this function; one for POSIX
3173 // threads and one for Windows threads.
3175 #if !defined(_MSC_VER)
3177 void* init_thread(void *threadID) {
3179 idle_loop(*(int*)threadID, NULL);
3185 DWORD WINAPI init_thread(LPVOID threadID) {
3187 idle_loop(*(int*)threadID, NULL);