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 // Use internal iterative deepening?
130 const bool UseIIDAtPVNodes = true;
131 const bool UseIIDAtNonPVNodes = true;
133 // Internal iterative deepening margin. At Non-PV moves, when
134 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
135 // search when the static evaluation is at most IIDMargin below beta.
136 const Value IIDMargin = Value(0x100);
138 // Easy move margin. An easy move candidate must be at least this much
139 // better than the second best move.
140 const Value EasyMoveMargin = Value(0x200);
142 // Null move margin. A null move search will not be done if the static
143 // evaluation of the position is more than NullMoveMargin below beta.
144 const Value NullMoveMargin = Value(0x200);
146 // If the TT move is at least SingleReplyMargin better then the
147 // remaining ones we will extend it.
148 const Value SingleReplyMargin = Value(0x20);
150 // Depth limit for razoring
151 const Depth RazorDepth = 4 * OnePly;
153 /// Lookup tables initialized at startup
155 // Reduction lookup tables and their getter functions
156 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
157 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
159 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
160 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
162 // Futility lookup tables and their getter functions
163 const Value FutilityMarginQS = Value(0x80);
164 int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
165 int FutilityMoveCountArray[32]; // [depth]
167 inline Value futility_margin(Depth d, int mn) { return (Value) (d < 14? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2*VALUE_INFINITE); }
168 inline int futility_move_count(Depth d) { return (d < 32? FutilityMoveCountArray[d] : 512); }
170 /// Variables initialized by UCI options
172 // Depth limit for use of dynamic threat detection
175 // Last seconds noise filtering (LSN)
176 const bool UseLSNFiltering = true;
177 const int LSNTime = 4000; // In milliseconds
178 const Value LSNValue = value_from_centipawns(200);
179 bool loseOnTime = false;
181 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
182 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
183 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
185 // Iteration counters
187 BetaCounterType BetaCounter;
189 // Scores and number of times the best move changed for each iteration
190 Value ValueByIteration[PLY_MAX_PLUS_2];
191 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
193 // Search window management
199 // Time managment variables
202 int MaxNodes, MaxDepth;
203 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
204 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
205 bool AbortSearch, Quit;
206 bool AspirationFailLow;
208 // Show current line?
209 bool ShowCurrentLine;
213 std::ofstream LogFile;
215 // MP related variables
216 int ActiveThreads = 1;
217 Depth MinimumSplitDepth;
218 int MaxThreadsPerSplitPoint;
219 Thread Threads[THREAD_MAX];
222 bool AllThreadsShouldExit = false;
223 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
226 #if !defined(_MSC_VER)
227 pthread_cond_t WaitCond;
228 pthread_mutex_t WaitLock;
230 HANDLE SitIdleEvent[THREAD_MAX];
233 // Node counters, used only by thread[0] but try to keep in different
234 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
236 int NodesBetweenPolls = 30000;
243 Value id_loop(const Position& pos, Move searchMoves[]);
244 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
245 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
246 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
247 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
248 void sp_search(SplitPoint* sp, int threadID);
249 void sp_search_pv(SplitPoint* sp, int threadID);
250 void init_node(SearchStack ss[], int ply, int threadID);
251 void update_pv(SearchStack ss[], int ply);
252 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
253 bool connected_moves(const Position& pos, Move m1, Move m2);
254 bool value_is_mate(Value value);
255 bool move_is_killer(Move m, const SearchStack& ss);
256 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
257 bool ok_to_do_nullmove(const Position& pos);
258 bool ok_to_prune(const Position& pos, Move m, Move threat);
259 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
260 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
261 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
262 void update_killers(Move m, SearchStack& ss);
263 void update_gains(const Position& pos, Move move, Value before, Value after);
265 int current_search_time();
269 void print_current_line(SearchStack ss[], int ply, int threadID);
270 void wait_for_stop_or_ponderhit();
271 void init_ss_array(SearchStack ss[]);
273 void idle_loop(int threadID, SplitPoint* waitSp);
274 void init_split_point_stack();
275 void destroy_split_point_stack();
276 bool thread_should_stop(int threadID);
277 bool thread_is_available(int slave, int master);
278 bool idle_thread_exists(int master);
279 bool split(const Position& pos, SearchStack* ss, int ply,
280 Value *alpha, Value *beta, Value *bestValue,
281 const Value futilityValue, Depth depth, int *moves,
282 MovePicker *mp, int master, bool pvNode);
283 void wake_sleeping_threads();
285 #if !defined(_MSC_VER)
286 void *init_thread(void *threadID);
288 DWORD WINAPI init_thread(LPVOID threadID);
299 /// perft() is our utility to verify move generation is bug free. All the legal
300 /// moves up to given depth are generated and counted and the sum returned.
302 int perft(Position& pos, Depth depth)
306 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
308 // If we are at the last ply we don't need to do and undo
309 // the moves, just to count them.
310 if (depth <= OnePly) // Replace with '<' to test also qsearch
312 while (mp.get_next_move()) sum++;
316 // Loop through all legal moves
318 while ((move = mp.get_next_move()) != MOVE_NONE)
321 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
322 sum += perft(pos, depth - OnePly);
329 /// think() is the external interface to Stockfish's search, and is called when
330 /// the program receives the UCI 'go' command. It initializes various
331 /// search-related global variables, and calls root_search(). It returns false
332 /// when a quit command is received during the search.
334 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
335 int time[], int increment[], int movesToGo, int maxDepth,
336 int maxNodes, int maxTime, Move searchMoves[]) {
338 // Initialize global search variables
339 Idle = StopOnPonderhit = AbortSearch = Quit = false;
340 AspirationFailLow = false;
342 SearchStartTime = get_system_time();
343 ExactMaxTime = maxTime;
346 InfiniteSearch = infinite;
347 PonderSearch = ponder;
348 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
350 // Look for a book move, only during games, not tests
351 if (UseTimeManagement && get_option_value_bool("OwnBook"))
354 if (get_option_value_string("Book File") != OpeningBook.file_name())
355 OpeningBook.open(get_option_value_string("Book File"));
357 bookMove = OpeningBook.get_move(pos);
358 if (bookMove != MOVE_NONE)
361 wait_for_stop_or_ponderhit();
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 for (i = 0; i < 14; i++) // i == depth (OnePly = 2)
555 for (int j = 0; j < 64; j++) // j == moveNumber
557 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
560 // Init futility move count array
561 for (i = 0; i < 32; i++) // i == depth (OnePly = 2)
562 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
564 for (i = 0; i < THREAD_MAX; i++)
565 Threads[i].activeSplitPoints = 0;
567 // Initialize global locks
568 lock_init(&MPLock, NULL);
569 lock_init(&IOLock, NULL);
571 init_split_point_stack();
573 #if !defined(_MSC_VER)
574 pthread_mutex_init(&WaitLock, NULL);
575 pthread_cond_init(&WaitCond, NULL);
577 for (i = 0; i < THREAD_MAX; i++)
578 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
581 // All threads except the main thread should be initialized to idle state
582 for (i = 1; i < THREAD_MAX; i++)
584 Threads[i].stop = false;
585 Threads[i].workIsWaiting = false;
586 Threads[i].idle = true;
587 Threads[i].running = false;
590 // Launch the helper threads
591 for (i = 1; i < THREAD_MAX; i++)
593 #if !defined(_MSC_VER)
594 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
597 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
602 cout << "Failed to create thread number " << i << endl;
603 Application::exit_with_failure();
606 // Wait until the thread has finished launching
607 while (!Threads[i].running);
612 /// stop_threads() is called when the program exits. It makes all the
613 /// helper threads exit cleanly.
615 void stop_threads() {
617 ActiveThreads = THREAD_MAX; // HACK
618 Idle = false; // HACK
619 wake_sleeping_threads();
620 AllThreadsShouldExit = true;
621 for (int i = 1; i < THREAD_MAX; i++)
623 Threads[i].stop = true;
624 while (Threads[i].running);
626 destroy_split_point_stack();
630 /// nodes_searched() returns the total number of nodes searched so far in
631 /// the current search.
633 int64_t nodes_searched() {
635 int64_t result = 0ULL;
636 for (int i = 0; i < ActiveThreads; i++)
637 result += Threads[i].nodes;
642 // SearchStack::init() initializes a search stack. Used at the beginning of a
643 // new search from the root.
644 void SearchStack::init(int ply) {
646 pv[ply] = pv[ply + 1] = MOVE_NONE;
647 currentMove = threatMove = MOVE_NONE;
648 reduction = Depth(0);
653 void SearchStack::initKillers() {
655 mateKiller = MOVE_NONE;
656 for (int i = 0; i < KILLER_MAX; i++)
657 killers[i] = MOVE_NONE;
662 // id_loop() is the main iterative deepening loop. It calls root_search
663 // repeatedly with increasing depth until the allocated thinking time has
664 // been consumed, the user stops the search, or the maximum search depth is
667 Value id_loop(const Position& pos, Move searchMoves[]) {
670 SearchStack ss[PLY_MAX_PLUS_2];
672 // searchMoves are verified, copied, scored and sorted
673 RootMoveList rml(p, searchMoves);
675 // Handle special case of searching on a mate/stale position
676 if (rml.move_count() == 0)
679 wait_for_stop_or_ponderhit();
681 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
684 // Print RootMoveList c'tor startup scoring to the standard output,
685 // so that we print information also for iteration 1.
686 cout << "info depth " << 1 << "\ninfo depth " << 1
687 << " score " << value_to_string(rml.get_move_score(0))
688 << " time " << current_search_time()
689 << " nodes " << nodes_searched()
691 << " pv " << rml.get_move(0) << "\n";
697 ValueByIteration[1] = rml.get_move_score(0);
700 // Is one move significantly better than others after initial scoring ?
701 Move EasyMove = MOVE_NONE;
702 if ( rml.move_count() == 1
703 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
704 EasyMove = rml.get_move(0);
706 // Iterative deepening loop
707 while (Iteration < PLY_MAX)
709 // Initialize iteration
712 BestMoveChangesByIteration[Iteration] = 0;
716 cout << "info depth " << Iteration << endl;
718 // Calculate dynamic search window based on previous iterations
721 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
723 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
724 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
726 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
727 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
729 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
730 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
734 alpha = - VALUE_INFINITE;
735 beta = VALUE_INFINITE;
738 // Search to the current depth
739 Value value = root_search(p, ss, rml, alpha, beta);
741 // Write PV to transposition table, in case the relevant entries have
742 // been overwritten during the search.
743 TT.insert_pv(p, ss[0].pv);
746 break; // Value cannot be trusted. Break out immediately!
748 //Save info about search result
749 ValueByIteration[Iteration] = value;
751 // Drop the easy move if it differs from the new best move
752 if (ss[0].pv[0] != EasyMove)
753 EasyMove = MOVE_NONE;
755 if (UseTimeManagement)
758 bool stopSearch = false;
760 // Stop search early if there is only a single legal move,
761 // we search up to Iteration 6 anyway to get a proper score.
762 if (Iteration >= 6 && rml.move_count() == 1)
765 // Stop search early when the last two iterations returned a mate score
767 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
768 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
771 // Stop search early if one move seems to be much better than the rest
772 int64_t nodes = nodes_searched();
774 && EasyMove == ss[0].pv[0]
775 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
776 && current_search_time() > MaxSearchTime / 16)
777 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
778 && current_search_time() > MaxSearchTime / 32)))
781 // Add some extra time if the best move has changed during the last two iterations
782 if (Iteration > 5 && Iteration <= 50)
783 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
784 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
786 // Stop search if most of MaxSearchTime is consumed at the end of the
787 // iteration. We probably don't have enough time to search the first
788 // move at the next iteration anyway.
789 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
797 StopOnPonderhit = true;
801 if (MaxDepth && Iteration >= MaxDepth)
807 // If we are pondering or in infinite search, we shouldn't print the
808 // best move before we are told to do so.
809 if (!AbortSearch && (PonderSearch || InfiniteSearch))
810 wait_for_stop_or_ponderhit();
812 // Print final search statistics
813 cout << "info nodes " << nodes_searched()
815 << " time " << current_search_time()
816 << " hashfull " << TT.full() << endl;
818 // Print the best move and the ponder move to the standard output
819 if (ss[0].pv[0] == MOVE_NONE)
821 ss[0].pv[0] = rml.get_move(0);
822 ss[0].pv[1] = MOVE_NONE;
824 cout << "bestmove " << ss[0].pv[0];
825 if (ss[0].pv[1] != MOVE_NONE)
826 cout << " ponder " << ss[0].pv[1];
833 dbg_print_mean(LogFile);
835 if (dbg_show_hit_rate)
836 dbg_print_hit_rate(LogFile);
838 LogFile << "\nNodes: " << nodes_searched()
839 << "\nNodes/second: " << nps()
840 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
843 p.do_move(ss[0].pv[0], st);
844 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
846 return rml.get_move_score(0);
850 // root_search() is the function which searches the root node. It is
851 // similar to search_pv except that it uses a different move ordering
852 // scheme and prints some information to the standard output.
854 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
859 Depth depth, ext, newDepth;
862 int researchCount = 0;
863 bool moveIsCheck, captureOrPromotion, dangerous;
864 Value alpha = oldAlpha;
865 bool isCheck = pos.is_check();
867 // Evaluate the position statically
869 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
871 while (1) // Fail low loop
874 // Loop through all the moves in the root move list
875 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
879 // We failed high, invalidate and skip next moves, leave node-counters
880 // and beta-counters as they are and quickly return, we will try to do
881 // a research at the next iteration with a bigger aspiration window.
882 rml.set_move_score(i, -VALUE_INFINITE);
886 RootMoveNumber = i + 1;
888 // Save the current node count before the move is searched
889 nodes = nodes_searched();
891 // Reset beta cut-off counters
894 // Pick the next root move, and print the move and the move number to
895 // the standard output.
896 move = ss[0].currentMove = rml.get_move(i);
898 if (current_search_time() >= 1000)
899 cout << "info currmove " << move
900 << " currmovenumber " << RootMoveNumber << endl;
902 // Decide search depth for this move
903 moveIsCheck = pos.move_is_check(move);
904 captureOrPromotion = pos.move_is_capture_or_promotion(move);
905 depth = (Iteration - 2) * OnePly + InitialDepth;
906 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
907 newDepth = depth + ext;
909 value = - VALUE_INFINITE;
911 while (1) // Fail high loop
914 // Make the move, and search it
915 pos.do_move(move, st, ci, moveIsCheck);
917 if (i < MultiPV || value > alpha)
919 // Aspiration window is disabled in multi-pv case
921 alpha = -VALUE_INFINITE;
923 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
927 // Try to reduce non-pv search depth by one ply if move seems not problematic,
928 // if the move fails high will be re-searched at full depth.
929 bool doFullDepthSearch = true;
931 if ( depth >= 3*OnePly // FIXME was newDepth
933 && !captureOrPromotion
934 && !move_is_castle(move))
936 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
939 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
940 doFullDepthSearch = (value > alpha);
944 if (doFullDepthSearch)
946 ss[0].reduction = Depth(0);
947 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
950 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
956 // Can we exit fail high loop ?
957 if (AbortSearch || value < beta)
960 // We are failing high and going to do a research. It's important to update score
961 // before research in case we run out of time while researching.
962 rml.set_move_score(i, value);
964 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
965 rml.set_move_pv(i, ss[0].pv);
967 // Print search information to the standard output
968 cout << "info depth " << Iteration
969 << " score " << value_to_string(value)
970 << ((value >= beta) ? " lowerbound" :
971 ((value <= alpha)? " upperbound" : ""))
972 << " time " << current_search_time()
973 << " nodes " << nodes_searched()
977 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
978 cout << ss[0].pv[j] << " ";
984 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
985 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
987 LogFile << pretty_pv(pos, current_search_time(), Iteration,
988 nodes_searched(), value, type, ss[0].pv) << endl;
991 // Prepare for a research after a fail high, each time with a wider window
993 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
995 } // End of fail high loop
997 // Finished searching the move. If AbortSearch is true, the search
998 // was aborted because the user interrupted the search or because we
999 // ran out of time. In this case, the return value of the search cannot
1000 // be trusted, and we break out of the loop without updating the best
1005 // Remember beta-cutoff and searched nodes counts for this move. The
1006 // info is used to sort the root moves at the next iteration.
1008 BetaCounter.read(pos.side_to_move(), our, their);
1009 rml.set_beta_counters(i, our, their);
1010 rml.set_move_nodes(i, nodes_searched() - nodes);
1012 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1014 if (value <= alpha && i >= MultiPV)
1015 rml.set_move_score(i, -VALUE_INFINITE);
1018 // PV move or new best move!
1021 rml.set_move_score(i, value);
1023 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1024 rml.set_move_pv(i, ss[0].pv);
1028 // We record how often the best move has been changed in each
1029 // iteration. This information is used for time managment: When
1030 // the best move changes frequently, we allocate some more time.
1032 BestMoveChangesByIteration[Iteration]++;
1034 // Print search information to the standard output
1035 cout << "info depth " << Iteration
1036 << " score " << value_to_string(value)
1037 << ((value >= beta) ? " lowerbound" :
1038 ((value <= alpha)? " upperbound" : ""))
1039 << " time " << current_search_time()
1040 << " nodes " << nodes_searched()
1044 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1045 cout << ss[0].pv[j] << " ";
1051 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1052 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1054 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1055 nodes_searched(), value, type, ss[0].pv) << endl;
1062 rml.sort_multipv(i);
1063 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1065 cout << "info multipv " << j + 1
1066 << " score " << value_to_string(rml.get_move_score(j))
1067 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1068 << " time " << current_search_time()
1069 << " nodes " << nodes_searched()
1073 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1074 cout << rml.get_move_pv(j, k) << " ";
1078 alpha = rml.get_move_score(Min(i, MultiPV-1));
1080 } // PV move or new best move
1082 assert(alpha >= oldAlpha);
1084 AspirationFailLow = (alpha == oldAlpha);
1086 if (AspirationFailLow && StopOnPonderhit)
1087 StopOnPonderhit = false;
1090 // Can we exit fail low loop ?
1091 if (AbortSearch || alpha > oldAlpha)
1094 // Prepare for a research after a fail low, each time with a wider window
1096 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1105 // search_pv() is the main search function for PV nodes.
1107 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1108 Depth depth, int ply, int threadID) {
1110 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1111 assert(beta > alpha && beta <= VALUE_INFINITE);
1112 assert(ply >= 0 && ply < PLY_MAX);
1113 assert(threadID >= 0 && threadID < ActiveThreads);
1115 Move movesSearched[256];
1119 Depth ext, newDepth;
1120 Value oldAlpha, value;
1121 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1123 Value bestValue = value = -VALUE_INFINITE;
1126 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1128 // Initialize, and make an early exit in case of an aborted search,
1129 // an instant draw, maximum ply reached, etc.
1130 init_node(ss, ply, threadID);
1132 // After init_node() that calls poll()
1133 if (AbortSearch || thread_should_stop(threadID))
1136 if (pos.is_draw() || ply >= PLY_MAX - 1)
1139 // Mate distance pruning
1141 alpha = Max(value_mated_in(ply), alpha);
1142 beta = Min(value_mate_in(ply+1), beta);
1146 // Transposition table lookup. At PV nodes, we don't use the TT for
1147 // pruning, but only for move ordering. This is to avoid problems in
1148 // the following areas:
1150 // * Repetition draw detection
1151 // * Fifty move rule detection
1152 // * Searching for a mate
1153 // * Printing of full PV line
1155 tte = TT.retrieve(pos.get_key());
1156 ttMove = (tte ? tte->move() : MOVE_NONE);
1158 // Go with internal iterative deepening if we don't have a TT move
1159 if ( UseIIDAtPVNodes
1160 && depth >= 5*OnePly
1161 && ttMove == MOVE_NONE)
1163 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1164 ttMove = ss[ply].pv[ply];
1165 tte = TT.retrieve(pos.get_key());
1168 isCheck = pos.is_check();
1171 // Update gain statistics of the previous move that lead
1172 // us in this position.
1174 ss[ply].eval = evaluate(pos, ei, threadID);
1175 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1178 // Initialize a MovePicker object for the current position, and prepare
1179 // to search all moves
1180 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1182 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1184 // Loop through all legal moves until no moves remain or a beta cutoff
1186 while ( alpha < beta
1187 && (move = mp.get_next_move()) != MOVE_NONE
1188 && !thread_should_stop(threadID))
1190 assert(move_is_ok(move));
1192 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1193 moveIsCheck = pos.move_is_check(move, ci);
1194 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1196 // Decide the new search depth
1197 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1199 // Singular extension search. We extend the TT move if its value is much better than
1200 // its siblings. To verify this we do a reduced search on all the other moves but the
1201 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1202 if ( depth >= 6 * OnePly
1204 && move == tte->move()
1206 && is_lower_bound(tte->type())
1207 && tte->depth() >= depth - 3 * OnePly)
1209 Value ttValue = value_from_tt(tte->value(), ply);
1211 if (abs(ttValue) < VALUE_KNOWN_WIN)
1213 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1215 if (excValue < ttValue - SingleReplyMargin)
1220 newDepth = depth - OnePly + ext;
1222 // Update current move
1223 movesSearched[moveCount++] = ss[ply].currentMove = move;
1225 // Make and search the move
1226 pos.do_move(move, st, ci, moveIsCheck);
1228 if (moveCount == 1) // The first move in list is the PV
1229 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1232 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1233 // if the move fails high will be re-searched at full depth.
1234 bool doFullDepthSearch = true;
1236 if ( depth >= 3*OnePly
1238 && !captureOrPromotion
1239 && !move_is_castle(move)
1240 && !move_is_killer(move, ss[ply]))
1242 ss[ply].reduction = pv_reduction(depth, moveCount);
1243 if (ss[ply].reduction)
1245 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1246 doFullDepthSearch = (value > alpha);
1250 if (doFullDepthSearch) // Go with full depth non-pv search
1252 ss[ply].reduction = Depth(0);
1253 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1254 if (value > alpha && value < beta)
1255 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1258 pos.undo_move(move);
1260 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1263 if (value > bestValue)
1270 if (value == value_mate_in(ply + 1))
1271 ss[ply].mateKiller = move;
1276 if ( ActiveThreads > 1
1278 && depth >= MinimumSplitDepth
1280 && idle_thread_exists(threadID)
1282 && !thread_should_stop(threadID)
1283 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1284 depth, &moveCount, &mp, threadID, true))
1288 // All legal moves have been searched. A special case: If there were
1289 // no legal moves, it must be mate or stalemate.
1291 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1293 // If the search is not aborted, update the transposition table,
1294 // history counters, and killer moves.
1295 if (AbortSearch || thread_should_stop(threadID))
1298 if (bestValue <= oldAlpha)
1299 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1301 else if (bestValue >= beta)
1303 BetaCounter.add(pos.side_to_move(), depth, threadID);
1304 move = ss[ply].pv[ply];
1305 if (!pos.move_is_capture_or_promotion(move))
1307 update_history(pos, move, depth, movesSearched, moveCount);
1308 update_killers(move, ss[ply]);
1310 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1313 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1319 // search() is the search function for zero-width nodes.
1321 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1322 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1324 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1325 assert(ply >= 0 && ply < PLY_MAX);
1326 assert(threadID >= 0 && threadID < ActiveThreads);
1328 Move movesSearched[256];
1333 Depth ext, newDepth;
1334 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1335 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1336 bool mateThreat = false;
1338 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1341 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1343 // Initialize, and make an early exit in case of an aborted search,
1344 // an instant draw, maximum ply reached, etc.
1345 init_node(ss, ply, threadID);
1347 // After init_node() that calls poll()
1348 if (AbortSearch || thread_should_stop(threadID))
1351 if (pos.is_draw() || ply >= PLY_MAX - 1)
1354 // Mate distance pruning
1355 if (value_mated_in(ply) >= beta)
1358 if (value_mate_in(ply + 1) < beta)
1361 // We don't want the score of a partial search to overwrite a previous full search
1362 // TT value, so we use a different position key in case of an excluded move exsists.
1363 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1365 // Transposition table lookup
1366 tte = TT.retrieve(posKey);
1367 ttMove = (tte ? tte->move() : MOVE_NONE);
1369 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1371 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1372 return value_from_tt(tte->value(), ply);
1375 isCheck = pos.is_check();
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 + futility_margin(depth, 0); //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 - futility_margin(depth, 0) >= beta)
1401 return staticValue - futility_margin(depth, 0);
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(posKey);
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 >= futility_move_count(depth)
1534 && ok_to_prune(pos, move, ss[ply].threatMove)
1535 && bestValue > value_mated_in(PLY_MAX))
1538 // Value based pruning
1539 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1540 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount) + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1542 if (futilityValueScaled < beta)
1544 if (futilityValueScaled > bestValue)
1545 bestValue = futilityValueScaled;
1550 // Make and search the move
1551 pos.do_move(move, st, ci, moveIsCheck);
1553 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1554 // if the move fails high will be re-searched at full depth.
1555 bool doFullDepthSearch = true;
1557 if ( depth >= 3*OnePly
1559 && !captureOrPromotion
1560 && !move_is_castle(move)
1561 && !move_is_killer(move, ss[ply]))
1563 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1564 if (ss[ply].reduction)
1566 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1567 doFullDepthSearch = (value >= beta);
1571 if (doFullDepthSearch) // Go with full depth non-pv search
1573 ss[ply].reduction = Depth(0);
1574 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1576 pos.undo_move(move);
1578 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1581 if (value > bestValue)
1587 if (value == value_mate_in(ply + 1))
1588 ss[ply].mateKiller = move;
1592 if ( ActiveThreads > 1
1594 && depth >= MinimumSplitDepth
1596 && idle_thread_exists(threadID)
1598 && !thread_should_stop(threadID)
1599 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1600 depth, &moveCount, &mp, threadID, false))
1604 // All legal moves have been searched. A special case: If there were
1605 // no legal moves, it must be mate or stalemate.
1607 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1609 // If the search is not aborted, update the transposition table,
1610 // history counters, and killer moves.
1611 if (AbortSearch || thread_should_stop(threadID))
1614 if (bestValue < beta)
1615 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1618 BetaCounter.add(pos.side_to_move(), depth, threadID);
1619 move = ss[ply].pv[ply];
1620 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1621 if (!pos.move_is_capture_or_promotion(move))
1623 update_history(pos, move, depth, movesSearched, moveCount);
1624 update_killers(move, ss[ply]);
1629 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1635 // qsearch() is the quiescence search function, which is called by the main
1636 // search function when the remaining depth is zero (or, to be more precise,
1637 // less than OnePly).
1639 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1640 Depth depth, int ply, int threadID) {
1642 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1643 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1645 assert(ply >= 0 && ply < PLY_MAX);
1646 assert(threadID >= 0 && threadID < ActiveThreads);
1651 Value staticValue, bestValue, value, futilityBase, futilityValue;
1652 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1653 const TTEntry* tte = NULL;
1655 bool pvNode = (beta - alpha != 1);
1656 Value oldAlpha = alpha;
1658 // Initialize, and make an early exit in case of an aborted search,
1659 // an instant draw, maximum ply reached, etc.
1660 init_node(ss, ply, threadID);
1662 // After init_node() that calls poll()
1663 if (AbortSearch || thread_should_stop(threadID))
1666 if (pos.is_draw() || ply >= PLY_MAX - 1)
1669 // Transposition table lookup. At PV nodes, we don't use the TT for
1670 // pruning, but only for move ordering.
1671 tte = TT.retrieve(pos.get_key());
1672 ttMove = (tte ? tte->move() : MOVE_NONE);
1674 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1676 assert(tte->type() != VALUE_TYPE_EVAL);
1678 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1679 return value_from_tt(tte->value(), ply);
1682 isCheck = pos.is_check();
1684 // Evaluate the position statically
1686 staticValue = -VALUE_INFINITE;
1687 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1688 staticValue = value_from_tt(tte->value(), ply);
1690 staticValue = evaluate(pos, ei, threadID);
1694 ss[ply].eval = staticValue;
1695 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1698 // Initialize "stand pat score", and return it immediately if it is
1700 bestValue = staticValue;
1702 if (bestValue >= beta)
1704 // Store the score to avoid a future costly evaluation() call
1705 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1706 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1711 if (bestValue > alpha)
1714 // If we are near beta then try to get a cutoff pushing checks a bit further
1715 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1717 // Initialize a MovePicker object for the current position, and prepare
1718 // to search the moves. Because the depth is <= 0 here, only captures,
1719 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1720 // and we are near beta) will be generated.
1721 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1723 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1724 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1726 // Loop through the moves until no moves remain or a beta cutoff
1728 while ( alpha < beta
1729 && (move = mp.get_next_move()) != MOVE_NONE)
1731 assert(move_is_ok(move));
1733 moveIsCheck = pos.move_is_check(move, ci);
1735 // Update current move
1737 ss[ply].currentMove = move;
1745 && !move_is_promotion(move)
1746 && !pos.move_is_passed_pawn_push(move))
1748 futilityValue = futilityBase
1749 + pos.endgame_value_of_piece_on(move_to(move))
1750 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1752 if (futilityValue < alpha)
1754 if (futilityValue > bestValue)
1755 bestValue = futilityValue;
1760 // Detect blocking evasions that are candidate to be pruned
1761 evasionPrunable = isCheck
1762 && bestValue != -VALUE_INFINITE
1763 && !pos.move_is_capture(move)
1764 && pos.type_of_piece_on(move_from(move)) != KING
1765 && !pos.can_castle(pos.side_to_move());
1767 // Don't search moves with negative SEE values
1768 if ( (!isCheck || evasionPrunable)
1770 && !move_is_promotion(move)
1771 && pos.see_sign(move) < 0)
1774 // Make and search the move
1775 pos.do_move(move, st, ci, moveIsCheck);
1776 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1777 pos.undo_move(move);
1779 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1782 if (value > bestValue)
1793 // All legal moves have been searched. A special case: If we're in check
1794 // and no legal moves were found, it is checkmate.
1795 if (!moveCount && pos.is_check()) // Mate!
1796 return value_mated_in(ply);
1798 // Update transposition table
1799 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1800 if (bestValue <= oldAlpha)
1802 // If bestValue isn't changed it means it is still the static evaluation
1803 // of the node, so keep this info to avoid a future evaluation() call.
1804 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1805 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1807 else if (bestValue >= beta)
1809 move = ss[ply].pv[ply];
1810 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1812 // Update killers only for good checking moves
1813 if (!pos.move_is_capture_or_promotion(move))
1814 update_killers(move, ss[ply]);
1817 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1819 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1825 // sp_search() is used to search from a split point. This function is called
1826 // by each thread working at the split point. It is similar to the normal
1827 // search() function, but simpler. Because we have already probed the hash
1828 // table, done a null move search, and searched the first move before
1829 // splitting, we don't have to repeat all this work in sp_search(). We
1830 // also don't need to store anything to the hash table here: This is taken
1831 // care of after we return from the split point.
1833 void sp_search(SplitPoint* sp, int threadID) {
1835 assert(threadID >= 0 && threadID < ActiveThreads);
1836 assert(ActiveThreads > 1);
1838 Position pos(*sp->pos);
1840 SearchStack* ss = sp->sstack[threadID];
1841 Value value = -VALUE_INFINITE;
1844 bool isCheck = pos.is_check();
1845 bool useFutilityPruning = sp->depth < 7 * OnePly //FIXME: sync with search
1848 while ( lock_grab_bool(&(sp->lock))
1849 && sp->bestValue < sp->beta
1850 && !thread_should_stop(threadID)
1851 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1853 moveCount = ++sp->moves;
1854 lock_release(&(sp->lock));
1856 assert(move_is_ok(move));
1858 bool moveIsCheck = pos.move_is_check(move, ci);
1859 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1861 ss[sp->ply].currentMove = move;
1863 // Decide the new search depth
1865 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1866 Depth newDepth = sp->depth - OnePly + ext;
1869 if ( useFutilityPruning
1871 && !captureOrPromotion)
1873 // Move count based pruning
1874 if ( moveCount >= futility_move_count(sp->depth)
1875 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1876 && sp->bestValue > value_mated_in(PLY_MAX))
1879 // Value based pruning
1880 Value futilityValueScaled = sp->futilityValue - moveCount * 8; //FIXME: sync with search
1882 if (futilityValueScaled < sp->beta)
1884 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1886 lock_grab(&(sp->lock));
1887 if (futilityValueScaled > sp->bestValue)
1888 sp->bestValue = futilityValueScaled;
1889 lock_release(&(sp->lock));
1895 // Make and search the move.
1897 pos.do_move(move, st, ci, moveIsCheck);
1899 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1900 // if the move fails high will be re-searched at full depth.
1901 bool doFullDepthSearch = true;
1904 && !captureOrPromotion
1905 && !move_is_castle(move)
1906 && !move_is_killer(move, ss[sp->ply]))
1908 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1909 if (ss[sp->ply].reduction)
1911 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1912 doFullDepthSearch = (value >= sp->beta);
1916 if (doFullDepthSearch) // Go with full depth non-pv search
1918 ss[sp->ply].reduction = Depth(0);
1919 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1921 pos.undo_move(move);
1923 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1925 if (thread_should_stop(threadID))
1927 lock_grab(&(sp->lock));
1932 if (value > sp->bestValue) // Less then 2% of cases
1934 lock_grab(&(sp->lock));
1935 if (value > sp->bestValue && !thread_should_stop(threadID))
1937 sp->bestValue = value;
1938 if (sp->bestValue >= sp->beta)
1940 sp_update_pv(sp->parentSstack, ss, sp->ply);
1941 for (int i = 0; i < ActiveThreads; i++)
1942 if (i != threadID && (i == sp->master || sp->slaves[i]))
1943 Threads[i].stop = true;
1945 sp->finished = true;
1948 lock_release(&(sp->lock));
1952 /* Here we have the lock still grabbed */
1954 // If this is the master thread and we have been asked to stop because of
1955 // a beta cutoff higher up in the tree, stop all slave threads.
1956 if (sp->master == threadID && thread_should_stop(threadID))
1957 for (int i = 0; i < ActiveThreads; i++)
1959 Threads[i].stop = true;
1962 sp->slaves[threadID] = 0;
1964 lock_release(&(sp->lock));
1968 // sp_search_pv() is used to search from a PV split point. This function
1969 // is called by each thread working at the split point. It is similar to
1970 // the normal search_pv() function, but simpler. Because we have already
1971 // probed the hash table and searched the first move before splitting, we
1972 // don't have to repeat all this work in sp_search_pv(). We also don't
1973 // need to store anything to the hash table here: This is taken care of
1974 // after we return from the split point.
1976 void sp_search_pv(SplitPoint* sp, int threadID) {
1978 assert(threadID >= 0 && threadID < ActiveThreads);
1979 assert(ActiveThreads > 1);
1981 Position pos(*sp->pos);
1983 SearchStack* ss = sp->sstack[threadID];
1984 Value value = -VALUE_INFINITE;
1988 while ( lock_grab_bool(&(sp->lock))
1989 && sp->alpha < sp->beta
1990 && !thread_should_stop(threadID)
1991 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1993 moveCount = ++sp->moves;
1994 lock_release(&(sp->lock));
1996 assert(move_is_ok(move));
1998 bool moveIsCheck = pos.move_is_check(move, ci);
1999 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
2001 ss[sp->ply].currentMove = move;
2003 // Decide the new search depth
2005 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2006 Depth newDepth = sp->depth - OnePly + ext;
2008 // Make and search the move.
2010 pos.do_move(move, st, ci, moveIsCheck);
2012 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2013 // if the move fails high will be re-searched at full depth.
2014 bool doFullDepthSearch = true;
2017 && !captureOrPromotion
2018 && !move_is_castle(move)
2019 && !move_is_killer(move, ss[sp->ply]))
2021 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
2022 if (ss[sp->ply].reduction)
2024 Value localAlpha = sp->alpha;
2025 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2026 doFullDepthSearch = (value > localAlpha);
2030 if (doFullDepthSearch) // Go with full depth non-pv search
2032 Value localAlpha = sp->alpha;
2033 ss[sp->ply].reduction = Depth(0);
2034 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2036 if (value > localAlpha && value < sp->beta)
2038 // If another thread has failed high then sp->alpha has been increased
2039 // to be higher or equal then beta, if so, avoid to start a PV search.
2040 localAlpha = sp->alpha;
2041 if (localAlpha < sp->beta)
2042 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2044 assert(thread_should_stop(threadID));
2047 pos.undo_move(move);
2049 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2051 if (thread_should_stop(threadID))
2053 lock_grab(&(sp->lock));
2058 if (value > sp->bestValue) // Less then 2% of cases
2060 lock_grab(&(sp->lock));
2061 if (value > sp->bestValue && !thread_should_stop(threadID))
2063 sp->bestValue = value;
2064 if (value > sp->alpha)
2066 // Ask threads to stop before to modify sp->alpha
2067 if (value >= sp->beta)
2069 for (int i = 0; i < ActiveThreads; i++)
2070 if (i != threadID && (i == sp->master || sp->slaves[i]))
2071 Threads[i].stop = true;
2073 sp->finished = true;
2078 sp_update_pv(sp->parentSstack, ss, sp->ply);
2079 if (value == value_mate_in(sp->ply + 1))
2080 ss[sp->ply].mateKiller = move;
2083 lock_release(&(sp->lock));
2087 /* Here we have the lock still grabbed */
2089 // If this is the master thread and we have been asked to stop because of
2090 // a beta cutoff higher up in the tree, stop all slave threads.
2091 if (sp->master == threadID && thread_should_stop(threadID))
2092 for (int i = 0; i < ActiveThreads; i++)
2094 Threads[i].stop = true;
2097 sp->slaves[threadID] = 0;
2099 lock_release(&(sp->lock));
2102 /// The BetaCounterType class
2104 BetaCounterType::BetaCounterType() { clear(); }
2106 void BetaCounterType::clear() {
2108 for (int i = 0; i < THREAD_MAX; i++)
2109 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2112 void BetaCounterType::add(Color us, Depth d, int threadID) {
2114 // Weighted count based on depth
2115 Threads[threadID].betaCutOffs[us] += unsigned(d);
2118 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2121 for (int i = 0; i < THREAD_MAX; i++)
2123 our += Threads[i].betaCutOffs[us];
2124 their += Threads[i].betaCutOffs[opposite_color(us)];
2129 /// The RootMoveList class
2131 // RootMoveList c'tor
2133 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2135 SearchStack ss[PLY_MAX_PLUS_2];
2136 MoveStack mlist[MaxRootMoves];
2138 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2140 // Generate all legal moves
2141 MoveStack* last = generate_moves(pos, mlist);
2143 // Add each move to the moves[] array
2144 for (MoveStack* cur = mlist; cur != last; cur++)
2146 bool includeMove = includeAllMoves;
2148 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2149 includeMove = (searchMoves[k] == cur->move);
2154 // Find a quick score for the move
2156 pos.do_move(cur->move, st);
2157 moves[count].move = cur->move;
2158 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2159 moves[count].pv[0] = cur->move;
2160 moves[count].pv[1] = MOVE_NONE;
2161 pos.undo_move(cur->move);
2168 // RootMoveList simple methods definitions
2170 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2172 moves[moveNum].nodes = nodes;
2173 moves[moveNum].cumulativeNodes += nodes;
2176 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2178 moves[moveNum].ourBeta = our;
2179 moves[moveNum].theirBeta = their;
2182 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2186 for (j = 0; pv[j] != MOVE_NONE; j++)
2187 moves[moveNum].pv[j] = pv[j];
2189 moves[moveNum].pv[j] = MOVE_NONE;
2193 // RootMoveList::sort() sorts the root move list at the beginning of a new
2196 void RootMoveList::sort() {
2198 sort_multipv(count - 1); // Sort all items
2202 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2203 // list by their scores and depths. It is used to order the different PVs
2204 // correctly in MultiPV mode.
2206 void RootMoveList::sort_multipv(int n) {
2210 for (i = 1; i <= n; i++)
2212 RootMove rm = moves[i];
2213 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2214 moves[j] = moves[j - 1];
2221 // init_node() is called at the beginning of all the search functions
2222 // (search(), search_pv(), qsearch(), and so on) and initializes the
2223 // search stack object corresponding to the current node. Once every
2224 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2225 // for user input and checks whether it is time to stop the search.
2227 void init_node(SearchStack ss[], int ply, int threadID) {
2229 assert(ply >= 0 && ply < PLY_MAX);
2230 assert(threadID >= 0 && threadID < ActiveThreads);
2232 Threads[threadID].nodes++;
2237 if (NodesSincePoll >= NodesBetweenPolls)
2244 ss[ply + 2].initKillers();
2246 if (Threads[threadID].printCurrentLine)
2247 print_current_line(ss, ply, threadID);
2251 // update_pv() is called whenever a search returns a value > alpha.
2252 // It updates the PV in the SearchStack object corresponding to the
2255 void update_pv(SearchStack ss[], int ply) {
2257 assert(ply >= 0 && ply < PLY_MAX);
2261 ss[ply].pv[ply] = ss[ply].currentMove;
2263 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2264 ss[ply].pv[p] = ss[ply + 1].pv[p];
2266 ss[ply].pv[p] = MOVE_NONE;
2270 // sp_update_pv() is a variant of update_pv for use at split points. The
2271 // difference between the two functions is that sp_update_pv also updates
2272 // the PV at the parent node.
2274 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2276 assert(ply >= 0 && ply < PLY_MAX);
2280 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2282 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2283 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2285 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2289 // connected_moves() tests whether two moves are 'connected' in the sense
2290 // that the first move somehow made the second move possible (for instance
2291 // if the moving piece is the same in both moves). The first move is assumed
2292 // to be the move that was made to reach the current position, while the
2293 // second move is assumed to be a move from the current position.
2295 bool connected_moves(const Position& pos, Move m1, Move m2) {
2297 Square f1, t1, f2, t2;
2300 assert(move_is_ok(m1));
2301 assert(move_is_ok(m2));
2303 if (m2 == MOVE_NONE)
2306 // Case 1: The moving piece is the same in both moves
2312 // Case 2: The destination square for m2 was vacated by m1
2318 // Case 3: Moving through the vacated square
2319 if ( piece_is_slider(pos.piece_on(f2))
2320 && bit_is_set(squares_between(f2, t2), f1))
2323 // Case 4: The destination square for m2 is defended by the moving piece in m1
2324 p = pos.piece_on(t1);
2325 if (bit_is_set(pos.attacks_from(p, t1), t2))
2328 // Case 5: Discovered check, checking piece is the piece moved in m1
2329 if ( piece_is_slider(p)
2330 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2331 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2333 // discovered_check_candidates() works also if the Position's side to
2334 // move is the opposite of the checking piece.
2335 Color them = opposite_color(pos.side_to_move());
2336 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2338 if (bit_is_set(dcCandidates, f2))
2345 // value_is_mate() checks if the given value is a mate one
2346 // eventually compensated for the ply.
2348 bool value_is_mate(Value value) {
2350 assert(abs(value) <= VALUE_INFINITE);
2352 return value <= value_mated_in(PLY_MAX)
2353 || value >= value_mate_in(PLY_MAX);
2357 // move_is_killer() checks if the given move is among the
2358 // killer moves of that ply.
2360 bool move_is_killer(Move m, const SearchStack& ss) {
2362 const Move* k = ss.killers;
2363 for (int i = 0; i < KILLER_MAX; i++, k++)
2371 // extension() decides whether a move should be searched with normal depth,
2372 // or with extended depth. Certain classes of moves (checking moves, in
2373 // particular) are searched with bigger depth than ordinary moves and in
2374 // any case are marked as 'dangerous'. Note that also if a move is not
2375 // extended, as example because the corresponding UCI option is set to zero,
2376 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2378 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2379 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2381 assert(m != MOVE_NONE);
2383 Depth result = Depth(0);
2384 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2389 result += CheckExtension[pvNode];
2392 result += SingleEvasionExtension[pvNode];
2395 result += MateThreatExtension[pvNode];
2398 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2400 Color c = pos.side_to_move();
2401 if (relative_rank(c, move_to(m)) == RANK_7)
2403 result += PawnPushTo7thExtension[pvNode];
2406 if (pos.pawn_is_passed(c, move_to(m)))
2408 result += PassedPawnExtension[pvNode];
2413 if ( captureOrPromotion
2414 && pos.type_of_piece_on(move_to(m)) != PAWN
2415 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2416 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2417 && !move_is_promotion(m)
2420 result += PawnEndgameExtension[pvNode];
2425 && captureOrPromotion
2426 && pos.type_of_piece_on(move_to(m)) != PAWN
2427 && pos.see_sign(m) >= 0)
2433 return Min(result, OnePly);
2437 // ok_to_do_nullmove() looks at the current position and decides whether
2438 // doing a 'null move' should be allowed. In order to avoid zugzwang
2439 // problems, null moves are not allowed when the side to move has very
2440 // little material left. Currently, the test is a bit too simple: Null
2441 // moves are avoided only when the side to move has only pawns left.
2442 // It's probably a good idea to avoid null moves in at least some more
2443 // complicated endgames, e.g. KQ vs KR. FIXME
2445 bool ok_to_do_nullmove(const Position& pos) {
2447 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2451 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2452 // non-tactical moves late in the move list close to the leaves are
2453 // candidates for pruning.
2455 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2457 assert(move_is_ok(m));
2458 assert(threat == MOVE_NONE || move_is_ok(threat));
2459 assert(!pos.move_is_check(m));
2460 assert(!pos.move_is_capture_or_promotion(m));
2461 assert(!pos.move_is_passed_pawn_push(m));
2463 Square mfrom, mto, tfrom, tto;
2465 // Prune if there isn't any threat move
2466 if (threat == MOVE_NONE)
2469 mfrom = move_from(m);
2471 tfrom = move_from(threat);
2472 tto = move_to(threat);
2474 // Case 1: Don't prune moves which move the threatened piece
2478 // Case 2: If the threatened piece has value less than or equal to the
2479 // value of the threatening piece, don't prune move which defend it.
2480 if ( pos.move_is_capture(threat)
2481 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2482 || pos.type_of_piece_on(tfrom) == KING)
2483 && pos.move_attacks_square(m, tto))
2486 // Case 3: If the moving piece in the threatened move is a slider, don't
2487 // prune safe moves which block its ray.
2488 if ( piece_is_slider(pos.piece_on(tfrom))
2489 && bit_is_set(squares_between(tfrom, tto), mto)
2490 && pos.see_sign(m) >= 0)
2497 // ok_to_use_TT() returns true if a transposition table score
2498 // can be used at a given point in search.
2500 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2502 Value v = value_from_tt(tte->value(), ply);
2504 return ( tte->depth() >= depth
2505 || v >= Max(value_mate_in(PLY_MAX), beta)
2506 || v < Min(value_mated_in(PLY_MAX), beta))
2508 && ( (is_lower_bound(tte->type()) && v >= beta)
2509 || (is_upper_bound(tte->type()) && v < beta));
2513 // refine_eval() returns the transposition table score if
2514 // possible otherwise falls back on static position evaluation.
2516 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2521 Value v = value_from_tt(tte->value(), ply);
2523 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2524 || (is_upper_bound(tte->type()) && v < defaultEval))
2531 // update_history() registers a good move that produced a beta-cutoff
2532 // in history and marks as failures all the other moves of that ply.
2534 void update_history(const Position& pos, Move move, Depth depth,
2535 Move movesSearched[], int moveCount) {
2539 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2541 for (int i = 0; i < moveCount - 1; i++)
2543 m = movesSearched[i];
2547 if (!pos.move_is_capture_or_promotion(m))
2548 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2553 // update_killers() add a good move that produced a beta-cutoff
2554 // among the killer moves of that ply.
2556 void update_killers(Move m, SearchStack& ss) {
2558 if (m == ss.killers[0])
2561 for (int i = KILLER_MAX - 1; i > 0; i--)
2562 ss.killers[i] = ss.killers[i - 1];
2568 // update_gains() updates the gains table of a non-capture move given
2569 // the static position evaluation before and after the move.
2571 void update_gains(const Position& pos, Move m, Value before, Value after) {
2574 && before != VALUE_NONE
2575 && after != VALUE_NONE
2576 && pos.captured_piece() == NO_PIECE_TYPE
2577 && !move_is_castle(m)
2578 && !move_is_promotion(m))
2579 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2583 // current_search_time() returns the number of milliseconds which have passed
2584 // since the beginning of the current search.
2586 int current_search_time() {
2588 return get_system_time() - SearchStartTime;
2592 // nps() computes the current nodes/second count.
2596 int t = current_search_time();
2597 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2601 // poll() performs two different functions: It polls for user input, and it
2602 // looks at the time consumed so far and decides if it's time to abort the
2607 static int lastInfoTime;
2608 int t = current_search_time();
2613 // We are line oriented, don't read single chars
2614 std::string command;
2616 if (!std::getline(std::cin, command))
2619 if (command == "quit")
2622 PonderSearch = false;
2626 else if (command == "stop")
2629 PonderSearch = false;
2631 else if (command == "ponderhit")
2635 // Print search information
2639 else if (lastInfoTime > t)
2640 // HACK: Must be a new search where we searched less than
2641 // NodesBetweenPolls nodes during the first second of search.
2644 else if (t - lastInfoTime >= 1000)
2652 if (dbg_show_hit_rate)
2653 dbg_print_hit_rate();
2655 cout << "info nodes " << nodes_searched() << " nps " << nps()
2656 << " time " << t << " hashfull " << TT.full() << endl;
2658 lock_release(&IOLock);
2660 if (ShowCurrentLine)
2661 Threads[0].printCurrentLine = true;
2664 // Should we stop the search?
2668 bool stillAtFirstMove = RootMoveNumber == 1
2669 && !AspirationFailLow
2670 && t > MaxSearchTime + ExtraSearchTime;
2672 bool noMoreTime = t > AbsoluteMaxSearchTime
2673 || stillAtFirstMove;
2675 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2676 || (ExactMaxTime && t >= ExactMaxTime)
2677 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2682 // ponderhit() is called when the program is pondering (i.e. thinking while
2683 // it's the opponent's turn to move) in order to let the engine know that
2684 // it correctly predicted the opponent's move.
2688 int t = current_search_time();
2689 PonderSearch = false;
2691 bool stillAtFirstMove = RootMoveNumber == 1
2692 && !AspirationFailLow
2693 && t > MaxSearchTime + ExtraSearchTime;
2695 bool noMoreTime = t > AbsoluteMaxSearchTime
2696 || stillAtFirstMove;
2698 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2703 // print_current_line() prints the current line of search for a given
2704 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2706 void print_current_line(SearchStack ss[], int ply, int threadID) {
2708 assert(ply >= 0 && ply < PLY_MAX);
2709 assert(threadID >= 0 && threadID < ActiveThreads);
2711 if (!Threads[threadID].idle)
2714 cout << "info currline " << (threadID + 1);
2715 for (int p = 0; p < ply; p++)
2716 cout << " " << ss[p].currentMove;
2719 lock_release(&IOLock);
2721 Threads[threadID].printCurrentLine = false;
2722 if (threadID + 1 < ActiveThreads)
2723 Threads[threadID + 1].printCurrentLine = true;
2727 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2729 void init_ss_array(SearchStack ss[]) {
2731 for (int i = 0; i < 3; i++)
2734 ss[i].initKillers();
2739 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2740 // while the program is pondering. The point is to work around a wrinkle in
2741 // the UCI protocol: When pondering, the engine is not allowed to give a
2742 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2743 // We simply wait here until one of these commands is sent, and return,
2744 // after which the bestmove and pondermove will be printed (in id_loop()).
2746 void wait_for_stop_or_ponderhit() {
2748 std::string command;
2752 if (!std::getline(std::cin, command))
2755 if (command == "quit")
2760 else if (command == "ponderhit" || command == "stop")
2766 // idle_loop() is where the threads are parked when they have no work to do.
2767 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2768 // object for which the current thread is the master.
2770 void idle_loop(int threadID, SplitPoint* waitSp) {
2772 assert(threadID >= 0 && threadID < THREAD_MAX);
2774 Threads[threadID].running = true;
2778 if (AllThreadsShouldExit && threadID != 0)
2781 // If we are not thinking, wait for a condition to be signaled
2782 // instead of wasting CPU time polling for work.
2783 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2786 #if !defined(_MSC_VER)
2787 pthread_mutex_lock(&WaitLock);
2788 if (Idle || threadID >= ActiveThreads)
2789 pthread_cond_wait(&WaitCond, &WaitLock);
2791 pthread_mutex_unlock(&WaitLock);
2793 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2797 // If this thread has been assigned work, launch a search
2798 if (Threads[threadID].workIsWaiting)
2800 assert(!Threads[threadID].idle);
2802 Threads[threadID].workIsWaiting = false;
2803 if (Threads[threadID].splitPoint->pvNode)
2804 sp_search_pv(Threads[threadID].splitPoint, threadID);
2806 sp_search(Threads[threadID].splitPoint, threadID);
2808 Threads[threadID].idle = true;
2811 // If this thread is the master of a split point and all threads have
2812 // finished their work at this split point, return from the idle loop.
2813 if (waitSp != NULL && waitSp->cpus == 0)
2817 Threads[threadID].running = false;
2821 // init_split_point_stack() is called during program initialization, and
2822 // initializes all split point objects.
2824 void init_split_point_stack() {
2826 for (int i = 0; i < THREAD_MAX; i++)
2827 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2829 SplitPointStack[i][j].parent = NULL;
2830 lock_init(&(SplitPointStack[i][j].lock), NULL);
2835 // destroy_split_point_stack() is called when the program exits, and
2836 // destroys all locks in the precomputed split point objects.
2838 void destroy_split_point_stack() {
2840 for (int i = 0; i < THREAD_MAX; i++)
2841 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2842 lock_destroy(&(SplitPointStack[i][j].lock));
2846 // thread_should_stop() checks whether the thread with a given threadID has
2847 // been asked to stop, directly or indirectly. This can happen if a beta
2848 // cutoff has occurred in the thread's currently active split point, or in
2849 // some ancestor of the current split point.
2851 bool thread_should_stop(int threadID) {
2853 assert(threadID >= 0 && threadID < ActiveThreads);
2857 if (Threads[threadID].stop)
2859 if (ActiveThreads <= 2)
2861 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2864 Threads[threadID].stop = true;
2871 // thread_is_available() checks whether the thread with threadID "slave" is
2872 // available to help the thread with threadID "master" at a split point. An
2873 // obvious requirement is that "slave" must be idle. With more than two
2874 // threads, this is not by itself sufficient: If "slave" is the master of
2875 // some active split point, it is only available as a slave to the other
2876 // threads which are busy searching the split point at the top of "slave"'s
2877 // split point stack (the "helpful master concept" in YBWC terminology).
2879 bool thread_is_available(int slave, int master) {
2881 assert(slave >= 0 && slave < ActiveThreads);
2882 assert(master >= 0 && master < ActiveThreads);
2883 assert(ActiveThreads > 1);
2885 if (!Threads[slave].idle || slave == master)
2888 // Make a local copy to be sure doesn't change under our feet
2889 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
2891 if (localActiveSplitPoints == 0)
2892 // No active split points means that the thread is available as
2893 // a slave for any other thread.
2896 if (ActiveThreads == 2)
2899 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2900 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
2901 // could have been set to 0 by another thread leading to an out of bound access.
2902 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2909 // idle_thread_exists() tries to find an idle thread which is available as
2910 // a slave for the thread with threadID "master".
2912 bool idle_thread_exists(int master) {
2914 assert(master >= 0 && master < ActiveThreads);
2915 assert(ActiveThreads > 1);
2917 for (int i = 0; i < ActiveThreads; i++)
2918 if (thread_is_available(i, master))
2925 // split() does the actual work of distributing the work at a node between
2926 // several threads at PV nodes. If it does not succeed in splitting the
2927 // node (because no idle threads are available, or because we have no unused
2928 // split point objects), the function immediately returns false. If
2929 // splitting is possible, a SplitPoint object is initialized with all the
2930 // data that must be copied to the helper threads (the current position and
2931 // search stack, alpha, beta, the search depth, etc.), and we tell our
2932 // helper threads that they have been assigned work. This will cause them
2933 // to instantly leave their idle loops and call sp_search_pv(). When all
2934 // threads have returned from sp_search_pv (or, equivalently, when
2935 // splitPoint->cpus becomes 0), split() returns true.
2937 bool split(const Position& p, SearchStack* sstck, int ply,
2938 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2939 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2942 assert(sstck != NULL);
2943 assert(ply >= 0 && ply < PLY_MAX);
2944 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2945 assert(!pvNode || *alpha < *beta);
2946 assert(*beta <= VALUE_INFINITE);
2947 assert(depth > Depth(0));
2948 assert(master >= 0 && master < ActiveThreads);
2949 assert(ActiveThreads > 1);
2951 SplitPoint* splitPoint;
2955 // If no other thread is available to help us, or if we have too many
2956 // active split points, don't split.
2957 if ( !idle_thread_exists(master)
2958 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2960 lock_release(&MPLock);
2964 // Pick the next available split point object from the split point stack
2965 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2966 Threads[master].activeSplitPoints++;
2968 // Initialize the split point object
2969 splitPoint->parent = Threads[master].splitPoint;
2970 splitPoint->finished = false;
2971 splitPoint->ply = ply;
2972 splitPoint->depth = depth;
2973 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2974 splitPoint->beta = *beta;
2975 splitPoint->pvNode = pvNode;
2976 splitPoint->bestValue = *bestValue;
2977 splitPoint->futilityValue = futilityValue;
2978 splitPoint->master = master;
2979 splitPoint->mp = mp;
2980 splitPoint->moves = *moves;
2981 splitPoint->cpus = 1;
2982 splitPoint->pos = &p;
2983 splitPoint->parentSstack = sstck;
2984 for (int i = 0; i < ActiveThreads; i++)
2985 splitPoint->slaves[i] = 0;
2987 Threads[master].idle = false;
2988 Threads[master].stop = false;
2989 Threads[master].splitPoint = splitPoint;
2991 // Allocate available threads setting idle flag to false
2992 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2993 if (thread_is_available(i, master))
2995 Threads[i].idle = false;
2996 Threads[i].stop = false;
2997 Threads[i].splitPoint = splitPoint;
2998 splitPoint->slaves[i] = 1;
3002 assert(splitPoint->cpus > 1);
3004 // We can release the lock because master and slave threads are already booked
3005 lock_release(&MPLock);
3007 // Tell the threads that they have work to do. This will make them leave
3008 // their idle loop. But before copy search stack tail for each thread.
3009 for (int i = 0; i < ActiveThreads; i++)
3010 if (i == master || splitPoint->slaves[i])
3012 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
3013 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3016 // Everything is set up. The master thread enters the idle loop, from
3017 // which it will instantly launch a search, because its workIsWaiting
3018 // slot is 'true'. We send the split point as a second parameter to the
3019 // idle loop, which means that the main thread will return from the idle
3020 // loop when all threads have finished their work at this split point
3021 // (i.e. when splitPoint->cpus == 0).
3022 idle_loop(master, splitPoint);
3024 // We have returned from the idle loop, which means that all threads are
3025 // finished. Update alpha, beta and bestValue, and return.
3029 *alpha = splitPoint->alpha;
3031 *beta = splitPoint->beta;
3032 *bestValue = splitPoint->bestValue;
3033 Threads[master].stop = false;
3034 Threads[master].idle = false;
3035 Threads[master].activeSplitPoints--;
3036 Threads[master].splitPoint = splitPoint->parent;
3038 lock_release(&MPLock);
3043 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3044 // to start a new search from the root.
3046 void wake_sleeping_threads() {
3048 if (ActiveThreads > 1)
3050 for (int i = 1; i < ActiveThreads; i++)
3052 Threads[i].idle = true;
3053 Threads[i].workIsWaiting = false;
3056 #if !defined(_MSC_VER)
3057 pthread_mutex_lock(&WaitLock);
3058 pthread_cond_broadcast(&WaitCond);
3059 pthread_mutex_unlock(&WaitLock);
3061 for (int i = 1; i < THREAD_MAX; i++)
3062 SetEvent(SitIdleEvent[i]);
3068 // init_thread() is the function which is called when a new thread is
3069 // launched. It simply calls the idle_loop() function with the supplied
3070 // threadID. There are two versions of this function; one for POSIX
3071 // threads and one for Windows threads.
3073 #if !defined(_MSC_VER)
3075 void* init_thread(void *threadID) {
3077 idle_loop(*(int*)threadID, NULL);
3083 DWORD WINAPI init_thread(LPVOID threadID) {
3085 idle_loop(*(int*)threadID, NULL);